@macrostrat/data-sheet 4.9.0 → 4.10.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 (58) hide show
  1. package/CHANGELOG.md +70 -31
  2. package/dist/actions/selection.cjs +5 -1
  3. package/dist/actions/selection.cjs.map +1 -1
  4. package/dist/actions/selection.d.ts +7 -1
  5. package/dist/actions/selection.js +5 -1
  6. package/dist/actions/selection.js.map +1 -1
  7. package/dist/components/editor-actions.cjs +1 -1
  8. package/dist/components/editor-actions.cjs.map +1 -1
  9. package/dist/components/editor-actions.js +2 -2
  10. package/dist/components/editor-actions.js.map +1 -1
  11. package/dist/components/indicators/unified-filters.cjs +3 -0
  12. package/dist/components/indicators/unified-filters.cjs.map +1 -1
  13. package/dist/components/indicators/unified-filters.js +3 -0
  14. package/dist/components/indicators/unified-filters.js.map +1 -1
  15. package/dist/components/toolbars/actions-toolbar.cjs +5 -2
  16. package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
  17. package/dist/components/toolbars/actions-toolbar.js +6 -3
  18. package/dist/components/toolbars/actions-toolbar.js.map +1 -1
  19. package/dist/data-sheet.cjs +4 -0
  20. package/dist/data-sheet.cjs.map +1 -1
  21. package/dist/data-sheet.css +38 -22
  22. package/dist/data-sheet.js +4 -0
  23. package/dist/data-sheet.js.map +1 -1
  24. package/dist/index.cjs +15 -14
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.js +2 -1
  27. package/dist/main.module.sass.cjs +14 -14
  28. package/dist/main.module.sass.js +14 -14
  29. package/dist/provider/column-spec.cjs.map +1 -1
  30. package/dist/provider/column-spec.d.ts +8 -0
  31. package/dist/provider/column-spec.js.map +1 -1
  32. package/dist/provider/types.cjs.map +1 -1
  33. package/dist/provider/types.d.ts +11 -0
  34. package/dist/provider/types.js.map +1 -1
  35. package/dist/provider/zustand-store.cjs +40 -24
  36. package/dist/provider/zustand-store.cjs.map +1 -1
  37. package/dist/provider/zustand-store.js +40 -24
  38. package/dist/provider/zustand-store.js.map +1 -1
  39. package/dist/renderers/cell-renderer.cjs +9 -2
  40. package/dist/renderers/cell-renderer.cjs.map +1 -1
  41. package/dist/renderers/cell-renderer.js +9 -2
  42. package/dist/renderers/cell-renderer.js.map +1 -1
  43. package/dist/utils/key-handling.cjs +6 -5
  44. package/dist/utils/key-handling.cjs.map +1 -1
  45. package/dist/utils/key-handling.js +2 -1
  46. package/dist/utils/key-handling.js.map +1 -1
  47. package/package.json +2 -2
  48. package/src/actions/selection.ts +11 -2
  49. package/src/components/editor-actions.ts +5 -2
  50. package/src/components/indicators/unified-filters.ts +3 -0
  51. package/src/components/toolbars/actions-toolbar.ts +10 -4
  52. package/src/data-sheet.ts +6 -0
  53. package/src/main.module.sass +14 -0
  54. package/src/provider/column-spec.ts +8 -0
  55. package/src/provider/types.ts +15 -1
  56. package/src/provider/zustand-store.ts +58 -28
  57. package/src/renderers/cell-renderer.ts +12 -0
  58. package/src/utils/key-handling.ts +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cell-renderer.js","sources":["../../src/renderers/cell-renderer.ts"],"sourcesContent":["import type {\n ColumnSpec,\n CellRenderContext,\n CellDetailContext,\n DataSheetStore,\n} from \"../provider\";\nimport { TableElementStatus } from \"../provider\";\nimport { editorKeyHandlerAtom, validateCell } from \"../utils\";\nimport h from \"../main.module.sass\";\nimport { memo, ReactNode, useEffect, useRef, useState } from \"react\";\nimport { EditorPopup, CellDetailModal } from \"../components\";\nimport { singleFocusedCell } from \"../provider\";\nimport { Cell } from \"@blueprintjs/table\";\nimport { ctx, dragValueHandlerAtom, useSelector } from \"../provider\";\nimport { Intent } from \"@blueprintjs/core\";\nimport classNames from \"classnames\";\n\n/** Two validations are equivalent if they convey the same thing — so a fresh\n * `validateCell` result object doesn't force a re-render when nothing changed. */\nfunction validationEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return a == b;\n return a.severity === b.severity && a.message === b.message;\n}\n\n/** Memoize on the *fields* of `cellContext` (not its identity — it's rebuilt\n * fresh each render), so an unchanged cell skips re-rendering. */\nfunction cellContentsEqual(\n a: { cellContext: CellRenderContext },\n b: { cellContext: CellRenderContext },\n): boolean {\n const x = a.cellContext;\n const y = b.cellContext;\n return (\n x.column === y.column &&\n x.value === y.value &&\n x.row === y.row &&\n x.rowIndex === y.rowIndex &&\n x.colIndex === y.colIndex &&\n x.isEdited === y.isEdited &&\n x.isDeleted === y.isDeleted &&\n x.status === y.status &&\n validationEqual(x.validation, y.validation)\n );\n}\n\n/** The rendered *content* of a read-only cell — the value renderer's output —\n * memoized on the cell's own inputs. It is placed as the CHILD of a real\n * Blueprint `Cell` (never a wrapper: Blueprint clones the returned `Cell` to\n * position/size it, so the renderer must return a `Cell` directly). This lets a\n * re-render from unrelated state — the focused cell moving, or a\n * scroll-triggered data load that swaps the `data`/overlay arrays — reposition\n * the lightweight `Cell` without re-running this (possibly heavy) value\n * renderer; only cells whose own value/status changed re-render. */\nconst CellContent = memo(function CellContent({\n cellContext,\n}: {\n cellContext: CellRenderContext;\n}) {\n const { value, column } = cellContext;\n if (value == null || value === \"\") return null;\n return column.valueRenderer?.(value, cellContext) ?? value;\n}, cellContentsEqual);\n\nexport function basicCellRenderer<T>(\n rowIndex: number,\n colIndex: number,\n columnSpec: ColumnSpec,\n state: DataSheetStore<T>,\n filteredRowIndices?: number[] | null,\n): any {\n // Auto-activation is on when the mode is \"auto\" and it hasn't been suppressed\n // (Escape enters navigation mode until the next click).\n // Whether the inline editor grabs focus. It follows the store-owned surface\n // open state, so it focuses on selection in auto mode and on click in manual\n // mode, and not at all in navigation mode. The popover surfaces read the\n // same state directly.\n const focusOnOpen = state.cellSurfaceOpen;\n // When filters are active, `rowIndex` is the visible row position.\n // Map it to the actual data index for data access.\n const dataRowIndex =\n filteredRowIndices != null\n ? (filteredRowIndices[rowIndex] ?? rowIndex)\n : rowIndex;\n\n const data = state.data;\n const updatedData = state.updatedData;\n\n const statusVal = state.rowStatus[dataRowIndex];\n const isDeleted = statusVal == TableElementStatus.DELETED;\n // Presentation for this row's status (deleted, or a consumer-defined status\n // like \"omitted\"), from the merged `rowStatusStyles`.\n const statusStyle =\n statusVal != null ? state.rowStatusStyles?.[statusVal] : undefined;\n\n const row = data[dataRowIndex] ?? updatedData[dataRowIndex];\n const loading = row == null;\n const col = columnSpec;\n\n const _topLeftCell = state.topLeftCell;\n const onCellEdited = state.onCellEdited;\n\n const value: T | undefined =\n updatedData[dataRowIndex]?.[col.key] ?? data[dataRowIndex]?.[col.key];\n\n const edited =\n updatedData[dataRowIndex]?.[col.key] != null ||\n state.rowStatus[dataRowIndex] === TableElementStatus.ADDED;\n\n // Validate the cell (skipped for deleted rows). Orthogonal to edit status.\n const validation = isDeleted\n ? null\n : validateCell(col, value, row, dataRowIndex);\n\n // A derived column is never writable, whatever `editable` says — see\n // `isColumnWritable`, which every write path in the store applies too.\n const editable =\n (col.editable ?? state.editable) && !isDeleted && !col.derived;\n const tableIsEditable = state.editable;\n\n // topLeftCell stores visible row indices, so compare with the visible rowIndex\n const topLeft =\n _topLeftCell?.col === colIndex && _topLeftCell?.row === rowIndex;\n\n // Intent precedence: error > warning > row-status intent > edited. Validation\n // state overrides the edited-green so an edited-but-invalid cell reads as\n // invalid. A row's status intent (e.g. deleted → danger) outranks the\n // edited-green so status reads through even on an edited row.\n let intent: Intent | undefined;\n if (validation?.severity === \"error\") {\n intent = \"danger\";\n } else if (validation?.severity === \"warning\") {\n intent = \"warning\";\n } else if (statusStyle?.intent != null) {\n intent = statusStyle.intent;\n } else if (edited) {\n intent = \"success\";\n }\n\n // One context object, assembled once and threaded through every path (fast,\n // slow, focused). `rowIndex` is the data-row index, stable under sort/filter.\n const cellContext: CellRenderContext<T> = {\n value,\n rowIndex: dataRowIndex,\n colIndex,\n column: col,\n row,\n isEdited: edited,\n isDeleted,\n status: statusVal,\n validation,\n };\n\n // Only allocate a new style object when a row-status style must be layered on\n // (deleted → dimmed/struck-through; consumer statuses supply their own\n // `cellStyle`). The common case passes the column's own `style` straight\n // through — no per-cell clone, and a stable identity that diffs cheaply.\n // (Nothing downstream mutates `style`.)\n const style =\n statusStyle?.cellStyle != null\n ? { ...col.style, ...statusStyle.cellStyle }\n : col.style;\n\n const detailPresentation =\n col.cellDetail != null ? (col.detailPresentation ?? \"popover\") : null;\n\n // Derived values are drawn dimmed, so a reader can tell a record from a\n // restatement of one. Applied on every path below.\n const derivedClass = col.derived ? \"derived-cell\" : undefined;\n\n // Fast path — any non-focused cell whose *unfocused* appearance is just the\n // value viewer (a plain Blueprint `Cell`). That's everything except a custom\n // `cellComponent` (its own markup on every cell) and an *inline* `cellDetail`\n // (a persistent in-cell surface). A `cellDetail` popover/modal or a\n // `detailRenderer` only surfaces on the focused cell, so unfocused they show\n // the value viewer too — and take the fast path. Return a real `Cell`\n // (Blueprint clones it to position/size it) whose CHILD is the memoized\n // content, so unrelated re-renders (focus moving, a data load that swaps the\n // arrays) reposition the cheap `Cell` without re-running the value renderer.\n const usesCustomCell =\n col.cellComponent != null || detailPresentation === \"inline\";\n if (!topLeft && !usesCustomCell) {\n return h(\n Cell,\n {\n intent,\n loading,\n //value,\n style,\n className: derivedClass,\n interactive: false,\n //disabled: tableIsEditable && !editable,\n },\n h(CellContent, { cellContext }),\n );\n }\n\n const isEmpty = value == null || value === \"\";\n\n const _renderedValue: any = isEmpty\n ? null\n : (col.valueRenderer?.(value, cellContext) ?? value);\n\n const _Cell = col.cellComponent ?? Cell;\n\n // Only forward the render context to a custom cell component; the default\n // Blueprint Cell would spread unknown props onto the DOM.\n const cellComponentProps = col.cellComponent != null ? { cellContext } : {};\n\n // Allow a column to pick the editor per-cell (e.g. textarea only when the\n // value is long). A returned key overrides the static column field even\n // when its value is false/null, so use `in` rather than nullish-coalesce.\n const perCellEditors = col.editorForCell?.(cellContext);\n const dataEditorSpec =\n perCellEditors != null && \"dataEditor\" in perCellEditors\n ? perCellEditors.dataEditor\n : col.dataEditor;\n const inlineEditorSpec =\n perCellEditors != null && \"inlineEditor\" in perCellEditors\n ? perCellEditors.inlineEditor\n : col.inlineEditor;\n\n let inlineEditor = editable ? (inlineEditorSpec ?? true) : false;\n\n // Build the detail context for the unified `cellDetail` surface.\n const makeDetailCtx = (editableFlag: boolean): CellDetailContext<T> => ({\n ...cellContext,\n surface: \"cell\",\n editable: editableFlag,\n onChange(v: any) {\n if (editableFlag) onCellEdited(dataRowIndex, col.key, v);\n },\n resetValue() {\n state.resetChanges();\n },\n close() {\n state.closeCellSurface();\n state.tableElement?.focus?.();\n },\n });\n\n if (!topLeft) {\n // Non-focused cell that took the slow path — a custom `cellComponent`, or a\n // `cellDetail` / `detailRenderer` surface. An inline surface is a persistent\n // in-cell renderer (read-only here); others show the value viewer. (The\n // plain default-`Cell` case is handled by the memoized fast path above.)\n if (detailPresentation === \"inline\") {\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: \"value-viewer-cell\",\n interactive: false,\n ...cellComponentProps,\n },\n col.cellDetail!(makeDetailCtx(false)),\n );\n }\n return h(\n _Cell,\n {\n intent,\n loading,\n value,\n style,\n className: derivedClass,\n disabled: tableIsEditable && !editable,\n interactive: false,\n ...cellComponentProps,\n },\n _renderedValue,\n );\n }\n\n // The rest is for the top-left cell of a selection or the focused cell\n\n // Unified cell surface: one renderer that acts as editor (when editable) or\n // viewer (otherwise), presented as a popover / modal / inline. Supersedes\n // dataEditor / detailRenderer / editorForCell.\n if (col.cellDetail != null) {\n const content = col.cellDetail(makeDetailCtx(editable));\n\n if (detailPresentation === \"inline\") {\n // Persistent in-cell surface (editable on the focused cell). No popover.\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: editable ? \"input-cell\" : \"value-viewer-cell\",\n interactive: editable,\n ...cellComponentProps,\n },\n content,\n );\n }\n\n if (detailPresentation === \"modal\") {\n // CellDetailModal subscribes to the store so the dialog closes reactively.\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: \"value-viewer-cell\",\n interactive: false,\n ...cellComponentProps,\n },\n h(\n CellDetailModal,\n { title: col.name, valueViewer: _renderedValue },\n content,\n ),\n );\n }\n\n // Default: popover (same open/close machinery as editors and panels).\n const panel = h(\n EditorPopup,\n { valueViewer: _renderedValue, placement: col.detailPlacement },\n content,\n );\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: \"editor-cell\",\n interactive: editable,\n ...cellComponentProps,\n },\n panel,\n );\n }\n\n // Read-only detail panel: a surface that opens on selection (auto) or click,\n // shows arbitrary content, and never takes keyboard focus — so arrow keys\n // keep navigating the table. Uses the same open/close machinery as editors.\n if (col.detailRenderer != null) {\n const panel = h(\n EditorPopup,\n { valueViewer: _renderedValue },\n col.detailRenderer(cellContext),\n );\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n // Use the editor-cell popover layout so the target fills the cell\n // without the double-padding offset of `value-viewer-cell`.\n className: \"editor-cell\",\n interactive: false,\n ...cellComponentProps,\n },\n panel,\n );\n }\n\n let cellContents: any = _renderedValue;\n\n let _dataEditor: ReactNode = null;\n let className: string | null = null;\n\n if (dataEditorSpec != null) {\n _dataEditor = h(\n EditorPopup,\n {\n valueViewer: _renderedValue,\n },\n [\n h(dataEditorSpec, {\n value,\n editable,\n isEdited: edited,\n onChange(value) {\n if (!editable) return;\n // Commit to THIS cell — not the live selection. The editor can\n // commit (e.g. on blur) after the selection has moved to another\n // cell or a whole column; `onSelectionEdited` would then write the\n // value to the wrong target (emptying it). `onCellEdited` addresses\n // the editor's own data cell.\n state.onCellEdited(dataRowIndex, col.key, value);\n },\n resetValue() {\n state.resetChanges();\n },\n }),\n ],\n );\n }\n\n if (!editable) {\n if (_dataEditor != null) {\n cellContents = _dataEditor;\n }\n const className = classNames(\"value-viewer-cell\", derivedClass);\n\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className,\n interactive: false,\n ...cellComponentProps,\n },\n cellContents,\n );\n }\n\n /* The remaining logic covers cells that are focused and editable */\n\n const onChange = (e) => {\n if (!editable) return;\n if (_renderedValue === e.target.value) return;\n // Use dataRowIndex for the actual data mutation\n onCellEdited(dataRowIndex, col.key, e.target.value);\n };\n\n const isSingleCellSelection = singleFocusedCell(state.selection) != null;\n\n let _inlineEditor: ReactNode = null;\n if (typeof inlineEditor == \"boolean\") {\n let _value: any = value;\n if (\n typeof _renderedValue === \"string\" ||\n typeof _renderedValue === \"number\" ||\n _renderedValue == null\n ) {\n _value = _renderedValue;\n }\n _inlineEditor = h(EditorInput, {\n className: \"main-editor\",\n value: _value ?? \"\",\n autoFocus: focusOnOpen,\n onChange,\n });\n } else {\n // If inlineEditor is a ReactNode, we use it directly\n _inlineEditor = inlineEditor as ReactNode;\n }\n\n let hiddenInput: React.ReactNode = h(EditorInput, {\n className: \"hidden-input\",\n autoFocus: true,\n });\n\n if (_dataEditor != null) {\n className = \"editor-cell\";\n cellContents = _dataEditor;\n hiddenInput = null;\n } else if (_inlineEditor != null) {\n cellContents = _inlineEditor;\n className = \"input-cell\";\n hiddenInput = null;\n }\n\n // Hidden html input\n return h(\n _Cell,\n {\n intent,\n value,\n className,\n style,\n interactive: true,\n ...cellComponentProps,\n //truncated: false,\n },\n [\n cellContents,\n h.if(editable && isSingleCellSelection)(CornerDragHandle),\n //hiddenInput,\n ],\n );\n}\n\nfunction EditorInput(props) {\n const { value, onChange, ...rest } = props;\n const onKeyDown = ctx.useValue(editorKeyHandlerAtom);\n const navDirection = useSelector((s) => s.lastNavDirection);\n const surfaceOpen = useSelector((s) => s.cellSurfaceOpen);\n const inputRef = useRef<HTMLInputElement>(null);\n const [_value, setValue] = useState(value);\n useEffect(() => {\n setValue(value);\n }, [value]);\n useEffect(() => {\n // Focus when the cell's surface is open (on mount, and when reopened via\n // click/F2 while already mounted), placing the cursor on the side we're\n // travelling toward so another arrow in that direction leaves the cell.\n const el = inputRef.current;\n if (el == null || !surfaceOpen) return;\n el.focus();\n const atStart = navDirection === \"up\" || navDirection === \"left\";\n const pos = atStart ? 0 : (el.value?.length ?? 0);\n el.setSelectionRange(pos, pos);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [surfaceOpen]);\n return h(\"input\", {\n ref: inputRef,\n onKeyDown,\n onBlur: onChange,\n value: _value ?? value,\n onChange: (e) => setValue(e.target.value),\n ...rest,\n });\n}\n\nfunction CornerDragHandle() {\n // TODO: we might want to drag multiple columns in some cases\n // This should be on the last cell of a selection\n const onDragValue = ctx.useValue(dragValueHandlerAtom);\n if (onDragValue == null) return null;\n\n return h(\"div.corner-drag-handle\", {\n onMouseDown: onDragValue,\n });\n}\n"],"names":["CellContent","value","className"],"mappings":";;;;;;;;;;;;AAmBA,SAAS,gBAAgB,GAAQ,GAAiB;AAChD,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,KAAK,QAAQ,KAAK,aAAa,KAAK;AACxC,SAAO,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE;AACtD;AAIA,SAAS,kBACP,GACA,GACS;AACT,QAAM,IAAI,EAAE;AACZ,QAAM,IAAI,EAAE;AACZ,SACE,EAAE,WAAW,EAAE,UACf,EAAE,UAAU,EAAE,SACd,EAAE,QAAQ,EAAE,OACZ,EAAE,aAAa,EAAE,YACjB,EAAE,aAAa,EAAE,YACjB,EAAE,aAAa,EAAE,YACjB,EAAE,cAAc,EAAE,aAClB,EAAE,WAAW,EAAE,UACf,gBAAgB,EAAE,YAAY,EAAE,UAAU;AAE9C;AAUA,MAAM,cAAc,KAAK,SAASA,aAAY;AAAA,EAC5C;AACF,GAEG;AACD,QAAM,EAAE,OAAO,OAAA,IAAW;AAC1B,MAAI,SAAS,QAAQ,UAAU,GAAI,QAAO;AAC1C,SAAO,OAAO,gBAAgB,OAAO,WAAW,KAAK;AACvD,GAAG,iBAAiB;AAEb,SAAS,kBACd,UACA,UACA,YACA,OACA,oBACK;AAOL,QAAM,cAAc,MAAM;AAG1B,QAAM,eACJ,sBAAsB,OACjB,mBAAmB,QAAQ,KAAK,WACjC;AAEN,QAAM,OAAO,MAAM;AACnB,QAAM,cAAc,MAAM;AAE1B,QAAM,YAAY,MA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AAU;AAAA,IACjB,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA,IACxC,GAAG;AAAA,EAAA,CACJ;AACH;AAEA,SAAS,mBAAmB;AAG1B,QAAM,cAAc,IAAI,SAAS,oBAAoB;AACrD,MAAI,eAAe,KAAM,QAAO;AAEhC,SAAO,EAAE,0BAA0B;AAAA,IACjC,aAAa;AAAA,EAAA,CACd;AACH;"}
