@eifi1/ui-kit 0.6.1 → 0.7.1

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 (271) hide show
  1. package/README.md +69 -33
  2. package/dist/chart.d.ts +1 -0
  3. package/dist/components/account-settings.js +3 -2
  4. package/dist/components/account-settings.js.map +1 -1
  5. package/dist/components/amount-input.d.ts +5 -0
  6. package/dist/components/amount-input.js +6 -4
  7. package/dist/components/amount-input.js.map +1 -1
  8. package/dist/components/autocomplete.d.ts +33 -6
  9. package/dist/components/autocomplete.js +62 -16
  10. package/dist/components/autocomplete.js.map +1 -1
  11. package/dist/components/calculator.d.ts +5 -0
  12. package/dist/components/calculator.js +2 -1
  13. package/dist/components/calculator.js.map +1 -1
  14. package/dist/components/chart-zoom.js +2 -1
  15. package/dist/components/chart-zoom.js.map +1 -1
  16. package/dist/components/chart.d.ts +33 -2
  17. package/dist/components/chart.js +20 -8
  18. package/dist/components/chart.js.map +1 -1
  19. package/dist/components/chip.d.ts +34 -14
  20. package/dist/components/chip.js +63 -28
  21. package/dist/components/chip.js.map +1 -1
  22. package/dist/components/choice-card.d.ts +18 -1
  23. package/dist/components/choice-card.js +21 -8
  24. package/dist/components/choice-card.js.map +1 -1
  25. package/dist/components/combobox-core.d.ts +61 -2
  26. package/dist/components/combobox-core.js +68 -17
  27. package/dist/components/combobox-core.js.map +1 -1
  28. package/dist/components/combobox.d.ts +11 -7
  29. package/dist/components/combobox.js +51 -28
  30. package/dist/components/combobox.js.map +1 -1
  31. package/dist/components/currency-select.js +3 -3
  32. package/dist/components/currency-select.js.map +1 -1
  33. package/dist/components/danger-confirm.d.ts +30 -6
  34. package/dist/components/danger-confirm.js +51 -32
  35. package/dist/components/danger-confirm.js.map +1 -1
  36. package/dist/components/data-table-filter-popover.d.ts +1 -1
  37. package/dist/components/data-table-filters.d.ts +1 -1
  38. package/dist/components/data-table-pagination.d.ts +6 -3
  39. package/dist/components/data-table-pagination.js +6 -5
  40. package/dist/components/data-table-pagination.js.map +1 -1
  41. package/dist/components/data-table.d.ts +1 -1
  42. package/dist/components/data-table.js +332 -248
  43. package/dist/components/data-table.js.map +1 -1
  44. package/dist/components/date-picker.js +17 -7
  45. package/dist/components/date-picker.js.map +1 -1
  46. package/dist/components/dialog-frame.d.ts +28 -3
  47. package/dist/components/dialog-frame.js +47 -11
  48. package/dist/components/dialog-frame.js.map +1 -1
  49. package/dist/components/disclosure.d.ts +22 -2
  50. package/dist/components/disclosure.js +41 -8
  51. package/dist/components/disclosure.js.map +1 -1
  52. package/dist/components/dropdown.d.ts +7 -3
  53. package/dist/components/dropdown.js +6 -2
  54. package/dist/components/dropdown.js.map +1 -1
  55. package/dist/components/entity-combobox.d.ts +17 -8
  56. package/dist/components/entity-combobox.js +7 -5
  57. package/dist/components/entity-combobox.js.map +1 -1
  58. package/dist/components/file-button.d.ts +38 -5
  59. package/dist/components/file-button.js +23 -2
  60. package/dist/components/file-button.js.map +1 -1
  61. package/dist/components/file-dropzone.d.ts +11 -5
  62. package/dist/components/file-dropzone.js +14 -19
  63. package/dist/components/file-dropzone.js.map +1 -1
  64. package/dist/components/grouped-picker.js +2 -2
  65. package/dist/components/grouped-picker.js.map +1 -1
  66. package/dist/components/hover-menu.d.ts +8 -3
  67. package/dist/components/hover-menu.js +88 -4
  68. package/dist/components/hover-menu.js.map +1 -1
  69. package/dist/components/icon-picker.d.ts +10 -1
  70. package/dist/components/icon-picker.js +5 -1
  71. package/dist/components/icon-picker.js.map +1 -1
  72. package/dist/components/measured-grid.d.ts +165 -0
  73. package/dist/components/measured-grid.js +559 -0
  74. package/dist/components/measured-grid.js.map +1 -0
  75. package/dist/components/mini-calendar.js +7 -8
  76. package/dist/components/mini-calendar.js.map +1 -1
  77. package/dist/components/month-picker.js +13 -9
  78. package/dist/components/month-picker.js.map +1 -1
  79. package/dist/components/multi-entity-combobox.js +2 -2
  80. package/dist/components/multi-entity-combobox.js.map +1 -1
  81. package/dist/components/multi-select.d.ts +9 -1
  82. package/dist/components/multi-select.js +22 -8
  83. package/dist/components/multi-select.js.map +1 -1
  84. package/dist/components/number-field.d.ts +5 -0
  85. package/dist/components/number-input.d.ts +5 -0
  86. package/dist/components/number-input.js +3 -3
  87. package/dist/components/number-input.js.map +1 -1
  88. package/dist/components/numpad-sheet.d.ts +5 -0
  89. package/dist/components/numpad-sheet.js +3 -3
  90. package/dist/components/numpad-sheet.js.map +1 -1
  91. package/dist/components/picker-sheet.js +1 -1
  92. package/dist/components/picker-sheet.js.map +1 -1
  93. package/dist/components/popover.js +11 -2
  94. package/dist/components/popover.js.map +1 -1
  95. package/dist/components/series-chart-ticks.d.ts +13 -0
  96. package/dist/components/series-chart-ticks.js +29 -0
  97. package/dist/components/series-chart-ticks.js.map +1 -0
  98. package/dist/components/series-chart.js +33 -27
  99. package/dist/components/series-chart.js.map +1 -1
  100. package/dist/components/settings-fields.d.ts +2 -0
  101. package/dist/components/swatch-picker.d.ts +10 -1
  102. package/dist/components/swatch-picker.js +2 -0
  103. package/dist/components/swatch-picker.js.map +1 -1
  104. package/dist/components/swipeable-row.d.ts +11 -2
  105. package/dist/components/swipeable-row.js +5 -3
  106. package/dist/components/swipeable-row.js.map +1 -1
  107. package/dist/components/tile-radio.js +5 -7
  108. package/dist/components/tile-radio.js.map +1 -1
  109. package/dist/components/time-input.d.ts +2 -0
  110. package/dist/components/toggle-group.d.ts +13 -3
  111. package/dist/components/toggle-group.js +21 -1
  112. package/dist/components/toggle-group.js.map +1 -1
  113. package/dist/components/toggle-legend.js +1 -2
  114. package/dist/components/toggle-legend.js.map +1 -1
  115. package/dist/components/tooltip.d.ts +10 -4
  116. package/dist/components/tooltip.js +23 -6
  117. package/dist/components/tooltip.js.map +1 -1
  118. package/dist/components/treemap.d.ts +6 -1
  119. package/dist/components/treemap.js +16 -6
  120. package/dist/components/treemap.js.map +1 -1
  121. package/dist/components/ui.d.ts +36 -8
  122. package/dist/components/ui.js +27 -19
  123. package/dist/components/ui.js.map +1 -1
  124. package/dist/components/use-anchor-dir.d.ts +15 -0
  125. package/dist/components/use-anchor-dir.js +14 -0
  126. package/dist/components/use-anchor-dir.js.map +1 -0
  127. package/dist/components/use-mobile-reveal.d.ts +8 -1
  128. package/dist/components/use-mobile-reveal.js +3 -2
  129. package/dist/components/use-mobile-reveal.js.map +1 -1
  130. package/dist/components/use-table-state.d.ts +4 -4
  131. package/dist/components/use-table-state.js +12 -5
  132. package/dist/components/use-table-state.js.map +1 -1
  133. package/dist/{data-table-filters-DM1auUfH.d.ts → data-table-filters-noy0Abvi.d.ts} +40 -7
  134. package/dist/data-table.d.ts +1 -1
  135. package/dist/data-table.js.map +1 -1
  136. package/dist/feedback/feedback-attachment.d.ts +22 -3
  137. package/dist/feedback/feedback-attachment.js +15 -7
  138. package/dist/feedback/feedback-attachment.js.map +1 -1
  139. package/dist/feedback/feedback-dialog.d.ts +3 -2
  140. package/dist/feedback/feedback-dialog.js.map +1 -1
  141. package/dist/feedback.d.ts +1 -1
  142. package/dist/hooks/use-windowed-rows.d.ts +29 -0
  143. package/dist/hooks/use-windowed-rows.js +31 -0
  144. package/dist/hooks/use-windowed-rows.js.map +1 -0
  145. package/dist/i18n/defaults.d.ts +5 -0
  146. package/dist/i18n/defaults.js +5 -1
  147. package/dist/i18n/defaults.js.map +1 -1
  148. package/dist/i18n/kit-labels.d.ts +7 -0
  149. package/dist/i18n/kit-labels.js.map +1 -1
  150. package/dist/i18n/locales/de-CH.d.ts +45 -0
  151. package/dist/i18n/locales/de-CH.js +21 -0
  152. package/dist/i18n/locales/de-CH.js.map +1 -0
  153. package/dist/i18n/locales/de.d.ts +45 -0
  154. package/dist/i18n/locales/de.js +344 -0
  155. package/dist/i18n/locales/de.js.map +1 -0
  156. package/dist/i18n/locales/es.d.ts +45 -0
  157. package/dist/i18n/locales/es.js +339 -0
  158. package/dist/i18n/locales/es.js.map +1 -0
  159. package/dist/i18n/locales/fr.d.ts +45 -0
  160. package/dist/i18n/locales/fr.js +344 -0
  161. package/dist/i18n/locales/fr.js.map +1 -0
  162. package/dist/i18n/locales/hu.d.ts +45 -0
  163. package/dist/i18n/locales/hu.js +343 -0
  164. package/dist/i18n/locales/hu.js.map +1 -0
  165. package/dist/i18n/locales/it.d.ts +45 -0
  166. package/dist/i18n/locales/it.js +342 -0
  167. package/dist/i18n/locales/it.js.map +1 -0
  168. package/dist/i18n/locales/zh.d.ts +45 -0
  169. package/dist/i18n/locales/zh.js +338 -0
  170. package/dist/i18n/locales/zh.js.map +1 -0
  171. package/dist/index.d.ts +7 -4
  172. package/dist/index.js +4 -1
  173. package/dist/index.js.map +1 -1
  174. package/dist/lib/direction.d.ts +24 -0
  175. package/dist/lib/direction.js +19 -0
  176. package/dist/lib/direction.js.map +1 -0
  177. package/dist/rhf/form.d.ts +2 -0
  178. package/dist/rhf/form.js.map +1 -1
  179. package/dist/rhf.d.ts +2 -0
  180. package/dist/search/command-palette.d.ts +5 -0
  181. package/dist/search/command-palette.js +80 -50
  182. package/dist/search/command-palette.js.map +1 -1
  183. package/dist/shell/app-shell.d.ts +13 -1
  184. package/dist/shell/app-shell.js +134 -85
  185. package/dist/shell/app-shell.js.map +1 -1
  186. package/dist/shell/topbar-action-menu.js +1 -1
  187. package/dist/shell/topbar-action-menu.js.map +1 -1
  188. package/dist/shell/topbar-controls.d.ts +7 -3
  189. package/dist/shell/topbar-controls.js +38 -31
  190. package/dist/shell/topbar-controls.js.map +1 -1
  191. package/dist/theme/chart-palette.d.ts +7 -1
  192. package/dist/theme/chart-palette.js +2 -1
  193. package/dist/theme/chart-palette.js.map +1 -1
  194. package/dist/tour/tour.d.ts +11 -5
  195. package/dist/tour/tour.js +124 -58
  196. package/dist/tour/tour.js.map +1 -1
  197. package/dist/wizard/use-wizard.js +30 -13
  198. package/dist/wizard/use-wizard.js.map +1 -1
  199. package/dist/wizard/wizard-summary.js +1 -1
  200. package/dist/wizard/wizard-summary.js.map +1 -1
  201. package/package.json +12 -2
  202. package/src/components/account-settings.tsx +6 -2
  203. package/src/components/amount-input.tsx +10 -8
  204. package/src/components/autocomplete.tsx +110 -24
  205. package/src/components/calculator.tsx +5 -1
  206. package/src/components/chart-zoom.tsx +8 -1
  207. package/src/components/chart.tsx +68 -7
  208. package/src/components/chip.tsx +131 -49
  209. package/src/components/choice-card.tsx +77 -36
  210. package/src/components/combobox-core.tsx +147 -20
  211. package/src/components/combobox.tsx +100 -44
  212. package/src/components/currency-select.tsx +6 -6
  213. package/src/components/danger-confirm.tsx +90 -36
  214. package/src/components/data-table-pagination.tsx +32 -19
  215. package/src/components/data-table.tsx +198 -36
  216. package/src/components/date-picker.tsx +24 -7
  217. package/src/components/dialog-frame.tsx +97 -22
  218. package/src/components/disclosure.tsx +75 -13
  219. package/src/components/dropdown.tsx +17 -5
  220. package/src/components/entity-combobox.tsx +26 -13
  221. package/src/components/file-button.tsx +74 -5
  222. package/src/components/file-dropzone.tsx +44 -35
  223. package/src/components/grouped-picker.tsx +2 -2
  224. package/src/components/hover-menu.tsx +139 -10
  225. package/src/components/icon-picker.tsx +14 -1
  226. package/src/components/measured-grid.tsx +852 -0
  227. package/src/components/mini-calendar.tsx +11 -8
  228. package/src/components/month-picker.tsx +18 -11
  229. package/src/components/multi-entity-combobox.tsx +2 -2
  230. package/src/components/multi-select.tsx +34 -7
  231. package/src/components/number-input.tsx +4 -4
  232. package/src/components/numpad-sheet.tsx +5 -3
  233. package/src/components/picker-sheet.tsx +1 -1
  234. package/src/components/popover.tsx +18 -3
  235. package/src/components/series-chart-ticks.ts +52 -0
  236. package/src/components/series-chart.tsx +39 -31
  237. package/src/components/swatch-picker.tsx +11 -0
  238. package/src/components/swipeable-row.tsx +21 -6
  239. package/src/components/tile-radio.tsx +5 -7
  240. package/src/components/toggle-group.tsx +39 -3
  241. package/src/components/toggle-legend.tsx +5 -2
  242. package/src/components/tooltip.tsx +40 -12
  243. package/src/components/treemap.tsx +28 -5
  244. package/src/components/ui.tsx +79 -33
  245. package/src/components/use-anchor-dir.ts +20 -0
  246. package/src/components/use-mobile-reveal.ts +10 -2
  247. package/src/components/use-table-state.ts +44 -7
  248. package/src/data-table.ts +1 -0
  249. package/src/feedback/feedback-attachment.tsx +36 -9
  250. package/src/feedback/feedback-dialog.tsx +3 -2
  251. package/src/hooks/use-windowed-rows.ts +69 -0
  252. package/src/i18n/defaults.ts +4 -0
  253. package/src/i18n/kit-labels.tsx +4 -0
  254. package/src/i18n/locales/de-CH.ts +30 -0
  255. package/src/i18n/locales/de.ts +365 -0
  256. package/src/i18n/locales/es.ts +358 -0
  257. package/src/i18n/locales/fr.ts +371 -0
  258. package/src/i18n/locales/hu.ts +359 -0
  259. package/src/i18n/locales/it.ts +360 -0
  260. package/src/i18n/locales/zh.ts +348 -0
  261. package/src/index.ts +10 -1
  262. package/src/lib/direction.ts +37 -0
  263. package/src/rhf/form.tsx +21 -0
  264. package/src/search/command-palette.tsx +77 -19
  265. package/src/shell/app-shell.tsx +201 -130
  266. package/src/shell/topbar-action-menu.tsx +1 -1
  267. package/src/shell/topbar-controls.tsx +19 -8
  268. package/src/theme/chart-palette.ts +9 -2
  269. package/src/tour/tour.tsx +119 -18
  270. package/src/wizard/use-wizard.ts +55 -17
  271. package/src/wizard/wizard-summary.tsx +1 -1
