@emuanalytics/flow-rdf-ui 4.4.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,15 @@
1
- import { html } from 'lit';
2
- import { query, property } from 'lit/decorators.js';
1
+ import { html, nothing } from 'lit';
2
+ import { property, state, query } from 'lit/decorators.js';
3
3
  import { classMap } from 'lit/directives/class-map.js';
4
+ import { styleMap } from 'lit/directives/style-map.js';
5
+ import { boolean } from '../../internal/boolean.mjs';
4
6
  import { ensureArray } from '../../internal/ensure-array.mjs';
5
7
  import FlowRdfElement, { FlowRdfFormControl } from '../../internal/flow-ui-rdf-element.mjs';
6
- import { clamp } from '../../internal/math.mjs';
7
- import { isStringFull } from '../../internal/type-checks.mjs';
8
8
  import { watch } from '../../internal/watch.mjs';
9
9
  import { LocalizeController } from '../../utilities/localize.mjs';
10
+ import FlowUiCheckbox from '../checkbox/checkbox.component.mjs';
11
+ import FlowUiIcon from '../icon/icon.component.mjs';
12
+ import FlowUiProgressRing from '../progress-ring/progress-ring.component.mjs';
10
13
  import FlowUiTreeItem from '../tree-item/tree-item.component.mjs';
11
14
  import styles from './tree.styles.mjs';
12
15
 
@@ -21,360 +24,972 @@ var __decorateClass = (decorators, target, key, kind) => {
21
24
  __defProp(target, key, result);
22
25
  return result;
23
26
  };
