react-arborist 3.7.0 → 3.8.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.
Files changed (86) hide show
  1. package/dist/main/components/cursor.js +1 -2
  2. package/dist/main/components/default-container.js +31 -2
  3. package/dist/main/components/default-cursor.js +1 -1
  4. package/dist/main/components/default-drag-preview.d.ts +1 -1
  5. package/dist/main/components/default-drag-preview.js +1 -1
  6. package/dist/main/components/default-row.d.ts +1 -1
  7. package/dist/main/components/default-row.js +1 -1
  8. package/dist/main/components/list-outer-element.js +1 -1
  9. package/dist/main/components/provider.d.ts +1 -1
  10. package/dist/main/components/provider.js +2 -2
  11. package/dist/main/components/provider.test.js +70 -0
  12. package/dist/main/components/row-container.d.ts +1 -1
  13. package/dist/main/components/row-container.js +2 -3
  14. package/dist/main/dnd/drag-hook.js +1 -0
  15. package/dist/main/hooks/use-validated-props.js +1 -2
  16. package/dist/main/interfaces/node-api.js +4 -1
  17. package/dist/main/interfaces/tree-api.d.ts +27 -5
  18. package/dist/main/interfaces/tree-api.js +98 -14
  19. package/dist/main/interfaces/tree-api.test.js +31 -0
  20. package/dist/main/state/drag-slice.js +1 -2
  21. package/dist/main/types/state.d.ts +1 -1
  22. package/dist/main/types/tree-props.d.ts +3 -1
  23. package/dist/module/components/cursor.js +1 -2
  24. package/dist/module/components/default-container.js +32 -3
  25. package/dist/module/components/default-cursor.js +1 -1
  26. package/dist/module/components/default-drag-preview.d.ts +1 -1
  27. package/dist/module/components/default-drag-preview.js +1 -1
  28. package/dist/module/components/default-row.d.ts +1 -1
  29. package/dist/module/components/default-row.js +1 -1
  30. package/dist/module/components/list-outer-element.js +1 -1
  31. package/dist/module/components/provider.d.ts +1 -1
  32. package/dist/module/components/provider.js +4 -4
  33. package/dist/module/components/provider.test.js +71 -1
  34. package/dist/module/components/row-container.d.ts +1 -1
  35. package/dist/module/components/row-container.js +2 -3
  36. package/dist/module/dnd/compute-drop.js +1 -1
  37. package/dist/module/dnd/drag-hook.js +1 -0
  38. package/dist/module/hooks/use-validated-props.js +1 -2
  39. package/dist/module/interfaces/node-api.js +4 -1
  40. package/dist/module/interfaces/tree-api.d.ts +27 -5
  41. package/dist/module/interfaces/tree-api.js +98 -14
  42. package/dist/module/interfaces/tree-api.test.js +31 -0
  43. package/dist/module/state/drag-slice.js +1 -2
  44. package/dist/module/types/state.d.ts +1 -1
  45. package/dist/module/types/tree-props.d.ts +3 -1
  46. package/package.json +27 -27
  47. package/src/components/cursor.tsx +1 -2
  48. package/src/components/default-container.tsx +40 -19
  49. package/src/components/default-cursor.tsx +1 -5
  50. package/src/components/default-drag-preview.tsx +3 -16
  51. package/src/components/default-node.tsx +0 -1
  52. package/src/components/default-row.tsx +2 -13
  53. package/src/components/drag-preview-container.tsx +1 -1
  54. package/src/components/list-inner-element.tsx +1 -1
  55. package/src/components/list-outer-element.tsx +2 -3
  56. package/src/components/provider.test.tsx +85 -9
  57. package/src/components/provider.tsx +8 -23
  58. package/src/components/row-container.tsx +4 -9
  59. package/src/components/tree.tsx +2 -6
  60. package/src/context.ts +2 -3
  61. package/src/data/create-index.ts +0 -1
  62. package/src/data/create-list.ts +1 -2
  63. package/src/data/create-root.ts +2 -9
  64. package/src/data/simple-tree.ts +5 -3
  65. package/src/dnd/compute-drop.ts +6 -15
  66. package/src/dnd/drag-hook.ts +1 -0
  67. package/src/dnd/measure-hover.ts +2 -6
  68. package/src/dnd/outer-drop-hook.ts +1 -1
  69. package/src/hooks/use-fresh-node.ts +0 -1
  70. package/src/hooks/use-simple-tree.ts +2 -8
  71. package/src/hooks/use-validated-props.ts +4 -8
  72. package/src/interfaces/node-api.ts +2 -2
  73. package/src/interfaces/tree-api.test.ts +35 -0
  74. package/src/interfaces/tree-api.ts +103 -36
  75. package/src/state/dnd-slice.ts +1 -1
  76. package/src/state/drag-slice.ts +2 -5
  77. package/src/state/edit-slice.ts +1 -4
  78. package/src/state/focus-slice.ts +1 -1
  79. package/src/state/open-slice.ts +2 -5
  80. package/src/state/selection-slice.ts +2 -6
  81. package/src/types/handlers.ts +1 -3
  82. package/src/types/renderers.ts +0 -1
  83. package/src/types/state.ts +1 -1
  84. package/src/types/tree-props.ts +6 -10
  85. package/src/types/utils.ts +2 -3
  86. package/src/utils.ts +5 -14
