npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-treekey

v1.1.1

Published

A keyboard controllable tree for react

Downloads

15

Readme

react-treekey

npm package Code style

A React Tree View Component with Keyboard Navigation. Intuitive and Customisable.

Installation

npm install react-treekey --save

Example

The example page includes both a basic no config usage of the component as well as another one with customized elements and manual management of current selected and expanded nodes.

The code for the examples can be found here:

No Config Example

Customized Example

Usage

Here is the minimum code required, it's all you need:

(The examples page include a few extra details to help with styling)

import React from "react";
import { TreeKey } from "../../src";

let treeA = {
  name: "root",
  children: [
    {
      name: "child1",
    },
    {
      name: "child2",
    },
    {
      name: "child3",
      children: [
        {
          name: "grandchild1",
        },
        {
          name: "grandchild2",
          children: [
            {
              name: "greatgrandchild1",
            },
            {
              name: "greatgrandchild2",
            },
          ],
        },
        {
          name: "grandchild3",
        },
        {
          name: "grandchild4",
        },
        {
          name: "grandchild5",
        },
      ],
    },
    {
      name: "child4",
    },
  ],
};

export class BasicTree extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // the tree's default starting selected node is the root if we don't pass it manually
      // this prop is here only to keep track of the current selected node, so we're initing it as the root
      selectedNode: treeA,
    };

    this.onSelectNode = this.onSelectNode.bind(this);
  }

  onSelectNode(node) {
    console.log(node);
    this.setState({ selectedNode: node });
  }

  render() {
    return (
        <TreeKey tree={treeA} onSelectNode={this.onSelectNode} />
        <pre>{JSON.stringify(this.state.selectedNode, undefined, 2)}</pre>
    );
  }
}

Props

data

PropTypes.oneOfType([PropTypes.object]).isRequired

The tree structure that gets passed down to the component. It can include any properties you like, as long as a given property's children are contained in an array called 'children' (see data example above).

This structure gets mutated with non-enumerable properties prepended with a dollar sign ($) that contain references to each properties' siblings, parents, and children. They get automatically stripped out if you deserialize the structure back to a JSON string, so you can mutate and save the tree state without worrying about that. You can also use these properties for the sake of other advanced operations you might want to make, including CRUD operations. (see customized examples). These properties are $parent, $firstChild, $lastChild, $previousNode and $nextNode.

NOTE: The component was built mostly for read-only use cases. A couple of CRUD operations were added in the customized example for fun, but they're not as efficient as if they were built natively (with a flat map based data structure the process wouldn't require full tree traversals like in the example). Currently, following a CRUD operation, it's necessary to perform a serialization followed by deserialization (to strip the metadata props), as well as an increment to the 'key' prop in the TreeKey component to force the constructor to rerun the metadata attribution. Unless the data tree is huge, the approach from the example should work just fine.

multiSelection

multiSelection: PropTypes.bool Indicates whether selecting multiple nodes is allowed. If false, SHIFT and CTRL keys have no effect and onSelectNode gets called with only the selected node. Otherwise, multiselection works as normal and onSelectedNode gets called with an array of selected nodes.

onSelectNode

onSelectNode: PropTypes.func Gets called every time a node gets selected (whether by mouse click or keyboard control). If you're passing the selected nodes list manually, you need to use this function to keep the state updated. If the multiselection prop is false, it gets called with the single selected node, otherwise it gets called with the array of selected nodes (even if it's just one).

onExpandNode

onSelectNode: PropTypes.func Gets called every time a node gets expanded/collapsed (whether by mouse click or keyboard control). Like with the selected nodes, if you're passing the expanded nodes list manually, you need to use this function to keep the state updated.

selectedNodes

PropTypes.arrayOf(PropTypes.object) The list of selected nodes. This allows you to manually decide which nodes should be displayed as selected. If omitted, the component automatically selects the root on initialization and handles the selection by itself. This is always an array, whether or not multiselection is true.

expandedNodes

PropTypes.arrayOf(PropTypes.object) The list of expanded nodes. This allows you to manually decide which nodes should be expanded. If omitted, the component automatically expands the root on initialization and handles the expansion automatically by itself.

style

PropTypes.shape({ 
    root: PropTypes.object,
    node: PropTypes.object,
    listItem: PropTypes.object,
    nodeToggleWrapper: PropTypes.object,
    nodeToggleSvg: PropTypes.object,
    nestedList: PropTypes.object
    })

An object with the styling for each of the main components. Any property that isn't set will be set to the default found here.

templates

PropTypes.shape({ header: PropTypes.func, toggle: PropTypes.func }) If you want to override the components for the header or the toggle, to include specific styles or behaviors, use this object to override one or both components.

The default templates are here.

Example:

let templates = {
  toggle(isExpanded) {
    // this actually gets called with the node argument as well
    // it's omitted, because the default template doesn't make use of it
    const svgStyles = {
      fill: "white",
      strokeWidth: 0,
      transformOrigin: "center",
      transform: `rotate(${isExpanded ? "90deg" : "0"})`,
    };

    let { height, width, points } = styles.nodeToggleSvg;

    return (
      <svg height={height} width={width}>
        <polygon points={points} style={svgStyles} />
      </svg>
    );
  },

  header(node) {
    return <span style={{ paddingLeft: "7px" }}>{node.name}</span>;
  },
};