Build Interactive Organization Charts with treeSpider JavaScript Library

Category: Chart & Graph , Javascript , Recommended | March 10, 2025
Author:paulosabayomi
Views Total:129 views
Official Page:Go to website
Last Update:March 10, 2025
License:MIT

Preview:

Build Interactive Organization Charts with treeSpider JavaScript Library

Description:

TreeSpider is a robust JavaScript library that helps you generate responsive, interactive organization charts, family trees, or any tree-like structure.

Features:

  • Interactive Charts: Create zoomable and rotatable tree charts.
  • CSS Customizable: Fully style the appearance to match your branding.
  • Multiple Chart Types: Supports various chart types, e.g., default, cellar, goldenRod, hSpider, hSpiderWalk, radialSpiderLeg, vSpiderWalk.
  • Data-Driven: Uses a simple, linear data structure (ID and parentID).
  • No Dependencies: Lightweight and easy to integrate.
  • API Control: Programmatically control zoom, rotation, and appearance.
  • Event Handling: Listen for events like initialization, expansion, collapse, and zooming.
  • Large Data Handling: Display a large amount of data in steps.
  • D3.js Powered: Built using the D3.js library for robust visualization.
  • TypeScript Based: Developed with TypeScript.

How to use it:

1. Install & download.

# NPM
$ npm install treespider
2. Import TreeSpider into your project.
// ES Module
import TreeSpider from 'treespider';
// Browser
<link rel="stylesheet" href="treeSpider.css" />
<script src="treeSpider.bundle.min.js"></script>

3. Create a container element where the tree chart will appear:

<div id="example"></div>

4. Prepare your data as an array of objects. Each object must include a unique id, a parentId for subordinates (except the overall head), and additional fields. For example:

const myData = [
  {id: "A1", name: "John Smith", role: "CEO", location: "New York, USA"},
  {id: "A2", parentId: "A1", name: "Alice Johnson", role: "VP of Marketing", location: "London, UK", image: "/path/to/image/"},
  {id: "A3", parentId: "A1", name: "Bob Williams", role: "VP of Engineering", location: "San Francisco, USA"},
  // ...
];

5. Initialize TreeSpider with your container and data:

const instance = new TreeSpider({
  targetContainer: '#example',
  tree_data: myData,
});

6. All available options to customize the tree chart.

