@eifi1/ui-kit 0.7.1 → 0.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 (222) hide show
  1. package/README.md +32 -17
  2. package/dist/chart.d.ts +3 -2
  3. package/dist/components/alert-banner.d.ts +59 -10
  4. package/dist/components/alert-banner.js +114 -8
  5. package/dist/components/alert-banner.js.map +1 -1
  6. package/dist/components/amount-input.d.ts +3 -0
  7. package/dist/components/button-group.d.ts +26 -0
  8. package/dist/components/button-group.js +49 -0
  9. package/dist/components/button-group.js.map +1 -0
  10. package/dist/components/calculator.d.ts +3 -0
  11. package/dist/components/chart-zoom.d.ts +63 -14
  12. package/dist/components/chart-zoom.js +82 -16
  13. package/dist/components/chart-zoom.js.map +1 -1
  14. package/dist/components/chip.d.ts +67 -2
  15. package/dist/components/chip.js +73 -8
  16. package/dist/components/chip.js.map +1 -1
  17. package/dist/components/confirm-dialog.d.ts +120 -0
  18. package/dist/components/confirm-dialog.js +96 -0
  19. package/dist/components/confirm-dialog.js.map +1 -0
  20. package/dist/components/copy-button.d.ts +62 -0
  21. package/dist/components/copy-button.js +95 -0
  22. package/dist/components/copy-button.js.map +1 -0
  23. package/dist/components/data-table-filter-popover.d.ts +1 -1
  24. package/dist/components/data-table-filters.d.ts +1 -1
  25. package/dist/components/data-table-pagination.d.ts +5 -1
  26. package/dist/components/data-table-pagination.js +71 -58
  27. package/dist/components/data-table-pagination.js.map +1 -1
  28. package/dist/components/data-table-sort.d.ts +28 -5
  29. package/dist/components/data-table-sort.js +11 -7
  30. package/dist/components/data-table-sort.js.map +1 -1
  31. package/dist/components/data-table.d.ts +1 -1
  32. package/dist/components/data-table.js +544 -423
  33. package/dist/components/data-table.js.map +1 -1
  34. package/dist/components/date-picker.d.ts +51 -5
  35. package/dist/components/date-picker.js +152 -40
  36. package/dist/components/date-picker.js.map +1 -1
  37. package/dist/components/description-list.d.ts +60 -0
  38. package/dist/components/description-list.js +112 -0
  39. package/dist/components/description-list.js.map +1 -0
  40. package/dist/components/disclosure.d.ts +37 -2
  41. package/dist/components/disclosure.js +14 -5
  42. package/dist/components/disclosure.js.map +1 -1
  43. package/dist/components/facing-pair.d.ts +2 -0
  44. package/dist/components/file-button.d.ts +17 -1
  45. package/dist/components/file-button.js +8 -1
  46. package/dist/components/file-button.js.map +1 -1
  47. package/dist/components/file-dropzone.d.ts +54 -9
  48. package/dist/components/file-dropzone.js +100 -70
  49. package/dist/components/file-dropzone.js.map +1 -1
  50. package/dist/components/floating-panel.d.ts +107 -0
  51. package/dist/components/floating-panel.js +206 -0
  52. package/dist/components/floating-panel.js.map +1 -0
  53. package/dist/components/full-bleed-dialog.d.ts +12 -1
  54. package/dist/components/full-bleed-dialog.js +26 -5
  55. package/dist/components/full-bleed-dialog.js.map +1 -1
  56. package/dist/components/modal.d.ts +6 -2
  57. package/dist/components/modal.js +2 -1
  58. package/dist/components/modal.js.map +1 -1
  59. package/dist/components/number-field.d.ts +3 -0
  60. package/dist/components/number-input.d.ts +3 -0
  61. package/dist/components/numpad-sheet.d.ts +3 -0
  62. package/dist/components/progress-bar.d.ts +54 -0
  63. package/dist/components/progress-bar.js +94 -0
  64. package/dist/components/progress-bar.js.map +1 -0
  65. package/dist/components/scroll-area.d.ts +53 -0
  66. package/dist/components/scroll-area.js +86 -0
  67. package/dist/components/scroll-area.js.map +1 -0
  68. package/dist/components/separator.d.ts +23 -0
  69. package/dist/components/separator.js +24 -0
  70. package/dist/components/separator.js.map +1 -0
  71. package/dist/components/series-chart-ticks.d.ts +34 -1
  72. package/dist/components/series-chart-ticks.js +83 -1
  73. package/dist/components/series-chart-ticks.js.map +1 -1
  74. package/dist/components/series-chart.d.ts +314 -19
  75. package/dist/components/series-chart.js +510 -120
  76. package/dist/components/series-chart.js.map +1 -1
  77. package/dist/components/skeleton.d.ts +36 -0
  78. package/dist/components/skeleton.js +35 -0
  79. package/dist/components/skeleton.js.map +1 -0
  80. package/dist/components/stat-tile.d.ts +60 -6
  81. package/dist/components/stat-tile.js +60 -26
  82. package/dist/components/stat-tile.js.map +1 -1
  83. package/dist/components/table.d.ts +83 -0
  84. package/dist/components/table.js +166 -0
  85. package/dist/components/table.js.map +1 -0
  86. package/dist/components/toggle-legend.d.ts +3 -2
  87. package/dist/components/toggle-legend.js +1 -1
  88. package/dist/components/toggle-legend.js.map +1 -1
  89. package/dist/components/tree-view.d.ts +129 -0
  90. package/dist/components/tree-view.js +376 -0
  91. package/dist/components/tree-view.js.map +1 -0
  92. package/dist/components/treemap.d.ts +9 -2
  93. package/dist/components/treemap.js +2 -1
  94. package/dist/components/treemap.js.map +1 -1
  95. package/dist/components/ui.d.ts +87 -13
  96. package/dist/components/ui.js +111 -29
  97. package/dist/components/ui.js.map +1 -1
  98. package/dist/components/use-table-state.d.ts +1 -1
  99. package/dist/{data-table-filters-noy0Abvi.d.ts → data-table-filters-CF1PXqjQ.d.ts} +73 -3
  100. package/dist/data-table.d.ts +2 -2
  101. package/dist/data-table.js.map +1 -1
  102. package/dist/hooks/use-copy-to-clipboard.d.ts +28 -0
  103. package/dist/hooks/use-copy-to-clipboard.js +81 -0
  104. package/dist/hooks/use-copy-to-clipboard.js.map +1 -0
  105. package/dist/hooks/use-debounce.d.ts +43 -0
  106. package/dist/hooks/use-debounce.js +56 -0
  107. package/dist/hooks/use-debounce.js.map +1 -0
  108. package/dist/hooks/use-file-drop.d.ts +72 -0
  109. package/dist/hooks/use-file-drop.js +57 -0
  110. package/dist/hooks/use-file-drop.js.map +1 -0
  111. package/dist/i18n/defaults.d.ts +3 -0
  112. package/dist/i18n/defaults.js +7 -1
  113. package/dist/i18n/defaults.js.map +1 -1
  114. package/dist/i18n/kit-labels.d.ts +15 -0
  115. package/dist/i18n/kit-labels.js +6 -2
  116. package/dist/i18n/kit-labels.js.map +1 -1
  117. package/dist/i18n/locales/de-CH-informal.d.ts +43 -0
  118. package/dist/i18n/locales/de-CH-informal.js +8 -0
  119. package/dist/i18n/locales/de-CH-informal.js.map +1 -0
  120. package/dist/i18n/locales/de-CH.d.ts +3 -0
  121. package/dist/i18n/locales/de-CH.js +1 -14
  122. package/dist/i18n/locales/de-CH.js.map +1 -1
  123. package/dist/i18n/locales/de-informal.d.ts +64 -0
  124. package/dist/i18n/locales/de-informal.js +37 -0
  125. package/dist/i18n/locales/de-informal.js.map +1 -0
  126. package/dist/i18n/locales/de.d.ts +3 -0
  127. package/dist/i18n/locales/de.js +25 -0
  128. package/dist/i18n/locales/de.js.map +1 -1
  129. package/dist/i18n/locales/es.d.ts +3 -0
  130. package/dist/i18n/locales/es.js +25 -0
  131. package/dist/i18n/locales/es.js.map +1 -1
  132. package/dist/i18n/locales/fr.d.ts +3 -0
  133. package/dist/i18n/locales/fr.js +25 -0
  134. package/dist/i18n/locales/fr.js.map +1 -1
  135. package/dist/i18n/locales/hu.d.ts +3 -0
  136. package/dist/i18n/locales/hu.js +25 -0
  137. package/dist/i18n/locales/hu.js.map +1 -1
  138. package/dist/i18n/locales/it.d.ts +3 -0
  139. package/dist/i18n/locales/it.js +25 -0
  140. package/dist/i18n/locales/it.js.map +1 -1
  141. package/dist/i18n/locales/zh.d.ts +3 -0
  142. package/dist/i18n/locales/zh.js +25 -0
  143. package/dist/i18n/locales/zh.js.map +1 -1
  144. package/dist/i18n/swiss.d.ts +13 -0
  145. package/dist/i18n/swiss.js +19 -0
  146. package/dist/i18n/swiss.js.map +1 -0
  147. package/dist/index.d.ts +25 -10
  148. package/dist/index.js +22 -0
  149. package/dist/index.js.map +1 -1
  150. package/dist/lib/dates.d.ts +37 -1
  151. package/dist/lib/dates.js +19 -0
  152. package/dist/lib/dates.js.map +1 -1
  153. package/dist/search/command-palette.d.ts +15 -1
  154. package/dist/search/command-palette.js +10 -2
  155. package/dist/search/command-palette.js.map +1 -1
  156. package/dist/wizard/stepper-nav.d.ts +35 -2
  157. package/dist/wizard/stepper-nav.js +54 -22
  158. package/dist/wizard/stepper-nav.js.map +1 -1
  159. package/dist/wizard/types.d.ts +107 -5
  160. package/dist/wizard/types.js +2 -1
  161. package/dist/wizard/types.js.map +1 -1
  162. package/dist/wizard/use-wizard.js +141 -21
  163. package/dist/wizard/use-wizard.js.map +1 -1
  164. package/dist/wizard/wizard-summary.d.ts +10 -2
  165. package/dist/wizard/wizard-summary.js +3 -1
  166. package/dist/wizard/wizard-summary.js.map +1 -1
  167. package/dist/wizard.d.ts +4 -1
  168. package/dist/wizard.js.map +1 -1
  169. package/package.json +1 -1
  170. package/src/components/alert-banner.tsx +211 -20
  171. package/src/components/button-group.tsx +75 -0
  172. package/src/components/chart-zoom.tsx +158 -20
  173. package/src/components/chip.tsx +160 -9
  174. package/src/components/confirm-dialog.tsx +242 -0
  175. package/src/components/copy-button.tsx +158 -0
  176. package/src/components/data-table-pagination.tsx +19 -6
  177. package/src/components/data-table-sort.ts +49 -10
  178. package/src/components/data-table.tsx +293 -24
  179. package/src/components/date-picker.tsx +262 -57
  180. package/src/components/description-list.tsx +174 -0
  181. package/src/components/disclosure.tsx +58 -5
  182. package/src/components/file-button.tsx +22 -2
  183. package/src/components/file-dropzone.tsx +198 -100
  184. package/src/components/floating-panel.tsx +341 -0
  185. package/src/components/full-bleed-dialog.tsx +48 -5
  186. package/src/components/modal.tsx +9 -2
  187. package/src/components/progress-bar.tsx +163 -0
  188. package/src/components/scroll-area.tsx +129 -0
  189. package/src/components/separator.tsx +37 -0
  190. package/src/components/series-chart-ticks.ts +135 -0
  191. package/src/components/series-chart.tsx +934 -67
  192. package/src/components/skeleton.tsx +65 -0
  193. package/src/components/stat-tile.tsx +160 -27
  194. package/src/components/table.tsx +263 -0
  195. package/src/components/toggle-legend.tsx +4 -3
  196. package/src/components/tree-view.tsx +589 -0
  197. package/src/components/treemap.tsx +10 -2
  198. package/src/components/ui.tsx +263 -39
  199. package/src/data-table.ts +2 -0
  200. package/src/hooks/use-copy-to-clipboard.ts +122 -0
  201. package/src/hooks/use-debounce.ts +105 -0
  202. package/src/hooks/use-file-drop.ts +123 -0
  203. package/src/i18n/defaults.ts +6 -0
  204. package/src/i18n/kit-labels.tsx +19 -0
  205. package/src/i18n/locales/de-CH-informal.ts +10 -0
  206. package/src/i18n/locales/de-CH.ts +1 -16
  207. package/src/i18n/locales/de-informal.ts +61 -0
  208. package/src/i18n/locales/de.ts +25 -0
  209. package/src/i18n/locales/es.ts +25 -0
  210. package/src/i18n/locales/fr.ts +25 -0
  211. package/src/i18n/locales/hu.ts +25 -0
  212. package/src/i18n/locales/it.ts +25 -0
  213. package/src/i18n/locales/zh.ts +25 -0
  214. package/src/i18n/swiss.ts +25 -0
  215. package/src/index.ts +29 -0
  216. package/src/lib/dates.ts +48 -0
  217. package/src/search/command-palette.tsx +29 -3
  218. package/src/wizard/stepper-nav.tsx +102 -28
  219. package/src/wizard/types.ts +106 -4
  220. package/src/wizard/use-wizard.ts +211 -31
  221. package/src/wizard/wizard-summary.tsx +24 -12
  222. package/src/wizard.ts +3 -2
