@eifi1/ui-kit 0.22.0 → 0.24.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 (208) hide show
  1. package/README.md +42 -25
  2. package/dist/chart.d.ts +8 -7
  3. package/dist/components/amount-input.d.ts +34 -7
  4. package/dist/components/amount-input.js +14 -10
  5. package/dist/components/amount-input.js.map +1 -1
  6. package/dist/components/autocomplete.d.ts +26 -0
  7. package/dist/components/autocomplete.js +164 -137
  8. package/dist/components/autocomplete.js.map +1 -1
  9. package/dist/components/button-group.d.ts +8 -7
  10. package/dist/components/calculator.d.ts +8 -7
  11. package/dist/components/column-mapper.d.ts +235 -0
  12. package/dist/components/column-mapper.js +411 -0
  13. package/dist/components/column-mapper.js.map +1 -0
  14. package/dist/components/combobox-core.d.ts +39 -2
  15. package/dist/components/combobox-core.js +29 -6
  16. package/dist/components/combobox-core.js.map +1 -1
  17. package/dist/components/combobox.d.ts +113 -3
  18. package/dist/components/combobox.js +456 -313
  19. package/dist/components/combobox.js.map +1 -1
  20. package/dist/components/confirm-dialog.d.ts +8 -7
  21. package/dist/components/confirm-dialog.js +7 -8
  22. package/dist/components/confirm-dialog.js.map +1 -1
  23. package/dist/components/copy-button.d.ts +5 -4
  24. package/dist/components/country-select.d.ts +50 -7
  25. package/dist/components/country-select.js +65 -9
  26. package/dist/components/country-select.js.map +1 -1
  27. package/dist/components/danger-confirm.d.ts +8 -7
  28. package/dist/components/danger-confirm.js +64 -7
  29. package/dist/components/danger-confirm.js.map +1 -1
  30. package/dist/components/date-picker.d.ts +41 -0
  31. package/dist/components/date-picker.js +269 -8
  32. package/dist/components/date-picker.js.map +1 -1
  33. package/dist/components/entity-combobox.d.ts +48 -2
  34. package/dist/components/entity-combobox.js +159 -114
  35. package/dist/components/entity-combobox.js.map +1 -1
  36. package/dist/components/facing-pair.d.ts +8 -7
  37. package/dist/components/field-parts.d.ts +116 -6
  38. package/dist/components/field-parts.js +84 -0
  39. package/dist/components/field-parts.js.map +1 -1
  40. package/dist/components/field-strip.d.ts +105 -0
  41. package/dist/components/field-strip.js +46 -0
  42. package/dist/components/field-strip.js.map +1 -0
  43. package/dist/components/file-button.d.ts +8 -7
  44. package/dist/components/file-dropzone.d.ts +8 -7
  45. package/dist/components/form-actions.d.ts +8 -7
  46. package/dist/components/form-actions.js +23 -3
  47. package/dist/components/form-actions.js.map +1 -1
  48. package/dist/components/iban-input.d.ts +8 -7
  49. package/dist/components/icon-picker.d.ts +10 -1
  50. package/dist/components/icon-picker.js +12 -4
  51. package/dist/components/icon-picker.js.map +1 -1
  52. package/dist/components/language-select.d.ts +8 -7
  53. package/dist/components/money-field.d.ts +11 -7
  54. package/dist/components/money-field.js.map +1 -1
  55. package/dist/components/month-picker.js +2 -1
  56. package/dist/components/month-picker.js.map +1 -1
  57. package/dist/components/multi-entity-combobox.d.ts +31 -2
  58. package/dist/components/multi-entity-combobox.js +152 -103
  59. package/dist/components/multi-entity-combobox.js.map +1 -1
  60. package/dist/components/number-field.d.ts +8 -7
  61. package/dist/components/number-input.d.ts +8 -7
  62. package/dist/components/numpad-sheet.d.ts +8 -7
  63. package/dist/components/phone-input.d.ts +8 -7
  64. package/dist/components/reauth-dialog.d.ts +2 -2
  65. package/dist/components/reauth-dialog.js +6 -8
  66. package/dist/components/reauth-dialog.js.map +1 -1
  67. package/dist/components/series-chart.d.ts +8 -7
  68. package/dist/components/settings-fields.d.ts +8 -7
  69. package/dist/components/share-card.d.ts +8 -7
  70. package/dist/components/swatch-picker.d.ts +17 -1
  71. package/dist/components/swatch-picker.js +10 -4
  72. package/dist/components/swatch-picker.js.map +1 -1
  73. package/dist/components/text-link.d.ts +8 -7
  74. package/dist/components/tile-radio.d.ts +20 -0
  75. package/dist/components/tile-radio.js +25 -8
  76. package/dist/components/tile-radio.js.map +1 -1
  77. package/dist/components/time-input.d.ts +8 -7
  78. package/dist/components/toggle-group.js +2 -2
  79. package/dist/components/toggle-group.js.map +1 -1
  80. package/dist/components/trigger-aria.d.ts +3 -0
  81. package/dist/components/trigger-aria.js +3 -1
  82. package/dist/components/trigger-aria.js.map +1 -1
  83. package/dist/components/ui.d.ts +5 -4
  84. package/dist/components/ui.js +60 -28
  85. package/dist/components/ui.js.map +1 -1
  86. package/dist/feedback/feedback-attachment.d.ts +66 -1
  87. package/dist/feedback/feedback-attachment.js +185 -65
  88. package/dist/feedback/feedback-attachment.js.map +1 -1
  89. package/dist/feedback/feedback-dialog.d.ts +66 -1
  90. package/dist/feedback/feedback-dialog.js.map +1 -1
  91. package/dist/feedback/feedback-inbox.d.ts +67 -252
  92. package/dist/feedback/feedback-inbox.js.map +1 -1
  93. package/dist/feedback/feedback-thread.d.ts +66 -287
  94. package/dist/feedback/feedback-thread.js +16 -3
  95. package/dist/feedback/feedback-thread.js.map +1 -1
  96. package/dist/{kit-labels-R8mIAc9N.d.ts → feedback-DOwPu-Il.d.ts} +1273 -30
  97. package/dist/feedback.d.ts +65 -3
  98. package/dist/hooks/use-file-drop.d.ts +8 -7
  99. package/dist/i18n/defaults.d.ts +8 -7
  100. package/dist/i18n/defaults.js +3 -1
  101. package/dist/i18n/defaults.js.map +1 -1
  102. package/dist/i18n/german.d.ts +8 -7
  103. package/dist/i18n/german.js +36 -2
  104. package/dist/i18n/german.js.map +1 -1
  105. package/dist/i18n/kit-labels.d.ts +5 -4
  106. package/dist/i18n/kit-labels.js.map +1 -1
  107. package/dist/i18n/languages.d.ts +8 -7
  108. package/dist/i18n/locales/de-CH.d.ts +8 -7
  109. package/dist/i18n/locales/en.d.ts +8 -7
  110. package/dist/i18n/locales/en.js +7 -0
  111. package/dist/i18n/locales/en.js.map +1 -1
  112. package/dist/i18n/locales/es.d.ts +8 -7
  113. package/dist/i18n/locales/es.js +37 -2
  114. package/dist/i18n/locales/es.js.map +1 -1
  115. package/dist/i18n/locales/fr.d.ts +8 -7
  116. package/dist/i18n/locales/fr.js +36 -2
  117. package/dist/i18n/locales/fr.js.map +1 -1
  118. package/dist/i18n/locales/hu.d.ts +8 -7
  119. package/dist/i18n/locales/hu.js +38 -2
  120. package/dist/i18n/locales/hu.js.map +1 -1
  121. package/dist/i18n/locales/it.d.ts +8 -7
  122. package/dist/i18n/locales/it.js +37 -2
  123. package/dist/i18n/locales/it.js.map +1 -1
  124. package/dist/i18n/locales/zh.d.ts +8 -7
  125. package/dist/i18n/locales/zh.js +34 -2
  126. package/dist/i18n/locales/zh.js.map +1 -1
  127. package/dist/i18n/review.d.ts +8 -7
  128. package/dist/i18n/review.js +20 -1
  129. package/dist/i18n/review.js.map +1 -1
  130. package/dist/index.d.ts +6 -4
  131. package/dist/index.js +16 -0
  132. package/dist/index.js.map +1 -1
  133. package/dist/lib/column-mapping.d.ts +81 -0
  134. package/dist/lib/column-mapping.js +108 -0
  135. package/dist/lib/column-mapping.js.map +1 -0
  136. package/dist/lib/strip-fade.d.ts +2 -2
  137. package/dist/lib/strip-fade.js.map +1 -1
  138. package/dist/lib/table-text.d.ts +109 -1
  139. package/dist/lib/table-text.js +122 -1
  140. package/dist/lib/table-text.js.map +1 -1
  141. package/dist/rhf/fields.d.ts +142 -13
  142. package/dist/rhf/fields.js +185 -3
  143. package/dist/rhf/fields.js.map +1 -1
  144. package/dist/rhf/form.d.ts +8 -7
  145. package/dist/rhf.d.ts +9 -8
  146. package/dist/rhf.js.map +1 -1
  147. package/dist/shell/app-shell.d.ts +8 -7
  148. package/dist/shell/top-bar-brand.d.ts +8 -7
  149. package/dist/shell/topbar-action-menu.d.ts +36 -3
  150. package/dist/shell/topbar-action-menu.js +74 -33
  151. package/dist/shell/topbar-action-menu.js.map +1 -1
  152. package/dist/shell.d.ts +8 -7
  153. package/dist/table-text.d.ts +1 -1
  154. package/dist/wizard/stepper-nav.d.ts +38 -9
  155. package/dist/wizard/stepper-nav.js +4 -0
  156. package/dist/wizard/stepper-nav.js.map +1 -1
  157. package/dist/wizard.d.ts +8 -7
  158. package/package.json +1 -1
  159. package/src/components/amount-input.tsx +50 -14
  160. package/src/components/autocomplete.tsx +188 -116
  161. package/src/components/column-mapper.tsx +768 -0
  162. package/src/components/combobox-core.tsx +82 -9
  163. package/src/components/combobox.tsx +655 -335
  164. package/src/components/confirm-dialog.tsx +12 -8
  165. package/src/components/country-select.tsx +135 -22
  166. package/src/components/danger-confirm.tsx +274 -24
  167. package/src/components/date-picker.tsx +423 -10
  168. package/src/components/entity-combobox.tsx +243 -129
  169. package/src/components/field-parts.tsx +224 -5
  170. package/src/components/field-strip.tsx +149 -0
  171. package/src/components/form-actions.tsx +52 -5
  172. package/src/components/icon-picker.tsx +23 -4
  173. package/src/components/money-field.tsx +3 -0
  174. package/src/components/month-picker.tsx +2 -1
  175. package/src/components/multi-entity-combobox.tsx +221 -121
  176. package/src/components/reauth-dialog.tsx +17 -18
  177. package/src/components/swatch-picker.tsx +29 -5
  178. package/src/components/tile-radio.tsx +74 -13
  179. package/src/components/toggle-group.tsx +2 -2
  180. package/src/components/trigger-aria.ts +5 -0
  181. package/src/components/ui.tsx +114 -33
  182. package/src/feedback/feedback-attachment.tsx +372 -72
  183. package/src/feedback/feedback-dialog.tsx +7 -3
  184. package/src/feedback/feedback-inbox.tsx +3 -2
  185. package/src/feedback/feedback-thread.tsx +112 -9
  186. package/src/i18n/defaults.ts +2 -0
  187. package/src/i18n/german.ts +42 -0
  188. package/src/i18n/kit-labels.tsx +4 -0
  189. package/src/i18n/locales/en.ts +27 -5
  190. package/src/i18n/locales/es.ts +41 -0
  191. package/src/i18n/locales/fr.ts +42 -0
  192. package/src/i18n/locales/hu.ts +37 -0
  193. package/src/i18n/locales/it.ts +41 -0
  194. package/src/i18n/locales/zh.ts +32 -0
  195. package/src/i18n/review.ts +19 -0
  196. package/src/index.ts +18 -0
  197. package/src/lib/column-mapping.ts +234 -0
  198. package/src/lib/strip-fade.ts +2 -2
  199. package/src/lib/table-text.ts +271 -0
  200. package/src/rhf/fields.tsx +421 -6
  201. package/src/rhf.ts +2 -1
  202. package/src/shell/topbar-action-menu.tsx +134 -38
  203. package/src/wizard/stepper-nav.tsx +35 -1
  204. package/dist/components/field-anatomy.d.ts +0 -95
  205. package/dist/components/field-anatomy.js +0 -84
  206. package/dist/components/field-anatomy.js.map +0 -1
  207. package/dist/feedback-attachment-NhUm7Zga.d.ts +0 -367
  208. package/src/components/field-anatomy.tsx +0 -190
