Giter Club home page Giter Club logo

orgchart's Introduction

OrgChart

It's a simple and direct organization chart plugin. Anytime you want a tree-like chart, you can turn to OrgChart.

#Native javascript version of orgchart is coming soon ๐Ÿ˜Š#

Foreword

  • First of all, thanks a lot for wesnolte's great work:blush: -- jOrgChart. The thought that using nested tables to build out the tree-like orgonization chart is amazing. This idea is more simple and direct than its counterparts based on svg.
  • Unfortunately, it's long time not to see the update of jOrgChart. on the other hand, I got some interesting ideas to add, so I choose to create a new repo.
  • Font Awesome provides us with administration icon, second level menu icon and loading spinner.

Features

  • Supports both local data and remote data (JSON).
  • Smooth expand/collapse effects based on CSS3 transitions.
  • Align the chart in 4 orientations.
  • Allows user to change orgchart structure by drag/drop nodes.
  • Allows user to edit orgchart dynamically and save the final hierarchy as a JSON object.
  • Supports exporting chart as a picture.
  • Supports pan and zoom
  • Users can adopt multiple solutions to build up a huge organization chart(please refer to multiple-layers or hybrid layout sections)
  • touch-enabled plugin for mobile divice

Installation

Of course, you can directly use the standalone build by including dist/js/jquery.orgchart.js and dist/css/jquery.orgchart.css in your webapp.

Install with Bower

# From version 1.0.2 on, users can install orgchart and add it to bower.json dependencies
$ bower install orgchart

Install with npm

# From version 1.0.4 on, users can install orgchart with npm
$ npm install orgchart

require('orgchart') will load orgchart plugin onto the jQuery object. The orgchart module itself does not export anything.

Demo

<!-- wrap the text node with <a href="#"> , <span>, blabla is also OK. Note:text node must immediately follow the <li> tag, with no intervening characters of any kind.  -->
<ul id="ul-data">
  <li>Lao Lao
    <ul>
      <li>Bo Miao</li>
      <li>Su Miao
        <ul>
          <li>Tie Hua</li>
          <li>Hei Hei
            <ul>
              <li>Pang Pang</li>
              <li>Xiang Xiang</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
$('#chart-container').orgchart({
  'data' : $('#ul-data')
});

ul datasource

// sample of core source code
var datasource = {
  'name': 'Lao Lao',
  'title': 'general manager',
  'children': [
    { 'name': 'Bo Miao', 'title': 'department manager' },
    { 'name': 'Su Miao', 'title': 'department manager',
      'children': [
        { 'name': 'Tie Hua', 'title': 'senior engineer' },
        { 'name': 'Hei Hei', 'title': 'senior engineer' }
      ]
    },
    { 'name': 'Hong Miao', 'title': 'department manager' },
    { 'name': 'Chun Miao', 'title': 'department manager' }
  ]
};

$('#chart-container').orgchart({
  'data' : datasource,
  'depth': 2,
  'nodeContent': 'title'
});

local datasource

pan & zoom

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'nodeContent': 'title',
  'direction': 'b2t'
});

Bottom to Top

Left to Right

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'nodeContent': 'title',
  'direction': 'l2r'
});

Left to Right

Right to Left

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'nodeContent': 'title',
  'direction': 'r2l'
});

Right to Left

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'nodeContent': 'title',
  'toggleSiblingsResp': true
});

toggle siblings respectively

// sample of core source code
$('#chart-container').orgchart({
  'data' : '/orgchart/initdata',
  'depth': 2,
  'nodeContent': 'title'
});

ajax datasource

Note: when users use ajaxURL option to build orghchart, they must use json datasource(both local and remote are OK) and set the relationship property of datasource by themselves. All of these staff are used to generate the correct expanding/collapsing arrows for nodes.

// sample of core source code
var datasource = {
  'id': '1',
  'name': 'Su Miao',
  'title': 'department manager',
  'relationship': '111',
  'children': [
    { 'id': '2','name': 'Tie Hua', 'title': 'senior engineer', 'relationship': '110' },
    { 'id': '3','name': 'Hei Hei', 'title': 'senior engineer', 'relationship': '111' }
  ]
};

var ajaxURLs = {
  'children': '/orgchart/children/',
  'parent': '/orgchart/parent/',
  // It would be helpful to have functions instead of URLs for the AJAX fetching
  // as it would allow a more flexible treatment of the results.
  'siblings': function(nodeData) {
    return '/orgchart/siblings/' + nodeData.id;
  },
  'families': function(nodeData) {
    return '/orgchart/families/' + nodeData.id;
  }
};

