@macrostrat/data-sheet 4.8.0 → 4.9.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 (95) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +60 -19
  3. package/dist/actions/context.cjs +10 -1
  4. package/dist/actions/context.cjs.map +1 -1
  5. package/dist/actions/context.js +10 -1
  6. package/dist/actions/context.js.map +1 -1
  7. package/dist/actions/types.d.ts +4 -0
  8. package/dist/components/data-editor.cjs +527 -0
  9. package/dist/components/data-editor.cjs.map +1 -0
  10. package/dist/components/data-editor.d.ts +142 -0
  11. package/dist/components/data-editor.js +524 -0
  12. package/dist/components/data-editor.js.map +1 -0
  13. package/dist/components/editor-actions.cjs +167 -0
  14. package/dist/components/editor-actions.cjs.map +1 -0
  15. package/dist/components/editor-actions.d.ts +37 -0
  16. package/dist/components/editor-actions.js +165 -0
  17. package/dist/components/editor-actions.js.map +1 -0
  18. package/dist/components/editor-popup.cjs +11 -1
  19. package/dist/components/editor-popup.cjs.map +1 -1
  20. package/dist/components/editor-popup.js +11 -1
  21. package/dist/components/editor-popup.js.map +1 -1
  22. package/dist/components/index.d.ts +3 -0
  23. package/dist/components/indicators/selection.cjs +10 -4
  24. package/dist/components/indicators/selection.cjs.map +1 -1
  25. package/dist/components/indicators/selection.js +10 -4
  26. package/dist/components/indicators/selection.js.map +1 -1
  27. package/dist/components/row-editor.cjs +351 -0
  28. package/dist/components/row-editor.cjs.map +1 -0
  29. package/dist/components/row-editor.d.ts +181 -0
  30. package/dist/components/row-editor.js +349 -0
  31. package/dist/components/row-editor.js.map +1 -0
  32. package/dist/components/row-editor.module.sass.cjs +51 -0
  33. package/dist/components/row-editor.module.sass.cjs.map +1 -0
  34. package/dist/components/row-editor.module.sass.js +49 -0
  35. package/dist/components/row-editor.module.sass.js.map +1 -0
  36. package/dist/components/toolbars/actions-toolbar.cjs +1 -1
  37. package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
  38. package/dist/components/toolbars/actions-toolbar.js +1 -1
  39. package/dist/components/toolbars/actions-toolbar.js.map +1 -1
  40. package/dist/data-sheet.css +208 -20
  41. package/dist/index.cjs +27 -0
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.js +29 -2
  44. package/dist/index.js.map +1 -1
  45. package/dist/main.module.sass.cjs +14 -13
  46. package/dist/main.module.sass.cjs.map +1 -1
  47. package/dist/main.module.sass.js +14 -13
  48. package/dist/main.module.sass.js.map +1 -1
  49. package/dist/provider/column-spec.cjs +8 -1
  50. package/dist/provider/column-spec.cjs.map +1 -1
  51. package/dist/provider/column-spec.d.ts +105 -1
  52. package/dist/provider/column-spec.js +8 -1
  53. package/dist/provider/column-spec.js.map +1 -1
  54. package/dist/provider/core.cjs +16 -4
  55. package/dist/provider/core.cjs.map +1 -1
  56. package/dist/provider/core.d.ts +4 -0
  57. package/dist/provider/core.js +16 -4
  58. package/dist/provider/core.js.map +1 -1
  59. package/dist/provider/types.cjs.map +1 -1
  60. package/dist/provider/types.d.ts +1 -1
  61. package/dist/provider/types.js.map +1 -1
  62. package/dist/provider/zustand-store.cjs +26 -13
  63. package/dist/provider/zustand-store.cjs.map +1 -1
  64. package/dist/provider/zustand-store.js +14 -1
  65. package/dist/provider/zustand-store.js.map +1 -1
  66. package/dist/renderers/cell-renderer.cjs +15 -4
  67. package/dist/renderers/cell-renderer.cjs.map +1 -1
  68. package/dist/renderers/cell-renderer.js +13 -4
  69. package/dist/renderers/cell-renderer.js.map +1 -1
  70. package/dist/renderers/column-header-cell.cjs +12 -1
  71. package/dist/renderers/column-header-cell.cjs.map +1 -1
  72. package/dist/renderers/column-header-cell.js +11 -1
  73. package/dist/renderers/column-header-cell.js.map +1 -1
  74. package/dist/types.cjs.map +1 -1
  75. package/dist/types.d.ts +5 -1
  76. package/dist/types.js.map +1 -1
  77. package/package.json +2 -2
  78. package/src/actions/context.ts +13 -2
  79. package/src/actions/types.ts +5 -0
  80. package/src/components/data-editor.ts +741 -0
  81. package/src/components/editor-actions.ts +228 -0
  82. package/src/components/editor-popup.ts +16 -3
  83. package/src/components/index.ts +3 -0
  84. package/src/components/indicators/selection.ts +12 -4
  85. package/src/components/row-editor.module.sass +161 -0
  86. package/src/components/row-editor.ts +620 -0
  87. package/src/components/toolbars/actions-toolbar.ts +3 -2
  88. package/src/main.module.sass +19 -0
  89. package/src/provider/column-spec.ts +94 -16
  90. package/src/provider/core.ts +19 -4
  91. package/src/provider/types.ts +1 -1
  92. package/src/provider/zustand-store.ts +30 -1
  93. package/src/renderers/cell-renderer.ts +18 -3
  94. package/src/renderers/column-header-cell.ts +10 -0
  95. package/src/types.ts +5 -1