@@ -0,0 +1,768 @@
1
+ import { useCallback, useEffect, useEffectEvent, useRef, useState } from "react";
2
+ import type { ChangeEvent, DragEvent, HTMLAttributes, ReactNode } from "react";
3
+ import { Upload } from "lucide-react";
4
+
5
+ import { useKitLabels, useKitLocale } from "../i18n/kit-labels";
6
+ import { cn } from "../lib/cn";
7
+ import {
8
+ assignColumnRole,
9
+ guessMapping,
10
+ missingRoles,
11
+ readMappedTable,
12
+ readTextFile,
13
+ roleOfColumn,
14
+ } from "../lib/column-mapping";
15
+ import type {
16
+ ColumnMapperResult,
17
+ ColumnMapping,
18
+ ColumnRole,
19
+ } from "../lib/column-mapping";
20
+ import { scrollIntoStrip, useStripFade } from "../lib/strip-fade";
21
+ import { parseTextTable } from "../lib/table-text";
22
+ import type { TableSeparator, TextTable } from "../lib/table-text";
23
+ import { AlertBanner } from "./alert-banner";
24
+ import { Checkbox } from "./checkbox";
25
+ import { Disclosure } from "./disclosure";
26
+ import { FileButton, useFilePicker } from "./file-button";
27
+ import {
28
+ Table,
29
+ TableBody,
30
+ TableCell,
31
+ TableHead,
32
+ TableHeaderCell,
33
+ TableRow,
34
+ } from "./table";
35
+ import { Select, Textarea } from "./ui";
36
+
37
+ /**
38
+ * A table pasted, dropped or chosen as a file, and which of its columns plays which
39
+ * part — Kurvenschmiede's columns input and keksdose's bank-file mapping step, once.
40
+ *
41
+ * Kurvenschmiede (`features/control/columns-input.tsx` + `csv.ts`) reads a recorder's
42
+ * export into a playground signal (time, value) and a comparison (time, setpoint,
43
+ * actual): a textarea, a file button, a parse, a select per role, and a line that says
44
+ * which decimal convention was assumed and how many lines were skipped. keksdose
45
+ * (`import-map-step.tsx`) shows a bank's CSV as a table with a role select on every
46
+ * column's header, the file's real values under it, ignored columns dimmed, and what
47
+ * the import still needs named under it. Same problem, two hand-built answers.
48
+ *
49
+ * Two layers, so both shapes fit:
50
+ *
51
+ * * {@link ColumnMapper} — the whole single panel: paste, drop or choose → parse
52
+ * ({@link parseTextTable}: separator, decimal convention, header line, all stated
53
+ * back) → preview with a role per column → `onChange(result)`. Kurvenschmiede's.
54
+ * * {@link ColumnRoleTable} — the preview with the role selects alone, controlled, over
55
+ * rows the caller already has. keksdose's map step, whose rows come from its server's
56
+ * sniff (encodings, quoted multi-line cells, skipped title rows) and whose mapping
57
+ * lives in the wizard's state between steps.
58
+ *
59
+ * The rules under both are headless in `lib/column-mapping.ts`: a role moves rather
60
+ * than doubling up, what is missing is named, and the rows a numeric role cannot read
61
+ * are reported by line number rather than dropped.
62
+ */
63
+
64
+ // ── Labels ────────────────────────────────────────────────────────────────────
65
+
66
+ export interface ColumnMapperLabels {
67
+ /** The paste box's label. */
68
+ paste: string;
69
+ /** The caption under the paste box. */
70
+ pasteHint: string;
71
+ /** The file button. */
72
+ chooseFile: string;
73
+ /** A chosen or dropped file whose bytes could not be read at all. */
74
+ readError: (name: string) => string;
75
+ /** The checkbox that says whether the first line names the columns. */
76
+ headerRow: string;
77
+ /** What was read: so many columns and rows. */
78
+ summary: (columns: number, rows: number) => string;
79
+ /** The separator that was assumed. */
80
+ separatorSemicolon: string;
81
+ separatorComma: string;
82
+ separatorTab: string;
83
+ separatorSpace: string;
84
+ /** The decimal convention that was assumed — with an example, because "decimal
85
+ * comma" alone is a term, and `1,5` is something a reader recognises. */
86
+ decimalComma: string;
87
+ decimalPoint: string;
88
+ /** The title over the lines that could not be read. */
89
+ unreadCount: (count: number) => string;
90
+ /** One of them. */
91
+ unreadLine: (line: number) => string;
92
+ /** Past the first hundred listed. */
93
+ unreadMore: (count: number) => string;
94
+ /** The text has content, and none of it is a row. */
95
+ noRows: string;
96
+ /** The preview table's name. */
97
+ table: string;
98
+ /** A column the table names no header for. */
99
+ columnN: (n: number) => string;
100
+ /** The role select on a column's header — its accessible name. */
101
+ roleOf: (column: string) => string;
102
+ /** The role select's "no role" option. */
103
+ ignore: string;
104
+ /** A required role in the select — only while some role is NOT required: when
105
+ * every one is, the mark tells no role from another (0.24, Kurvenschmiede). */
106
+ requiredRole: (role: string) => string;
107
+ /** Under the preview, when it shows fewer rows than were read. */
108
+ previewOf: (shown: number, total: number) => string;
109
+ /** A required group's roles, already joined as a list with "or". */
110
+ oneOf: (roles: string) => string;
111
+ /** What the table still needs, already joined as a list with "and". */
112
+ missing: (roles: string) => string;
113
+ }
114
+
115
+ export const DEFAULT_COLUMN_MAPPER_LABELS: ColumnMapperLabels = {
116
+ paste: "Paste a table",
117
+ pasteHint:
118
+ "Copy the rows out of a spreadsheet and paste them here, or drop a CSV or text file.",
119
+ chooseFile: "Choose a file",
120
+ readError: (name) => `“${name}” could not be read`,
121
+ headerRow: "The first line names the columns",
122
+ summary: (columns, rows) =>
123
+ `${columns} ${columns === 1 ? "column" : "columns"}, ${rows} ${rows === 1 ? "row" : "rows"}`,
124
+ separatorSemicolon: "separated by semicolons",
125
+ separatorComma: "separated by commas",
126
+ separatorTab: "separated by tabs",
127
+ separatorSpace: "separated by spaces",
128
+ decimalComma: "decimal comma (1,5)",
129
+ decimalPoint: "decimal point (1.5)",
130
+ unreadCount: (count) =>
131
+ count === 1
132
+ ? "1 line could not be read"
133
+ : `${count} lines could not be read`,
134
+ unreadLine: (line) => `Line ${line} could not be read`,
135
+ unreadMore: (count) => `…and ${count} more`,
136
+ noRows: "No line of this text reads as a row of the table.",
137
+ table: "Columns and their roles",
138
+ columnN: (n) => `Column ${n}`,
139
+ roleOf: (column) => `What does column “${column}” hold?`,
140
+ ignore: "Ignore",
141
+ requiredRole: (role) => `${role} (required)`,
142
+ previewOf: (shown, total) =>
143
+ shown === 1
144
+ ? `The first of ${total} rows`
145
+ : `The first ${shown} of ${total} rows`,
146
+ oneOf: (roles) => `either ${roles}`,
147
+ missing: (roles) => `Still needed: ${roles}.`,
148
+ };
149
+
150
+ const SEPARATOR_LABEL: Record<
151
+ TableSeparator,
152
+ "separatorSemicolon" | "separatorComma" | "separatorTab" | "separatorSpace"
153
+ > = {
154
+ ";": "separatorSemicolon",
155
+ ",": "separatorComma",
156
+ "\t": "separatorTab",
157
+ " ": "separatorSpace",
158
+ };
159
+
160
+ /** How many unread lines are listed before "…and N more". */
161
+ const UNREAD_LISTED = 100;
162
+
163
+ /** A file a table is likely to be in. Extensions only, so a refusal reads "Only .csv,
164
+ * .tsv, … files" rather than a list of MIME types; the parse is the real check. */
165
+ const DEFAULT_ACCEPT = ".csv,.tsv,.txt,.dat,.asc";
166
+
167
+ function formatList(
168
+ items: string[],
169
+ type: "conjunction" | "disjunction",
170
+ locale: string | undefined,
171
+ ): string {
172
+ try {
173
+ return new Intl.ListFormat(locale, { type, style: "long" }).format(items);
174
+ } catch {
175
+ return items.join(", ");
176
+ }
177
+ }
178
+
179
+ // ── ColumnRoleTable ───────────────────────────────────────────────────────────
180
+
181
+ /** A `data-*` attribute, typed so `{ "data-private": "" }` needs no cast. */
182
+ type DataAttributes = { [key: `data-${string}`]: string | number | boolean | undefined };
183
+
184
+ /**
185
+ * What {@link ColumnRoleTableProps.bodyProps} puts on the preview's `<tbody>`: `data-*`
186
+ * hooks, an `id`, a class, a style.
187
+ */
188
+ export type ColumnRoleTableBodyProps = Omit<
189
+ HTMLAttributes<HTMLTableSectionElement>,
190
+ "children" | "dangerouslySetInnerHTML"
191
+ > &
192
+ DataAttributes;
193
+
194
+ /**
195
+ * What {@link ColumnRoleTableProps.rowProps} returns for one preview row's `<tr>` —
196
+ * the same shape as LineItems' `LineItemsRowProps`, on a table row.
197
+ */
198
+ export type ColumnRoleTableRowProps = Omit<
199
+ HTMLAttributes<HTMLTableRowElement>,
200
+ "children" | "dangerouslySetInnerHTML"
201
+ > &
202
+ DataAttributes;
203
+
204
+ export interface ColumnRoleTableProps<
205
+ R extends string,
206
+ M extends ColumnMapping<R> = ColumnMapping<R>,
207
+ > {
208
+ /** The columns' names — the file's header line — or `null` for a table without one
209
+ * (each column is then "Column 1", "Column 2", …). */
210
+ header: readonly string[] | null;
211
+ /** The rows to preview, as text. Only the first {@link previewRows} are drawn. */
212
+ rows: readonly (readonly string[])[];
213
+ /** How many columns. Default: the header's length or the widest previewed row. */
214
+ width?: number;
215
+ /** The parts a column can play. */
216
+ roles: readonly ColumnRole<R>[];
217
+ /** Role → column. Any object with the roles as nullable number fields — keksdose's
218
+ * `CsvMapping` as it stands; the other fields are handed back untouched. */
219
+ mapping: M;
220
+ /** The next mapping, with the picked role moved onto its column. */
221
+ onMappingChange: (next: M) => void;
222
+ /** Default 5. */
223
+ previewRows?: number;
224
+ /** How many rows the table has in all, for "The first 5 of 120 rows". Default:
225
+ * `rows.length`. */
226
+ totalRows?: number;
227
+ /** Every role select disabled — keksdose locks them while a re-sniff replaces the
228
+ * table they point into. */
229
+ disabled?: boolean;
230
+ /**
231
+ * Extra attributes for the preview's `<tbody>` (0.24) — keksdose: the sample rows are
232
+ * the user's own bank data (payees, memos, amounts), and its demo mode blurs exactly
233
+ * that through `.demo-mode [data-private]` (#336). With nowhere to put the attribute,
234
+ * its map step reached into the table with a `useLayoutEffect` that set it on the
235
+ * `<tbody>` after every commit; `bodyProps={{ "data-private": "" }}` declares it.
236
+ * There is deliberately no head counterpart: the column names and the role selects
237
+ * are what such a mode is there to show.
238
+ *
239
+ * Spread on the kit `TableBody`; a `className` is added to its own.
240
+ */
241
+ bodyProps?: ColumnRoleTableBodyProps;
242
+ /**
243
+ * Extra attributes for one preview row's `<tr>`, from its cells and its index in the
244
+ * preview (0.24) — the contract of LineItems' `rowProps` (keksdose K20), on a table:
245
+ * `data-*` hooks (a per-row `data-private`, a test id), an `id`, a class. Called for
246
+ * the rows drawn, the first {@link previewRows}. The row has no attributes of its own
247
+ * to protect; a `className` is added after its classes.
248
+ */
249
+ rowProps?: (row: readonly string[], index: number) => ColumnRoleTableRowProps | undefined;
250
+ labels?: Partial<ColumnMapperLabels>;
251
+ className?: string;
252
+ }
253
+
254
+ /**
255
+ * A table's first rows, with a role select on every column's header.
256
+ *
257
+ * keksdose's mapping step (dev#462: "make it more table like, where the table columns
258
+ * can be chosen from the input and the column data changes with the chosen column
259
+ * header"): the file IS the form. The file's own column name sits on top, verbatim —
260
+ * it is how the reader recognises the column; under it the role, picked in place;
261
+ * under that the column's real values, so a column that is one off shows up here and
262
+ * not after the import. A column with no role says "Ignore" and its values are dimmed:
263
+ * the state that most needs to be visible in a twelve-column bank export.
264
+ *
265
+ * Picking a role another column holds MOVES it ({@link assignColumnRole}). What the
266
+ * table still needs is named under it — a required group as "either Amount, Debit or
267
+ * Credit". Required roles say "(required)" in the list only where some role is not
268
+ * (0.24): Kurvenschmiede's roles are all required, so the mark told no option from
269
+ * another, and on a phone it cut the role's own name short ("Zeit (s) (erforderl…")
270
+ * — the part of the option the reader has to read. The "Still needed" line already
271
+ * says what is missing; a mark that distinguishes nothing is only noise.
272
+ *
273
+ * The table scrolls sideways inside its own box (the kit {@link Table}'s wrapper, a
274
+ * named, keyboard-reachable region while it overflows), so a wide export never widens
275
+ * the page at 390px. An edge with columns behind it fades out (0.24, Kurvenschmiede:
276
+ * on a phone the fourth column's select sat off-screen and nothing said there was more
277
+ * to the right; phone scrollbars are overlays that show only while you drag). It is
278
+ * the kit Tabs strip's measured fade: drawn only while something is hidden on that
279
+ * side, so a table that fits is painted as before; both ends once scrolled into the
280
+ * middle; the reading direction's own in RTL; never animated, so there is nothing for
281
+ * reduced motion to turn off; and a `mask-image`, which changes no layout and needs no
282
+ * background colour to fade to. A role select focused behind the fade is scrolled
283
+ * clear of it.
284
+ */
285
+ export function ColumnRoleTable<
286
+ R extends string,
287
+ M extends ColumnMapping<R> = ColumnMapping<R>,
288
+ >({
289
+ header,
290
+ rows,
291
+ width: widthProp,
292
+ roles,
293
+ mapping,
294
+ onMappingChange,
295
+ previewRows = 5,
296
+ totalRows,
297
+ disabled,
298
+ bodyProps,
299
+ rowProps,
300
+ labels: labelsProp,
301
+ className,
302
+ }: ColumnRoleTableProps<R, M>) {
303
+ const labels: ColumnMapperLabels = useKitLabels(
304
+ "columnMapper",
305
+ DEFAULT_COLUMN_MAPPER_LABELS,
306
+ labelsProp,
307
+ );
308
+ const locale = useKitLocale();
309
+ const shown = rows.slice(0, previewRows);
310
+ const width =
311
+ widthProp ??
312
+ shown.reduce(
313
+ (widest, row) => Math.max(widest, row.length),
314
+ header?.length ?? 0,
315
+ );
316
+ const columns = Array.from({ length: width }, (_, index) => index);
317
+ const total = totalRows ?? rows.length;
318
+ const nameOf = (column: number) =>
319
+ header?.[column] || labels.columnN(column + 1);
320
+ const labelOf = (value: R) =>
321
+ roles.find((role) => role.value === value)?.label ?? value;
322
+ const gaps = missingRoles(roles, mapping, width).map((gap) =>
323
+ gap.length === 1
324
+ ? labelOf(gap[0])
325
+ : labels.oneOf(formatList(gap.map(labelOf), "disjunction", locale)),
326
+ );
327
+ // "(required)" only where it tells one option from another.
328
+ const markRequired = roles.some((role) => role.required !== true);
329
+
330
+ // The Table's own scroll wrapper — the `<table>`'s parent — is what overflows; the
331
+ // fade is measured on it and drawn on the box round it, which has the same edges.
332
+ const scroller = useRef<HTMLElement | null>(null);
333
+ const tableRef = useCallback((table: HTMLTableElement | null) => {
334
+ scroller.current = table?.parentElement ?? null;
335
+ }, []);
336
+ const fade = useStripFade(scroller);
337
+
338
+ return (
339
+ <div
340
+ className={cn("min-w-0 space-y-1.5", className)}
341
+ data-slot="column-role-table"
342
+ >
343
+ <div
344
+ data-slot="column-role-table-scroll"
345
+ // In reading-direction terms ("start", "end", "both"), for a caller's styling.
346
+ data-overflow={fade.overflow}
347
+ style={
348
+ fade.mask
349
+ ? { maskImage: fade.mask, WebkitMaskImage: fade.mask }
350
+ : undefined
351
+ }
352
+ >
353
+ <Table
354
+ ref={tableRef}
355
+ density="compact"
356
+ framed
357
+ aria-label={labels.table}
358
+ >
359
+ <TableHead>
360
+ <TableRow>
361
+ {columns.map((column) => {
362
+ const role = roleOfColumn(roles, mapping, column);
363
+ const name = nameOf(column);
364
+ return (
365
+ <TableHeaderCell
366
+ key={column}
367
+ scope="col"
368
+ className="min-w-36 py-2 align-top"
369
+ >
370
+ <span className="block max-w-56 truncate pb-1 text-[11px] font-normal text-[var(--text-muted)]">
371
+ {name}
372
+ </span>
373
+ <Select
374
+ size="sm"
375
+ className="w-full"
376
+ aria-label={labels.roleOf(name)}
377
+ value={role ?? ""}
378
+ disabled={disabled}
379
+ // Focus brings a select behind the fade clear of it — the browser's
380
+ // own scroll stops at the edge, under the fade.
381
+ onFocus={(event) => {
382
+ const cell = event.currentTarget.closest("th");
383
+ if (scroller.current && cell)
384
+ scrollIntoStrip(scroller.current, cell);
385
+ }}
386
+ onChange={(event) =>
387
+ onMappingChange(
388
+ assignColumnRole(
389
+ roles,
390
+ mapping,
391
+ column,
392
+ event.target.value === ""
393
+ ? null
394
+ : (event.target.value as R),
395
+ ),
396
+ )
397
+ }
398
+ >
399
+ <option value="">{labels.ignore}</option>
400
+ {roles.map((option) => (
401
+ <option key={option.value} value={option.value}>
402
+ {option.required === true && markRequired
403
+ ? labels.requiredRole(option.label)
404
+ : option.label}
405
+ </option>
406
+ ))}
407
+ </Select>
408
+ </TableHeaderCell>
409
+ );
410
+ })}
411
+ </TableRow>
412
+ </TableHead>
413
+ <TableBody {...bodyProps}>
414
+ {shown.map((row, index) => (
415
+ <TableRow {...rowProps?.(row, index)} key={index}>
416
+ {columns.map((column) => (
417
+ <TableCell
418
+ key={column}
419
+ data-ignored={
420
+ roleOfColumn(roles, mapping, column) === null || undefined
421
+ }
422
+ className={cn(
423
+ "font-mono whitespace-nowrap",
424
+ // Dimmed, not hidden: its values are what tell you whether ignoring
425
+ // it was right.
426
+ roleOfColumn(roles, mapping, column) === null &&
427
+ "text-[var(--text-muted)]",
428
+ )}
429
+ >
430
+ <span className="block max-w-56 truncate">
431
+ {row[column] ?? ""}
432
+ </span>
433
+ </TableCell>
434
+ ))}
435
+ </TableRow>
436
+ ))}
437
+ </TableBody>
438
+ </Table>
439
+ </div>
440
+ {total > shown.length && (
441
+ <p className="text-xs text-[var(--text-muted)]">
442
+ {labels.previewOf(shown.length, total)}
443
+ </p>
444
+ )}
445
+ {gaps.length > 0 && (
446
+ <AlertBanner tone="warning" variant="inline" size="sm" block>
447
+ {labels.missing(formatList(gaps, "conjunction", locale))}
448
+ </AlertBanner>
449
+ )}
450
+ </div>
451
+ );
452
+ }
453
+
454
+ // ── ColumnMapper ──────────────────────────────────────────────────────────────
455
+
456
+ export interface ColumnMapperProps<R extends string> {
457
+ /** The parts the columns play — translated labels, which are required, which must
458
+ * be numbers. See {@link ColumnRole}. */
459
+ roles: readonly ColumnRole<R>[];
460
+ /**
461
+ * The table read through the current mapping, on every change: the text, the header
462
+ * checkbox, a role. `null` while there is no table at all (an empty box). Use it when
463
+ * `result.complete`; until then `result.missing` says what is not placed yet.
464
+ *
465
+ * The rows are strings. A numeric role's cells are guaranteed to read with
466
+ * `tableNumber(cell, result.decimalComma)`; anything else is the caller's to convert.
467
+ */
468
+ onChange: (result: ColumnMapperResult<R> | null) => void;
469
+ /** The paste box's label. Default: `labels.paste`. */
470
+ label?: ReactNode;
471
+ /** The caption under the paste box. Default: `labels.pasteHint`. */
472
+ hint?: ReactNode;
473
+ /** What the file dialog offers, and what a drop is checked against. Default:
474
+ * `.csv,.tsv,.txt,.dat,.asc`. */
475
+ accept?: string;
476
+ /** The largest file taken, in bytes. Default: no limit. */
477
+ maxSize?: number;
478
+ /** Text to start with. `onChange` is called with its result once, on mount. */
479
+ defaultText?: string;
480
+ /** Rows in the preview. Default 5. */
481
+ previewRows?: number;
482
+ /** The first mapping for a new table. Default {@link guessMapping}: a column named
483
+ * like a role gets it, and the required roles left over take the free columns in
484
+ * order. */
485
+ guess?: (table: TextTable) => ColumnMapping<R>;
486
+ disabled?: boolean;
487
+ /** The preview table's `<tbody>` attributes — {@link ColumnRoleTableProps.bodyProps}
488
+ * (0.24): `{ "data-private": "" }` for a table of someone's own data. */
489
+ bodyProps?: ColumnRoleTableBodyProps;
490
+ /** One preview row's `<tr>` attributes — {@link ColumnRoleTableProps.rowProps}
491
+ * (0.24). `row` is the row as read, `index` its place in the preview. */
492
+ rowProps?: (row: readonly string[], index: number) => ColumnRoleTableRowProps | undefined;
493
+ labels?: Partial<ColumnMapperLabels>;
494
+ className?: string;
495
+ }
496
+
497
+ interface MapperState<R extends string> {
498
+ text: string;
499
+ /** The reader's answer to "does the first line name the columns", or `null` for
500
+ * the parse's own. */
501
+ header: boolean | null;
502
+ table: TextTable;
503
+ mapping: ColumnMapping<R>;
504
+ }
505
+
506
+ const hasFiles = (event: DragEvent) =>
507
+ Array.from(event.dataTransfer?.types ?? []).includes("Files");
508
+
509
+ /**
510
+ * Paste, drop or choose a table, see what it was read as, and say which column is
511
+ * which — Kurvenschmiede's playground signal and comparison input as one kit part.
512
+ *
513
+ * Everything the parse assumed is stated, because a guess the reader cannot see is a
514
+ * guess they cannot correct: the shape it found, the separator, the decimal
515
+ * convention ("decimal comma (1,5)"), and every line it could not read, by number and
516
+ * with its text. The header line is a checkbox, since the detection is a guess either
517
+ * way and toggling it does not move a column (the mapping is kept, keksdose's
518
+ * `keepRoles`). A new file is a new table and is mapped afresh; typing that changes the
519
+ * column count re-guesses, because the old indexes point at nothing.
520
+ *
521
+ * A file can be chosen, dropped on the button, or dropped on the paste box — which,
522
+ * left to the browser, would open the file in place of the page. It is read as UTF-8,
523
+ * or as Windows-1252 when it is not UTF-8 ({@link readTextFile}).
524
+ *
525
+ * A two-step wizard that keeps the drop and the mapping apart (keksdose's) uses the
526
+ * parts: {@link parseTextTable} or its own server's sniff, then {@link ColumnRoleTable},
527
+ * then {@link readMappedTable}.
528
+ */
529
+ export function ColumnMapper<R extends string>({
530
+ roles,
531
+ onChange,
532
+ label,
533
+ hint,
534
+ accept = DEFAULT_ACCEPT,
535
+ maxSize,
536
+ defaultText = "",
537
+ previewRows = 5,
538
+ guess,
539
+ disabled = false,
540
+ bodyProps,
541
+ rowProps,
542
+ labels: labelsProp,
543
+ className,
544
+ }: ColumnMapperProps<R>) {
545
+ const labels: ColumnMapperLabels = useKitLabels(
546
+ "columnMapper",
547
+ DEFAULT_COLUMN_MAPPER_LABELS,
548
+ labelsProp,
549
+ );
550
+ const firstMapping = (table: TextTable) =>
551
+ guess ? guess(table) : guessMapping(roles, table.header, table.width);
552
+ const [state, setState] = useState<MapperState<R>>(() => {
553
+ const table = parseTextTable(defaultText);
554
+ return {
555
+ text: defaultText,
556
+ header: null,
557
+ table,
558
+ mapping: firstMapping(table),
559
+ };
560
+ });
561
+ const [reading, setReading] = useState(false);
562
+ const [refusal, setRefusal] = useState<string | null>(null);
563
+ const [dragOver, setDragOver] = useState(false);
564
+
565
+ // What is drawn and what is handed over are the same computation. Not memoised: a
566
+ // caller writes `roles={[…]}` inline, so a memo keyed on them would miss every time,
567
+ // and the read is one pass over rows that are already split.
568
+ const result = readMappedTable(state.table, roles, state.mapping);
569
+
570
+ const commit = (next: MapperState<R>) => {
571
+ setState(next);
572
+ onChange(
573
+ next.table.width === 0
574
+ ? null
575
+ : readMappedTable(next.table, roles, next.mapping),
576
+ );
577
+ };
578
+
579
+ /** New text. `fresh` (a file): the reader's header answer and the mapping start over. */
580
+ const take = (text: string, fresh: boolean) => {
581
+ const header = fresh ? null : state.header;
582
+ const table = parseTextTable(text, header === null ? {} : { header });
583
+ const keep =
584
+ !fresh && table.width === state.table.width && state.table.width > 0;
585
+ commit({
586
+ text,
587
+ header,
588
+ table,
589
+ mapping: keep ? state.mapping : firstMapping(table),
590
+ });
591
+ };
592
+
593
+ const load = (file: File) => {
594
+ setRefusal(null);
595
+ setReading(true);
596
+ void readTextFile(file)
597
+ .then(
598
+ (text) => take(text, true),
599
+ // Only the read: an error thrown by the caller's onChange is not the file's.
600
+ () => setRefusal(labels.readError(file.name)),
601
+ )
602
+ .finally(() => setReading(false));
603
+ };
604
+
605
+ const refuse = (rejections: { message: string }[]) =>
606
+ setRefusal(rejections[0]?.message ?? null);
607
+
608
+ // A file dropped on the paste box. The same screening as the button's.
609
+ const drop = useFilePicker({
610
+ accept,
611
+ maxSize,
612
+ disabled,
613
+ onFiles: ([file]) => load(file),
614
+ onReject: refuse,
615
+ });
616
+
617
+ const seeded = useEffectEvent(() => {
618
+ if (state.table.width > 0) onChange(result);
619
+ });
620
+ useEffect(() => {
621
+ seeded();
622
+ }, []);
623
+
624
+ const { table } = state;
625
+ const separator = labels[SEPARATOR_LABEL[table.separator]];
626
+ const unread = result.unread;
627
+
628
+ return (
629
+ <div
630
+ className={cn("min-w-0 space-y-3", className)}
631
+ data-slot="column-mapper"
632
+ >
633
+ <Textarea
634
+ label={label ?? labels.paste}
635
+ hint={hint ?? labels.pasteHint}
636
+ rows={5}
637
+ wrap="off"
638
+ spellCheck={false}
639
+ autoCapitalize="off"
640
+ autoCorrect="off"
641
+ value={state.text}
642
+ disabled={disabled}
643
+ className={cn(
644
+ "font-mono text-xs",
645
+ dragOver && "rounded-md ring-2 ring-[var(--brand)]",
646
+ )}
647
+ data-drag-over={dragOver || undefined}
648
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {
649
+ setRefusal(null);
650
+ take(event.target.value, false);
651
+ }}
652
+ onDragEnter={(event) => {
653
+ if (!hasFiles(event)) return;
654
+ event.preventDefault();
655
+ if (!disabled) setDragOver(true);
656
+ }}
657
+ onDragOver={(event) => {
658
+ if (!hasFiles(event)) return;
659
+ // Cancelled for every file drag: an uncancelled one makes the browser open
660
+ // the file in place of the page.
661
+ event.preventDefault();
662
+ event.dataTransfer.dropEffect = disabled ? "none" : "copy";
663
+ }}
664
+ onDragLeave={() => setDragOver(false)}
665
+ onDrop={(event) => {
666
+ if (!hasFiles(event)) return;
667
+ event.preventDefault();
668
+ setDragOver(false);
669
+ drop.take(event.dataTransfer.files);
670
+ }}
671
+ />
672
+ {drop.element}
673
+
674
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
675
+ <FileButton
676
+ variant="secondary"
677
+ accept={accept}
678
+ maxSize={maxSize}
679
+ droppable
680
+ pending={reading}
681
+ disabled={disabled}
682
+ onFiles={([file]) => load(file)}
683
+ onReject={refuse}
684
+ >
685
+ <Upload className="size-4" aria-hidden />
686
+ {labels.chooseFile}
687
+ </FileButton>
688
+ {table.width > 0 && (
689
+ <Checkbox
690
+ label={labels.headerRow}
691
+ checked={table.header !== null}
692
+ disabled={disabled}
693
+ onCheckedChange={(checked) => {
694
+ const next = parseTextTable(state.text, { header: checked });
695
+ // Same text, same split: the columns are where they were, and so are the
696
+ // roles on them.
697
+ commit({ ...state, header: checked, table: next });
698
+ }}
699
+ />
700
+ )}
701
+ </div>
702
+
703
+ {refusal && (
704
+ <AlertBanner tone="danger" variant="inline" size="sm" block>
705
+ {refusal}
706
+ </AlertBanner>
707
+ )}
708
+
709
+ {table.width > 0 && (
710
+ <>
711
+ <p
712
+ className="text-xs text-[var(--text-secondary)]"
713
+ data-slot="column-mapper-summary"
714
+ >
715
+ {[
716
+ labels.summary(table.width, result.rows.length),
717
+ separator,
718
+ table.decimalComma ? labels.decimalComma : labels.decimalPoint,
719
+ ].join(" · ")}
720
+ </p>
721
+ {result.rows.length === 0 && (
722
+ <AlertBanner tone="warning" variant="inline" size="sm" block>
723
+ {labels.noRows}
724
+ </AlertBanner>
725
+ )}
726
+ <ColumnRoleTable
727
+ header={table.header}
728
+ rows={result.rows}
729
+ width={table.width}
730
+ roles={roles}
731
+ mapping={state.mapping}
732
+ onMappingChange={(mapping) => commit({ ...state, mapping })}
733
+ previewRows={previewRows}
734
+ disabled={disabled}
735
+ bodyProps={bodyProps}
736
+ rowProps={rowProps}
737
+ labels={labelsProp}
738
+ />
739
+ {unread.length > 0 && (
740
+ <Disclosure
741
+ variant="bare"
742
+ title={labels.unreadCount(unread.length)}
743
+ data-slot="column-mapper-unread"
744
+ >
745
+ <ul className="space-y-1 text-xs">
746
+ {unread.slice(0, UNREAD_LISTED).map((line) => (
747
+ <li key={line.line} className="min-w-0">
748
+ <span className="block text-[var(--text-secondary)]">
749
+ {labels.unreadLine(line.line)}
750
+ </span>
751
+ <code className="block truncate font-mono text-[var(--text-muted)]">
752
+ {line.text}
753
+ </code>
754
+ </li>
755
+ ))}
756
+ {unread.length > UNREAD_LISTED && (
757
+ <li className="text-[var(--text-muted)]">
758
+ {labels.unreadMore(unread.length - UNREAD_LISTED)}
759
+ </li>
760
+ )}
761
+ </ul>
762
+ </Disclosure>
763
+ )}
764
+ </>
765
+ )}
766
+ </div>
767
+ );
768
+ }