1
+ {"version":3,"file":"cell-renderer.js","sources":["../../src/renderers/cell-renderer.ts"],"sourcesContent":["import type {\n ColumnSpec,\n CellRenderContext,\n CellDetailContext,\n DataSheetStore,\n} from \"../provider\";\nimport { TableElementStatus } from \"../provider\";\nimport { editorKeyHandlerAtom, validateCell } from \"../utils\";\nimport h from \"../main.module.sass\";\nimport { memo, ReactNode, useEffect, useRef, useState } from \"react\";\nimport { EditorPopup, CellDetailModal } from \"../components\";\nimport { singleFocusedCell } from \"../provider\";\nimport { Cell } from \"@blueprintjs/table\";\nimport { ctx, dragValueHandlerAtom, useSelector } from \"../provider\";\nimport { Intent } from \"@blueprintjs/core\";\nimport classNames from \"classnames\";\n\n/** Two validations are equivalent if they convey the same thing — so a fresh\n * `validateCell` result object doesn't force a re-render when nothing changed. */\nfunction validationEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return a == b;\n return a.severity === b.severity && a.message === b.message;\n}\n\n/** Memoize on the *fields* of `cellContext` (not its identity — it's rebuilt\n * fresh each render), so an unchanged cell skips re-rendering. */\nfunction cellContentsEqual(\n a: { cellContext: CellRenderContext },\n b: { cellContext: CellRenderContext },\n): boolean {\n const x = a.cellContext;\n const y = b.cellContext;\n return (\n x.column === y.column &&\n x.value === y.value &&\n x.row === y.row &&\n x.rowIndex === y.rowIndex &&\n x.colIndex === y.colIndex &&\n x.isEdited === y.isEdited &&\n x.isDeleted === y.isDeleted &&\n x.status === y.status &&\n x.width === y.width &&\n x.height === y.height &&\n validationEqual(x.validation, y.validation)\n );\n}\n\n/** The rendered *content* of a read-only cell — the value renderer's output —\n * memoized on the cell's own inputs. It is placed as the CHILD of a real\n * Blueprint `Cell` (never a wrapper: Blueprint clones the returned `Cell` to\n * position/size it, so the renderer must return a `Cell` directly). This lets a\n * re-render from unrelated state — the focused cell moving, or a\n * scroll-triggered data load that swaps the `data`/overlay arrays — reposition\n * the lightweight `Cell` without re-running this (possibly heavy) value\n * renderer; only cells whose own value/status changed re-render. */\nconst CellContent = memo(function CellContent({\n cellContext,\n}: {\n cellContext: CellRenderContext;\n}) {\n const { value, column } = cellContext;\n if (value == null || value === \"\") return null;\n return column.valueRenderer?.(value, cellContext) ?? value;\n}, cellContentsEqual);\n\nexport function basicCellRenderer<T>(\n rowIndex: number,\n colIndex: number,\n columnSpec: ColumnSpec,\n state: DataSheetStore<T>,\n filteredRowIndices?: number[] | null,\n): any {\n // Auto-activation is on when the mode is \"auto\" and it hasn't been suppressed\n // (Escape enters navigation mode until the next click).\n // Whether the inline editor grabs focus. It follows the store-owned surface\n // open state, so it focuses on selection in auto mode and on click in manual\n // mode, and not at all in navigation mode. The popover surfaces read the\n // same state directly.\n const focusOnOpen = state.cellSurfaceOpen;\n // When filters are active, `rowIndex` is the visible row position.\n // Map it to the actual data index for data access.\n const dataRowIndex =\n filteredRowIndices != null\n ? (filteredRowIndices[rowIndex] ?? rowIndex)\n : rowIndex;\n\n const data = state.data;\n const updatedData = state.updatedData;\n\n const statusVal = state.rowStatus[dataRowIndex];\n const isDeleted = statusVal == TableElementStatus.DELETED;\n // Presentation for this row's status (deleted, or a consumer-defined status\n // like \"omitted\"), from the merged `rowStatusStyles`.\n const statusStyle =\n statusVal != null ? state.rowStatusStyles?.[statusVal] : undefined;\n\n const row = data[dataRowIndex] ?? updatedData[dataRowIndex];\n const loading = row == null;\n const col = columnSpec;\n\n const _topLeftCell = state.topLeftCell;\n const onCellEdited = state.onCellEdited;\n\n const value: T | undefined =\n updatedData[dataRowIndex]?.[col.key] ?? data[dataRowIndex]?.[col.key];\n\n const edited =\n updatedData[dataRowIndex]?.[col.key] != null ||\n state.rowStatus[dataRowIndex] === TableElementStatus.ADDED;\n\n // Validate the cell (skipped for deleted rows). Orthogonal to edit status.\n const validation = isDeleted\n ? null\n : validateCell(col, value, row, dataRowIndex);\n\n // A derived column is never writable, whatever `editable` says — see\n // `isColumnWritable`, which every write path in the store applies too.\n const editable =\n (col.editable ?? state.editable) && !isDeleted && !col.derived;\n const tableIsEditable = state.editable;\n\n // topLeftCell stores visible row indices, so compare with the visible rowIndex\n const topLeft =\n _topLeftCell?.col === colIndex && _topLeftCell?.row === rowIndex;\n\n // Intent precedence: error > warning > row-status intent > edited. Validation\n // state overrides the edited-green so an edited-but-invalid cell reads as\n // invalid. A row's status intent (e.g. deleted → danger) outranks the\n // edited-green so status reads through even on an edited row.\n let intent: Intent | undefined;\n if (validation?.severity === \"error\") {\n intent = \"danger\";\n } else if (validation?.severity === \"warning\") {\n intent = \"warning\";\n } else if (statusStyle?.intent != null) {\n intent = statusStyle.intent;\n } else if (edited) {\n intent = \"success\";\n }\n\n // One context object, assembled once and threaded through every path (fast,\n // slow, focused). `rowIndex` is the data-row index, stable under sort/filter.\n const cellContext: CellRenderContext<T> = {\n value,\n rowIndex: dataRowIndex,\n colIndex,\n column: col,\n row,\n isEdited: edited,\n isDeleted,\n status: statusVal,\n validation,\n // The size the table gives the cell (resized columns included), so a\n // renderer that fits itself to it needn't measure\n width:\n state.columnWidthsIndex?.get(col.key) ??\n col.width ??\n state.defaultColumnWidth,\n height: state.rowHeight,\n };\n\n // Only allocate a new style object when a row-status style must be layered on\n // (deleted → dimmed/struck-through; consumer statuses supply their own\n // `cellStyle`). The common case passes the column's own `style` straight\n // through — no per-cell clone, and a stable identity that diffs cheaply.\n // (Nothing downstream mutates `style`.)\n const style =\n statusStyle?.cellStyle != null\n ? { ...col.style, ...statusStyle.cellStyle }\n : col.style;\n\n const detailPresentation =\n col.cellDetail != null ? (col.detailPresentation ?? \"popover\") : null;\n\n // Derived values are drawn dimmed, so a reader can tell a record from a\n // restatement of one. Applied on every path below.\n const derivedClass = col.derived ? \"derived-cell\" : undefined;\n\n // Fast path — any non-focused cell whose *unfocused* appearance is just the\n // value viewer (a plain Blueprint `Cell`). That's everything except a custom\n // `cellComponent` (its own markup on every cell) and an *inline* `cellDetail`\n // (a persistent in-cell surface). A `cellDetail` popover/modal or a\n // `detailRenderer` only surfaces on the focused cell, so unfocused they show\n // the value viewer too — and take the fast path. Return a real `Cell`\n // (Blueprint clones it to position/size it) whose CHILD is the memoized\n // content, so unrelated re-renders (focus moving, a data load that swaps the\n // arrays) reposition the cheap `Cell` without re-running the value renderer.\n const usesCustomCell =\n col.cellComponent != null || detailPresentation === \"inline\";\n if (!topLeft && !usesCustomCell) {\n return h(\n Cell,\n {\n intent,\n loading,\n //value,\n style,\n className: derivedClass,\n interactive: false,\n //disabled: tableIsEditable && !editable,\n },\n h(CellContent, { cellContext }),\n );\n }\n\n const isEmpty = value == null || value === \"\";\n\n const _renderedValue: any = isEmpty\n ? null\n : (col.valueRenderer?.(value, cellContext) ?? value);\n\n const _Cell = col.cellComponent ?? Cell;\n\n // Only forward the render context to a custom cell component; the default\n // Blueprint Cell would spread unknown props onto the DOM.\n const cellComponentProps = col.cellComponent != null ? { cellContext } : {};\n\n // Allow a column to pick the editor per-cell (e.g. textarea only when the\n // value is long). A returned key overrides the static column field even\n // when its value is false/null, so use `in` rather than nullish-coalesce.\n const perCellEditors = col.editorForCell?.(cellContext);\n const dataEditorSpec =\n perCellEditors != null && \"dataEditor\" in perCellEditors\n ? perCellEditors.dataEditor\n : col.dataEditor;\n const inlineEditorSpec =\n perCellEditors != null && \"inlineEditor\" in perCellEditors\n ? perCellEditors.inlineEditor\n : col.inlineEditor;\n\n let inlineEditor = editable ? (inlineEditorSpec ?? true) : false;\n\n // Build the detail context for the unified `cellDetail` surface.\n const makeDetailCtx = (editableFlag: boolean): CellDetailContext<T> => ({\n ...cellContext,\n // A popover isn't laid out in the cell\n width: undefined,\n height: undefined,\n surface: \"cell\",\n editable: editableFlag,\n onChange(v: any) {\n if (editableFlag) onCellEdited(dataRowIndex, col.key, v);\n },\n resetValue() {\n state.resetChanges();\n },\n close() {\n state.closeCellSurface();\n state.tableElement?.focus?.();\n },\n });\n\n if (!topLeft) {\n // Non-focused cell that took the slow path — a custom `cellComponent`, or a\n // `cellDetail` / `detailRenderer` surface. An inline surface is a persistent\n // in-cell renderer (read-only here); others show the value viewer. (The\n // plain default-`Cell` case is handled by the memoized fast path above.)\n if (detailPresentation === \"inline\") {\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: \"value-viewer-cell\",\n interactive: false,\n ...cellComponentProps,\n },\n col.cellDetail!(makeDetailCtx(false)),\n );\n }\n return h(\n _Cell,\n {\n intent,\n loading,\n value,\n style,\n className: derivedClass,\n disabled: tableIsEditable && !editable,\n interactive: false,\n ...cellComponentProps,\n },\n _renderedValue,\n );\n }\n\n // The rest is for the top-left cell of a selection or the focused cell\n\n // Unified cell surface: one renderer that acts as editor (when editable) or\n // viewer (otherwise), presented as a popover / modal / inline. Supersedes\n // dataEditor / detailRenderer / editorForCell.\n if (col.cellDetail != null) {\n const content = col.cellDetail(makeDetailCtx(editable));\n\n if (detailPresentation === \"inline\") {\n // Persistent in-cell surface (editable on the focused cell). No popover.\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: editable ? \"input-cell\" : \"value-viewer-cell\",\n interactive: editable,\n ...cellComponentProps,\n },\n content,\n );\n }\n\n if (detailPresentation === \"modal\") {\n // CellDetailModal subscribes to the store so the dialog closes reactively.\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: \"value-viewer-cell\",\n interactive: false,\n ...cellComponentProps,\n },\n h(\n CellDetailModal,\n { title: col.name, valueViewer: _renderedValue },\n content,\n ),\n );\n }\n\n // Default: popover (same open/close machinery as editors and panels).\n const panel = h(\n EditorPopup,\n { valueViewer: _renderedValue, placement: col.detailPlacement },\n content,\n );\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className: \"editor-cell\",\n interactive: editable,\n ...cellComponentProps,\n },\n panel,\n );\n }\n\n // Read-only detail panel: a surface that opens on selection (auto) or click,\n // shows arbitrary content, and never takes keyboard focus — so arrow keys\n // keep navigating the table. Uses the same open/close machinery as editors.\n if (col.detailRenderer != null) {\n const panel = h(\n EditorPopup,\n { valueViewer: _renderedValue },\n col.detailRenderer(cellContext),\n );\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n // Use the editor-cell popover layout so the target fills the cell\n // without the double-padding offset of `value-viewer-cell`.\n className: \"editor-cell\",\n interactive: false,\n ...cellComponentProps,\n },\n panel,\n );\n }\n\n let cellContents: any = _renderedValue;\n\n let _dataEditor: ReactNode = null;\n let className: string | null = null;\n\n if (dataEditorSpec != null) {\n _dataEditor = h(\n EditorPopup,\n {\n valueViewer: _renderedValue,\n },\n [\n h(dataEditorSpec, {\n value,\n editable,\n isEdited: edited,\n onChange(value) {\n if (!editable) return;\n // Commit to THIS cell — not the live selection. The editor can\n // commit (e.g. on blur) after the selection has moved to another\n // cell or a whole column; `onSelectionEdited` would then write the\n // value to the wrong target (emptying it). `onCellEdited` addresses\n // the editor's own data cell.\n state.onCellEdited(dataRowIndex, col.key, value);\n },\n resetValue() {\n state.resetChanges();\n },\n }),\n ],\n );\n }\n\n if (!editable) {\n if (_dataEditor != null) {\n cellContents = _dataEditor;\n }\n const className = classNames(\"value-viewer-cell\", derivedClass);\n\n return h(\n _Cell,\n {\n intent,\n value,\n style,\n className,\n interactive: false,\n ...cellComponentProps,\n },\n cellContents,\n );\n }\n\n /* The remaining logic covers cells that are focused and editable */\n\n const onChange = (e) => {\n if (!editable) return;\n if (_renderedValue === e.target.value) return;\n // Use dataRowIndex for the actual data mutation\n onCellEdited(dataRowIndex, col.key, e.target.value);\n };\n\n const isSingleCellSelection = singleFocusedCell(state.selection) != null;\n\n let _inlineEditor: ReactNode = null;\n if (typeof inlineEditor == \"boolean\") {\n let _value: any = value;\n if (\n typeof _renderedValue === \"string\" ||\n typeof _renderedValue === \"number\" ||\n _renderedValue == null\n ) {\n _value = _renderedValue;\n }\n _inlineEditor = h(EditorInput, {\n className: \"main-editor\",\n value: _value ?? \"\",\n autoFocus: focusOnOpen,\n onChange,\n });\n } else {\n // If inlineEditor is a ReactNode, we use it directly\n _inlineEditor = inlineEditor as ReactNode;\n }\n\n let hiddenInput: React.ReactNode = h(EditorInput, {\n className: \"hidden-input\",\n autoFocus: true,\n });\n\n if (_dataEditor != null) {\n className = \"editor-cell\";\n cellContents = _dataEditor;\n hiddenInput = null;\n } else if (_inlineEditor != null) {\n cellContents = _inlineEditor;\n className = \"input-cell\";\n hiddenInput = null;\n }\n\n // Hidden html input\n return h(\n _Cell,\n {\n intent,\n value,\n className,\n style,\n interactive: true,\n ...cellComponentProps,\n //truncated: false,\n },\n [\n cellContents,\n h.if(editable && isSingleCellSelection)(CornerDragHandle),\n //hiddenInput,\n ],\n );\n}\n\nfunction EditorInput(props) {\n const { value, onChange, ...rest } = props;\n const onKeyDown = ctx.useValue(editorKeyHandlerAtom);\n const navDirection = useSelector((s) => s.lastNavDirection);\n const surfaceOpen = useSelector((s) => s.cellSurfaceOpen);\n const inputRef = useRef<HTMLInputElement>(null);\n const [_value, setValue] = useState(value);\n useEffect(() => {\n setValue(value);\n }, [value]);\n useEffect(() => {\n // Focus when the cell's surface is open (on mount, and when reopened via\n // click/F2 while already mounted), placing the cursor on the side we're\n // travelling toward so another arrow in that direction leaves the cell.\n const el = inputRef.current;\n if (el == null || !surfaceOpen) return;\n el.focus();\n const atStart = navDirection === \"up\" || navDirection === \"left\";\n const pos = atStart ? 0 : (el.value?.length ?? 0);\n el.setSelectionRange(pos, pos);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [surfaceOpen]);\n return h(\"input\", {\n ref: inputRef,\n onKeyDown,\n onBlur: onChange,\n value: _value ?? value,\n onChange: (e) => setValue(e.target.value),\n ...rest,\n });\n}\n\nfunction CornerDragHandle() {\n // TODO: we might want to drag multiple columns in some cases\n // This should be on the last cell of a selection\n const onDragValue = ctx.useValue(dragValueHandlerAtom);\n if (onDragValue == null) return null;\n\n return h(\"div.corner-drag-handle\", {\n onMouseDown: onDragValue,\n });\n}\n"],"names":["CellContent","value","className"],"mappings":";;;;;;;;;;;;AAmBA,SAAS,gBAAgB,GAAQ,GAAiB;AAChD,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,KAAK,QAAQ,KAAK,aAAa,KAAK;AACxC,SAAO,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE;AACtD;AAIA,SAAS,kBACP,GACA,GACS;AACT,QAAM,IAAI,EAAE;AACZ,QAAM,IAAI,EAAE;AACZ,SACE,EAAE,WAAW,EAAE,UACf,EAAE,UAAU,EAAE,SACd,EAAE,QAAQ,EAAE,OACZ,EAAE,aAAa,EAAE,YACjB,EAAE,aAAa,EAAE,YACjB,EAAE,aAAa,EAAE,YACjB,EAAE,cAAc,EAAE,aAClB,EAAE,WAAW,EAAE,UACf,EAAE,UAAU,EAAE,SACd,EAAE,WAAW,EAAE,UACf,gBAAgB,EAAE,YAAY,EAAE,UAAU;AAE9C;AAUA,MAAM,cAAc,KAAK,SAASA,aAAY;AAAA,EAC5C;AACF,GAEG;AACD,QAAM,EAAE,OAAO,OAAA,IAAW;AAC1B,MAAI,SAAS,QAAQ,UAAU,GAAI,QAAO;AAC1C,SAAO,OAAO,gBAAgB,OAAO,WAAW,KAAK;AACvD,GAAG,iBAAiB;AAEb,SAAS,kBACd,UACA,UACA,YACA,OACA,oBACK;AAOL,QAAM,cAAc,MAAM;AAG1B,QAAM,eACJ,sBAAsB,OACjB,mBAAmB,QAAQ,KAAK,WACjC;AAEN,QAAM,OAAO,MAAM;AACnB,QAAM,cAAc,MAAM;AAE1B,QAAM,YAAY,MAAM,UAAU,YAAY;AAC9C,QAAM,YAAY,aAAa,mBAAmB;AAGlD,QAAM,cACJ,aAAa,OAAO,MAAM,kBAAkB,SAAS,IAAI;AAE3D,QAAM,MAAM,KAAK,YAAY,K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,IACR,OAAO,UAAU;AAAA,IACjB,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA,IACxC,GAAG;AAAA,EAAA,CACJ;AACH;AAEA,SAAS,mBAAmB;AAG1B,QAAM,cAAc,IAAI,SAAS,oBAAoB;AACrD,MAAI,eAAe,KAAM,QAAO;AAEhC,SAAO,EAAE,0BAA0B;AAAA,IACjC,aAAa;AAAA,EAAA,CACd;AACH;"}
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const jotai = require("jotai");
4
+ const selection = require("../actions/selection.cjs");
4
5
  const notifications = require("../notifications.cjs");