@@ -0,0 +1,741 @@
1
+ /**
2
+ * Data editor — one record's fields as a form, from a data spec.
3
+ *
4
+ * A **data spec** is a list of fields with the semantics of a sheet's column
5
+ * spec — any column spec is one: a field's label is its `name`, its value is
6
+ * drawn by its `valueRenderer`, and its editor is its `cellDetail` when it
7
+ * has one, else an input chosen from `dataType`. Locked and derived fields
8
+ * show read-only (`isColumnWritable`), `validate` and `required` flag values,
9
+ * and the form as a whole is a read-only viewer when `editable` is off.
10
+ *
11
+ * `DataEditor` stands alone: it takes a record, keeps its own pending edits
12
+ * (or takes them controlled), and has the sheet's save/reset semantics — a
13
+ * footer with Reset and Save (disabled until there are edits, and while any
14
+ * field has an error), `onSave` handed the edited record and the edits. Its
15
+ * actions are a sheet's table actions scoped to the form: those for a row
16
+ * act on the record, those for a cell or column on one field (see
17
+ * `editor-actions.ts`). It has no notion of a selected field; that belongs to
18
+ * a sheet.
19
+ *
20
+ * The parts it is built from are exported for the sheet's row editor, which
21
+ * is this form over the sheet's selected rows: `DataEditorFields` (a form
22
+ * over one record or several, writing through callbacks), `DataEditorFrame`
23
+ * (the panel, its title bar and footer) and `DataEditorField`.
24
+ */
25
+ import hyper from "@macrostrat/hyper";
26
+ import classNames from "classnames";
27
+ import {
28
+ Button,
29
+ FormGroup,
30
+ InputGroup,
31
+ Intent,
32
+ Switch,
33
+ Tag,
34
+ TextArea,
35
+ } from "@blueprintjs/core";
36
+ import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
37
+ import {
38
+ type CellDetailContext,
39
+ type CellSelectionEntry,
40
+ type CellValidation,
41
+ type ColumnSpec,
42
+ isColumnWritable,
43
+ } from "../provider";
44
+ import { validateCell } from "../utils/validation.ts";
45
+ import type { TableAction } from "../actions";
46
+ import {
47
+ EditorActionButton,
48
+ editorActionsFor,
49
+ type EditorActionTarget,
50
+ } from "./editor-actions";
51
+ import styles from "./row-editor.module.sass";
52
+
53
+ const h = hyper.styled(styles);
54
+
55
+ /** A field of a data spec: a column spec's field, read the same way. */
56
+ export type FieldSpec = ColumnSpec;
57
+
58
+ export interface DataEditorProps<T = any> {
59
+ /** The fields, in order. */
60
+ dataSpec: FieldSpec[];
61
+ /** The record as loaded. A new record clears pending edits (uncontrolled). */
62
+ data: T;
63
+ /** Pending edits, when the caller keeps them (controlled). */
64
+ edits?: Partial<T>;
65
+ /** Pending edits changed — every field change, reset and save. */
66
+ onEditsChange?: (edits: Partial<T>) => void;
67
+ /** Persist the edited record. Absent, the editor has no Save. A returned
68
+ * promise holds the Save button busy; the edits clear once it resolves. */
69
+ onSave?: (value: T, edits: Partial<T>) => void | Promise<void>;
70
+ /** Whether the form takes edits (default). Off, it is a viewer. */
71
+ editable?: boolean;
72
+ /** A sheet's actions, scoped to the form (see `editor-actions.ts`): those
73
+ * for a row as the record's, in the footer before Reset and Save; those
74
+ * for a cell or a column, and a field's own column `actions`, beside each
75
+ * field's label. */
76
+ actions?: TableAction<T>[];
77
+ /** Whether to show the actions (default). A sheet's own editors turn them
78
+ * off, where its toolbar already carries them. */
79
+ showActions?: boolean;
80
+ /** Draw the form as a panel: bordered, with a title bar and footer. */
81
+ panel?: boolean;
82
+ title?: ReactNode;
83
+ /** Close the editor — a ✕ in the title bar. */
84
+ onClose?: () => void;
85
+ closeLabel?: string;
86
+ saveLabel?: string;
87
+ showHidden?: boolean;
88
+ hideEmpty?: boolean;
89
+ inline?: boolean;
90
+ className?: string;
91
+ /** Rendered above the fields. */
92
+ header?: ReactNode;
93
+ children?: ReactNode;
94
+ }
95
+
96
+ export function DataEditor<T = any>(props: DataEditorProps<T>) {
97
+ const {
98
+ dataSpec,
99
+ data,
100
+ onEditsChange,
101
+ onSave,
102
+ editable = true,
103
+ actions = [],
104
+ showActions = true,
105
+ panel = false,
106
+ title,
107
+ onClose,
108
+ closeLabel,
109
+ saveLabel = "Save",
110
+ showHidden,
111
+ hideEmpty,
112
+ inline,
113
+ className,
114
+ header,
115
+ children,
116
+ } = props;
117
+
118
+ const [ownEdits, setOwnEdits] = useState<Partial<T>>({});
119
+ const [saving, setSaving] = useState(false);
120
+ // A new record starts clean
121
+ useEffect(() => {
122
+ setOwnEdits({});
123
+ }, [data]);
124
+
125
+ let edits = ownEdits;
126
+ if (props.edits != null) edits = props.edits;
127
+ // The latest edits, so several changes in one event (an action's batch of
128
+ // cells) build on each other rather than on the last render's
129
+ const latest = useRef(edits);
130
+ latest.current = edits;
131
+ const setEdits = (next: Partial<T>) => {
132
+ latest.current = next;
133
+ if (props.edits == null) setOwnEdits(next);
134
+ onEditsChange?.(next);
135
+ };
136
+
137
+ const value = useMemo(() => ({ ...data, ...edits }) as T, [data, edits]);
138
+ const hasChanges = Object.keys(edits).length > 0;
139
+ const errors = useMemo(() => fieldErrors(dataSpec, value), [dataSpec, value]);
140
+
141
+ const setFields = (patch: Record<string, any>) => {
142
+ const updated: any = { ...latest.current };
143
+ for (const [key, next] of Object.entries(patch)) {
144
+ updated[key] = next;
145
+ // A value set back to what was loaded is no edit
146
+ if (valueToken(next) === valueToken((data as any)?.[key])) {
147
+ delete updated[key];
148
+ }
149
+ }
150
+ setEdits(updated);
151
+ };
152
+ const setField = (key: string, next: any) => setFields({ [key]: next });
153
+
154
+ const resetField = (key: string) => {
155
+ const updated: any = { ...latest.current };
156
+ delete updated[key];
157
+ setEdits(updated);
158
+ };
159
+ const reset = () => setEdits({});
160
+
161
+ const save = async () => {
162
+ if (onSave == null || !hasChanges || errors.length > 0) return;
163
+ setSaving(true);
164
+ try {
165
+ await onSave(value, edits);
166
+ setEdits({});
167
+ } finally {
168
+ setSaving(false);
169
+ }
170
+ };
171
+
172
+ // What the actions act on: this record, as a one-row table
173
+ const target: EditorActionTarget<T> = {
174
+ dataSpec,
175
+ data,
176
+ value,
177
+ edits,
178
+ editable,
179
+ setFields,
180
+ reset,
181
+ onSave,
182
+ };
183
+ let usedActions: TableAction<T>[] = [];
184
+ if (showActions) usedActions = actions;
185
+ const record = editorActionsFor(usedActions, target, { kind: "record" });
186
+
187
+ let fieldActions: ((key: string) => ReactNode) | undefined;
188
+ if (usedActions.length > 0 || dataSpec.some((d) => d.actions != null)) {
189
+ fieldActions = (columnKey) => {
190
+ if (!showActions) return null;
191
+ const scoped = editorActionsFor(usedActions, target, {
192
+ kind: "field",
193
+ columnKey,
194
+ });
195
+ return scoped.actions.map((action) =>
196
+ h(EditorActionButton<T>, {
197
+ key: action.id,
198
+ action,
199
+ ctx: scoped.ctx,
200
+ iconOnly: true,
201
+ }),
202
+ );
203
+ };
204
+ }
205
+
206
+ let footer: ReactNode = null;
207
+ if (editable && (onSave != null || record.actions.length > 0)) {
208
+ let errorsTitle: string | undefined;
209
+ if (errors.length > 0) {
210
+ errorsTitle = errors.map((d) => d.message).join("; ");
211
+ }
212
+ footer = h("div.data-editor-footer", [
213
+ record.actions.map((action) =>
214
+ h(EditorActionButton<T>, { key: action.id, action, ctx: record.ctx }),
215
+ ),
216
+ h("span.data-editor-footer-spacer"),
217
+ h(Button, {
218
+ small: true,
219
+ minimal: true,
220
+ icon: "undo",
221
+ text: "Reset",
222
+ disabled: !hasChanges || saving,
223
+ onClick: reset,
224
+ }),
225
+ h.if(onSave != null)(Button, {
226
+ small: true,
227
+ intent: "primary",
228
+ icon: "floppy-disk",
229
+ text: saveLabel,
230
+ loading: saving,
231
+ title: errorsTitle,
232
+ disabled: !hasChanges || errors.length > 0,
233
+ onClick: save,
234
+ }),
235
+ ]);
236
+ }
237
+
238
+ return h(
239
+ DataEditorFrame,
240
+ {
241
+ className: classNames("data-editor", className, { editable }),
242
+ panel,
243
+ title,
244
+ onClose,
245
+ closeLabel,
246
+ footer,
247
+ },
248
+ [
249
+ header,
250
+ h(DataEditorFields<T>, {
251
+ dataSpec,
252
+ rows: [data],
253
+ rowEdits: [edits],
254
+ surface: "editor",
255
+ editable,
256
+ showHidden,
257
+ hideEmpty,
258
+ inline,
259
+ onChange: setField,
260
+ onResetField: resetField,
261
+ fieldActions,
262
+ }),
263
+ children,
264
+ ],
265
+ );
266
+ }
267
+
268
+ /** The fields whose values are errors. */
269
+ function fieldErrors<T>(
270
+ dataSpec: FieldSpec[],
271
+ value: T,
272
+ ): { key: string; message: string }[] {
273
+ const errors: { key: string; message: string }[] = [];
274
+ for (const field of dataSpec) {
275
+ if (field.hidden || !isColumnWritable(field, true)) continue;
276
+ const result = validateCell(field, (value as any)?.[field.key], value, -1);
277
+ if (result?.severity === "error") {
278
+ errors.push({ key: field.key, message: result.message ?? field.name });
279
+ }
280
+ }
281
+ return errors;
282
+ }
283
+
284
+ /* ------------------------------------------------------------ the fields */
285
+
286
+ export interface DataEditorFieldsProps<T = any> {
287
+ /** The fields, in order; hidden ones are left out unless `showHidden`. */
288
+ dataSpec: FieldSpec[];
289
+ /** The records the form stands for — one, or several at once. */
290
+ rows: (T | null | undefined)[];
291
+ /** Edit overlays aligned with `rows`. */
292
+ rowEdits?: (Partial<T> | null | undefined)[];
293
+ /** The rows' data indices, aligned with `rows`, handed to `validate` and
294
+ * `cellDetail`. */
295
+ rowIndices?: number[];
296
+ /** Where the form is drawn, handed to each `cellDetail` as `ctx.surface`. */
297
+ surface: CellDetailContext["surface"];
298
+ /** Whether the form takes edits. */
299
+ editable?: boolean;
300
+ /** A field changed — for every row the form stands for. */
301
+ onChange?: (key: string, value: any) => void;
302
+ /** A field changed row by row, a value per row. */
303
+ onChangeCells?: (key: string, values: any[]) => void;
304
+ /** Revert one field in every row. */
305
+ onResetField?: (key: string) => void;
306
+ /** The only fields that take edits (the rest shown for context); `null`
307
+ * for all. A sheet's cell selection. */
308
+ focusFields?: string[] | null;
309
+ /** A field to mark without narrowing what is editable. */
310
+ activeField?: string | null;
311
+ /** A field was clicked. */
312
+ onFieldClick?: (key: string) => void;
313
+ /** Controls beside a field's label — its actions. */
314
+ fieldActions?: (key: string) => ReactNode;
315
+ showHidden?: boolean;
316
+ hideEmpty?: boolean;
317
+ inline?: boolean;
318
+ }
319
+
320
+ /** A form over one record or several, writing through callbacks. Over
321
+ * several, each field stands for that key in every record: a shared value is
322
+ * shown and edited as one, differing ones read "Multiple values", and a
323
+ * field's own `cellDetail` edits them only when it declares `multiCell`. */
324
+ export function DataEditorFields<T = any>(props: DataEditorFieldsProps<T>) {
325
+ const {
326
+ dataSpec,
327
+ rows,
328
+ rowEdits = [],
329
+ rowIndices = [],
330
+ surface,
331
+ editable = true,
332
+ onChange,
333
+ onChangeCells,
334
+ onResetField,
335
+ focusFields = null,
336
+ activeField = null,
337
+ onFieldClick,
338
+ fieldActions,
339
+ showHidden = false,
340
+ hideEmpty = false,
341
+ inline = false,
342
+ } = props;
343
+
344
+ const merged = useMemo(
345
+ () => rows.map((row, i) => ({ ...(row ?? {}), ...(rowEdits[i] ?? {}) })),
346
+ [rows, rowEdits],
347
+ );
348
+ const several = rows.length > 1;
349
+
350
+ const fieldsShown = useMemo(
351
+ () => dataSpec.filter((field) => showHidden || !field.hidden),
352
+ [dataSpec, showHidden],
353
+ );
354
+
355
+ const canEdit = editable && onChange != null;
356
+ let focus: Set<string> | null = null;
357
+ if (focusFields != null) focus = new Set(focusFields);
358
+
359
+ const fields = fieldsShown.map((col, colIndex) => {
360
+ const values = merged.map((row) => row[col.key]);
361
+ const shared = sharedValue(values);
362
+ let value = shared.value;
363
+ if (shared.mixed) value = undefined;
364
+ const focused = focus == null || focus.has(col.key);
365
+ // A field's own surface edits several records only when it says it can;
366
+ // the default editors always can.
367
+ const canEditSeveral =
368
+ !several || col.cellDetail == null || (col.multiCell ?? false);
369
+ const writable =
370
+ canEdit && focused && canEditSeveral && isColumnWritable(col, true);
371
+ const isEmpty = value == null || value === "";
372
+ if (hideEmpty && isEmpty && !shared.mixed && !writable) return null;
373
+ const isEdited = rowEdits.some((e) => e != null && col.key in e);
374
+ let validation: CellValidation | null = null;
375
+ if (!shared.mixed) {
376
+ validation = validateCell(col, value, merged[0], rowIndices[0] ?? -1);
377
+ }
378
+ const ctx: CellDetailContext = {
379
+ surface,
380
+ value,
381
+ rowIndex: rowIndices[0] ?? -1,
382
+ colIndex,
383
+ column: col,
384
+ row: merged[0],
385
+ isEdited,
386
+ isDeleted: false,
387
+ status: undefined,
388
+ validation,
389
+ editable: writable,
390
+ onChange(next) {
391
+ if (!writable) return;
392
+ onChange?.(col.key, next);
393
+ },
394
+ resetValue() {
395
+ onResetField?.(col.key);
396
+ },
397
+ close() {},
398
+ };
399
+ if (several) {
400
+ ctx.cells = rows.map((row, i): CellSelectionEntry => ({
401
+ rowIndex: rowIndices[i] ?? -1,
402
+ row: merged[i],
403
+ value: values[i],
404
+ }));
405
+ ctx.mixed = shared.mixed;
406
+ if (onChangeCells != null) {
407
+ ctx.onChangeCells = (next) => {
408
+ if (!writable) return;
409
+ onChangeCells(col.key, next);
410
+ };
411
+ }
412
+ }
413
+ let onClick: (() => void) | undefined;
414
+ if (onFieldClick != null) onClick = () => onFieldClick(col.key);
415
+ let onReset: (() => void) | null = null;
416
+ if (isEdited && onResetField != null) onReset = ctx.resetValue;
417
+ return h(DataEditorField, {
418
+ key: col.key,
419
+ ctx,
420
+ inline,
421
+ onClick,
422
+ actions: fieldActions?.(col.key),
423
+ selected:
424
+ (focus != null && focus.has(col.key)) || activeField === col.key,
425
+ onReset,
426
+ });
427
+ });
428
+
429
+ return h(
430
+ "div.row-editor-fields",
431
+ { className: classNames({ editable: canEdit, inline, several }) },
432
+ fields,
433
+ );
434
+ }
435
+
436
+ /* ------------------------------------------------------------- the frame */
437
+
438
+ /** The form's frame: as a panel, a title bar over a scrolling body and an
439
+ * optional footer; otherwise the body (and footer) alone. The title bar is
440
+ * the sheet toolbar's selection tag at full width — minimal, large, primary —
441
+ * and its ✕ is the tag's own. */
442
+ export function DataEditorFrame({
443
+ panel = false,
444
+ title,
445
+ onClose,
446
+ closeLabel = "Close",
447
+ footer,
448
+ className,
449
+ children,
450
+ }: {
451
+ panel?: boolean;
452
+ title?: ReactNode;
453
+ onClose?: () => void;
454
+ closeLabel?: string;
455
+ footer?: ReactNode;
456
+ className?: string;
457
+ children?: ReactNode;
458
+ }) {
459
+ let titleBar: ReactNode = null;
460
+ if (panel && (title != null || onClose != null)) {
461
+ titleBar = h(
462
+ Tag,
463
+ {
464
+ minimal: true,
465
+ large: true,
466
+ fill: true,
467
+ intent: "primary",
468
+ className: "row-editor-title-bar",
469
+ onRemove: onClose,
470
+ removeButtonProps: { title: closeLabel, "aria-label": closeLabel },
471
+ } as any,
472
+ title,
473
+ );
474
+ }
475
+ return h("div.row-editor", { className: classNames(className, { panel }) }, [
476
+ titleBar,
477
+ h("div.row-editor-body", children),
478
+ footer,
479
+ ]);
480
+ }
481
+
482
+ /* ---------------------------------------------------------- shared values */
483
+
484
+ /** The value a set of cells share, or that they differ. Structured values
485
+ * compare by their JSON form, so two equal lithology arrays count as one. */
486
+ export function sharedValue(values: any[]): { value: any; mixed: boolean } {
487
+ if (values.length === 0) return { value: undefined, mixed: false };
488
+ const first = values[0];
489
+ const key = valueToken(first);
490
+ for (const v of values.slice(1)) {
491
+ if (valueToken(v) !== key) return { value: undefined, mixed: true };
492
+ }
493
+ return { value: first, mixed: false };
494
+ }
495
+
496
+ export function valueToken(value: any): string {
497
+ if (value == null || value === "") return "";
498
+ if (typeof value === "object") return JSON.stringify(value);
499
+ return String(value);
500
+ }
501
+
502
+ /* ------------------------------------------------------------------ field */
503
+
504
+ interface DataEditorFieldProps {
505
+ ctx: CellDetailContext;
506
+ inline?: boolean;
507
+ /** Controls after the label: the field's actions. */
508
+ actions?: ReactNode;
509
+ /** A click anywhere in the field. */
510
+ onClick?: () => void;
511
+ /** Part of the cell selection the form is focused on. */
512
+ selected?: boolean;
513
+ onReset?: (() => void) | null;
514
+ }
515
+
516
+ /** One field: the column's name, a marker for what kind of value it is, the
517
+ * value or its editor, and any validation message. */
518
+ export function DataEditorField({
519
+ ctx,
520
+ inline,
521
+ selected = false,
522
+ onReset,
523
+ onClick,
524
+ actions,
525
+ }: DataEditorFieldProps) {
526
+ const { column: col, validation, isEdited, editable, mixed } = ctx;
527
+
528
+ let intent: Intent | undefined;
529
+ if (validation?.severity === "error") {
530
+ intent = "danger";
531
+ } else if (validation?.severity === "warning") {
532
+ intent = "warning";
533
+ }
534
+
535
+ let marker: ReactNode = null;
536
+ if (col.derived) {
537
+ marker = h(
538
+ Tag,
539
+ {
540
+ minimal: true,
541
+ icon: "function",
542
+ className: "field-marker",
543
+ title: "Derived — computed from other values",
544
+ },
545
+ "derived",
546
+ );
547
+ } else if (col.required && editable) {
548
+ marker = h("span.required-marker", { title: "Required" }, "*");
549
+ }
550
+
551
+ let reset: ReactNode = null;
552
+ if (onReset != null) {
553
+ reset = h(Button, {
554
+ icon: "undo",
555
+ minimal: true,
556
+ small: true,
557
+ className: "reset-field",
558
+ title: "Revert to the loaded value",
559
+ onClick: onReset,
560
+ });
561
+ }
562
+
563
+ const label = h("span.field-label", [
564
+ h("span.field-name", col.name),
565
+ marker,
566
+ reset,
567
+ h.if(actions != null)("span.field-actions", actions),
568
+ ]);
569
+
570
+ // The wrapper takes no space (`display: contents`); it catches the click
571
+ // Blueprint's FormGroup doesn't pass through
572
+ return h(
573
+ "div.row-editor-field-target",
574
+ { onClick },
575
+ h(
576
+ FormGroup,
577
+ {
578
+ label,
579
+ inline,
580
+ intent,
581
+ helperText: validation?.message,
582
+ className: classNames("row-editor-field", {
583
+ edited: isEdited,
584
+ derived: col.derived,
585
+ selected,
586
+ mixed,
587
+ "read-only": !editable,
588
+ [`data-type-${col.dataType ?? "string"}`]: true,
589
+ }),
590
+ },
591
+ h(FieldSurface, { ctx }),
592
+ ),
593
+ );
594
+ }
595
+
596
+ /** The value or its editor: the column's own `cellDetail` when it has one
597
+ * (the unified surface, which is an editor when `ctx.editable`), else a
598
+ * default by `dataType`. A surface that can't stand for several cells shows
599
+ * the shared value, or "Multiple values". */
600
+ function FieldSurface({ ctx }: { ctx: CellDetailContext }) {
601
+ const { column: col, editable } = ctx;
602
+ const several = ctx.cells != null;
603
+ if (col.cellDetail != null && (!several || col.multiCell)) {
604
+ return h("div.field-surface.cell-detail", col.cellDetail(ctx));
605
+ }
606
+ if (!editable) {
607
+ return h(FieldValue, { ctx });
608
+ }
609
+ return h(DefaultFieldEditor, { ctx });
610
+ }
611
+
612
+ /** The read-only rendering of a value, through the column's renderer. */
613
+ export function FieldValue({ ctx }: { ctx: CellDetailContext }) {
614
+ const { value, column: col } = ctx;
615
+ if (ctx.mixed) {
616
+ return h(MixedValues, { ctx });
617
+ }
618
+ if (value == null || value === "") {
619
+ return h("span.field-value.empty", "—");
620
+ }
621
+ const rendered = col.valueRenderer?.(value, ctx) ?? String(value);
622
+ return h("span.field-value", rendered);
623
+ }
624
+
625
+ /** "Multiple values", naming how many distinct ones the cells hold. */
626
+ export function MixedValues({ ctx }: { ctx: CellDetailContext }) {
627
+ const distinct = new Set((ctx.cells ?? []).map((c) => valueToken(c.value)));
628
+ return h(
629
+ "span.field-value.mixed-values",
630
+ {
631
+ title: `${distinct.size} distinct values across ${ctx.cells?.length} rows`,
632
+ },
633
+ "Multiple values",
634
+ );
635
+ }
636
+
637
+ function DefaultFieldEditor({ ctx }: { ctx: CellDetailContext }) {
638
+ const { value, column: col, onChange, mixed } = ctx;
639
+ const type = col.dataType ?? "string";
640
+ const placeholder = mixed ? "Multiple values" : undefined;
641
+
642
+ if (type === "boolean") {
643
+ return h(Switch, {
644
+ checked: Boolean(value),
645
+ // An indeterminate switch has no Blueprint form; say so beside it.
646
+ label: mixed ? "Multiple values" : undefined,
647
+ onChange: (evt: any) => onChange(evt.target.checked),
648
+ className: "field-switch",
649
+ });
650
+ }
651
+ if (type === "text") {
652
+ return h(CommittedTextArea, { value, placeholder, onCommit: onChange });
653
+ }
654
+ if (type === "number" || type === "integer") {
655
+ return h(CommittedInput, {
656
+ value,
657
+ placeholder,
658
+ onCommit: (text: string) => onChange(parseNumber(text, type)),
659
+ type: "number",
660
+ step: type === "integer" ? 1 : "any",
661
+ });
662
+ }
663
+ if (type === "object" || type === "array") {
664
+ // No default editor for structured values: the column should supply a
665
+ // `cellDetail`. Show the value so the form is still complete.
666
+ return h(FieldValue, { ctx });
667
+ }
668
+ return h(CommittedInput, { value, placeholder, onCommit: onChange });
669
+ }
670
+
671
+ function parseNumber(text: string, type: "number" | "integer") {
672
+ if (text === "" || text == null) return null;
673
+ const n = type === "integer" ? parseInt(text, 10) : parseFloat(text);
674
+ if (isNaN(n)) return text;
675
+ return n;
676
+ }
677
+
678
+ /** An input that commits on blur or Enter rather than on every keystroke, the
679
+ * way a sheet cell does — so a half-typed number doesn't move a column. */
680
+ function CommittedInput({
681
+ value,
682
+ onCommit,
683
+ ...rest
684
+ }: {
685
+ value: any;
686
+ onCommit: (text: string) => void;
687
+ [key: string]: any;
688
+ }) {
689
+ const [text, setText] = useState(toText(value));
690
+ useEffect(() => {
691
+ setText(toText(value));
692
+ }, [value]);
693
+ const commit = () => {
694
+ if (text === toText(value)) return;
695
+ onCommit(text);
696
+ };
697
+ return h(InputGroup, {
698
+ small: true,
699
+ fill: true,
700
+ value: text,
701
+ onValueChange: setText,
702
+ onBlur: commit,
703
+ onKeyDown(evt) {
704
+ if (evt.key === "Enter") commit();
705
+ if (evt.key === "Escape") setText(toText(value));
706
+ },
707
+ ...rest,
708
+ });
709
+ }
710
+
711
+ function CommittedTextArea({
712
+ value,
713
+ onCommit,
714
+ placeholder,
715
+ }: {
716
+ value: any;
717
+ onCommit: (text: string) => void;
718
+ placeholder?: string;
719
+ }) {
720
+ const [text, setText] = useState(toText(value));
721
+ useEffect(() => {
722
+ setText(toText(value));
723
+ }, [value]);
724
+ return h(TextArea, {
725
+ small: true,
726
+ fill: true,
727
+ autoResize: true,
728
+ placeholder,
729
+ value: text,
730
+ onChange: (evt: any) => setText(evt.target.value),
731
+ onBlur() {
732
+ if (text === toText(value)) return;
733
+ onCommit(text);
734
+ },
735
+ });
736
+ }
737
+
738
+ function toText(value: any): string {
739
+ if (value == null) return "";
740
+ return String(value);
741
+ }