Giter VIP home page Giter VIP logo

treeviz's Introduction

Treeviz

Known Vulnerabilities license

This javascript module aims at providing an easy interface in order to represent tree diagrams on screen with the ability to handle dynamic data flows. The data format must be JSON.

Installation

With npm :

npm install treeviz

and then you can use it with :

import {Treeviz} from 'treeviz';

Or download this zip repository in the Github Release section and link the dist/treeviz.js file in your page directly : <script src="./dist/index.js><script>

Usage

Vanilla JavaScript

// Define a tree element where dimensions are mandatory
<div id="tree" style="height:700px; width:900px"></div>

<script>
// Define a dataset
var data = [
  { id: 1, text_1: "Father", father: null },
  { id: 2, text_1: "Child A", father: 1 },
  { id: 3, text_1: "Child B", father: 1 },
  { id: 4, text_1: "Subchild C", father: 2 }
];

// Define and configure a tree object
var myTree = Treeviz.create({
  htmlId: "tree",
  idKey: "id",
  hasFlatData: true,
  nodeColor: (nodeData) => "grey",
  relationnalField: "father",
});

// Display the tree based on the data
myTree.refresh(data);
</script>

To update the tree visually you will just have to pass new data to the refresh method like this :

myTree.refresh(data);
myTree.refresh(data_update1);
myTree.refresh(data_update2);

The tree will be clever enough to updates only the part of the trees that have been added or removed in the dataset, and so it won't redraw the entire tree.

Treeviz Example

Hierarchical data case :

var hierarchical_data_example = {
  name: "Mom",
  qty: 10,
  children: [
    { name: "Son A", qty: 3 },
    { name: "Son B", qty: 7 },
  ],
};

var myTree = Treeviz.create({
  htmlId: "tree",
  idKey: "name",
  hasFlatData: false,
  relationnalField: "children",
});

myTree.refresh(hierarchical_data_example);

API

The big part of the API is configuring the tree before passing data to it :

Treeviz.create(config);

The table below lists all the avalaible key that the config object can have

Key Type Default Definition
htmlId string (Required) The HTML id tag on the page where the tree should be drawn. It must have a width and an height specified
idKey string "id" The key in a data item representing the unique identifier of a node
relationnalField string "father" In case of flat dataset, usually the relationnal field between each node is the field representing the father of the node, linking it to the id of the field. (See example below).
hasFlatData boolean true Specify whether the data passed to the tree is flat or already hierarchical
hasPan boolean false Toggle the ability to pan the tree
hasZoom boolean false Toggle the ability to zoom the tree
nodeWidth number 160 Width of a node in px
nodeHeight number 100 Height of a node in px
linkColor function (node: NodeData) => "#ffcc80" Color of the link
linkWidth function (node: NodeData) => 10 Width of the link
linkShape "quadraticBeziers" | "orthogonal" | "curve" "quadraticBeziers" Shape of the link
renderNode function (node: NodeData) => null HTML template for every node
isHorizontal boolean true Direction of the tree. If true, the tree expands from left to right. If false, it goes from top to bottom
onNodeClick function (node: NodeData) => null Function handling the event when someone click on it
onNodeMouseEnter function (node: NodeData) => null Function handling the event when someone hover a node
onNodeMouseLeave function (node: NodeData) => null Function handling the event when the mouse pointer leaves a node
mainAxisNodeSpacing number or "auto" 300 Set the distance in pixels between two depths in the tree. If the value is auto it will automatically display the tree to fit the size of the container.
secondaryAxisNodeSpacing number 1.25 Set the distance between nodes in the same level as a coefficient of node dimensions. Recommended to have the value superior to 1
marginTop number 1.25 Set the margin between the SVG element and the tree
marginBottom number 1.25 Set the margin between the SVG element and the tree
marginLeft number 1.25 Set the margin between the SVG element and the tree
marginRight number 1.25 Set the margin between the SVG element and the tree
duration number 600 The duration of the animation transition between layouts
data any Needed for Typescript projects only to type the NodeData argument