@@ -8,8 +8,7 @@ export function Cursor() {
8
8
  if (!cursor || cursor.type !== "line")
9
9
  return null;
10
10
  const indent = tree.indent;
11
- const top = tree.rowHeight * cursor.index +
12
- ((_b = (_a = tree.props.padding) !== null && _a !== void 0 ? _a : tree.props.paddingTop) !== null && _b !== void 0 ? _b : 0);
11
+ const top = tree.rowTopPosition(cursor.index) + ((_b = (_a = tree.props.padding) !== null && _a !== void 0 ? _a : tree.props.paddingTop) !== null && _b !== void 0 ? _b : 0);
13
12
  const left = indent * cursor.level;
14
13
  const Cursor = tree.renderCursor;
15
14
  return _jsx(Cursor, { top, left, indent });
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { FixedSizeList } from "react-window";
2
+ import { FixedSizeList, VariableSizeList } from "react-window";
3
3
  import { useDataUpdates, useTreeApi } from "../context";
4
4
  import { focusNextElement, focusPrevElement } from "../utils";
5
5
  import { ListOuterElement } from "./list-outer-element";
@@ -13,7 +13,6 @@ let timeoutId = null;
13
13
  * the event handler. Future clean up welcome.
14
14
  */
15
15
  export function DefaultContainer() {
16
- var _a, _b;
17
16
  useDataUpdates();
18
17
  const tree = useTreeApi();
19
18
  return (_jsx("div", { role: "tree", style: {
@@ -231,5 +230,35 @@ export function DefaultContainer() {
231
230
  });
232
231
  if (node)
233
232
  tree.focus(node.id);
234
- }, children: _jsx(FixedSizeList, { className: tree.props.className, outerRef: tree.listEl, itemCount: tree.visibleNodes.length, height: tree.height, width: tree.width, itemSize: tree.rowHeight, overscanCount: tree.overscanCount, itemKey: (index) => { var _a; return ((_a = tree.visibleNodes[index]) === null || _a === void 0 ? void 0 : _a.id) || index; }, outerElementType: (_a = tree.props.outerElementType) !== null && _a !== void 0 ? _a : ListOuterElement, innerElementType: (_b = tree.props.innerElementType) !== null && _b !== void 0 ? _b : ListInnerElement, onScroll: tree.props.onScroll, onItemsRendered: tree.onItemsRendered.bind(tree), ref: tree.list, children: RowContainer }) }));
233
+ }, children: _jsx(List, {}) }));
234
+ }
235
+ /**
236
+ * Fixed-height trees (numeric rowHeight) render a FixedSizeList, preserving the
237
+ * original O(1) layout and avoiding VariableSizeList's measurement cache. Only
238
+ * the function form, which needs per-row heights, uses VariableSizeList.
239
+ */
240
+ function List() {
241
+ var _a, _b;
242
+ const tree = useTreeApi();
243
+ const commonProps = {
244
+ className: tree.props.className,
245
+ outerRef: tree.listEl,
246
+ itemCount: tree.visibleNodes.length,
247
+ height: tree.height,
248
+ width: tree.width,
249
+ overscanCount: tree.overscanCount,
250
+ itemKey: (index) => { var _a; return ((_a = tree.visibleNodes[index]) === null || _a === void 0 ? void 0 : _a.id) || index; },
251
+ outerElementType: (_a = tree.props.outerElementType) !== null && _a !== void 0 ? _a : ListOuterElement,
252
+ innerElementType: (_b = tree.props.innerElementType) !== null && _b !== void 0 ? _b : ListInnerElement,
253
+ onScroll: tree.props.onScroll,
254
+ onItemsRendered: tree.onItemsRendered.bind(tree),
255
+ };
256
+ if (typeof tree.props.rowHeight === "function") {
257
+ return (
258
+ // @ts-ignore
259
+ _jsx(VariableSizeList, Object.assign({}, commonProps, { itemSize: tree.rowHeightAt, ref: tree.list, children: RowContainer })));
260
+ }
261
+ return (
262
+ // @ts-ignore
263
+ _jsx(FixedSizeList, Object.assign({}, commonProps, { itemSize: tree.rowHeight, ref: tree.list, children: RowContainer })));
235
264
  }
@@ -17,7 +17,7 @@ const circleStyle = {
17
17
  boxShadow: "0 0 0 3px #4B91E2",
18
18
  borderRadius: "50%",
19
19
  };
