A lightweight, framework-agnostic treeview web component — virtual scroll, drag and drop, multi-select, search, context menus — built with vanilla TypeScript.
- 🚀 Showcase
- 🧪 Live demo
- 📘 Usage / API reference — every attribute, property, method, event.
- 🎨 Theming —
--wtv-*variables, dark mode,@layercascade. - 📚 Examples / cookbook — drag-drop, multi-select, clipboard, render callbacks, context menus.
- ♿ Accessibility — keyboard navigation, focus model, ARIA status.
- 📜 Release history
@keenmate/web-treeview is a custom element (<web-treeview>) that renders a hierarchical data list with full keyboard navigation, drag-and-drop, multi-select, search, context menus, and pluggable rendering. Framework-agnostic — works in React, Vue, Svelte, Blazor, plain HTML: assign nodes, and the tree renders.
Built on the same LTree path-based engine as @keenmate/svelte-treeview and ported to vanilla TypeScript with zero framework dependencies. If you know svelte-treeview, you already know the API surface.
Headline features:
- Flat rendering (up to ~10k nodes) and built-in virtual scroll (~50 DOM nodes for trees of 100k+).
- LTree path model (
'1','1.1','1.2.3') — including window trees cut from a big database ltree. - Three node states — the focused row, the selected set (Ctrl / Shift+click, Shift+arrows) and the checked set (checkboxes, cascade policies).
- Drag and drop — reorder, cross-tree, multi-drag, touch, glow / floating drop zones, page-wide arming.
- Multi-level context menus on core
/menu, clipboard (copyNodes/cutNodes/pasteNodes, cross-tree), bulk branch operations. - FlexSearch full-text search with filter and highlight modes.
- Theming via
--wtv-*variables on the--base-*contract — one theme drives svelte-treeview and every Keenmate component. - Render callbacks for rows, icons, tooltips, menus and empty / loading states; a pluggable
TreeViewRenderer<T>; fully typed generic<T>API; SSR safe.
Same logical tree, different DOM strategy — neither is "more mature", they target different priorities.
| svelte-treeview | web-treeview | |
|---|---|---|
| Rendering modes | Recursive (default) + flat | Flat only |
| Children DOM | .stv__children wrapper (recursive mode) |
None — siblings under .wtv__tree |
| Indent math | level × indent |
(level − 1) × indent (root at zero offset) |
| Virtual scroll | Flat mode only | Built-in (three-div spacer / translateY) |
| Label markup | <span class="stv__node-label"> by default — replace via nodeTemplate snippet |
<span class="wtv__node-label"> by default — replace via renderNodeCallback |
| Update mechanism | Svelte 5 runes + per-node _rev keyed {#each} |
Imperative reconciler diffing data-rev / data-expanded attributes |
svelte-treeview is broader (two rendering modes, easier vertical guide lines via .stv__children); web-treeview is purpose-built for virtual scrolling over large datasets with a flatter DOM.
Upgrade guide: the 2.0.0-rc07 release notes; full list: the CHANGELOG 2.0.0-rc07 section.
- Render callbacks — return the content, core
renderSlot, breaking —renderNodeCallback,renderHeaderCallback,renderFooterCallback,renderEmptyStateCallbackandrenderEmptyZoneCallbacknow return what to draw instead of fillingctx.contentElement/ctx.containerElement: a string is HTML, aNodeis mounted,null/undefineddraws the built-in content andfalsehides the slot. Their ctx gainslabels(ctx.labels.text(key, params)),isReadonlyandisDisabled. A node callback re-runs only when the node's state or something it receives changes (labels, locale, read-only / disabled), in place, so a focused input inside a custom node survives an unrelated input change. - Icons — core
renderIcon,renderIconCallback(name, ctx), breaking — Node icons follow the order every Keenmate component uses: markup → a core built-in name (user,check,settings, … as a masked--base-icon-*glyph) → the tree's ownrenderIconCallback(name, ctx)→ the page-widewindow.components.renderIconCallback→ an icon-font class on an inner<i class="wtv__icon …">inside the.wtv__node-iconwrapper. The rc06 hook(ctx) => voidthat filledctx.iconElementis gone; per-node markup comes fromgetIconCallback. Assigning the page-wide hook later repaints the icons in place. - Localization — flat label keys, page-wide dictionary,
translateCallback,locale, breaking —labelskeys are core/locale's flat<elementType>.<name>(noData→messages.noData,copy→menuItems.copy,loading→ariaLabels.loading);resolveLabel()is gone. Per key the instancelabelswin, then the tree's owntranslateCallback, the page-widewindow.components.locale.translateCallback, the page-wide flat dictionary ('web-treeview.messages.noData') and English. The newlocaleinput formats the counts in announcements through coreformatNumber, and assigningwindow.components.localere-renders every live tree in place. - Labels read their context —
{ctx.count},{ctx.name}, breaking — The announcement labels get their spot's context as{ ctx }(SearchResultsLabelContext,DropLabelContext, …): templates read{ctx.count}/{ctx.name}/{ctx.target}, atranslateCallbackgets it asparams.ctx(ctx.countfor the app's plural forms). English: "Results: {ctx.count}", "Items ({ctx.count})";ariaLabels.searchResultsOneis gone. - Accessibility and RTL — ARIA tree, announcements, mirrored layout — The body is
role="tree"and every row atreeitemwith level, position, expanded / selected / checked state; focus stays on the body and the active row isaria-activedescendant(core/a11y). Search results and drop outcomes are announced through coreannounce(). In adir="rtl"tree the indent, drop pads and glyphs mirror and ArrowLeft / ArrowRight follow the reading direction. Row ids now come from the node path, so repeated node ids no longer breakaria-activedescendant. - Selection and keyboard — the shared core rules, behaviour change — The selected set and Shift anchor run on core
createSelection: Ctrl+Shift+click adds a range, clicking an unselectable node keeps the selection, single mode ignoresselectAll(), and a click that changes nothing fires noselection-change. Shortcuts are matched by corematchesShortcut()with exact modifiers, and keys typed into a field inside a node stay in the field. Touch drag runs on corecreatePointerDrag(auto-scroll near the edges, Escape cancels; a touch drop'seventis aPointerEvent). The keyboard-navigation methods are renamed (breaking, no aliases):nav*→focus*/extendSelection*(navTo→focusAndSelectNode,navSelectNext→extendSelectionNext, also thenavigationOverrideskeys), andcopyNodeWithDescendantsisduplicateNode. - Inputs —
disabled/readonly, state attributes, stricter values —disabledblocks every user interaction and leaves the tab order;readonlyblocks data changes but keeps navigation, expand / collapse, selection and copy.expanded-paths/selected-paths/checked-pathsare attributes too.el.update(props)is gone: batch writes go through core'sel.setAttributes(props), which validates and reports refusals throughinput-rejected.drag-drop-moderefuses unknown modes, pixel inputs take bare numbers, anddrop-zone-max-width/flat-indent-size/virtual-scroll-container-heightare CSS lengths. Thethemeattribute is removed;data-themeon the host is the one per-instance switch.enable-flat-renderingis removed: flat rows are the only mode. - Motion and menus — animated expand / collapse, phone sheet — Rows an expand reveals fade and slide in, rows a collapse hides shrink away;
motion="none"or OS reduced motion makes it instant androw-animation-limitcaps it.collapseNodes()/collapseAll()now return a Promise that settles after the collapse applied, andexpanded-changefires then. The context menu takesmenu-presentation(auto= a bottom sheet on a phone,floating,sheet,drawer) andmenu-side, and is named by its node. - Build your own UI —
TreeViewEngineandTreeViewState, breaking for engine users — The engine classWebTreeViewisTreeViewEngine, with one settings shape: constructor →setOptions(partial)→getOptions()(TreeViewEngineOptions);getEngine()isgetState(). The headlessTreeEngineis the publicTreeViewState(setOptions/getOptions,TreeViewStateOptions). Both fill every missing option with the element's defaults from one input table, so an engine given onlynodesrenders like the element. Page-wide custom CSS (window.components['web-treeview'].customStyles) and thecustom-stylesattribute style the shadow root.
- Names — one vocabulary with
@keenmate/base-css-variables2.0 and svelte-treeview (breaking within the RC) — The click / Ctrl / Shift-click set is now selected (selectedPaths,selectNode,selection-change,.wtv__node-content--selected) and the checkbox state is checked (checkedPaths,checkNode/uncheckNode,checked-change), the words web-multiselect and the shared--base-selected-*tokens use. A wider naming pass followed: booleans readis*/should*/show-*/enable-*, state is a property (expandedPaths,selectedPaths,checkedPaths,focusedNode— noget*/set*twins), remove is programmatic (removeNode(s)) and delete is the user command (Delete key,beforeDeleteCallback,node-delete). There are no deprecated aliases, so search your code for the old names; the CHANGELOG lists every rename. - Callbacks & events — one context object,
el.controller, core actions — Every callback now takes ONE ctx carrying the node plus non-enumerablecontroller(the publicTreeViewControllerfacade, alsoel.controller) andelement;el.getController(), which leaked the internal engine, is gone. Events are present tense,composed: false, and each has anon*twin receiving the same detail (node-click,node-drop,selection-change,tree-change,action, …). Interceptors share core's before-hook contract:falsecancels, a value redirects, a throw cancels (beforeCopy/Cut/Paste/Delete/DragStart/Drop/Expand/Keydown/CheckboxToggleCallback). The context menu runs on core/menuwith action items, dividers and built-ins ('copy' | 'cut' | 'paste' | 'delete' | 'expand' | 'collapse'), plusrenderContextMenuCallbackfor a fully custom menu. - Window trees — the LTree keeps a path index (breaking for direct LTree users) —
LTreeNode.childrenis now an ordered array, and paths resolve through an internal path → node index, so lookups no longer walk segment by segment from the root. A node whoseparentPathis null,''or its own path is top-level whatever its path, so a window cut from a big database ltree (1.20.302without1/1.20) renders with its real paths: mapparentPathMemberand send the rows as they come. Levels count from the parent, soexpandLevelworks inside a window. - Scrolling — the container, never the page;
beforeScrollCallback— Keyboard moves,scrollToPathand the reveal after a paste scroll only the row's scroll container (the tree's own or a wrapper around the element) through core'sscrollIntoContainer, honouringscroll-padding/scroll-margin.beforeScrollCallback({ node, path, source, container, options })runs first for each of them (source: 'keyboard' | 'scroll-to-path' | 'paste'): returnfalseto skip the scroll, or options such as{ block: 'start' }to replace the defaults.scrollToPathgainsshouldRevealContainer(default on), which first scrolls the page to a tree that's off-screen. Keyboard moves always scroll instantly; programmatic jumps read--wtv-scroll-behavior. - Drag and drop — page-wide arming, a new empty drop zone, batch moves —
highlight-on-page-drag(same option and names as web-dropzone) arms a tree as soon as any node is dragged anywhere on the page: the host gets thearmedattribute and:state(armed), and an empty tree shows its drop zone at once. The empty zone has a new look (an icon above "Drop here", a thin dashed accent border, and a spotlight with the standard--base-shadow-lglift when engaged), and it no longer stays engaged after the pointer leaves across a fractional edge. Underneath sit themoveNodes/duplicateNodesbatch primitives, multi-drag, cross-tree copy through the clipboard registry,DropGroup[]fan-out frombeforeDropCallback,enable-tree-drop-zone, and reject feedback (node-drag-reject/node-drop-reject, the 🚫 badge). - Core platform —
BlissElement, responsive rules, motion level, the shared loader — The element runs on@keenmate/web-components-core(^1.0.0-rc17): onestatic inputstable,defer/release()/readywith a FOUC guard, and generatedcustom-elements.json/web-types.json/ VS Code data. Responsive rules (responsive/responsiveCallback, keyed by device or breakpoint) swap in a partial config per device class or window width.motion="auto | none | snappy | smooth",window.components.motionor adata-motionancestor sets every transition speed and the scroll behaviour; the OS reduced-motion setting always wins. Loading states draw the shared Keenmate loader (renderLoadingCallback,--wtv-loader-*). - Theming — one token list with svelte-treeview on the base-css-variables 2.0 contract — Every
--wtv-*token falls back to a--base-*token (^2.0.0-rc08), and the list matches svelte-treeview's--stv-*one for one, so one theme drives both packages and every Keenmate component. Drop targets use the contract's green--base-drop-target-*tokens, the indent reads--base-tree-indent, andicon-set(chevron,triangle,plus-minus,arrow) points the disclosure glyph at the shared--base-icon-*masks. The checkbox is the canonical single styled<input>, and its indeterminate state survives virtual-scroll row recycling. - Icons, tooltips and render context —
iconMember/getIconCallbackput a dedicated.wtv__node-iconon every node, branch and leaf, with per-node colour and arenderIconCallbackhook for SVG or custom markup.show-node-tooltips+getNodeTooltipCallback({ node })add hover / focus tooltips (text or a rich element) on core's sharedcreateTooltip, styled by the shared--base-tooltip-*tokens. The render callbacks receive the device class, the container size and the live node state in their ctx. UI strings are configurable throughlabels.
Earlier releases: CHANGELOG.
npm install @keenmate/web-treeview<script type="module" src="./node_modules/@keenmate/web-treeview/dist/web-treeview.js"></script>
<web-treeview id="my-tree" expand-level="2"></web-treeview>
<script type="module">
const tree = document.getElementById('my-tree');
tree.nodes = [
{ id: 1, path: '1', displayValue: 'Documents' },
{ id: 2, path: '1.1', displayValue: 'Projects' },
{ id: 3, path: '1.1.1', displayValue: 'Web App' },
{ id: 4, path: '1.1.2', displayValue: 'Mobile App' },
{ id: 5, path: '1.2', displayValue: 'Photos' },
{ id: 6, path: '2', displayValue: 'Downloads' },
];
tree.addEventListener('node-click', (e) => console.log(e.detail.path));
</script>Map your own data shape with idMember / pathMember / displayValueMember (or parentPathMember for window trees). See docs/usage.md for the full API and docs/examples.md for end-to-end recipes.
Theme the tree with CSS variables (--wtv-*, falling back to the shared --base-* tokens) — see
docs/theming.md. To restyle internal parts, inject CSS into the shadow root: per tree with
custom-styles / getCustomStylesCallback, or for every tree on the page with
window.components['web-treeview'].customStyles (Custom CSS).
Tune any input per device class or window width without app-side viewport code — the generic core
mechanism (core SPEC §6.7).
A rule is a map of partial configs (TreeViewResponsiveMap) or a function of the environment
(TreeViewResponsiveCallback, (ctx) => partial | null | undefined), set at three levels. A map has two
axes, each keyed mobile / tablet / desktop:
device— the kind of device, by capability:mobile= a touch-primary phone (short side under 600 px),tablet= a larger touch device; a mouse / trackpad device isdesktopat any width.breakpoint— the window width (768 / 1024 px lines): a desktop window narrowed below 768 px ismobile.
The breakpoint entry applies first, the device entry over it (device wins on the same key). Your own
widths or combinations (e.g. "desktop AND narrower than 600 px") go in a responsiveCallback.
// page-wide (every Keenmate component; unknown keys are skipped silently)
window.components.responsive = { device: { mobile: { expandLevel: 1 } } };
// per tag: phones by capability, plus any narrow window
window.components['web-treeview'].responsive = {
device: { mobile: { expandLevel: 1, isNodeTooltipsShown: false } },
breakpoint: { mobile: { expandLevel: 1 } },
};
// own widths / combinations → callback (re-runs as the window width changes)
window.components['web-treeview'].responsiveCallback = ({ deviceClass, env }) =>
deviceClass === 'desktop' && env.viewportWidth < 600 ? { isNodeTooltipsShown: false } : undefined;
// one instance (property, or the JSON attribute responsive='{"device":{"tablet":{"expandLevel":2}}}')
tree.responsive = { device: { tablet: { expandLevel: 2 } } };Precedence, later wins key by key: global map → global callback → per-tag map → per-tag callback →
attributes / properties set on the instance → instance map → instance callback. So
<web-treeview expand-level="3"> keeps 3 whatever the page rules say; an instance rule returning null
ignores all page rules. Responsive values never reflect to attributes; el.expandLevel / el.config read
the effective value. Any other top-level map key (the pre-rc15 { mobile: … } shape) warns and is ignored.
The package ships editor metadata so you get autocomplete and hover docs for the
element's attributes, events, and all --wtv-* CSS custom properties. All of it is
generated from the component's source on every build, so it never drifts.
-
JetBrains (WebStorm / IntelliJ) — works automatically. The IDE discovers
web-types.jsonvia theweb-typesfield inpackage.json; no setup needed. -
VS Code — the data files ship but VS Code doesn't auto-discover them from a dependency, so point your workspace at them once in
.vscode/settings.json:{ "html.customData": [ "./node_modules/@keenmate/web-treeview/vscode.html-custom-data.json" ], "css.customData": [ "./node_modules/@keenmate/web-treeview/vscode.css-custom-data.json" ] }html.customDatapowers tag/attribute completion on<web-treeview>;css.customDatapowers completion for the--wtv-*theming variables. Reload the window after adding them.
The tree inserts node data as plain text: display values, labels, tooltip strings
(getNodeTooltipCallback returning a string) and context-menu item text / tooltip are all
written with textContent, so untrusted node names are safe by default.
These inputs are raw markup — intentionally not XSS-safe, so you control the output. Sanitize any untrusted text before passing it in:
| Input | Output used in |
|---|---|
Context-menu item icon |
The menu item's icon slot (innerHTML — meant for an <svg> / <i class> / glyph) |
customStyles / getCustomStylesCallback, page-wide window.components['web-treeview'].customStyles / .getCustomStylesCallback |
CSS injected into the shadow root |
The render callbacks are code, like a template: a string returned by renderNodeCallback /
render{EmptyState,EmptyZone,Header,Footer}Callback / renderIconCallback (or an icon value starting with <)
is HTML, and the fill hooks (renderLoadingCallback, renderContextMenuCallback, renderContextMenuItemCallback) and a tooltip
callback returning an HTMLElement hand you a DOM element — whatever you write (innerHTML included)
is on you; escape the data you put in it.
Modern evergreen browsers — the standalone colour fallbacks use CSS relative-colour syntax (oklch(from …)), the same floor as @keenmate/base-css-variables 2.x:
- Chrome / Edge 119+
- Firefox 128+
- Safari 18+
No polyfills are shipped. SSR-safe: the module imports without crashing in Node, but renders only after hydration in the browser.
npm install
npm run dev # Dev server on port 12300 (make dev)
npm run build # Production build
npm run package # Build + npm pack
npm run test:e2e # Playwright e2e (Chromium)Live HTML demos sit at the repo root, one page per topic (start from index.html): examples-basic.html, examples-data.html, examples-search.html, examples-interaction.html, examples-drag-drop.html, examples-icons.html, examples-tooltips.html, examples-context-menu.html, examples-custom-layout.html, examples-tree-editor.html, examples-responsive.html, examples-localization.html, examples-theming.html, examples-performance.html, examples-logging.html. npm run build:examples builds the static site into dist-examples/; the page chrome comes from @keenmate/web-components-devkit.
Authored and maintained by Keenmate. The component ships standalone with sensible light/dark defaults; when mounted inside Pure Admin — or any host that publishes the --base-* taxonomy via @keenmate/theme-designer — it adopts the host's colors, typography, and sizing automatically. There is no runtime dependency on Pure Admin; the integration is opt-in via CSS variables.
Follows the BlissFramework component guidelines for structure, theming, color-scheme, and accessibility. The VALIDATION-NOTES.md register documents the four accepted deviations against /validate-web-component.
MIT