Giter VIP home page Giter VIP logo

treejs's Introduction

@widgetjs/tree

Version Downloads Total Downloads Monthly gzip size gzip size

A lightweight flexible tree widget.

Features

  • ๐Ÿš€ Compatible with VanillaJS / React / Vue
  • โœ‚๏ธ Tiny size after gzip
  • ๐ŸŽŠ Zero dependence
  • ๐ŸŽ‰ Events supported

Demo

Online Demo

demo.gif

Install

npm i -S @widgetjs/tree

Usage

React/Vue usage

import Tree from '@widgetjs/tree';

VanillaJS usage

<script src="path/to/tree.min.js"></script>

Initialize

new Tree(treeContainer, parameters), returns initialized Tree instance.

  • treeContainer - string - css selector of the tree container(document.querySelector inside).
  • parameters - object - options of the tree.

Basic Node Format

{
  "id": "unique_ID",
  "text": "node-0",
  "attributes": {},
  "children": [],
  "checked": true
}
Name Type Description Required
id any unique id Required
text string tree node label Required
attributes object custom attributes of the node Optional
children array children of current node Optional
checked boolean whether the node is selected or not Optional

Example

const myTree = new Tree('#container', {
  url: '/api/treeJson',
});

Parameters

Name Type Description
url string a URL to retrieve remote data,or use data
method string http method(GET/POST), default 'GET'
data array the json tree data
values array ids which you want to check
closeDepth integer expand level
beforeLoad function invoke before the tree load data. Format raw data in this function.
loaded function invoke after the tree load data
onChange function invoke when the node status change

Example

const treeData = [
  {
    id: '0',
    text: 'node-0',
    children: [
      {
        id: '0-0',
        text: 'node-0-0',
        children: [
          {id: '0-0-0', text: 'node-0-0-0'},
          {id: '0-0-1', text: 'node-0-0-1'},
          {id: '0-0-2', text: 'node-0-0-2'},
        ],
      },
      {id: '0-1', text: 'node-0-1'},
    ],
  },
  {
    id: '1',
    text: 'node-1',
    children: [{id: '1-0', text: 'node-1-0'}, {id: '1-1', text: 'node-1-1'}],
  },
];

const myTree = new Tree('#container', {
  data: treeData,
});
const myTree = new Tree('#container', {
  url: '/api/treeJson',
  method: 'GET',

  values: ['1', '2', '3'],

  // only expand level 1 node
  closeDepth: 1,

  beforeLoad: function(rawData) {
    function formatData() {
      // do some format
    }
    return formatData(rawData);
  },

  loaded: function() {
    // do something or set values after Tree loaded callback
    // do not use arrow function `()=>` , if you use `this`, use function instead.
    // this context bind current tree instance
    this.values = ['0-1'];
  },

  onChange: function() {
    console.log(this.values);
  },
});

Properties

Property Type Operation Description
values array get/set selected values.
selectedNodes array get selected nodes data with attributes.
disables array get/set get disabled values, or set disable nodes.
disabledNodes array get disabled nodes data with attributes.

myTree.values

// get
const values = myTree.values;

// set
tree.values = ['0-1'];

myTree.selectedNodes

// get
const selectedNodes = myTree.selectedNodes;

myTree.disables

// get
const disables = myTree.disables;

// set
tree.disables = ['0-1'];

myTree.disabledNodes

// get
const disabledNodes = myTree.disabledNodes;

Events

Event Parameters Description
beforeLoad current data invoke before the tree load data
loaded null invoke after the tree load data
onChange null invoke when the node status change

Methods

Method Parameters Description
expandAll null expand all tree nodes
collapseAll null collapse all tree nodes

License

MIT


Like @widgetjs/tree? just ๐ŸŒŸ star the project! Create issues if you find bug.

treejs's People

Contributors

daweilv avatar dependabot[bot] avatar panietoar avatar shashfrankenstien avatar tuj84257 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  avatar  avatar  avatar  avatar

treejs's Issues

Darkmode would be nice

Here is how I got it to work if it helps anyone.