And then, we have the NodeData type that is passed as callback of some functions: type NodeData { data: // the data of each item settings: // the settings object }

Contributing

  • Clone the repo.
  • Run npm install.
  • Run npm run dev, then you can edit the files in the ./src folder and the ./example/index.html file.
  • To publish (admin rights), run npm run build && npm publish.

Credits

This module is based on d3 library, credit to all the contributors of this project.

License

MIT

treeviz's People

Contributors

andrew9994 avatar kyjus25 avatar pierrecapo avatar pronink avatar stevegichure avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

treeviz's Issues

Dynamic Node Height

There must be feature to have a dynamic node height, based on the content of the node, instead of having just pixel based node height.
Thanks

Unable to use React components within the node HTML

HI Pierre,

Was hoping you could shed some light here. In the demo code you have this for the renderNode parameter of the TreeViz call:

renderNode={(node) =>
<div style="height:${node.settings.nodeHeight}px;display:flex;align-items:center;margin-left:12px">Node name: ${node.data.text_1}</div>
}

Is there an accepted way to return a React component rather than constructing bare HTML?

If not, do you think it is possible it could be updated to do so?

Thanks very much,

Peter.

Doc/readme using in correct parameter for flat data

Hi Pierre,

Still working with this, it's great!

Had a bit of a wrangle with flat data, and found that the configuration table are correct in the use of 'hasFlatData=', but the two examples you give just above uses 'flatData='

Hope that helps! :)

Peter.

[FEAT] Expose scrolling functions

Issue

There currently exists no way to manipulate the transform of the tree after it has been rendered. When the SVG is given full page width/height, the tree is rendered to the top left of the screen.

For instance, to center the tree, marginLeft and marginTop can be used on initial creation, but unless you know ahead of time how big your tree is it is difficult to calculate the centerpoint. These functions also have no effect once the tree is already rendered, like when calling refresh() and providing a new settings. I would expect the new margin values to be respected.

Proposed Solution

Expose various functions to smoothly scroll to common key views:

  • Smoothly translate/zoom the tree so that the entire tree is in view and maximizes available screen/SVG dimensions
  • Smoothly translate to a specified Node at a configurable zoom

IE11 TypeError

Hi Pierre,

it's always me, and I apologize as I know IE is not the best browser but in this situation I am forced to use it. After fixing the various (nodeData) => XX stuff, running Treeviz on IE11 I get this:

Unable to get property 'setProperty' of undefined or null reference

