Data TreeATM
A tree too big to write as markup. The records are one flat array - each names its parent - and defuss-dataview turns them into what is visible: open branches, sorted siblings, and for a filter every match with the path that leads to it. Only the items on screen exist in the DOM; focus stays on the tree and screen readers still hear "level 3, 42 of 100". For a small tree written as markup, use Tree View; for columns, the Tree Grid.
On this page (13)
§Custom labels and a kept view
render(label, record, meta) fills each label - an icon, the name, a size. The open branches, the filters, the sort and the selection are kept: in session storage by default, here in local storage under its own key (data-persist='local', data-persist-key) - on your page they survive a reload and the next visit (this sandboxed example has no storage).
§Custom editors
getEditorFn(field, value, ctx) hands the tree any editor: an element, or { el, getValue, validate?, focus?, immediate?, patch? }. Here a label edits as its name and its colour together - an Input and a row of colour swatches (radio buttons) in one editor; getValue() returns the name, patch() the colour, and both are written in one edit. render() draws the colour dot. Return false to keep an item from editing: the system labels Inbox and Sent stay as they are.
§Inline editing
data-editable lets a reader rename an item in place: double-click it, or press F2 on the active item. The editor is the library's Input (data-editor picks another: enum with data-options, number ...); Enter or leaving it writes the name, Escape keeps the old one. data-required, data-max-length and data-pattern refuse a value with a message; validateFn(field, value, ctx) refuses across records - here a name its siblings already use. Every edit replaces the record and runs the query again, so the siblings sort by name (data-sort) and a renamed folder moves among them. The line below listens to data-tree-edit.
§Drag and drop between trees
data-drag lets items drag out - each with everything under it - and data-drop lets records drop in. Within the Library, drag a song onto another genre: the middle of an item drops into it (it opens), its top or bottom edge before or after it. Drag a genre or a song into the Playlist: the Playlist takes copies only (data-drop='copy'), so the Library keeps it and the copies get ids of their own. From the Playlist back into the Library a drag moves; hold Alt (Option) or Ctrl to copy. A move into its own subtree goes nowhere. The line below follows data-tree-drop.
§111,110 nodes
Ten regions × ten countries × a hundred cities × ten districts. Open branches with the chevrons or the keyboard (↑ ↓ → ← Home End, Enter selects, * opens every sibling). The input is bound by data-tree-filter: type 'district 7.3.4' - every match shows with the path to it opened, the first match becomes active. The line below subscribes to the tree's store.
§Selection drives a detail pane
Selecting (click, Enter, Space) dispatches data-tree-select with the record - here a detail pane follows it. Sorting orders siblings: the select writes config.sorters.
§One open way
data-exclusive keeps one way open: open Region 3, then Region 5 - Region 3 closes with everything below it. The field picks a district somewhere else; reveal() opens only the way to it, selects it and scrolls it into view.
§Aggregated branches: 250,000 requests
Each node is a group of request log lines - service, then endpoint, then outcome - measured by an aggregate plan per level: the requests, the average and slowest latency and the errors (a count with a where). Its label shows them, the error share computed from two measures. Turn on Only slow requests: the plans run again with a where (latency > 800 ms) and the open branches stay open.
§Loading and empty
A tree without records waits in 'loading' (placeholder rows, aria-busy); a filter nothing matches lands in 'empty' with data-empty-text.
§States
Named states via the shared State API, driven per instance through the bound api; the config of every state is the query (filters, sorters, expanded, collapsed, selected), merged on each setState and observable as el.store:
default- the visible nodes of the query; nothing visible lands inemptyloading-aria-busy="true"and placeholder rows; a tree without records starts hereempty- nothing to show: thedata-empty-textmessage
The first example carries data-state-demo; bun run screenshots drives it via el.api.setState(name) and captures screenshots/{mode}/data-tree-{state}.png.
Machine contract - verified against data-tree.schema.json by bun run verify:
| State | Type | Values | Default | Description |
|---|---|---|---|---|
loading | boolean | true, false | false | aria-busy with placeholder rows (setState('loading')). |
empty | boolean | true, false | false | Nothing to show - shows data-empty-text (setState('empty')). |
§API
Generated from data-tree.ts and the shared State API - the descriptions are their JSDoc, the types are checked by the compiler.
States
type DataTreeState = 'default' | 'loading' | 'empty' - setState(name, config) takes the config of the state it names.
| State | Description | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
default | The visible items of the query; nothing visible lands in empty.
| ||||||||||||||||||
loading | Busy: placeholder rows, aria-busy - a tree without records starts here.
| ||||||||||||||||||
empty | Nothing to show: the data-empty-text shows.
|
Every element
| Member | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
el.api.setState<S extends DataTreeState>(name: S, config?: DataTreeStateConfigs[S]): unknown | Enter a state: the DOM work runs (also when it is the current state), the store records it.
Returns | |||||||||
el.api.getState(): { name: DataTreeState; config: DataTreeStateConfigs[DataTreeState]; model?: ElementModel } | The state the element shows now - read back from the DOM, so it includes what the user changed. Returns | |||||||||
el.api.render(state?: { name: DataTreeState; config: DataTreeStateConfigs[DataTreeState]; model?: ElementModel }): string | The element's markup in a state - the authored markup with that state applied; a pure function of the state.
Returns | |||||||||
el.api.settled(): Promise<void> | Wait for the last state's DOM work (async states: a diagram rendering, a chart mounting). Returns | |||||||||
el.store: Store<{ name: DataTreeState; config: DataTreeStateConfigs[DataTreeState] }> | A defuss-store store of the element's state - subscribe to follow every change (also the user's), set it to drive the component. |
Registry
| Member | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
df$.shadcn.dataTreeApi.setState<S extends DataTreeState>(el: HTMLElement, name: S, config?: DataTreeStateConfigs[S]): unknown | Enter a state: the DOM work runs (also when it is the current state), the store records it.
Returns | ||||||||||||
df$.shadcn.dataTreeApi.getState(el: HTMLElement): { name: DataTreeState; config: DataTreeStateConfigs[DataTreeState]; model?: ElementModel } | The state the element shows now - read back from the DOM, so it includes what the user changed.
Returns | ||||||||||||
df$.shadcn.dataTreeApi.render(state: { name: DataTreeState; config: DataTreeStateConfigs[DataTreeState]; model?: ElementModel }): string | The element's markup in a state - the authored markup with that state applied; a pure function of the state.
Returns | ||||||||||||
df$.shadcn.dataTreeApi.store(el: HTMLElement): Store<{ name: DataTreeState; config: DataTreeStateConfigs[DataTreeState] }> | The element's store (bindComponent made it).
Returns | ||||||||||||
df$.shadcn.dataTreeApi.commit<S extends DataTreeState>(el: HTMLElement, name: S, config?: DataTreeStateConfigs[S]): void | Record a state the element reached on its own (no DOM work) - for a component's own handlers.
| ||||||||||||
df$.shadcn.dataTreeStates: DataTreeState[] | The declared states, 'default' first: default, loading, empty. |
df$.shadcn.dataTree
| Member | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
setSource(target: string | HTMLElement, rows: DataviewRow[], options: DataTreeOptions = {}): void | Hand the tree its records. Options: idField ('id'), parentIdField ('parentId', or data-parent-field), render(el, record, meta) for the label (default: the data-label-field value), query (the starting view), persist ({ area: 'session' | 'local' | 'none', prefix, key }).
| ||||||||||||
query(target: string | HTMLElement, patch: DataTreeQuery): void | Merge into the query: { filters?, sorters?, expanded?, selected? }.
| ||||||||||||
expandAll(target: string | HTMLElement): void | Open every branch.
| ||||||||||||
collapseAll(target: string | HTMLElement): void | Close every branch (while filtering: the ways to the matches too).
| ||||||||||||
reveal(target: string | HTMLElement, id: DataviewJsonValue): boolean | Shows a record: opens the way to it (with data-exclusive only that way - every other branch closes), selects it and scrolls it into view as the active item. No data-tree-select fires - the page asked for it.
Returns | ||||||||||||
source(target: string | HTMLElement): DataSource<DataviewRow> | undefined | The tree's query source: its records (source.rows - every edit included) and the cached query over them.
Returns | ||||||||||||
edit(target: string | HTMLElement, id: DataviewJsonValue): boolean | Open the editor of a record's item (data-editable on the tree) - its branch opens and it scrolls into view first.
Returns | ||||||||||||
commit(target: string | HTMLElement): boolean | Commit the open editor.
Returns | ||||||||||||
cancel(target: string | HTMLElement): void | Close the open editor without writing.
| ||||||||||||
update(target: string | HTMLElement, id: DataviewJsonValue, patch: DataviewRow): DataviewRow | null | Write new values into one record from script - what an edit writes. The record is replaced by a new object; the query runs again. Fires data-tree-edit per field.
Returns | ||||||||||||
selected(target: string | HTMLElement): DataviewRow | null | The selected record.
Returns | ||||||||||||
insert(target: string | HTMLElement, records: DataviewRow[], at: DataTreeDropAt = { id: null, place: 'end' }): DataviewRow[] | null | Insert records - what a drop writes, from script (a button that moves the selected item to another tree, the keyboard's way to do what a drag does). Records may bring their children (linked by parent id among themselves); the others take the place's parent: beside a record its parent, into a record that record, at the end none. A record whose id the tree already holds gets a new one (numbers: after the largest, text: "id-2" ...). No event fires - the page asked for it.
Returns | ||||||||||||
remove(target: string | HTMLElement, ids: DataviewJsonValue[]): DataviewRow[] | Take records out with everything under them - what a move takes out of the tree it leaves. A selected record that goes is no longer selected. No event fires - the page asked for it.
Returns |
Events
| Event | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
data-tree-beforedrop | Fires before dropped records are written - cancel it to refuse them (the drag ends without a change).
| |||||||||||||||
data-tree-beforeedit | Fires before an edited value is written - cancelable: preventDefault() keeps the old value.
| |||||||||||||||
data-tree-dragend | Fires on the tree an item was dragged from, once a drop took it - on a move it has left (with its subtree).
| |||||||||||||||
data-tree-drop | Fires after dropped records were written into the tree - as inserted, with new ids where they needed one.
| |||||||||||||||
data-tree-edit | Fires after an edited value was written - the new record, the field, the new and the old value.
| |||||||||||||||
data-tree-select | Fires when an item is selected (click, Enter, Space) - its record and its tree meta (depth, hasChildren ...).
|
Types
| Type | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DataTreeBeforeDropDetail | What data-tree-beforedrop carries - cancel it to refuse the drop.
| ||||||||||||||||||||||||
DataTreeBeforeEditDetail | What data-tree-beforeedit carries.
| ||||||||||||||||||||||||
DataTreeDragEndDetail | What data-tree-dragend carries - on the tree the records were dragged from.
| ||||||||||||||||||||||||
DataTreeDropAt | Where records land in a tree: beside a record (before / after - its siblings), into it (its children), or at the end (roots).
| ||||||||||||||||||||||||
DataTreeDropDetail | What data-tree-drop carries.
| ||||||||||||||||||||||||
DataTreeEditContext | Where an edit happens - what getEditorFn and validateFn receive.
| ||||||||||||||||||||||||
DataTreeEditDetail | What data-tree-edit carries.
| ||||||||||||||||||||||||
DataTreeMeta | Where a record sits in the tree - what render() and data-tree-select receive.
| ||||||||||||||||||||||||
DataTreeOptions | What setSource() takes besides the records.
| ||||||||||||||||||||||||
DataTreeQuery | The tree's query - its state config (merged on every query()).
| ||||||||||||||||||||||||
DataTreeSelectDetail | What data-tree-select carries.
|
§CSS view file
/* -- Data Tree --------------------------------------------------- *//* A windowed tree: the sizer gives the scrollbar its length, a *//* recycled pool of items rides inside it. Depth is one custom *//* property per item - indentation is CSS. */@layer components { .data-tree { --data-tree-row-height: 32px; --data-tree-indent: 1.25rem; position: relative; overflow-y: auto; overscroll-behavior: contain; /* the windowing owns the scroll position: Firefox's scroll anchoring would follow the recycled rows, move scrollTop, re-render and move it again - a scroll that runs on by itself (big-data-firefox.e2e) */ overflow-anchor: none; scrollbar-gutter: stable; border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--card); color: var(--card-foreground); font-size: 0.875rem; contain: strict; &:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; } } .data-tree-sizer { position: relative; width: 100%; } .data-tree-items { position: absolute; inset-inline: 0; top: 0; padding-inline: 0.25rem; will-change: translate; } .data-tree-item { display: flex; align-items: center; gap: 0.25rem; height: var(--data-tree-row-height); padding-inline-start: calc(var(--depth, 0) * var(--data-tree-indent) + 0.25rem); padding-inline-end: 0.5rem; border-radius: var(--radius-sm); cursor: default; user-select: none; &:hover { background: var(--accent); color: var(--accent-foreground); } &[aria-selected="true"] { background: color-mix(in oklch, var(--primary) 14%, var(--card)); color: var(--foreground); font-weight: 500; /* the selected item under the pointer: more selected, never the soft hover */ &:hover { background: color-mix(in oklch, var(--primary) 24%, var(--card)); } } /* a filter's own hits, among the ancestors kept to reach them */ &[data-match] .data-tree-label { color: var(--foreground); font-weight: 600; } } .data-tree:focus-visible .data-tree-item[data-active] { box-shadow: inset 0 0 0 2px var(--ring); } .data-tree-toggle { flex: none; display: grid; place-items: center; width: 1.25rem; height: 1.25rem; border-radius: var(--radius-sm); color: var(--muted-foreground); cursor: pointer; &::before { content: ""; width: 0.375rem; height: 0.375rem; border-inline-end: 1.5px solid currentColor; border-bottom: 1.5px solid currentColor; rotate: -45deg; transition: rotate 150ms ease; } &:hover { background: color-mix(in oklch, var(--foreground) 8%, transparent); } } /* a leaf has no toggle - only its place, so labels line up */ .data-tree-item:not([aria-expanded]) .data-tree-toggle { cursor: default; &::before { content: none; } } .data-tree-item[aria-expanded="true"] .data-tree-toggle::before { rotate: 45deg; } .data-tree-label { display: flex; align-items: center; gap: 0.375rem; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* secondary text inside a label (counts, sizes) */ .data-tree-meta { margin-inline-start: auto; padding-inline-start: 0.75rem; color: var(--muted-foreground); font-size: 0.75rem; font-variant-numeric: tabular-nums; } /* -- loading and empty -------------------------------------- */ .data-tree[data-state="loading"], .data-tree[data-state="empty"] { & .data-tree-items { display: none; } & .data-tree-sizer { height: 100% !important; /* nothing to scroll in these states */ } } .data-tree[data-state="loading"]::before { content: ""; position: absolute; inset: 0.25rem; background: repeating-linear-gradient( to bottom, var(--muted) 0, var(--muted) calc(var(--data-tree-row-height) - 6px), transparent calc(var(--data-tree-row-height) - 6px), transparent var(--data-tree-row-height) ); opacity: 0.6; animation: data-tree-pulse 1.6s ease-in-out infinite; } .data-tree[data-state="empty"]::after { content: attr(data-empty-text); position: absolute; inset: 0; display: grid; place-items: center; color: var(--muted-foreground); } .data-tree:not([data-empty-text])[data-state="empty"]::after { content: "Nothing matches."; } @keyframes data-tree-pulse { 0%, 100% { opacity: 0.6; } 50% { opacity: 0.3; } } /* -- drag and drop: items that drag (data-drag), where dropped records would land (data-drop) -- */ .data-tree[data-drag] .data-tree-item[draggable="true"] { cursor: grab; } .data-tree-drop { position: absolute; inset-inline: 0.25rem; z-index: 3; height: 2px; margin-top: -1px; /* a line starts where the level it lands on does */ margin-inline-start: calc(var(--depth, 0) * var(--data-tree-indent) + 1.5rem); border-radius: 1px; background: var(--primary); pointer-events: none; /* into an item: it becomes its parent - framed */ &[data-place="into"] { height: var(--data-tree-row-height); margin: 0; border-radius: var(--radius-sm); background: color-mix(in oklch, var(--primary) 12%, transparent); box-shadow: inset 0 0 0 2px var(--primary); } } /* -- inline editing (data-editable): the label holds its editor; a refused value shows its message below -- */ .data-tree-item[data-editing] { overflow: visible; z-index: 2; & .data-tree-label { flex: 1; overflow: visible; } } .data-tree-editor { position: relative; display: flex; flex: 1; align-items: center; gap: 0.375rem; min-width: 0; & > :is(.input, .select) { flex: 1; min-width: 0; } } .data-tree-error { position: absolute; inset-block-start: calc(100% + 0.25rem); inset-inline-start: 0; z-index: 4; padding: 0.25rem 0.5rem; border-radius: var(--radius-sm); background: var(--destructive); color: var(--destructive-foreground); font-size: 0.75rem; white-space: nowrap; box-shadow: var(--shadow-md); }}@media (prefers-reduced-motion: reduce) { @layer components { .data-tree, .data-tree *, .data-tree::before, .data-tree::after, .data-tree *::before, .data-tree *::after, .data-tree[data-state="loading"]::before { transition: none; animation: none; scroll-behavior: auto; } }}@media (prefers-contrast: more) { @layer components { .data-tree { border-color: var(--muted-foreground); } .data-tree:focus-visible .data-tree-item[data-active] { box-shadow: inset 0 0 0 2px var(--foreground); } }}@media (forced-colors: active) { @layer components { .data-tree { border-color: ButtonText; } .data-tree-item[aria-selected="true"] { background: Highlight; color: HighlightText; } .data-tree:focus-visible .data-tree-item[data-active] { outline: 2px solid Highlight; outline-offset: -2px; } .data-tree-toggle::before { border-color: ButtonText; } .data-tree-drop { background: Highlight; } }}§JS view file
// -- Data Tree ------------------------------------------------// A tree over any number of records that each name their parent: only the// rows on screen exist (shared windowing, src/shared/virtual.ts), and the// hierarchy, filtering and sorting run locally over every record through// defuss-dataview (src/shared/dataview.ts). A filter keeps the ancestors of// every match and opens the way to it; collapsing keeps the query.//// The query IS the state's config (AGENTS.md "State through stores"):// el.store.value.config = { filters, sorters, expanded, collapsed, selected }.// The view survives a reload: session storage by default, local storage or// nothing per instance (data-persist, data-persist-prefix / -key, or// setSource's persist option).// Shared preamble (AGENTS.md "State API"); the implementation lives in core.js —// build.ts rewrites this import into a df$.shadcn.shared binding in dist/.import { defussGlobals, defussQuery, componentState, bindComponent, persisted, viewPersistence, dataSource, parseFilter, filterText, virtualWindow, sizerHeight, scrollIntoViewTop, asEditor, builtinEditor, editorControl, editorKey, editorProblem, focusEditor, valueType, carriesRecords, dropEffectFor, dropEffects, droppedRecords, endRecordDrag, placeRecords, recordDrag, startRecordDrag, subtreeOf, withoutRecords,} from '../../../shared/state-api.js';import type { CellEditor, EditorRules } from '../../../shared/editors.js';import type { DropEffect, DropPlace, RecordDrag } from '../../../shared/record-drag.js';import type { DataSource, DataviewFilter, DataviewJsonValue, DataviewRow, DataviewSorter,} from '../../../shared/dataview.js';import type { ViewPersistence } from '../../../shared/store.js';const df$ = defussGlobals();const dfDollar = defussQuery();// VERIFIED: (verify's component types ratchet - tsc -p tsconfig.components.json) every type// this file's API docs state - arguments, return values, event details - holds// against its code: a wrong one is a new type error and fails the build./** The tree's query - its state config (merged on every query()). */interface DataTreeQuery { /** filters over every record (a match shows with its ancestors) */ filters?: DataviewFilter[]; /** the order of siblings */ sorters?: DataviewSorter[]; /** the ids of the open branches */ expanded?: DataviewJsonValue[]; /** while filtering: the branches the user closed again */ collapsed?: DataviewJsonValue[]; /** the selected record's id, null for none */ selected?: DataviewJsonValue | null;}/** Where a record sits in the tree - what render() and data-tree-select receive. */interface DataTreeMeta { /** 0 for a root */ depth: number; /** whether it has child records */ hasChildren: boolean; /** whether its branch is open */ isExpanded: boolean; /** whether it matches the filters (false for an ancestor shown for a match) */ isMatch: boolean; /** whether it is the selected record */ isSelected: boolean; /** its parent's id, null for a root */ parentId: DataviewJsonValue | null;}/** Where an edit happens - what getEditorFn and validateFn receive. */interface DataTreeEditContext { /** the record being edited (unchanged until the edit commits) */ record: DataviewRow; /** where it sits in the tree */ meta: DataTreeMeta; /** the field that edits (data-edit-field, else the label field) */ field: string; /** the type it edits as (data-editor, else from the value) */ type: string; /** the tree's rules (data-required, data-min-length, data-max-length, data-pattern) */ rules: EditorRules; /** the tree element */ tree: HTMLElement;}/** What setSource() takes besides the records. */interface DataTreeOptions { /** an editor for an item (data-editable on the tree): an element or a CellEditor; null: the built-in Input; false: * this item does not edit */ getEditorFn?: (field: string, value: unknown, ctx: DataTreeEditContext) => HTMLElement | CellEditor | null | false; /** refuse a value: return a message, or false for a generic one; anything else accepts it */ validateFn?: (field: string, value: unknown, ctx: DataTreeEditContext) => string | false | null | undefined; /** the id field (default 'id', or data-id-field) */ idField?: string; /** the parent-id field (default 'parentId', or data-parent-field) */ parentIdField?: string; /** fill an item's label yourself (default: the data-label-field value as text) */ render?: (el: HTMLElement, record: DataviewRow, meta: DataTreeMeta) => void; /** the starting view (a kept view wins over it) */ query?: DataTreeQuery; /** where the view is kept between visits (default: session storage under a generated key) */ persist?: ViewPersistence;}/** What data-tree-beforeedit carries. */interface DataTreeBeforeEditDetail { /** the record as it is */ record: DataviewRow; /** the field that edits */ field: string; /** the value about to be written */ value: unknown; /** the value it holds now */ oldValue: unknown;}/** What data-tree-edit carries. */interface DataTreeEditDetail { /** the record as it is now (a new object - the old one is never mutated) */ record: DataviewRow; /** the field that edited */ field: string; /** the value written */ value: unknown; /** the value it held */ oldValue: unknown;}/** What data-tree-select carries. */interface DataTreeSelectDetail { /** the selected record */ record: DataviewRow; /** where it sits in the tree */ meta: DataTreeMeta;}/** Where records land in a tree: beside a record (before / after - its siblings), into it (its children), or at the * end (roots). */interface DataTreeDropAt { /** the record the records land beside or into; null at the end */ id: DataviewJsonValue | null; /** 'before', 'after', 'into' or 'end' */ place: DropPlace;}/** What data-tree-beforedrop carries - cancel it to refuse the drop. */interface DataTreeBeforeDropDetail { /** the records as they will be inserted (new ids where a copy or a taken id needs one) */ records: DataviewRow[]; /** 'move' (they leave their source) or 'copy' */ effect: DropEffect; /** the component they come from (a tree, a grid; this tree when they move within it); null from another document */ source: HTMLElement | null; /** where they land */ at: DataTreeDropAt;}/** What data-tree-drop carries. */interface DataTreeDropDetail { /** the records as they were inserted */ records: DataviewRow[]; /** 'move' or 'copy' */ effect: DropEffect; /** the component they came from; null from another document */ source: HTMLElement | null; /** where they landed */ at: DataTreeDropAt;}/** What data-tree-dragend carries - on the tree the records were dragged from. */interface DataTreeDragEndDetail { /** the records dragged - the item and everything under it (on a move they have left this tree) */ records: DataviewRow[]; /** 'move' or 'copy' */ effect: DropEffect; /** the component that took them */ target: HTMLElement;}const dataTreeStates = ['default', 'loading', 'empty'];/** setState() configs per state - the config IS the tree's query, merged into the stored one ({ expanded } keeps the filters). */export interface DataTreeStateConfigs { /** The visible items of the query; nothing visible lands in empty. */ default: DataTreeQuery; /** Busy: placeholder rows, aria-busy - a tree without records starts here. */ loading: DataTreeQuery; /** Nothing to show: the data-empty-text shows. */ empty: DataTreeQuery;}let uid = 0;// the config being shown: set first thing in apply (the store records it// only AFTER the DOM work - reading the store there would be one step behind)const configOf = (tree) => tree._config ?? tree.store?.value.config ?? {};const labelField = (tree) => tree.dataset.labelField || 'name';/** * The markup of a state, for render() AND the live element: data-state and * aria-busy. Everything else a tree shows is its records (runtime). */function applyMarkup(el, state) { dfDollar(el) .attr('data-state', state.name) .attr('aria-busy', state.name === 'loading' ? 'true' : null);}/** position among visible siblings (aria-posinset / aria-setsize), per result */function siblingInfo(tree) { const result = tree._result; if (tree._siblings?.result === result) return tree._siblings; const size = new Map(); const pos = Array.from({ length: result.entries.length }, () => 0); result.entries.forEach((entry, i) => { const parent = entry.meta.parentId ?? null; const n = (size.get(parent) ?? 0) + 1; size.set(parent, n); pos[i] = n; }); tree._siblings = { result, size, pos }; return tree._siblings;}/** writes the window of items that belongs at the current scroll position */function renderItems(tree) { const pool = tree._pool; if (!pool || !tree._result) return; const entries = tree._result.entries; const total = entries.length; const h = tree._rowHeight; const win = virtualWindow(tree.scrollTop, tree.clientHeight, h, total); tree._sizer.style.height = `${sizerHeight(total, h)}px`; while (pool.children.length < win.count) { const item = document.createElement('div'); item.className = 'data-tree-item'; item.setAttribute('role', 'treeitem'); item.id = `${tree._uid}-item-${pool.children.length}`; const toggle = document.createElement('span'); toggle.className = 'data-tree-toggle'; toggle.setAttribute('aria-hidden', 'true'); const label = document.createElement('span'); label.className = 'data-tree-label'; item.append(toggle, label); pool.append(item); } while (pool.children.length > win.count) pool.lastElementChild.remove(); pool.style.translate = `0 ${win.shift}px`; const { size, pos } = siblingInfo(tree); const selected = configOf(tree).selected ?? null; const idField = tree._source.idField; const draggable = tree.hasAttribute('data-drag'); let active = null; let edShown = false; for (let i = 0; i < pool.children.length; i++) { const item = pool.children[i]; const index = win.first + i; const entry = entries[index]; const key = `${tree._gen}:${index}`; if (item._key !== key) { item._key = key; item._index = index; item.dataset.index = String(index); const meta = entry.meta; item.style.setProperty('--depth', String(meta.depth)); item.setAttribute('aria-level', String(meta.depth + 1)); item.setAttribute('aria-setsize', String(size.get(meta.parentId ?? null))); item.setAttribute('aria-posinset', String(pos[index])); if (meta.hasChildren) item.setAttribute('aria-expanded', String(meta.isExpanded)); else item.removeAttribute('aria-expanded'); item.toggleAttribute('data-match', !!(configOf(tree).filters || []).length && meta.isMatch); delete item.dataset.editing; const label = item.lastElementChild; if (tree._render) { label.textContent = ''; tree._render(label, entry.row, meta); } else { label.textContent = String(entry.row[labelField(tree)] ?? ''); } } const ed = tree._editor; if (ed && ed.id === entry.row[idField]) { edShown = true; if (!item.contains(ed.wrap)) { // the item was filled again (a scroll moved its record to another pool element): the editor goes back const focused = ed.wrap.contains(document.activeElement) || document.activeElement === document.body; placeTreeEditor(item, ed); if (focused) (editorControl(ed.editor) as HTMLElement).focus({ preventScroll: true }); } } item.setAttribute('aria-selected', String(selected !== null && entry.row[idField] === selected)); // data-drag: items drag out - the one being edited does not (a drag in its field selects text) const drags = draggable && !(ed && ed.id === entry.row[idField]); if (item.draggable !== drags) item.draggable = drags; item.toggleAttribute('data-active', index === tree._active); if (index === tree._active) active = item; } if (active) tree.setAttribute('aria-activedescendant', active.id); else tree.removeAttribute('aria-activedescendant'); // the edited record scrolled out of the window: write what the editor holds (refused: drop it) if (tree._editor && !edShown && !tree._writing) queueMicrotask(() => { if (tree._editor && !commitTreeEdit(tree, false)) cancelTreeEdit(tree, false); });}// -- inline editing ---------------------------------------------------------/** the field an edit writes */const editField = (tree) => tree.dataset.editField || labelField(tree);/** the tree's edit rules, from its attributes */function treeRules(tree): EditorRules { const d = tree.dataset; const rules: EditorRules = {}; if (tree.hasAttribute('data-required')) rules.required = true; if (d.minLength) rules.minLength = Number(d.minLength); if (d.maxLength) rules.maxLength = Number(d.maxLength); if (d.pattern) rules.pattern = d.pattern; if (d.message) rules.message = d.message; if (d.options) rules.options = d.options.split(',').map((o) => o.trim()); return rules;}const treeContext = (tree, entry): DataTreeEditContext => { const field = editField(tree); const rules = treeRules(tree); return { record: entry.row, meta: entry.meta, field, type: tree.dataset.editor || valueType(entry.row[field], rules), rules, tree, };};/** put the open editor into an item's label */function placeTreeEditor(item, ed) { ed.item = item; item.dataset.editing = ''; const label = item.lastElementChild; label.textContent = ''; label.append(ed.wrap);}/** open the editor of the item at an index */function openTreeEdit(tree, index) { if (!tree.hasAttribute('data-editable') || tree.hasAttribute('data-readonly')) return false; const entry = entryAt(tree, index); if (!entry) return false; if (tree._editor && !commitTreeEdit(tree, false)) return false; const ctx = treeContext(tree, entry); const value = entry.row[ctx.field]; const custom = tree._sourceOptions?.getEditorFn?.(ctx.field, value, ctx); if (custom === false) return false; const editor: CellEditor = asEditor(custom) ?? builtinEditor(ctx.type, value, ctx.rules); activate(tree, index); const wrap = document.createElement('span'); wrap.className = 'data-tree-editor'; wrap.append(editor.el); const ed = { id: entry.row[tree._source.idField], field: ctx.field, editor, wrap, value, entry, item: null }; tree._editor = ed; const item = dfDollar(tree._pool) .children('.data-tree-item') .toArray() .find((x) => x._index === index); if (item) placeTreeEditor(item, ed); wrap.addEventListener('keydown', (e) => { e.stopPropagation(); // the tree's keys (arrows, Space, Enter) stay out of the editor const act = editorKey(e, editor); if (!act) return; e.preventDefault(); if (act === 'cancel') cancelTreeEdit(tree); else commitTreeEdit(tree); }); wrap.addEventListener('click', (e) => e.stopPropagation()); wrap.addEventListener('dblclick', (e) => e.stopPropagation()); wrap.addEventListener('change', () => { if (editor.immediate) commitTreeEdit(tree); }); wrap.addEventListener('focusout', (e) => { if (wrap.contains(e.relatedTarget as Node)) return; setTimeout(() => { if (tree._editor === ed && !wrap.contains(document.activeElement)) commitTreeEdit(tree, false); }, 0); }); focusEditor(editor); return true;}/** close the editor without writing; the tree takes the focus back */function cancelTreeEdit(tree, focus = true) { if (!tree._editor) return; tree._editor = null; tree._gen = (tree._gen || 0) + 1; renderItems(tree); if (focus) tree.focus({ preventScroll: true });}/** write one record's new values: a new record replaces the old one, the query runs again */function writeTreeRecord(tree, id, patch) { const idField = tree._source.idField; const rows = tree._source.rows; const at = rows.findIndex((r) => r[idField] === id); if (at < 0) return null; const record = { ...rows[at], ...patch }; const next = rows.slice(); next[at] = record; tree._source.setRows(next); tree._writing = true; triggerStateChange(tree, tree.store.value, tree.store.value); tree._writing = false; // the active item follows its record (a sort may move it) const index = tree._result.entries.findIndex((x) => x.row[idField] === id); if (index >= 0) activate(tree, index); return record;}/** * Commit the open editor: validate (the editor, the tree's rules, validateFn), ask data-tree-beforeedit (cancelable), * write the record, then data-tree-edit. Returns false while the value is refused (the editor stays). */function commitTreeEdit(tree, focus = true) { const ed = tree._editor; if (!ed) return true; let problem = ed.editor.validate?.() ?? ''; let value; if (!problem) { try { value = ed.editor.getValue(); } catch (error) { problem = String((error as Error).message ?? error); } } const ctx = treeContext(tree, ed.entry); if (!problem) problem = editorProblem(ctx.rules, value); if (!problem) { const answer = tree._sourceOptions?.validateFn?.(ed.field, value, ctx); if (typeof answer === 'string' && answer) problem = answer; else if (answer === false) problem = 'Invalid value'; } if (problem) { const control = editorControl(ed.editor); control.setAttribute('aria-invalid', 'true'); let note = dfDollar(ed.wrap).children('.data-tree-error').get(0); if (!note) { note = document.createElement('span'); note.className = 'data-tree-error'; note.setAttribute('role', 'alert'); note.id = `dt-error-${Math.random().toString(36).slice(2, 8)}`; ed.wrap.append(note); control.setAttribute('aria-describedby', note.id); } dfDollar(note).text(problem); return false; } tree._editor = null; const oldValue = ed.value; // Fires before an edited value is written - cancelable: preventDefault() keeps the old value. const before = new CustomEvent<DataTreeBeforeEditDetail>('data-tree-beforeedit', { bubbles: true, cancelable: true, detail: { record: ed.entry.row, field: ed.field, value, oldValue }, }); const same = JSON.stringify(value) === JSON.stringify(oldValue) && !ed.editor.patch; if (same || !tree.dispatchEvent(before)) { tree._gen = (tree._gen || 0) + 1; renderItems(tree); } else { const record = writeTreeRecord(tree, ed.id, { ...ed.editor.patch?.(), [ed.field]: value }); // Fires after an edited value was written - the new record, the field, the new and the old value. tree.dispatchEvent( new CustomEvent<DataTreeEditDetail>('data-tree-edit', { bubbles: true, detail: { record, field: ed.field, value, oldValue }, }), ); } if (focus) tree.focus({ preventScroll: true }); return true;}/** evaluate the config's query, re-render; returns the visible count */function refresh(tree, config, previous) { if (!tree._source) return 0; // a new query: the edited item may go - write it first (refused: drop it) if (tree._editor && !tree._writing) { tree._writing = true; if (!commitTreeEdit(tree, false)) tree._editor = null; tree._writing = false; } tree._result = tree._source.query({ filters: config.filters, sorters: config.sorters, expanded: config.expanded, collapsed: config.collapsed, }); tree._gen = (tree._gen || 0) + 1; const prev = previous?.config || {}; if (JSON.stringify(prev.filters ?? []) !== JSON.stringify(config.filters ?? [])) { tree.scrollTop = 0; // the first match is where the eye goes const first = tree._result.entries.findIndex((e) => e.meta.isMatch); tree._active = (config.filters || []).length ? Math.max(0, first) : 0; } tree._active = Math.min(tree._active ?? 0, Math.max(0, tree._result.entries.length - 1)); renderItems(tree); return tree._result.entries.length;}/** * UI side of setState: 'default' shows the records of the config's query * (none match → 'empty'), 'loading' shows placeholder rows, 'empty' shows * data-empty-text. Every state keeps the query. */function triggerStateChange(tree, state, previous) { tree._config = state.config; let name = state.name; if (name !== 'loading') { const rows = refresh(tree, state.config, previous); if (name === 'default' && !rows) name = 'empty'; } applyMarkup(tree, { name, config: state.config }); tree.dataset.stateName = name; if (tree._saved) { tree._saved.set({ filters: state.config.filters ?? [], sorters: state.config.sorters ?? [], expanded: state.config.expanded ?? [], selected: state.config.selected ?? null, }); } // bound filter inputs show the query (a restored one too) - never the one being typed in if (tree.id) { for (const input of dfDollar<HTMLInputElement>(`[data-tree-filter="${CSS.escape(tree.id)}"]`).toArray()) { if (input === document.activeElement) continue; const field = input.dataset.field || labelField(tree); input.value = filterText((state.config.filters || []).find((x) => x.field === field)); } }}/** the persisted view (viewPersistence: data-persist, -prefix, -key, or the config) */const KEPT = ['filters', 'sorters', 'expanded'];function attachPersistence(tree, config) { tree._saved?.destroy(); const where = viewPersistence( tree, 'data-tree', String(dfDollar('.data-tree').toArray().indexOf(tree)), config || {}, ); tree._saved = where ? persisted<Record<string, unknown>>( where.key, {}, { area: where.area, validate: (v): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v), }, ) : null; const kept: Record<string, unknown> = {}; for (const k of KEPT) if (Array.isArray(tree._saved?.value[k])) kept[k] = tree._saved.value[k]; if (tree._saved && tree._saved.value.selected !== undefined) kept.selected = tree._saved.value.selected; return kept;}/** Registry-level API; pass the tree explicitly. Unknown names throw. */export const dataTreeApi = componentState({ component: 'data-tree', states: dataTreeStates, // a config merges: { expanded } keeps the filters mergeConfig: true, apply: (tree, state, previous) => triggerStateChange(tree, state, previous), markup: (el, state) => applyMarkup(el, state),});df$.dataTreeApi = dataTreeApi;df$.dataTreeStates = dataTreeStates;// -- interaction ------------------------------------------------------------------const query = (tree, patch) => dataTreeApi.setState(tree, tree.store.value.name === 'loading' ? 'loading' : 'default', patch);const entryAt = (tree, index) => tree._result?.entries[index];/** a record's ancestors, the root first (parent ids cached per set of records - a drop or an edit replaces them) */function ancestorsOf(tree, id) { const src = tree._source; if (tree._parents?.rows !== src.rows) { const field = tree._parentField || 'parentId'; const map = new Map(); for (const row of src.rows) map.set(row[src.idField], row[field] ?? null); tree._parents = { rows: src.rows, map }; } const map = tree._parents.map; const out = []; const seen = new Set(); for (let at = map.get(id) ?? null; at !== null && map.has(at) && !seen.has(at); at = map.get(at) ?? null) { seen.add(at); out.unshift(at); } return out;}function setExpanded(tree, index, open) { const entry = entryAt(tree, index); if (!entry?.meta.hasChildren || entry.meta.isExpanded === open) return false; const id = entry.row[tree._source.idField]; const config = configOf(tree); if ((config.filters || []).length) { const collapsed = new Set(config.collapsed || []); if (open) collapsed.delete(id); else collapsed.add(id); query(tree, { collapsed: [...collapsed] }); } else if (open && tree.hasAttribute('data-exclusive')) { // one open way: the branch and its ancestors - its open siblings close, with what was open below them query(tree, { expanded: [...ancestorsOf(tree, id), id] }); } else { const expanded = new Set(config.expanded || []); if (open) expanded.add(id); else expanded.delete(id); query(tree, { expanded: [...expanded] }); } return true;}function select(tree, index) { const entry = entryAt(tree, index); if (!entry) return; query(tree, { selected: entry.row[tree._source.idField] }); // Fires when an item is selected (click, Enter, Space) - its record and its tree meta (depth, hasChildren ...). tree.dispatchEvent( new CustomEvent<DataTreeSelectDetail>('data-tree-select', { bubbles: true, detail: { record: entry.row, meta: entry.meta }, }), );}/** move the active item and keep it on screen */function activate(tree, index) { const total = tree._result?.entries.length ?? 0; if (!total) return; tree._active = Math.max(0, Math.min(total - 1, index)); tree.scrollTop = scrollIntoViewTop(tree._active, tree.scrollTop, tree.clientHeight, tree._rowHeight, total); renderItems(tree);}function onKeydown(tree, e) { if (tree._editor && tree._editor.wrap.contains(e.target)) return; const index = tree._active ?? 0; const entry = entryAt(tree, index); if (!entry) return; const page = Math.max(1, Math.floor(tree.clientHeight / tree._rowHeight) - 1); switch (e.key) { case 'ArrowDown': activate(tree, index + 1); break; case 'ArrowUp': activate(tree, index - 1); break; case 'ArrowRight': // closed: open it; open: step to its first child if (entry.meta.hasChildren && !setExpanded(tree, index, true)) activate(tree, index + 1); break; case 'ArrowLeft': if (entry.meta.hasChildren && entry.meta.isExpanded) setExpanded(tree, index, false); else if (entry.meta.parentId != null) { const parent = tree._result.entries.findIndex((x) => x.row[tree._source.idField] === entry.meta.parentId); if (parent >= 0) activate(tree, parent); } break; case 'Home': activate(tree, 0); break; case 'End': activate(tree, tree._result.entries.length - 1); break; case 'PageDown': activate(tree, index + page); break; case 'PageUp': activate(tree, index - page); break; case 'F2': if (!openTreeEdit(tree, index)) return; break; case 'Enter': case ' ': select(tree, index); break; case '*': { // APG: open every sibling of the active item const parent = entry.meta.parentId ?? null; const ids = tree._result.entries .filter((x) => (x.meta.parentId ?? null) === parent && x.meta.hasChildren) .map((x) => x.row[tree._source.idField]); query(tree, { expanded: [...new Set([...(configOf(tree).expanded || []), ...ids])] }); break; } default: return; } e.preventDefault();}function onClick(tree, e) { const item = e.target.closest?.('.data-tree-item'); if (!item || !tree._pool.contains(item)) return; tree._active = item._index; if (e.target.closest('.data-tree-toggle')) { const entry = entryAt(tree, item._index); setExpanded(tree, item._index, !entry?.meta.isExpanded); return; } select(tree, item._index);}// -- drag and drop: items out of a tree with data-drag, into one with data-drop -----------------------------------// The drag, its effect and where a drop lands belong to src/shared/record-drag.ts (a Data Grid drags the same way);// this tree finds its records, draws where they would land and writes them.const fieldsOf = (tree) => ({ idField: tree._source.idField as string, parentIdField: (tree._source.tree?.parentIdField ?? tree._parentField ?? 'parentId') as string,});/** the dragged records as text: a label a line, indented by a tab per level - a spreadsheet shows the outline */function outline(tree, records: DataviewRow[], root: DataviewJsonValue) { const { idField, parentIdField } = fieldsOf(tree); const children = new Map<unknown, DataviewRow[]>(); for (const r of records) { const p = r[parentIdField] ?? null; if (!children.has(p)) children.set(p, []); children.get(p)!.push(r); } const lines: string[] = []; const items: string[] = []; const esc = (t) => t.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); const walk = (r: DataviewRow, depth: number) => { const label = String(r[labelField(tree)] ?? ''); lines.push('\t'.repeat(depth) + label); const kids = children.get(r[idField]) ?? []; items.push(`<li>${esc(label)}`); if (kids.length) { items.push('<ul>'); for (const k of kids) walk(k, depth + 1); items.push('</ul>'); } items.push('</li>'); }; const top = records.find((r) => r[idField] === root); if (top) walk(top, 0); return { plain: lines.join('\n'), html: `<ul>${items.join('')}</ul>` };}function onTreeDragStart(tree, e: DragEvent) { const item = e.target as HTMLElement & { _index?: number }; // a link or a picture in a label drags itself if (!tree.hasAttribute('data-drag') || !tree._source || !item.classList?.contains('data-tree-item')) return; if (!tree._pool.contains(item)) return; const entry = entryAt(tree, item._index); if (!entry) return e.preventDefault(); const fields = fieldsOf(tree); const root = entry.row[fields.idField]; const records = subtreeOf(tree._source.rows, [root], fields); const drag: RecordDrag = { source: tree, records, roots: [root], ...fields, effects: dropEffects(tree.dataset.drag), remove: () => writeTreeRows(tree, withoutRecords(tree._source.rows, records, fields.idField)), done: (effect, target) => // Fires on the tree an item was dragged from, once a drop took it - on a move it has left (with its subtree). tree.dispatchEvent( new CustomEvent<DataTreeDragEndDetail>('data-tree-dragend', { bubbles: true, detail: { records, effect, target }, }), ), }; const label = String(entry.row[labelField(tree)] ?? ''); startRecordDrag( e, drag, outline(tree, records, root), records.length > 1 ? `${label} (+${records.length - 1})` : label, ); tree.setAttribute('data-dragging-items', '');}function onTreeDragEnd(tree) { tree.removeAttribute('data-dragging-items'); const drag = recordDrag(); if (drag?.source === tree) endRecordDrag(drag);}/** where a drop lands: beside the item under the pointer (its outer quarters), into it (its middle half), or last */function treeDropAt(tree, e: DragEvent): { at: DataTreeDropAt; index: number } { const h = tree._rowHeight; const y = e.clientY - tree._sizer.getBoundingClientRect().top; const index = Math.max(0, Math.floor(y / h)); const entry = entryAt(tree, index); if (!entry) return { at: { id: null, place: 'end' }, index: tree._result?.entries.length ?? 0 }; const f = y / h - index; const place: DropPlace = f < 0.25 ? 'before' : f > 0.75 ? 'after' : 'into'; return { at: { id: entry.row[tree._source.idField], place }, index };}/** the line where a drop would land (indented to its level), or the frame of the item it goes into; null: away */function showTreeDrop(tree, at: DataTreeDropAt | null, index = 0) { let mark = tree._dropMark; if (!at) { mark?.remove(); tree._dropMark = null; return; } if (!mark) { mark = tree._dropMark = document.createElement('div'); mark.className = 'data-tree-drop'; mark.setAttribute('aria-hidden', 'true'); } if (mark.parentElement !== tree._sizer) tree._sizer.append(mark); const entries = tree._result?.entries ?? []; const row = at.place === 'end' ? entries.length : at.place === 'after' ? index + 1 : index; mark.dataset.place = at.place; mark.style.top = `${row * tree._rowHeight}px`; mark.style.setProperty('--depth', String(at.place === 'end' ? 0 : (entries[index]?.meta.depth ?? 0)));}function onTreeDragOver(tree, e: DragEvent) { if (!tree.hasAttribute('data-drop') || !tree._source || !carriesRecords(e)) return; const drag = recordDrag(); const effect = dropEffectFor(e, dropEffects(tree.dataset.drop), drag); const { at, index } = treeDropAt(tree, e); // near an edge the items scroll on const box = tree.getBoundingClientRect(); if (e.clientY < box.top + tree._rowHeight) tree.scrollTop -= 12; else if (e.clientY > box.bottom - tree._rowHeight) tree.scrollTop += 12; // a move onto the item it moves, or into what lies under it, goes nowhere const within = drag?.source === tree && effect === 'move'; const idField = tree._source.idField; if (!effect || (within && at.id !== null && drag.records.some((r) => r[idField] === at.id))) { if (e.dataTransfer) e.dataTransfer.dropEffect = 'none'; showTreeDrop(tree, null); return; } e.preventDefault(); if (e.dataTransfer) e.dataTransfer.dropEffect = effect; showTreeDrop(tree, at, index);}function onTreeDrop(tree, e: DragEvent) { showTreeDrop(tree, null); if (!tree.hasAttribute('data-drop') || !tree._source) return; const drag = recordDrag(); const payload = droppedRecords(e); const effect = dropEffectFor(e, dropEffects(tree.dataset.drop), drag); if (!payload || !effect) return; e.preventDefault(); dropTreeRecords(tree, payload, effect, treeDropAt(tree, e).at, drag);}/** * Take dropped records: data-tree-beforedrop may refuse them; a move out of another component lets go of them first, * then the tree writes its records once, opens the item they went into and selects the first of them. */function dropTreeRecords(tree, payload, effect: DropEffect, at: DataTreeDropAt, drag: RecordDrag | null) { const fields = fieldsOf(tree); const within = !!drag && drag.source === tree && effect === 'move'; const placed = placeRecords({ rows: tree._source.rows, ...fields, from: payload, at, copy: effect === 'copy', within, }); const source = drag?.source ?? null; const detail = { records: placed?.inserted ?? [], effect, source, at }; if ( !placed || // Fires before dropped records are written - cancel it to refuse them (the drag ends without a change). !tree.dispatchEvent( new CustomEvent<DataTreeBeforeDropDetail>('data-tree-beforedrop', { bubbles: true, cancelable: true, detail }), ) ) { endRecordDrag(drag); return null; } if (drag && effect === 'move' && !within) drag.remove(); const first = placed.roots[0]; // the way to it opens (into an item: that item too) - in the same write const parentOf = new Map(placed.rows.map((r) => [r[fields.idField], r[fields.parentIdField] ?? null])); const way: unknown[] = []; const seen = new Set(); for ( let p = parentOf.get(first) ?? null; p !== null && parentOf.has(p) && !seen.has(p); p = parentOf.get(p) ?? null ) { seen.add(p); way.unshift(p); } const patch: DataTreeQuery = { selected: first ?? null }; if (way.length) patch.expanded = [...new Set([...(configOf(tree).expanded || []), ...way])] as DataviewJsonValue[]; writeTreeRows(tree, placed.rows, patch); drag?.done(effect, tree); endRecordDrag(drag); const index = tree._result?.entries.findIndex((x) => x.row[fields.idField] === first) ?? -1; if (index >= 0) activate(tree, index); tree.focus({ preventScroll: true }); // Fires after dropped records were written into the tree - as inserted, with new ids where they needed one. tree.dispatchEvent(new CustomEvent<DataTreeDropDetail>('data-tree-drop', { bubbles: true, detail })); return placed.inserted;}/** Replace the records (a drop, a move out, insert(), remove()): a selection that is gone goes; patch goes with it. */function writeTreeRows(tree, next: DataviewRow[], patch: DataTreeQuery = {}) { tree._source.setRows(next); const sel = configOf(tree).selected ?? null; if (!('selected' in patch) && sel !== null && !next.some((r) => r[tree._source.idField] === sel)) patch = { ...patch, selected: null }; tree._writing = true; try { if (Object.keys(patch).length) query(tree, patch); else triggerStateChange(tree, tree.store.value, tree.store.value); } finally { tree._writing = false; }}// one page-wide listener: <input data-tree-filter="tree-id" [data-field]> filters that treeif (!document.__dataTreeFilterInit) { document.__dataTreeFilterInit = true; document.addEventListener('input', (e) => { const input = (e.target as HTMLElement).closest?.<HTMLInputElement>('[data-tree-filter]'); if (!input) return; const tree = dfDollar('#' + CSS.escape(input.dataset.treeFilter)).get(0); if (!tree?.store) return; clearTimeout(tree._filterTimer); tree._filterTimer = setTimeout(() => { const filter = parseFilter(input.dataset.field || labelField(tree), input.value, 'text'); query(tree, { filters: filter ? [filter] : [], collapsed: [] }); }, 150); });}// -- df$.shadcn.dataTree: the imperative surface ----------------------------------const resolve = (target) => (typeof target === 'string' ? dfDollar(target).get(0) : target);df$.dataTree = { /** * Hand the tree its records. Options: idField ('id'), parentIdField * ('parentId', or data-parent-field), render(el, record, meta) for the * label (default: the data-label-field value), query (the starting view), * persist ({ area: 'session' | 'local' | 'none', prefix, key }). * @param target - the .data-tree element or its selector * @param rows - the records, a flat list linked by parent id * @param options - fields, label rendering, the starting view and its persistence */ setSource(target: string | HTMLElement, rows: DataviewRow[], options: DataTreeOptions = {}): void { const tree = resolve(target); const idField = options.idField || tree.dataset.idField || 'id'; const parentIdField = options.parentIdField || tree.dataset.parentField || 'parentId'; tree._source = dataSource(rows, { idField, tree: { idField, parentIdField } }); tree._parentField = parentIdField; tree._render = options.render || null; tree._sourceOptions = options; // options.query starts the view; a kept view (options.persist moves it) wins if (tree.store) dataTreeApi.setState(tree, 'default', { ...options.query, ...(options.persist ? attachPersistence(tree, options.persist) : {}), }); }, /** * Merge into the query: { filters?, sorters?, expanded?, selected? }. * @param target - the .data-tree element or its selector * @param patch - the query keys to change */ query: (target: string | HTMLElement, patch: DataTreeQuery): void => { query(resolve(target), patch); }, /** * Open every branch. * @param target - the .data-tree element or its selector */ expandAll(target: string | HTMLElement): void { const tree = resolve(target); query(tree, { expanded: tree._source.branchIds(), collapsed: [] }); }, /** * Close every branch (while filtering: the ways to the matches too). * @param target - the .data-tree element or its selector */ collapseAll(target: string | HTMLElement): void { const tree = resolve(target); const filtering = (configOf(tree).filters || []).length > 0; query(tree, filtering ? { collapsed: tree._source.branchIds() } : { expanded: [] }); }, /** * Shows a record: opens the way to it (with data-exclusive only that way - every other branch closes), selects it * and scrolls it into view as the active item. No data-tree-select fires - the page asked for it. * @param target - the .data-tree element or its selector * @param id - the record's id * @returns false when the record is unknown or a filter hides it */ reveal(target: string | HTMLElement, id: DataviewJsonValue): boolean { const tree = resolve(target); if (!tree?._source || !tree.store) return false; if (!tree._source.rows.some((r) => r[tree._source.idField] === id)) return false; const way = ancestorsOf(tree, id); const config = configOf(tree); if ((config.filters || []).length) { const collapsed = new Set(config.collapsed || []); for (const a of way) collapsed.delete(a); query(tree, { collapsed: [...collapsed], selected: id }); } else { const expanded = tree.hasAttribute('data-exclusive') ? way : [...new Set([...(config.expanded || []), ...way])]; query(tree, { expanded, selected: id }); } const index = tree._result?.entries.findIndex((e) => e.row[tree._source.idField] === id) ?? -1; if (index < 0) return false; activate(tree, index); return true; }, /** * The tree's query source: its records (source.rows - every edit included) and the cached query over them. * @param target - the .data-tree element or its selector * @returns its source, undefined before setSource() */ source: (target: string | HTMLElement): DataSource<DataviewRow> | undefined => resolve(target)._source, /** * Open the editor of a record's item (data-editable on the tree) - its branch opens and it scrolls into view first. * @param target - the .data-tree element or its selector * @param id - the record's id * @returns false when it does not edit (no such record, no data-editable, getEditorFn answered false) */ edit(target: string | HTMLElement, id: DataviewJsonValue): boolean { const tree = resolve(target); if (!(df$.dataTree as { reveal(t: HTMLElement, id: DataviewJsonValue): boolean }).reveal(tree, id)) return false; const index = tree._result.entries.findIndex((x) => x.row[tree._source.idField] === id); return openTreeEdit(tree, index); }, /** * Commit the open editor. * @param target - the .data-tree element or its selector * @returns false when its value is refused (the editor stays open with the message); true otherwise */ commit: (target: string | HTMLElement): boolean => commitTreeEdit(resolve(target)), /** * Close the open editor without writing. * @param target - the .data-tree element or its selector */ cancel: (target: string | HTMLElement): void => cancelTreeEdit(resolve(target)), /** * Write new values into one record from script - what an edit writes. The record is replaced by a new object; the * query runs again. Fires data-tree-edit per field. * @param target - the .data-tree element or its selector * @param id - the record's id * @param patch - the fields to change and their new values * @returns the new record, null when no record has that id */ update(target: string | HTMLElement, id: DataviewJsonValue, patch: DataviewRow): DataviewRow | null { const tree = resolve(target); const old = tree._source.rows.find((r) => r[tree._source.idField] === id); if (!old) return null; const record = writeTreeRecord(tree, id, patch); for (const field of Object.keys(patch)) tree.dispatchEvent( new CustomEvent<DataTreeEditDetail>('data-tree-edit', { bubbles: true, detail: { record, field, value: patch[field], oldValue: old[field] }, }), ); return record; }, /** * The selected record. * @param target - the .data-tree element or its selector * @returns the record whose id is selected, null when none is */ selected(target: string | HTMLElement): DataviewRow | null { const tree = resolve(target); const id = configOf(tree).selected ?? null; return id === null ? null : (tree._source?.rows.find((r) => r[tree._source.idField] === id) ?? null); }, /** * Insert records - what a drop writes, from script (a button that moves the selected item to another tree, the * keyboard's way to do what a drag does). Records may bring their children (linked by parent id among themselves); * the others take the place's parent: beside a record its parent, into a record that record, at the end none. A * record whose id the tree already holds gets a new one (numbers: after the largest, text: "id-2" ...). No event * fires - the page asked for it. * @param target - the .data-tree element or its selector * @param records - the records to insert * @param at - where: beside a record ({ id, place: 'before' | 'after' }), into one ('into'), or at the end (the * default: roots) * @returns the records as inserted (with their ids), null when the place is no record of the tree */ insert( target: string | HTMLElement, records: DataviewRow[], at: DataTreeDropAt = { id: null, place: 'end' }, ): DataviewRow[] | null { const tree = resolve(target); if (!tree?._source || !tree.store) return null; const fields = fieldsOf(tree); const placed = placeRecords({ rows: tree._source.rows, ...fields, from: { version: 1, records, roots: records.map((r) => r[fields.idField] as DataviewJsonValue), ...fields }, at, copy: false, within: false, }); if (!placed) return null; writeTreeRows(tree, placed.rows); return placed.inserted; }, /** * Take records out with everything under them - what a move takes out of the tree it leaves. A selected record * that goes is no longer selected. No event fires - the page asked for it. * @param target - the .data-tree element or its selector * @param ids - the ids of the records to take out * @returns the records taken out (with the ones under them), in source order */ remove(target: string | HTMLElement, ids: DataviewJsonValue[]): DataviewRow[] { const tree = resolve(target); if (!tree?._source || !tree.store) return []; const fields = fieldsOf(tree); const gone = subtreeOf(tree._source.rows, ids, fields); if (gone.length) writeTreeRows(tree, withoutRecords(tree._source.rows, gone, fields.idField)); return gone; },};// -- init --------------------------------------------------------------------------function init() { dfDollar('.data-tree:not([data-init])') .toArray() .forEach((tree) => { tree.dataset.init = ''; tree._uid = tree.id || `data-tree-${++uid}`; const sizer = document.createElement('div'); sizer.className = 'data-tree-sizer'; const pool = document.createElement('div'); pool.className = 'data-tree-items'; pool.setAttribute('role', 'presentation'); sizer.append(pool); dfDollar(tree).append(sizer); tree._sizer = sizer; tree._pool = pool; tree._active = 0; tree._rowHeight = parseFloat(getComputedStyle(tree).getPropertyValue('--data-tree-row-height')) || 32; tree.setAttribute('role', 'tree'); if (!tree.hasAttribute('tabindex')) tree.tabIndex = 0; const early = tree._sourceOptions || {}; const config = { filters: [], sorters: [], expanded: [], collapsed: [], selected: null, ...early.query, ...attachPersistence(tree, early.persist), }; let queued = false; tree.addEventListener( 'scroll', () => { if (queued) return; queued = true; requestAnimationFrame(() => { queued = false; renderItems(tree); }); }, { passive: true }, ); new ResizeObserver(() => renderItems(tree)).observe(tree); tree.addEventListener('click', (e) => onClick(tree, e)); tree.addEventListener('keydown', (e) => onKeydown(tree, e)); // items drag out (data-drag) and records drop in (data-drop) - the native Drag and Drop API tree.addEventListener('dragstart', (e) => onTreeDragStart(tree, e)); tree.addEventListener('dragend', () => onTreeDragEnd(tree)); tree.addEventListener('dragenter', (e) => onTreeDragOver(tree, e)); tree.addEventListener('dragover', (e) => onTreeDragOver(tree, e)); tree.addEventListener('dragleave', (e) => { if (!tree.contains(e.relatedTarget as Node | null)) showTreeDrop(tree, null); }); tree.addEventListener('drop', (e) => onTreeDrop(tree, e)); // data-drag switched: the items say whether they drag new MutationObserver(() => { tree._gen = (tree._gen || 0) + 1; renderItems(tree); }).observe(tree, { attributes: true, attributeFilter: ['data-drag'] }); // a double click on an item edits it (data-editable) tree.addEventListener('dblclick', (e) => { const item = (e.target as HTMLElement).closest?.<HTMLElement & { _index?: number }>('.data-tree-item'); if (!item || !tree._pool.contains(item) || (e.target as HTMLElement).closest('.data-tree-toggle')) return; if (openTreeEdit(tree, item._index)) e.preventDefault(); }); // el.store + el.api (AGENTS.md "State through stores"): no records yet = loading bindComponent(tree, dataTreeApi, { name: tree._source ? 'default' : 'loading', config }); dataTreeApi.setState(tree, tree._source ? 'default' : 'loading', config); });}init();new MutationObserver(init).observe(document, { childList: true, subtree: true });Comments, ideas or improvements? Edit this page's source on GitHub