20
- export const DefaultCursor = React.memo(function DefaultCursor({ top, left, indent, }) {
20
+ export const DefaultCursor = React.memo(function DefaultCursor({ top, left, indent }) {
21
21
  const style = {
22
22
  position: "absolute",
23
23
  pointerEvents: "none",
@@ -1,2 +1,2 @@
1
1
  import { DragPreviewProps } from "../types/renderers";
2
- export declare function DefaultDragPreview({ offset, mouse, id, dragIds, isDragging, }: DragPreviewProps): import("react/jsx-runtime").JSX.Element;
2
+ export declare function DefaultDragPreview({ offset, mouse, id, dragIds, isDragging }: DragPreviewProps): import("react/jsx-runtime").JSX.Element;
@@ -22,7 +22,7 @@ const getCountStyle = (offset) => {
22
22
  const { x, y } = offset;
23
23
  return { transform: `translate(${x + 10}px, ${y + 10}px)` };
24
24
  };
25
- export function DefaultDragPreview({ offset, mouse, id, dragIds, isDragging, }) {
25
+ export function DefaultDragPreview({ offset, mouse, id, dragIds, isDragging }) {
26
26
  return (_jsxs(Overlay, { isDragging: isDragging, children: [_jsx(Position, { offset: offset, children: _jsx(PreviewNode, { id: id, dragIds: dragIds }) }), _jsx(Count, { mouse: mouse, count: dragIds.length })] }));
27
27
  }
28
28
  const Overlay = memo(function Overlay(props) {
@@ -1,2 +1,2 @@
1
1
  import { RowRendererProps } from "../types/renderers";
2
- export declare function DefaultRow<T>({ node, attrs, innerRef, children, }: RowRendererProps<T>): import("react/jsx-runtime").JSX.Element;
2
+ export declare function DefaultRow<T>({ node, attrs, innerRef, children }: RowRendererProps<T>): import("react/jsx-runtime").JSX.Element;
@@ -1,4 +1,4 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- export function DefaultRow({ node, attrs, innerRef, children, }) {
2
+ export function DefaultRow({ node, attrs, innerRef, children }) {
3
3
  return (_jsx("div", Object.assign({}, attrs, { ref: innerRef, onFocus: (e) => e.stopPropagation(), onClick: node.handleClick, children: children })));
4
4
  }
@@ -26,7 +26,7 @@ export const ListOuterElement = forwardRef(function Outer(props, ref) {
26
26
  export const DropContainer = () => {
27
27
  const tree = useTreeApi();
28
28
  return (_jsx("div", { style: {
29
- height: tree.visibleNodes.length * tree.rowHeight,
29
+ height: tree.rowTopPosition(tree.visibleNodes.length),
30
30
  width: "100%",
31
31
  position: "absolute",
32
32
  left: "0",
@@ -6,5 +6,5 @@ type Props<T> = {
6
6
  imperativeHandle: React.Ref<TreeApi<T> | undefined>;
7
7
  children: ReactNode;
8
8
  };
9
- export declare function TreeProvider<T>({ treeProps, imperativeHandle, children, }: Props<T>): import("react/jsx-runtime").JSX.Element;
9
+ export declare function TreeProvider<T>({ treeProps, imperativeHandle, children }: Props<T>): import("react/jsx-runtime").JSX.Element;
10
10
  export {};
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useEffect, useImperativeHandle, useMemo, useRef, } from "react";
2
+ import { useEffect, useImperativeHandle, useMemo, useRef } from "react";
3
3
  import { useSyncExternalStore } from "use-sync-external-store/shim";
4
- import { DataUpdatesContext, DndContext, NodesContext, TreeApiContext, } from "../context";
4
+ import { DataUpdatesContext, DndContext, NodesContext, TreeApiContext } from "../context";
5
5
  import { TreeApi } from "../interfaces/tree-api";
6
6
  import { initialState } from "../state/initial";
7
7
  import { rootReducer } from "../state/root-reducer";
@@ -10,7 +10,7 @@ import { DndProvider } from "react-dnd";
10
10
  import { createStore } from "redux";
11
11
  import { actions as visibility } from "../state/open-slice";
12
12
  const SERVER_STATE = initialState();
13
- export function TreeProvider({ treeProps, imperativeHandle, children, }) {
13
+ export function TreeProvider({ treeProps, imperativeHandle, children }) {
14
14
  const list = useRef(null);
15
15
  const listEl = useRef(null);
16
16
  const store = useRef(
@@ -26,7 +26,7 @@ export function TreeProvider({ treeProps, imperativeHandle, children, }) {
26
26
  useMemo(() => {
27
27
  updateCount.current += 1;
28
28
  api.update(treeProps);
29
- }, [...Object.values(treeProps)]);
29
+ }, Object.values(treeProps));
30
30
  /* Rebuild visible nodes when open state changes, without clobbering
31
31
  props set imperatively via api.update(). Bumping updateCount keeps
32
32
  DataUpdates consumers (e.g. DefaultContainer) in sync. */
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { createRef } from "react";
3
- import { act, render } from "@testing-library/react";
3
+ import { act, render, screen } from "@testing-library/react";
4
+ import { FixedSizeList, VariableSizeList } from "react-window";
4
5
  import { Tree } from "./tree";
5
6
  const data = [
6
7
  {
@@ -29,3 +30,72 @@ test("imperative tree.update() props survive node toggles (#228)", () => {
29
30
  });
30
31
  expect(api.rowHeight).toBe(48);
31
32
  });
33
+ /* Backwards compatibility: switching FixedSizeList -> VariableSizeList must not
34
+ change layout for a numeric rowHeight. With openByDefault, all four nodes
35
+ (1 > 2, 3 > 4) are visible in DFS order. */
36
+ test("numeric rowHeight positions rows at index * height (#238 back-compat)", () => {
37
+ render(_jsx(Tree, { data: data, rowHeight: 24, openByDefault: true }));
38
+ const rows = screen.getAllByRole("treeitem");
39
+ expect(rows).toHaveLength(4);
40
+ rows.forEach((row, i) => {
41
+ expect(row.style.height).toBe("24px");
42
+ expect(row.style.top).toBe(`${i * 24}px`);
43
+ });
44
+ });
45
+ test("function rowHeight gives each row its own height and cumulative top (#238)", () => {
46
+ const heights = { "1": 40, "2": 20, "3": 30, "4": 10 };
47
+ render(_jsx(Tree, { data: data, rowHeight: (node) => heights[node.id], openByDefault: true }));
48
+ const rows = screen.getAllByRole("treeitem");
49
+ expect(rows).toHaveLength(4);
50
+ const expected = [40, 20, 30, 10];
51
+ let top = 0;
52
+ rows.forEach((row, i) => {
53
+ expect(row.style.height).toBe(`${expected[i]}px`);
54
+ expect(row.style.top).toBe(`${top}px`);
55
+ top += expected[i];
56
+ });
57
+ });
58
+ test("mutations tell the list to recompute heights (#238)", () => {
59
+ const ref = createRef();
60
+ /* Only variable-height mode renders a VariableSizeList with a measurement
61
+ cache to recompute, so use a function rowHeight here. */
62
+ render(_jsx(Tree, { data: data, ref: ref, rowHeight: () => 24, openByDefault: true }));
63
+ const api = ref.current;
64
+ const reset = jest.spyOn(api.list.current, "resetAfterIndex");
65
+ act(() => api.close("1"));
66
+ expect(reset).toHaveBeenCalled();
67
+ reset.mockClear();
68
+ act(() => api.open("1"));
69
+ expect(reset).toHaveBeenCalled();
70
+ });
71
+ /* react-window caches measurements by index and never invalidates them itself.
72
+ When data changes via props in variable-height mode, those cached sizes belong
73
+ to the wrong rows, so update() must drop the cache. It runs during render, so
74
+ it uses the shouldForceUpdate=false variant. */
75
+ test("changing data in variable-height mode resets the list cache (#238)", () => {
76
+ const ref = createRef();
77
+ const rowHeight = (node) => (node.isInternal ? 40 : 20);
78
+ const { rerender } = render(_jsx(Tree, { data: data, ref: ref, rowHeight: rowHeight, openByDefault: true }));
79
+ const reset = jest.spyOn(ref.current.list.current, "resetAfterIndex");
80
+ const nextData = [{ id: "9", name: "fresh" }, ...data];
81
+ act(() => {
82
+ rerender(_jsx(Tree, { data: nextData, ref: ref, rowHeight: rowHeight, openByDefault: true }));
83
+ });
84
+ expect(reset).toHaveBeenCalledWith(0, false);
85
+ });
86
+ /* The numeric path must stay on FixedSizeList: it has constant item sizes, so
87
+ there is no measurement cache to go stale and none of VariableSizeList's
88
+ overhead. A FixedSizeList has no resetAfterIndex method at all. */
89
+ test("numeric rowHeight renders a cache-free FixedSizeList (#238)", () => {
90
+ const ref = createRef();
91
+ render(_jsx(Tree, { data: data, ref: ref, rowHeight: 24, openByDefault: true }));
92
+ const list = ref.current.list.current;
93
+ expect(list).toBeInstanceOf(FixedSizeList);
94
+ expect("resetAfterIndex" in list).toBe(false);
95
+ });
96
+ /* The function path uses VariableSizeList so per-row heights are possible. */
97
+ test("function rowHeight renders a VariableSizeList (#238)", () => {
98
+ const ref = createRef();
99
+ render(_jsx(Tree, { data: data, ref: ref, rowHeight: () => 24, openByDefault: true }));
100
+ expect(ref.current.list.current).toBeInstanceOf(VariableSizeList);
101
+ });
@@ -3,5 +3,5 @@ type Props = {
3
3
  style: React.CSSProperties;
4
4
  index: number;
5
5
  };
6
- export declare const RowContainer: React.MemoExoticComponent<(<T>({ index, style, }: Props) => import("react/jsx-runtime").JSX.Element)>;
6
+ export declare const RowContainer: React.MemoExoticComponent<(<T>({ index, style }: Props) => import("react/jsx-runtime").JSX.Element)>;
7
7
  export {};
@@ -4,7 +4,7 @@ import { useDataUpdates, useNodesContext, useTreeApi } from "../context";
4
4
  import { useDragHook } from "../dnd/drag-hook";
5
5
  import { useDropHook } from "../dnd/drop-hook";
6
6
  import { useFreshNode } from "../hooks/use-fresh-node";
7
- export const RowContainer = React.memo(function RowContainer({ index, style, }) {
7
+ export const RowContainer = React.memo(function RowContainer({ index, style }) {
8
8
  /* When will the <Row> will re-render.
9
9
  *
10
10
  * The row component is memo'd so it will only render
@@ -35,8 +35,7 @@ export const RowContainer = React.memo(function RowContainer({ index, style, })
35
35
  const nodeStyle = useMemo(() => ({ paddingLeft: indent }), [indent]);
36
36
  const rowStyle = useMemo(() => {
37
37
  var _a, _b;
38
- return (Object.assign(Object.assign({}, style), { top: parseFloat(style.top) +
39
- ((_b = (_a = tree.props.padding) !== null && _a !== void 0 ? _a : tree.props.paddingTop) !== null && _b !== void 0 ? _b : 0) }));
38
+ return (Object.assign(Object.assign({}, style), { top: parseFloat(style.top) + ((_b = (_a = tree.props.padding) !== null && _a !== void 0 ? _a : tree.props.paddingTop) !== null && _b !== void 0 ? _b : 0) }));
40
39
  }, [style, tree.props.padding, tree.props.paddingTop]);
41
40
  const rowAttrs = {
42
41
  role: "treeitem",
@@ -1,4 +1,4 @@
1
- import { bound, indexOf, isClosed, isItem, isOpenWithEmptyChildren, } from "../utils";
1
+ import { bound, indexOf, isClosed, isItem, isOpenWithEmptyChildren } from "../utils";
2
2
  function measureHover(el, offset) {
3
3
  const rect = el.getBoundingClientRect();
4
4
  const x = offset.x - Math.round(rect.x);
@@ -17,6 +17,7 @@ export function useDragHook(node) {
17
17
  },
18
18
  end: () => {
19
19
  tree.hideCursor();
20
+ tree.redrawList();
20
21
  tree.dispatch(dnd.dragEnd());
21
22
  },
22
23
  }), [ids, node]);
@@ -3,8 +3,7 @@ export function useValidatedProps(props) {
3
3
  if (props.initialData && props.data) {
4
4
  throw new Error(`React Arborist Tree => Provide either a data or initialData prop, but not both.`);
5
5
  }
6
- if (props.initialData &&
7
- (props.onCreate || props.onDelete || props.onMove || props.onRename)) {
6
+ if (props.initialData && (props.onCreate || props.onDelete || props.onMove || props.onRename)) {
8
7
  throw new Error(`React Arborist Tree => You passed the initialData prop along with a data handler.
9
8
  Use the data prop if you want to provide your own handlers.`);
10
9
  }
@@ -3,7 +3,10 @@ export class NodeApi {
3
3
  constructor(params) {
4
4
  this.handleClick = (e) => {
5
5
  if (e.metaKey && !this.tree.props.disableMultiSelection) {
6
- this.isSelected ? this.deselect() : this.selectMulti();
6
+ if (this.isSelected)
7
+ this.deselect();
8
+ else
9
+ this.selectMulti();
7
10
  }
8
11
  else if (e.shiftKey && !this.tree.props.disableMultiSelection) {
9
12
  this.selectContiguous();
@@ -2,7 +2,7 @@ import { EditResult } from "../types/handlers";
2
2
  import { Identity, IdObj } from "../types/utils";
3
3
  import { TreeProps } from "../types/tree-props";
4
4
  import { MutableRefObject } from "react";
5
- import { Align, FixedSizeList, ListOnItemsRenderedProps } from "react-window";
5
+ import { Align, FixedSizeList, ListOnItemsRenderedProps, VariableSizeList } from "react-window";
6
6
  import { DefaultRow } from "../components/default-row";
7
7
  import { DefaultNode } from "../components/default-node";
8
8
  import { NodeApi } from "./node-api";
@@ -14,7 +14,7 @@ import { Store } from "redux";
14
14
  export declare class TreeApi<T> {
15
15
  store: Store<RootState, Actions>;
16
16
  props: TreeProps<T>;
17
- list: MutableRefObject<FixedSizeList | null>;
17
+ list: MutableRefObject<FixedSizeList | VariableSizeList | null>;
18
18
  listEl: MutableRefObject<HTMLDivElement | null>;
19
19
  static editPromise: null | ((args: EditResult) => void);
20
20
  root: NodeApi<T>;
@@ -24,7 +24,8 @@ export declare class TreeApi<T> {
24
24
  idToIndex: {
25
25
  [id: string]: number;
26
26
  };
27
- constructor(store: Store<RootState, Actions>, props: TreeProps<T>, list: MutableRefObject<FixedSizeList | null>, listEl: MutableRefObject<HTMLDivElement | null>);
27
+ private rowOffsets;
28
+ constructor(store: Store<RootState, Actions>, props: TreeProps<T>, list: MutableRefObject<FixedSizeList | VariableSizeList | null>, listEl: MutableRefObject<HTMLDivElement | null>);
28
29
  update(props: TreeProps<T>): void;
29
30
  dispatch(action: Actions): {
30
31
  type: "FOCUS";
@@ -121,7 +122,28 @@ export declare class TreeApi<T> {
121
122
  get width(): string | number;
122
123
  get height(): number;
123
124
  get indent(): number;
125
+ /**
126
+ * The fixed row height. When a `rowHeight` function is supplied for variable
127
+ * heights, this returns the default (24); use `rowHeightAt(index)` to get the
128
+ * height of a specific row.
129
+ */
124
130
  get rowHeight(): number;
131
+ /**
132
+ * The height of the row at `index`, evaluating the `rowHeight` function if
133
+ * given. Falls back to the default height for an out-of-range index so this
134
+ * never feeds an invalid `0` to react-window's `itemSize`.
135
+ */
136
+ rowHeightAt: (index: number) => number;
137
+ /** The pixel offset of the top of the row at `index` from the top of the list. */
138
+ rowTopPosition: (index: number) => number;
139
+ /**
140
+ * Tell the underlying virtualized list to recompute row heights at and after
141
+ * `index`. Call this if a `rowHeight` function's output changes for reasons
142
+ * the tree can't observe (e.g. external state).
143
+ */
144
+ redrawList: (afterIndex?: number) => void;
145
+ /** Lazily-built prefix sum where offsets[i] is the top of row i. */
146
+ private getRowOffsets;
125
147
  get overscanCount(): number;
126
148
  get searchTerm(): string;
127
149
  get matchFn(): (node: NodeApi<T>) => boolean;
@@ -185,8 +207,8 @@ export declare class TreeApi<T> {
185
207
  canDrop(): boolean;
186
208
  hideCursor(): void;
187
209
  showCursor(cursor: Cursor): void;
188
- open(identity: Identity): void;
189
- close(identity: Identity): void;
210
+ open(identity: Identity, redraw?: boolean): void;
211
+ close(identity: Identity, redraw?: boolean): void;
190
212
  toggle(identity: Identity): void;
191
213
  openParents(identity: Identity): void;
192
214
  openSiblings(node: NodeApi<T>): void;
@@ -30,6 +30,46 @@ export class TreeApi {
30
30
  this.listEl = listEl;
31
31
  this.visibleStartIndex = 0;
32
32
  this.visibleStopIndex = 0;
33
+ /* Memoized prefix-sum of row heights; only used for variable heights. */
34
+ this.rowOffsets = null;
35
+ /**
36
+ * The height of the row at `index`, evaluating the `rowHeight` function if
37
+ * given. Falls back to the default height for an out-of-range index so this
38
+ * never feeds an invalid `0` to react-window's `itemSize`.
39
+ */
40
+ this.rowHeightAt = (index) => {
41
+ const rowHeight = this.props.rowHeight;
42
+ if (typeof rowHeight === "function") {
43
+ const node = this.at(index);
44
+ return node ? rowHeight(node) : this.rowHeight;
45
+ }
46
+ return rowHeight !== null && rowHeight !== void 0 ? rowHeight : 24;
47
+ };
48
+ /** The pixel offset of the top of the row at `index` from the top of the list. */
49
+ this.rowTopPosition = (index) => {
50
+ /* Fixed heights: O(1). */
51
+ if (typeof this.props.rowHeight !== "function") {
52
+ return index * this.rowHeight;
53
+ }
54
+ /* Variable heights: O(1) amortized via a memoized prefix sum. */
55
+ const offsets = this.getRowOffsets();
56
+ const clamped = Math.max(0, Math.min(index, offsets.length - 1));
57
+ return offsets[clamped];
58
+ };
59
+ /**
60
+ * Tell the underlying virtualized list to recompute row heights at and after
61
+ * `index`. Call this if a `rowHeight` function's output changes for reasons
62
+ * the tree can't observe (e.g. external state).
63
+ */
64
+ this.redrawList = (afterIndex = 0) => {
65
+ this.rowOffsets = null;
66
+ /* Only the VariableSizeList (function rowHeight) caches measurements; a
67
+ FixedSizeList has constant heights and nothing to recompute. */
68
+ const list = this.list.current;
69
+ if (list && "resetAfterIndex" in list) {
70
+ list.resetAfterIndex(Math.max(0, afterIndex));
71
+ }
72
+ };
33
73
  /* Changes here must also be made in update() */
34
74
  this.root = createRoot(this);
35
75
  this.visibleNodes = createList(this);
@@ -41,6 +81,18 @@ export class TreeApi {
41
81
  this.root = createRoot(this);
42
82
  this.visibleNodes = createList(this);
43
83
  this.idToIndex = createIndex(this.visibleNodes);
84
+ this.rowOffsets = null;
85
+ /* Variable-height mode renders a VariableSizeList, which caches item
86
+ measurements by index and never invalidates them on its own. When the
87
+ visible nodes change (insert/remove/reorder), those cached sizes belong
88
+ to the wrong rows, so drop them. Fixed-height mode renders a
89
+ FixedSizeList (no cache, nothing to reset). update() runs during render,
90
+ so pass shouldForceUpdate=false: the in-progress render repaints the list
91
+ and a forceUpdate here would warn about setting state mid-render. */
92
+ const list = this.list.current;
93
+ if (list && "resetAfterIndex" in list) {
94
+ list.resetAfterIndex(0, false);
95
+ }
44
96
  }
45
97
  /* Store helpers */
46
98
  dispatch(action) {
@@ -65,9 +117,24 @@ export class TreeApi {
65
117
  var _a;
66
118
  return (_a = this.props.indent) !== null && _a !== void 0 ? _a : 24;
67
119
  }
120
+ /**
121
+ * The fixed row height. When a `rowHeight` function is supplied for variable
122
+ * heights, this returns the default (24); use `rowHeightAt(index)` to get the
123
+ * height of a specific row.
124
+ */
68
125
  get rowHeight() {
69
- var _a;
70
- return (_a = this.props.rowHeight) !== null && _a !== void 0 ? _a : 24;
126
+ return typeof this.props.rowHeight === "number" ? this.props.rowHeight : 24;
127
+ }
128
+ /** Lazily-built prefix sum where offsets[i] is the top of row i. */
129
+ getRowOffsets() {
130
+ if (this.rowOffsets)
131
+ return this.rowOffsets;
132
+ const offsets = [0];
133
+ for (let i = 0; i < this.visibleNodes.length; i++) {
134
+ offsets.push(offsets[i] + this.rowHeightAt(i));
135
+ }
136
+ this.rowOffsets = offsets;
137
+ return offsets;
71
138
  }
72
139
  get overscanCount() {
73
140
  var _a;
@@ -169,9 +236,7 @@ export class TreeApi {
169
236
  create() {
170
237
  return __awaiter(this, arguments, void 0, function* (opts = {}) {
171
238
  var _a, _b;
172
- const parentId = opts.parentId === undefined
173
- ? utils.getInsertParentId(this)
174
- : opts.parentId;
239
+ const parentId = opts.parentId === undefined ? utils.getInsertParentId(this) : opts.parentId;
175
240
  const index = (_a = opts.index) !== null && _a !== void 0 ? _a : utils.getInsertIndex(this);
176
241
  const type = (_b = opts.type) !== null && _b !== void 0 ? _b : "leaf";
177
242
  const data = yield safeRun(this.props.onCreate, {
@@ -198,20 +263,26 @@ export class TreeApi {
198
263
  const idents = Array.isArray(node) ? node : [node];
199
264
  const ids = idents.map(identify);
200
265
  const nodes = ids.map((id) => this.get(id)).filter((n) => !!n);
266
+ /* Guard against Math.min(...[]) === Infinity when no ids resolve to nodes. */
267
+ const fromIndex = nodes.length ? Math.min(...nodes.map((n) => { var _a; return (_a = n.rowIndex) !== null && _a !== void 0 ? _a : 0; })) : 0;
201
268
  yield safeRun(this.props.onDelete, { nodes, ids });
269
+ this.redrawList(fromIndex);
202
270
  });
203
271
  }
204
272
  edit(node) {
273
+ var _a, _b;
205
274
  const id = identify(node);
206
275
  this.resolveEdit({ cancelled: true });
207
276
  this.scrollTo(id);
208
277
  this.dispatch(edit(id));
278
+ this.redrawList((_b = (_a = this.get(id)) === null || _a === void 0 ? void 0 : _a.rowIndex) !== null && _b !== void 0 ? _b : 0);
209
279
  return new Promise((resolve) => {
210
280
  TreeApi.editPromise = resolve;
211
281
  });
212
282
  }
213
283
  submit(identity, value) {
214
284
  return __awaiter(this, void 0, void 0, function* () {
285
+ var _a, _b;
215
286
  if (!identity)
216
287
  return;
217
288
  const id = identify(identity);
@@ -222,12 +293,14 @@ export class TreeApi {
222
293
  });
223
294
  this.dispatch(edit(null));
224
295
  this.resolveEdit({ cancelled: false, value });
296
+ this.redrawList((_b = (_a = this.get(id)) === null || _a === void 0 ? void 0 : _a.rowIndex) !== null && _b !== void 0 ? _b : 0);
225
297
  setTimeout(() => this.onFocus()); // Return focus to element;
226
298
  });
227
299
  }
228
300
  reset() {
229
301
  this.dispatch(edit(null));
230
302
  this.resolveEdit({ cancelled: true });
303
+ this.redrawList();
231
304
  setTimeout(() => this.onFocus()); // Return focus to element;
232
305
  }
233
306
  activate(id) {
@@ -407,9 +480,7 @@ export class TreeApi {
407
480
  return this.state.dnd.cursor.type === "highlight";
408
481
  }
409
482
  get dragNodes() {
410
- return this.state.dnd.dragIds
411
- .map((id) => this.get(id))
412
- .filter((n) => !!n);
483
+ return this.state.dnd.dragIds.map((id) => this.get(id)).filter((n) => !!n);
413
484
  }
414
485
  get dragNode() {
415
486
  return this.get(this.state.nodes.drag.id);
@@ -461,22 +532,28 @@ export class TreeApi {
461
532
  this.dispatch(dnd.cursor(cursor));
462
533
  }
463
534
  /* Visibility */
464
- open(identity) {
535
+ open(identity, redraw = true) {
536
+ var _a, _b;
465
537
  const id = identifyNull(identity);
466
538
  if (!id)
467
539
  return;
468
540
  if (this.isOpen(id))
469
541
  return;
470
542
  this.dispatch(visibility.open(id, this.isFiltered));
543
+ if (redraw)
544
+ this.redrawList((_b = (_a = this.get(id)) === null || _a === void 0 ? void 0 : _a.rowIndex) !== null && _b !== void 0 ? _b : 0);
471
545
  safeRun(this.props.onToggle, id);
472
546
  }
473
- close(identity) {
547
+ close(identity, redraw = true) {
548
+ var _a, _b;
474
549
  const id = identifyNull(identity);
475
550
  if (!id)
476
551
  return;
477
552
  if (!this.isOpen(id))
478
553
  return;
479
554
  this.dispatch(visibility.close(id, this.isFiltered));
555
+ if (redraw)
556
+ this.redrawList((_b = (_a = this.get(id)) === null || _a === void 0 ? void 0 : _a.rowIndex) !== null && _b !== void 0 ? _b : 0);
480
557
  safeRun(this.props.onToggle, id);
481
558
  }
482
559
  toggle(identity) {
@@ -492,9 +569,10 @@ export class TreeApi {
492
569
  const node = utils.dfs(this.root, id);
493
570
  let parent = node === null || node === void 0 ? void 0 : node.parent;
494
571
  while (parent) {
495
- this.open(parent.id);
572
+ this.open(parent.id, false);
496
573
  parent = parent.parent;
497
574
  }
575
+ this.redrawList();
498
576
  }
499
577
  openSiblings(node) {
500
578
  const parent = node.parent;
@@ -505,23 +583,29 @@ export class TreeApi {
505
583
  const isOpen = node.isOpen;
506
584
  for (let sibling of parent.children) {
507
585
  if (sibling.isInternal) {
508
- isOpen ? this.close(sibling.id) : this.open(sibling.id);
586
+ if (isOpen)
587
+ this.close(sibling.id, false);
588
+ else
589
+ this.open(sibling.id, false);
509
590
  }
510
591
  }
592
+ this.redrawList();
511
593
  this.scrollTo(this.focusedNode);
512
594
  }
513
595
  }
514
596
  openAll() {
515
597
  utils.walk(this.root, (node) => {
516
598
  if (node.isInternal)
517
- node.open();
599
+ this.open(node.id, false);
518
600
  });
601
+ this.redrawList();
519
602
  }
520
603
  closeAll() {
521
604
  utils.walk(this.root, (node) => {
522
605
  if (node.isInternal)
523
- node.close();
606
+ this.close(node.id, false);
524
607
  });
608
+ this.redrawList();
525
609
  }
526
610
  /* Scrolling */
527
611
  scrollTo(identity, align = "smart") {
@@ -10,3 +10,34 @@ test("tree.canDrop()", () => {
10
10
  expect(setupApi({ disableDrop: () => false }).canDrop()).toBe(true);
11
11
  expect(setupApi({ disableDrop: false }).canDrop()).toBe(true);
12
12
  });
13
+ const rowData = [{ id: "a" }, { id: "b" }, { id: "c" }];
14
+ test("rowHeight defaults to 24", () => {
15
+ const api = setupApi({});
16
+ expect(api.rowHeight).toBe(24);
17
+ expect(api.rowHeightAt(0)).toBe(24);
18
+ });
19
+ test("fixed numeric rowHeight", () => {
20
+ const api = setupApi({ data: rowData, rowHeight: 30 });
21
+ expect(api.rowHeight).toBe(30);
22
+ expect(api.rowHeightAt(0)).toBe(30);
23
+ expect(api.rowTopPosition(0)).toBe(0);
24
+ expect(api.rowTopPosition(2)).toBe(60);
25
+ expect(api.rowTopPosition(3)).toBe(90); // total list height
26
+ });
27
+ test("variable rowHeight function", () => {
28
+ const heights = { a: 10, b: 20, c: 40 };
29
+ const api = setupApi({
30
+ data: rowData,
31
+ rowHeight: (node) => heights[node.id],
32
+ });
33
+ // The back-compat getter falls back to the default for variable heights.
34
+ expect(api.rowHeight).toBe(24);
35
+ expect(api.rowHeightAt(0)).toBe(10);
36
+ expect(api.rowHeightAt(1)).toBe(20);
37
+ expect(api.rowTopPosition(0)).toBe(0);
38
+ expect(api.rowTopPosition(1)).toBe(10);
39
+ expect(api.rowTopPosition(2)).toBe(30);
40
+ expect(api.rowTopPosition(3)).toBe(70); // total list height
41
+ // Out-of-range index falls back to the default height, never an invalid 0.
42
+ expect(api.rowHeightAt(99)).toBe(24);
43
+ });
@@ -7,8 +7,7 @@ export function reducer(state = initialState().nodes.drag, action) {
7
7
  case "DND_DRAG_END":
8
8
  return Object.assign(Object.assign({}, state), { id: null, destinationParentId: null, destinationIndex: null, selectedIds: [] });
9
9
  case "DND_HOVERING":
10
- if (action.parentId !== state.destinationParentId ||
11
- action.index != state.destinationIndex) {
10
+ if (action.parentId !== state.destinationParentId || action.index != state.destinationIndex) {
12
11
  return Object.assign(Object.assign({}, state), { destinationParentId: action.parentId, destinationIndex: action.index });
13
12
  }
14
13
  else {
@@ -1,2 +1,2 @@
1
1
  import { NodeApi } from "../interfaces/node-api";
2
- export type NodeState = typeof NodeApi.prototype["state"];
2
+ export type NodeState = (typeof NodeApi.prototype)["state"];