@@ -0,0 +1,589 @@
1
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
2
+ import type { ComponentPropsWithoutRef, KeyboardEvent, MouseEvent, ReactNode } from "react";
3
+ import { ChevronRight } from "lucide-react";
4
+ import { cn } from "../lib/cn";
5
+ import { horizontalStep } from "../lib/direction";
6
+ import { Spinner } from "./ui";
7
+
8
+ /**
9
+ * A hierarchy you walk with the keyboard: kastlan's chart of accounts (Assets › Current
10
+ * assets › Bank › 1020 Operating account), and — through {@link TreeRow} alone — the
11
+ * row labels of its gantt, which indent and fold like a tree but sit beside a timeline
12
+ * and so cannot be one.
13
+ *
14
+ * Both apps had written it as nested `<div>`s with a chevron button per row: every
15
+ * row a Tab stop (a 300-account chart was 300 presses to get past), no way to say
16
+ * "level 3 of 5, collapsed" to a screen reader, and no ←/→ at all. This is the WAI-ARIA
17
+ * tree pattern instead:
18
+ *
19
+ * - `role="tree"` › `treeitem` (with `aria-level`, `aria-expanded` on a parent,
20
+ * `aria-selected` when selectable) › `role="group"` for its children — so the
21
+ * reader announces the position and the state it needs.
22
+ * - ONE Tab stop (roving tabindex). ↑/↓ walk the visible rows, → opens a closed
23
+ * parent and then steps into it, ← closes an open one and then steps out to the
24
+ * parent, Home/End jump to the ends, `*` opens every sibling, and typing a few
25
+ * letters jumps to the next row that starts with them. ←/→ follow the reading
26
+ * direction (`horizontalStep`): in an RTL tree the children hang off to the left,
27
+ * and ← is what opens them.
28
+ * - Enter / Space, or a click, select. The chevron alone toggles on click.
29
+ *
30
+ * `expanded` and `selected` each work controlled or uncontrolled.
31
+ */
32
+
33
+ /* ── Nodes ───────────────────────────────────────────────────────────────── */
34
+
35
+ export interface TreeNode<T = unknown> {
36
+ /** Unique across the whole tree — it is what `expanded` and `selected` hold. */
37
+ id: string;
38
+ label: ReactNode;
39
+ /** The text type-ahead matches. Defaults to the row's rendered text. */
40
+ textValue?: string;
41
+ /** Before the label: an account-type icon, a colour dot. */
42
+ icon?: ReactNode;
43
+ /** After the label, pushed to the end of the row: a balance, a count, an action. */
44
+ trailing?: ReactNode;
45
+ children?: readonly TreeNode<T>[];
46
+ /**
47
+ * The node has children that are not loaded yet — it gets a chevron, and opening it
48
+ * calls `loadChildren`. Pass the children in `items` once they arrive.
49
+ */
50
+ hasChildren?: boolean;
51
+ /** Focusable and announced as unavailable (`aria-disabled`), but not selectable. */
52
+ disabled?: boolean;
53
+ /** Anything of the host's own, handed back to `renderItem` and `onSelectedChange`. */
54
+ data?: T;
55
+ }
56
+
57
+ /** What {@link TreeViewProps.renderItem} is told about a row. */
58
+ export interface TreeItemState {
59
+ level: number;
60
+ expanded: boolean;
61
+ selected: boolean;
62
+ /** It has children, loaded or not — it shows a chevron. */
63
+ expandable: boolean;
64
+ loading: boolean;
65
+ disabled: boolean;
66
+ }
67
+
68
+ /* ── TreeRow ─────────────────────────────────────────────────────────────── */
69
+
70
+ export interface TreeRowProps extends ComponentPropsWithoutRef<"div"> {
71
+ /** 1 for a top-level row. Sets the indent and the number of guides. */
72
+ level: number;
73
+ /** `true`/`false` for a row that can fold; leave it `undefined` for a leaf, which
74
+ * gets a chevron-sized gap instead so labels at one level still line up. */
75
+ expanded?: boolean;
76
+ /**
77
+ * Make the chevron a real button (with `aria-expanded`, named by the label) that
78
+ * calls this. For a row used ON ITS OWN — kastlan's gantt labels, where each row is
79
+ * a line of a timeline and not an item of a tree widget. Inside {@link TreeView} it
80
+ * is omitted: the tree owns the keys, and a button per row would be a Tab stop per
81
+ * row, which is what the tree exists to remove.
82
+ */
83
+ onToggle?: () => void;
84
+ /** The toggle button's name. By default it is named by the row's label (the state
85
+ * is `aria-expanded`'s to say); required when `children` replaces the label. */
86
+ toggleLabel?: string;
87
+ label: ReactNode;
88
+ icon?: ReactNode;
89
+ trailing?: ReactNode;
90
+ /** Pixels per level. Default 16. */
91
+ indent?: number;
92
+ /** Draw a vertical hairline per ancestor level. Default `true`. */
93
+ guides?: boolean;
94
+ selected?: boolean;
95
+ /** A spinner in place of the chevron, while lazy children load. */
96
+ loading?: boolean;
97
+ /** Replace the label + trailing part of the row (the indent and chevron stay). */
98
+ children?: ReactNode;
99
+ }
100
+
101
+ const DEFAULT_INDENT = 16;
102
+ /** The chevron's box; the guide for a level runs through its centre. */
103
+ const CHEVRON = 16;
104
+ /** The row's start padding, before any indent. */
105
+ const ROW_PAD = 4;
106
+
107
+ /**
108
+ * One row: indent, guides, chevron, icon, label, trailing — no tree semantics of its
109
+ * own. {@link TreeView} is built from it, and a host that needs the look without the
110
+ * widget (a gantt's label column) uses it directly.
111
+ *
112
+ * Laid out with logical properties throughout (`padding-inline-start`,
113
+ * `inset-inline-start`), so the indent, the guides and the chevron all hang from the
114
+ * reading start in an RTL layout without a second code path.
115
+ */
116
+ export function TreeRow({
117
+ level,
118
+ expanded,
119
+ onToggle,
120
+ toggleLabel,
121
+ label,
122
+ icon,
123
+ trailing,
124
+ indent = DEFAULT_INDENT,
125
+ guides = true,
126
+ selected,
127
+ loading,
128
+ children,
129
+ className,
130
+ style,
131
+ ...rest
132
+ }: TreeRowProps) {
133
+ const labelId = useId();
134
+ const depth = Math.max(0, level - 1);
135
+ const expandable = expanded !== undefined;
136
+ // A right-pointing chevron that turns DOWN when open. In RTL it is mirrored to point
137
+ // left, and turning that one clockwise would point it UP — so it turns the other way.
138
+ const chevron = (
139
+ <ChevronRight
140
+ aria-hidden
141
+ className={cn(
142
+ "size-4 transition-transform motion-reduce:transition-none rtl:-scale-x-100",
143
+ expanded && "rotate-90 rtl:-rotate-90",
144
+ )}
145
+ />
146
+ );
147
+ return (
148
+ <div
149
+ {...rest}
150
+ data-tree-row=""
151
+ data-selected={selected || undefined}
152
+ style={{ paddingInlineStart: ROW_PAD + depth * indent, ...style }}
153
+ className={cn(
154
+ "relative flex min-h-8 items-center gap-1.5 rounded pe-2 text-sm",
155
+ selected
156
+ ? "bg-[var(--bg-active)] font-medium text-[var(--text-primary)]"
157
+ : "text-[var(--text-secondary)]",
158
+ className,
159
+ )}
160
+ >
161
+ {guides &&
162
+ Array.from({ length: depth }, (_, i) => (
163
+ <span
164
+ key={i}
165
+ aria-hidden
166
+ data-tree-guide=""
167
+ className="pointer-events-none absolute inset-y-0 w-px bg-[var(--border)]"
168
+ style={{ insetInlineStart: ROW_PAD + i * indent + CHEVRON / 2 }}
169
+ />
170
+ ))}
171
+ {loading ? (
172
+ <span className="flex size-4 shrink-0 items-center justify-center">
173
+ <Spinner label={null} className="size-3 border" />
174
+ </span>
175
+ ) : expandable && onToggle ? (
176
+ <button
177
+ type="button"
178
+ aria-expanded={expanded}
179
+ aria-label={toggleLabel}
180
+ aria-labelledby={toggleLabel ? undefined : labelId}
181
+ onClick={(e) => {
182
+ e.stopPropagation();
183
+ onToggle();
184
+ }}
185
+ className="flex size-4 shrink-0 items-center justify-center rounded text-[var(--text-muted)] outline-none hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--brand)]"
186
+ >
187
+ {chevron}
188
+ </button>
189
+ ) : expandable ? (
190
+ <span data-tree-toggle="" className="flex size-4 shrink-0 cursor-pointer items-center justify-center text-[var(--text-muted)]">
191
+ {chevron}
192
+ </span>
193
+ ) : (
194
+ <span aria-hidden className="size-4 shrink-0" />
195
+ )}
196
+ {children ?? (
197
+ <>
198
+ {icon && <span className="flex shrink-0 items-center">{icon}</span>}
199
+ <span id={labelId} data-tree-label="" className="min-w-0 flex-1 truncate">
200
+ {label}
201
+ </span>
202
+ {trailing !== undefined && trailing !== null && (
203
+ <span className="ms-auto flex shrink-0 items-center gap-1 text-xs tabular-nums text-[var(--text-muted)]">
204
+ {trailing}
205
+ </span>
206
+ )}
207
+ </>
208
+ )}
209
+ </div>
210
+ );
211
+ }
212
+
213
+ /* ── TreeView ────────────────────────────────────────────────────────────── */
214
+
215
+ export interface TreeViewProps<T = unknown>
216
+ extends Omit<ComponentPropsWithoutRef<"ul">, "onSelect" | "children" | "defaultValue"> {
217
+ items: readonly TreeNode<T>[];
218
+ /** Open nodes, controlled. */
219
+ expanded?: readonly string[];
220
+ /** Open nodes on first render, uncontrolled. */
221
+ defaultExpanded?: readonly string[];
222
+ onExpandedChange?: (expanded: string[]) => void;
223
+ /** The selected node's id, controlled; `null` for none. */
224
+ selected?: string | null;
225
+ defaultSelected?: string | null;
226
+ onSelectedChange?: (id: string, node: TreeNode<T>) => void;
227
+ /** `"none"` makes it a navigation-only tree: no `aria-selected`, Enter toggles. */
228
+ selectionMode?: "single" | "none";
229
+ /** The whole row content after the chevron, per node. Wins over `label`/`trailing`. */
230
+ renderItem?: (node: TreeNode<T>, state: TreeItemState) => ReactNode;
231
+ /**
232
+ * Called when a node with `hasChildren` and no `children` is opened. While the
233
+ * promise is pending the row shows a spinner and is `aria-busy`; put the children
234
+ * into `items` before it resolves (or after — the row opens either way).
235
+ */
236
+ loadChildren?: (node: TreeNode<T>) => Promise<void> | void;
237
+ /** Pixels per level. Default 16. */
238
+ indent?: number;
239
+ /** Vertical hairlines per level. Default `true`. */
240
+ indentGuides?: boolean;
241
+ /** Extra classes for each row (the `TreeRow`), e.g. a denser height. */
242
+ rowClassName?: string;
243
+ }
244
+
245
+ interface FlatNode<T> {
246
+ node: TreeNode<T>;
247
+ level: number;
248
+ parentId: string | null;
249
+ }
250
+
251
+ const isExpandable = (n: TreeNode<unknown>) => Boolean(n.children?.length || n.hasChildren);
252
+
253
+ /** Controlled when `value` is given, otherwise state seeded from `initial`. */
254
+ function useControllable<V>(value: V | undefined, initial: V): [V, (next: V) => void] {
255
+ const [own, setOwn] = useState<V>(initial);
256
+ const controlled = value !== undefined;
257
+ const set = (next: V) => {
258
+ if (!controlled) setOwn(next);
259
+ };
260
+ return [controlled ? value : own, set];
261
+ }
262
+
263
+ /** How long a type-ahead run stays open between keys — the APG's suggested half second. */
264
+ const TYPEAHEAD_MS = 500;
265
+
266
+ export function TreeView<T = unknown>({
267
+ items,
268
+ expanded: expandedProp,
269
+ defaultExpanded,
270
+ onExpandedChange,
271
+ selected: selectedProp,
272
+ defaultSelected,
273
+ onSelectedChange,
274
+ selectionMode = "single",
275
+ renderItem,
276
+ loadChildren,
277
+ indent = DEFAULT_INDENT,
278
+ indentGuides = true,
279
+ rowClassName,
280
+ className,
281
+ onKeyDown,
282
+ onClick,
283
+ ...rest
284
+ }: TreeViewProps<T>) {
285
+ const [expandedList, setExpandedOwn] = useControllable<readonly string[]>(
286
+ expandedProp,
287
+ defaultExpanded ?? [],
288
+ );
289
+ const [selected, setSelectedOwn] = useControllable<string | null>(
290
+ selectedProp,
291
+ defaultSelected ?? null,
292
+ );
293
+ const expandedSet = useMemo(() => new Set(expandedList), [expandedList]);
294
+ const [loading, setLoading] = useState<ReadonlySet<string>>(() => new Set());
295
+ const [focusedId, setFocusedId] = useState<string | null>(null);
296
+ const itemRefs = useRef(new Map<string, HTMLLIElement>());
297
+ const pendingFocus = useRef<string | null>(null);
298
+ const typeahead = useRef({ text: "", at: 0 });
299
+ const baseId = useId();
300
+
301
+ // Every node by id (for parents and lookups), and the rows currently on screen in
302
+ // order — the list the arrow keys walk.
303
+ const { byId, visible } = useMemo(() => {
304
+ const map = new Map<string, FlatNode<T>>();
305
+ const rows: FlatNode<T>[] = [];
306
+ const walk = (nodes: readonly TreeNode<T>[], level: number, parentId: string | null, shown: boolean) => {
307
+ for (const node of nodes) {
308
+ const flat = { node, level, parentId };
309
+ map.set(node.id, flat);
310
+ if (shown) rows.push(flat);
311
+ if (node.children) walk(node.children, level + 1, node.id, shown && expandedSet.has(node.id));
312
+ }
313
+ };
314
+ walk(items, 1, null, true);
315
+ return { byId: map, visible: rows };
316
+ }, [items, expandedSet]);
317
+
318
+ // The one tabbable row. Focus that was inside a branch that has since closed (a
319
+ // click on its parent's chevron) moves up to the nearest ancestor still on screen,
320
+ // so the tab stop never points at a row that is not rendered.
321
+ const visibleIds = useMemo(() => new Set(visible.map((f) => f.node.id)), [visible]);
322
+ const nearestVisible = (id: string | null): string | null => {
323
+ let cur = id;
324
+ while (cur && !visibleIds.has(cur)) cur = byId.get(cur)?.parentId ?? null;
325
+ return cur;
326
+ };
327
+ const tabbable =
328
+ nearestVisible(focusedId) ?? nearestVisible(selected) ?? visible[0]?.node.id ?? null;
329
+
330
+ useEffect(() => {
331
+ const id = pendingFocus.current;
332
+ if (!id) return;
333
+ pendingFocus.current = null;
334
+ itemRefs.current.get(id)?.focus();
335
+ });
336
+
337
+ const focusRow = (id: string) => {
338
+ setFocusedId(id);
339
+ // After the commit: moving into a branch that just opened targets a row that is
340
+ // not in the DOM yet.
341
+ pendingFocus.current = id;
342
+ itemRefs.current.get(id)?.focus();
343
+ };
344
+
345
+ const setExpanded = (next: Set<string>) => {
346
+ const list = [...next];
347
+ setExpandedOwn(list);
348
+ onExpandedChange?.(list);
349
+ };
350
+
351
+ const open = (node: TreeNode<T>) => {
352
+ if (expandedSet.has(node.id) || !isExpandable(node)) return;
353
+ const next = new Set(expandedSet);
354
+ next.add(node.id);
355
+ setExpanded(next);
356
+ if (loadChildren && node.hasChildren && !node.children?.length) {
357
+ const pending = loadChildren(node);
358
+ if (pending && typeof pending.then === "function") {
359
+ setLoading((s) => new Set(s).add(node.id));
360
+ const done = () =>
361
+ setLoading((s) => {
362
+ const n = new Set(s);
363
+ n.delete(node.id);
364
+ return n;
365
+ });
366
+ pending.then(done, done);
367
+ }
368
+ }
369
+ };
370
+
371
+ const close = (node: TreeNode<T>) => {
372
+ if (!expandedSet.has(node.id)) return;
373
+ const next = new Set(expandedSet);
374
+ next.delete(node.id);
375
+ setExpanded(next);
376
+ };
377
+
378
+ const toggle = (node: TreeNode<T>) => (expandedSet.has(node.id) ? close(node) : open(node));
379
+
380
+ const select = (node: TreeNode<T>) => {
381
+ if (node.disabled) return;
382
+ if (selectionMode === "none") {
383
+ toggle(node);
384
+ return;
385
+ }
386
+ setSelectedOwn(node.id);
387
+ onSelectedChange?.(node.id, node);
388
+ };
389
+
390
+ const idOf = (target: EventTarget | null): string | null =>
391
+ (target as Element | null)?.closest?.<HTMLElement>('[role="treeitem"]')?.dataset.treeId ?? null;
392
+
393
+ const textOf = (flat: FlatNode<T>): string => {
394
+ if (flat.node.textValue !== undefined) return flat.node.textValue;
395
+ if (typeof flat.node.label === "string") return flat.node.label;
396
+ const row = itemRefs.current.get(flat.node.id)?.querySelector("[data-tree-row]");
397
+ return row?.textContent ?? "";
398
+ };
399
+
400
+ const findByText = (fromIndex: number, text: string): string | null => {
401
+ const needle = text.toLocaleLowerCase();
402
+ for (let i = 1; i <= visible.length; i++) {
403
+ const flat = visible[(fromIndex + i) % visible.length];
404
+ if (textOf(flat).trim().toLocaleLowerCase().startsWith(needle)) return flat.node.id;
405
+ }
406
+ return null;
407
+ };
408
+
409
+ const handleKeyDown = (e: KeyboardEvent<HTMLUListElement>) => {
410
+ onKeyDown?.(e);
411
+ if (e.defaultPrevented) return;
412
+ const id = idOf(e.target);
413
+ const flat = id ? byId.get(id) : undefined;
414
+ if (!flat) return;
415
+ const { node } = flat;
416
+ const index = visible.findIndex((f) => f.node.id === node.id);
417
+ const expandedNow = expandedSet.has(node.id);
418
+ // Forward / backward along the reading direction, from the row itself.
419
+ const step = horizontalStep(e.key, e.target as Element);
420
+ // A space inside a type-ahead run is part of the name being typed ("current a…"),
421
+ // not a request to select.
422
+ const inRun = Date.now() - typeahead.current.at < TYPEAHEAD_MS && typeahead.current.text !== "";
423
+ const key = e.key === " " && inRun ? "typeahead" : e.key;
424
+
425
+ let handled = true;
426
+ if (step === 1) {
427
+ if (!isExpandable(node)) handled = false;
428
+ else if (!expandedNow) open(node);
429
+ else if (node.children?.length) focusRow(node.children[0].id);
430
+ } else if (step === -1) {
431
+ if (expandedNow) close(node);
432
+ else if (flat.parentId) focusRow(flat.parentId);
433
+ else handled = false;
434
+ } else {
435
+ switch (key) {
436
+ case "ArrowDown":
437
+ if (index < visible.length - 1) focusRow(visible[index + 1].node.id);
438
+ break;
439
+ case "ArrowUp":
440
+ if (index > 0) focusRow(visible[index - 1].node.id);
441
+ break;
442
+ case "Home":
443
+ if (visible.length) focusRow(visible[0].node.id);
444
+ break;
445
+ case "End":
446
+ if (visible.length) focusRow(visible[visible.length - 1].node.id);
447
+ break;
448
+ case "Enter":
449
+ case " ":
450
+ select(node);
451
+ break;
452
+ case "*": {
453
+ // Every sibling at this level, as the pattern suggests.
454
+ const siblings = flat.parentId ? (byId.get(flat.parentId)?.node.children ?? []) : items;
455
+ const next = new Set(expandedSet);
456
+ for (const s of siblings) if (isExpandable(s)) next.add(s.id);
457
+ setExpanded(next);
458
+ break;
459
+ }
460
+ default: {
461
+ const printable = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
462
+ if (!printable) {
463
+ handled = false;
464
+ break;
465
+ }
466
+ const now = Date.now();
467
+ const run = now - typeahead.current.at < TYPEAHEAD_MS ? typeahead.current.text : "";
468
+ typeahead.current = { text: run + e.key, at: now };
469
+ const typed = typeahead.current.text;
470
+ // "aaa" cycles through the rows starting with "a", as a file list does;
471
+ // anything else extends the prefix, searched from the row after this one
472
+ // (or from this one, when it still matches the longer prefix).
473
+ const repeated = typed.length > 1 && [...typed].every((c) => c === typed[0]);
474
+ const target = repeated
475
+ ? findByText(index, typed[0])
476
+ : typed.length > 1 && textOf(flat).trim().toLocaleLowerCase().startsWith(typed.toLocaleLowerCase())
477
+ ? node.id
478
+ : findByText(index, typed);
479
+ if (target) focusRow(target);
480
+ }
481
+ }
482
+ }
483
+ if (handled) {
484
+ e.preventDefault();
485
+ e.stopPropagation();
486
+ }
487
+ };
488
+
489
+ const handleClick = (e: MouseEvent<HTMLUListElement>) => {
490
+ onClick?.(e);
491
+ const id = idOf(e.target);
492
+ const flat = id ? byId.get(id) : undefined;
493
+ if (!flat) return;
494
+ // Controls a host rendered into a row (an action in `trailing`) are their own.
495
+ const control = (e.target as Element).closest("button, a[href], input, select, textarea");
496
+ if (control && itemRefs.current.get(flat.node.id)?.contains(control)) return;
497
+ setFocusedId(flat.node.id);
498
+ if ((e.target as Element).closest("[data-tree-toggle]")) {
499
+ toggle(flat.node);
500
+ return;
501
+ }
502
+ select(flat.node);
503
+ };
504
+
505
+ const renderNodes = (nodes: readonly TreeNode<T>[], level: number, path: string): ReactNode =>
506
+ nodes.map((node, i) => {
507
+ // Named by its own row, not by its content: a treeitem's content is the whole
508
+ // open branch below it, and "Assets Current assets 1020 Bank …" is not a name.
509
+ // A path of indices, because a host's id may hold spaces an idref cannot.
510
+ const rowId = `${baseId}-${path}${i}`;
511
+ const expandable = isExpandable(node);
512
+ const isOpen = expandable && expandedSet.has(node.id);
513
+ const isSelected = selectionMode !== "none" && selected === node.id;
514
+ const isLoading = loading.has(node.id);
515
+ const state: TreeItemState = {
516
+ level,
517
+ expanded: isOpen,
518
+ selected: isSelected,
519
+ expandable,
520
+ loading: isLoading,
521
+ disabled: Boolean(node.disabled),
522
+ };
523
+ return (
524
+ <li
525
+ key={node.id}
526
+ ref={(el) => {
527
+ if (el) itemRefs.current.set(node.id, el);
528
+ else itemRefs.current.delete(node.id);
529
+ }}
530
+ role="treeitem"
531
+ data-tree-id={node.id}
532
+ aria-labelledby={rowId}
533
+ aria-level={level}
534
+ aria-expanded={expandable ? isOpen : undefined}
535
+ aria-selected={selectionMode === "none" ? undefined : isSelected}
536
+ aria-disabled={node.disabled || undefined}
537
+ aria-busy={isLoading || undefined}
538
+ tabIndex={node.id === tabbable ? 0 : -1}
539
+ onFocus={(e) => {
540
+ // Only the row itself: a focus event bubbling up from a nested row, or from
541
+ // a control inside this one, is not this row being focused.
542
+ if (e.target === e.currentTarget) setFocusedId(node.id);
543
+ }}
544
+ // The ring goes on this row's own box, not the <li>: the <li> contains the
545
+ // whole open branch below it, and ringing that would outline a subtree.
546
+ className="outline-none [&:focus-visible>[data-tree-row]]:ring-2 [&:focus-visible>[data-tree-row]]:ring-[var(--brand)]"
547
+ >
548
+ <TreeRow
549
+ id={rowId}
550
+ level={level}
551
+ expanded={expandable ? isOpen : undefined}
552
+ label={node.label}
553
+ icon={node.icon}
554
+ trailing={node.trailing}
555
+ indent={indent}
556
+ guides={indentGuides}
557
+ selected={isSelected}
558
+ loading={isLoading}
559
+ className={cn(
560
+ node.disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer hover:bg-[var(--bg-hover)]",
561
+ rowClassName,
562
+ )}
563
+ >
564
+ {renderItem ? renderItem(node, state) : undefined}
565
+ </TreeRow>
566
+ {isOpen && (
567
+ <ul role="group">
568
+ {/* Empty while lazy children load: a "Loading…" line in here would be
569
+ a child that is not a treeitem, and the parent row already says
570
+ `aria-busy` and shows the spinner. */}
571
+ {node.children?.length ? renderNodes(node.children, level + 1, `${path}${i}-`) : null}
572
+ </ul>
573
+ )}
574
+ </li>
575
+ );
576
+ });
577
+
578
+ return (
579
+ <ul
580
+ {...rest}
581
+ role="tree"
582
+ onKeyDown={handleKeyDown}
583
+ onClick={handleClick}
584
+ className={cn("flex flex-col text-sm", className)}
585
+ >
586
+ {renderNodes(items, 1, "")}
587
+ </ul>
588
+ );
589
+ }
@@ -37,8 +37,13 @@ export interface TreemapNode {
37
37
  /** Overrides the by-index palette colour for this tile — e.g. to paint every child
38
38
  * in its parent group's colour, so the groups stay legible in one picture. A
39
39
  * concrete `#rrggbb` keeps the label ink measured; anything else (a CSS var) gets
40
- * `currentColor` ink, because there is nothing to measure. */
40
+ * `currentColor` ink, because there is nothing to measure — set `labelColor` then. */
41
41
  fill?: string;
42
+ /** The label's ink, for a `fill` the kit cannot measure (a `var()` or `color-mix()`):
43
+ * keksdose's recency plot fills with `color-mix(in srgb, var(--chart-1) N%,
44
+ * transparent)`, where `currentColor` put dark page text on full-strength indigo
45
+ * (~1.5:1). Wins over the measured ink when given. */
46
+ labelColor?: string;
42
47
  }
