e812fe8b7252a290d0d506fa92fdf73c9e95285d
Checkbox Tree
A dependency-free, instance-based checkbox tree for browser ES modules. It supports cascading selection, indeterminate parent states, expandable branches, multiple independent instances, and optional local-storage persistence.
Install
npm install @aaronaxvig/checkbox-tree
The package is not published yet. During local development, install it by path:
npm install ../checkbox-tree
Usage
import { CheckboxTree } from "@aaronaxvig/checkbox-tree";
import "@aaronaxvig/checkbox-tree/styles.css";
const tree = new CheckboxTree(document.querySelector("#example-tree"), {
initiallySelected: true,
storageKey: "example-tree-state",
onSelectionChange({ selectedIds, selectedNodes }) {
console.log(selectedIds, selectedNodes);
},
});
tree.setData([
{
id: "fruit",
label: "Fruit",
children: [
{ id: "apple", label: "Apple", metadata: { color: "red" } },
{ id: "pear", label: "Pear", metadata: { color: "green" } },
],
},
]);
For applications without a bundler, serve or copy the two files in src/ and
use relative URLs:
<link rel="stylesheet" href="./checkbox-tree.css">
<script type="module">
import { CheckboxTree } from "./checkbox-tree.js";
</script>
Every node requires unique string id and label properties. Nodes may also
have children, application-owned metadata, and selectable or disabled
flags.
API
new CheckboxTree(container, options)creates an independent instance.setData(nodes)validates and renders nodes, then restores saved state.getSelectedIds()returns selected node IDs.getSelectedNodes()returns selected source node objects.setSelectedIds(ids, { notify })replaces the selection.restoreState()restores selection and expansion state.destroy()removes listeners, markup, and the root CSS class.
Options:
initiallyCollapseddefaults totrue.initiallySelecteddefaults tofalse.storageKeydefaults tonull, which disables persistence.onSelectionChangereceives{ selectedIds, selectedNodes }.
Styling is namespaced under .checkbox-tree. Override the custom properties
--checkbox-tree-indent, --checkbox-tree-toggle-size, and
--checkbox-tree-hover-color in the consuming application.
Development
npm install
npm test
npm run pack:check
Future demo ideas
- Add population metadata to the country, state, and county nodes and display the total population represented by the current selection. Define the aggregation rule carefully so checked ancestors and their checked descendants are not counted twice; one option is to total only the most specific checked nodes.
Languages
JavaScript
96.7%
CSS
3.3%