@@ -0,0 +1,852 @@
1
+ import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
2
+ import type { ComponentPropsWithoutRef, KeyboardEvent, ReactNode } from "react";
3
+ import { ClipboardPaste, Eraser, Plus, Trash2 } from "lucide-react";
4
+ import { cn } from "../lib/cn";
5
+ import { horizontalStep } from "../lib/direction";
6
+ // The cell pair reads ONE cell, where a comma has no columns to separate and so is
7
+ // always a decimal mark; `splitRow` and `parseRows` read a pasted table, where it may
8
+ // be either and the line decides. See the three named rules at the top of table-text.
9
+ import { cellNumber, isCellNumber, parseRows, splitRow } from "../lib/table-text";
10
+ import { useKitLabels, useKitLocale } from "../i18n/kit-labels";
11
+ import { useWindowedRows } from "../hooks/use-windowed-rows";
12
+ import { ToggleGroup } from "./toggle-group";
13
+ import { Button, FIELD_INVALID, Textarea } from "./ui";
14
+
15
+ /**
16
+ * A measured table: a fixed set of numeric columns, typed cell by cell or pasted as a
17
+ * block out of a spreadsheet — and the hook that holds it as a draft.
18
+ *
19
+ * Moved from Lenkbank (`shared/ui/measured-grid.tsx`), where four gear editors and a
20
+ * setpoint dialog type rig measurements into it. Nothing in it knows what a column
21
+ * holds: the caller passes `{ label, unit }[]`, and the vocabulary of this file is
22
+ * cells, rows, a caret and a paste. The lexing under it is `@eifi1/ui-kit/table-text`.
23
+ *
24
+ * What it is NOT: a `DataTable` mode (that one finds rows among many; this one types
25
+ * numbers into columns), a spreadsheet (no formulas, no multi-cell selection, no undo
26
+ * beyond the browser's per-input one), or typed columns — every cell is a string that
27
+ * should read as a number.
28
+ */
29
+
30
+ /**
31
+ * Every string the grid can speak — the `measuredGrid` namespace of
32
+ * `<UiKitProvider labels>`, overridable per instance through the `labels` prop. The
33
+ * ones that carry a number are functions of it, for the reason `DataTableLabels` gives:
34
+ * the grammar around a count moves with it in most languages.
35
+ */
36
+ export interface MeasuredGridLabels {
37
+ /** Accessible name of the cells/text toggle. */
38
+ view: string;
39
+ cellsView: string;
40
+ textView: string;
41
+ addRow: string;
42
+ /** The row's remove button, given its 1-based number. */
43
+ removeRow: (row: number) => string;
44
+ /** Empties the whole table. */
45
+ clear: string;
46
+ /** The footer's standing note that a block can be pasted into any cell. */
47
+ pasteHint: string;
48
+ /**
49
+ * Accessible name of one cell's input, given its column's label and 1-based row.
50
+ * A screen reader in a grid announces the headers on its own when the caret crosses
51
+ * one; this is what it reads when the caret lands on an input with no crossing — and
52
+ * what a voice-control user says to reach it.
53
+ */
54
+ cell: (column: string, row: number) => string;
55
+ /** The row-number column's header, which shows only "#". */
56
+ rowNumber: string;
57
+ /** The remove-button column's header, which shows nothing. */
58
+ rowActions: string;
59
+ /** The grid's description: how its keyboard works. Read once, on entry. */
60
+ keyboardHint: string;
61
+ /** The text view could not read this 1-based line of what was typed or pasted. */
62
+ lineError: (line: number) => string;
63
+ /** How many filled rows (measured points) the table holds. */
64
+ points: (count: number) => string;
65
+ /** How many cells are typed but are not numbers. */
66
+ problems: (count: number) => string;
67
+ }
68
+
69
+ /** English defaults. Exported as the `measuredGrid` namespace of `UiKitLabels`
70
+ * (src/i18n), the complete reference a translation is written against. */
71
+ export const DEFAULT_MEASURED_GRID_LABELS: MeasuredGridLabels = {
72
+ view: "Table view",
73
+ cellsView: "Cells",
74
+ textView: "Text",
75
+ addRow: "Add row",
76
+ removeRow: (row) => `Remove row ${row}`,
77
+ clear: "Clear table",
78
+ pasteHint: "Paste a block from a spreadsheet into any cell",
79
+ cell: (column, row) => `${column}, row ${row}`,
80
+ rowNumber: "Row",
81
+ rowActions: "Row actions",
82
+ keyboardHint:
83
+ "Arrow keys move between cells. Type to replace a cell, F2 to edit it, Escape to undo the edit. Enter moves down and adds a row at the end.",
84
+ lineError: (line) => `Line ${line} could not be read`,
85
+ points: (count) => (count === 1 ? "1 point" : `${count} points`),
86
+ problems: (count) => (count === 1 ? "1 cell is not a number" : `${count} cells are not numbers`),
87
+ };
88
+
89
+ /** One column of a measured table: what it holds and what it is measured in. The unit
90
+ * is separate from the name because the header shows it small and underneath, and
91
+ * because a column with no unit (a count, an index) should not render empty brackets. */
92
+ export interface MeasuredGridColumn {
93
+ label: string;
94
+ unit?: string;
95
+ }
96
+
97
+ /** The two ways to look at the same table. */
98
+ export type MeasuredGridView = "cells" | "text";
99
+
100
+ /** A cell that has not been typed into yet. Distinguished from `"0"` on purpose: an
101
+ * empty cell is a hole in the measurement, and a table with a hole is not one to save. */
102
+ const BLANK = "";
103
+
104
+ /** Height of one grid row, in pixels. Fixed, which is what lets the windowing be
105
+ * arithmetic rather than measurement. */
106
+ const DEFAULT_ROW_HEIGHT = 28;
107
+
108
+ const ALL_VIEWS: readonly MeasuredGridView[] = ["cells", "text"];
109
+
110
+ /** The locale's decimal mark, as far as a cell can hold it: "," or ".". A mark outside
111
+ * those two (Arabic's "٫") is not one `cellNumber` reads, so those locales keep the
112
+ * dot. The same answer `NumberField` gives, for the same reason. */
113
+ function decimalMark(locale: string | undefined): "," | "." {
114
+ try {
115
+ const part = new Intl.NumberFormat(locale).formatToParts(1.5).find((p) => p.type === "decimal");
116
+ return part?.value === "," ? "," : ".";
117
+ } catch {
118
+ // An invalid tag throws a RangeError; a typo in a locale must not take the grid down.
119
+ return ".";
120
+ }
121
+ }
122
+
123
+ /** A number-shaped cell written with the locale's mark. The lexer hands back points;
124
+ * a German user typed commas and should read commas back. Anything that is not a
125
+ * number is left exactly as it was, so the mistake stays visible where it was made. */
126
+ const withMark = (cell: string, mark: "," | ".") =>
127
+ mark === "," && isCellNumber(cell) ? cell.replace(".", ",") : cell;
128
+
129
+ /** A computed number as a draft cell: rounded to `digits`, with no trailing zeros. */
130
+ const formatCell = (value: number, digits: number, mark: "," | ".") =>
131
+ withMark(String(Number(value.toFixed(digits))), mark);
132
+
133
+ const hasContent = (row: readonly string[]) => row.some((cell) => cell.trim() !== "");
134
+
135
+ export interface UseMeasuredRowsOptions {
136
+ /** Decimals a computed number is rounded to on its way into a cell. Default 4. */
137
+ digits?: number;
138
+ /** BCP 47 tag whose decimal mark the cells are written with, else the
139
+ * `<UiKitProvider locale>`, else the runtime's. */
140
+ locale?: string;
141
+ }
142
+
143
+ export interface MeasuredRows {
144
+ /** The draft, as text — what the grid shows and edits. */
145
+ cells: string[][];
146
+ setCells: (next: string[][]) => void;
147
+ /** The filled rows as numbers — EMPTY until the table is `ready`. */
148
+ rows: number[][];
149
+ /** Replace the whole table with computed numbers (a generated shape, say). */
150
+ setRows: (next: number[][]) => void;
151
+ /** At least two filled rows, and every cell in them is a number. */
152
+ ready: boolean;
153
+ /** How many cells are typed but are not numbers — what the grid marks invalid. */
154
+ problems: number;
155
+ /** Everything `MeasuredGrid` needs, so a caller spreads it in one line. */
156
+ props: { cells: string[][]; onCells: (next: string[][]) => void };
157
+ }
158
+
159
+ /**
160
+ * The draft a measured table is edited as.
161
+ *
162
+ * **Strings, not numbers.** A cell is text while it is being typed — `"-"`, `"1."` and
163
+ * `"1e"` are all states a number passes through on its way to being one, and a grid
164
+ * that parses on every keystroke turns each of them into a `NaN` and then into a `0`.
165
+ * So the draft is text, and the numbers are what falls out when every cell is one.
166
+ *
167
+ * **"Whole" is a question this answers**, because every editor asks it before it
168
+ * offers to save: `ready` wants at least two filled rows with a number in every cell.
169
+ * An empty cell is a hole in the measurement, not a zero; a wholly empty row is not a
170
+ * row at all (it is what walking off the bottom of the grid leaves behind).
171
+ *
172
+ * `initial` is read once, like `useState`'s.
173
+ */
174
+ export function useMeasuredRows(
175
+ initial: number[][] | (() => number[][]),
176
+ options: UseMeasuredRowsOptions = {},
177
+ ): MeasuredRows {
178
+ const { digits = 4 } = options;
179
+ const mark = decimalMark(useKitLocale(options.locale));
180
+ const [cells, setCells] = useState<string[][]>(() =>
181
+ (typeof initial === "function" ? initial() : initial).map((row) =>
182
+ row.map((value) => formatCell(value, digits, mark)),
183
+ ),
184
+ );
185
+
186
+ const { rows, ready, problems } = useMemo(() => {
187
+ const filled = cells.filter(hasContent);
188
+ const whole = filled.length >= 2 && filled.every((row) => row.every(isCellNumber));
189
+ return {
190
+ rows: whole ? filled.map((row) => row.map(cellNumber)) : [],
191
+ ready: whole,
192
+ problems: filled.flat().filter((cell) => cell.trim() !== "" && !isCellNumber(cell)).length,
193
+ };
194
+ }, [cells]);
195
+
196
+ const setRows = useCallback(
197
+ (next: number[][]) => setCells(next.map((row) => row.map((value) => formatCell(value, digits, mark)))),
198
+ [digits, mark],
199
+ );
200
+ const props = useMemo(() => ({ cells, onCells: setCells }), [cells]);
201
+
202
+ return { cells, setCells, rows, setRows, ready, problems, props };
203
+ }
204
+
205
+ export interface MeasuredGridProps
206
+ extends Omit<ComponentPropsWithoutRef<"div">, "children" | "onChange"> {
207
+ /** What the table is — shown above it, and the grid's accessible name. */
208
+ label: string;
209
+ /** A note under the table (which columns a layout expects, say). Also the grid's
210
+ * description. */
211
+ hint?: ReactNode;
212
+ columns: MeasuredGridColumn[];
213
+ /** The draft — typically `useMeasuredRows().props`. */
214
+ cells: string[][];
215
+ onCells: (next: string[][]) => void;
216
+ /** Read-only: the cells can still be walked and read, nothing can be changed. */
217
+ disabled?: boolean;
218
+ /** Which views the toggle offers, the first being where it opens. Default both;
219
+ * one view hides the toggle. */
220
+ views?: ReadonlyArray<MeasuredGridView>;
221
+ /** Row height in pixels, for the windowing. Fixed on purpose. Default 28. */
222
+ rowHeight?: number;
223
+ /** BCP 47 tag for the decimal mark of cells written by a paste or the text view,
224
+ * and for the row numbers; else the `<UiKitProvider locale>`. */
225
+ locale?: string;
226
+ labels?: Partial<MeasuredGridLabels>;
227
+ }
228
+
229
+ /**
230
+ * A measured table as a grid of cells, one number each, with a text view beside it.
231
+ *
232
+ * The grid is the primary form because a linkage typed off a drawing arrives as
233
+ * numbers somebody reads out loud, and a textarea made that an exercise in counting
234
+ * tab characters. The paste still works: a block pasted into any cell fills from that
235
+ * cell outwards, growing the table to fit. The text view is kept for what a grid is
236
+ * worst at — reading a thousand-row export back in one piece.
237
+ *
238
+ * **It is a grid in the APG sense**, which the Lenkbank original was not (a `<table>`
239
+ * of inputs, fifteen tab stops per row). One tab stop — the roving tabindex — and the
240
+ * keyboard inside it, as a spreadsheet has it:
241
+ *
242
+ * - **Arrows** move between cells. Left/Right flip under `dir="rtl"`.
243
+ * - **Home/End** go to the first/last column; with Ctrl (or ⌘), to the first/last
244
+ * cell of the table. **PageUp/PageDown** move a screenful.
245
+ * - **Enter** (and ArrowDown) move down a column, and past the last row ADD one —
246
+ * typing down a column is how measured data is entered, and stopping at the last
247
+ * row to reach for a button is what makes people paste instead. Shift+Enter moves up.
248
+ * - **Typing** replaces the cell: arriving by keyboard selects its text, so the first
249
+ * key overwrites it. That is the edit mode data entry wants, entered without a key.
250
+ * **F2** edits in place instead (caret at the end). Either way the cell is then
251
+ * *editing*: Left/Right move the caret, and cross to the next cell only at the edge
252
+ * of the text; Home/End stay in the text. **Escape** puts back what the cell held
253
+ * when the caret arrived, and leaves editing.
254
+ *
255
+ * APG's grid pattern pairs Enter with F2 as the keys that start editing. Enter is
256
+ * spent on "next row" here on purpose — it is the one key a person typing a column of
257
+ * numbers presses between every one of them, and every spreadsheet spends it the same
258
+ * way — and typing-to-replace makes an explicit "start editing" key unnecessary for
259
+ * the common case. F2 remains for the uncommon one.
260
+ */
261
+ export function MeasuredGrid({
262
+ label,
263
+ hint,
264
+ columns,
265
+ cells,
266
+ onCells,
267
+ disabled,
268
+ views = ALL_VIEWS,
269
+ rowHeight = DEFAULT_ROW_HEIGHT,
270
+ locale: localeProp,
271
+ labels: labelsProp,
272
+ className,
273
+ ...rest
274
+ }: MeasuredGridProps) {
275
+ const labels = useKitLabels("measuredGrid", DEFAULT_MEASURED_GRID_LABELS, labelsProp);
276
+ const locale = useKitLocale(localeProp);
277
+ const mark = decimalMark(locale);
278
+ const id = useId();
279
+ const labelId = `${id}-label`;
280
+ const hintId = `${id}-hint`;
281
+ const keysId = `${id}-keys`;
282
+ const offered = views.length ? views : ALL_VIEWS;
283
+ const [chosen, setChosen] = useState<MeasuredGridView>(offered[0]);
284
+ const view = offered.includes(chosen) ? chosen : offered[0];
285
+
286
+ return (
287
+ // `relative` so the keyboard description below can be `sr-only` without escaping
288
+ // to the initial containing block (see sr-only-containment.test).
289
+ <div {...rest} className={cn("relative", className)}>
290
+ <div className="mb-1 flex flex-wrap items-center justify-between gap-2">
291
+ <span id={labelId} className="text-[11px] font-medium text-[var(--text-muted)]">
292
+ {label}
293
+ </span>
294
+ {offered.length > 1 && (
295
+ <ToggleGroup
296
+ className="w-auto"
297
+ aria-label={labels.view}
298
+ value={view}
299
+ onChange={setChosen}
300
+ options={offered.map((value) => ({
301
+ value,
302
+ label: value === "cells" ? labels.cellsView : labels.textView,
303
+ }))}
304
+ />
305
+ )}
306
+ </div>
307
+ {view === "cells" ? (
308
+ <CellGrid
309
+ columns={columns}
310
+ cells={cells}
311
+ onCells={onCells}
312
+ disabled={disabled}
313
+ rowHeight={rowHeight}
314
+ locale={locale}
315
+ mark={mark}
316
+ labels={labels}
317
+ labelledBy={labelId}
318
+ describedBy={hint ? `${keysId} ${hintId}` : keysId}
319
+ />
320
+ ) : (
321
+ <TextView
322
+ columns={columns}
323
+ cells={cells}
324
+ onCells={onCells}
325
+ disabled={disabled}
326
+ mark={mark}
327
+ labels={labels}
328
+ labelledBy={labelId}
329
+ describedBy={hint ? hintId : undefined}
330
+ />
331
+ )}
332
+ {hint && (
333
+ <p id={hintId} className="mt-1 px-1 text-[11px] text-[var(--text-muted)]">
334
+ {hint}
335
+ </p>
336
+ )}
337
+ {view === "cells" && (
338
+ <span id={keysId} className="sr-only">
339
+ {labels.keyboardHint}
340
+ </span>
341
+ )}
342
+ </div>
343
+ );
344
+ }
345
+
346
+ /** Where the caret is. Held in state rather than read off `document`, because a
347
+ * windowed grid unmounts the cell being walked towards: the move is decided first and
348
+ * focused after the row it lands on has been rendered. */
349
+ interface Caret {
350
+ row: number;
351
+ column: number;
352
+ }
353
+
354
+ interface ViewProps {
355
+ columns: MeasuredGridColumn[];
356
+ cells: string[][];
357
+ onCells: (next: string[][]) => void;
358
+ disabled?: boolean;
359
+ mark: "," | ".";
360
+ labels: MeasuredGridLabels;
361
+ labelledBy: string;
362
+ describedBy?: string;
363
+ }
364
+
365
+ function CellGrid({
366
+ columns,
367
+ cells,
368
+ onCells,
369
+ disabled,
370
+ rowHeight,
371
+ locale,
372
+ mark,
373
+ labels,
374
+ labelledBy,
375
+ describedBy,
376
+ }: ViewProps & { rowHeight: number; locale: string | undefined }) {
377
+ const scrollRef = useRef<HTMLDivElement>(null);
378
+ const headRef = useRef<HTMLDivElement>(null);
379
+ const width = columns.length;
380
+ const blankRow = () => columns.map(() => BLANK);
381
+ // At least one row to type into: a grid with nothing in it has nowhere to put the
382
+ // first number, and "add a row" is not the first thing to ask of someone who has
383
+ // just opened an empty table. It is not written back until something is typed.
384
+ const grid = cells.length ? cells : [blankRow()];
385
+ const { first, last, totalHeight } = useWindowedRows(grid.length, rowHeight, scrollRef);
386
+ const rowNumber = useMemo(() => new Intl.NumberFormat(locale), [locale]);
387
+
388
+ // The remove buttons are the last column of the grid, reachable by the arrows like
389
+ // any cell — except where they are disabled (a read-only grid, or the placeholder
390
+ // row of an empty one), because a disabled button cannot hold the tab stop.
391
+ const removable = !disabled && cells.length > 0;
392
+ const lastColumn = removable ? width : width - 1;
393
+
394
+ const [caret, setCaret] = useState<Caret>({ row: 0, column: 0 });
395
+ // Clamped on read, not corrected in an effect: rows removed or columns changed from
396
+ // outside must never leave the tab stop on a cell that is not there.
397
+ const at = { row: Math.min(caret.row, grid.length - 1), column: Math.min(caret.column, lastColumn) };
398
+ /** Whether the caret cell is being edited in place (see the component note). */
399
+ const [editing, setEditing] = useState(false);
400
+ /** A cell that has to take focus once it exists — one commit away when the move
401
+ * crossed the edge of the window. `select` is arrival by keyboard. */
402
+ const pending = useRef<(Caret & { select: boolean }) | null>(null);
403
+ /** What the caret cell held when the caret arrived: what Escape puts back. */
404
+ const origin = useRef(BLANK);
405
+ /** The next focus was a pointer's: place the caret where it was clicked, edit. */
406
+ const pointer = useRef(false);
407
+
408
+ useEffect(() => {
409
+ const target = pending.current;
410
+ if (!target) return;
411
+ const element = scrollRef.current?.querySelector<HTMLElement>(
412
+ `[data-cell="${target.row}:${target.column}"]`,
413
+ );
414
+ if (!element) return;
415
+ pending.current = null;
416
+ // `preventScroll`: `reveal` already scrolled the row clear of the sticky header,
417
+ // which the browser's own scroll-into-view does not know is there.
418
+ element.focus({ preventScroll: true });
419
+ if (target.select && element instanceof HTMLInputElement) element.select();
420
+ });
421
+
422
+ const pad = (row: readonly string[] | undefined) =>
423
+ Array.from({ length: width }, (_, index) => row?.[index] ?? BLANK);
424
+
425
+ const setCell = (row: number, column: number, value: string) => {
426
+ const next = grid.map(pad);
427
+ next[row][column] = value;
428
+ onCells(next);
429
+ };
430
+
431
+ /** Scroll `row` into the band below the sticky header. */
432
+ const reveal = (row: number) => {
433
+ const element = scrollRef.current;
434
+ if (!element) return;
435
+ const room = element.clientHeight - (headRef.current?.offsetHeight ?? 0);
436
+ if (room <= 0) return;
437
+ const top = row * rowHeight;
438
+ if (top < element.scrollTop) element.scrollTop = top;
439
+ else if (top + rowHeight > element.scrollTop + room) element.scrollTop = top + rowHeight - room;
440
+ };
441
+
442
+ const focusCell = (row: number, column: number) => {
443
+ reveal(row);
444
+ pending.current = { row, column, select: true };
445
+ setCaret({ row, column });
446
+ setEditing(false);
447
+ };
448
+
449
+ const go = (row: number, column: number) => {
450
+ const target = {
451
+ row: Math.max(0, Math.min(row, grid.length - 1)),
452
+ column: Math.max(0, Math.min(column, lastColumn)),
453
+ };
454
+ if (target.row === at.row && target.column === at.column) return;
455
+ focusCell(target.row, target.column);
456
+ };
457
+
458
+ /** Down a column — and off the bottom, a new row, unless the last one is still
459
+ * empty: holding ArrowDown should not leave a trail of blank rows behind it. */
460
+ const down = (row: number, column: number) => {
461
+ if (row + 1 < grid.length) return go(row + 1, column);
462
+ if (disabled || !hasContent(grid[row])) return;
463
+ onCells([...grid.map(pad), blankRow()]);
464
+ focusCell(row + 1, Math.min(column, width - 1));
465
+ };
466
+
467
+ const page = () => {
468
+ const element = scrollRef.current;
469
+ const room = element ? element.clientHeight - (headRef.current?.offsetHeight ?? 0) : 0;
470
+ // No layout (a hidden pane, jsdom): a fixed ten rather than one row at a time.
471
+ return room > 0 ? Math.max(1, Math.floor(room / rowHeight) - 1) : 10;
472
+ };
473
+
474
+ /**
475
+ * On each cell rather than once on the grid, for the reason `MiniCalendar` gives:
476
+ * the cell is where focus is, and a container listening for keys it cannot receive
477
+ * is the shape `jsx-a11y/interactive-supports-focus` objects to.
478
+ */
479
+ const onCellKeyDown = (event: KeyboardEvent<HTMLElement>, row: number, column: number) => {
480
+ const input = event.currentTarget instanceof HTMLInputElement ? event.currentTarget : null;
481
+ const inText = Boolean(input) && editing;
482
+ const modified = event.ctrlKey || event.metaKey;
483
+ switch (event.key) {
484
+ case "ArrowUp":
485
+ event.preventDefault();
486
+ return go(row - 1, column);
487
+ case "ArrowDown":
488
+ event.preventDefault();
489
+ return down(row, column);
490
+ case "Enter":
491
+ // On the remove button Enter is the button's own.
492
+ if (!input) return;
493
+ event.preventDefault();
494
+ return event.shiftKey ? go(row - 1, column) : down(row, column);
495
+ case "ArrowLeft":
496
+ case "ArrowRight": {
497
+ // Along the reading direction: ArrowLeft is "next column" in RTL.
498
+ const forward = horizontalStep(event.key, event.currentTarget) === 1;
499
+ if (inText && input) {
500
+ const edge = forward ? input.value.length : 0;
501
+ // Inside the text the caret moves; only at its edge does it leave the cell.
502
+ if (input.selectionStart !== edge || input.selectionEnd !== edge) return;
503
+ }
504
+ event.preventDefault();
505
+ return go(row, column + (forward ? 1 : -1));
506
+ }
507
+ case "Home":
508
+ case "End": {
509
+ if (inText && !modified) return;
510
+ event.preventDefault();
511
+ const home = event.key === "Home";
512
+ if (modified) return go(home ? 0 : grid.length - 1, home ? 0 : width - 1);
513
+ return go(row, home ? 0 : width - 1);
514
+ }
515
+ case "PageUp":
516
+ event.preventDefault();
517
+ return go(row - page(), column);
518
+ case "PageDown":
519
+ event.preventDefault();
520
+ return go(row + page(), column);
521
+ case "F2":
522
+ if (!input || disabled) return;
523
+ event.preventDefault();
524
+ setEditing(true);
525
+ input.setSelectionRange(input.value.length, input.value.length);
526
+ return;
527
+ case "Escape":
528
+ // Not editing: nothing of ours to undo, so the key belongs to whatever the
529
+ // grid sits in — the dialog it is in closes, as it should.
530
+ if (!input || !editing) return;
531
+ event.preventDefault();
532
+ event.stopPropagation();
533
+ if (input.value !== origin.current) setCell(row, column, origin.current);
534
+ pending.current = { row, column, select: true };
535
+ setEditing(false);
536
+ return;
537
+ }
538
+ };
539
+
540
+ /**
541
+ * A pasted block, written in from the cell it was pasted into.
542
+ *
543
+ * Rows past the end grow the table; columns past the last are dropped, because a
544
+ * paste wider than the measurement is a paste with a trailing timestamp column and
545
+ * not an error worth refusing. One header line is skipped — pasted data almost
546
+ * always has one. Each line is read on its own evidence (`splitRow`, the per-line
547
+ * comma rule), so one line cannot change what another means.
548
+ */
549
+ const paste = (row: number, column: number, text: string) => {
550
+ const lines = text.split(/\r?\n/).filter((line) => line.trim() !== "");
551
+ if (!lines.length) return;
552
+ const block = lines.map(splitRow);
553
+ if (block.length > 1 && block[0].some((cell) => !isCellNumber(cell))) block.shift();
554
+
555
+ const height = Math.max(grid.length, row + block.length);
556
+ const next = Array.from({ length: height }, (_, index) => pad(grid[index]));
557
+ block.forEach((line, downwards) => {
558
+ line.forEach((cell, across) => {
559
+ const target = column + across;
560
+ if (target < width) next[row + downwards][target] = withMark(cell.trim(), mark);
561
+ });
562
+ });
563
+ onCells(next);
564
+ pending.current = { row, column, select: true };
565
+ setEditing(false);
566
+ };
567
+
568
+ const template = `2.5rem repeat(${width}, minmax(5.5rem, 1fr)) 2rem`;
569
+ // The caret's row is mounted even when it has been scrolled out of the window: it
570
+ // holds the grid's only tab stop, and a tab stop that is not in the DOM is a grid
571
+ // Tab walks straight past.
572
+ const mounted: number[] = [];
573
+ for (let index = first; index < last; index += 1) mounted.push(index);
574
+ if (at.row < first || at.row >= last) mounted.push(at.row);
575
+
576
+ const filled = cells.filter(hasContent);
577
+ const problems = filled.flat().filter((cell) => cell.trim() !== "" && !isCellNumber(cell)).length;
578
+
579
+ return (
580
+ <div className="rounded-md border border-[var(--border)] bg-[var(--bg-surface)]">
581
+ <div ref={scrollRef} className="max-h-72 overflow-auto">
582
+ <div
583
+ role="grid"
584
+ aria-labelledby={labelledBy}
585
+ aria-describedby={describedBy}
586
+ // The true size, not the mounted one: a screen reader otherwise reports the
587
+ // thirty rows in the window as the whole table.
588
+ aria-rowcount={grid.length + 1}
589
+ aria-colcount={width + 2}
590
+ aria-readonly={disabled || undefined}
591
+ className="text-xs"
592
+ style={{ minWidth: `calc(4.5rem + ${width} * 5.5rem)` }}
593
+ >
594
+ {/* The header stays put vertically and scrolls sideways with the body, so a
595
+ fifteen-column linkage can be read without losing which column is which. */}
596
+ <div ref={headRef} role="rowgroup" className="sticky top-0 z-10 bg-[var(--bg-surface-2)]">
597
+ <div
598
+ role="row"
599
+ aria-rowindex={1}
600
+ className="grid border-b border-[var(--border)]"
601
+ style={{ gridTemplateColumns: template }}
602
+ >
603
+ <div
604
+ role="columnheader"
605
+ aria-label={labels.rowNumber}
606
+ className="flex items-end justify-end px-1 py-1 text-[10px] text-[var(--text-placeholder)]"
607
+ >
608
+ #
609
+ </div>
610
+ {columns.map((column, index) => (
611
+ <div
612
+ key={index}
613
+ role="columnheader"
614
+ className="min-w-0 border-s border-[var(--border)] px-2 py-1 text-end"
615
+ >
616
+ <span className="block truncate font-medium text-[var(--text-primary)]">
617
+ {column.label}
618
+ </span>
619
+ {column.unit && (
620
+ <span className="block truncate text-[10px] text-[var(--text-muted)]">
621
+ {column.unit}
622
+ </span>
623
+ )}
624
+ </div>
625
+ ))}
626
+ <div
627
+ role="columnheader"
628
+ aria-label={labels.rowActions}
629
+ className="border-s border-[var(--border)]"
630
+ />
631
+ </div>
632
+ </div>
633
+ {/* Only the rows in the window are mounted — a swept linkage is thousands of
634
+ them across fifteen inputs — each placed at its own offset, so mounting
635
+ one more (the caret's) costs nothing in the arithmetic. */}
636
+ <div role="rowgroup" className="relative" style={{ height: totalHeight }}>
637
+ {mounted.map((index) => {
638
+ const row = grid[index];
639
+ return (
640
+ <div
641
+ key={index}
642
+ role="row"
643
+ aria-rowindex={index + 2}
644
+ className="absolute inset-x-0 grid hover:bg-[var(--bg-hover)]"
645
+ style={{ top: index * rowHeight, height: rowHeight, gridTemplateColumns: template }}
646
+ >
647
+ <div
648
+ role="rowheader"
649
+ className="flex items-center justify-end px-1 text-[10px] tabular-nums text-[var(--text-placeholder)]"
650
+ >
651
+ {rowNumber.format(index + 1)}
652
+ </div>
653
+ {columns.map((column, columnIndex) => {
654
+ const value = row[columnIndex] ?? BLANK;
655
+ const bad = value.trim() !== "" && !isCellNumber(value);
656
+ const isCaret = at.row === index && at.column === columnIndex;
657
+ return (
658
+ <div key={columnIndex} role="gridcell" className="min-w-0 border-s border-[var(--border)]">
659
+ <input
660
+ data-cell={`${index}:${columnIndex}`}
661
+ value={value}
662
+ // `readOnly`, not `disabled`: a disabled input cannot take
663
+ // focus, and a read-only table should still be walkable.
664
+ readOnly={disabled}
665
+ tabIndex={isCaret ? 0 : -1}
666
+ inputMode="decimal"
667
+ spellCheck={false}
668
+ autoComplete="off"
669
+ aria-label={labels.cell(column.label, index + 1)}
670
+ // Said, not only painted: the ring is what a sighted user
671
+ // sees, `aria-invalid` is what a screen reader reads.
672
+ aria-invalid={bad || undefined}
673
+ className={cn(
674
+ "block size-full bg-transparent px-2 text-end tabular-nums text-[var(--text-primary)] outline-none",
675
+ // Arriving selects the text (typing replaces it); editing
676
+ // in place is the plain surface with a caret in it.
677
+ "focus:bg-[var(--brand-bg)] focus:ring-2 focus:ring-inset focus:ring-[var(--brand)]",
678
+ isCaret && editing && "focus:bg-[var(--bg-surface)]",
679
+ disabled && "text-[var(--text-muted)]",
680
+ bad && cn(FIELD_INVALID, "ring-inset"),
681
+ )}
682
+ onMouseDown={(event) => {
683
+ // A click places a caret, which is editing. On the cell
684
+ // already focused there is no focus event to say so.
685
+ if (document.activeElement === event.currentTarget) setEditing(!disabled);
686
+ else pointer.current = true;
687
+ }}
688
+ onFocus={(event) => {
689
+ origin.current = event.currentTarget.value;
690
+ if (!isCaret) setCaret({ row: index, column: columnIndex });
691
+ const byPointer = pointer.current;
692
+ pointer.current = false;
693
+ setEditing(byPointer && !disabled);
694
+ if (!byPointer) event.currentTarget.select();
695
+ }}
696
+ onBlur={() => setEditing(false)}
697
+ onChange={(event) => {
698
+ setCell(index, columnIndex, event.target.value);
699
+ setEditing(true);
700
+ }}
701
+ onPaste={(event) => {
702
+ if (disabled) return;
703
+ const text = event.clipboardData.getData("text/plain");
704
+ // One cell's worth of text is an ordinary paste, and the
705
+ // browser does it better than this would; only a block is
706
+ // the grid's business.
707
+ if (!/[\t\n;]/.test(text)) return;
708
+ event.preventDefault();
709
+ paste(index, columnIndex, text);
710
+ }}
711
+ onKeyDown={(event) => onCellKeyDown(event, index, columnIndex)}
712
+ />
713
+ </div>
714
+ );
715
+ })}
716
+ <div
717
+ role="gridcell"
718
+ className="flex items-center justify-center border-s border-[var(--border)]"
719
+ >
720
+ <button
721
+ type="button"
722
+ data-cell={`${index}:${width}`}
723
+ disabled={!removable}
724
+ tabIndex={at.row === index && at.column === width ? 0 : -1}
725
+ aria-label={labels.removeRow(index + 1)}
726
+ className="rounded p-1 text-[var(--text-placeholder)] outline-none hover:text-[var(--danger)] focus-visible:ring-2 focus-visible:ring-[var(--brand)] disabled:cursor-default disabled:hover:text-[var(--text-placeholder)]"
727
+ onKeyDown={(event) => onCellKeyDown(event, index, width)}
728
+ onFocus={() => {
729
+ if (at.row !== index || at.column !== width) setCaret({ row: index, column: width });
730
+ }}
731
+ onClick={() => {
732
+ const next = grid.filter((_, other) => other !== index);
733
+ onCells(next);
734
+ // Focus stays in the column, on the row that moved up into
735
+ // this one; an emptied table sends it to the first cell.
736
+ if (next.length) focusCell(Math.min(index, next.length - 1), width);
737
+ else focusCell(0, 0);
738
+ }}
739
+ >
740
+ <Trash2 aria-hidden className="size-3.5" />
741
+ </button>
742
+ </div>
743
+ </div>
744
+ );
745
+ })}
746
+ </div>
747
+ </div>
748
+ </div>
749
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-[var(--border)] px-2 py-1.5">
750
+ <Button
751
+ variant="ghost"
752
+ className="px-2 py-1 text-xs"
753
+ disabled={disabled}
754
+ onClick={() => {
755
+ onCells([...grid.map(pad), blankRow()]);
756
+ focusCell(grid.length, 0);
757
+ }}
758
+ >
759
+ <Plus aria-hidden className="size-3.5" /> {labels.addRow}
760
+ </Button>
761
+ <Button
762
+ variant="ghost"
763
+ className="px-2 py-1 text-xs text-[var(--text-muted)]"
764
+ disabled={disabled || !cells.length}
765
+ onClick={() => {
766
+ onCells([]);
767
+ // The button is about to disable itself; focus must not go down with it.
768
+ focusCell(0, 0);
769
+ }}
770
+ >
771
+ <Eraser aria-hidden className="size-3.5" /> {labels.clear}
772
+ </Button>
773
+ <span className="text-[11px] tabular-nums text-[var(--text-muted)]">
774
+ {labels.points(filled.length)}
775
+ </span>
776
+ {problems > 0 && (
777
+ <span className="text-[11px] text-[var(--danger)]">{labels.problems(problems)}</span>
778
+ )}
779
+ <span className="ms-auto flex items-center gap-1 text-[11px] text-[var(--text-muted)]">
780
+ <ClipboardPaste aria-hidden className="size-3.5" /> {labels.pasteHint}
781
+ </span>
782
+ </div>
783
+ </div>
784
+ );
785
+ }
786
+
787
+ const textOf = (cells: string[][]) => cells.map((row) => row.join("\t")).join("\n");
788
+
789
+ /**
790
+ * The same table as text.
791
+ *
792
+ * Kept because the grid is worst at exactly what a textarea is best at: reading a long
793
+ * export back in one piece. It commits on blur — through `parseRows`, the paste door —
794
+ * and a line it cannot read is NAMED rather than dropped: half a sweep saved as a
795
+ * measurement is worse than a refusal.
796
+ */
797
+ function TextView({ columns, cells, onCells, disabled, mark, labels, labelledBy, describedBy }: ViewProps) {
798
+ const text = textOf(cells);
799
+ const [draft, setDraft] = useState(text);
800
+ const [errorLine, setErrorLine] = useState<number | null>(null);
801
+ // Follow the table when it changes from outside (a generated shape, a cleared form).
802
+ // Compared as text, so a caller that rebuilds the same cells every render does not
803
+ // wipe what is being typed.
804
+ const [seen, setSeen] = useState(text);
805
+ if (seen !== text) {
806
+ setSeen(text);
807
+ setDraft(text);
808
+ setErrorLine(null);
809
+ }
810
+
811
+ const commit = () => {
812
+ // Untouched: nothing to read back, and re-reading would rewrite every cell in the
813
+ // lexer's spelling of it.
814
+ if (draft === text) return;
815
+ if (!draft.trim()) {
816
+ setErrorLine(null);
817
+ onCells([]);
818
+ return;
819
+ }
820
+ const parsed = parseRows(draft, columns.length);
821
+ if ("error" in parsed) {
822
+ setErrorLine(parsed.error);
823
+ return;
824
+ }
825
+ setErrorLine(null);
826
+ onCells(parsed.rows.map((row) => row.map((value) => withMark(String(value), mark))));
827
+ };
828
+
829
+ const lines = draft.split("\n").filter((line) => line.trim()).length;
830
+
831
+ return (
832
+ <div>
833
+ <Textarea
834
+ aria-labelledby={labelledBy}
835
+ aria-describedby={describedBy}
836
+ rows={10}
837
+ value={draft}
838
+ readOnly={disabled}
839
+ spellCheck={false}
840
+ className="font-mono text-xs"
841
+ error={errorLine !== null ? labels.lineError(errorLine) : undefined}
842
+ onChange={(event) => setDraft(event.target.value)}
843
+ onBlur={commit}
844
+ />
845
+ <p className="mt-1 px-1 text-[11px] text-[var(--text-muted)]">
846
+ {columns.map((column) => column.label).join(" · ")}
847
+ {" — "}
848
+ {labels.points(lines)}
849
+ </p>
850
+ </div>
851
+ );
852
+ }