@macrostrat/data-sheet 4.0.0 → 4.1.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.
- package/CHANGELOG.md +24 -0
- package/README.md +11 -1
- package/dist/actions/column-controls.cjs +89 -0
- package/dist/actions/column-controls.cjs.map +1 -1
- package/dist/actions/column-controls.js +90 -1
- package/dist/actions/column-controls.js.map +1 -1
- package/dist/actions/selection.cjs +13 -2
- package/dist/actions/selection.cjs.map +1 -1
- package/dist/actions/selection.js +13 -2
- package/dist/actions/selection.js.map +1 -1
- package/dist/actions/table-controls.cjs +17 -0
- package/dist/actions/table-controls.cjs.map +1 -1
- package/dist/actions/table-controls.d.ts +4 -0
- package/dist/actions/table-controls.js +17 -0
- package/dist/actions/table-controls.js.map +1 -1
- package/dist/actions/toolbar.cjs +18 -2
- package/dist/actions/toolbar.cjs.map +1 -1
- package/dist/actions/toolbar.js +18 -2
- package/dist/actions/toolbar.js.map +1 -1
- package/dist/actions/types.d.ts +9 -0
- package/dist/cell-renderer.cjs +8 -6
- package/dist/cell-renderer.cjs.map +1 -1
- package/dist/cell-renderer.js +8 -6
- package/dist/cell-renderer.js.map +1 -1
- package/dist/core.cjs +59 -9
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.ts +28 -1
- package/dist/core.js +60 -10
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +4 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -2
- package/dist/renderers/column-header-cell.cjs +14 -28
- package/dist/renderers/column-header-cell.cjs.map +1 -1
- package/dist/renderers/column-header-cell.js +15 -29
- package/dist/renderers/column-header-cell.js.map +1 -1
- package/dist/types.cjs +11 -0
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +45 -1
- package/dist/types.js +11 -0
- package/dist/types.js.map +1 -1
- package/dist/utils/column-spec.cjs.map +1 -1
- package/dist/utils/column-spec.d.ts +4 -0
- package/dist/utils/column-spec.js.map +1 -1
- package/dist/zustand-store.cjs +6 -3
- package/dist/zustand-store.cjs.map +1 -1
- package/dist/zustand-store.js +7 -4
- package/dist/zustand-store.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/column-controls.ts +114 -0
- package/src/actions/selection.ts +15 -2
- package/src/actions/table-controls.ts +20 -0
- package/src/actions/toolbar.ts +30 -2
- package/src/actions/types.ts +10 -0
- package/src/cell-renderer.ts +17 -9
- package/src/core.ts +107 -12
- package/src/renderers/column-header-cell.ts +20 -32
- package/src/types.ts +56 -1
- package/src/utils/column-spec.ts +4 -0
- package/src/zustand-store.ts +11 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cell-renderer.js","sources":["../src/cell-renderer.ts"],"sourcesContent":["import {\n ColumnSpec,\n CellRenderContext,\n CellDetailContext,\n editorKeyHandlerAtom,\n validateCell,\n} from \"./utils\";\nimport { DataSheetStore, TableElementStatus } from \"./types.ts\";\nimport h from \"./main.module.sass\";\nimport { ReactNode, useEffect, useRef, useState } from \"react\";\nimport { EditorPopup, CellDetailModal } from \"./components\";\nimport { singleFocusedCell } from \"./zustand-store.ts\";\nimport { Cell } from \"@blueprintjs/table\";\nimport { ctx, useSelector } from \"./provider.ts\";\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 isDeleted = state.rowStatus[dataRowIndex] == TableElementStatus.DELETED;\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 const isEmpty = value == null || value === \"\";\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 ? null : validateCell(col, value, row, dataRowIndex);\n\n // Context passed to custom renderers so they can render based on the\n // row/column position and cell status (and, with the editing API, write\n // edits back). `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 validation,\n };\n\n const _renderedValue = isEmpty\n ? null\n : (col.valueRenderer?.(value, cellContext) ?? value);\n\n // Clone so we never mutate the caller's column-spec style object\n let style = { ...(col.style ?? {}) };\n\n if (isDeleted) {\n style.opacity = 0.5;\n style.textDecoration = \"line-through\";\n }\n\n const editable = (col.editable ?? state.editable) && !isDeleted;\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 const tableIsEditable = state.editable;\n\n // Intent precedence: error > warning > deleted > edited. Validation state\n // overrides the edited-green so an edited-but-invalid cell reads as invalid.\n let intent: string | undefined;\n if (validation?.severity === \"error\") {\n intent = \"danger\";\n } else if (validation?.severity === \"warning\") {\n intent = \"warning\";\n } else if (isDeleted) {\n intent = \"danger\";\n } else if (edited) {\n intent = \"success\";\n }\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 =\n 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 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 const detailPresentation =\n col.cellDetail != null ? (col.detailPresentation ?? \"popover\") : null;\n\n if (!topLeft) {\n // An inline surface is a persistent in-cell renderer, so it draws on every\n // cell (read-only when not the focused/editing cell).\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 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(EditorPopup, { valueViewer: _renderedValue }, content);\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: ReactNode = _renderedValue;\n\n let _dataEditor = null;\n let className = 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 state.onSelectionEdited(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 = \"value-viewer-cell\";\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 = 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)(DragHandle),\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 DragHandle() {\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 onMouseDown = useSelector((state) => state.onDragValue);\n return h(\"div.corner-drag-handle\", { onMouseDown });\n}\n"],"names":["value","className"],"mappings":";;;;;;;;;;AAeO,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,KAAK,mBAAmB;AAEtE,QAAM,MAAM,KAAK,YAAY,KAAK,YAAY,YAAY;AAC1D,QAAM,UAAU,OAAO;AACvB,QAAM,MAAM;AAEZ,QAAM,eAAe,MAAM;AAC3B,QAAM,eAAe,MAAM;AAE3B,QAAM,QACJ,YAAY,YAAY,IAAI,IAAI,GAAG,KAAK,KAAK,YAAY,IAAI,IAAI,GAAG;AACtE,QAAM,UAAU,SAAS,QAAQ,UAAU;AAE3C,QAAM,SACJ,YAAY,YAAY,IAAI,IAAI,GAAG,KAAK,QACxC,MAAM,UAAU,YAAY,MAAM,mBAAmB;AAGvD,QAAM,aAAa,YAAY,OAAO,aAAa,KAAK,OAAO,KAAK,YAAY;AAKhF,QAAM,cAAoC;AAAA,IACxC;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EAAA;AAGF,QAAM,iBAAiB,UACnB,OACC,IAAI,gBAAgB,OAAO,WAAW,KAAK;AAGhD,MAAI,QAAQ,EAAE,GAAI,IAAI,SAAS,CAAA,EAAC;AAEhC,MAAI,WAAW;AACb,UAAM,UAAU;AAChB,UAAM,iBAAiB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AAG;AAAA,EAAA,CACJ;AACH;AAEA,SAAS,aAAa;AAGpB,QAAM,cAAc,YAAY,CAAC,UAAU,MAAM,WAAW;AAC5D,SAAO,EAAE,0BAA0B,EAAE,aAAa;AACpD;"}
|
|
1
|
+
{"version":3,"file":"cell-renderer.js","sources":["../src/cell-renderer.ts"],"sourcesContent":["import {\n ColumnSpec,\n CellRenderContext,\n CellDetailContext,\n editorKeyHandlerAtom,\n validateCell,\n} from \"./utils\";\nimport { DataSheetStore, TableElementStatus } from \"./types.ts\";\nimport h from \"./main.module.sass\";\nimport { ReactNode, useEffect, useRef, useState } from \"react\";\nimport { EditorPopup, CellDetailModal } from \"./components\";\nimport { singleFocusedCell } from \"./zustand-store.ts\";\nimport { Cell } from \"@blueprintjs/table\";\nimport { ctx, useSelector } from \"./provider.ts\";\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 = 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 const isEmpty = value == null || value === \"\";\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 ? null : validateCell(col, value, row, dataRowIndex);\n\n // Context passed to custom renderers so they can render based on the\n // row/column position and cell status (and, with the editing API, write\n // edits back). `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 const _renderedValue = isEmpty\n ? null\n : (col.valueRenderer?.(value, cellContext) ?? value);\n\n // Clone so we never mutate the caller's column-spec style object, then layer\n // the row-status presentation (deleted → dimmed/struck-through by default;\n // consumer statuses supply their own `cellStyle`).\n let style = { ...(col.style ?? {}) };\n\n if (statusStyle?.cellStyle != null) {\n style = { ...style, ...statusStyle.cellStyle };\n }\n\n const editable = (col.editable ?? state.editable) && !isDeleted;\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 const tableIsEditable = state.editable;\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: string | 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 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 =\n 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 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 const detailPresentation =\n col.cellDetail != null ? (col.detailPresentation ?? \"popover\") : null;\n\n if (!topLeft) {\n // An inline surface is a persistent in-cell renderer, so it draws on every\n // cell (read-only when not the focused/editing cell).\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 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(EditorPopup, { valueViewer: _renderedValue }, content);\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: ReactNode = _renderedValue;\n\n let _dataEditor = null;\n let className = 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 state.onSelectionEdited(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 = \"value-viewer-cell\";\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 = 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)(DragHandle),\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 DragHandle() {\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 onMouseDown = useSelector((state) => state.onDragValue);\n return h(\"div.corner-drag-handle\", { onMouseDown });\n}\n"],"names":["value","className"],"mappings":";;;;;;;;;;AAeO,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,cAAc,aAAa,OAAO,MAAM,kBAAkB,SAAS,IAAI;AAE7E,QAAM,MAAM,KAAK,YAAY,KAAK,YAAY,YAAY;AAC1D,QAAM,UAAU,OAAO;AACvB,QAAM,MAAM;AAEZ,QAAM,eAAe,MAAM;AAC3B,QAAM,eAAe,MAAM;AAE3B,QAAM,QACJ,YAAY,YAAY,IAAI,IAAI,GAAG,KAAK,KAAK,YAAY,IAAI,IAAI,GAAG;AACtE,QAAM,UAAU,SAAS,QAAQ,UAAU;AAE3C,QAAM,SACJ,YAAY,YAAY,IAAI,IAAI,GAAG,KAAK,QACxC,MAAM,UAAU,YAAY,MAAM,mBAAmB;AAGvD,QAAM,aAAa,YAAY,OAAO,aAAa,KAAK,OAAO,KAAK,YAAY;AAKhF,QAAM,cAAoC;AAAA,IACxC;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,EAAA;AAGF,QAAM,iBAAiB,UACnB,OACC,IAAI,gBAAgB,OAAO,W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AAC;AAChB,SAAO,EAAE,SAAS;AAAA,IAChB,KAAK;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR,OAAO,UAAU;AAAA,IACjB,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA,IACxC,GAAG;AAAA,EAAA,CACJ;AACH;AAEA,SAAS,aAAa;AAGpB,QAAM,cAAc,YAAY,CAAC,UAAU,MAAM,WAAW;AAC5D,SAAO,EAAE,0BAA0B,EAAE,aAAa;AACpD;"}
|
package/dist/core.cjs
CHANGED
|
@@ -17,6 +17,7 @@ const toolbar = require("./actions/toolbar.cjs");
|
|
|
17
17
|
const viewInfo = require("./components/view-info.cjs");
|
|
18
18
|
const debugOverlay = require("./utils/debug-overlay.cjs");
|
|
19
19
|
const columnControls = require("./actions/column-controls.cjs");
|
|
20
|
+
const tableControls = require("./actions/table-controls.cjs");
|
|
20
21
|
const clipboard = require("./actions/clipboard.cjs");
|
|
21
22
|
const builtin = require("./actions/builtin.cjs");
|
|
22
23
|
const editActions = require("./actions/edit-actions.cjs");
|
|
@@ -61,10 +62,6 @@ function DataSheet(props) {
|
|
|
61
62
|
})
|
|
62
63
|
);
|
|
63
64
|
}
|
|
64
|
-
const deletedRowHeaderStyle = {
|
|
65
|
-
opacity: 0.5,
|
|
66
|
-
textDecoration: "line-through"
|
|
67
|
-
};
|
|
68
65
|
async function persistViaProvider(provider2, ctx2) {
|
|
69
66
|
const base = ctx2.data ?? [];
|
|
70
67
|
const updates = ctx2.updatedData ?? [];
|
|
@@ -110,6 +107,8 @@ function _DataSheet({
|
|
|
110
107
|
updatedData: updatedDataProp,
|
|
111
108
|
rowStatus: rowStatusProp,
|
|
112
109
|
identity,
|
|
110
|
+
deriveOverlay,
|
|
111
|
+
refreshToken,
|
|
113
112
|
onDeleteRows,
|
|
114
113
|
name,
|
|
115
114
|
verbose = false,
|
|
@@ -122,6 +121,9 @@ function _DataSheet({
|
|
|
122
121
|
actions,
|
|
123
122
|
filters: filters$1,
|
|
124
123
|
columnHeaderCellRenderer,
|
|
124
|
+
statusBar,
|
|
125
|
+
rowStatusStyles,
|
|
126
|
+
rowHeaderRenderer,
|
|
125
127
|
children,
|
|
126
128
|
...rest
|
|
127
129
|
}) {
|
|
@@ -162,6 +164,7 @@ function _DataSheet({
|
|
|
162
164
|
};
|
|
163
165
|
if (actions != null) add(actions);
|
|
164
166
|
add(columnControls.columnControlActions);
|
|
167
|
+
add([tableControls.clearSelectionAction]);
|
|
165
168
|
if (enableClipboard) add(clipboard.clipboardActions);
|
|
166
169
|
if (editable) {
|
|
167
170
|
if (saveHandler != null) add([editActions.createSaveAction(saveHandler)]);
|
|
@@ -236,12 +239,30 @@ function _DataSheet({
|
|
|
236
239
|
storeState.setState({ onEdit });
|
|
237
240
|
}, [storeState, onEdit]);
|
|
238
241
|
react.useEffect(() => {
|
|
239
|
-
const controlled = updatedDataProp !== void 0 || rowStatusProp !== void 0;
|
|
242
|
+
const controlled = updatedDataProp !== void 0 || rowStatusProp !== void 0 || deriveOverlay != null;
|
|
240
243
|
const patch = { controlledOverlay: controlled };
|
|
241
244
|
if (updatedDataProp !== void 0) patch.updatedData = updatedDataProp;
|
|
242
245
|
if (rowStatusProp !== void 0) patch.rowStatus = rowStatusProp;
|
|
243
246
|
storeState.setState(patch);
|
|
244
|
-
}, [storeState, updatedDataProp, rowStatusProp]);
|
|
247
|
+
}, [storeState, updatedDataProp, rowStatusProp, deriveOverlay]);
|
|
248
|
+
const loadedData = provider.useSelector((state) => state.data);
|
|
249
|
+
react.useEffect(() => {
|
|
250
|
+
if (deriveOverlay == null) return;
|
|
251
|
+
const overlay = deriveOverlay(loadedData);
|
|
252
|
+
storeState.setState({
|
|
253
|
+
updatedData: overlay.updatedData,
|
|
254
|
+
rowStatus: overlay.rowStatus
|
|
255
|
+
});
|
|
256
|
+
}, [deriveOverlay, loadedData, storeState]);
|
|
257
|
+
const bumpRefreshFromToken = provider.ctx.useSet(dataLoaders.dataRefreshTokenAtom);
|
|
258
|
+
const firstRefreshToken = react.useRef(true);
|
|
259
|
+
react.useEffect(() => {
|
|
260
|
+
if (firstRefreshToken.current) {
|
|
261
|
+
firstRefreshToken.current = false;
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
bumpRefreshFromToken((v) => v + 1);
|
|
265
|
+
}, [refreshToken, bumpRefreshFromToken]);
|
|
245
266
|
react.useEffect(() => {
|
|
246
267
|
const id = activeProvider?.identity ?? identity;
|
|
247
268
|
if (id != null) storeState.setState({ identity: id });
|
|
@@ -250,6 +271,13 @@ function _DataSheet({
|
|
|
250
271
|
const canDeleteRows = provider$1 == null || provider$1.deleteRows != null;
|
|
251
272
|
storeState.setState({ canDeleteRows });
|
|
252
273
|
}, [storeState, provider$1]);
|
|
274
|
+
const mergedRowStatusStyles = react.useMemo(
|
|
275
|
+
() => ({ ...types.DEFAULT_ROW_STATUS_STYLES, ...rowStatusStyles }),
|
|
276
|
+
[rowStatusStyles]
|
|
277
|
+
);
|
|
278
|
+
react.useEffect(() => {
|
|
279
|
+
storeState.setState({ rowStatusStyles: mergedRowStatusStyles });
|
|
280
|
+
}, [storeState, mergedRowStatusStyles]);
|
|
253
281
|
const realizedColumns = react.useMemo(() => {
|
|
254
282
|
return columnSpec.map((col, colIndex) => {
|
|
255
283
|
let fn = col.headerCellRenderer ?? columnHeaderCellRenderer ?? columnHeaderCell.renderColumnHeaderCell;
|
|
@@ -302,15 +330,36 @@ function _DataSheet({
|
|
|
302
330
|
const rowHeaderCellRenderer = react.useCallback(
|
|
303
331
|
(rowIndex) => {
|
|
304
332
|
const dataRowIndex = filteredRowIndices != null ? filteredRowIndices[rowIndex] ?? rowIndex : rowIndex;
|
|
305
|
-
const
|
|
333
|
+
const statusVal = rowStatus[dataRowIndex];
|
|
334
|
+
const style2 = (statusVal != null ? mergedRowStatusStyles[statusVal]?.headerStyle : null) ?? null;
|
|
335
|
+
const defaultLabel = `${dataRowIndex + 1}`;
|
|
336
|
+
let name2 = defaultLabel;
|
|
337
|
+
if (rowHeaderRenderer != null) {
|
|
338
|
+
const custom = rowHeaderRenderer({
|
|
339
|
+
rowIndex: dataRowIndex,
|
|
340
|
+
visibleIndex: rowIndex,
|
|
341
|
+
row: data[dataRowIndex] ?? updatedData[dataRowIndex],
|
|
342
|
+
status: statusVal,
|
|
343
|
+
isDeleted: statusVal === types.TableElementStatus.DELETED,
|
|
344
|
+
defaultLabel
|
|
345
|
+
});
|
|
346
|
+
if (custom != null) name2 = custom;
|
|
347
|
+
}
|
|
306
348
|
return main_module.default(table.RowHeaderCell, {
|
|
307
349
|
enableRowReordering: false,
|
|
308
350
|
index: rowIndex,
|
|
309
|
-
name:
|
|
351
|
+
name: name2,
|
|
310
352
|
style: style2
|
|
311
353
|
});
|
|
312
354
|
},
|
|
313
|
-
[
|
|
355
|
+
[
|
|
356
|
+
rowStatus,
|
|
357
|
+
filteredRowIndices,
|
|
358
|
+
mergedRowStatusStyles,
|
|
359
|
+
rowHeaderRenderer,
|
|
360
|
+
data,
|
|
361
|
+
updatedData
|
|
362
|
+
]
|
|
314
363
|
);
|
|
315
364
|
let _selectionModes = selectionModes;
|
|
316
365
|
if (editable && _selectionModes != null && !_selectionModes.includes(table.RegionCardinality.CELLS)) {
|
|
@@ -385,6 +434,7 @@ function _DataSheet({
|
|
|
385
434
|
),
|
|
386
435
|
main_module.default("div.status-bar", [
|
|
387
436
|
filterStatus,
|
|
437
|
+
statusBar,
|
|
388
438
|
main_module.default("div.spacer"),
|
|
389
439
|
main_module.default.if(_showLoadProgress)(viewInfo.LoadProgressIndicator)
|
|
390
440
|
]),
|
package/dist/core.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs","sources":["../src/core.ts"],"sourcesContent":["import { useHotkeys } from \"@blueprintjs/core\";\nimport {\n Column,\n Region,\n RegionCardinality,\n RowHeaderCell,\n Table,\n TableProps,\n} from \"@blueprintjs/table\";\nimport \"@blueprintjs/table/lib/css/table.css\";\nimport { ReactNode, useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { LoadProgressIndicator } from \"./components\";\nimport { renderColumnHeaderCell } from \"./renderers\";\nimport h from \"./main.module.sass\";\nimport {\n columnSpecAtom,\n ctx,\n DataSheetProvider,\n storeAtom,\n tableActionsAtom,\n useSelector,\n useStoreAPI,\n} from \"./provider\";\nimport { atom } from \"jotai\";\nimport {\n DataSheetProviderProps,\n EditEvent,\n TableElementStatus,\n VisibleCells,\n} from \"./types.ts\";\nimport { basicCellRenderer } from \"./cell-renderer.ts\";\nimport { CellRendererDebugOverlay, tableHotkeysAtom } from \"./utils\";\nimport {\n ActionsToolbar,\n clipboardActions,\n columnControlActions,\n createSaveAction,\n FilterBar,\n resetChangesAction,\n TableAction,\n TableActionContext,\n TableFilter,\n} from \"./actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataOptions,\n tableFooterAtom,\n TableDataProvider,\n useScrollHandler,\n useDataLoader,\n} from \"./postgrest-table\";\n\n// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args\n\n// TODO: add a \"copy to selection\" tool (the little square in the bottom right corner of a cell)\n// This should copy the value of a cell (or a set of cells in the same row) downwards.\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/** Approximate column-header + scrollbar allowance, used to size the table to\n * its content in paged mode. */\nconst COLUMN_HEADER_HEIGHT = 34;\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\ninterface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n // An optional table name that will be used in toolbars if given\n name?: string;\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n editable?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n}\n\ntype DataSheetProps<T> = DataSheetProviderProps<T> & DataSheetInternalProps<T>;\n\nconst emptyData: any[] = [];\n\nexport function DataSheet<T>(props: DataSheetProps<T>) {\n const {\n data,\n columnSpec,\n columnSpecOptions,\n editable = true,\n enableColumnReordering = false,\n enableFocusedCell = false,\n defaultColumnWidth = 150,\n children,\n ...rest\n } = props;\n\n return h(\n DataSheetProvider<T>,\n {\n data: data ?? emptyData,\n columnSpec,\n columnSpecOptions,\n enableColumnReordering,\n defaultColumnWidth,\n editable,\n ...rest,\n },\n h(_DataSheet<any>, {\n ...rest,\n data: data ?? emptyData,\n children,\n editable,\n enableColumnReordering,\n enableFocusedCell,\n }),\n );\n}\n\nconst deletedRowHeaderStyle = {\n opacity: 0.5,\n textDecoration: \"line-through\",\n};\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nasync function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n\nfunction _DataSheet<T>({\n data: sourceData,\n fetchData,\n provider,\n pageSize,\n fetchMode,\n onVisibleCellsChange,\n onUpdateData,\n onEdit,\n onSave,\n updatedData: updatedDataProp,\n rowStatus: rowStatusProp,\n identity,\n onDeleteRows,\n name,\n verbose = false,\n enableFocusedCell,\n autoFocusEditor = true,\n cellInteraction,\n enableClipboard = true,\n density = DataSheetDensity.HIGH,\n selectionModes,\n actions,\n filters,\n columnHeaderCellRenderer,\n children,\n ...rest\n}: DataSheetInternalProps<T>) {\n /**\n * @param data: The data to be displayed in the table\n * @param columnSpec: The specification for all columns in the table. If not provided, the column spec will be generated from the data.\n * @param columnSpecOptions: Options for generating a column spec from data\n */\n\n // Turn on debug features\n const debugMode = false;\n\n const editable = useSelector((state) => state.editable);\n\n // Resolve the active data provider: an explicit `provider` prop wins; else a\n // loose `fetchData` (+ identity) is wrapped as one; else in-memory `data`\n // becomes a local provider. Local and remote thus share one path, and the\n // provider is an explicit contract rather than a set of scattered props.\n const isLocalProvider = provider == null && fetchData == null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (provider != null) return provider;\n if (fetchData != null) {\n return { fetchData, identity: identity ?? ((r: any) => r?.id) };\n }\n if (sourceData != null && sourceData.length > 0) {\n return createLocalProvider(\n sourceData,\n identity != null ? { identity } : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [provider, fetchData, sourceData, identity]);\n\n // When an explicit provider owns persistence, its methods drive the built-in\n // Save (batch: edits→saveRows, added→insertRow, deleted→deleteRows), then a\n // refresh. Otherwise the loose `onSave` handler is used.\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n const providerSave = useMemo(() => {\n const p = provider;\n if (\n p == null ||\n (p.saveRows == null && p.deleteRows == null && p.insertRow == null)\n ) {\n return null;\n }\n return async (actionCtx: TableActionContext<T>) => {\n await persistViaProvider(p, actionCtx);\n bumpRefresh((v) => v + 1);\n };\n }, [provider, bumpRefresh]);\n const saveHandler = onSave ?? providerSave;\n\n // Sync table actions to atom. Consumer actions come first (they override a\n // built-in by reusing its id); the built-in column controls (sort/filter)\n // fill in the rest — so both the toolbar and the header dropdown source from\n // one registry. Built-ins self-gate (single sortable/filterable column).\n const _actions: TableAction[] = useMemo(() => {\n const _actions: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!_actions.some((x) => x.id === a.id)) _actions.push(a);\n }\n };\n if (actions != null) add(actions);\n add(columnControlActions);\n if (enableClipboard) add(clipboardActions);\n // Save/reset last — they're the most significant actions — and present for\n // every cardinality (editable), so the toolbar stays mounted regardless of\n // selection.\n if (editable) {\n if (saveHandler != null) add([createSaveAction(saveHandler)]);\n add([resetChangesAction]);\n }\n return _actions;\n }, [actions, enableClipboard, editable, saveHandler]);\n\n ctx.useSync(tableActionsAtom, _actions);\n\n const hotkeysConfig = ctx.useValue(tableHotkeysAtom);\n const { handleKeyDown, handleKeyUp } = useHotkeys(hotkeysConfig);\n\n // For now, we only consider a single cell \"focused\" when we have one cell selected.\n // Multi-cell selections have a different set of \"bulk\" actions.\n const selectedRegions = useSelector<T>((state) => state.selection ?? []);\n\n const data = useSelector((state) => state.data);\n\n const rowStatus = useSelector((state) => state.rowStatus);\n\n const focusedCell = useSelector((state) => state.focusedCell);\n\n const ref = useSelector((state) => state.tableRef);\n\n const columnSpec = useSelector((state) => state.columnSpec);\n\n // A sparse array to hold updates\n // TODO: create a \"changeset\" concept to facilitate undo/redo\n const updatedData = useSelector((state) => state.updatedData);\n\n const onSelection = useSelector((state) => state.onSelection);\n\n const storeAPI = useStoreAPI<T>();\n\n const onScroll = useScrollHandler();\n const _onVisibleCellsChange = useCallback(\n (visibleCells: VisibleCells) => {\n onScroll(visibleCells);\n onVisibleCellsChange?.(visibleCells);\n },\n [onVisibleCellsChange, onScroll],\n );\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Updated data\", updatedData);\n }, [updatedData]);\n\n useEffect(() => {\n onUpdateData?.(updatedData, data);\n }, [onUpdateData, data, updatedData]);\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Selected regions\", selectedRegions);\n }, [selectedRegions]);\n\n const tableElementRef = useRef<HTMLElement>(null);\n useEffect(() => {\n // Return the focus to the table\n tableElementRef.current?.focus();\n }, [focusedCell]);\n\n const columnWidths = ctx.useValue(columnWidthsAtom);\n\n // When filters are active, only show matching rows\n const filteredRowIndices = useSelector((state) => state.filteredRowIndices);\n const totalRows = Math.max(updatedData.length, data.length);\n const numRows =\n filteredRowIndices != null ? filteredRowIndices.length : totalRows;\n\n let className = `${density}-density`;\n\n const { rowHeight, style } = styleParamsForDensity(density);\n\n // In paged mode the row count is small and fixed, so let the table size to\n // its content (header + rows) instead of filling the viewport.\n const footerInfo = ctx.useValue(tableFooterAtom);\n const holderStyle =\n footerInfo.mode === \"paged\"\n ? {\n flex: \"0 0 auto\" as const,\n height: numRows * rowHeight + COLUMN_HEADER_HEIGHT,\n }\n : undefined;\n\n const onColumnsReordered = useSelector((state) => state.onColumnsReordered);\n\n // Auto-detect if any columns have sortable/filterable set.\n // If so and no explicit columnHeaderCellRenderer was provided,\n // use the built-in client-side sort/filter header.\n const hasSortableOrFilterable = useMemo(\n () =>\n columnSpec.some(\n (col) =>\n col.sortable ||\n col.filterable ||\n (Array.isArray(col.filters) && col.filters.length > 0),\n ),\n [columnSpec],\n );\n\n const columnSorts = useSelector((state) => state.columnSorts);\n const activeFilters = useSelector((state) => state.activeFilters);\n\n // Cell activation mode, defaulting from the legacy `autoFocusEditor` boolean\n // so existing consumers are unaffected. Synced into the store so the cell\n // renderer, editors, and key handlers all read it consistently.\n const cellInteractionMode: CellInteraction =\n cellInteraction ?? (autoFocusEditor ? \"auto\" : \"manual\");\n\n const storeState = storeAPI;\n useEffect(() => {\n storeState.setState({ cellInteraction: cellInteractionMode });\n }, [storeState, cellInteractionMode]);\n\n useEffect(() => {\n // Give the store a handle to the focusable holder so editors can return\n // keyboard focus to the table when the cursor leaves them.\n storeState.setState({ tableElement: tableElementRef.current });\n }, [storeState]);\n\n useEffect(() => {\n storeState.setState({ onEdit });\n }, [storeState, onEdit]);\n\n useEffect(() => {\n // Controlled overlay: mirror the caller's edited state into the store as\n // the source of truth. Optimistic in-table edits are superseded on the\n // next render when the caller passes an updated value back. When the caller\n // controls it, the loader-boundary identity remap steps aside.\n const controlled =\n updatedDataProp !== undefined || rowStatusProp !== undefined;\n const patch: Record<string, unknown> = { controlledOverlay: controlled };\n if (updatedDataProp !== undefined) patch.updatedData = updatedDataProp;\n if (rowStatusProp !== undefined) patch.rowStatus = rowStatusProp;\n storeState.setState(patch);\n }, [storeState, updatedDataProp, rowStatusProp]);\n\n // The active provider supplies the row identity for the edit overlay.\n useEffect(() => {\n const id = activeProvider?.identity ?? identity;\n if (id != null) storeState.setState({ identity: id });\n }, [storeState, activeProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` without\n // `deleteRows` disables deletion entirely. (Local / loose sources keep the\n // local delete overlay.)\n useEffect(() => {\n const canDeleteRows = provider == null || provider.deleteRows != null;\n storeState.setState({ canDeleteRows });\n }, [storeState, provider]);\n\n const realizedColumns = useMemo(() => {\n return columnSpec.map((col, colIndex) => {\n let fn =\n col.headerCellRenderer ??\n columnHeaderCellRenderer ??\n renderColumnHeaderCell;\n let activeSort = null;\n let activeFilter = null;\n if (col.sortable) {\n activeSort = columnSorts?.find((s) => s.key === col.key);\n }\n // The active filter for this column is whichever active filter targets\n // it (a rich `col.filters` filter or the generic operator filter) — match\n // by columnKey rather than a fixed id.\n for (const entry of activeFilters?.values() ?? []) {\n if ((entry as any)?.filter?.columnKey === col.key) {\n activeFilter = entry;\n break;\n }\n }\n\n const _columnHeaderCellRenderer = (colIndex) => {\n return fn({\n col,\n colIndex,\n activeSort,\n activeFilter,\n });\n };\n\n return h(Column, {\n id: col.key,\n name: col.name,\n columnHeaderCellRenderer: _columnHeaderCellRenderer,\n cellRenderer: (rowIndex) => {\n const state = storeAPI.getState();\n return basicCellRenderer<T>(\n rowIndex,\n colIndex,\n col,\n state,\n filteredRowIndices,\n );\n },\n });\n });\n }, [\n columnSpec,\n columnSorts,\n activeFilters,\n storeAPI,\n filteredRowIndices,\n columnHeaderCellRenderer,\n ]);\n\n const onColumnWidthChanged = useSelector(\n (state) => state.onColumnWidthChanged,\n );\n\n const rowHeaderCellRenderer = useCallback(\n (rowIndex: number) => {\n const dataRowIndex =\n filteredRowIndices != null\n ? (filteredRowIndices[rowIndex] ?? rowIndex)\n : rowIndex;\n const style =\n rowStatus[dataRowIndex] == TableElementStatus.DELETED\n ? deletedRowHeaderStyle\n : null;\n\n return h(RowHeaderCell, {\n enableRowReordering: false,\n index: rowIndex,\n name: `${dataRowIndex + 1}`,\n style,\n });\n },\n [rowStatus, filteredRowIndices],\n );\n\n let _selectionModes = selectionModes;\n if (\n editable &&\n _selectionModes != null &&\n !_selectionModes.includes(RegionCardinality.CELLS)\n ) {\n _selectionModes = [..._selectionModes, RegionCardinality.CELLS];\n // Ensure selection mode includes \"cells\"\n }\n\n const cellRendererDependencies = [\n data,\n updatedData,\n focusedCell,\n rowStatus,\n filteredRowIndices,\n ];\n\n // Drive the table from the active provider's `fetchData`. A local (in-memory)\n // provider loads the whole array at once; a remote one uses the `pageSize` /\n // `fetchMode` props and shows load progress.\n let _showLoadProgress: boolean = false;\n let dataLoader: ReactNode = null;\n if (activeProvider != null) {\n _showLoadProgress = !isLocalProvider;\n dataLoader = h(_DataLoaderManager, {\n key: \"__data_loader\",\n fetchData: activeProvider.fetchData,\n pageSize: isLocalProvider\n ? Math.max(sourceData?.length ?? 1, 1)\n : pageSize,\n fetchMode: isLocalProvider ? undefined : fetchMode,\n });\n }\n const showFilterBar =\n (filters != null && filters.length > 0) || hasSortableOrFilterable;\n\n let filterStatus: ReactNode = null;\n if (showFilterBar) {\n filterStatus = h(FilterBar, { filters: filters ?? [] });\n }\n\n return h(\"div.data-sheet-container\", { className, style }, [\n // The actions/tools toolbar (selection-modal). Table-scoped controls like\n // scroll-to-row / full-text search live here as ordinary actions.\n h(ActionsToolbar, { actions: _actions, tableName: name }),\n dataLoader,\n children,\n h(\n \"div.data-sheet-holder\",\n {\n tabIndex: 0,\n onKeyDown: handleKeyDown,\n onKeyUp: handleKeyUp,\n ref: tableElementRef,\n style: holderStyle,\n },\n h(\n Table,\n {\n ref,\n numRows,\n className: \"data-sheet\",\n enableFocusedCell,\n onColumnsReordered,\n focusedCell,\n selectedRegions,\n defaultRowHeight: rowHeight,\n minRowHeight: rowHeight,\n columnWidths,\n onColumnWidthChanged,\n onSelection,\n /** TODO: we could enable this, but we need a use-case first... */\n enableRowReordering: false,\n enableRowResizing: false,\n // The cell renderer is memoized internally based on these data dependencies\n cellRendererDependencies,\n onVisibleCellsChange: _onVisibleCellsChange,\n rowHeaderCellRenderer,\n selectionModes: _selectionModes,\n ...rest,\n getCellClipboardData: null,\n },\n realizedColumns,\n ),\n ),\n h(\"div.status-bar\", [\n filterStatus,\n h(\"div.spacer\"),\n h.if(_showLoadProgress)(LoadProgressIndicator),\n ]),\n h.if(debugMode)(CellRendererDebugOverlay, {\n cellRendererDependencies,\n names: [\n \"data\",\n \"updatedData\",\n \"focusedCell\",\n \"rowStatus\",\n \"filteredRowIndices\",\n ],\n }),\n ]);\n}\n\nconst columnWidthsIndexAtom = atom((get) => get(storeAtom).columnWidthsIndex);\nconst defaultColumnWidthAtom = atom((get) => get(storeAtom).defaultColumnWidth);\n\nconst columnWidthsAtom = atom((get) => {\n const ix = get(columnWidthsIndexAtom);\n return get(columnSpecAtom).map(\n (col) => ix.get(col.key) ?? col.width ?? get(defaultColumnWidthAtom),\n );\n});\n\nfunction styleParamsForDensity(density: DataSheetDensity) {\n switch (density) {\n case DataSheetDensity.MEDIUM:\n return {\n rowHeight: 24,\n style: {\n \"--data-sheet-row-height\": \"24px\",\n \"--data-sheet-font-size\": \"14px\",\n },\n };\n case DataSheetDensity.LOW:\n return {\n rowHeight: 30,\n style: {\n \"--data-sheet-row-height\": \"30px\",\n \"--data-sheet-font-size\": \"18px\",\n },\n };\n case DataSheetDensity.HIGH:\n default:\n return {\n rowHeight: 20,\n style: {\n \"--data-sheet-row-height\": \"20px\",\n \"--data-sheet-font-size\": \"12px\",\n },\n };\n }\n}\n\n/** Convenience component: runs `useChunkLoader` from inside a `DataSheet`.\n * Render as a child of `DataSheet` (it renders nothing itself). */\nfunction _DataLoaderManager<T = any>({\n fetchData,\n ...rest\n}: {\n fetchData: FetchData<T>;\n} & FetchDataOptions) {\n useDataLoader(fetchData, rest);\n return null;\n}\n\nexport function getRowsToDelete(selection) {\n let rowIndices: number[] = [];\n for (const sel of selection) {\n // This isn't a full-row selection\n if (sel.cols != null) continue;\n if (sel.rows == null) continue;\n const [startIndex, endIndex] = sel.rows;\n for (let i = startIndex; i <= endIndex; i++) {\n rowIndices.push(i);\n }\n }\n return rowIndices;\n}\n"],"names":["DataSheetDensity","h","DataSheetProvider","provider","ctx","TableElementStatus","filters","useSelector","useMemo","createLocalProvider","dataRefreshTokenAtom","_actions","columnControlActions","clipboardActions","createSaveAction","resetChangesAction","tableActionsAtom","tableHotkeysAtom","useHotkeys","useStoreAPI","useScrollHandler","useCallback","useEffect","useRef","tableFooterAtom","renderColumnHeaderCell","colIndex","Column","basicCellRenderer","style","RowHeaderCell","RegionCardinality","FilterBar","ActionsToolbar","Table","LoadProgressIndicator","CellRendererDebugOverlay","atom","storeA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AAE3B,QAAI,IAAI,QAAQ,KAAM;AACtB,QAAI,IAAI,QAAQ,KAAM;AACtB,UAAM,CAAC,YAAY,QAAQ,IAAI,IAAI;AACnC,aAAS,IAAI,YAAY,KAAK,UAAU,KAAK;AAC3C,iBAAW,KAAK,CAAC;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"core.cjs","sources":["../src/core.ts"],"sourcesContent":["import { useHotkeys } from \"@blueprintjs/core\";\nimport {\n Column,\n Region,\n RegionCardinality,\n RowHeaderCell,\n Table,\n TableProps,\n} from \"@blueprintjs/table\";\nimport \"@blueprintjs/table/lib/css/table.css\";\nimport { ReactNode, useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { LoadProgressIndicator } from \"./components\";\nimport { renderColumnHeaderCell } from \"./renderers\";\nimport h from \"./main.module.sass\";\nimport {\n columnSpecAtom,\n ctx,\n DataSheetProvider,\n storeAtom,\n tableActionsAtom,\n useSelector,\n useStoreAPI,\n} from \"./provider\";\nimport { atom } from \"jotai\";\nimport {\n DataSheetProviderProps,\n DEFAULT_ROW_STATUS_STYLES,\n EditEvent,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableElementStatus,\n VisibleCells,\n} from \"./types.ts\";\nimport { basicCellRenderer } from \"./cell-renderer.ts\";\nimport { CellRendererDebugOverlay, tableHotkeysAtom } from \"./utils\";\nimport {\n ActionsToolbar,\n clearSelectionAction,\n clipboardActions,\n columnControlActions,\n createSaveAction,\n FilterBar,\n resetChangesAction,\n TableAction,\n TableActionContext,\n TableFilter,\n} from \"./actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataOptions,\n tableFooterAtom,\n TableDataProvider,\n useScrollHandler,\n useDataLoader,\n} from \"./postgrest-table\";\n\n// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args\n\n// TODO: add a \"copy to selection\" tool (the little square in the bottom right corner of a cell)\n// This should copy the value of a cell (or a set of cells in the same row) downwards.\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/** Approximate column-header + scrollbar allowance, used to size the table to\n * its content in paged mode. */\nconst COLUMN_HEADER_HEIGHT = 34;\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\ninterface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n // An optional table name that will be used in toolbars if given\n name?: string;\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Derive the controlled edit overlay from the loaded rows, *inside* the\n * sheet. For provider-backed tables whose overlay is a function of the loaded\n * data plus external edit state (e.g. an ops stack): the library owns the\n * rows, so it calls this with them and uses the result as the controlled\n * overlay, re-deriving when the rows — or this function's identity (close it\n * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */\n deriveOverlay?: (rows: T[]) => {\n updatedData: T[];\n rowStatus: TableElementStatus[];\n };\n /** Bump to force the data provider to re-fetch from scratch (e.g. after a\n * save/delete that invalidated the loaded rows). */\n refreshToken?: number | string;\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n editable?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n /** Arbitrary nodes for the bottom status bar (left group), rendered beside\n * the active sort/filter tags — the home for view-state controls (show/hide\n * omitted rows/columns, a group-by indicator, etc.). */\n statusBar?: ReactNode;\n /** Presentation per row-status value, merged over the built-in defaults\n * (which style `\"deleted\"`). Supply styles for consumer-defined statuses\n * (e.g. `\"omitted\"`) and/or override the defaults. Each entry may set the\n * cells' style/intent and the row header's style. */\n rowStatusStyles?: RowStatusStyles;\n /** Render the content of a row's header cell (the left gutter). Receives the\n * row, its status, and the default 1-based label; return a node to use, or a\n * nullish value to keep the default. For group-key labels, omit indicators,\n * etc. Header-cell *styling* still comes from `rowStatusStyles`. */\n rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;\n}\n\ntype DataSheetProps<T> = DataSheetProviderProps<T> & DataSheetInternalProps<T>;\n\nconst emptyData: any[] = [];\n\nexport function DataSheet<T>(props: DataSheetProps<T>) {\n const {\n data,\n columnSpec,\n columnSpecOptions,\n editable = true,\n enableColumnReordering = false,\n enableFocusedCell = false,\n defaultColumnWidth = 150,\n children,\n ...rest\n } = props;\n\n return h(\n DataSheetProvider<T>,\n {\n data: data ?? emptyData,\n columnSpec,\n columnSpecOptions,\n enableColumnReordering,\n defaultColumnWidth,\n editable,\n ...rest,\n },\n h(_DataSheet<any>, {\n ...rest,\n data: data ?? emptyData,\n children,\n editable,\n enableColumnReordering,\n enableFocusedCell,\n }),\n );\n}\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nasync function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n\nfunction _DataSheet<T>({\n data: sourceData,\n fetchData,\n provider,\n pageSize,\n fetchMode,\n onVisibleCellsChange,\n onUpdateData,\n onEdit,\n onSave,\n updatedData: updatedDataProp,\n rowStatus: rowStatusProp,\n identity,\n deriveOverlay,\n refreshToken,\n onDeleteRows,\n name,\n verbose = false,\n enableFocusedCell,\n autoFocusEditor = true,\n cellInteraction,\n enableClipboard = true,\n density = DataSheetDensity.HIGH,\n selectionModes,\n actions,\n filters,\n columnHeaderCellRenderer,\n statusBar,\n rowStatusStyles,\n rowHeaderRenderer,\n children,\n ...rest\n}: DataSheetInternalProps<T>) {\n /**\n * @param data: The data to be displayed in the table\n * @param columnSpec: The specification for all columns in the table. If not provided, the column spec will be generated from the data.\n * @param columnSpecOptions: Options for generating a column spec from data\n */\n\n // Turn on debug features\n const debugMode = false;\n\n const editable = useSelector((state) => state.editable);\n\n // Resolve the active data provider: an explicit `provider` prop wins; else a\n // loose `fetchData` (+ identity) is wrapped as one; else in-memory `data`\n // becomes a local provider. Local and remote thus share one path, and the\n // provider is an explicit contract rather than a set of scattered props.\n const isLocalProvider = provider == null && fetchData == null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (provider != null) return provider;\n if (fetchData != null) {\n return { fetchData, identity: identity ?? ((r: any) => r?.id) };\n }\n if (sourceData != null && sourceData.length > 0) {\n return createLocalProvider(\n sourceData,\n identity != null ? { identity } : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [provider, fetchData, sourceData, identity]);\n\n // When an explicit provider owns persistence, its methods drive the built-in\n // Save (batch: edits→saveRows, added→insertRow, deleted→deleteRows), then a\n // refresh. Otherwise the loose `onSave` handler is used.\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n const providerSave = useMemo(() => {\n const p = provider;\n if (\n p == null ||\n (p.saveRows == null && p.deleteRows == null && p.insertRow == null)\n ) {\n return null;\n }\n return async (actionCtx: TableActionContext<T>) => {\n await persistViaProvider(p, actionCtx);\n bumpRefresh((v) => v + 1);\n };\n }, [provider, bumpRefresh]);\n const saveHandler = onSave ?? providerSave;\n\n // Sync table actions to atom. Consumer actions come first (they override a\n // built-in by reusing its id); the built-in column controls (sort/filter)\n // fill in the rest — so both the toolbar and the header dropdown source from\n // one registry. Built-ins self-gate (single sortable/filterable column).\n const _actions: TableAction[] = useMemo(() => {\n const _actions: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!_actions.some((x) => x.id === a.id)) _actions.push(a);\n }\n };\n if (actions != null) add(actions);\n add(columnControlActions);\n add([clearSelectionAction]);\n if (enableClipboard) add(clipboardActions);\n // Save/reset last — they're the most significant actions — and present for\n // every cardinality (editable), so the toolbar stays mounted regardless of\n // selection.\n if (editable) {\n if (saveHandler != null) add([createSaveAction(saveHandler)]);\n add([resetChangesAction]);\n }\n return _actions;\n }, [actions, enableClipboard, editable, saveHandler]);\n\n ctx.useSync(tableActionsAtom, _actions);\n\n const hotkeysConfig = ctx.useValue(tableHotkeysAtom);\n const { handleKeyDown, handleKeyUp } = useHotkeys(hotkeysConfig);\n\n // For now, we only consider a single cell \"focused\" when we have one cell selected.\n // Multi-cell selections have a different set of \"bulk\" actions.\n const selectedRegions = useSelector<T>((state) => state.selection ?? []);\n\n const data = useSelector((state) => state.data);\n\n const rowStatus = useSelector((state) => state.rowStatus);\n\n const focusedCell = useSelector((state) => state.focusedCell);\n\n const ref = useSelector((state) => state.tableRef);\n\n const columnSpec = useSelector((state) => state.columnSpec);\n\n // A sparse array to hold updates\n // TODO: create a \"changeset\" concept to facilitate undo/redo\n const updatedData = useSelector((state) => state.updatedData);\n\n const onSelection = useSelector((state) => state.onSelection);\n\n const storeAPI = useStoreAPI<T>();\n\n const onScroll = useScrollHandler();\n const _onVisibleCellsChange = useCallback(\n (visibleCells: VisibleCells) => {\n onScroll(visibleCells);\n onVisibleCellsChange?.(visibleCells);\n },\n [onVisibleCellsChange, onScroll],\n );\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Updated data\", updatedData);\n }, [updatedData]);\n\n useEffect(() => {\n onUpdateData?.(updatedData, data);\n }, [onUpdateData, data, updatedData]);\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Selected regions\", selectedRegions);\n }, [selectedRegions]);\n\n const tableElementRef = useRef<HTMLElement>(null);\n useEffect(() => {\n // Return the focus to the table\n tableElementRef.current?.focus();\n }, [focusedCell]);\n\n const columnWidths = ctx.useValue(columnWidthsAtom);\n\n // When filters are active, only show matching rows\n const filteredRowIndices = useSelector((state) => state.filteredRowIndices);\n const totalRows = Math.max(updatedData.length, data.length);\n const numRows =\n filteredRowIndices != null ? filteredRowIndices.length : totalRows;\n\n let className = `${density}-density`;\n\n const { rowHeight, style } = styleParamsForDensity(density);\n\n // In paged mode the row count is small and fixed, so let the table size to\n // its content (header + rows) instead of filling the viewport.\n const footerInfo = ctx.useValue(tableFooterAtom);\n const holderStyle =\n footerInfo.mode === \"paged\"\n ? {\n flex: \"0 0 auto\" as const,\n height: numRows * rowHeight + COLUMN_HEADER_HEIGHT,\n }\n : undefined;\n\n const onColumnsReordered = useSelector((state) => state.onColumnsReordered);\n\n // Auto-detect if any columns have sortable/filterable set.\n // If so and no explicit columnHeaderCellRenderer was provided,\n // use the built-in client-side sort/filter header.\n const hasSortableOrFilterable = useMemo(\n () =>\n columnSpec.some(\n (col) =>\n col.sortable ||\n col.filterable ||\n (Array.isArray(col.filters) && col.filters.length > 0),\n ),\n [columnSpec],\n );\n\n const columnSorts = useSelector((state) => state.columnSorts);\n const activeFilters = useSelector((state) => state.activeFilters);\n\n // Cell activation mode, defaulting from the legacy `autoFocusEditor` boolean\n // so existing consumers are unaffected. Synced into the store so the cell\n // renderer, editors, and key handlers all read it consistently.\n const cellInteractionMode: CellInteraction =\n cellInteraction ?? (autoFocusEditor ? \"auto\" : \"manual\");\n\n const storeState = storeAPI;\n useEffect(() => {\n storeState.setState({ cellInteraction: cellInteractionMode });\n }, [storeState, cellInteractionMode]);\n\n useEffect(() => {\n // Give the store a handle to the focusable holder so editors can return\n // keyboard focus to the table when the cursor leaves them.\n storeState.setState({ tableElement: tableElementRef.current });\n }, [storeState]);\n\n useEffect(() => {\n storeState.setState({ onEdit });\n }, [storeState, onEdit]);\n\n useEffect(() => {\n // Controlled overlay: mirror the caller's edited state into the store as\n // the source of truth. Optimistic in-table edits are superseded on the\n // next render when the caller passes an updated value back. When the caller\n // controls it, the loader-boundary identity remap steps aside.\n const controlled =\n updatedDataProp !== undefined ||\n rowStatusProp !== undefined ||\n deriveOverlay != null;\n const patch: Record<string, unknown> = { controlledOverlay: controlled };\n if (updatedDataProp !== undefined) patch.updatedData = updatedDataProp;\n if (rowStatusProp !== undefined) patch.rowStatus = rowStatusProp;\n storeState.setState(patch);\n }, [storeState, updatedDataProp, rowStatusProp, deriveOverlay]);\n\n // Derived controlled overlay: the library owns the loaded rows, so it runs\n // the consumer's `deriveOverlay(rows)` here and pushes the result. Re-derives\n // when the rows load/change or the function's identity changes (close it over\n // your external edit state). The `controlledOverlay` flag above suppresses the\n // loader-boundary identity remap so this derivation is authoritative.\n const loadedData = useSelector((state) => state.data);\n useEffect(() => {\n if (deriveOverlay == null) return;\n const overlay = deriveOverlay(loadedData);\n storeState.setState({\n updatedData: overlay.updatedData,\n rowStatus: overlay.rowStatus,\n });\n }, [deriveOverlay, loadedData, storeState]);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g. after\n // a save). Skips the initial mount (the loader does its own first fetch).\n const bumpRefreshFromToken = ctx.useSet(dataRefreshTokenAtom);\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefreshFromToken((v) => v + 1);\n }, [refreshToken, bumpRefreshFromToken]);\n\n // The active provider supplies the row identity for the edit overlay.\n useEffect(() => {\n const id = activeProvider?.identity ?? identity;\n if (id != null) storeState.setState({ identity: id });\n }, [storeState, activeProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` without\n // `deleteRows` disables deletion entirely. (Local / loose sources keep the\n // local delete overlay.)\n useEffect(() => {\n const canDeleteRows = provider == null || provider.deleteRows != null;\n storeState.setState({ canDeleteRows });\n }, [storeState, provider]);\n\n // Merge consumer `rowStatusStyles` over the built-in defaults and hand the\n // result to the store, where the cell renderer and row-header renderer read\n // it. Merged (not replaced) so overriding one status doesn't drop the rest.\n const mergedRowStatusStyles = useMemo<RowStatusStyles>(\n () => ({ ...DEFAULT_ROW_STATUS_STYLES, ...rowStatusStyles }),\n [rowStatusStyles],\n );\n useEffect(() => {\n storeState.setState({ rowStatusStyles: mergedRowStatusStyles });\n }, [storeState, mergedRowStatusStyles]);\n\n const realizedColumns = useMemo(() => {\n return columnSpec.map((col, colIndex) => {\n let fn =\n col.headerCellRenderer ??\n columnHeaderCellRenderer ??\n renderColumnHeaderCell;\n let activeSort = null;\n let activeFilter = null;\n if (col.sortable) {\n activeSort = columnSorts?.find((s) => s.key === col.key);\n }\n // The active filter for this column is whichever active filter targets\n // it (a rich `col.filters` filter or the generic operator filter) — match\n // by columnKey rather than a fixed id.\n for (const entry of activeFilters?.values() ?? []) {\n if ((entry as any)?.filter?.columnKey === col.key) {\n activeFilter = entry;\n break;\n }\n }\n\n const _columnHeaderCellRenderer = (colIndex) => {\n return fn({\n col,\n colIndex,\n activeSort,\n activeFilter,\n });\n };\n\n return h(Column, {\n id: col.key,\n name: col.name,\n columnHeaderCellRenderer: _columnHeaderCellRenderer,\n cellRenderer: (rowIndex) => {\n const state = storeAPI.getState();\n return basicCellRenderer<T>(\n rowIndex,\n colIndex,\n col,\n state,\n filteredRowIndices,\n );\n },\n });\n });\n }, [\n columnSpec,\n columnSorts,\n activeFilters,\n storeAPI,\n filteredRowIndices,\n columnHeaderCellRenderer,\n ]);\n\n const onColumnWidthChanged = useSelector(\n (state) => state.onColumnWidthChanged,\n );\n\n const rowHeaderCellRenderer = useCallback(\n (rowIndex: number) => {\n const dataRowIndex =\n filteredRowIndices != null\n ? (filteredRowIndices[rowIndex] ?? rowIndex)\n : rowIndex;\n const statusVal = rowStatus[dataRowIndex];\n const style =\n (statusVal != null\n ? mergedRowStatusStyles[statusVal]?.headerStyle\n : null) ?? null;\n\n const defaultLabel = `${dataRowIndex + 1}`;\n let name: ReactNode = defaultLabel;\n if (rowHeaderRenderer != null) {\n const custom = rowHeaderRenderer({\n rowIndex: dataRowIndex,\n visibleIndex: rowIndex,\n row: data[dataRowIndex] ?? updatedData[dataRowIndex],\n status: statusVal,\n isDeleted: statusVal === TableElementStatus.DELETED,\n defaultLabel,\n });\n if (custom != null) name = custom;\n }\n\n return h(RowHeaderCell, {\n enableRowReordering: false,\n index: rowIndex,\n name,\n style,\n });\n },\n [\n rowStatus,\n filteredRowIndices,\n mergedRowStatusStyles,\n rowHeaderRenderer,\n data,\n updatedData,\n ],\n );\n\n let _selectionModes = selectionModes;\n if (\n editable &&\n _selectionModes != null &&\n !_selectionModes.includes(RegionCardinality.CELLS)\n ) {\n _selectionModes = [..._selectionModes, RegionCardinality.CELLS];\n // Ensure selection mode includes \"cells\"\n }\n\n const cellRendererDependencies = [\n data,\n updatedData,\n focusedCell,\n rowStatus,\n filteredRowIndices,\n ];\n\n // Drive the table from the active provider's `fetchData`. A local (in-memory)\n // provider loads the whole array at once; a remote one uses the `pageSize` /\n // `fetchMode` props and shows load progress.\n let _showLoadProgress: boolean = false;\n let dataLoader: ReactNode = null;\n if (activeProvider != null) {\n _showLoadProgress = !isLocalProvider;\n dataLoader = h(_DataLoaderManager, {\n key: \"__data_loader\",\n fetchData: activeProvider.fetchData,\n pageSize: isLocalProvider\n ? Math.max(sourceData?.length ?? 1, 1)\n : pageSize,\n fetchMode: isLocalProvider ? undefined : fetchMode,\n });\n }\n const showFilterBar =\n (filters != null && filters.length > 0) || hasSortableOrFilterable;\n\n let filterStatus: ReactNode = null;\n if (showFilterBar) {\n filterStatus = h(FilterBar, { filters: filters ?? [] });\n }\n\n return h(\"div.data-sheet-container\", { className, style }, [\n // The actions/tools toolbar (selection-modal). Table-scoped controls like\n // scroll-to-row / full-text search live here as ordinary actions.\n h(ActionsToolbar, { actions: _actions, tableName: name }),\n dataLoader,\n children,\n h(\n \"div.data-sheet-holder\",\n {\n tabIndex: 0,\n onKeyDown: handleKeyDown,\n onKeyUp: handleKeyUp,\n ref: tableElementRef,\n style: holderStyle,\n },\n h(\n Table,\n {\n ref,\n numRows,\n className: \"data-sheet\",\n enableFocusedCell,\n onColumnsReordered,\n focusedCell,\n selectedRegions,\n defaultRowHeight: rowHeight,\n minRowHeight: rowHeight,\n columnWidths,\n onColumnWidthChanged,\n onSelection,\n /** TODO: we could enable this, but we need a use-case first... */\n enableRowReordering: false,\n enableRowResizing: false,\n // The cell renderer is memoized internally based on these data dependencies\n cellRendererDependencies,\n onVisibleCellsChange: _onVisibleCellsChange,\n rowHeaderCellRenderer,\n selectionModes: _selectionModes,\n ...rest,\n getCellClipboardData: null,\n },\n realizedColumns,\n ),\n ),\n h(\"div.status-bar\", [\n filterStatus,\n statusBar,\n h(\"div.spacer\"),\n h.if(_showLoadProgress)(LoadProgressIndicator),\n ]),\n h.if(debugMode)(CellRendererDebugOverlay, {\n cellRendererDependencies,\n names: [\n \"data\",\n \"updatedData\",\n \"focusedCell\",\n \"rowStatus\",\n \"filteredRowIndices\",\n ],\n }),\n ]);\n}\n\nconst columnWidthsIndexAtom = atom((get) => get(storeAtom).columnWidthsIndex);\nconst defaultColumnWidthAtom = atom((get) => get(storeAtom).defaultColumnWidth);\n\nconst columnWidthsAtom = atom((get) => {\n const ix = get(columnWidthsIndexAtom);\n return get(columnSpecAtom).map(\n (col) => ix.get(col.key) ?? col.width ?? get(defaultColumnWidthAtom),\n );\n});\n\nfunction styleParamsForDensity(density: DataSheetDensity) {\n switch (density) {\n case DataSheetDensity.MEDIUM:\n return {\n rowHeight: 24,\n style: {\n \"--data-sheet-row-height\": \"24px\",\n \"--data-sheet-font-size\": \"14px\",\n },\n };\n case DataSheetDensity.LOW:\n return {\n rowHeight: 30,\n style: {\n \"--data-sheet-row-height\": \"30px\",\n \"--data-sheet-font-size\": \"18px\",\n },\n };\n case DataSheetDensity.HIGH:\n default:\n return {\n rowHeight: 20,\n style: {\n \"--data-sheet-row-height\": \"20px\",\n \"--data-sheet-font-size\": \"12px\",\n },\n };\n }\n}\n\n/** Convenience component: runs `useChunkLoader` from inside a `DataSheet`.\n * Render as a child of `DataSheet` (it renders nothing itself). */\nfunction _DataLoaderManager<T = any>({\n fetchData,\n ...rest\n}: {\n fetchData: FetchData<T>;\n} & FetchDataOptions) {\n useDataLoader(fetchData, rest);\n return null;\n}\n\nexport function getRowsToDelete(selection) {\n let rowIndices: number[] = [];\n for (const sel of selection) {\n // This isn't a full-row selection\n if (sel.cols != null) continue;\n if (sel.rows == null) continue;\n const [startIndex, endIndex] = sel.rows;\n for (let i = startIndex; i <= endIndex; i++) {\n rowIndices.push(i);\n }\n }\n return rowIndices;\n}\n"],"names":["DataSheetDensity","h","DataSheetProvider","provider","ctx","TableElementStatus","filters","useSelector","useMemo","createLocalProvider","dataRefreshTokenAtom","_actions","columnControlActions","clearSelectionAction","clipboardActions","createSaveAction","resetChangesAction","tableActionsAtom","tableHotkeysAtom","useHotkeys","useStoreAPI","useScrollHandler","useCallback","useEffect","useRef","tableFooterAtom","DEFAULT_ROW_STATUS_STYLES","renderColumnHeaderCell","colIndex","Column","basicCellRenderer","style","name","RowHeaderCell","RegionCardinality","FilterBar","ActionsToolbar","Table","LoadProgressIndicator","CellRendererDebugOverlay","atom","storeAtom","columnSpecAtom","useDataLoader"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+DO,IAAK,qCAAAA,sBAAL;AACLA,oBAAA,MAAA,IAAO;AACPA,oBAAA,QAAA,IAAS;AACTA,oBAAA,KAAA,IAAM;AAHI,SAAAA;AAAA,GAAA,oBAAA,CAAA,CAAA;AAQZ,MAAM,uBAAuB;AA2G7B,MAAM,YAAmB,CAAA;AAElB,SAAS,UAAa,OAA0B;AACrD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AAAA,IACX,yBAAyB;AAAA,IACzB,oBAAoB;AAAA,IACpB,qBAAqB;AAAA,IACrB;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAEJ,SAAOC,YAAAA;AAAAA,IACLC,SAAAA;AAAAA,IACA;AAAA,MACE,MAAM,QAAQ;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA;AAAA,IAELD,YAAAA,QAAE,YAAiB;AAAA,MACjB,GAAG;AAAA,MACH,MAAM,QAAQ;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA,CACD;AAAA,EAAA;AAEL;AAMA,eAAe,mBACbE,WACAC,MACe;AACf,QAAM,OAAQA,KAAI,QAAQ,CAAA;AAC1B,QAAM,UAAWA,KAAI,eAAe,CAAA;AACpC,QAAM,SAAUA,KAAI,aAAa,CAAA;AACjC,QAAM,IAAI,KAAK,IAAI,KAAK,QAAQ,QAAQ,QAAQ,OAAO,MAAM;AAC7D,QAAM,SAAc,CAAA;AACpB,QAAM,WAAgB,CAAA;AACtB,QAAM,WAAmC,CAAA;AACzC,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,QAAI,OAAO,CAAC,MAAMC,MAAAA,mBAAmB,SAA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ACT;AAEO,SAAS,gBAAgB,WAAW;AACzC,MAAI,aAAuB,CAAA;AAC3B,aAAW,OAAO,WAAW;AAE3B,QAAI,IAAI,QAAQ,KAAM;AACtB,QAAI,IAAI,QAAQ,KAAM;AACtB,UAAM,CAAC,YAAY,QAAQ,IAAI,IAAI;AACnC,aAAS,IAAI,YAAY,KAAK,UAAU,KAAK;AAC3C,iBAAW,KAAK,CAAC;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AACT;;;;"}
|
package/dist/core.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Region, TableProps } from '@blueprintjs/table';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { DataSheetProviderProps, EditEvent, TableElementStatus, VisibleCells } from './types.ts';
|
|
3
|
+
import { DataSheetProviderProps, EditEvent, RowHeaderRenderContext, RowStatusStyles, TableElementStatus, VisibleCells } from './types.ts';
|
|
4
4
|
import { TableAction, TableActionContext, TableFilter } from './actions';
|
|
5
5
|
import { FetchData, FetchDataOptions, TableDataProvider } from './postgrest-table';
|
|
6
6
|
export declare enum DataSheetDensity {
|
|
@@ -51,6 +51,19 @@ interface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {
|
|
|
51
51
|
* data provider supplies its own; defaults to `(row) => row?.id`). Lets edits
|
|
52
52
|
* survive a re-ordered re-fetch. */
|
|
53
53
|
identity?: (row: T) => string | number | null | undefined;
|
|
54
|
+
/** Derive the controlled edit overlay from the loaded rows, *inside* the
|
|
55
|
+
* sheet. For provider-backed tables whose overlay is a function of the loaded
|
|
56
|
+
* data plus external edit state (e.g. an ops stack): the library owns the
|
|
57
|
+
* rows, so it calls this with them and uses the result as the controlled
|
|
58
|
+
* overlay, re-deriving when the rows — or this function's identity (close it
|
|
59
|
+
* over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */
|
|
60
|
+
deriveOverlay?: (rows: T[]) => {
|
|
61
|
+
updatedData: T[];
|
|
62
|
+
rowStatus: TableElementStatus[];
|
|
63
|
+
};
|
|
64
|
+
/** Bump to force the data provider to re-fetch from scratch (e.g. after a
|
|
65
|
+
* save/delete that invalidated the loaded rows). */
|
|
66
|
+
refreshToken?: number | string;
|
|
54
67
|
/** Persistence handler for the built-in Save action. When provided, a Save
|
|
55
68
|
* control is added to the toolbar (always visible, disabled when there are
|
|
56
69
|
* no pending changes). */
|
|
@@ -79,6 +92,20 @@ interface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {
|
|
|
79
92
|
* Receives the ColumnSpec and column index; should return a React element
|
|
80
93
|
* (typically a Blueprint ColumnHeaderCell). */
|
|
81
94
|
columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;
|
|
95
|
+
/** Arbitrary nodes for the bottom status bar (left group), rendered beside
|
|
96
|
+
* the active sort/filter tags — the home for view-state controls (show/hide
|
|
97
|
+
* omitted rows/columns, a group-by indicator, etc.). */
|
|
98
|
+
statusBar?: ReactNode;
|
|
99
|
+
/** Presentation per row-status value, merged over the built-in defaults
|
|
100
|
+
* (which style `"deleted"`). Supply styles for consumer-defined statuses
|
|
101
|
+
* (e.g. `"omitted"`) and/or override the defaults. Each entry may set the
|
|
102
|
+
* cells' style/intent and the row header's style. */
|
|
103
|
+
rowStatusStyles?: RowStatusStyles;
|
|
104
|
+
/** Render the content of a row's header cell (the left gutter). Receives the
|
|
105
|
+
* row, its status, and the default 1-based label; return a node to use, or a
|
|
106
|
+
* nullish value to keep the default. For group-key labels, omit indicators,
|
|
107
|
+
* etc. Header-cell *styling* still comes from `rowStatusStyles`. */
|
|
108
|
+
rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;
|
|
82
109
|
}
|
|
83
110
|
type DataSheetProps<T> = DataSheetProviderProps<T> & DataSheetInternalProps<T>;
|
|
84
111
|
export declare function DataSheet<T>(props: DataSheetProps<T>): import('react').FunctionComponentElement<DataSheetProviderProps<T>>;
|
package/dist/core.js
CHANGED
|
@@ -5,7 +5,7 @@ import { useMemo, useCallback, useEffect, useRef } from "react";
|
|
|
5
5
|
import h from "./main.module.sass.js";
|
|
6
6
|
import { DataSheetProvider, useSelector, ctx, tableActionsAtom, useStoreAPI, columnSpecAtom, storeAtom } from "./provider.js";
|
|
7
7
|
import { atom } from "jotai";
|
|
8
|
-
import { TableElementStatus } from "./types.js";
|
|
8
|
+
import { DEFAULT_ROW_STATUS_STYLES, TableElementStatus } from "./types.js";
|
|
9
9
|
import { basicCellRenderer } from "./cell-renderer.js";
|
|
10
10
|
import { createLocalProvider, dataRefreshTokenAtom, useScrollHandler, tableFooterAtom, useDataLoader } from "./postgrest-table/data-loaders.js";
|
|
11
11
|
import { tableHotkeysAtom } from "./utils/key-handling.js";
|
|
@@ -15,6 +15,7 @@ import { ActionsToolbar } from "./actions/toolbar.js";
|
|
|
15
15
|
import { LoadProgressIndicator } from "./components/view-info.js";
|
|
16
16
|
import { CellRendererDebugOverlay } from "./utils/debug-overlay.js";
|
|
17
17
|
import { columnControlActions } from "./actions/column-controls.js";
|
|
18
|
+
import { clearSelectionAction } from "./actions/table-controls.js";
|
|
18
19
|
import { clipboardActions } from "./actions/clipboard.js";
|
|
19
20
|
import { resetChangesAction } from "./actions/builtin.js";
|
|
20
21
|
import { createSaveAction } from "./actions/edit-actions.js";
|
|
@@ -59,10 +60,6 @@ function DataSheet(props) {
|
|
|
59
60
|
})
|
|
60
61
|
);
|
|
61
62
|
}
|
|
62
|
-
const deletedRowHeaderStyle = {
|
|
63
|
-
opacity: 0.5,
|
|
64
|
-
textDecoration: "line-through"
|
|
65
|
-
};
|
|
66
63
|
async function persistViaProvider(provider, ctx2) {
|
|
67
64
|
const base = ctx2.data ?? [];
|
|
68
65
|
const updates = ctx2.updatedData ?? [];
|
|
@@ -108,6 +105,8 @@ function _DataSheet({
|
|
|
108
105
|
updatedData: updatedDataProp,
|
|
109
106
|
rowStatus: rowStatusProp,
|
|
110
107
|
identity,
|
|
108
|
+
deriveOverlay,
|
|
109
|
+
refreshToken,
|
|
111
110
|
onDeleteRows,
|
|
112
111
|
name,
|
|
113
112
|
verbose = false,
|
|
@@ -120,6 +119,9 @@ function _DataSheet({
|
|
|
120
119
|
actions,
|
|
121
120
|
filters,
|
|
122
121
|
columnHeaderCellRenderer,
|
|
122
|
+
statusBar,
|
|
123
|
+
rowStatusStyles,
|
|
124
|
+
rowHeaderRenderer,
|
|
123
125
|
children,
|
|
124
126
|
...rest
|
|
125
127
|
}) {
|
|
@@ -160,6 +162,7 @@ function _DataSheet({
|
|
|
160
162
|
};
|
|
161
163
|
if (actions != null) add(actions);
|
|
162
164
|
add(columnControlActions);
|
|
165
|
+
add([clearSelectionAction]);
|
|
163
166
|
if (enableClipboard) add(clipboardActions);
|
|
164
167
|
if (editable) {
|
|
165
168
|
if (saveHandler != null) add([createSaveAction(saveHandler)]);
|
|
@@ -234,12 +237,30 @@ function _DataSheet({
|
|
|
234
237
|
storeState.setState({ onEdit });
|
|
235
238
|
}, [storeState, onEdit]);
|
|
236
239
|
useEffect(() => {
|
|
237
|
-
const controlled = updatedDataProp !== void 0 || rowStatusProp !== void 0;
|
|
240
|
+
const controlled = updatedDataProp !== void 0 || rowStatusProp !== void 0 || deriveOverlay != null;
|
|
238
241
|
const patch = { controlledOverlay: controlled };
|
|
239
242
|
if (updatedDataProp !== void 0) patch.updatedData = updatedDataProp;
|
|
240
243
|
if (rowStatusProp !== void 0) patch.rowStatus = rowStatusProp;
|
|
241
244
|
storeState.setState(patch);
|
|
242
|
-
}, [storeState, updatedDataProp, rowStatusProp]);
|
|
245
|
+
}, [storeState, updatedDataProp, rowStatusProp, deriveOverlay]);
|
|
246
|
+
const loadedData = useSelector((state) => state.data);
|
|
247
|
+
useEffect(() => {
|
|
248
|
+
if (deriveOverlay == null) return;
|
|
249
|
+
const overlay = deriveOverlay(loadedData);
|
|
250
|
+
storeState.setState({
|
|
251
|
+
updatedData: overlay.updatedData,
|
|
252
|
+
rowStatus: overlay.rowStatus
|
|
253
|
+
});
|
|
254
|
+
}, [deriveOverlay, loadedData, storeState]);
|
|
255
|
+
const bumpRefreshFromToken = ctx.useSet(dataRefreshTokenAtom);
|
|
256
|
+
const firstRefreshToken = useRef(true);
|
|
257
|
+
useEffect(() => {
|
|
258
|
+
if (firstRefreshToken.current) {
|
|
259
|
+
firstRefreshToken.current = false;
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
bumpRefreshFromToken((v) => v + 1);
|
|
263
|
+
}, [refreshToken, bumpRefreshFromToken]);
|
|
243
264
|
useEffect(() => {
|
|
244
265
|
const id = activeProvider?.identity ?? identity;
|
|
245
266
|
if (id != null) storeState.setState({ identity: id });
|
|
@@ -248,6 +269,13 @@ function _DataSheet({
|
|
|
248
269
|
const canDeleteRows = provider == null || provider.deleteRows != null;
|
|
249
270
|
storeState.setState({ canDeleteRows });
|
|
250
271
|
}, [storeState, provider]);
|
|
272
|
+
const mergedRowStatusStyles = useMemo(
|
|
273
|
+
() => ({ ...DEFAULT_ROW_STATUS_STYLES, ...rowStatusStyles }),
|
|
274
|
+
[rowStatusStyles]
|
|
275
|
+
);
|
|
276
|
+
useEffect(() => {
|
|
277
|
+
storeState.setState({ rowStatusStyles: mergedRowStatusStyles });
|
|
278
|
+
}, [storeState, mergedRowStatusStyles]);
|
|
251
279
|
const realizedColumns = useMemo(() => {
|
|
252
280
|
return columnSpec.map((col, colIndex) => {
|
|
253
281
|
let fn = col.headerCellRenderer ?? columnHeaderCellRenderer ?? renderColumnHeaderCell;
|
|
@@ -300,15 +328,36 @@ function _DataSheet({
|
|
|
300
328
|
const rowHeaderCellRenderer = useCallback(
|
|
301
329
|
(rowIndex) => {
|
|
302
330
|
const dataRowIndex = filteredRowIndices != null ? filteredRowIndices[rowIndex] ?? rowIndex : rowIndex;
|
|
303
|
-
const
|
|
331
|
+
const statusVal = rowStatus[dataRowIndex];
|
|
332
|
+
const style2 = (statusVal != null ? mergedRowStatusStyles[statusVal]?.headerStyle : null) ?? null;
|
|
333
|
+
const defaultLabel = `${dataRowIndex + 1}`;
|
|
334
|
+
let name2 = defaultLabel;
|
|
335
|
+
if (rowHeaderRenderer != null) {
|
|
336
|
+
const custom = rowHeaderRenderer({
|
|
337
|
+
rowIndex: dataRowIndex,
|
|
338
|
+
visibleIndex: rowIndex,
|
|
339
|
+
row: data[dataRowIndex] ?? updatedData[dataRowIndex],
|
|
340
|
+
status: statusVal,
|
|
341
|
+
isDeleted: statusVal === TableElementStatus.DELETED,
|
|
342
|
+
defaultLabel
|
|
343
|
+
});
|
|
344
|
+
if (custom != null) name2 = custom;
|
|
345
|
+
}
|
|
304
346
|
return h(RowHeaderCell, {
|
|
305
347
|
enableRowReordering: false,
|
|
306
348
|
index: rowIndex,
|
|
307
|
-
name:
|
|
349
|
+
name: name2,
|
|
308
350
|
style: style2
|
|
309
351
|
});
|
|
310
352
|
},
|
|
311
|
-
[
|
|
353
|
+
[
|
|
354
|
+
rowStatus,
|
|
355
|
+
filteredRowIndices,
|
|
356
|
+
mergedRowStatusStyles,
|
|
357
|
+
rowHeaderRenderer,
|
|
358
|
+
data,
|
|
359
|
+
updatedData
|
|
360
|
+
]
|
|
312
361
|
);
|
|
313
362
|
let _selectionModes = selectionModes;
|
|
314
363
|
if (editable && _selectionModes != null && !_selectionModes.includes(RegionCardinality.CELLS)) {
|
|
@@ -383,6 +432,7 @@ function _DataSheet({
|
|
|
383
432
|
),
|
|
384
433
|
h("div.status-bar", [
|
|
385
434
|
filterStatus,
|
|
435
|
+
statusBar,
|
|
386
436
|
h("div.spacer"),
|
|
387
437
|
h.if(_showLoadProgress)(LoadProgressIndicator)
|
|
388
438
|
]),
|