$('#chart-container').orgchart({
  'data' : datasource,
  'ajaxURL': ajaxURLs,
  'nodeContent': 'title',
  'nodeId': 'id'
});

on-demand loading data

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'depth': 2,
  'nodeContent': 'title',
  'nodeID': 'id',
  'createNode': function($node, data) {
    var secondMenuIcon = $('<i>', {
      'class': 'fa fa-info-circle second-menu-icon',
      click: function() {
        $(this).siblings('.second-menu').toggle();
      }
    });
    var secondMenu = '<div class="second-menu"><img class="avatar" src="../img/avatar/' + data.id + '.jpg"></div>';
    $node.append(secondMenuIcon).append(secondMenu);
  }
});

option--createNode

Here, we need the help from html2canvas.

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'depth': 2,
  'nodeContent': 'title',
  'exportButton': true,
  'exportFilename': 'MyOrgChart'
});

export orgchart

Here, we fall back on OpenLayers. It's the most aewsome open-source js library for Web GIS you sholdn't miss.

// sample of core source code
var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.Stamen({
        layer: 'watercolor'
      }),
      preload: 4
    }),
    new ol.layer.Tile({
      source: new ol.source.Stamen({
        layer: 'terrain-labels'
      }),
      preload: 1
    })
  ],
  target: 'pageBody',
  view: new ol.View({
    center: ol.proj.transform([-87.6297980, 41.8781140], 'EPSG:4326', 'EPSG:3857'),
    zoom: 10
  })
});
$('body').prepend(map.getViewport());

var datasource = {
  'name': 'Lao Lao',
  'title': 'President Office',
  'position': [-87.6297980, 41.8781140],
  'children': [
    { 'name': 'Bo Miao', 'title': 'Administration  Dept.', 'position': [-83.0457540, 42.3314270]},
    { 'name': 'Yu Jie', 'title': 'Product Dept.', 'position': [-71.0588800, 42.3600820]},
    { 'name': 'Yu Tie', 'title': 'Marketing Dept.', 'position': [-80.1917900, 25.7616800] }
  ]
};

$('#chart-container').orgchart({
  'data' : datasource,
  'nodeContent': 'title',
  'createNode': function($node, data) {
    $node.on('click', function() {
      var view = map.getView();
      var duration = 2000;
      var start = +new Date();
      var pan = ol.animation.pan({
        duration: duration,
        source:  view.getCenter(),
        start: start
      });
      var bounce = ol.animation.bounce({
        duration: duration,
        resolution: 4 * view.getResolution(),
        start: start
      });
      map.beforeRender(pan, bounce);
      view.setCenter(ol.proj.transform(data.position, 'EPSG:4326', 'EPSG:3857'));
    });
  }
});

integrate map

With the help of exposed core methods(addParent(), addSiblings(), addChildren(), removeNodes()) of orgchart plugin, we can finish this task easily.

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'exportButton': true,
  'exportFilename': 'SportsChart',
  'parentNodeSymbol': 'fa-th-large',
  'createNode': function($node, data) {
    $node.on('click', function(event) {
      if (!$(event.target).is('.edge')) {
        $('#selected-node').val(data.name).data('node', $node);
      }
    });
  }
})
.on('click', '.orgchart', function(event) {
  if (!$(event.target).closest('.node').length) {
    $('#selected-node').val('');
  }
});

$('#btn-add-nodes').on('click', function() {
  var nodeVals = [];
  $('#new-nodelist').find('.new-node').each(function(index, item) {
    var validVal = item.value.trim();
    if (validVal.length) {
      nodeVals.push(validVal);
    }
  });
  var $node = $('#selected-node').data('node');
  var nodeType = $('input[name="node-type"]:checked');
  if (nodeType.val() === 'parent') {
    $('#chart-container').orgchart('addParent', $('#chart-container').find('.node:first'), { 'name': nodeVals[0] });
  } else if (nodeType.val() === 'siblings') {
    $('#chart-container').orgchart('addSiblings', $node,
      { 'siblings': nodeVals.map(function(item) { return { 'name': item, 'relationship': '110' }; })
    });
  } else {
    var hasChild = $node.parent().attr('colspan') > 0 ? true : false;
    if (!hasChild) {
      var rel = nodeVals.length > 1 ? '110' : '100';
      $('#chart-container').orgchart('addChildren', $node, {
          'children': nodeVals.map(function(item) {
            return { 'name': item, 'relationship': rel };
          })
        }, $.extend({}, $('#chart-container').data('orgchart').options, { depth: 0 }));
    } else {
      $('#chart-container').orgchart('addSiblings', $node.closest('tr').siblings('.nodes').find('.node:first'),
        { 'siblings': nodeVals.map(function(item) { return { 'name': item, 'relationship': '110' }; })
      });
    }
  }
});