css
:root{--text-color:#000;--switcher-color:rgba(0,0,0,.4);--switcher-hover-color:rgba(0,0,0,.65);--checkbox-border-color:#d9d9d9;--checkbox-background-color:#f5f5f5;--checked-color:#1890ff;--disabled-color:rgba(0,0,0,.25);--disabled-border-color:#d9d9d9;--disabled-background-color:#f5f5f5}.treejs{color:var(--text-color)}.treejs .treejs-switcher:before{border-top-color:var(--switcher-color)}.treejs .treejs-switcher:hover:before{border-top-color:var(--switcher-hover-color)}.treejs .treejs-checkbox:before{border-color:var(--checkbox-border-color)}.treejs .treejs-checkbox:hover:before{box-shadow:0 0 2px 1px var(--checked-color)}.treejs .treejs-node__checked>.treejs-checkbox:before{background-color:var(--checked-color);border-color:var(--checked-color)}.treejs .treejs-node__checked>.treejs-checkbox:after{border-color:#fff}.treejs .treejs-node__halfchecked>.treejs-checkbox:before{background-color:var(--checked-color);border-color:var(--checked-color)}.treejs .treejs-node__halfchecked>.treejs-checkbox:after{background-color:#fff}.treejs .treejs-node__disabled{color:var(--disabled-color)}.treejs .treejs-node__disabled .treejs-checkbox:before{border-color:var(--disabled-border-color)!important;background-color:var(--disabled-background-color)!important}.treejs .treejs-node__disabled .treejs-checkbox:hover:before{box-shadow:none!important}.treejs .treejs-node__disabled .treejs-node__checked>.treejs-checkbox:after,.treejs .treejs-node__disabled .treejs-node__halfchecked>.treejs-checkbox:after{border-color:var(--disabled-border-color);background-color:var(--disabled-background-color)}@media (prefers-color-scheme: dark){:root{--text-color:#fff;--switcher-color:rgba(255,255,255,.4);--switcher-hover-color:rgba(255,255,255,.65);--checkbox-border-color:#555;--checkbox-background-color:#444;--checked-color:#1890ff;--disabled-color:rgba(255,255,255,.25);--disabled-border-color:#555;--disabled-background-color:#444}}

JS in loaded
`
const treeContainer = document.querySelector('.treejs');
const applyDarkMode = (isDarkMode) => {
if (isDarkMode) {
treeContainer.classList.add('treejs-dark');
} else {
treeContainer.classList.remove('treejs-dark');
}
};

            const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
            applyDarkMode(darkModeMediaQuery.matches);

            darkModeMediaQuery.addEventListener('change', (event) => {
                applyDarkMode(event.matches);
            });

`

'check' property not working as expected

I believe this to be a bug, but if not, please could you explain the correct use?

I get a collection of data (not through jstree ajax) which is in a flat form. Each datum has a Parent ID field which allows me to build a hierarchical structure from the data.

The first think I do, before building this structure is to map my data over into a structure that matches a treejs node stucture, and I also set the checked property based on some condition, ie

{ "id": datum.id, "text": datum.text, "checked": true, "children":[] }

When I do this, only nodes without children are set. Yet, when looking at the data for the nodes, all nodes have 'checked':true.

I can use the values option to set the checked nodes, but it is difficult to set nodes deeper than one level to checked, as i have to figure out the id path to that node first to check it, eg "3-3-6-1"

Any thoughts?

Remove checkbox

Hi, is it possible to remove the checkboxes? just to have a normal tree view behaviour.
Kr

`checked: true` boolean inversion issue

Hi,

If your tree array is as such:

let data = [
  {
    "id": "0",
    "text": "0",
    "checked": true,
    "children": [
      {
        "id": "0-0",
        "text": "0-0",
	"checked": true,
        "children": []
      }
    ]
  }
]

Then no nodes are selected. This is because the checked must be implemented as a toggle of sorts, inverting the previous value, so because the parent is checked, setting checked: true on a child causes the parent to be inverted, unchecking it and seemingly also unchecking the child.

This doesn't make intuitive sense and it took me a good few minutes to figure out what was going on in this case.

Because of this, you either need to set checked: true on the most-parent node that you want all children checked in, or, if you don't want all that parent's children checked, then you need to not have the property on the parent and only on the child nodes you want checked.

checked: true should mean I want that entry checked, regardless of any previous values; there should be no inversion toggling.

Is there any way to add data later?

All the examples except the Ajax one need the tree data structure to be defined prior to creating the tree object.
We cant use the ajax option as the data returned from the ajax APi needs transformation into the right json format.
We use fetch to get the required data, then format it into the right data structure in the promise, then we need to get the tree to "take" this data at runtime, and display it.

is there any mechanism to dynamically add or change the data structure?

Cannot convert undefined or null to object

Uncaught TypeError: Cannot convert undefined or null to object
at Function.entries ()
at t.default (tree-1.8.3.min.js:1:9571)
at d.load (tree-1.8.3.min.js:1:3392)
at new d (tree-1.8.3.min.js:1:2846)

I try to load from url but url is not requested at all.

const myTree = new Tree("#WzIndustry", {
    url: "@Url.Action("GetIndustriesWzAsJson", "Data")",
    method: "GET",
    values: null // selected values
});

Submit Checkboxes to form

Is it possible for the tree to use checkboxes to allow for the tree values to be submitted in a form?

Support for adding tree in shadowRoot

Hi,
I want to use treejs in my web-component but the initialisation of tree is done by providing a query selector input( container ). but this query over entire document. If the container input for attaching tree could be a HTMLElement or a string( for query selector input ) then i could attach it in my web component.

Some nodes are not checked

Hello,
Strange problems, please see code bellow

`

<title>
</title>
<script src="dist/tree.min.js"></script>
<script> let data = [{"id":1,"text":"Home","checked":true,"children":[{"id":7,"text":"TimeTable","checked":true,"children":[{"id":8,"text":"Staff Att","checked":true,"children":[]}]}]},{"id":2,"text":"Student","checked":true,"children":[]},{"id":3,"text":"Staff","checked":true,"children":[]},{"id":4,"text":"Library","checked":true,"children":[{"id":9,"text":"Book Issue","checked":true,"children":[]},{"id":10,"text":"Book Return","checked":true,"children":[]},{"id":11,"text":"Book Fine","checked":true,"children":[{"id":12,"text":"Fee Payment","checked":true,"children":[]}]}]},{"id":6,"text":"StudentAtt","checked":true,"children":[]}]
let tree = new Tree('.treeContainer', {
    data: [{ id: '-1', text: 'root', children: data }],
    closeDepth: 3,
    loaded: function () {
    },
    onChange: function () {
        console.log(this.values);
    }
})
</script> `

All nodes are checked by initial data, but 2 nodes "Book Issue" and "Book Return" are not checked, very strange.

obrazek
Can you check it, please? Thank you.

Invalid Node Names in Event Handler

Hi,

The event handler for the nodes has the nodeName properties encoded as all capitals.

HTML specification says lowercase; while this seems to work on plain HTML sites, this breaks the event handler for anything using xHTML.

Unfortunately, this is an inconsistency and mis-implementation by browser vendors that has persisted due to compatibility reasons.

The fix would be to either convert all nodeName properties to upper/lowercase before comparison or using the localName property instead, which correctly returns lowercase values in both cases.

expand tree

I make great use of the library, thanks a lot! Below is more of an idea than issue.
I found that it should be nice to have some hook/callback to expand/close the entire tree.
Logging tree.closeDepth yields undefined, so it can't be manipulated once the tree is instantiated.
Thank you!

Some questions

Hi

This is awesome, a couple of questions.

Q1. Is it possible to indicate an icon for open/closed state?
Q2. Is is possible to create, update and delete nodes at runtime from the tree?
Q3. Is it possible to find a node by path or particular reference like id?

Thanks.

Last changes are not published to npm

This tree widgets looks good. It's simple and easy to use. It is a pity that the latest changes that include the onChange event handler are not published to npm. Is it possible to release a new version?

TypeError with data via url

I got a JS-Error when I try to get data via Url:

Uncaught TypeError: can't convert undefined to object

This is the code:

    const myTree = new Tree('#myTree', {
      url: 'http://localhost:8000/treeviewJson',
      method: 'GET',
    });

But this works:

let url = 'http://localhost:8000/treeviewJson';

fetch(url)
.then(res => res.json())
.then(out => {
  
  const myTree = new Tree('#myTree', {
    data: [out],
    })
}
  );

This is the response of the URL

# curl http://localhost:8000/treeviewJson
{"id":"0","text":"Node 0","children":[{"id":1,"text":"Node 0-1"},{"id":2,"text":"Node 0-2"}]}[]

It's generate by PHP:

function treeviewJson(): Response
    {
        $data = [
            'id' => '0',
            'text' => 'Node 0',
            'children' => [
                [
                    'id' => 1,
                    'text' => 'Node 0-1'
                ],
                [
                    'id' => 2,
                    'text' => 'Node 0-2'
                ],
            ]
        ];



        $response = new Response();
        $response->setContent(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
}

expand the tree only one level

is there a possible way that i can expand just one level of the tree ? so my tree has like 5 levels and i only want to open one level at a time? is there a possible way to do so ?

my tree looks like this:

root
sublevel1
sublevel2

if i click on the root node i just want sublevel 1 to appear, but everytime all nodes appear.

thanks! :)

Only parent selected

Hey, I was wondering how to select only the parent node and deselect all of the children?

Does not work in IE11 in Win10.

This component does not appear to work in Internet Explorer 11 under Windows 10.

It requires polyfills for Object.assign/entries/values.

Vanilla/Dist completely broken?

Using tree.js and tree.min.js from the dist/ in this repo results in:

Uncaught SyntaxError: unexpected token: ':'[tree.js:1:11](https://<redacted>/js/tree.js)

Using standard script tag as documented for vanilla usage.

Looking at the object itself, doesn't look right either aside from the apparent syntax error.

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.