OptionTypeDefaultRequiredDescription
targetContainerstringnoneYesThe CSS selector of the HTML element where treeSpider will be created. Use body for the entire page.
placeEl`’override’ \‘start’ \‘end’ \{ beforeEl: string; }`'override'NoHow to place the treeSpider container within the targetContainer. Use { beforeEl: 'selector' } to insert before a specific element.
widthstring'900px'NoWidth of the treeSpider container.
heightstring'500px'NoHeight of the treeSpider container.
autoInitializebooleantrueNoSet to false to manually initialize treeSpider using the initialize() method.
tree_dataArray<IChartHead>undefinedNoArray of data representing the hierarchical structure. See the “Data Structure” section for details.
color_rangestring[]['#b31212', '#b34712', '#b38d12', '#9ab312', '#2fb312', '#12b362', '#12b3a8', '#1278b3', '#1712b3', '#5712b3', '#8d12b3', '#b3128d', '#b3124a', '#b31212']NoArray of colors (hex or names) used for chart heads. treeSpider interpolates these colors.
tree_typestringdefaultNoType of chart. Options: default, cellar, goldenRod, hSpider, hSpiderWalk, radialSpiderLeg, vSpiderWalk.
chart_head_typestringdefaultNoChart head style. Options: default, landscape, rounded.
show_toolsbooleantrueNoSet to false to hide the UI tools panel.
show_chart_head_borderbooleantrueNoSet to false to hide borders around chart heads.
animation_rotation_speednumber10NoRotation speed in milliseconds (lower value = faster, smoother rotation).
animation_rotation_intervalnumber1NoRotation increment in degrees (lower value = smoother rotation).
backgroundPatternstringdefaultNoBackground pattern. Options: none, default, flux, quad, blurry, chaos, flurry, spiral, whirling, replicate, scribble, squiggly, gyrrate, leaves, spot.
backgroundPositionstringundefinedNoCSS background-position for the SVG background.
backgroundSizestringundefinedNoCSS background-size for the SVG background pattern.
customBackgroundstringundefinedNoStringified SVG element for a custom background pattern.
head_linker_thumb_circle_radiusnumber8NoRadius of the linker thumb shape (the expand/collapse control).
linker_thumb_icon_colorstringbright500NoColor of the icon within the linker thumb. Options: brighter, bright500, bright100.
linker_thumb_shapestringsymbolCircleNoD3 shape of the linker thumb. Options: symbolAsterisk, symbolCircle, symbolCross, symbolDiamond, symbolDiamond2, symbolPlus, symbolSquare, symbolSquare2, symbolStar, symbolTriangle, symbolTriangle2, symbolWye, symbolX.
head_image_shapestringsymbolCircleNoD3 shape of the chart head image/initials container. Options: symbolCircle, symbolCross, symbolDiamond, symbolDiamond2, symbolSquare, symbolSquare2, symbolStar, symbolTriangle, symbolTriangle2, symbolWye.
chart_head_bgstring#ffffffNoBackground color of chart heads.
auto_set_chart_head_bgbooleanfalseNoIf true, uses the webpage’s body background color for chart heads.
display_tree_in_stepbooleanfalseNoIf true, renders the tree in steps (useful for large datasets).
auto_display_tree_in_stepbooleantrueNoAutomatically displays the tree in steps if the data length exceeds 500.
tree_level_stepnumber2NoNumber of levels to display per step when display_tree_in_step is true.
dropshadowobject{ x: "-50%", y: "-50%", width: "200%", height: "200%", dx: 1, dy: 1, stdDeviation: 4, floodColor: "rgba(91, 91, 91, 0.19)", }NoOptions to configure the SVG feDropShadow filter for chart heads (not applicable to rounded chart head type). See the breakdown below the main table.
palletobject{ h: 10, s: 0.5, l: 0.5, darker: 3, brighter: 0.8, bright100: 0.5, dark100: 0.5, gray: 50, gray85: 85 }NoOptions for tuning color variants within chart heads. See the breakdown below the main table.
tree_link_typestringundefinedNoD3 link curve type. Options: curveBumpX, curveBumpY, curveBasisClosed, curveLinear, curveStep, curveStepAfter, curveStepBefore.
random_data_lengthnumber200NoLength of randomly generated data (if used).
zoom_in_distancenumber1.5NoZoom-in extent when using the zoom-in button.
zoom_out_distancenumber0.5NoZoom-out extent when using the zoom-out button.
verticalSpacestring'120px'NoVertical space between parent and child chart heads.
font_linkstringhttps://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swapNoGoogle Fonts link (or local font path)
font_namestringLatoNoName of the font provided in font_link.

dropshadow Option Details:

PropertyTypeDescription
xstringX position of the drop shadow.
ystringY position of the drop shadow.
widthstringWidth of the drop shadow effect area.
heightstringHeight of the drop shadow effect area.
dxnumberX offset of the drop shadow.
dynumberY offset of the drop shadow.
stdDeviationnumberStandard deviation for the blur effect.
floodColorstringColor of the drop shadow.

pallet Option Details:

