@bolid-ui/data-tree
v0.2.0
Published
Виртуализированное дерево дизайн-системы Bolid UI для React
Maintainers
Readme
Bolid Data Tree
A virtualized, accessible tree for React, styled for Bolid UI.
Selection, keyboard navigation, search, sorting, sticky scroll and drag and drop within and between trees. Includes a React adapter, named Zustand stores and an imperative API. Ships ESM, CJS and TypeScript declarations. Requires React 19.
Installation
npm install @bolid-ui/data-tree
# or
yarn add @bolid-ui/data-tree
# or
pnpm add @bolid-ui/data-treeFor the default theme, also install @bolid-ui/themes. Zustand is included as
a dependency; install it directly if your application imports useStore.
Usage
Import the engine stylesheet once. Give the tree an explicit height and keep its delegate and renderers stable: they are captured when the tree mounts.
import { Theme } from '@bolid-ui/themes'
import '@bolid-ui/themes/styles.css'
import {
Tree,
TreeStoreProvider,
type IListVirtualDelegate,
type ITreeRenderer,
} from '@bolid-ui/data-tree'
import '@bolid-ui/data-tree/styles.css'
type Node = { id: string; label: string; children?: Node[] }
const roots: Node[] = [
{
id: 'devices',
label: 'Devices',
children: [{ id: 'device-1', label: 'Device 1' }],
},
]
const delegate: IListVirtualDelegate<Node> = {
getHeight: () => 32,
getTemplateId: () => 'node',
}
const renderer: ITreeRenderer<Node, void, HTMLSpanElement> = {
templateId: 'node',
renderTemplate(container) {
const label = document.createElement('span')
container.appendChild(label)
return label
},
renderElement(node, _index, label) {
label.textContent = node.element.label
},
renderTwistie(element, twistie) {
twistie.textContent = element.children?.length ? '›' : ''
return true
},
disposeTemplate() {},
}
const renderers = [renderer]
export function App() {
return (
<Theme accentColor="blue" grayColor="slate">
<TreeStoreProvider<Node> names={['devices']}>
<Tree<Node>
name="devices"
roots={roots}
delegate={delegate}
renderers={renderers}
defaultExpanded
options={{ multipleSelectionSupport: true }}
style={{ height: 400, width: '100%' }}
/>
</TreeStoreProvider>
</Theme>
)
}Rows use imperative DOM renderers, with templates recycled by the virtual
scroller. Set up DOM in renderTemplate, update it in renderElement, and
release listeners or React roots in disposeTemplate. Supply renderTwistie
for a custom expansion icon; the example needs no icon font. Style your row
contents in application CSS. The package stylesheet supplies engine layout,
scrollbars and tree states.
Entry points
| Import | Contents |
| --- | --- |
| @bolid-ui/data-tree | Tree, TreeStoreProvider, TreeApi, hooks, store factories, DnD helpers, core types/enums and treeTheme |
| @bolid-ui/data-tree/theme | treeTheme, without loading the React adapter |
| @bolid-ui/data-tree/styles.css | Required engine stylesheet |
Data and API
Every mounted tree needs a unique name registered in its provider. IDs must
be unique and stable within each tree. By default nodes have id and
children fields; override idAccessor and childrenAccessor with a field
name or function. Use sortAccessor for sibling ordering.
roots initializes the store and replaces its data when the prop reference
changes. Keep it stable when mutating data through api.setRoots(...) or the
other API methods, so parent renders do not reset those changes.
Obtain the API with onReady, useTreeApi(name) or getTreeApi(name) outside
React. Registry lookups return undefined while the tree is unmounted.
import { getTreeApi } from '@bolid-ui/data-tree'
const api = getTreeApi<Node>('devices')
if (api) {
api.insertNode('devices', { id: 'device-2', label: 'Device 2' })
api.expandTo('device-2')
api.setSelection(['device-2'])
api.revealById('device-2')
}| Area | Methods |
| --- | --- |
| Data | setRoots, insertNode(s), updateNode(s), removeNodes, moveNode(s), replaceChildren, moveFrom |
| Queries | getRoots, getRootIds, getNodeById, getChildrenIds, getDescendantIds, getParentId, findId, findAllIds |
| Selection / focus | setSelection, addToSelection, selectAll, focusById, setFocus, isSelected, isFocused |
| Expansion | expand, collapse, toggleExpanded, expandAll, collapseAll, expandTo |
| View | revealById, scrollToTop, layout, rerender, refilter, domFocus |
Use useTreeStore<Node>(name) inside the provider to access the store. For
React subscriptions, use Zustand's useStore(store, selector) to subscribe to
the fields needed by your component. Data, selection, focus, expansion,
context target and transient DnD state are stored per tree.
Search and events
Pass searchTerm to use built-in search. Customize matching with
searchMatch={(node, term) => node.label.toLocaleLowerCase().includes(term)};
the term is trimmed and lowercased. expandOnFilter expands matching paths
while filtering and restores the previous expansion afterward. For custom
filters use filter and change filterVersion when external filter state changes.
Callbacks include onSelectionChange, onFocusChange, onExpand,
onCollapse, onContextMenu, mouse events and onDidScroll. Policy props
include canSelectNode, canMultiSelectNode, canDragNode, canDeleteNode.
onCreate and onDelete handle requests; application code performs the
corresponding data changes. Loading and empty states are configured through
loading, error, renderLoader, renderError, renderEmpty and
renderNoSearchResults.
Drag and drop
Create the handler inside a component under TreeStoreProvider:
import { useMemo } from 'react'
import { createTreeDnd, useTreeStore } from '@bolid-ui/data-tree'
function useDeviceDnd(name: string) {
const store = useTreeStore<Node>(name)
return useMemo(() => createTreeDnd<Node>({
treeName: name,
store,
getIsFolder: node => node.children !== undefined,
getDragLabel: node => node.label,
onMove(args) {
if (args.sourceTreeName === args.targetTreeName) return false
if (!args.sourceApi || !args.targetApi) return
args.targetApi.moveFrom(args.sourceApi, args.dragIds, {
parentId: args.targetParentId,
index: args.targetIndex ?? undefined,
})
},
}), [name, store])
}Pass the result as <Tree dnd={dnd} ... />. Same-tree moves are handled
automatically when onMove returns false. Cross-tree moves require an
onMove handler and both trees mounted with distinct names. canDrop,
isDropDisabled, onlyFolderDrop and onlyOverDrop control drop policy.
Use dragPreview for a React preview, or false to disable the preview.
Theming
treeTheme is applied by default. Its CSS variables follow the surrounding
Bolid Theme, including appearance, accent, radii and scrollbar colors.
Unlike the theme object, the engine CSS must be imported explicitly.
import { treeTheme } from '@bolid-ui/data-tree/theme'
import type { IListStyles } from '@bolid-ui/data-tree'
const theme: IListStyles = {
...treeTheme,
listHoverBackground: 'var(--accent-a4)',
}
// <Tree theme={theme} ... />Without @bolid-ui/themes, supply the CSS variables referenced by treeTheme
or provide a complete IListStyles object with your own values. The engine
uses browser DOM APIs; mount it on the client in applications with server rendering.
Keyboard navigation and selection shortcuts are described in KEYBOARD_SHORTCUTS.md.
Development and publishing
From the repository root:
pnpm build:data-tree
pnpm --filter @bolid-ui/data-tree typecheck
pnpm changesetThe package participates in the workspace build and the existing Changesets
release workflow. Changesets on main create a version PR; after that PR is
merged, the release workflow publishes public npm packages using the repository's
NPM_TOKEN. pnpm release builds the packages and runs changeset publish.
License
MIT. See LICENSE and THIRD_PARTY_NOTICES.md for the vendored VS Code core.