24
- function syncCheckboxes(changedTreeItem, initialSync = false) {
25
- function syncParentItem(treeItem) {
26
- const children = treeItem.getChildrenItems({ includeDisabled: false });
27
- if (children.length) {
28
- const allChecked = children.every((item) => item.selected);
29
- const allUnchecked = children.every((item) => !item.selected && !item.indeterminate);
30
- treeItem.selected = allChecked;
31
- treeItem.indeterminate = !allChecked && !allUnchecked;
27
+ const isParent = (node) => !!node.children?.length;
28
+ const ROW_HEIGHTS = { small: 24, medium: 28, large: 36 };
29
+ const ITEM_TAG = FlowUiTreeItem.tagName;
30
+ const ITEM_ATTRIBUTES = ["value", "expanded", "selected", "disabled", "lazy", "hidden", "icon", "icon-library"];
31
+ const ITEM_EXPAND_EVENTS = ["flow-ui-expand", "flow-ui-after-expand", "flow-ui-collapse", "flow-ui-after-collapse"];
32
+ function itemLabel(item) {
33
+ let text = "";
34
+ for (const child of item.childNodes) {
35
+ if (child.nodeType === Node.TEXT_NODE)
36
+ text += child.textContent;
37
+ else if (child instanceof Element && child.localName !== ITEM_TAG && !child.hasAttribute("slot")) {
38
+ text += child.textContent;
32
39
  }
33
40
  }
34
- function syncAncestors(treeItem) {
35
- const parentItem = treeItem.parentElement;
36
- if (FlowUiTreeItem.isTreeItem(parentItem)) {
37
- syncParentItem(parentItem);
38
- syncAncestors(parentItem);
39
- }
40
- }
41
- function syncDescendants(treeItem) {
42
- for (const childItem of treeItem.getChildrenItems()) {
43
- childItem.selected = initialSync ? treeItem.selected || childItem.selected : !childItem.disabled && treeItem.selected;
44
- syncDescendants(childItem);
45
- }
46
- if (initialSync) {
47
- syncParentItem(treeItem);
48
- }
49
- }
50
- syncDescendants(changedTreeItem);
51
- syncAncestors(changedTreeItem);
41
+ return text.replace(/\s+/g, " ").trim();
52
42
  }
43
+ function itemValue(item, name) {
44
+ if (item instanceof FlowUiTreeItem)
45
+ return item[name] ? String(item[name]) : void 0;
46
+ return item.getAttribute(name === "iconLibrary" ? "icon-library" : name) ?? void 0;
47
+ }
48
+ function itemFlag(item, name) {
49
+ return item instanceof FlowUiTreeItem ? boolean(item[name], true) : item.hasAttribute(name);
50
+ }
51
+ function layoutParent(el) {
52
+ if (el.assignedSlot)
53
+ return el.assignedSlot;
54
+ if (el.parentElement)
55
+ return el.parentElement;
56
+ const root = el.getRootNode();
57
+ return root instanceof ShadowRoot ? root.host : null;
58
+ }
59
+ let generatedIds = 0;
53
60
  class FlowUiTree extends FlowRdfElement {
54
61
  constructor() {
55
62
  super(...arguments);
63
+ this._nodes = [];
64
+ this.settingItemNodes = false;
56
65
  this.value = [];
66
+ this.expandedIds = [];
57
67
  this.selectionMode = "multiple";
68
+ this.filter = "";
69
+ this.overscan = 10;
58
70
  this.size = "medium";
71
+ this.rowSlots = false;
72
+ this.visibleTop = 0;
73
+ this.visibleBottom = 600;
74
+ this.activeIndex = -1;
59
75
  this.localize = new LocalizeController(this);
60
- this.clickTarget = null;
61
- // Initializes new items by setting the `selectable` property and the expanded/collapsed icons if any
62
- this.initTreeItem = (item) => {
63
- item.selectable = this.selectionMode === "multiple";
64
- item.selected = !!item.value && ensureArray(this.value).includes(item.value);
65
- item.size = this.size;
66
- ["expand", "collapse"].filter((status) => !!this.querySelector(`[slot="${status}-icon"]`)).forEach((status) => {
67
- const existingIcon = item.querySelector(`[slot="${status}-icon"]`);
68
- if (existingIcon === null) {
69
- item.append(this.getExpandButtonIcon(status));
70
- } else if (existingIcon.hasAttribute("data-default")) {
71
- existingIcon.replaceWith(this.getExpandButtonIcon(status));
72
- } else ;
73
- });
74
- syncCheckboxes(item);
76
+ this.info = /* @__PURE__ */ new Map();
77
+ this.expanded = /* @__PURE__ */ new Set();
78
+ /** The selection: leaf ids in multiple selection, plus ids the tree doesn't know (so a reload keeps them). */
79
+ this.selected = /* @__PURE__ */ new Set();
80
+ /** Selected-leaf counts per parent, derived from `selected`. */
81
+ this.selectedCounts = /* @__PURE__ */ new Map();
82
+ /** Nodes with a match below them while filtering (null when not filtering). */
83
+ this.matching = null;
84
+ /** Nodes the user collapsed while filtering (filtering otherwise expands every match). */
85
+ this.filterCollapsed = /* @__PURE__ */ new Set();
86
+ this.rows = [];
87
+ this.lastVisibleKey = "";
88
+ /**
89
+ * The node id each rendered row showed last time. Rows are rendered by position in the window, so scrolling,
90
+ * expanding or collapsing gives a row another node, and its checkbox would fade from the old node's state.
91
+ */
92
+ this.rowNodeIds = [];
93
+ this.hasReusedRows = false;
94
+ this.restoringTransitions = false;
95
+ /** A row to render whatever is in view, so that it can be scrolled to. */
96
+ this.pinnedIndex = -1;
97
+ // Layout: the tree is as tall as its rows, and renders the ones in view of the elements that clip it
98
+ this.scrollParents = [];
99
+ // Tree items
100
+ /** Where the nodes come from: the tree items until the application sets `nodes`. */
101
+ this.source = "items";
102
+ this.itemSyncScheduled = false;
103
+ this.itemIds = /* @__PURE__ */ new WeakMap();
104
+ /** Ids the tree made for items without a value. They never appear in `value`. */
105
+ this.generatedIds = /* @__PURE__ */ new Set();
106
+ this.itemsById = /* @__PURE__ */ new Map();
107
+ /** Each item's node, and its `expanded` and `selected` as the tree last read or wrote them. */
108
+ this.itemsSeen = /* @__PURE__ */ new WeakMap();
109
+ this.itemReads = 0;
110
+ /** Selections the application made on items (`selected`), applied once the nodes are indexed. */
111
+ this.pendingItemSelections = /* @__PURE__ */ new Map();
112
+ /** The selection or expansion changed since the items were last updated. */
113
+ this.itemStatesDirty = false;
114
+ //
115
+ // Tree items
116
+ //
117
+ this.handleItemMutations = (records) => {
118
+ if (this.source !== "items")
119
+ return;
120
+ let relevant = false;
121
+ for (const record of records) {
122
+ const target = record.target;
123
+ if (record.type === "attributes") {
124
+ if (target.localName !== ITEM_TAG || !this.itemAttributeChanged(target, record.attributeName))
125
+ continue;
126
+ if (record.attributeName === "selected") {
127
+ this.pendingItemSelections.set(target, itemFlag(target, "selected"));
128
+ }
129
+ relevant = true;
130
+ } else if (record.type === "childList") {
131
+ const nodes = [...record.addedNodes, ...record.removedNodes];
132
+ if (target === this && !nodes.some((n) => n instanceof Element && n.localName === ITEM_TAG))
133
+ continue;
134
+ relevant = true;
135
+ } else {
136
+ relevant = true;
137
+ }
138
+ }
139
+ if (relevant)
140
+ this.scheduleItemSync();
75
141
  };
142
+ this.stopItemEvent = (event) => {
143
+ if (event.target !== this)
144
+ event.stopPropagation();
145
+ };
146
+ /** Finds the part of the rows in view: inside the viewport and every element that clips the tree. */
147
+ this.measure = () => {
148
+ if (!this.spacer)
149
+ return;
150
+ const { top, height } = this.spacer.getBoundingClientRect();
151
+ const scale = this.spacer.offsetHeight > 0 && height > 0 ? height / this.spacer.offsetHeight : 1;
152
+ let clipTop = 0;
153
+ let clipBottom = window.innerHeight;
154
+ for (const el of this.scrollParents) {
155
+ const rect = el.getBoundingClientRect();
156
+ const elScale = el instanceof HTMLElement && el.offsetHeight > 0 ? rect.height / el.offsetHeight : 1;
157
+ const contentTop = rect.top + el.clientTop * elScale;
158
+ clipTop = Math.max(clipTop, contentTop);
159
+ clipBottom = Math.min(clipBottom, contentTop + el.clientHeight * elScale);
160
+ }
161
+ this.visibleTop = (clipTop - top) / scale;
162
+ this.visibleBottom = (Math.max(clipTop, clipBottom) - top) / scale;
163
+ };
164
+ this.handleGapIntersection = (entries) => {
165
+ this.measure();
166
+ if (entries.some((entry) => entry.isIntersecting && entry.intersectionRatio > 0))
167
+ this.followMotion();
168
+ };
169
+ }
170
+ get nodes() {
171
+ return this._nodes;
172
+ }
173
+ set nodes(nodes) {
174
+ const old = this._nodes;
175
+ this._nodes = nodes;
176
+ if (!this.settingItemNodes)
177
+ this.source = "data";
178
+ this.requestUpdate("nodes", old);
76
179
  }
77
- async connectedCallback() {
180
+ connectedCallback() {
78
181
  super.connectedCallback();
79
182
  this.classList.add(FlowRdfFormControl.FLOW_UI_FORM_CONTROL_CLASS);
80
- this.handleTreeChanged = this.handleTreeChanged.bind(this);
81
- this.handleFocusIn = this.handleFocusIn.bind(this);
82
- this.handleFocusOut = this.handleFocusOut.bind(this);
83
- this.setAttribute("role", "tree");
84
- this.setAttribute("tabindex", "0");
85
- this.addEventListener("focusin", this.handleFocusIn);
86
- this.addEventListener("focusout", this.handleFocusOut);
87
- this.addEventListener("flow-ui-lazy-change", this.handleSlotChange);
88
- this.addEventListener("flow-ui-expand", this.handleHostExpandCollapse);
89
- this.addEventListener("flow-ui-collapse", this.handleHostExpandCollapse);
90
- this.addEventListener("flow-ui-after-expand", this.handleHostExpandCollapse);
91
- this.addEventListener("flow-ui-after-collapse", this.handleHostExpandCollapse);
92
- await this.updateComplete;
93
- this.mutationObserver = new MutationObserver(this.handleTreeChanged);
94
- this.mutationObserver.observe(this, { childList: true, subtree: true });
183
+ for (const type of ITEM_EXPAND_EVENTS)
184
+ this.addEventListener(type, this.stopItemEvent);
185
+ this.itemObserver = new MutationObserver(this.handleItemMutations);
186
+ this.itemObserver.observe(this, {
187
+ childList: true,
188
+ subtree: true,
189
+ characterData: true,
190
+ attributes: true,
191
+ attributeFilter: ITEM_ATTRIBUTES
192
+ });
193
+ if (this.source === "items")
194
+ this.syncFromItems();
195
+ this.resizeObserver = new ResizeObserver(this.measure);
196
+ this.gapObserver = new IntersectionObserver(this.handleGapIntersection, { threshold: [0, 1e-6] });
197
+ if (this.hasUpdated)
198
+ this.watchLayout();
95
199
  }
96
200
  disconnectedCallback() {
97
201
  super.disconnectedCallback();
98
- this.mutationObserver.disconnect();
99
- this.removeEventListener("focusin", this.handleFocusIn);
100
- this.removeEventListener("focusout", this.handleFocusOut);
101
- this.removeEventListener("flow-ui-lazy-change", this.handleSlotChange);
202
+ for (const type of ITEM_EXPAND_EVENTS)
203
+ this.removeEventListener(type, this.stopItemEvent);
204
+ this.itemObserver?.disconnect();
205
+ this.unwatchLayout();
102
206
  }
103
207
  handleClassChange() {
104
208
  this.classList.add(FlowRdfFormControl.FLOW_UI_FORM_CONTROL_CLASS);
105
209
  }
106
- // Generates a clone of the expand icon element to use for each tree item
107
- getExpandButtonIcon(status) {
108
- const slot = status === "expand" ? this.expandedIconSlot : this.collapsedIconSlot;
109
- const icon = slot.assignedElements({ flatten: true })[0];
110
- if (icon) {
111
- const clone = icon.cloneNode(true);
112
- [clone, ...clone.querySelectorAll("[id]")].forEach((el) => el.removeAttribute("id"));
113
- clone.setAttribute("data-default", "");
114
- clone.slot = `${status}-icon`;
115
- return clone;
116
- }
117
- return null;
118
- }
119
- handleTreeChanged(mutations) {
120
- for (const mutation of mutations) {
121
- const addedNodes = [...mutation.addedNodes].filter(FlowUiTreeItem.isTreeItem);
122
- const removedNodes = [...mutation.removedNodes].filter(FlowUiTreeItem.isTreeItem);
123
- addedNodes.forEach(this.initTreeItem);
124
- if (removedNodes.includes(this.lastFocusedItem)) {
125
- this.focusItem(this.getFocusableItems()[0]);
126
- }
210
+ firstUpdated() {
211
+ this.watchLayout();
212
+ }
213
+ willUpdate(changed) {
214
+ let rebuild = false;
215
+ if (changed.has("nodes")) {
216
+ this.indexNodes();
217
+ rebuild = true;
218
+ }
219
+ if (changed.has("expandedIds")) {
220
+ this.expanded = new Set(this.expandedIds);
221
+ rebuild = true;
222
+ }
223
+ if (changed.has("value") && this.value !== this.writtenValue) {
224
+ const kept = [...this.selected].filter((id) => this.generatedIds.has(id));
225
+ this.selected = this.normalizeSelection([...ensureArray(this.value), ...kept]);
226
+ } else if (changed.has("nodes") || changed.has("selectionMode")) {
227
+ this.selected = this.normalizeSelection(
228
+ [...this.selected].filter((id) => !this.generatedIds.has(id) || this.info.has(id))
229
+ );
230
+ }
231
+ if (changed.has("nodes") || changed.has("value") || changed.has("selectionMode") || changed.has("expandedIds")) {
232
+ this.itemStatesDirty = true;
233
+ }
234
+ if (changed.has("nodes") || changed.has("value") || changed.has("selectionMode")) {
235
+ this.applyItemSelections();
236
+ this.countSelected();
237
+ this.publishValue();
238
+ }
239
+ if (changed.has("filter") || changed.has("filterFn") || changed.has("nodes")) {
240
+ this.computeMatches();
241
+ if (changed.has("filter"))
242
+ this.filterCollapsed.clear();
243
+ rebuild = true;
127
244
  }
245
+ if (rebuild)
246
+ this.flatten();
128
247
  }
129
- handleSizeChange() {
130
- this.syncTreeItems();
248
+ updated() {
249
+ if (this.hasReusedRows && !this.restoringTransitions) {
250
+ this.restoringTransitions = true;
251
+ requestAnimationFrame(
252
+ () => requestAnimationFrame(() => {
253
+ this.restoringTransitions = false;
254
+ this.requestUpdate();
255
+ })
256
+ );
257
+ }
258
+ if (this.source === "items")
259
+ this.writeItemStates();
260
+ if (!this.rowSlots)
261
+ return;
262
+ const [start, end] = this.windowRange();
263
+ const ids = this.rows.slice(start, end).map((row) => row.node.id);
264
+ const key = `${start}:${end}:${ids.length}:${ids[0]}:${ids[ids.length - 1]}`;
265
+ if (key !== this.lastVisibleKey) {
266
+ this.lastVisibleKey = key;
267
+ this.dispatch("flow-ui-visible-change", { ids });
268
+ }
131
269
  }
132
- syncTreeItems(selectedItem) {
133
- const items = this.getAllTreeItems();
134
- items.forEach((items2) => {
135
- items2.size = this.size;
136
- });
137
- if (selectedItem) {
138
- if (this.selectionMode === "multiple") {
139
- syncCheckboxes(selectedItem);
270
+ //
271
+ // Data
272
+ //
273
+ indexNodes() {
274
+ const info = /* @__PURE__ */ new Map();
275
+ const walk = (node, parent) => {
276
+ const entry = { node, parent, leafCount: 0 };
277
+ info.set(node.id, entry);
278
+ if (isParent(node)) {
279
+ entry.leafCount = node.children.reduce((sum, child) => sum + walk(child, node), 0);
140
280
  } else {
141
- for (const item of items) {
142
- if (item !== selectedItem) {
143
- item.selected = false;
144
- }
145
- }
281
+ entry.leafCount = node.disabled ? 0 : 1;
282
+ }
283
+ return entry.leafCount;
284
+ };
285
+ this.nodes.forEach((node) => walk(node, null));
286
+ this.info = info;
287
+ }
288
+ /** Leaf ids only: a selected parent (for example a lazy node that has loaded) stands for its leaves. */
289
+ normalizeSelection(ids) {
290
+ const out = /* @__PURE__ */ new Set();
291
+ const single = this.selectionMode === "single" || this.selectionMode === "leaf";
292
+ for (const id of ids) {
293
+ const entry = this.info.get(id);
294
+ if (!entry) {
295
+ out.add(id);
296
+ } else if (this.selectionMode !== "multiple" || !isParent(entry.node)) {
297
+ out.add(id);
298
+ } else {
299
+ this.forEachLeaf(entry.node, (leaf) => out.add(leaf.id));
146
300
  }
147
301
  }
302
+ return single && out.size > 1 ? /* @__PURE__ */ new Set([[...out].pop()]) : out;
148
303
  }
149
- selectItem(selectedItem) {
150
- const previousSelection = [...this.selectedItems];
304
+ /** Publishes the selection as `value`, without the ids the tree made for items without a value. */
305
+ publishValue() {
306
+ const value = [...this.selected].filter((id) => !this.generatedIds.has(id));
307
+ const current = ensureArray(this.value);
308
+ if (value.length === current.length && value.every((id, i) => id === current[i]))
309
+ return;
310
+ this.writtenValue = value;
311
+ this.value = value;
312
+ }
313
+ countSelected() {
314
+ const counts = /* @__PURE__ */ new Map();
151
315
  if (this.selectionMode === "multiple") {
152
- selectedItem.selected = !selectedItem.selected;
153
- if (selectedItem.lazy) {
154
- selectedItem.expanded = true;
155
- }
156
- this.syncTreeItems(selectedItem);
157
- } else if (this.selectionMode === "single" || selectedItem.isLeaf) {
158
- selectedItem.expanded = !selectedItem.expanded;
159
- selectedItem.selected = true;
160
- this.syncTreeItems(selectedItem);
161
- } else if (this.selectionMode === "leaf") {
162
- selectedItem.expanded = !selectedItem.expanded;
163
- }
164
- const nextSelection = this.selectedItems;
165
- if (previousSelection.length !== nextSelection.length || nextSelection.some((item) => !previousSelection.includes(item))) {
166
- Promise.all(nextSelection.map((el) => el.updateComplete)).then(() => {
167
- this.value = nextSelection.map((item) => item.value).filter((value) => isStringFull(value));
168
- this.emit("flow-ui-input");
169
- this.emit("flow-ui-change");
316
+ const walk = (node) => {
317
+ if (!isParent(node))
318
+ return !node.disabled && this.selected.has(node.id) ? 1 : 0;
319
+ const count = node.children.reduce((sum, child) => sum + walk(child), 0);
320
+ counts.set(node.id, count);
321
+ return count;
322
+ };
323
+ this.nodes.forEach(walk);
324
+ }
325
+ this.selectedCounts = counts;
326
+ }
327
+ forEachLeaf(node, callback, onlyMatching = false) {
328
+ if (onlyMatching && this.matching && !this.matching.has(node.id))
329
+ return;
330
+ if (!isParent(node)) {
331
+ if (!node.disabled)
332
+ callback(node);
333
+ return;
334
+ }
335
+ node.children.forEach((child) => this.forEachLeaf(child, callback, onlyMatching));
336
+ }
337
+ computeMatches() {
338
+ const text = this.filter?.trim().toUpperCase();
339
+ if (!text) {
340
+ this.matching = null;
341
+ return;
342
+ }
343
+ const matches = this.filterFn ? (node) => this.filterFn(node, this.filter) : (node) => node.label.toUpperCase().includes(text);
344
+ const matching = /* @__PURE__ */ new Set();
345
+ const walk = (node) => {
346
+ const hit = isParent(node) ? node.children.map(walk).some(Boolean) : matches(node);
347
+ if (hit)
348
+ matching.add(node.id);
349
+ return hit;
350
+ };
351
+ this.nodes.forEach(walk);
352
+ this.matching = matching;
353
+ }
354
+ isExpanded(node) {
355
+ return this.matching ? !this.filterCollapsed.has(node.id) : this.expanded.has(node.id);
356
+ }
357
+ flatten() {
358
+ const rows = [];
359
+ const walk = (siblings, level, parent) => {
360
+ const visible = this.matching ? siblings.filter((node) => this.matching.has(node.id)) : siblings;
361
+ visible.forEach((node, i) => {
362
+ const row = { node, level, parent, posinset: i + 1, setsize: visible.length };
363
+ rows.push(row);
364
+ if (isParent(node) && this.isExpanded(node))
365
+ walk(node.children, level + 1, row);
170
366
  });
367
+ };
368
+ walk(this.nodes, 1, null);
369
+ const activeId = this.rows[this.activeIndex]?.node.id;
370
+ this.rows = rows;
371
+ if (activeId !== void 0)
372
+ this.activeIndex = rows.findIndex((row) => row.node.id === activeId);
373
+ }
374
+ /**
375
+ * Returns the check state of a node. In multiple selection, a parent's state is derived from its selected leaves;
376
+ * an unknown ID is `unchecked`.
377
+ */
378
+ checkState(id) {
379
+ const entry = this.info.get(id);
380
+ if (!entry)
381
+ return "unchecked";
382
+ if (this.selectionMode !== "multiple" || !isParent(entry.node)) {
383
+ return this.selected.has(id) ? "checked" : "unchecked";
171
384
  }
385
+ const count = this.selectedCounts.get(id) ?? 0;
386
+ return count === 0 ? "unchecked" : count >= entry.leafCount ? "checked" : "mixed";
172
387
  }
173
- getAllTreeItems() {
174
- return [...this.querySelectorAll("flow-ui-tree-item")];
388
+ /**
389
+ * Whether an item's attribute differs from what the tree last read from the item or wrote to it. Items reflect
390
+ * their properties to attributes in their own updates, which can come after the tree has read them (every item's
391
+ * `value`, when the items first render): reading every item again for those would double the work of a change.
392
+ */
393
+ itemAttributeChanged(item, name) {
394
+ const seen = this.itemsSeen.get(item);
395
+ if (seen?.read !== this.itemReads)
396
+ return true;
397
+ switch (name) {
398
+ case "value":
399
+ return this.itemId(item) !== seen.node.id;
400
+ case "expanded":
401
+ case "selected":
402
+ return itemFlag(item, name) !== seen[name];
403
+ case "disabled":
404
+ case "lazy":
405
+ return itemFlag(item, name) !== !!seen.node[name];
406
+ case "icon":
407
+ return itemValue(item, "icon") !== seen.node.icon;
408
+ case "icon-library":
409
+ return itemValue(item, "iconLibrary") !== seen.node.iconLibrary;
410
+ default:
411
+ return true;
412
+ }
175
413
  }
176
- focusItem(item) {
177
- item?.focus();
414
+ scheduleItemSync() {
415
+ if (this.itemSyncScheduled)
416
+ return;
417
+ this.itemSyncScheduled = true;
418
+ queueMicrotask(() => {
419
+ this.itemSyncScheduled = false;
420
+ this.syncFromItems();
421
+ });
178
422
  }
179
- handleKeyDown(event) {
180
- if (!["ArrowDown", "ArrowUp", "ArrowRight", "ArrowLeft", "Home", "End", "Enter", " "].includes(event.key)) {
423
+ /** Reads the tree items into `nodes` and `expandedIds`. */
424
+ syncFromItems() {
425
+ if (this.source !== "items")
181
426
  return;
427
+ const itemsById = /* @__PURE__ */ new Map();
428
+ const read = ++this.itemReads;
429
+ const expandedIds = [];
430
+ const known = this.itemsById;
431
+ const readItems = (parent) => [...parent.children].filter((el) => el.localName === ITEM_TAG && !el.hidden).map((item) => {
432
+ const id = this.itemId(item);
433
+ itemsById.set(id, item);
434
+ const expanded = itemFlag(item, "expanded");
435
+ const selected = itemFlag(item, "selected");
436
+ const node = { id, label: itemLabel(item) };
437
+ const seen = this.itemsSeen.get(item);
438
+ if (known.get(id) !== item || !seen) {
439
+ if (selected)
440
+ this.pendingItemSelections.set(item, true);
441
+ } else if (selected !== seen.selected) {
442
+ this.pendingItemSelections.set(item, selected);
443
+ }
444
+ if (seen) {
445
+ seen.node = node;
446
+ seen.expanded = expanded;
447
+ seen.selected = selected;
448
+ seen.read = read;
449
+ } else {
450
+ this.itemsSeen.set(item, { node, expanded, selected, read });
451
+ }
452
+ if (expanded)
453
+ expandedIds.push(id);
454
+ const children = readItems(item);
455
+ if (children.length)
456
+ node.children = children;
457
+ const icon = itemValue(item, "icon");
458
+ const iconLibrary = itemValue(item, "iconLibrary");
459
+ if (icon)
460
+ node.icon = icon;
461
+ if (iconLibrary)
462
+ node.iconLibrary = iconLibrary;
463
+ if (itemFlag(item, "disabled"))
464
+ node.disabled = true;
465
+ if (itemFlag(item, "lazy"))
466
+ node.lazy = true;
467
+ return node;
468
+ });
469
+ const nodes = readItems(this);
470
+ this.itemsById = itemsById;
471
+ this.settingItemNodes = true;
472
+ this.nodes = nodes;
473
+ this.settingItemNodes = false;
474
+ this.expandedIds = expandedIds;
475
+ }
476
+ /** The item's value, or an id the tree makes for it. */
477
+ itemId(item) {
478
+ const value = itemValue(item, "value");
479
+ if (value)
480
+ return value;
481
+ let id = this.itemIds.get(item);
482
+ if (!id) {
483
+ id = `flow-ui-tree-item-${++generatedIds}`;
484
+ this.itemIds.set(item, id);
485
+ this.generatedIds.add(id);
182
486
  }
183
- const items = this.getFocusableItems();
184
- const isLtr = this.localize.dir() === "ltr";
185
- const isRtl = this.localize.dir() === "rtl";
186
- if (items.length > 0) {
187
- event.preventDefault();
188
- const activeItemIndex = items.findIndex((item) => item.matches(":focus"));
189
- const activeItem = items[activeItemIndex];
190
- const focusItemAt = (index) => {
191
- const item = items[clamp(index, 0, items.length - 1)];
192
- this.focusItem(item);
193
- };
194
- const toggleExpand = (expanded) => {
195
- activeItem.expanded = expanded;
196
- };
197
- if (event.key === "ArrowDown") {
198
- focusItemAt(activeItemIndex + 1);
199
- } else if (event.key === "ArrowUp") {
200
- focusItemAt(activeItemIndex - 1);
201
- } else if (isLtr && event.key === "ArrowRight" || isRtl && event.key === "ArrowLeft") {
202
- if (!activeItem || activeItem.disabled || activeItem.expanded || activeItem.isLeaf && !activeItem.lazy) {
203
- focusItemAt(activeItemIndex + 1);
204
- } else {
205
- toggleExpand(true);
206
- }
207
- } else if (isLtr && event.key === "ArrowLeft" || isRtl && event.key === "ArrowRight") {
208
- if (!activeItem || activeItem.disabled || activeItem.isLeaf || !activeItem.expanded) {
209
- focusItemAt(activeItemIndex - 1);
210
- } else {
211
- toggleExpand(false);
212
- }
213
- } else if (event.key === "Home") {
214
- focusItemAt(0);
215
- } else if (event.key === "End") {
216
- focusItemAt(items.length - 1);
217
- } else if (event.key === "Enter" || event.key === " ") {
218
- if (!activeItem.disabled) {
219
- this.selectItem(activeItem);
220
- }
487
+ return id;
488
+ }
489
+ /** Applies the selections the application made on items, now that the nodes are indexed. */
490
+ applyItemSelections() {
491
+ if (!this.pendingItemSelections.size)
492
+ return;
493
+ for (const [item, select] of this.pendingItemSelections) {
494
+ const id = this.itemId(item);
495
+ const entry = this.info.get(id);
496
+ if (!entry)
497
+ continue;
498
+ if (this.selectionMode === "single" || this.selectionMode === "leaf") {
499
+ if (select)
500
+ this.selected = /* @__PURE__ */ new Set([id]);
501
+ else
502
+ this.selected.delete(id);
503
+ } else if (isParent(entry.node) && this.selectionMode === "multiple") {
504
+ this.forEachLeaf(entry.node, (leaf) => select ? this.selected.add(leaf.id) : this.selected.delete(leaf.id));
505
+ } else if (select)
506
+ this.selected.add(id);
507
+ else
508
+ this.selected.delete(id);
509
+ }
510
+ this.pendingItemSelections.clear();
511
+ }
512
+ /** Mirrors the selection and expansion onto the items, so their `selected` and `expanded` stay current. */
513
+ writeItemStates() {
514
+ if (!this.itemStatesDirty || !this.itemsById.size || !this.itemObserver)
515
+ return;
516
+ this.itemStatesDirty = false;
517
+ const pending = this.itemObserver.takeRecords();
518
+ for (const [id, item] of this.itemsById) {
519
+ const selected = this.selectionMode !== "none" && this.checkState(id) === "checked";
520
+ const expanded = this.expanded.has(id);
521
+ if (item.hasAttribute("selected") !== selected)
522
+ item.toggleAttribute("selected", selected);
523
+ if (item.hasAttribute("expanded") !== expanded)
524
+ item.toggleAttribute("expanded", expanded);
525
+ const seen = this.itemsSeen.get(item);
526
+ if (seen) {
527
+ seen.selected = selected;
528
+ seen.expanded = expanded;
221
529
  }
222
530
  }
531
+ this.itemObserver.takeRecords();
532
+ if (pending.length)
533
+ this.handleItemMutations(pending);
223
534
  }
224
- handleClick(event) {
225
- const target = event.target;
226
- const treeItem = target.closest("flow-ui-tree-item");
227
- const isExpandButton = event.composedPath().some((el) => el?.classList?.contains("tree-item__expand-button"));
228
- if (!treeItem || treeItem.disabled || target !== this.clickTarget) {
535
+ //
536
+ // Commands
537
+ //
538
+ /** Expands every parent node. */
539
+ expandAll() {
540
+ const ids = [];
541
+ this.info.forEach((entry, id) => isParent(entry.node) && ids.push(id));
542
+ this.filterCollapsed.clear();
543
+ this.expandedIds = ids;
544
+ }
545
+ /** Collapses every parent node. */
546
+ collapseAll() {
547
+ this.filterCollapsed = /* @__PURE__ */ new Set([...this.info.keys()]);
548
+ this.expandedIds = [];
549
+ }
550
+ /**
551
+ * Selects every enabled leaf, or, with `select` set to `false`, deselects every leaf. While filtering, only the
552
+ * leaves the filter shows are selected or deselected.
553
+ */
554
+ selectAll(select = true) {
555
+ const ids = new Set(this.selected);
556
+ this.nodes.forEach(
557
+ (node) => this.forEachLeaf(node, (leaf) => select ? ids.add(leaf.id) : ids.delete(leaf.id), true)
558
+ );
559
+ this.setSelection(ids);
560
+ }
561
+ /**
562
+ * Expands the node's ancestors, scrolls its row into view (in the tree, or in the elements that scroll the tree) and
563
+ * makes it the active row. Returns a promise that resolves to `true` when the row is in view, or to `false`, without
564
+ * scrolling, if the node is not in the tree or the filter hides it.
565
+ */
566
+ async scrollToNode(id, { block = "center" } = {}) {
567
+ const ancestors = [];
568
+ for (let entry = this.info.get(id); entry?.parent; entry = this.info.get(entry.parent.id))
569
+ ancestors.push(entry.parent.id);
570
+ if (ancestors.some((a) => !this.expanded.has(a))) {
571
+ this.expandedIds = [.../* @__PURE__ */ new Set([...this.expandedIds, ...ancestors])];
572
+ ancestors.forEach((a) => this.filterCollapsed.delete(a));
573
+ await this.updateComplete;
574
+ }
575
+ const index = this.rows.findIndex((row) => row.node.id === id);
576
+ if (index < 0)
577
+ return false;
578
+ this.activeIndex = index;
579
+ await this.scrollIndexIntoView(index, block);
580
+ return true;
581
+ }
582
+ /**
583
+ * The visible rows: every row that is not collapsed or filtered out, rendered or not. See
584
+ * [FlowTreeRow](../public-api/interfaces/FlowTreeRow).
585
+ */
586
+ get visibleRows() {
587
+ return this.rows;
588
+ }
589
+ /** Sets focus on the tree. */
590
+ focus(options) {
591
+ this.base?.focus({ preventScroll: true, ...options });
592
+ }
593
+ //
594
+ // Interaction
595
+ //
596
+ dispatch(name, detail, target = this) {
597
+ target.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail }));
598
+ }
599
+ setSelection(ids) {
600
+ this.selected = ids;
601
+ this.countSelected();
602
+ this.publishValue();
603
+ this.itemStatesDirty = true;
604
+ this.requestUpdate();
605
+ this.dispatch("flow-ui-input", {});
606
+ this.dispatch("flow-ui-change", {});
607
+ }
608
+ toggleExpanded(row, expanded = !this.isExpanded(row.node)) {
609
+ const node = row.node;
610
+ if (!isParent(node) && !node.lazy)
229
611
  return;
612
+ if (this.matching) {
613
+ if (expanded)
614
+ this.filterCollapsed.delete(node.id);
615
+ else
616
+ this.filterCollapsed.add(node.id);
230
617
  }
231
- if (this.selectionMode === "multiple" && isExpandButton) {
232
- treeItem.expanded = !treeItem.expanded;
233
- } else {
234
- this.selectItem(treeItem);
618
+ const next = new Set(this.expanded);
619
+ if (expanded)
620
+ next.add(node.id);
621
+ else
622
+ next.delete(node.id);
623
+ this.expandedIds = [...next];
624
+ if (this.matching)
625
+ this.requestUpdate("expandedIds");
626
+ const item = this.source === "items" ? this.itemsById.get(node.id) : void 0;
627
+ this.dispatch("flow-ui-node-toggle", { id: node.id, expanded });
628
+ if (item) {
629
+ this.dispatch(expanded ? "flow-ui-expand" : "flow-ui-collapse", null, item);
630
+ this.updateComplete.then(
631
+ () => this.dispatch(expanded ? "flow-ui-after-expand" : "flow-ui-after-collapse", null, item)
632
+ );
633
+ }
634
+ if (expanded && node.lazy) {
635
+ this.dispatch("flow-ui-node-lazy-load", { id: node.id });
636
+ if (item)
637
+ this.dispatch("flow-ui-lazy-load", null, item);
235
638
  }
236
639
  }
237
- handleMouseDown(event) {
238
- this.clickTarget = event.target;
640
+ toggleSelected(row) {
641
+ const node = row.node;
642
+ if (this.selectionMode === "leaf" && (isParent(node) || node.lazy)) {
643
+ this.toggleExpanded(row);
644
+ return;
645
+ }
646
+ if (node.disabled || this.selectionMode === "none")
647
+ return;
648
+ if (this.selectionMode === "single" || this.selectionMode === "leaf") {
649
+ this.setSelection(/* @__PURE__ */ new Set([node.id]));
650
+ return;
651
+ }
652
+ const ids = new Set(this.selected);
653
+ if (isParent(node)) {
654
+ let select = false;
655
+ this.forEachLeaf(node, (leaf) => select || (select = !ids.has(leaf.id)), true);
656
+ this.forEachLeaf(node, (leaf) => select ? ids.add(leaf.id) : ids.delete(leaf.id), true);
657
+ } else if (this.checkState(node.id) !== "checked")
658
+ ids.add(node.id);
659
+ else
660
+ ids.delete(node.id);
661
+ this.setSelection(ids);
239
662
  }
240
- handleFocusOut(event) {
241
- const relatedTarget = event.relatedTarget;
242
- if (!relatedTarget || !this.contains(relatedTarget)) {
243
- this.tabIndex = 0;
663
+ rowFromEvent(event) {
664
+ for (const el of event.composedPath()) {
665
+ if (el instanceof HTMLElement && el.dataset.index !== void 0)
666
+ return Number(el.dataset.index);
667
+ if (el === this.base)
668
+ break;
244
669
  }
670
+ return -1;
245
671
  }
246
- handleFocusIn(event) {
247
- const target = event.target;
248
- if (event.target === this) {
249
- this.focusItem(this.lastFocusedItem || this.getAllTreeItems()[0]);
672
+ handleClick(event) {
673
+ const index = this.rowFromEvent(event);
674
+ const row = this.rows[index];
675
+ if (!row)
676
+ return;
677
+ const path = event.composedPath();
678
+ if (path.some((el) => el instanceof HTMLElement && el.classList.contains("tree__end")))
679
+ return;
680
+ this.activeIndex = index;
681
+ const onExpandButton = path.some((el) => el instanceof HTMLElement && el.classList.contains("tree__expand"));
682
+ if (onExpandButton || this.selectionMode === "none")
683
+ this.toggleExpanded(row);
684
+ else
685
+ this.toggleSelected(row);
686
+ }
687
+ handleKeyDown(event) {
688
+ const keys = ["ArrowDown", "ArrowUp", "ArrowRight", "ArrowLeft", "Home", "End", "PageDown", "PageUp", "Enter", " "];
689
+ if (!keys.includes(event.key) || !this.rows.length)
690
+ return;
691
+ event.preventDefault();
692
+ const rtl = this.localize.dir() === "rtl";
693
+ const forward = rtl ? "ArrowLeft" : "ArrowRight";
694
+ const back = rtl ? "ArrowRight" : "ArrowLeft";
695
+ const index = Math.max(0, this.activeIndex);
696
+ const row = this.rows[index];
697
+ const visibleHeight = Math.max(0, this.visibleBottom - Math.max(0, this.visibleTop));
698
+ const page = Math.max(1, Math.floor(visibleHeight / this.effectiveRowHeight) - 1);
699
+ const moveTo = (i) => {
700
+ this.activeIndex = Math.min(this.rows.length - 1, Math.max(0, i));
701
+ this.scrollIndexIntoView(this.activeIndex, "nearest");
702
+ };
703
+ if (this.activeIndex < 0)
704
+ return moveTo(0);
705
+ switch (event.key) {
706
+ case "ArrowDown":
707
+ return moveTo(index + 1);
708
+ case "ArrowUp":
709
+ return moveTo(index - 1);
710
+ case "Home":
711
+ return moveTo(0);
712
+ case "End":
713
+ return moveTo(this.rows.length - 1);
714
+ case "PageDown":
715
+ return moveTo(index + page);
716
+ case "PageUp":
717
+ return moveTo(index - page);
718
+ case "Enter":
719
+ case " ":
720
+ return this.selectionMode === "none" ? this.toggleExpanded(row) : this.toggleSelected(row);
250
721
  }
251
- if (FlowUiTreeItem.isTreeItem(target) && !target.disabled) {
252
- if (this.lastFocusedItem) {
253
- this.lastFocusedItem.tabIndex = -1;
254
- }
255
- this.lastFocusedItem = target;
256
- this.tabIndex = -1;
257
- target.tabIndex = 0;
722
+ const expandable = isParent(row.node) || row.node.lazy;
723
+ if (event.key === forward) {
724
+ if (expandable && !this.isExpanded(row.node))
725
+ this.toggleExpanded(row, true);
726
+ else if (expandable)
727
+ moveTo(index + 1);
728
+ } else if (event.key === back) {
729
+ if (expandable && this.isExpanded(row.node))
730
+ this.toggleExpanded(row, false);
731
+ else if (row.parent)
732
+ moveTo(this.rows.indexOf(row.parent));
258
733
  }
259
734
  }
260
- handleHostExpandCollapse(event) {
261
- event.stopPropagation();
735
+ handleFocus() {
736
+ if (this.activeIndex < 0 && this.rows.length) {
737
+ const top = Math.floor(Math.max(0, this.visibleTop) / this.effectiveRowHeight);
738
+ this.activeIndex = Math.min(top, this.rows.length - 1);
739
+ }
262
740
  }
263
- handleSlotChange() {
264
- const items = this.getAllTreeItems();
265
- items.forEach(this.initTreeItem);
741
+ //
742
+ // Layout
743
+ //
744
+ get effectiveRowHeight() {
745
+ return this.rowHeight || ROW_HEIGHTS[this.size] || ROW_HEIGHTS.medium;
266
746
  }
267
- async handleSelectionChange() {
268
- const isSelectionMultiple = this.selectionMode === "multiple";
269
- const items = this.getAllTreeItems();
270
- this.setAttribute("aria-multiselectable", isSelectionMultiple ? "true" : "false");
271
- for (const item of items) {
272
- item.selectable = isSelectionMultiple;
747
+ /** Watches the tree and every element that clips it (the tree itself scrolls when it has a height). */
748
+ watchLayout() {
749
+ this.unwatchLayout();
750
+ const parents = [this];
751
+ for (let el = layoutParent(this); el; el = layoutParent(el)) {
752
+ if (el === document.documentElement || el === document.body)
753
+ break;
754
+ if (getComputedStyle(el).overflowY !== "visible")
755
+ parents.push(el);
273
756
  }
274
- if (isSelectionMultiple) {
275
- await this.updateComplete;
276
- [...this.querySelectorAll(":scope > flow-ui-tree-item")].forEach(
277
- (treeItem) => syncCheckboxes(treeItem, true)
278
- );
757
+ this.scrollParents = parents;
758
+ for (const el of parents) {
759
+ el.addEventListener("scroll", this.measure, { passive: true });
760
+ this.resizeObserver?.observe(el);
279
761
  }
762
+ window.addEventListener("scroll", this.measure, { passive: true });
763
+ window.addEventListener("resize", this.measure, { passive: true });
764
+ for (const gap of this.shadowRoot.querySelectorAll(".tree__gap"))
765
+ this.gapObserver?.observe(gap);
766
+ this.measure();
280
767
  }
281
- handleValueChange(previousValueOrNull) {
282
- const previousValue = ensureArray(previousValueOrNull);
283
- this.value = ensureArray(this.value);
284
- if (previousValue.length !== this.value.length || this.value.some((val) => !previousValue.includes(val)) || previousValue.some((val) => !this.value.includes(val))) {
285
- const selected = this.value.filter((val) => !previousValue.includes(val));
286
- const deselected = previousValue.filter((val) => !this.value.includes(val));
287
- const allItems = this.getAllTreeItems();
288
- const selectedItems = allItems.filter((item) => selected.includes(item.value));
289
- const deselectedItems = allItems.filter((item) => deselected.includes(item.value));
290
- selectedItems.forEach((item) => {
291
- item.selected = true;
292
- syncCheckboxes(item);
293
- });
294
- deselectedItems.forEach((item) => {
295
- item.selected = false;
296
- syncCheckboxes(item);
297
- });
768
+ unwatchLayout() {
769
+ for (const el of this.scrollParents)
770
+ el.removeEventListener("scroll", this.measure);
771
+ window.removeEventListener("scroll", this.measure);
772
+ window.removeEventListener("resize", this.measure);
773
+ this.resizeObserver?.disconnect();
774
+ this.gapObserver?.disconnect();
775
+ if (this.followFrame !== void 0)
776
+ cancelAnimationFrame(this.followFrame);
777
+ this.followFrame = void 0;
778
+ this.scrollParents = [];
779
+ }
780
+ followMotion() {
781
+ if (this.followFrame !== void 0)
782
+ return;
783
+ let last = "";
784
+ const step = () => {
785
+ this.measure();
786
+ const view = `${this.visibleTop}:${this.visibleBottom}`;
787
+ this.followFrame = view === last ? void 0 : requestAnimationFrame(step);
788
+ last = view;
789
+ };
790
+ this.followFrame = requestAnimationFrame(step);
791
+ }
792
+ async scrollIndexIntoView(index, block) {
793
+ this.pinnedIndex = index;
794
+ this.requestUpdate();
795
+ await this.updateComplete;
796
+ this.shadowRoot.getElementById(this.rowId(index))?.scrollIntoView({ block, inline: "nearest" });
797
+ this.pinnedIndex = -1;
798
+ this.measure();
799
+ await this.updateComplete;
800
+ }
801
+ //
802
+ // Rendering
803
+ //
804
+ windowRange() {
805
+ const rowHeight = this.effectiveRowHeight;
806
+ const first = Math.floor(Math.max(0, this.visibleTop) / rowHeight);
807
+ const last = Math.ceil(Math.max(0, this.visibleBottom) / rowHeight);
808
+ let start = Math.max(0, first - this.overscan);
809
+ let end = Math.min(this.rows.length, Math.max(last, first + 1) + this.overscan);
810
+ if (this.pinnedIndex >= 0 && (this.pinnedIndex < start || this.pinnedIndex >= end)) {
811
+ start = Math.max(0, this.pinnedIndex - this.overscan);
812
+ end = Math.min(this.rows.length, this.pinnedIndex + this.overscan + 1);
298
813
  }
814
+ return [start, end];
299
815
  }
300
- /** @internal Returns the list of tree items that are selected in the tree. */
301
- get selectedItems() {
302
- const items = this.getAllTreeItems();
303
- const isSelected = (item) => item.selected;
304
- return items.filter(isSelected);
305
- }
306
- /** @internal Gets focusable tree items in the tree. */
307
- getFocusableItems() {
308
- const items = this.getAllTreeItems();
309
- const collapsedItems = /* @__PURE__ */ new Set();
310
- return items.filter((item) => {
311
- if (item.disabled)
312
- return false;
313
- const parent = item.parentElement?.closest("[role=treeitem]");
314
- if (parent && (!parent.expanded || parent.loading || collapsedItems.has(parent))) {
315
- collapsedItems.add(item);
316
- }
317
- return !collapsedItems.has(item);
318
- });
816
+ rowId(index) {
817
+ return `row-${index}`;
319
818
  }
320
- render() {
819
+ renderRow(row, index, reused) {
820
+ const node = row.node;
821
+ const expandable = isParent(node) || !!node.lazy;
822
+ const expanded = expandable && this.isExpanded(node);
823
+ const loading = !!node.lazy && expanded;
824
+ const state2 = this.selectionMode === "none" ? "unchecked" : this.checkState(node.id);
825
+ const multiple = this.selectionMode === "multiple";
826
+ const single = this.selectionMode === "single" || this.selectionMode === "leaf";
827
+ const rtl = this.localize.dir() === "rtl";
321
828
  return html`
322
829
  <div
323
- part="base"
830
+ part="row"
831
+ id=${this.rowId(index)}
832
+ role="treeitem"
833
+ data-index=${index}
834
+ aria-level=${row.level}
835
+ aria-posinset=${row.posinset}
836
+ aria-setsize=${row.setsize}
837
+ aria-expanded=${expandable ? String(expanded) : nothing}
838
+ aria-selected=${single ? String(state2 === "checked") : nothing}
839
+ aria-checked=${multiple ? state2 === "mixed" ? "mixed" : String(state2 === "checked") : nothing}
840
+ aria-disabled=${node.disabled ? "true" : nothing}
841
+ aria-busy=${loading ? "true" : nothing}
324
842
  class=${classMap({
325
- tree: true,
326
- "tree--multiple": this.selectionMode === "multiple",
327
- "tree--small": this.size === "small",
328
- "tree--medium": this.size === "medium",
329
- "tree--large": this.size === "large"
843
+ tree__row: true,
844
+ "tree__row--active": index === this.activeIndex,
845
+ "tree__row--selected": single && state2 === "checked",
846
+ "tree__row--disabled": !!node.disabled
330
847
  })}
848
+ style=${styleMap({
849
+ height: `${this.effectiveRowHeight}px`,
850
+ paddingInlineStart: `calc(${row.level - 1} * var(--indent-size))`
851
+ })}
852
+ >
853
+ <span
854
+ class=${classMap({ tree__expand: true, "tree__expand--expanded": expanded && !loading })}
855
+ aria-hidden="true"
856
+ >
857
+ ${loading ? html`
858
+ <flow-ui-progress-ring
859
+ class="tree__spinner"
860
+ size=${this.size === "large" ? "medium" : this.size}
861
+ indeterminate
862
+ ></flow-ui-progress-ring>
863
+ ` : expandable ? html`
864
+ <flow-ui-icon library="system" name=${rtl ? "chevron-left" : "chevron-right"}></flow-ui-icon>
865
+ ` : nothing}
866
+ </span>
867
+ ${multiple ? html`
868
+ <flow-ui-checkbox
869
+ class=${classMap({ tree__checkbox: true, "tree__checkbox--reused": reused })}
870
+ size=${this.size}
871
+ tabindex="-1"
872
+ aria-hidden="true"
873
+ .checked=${state2 === "checked"}
874
+ .indeterminate=${state2 === "mixed"}
875
+ ?disabled=${!!node.disabled}
876
+ ></flow-ui-checkbox>
877
+ ` : nothing}
878
+ ${node.icon ? html`
879
+ <flow-ui-icon
880
+ class="tree__icon"
881
+ name=${node.icon}
882
+ library=${node.iconLibrary ?? "default"}
883
+ ></flow-ui-icon>
884
+ ` : nothing}
885
+ <span class="tree__label" part="label">${node.label}</span>
886
+ ${this.rowSlots || this.renderRowEnd ? html`
887
+ <span class="tree__end">
888
+ ${this.renderRowEnd ? this.renderRowEnd(node, row) : nothing}
889
+ ${this.rowSlots ? html`
890
+ <slot name=${node.id}></slot>
891
+ ` : nothing}
892
+ </span>
893
+ ` : nothing}
894
+ </div>
895
+ `;
896
+ }
897
+ render() {
898
+ const [start, end] = this.windowRange();
899
+ const windowRows = this.rows.slice(start, end);
900
+ const previousIds = this.rowNodeIds;
901
+ this.rowNodeIds = windowRows.map((row) => row.node.id);
902
+ const reused = this.rowNodeIds.map((id, i) => previousIds[i] !== void 0 && previousIds[i] !== id);
903
+ this.hasReusedRows = reused.includes(true);
904
+ const rowHeight = this.effectiveRowHeight;
905
+ return html`
906
+ <div
907
+ part="base"
908
+ class=${classMap({ tree: true, "tree--small": this.size === "small", "tree--large": this.size === "large" })}
909
+ role="tree"
910
+ tabindex="0"
911
+ aria-multiselectable=${this.selectionMode === "multiple" ? "true" : nothing}
912
+ aria-activedescendant=${this.activeIndex >= start && this.activeIndex < end ? this.rowId(this.activeIndex) : nothing}
331
913
  @click=${this.handleClick}
332
914
  @keydown=${this.handleKeyDown}
333
- @mousedown=${this.handleMouseDown}
915
+ @focus=${this.handleFocus}
334
916
  >
335
- <slot @slotchange=${this.handleSlotChange}></slot>
336
- <slot name="expand-icon" hidden aria-hidden="true"></slot>
337
- <slot name="collapse-icon" hidden aria-hidden="true"></slot>
917
+ <div class="tree__sizer"></div>
918
+ <div class="tree__spacer" style=${styleMap({ height: `${this.rows.length * rowHeight}px` })}>
919
+ <div class="tree__gap" style=${styleMap({ top: "0", height: `${start * rowHeight}px` })}></div>
920
+ <div
921
+ class="tree__gap"
922
+ style=${styleMap({ top: `${end * rowHeight}px`, height: `${(this.rows.length - end) * rowHeight}px` })}
923
+ ></div>
924
+ <div class="tree__window" style=${styleMap({ transform: `translateY(${start * rowHeight}px)` })}>
925
+ ${windowRows.map((row, i) => this.renderRow(row, start + i, reused[i]))}
926
+ </div>
927
+ </div>
338
928
  </div>
339
929
  `;
340
930
  }
341
931
  }
342
932
  FlowUiTree.tagName = "flow-ui-tree";
343
933
  FlowUiTree.styles = styles;
934
+ FlowUiTree.dependencies = [FlowUiCheckbox, FlowUiIcon, FlowUiProgressRing];
344
935
  __decorateClass([
345
- query("slot[name=expand-icon]")
346
- ], FlowUiTree.prototype, "expandedIconSlot", 2);
347
- __decorateClass([
348
- query("slot[name=collapse-icon]")
349
- ], FlowUiTree.prototype, "collapsedIconSlot", 2);
350
- __decorateClass([
351
- property({ reflect: true })
352
- ], FlowUiTree.prototype, "class", 2);
936
+ property({ attribute: false })
937
+ ], FlowUiTree.prototype, "nodes", 1);
353
938
  __decorateClass([
354
939
  property({
355
940
  converter: {
356
- fromAttribute: (value) => value.split(" "),
357
- toAttribute: (value) => value.join(" ")
941
+ fromAttribute: (value) => (value ?? "").split(" ").filter(Boolean),
942
+ toAttribute: (value) => ensureArray(value).join(" ")
358
943
  }
359
944
  })
360
945
  ], FlowUiTree.prototype, "value", 2);
946
+ __decorateClass([
947
+ property({ attribute: false })
948
+ ], FlowUiTree.prototype, "expandedIds", 2);
361
949
  __decorateClass([
362
950
  property({ attribute: "selection-mode" })
363
951
  ], FlowUiTree.prototype, "selectionMode", 2);
952
+ __decorateClass([
953
+ property()
954
+ ], FlowUiTree.prototype, "filter", 2);
955
+ __decorateClass([
956
+ property({ attribute: false })
957
+ ], FlowUiTree.prototype, "filterFn", 2);
958
+ __decorateClass([
959
+ property({ type: Number, attribute: "row-height" })
960
+ ], FlowUiTree.prototype, "rowHeight", 2);
961
+ __decorateClass([
962
+ property({ type: Number })
963
+ ], FlowUiTree.prototype, "overscan", 2);
364
964
  __decorateClass([
365
965
  property({ reflect: true })
366
966
  ], FlowUiTree.prototype, "size", 2);
367
967
  __decorateClass([
368
- watch("class")
369
- ], FlowUiTree.prototype, "handleClassChange", 1);
968
+ property({ type: Boolean, attribute: "row-slots" })
969
+ ], FlowUiTree.prototype, "rowSlots", 2);
370
970
  __decorateClass([
371
- watch("size", { waitUntilFirstUpdate: true })
372
- ], FlowUiTree.prototype, "handleSizeChange", 1);
971
+ property({ attribute: false })
972
+ ], FlowUiTree.prototype, "renderRowEnd", 2);
373
973
  __decorateClass([
374
- watch("selectionMode")
375
- ], FlowUiTree.prototype, "handleSelectionChange", 1);
974
+ property({ reflect: true })
975
+ ], FlowUiTree.prototype, "class", 2);
976
+ __decorateClass([
977
+ state()
978
+ ], FlowUiTree.prototype, "visibleTop", 2);
979
+ __decorateClass([
980
+ state()
981
+ ], FlowUiTree.prototype, "visibleBottom", 2);
982
+ __decorateClass([
983
+ state()
984
+ ], FlowUiTree.prototype, "activeIndex", 2);
376
985
  __decorateClass([
377
- watch("value", { waitUntilFirstUpdate: true })
378
- ], FlowUiTree.prototype, "handleValueChange", 1);
986
+ query(".tree")
987
+ ], FlowUiTree.prototype, "base", 2);
988
+ __decorateClass([
989
+ query(".tree__spacer")
990
+ ], FlowUiTree.prototype, "spacer", 2);
991
+ __decorateClass([
992
+ watch("class")
993
+ ], FlowUiTree.prototype, "handleClassChange", 1);
379
994
 
380
995
  export { FlowUiTree as default };