PropertyTypeDescription
hnumberHue (HSL color).
snumberSaturation (HSL color).
lnumberLightness (HSL color). Adjusts brightness of color variants.
darkernumberHow much darker the darker color variants should be.
brighternumberHow much brighter the brighter color variants should be (direct variant).
bright100numberBrighter variant of the HSL-tuned color.
dark100numberDarker variant of the HSL-tuned color.
graynumberGray level (0-100, 0 = darkest, 100 = lightest) generated with d3.gray.
gray85numberGray level, 85% by default.
const instance = new TreeSpider({
  targetContainer: '',
  width: '100%',
  height: '500px',
  placeEl: 'override',
  tree_data: undefined,
  color_range: [],
  /* default
  cellar
  goldenRod
  hSpider
  hSpiderWalk
  radialSpiderLeg
  vSpiderWalk */
  tree_type: 'default',
  chart_head_type: 'default', // 'default', 'landscape', 'rounded'
  show_tools: true,
  show_chart_head_border: false,
  animation_rotation_speed: 10,
  animation_rotation_interval: 1,
  backgroundPattern: 'default',
  backgroundSize: undefined,
  customBackground: undefined,
  backgroundPosition: undefined,
  head_linker_thumb_circle_radius: 8,
  linker_thumb_icon_color: 'bright500',
  /* symbolAsterisk
  symbolCircle
  symbolCross
  symbolDiamond
  symbolDiamond2
  symbolPlus
  symbolSquare
  symbolSquare2
  symbolStar
  symbolTriangle
  symbolTriangle2
  symbolWye
  symbolX */
  linker_thumb_shape: 'symbolCircle',
  /* symbolCircle
  symbolCross
  symbolDiamond
  symbolDiamond2
  symbolSquare
  symbolSquare2
  symbolStar
  symbolTriangle
  symbolTriangle2
  symbolWye */
  head_image_shape: 'symbolCircle',
  chart_head_bg: '#ffffff',
  auto_set_chart_head_bg: false,
  display_tree_in_step: false,
  auto_display_tree_in_step: true,
  tree_level_step: 2,
  pallet: {
    h: 10,
    s: 0.5,
    l: 0.5,
    darker: 3,
    brighter: 0.8,
    bright100: 0.5,
    dark100: 0.5,
    gray: 50,
    gray85: 85
  },
  tree_link_type: undefined,
  random_data_length: 200,
  // random_data_locale: window.navigator.language, // Suspended - the user's device's locale
  autoInitialize: true,
  zoom_in_distance: 1.5,
  zoom_out_distance: 0.5,
  verticalSpace: '120px',
  font_link: "https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swap",
  font_name: "Lato",
  dropshadow: {
    x: "-50%",
    y: "-50%",
    width: "200%",
    height: "200%",
    dx: 1,
    dy: 1,
    stdDeviation: 4,
    floodColor: "rgba(91, 91, 91, 0.19)",
  }
})

7. API methods.

MethodParametersDescription
initialize()noneManually initializes treeSpider (required if autoInitialize is false).
resetZoom()noneResets zoom level and centers the chart to the default view.
updateChartHeadBg(color: string)color: stringSets the background color of all chart heads. Accepts hex codes, color names, or other CSS color formats.
on(eventName, callbackFn)eventName: TEventType
callbackFn: (data?: any) => null
Adds an event listener. See the “Events” table for available event types.
setOptions(options)options_to_set: Omit<ITreeSpiderMain,'targetContainer'>Sets or overrides library options. Best used before initialization, especially when autoInitialize is false.
zoom(direction)`dir: ‘in’ \‘out’`Programmatically zooms the chart in or out.
startStopRotateCW()noneStarts or stops clockwise rotation (only applicable to radial/circular tree types).
startStopRotateACW()noneStarts or stops anticlockwise rotation (only applicable to radial/circular tree types).
rotateOnceCW()noneRotates the tree once clockwise (only applicable to radial/circular tree types).
rotateOnceACW()noneRotates the tree once anticlockwise (only applicable to radial/circular tree types).

8. Event handlers.

Event NameDataDescription
library.init{ rootContainer: HTMLElement }Emitted once after treeSpider is initialized.
chart_head.create{ headNode: SVG }Emitted after a chart head is created, but before it’s added to the UI. Provides the SVG element.
chart_head.expanded{ svgNode: SVG, head_data: Object, pointPosition: number }Emitted when a chart head is expanded. Provides the SVG node, data, and point position.
chart_head.collapsed{ svgNode: SVG, head_data: Object, pointPosition: number }Emitted when a chart head is collapsed. Provides the SVG node, data, and point position.
zooming{ e: ZoomBehavior }Emitted during zooming and panning interactions (including automatic zooming/panning). Provides D3 zoom data.

You Might Be Interested In:


Leave a Reply