5
6
  const core = require("../provider/core.cjs");
6
7
  const context = require("../actions/context.cjs");
@@ -11,8 +12,8 @@ const isEditableAtom = jotai.atom((get) => {
11
12
  });
12
13
  jotai.atom((get) => {
13
14
  const store = get(core.storeAtom);
14
- const selection = store?.selection ?? [];
15
- return selection.length > 0;
15
+ const selection2 = store?.selection ?? [];
16
+ return selection2.length > 0;
16
17
  });
17
18
  const tableHotkeysAtom = jotai.atom(
18
19
  null,
@@ -64,7 +65,7 @@ const tableHotkeysAtom = jotai.atom(
64
65
  label: action.name,
65
66
  group: action.group ?? "Actions",
66
67
  preventDefault: true,
67
- disabled: action.requiresEditable !== false && !editable,
68
+ disabled: selection.actionRequiresEditable(action) && !editable,
68
69
  onKeyDown(event) {
69
70
  context.runActionWrapper(action, get, set, toaster);
70
71
  }
@@ -160,8 +161,8 @@ const selectionAtom = jotai.atom((get) => {
160
161
  return store?.selection ?? [];
161
162
  });
162
163
  const isSingleCellSelectionAtom = jotai.atom((get) => {
163
- const selection = get(selectionAtom);
164
- return zustandStore.singleFocusedCell(selection) != null;
164
+ const selection2 = get(selectionAtom);
165
+ return zustandStore.singleFocusedCell(selection2) != null;
165
166
  });
166
167
  const editorKeyHandlerAtom = jotai.atom((get) => {
167
168
  const store = get(core.storeAPIAtom);
@@ -1 +1 @@
1
- {"version":3,"file":"key-handling.cjs","sources":["../../src/utils/key-handling.ts"],"sourcesContent":["import type { KeyboardEvent } from \"react\";\nimport {\n storeAPIAtom,\n storeAtom,\n tableActionsAtom,\n type DataSheetStoreMain,\n singleFocusedCell,\n ctx,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { runActionWrapper } from \"../actions\";\nimport { HotkeyConfig } from \"@blueprintjs/core\";\nimport { toasterAtom } from \"../notifications.ts\";\n\ntype HotkeyActionRunner = (\n e: KeyboardEvent,\n state: DataSheetStoreMain<any>,\n setState: (state: Partial<DataSheetStoreMain<any>>) => void,\n) => void | Promise<void>;\n\nconst isEditableAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.editable ?? false;\n});\n\nconst hasSelectionAtom = atom((get) => {\n const store = get(storeAtom);\n const selection = store?.selection ?? [];\n return selection.length > 0;\n});\n\nexport const tableHotkeysAtom = atom<null, [], HotkeyConfig[]>(\n null,\n (get, set) => {\n const store = get(storeAPIAtom);\n const toaster = get(toasterAtom);\n const editable = get(isEditableAtom);\n\n /** Set up hotkeys for table actions */\n const tableActions = get(tableActionsAtom);\n\n if (store == null) return [];\n const keyHandler = (\n actionRunner: HotkeyActionRunner,\n ): HotkeyConfig[\"onKeyDown\"] => {\n return (e) => {\n // Kind of a ridiculous hack to get the store from the atom.\n const state = store.getState();\n const setState = store.setState;\n try {\n const res = actionRunner(e as any, state, setState);\n if (res instanceof Promise) {\n res\n .then(() => {})\n .catch((err) => {\n console.error(err);\n handleError(toaster, err);\n });\n }\n } catch (err) {\n handleError(toaster, err);\n }\n };\n };\n\n function handleError(toaster, err) {\n toaster.show({\n message: `${err}`,\n intent: \"danger\",\n });\n }\n\n const directionCombos = [\"up\", \"down\", \"left\", \"right\"].map((dir) => {\n return {\n combo: dir,\n group: \"Navigation\",\n label: \"Move focus \" + dir,\n preventDefault: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(dir as any);\n }),\n };\n });\n\n /** TODO: merge a bit more with the actions config */\n\n const actionsCombos = tableActions\n .map((action) => {\n if (action.hotkey == null) return null;\n return {\n combo: action.hotkey,\n label: action.name,\n group: action.group ?? \"Actions\",\n preventDefault: true,\n disabled: action.requiresEditable !== false && !editable,\n onKeyDown(event: KeyboardEvent<any>): any {\n runActionWrapper(action, get, set, toaster);\n },\n } as any as HotkeyConfig;\n })\n .filter(Boolean) as HotkeyConfig[];\n\n // Backspace/Delete: on a whole-row selection, delete the row(s); otherwise\n // clear the selected cells.\n const clearOrDeleteSelection = keyHandler((e, state) => {\n const sel = state.selection ?? [];\n const isRowSelection =\n sel.length > 0 && sel.every((r) => r.cols == null && r.rows != null);\n if (isRowSelection) {\n state.deleteSelectedRows();\n } else {\n state.clearSelection();\n }\n });\n\n return [\n {\n combo: \"esc\",\n label: \"Exit editing / clear selection\",\n group: \"Selection\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // First Escape closes the focused cell's open surface (editor/panel)\n // while keeping the selection, so arrow keys keep working — in both\n // auto and manual modes. A second Escape (nothing open) clears the\n // selection.\n if (state.cellSurfaceOpen) {\n state.closeCellSurface();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n if (state.selection.length == 0) {\n // Focus goes back to parent\n return;\n }\n state.setSelection([]);\n e.preventDefault();\n e.stopPropagation();\n }),\n },\n {\n combo: \"backspace\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"del\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"tab\",\n label: \"Move focus right (or left with shift)\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(e.shiftKey ? \"left\" : \"right\");\n }),\n },\n {\n combo: \"enter\",\n label: \"Edit cell / move focus down\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // In navigation mode (no surface open), Enter enters edit mode —\n // opening and focusing the focused cell's surface (Google Sheets\n // style). While a surface is open, Enter advances downward as usual\n // (an inline editor blurs and this moves to the next row).\n if (!state.cellSurfaceOpen) {\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n return;\n }\n state.moveFocusedCell(\"down\");\n }),\n },\n {\n combo: \"f2\",\n label: \"Edit / open cell\",\n group: \"Editing\",\n onKeyDown: keyHandler((e, state) => {\n // Enter edit mode from the keyboard: re-arm auto-activation and open\n // the focused cell's surface (which focuses the editor).\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n }),\n },\n ...directionCombos,\n ...actionsCombos,\n ];\n },\n);\n\nconst selectionAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.selection ?? [];\n});\n\nconst isSingleCellSelectionAtom = atom((get) => {\n const selection = get(selectionAtom);\n return singleFocusedCell(selection) != null;\n});\n\nexport const editorKeyHandlerAtom = atom((get) => {\n const store = get(storeAPIAtom);\n return (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n // Escape exits the inline editor: close the surface (which enters\n // navigation mode in auto), keep the selection, and return focus to the\n // table so arrow keys navigate. Stop propagation so the table's own\n // Escape hotkey doesn't also fire.\n const state = store?.getState();\n state?.closeCellSurface();\n state?.tableElement?.focus();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n const isSingleCellSelection = get(isSingleCellSelectionAtom);\n editorKeyHandler(e as any, isSingleCellSelection);\n };\n});\n\nfunction editorKeyHandler(\n e: KeyboardEvent<HTMLInputElement>,\n isSingleCellSelection: boolean,\n) {\n /** Get a key handler for inline cell editing */\n\n const target = e.target as HTMLInputElement;\n\n let shouldCaptureEventForInlineEditing = true;\n\n if (e.key == \"Enter\") {\n shouldCaptureEventForInlineEditing = e.shiftKey;\n }\n\n if (e.key == \"Escape\" || e.key == \"Tab\") {\n shouldCaptureEventForInlineEditing = false;\n }\n\n if (e.key == \"Backspace\" || e.key == \"Delete\") {\n /** Clear selection on Backspace or Delete on a multi-cell selection\n * (if shift is held, we allow deletion in a single cell)\n */\n shouldCaptureEventForInlineEditing = isSingleCellSelection && !e.shiftKey;\n }\n\n if (!shouldCaptureEventForInlineEditing) {\n target.blur();\n e.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(e);\n if (!shouldPropagate) {\n e.stopPropagation();\n //e.preventDefault();\n } else {\n // we blur the editor and dispatch a keydown event on the parent to propagate the event to the table\n e.preventDefault();\n target.blur();\n //console.log(tableElement);\n //tableElement.focus();\n //target.parentNode?.dispatchEvent(e);\n target.parentNode?.dispatchEvent(new KeyboardEvent(\"keydown\", e as any));\n }\n}\n\nfunction shouldPropagateKeystroke(evt: any): boolean {\n if (evt.target.selectionStart == evt.target.selectionEnd) {\n // We don't have anything selected, so we can propagate the event potentially\n // Propagate copy and paste events even if there is no selection, since they might want to copy/paste an entire row/column based on the focused cell.\n if (evt.key === \"c\" || evt.key === \"v\" || evt.key === \"x\") {\n if (evt.ctrlKey || evt.metaKey) {\n return true;\n }\n }\n }\n\n if (evt.key === \"ArrowUp\" || evt.key === \"ArrowDown\") {\n return true;\n }\n\n const target = evt.target;\n if (\n (evt.key === \"ArrowLeft\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === 0\n ) {\n return true;\n }\n\n if (\n (evt.key === \"ArrowRight\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"Tab\" ||\n evt.key === \"Enter\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === evt.target.value.length\n ) {\n return true;\n }\n\n return false;\n}\n\nexport function multiLineTextKeyHandler(evt: any) {\n if (evt.key === \"Enter\") {\n //evt.preventDefault();\n evt.stopPropagation();\n return;\n }\n\n if (evt.key === \"Escape\") {\n evt.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(evt);\n if (!shouldPropagate) {\n evt.stopPropagation();\n } else {\n evt.target.blur();\n }\n}\n"],"names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,aAAa;AACpD,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,IAAI;AACnB,OACG,IAAI,QAAQ,eACX,IAAI,QAAQ,aACZ,IAAI,QAAQ,gBACd,OAAO,mBAAmB,GAC1B;AACA,WAAO;AAAA,EACT;AAEA,OACG,IAAI,QAAQ,gBACX,IAAI,QAAQ,aACZ,IAAI,QAAQ,SACZ,IAAI,QAAQ,WACZ,IAAI,QAAQ,gBACd,OAAO,mBAAmB,IAAI,OAAO,MAAM,QAC3C;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEO,SAAS,wBAAwB,KAAU;AAChD,MAAI,IAAI,QAAQ,SAAS;AAEvB,QAAI,gBAAA;AACJ;AAAA,EACF;AAEA,MAAI,IAAI,QAAQ,UAAU;AACxB,QAAI,eAAA;AACJ;AAAA,EACF;AAEA,QAAM,kBAAkB,yBAAyB,GAAG;AACpD,MAAI,CAAC,iBAAiB;AACpB,QAAI,gBAAA;AAAA,EACN,OAAO;AACL,QAAI,OAAO,KAAA;AAAA,EACb;AACF;;;;"}
1
+ {"version":3,"file":"key-handling.cjs","sources":["../../src/utils/key-handling.ts"],"sourcesContent":["import type { KeyboardEvent } from \"react\";\nimport {\n storeAPIAtom,\n storeAtom,\n tableActionsAtom,\n type DataSheetStoreMain,\n singleFocusedCell,\n ctx,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { runActionWrapper } from \"../actions\";\nimport { actionRequiresEditable } from \"../actions/selection.ts\";\nimport { HotkeyConfig } from \"@blueprintjs/core\";\nimport { toasterAtom } from \"../notifications.ts\";\n\ntype HotkeyActionRunner = (\n e: KeyboardEvent,\n state: DataSheetStoreMain<any>,\n setState: (state: Partial<DataSheetStoreMain<any>>) => void,\n) => void | Promise<void>;\n\nconst isEditableAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.editable ?? false;\n});\n\nconst hasSelectionAtom = atom((get) => {\n const store = get(storeAtom);\n const selection = store?.selection ?? [];\n return selection.length > 0;\n});\n\nexport const tableHotkeysAtom = atom<null, [], HotkeyConfig[]>(\n null,\n (get, set) => {\n const store = get(storeAPIAtom);\n const toaster = get(toasterAtom);\n const editable = get(isEditableAtom);\n\n /** Set up hotkeys for table actions */\n const tableActions = get(tableActionsAtom);\n\n if (store == null) return [];\n const keyHandler = (\n actionRunner: HotkeyActionRunner,\n ): HotkeyConfig[\"onKeyDown\"] => {\n return (e) => {\n // Kind of a ridiculous hack to get the store from the atom.\n const state = store.getState();\n const setState = store.setState;\n try {\n const res = actionRunner(e as any, state, setState);\n if (res instanceof Promise) {\n res\n .then(() => {})\n .catch((err) => {\n console.error(err);\n handleError(toaster, err);\n });\n }\n } catch (err) {\n handleError(toaster, err);\n }\n };\n };\n\n function handleError(toaster, err) {\n toaster.show({\n message: `${err}`,\n intent: \"danger\",\n });\n }\n\n const directionCombos = [\"up\", \"down\", \"left\", \"right\"].map((dir) => {\n return {\n combo: dir,\n group: \"Navigation\",\n label: \"Move focus \" + dir,\n preventDefault: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(dir as any);\n }),\n };\n });\n\n /** TODO: merge a bit more with the actions config */\n\n const actionsCombos = tableActions\n .map((action) => {\n if (action.hotkey == null) return null;\n return {\n combo: action.hotkey,\n label: action.name,\n group: action.group ?? \"Actions\",\n preventDefault: true,\n disabled: actionRequiresEditable(action) && !editable,\n onKeyDown(event: KeyboardEvent<any>): any {\n runActionWrapper(action, get, set, toaster);\n },\n } as any as HotkeyConfig;\n })\n .filter(Boolean) as HotkeyConfig[];\n\n // Backspace/Delete: on a whole-row selection, delete the row(s); otherwise\n // clear the selected cells.\n const clearOrDeleteSelection = keyHandler((e, state) => {\n const sel = state.selection ?? [];\n const isRowSelection =\n sel.length > 0 && sel.every((r) => r.cols == null && r.rows != null);\n if (isRowSelection) {\n state.deleteSelectedRows();\n } else {\n state.clearSelection();\n }\n });\n\n return [\n {\n combo: \"esc\",\n label: \"Exit editing / clear selection\",\n group: \"Selection\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // First Escape closes the focused cell's open surface (editor/panel)\n // while keeping the selection, so arrow keys keep working — in both\n // auto and manual modes. A second Escape (nothing open) clears the\n // selection.\n if (state.cellSurfaceOpen) {\n state.closeCellSurface();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n if (state.selection.length == 0) {\n // Focus goes back to parent\n return;\n }\n state.setSelection([]);\n e.preventDefault();\n e.stopPropagation();\n }),\n },\n {\n combo: \"backspace\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"del\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"tab\",\n label: \"Move focus right (or left with shift)\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(e.shiftKey ? \"left\" : \"right\");\n }),\n },\n {\n combo: \"enter\",\n label: \"Edit cell / move focus down\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // In navigation mode (no surface open), Enter enters edit mode —\n // opening and focusing the focused cell's surface (Google Sheets\n // style). While a surface is open, Enter advances downward as usual\n // (an inline editor blurs and this moves to the next row).\n if (!state.cellSurfaceOpen) {\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n return;\n }\n state.moveFocusedCell(\"down\");\n }),\n },\n {\n combo: \"f2\",\n label: \"Edit / open cell\",\n group: \"Editing\",\n onKeyDown: keyHandler((e, state) => {\n // Enter edit mode from the keyboard: re-arm auto-activation and open\n // the focused cell's surface (which focuses the editor).\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n }),\n },\n ...directionCombos,\n ...actionsCombos,\n ];\n },\n);\n\nconst selectionAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.selection ?? [];\n});\n\nconst isSingleCellSelectionAtom = atom((get) => {\n const selection = get(selectionAtom);\n return singleFocusedCell(selection) != null;\n});\n\nexport const editorKeyHandlerAtom = atom((get) => {\n const store = get(storeAPIAtom);\n return (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n // Escape exits the inline editor: close the surface (which enters\n // navigation mode in auto), keep the selection, and return focus to the\n // table so arrow keys navigate. Stop propagation so the table's own\n // Escape hotkey doesn't also fire.\n const state = store?.getState();\n state?.closeCellSurface();\n state?.tableElement?.focus();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n const isSingleCellSelection = get(isSingleCellSelectionAtom);\n editorKeyHandler(e as any, isSingleCellSelection);\n };\n});\n\nfunction editorKeyHandler(\n e: KeyboardEvent<HTMLInputElement>,\n isSingleCellSelection: boolean,\n) {\n /** Get a key handler for inline cell editing */\n\n const target = e.target as HTMLInputElement;\n\n let shouldCaptureEventForInlineEditing = true;\n\n if (e.key == \"Enter\") {\n shouldCaptureEventForInlineEditing = e.shiftKey;\n }\n\n if (e.key == \"Escape\" || e.key == \"Tab\") {\n shouldCaptureEventForInlineEditing = false;\n }\n\n if (e.key == \"Backspace\" || e.key == \"Delete\") {\n /** Clear selection on Backspace or Delete on a multi-cell selection\n * (if shift is held, we allow deletion in a single cell)\n */\n shouldCaptureEventForInlineEditing = isSingleCellSelection && !e.shiftKey;\n }\n\n if (!shouldCaptureEventForInlineEditing) {\n target.blur();\n e.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(e);\n if (!shouldPropagate) {\n e.stopPropagation();\n //e.preventDefault();\n } else {\n // we blur the editor and dispatch a keydown event on the parent to propagate the event to the table\n e.preventDefault();\n target.blur();\n //console.log(tableElement);\n //tableElement.focus();\n //target.parentNode?.dispatchEvent(e);\n target.parentNode?.dispatchEvent(new KeyboardEvent(\"keydown\", e as any));\n }\n}\n\nfunction shouldPropagateKeystroke(evt: any): boolean {\n if (evt.target.selectionStart == evt.target.selectionEnd) {\n // We don't have anything selected, so we can propagate the event potentially\n // Propagate copy and paste events even if there is no selection, since they might want to copy/paste an entire row/column based on the focused cell.\n if (evt.key === \"c\" || evt.key === \"v\" || evt.key === \"x\") {\n if (evt.ctrlKey || evt.metaKey) {\n return true;\n }\n }\n }\n\n if (evt.key === \"ArrowUp\" || evt.key === \"ArrowDown\") {\n return true;\n }\n\n const target = evt.target;\n if (\n (evt.key === \"ArrowLeft\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === 0\n ) {\n return true;\n }\n\n if (\n (evt.key === \"ArrowRight\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"Tab\" ||\n evt.key === \"Enter\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === evt.target.value.length\n ) {\n return true;\n }\n\n return false;\n}\n\nexport function multiLineTextKeyHandler(evt: any) {\n if (evt.key === \"Enter\") {\n //evt.preventDefault();\n evt.stopPropagation();\n return;\n }\n\n if (evt.key === \"Escape\") {\n evt.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(evt);\n if (!shouldPropagate) {\n evt.stopPropagation();\n } else {\n evt.target.blur();\n }\n}\n"],"names":["atom","storeAtom","selection","storeAPIAtom","toasterAtom","tableActionsAtom","toaster","actionRequiresEditable","runActionWrapper","singleFocusedCell"],"mappings":";;;;;;;;AAqBA,MAAM,iBAAiBA,MAAAA,KAAK,CAAC,QAAQ;AACnC,QAAM,QAAQ,IAAIC,cAAS;AAC3B,SAAO,OAAO,YAAY;AAC5B,CAAC;AAEwBD,MAAAA,KAAK,CAAC,QAAQ;AACrC,QAAM,QAAQ,IAAIC,cAAS;AAC3B,QAAMC,aAAY,OAAO,aAAa,CAAA;AACtC,SAAOA,WAAU,SAAS;AAC5B,CAAC;AAEM,MAAM,mBAAmBF,MAAAA;AAAAA,EAC9B;AAAA,EACA,CAAC,KAAK,QAAQ;AACZ,UAAM,QAAQ,IAAIG,iBAAY;AAC9B,UAAM,UAAU,IAAIC,yBAAW;AAC/B,UAAM,WAAW,IAAI,cAA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,EACF;AAEA,QAAM,kBAAkB,yBAAyB,GAAG;AACpD,MAAI,CAAC,iBAAiB;AACpB,QAAI,gBAAA;AAAA,EACN,OAAO;AACL,QAAI,OAAO,KAAA;AAAA,EACb;AACF;;;;"}
@@ -1,4 +1,5 @@
1
1
  import { atom } from "jotai";
2
+ import { actionRequiresEditable } from "../actions/selection.js";
2
3
  import { toasterAtom } from "../notifications.js";
3
4
  import { storeAPIAtom, tableActionsAtom, storeAtom } from "../provider/core.js";
4
5
  import { runActionWrapper } from "../actions/context.js";
@@ -62,7 +63,7 @@ const tableHotkeysAtom = atom(
62
63
  label: action.name,
63
64
  group: action.group ?? "Actions",
64
65
  preventDefault: true,
65
- disabled: action.requiresEditable !== false && !editable,
66
+ disabled: actionRequiresEditable(action) && !editable,
66
67
  onKeyDown(event) {
67
68
  runActionWrapper(action, get, set, toaster);
68
69
  }
@@ -1 +1 @@
1
- {"version":3,"file":"key-handling.js","sources":["../../src/utils/key-handling.ts"],"sourcesContent":["import type { KeyboardEvent } from \"react\";\nimport {\n storeAPIAtom,\n storeAtom,\n tableActionsAtom,\n type DataSheetStoreMain,\n singleFocusedCell,\n ctx,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { runActionWrapper } from \"../actions\";\nimport { HotkeyConfig } from \"@blueprintjs/core\";\nimport { toasterAtom } from \"../notifications.ts\";\n\ntype HotkeyActionRunner = (\n e: KeyboardEvent,\n state: DataSheetStoreMain<any>,\n setState: (state: Partial<DataSheetStoreMain<any>>) => void,\n) => void | Promise<void>;\n\nconst isEditableAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.editable ?? false;\n});\n\nconst hasSelectionAtom = atom((get) => {\n const store = get(storeAtom);\n const selection = store?.selection ?? [];\n return selection.length > 0;\n});\n\nexport const tableHotkeysAtom = atom<null, [], HotkeyConfig[]>(\n null,\n (get, set) => {\n const store = get(storeAPIAtom);\n const toaster = get(toasterAtom);\n const editable = get(isEditableAtom);\n\n /** Set up hotkeys for table actions */\n const tableActions = get(tableActionsAtom);\n\n if (store == null) return [];\n const keyHandler = (\n actionRunner: HotkeyActionRunner,\n ): HotkeyConfig[\"onKeyDown\"] => {\n return (e) => {\n // Kind of a ridiculous hack to get the store from the atom.\n const state = store.getState();\n const setState = store.setState;\n try {\n const res = actionRunner(e as any, state, setState);\n if (res instanceof Promise) {\n res\n .then(() => {})\n .catch((err) => {\n console.error(err);\n handleError(toaster, err);\n });\n }\n } catch (err) {\n handleError(toaster, err);\n }\n };\n };\n\n function handleError(toaster, err) {\n toaster.show({\n message: `${err}`,\n intent: \"danger\",\n });\n }\n\n const directionCombos = [\"up\", \"down\", \"left\", \"right\"].map((dir) => {\n return {\n combo: dir,\n group: \"Navigation\",\n label: \"Move focus \" + dir,\n preventDefault: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(dir as any);\n }),\n };\n });\n\n /** TODO: merge a bit more with the actions config */\n\n const actionsCombos = tableActions\n .map((action) => {\n if (action.hotkey == null) return null;\n return {\n combo: action.hotkey,\n label: action.name,\n group: action.group ?? \"Actions\",\n preventDefault: true,\n disabled: action.requiresEditable !== false && !editable,\n onKeyDown(event: KeyboardEvent<any>): any {\n runActionWrapper(action, get, set, toaster);\n },\n } as any as HotkeyConfig;\n })\n .filter(Boolean) as HotkeyConfig[];\n\n // Backspace/Delete: on a whole-row selection, delete the row(s); otherwise\n // clear the selected cells.\n const clearOrDeleteSelection = keyHandler((e, state) => {\n const sel = state.selection ?? [];\n const isRowSelection =\n sel.length > 0 && sel.every((r) => r.cols == null && r.rows != null);\n if (isRowSelection) {\n state.deleteSelectedRows();\n } else {\n state.clearSelection();\n }\n });\n\n return [\n {\n combo: \"esc\",\n label: \"Exit editing / clear selection\",\n group: \"Selection\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // First Escape closes the focused cell's open surface (editor/panel)\n // while keeping the selection, so arrow keys keep working — in both\n // auto and manual modes. A second Escape (nothing open) clears the\n // selection.\n if (state.cellSurfaceOpen) {\n state.closeCellSurface();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n if (state.selection.length == 0) {\n // Focus goes back to parent\n return;\n }\n state.setSelection([]);\n e.preventDefault();\n e.stopPropagation();\n }),\n },\n {\n combo: \"backspace\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"del\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"tab\",\n label: \"Move focus right (or left with shift)\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(e.shiftKey ? \"left\" : \"right\");\n }),\n },\n {\n combo: \"enter\",\n label: \"Edit cell / move focus down\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // In navigation mode (no surface open), Enter enters edit mode —\n // opening and focusing the focused cell's surface (Google Sheets\n // style). While a surface is open, Enter advances downward as usual\n // (an inline editor blurs and this moves to the next row).\n if (!state.cellSurfaceOpen) {\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n return;\n }\n state.moveFocusedCell(\"down\");\n }),\n },\n {\n combo: \"f2\",\n label: \"Edit / open cell\",\n group: \"Editing\",\n onKeyDown: keyHandler((e, state) => {\n // Enter edit mode from the keyboard: re-arm auto-activation and open\n // the focused cell's surface (which focuses the editor).\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n }),\n },\n ...directionCombos,\n ...actionsCombos,\n ];\n },\n);\n\nconst selectionAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.selection ?? [];\n});\n\nconst isSingleCellSelectionAtom = atom((get) => {\n const selection = get(selectionAtom);\n return singleFocusedCell(selection) != null;\n});\n\nexport const editorKeyHandlerAtom = atom((get) => {\n const store = get(storeAPIAtom);\n return (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n // Escape exits the inline editor: close the surface (which enters\n // navigation mode in auto), keep the selection, and return focus to the\n // table so arrow keys navigate. Stop propagation so the table's own\n // Escape hotkey doesn't also fire.\n const state = store?.getState();\n state?.closeCellSurface();\n state?.tableElement?.focus();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n const isSingleCellSelection = get(isSingleCellSelectionAtom);\n editorKeyHandler(e as any, isSingleCellSelection);\n };\n});\n\nfunction editorKeyHandler(\n e: KeyboardEvent<HTMLInputElement>,\n isSingleCellSelection: boolean,\n) {\n /** Get a key handler for inline cell editing */\n\n const target = e.target as HTMLInputElement;\n\n let shouldCaptureEventForInlineEditing = true;\n\n if (e.key == \"Enter\") {\n shouldCaptureEventForInlineEditing = e.shiftKey;\n }\n\n if (e.key == \"Escape\" || e.key == \"Tab\") {\n shouldCaptureEventForInlineEditing = false;\n }\n\n if (e.key == \"Backspace\" || e.key == \"Delete\") {\n /** Clear selection on Backspace or Delete on a multi-cell selection\n * (if shift is held, we allow deletion in a single cell)\n */\n shouldCaptureEventForInlineEditing = isSingleCellSelection && !e.shiftKey;\n }\n\n if (!shouldCaptureEventForInlineEditing) {\n target.blur();\n e.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(e);\n if (!shouldPropagate) {\n e.stopPropagation();\n //e.preventDefault();\n } else {\n // we blur the editor and dispatch a keydown event on the parent to propagate the event to the table\n e.preventDefault();\n target.blur();\n //console.log(tableElement);\n //tableElement.focus();\n //target.parentNode?.dispatchEvent(e);\n target.parentNode?.dispatchEvent(new KeyboardEvent(\"keydown\", e as any));\n }\n}\n\nfunction shouldPropagateKeystroke(evt: any): boolean {\n if (evt.target.selectionStart == evt.target.selectionEnd) {\n // We don't have anything selected, so we can propagate the event potentially\n // Propagate copy and paste events even if there is no selection, since they might want to copy/paste an entire row/column based on the focused cell.\n if (evt.key === \"c\" || evt.key === \"v\" || evt.key === \"x\") {\n if (evt.ctrlKey || evt.metaKey) {\n return true;\n }\n }\n }\n\n if (evt.key === \"ArrowUp\" || evt.key === \"ArrowDown\") {\n return true;\n }\n\n const target = evt.target;\n if (\n (evt.key === \"ArrowLeft\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === 0\n ) {\n return true;\n }\n\n if (\n (evt.key === \"ArrowRight\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"Tab\" ||\n evt.key === \"Enter\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === evt.target.value.length\n ) {\n return true;\n }\n\n return false;\n}\n\nexport function multiLineTextKeyHandler(evt: any) {\n if (evt.key === \"Enter\") {\n //evt.preventDefault();\n evt.stopPropagation();\n return;\n }\n\n if (evt.key === \"Escape\") {\n evt.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(evt);\n if (!shouldPropagate) {\n evt.stopPropagation();\n } else {\n evt.target.blur();\n }\n}\n"],"names":["toaster"],"mappings":";;;;;AAoBA,MAAM,iBAAiB,KAAK,CAAC,QAAQ;AACnC,QAAM,QAAQ,IAAI,SAAS;AAC3B,SAAO,OAAO,YAAY;AAC5B,CAAC;AAEwB,KAAK,CAAC,QAAQ;AACrC,QAAM,QAAQ,IAAI,SAAS;AAC3B,QAAM,YAAY,OAAO,aAAa,CAAA;AACtC,SAAO,UAAU,SAAS;AAC5B,CAAC;AAEM,MAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA,CAAC,KAAK,QAAQ;AACZ,UAAM,QAAQ,IAAI,YAAY;AAC9B,UAAM,UAAU,IAAI,WAAW;AAC/B,UAAM,WAAW,IAAI,cAAc;AAGnC,UAAM,eAAe,IAAI,gBAAgB;AAEzC,QAAI,SAAS,KAAM,QAAO,CAAA;AAC1B,UAAM,aAAa,CACjB,iBAC8B;AAC9B,aAAO,CAAC,MAAM;AAEZ,cAAM,QAAQ,MAAM,SAAA;AACpB,cAAM,WAAW,MAAM;AACvB,YAAI;AACF,gBAAM,MAAM,aAAa,GAAU,OAAO,QAAQ;AAClD,cAA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MAAE,gBAAA;AAAA,EAEJ,OAAO;AAEL,MAAE,eAAA;AACF,WAAO,KAAA;AAIP,WAAO,YAAY,cAAc,IAAI,cAAc,WAAW,CAAQ,CAAC;AAAA,EACzE;AACF;AAEA,SAAS,yBAAyB,KAAmB;AACnD,MAAI,IAAI,OAAO,kBAAkB,IAAI,OAAO,cAAc;AAGxD,QAAI,IAAI,QAAQ,OAAO,IAAI,QAAQ,OAAO,IAAI,QAAQ,KAAK;AACzD,UAAI,IAAI,WAAW,IAAI,SAAS;AAC9B,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,QAAQ,aAAa,IAAI,QAAQ,aAAa;AACpD,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,IAAI;AACnB,OACG,IAAI,QAAQ,eACX,IAAI,QAAQ,aACZ,IAAI,QAAQ,gBACd,OAAO,mBAAmB,GAC1B;AACA,WAAO;AAAA,EACT;AAEA,OACG,IAAI,QAAQ,gBACX,IAAI,QAAQ,aACZ,IAAI,QAAQ,SACZ,IAAI,QAAQ,WACZ,IAAI,QAAQ,gBACd,OAAO,mBAAmB,IAAI,OAAO,MAAM,QAC3C;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEO,SAAS,wBAAwB,KAAU;AAChD,MAAI,IAAI,QAAQ,SAAS;AAEvB,QAAI,gBAAA;AACJ;AAAA,EACF;AAEA,MAAI,IAAI,QAAQ,UAAU;AACxB,QAAI,eAAA;AACJ;AAAA,EACF;AAEA,QAAM,kBAAkB,yBAAyB,GAAG;AACpD,MAAI,CAAC,iBAAiB;AACpB,QAAI,gBAAA;AAAA,EACN,OAAO;AACL,QAAI,OAAO,KAAA;AAAA,EACb;AACF;"}
1
+ {"version":3,"file":"key-handling.js","sources":["../../src/utils/key-handling.ts"],"sourcesContent":["import type { KeyboardEvent } from \"react\";\nimport {\n storeAPIAtom,\n storeAtom,\n tableActionsAtom,\n type DataSheetStoreMain,\n singleFocusedCell,\n ctx,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { runActionWrapper } from \"../actions\";\nimport { actionRequiresEditable } from \"../actions/selection.ts\";\nimport { HotkeyConfig } from \"@blueprintjs/core\";\nimport { toasterAtom } from \"../notifications.ts\";\n\ntype HotkeyActionRunner = (\n e: KeyboardEvent,\n state: DataSheetStoreMain<any>,\n setState: (state: Partial<DataSheetStoreMain<any>>) => void,\n) => void | Promise<void>;\n\nconst isEditableAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.editable ?? false;\n});\n\nconst hasSelectionAtom = atom((get) => {\n const store = get(storeAtom);\n const selection = store?.selection ?? [];\n return selection.length > 0;\n});\n\nexport const tableHotkeysAtom = atom<null, [], HotkeyConfig[]>(\n null,\n (get, set) => {\n const store = get(storeAPIAtom);\n const toaster = get(toasterAtom);\n const editable = get(isEditableAtom);\n\n /** Set up hotkeys for table actions */\n const tableActions = get(tableActionsAtom);\n\n if (store == null) return [];\n const keyHandler = (\n actionRunner: HotkeyActionRunner,\n ): HotkeyConfig[\"onKeyDown\"] => {\n return (e) => {\n // Kind of a ridiculous hack to get the store from the atom.\n const state = store.getState();\n const setState = store.setState;\n try {\n const res = actionRunner(e as any, state, setState);\n if (res instanceof Promise) {\n res\n .then(() => {})\n .catch((err) => {\n console.error(err);\n handleError(toaster, err);\n });\n }\n } catch (err) {\n handleError(toaster, err);\n }\n };\n };\n\n function handleError(toaster, err) {\n toaster.show({\n message: `${err}`,\n intent: \"danger\",\n });\n }\n\n const directionCombos = [\"up\", \"down\", \"left\", \"right\"].map((dir) => {\n return {\n combo: dir,\n group: \"Navigation\",\n label: \"Move focus \" + dir,\n preventDefault: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(dir as any);\n }),\n };\n });\n\n /** TODO: merge a bit more with the actions config */\n\n const actionsCombos = tableActions\n .map((action) => {\n if (action.hotkey == null) return null;\n return {\n combo: action.hotkey,\n label: action.name,\n group: action.group ?? \"Actions\",\n preventDefault: true,\n disabled: actionRequiresEditable(action) && !editable,\n onKeyDown(event: KeyboardEvent<any>): any {\n runActionWrapper(action, get, set, toaster);\n },\n } as any as HotkeyConfig;\n })\n .filter(Boolean) as HotkeyConfig[];\n\n // Backspace/Delete: on a whole-row selection, delete the row(s); otherwise\n // clear the selected cells.\n const clearOrDeleteSelection = keyHandler((e, state) => {\n const sel = state.selection ?? [];\n const isRowSelection =\n sel.length > 0 && sel.every((r) => r.cols == null && r.rows != null);\n if (isRowSelection) {\n state.deleteSelectedRows();\n } else {\n state.clearSelection();\n }\n });\n\n return [\n {\n combo: \"esc\",\n label: \"Exit editing / clear selection\",\n group: \"Selection\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // First Escape closes the focused cell's open surface (editor/panel)\n // while keeping the selection, so arrow keys keep working — in both\n // auto and manual modes. A second Escape (nothing open) clears the\n // selection.\n if (state.cellSurfaceOpen) {\n state.closeCellSurface();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n if (state.selection.length == 0) {\n // Focus goes back to parent\n return;\n }\n state.setSelection([]);\n e.preventDefault();\n e.stopPropagation();\n }),\n },\n {\n combo: \"backspace\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"del\",\n label: \"Clear cells / delete rows\",\n group: \"Selection\",\n allowInInput: true,\n disabled: !editable,\n onKeyDown: clearOrDeleteSelection,\n },\n {\n combo: \"tab\",\n label: \"Move focus right (or left with shift)\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n state.moveFocusedCell(e.shiftKey ? \"left\" : \"right\");\n }),\n },\n {\n combo: \"enter\",\n label: \"Edit cell / move focus down\",\n group: \"Navigation\",\n allowInInput: true,\n onKeyDown: keyHandler((e, state) => {\n // In navigation mode (no surface open), Enter enters edit mode —\n // opening and focusing the focused cell's surface (Google Sheets\n // style). While a surface is open, Enter advances downward as usual\n // (an inline editor blurs and this moves to the next row).\n if (!state.cellSurfaceOpen) {\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n return;\n }\n state.moveFocusedCell(\"down\");\n }),\n },\n {\n combo: \"f2\",\n label: \"Edit / open cell\",\n group: \"Editing\",\n onKeyDown: keyHandler((e, state) => {\n // Enter edit mode from the keyboard: re-arm auto-activation and open\n // the focused cell's surface (which focuses the editor).\n state.armAutoActivate();\n state.openCellSurface();\n e.preventDefault();\n }),\n },\n ...directionCombos,\n ...actionsCombos,\n ];\n },\n);\n\nconst selectionAtom = atom((get) => {\n const store = get(storeAtom);\n return store?.selection ?? [];\n});\n\nconst isSingleCellSelectionAtom = atom((get) => {\n const selection = get(selectionAtom);\n return singleFocusedCell(selection) != null;\n});\n\nexport const editorKeyHandlerAtom = atom((get) => {\n const store = get(storeAPIAtom);\n return (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n // Escape exits the inline editor: close the surface (which enters\n // navigation mode in auto), keep the selection, and return focus to the\n // table so arrow keys navigate. Stop propagation so the table's own\n // Escape hotkey doesn't also fire.\n const state = store?.getState();\n state?.closeCellSurface();\n state?.tableElement?.focus();\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n const isSingleCellSelection = get(isSingleCellSelectionAtom);\n editorKeyHandler(e as any, isSingleCellSelection);\n };\n});\n\nfunction editorKeyHandler(\n e: KeyboardEvent<HTMLInputElement>,\n isSingleCellSelection: boolean,\n) {\n /** Get a key handler for inline cell editing */\n\n const target = e.target as HTMLInputElement;\n\n let shouldCaptureEventForInlineEditing = true;\n\n if (e.key == \"Enter\") {\n shouldCaptureEventForInlineEditing = e.shiftKey;\n }\n\n if (e.key == \"Escape\" || e.key == \"Tab\") {\n shouldCaptureEventForInlineEditing = false;\n }\n\n if (e.key == \"Backspace\" || e.key == \"Delete\") {\n /** Clear selection on Backspace or Delete on a multi-cell selection\n * (if shift is held, we allow deletion in a single cell)\n */\n shouldCaptureEventForInlineEditing = isSingleCellSelection && !e.shiftKey;\n }\n\n if (!shouldCaptureEventForInlineEditing) {\n target.blur();\n e.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(e);\n if (!shouldPropagate) {\n e.stopPropagation();\n //e.preventDefault();\n } else {\n // we blur the editor and dispatch a keydown event on the parent to propagate the event to the table\n e.preventDefault();\n target.blur();\n //console.log(tableElement);\n //tableElement.focus();\n //target.parentNode?.dispatchEvent(e);\n target.parentNode?.dispatchEvent(new KeyboardEvent(\"keydown\", e as any));\n }\n}\n\nfunction shouldPropagateKeystroke(evt: any): boolean {\n if (evt.target.selectionStart == evt.target.selectionEnd) {\n // We don't have anything selected, so we can propagate the event potentially\n // Propagate copy and paste events even if there is no selection, since they might want to copy/paste an entire row/column based on the focused cell.\n if (evt.key === \"c\" || evt.key === \"v\" || evt.key === \"x\") {\n if (evt.ctrlKey || evt.metaKey) {\n return true;\n }\n }\n }\n\n if (evt.key === \"ArrowUp\" || evt.key === \"ArrowDown\") {\n return true;\n }\n\n const target = evt.target;\n if (\n (evt.key === \"ArrowLeft\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === 0\n ) {\n return true;\n }\n\n if (\n (evt.key === \"ArrowRight\" ||\n evt.key === \"ArrowUp\" ||\n evt.key === \"Tab\" ||\n evt.key === \"Enter\" ||\n evt.key === \"ArrowDown\") &&\n target.selectionStart === evt.target.value.length\n ) {\n return true;\n }\n\n return false;\n}\n\nexport function multiLineTextKeyHandler(evt: any) {\n if (evt.key === \"Enter\") {\n //evt.preventDefault();\n evt.stopPropagation();\n return;\n }\n\n if (evt.key === \"Escape\") {\n evt.preventDefault();\n return;\n }\n\n const shouldPropagate = shouldPropagateKeystroke(evt);\n if (!shouldPropagate) {\n evt.stopPropagation();\n } else {\n evt.target.blur();\n }\n}\n"],"names":["toaster"],"mappings":";;;;;;AAqBA,MAAM,iBAAiB,KAAK,CAAC,QAAQ;AACnC,QAAM,QAAQ,IAAI,SAAS;AAC3B,SAAO,OAAO,YAAY;AAC5B,C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,OAAO,mBAAmB,IAAI,OAAO,MAAM,QAC3C;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEO,SAAS,wBAAwB,KAAU;AAChD,MAAI,IAAI,QAAQ,SAAS;AAEvB,QAAI,gBAAA;AACJ;AAAA,EACF;AAEA,MAAI,IAAI,QAAQ,UAAU;AACxB,QAAI,eAAA;AACJ;AAAA,EACF;AAEA,QAAM,kBAAkB,yBAAyB,GAAG;AACpD,MAAI,CAAC,iBAAiB;AACpB,QAAI,gBAAA;AAAA,EACN,OAAO;AACL,QAAI,OAAO,KAAA;AAAA,EACb;AACF;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macrostrat/data-sheet",
3
- "version": "4.9.0",
3
+ "version": "4.10.0",
4
4
  "description": "Scalable data sheet with optional editing capabilities",
5
5
  "repository": {
6
6
  "type": "git",
@@ -49,7 +49,7 @@
49
49
  "@blueprintjs/core": "^6.14.0",
50
50
  "@blueprintjs/table": "^6.1.0",
51
51
  "@macrostrat/color-utils": "^1.2.2",
52
- "@macrostrat/data-components": "^1.7.0",
52
+ "@macrostrat/data-components": "^1.8.0",
53
53
  "@macrostrat/hyper": "^3.1.1",
54
54
  "@macrostrat/scoped-store": "^1.1.0",
55
55
  "@macrostrat/ui-components": "^5.2.0",
@@ -127,14 +127,15 @@ export function computeSelectionShape(regions: Region[]): SelectionShape {
127
127
  }
128
128
 
129
129
  /** Filter actions to those applicable for the current selection cardinality
130
- * and edit mode. */
130
+ * and edit mode. An action takes edits unless it says otherwise
131
+ * (`requiresEditable` defaults to `true`). */
131
132
  export function getApplicableActions<T>(
132
133
  actions: TableAction<T>[],
133
134
  cardinality: RegionCardinality,
134
135
  editable: boolean,
135
136
  ): TableAction<T>[] {
136
137
  return actions.filter((action) => {
137
- if (action.requiresEditable && !editable) return false;
138
+ if (actionRequiresEditable(action) && !editable) return false;
138
139
  return action.targets.includes(cardinality);
139
140
  });
140
141
  }
@@ -242,3 +243,11 @@ export function range(arr: number[]) {
242
243
  const [start, end] = arr;
243
244
  return Array.from({ length: end - start + 1 }, (_, i) => i + start);
244
245
  }
246
+
247
+ /** Whether an action needs the table to be editable: unless it says it
248
+ * doesn't, as its type documents — and as the hotkeys have always read it. */
249
+ export function actionRequiresEditable(action: {
250
+ requiresEditable?: boolean;
251
+ }): boolean {
252
+ return action.requiresEditable ?? true;
253
+ }
@@ -27,7 +27,10 @@ import { type ReactNode, useState } from "react";
27
27
  import { Button, PopoverNext } from "@blueprintjs/core";
28
28
  import { type Region, RegionCardinality } from "@blueprintjs/table";
29
29
  import type { TableAction, TableActionContext } from "../actions";
30
- import { computeSelectionShape } from "../actions/selection.ts";
30
+ import {
31
+ actionRequiresEditable,
32
+ computeSelectionShape,
33
+ } from "../actions/selection.ts";
31
34
  import type { CellEdit, ColumnSpec } from "../provider";
32
35
  import styles from "./row-editor.module.sass";
33
36
 
@@ -69,7 +72,7 @@ export function editorActionsFor<T>(
69
72
  if (action.render != null || action.hotkey != null) return false;
70
73
  if (action.targets.includes(RegionCardinality.FULL_TABLE)) return false;
71
74
  if (!cardinalities.some((c) => action.targets.includes(c))) return false;
72
- if (action.requiresEditable && !target.editable) return false;
75
+ if (actionRequiresEditable(action) && !target.editable) return false;
73
76
  return action.appliesTo?.(ctx) ?? true;
74
77
  });
75
78
  return { actions: applicable, ctx };
@@ -99,6 +99,7 @@ export function useDataPanelControls(
99
99
  name: filter.name,
100
100
  icon: filter.icon,
101
101
  targets: ALL_CARDINALITIES,
102
+ requiresEditable: false,
102
103
  render: () => h(InlineFilterControl, { filter }),
103
104
  });
104
105
  }
@@ -303,6 +304,7 @@ function useFilterMenuAction(entries: FilterEntry[]): TableAction | null {
303
304
  icon: "filter",
304
305
  description: "Add a filter to the data panel.",
305
306
  targets: ALL_CARDINALITIES,
307
+ requiresEditable: false,
306
308
  render: (ctx) =>
307
309
  h(
308
310
  MenuDropdown,
@@ -341,6 +343,7 @@ function useSortAction(): TableAction | null {
341
343
  icon: "sort",
342
344
  description: "Add a sort to the data panel.",
343
345
  targets: ALL_CARDINALITIES,
346
+ requiresEditable: false,
344
347
  render: (ctx) =>
345
348
  h(MenuDropdown, { content: sortMenu }, [
346
349
  h(
@@ -3,6 +3,7 @@ import { type ReactNode, useCallback, useMemo, useState } from "react";
3
3
  import h from "./actions-toolbar.module.sass";
4
4
  import { ctx, selectionAtom, useSelector } from "../../provider";
5
5
  import {
6
+ actionRequiresEditable,
6
7
  getApplicableActions,
7
8
  getSelectionCardinality,
8
9
  mergeColumnActions,
@@ -58,11 +59,16 @@ export function ActionsToolbar<T>({
58
59
  );
59
60
 
60
61
  const store = ctx.useStore();
61
- // Context for `render`-style controls (they subscribe to the store
62
- // themselves; this resolves the selected column/rows).
62
+ // The context snapshots the store, so it is rebuilt when what it resolves
63
+ // changes: the selection (through `allActions`), and the rows. Keyed on the
64
+ // selection alone, a selection made together with new rows — an inserted
65
+ // row, selected as it arrives — resolved against the rows before it.
66
+ const data = useSelector((state) => state.data);
67
+ const updatedData = useSelector((state) => state.updatedData);
68
+ const filteredRowIndices = useSelector((state) => state.filteredRowIndices);
63
69
  const actionContext = useMemo(() => {
64
70
  return buildActionContext(store.get, store.set);
65
- }, [allActions]);
71
+ }, [allActions, data, updatedData, filteredRowIndices]);
66
72
 
67
73
  // The toolbar is for actions that AREN'T keyboard-accessible: any action
68
74
  // with a `hotkey` (copy/cut/paste, etc.) is reachable from the keyboard and
@@ -94,7 +100,7 @@ export function ActionsToolbar<T>({
94
100
  a.placement === "end" ||
95
101
  ((a.targets.includes(RegionCardinality.FULL_TABLE) ||
96
102
  a.targets.includes("none" as any)) &&
97
- a.requiresEditable);
103
+ actionRequiresEditable(a));
98
104
  const contextual = shownActions.filter((a) => !isGlobal(a));
99
105
  // Order the built-in global actions least→most impactful, left→right: reset
100
106
  // changes, then save. Any other global actions keep their natural order to
package/src/data-sheet.ts CHANGED
@@ -330,6 +330,12 @@ export function DataSheetRenderer<T>({
330
330
  storeState.setState({ tableElement: tableElementRef.current });
331
331
  }, [storeState]);
332
332
 
333
+ // The row height is the density's; cells report it to their renderers
334
+ const densityRowHeight = styleParamsForDensity(density).rowHeight;
335
+ useEffect(() => {
336
+ storeState.setState({ rowHeight: densityRowHeight });
337
+ }, [storeState, densityRowHeight]);
338
+
333
339
  useEffect(() => {
334
340
  storeState.setState({ onEdit });
335
341
  }, [storeState, onEdit]);
@@ -1,3 +1,10 @@
1
+ @use '@blueprintjs/core/lib/scss/variables' as bp
2
+
3
+ :global(.bp6-dark)
4
+ .data-sheet-container, .data-sheet-holder
5
+ --data-sheet-cell-background-color-internal: var(--data-sheet-cell-background-color, #{bp.$pt-dark-app-elevated-background-color})
6
+ --data-sheet-divider-color-internal: var(--data-sheet-divider-color, #{bp.$pt-dark-divider-black})
7
+
1
8
  .data-sheet-container, .data-sheet-holder
2
9
  flex: 1
3
10
  min-height: 0
@@ -6,6 +13,8 @@
6
13
  line-height: var(--data-sheet-row-height, 20px)
7
14
 
8
15
  --data-sheet-cell-padding: 0px 8px
16
+ --data-sheet-divider-color-internal: var(--data-sheet-divider-color, #{bp.$pt-divider-black})
17
+ --data-sheet-cell-background-color-internal: var(--data-sheet-cell-background-color, #{bp.$pt-app-elevated-background-color})
9
18
 
10
19
  :global
11
20
  // Tags drawn in a cell (a tag picker as a value renderer, say) are pinned
@@ -25,6 +34,11 @@
25
34
  font-size: var(--data-sheet-font-size)
26
35
  line-height: var(--data-sheet-row-height)
27
36
 
37
+ .bp6-table-cell
38
+ box-shadow: inset 0 -1px 0 var(--data-sheet-divider-color-internal), inset -1px 0 0 var(--data-sheet-divider-color-internal)
39
+ .bp6-table-cell-client
40
+ background-color: var(--data-sheet-cell-background-color-internal)
41
+
28
42
  .bp6-table-row-name
29
43
  color: var(--secondary-color)
30
44
 
@@ -65,6 +65,14 @@ export interface CellRenderContext<T = any> {
65
65
  /** Validation result for this cell, or `null` when valid. Orthogonal to the
66
66
  * edit status — a cell can be both edited and invalid. */
67
67
  validation: CellValidation | null;
68
+ /** The cell's size in pixels, border and padding included, when it is a
69
+ * grid cell — the column's width and the row's height, which the table
70
+ * knows and a renderer would otherwise have to measure. Absent on surfaces
71
+ * that aren't laid out in the cell (a popover, the row editor). A value
72
+ * renderer that lays itself out to fit — a row of tags — can re-fit when
73
+ * these change instead of observing its own size. */
74
+ width?: number;
75
+ height?: number;
68
76
  }
69
77
 
70
78
  /**
@@ -28,7 +28,14 @@ export type NavDirection = "up" | "down" | "left" | "right";
28
28
  */
29
29
  export type EditEvent<T = any> =
30
30
  | { type: "setCells"; cells: CellEdit[] }
31
- | { type: "deleteRows"; rowIndices: number[] }
31
+ | {
32
+ type: "deleteRows";
33
+ rowIndices: number[];
34
+ /** The rows deleted, as they were. Rows the table added are spliced out
35
+ * of its arrays before this is reported, so the indices alone can no
36
+ * longer be looked up. */
37
+ rows?: T[];
38
+ }
32
39
  | { type: "restoreRows"; rowIndices: number[] }
33
40
  | { type: "addRow"; rowIndex: number; value: Partial<T> }
34
41
  | { type: "resetChanges" };
@@ -115,7 +122,10 @@ export interface DataSheetState<T> {
115
122
  * suppressed — a function `columnSpec` derives it from the loaded rows
116
123
  * instead (in `_DataSheet`). Set at init from the prop's shape. */
117
124
  deferColumnSpec: boolean;
125
+ /** The cell a fill-drag copies from, while the drag lasts. */
118
126
  fillValueBaseCell: FocusedCellCoordinates | null;
127
+ /** The overlay as it stood when the fill-drag began. */
128
+ fillBaseData: T[] | null;
119
129
  focusedCell: FocusedCellCoordinates | null;
120
130
  topLeftCell: FocusedCellCoordinates | null;
121
131
  /**
@@ -204,6 +214,8 @@ export type StateUpdater<T> = T[] | ((state: T[]) => T[]);
204
214
  export interface DataSheetStoreMain<T> extends DataSheetVals<T> {
205
215
  setSelection(selection: Region[]): void;
206
216
  onDragValue(event: MouseEvent): void;
217
+ /** End a fill-drag: report the cells it wrote and disarm the anchor. */
218
+ finishFill(): void;
207
219
  setUpdatedData(data: StateUpdater<T>): void;
208
220
  onCellEdited(rowIndex: number, columnName: string, value: any): void;
209
221
  onSelectionEdited(value: any): void;
@@ -245,6 +257,8 @@ export interface DataSheetStoreMain<T> extends DataSheetVals<T> {
245
257
  tableRef: React.MutableRefObject<Table2> | null;
246
258
  columnWidthsIndex: Map<string, number>;
247
259
  defaultColumnWidth: number;
260
+ /** The grid's row height in pixels, from its density. */
261
+ rowHeight: number;
248
262
  // Editable is not optional on store
249
263
  editable: boolean;
250
264
  }