$('#btn-delete-nodes').on('click', function() {
  var $node = $('#selected-node').data('node');
  $('#chart-container').orgchart('removeNodes', $node);
  $('#selected-node').data('node', null);
});

edit orgchart

Users are allowed to drag & drop the nodes of orgchart when option "draggable" is assigned to true(Note: this feature doesn't work on IE due to its poor support for HTML5 drag & drop API).

drag & drop

Furthermore, users can make use of option dropCriteria to inject their custom limitations on drag & drop. As shown below, we don't want an manager employee to be under a engineer under no circumstance.

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'nodeContent': 'title',
  'draggable': true,
  'dropCriteria': function($draggedNode, $dragZone, $dropZone) {
    if($draggedNode.find('.content').text().indexOf('manager') > -1 && $dropZone.find('.content').text().indexOf('engineer') > -1) {
      return false;
    }
    return true;
  }
})

That's where getHierarchy() comes in.

<ul id="ul-data">
  <li id="1">Lao Lao
    <ul>
      <li id="2">Bo Miao</li>
      <li id="3">Su Miao
        <ul>
          <li id="4">Tie Hua</li>
          <li id="5">Hei Hei
            <ul>
              <li id="6">Pang Pang</li>
              <li id="7">Xiang Xiang</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
$('#chart-container').orgchart({
  'data' : $('#ul-data')
});

$('#btn-export-hier').on('click', function() {
  var hierarchy = $('#chart-container').orgchart('getHierarchy');
  $(this).after('<pre>').next().append(JSON.stringify(hierarchy, null, 2));
});

get hierarchy

It's a so easy task, we just need to append id or className property to node data.