43
48
 
44
49
  /**
@@ -171,6 +176,8 @@ export interface TreemapCellProps {
171
176
  height?: number;
172
177
  name?: string;
173
178
  fill?: string;
179
+ /** See {@link TreemapNode.labelColor}; recharts hands each node's fields to its cell. */
180
+ labelColor?: string;
174
181
  id?: string;
175
182
  onNodeClick?: (id: string, name: string) => void;
176
183
  redactNames?: boolean;
@@ -200,6 +207,7 @@ export function TreemapCell({
200
207
  height = 0,
201
208
  name,
202
209
  fill,
210
+ labelColor,
203
211
  id,
204
212
  onNodeClick,
205
213
  redactNames,
@@ -215,7 +223,7 @@ export function TreemapCell({
215
223
  const pw = Math.round(width);
216
224
  const ph = Math.round(height);
217
225
  const tileFill = fill ?? "var(--chart-1)";
218
- const ink = textOn(tileFill);
226
+ const ink = labelColor ?? textOn(tileFill);
219
227
  // Below ~44x20 there is no room for a readable word, so no label at all rather than
220
228
  // a one-letter stub bleeding over the tile edge.
221
229
  const label = pw >= 44 && ph >= 20 ? fitLabel(name ?? "", pw, LABEL_FONT_SIZE) : null;