I even added the Array.prototype.find from here (https://gist.github.com/markhowellsmead/7fa5ad4a7d2eb6245cae13942da78b6a), but it still bombs out...

Do you happen to know what the problem is?

Thank you in advance.

Andrea.

Graph not updating when data changes. (TreevizReact)

When data changes, the graph stays the same. I updated the percentage, but it is not changing in the graph. I also updated the selectedNode to change the color. But same. Here is my example code:

<TreevizReact
    data={data}
    idKey={'id'}
    relationnalField={'father'}
    nodeWidth={200}
    mainAxisNodeSpacing={2}
    secondaryAxisNodeSpacing={1.3}
    renderNode={(node: any) =>
        `<div style="height:${node.settings.nodeHeight}px;
        display:flex;
        align-items:center;
        background-color:${props.selectedNode?.id == node.data['id'] ? '#cccccc' : '#dfe8df'};
        border-radius: 0.3em;
        padding: 1em;
        margin-left:12px"
        id=${node.data['id']}>
        Node name: ${node.data['name'].split('|')[0]}
        Percentage: ${node.data['percentage']}
        </div>`
    }
    onNodeClick={(event: any) => {
        if (event?.target?.id != null) {
            props.setSelectedNode(ingredients.find((node: any) => node?.id == event?.target?.id));
        }

    }}
    duration={500}
    linkWidth={(node: any) => (node['weight'] * 100)}
    linkShape={'quadraticBeziers'}
/>

Changing position of root node after re-render tree

Hi Pierre! I am using Treeviz tree diagram with React. I am changing isHorizontal props of tree dinamically, whenever tree data is too long i switch to display it vertically and when my dataset is small I display it horizontally. I want to do that if i click one of the tree nodes it changes the dataset re-render my tree. It successfully changes from horizontal to vertical and vica versa but my root will stay in the same position. How could i centralize my tree whenever it re-renders.

Issue with importing when using NextJS

Hi again, sorry to bother you twice in one day...

When I refresh the page, or I am building my nextJS app, I'm getting this error come up :

Screenshot 2020-04-06 at 16 44 57

I'm unsure why this is happening, but suspect it may be something to do with the version of javascript that the typescript is being compiled into, causing the import to fall over.

I'm using the demo code almost unaltered for this, so I don't think it is something I have done, but happy to be corrected.

Hope you can point me in the right direction?

Thanks!

Peter

Separate options for hasPanAndZoom?

Would it be possible to split this out into two options? For example if I wanted to enable panning but disable zooming I could pass

hasPan: true,
hasZoom: false,

Thanks

issues updating data

Hello,
I get my data file from an ajax call, first time it works great, the second time, the original root stays the same. Am I missing something in my code? Here's relevant code:

<script type="text/javascript" src="~/Scripts/treeviz/index.js"></script> <script> var myTree = Treeviz.create({ htmlID: "tree", nodeField: "MatlItem", flatData: false, relationnalField: "Children", zoomBehavior: true, nodeWidth: 120, nodeHeight: 75, nodeColor: (nodeData) =>"#ffffff", horizontalLayout: false, linkColor: (nodeData) => "#000000", linkShape: "orthogonal", linkWidth: (nodeDatat) => 3, nodeTemplate: (nodeData) => "
" + nodeData.MatlItem + "
ย " + /* Number(*/ nodeData.LeadTime /*).toFixed(5) */ + "ย 
" }); function getBom() { var item = $("#txtItem").val(); $("divLoading").show(); if (item) { $.ajax({ cache: false, type: 'Get', url: '@Url.Action("GetBom")', data: { itm: item }, success: function (data) { $("#divLoading").hide(); if (data.Success == "OK") { myTree.refresh(data); } else { alert(data.Message); } } }); } } $(function () { $("#tree").width($(document).width()).height($(document).height() - $("#criteria").height()); }); </script>

bottom to top?

I know setting horizontalLayout to false will present tree vertically from top to bottom, but can I start from bottom to top? like real tree?
Where first parent starts at the bottom of a div then growing up.

bottom to top?

I know setting horizontalLayout to false will present tree vertically from top to bottom, but can I start from bottom to top? like real tree?
Where first parent starts at the bottom of a div then growing up.

online demo?

It would be nice to put link to online demo for "first look"

Zoom on mouse location

Hi Pierre,

Just wanted to flag something I have noticed. When using your Storybook example to zoom in, the zoom functionality works as expected on the x-axis but on the y-axis it seems to zoom downwards of the mouse position.

This in a horizontal layout isn't the largest of issues, however I use the treeviz in a vertical layout, which means while it maintains a correct y-axis position, the zoom seems to veer right on the x-axis.

Just wondering if there is a fix that you can see for this?

Thanks in advance,

Seb

treeviz and ie

Hi Pierre,
It's me again.
One of the requirements to display the diagram is IE compatibility. The reason IE is important is because the database that we are using uses IE to display reports, so it's kind of mandatory to have IE compatibility. Well, I hate IE and was using chrome to develop. But now, we're in a testing phase, and IE compatibility requirement is starting to bite me. I am getting the following errors while running treeviz in IE:
SCRIPT1002: Syntax error at index.js (1, 1192).
Since the index.js is minified there isn't a lot I can do on my end.
I believe it happens when parsing the config specifically when parsing the following line, because the second error is SCRIPT1002: Syntax error at my_html_file.js at this line:
nodeColor: (nodeData) => "#ffffff"
It works fine on Edge, it's just IE that's causing the issue.
Any help would be appreciated.

Refresh issue. TypeError: Cannot read property 'x0' of undefined

Hello !
I made a function when you click into one node, in one copy of original data, I delete all its childrens, making a "grouping feature" (gif at bottom). Then I call refresh(newData) to update the tree.
But sometimes the nodes and lines which connects that nodes disapears:
image
In the console, each refresh I received this: (index.js is the compiled treeviz library)

angular.js:14642 TypeError: Cannot read property 'x0' of undefined
    at SVGGElement.<anonymous> (index.js:1)
    at SVGGElement.<anonymous> (index.js:1)
    at xn.each (index.js:1)
    at ut (index.js:1)
    at xn.attr (index.js:1)
    at Object.n.drawNodeExit (index.js:1)
    at index.js:1
    at Object.refresh (index.js:1)
    at Controller.renderTree (Controller.ts:278)
    at eval (Controller.ts:142)
    at eval (angular.js:17000)
    at m.$digest (angular.js:18182)
    at m.$apply (angular.js:18480)
    at l (angular.js:12501)
    at XMLHttpRequest.s.onload (angular.js:12655) "Possibly unhandled rejection: {}"

If with the same current data I do:

this.treeChart.clean();
this.treeChart = null;

... and then re-render with the same data that before, it fixes:
image
So I think there must be an error in the refresh function. Can I get a "not minified" version of compiled treeviz to investigate it better?
Here one gif of grouping feature (and a minor transition glitch):
ezgif-2-2f62c045276f
Object example:

{
id: 90100000,
father: 1000100000,
...
},

Thanks a lot !!
Regards

areaWidth, areaHeight being ignored...?

Hi!

Been having a play with this, but no matter what I do, I can't get the canvas size to be any different from 800x500 as the default is.

Any ideas? I couldn't see anything in the code immediately.

Expected usage:

<TreevizReact
        className='machineView'
        data={data}
        idKey={'id'}
        relationnalField={'father'}
        nodeWidth={130}
        nodeHeight={60}
        areaHeight={300}
        areaWidth={1000}........

Thanks,

Peter.

Critical dependency: the request of a dependency is an expression

Hi, I'm using treeviz with React 17 and I get error when build in the build server: Critical dependency: the request of a dependency is an expression. In my MacBook I don't get this error, only in build server when build in docker container(image node:14-alpine). I googled this error message and get this response from Stackoverflow https://stackoverflow.com/questions/54354190/how-to-resolve-critical-dependency-the-request-of-a-dependency-is-an-expressio. Can you help me?

Zoom and Pan has not effect

I am using treeviz with an Angular application using typescript. The tree is created without a problem. I am setting hasZoom and hasPan to false but unfortunately it does not show any effect. The tree gets zoomed on scroll anyway and pan still works.

Standalone library?

I am having a phenomenally hard time to get npm to work behind a corporate firewall, no matter what I do with the npm proxy settings. Is there any chance someone could make a standalone Javascript library out of this beautiful tree renderer?

Thank you in advance.

Andrea.

linkColor doesn't re-trigger on update

If you have a linkColor that depends on some property of the node itself, and the node updates, the linkColor won't update acording to it:

image

In this case, the node and the link started in red color, after an update a property of the node changed and the node background changed to green (but not the link).

I found that this is because the links only draw 1 time. (probable because performance)

Maybe its posible to configurate if linkColor is executed several times or no ?

package is not built when installing with npm

Hi @PierreCapo !
First of all thank you for the awesome package ๐Ÿ‘Œ
Unfortunately if i run npm install treeviz the package is not built and the dist folder is missing from the node_modules/treeviz.
I believe this can be solved with the prepare hook in the package.json

Request for more documentation on the new version

Hello,
Thank you for your work I love this library

I am currently using an older version of this library and I could see that some options have changed, for
example:

  • clicking on a node, the actions are not the same. I didn't find any concrete
  • I'm looking for the possibility to use already hierarchical data and parent-child data to display the data in steps and at the same time to be able to click on a node, to open only the information of the parent and child node. I see that it is possible to do it more easily with the new version

example on the more advanced use of the library except this old link I used to learn: https://codepen.io/pierrecapo/pen/MPbBdv which is not up to date either.

The only link I found was to the storybook site, but it didn't show me the 'inner' workings of the code. Is it possible to have a more advanced and visible use of the code like in the old example in codepen.io?

Thank you very much for your answer

treeviz issue with Edge

On Edge, when you zoom in/out the node looks like it's cutoff.
Here's what it looks like, prior to zoom:
image
And after zoom:
image
Thanks,
Yury

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.