var datasource = {
  'name': 'Lao Lao',
  'title': 'general manager',
  'className': 'top-level',
  'children': [
    { 'name': 'Bo Miao', 'title': 'department manager', 'className': 'middle-level',
      'children': [
        { 'name': 'Li Jing', 'title': 'senior engineer', 'className': 'bottom-level' },
        { 'name': 'Li Xin', 'title': 'senior engineer', 'className': 'bottom-level' }
      ]
    }
  };
.orgchart .top-level .title {
  background-color: #006699;
}
.orgchart .top-level .content {
  border-color: #006699;
}
.orgchart .middle-level .title {
  background-color: #009933;
}
.orgchart .middle-level .content {
  border-color: #009933;
}
.orgchart .bottom-level .title {
  background-color: #993366;
}
.orgchart .bottom-level .content {
  border-color: #993366;
}

color coded

In fact, this is a wonderful solution to display a orgchart which includes a huge number of node data.

multiple layers

This feature is inspired by the issues(Aligning Children Vertical, Hybrid(horizontal + vertical) OrgChart). Thank mfahadi and Destructrix for their constructive suggestions:blush:

From now on, users never have to worry about how to align a huge of nodes in one screen of browser. The option "verticalDepth" allows users to align child nodes vertically from the given depth.

Note: currently, this option is incompatible with many other options or methods, like direction, drag&drop, addChildren(), removeNodes(), getHierarchy() and so on. These conflicts will be solved one by one in the later versions.

// sample of core source code
$('#chart-container').orgchart({
  'data' : datasource,
  'nodeContent': 'title',
  'verticalDepth': 3 // From the 3th level of orgchart, nodes will be aligned vertically.
});

hybrid layout

Usage

Instantiation Statement

$('#chartContainerId').orgchart(options);

Structure of Datasource

{
  'id': 'rootNode', // It's a optional property which will be used as id attribute of node
  // and data-parent attribute, which contains the id of the parent node
  'className': 'top-level', // It's a optional property which will be used as className attribute of node.
  'nodeTitlePro': 'Lao Lao',
  'nodeContentPro': 'general manager',
  'relationship': relationshipValue, // Note: when you activate ondemand loading nodes feature,
  // you should use json datsource (local or remote) and set this property.
  // This property implies that whether this node has parent node, siblings nodes or children nodes.
  // relationshipValue is a string composed of three "0/1" identifier.
  // First character stands for wether current node has parent node;
  // Scond character stands for wether current node has siblings nodes;
  // Third character stands for wether current node has children node.
  'children': [ // The property stands for nested nodes. "children" is just default name you can override.
    { 'nodeTitlePro': 'Bo Miao', 'nodeContentPro': 'department manager', 'relationship': '110' },
    { 'nodeTitlePro': 'Su Miao', 'nodeContentPro': 'department manager', 'relationship': '111',
      'children': [
        { 'nodeTitlePro': 'Tie Hua', 'nodeContentPro': 'senior engineer', 'relationship': '110' },
        { 'nodeTitlePro': 'Hei Hei', 'nodeContentPro': 'senior engineer', 'relationship': '110' }
      ]
    },
    { 'nodeTitlePro': 'Yu Jie', 'nodeContentPro': 'department manager', 'relationship': '110' }
  ],
  'otherPro': anyValue
};

Options

NameTypeRequiredDefaultDescription
datajson or stringyesdatasource usded to build out structure of orgchart. It could be a json object or a string containing the URL to which the ajax request is sent.
panbooleannofalseUsers could pan the orgchart by mouse drag&drop if they enable this option.
zoombooleannofalseUsers could zoomin/zoomout the orgchart by mouse wheel if they enable this option.
directionstringno"t2b"The available values are t2b(implies "top to bottom", it's default value), b2t(implies "bottom to top"), l2r(implies "left to right"), r2l(implies "right to left").
verticalDepthintegernoUsers can make use of this option to align the nodes vertically from the specified depth.
toggleSiblingsRespbooleannofalseOnce enable this option, users can show/hide left/right sibling nodes respectively by clicking left/right arrow.
ajaxURLjsonnoIt inclueds four properites -- parent, children, siblings, families(ask for parent node and siblings nodes). As their names imply, different propety provides the URL to which ajax request for different nodes is sent.
depthpositive integerno999It indicates the level that at the very beginning orgchart is expanded to.
nodeTitlestringno"name"It sets one property of datasource as text content of title section of orgchart node. In fact, users can create a simple orghcart with only nodeTitle option.
parentNodeSymbolstringno"fa-users"Using font awesome icon to imply that the node has child nodes.
nodeContentstringnoIt sets one property of datasource as text content of content section of orgchart node.
nodeIdstringno"id"It sets one property of datasource as unique identifier of every orgchart node.
createNodefunctionnoIt's a callback function used to customize every orgchart node. It recieves two parament: "$node" stands for jquery object of single node div; "data" stands for datasource of single node.
exportButtonbooleannofalseIt enable the export button for orgchart.
exportFilenamestringno"Orgchart"It's filename when you export current orgchart as a picture.
chartClassstringno""when you wanna instantiate multiple orgcharts on one page, you should add diffent classname to them in order to distinguish them.
draggablebooleannofalseUsers can drag & drop the nodes of orgchart if they enable this option. **Note**: this feature doesn't work on IE due to its poor support for HTML5 drag & drop API.
dropCriteriafunctionnoUsers can construct their own criteria to limit the relationships between dragged node and drop zone. Furtherly, this function accept three arguments(draggedNode, dragZone, dropZone) and just only return boolen values.

Methods

I'm sure that you can grasp the key points of the methods below after you try out demo -- edit orgchart.

$container.orgchart(options)

Embeds an organization chart in designated container. Accepts an options object and you can go through the "options" section to find which options are required.

.orgchart('addParent', data, opts)

Adds parent node(actullay it's always root node) for current orgchart.

NameTypeRequiredDefaultDescription
datajson objectyesdatasource for building root node
optsjson objectnoinitial options of current orgchartoptions used for overriding initial options
##### .orgchart('addSiblings', $node, data, opts) Adds sibling nodes for designated node.
NameTypeRequiredDefaultDescription
$nodejquery objectyeswe'll add sibling nodes based on this node
datajson objectyesdatasource for building sibling nodes
optsjson objectnoinitial options of current orgchartoptions used for overriding initial options
##### .orgchart('addChildren', $node, data, opts๏ผ‰ Adds child nodes for designed node.
NameTypeRequiredDefaultDescription
$nodejquery objectyeswe'll add child nodes based on this node
datajson objectyesdatasource for building child nodes
optsjson objectnoinitial options of current orgchartoptions used for overriding initial options
##### .orgchart('removeNodes', $node๏ผ‰ Removes the designated node and its descedant nodes.
NameTypeRequiredDefaultDescription
$nodejquery objectyesnode to be removed
##### .orgchart('getHierarchy'๏ผ‰ This method is designed to get the hierarchy relationships of orgchart for further processing. For example, after editing the orgchart, you could send the returned value of this method to server-side and save the new state of orghcart. ##### .orgchart('hideDescendants',$node) This method allows you to hide programatically the children of any specific node(.node element), if it has
Name Type Required Default Description
$node JQuery Object Yes None Is the desired JQuery Object to hide its children nodes
##### .orgchart('showDescendants',$node) This method allows you to show programatically the children of any specific node(.node element), if it has
Name Type Required Default Description
$node JQuery Object Yes None Is the desired JQuery Object to show its children nodes
##### .orgchart('hideSiblings',$node,direction) This method allows you to hide programatically the siblings of any specific node(.node element), if it has
Name Type Required Default Description
$node JQuery Object Yes None Is the desired JQuery Object to hide its siblings nodes
direction string No None Possible values:"left","rigth". Specifies if hide the siblings at left or rigth. If not defined hide both of them.
##### .orgchart('showSiblings',$node,direction) This method allows you to show programatically the siblings of any specific node(.node element), if it has
Name Type Required Default Description
$node JQuery Object Yes None Is the desired JQuery Object to show its siblings nodes
direction string No None Possible values:"left","rigth". Specifies if hide the siblings at left or rigth. If not defined hide both of them.
##### .orgchart('getNodeState',$node,relation) This method returns you the specified relation of a node
Name Type Required Default Description
$node JQuery Object Yes None Is the desired JQuery Object to know its relationship
relation String No None Possible values:"children","parent". Specifies the desired relation to return, in case the parameter is not defined, it will return the siblings.
The returning object will have the next structure: ```js { "exists": true|false, //Indicates if has parent|children|siblings "visible":true|false, //Indicates if the relationship nodes are visible "nodes": JQueryObject //The jquery object with the matching elements } ```

Events

Event TypeAttached DataDescription
nodedropped.orgchartdraggedNode, dragZone, dropZoneThe event's handler is where you can place your customized function after node drop over. For more details, please refer to example drag & drop.

Tips

How can I deactivate expand/collapse feature of orgchart?

This use case is inspired by the issue. Thanks der-robert and ActiveScottShaw for their constructive discussions:blush:

Users can enable/disable exapand/collapse feature with className "noncollapsable" as shown below.

$('.orgchart').addClass('noncollapsable'); // deactivate

$('.orgchart').removeClass('noncollapsable'); // activate

How can I search nodes and show the minimized chart?

This use case is inspired by the issue. Thanks Mmannem for his constructive discussions:blush: The following statements show the core logic and this is the complete demo - filter node.

var $chart = $('.orgchart');
// disalbe the expand/collapse feture
$chart.addClass('noncollapsable');
// distinguish the matched nodes and the unmatched nodes according to the given key word
$chart.find('.node').filter(function(index, node) {
    return $(node).text().toLowerCase().indexOf(keyWord) > -1;
  }).addClass('matched')
  .closest('table').parents('table').find('tr:first').find('.node').addClass('retained');
// hide the unmatched nodes
$chart.find('.matched,.retained').each(function(index, node) {
  var $unmatched = $(node).closest('table').parent().siblings().find('.node:first:not(.matched,.retained)')
    .closest('table').parent().addClass('hidden');
  $unmatched.parent().prev().children().slice(1, $unmatched.length * 2 + 1).addClass('hidden');
});
// hide the redundant descendant nodes of the matched nodes
$chart.find('.matched').each(function(index, node) {
  if (!$(node).closest('tr').siblings(':last').find('.matched').length) {
    $(node).closest('tr').siblings().addClass('hidden');
  }
});

Why is the root node gone?

When I have a huge orgchart with enabled "pan" option, if I hide all the children of one of the topmost parents then the chart disappear from screen. It seems that we need to add a reset button to keep the chart visible. For details, please refer to the issue opened by manuel-84 ๐Ÿ˜Š

Users can embed any clear up logics into the click handler of the reset buttton as shown below.

$('.orgchart').css('transform',''); // remove the tansform settings

Browser Compatibility

  • Chrome 19+
  • Firefox 4+
  • Safari 6+
  • Opera 15+
  • IE 10+

Work Show

I love NBA. 2016 NBA Playoff

We thank JordiCorbilla๐Ÿ˜Š for his sharing how to save datasource after chart editing. save datasource

orgchart's People

Contributors

dabeng avatar joakku avatar lybkf avatar newghost avatar tfrizzell avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.