@macrostrat/data-sheet 4.9.1 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -31
- package/dist/actions/selection.cjs +5 -1
- package/dist/actions/selection.cjs.map +1 -1
- package/dist/actions/selection.d.ts +7 -1
- package/dist/actions/selection.js +5 -1
- package/dist/actions/selection.js.map +1 -1
- package/dist/components/editor-actions.cjs +1 -1
- package/dist/components/editor-actions.cjs.map +1 -1
- package/dist/components/editor-actions.js +2 -2
- package/dist/components/editor-actions.js.map +1 -1
- package/dist/components/indicators/unified-filters.cjs +3 -0
- package/dist/components/indicators/unified-filters.cjs.map +1 -1
- package/dist/components/indicators/unified-filters.js +3 -0
- package/dist/components/indicators/unified-filters.js.map +1 -1
- package/dist/components/toolbars/actions-toolbar.cjs +5 -2
- package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
- package/dist/components/toolbars/actions-toolbar.js +6 -3
- package/dist/components/toolbars/actions-toolbar.js.map +1 -1
- package/dist/data-sheet.cjs +4 -0
- package/dist/data-sheet.cjs.map +1 -1
- package/dist/data-sheet.css +38 -22
- package/dist/data-sheet.js +4 -0
- package/dist/data-sheet.js.map +1 -1
- package/dist/index.cjs +15 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2 -1
- package/dist/main.module.sass.cjs +14 -14
- package/dist/main.module.sass.js +14 -14
- package/dist/provider/column-spec.cjs.map +1 -1
- package/dist/provider/column-spec.d.ts +8 -0
- package/dist/provider/column-spec.js.map +1 -1
- package/dist/provider/types.cjs.map +1 -1
- package/dist/provider/types.d.ts +6 -0
- package/dist/provider/types.js.map +1 -1
- package/dist/provider/zustand-store.cjs +9 -2
- package/dist/provider/zustand-store.cjs.map +1 -1
- package/dist/provider/zustand-store.js +9 -2
- package/dist/provider/zustand-store.js.map +1 -1
- package/dist/renderers/cell-renderer.cjs +9 -2
- package/dist/renderers/cell-renderer.cjs.map +1 -1
- package/dist/renderers/cell-renderer.js +9 -2
- package/dist/renderers/cell-renderer.js.map +1 -1
- package/dist/utils/key-handling.cjs +6 -5
- package/dist/utils/key-handling.cjs.map +1 -1
- package/dist/utils/key-handling.js +2 -1
- package/dist/utils/key-handling.js.map +1 -1
- package/package.json +2 -2
- package/src/actions/selection.ts +11 -2
- package/src/components/editor-actions.ts +5 -2
- package/src/components/indicators/unified-filters.ts +3 -0
- package/src/components/toolbars/actions-toolbar.ts +10 -4
- package/src/data-sheet.ts +6 -0
- package/src/main.module.sass +14 -0
- package/src/provider/column-spec.ts +8 -0
- package/src/provider/types.ts +10 -1
- package/src/provider/zustand-store.ts +9 -2
- package/src/renderers/cell-renderer.ts +12 -0
- package/src/utils/key-handling.ts +2 -1
package/dist/data-sheet.js
CHANGED
|
@@ -192,6 +192,10 @@ function DataSheetRenderer({
|
|
|
192
192
|
useEffect(() => {
|
|
193
193
|
storeState.setState({ tableElement: tableElementRef.current });
|
|
194
194
|
}, [storeState]);
|
|
195
|
+
const densityRowHeight = styleParamsForDensity(density).rowHeight;
|
|
196
|
+
useEffect(() => {
|
|
197
|
+
storeState.setState({ rowHeight: densityRowHeight });
|
|
198
|
+
}, [storeState, densityRowHeight]);
|
|
195
199
|
useEffect(() => {
|
|
196
200
|
storeState.setState({ onEdit });
|
|
197
201
|
}, [storeState, onEdit]);
|
package/dist/data-sheet.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-sheet.js","sources":["../src/data-sheet.ts"],"sourcesContent":["import { useHotkeys } from \"@blueprintjs/core\";\nimport {\n Column,\n RegionCardinality,\n RowHeaderCell,\n Table,\n} from \"@blueprintjs/table\";\nimport \"@blueprintjs/table/lib/css/table.css\";\nimport {\n CSSProperties,\n ReactNode,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n} from \"react\";\nimport {\n LoadProgressIndicator,\n ActionsToolbar,\n ActiveFiltersList,\n} from \"./components\";\nimport { basicCellRenderer, renderColumnHeaderCell } from \"./renderers\";\nimport h from \"./main.module.sass\";\nimport {\n columnSpecAtom,\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n DataSheetProvider,\n DataViewRendererType,\n DEFAULT_ROW_STATUS_STYLES,\n FetchData,\n persistViaProvider,\n RowStatusStyles,\n splitDataProviderProps,\n storeAtom,\n tableActionsAtom,\n TableElementStatus,\n useSelector,\n useStoreAPI,\n VisibleCells,\n} from \"./provider\";\nimport { atom } from \"jotai\";\nimport { CellRendererDebugOverlay, tableHotkeysAtom } from \"./utils\";\nimport {\n clipboardActions,\n columnControlActions,\n createSaveAction,\n resetChangesAction,\n TableAction,\n TableActionContext,\n} from \"./actions\";\nimport {\n tableFooterAtom,\n useDataLoader,\n useScrollHandler,\n} from \"./postgrest-table\";\nimport {\n CellInteraction,\n DataSheetDensity,\n DataSheetProps,\n DataSheetRendererProps,\n FetchDataOptions,\n} from \"./types.ts\";\nimport { ErrorCallout } from \"@macrostrat/ui-components\";\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\n/** Approximate column-header + scrollbar allowance, used to size the table to\n * its content in paged mode. */\nconst COLUMN_HEADER_HEIGHT = 34;\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 name,\n ...rest\n } = props;\n\n const [providerProps, rendererProps] = splitDataProviderProps<T>({\n ...props,\n viewType: DataViewRendererType.TABLE,\n });\n return h(\n DataSheetProvider<T>,\n providerProps,\n h(DataSheetRenderer<any>, rendererProps),\n );\n}\n\nconst verboseAtom = atom(false);\n\n/** The table (cell-grid) renderer. Assumes it is rendered inside a\n * `DataSheetProvider` (the `DataSheet` wrapper, or `DataView`). Exported so a\n * shared-store `DataView` can mount it directly alongside `_DataPanel`. */\nexport function DataSheetRenderer<T>({\n fetchData,\n provider,\n pageSize,\n fetchMode,\n filterDebounce,\n initialData,\n onVisibleCellsChange,\n onUpdateData,\n onEdit,\n onSave,\n updatedData: updatedDataProp,\n rowStatus: rowStatusProp,\n // Identity/canDeleteRows sync (was here) is now handled by the provider\n // (`DataSheetProviderInner`); still destructured so `identity`/`refreshToken`\n // don't leak into `...rest` (spread onto the Blueprint `Table` below).\n identity: _identity,\n deriveOverlay,\n refreshToken: _refreshToken,\n onDeleteRows,\n name,\n verbose = false,\n debug = 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 ...tableProps\n}: DataSheetRendererProps<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 ctx.useSync(verboseAtom, verbose);\n\n const editable = useSelector((state) => state.editable);\n\n // The active data source is resolved in the wrapper (`DataSheet`) and held in\n // the provider layer; read it here rather than resolving per render.\n const {\n provider: activeProvider,\n isLocalProvider,\n localCount,\n } = ctx.useValue(dataProviderAtom);\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 /*** TODO: generalize this, probably shouldn't need 'set' */\n ctx.useSync(tableActionsAtom, _actions);\n const getHotkeys = ctx.useSet(tableHotkeysAtom);\n\n // This is quite hacky!\n const hotkeysConfig = useMemo(() => {\n return getHotkeys();\n }, [_actions]);\n\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 let holderStyle: CSSProperties | undefined = undefined;\n if (footerInfo.mode === \"paged\") {\n holderStyle = {\n flex: \"0 0 auto\" as const,\n height: numRows * rowHeight + COLUMN_HEADER_HEIGHT,\n };\n }\n\n const onColumnsReordered = useSelector((state) => state.onColumnsReordered);\n // Whether table-level column drag-reordering is enabled. Held in the store\n // (set from the `enableColumnReordering` prop by the provider); it must reach\n // the Blueprint `Table` — the `onColumnsReordered` handler alone doesn't turn\n // on the drag affordance.\n const enableColumnReordering = useSelector(\n (state) => state.enableColumnReordering,\n );\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 useEffect(() => {\n if (deriveOverlay == null) return;\n const overlay = deriveOverlay(data);\n storeState.setState({\n updatedData: overlay.updatedData,\n rowStatus: overlay.rowStatus,\n });\n }, [deriveOverlay, data, storeState]);\n\n // Function `columnSpec` derivation is hoisted to the provider\n // (`DataSheetProviderInner`), shared by both renderers.\n\n // Identity and canDeleteRows sync are hoisted to the provider\n // (`DataSheetProviderInner`), shared with `_DataPanel` — both depend only on\n // the resolved data provider, not any sheet-specific state.\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.headerRenderer ??\n columnHeaderCellRenderer ??\n renderColumnHeaderCell;\n let activeSort: any = null;\n let activeFilter: any = 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: any = (colIndex) => {\n return fn(\n {\n col,\n colIndex,\n activeSort,\n activeFilter,\n },\n colIndex,\n );\n };\n\n return h(Column, {\n id: col.key,\n name: col.name,\n columnHeaderCellRenderer: _columnHeaderCellRenderer as any,\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 let dataRowIndex = rowIndex;\n if (filteredRowIndices != null) {\n dataRowIndex = filteredRowIndices[rowIndex] ?? rowIndex;\n }\n const statusVal = rowStatus[dataRowIndex];\n let style: CSSProperties | undefined;\n if (statusVal != null) {\n style = mergedRowStatusStyles[statusVal]?.headerStyle;\n }\n\n const defaultLabel = `${dataRowIndex + 1}`;\n // A custom renderer supplies the header's *name* content (a group-key\n // label, an omit indicator, …); a nullish return keeps the default\n // 1-based label. Either way the node is wrapped in a `RowHeaderCell` so\n // status styling and the row index are always applied — the renderer is\n // not responsible for producing the whole cell.\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 // Done with hooks!\n /** Guard for unacceptable state combinations:\n * editable = true requires selectionModes to include cells, else the user cannot select a cell to edit.\n * TODO: make this an impossible state to enter.\n */\n if (\n editable &&\n selectionModes &&\n !selectionModes.includes(RegionCardinality.CELLS)\n ) {\n return h(ErrorCallout, {\n title: \"Invalid selection mode\",\n description: \"Editable sheet requires cell selection\",\n });\n }\n\n // TODO: hoist this\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 // A local (in-memory) source loads all its rows in one page; its count\n // rides on the resolved provider (`localCount`), so `_DataSheet` no longer\n // takes a `data` prop — live rows come only from the store.\n dataLoader = h(_DataLoaderManager, {\n key: \"__data_loader\",\n fetchData: activeProvider.fetchData,\n pageSize: isLocalProvider ? Math.max(localCount, 1) : pageSize,\n fetchMode: isLocalProvider ? undefined : fetchMode,\n filterDebounce,\n initialData,\n });\n }\n const showFilterBar =\n (filters != null && filters.length > 0) || hasSortableOrFilterable;\n\n let filterStatus: ReactNode = null;\n if (showFilterBar) {\n filterStatus = h(ActiveFiltersList, { 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 }),\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 as any, // Some sort of hyperscript type error\n {\n ref,\n numRows,\n className: \"data-sheet\",\n enableFocusedCell,\n enableColumnReordering,\n onColumnsReordered,\n focusedCell,\n selectedRegions,\n defaultRowHeight: rowHeight,\n columnWidths,\n onColumnWidthChanged,\n onSelection,\n /** TODO: we could enable this if we had a use-case */\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 ...tableProps,\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(debug)(CellRendererDebugOverlay, {\n cellRendererDependencies,\n names: [\n \"data\",\n \"updatedData\",\n \"focusedCell\",\n \"rowStatus\",\n \"filteredRowIndices\",\n ],\n }),\n ]);\n}\n\nconst EMPTY_MAP = new Map<string, number>();\n\nconst columnWidthsIndexAtom = atom(\n (get) => get(storeAtom)?.columnWidthsIndex ?? EMPTY_MAP,\n);\nconst defaultColumnWidthAtom = atom(\n (get) => get(storeAtom)?.defaultColumnWidth ?? 150,\n);\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 rowHeight: number;\n style: Record<string, string>;\n} {\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<any>) {\n useDataLoader(fetchData, rest);\n return null;\n}\n"],"names":["_actions","colIndex","style","name"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyEA,MAAM,uBAAuB;AAEtB,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;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAEJ,QAAM,CAAC,eAAe,aAAa,IAAI,uBAA0B;AAAA,IAC/D,GAAG;AAAA,IACH,UAAU,qBAAqB;AAAA,EAAA,CAChC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,EAAE,mBAAwB,aAAa;AAAA,EAAA;AAE3C;AAEA,MAAM,cAA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,KAAK,IAAI,SAAS,IAAI,sBAAsB;AAAA,EAAA;AAEvE,CAAC;AAED,SAAS,sBAAsB,SAG7B;AACA,UAAQ,SAAA;AAAA,IACN,KAAK,iBAAiB;AACpB,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,IAEJ,KAAK,iBAAiB;AACpB,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,IAEJ,KAAK,iBAAiB;AAAA,IACtB;AACE,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,EACF;AAEN;AAIA,SAAS,mBAA4B;AAAA,EACnC;AAAA,EACA,GAAG;AACL,GAE2B;AACzB,gBAAc,WAAW,IAAI;AAC7B,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"data-sheet.js","sources":["../src/data-sheet.ts"],"sourcesContent":["import { useHotkeys } from \"@blueprintjs/core\";\nimport {\n Column,\n RegionCardinality,\n RowHeaderCell,\n Table,\n} from \"@blueprintjs/table\";\nimport \"@blueprintjs/table/lib/css/table.css\";\nimport {\n CSSProperties,\n ReactNode,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n} from \"react\";\nimport {\n LoadProgressIndicator,\n ActionsToolbar,\n ActiveFiltersList,\n} from \"./components\";\nimport { basicCellRenderer, renderColumnHeaderCell } from \"./renderers\";\nimport h from \"./main.module.sass\";\nimport {\n columnSpecAtom,\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n DataSheetProvider,\n DataViewRendererType,\n DEFAULT_ROW_STATUS_STYLES,\n FetchData,\n persistViaProvider,\n RowStatusStyles,\n splitDataProviderProps,\n storeAtom,\n tableActionsAtom,\n TableElementStatus,\n useSelector,\n useStoreAPI,\n VisibleCells,\n} from \"./provider\";\nimport { atom } from \"jotai\";\nimport { CellRendererDebugOverlay, tableHotkeysAtom } from \"./utils\";\nimport {\n clipboardActions,\n columnControlActions,\n createSaveAction,\n resetChangesAction,\n TableAction,\n TableActionContext,\n} from \"./actions\";\nimport {\n tableFooterAtom,\n useDataLoader,\n useScrollHandler,\n} from \"./postgrest-table\";\nimport {\n CellInteraction,\n DataSheetDensity,\n DataSheetProps,\n DataSheetRendererProps,\n FetchDataOptions,\n} from \"./types.ts\";\nimport { ErrorCallout } from \"@macrostrat/ui-components\";\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\n/** Approximate column-header + scrollbar allowance, used to size the table to\n * its content in paged mode. */\nconst COLUMN_HEADER_HEIGHT = 34;\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 name,\n ...rest\n } = props;\n\n const [providerProps, rendererProps] = splitDataProviderProps<T>({\n ...props,\n viewType: DataViewRendererType.TABLE,\n });\n return h(\n DataSheetProvider<T>,\n providerProps,\n h(DataSheetRenderer<any>, rendererProps),\n );\n}\n\nconst verboseAtom = atom(false);\n\n/** The table (cell-grid) renderer. Assumes it is rendered inside a\n * `DataSheetProvider` (the `DataSheet` wrapper, or `DataView`). Exported so a\n * shared-store `DataView` can mount it directly alongside `_DataPanel`. */\nexport function DataSheetRenderer<T>({\n fetchData,\n provider,\n pageSize,\n fetchMode,\n filterDebounce,\n initialData,\n onVisibleCellsChange,\n onUpdateData,\n onEdit,\n onSave,\n updatedData: updatedDataProp,\n rowStatus: rowStatusProp,\n // Identity/canDeleteRows sync (was here) is now handled by the provider\n // (`DataSheetProviderInner`); still destructured so `identity`/`refreshToken`\n // don't leak into `...rest` (spread onto the Blueprint `Table` below).\n identity: _identity,\n deriveOverlay,\n refreshToken: _refreshToken,\n onDeleteRows,\n name,\n verbose = false,\n debug = 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 ...tableProps\n}: DataSheetRendererProps<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 ctx.useSync(verboseAtom, verbose);\n\n const editable = useSelector((state) => state.editable);\n\n // The active data source is resolved in the wrapper (`DataSheet`) and held in\n // the provider layer; read it here rather than resolving per render.\n const {\n provider: activeProvider,\n isLocalProvider,\n localCount,\n } = ctx.useValue(dataProviderAtom);\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 /*** TODO: generalize this, probably shouldn't need 'set' */\n ctx.useSync(tableActionsAtom, _actions);\n const getHotkeys = ctx.useSet(tableHotkeysAtom);\n\n // This is quite hacky!\n const hotkeysConfig = useMemo(() => {\n return getHotkeys();\n }, [_actions]);\n\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 let holderStyle: CSSProperties | undefined = undefined;\n if (footerInfo.mode === \"paged\") {\n holderStyle = {\n flex: \"0 0 auto\" as const,\n height: numRows * rowHeight + COLUMN_HEADER_HEIGHT,\n };\n }\n\n const onColumnsReordered = useSelector((state) => state.onColumnsReordered);\n // Whether table-level column drag-reordering is enabled. Held in the store\n // (set from the `enableColumnReordering` prop by the provider); it must reach\n // the Blueprint `Table` — the `onColumnsReordered` handler alone doesn't turn\n // on the drag affordance.\n const enableColumnReordering = useSelector(\n (state) => state.enableColumnReordering,\n );\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 // The row height is the density's; cells report it to their renderers\n const densityRowHeight = styleParamsForDensity(density).rowHeight;\n useEffect(() => {\n storeState.setState({ rowHeight: densityRowHeight });\n }, [storeState, densityRowHeight]);\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 useEffect(() => {\n if (deriveOverlay == null) return;\n const overlay = deriveOverlay(data);\n storeState.setState({\n updatedData: overlay.updatedData,\n rowStatus: overlay.rowStatus,\n });\n }, [deriveOverlay, data, storeState]);\n\n // Function `columnSpec` derivation is hoisted to the provider\n // (`DataSheetProviderInner`), shared by both renderers.\n\n // Identity and canDeleteRows sync are hoisted to the provider\n // (`DataSheetProviderInner`), shared with `_DataPanel` — both depend only on\n // the resolved data provider, not any sheet-specific state.\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.headerRenderer ??\n columnHeaderCellRenderer ??\n renderColumnHeaderCell;\n let activeSort: any = null;\n let activeFilter: any = 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: any = (colIndex) => {\n return fn(\n {\n col,\n colIndex,\n activeSort,\n activeFilter,\n },\n colIndex,\n );\n };\n\n return h(Column, {\n id: col.key,\n name: col.name,\n columnHeaderCellRenderer: _columnHeaderCellRenderer as any,\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 let dataRowIndex = rowIndex;\n if (filteredRowIndices != null) {\n dataRowIndex = filteredRowIndices[rowIndex] ?? rowIndex;\n }\n const statusVal = rowStatus[dataRowIndex];\n let style: CSSProperties | undefined;\n if (statusVal != null) {\n style = mergedRowStatusStyles[statusVal]?.headerStyle;\n }\n\n const defaultLabel = `${dataRowIndex + 1}`;\n // A custom renderer supplies the header's *name* content (a group-key\n // label, an omit indicator, …); a nullish return keeps the default\n // 1-based label. Either way the node is wrapped in a `RowHeaderCell` so\n // status styling and the row index are always applied — the renderer is\n // not responsible for producing the whole cell.\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 // Done with hooks!\n /** Guard for unacceptable state combinations:\n * editable = true requires selectionModes to include cells, else the user cannot select a cell to edit.\n * TODO: make this an impossible state to enter.\n */\n if (\n editable &&\n selectionModes &&\n !selectionModes.includes(RegionCardinality.CELLS)\n ) {\n return h(ErrorCallout, {\n title: \"Invalid selection mode\",\n description: \"Editable sheet requires cell selection\",\n });\n }\n\n // TODO: hoist this\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 // A local (in-memory) source loads all its rows in one page; its count\n // rides on the resolved provider (`localCount`), so `_DataSheet` no longer\n // takes a `data` prop — live rows come only from the store.\n dataLoader = h(_DataLoaderManager, {\n key: \"__data_loader\",\n fetchData: activeProvider.fetchData,\n pageSize: isLocalProvider ? Math.max(localCount, 1) : pageSize,\n fetchMode: isLocalProvider ? undefined : fetchMode,\n filterDebounce,\n initialData,\n });\n }\n const showFilterBar =\n (filters != null && filters.length > 0) || hasSortableOrFilterable;\n\n let filterStatus: ReactNode = null;\n if (showFilterBar) {\n filterStatus = h(ActiveFiltersList, { 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 }),\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 as any, // Some sort of hyperscript type error\n {\n ref,\n numRows,\n className: \"data-sheet\",\n enableFocusedCell,\n enableColumnReordering,\n onColumnsReordered,\n focusedCell,\n selectedRegions,\n defaultRowHeight: rowHeight,\n columnWidths,\n onColumnWidthChanged,\n onSelection,\n /** TODO: we could enable this if we had a use-case */\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 ...tableProps,\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(debug)(CellRendererDebugOverlay, {\n cellRendererDependencies,\n names: [\n \"data\",\n \"updatedData\",\n \"focusedCell\",\n \"rowStatus\",\n \"filteredRowIndices\",\n ],\n }),\n ]);\n}\n\nconst EMPTY_MAP = new Map<string, number>();\n\nconst columnWidthsIndexAtom = atom(\n (get) => get(storeAtom)?.columnWidthsIndex ?? EMPTY_MAP,\n);\nconst defaultColumnWidthAtom = atom(\n (get) => get(storeAtom)?.defaultColumnWidth ?? 150,\n);\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 rowHeight: number;\n style: Record<string, string>;\n} {\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<any>) {\n useDataLoader(fetchData, rest);\n return null;\n}\n"],"names":["_actions","colIndex","style","name"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyEA,MAAM,uBAAuB;AAEtB,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;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAEJ,QAAM,CAAC,eAAe,aAAa,IAAI,uBAA0B;AAAA,IAC/D,GAAG;AAAA,IACH,UAAU,qBAAqB;AAAA,EAAA,CAChC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,EAAE,mBAAwB,aAAa;AAAA,EAAA;AAE3C;AAEA,MAAM,cAAc,KAAK,KAAK;AAKvB,SAAS,kBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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AAAA,IACzB,CAAC,QAAQ,GAAG,IAAI,IAAI,GAAG,KAAK,IAAI,SAAS,IAAI,sBAAsB;AAAA,EAAA;AAEvE,CAAC;AAED,SAAS,sBAAsB,SAG7B;AACA,UAAQ,SAAA;AAAA,IACN,KAAK,iBAAiB;AACpB,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,IAEJ,KAAK,iBAAiB;AACpB,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,IAEJ,KAAK,iBAAiB;AAAA,IACtB;AACE,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,EACF;AAEN;AAIA,SAAS,mBAA4B;AAAA,EACnC;AAAA,EACA,GAAG;AACL,GAE2B;AACzB,gBAAc,WAAW,IAAI;AAC7B,SAAO;AACT;"}
|
package/dist/index.cjs
CHANGED
|
@@ -26,11 +26,11 @@ const viewInfo = require("./components/indicators/view-info.cjs");
|
|
|
26
26
|
const clipboard = require("./actions/clipboard.cjs");
|
|
27
27
|
const rowEditor = require("./components/row-editor.cjs");
|
|
28
28
|
const selection = require("./components/indicators/selection.cjs");
|
|
29
|
+
const selection$1 = require("./actions/selection.cjs");
|
|
29
30
|
const builtin = require("./actions/builtin.cjs");
|
|
30
|
-
const selection$
|
|
31
|
+
const selection$2 = require("./provider/selection.cjs");
|
|
31
32
|
const dataLoaders = require("./postgrest-table/data-loaders.cjs");
|
|
32
33
|
const context = require("./actions/context.cjs");
|
|
33
|
-
const selection$2 = require("./actions/selection.cjs");
|
|
34
34
|
const columnFilter = require("./actions/column-filter.cjs");
|
|
35
35
|
const validation = require("./utils/validation.cjs");
|
|
36
36
|
const columnControls = require("./actions/column-controls.cjs");
|
|
@@ -157,12 +157,23 @@ exports.useSelectedRow = rowEditor.useSelectedRow;
|
|
|
157
157
|
exports.useSelectedRows = rowEditor.useSelectedRows;
|
|
158
158
|
exports.SelectionIndicator = selection.SelectionIndicator;
|
|
159
159
|
exports.toggleModalSelectionAtom = selection.toggleModalSelectionAtom;
|
|
160
|
+
exports.actionRequiresEditable = selection$1.actionRequiresEditable;
|
|
161
|
+
exports.buildDataViewSelection = selection$1.buildDataViewSelection;
|
|
162
|
+
exports.computeFilteredRowIndices = selection$1.computeFilteredRowIndices;
|
|
163
|
+
exports.computeSelectionShape = selection$1.computeSelectionShape;
|
|
164
|
+
exports.getApplicableActions = selection$1.getApplicableActions;
|
|
165
|
+
exports.getSelectedColumnKeys = selection$1.getSelectedColumnKeys;
|
|
166
|
+
exports.getSelectedRowIndices = selection$1.getSelectedRowIndices;
|
|
167
|
+
exports.getSelectionCardinality = selection$1.getSelectionCardinality;
|
|
168
|
+
exports.mergeColumnActions = selection$1.mergeColumnActions;
|
|
169
|
+
exports.range = selection$1.range;
|
|
170
|
+
exports.rowIndicesToRegions = selection$1.rowIndicesToRegions;
|
|
160
171
|
exports.addRowAction = builtin.addRowAction;
|
|
161
172
|
exports.defaultTableActions = builtin.defaultTableActions;
|
|
162
173
|
exports.deleteRowsAction = builtin.deleteRowsAction;
|
|
163
174
|
exports.resetChangesAction = builtin.resetChangesAction;
|
|
164
|
-
exports.anchorRefAtom = selection$
|
|
165
|
-
exports.selectionAtom = selection$
|
|
175
|
+
exports.anchorRefAtom = selection$2.anchorRefAtom;
|
|
176
|
+
exports.selectionAtom = selection$2.selectionAtom;
|
|
166
177
|
exports.applyColumnFilters = dataLoaders.applyColumnFilters;
|
|
167
178
|
exports.autoLoadPagesAtom = dataLoaders.autoLoadPagesAtom;
|
|
168
179
|
exports.chunkPageAtom = dataLoaders.chunkPageAtom;
|
|
@@ -177,16 +188,6 @@ exports.useScrollHandler = dataLoaders.useScrollHandler;
|
|
|
177
188
|
exports.viewInfoAtom = dataLoaders.viewInfoAtom;
|
|
178
189
|
exports.buildActionContext = context.buildActionContext;
|
|
179
190
|
exports.runActionWrapper = context.runActionWrapper;
|
|
180
|
-
exports.buildDataViewSelection = selection$2.buildDataViewSelection;
|
|
181
|
-
exports.computeFilteredRowIndices = selection$2.computeFilteredRowIndices;
|
|
182
|
-
exports.computeSelectionShape = selection$2.computeSelectionShape;
|
|
183
|
-
exports.getApplicableActions = selection$2.getApplicableActions;
|
|
184
|
-
exports.getSelectedColumnKeys = selection$2.getSelectedColumnKeys;
|
|
185
|
-
exports.getSelectedRowIndices = selection$2.getSelectedRowIndices;
|
|
186
|
-
exports.getSelectionCardinality = selection$2.getSelectionCardinality;
|
|
187
|
-
exports.mergeColumnActions = selection$2.mergeColumnActions;
|
|
188
|
-
exports.range = selection$2.range;
|
|
189
|
-
exports.rowIndicesToRegions = selection$2.rowIndicesToRegions;
|
|
190
191
|
exports.buildMultiOperatorColumnFilter = columnFilter.buildMultiOperatorColumnFilter;
|
|
191
192
|
exports.columnFilterId = columnFilter.columnFilterId;
|
|
192
193
|
exports.enhanceColumnFilter = columnFilter.enhanceColumnFilter;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/index.js
CHANGED
|
@@ -24,11 +24,11 @@ import { LoadProgressIndicator, LoadProgressLabel } from "./components/indicator
|
|
|
24
24
|
import { PasteShape, clipboardActions, copyAction, cutAction, pasteAction, serializeSelectionToTSV } from "./actions/clipboard.js";
|
|
25
25
|
import { RowEditor, RowEditorField, RowEditorFrame, SelectedDataEditor, SelectedRowEditor, ShowRowEditor, rowEditorOpenAtom, showRowEditorAction, useRowEditorOpen, useSelectedRow, useSelectedRows } from "./components/row-editor.js";
|
|
26
26
|
import { SelectionIndicator, toggleModalSelectionAtom } from "./components/indicators/selection.js";
|
|
27
|
+
import { actionRequiresEditable, buildDataViewSelection, computeFilteredRowIndices, computeSelectionShape, getApplicableActions, getSelectedColumnKeys, getSelectedRowIndices, getSelectionCardinality, mergeColumnActions, range, rowIndicesToRegions } from "./actions/selection.js";
|
|
27
28
|
import { addRowAction, defaultTableActions, deleteRowsAction, resetChangesAction } from "./actions/builtin.js";
|
|
28
29
|
import { anchorRefAtom, selectionAtom } from "./provider/selection.js";
|
|
29
30
|
import { applyColumnFilters, autoLoadPagesAtom, chunkPageAtom, createPostgRESTFetchChunk, createPostgRESTProvider, resumeBaselineAtom, standardizeFilter, tableFooterAtom, useDataLoader, useLoadControls, useScrollHandler, viewInfoAtom } from "./postgrest-table/data-loaders.js";
|
|
30
31
|
import { buildActionContext, runActionWrapper } from "./actions/context.js";
|
|
31
|
-
import { buildDataViewSelection, computeFilteredRowIndices, computeSelectionShape, getApplicableActions, getSelectedColumnKeys, getSelectedRowIndices, getSelectionCardinality, mergeColumnActions, range, rowIndicesToRegions } from "./actions/selection.js";
|
|
32
32
|
import { buildMultiOperatorColumnFilter, columnFilterId, enhanceColumnFilter } from "./actions/column-filter.js";
|
|
33
33
|
import { collectValidationErrors, validateCell } from "./utils/validation.js";
|
|
34
34
|
import { columnControlActions, columnFilterAction, columnSortAction, isColumnFilterable } from "./actions/column-controls.js";
|
|
@@ -102,6 +102,7 @@ export {
|
|
|
102
102
|
SelectionInteractionStyle,
|
|
103
103
|
ShowRowEditor,
|
|
104
104
|
TableElementStatus,
|
|
105
|
+
actionRequiresEditable,
|
|
105
106
|
addRowAction,
|
|
106
107
|
anchorRefAtom,
|
|
107
108
|
applyColumnFilters,
|
|
@@ -3,22 +3,22 @@ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toString
|
|
|
3
3
|
const h$1 = require("@macrostrat/hyper");
|
|
4
4
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
|
5
5
|
const h__default = /* @__PURE__ */ _interopDefault(h$1);
|
|
6
|
-
const spacer = "
|
|
6
|
+
const spacer = "_spacer_14j1s_132";
|
|
7
7
|
const styles = {
|
|
8
|
-
"data-sheet-container": "_data-sheet-
|
|
9
|
-
"data-sheet-holder": "_data-sheet-
|
|
10
|
-
"data-sheet": "_data-
|
|
11
|
-
"input-cell": "_input-
|
|
12
|
-
"derived-cell": "_derived-
|
|
13
|
-
"value-viewer-cell": "_value-viewer-
|
|
14
|
-
"editor-cell": "_editor-
|
|
15
|
-
"hidden-input": "_hidden-
|
|
16
|
-
"data-editor-anchor": "_data-editor-
|
|
17
|
-
"corner-drag-handle": "_corner-drag-
|
|
18
|
-
"data-sheet-toolbar": "_data-sheet-
|
|
8
|
+
"data-sheet-container": "_data-sheet-container_14j1s_4",
|
|
9
|
+
"data-sheet-holder": "_data-sheet-holder_14j1s_4",
|
|
10
|
+
"data-sheet": "_data-sheet_14j1s_4",
|
|
11
|
+
"input-cell": "_input-cell_14j1s_61",
|
|
12
|
+
"derived-cell": "_derived-cell_14j1s_78",
|
|
13
|
+
"value-viewer-cell": "_value-viewer-cell_14j1s_83",
|
|
14
|
+
"editor-cell": "_editor-cell_14j1s_91",
|
|
15
|
+
"hidden-input": "_hidden-input_14j1s_103",
|
|
16
|
+
"data-editor-anchor": "_data-editor-anchor_14j1s_109",
|
|
17
|
+
"corner-drag-handle": "_corner-drag-handle_14j1s_116",
|
|
18
|
+
"data-sheet-toolbar": "_data-sheet-toolbar_14j1s_126",
|
|
19
19
|
spacer,
|
|
20
|
-
"table-control": "_table-
|
|
21
|
-
"status-bar": "_status-
|
|
20
|
+
"table-control": "_table-control_14j1s_136",
|
|
21
|
+
"status-bar": "_status-bar_14j1s_142"
|
|
22
22
|
};
|
|
23
23
|
let h = h__default.default.styled(styles);
|
|
24
24
|
Object.assign(h, styles);
|
package/dist/main.module.sass.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import h$1 from "@macrostrat/hyper";
|
|
2
|
-
const spacer = "
|
|
2
|
+
const spacer = "_spacer_14j1s_132";
|
|
3
3
|
const styles = {
|
|
4
|
-
"data-sheet-container": "_data-sheet-
|
|
5
|
-
"data-sheet-holder": "_data-sheet-
|
|
6
|
-
"data-sheet": "_data-
|
|
7
|
-
"input-cell": "_input-
|
|
8
|
-
"derived-cell": "_derived-
|
|
9
|
-
"value-viewer-cell": "_value-viewer-
|
|
10
|
-
"editor-cell": "_editor-
|
|
11
|
-
"hidden-input": "_hidden-
|
|
12
|
-
"data-editor-anchor": "_data-editor-
|
|
13
|
-
"corner-drag-handle": "_corner-drag-
|
|
14
|
-
"data-sheet-toolbar": "_data-sheet-
|
|
4
|
+
"data-sheet-container": "_data-sheet-container_14j1s_4",
|
|
5
|
+
"data-sheet-holder": "_data-sheet-holder_14j1s_4",
|
|
6
|
+
"data-sheet": "_data-sheet_14j1s_4",
|
|
7
|
+
"input-cell": "_input-cell_14j1s_61",
|
|
8
|
+
"derived-cell": "_derived-cell_14j1s_78",
|
|
9
|
+
"value-viewer-cell": "_value-viewer-cell_14j1s_83",
|
|
10
|
+
"editor-cell": "_editor-cell_14j1s_91",
|
|
11
|
+
"hidden-input": "_hidden-input_14j1s_103",
|
|
12
|
+
"data-editor-anchor": "_data-editor-anchor_14j1s_109",
|
|
13
|
+
"corner-drag-handle": "_corner-drag-handle_14j1s_116",
|
|
14
|
+
"data-sheet-toolbar": "_data-sheet-toolbar_14j1s_126",
|
|
15
15
|
spacer,
|
|
16
|
-
"table-control": "_table-
|
|
17
|
-
"status-bar": "_status-
|
|
16
|
+
"table-control": "_table-control_14j1s_136",
|
|
17
|
+
"status-bar": "_status-bar_14j1s_142"
|
|
18
18
|
};
|
|
19
19
|
let h = h$1.styled(styles);
|
|
20
20
|
Object.assign(h, styles);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-spec.cjs","sources":["../../src/provider/column-spec.ts"],"sourcesContent":["import React from \"react\";\nimport type { Placement } from \"@blueprintjs/core\";\nimport { enhanceColumnFilter, TableFilter } from \"../actions\";\n\nconst defaultRenderers = {\n string: (d) => d,\n number: (d) => d?.toFixed(2),\n boolean: (d) => (d ? \"T\" : \"F\"),\n object: (d) => JSON.stringify(d),\n integer: (d) => d?.toFixed(0),\n array: (d) => d?.join(\", \"),\n};\n\ninterface ColumnSpecGenerateOptions {\n calculateWidths?: boolean;\n defaultWidth?: number;\n getWidthForValue?: (value: any) => number;\n}\n\nconst defaultWidthForValue = (val) => String(val).length * 8;\n\n/** Inferred data type of a column, used to select appropriate\n * sort/filter operators. */\nexport type ColumnDataType =\n \"text\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\";\n\n/** Severity of a cell validation result. `warning` is soft (flagged, doesn't\n * block saving); `error` is hard (blocks saving). */\nexport type ValidationSeverity = \"warning\" | \"error\";\n\n/** The result of validating a cell. `null` means valid. */\nexport interface CellValidation {\n severity: ValidationSeverity;\n message?: string;\n}\n\n/**\n * Context handed to per-cell renderers (`valueRenderer`, and — as the\n * `cellContext` prop — a custom `cellComponent`). It lets a renderer draw\n * based on the row/column position and the cell's edit status, and, combined\n * with the editing API, write edits back for a specific cell.\n *\n * `rowIndex` is the underlying **data-row index** (the value edit methods\n * expect), so it stays stable when a sort or filter reorders the view.\n */\nexport interface CellRenderContext<T = any> {\n /** The cell's current value (the edited value if present, else the base). */\n value: any;\n /** Underlying data-row index — stable under sort/filter. */\n rowIndex: number;\n /** Column index within the active column spec. */\n colIndex: number;\n /** The full column spec for this cell's column. */\n column: ColumnSpec;\n /** The full row object backing this cell (may be undefined while loading). */\n row: T | null | undefined;\n /** Whether this cell has an uncommitted edit. */\n isEdited: boolean;\n /** Whether this cell's row is marked for deletion. */\n isDeleted: boolean;\n /** The row's status value (`RowStatusValue`) — `\"deleted\"` / `\"added\"` or a\n * consumer-defined status (e.g. `\"omitted\"`), or `undefined` for a normal\n * row. Lets a renderer style by arbitrary status, not just deletion. */\n status: string | undefined;\n /** Validation result for this cell, or `null` when valid. Orthogonal to the\n * edit status — a cell can be both edited and invalid. */\n validation: CellValidation | null;\n}\n\n/**\n * The editor configuration for a cell. Mirrors the static `dataEditor` /\n * `inlineEditor` column fields so a per-cell resolver (`editorForCell`) can\n * override either one for an individual cell.\n */\nexport interface CellEditors {\n dataEditor?: any;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n}\n\n/**\n * Context for a cell's detail surface (`cellDetail`). Extends the render\n * context with the edit affordances and controls a surface needs, so one\n * component can act as an editor (when `editable`) or a read-only viewer\n * (otherwise). This is the write side of the read/write contract, per-cell.\n */\nexport interface CellDetailContext<T = any> extends CellRenderContext<T> {\n /** Whether this cell is editable (column × table × not-deleted). */\n editable: boolean;\n /**\n * When the surface stands for several cells at once (the row editor over a\n * multi-row selection), the cells it stands for. `value` is then the value\n * they share, or `undefined` when they differ (`mixed`), and `onChange`\n * writes every one of them. Only offered to a column that declares\n * `multiCell`; absent for a single cell.\n */\n cells?: CellSelectionEntry<T>[];\n /** True when `cells` hold differing values. */\n mixed?: boolean;\n /** Where the surface is drawn: `\"cell\"`, the grid's own popover, modal or\n * in-cell surface; `\"row-editor\"`, a field of the sheet's row editor; or\n * `\"editor\"`, a field of a standalone `DataEditor` — so a surface can lay\n * itself out to suit (a picker nesting its own popovers only where it has\n * room). */\n surface?: \"cell\" | \"row-editor\" | \"editor\";\n /** Commit a new value for this cell — for every cell, when the surface\n * stands for several. */\n onChange: (value: any) => void;\n /** With `cells`, commit a value for each cell, aligned with them — for a\n * surface that changes each cell's own value (adding a tag to every row's\n * list) rather than setting them all to one. */\n onChangeCells?: (values: any[]) => void;\n /** Reset this cell (and selection) to its base value. */\n resetValue: () => void;\n /** Close the surface and return focus to the table. */\n close: () => void;\n}\n\n/** One of the cells a multi-cell surface stands for. */\nexport interface CellSelectionEntry<T = any> {\n rowIndex: number;\n row: T | null | undefined;\n value: any;\n}\n\n/** How a cell's detail surface is presented. Orthogonal to what it renders. */\nexport type DetailPresentation = \"popover\" | \"modal\" | \"inline\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n /** When true, an empty value is an error (sugar over `validate`). */\n required?: boolean;\n /** Validate a cell's value. Return a `{ severity, message }` for a\n * warning/error, or `null` when valid. Runs after the `required` check.\n * `warning` flags the cell but allows saving; `error` blocks saving. */\n validate?: (\n value: any,\n row: any,\n ctx: { rowIndex: number },\n ) => CellValidation | null;\n /** @deprecated Prefer `validate`, which carries severity + a message.\n * A falsy result maps to an `error`. */\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any, ctx?: CellRenderContext) => string | React.ReactNode;\n headerRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\n /**\n * Choose the editor for an individual cell from its render context,\n * overriding the static `dataEditor` / `inlineEditor` for that cell. Return\n * `undefined` (or omit a key) to fall back to the static configuration —\n * e.g. show a textarea only for cells whose value is long. A returned key is\n * respected even when its value is `false`/`null` (i.e. \"no editor here\").\n */\n editorForCell?: (ctx: CellRenderContext) => CellEditors | undefined;\n /**\n * Render a read-only detail panel for a cell. When set, selecting the cell\n * opens a popover with this content (following the table's `cellInteraction`\n * mode). The panel never takes keyboard focus, so arrow keys keep navigating\n * the table; Escape closes it. Mutually distinct from `dataEditor` — use this\n * for non-editable surfaces (previews, summaries, links).\n *\n * @deprecated Prefer `cellDetail`, which unifies editor and viewer.\n */\n detailRenderer?: (ctx: CellRenderContext) => React.ReactNode;\n /**\n * The unified cell surface (Workstream A): one renderer that acts as an\n * editor when `ctx.editable` and a read-only viewer otherwise, superseding\n * `dataEditor` / `detailRenderer` / `editorForCell`. Presentation is chosen\n * separately via `detailPresentation` (popover / modal / inline), so the\n * same component works in any container.\n */\n cellDetail?: (ctx: CellDetailContext) => React.ReactNode;\n /**\n * Whether this column's `cellDetail` can stand for several cells at once —\n * read the shared value (or `ctx.mixed`) and write every cell in\n * `ctx.cells` through one `onChange`. A surface that doesn't declare this\n * is shown read-only over a multi-row selection, with \"Multiple values\"\n * where they differ. The default editors (an input by `dataType`) always\n * can, since setting one value on every cell is what they do.\n */\n multiCell?: boolean;\n /** How `cellDetail` is presented. Defaults to `\"popover\"`. */\n detailPresentation?: DetailPresentation;\n /** What one cell of the column is called, for the selection indicator\n * (\"1 lithology\", \"3 lithologies\"). Defaults to the column's name. */\n cellLabel?: string;\n /** Where a popover `cellDetail` opens against its cell. Defaults to\n * `\"right-start\"`; a wide surface (a tag picker) reads better below, at\n * `\"bottom-start\"`. */\n detailPlacement?: Placement;\n cellComponent?: any;\n category?: string;\n editable?: boolean;\n /**\n * A **derived** column holds values computed from other data — a total, an\n * age that follows from an interval and a proportion — rather than values\n * anyone types. It is never writable, whatever `editable` or the table\n * says, and every write path (inline editing, fill, paste, the row editor)\n * leaves it alone; it is drawn dimmed so a reader can tell what is a record\n * and what is a restatement of one. Use it instead of `editable: false` when\n * the read-only-ness is a property of the *data* rather than of the view.\n */\n derived?: boolean;\n /**\n * A **hidden** column stays in the spec but is left out of the working\n * spec the table is built from: it isn't rendered, isn't part of a\n * selection, and isn't written by a fill or a paste. A consumer keeps one\n * spec and toggles this flag (\"show absolute ages\", \"show generated ids\")\n * rather than maintaining two arrays. Resolved by `postprocessColumnSpec`.\n */\n hidden?: boolean;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n style?: React.CSSProperties;\n width?: number;\n /** Column-specific table actions (TableAction[]). These appear in the\n * actions toolbar when this column is part of the current selection. */\n actions?: any[];\n /** Column-specific table filters (TableFilter[]). These appear in the\n * filter bar and apply to this column's values. */\n filters?: any[];\n /** Whether this column supports server-side sorting. */\n sortable?: boolean;\n /** Whether this column supports server-side filtering.\n * Set to `true` for default operators, or provide a config object\n * with a custom set of operators. */\n filterable?: boolean | { operators?: string[] };\n /** Inferred data type, used to select context-appropriate filter\n * operators when `filterable` is `true` without explicit operators. */\n dataType?: ColumnDataType;\n /** Whether this column may be drag-reordered. Defaults to `true`; set\n * `false` to pin a fixed/system column in place. Applied by the default\n * header renderer (requires table-level `enableColumnReordering`). */\n reorderable?: boolean;\n}\n\nexport interface ColumnSpecOptions<T> {\n overrides: Record<string, Partial<ColumnSpec> | string>;\n data?: T[]; // Data to use for type inference\n nRows?: number; // Number of rows to use for type inference\n omitColumns?: string[]; // Columns to omit. Takes precedence over includeColumns.\n includeColumns?: string[]; // Columns to include.\n}\n\nexport function generateDefaultColumnSpec<T>(\n data: Array<T>,\n options: ColumnSpecGenerateOptions = {},\n): ColumnSpec[] {\n /** Build a default column spec from a dataset based on the first n rows */\n if (data == null) return [];\n // Get the keys\n\n const {\n defaultWidth = 150,\n calculateWidths = true,\n getWidthForValue = defaultWidthForValue,\n } = options;\n\n const keys = new Set<string>();\n const types = new Map();\n\n const columnWidths = new Map<string, number>();\n\n for (const row of data) {\n if (row == null) continue;\n for (const key of Object.keys(row)) {\n const val = row[key];\n keys.add(key);\n\n if (val == null) continue;\n\n if (calculateWidths) {\n let width = getWidthForValue(val);\n if (width != null && width >= 0) {\n columnWidths.set(key, Math.max(width, columnWidths.get(key) ?? 0));\n }\n }\n\n let type: string = typeof val;\n // Special 'type' for integers\n if (Number.isInteger(val)) {\n type = \"integer\";\n }\n\n // Special 'type' for arrays of simple values\n if (\n Array.isArray(val) &&\n val.every((d) => typeof d === \"string\" || typeof d === \"number\")\n ) {\n type = \"array\";\n }\n\n // Check if it is strictly a string, if so, we can explicitly mark it as text\n if (type === \"string\") {\n type = \"text\";\n }\n\n if (types.has(key)) {\n if (types.get(key) !== type) {\n if (type === \"number\" && types.get(key) === \"integer\") {\n types.set(key, \"number\");\n }\n if (type === \"object\" && types.get(key) === \"array\") {\n types.set(key, \"object\");\n }\n\n types.set(key, \"string\");\n }\n } else {\n types.set(key, type);\n }\n }\n }\n\n // Build a column spec\n const spec: ColumnSpec[] = [];\n for (const key of keys) {\n let width: number | undefined = undefined;\n if (calculateWidths) {\n // If we are calculating widths, use the value lengths\n width = Math.min(\n Math.max(defaultWidth / 2, columnWidths.get(key) ?? defaultWidth),\n defaultWidth * 1.5,\n );\n }\n\n const dataType = (types.get(key) ?? \"string\") as ColumnDataType;\n\n // Auto-infer sortable/filterable based on data type.\n // Scalar types (string, number, integer, boolean) get sort/filter;\n // complex types (object, array) do not.\n const isScalar =\n dataType === \"text\" ||\n dataType === \"string\" ||\n dataType === \"number\" ||\n dataType === \"integer\" ||\n dataType === \"boolean\";\n\n spec.push({\n name: key,\n key,\n valueRenderer: defaultRenderers[types.get(key)],\n width,\n dataType,\n sortable: isScalar,\n filterable: isScalar,\n });\n }\n return spec;\n}\n\nexport function generateColumnSpec<T>(\n data: T[],\n options: Partial<ColumnSpecOptions<T>> = {},\n): ColumnSpec[] {\n /** Generate a column spec from a dataset */\n const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;\n\n if (data == null) return [];\n\n const _nRows = Math.min(nRows, data.length);\n\n let columnSpec = generateDefaultColumnSpec(data.slice(0, _nRows));\n let filteredSpec = columnSpec.filter((col) => {\n if (omitColumns != null && omitColumns.includes(col.key)) {\n return false;\n }\n if (includeColumns != null && !includeColumns.includes(col.key)) {\n return false;\n }\n return true;\n });\n\n // Apply overrides\n const improvedSpec = filteredSpec.map((col) => {\n let ovr = overrides[col.key];\n if (ovr == null) return col;\n if (typeof ovr === \"string\") {\n return { ...col, name: ovr };\n }\n return { ...col, ...ovr };\n });\n return postprocessColumnSpec(improvedSpec);\n}\n\nexport function postprocessColumnSpec(columnSpec: ColumnSpec[]) {\n /** Postprocess column spec to make sure that, e.g., column filters are\n * properly established, etc. Hidden columns are dropped here, so everything\n * downstream — the renderer, the selection, the edit paths — works with the\n * visible columns only and indexes into one array.\n */\n return columnSpec\n .filter((col) => !col.hidden)\n .map((col) => {\n return {\n ...col,\n filters: postprocessColumnFilters(col),\n actions: col.actions ?? [],\n };\n });\n}\n\n/**\n * Whether a column takes writes at all: the table is editable, the column\n * isn't locked (`editable: false`) and it isn't `derived`. This is the one\n * rule every write path consults — the inline editor, `onSelectionEdited`,\n * fill, clear, clipboard paste and the row editor — so a locked column is\n * locked however the edit arrives, not only when it is typed into.\n */\nexport function isColumnWritable(\n col: ColumnSpec | null | undefined,\n tableEditable: boolean = true,\n): boolean {\n if (col == null) return false;\n if (!tableEditable) return false;\n if (col.derived) return false;\n return col.editable !== false;\n}\n\nfunction postprocessColumnFilters(col: ColumnSpec): TableFilter[] | undefined {\n const { filterable = true, filters = [] } = col;\n if (!filterable) {\n return undefined;\n }\n return filters.map((f) => enhanceColumnFilter(col, f));\n}\n"],"names":["enhanceColumnFilter"],"mappings":";;;AAIA,MAAM,mBAAmB;AAAA,EACvB,QAAQ,CAAC,MAAM;AAAA,EACf,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC3B,SAAS,CAAC,MAAO,IAAI,MAAM;AAAA,EAC3B,QAAQ,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/B,SAAS,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC5B,OAAO,CAAC,MAAM,GAAG,KAAK,IAAI;AAC5B;AAQA,MAAM,uBAAuB,CAAC,QAAQ,OAAO,GAAG,EAAE,SAAS;AAiOpD,SAAS,0BACd,MACA,UAAqC,IACvB;AAEd,MAAI,QAAQ,KAAM,QAAO,CAAA;AAGzB,QAAM;AAAA,IACJ,eAAe;AAAA,IACf,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,EAAA,IACjB;AAEJ,QAAM,2BAAW,IAAA;AACjB,QAAM,4BAAY,IAAA;AAElB,QAAM,mCAAmB,IAAA;AAEzB,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,KAAM;AACjB,eAAW,OAAO,OA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C;AAAA,EAE7B,CAAC;AACL;AASO,SAAS,iBACd,KACA,gBAAyB,MAChB;AACT,MAAI,OAAO,KAAM,QAAO;AACxB,MAAI,CAAC,cAAe,QAAO;AAC3B,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,IAAI,aAAa;AAC1B;AAEA,SAAS,yBAAyB,KAA4C;AAC5E,QAAM,EAAE,aAAa,MAAM,UAAU,CAAA,MAAO;AAC5C,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,IAAI,CAAC,MAAMA,aAAAA,oBAAoB,KAAK,CAAC,CAAC;AACvD;;;;;"}
|
|
1
|
+
{"version":3,"file":"column-spec.cjs","sources":["../../src/provider/column-spec.ts"],"sourcesContent":["import React from \"react\";\nimport type { Placement } from \"@blueprintjs/core\";\nimport { enhanceColumnFilter, TableFilter } from \"../actions\";\n\nconst defaultRenderers = {\n string: (d) => d,\n number: (d) => d?.toFixed(2),\n boolean: (d) => (d ? \"T\" : \"F\"),\n object: (d) => JSON.stringify(d),\n integer: (d) => d?.toFixed(0),\n array: (d) => d?.join(\", \"),\n};\n\ninterface ColumnSpecGenerateOptions {\n calculateWidths?: boolean;\n defaultWidth?: number;\n getWidthForValue?: (value: any) => number;\n}\n\nconst defaultWidthForValue = (val) => String(val).length * 8;\n\n/** Inferred data type of a column, used to select appropriate\n * sort/filter operators. */\nexport type ColumnDataType =\n \"text\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\";\n\n/** Severity of a cell validation result. `warning` is soft (flagged, doesn't\n * block saving); `error` is hard (blocks saving). */\nexport type ValidationSeverity = \"warning\" | \"error\";\n\n/** The result of validating a cell. `null` means valid. */\nexport interface CellValidation {\n severity: ValidationSeverity;\n message?: string;\n}\n\n/**\n * Context handed to per-cell renderers (`valueRenderer`, and — as the\n * `cellContext` prop — a custom `cellComponent`). It lets a renderer draw\n * based on the row/column position and the cell's edit status, and, combined\n * with the editing API, write edits back for a specific cell.\n *\n * `rowIndex` is the underlying **data-row index** (the value edit methods\n * expect), so it stays stable when a sort or filter reorders the view.\n */\nexport interface CellRenderContext<T = any> {\n /** The cell's current value (the edited value if present, else the base). */\n value: any;\n /** Underlying data-row index — stable under sort/filter. */\n rowIndex: number;\n /** Column index within the active column spec. */\n colIndex: number;\n /** The full column spec for this cell's column. */\n column: ColumnSpec;\n /** The full row object backing this cell (may be undefined while loading). */\n row: T | null | undefined;\n /** Whether this cell has an uncommitted edit. */\n isEdited: boolean;\n /** Whether this cell's row is marked for deletion. */\n isDeleted: boolean;\n /** The row's status value (`RowStatusValue`) — `\"deleted\"` / `\"added\"` or a\n * consumer-defined status (e.g. `\"omitted\"`), or `undefined` for a normal\n * row. Lets a renderer style by arbitrary status, not just deletion. */\n status: string | undefined;\n /** Validation result for this cell, or `null` when valid. Orthogonal to the\n * edit status — a cell can be both edited and invalid. */\n validation: CellValidation | null;\n /** The cell's size in pixels, border and padding included, when it is a\n * grid cell — the column's width and the row's height, which the table\n * knows and a renderer would otherwise have to measure. Absent on surfaces\n * that aren't laid out in the cell (a popover, the row editor). A value\n * renderer that lays itself out to fit — a row of tags — can re-fit when\n * these change instead of observing its own size. */\n width?: number;\n height?: number;\n}\n\n/**\n * The editor configuration for a cell. Mirrors the static `dataEditor` /\n * `inlineEditor` column fields so a per-cell resolver (`editorForCell`) can\n * override either one for an individual cell.\n */\nexport interface CellEditors {\n dataEditor?: any;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n}\n\n/**\n * Context for a cell's detail surface (`cellDetail`). Extends the render\n * context with the edit affordances and controls a surface needs, so one\n * component can act as an editor (when `editable`) or a read-only viewer\n * (otherwise). This is the write side of the read/write contract, per-cell.\n */\nexport interface CellDetailContext<T = any> extends CellRenderContext<T> {\n /** Whether this cell is editable (column × table × not-deleted). */\n editable: boolean;\n /**\n * When the surface stands for several cells at once (the row editor over a\n * multi-row selection), the cells it stands for. `value` is then the value\n * they share, or `undefined` when they differ (`mixed`), and `onChange`\n * writes every one of them. Only offered to a column that declares\n * `multiCell`; absent for a single cell.\n */\n cells?: CellSelectionEntry<T>[];\n /** True when `cells` hold differing values. */\n mixed?: boolean;\n /** Where the surface is drawn: `\"cell\"`, the grid's own popover, modal or\n * in-cell surface; `\"row-editor\"`, a field of the sheet's row editor; or\n * `\"editor\"`, a field of a standalone `DataEditor` — so a surface can lay\n * itself out to suit (a picker nesting its own popovers only where it has\n * room). */\n surface?: \"cell\" | \"row-editor\" | \"editor\";\n /** Commit a new value for this cell — for every cell, when the surface\n * stands for several. */\n onChange: (value: any) => void;\n /** With `cells`, commit a value for each cell, aligned with them — for a\n * surface that changes each cell's own value (adding a tag to every row's\n * list) rather than setting them all to one. */\n onChangeCells?: (values: any[]) => void;\n /** Reset this cell (and selection) to its base value. */\n resetValue: () => void;\n /** Close the surface and return focus to the table. */\n close: () => void;\n}\n\n/** One of the cells a multi-cell surface stands for. */\nexport interface CellSelectionEntry<T = any> {\n rowIndex: number;\n row: T | null | undefined;\n value: any;\n}\n\n/** How a cell's detail surface is presented. Orthogonal to what it renders. */\nexport type DetailPresentation = \"popover\" | \"modal\" | \"inline\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n /** When true, an empty value is an error (sugar over `validate`). */\n required?: boolean;\n /** Validate a cell's value. Return a `{ severity, message }` for a\n * warning/error, or `null` when valid. Runs after the `required` check.\n * `warning` flags the cell but allows saving; `error` blocks saving. */\n validate?: (\n value: any,\n row: any,\n ctx: { rowIndex: number },\n ) => CellValidation | null;\n /** @deprecated Prefer `validate`, which carries severity + a message.\n * A falsy result maps to an `error`. */\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any, ctx?: CellRenderContext) => string | React.ReactNode;\n headerRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\n /**\n * Choose the editor for an individual cell from its render context,\n * overriding the static `dataEditor` / `inlineEditor` for that cell. Return\n * `undefined` (or omit a key) to fall back to the static configuration —\n * e.g. show a textarea only for cells whose value is long. A returned key is\n * respected even when its value is `false`/`null` (i.e. \"no editor here\").\n */\n editorForCell?: (ctx: CellRenderContext) => CellEditors | undefined;\n /**\n * Render a read-only detail panel for a cell. When set, selecting the cell\n * opens a popover with this content (following the table's `cellInteraction`\n * mode). The panel never takes keyboard focus, so arrow keys keep navigating\n * the table; Escape closes it. Mutually distinct from `dataEditor` — use this\n * for non-editable surfaces (previews, summaries, links).\n *\n * @deprecated Prefer `cellDetail`, which unifies editor and viewer.\n */\n detailRenderer?: (ctx: CellRenderContext) => React.ReactNode;\n /**\n * The unified cell surface (Workstream A): one renderer that acts as an\n * editor when `ctx.editable` and a read-only viewer otherwise, superseding\n * `dataEditor` / `detailRenderer` / `editorForCell`. Presentation is chosen\n * separately via `detailPresentation` (popover / modal / inline), so the\n * same component works in any container.\n */\n cellDetail?: (ctx: CellDetailContext) => React.ReactNode;\n /**\n * Whether this column's `cellDetail` can stand for several cells at once —\n * read the shared value (or `ctx.mixed`) and write every cell in\n * `ctx.cells` through one `onChange`. A surface that doesn't declare this\n * is shown read-only over a multi-row selection, with \"Multiple values\"\n * where they differ. The default editors (an input by `dataType`) always\n * can, since setting one value on every cell is what they do.\n */\n multiCell?: boolean;\n /** How `cellDetail` is presented. Defaults to `\"popover\"`. */\n detailPresentation?: DetailPresentation;\n /** What one cell of the column is called, for the selection indicator\n * (\"1 lithology\", \"3 lithologies\"). Defaults to the column's name. */\n cellLabel?: string;\n /** Where a popover `cellDetail` opens against its cell. Defaults to\n * `\"right-start\"`; a wide surface (a tag picker) reads better below, at\n * `\"bottom-start\"`. */\n detailPlacement?: Placement;\n cellComponent?: any;\n category?: string;\n editable?: boolean;\n /**\n * A **derived** column holds values computed from other data — a total, an\n * age that follows from an interval and a proportion — rather than values\n * anyone types. It is never writable, whatever `editable` or the table\n * says, and every write path (inline editing, fill, paste, the row editor)\n * leaves it alone; it is drawn dimmed so a reader can tell what is a record\n * and what is a restatement of one. Use it instead of `editable: false` when\n * the read-only-ness is a property of the *data* rather than of the view.\n */\n derived?: boolean;\n /**\n * A **hidden** column stays in the spec but is left out of the working\n * spec the table is built from: it isn't rendered, isn't part of a\n * selection, and isn't written by a fill or a paste. A consumer keeps one\n * spec and toggles this flag (\"show absolute ages\", \"show generated ids\")\n * rather than maintaining two arrays. Resolved by `postprocessColumnSpec`.\n */\n hidden?: boolean;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n style?: React.CSSProperties;\n width?: number;\n /** Column-specific table actions (TableAction[]). These appear in the\n * actions toolbar when this column is part of the current selection. */\n actions?: any[];\n /** Column-specific table filters (TableFilter[]). These appear in the\n * filter bar and apply to this column's values. */\n filters?: any[];\n /** Whether this column supports server-side sorting. */\n sortable?: boolean;\n /** Whether this column supports server-side filtering.\n * Set to `true` for default operators, or provide a config object\n * with a custom set of operators. */\n filterable?: boolean | { operators?: string[] };\n /** Inferred data type, used to select context-appropriate filter\n * operators when `filterable` is `true` without explicit operators. */\n dataType?: ColumnDataType;\n /** Whether this column may be drag-reordered. Defaults to `true`; set\n * `false` to pin a fixed/system column in place. Applied by the default\n * header renderer (requires table-level `enableColumnReordering`). */\n reorderable?: boolean;\n}\n\nexport interface ColumnSpecOptions<T> {\n overrides: Record<string, Partial<ColumnSpec> | string>;\n data?: T[]; // Data to use for type inference\n nRows?: number; // Number of rows to use for type inference\n omitColumns?: string[]; // Columns to omit. Takes precedence over includeColumns.\n includeColumns?: string[]; // Columns to include.\n}\n\nexport function generateDefaultColumnSpec<T>(\n data: Array<T>,\n options: ColumnSpecGenerateOptions = {},\n): ColumnSpec[] {\n /** Build a default column spec from a dataset based on the first n rows */\n if (data == null) return [];\n // Get the keys\n\n const {\n defaultWidth = 150,\n calculateWidths = true,\n getWidthForValue = defaultWidthForValue,\n } = options;\n\n const keys = new Set<string>();\n const types = new Map();\n\n const columnWidths = new Map<string, number>();\n\n for (const row of data) {\n if (row == null) continue;\n for (const key of Object.keys(row)) {\n const val = row[key];\n keys.add(key);\n\n if (val == null) continue;\n\n if (calculateWidths) {\n let width = getWidthForValue(val);\n if (width != null && width >= 0) {\n columnWidths.set(key, Math.max(width, columnWidths.get(key) ?? 0));\n }\n }\n\n let type: string = typeof val;\n // Special 'type' for integers\n if (Number.isInteger(val)) {\n type = \"integer\";\n }\n\n // Special 'type' for arrays of simple values\n if (\n Array.isArray(val) &&\n val.every((d) => typeof d === \"string\" || typeof d === \"number\")\n ) {\n type = \"array\";\n }\n\n // Check if it is strictly a string, if so, we can explicitly mark it as text\n if (type === \"string\") {\n type = \"text\";\n }\n\n if (types.has(key)) {\n if (types.get(key) !== type) {\n if (type === \"number\" && types.get(key) === \"integer\") {\n types.set(key, \"number\");\n }\n if (type === \"object\" && types.get(key) === \"array\") {\n types.set(key, \"object\");\n }\n\n types.set(key, \"string\");\n }\n } else {\n types.set(key, type);\n }\n }\n }\n\n // Build a column spec\n const spec: ColumnSpec[] = [];\n for (const key of keys) {\n let width: number | undefined = undefined;\n if (calculateWidths) {\n // If we are calculating widths, use the value lengths\n width = Math.min(\n Math.max(defaultWidth / 2, columnWidths.get(key) ?? defaultWidth),\n defaultWidth * 1.5,\n );\n }\n\n const dataType = (types.get(key) ?? \"string\") as ColumnDataType;\n\n // Auto-infer sortable/filterable based on data type.\n // Scalar types (string, number, integer, boolean) get sort/filter;\n // complex types (object, array) do not.\n const isScalar =\n dataType === \"text\" ||\n dataType === \"string\" ||\n dataType === \"number\" ||\n dataType === \"integer\" ||\n dataType === \"boolean\";\n\n spec.push({\n name: key,\n key,\n valueRenderer: defaultRenderers[types.get(key)],\n width,\n dataType,\n sortable: isScalar,\n filterable: isScalar,\n });\n }\n return spec;\n}\n\nexport function generateColumnSpec<T>(\n data: T[],\n options: Partial<ColumnSpecOptions<T>> = {},\n): ColumnSpec[] {\n /** Generate a column spec from a dataset */\n const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;\n\n if (data == null) return [];\n\n const _nRows = Math.min(nRows, data.length);\n\n let columnSpec = generateDefaultColumnSpec(data.slice(0, _nRows));\n let filteredSpec = columnSpec.filter((col) => {\n if (omitColumns != null && omitColumns.includes(col.key)) {\n return false;\n }\n if (includeColumns != null && !includeColumns.includes(col.key)) {\n return false;\n }\n return true;\n });\n\n // Apply overrides\n const improvedSpec = filteredSpec.map((col) => {\n let ovr = overrides[col.key];\n if (ovr == null) return col;\n if (typeof ovr === \"string\") {\n return { ...col, name: ovr };\n }\n return { ...col, ...ovr };\n });\n return postprocessColumnSpec(improvedSpec);\n}\n\nexport function postprocessColumnSpec(columnSpec: ColumnSpec[]) {\n /** Postprocess column spec to make sure that, e.g., column filters are\n * properly established, etc. Hidden columns are dropped here, so everything\n * downstream — the renderer, the selection, the edit paths — works with the\n * visible columns only and indexes into one array.\n */\n return columnSpec\n .filter((col) => !col.hidden)\n .map((col) => {\n return {\n ...col,\n filters: postprocessColumnFilters(col),\n actions: col.actions ?? [],\n };\n });\n}\n\n/**\n * Whether a column takes writes at all: the table is editable, the column\n * isn't locked (`editable: false`) and it isn't `derived`. This is the one\n * rule every write path consults — the inline editor, `onSelectionEdited`,\n * fill, clear, clipboard paste and the row editor — so a locked column is\n * locked however the edit arrives, not only when it is typed into.\n */\nexport function isColumnWritable(\n col: ColumnSpec | null | undefined,\n tableEditable: boolean = true,\n): boolean {\n if (col == null) return false;\n if (!tableEditable) return false;\n if (col.derived) return false;\n return col.editable !== false;\n}\n\nfunction postprocessColumnFilters(col: ColumnSpec): TableFilter[] | undefined {\n const { filterable = true, filters = [] } = col;\n if (!filterable) {\n return undefined;\n }\n return filters.map((f) => enhanceColumnFilter(col, f));\n}\n"],"names":["enhanceColumnFilter"],"mappings":";;;AAIA,MAAM,mBAAmB;AAAA,EACvB,QAAQ,CAAC,MAAM;AAAA,EACf,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC3B,SAAS,CAAC,MAAO,IAAI,MAAM;AAAA,EAC3B,QAAQ,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/B,SAAS,CAAC,MAAM,GAAG,QAAQ,CAA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AG;AAC3B,QAAI,OAAO,KAAM,QAAO;AACxB,QAAI,OAAO,QAAQ,UAAU;AAC3B,aAAO,EAAE,GAAG,KAAK,MAAM,IAAA;AAAA,IACzB;AACA,WAAO,EAAE,GAAG,KAAK,GAAG,IAAA;AAAA,EACtB,CAAC;AACD,SAAO,sBAAsB,YAAY;AAC3C;AAEO,SAAS,sBAAsB,YAA0B;AAM9D,SAAO,WACJ,OAAO,CAAC,QAAQ,CAAC,IAAI,MAAM,EAC3B,IAAI,CAAC,QAAQ;AACZ,WAAO;AAAA,MACL,GAAG;AAAA,MACH,SAAS,yBAAyB,GAAG;AAAA,MACrC,SAAS,IAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAE7B,CAAC;AACL;AASO,SAAS,iBACd,KACA,gBAAyB,MAChB;AACT,MAAI,OAAO,KAAM,QAAO;AACxB,MAAI,CAAC,cAAe,QAAO;AAC3B,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,IAAI,aAAa;AAC1B;AAEA,SAAS,yBAAyB,KAA4C;AAC5E,QAAM,EAAE,aAAa,MAAM,UAAU,CAAA,MAAO;AAC5C,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,IAAI,CAAC,MAAMA,aAAAA,oBAAoB,KAAK,CAAC,CAAC;AACvD;;;;;"}
|
|
@@ -48,6 +48,14 @@ export interface CellRenderContext<T = any> {
|
|
|
48
48
|
/** Validation result for this cell, or `null` when valid. Orthogonal to the
|
|
49
49
|
* edit status — a cell can be both edited and invalid. */
|
|
50
50
|
validation: CellValidation | null;
|
|
51
|
+
/** The cell's size in pixels, border and padding included, when it is a
|
|
52
|
+
* grid cell — the column's width and the row's height, which the table
|
|
53
|
+
* knows and a renderer would otherwise have to measure. Absent on surfaces
|
|
54
|
+
* that aren't laid out in the cell (a popover, the row editor). A value
|
|
55
|
+
* renderer that lays itself out to fit — a row of tags — can re-fit when
|
|
56
|
+
* these change instead of observing its own size. */
|
|
57
|
+
width?: number;
|
|
58
|
+
height?: number;
|
|
51
59
|
}
|
|
52
60
|
/**
|
|
53
61
|
* The editor configuration for a cell. Mirrors the static `dataEditor` /
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-spec.js","sources":["../../src/provider/column-spec.ts"],"sourcesContent":["import React from \"react\";\nimport type { Placement } from \"@blueprintjs/core\";\nimport { enhanceColumnFilter, TableFilter } from \"../actions\";\n\nconst defaultRenderers = {\n string: (d) => d,\n number: (d) => d?.toFixed(2),\n boolean: (d) => (d ? \"T\" : \"F\"),\n object: (d) => JSON.stringify(d),\n integer: (d) => d?.toFixed(0),\n array: (d) => d?.join(\", \"),\n};\n\ninterface ColumnSpecGenerateOptions {\n calculateWidths?: boolean;\n defaultWidth?: number;\n getWidthForValue?: (value: any) => number;\n}\n\nconst defaultWidthForValue = (val) => String(val).length * 8;\n\n/** Inferred data type of a column, used to select appropriate\n * sort/filter operators. */\nexport type ColumnDataType =\n \"text\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\";\n\n/** Severity of a cell validation result. `warning` is soft (flagged, doesn't\n * block saving); `error` is hard (blocks saving). */\nexport type ValidationSeverity = \"warning\" | \"error\";\n\n/** The result of validating a cell. `null` means valid. */\nexport interface CellValidation {\n severity: ValidationSeverity;\n message?: string;\n}\n\n/**\n * Context handed to per-cell renderers (`valueRenderer`, and — as the\n * `cellContext` prop — a custom `cellComponent`). It lets a renderer draw\n * based on the row/column position and the cell's edit status, and, combined\n * with the editing API, write edits back for a specific cell.\n *\n * `rowIndex` is the underlying **data-row index** (the value edit methods\n * expect), so it stays stable when a sort or filter reorders the view.\n */\nexport interface CellRenderContext<T = any> {\n /** The cell's current value (the edited value if present, else the base). */\n value: any;\n /** Underlying data-row index — stable under sort/filter. */\n rowIndex: number;\n /** Column index within the active column spec. */\n colIndex: number;\n /** The full column spec for this cell's column. */\n column: ColumnSpec;\n /** The full row object backing this cell (may be undefined while loading). */\n row: T | null | undefined;\n /** Whether this cell has an uncommitted edit. */\n isEdited: boolean;\n /** Whether this cell's row is marked for deletion. */\n isDeleted: boolean;\n /** The row's status value (`RowStatusValue`) — `\"deleted\"` / `\"added\"` or a\n * consumer-defined status (e.g. `\"omitted\"`), or `undefined` for a normal\n * row. Lets a renderer style by arbitrary status, not just deletion. */\n status: string | undefined;\n /** Validation result for this cell, or `null` when valid. Orthogonal to the\n * edit status — a cell can be both edited and invalid. */\n validation: CellValidation | null;\n}\n\n/**\n * The editor configuration for a cell. Mirrors the static `dataEditor` /\n * `inlineEditor` column fields so a per-cell resolver (`editorForCell`) can\n * override either one for an individual cell.\n */\nexport interface CellEditors {\n dataEditor?: any;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n}\n\n/**\n * Context for a cell's detail surface (`cellDetail`). Extends the render\n * context with the edit affordances and controls a surface needs, so one\n * component can act as an editor (when `editable`) or a read-only viewer\n * (otherwise). This is the write side of the read/write contract, per-cell.\n */\nexport interface CellDetailContext<T = any> extends CellRenderContext<T> {\n /** Whether this cell is editable (column × table × not-deleted). */\n editable: boolean;\n /**\n * When the surface stands for several cells at once (the row editor over a\n * multi-row selection), the cells it stands for. `value` is then the value\n * they share, or `undefined` when they differ (`mixed`), and `onChange`\n * writes every one of them. Only offered to a column that declares\n * `multiCell`; absent for a single cell.\n */\n cells?: CellSelectionEntry<T>[];\n /** True when `cells` hold differing values. */\n mixed?: boolean;\n /** Where the surface is drawn: `\"cell\"`, the grid's own popover, modal or\n * in-cell surface; `\"row-editor\"`, a field of the sheet's row editor; or\n * `\"editor\"`, a field of a standalone `DataEditor` — so a surface can lay\n * itself out to suit (a picker nesting its own popovers only where it has\n * room). */\n surface?: \"cell\" | \"row-editor\" | \"editor\";\n /** Commit a new value for this cell — for every cell, when the surface\n * stands for several. */\n onChange: (value: any) => void;\n /** With `cells`, commit a value for each cell, aligned with them — for a\n * surface that changes each cell's own value (adding a tag to every row's\n * list) rather than setting them all to one. */\n onChangeCells?: (values: any[]) => void;\n /** Reset this cell (and selection) to its base value. */\n resetValue: () => void;\n /** Close the surface and return focus to the table. */\n close: () => void;\n}\n\n/** One of the cells a multi-cell surface stands for. */\nexport interface CellSelectionEntry<T = any> {\n rowIndex: number;\n row: T | null | undefined;\n value: any;\n}\n\n/** How a cell's detail surface is presented. Orthogonal to what it renders. */\nexport type DetailPresentation = \"popover\" | \"modal\" | \"inline\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n /** When true, an empty value is an error (sugar over `validate`). */\n required?: boolean;\n /** Validate a cell's value. Return a `{ severity, message }` for a\n * warning/error, or `null` when valid. Runs after the `required` check.\n * `warning` flags the cell but allows saving; `error` blocks saving. */\n validate?: (\n value: any,\n row: any,\n ctx: { rowIndex: number },\n ) => CellValidation | null;\n /** @deprecated Prefer `validate`, which carries severity + a message.\n * A falsy result maps to an `error`. */\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any, ctx?: CellRenderContext) => string | React.ReactNode;\n headerRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\n /**\n * Choose the editor for an individual cell from its render context,\n * overriding the static `dataEditor` / `inlineEditor` for that cell. Return\n * `undefined` (or omit a key) to fall back to the static configuration —\n * e.g. show a textarea only for cells whose value is long. A returned key is\n * respected even when its value is `false`/`null` (i.e. \"no editor here\").\n */\n editorForCell?: (ctx: CellRenderContext) => CellEditors | undefined;\n /**\n * Render a read-only detail panel for a cell. When set, selecting the cell\n * opens a popover with this content (following the table's `cellInteraction`\n * mode). The panel never takes keyboard focus, so arrow keys keep navigating\n * the table; Escape closes it. Mutually distinct from `dataEditor` — use this\n * for non-editable surfaces (previews, summaries, links).\n *\n * @deprecated Prefer `cellDetail`, which unifies editor and viewer.\n */\n detailRenderer?: (ctx: CellRenderContext) => React.ReactNode;\n /**\n * The unified cell surface (Workstream A): one renderer that acts as an\n * editor when `ctx.editable` and a read-only viewer otherwise, superseding\n * `dataEditor` / `detailRenderer` / `editorForCell`. Presentation is chosen\n * separately via `detailPresentation` (popover / modal / inline), so the\n * same component works in any container.\n */\n cellDetail?: (ctx: CellDetailContext) => React.ReactNode;\n /**\n * Whether this column's `cellDetail` can stand for several cells at once —\n * read the shared value (or `ctx.mixed`) and write every cell in\n * `ctx.cells` through one `onChange`. A surface that doesn't declare this\n * is shown read-only over a multi-row selection, with \"Multiple values\"\n * where they differ. The default editors (an input by `dataType`) always\n * can, since setting one value on every cell is what they do.\n */\n multiCell?: boolean;\n /** How `cellDetail` is presented. Defaults to `\"popover\"`. */\n detailPresentation?: DetailPresentation;\n /** What one cell of the column is called, for the selection indicator\n * (\"1 lithology\", \"3 lithologies\"). Defaults to the column's name. */\n cellLabel?: string;\n /** Where a popover `cellDetail` opens against its cell. Defaults to\n * `\"right-start\"`; a wide surface (a tag picker) reads better below, at\n * `\"bottom-start\"`. */\n detailPlacement?: Placement;\n cellComponent?: any;\n category?: string;\n editable?: boolean;\n /**\n * A **derived** column holds values computed from other data — a total, an\n * age that follows from an interval and a proportion — rather than values\n * anyone types. It is never writable, whatever `editable` or the table\n * says, and every write path (inline editing, fill, paste, the row editor)\n * leaves it alone; it is drawn dimmed so a reader can tell what is a record\n * and what is a restatement of one. Use it instead of `editable: false` when\n * the read-only-ness is a property of the *data* rather than of the view.\n */\n derived?: boolean;\n /**\n * A **hidden** column stays in the spec but is left out of the working\n * spec the table is built from: it isn't rendered, isn't part of a\n * selection, and isn't written by a fill or a paste. A consumer keeps one\n * spec and toggles this flag (\"show absolute ages\", \"show generated ids\")\n * rather than maintaining two arrays. Resolved by `postprocessColumnSpec`.\n */\n hidden?: boolean;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n style?: React.CSSProperties;\n width?: number;\n /** Column-specific table actions (TableAction[]). These appear in the\n * actions toolbar when this column is part of the current selection. */\n actions?: any[];\n /** Column-specific table filters (TableFilter[]). These appear in the\n * filter bar and apply to this column's values. */\n filters?: any[];\n /** Whether this column supports server-side sorting. */\n sortable?: boolean;\n /** Whether this column supports server-side filtering.\n * Set to `true` for default operators, or provide a config object\n * with a custom set of operators. */\n filterable?: boolean | { operators?: string[] };\n /** Inferred data type, used to select context-appropriate filter\n * operators when `filterable` is `true` without explicit operators. */\n dataType?: ColumnDataType;\n /** Whether this column may be drag-reordered. Defaults to `true`; set\n * `false` to pin a fixed/system column in place. Applied by the default\n * header renderer (requires table-level `enableColumnReordering`). */\n reorderable?: boolean;\n}\n\nexport interface ColumnSpecOptions<T> {\n overrides: Record<string, Partial<ColumnSpec> | string>;\n data?: T[]; // Data to use for type inference\n nRows?: number; // Number of rows to use for type inference\n omitColumns?: string[]; // Columns to omit. Takes precedence over includeColumns.\n includeColumns?: string[]; // Columns to include.\n}\n\nexport function generateDefaultColumnSpec<T>(\n data: Array<T>,\n options: ColumnSpecGenerateOptions = {},\n): ColumnSpec[] {\n /** Build a default column spec from a dataset based on the first n rows */\n if (data == null) return [];\n // Get the keys\n\n const {\n defaultWidth = 150,\n calculateWidths = true,\n getWidthForValue = defaultWidthForValue,\n } = options;\n\n const keys = new Set<string>();\n const types = new Map();\n\n const columnWidths = new Map<string, number>();\n\n for (const row of data) {\n if (row == null) continue;\n for (const key of Object.keys(row)) {\n const val = row[key];\n keys.add(key);\n\n if (val == null) continue;\n\n if (calculateWidths) {\n let width = getWidthForValue(val);\n if (width != null && width >= 0) {\n columnWidths.set(key, Math.max(width, columnWidths.get(key) ?? 0));\n }\n }\n\n let type: string = typeof val;\n // Special 'type' for integers\n if (Number.isInteger(val)) {\n type = \"integer\";\n }\n\n // Special 'type' for arrays of simple values\n if (\n Array.isArray(val) &&\n val.every((d) => typeof d === \"string\" || typeof d === \"number\")\n ) {\n type = \"array\";\n }\n\n // Check if it is strictly a string, if so, we can explicitly mark it as text\n if (type === \"string\") {\n type = \"text\";\n }\n\n if (types.has(key)) {\n if (types.get(key) !== type) {\n if (type === \"number\" && types.get(key) === \"integer\") {\n types.set(key, \"number\");\n }\n if (type === \"object\" && types.get(key) === \"array\") {\n types.set(key, \"object\");\n }\n\n types.set(key, \"string\");\n }\n } else {\n types.set(key, type);\n }\n }\n }\n\n // Build a column spec\n const spec: ColumnSpec[] = [];\n for (const key of keys) {\n let width: number | undefined = undefined;\n if (calculateWidths) {\n // If we are calculating widths, use the value lengths\n width = Math.min(\n Math.max(defaultWidth / 2, columnWidths.get(key) ?? defaultWidth),\n defaultWidth * 1.5,\n );\n }\n\n const dataType = (types.get(key) ?? \"string\") as ColumnDataType;\n\n // Auto-infer sortable/filterable based on data type.\n // Scalar types (string, number, integer, boolean) get sort/filter;\n // complex types (object, array) do not.\n const isScalar =\n dataType === \"text\" ||\n dataType === \"string\" ||\n dataType === \"number\" ||\n dataType === \"integer\" ||\n dataType === \"boolean\";\n\n spec.push({\n name: key,\n key,\n valueRenderer: defaultRenderers[types.get(key)],\n width,\n dataType,\n sortable: isScalar,\n filterable: isScalar,\n });\n }\n return spec;\n}\n\nexport function generateColumnSpec<T>(\n data: T[],\n options: Partial<ColumnSpecOptions<T>> = {},\n): ColumnSpec[] {\n /** Generate a column spec from a dataset */\n const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;\n\n if (data == null) return [];\n\n const _nRows = Math.min(nRows, data.length);\n\n let columnSpec = generateDefaultColumnSpec(data.slice(0, _nRows));\n let filteredSpec = columnSpec.filter((col) => {\n if (omitColumns != null && omitColumns.includes(col.key)) {\n return false;\n }\n if (includeColumns != null && !includeColumns.includes(col.key)) {\n return false;\n }\n return true;\n });\n\n // Apply overrides\n const improvedSpec = filteredSpec.map((col) => {\n let ovr = overrides[col.key];\n if (ovr == null) return col;\n if (typeof ovr === \"string\") {\n return { ...col, name: ovr };\n }\n return { ...col, ...ovr };\n });\n return postprocessColumnSpec(improvedSpec);\n}\n\nexport function postprocessColumnSpec(columnSpec: ColumnSpec[]) {\n /** Postprocess column spec to make sure that, e.g., column filters are\n * properly established, etc. Hidden columns are dropped here, so everything\n * downstream — the renderer, the selection, the edit paths — works with the\n * visible columns only and indexes into one array.\n */\n return columnSpec\n .filter((col) => !col.hidden)\n .map((col) => {\n return {\n ...col,\n filters: postprocessColumnFilters(col),\n actions: col.actions ?? [],\n };\n });\n}\n\n/**\n * Whether a column takes writes at all: the table is editable, the column\n * isn't locked (`editable: false`) and it isn't `derived`. This is the one\n * rule every write path consults — the inline editor, `onSelectionEdited`,\n * fill, clear, clipboard paste and the row editor — so a locked column is\n * locked however the edit arrives, not only when it is typed into.\n */\nexport function isColumnWritable(\n col: ColumnSpec | null | undefined,\n tableEditable: boolean = true,\n): boolean {\n if (col == null) return false;\n if (!tableEditable) return false;\n if (col.derived) return false;\n return col.editable !== false;\n}\n\nfunction postprocessColumnFilters(col: ColumnSpec): TableFilter[] | undefined {\n const { filterable = true, filters = [] } = col;\n if (!filterable) {\n return undefined;\n }\n return filters.map((f) => enhanceColumnFilter(col, f));\n}\n"],"names":[],"mappings":";AAIA,MAAM,mBAAmB;AAAA,EACvB,QAAQ,CAAC,MAAM;AAAA,EACf,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC3B,SAAS,CAAC,MAAO,IAAI,MAAM;AAAA,EAC3B,QAAQ,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/B,SAAS,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC5B,OAAO,CAAC,MAAM,GAAG,KAAK,IAAI;AAC5B;AAQA,MAAM,uBAAuB,CAAC,QAAQ,OAAO,GAAG,EAAE,SAAS;AAiOpD,SAAS,0BACd,MACA,UAAqC,IACvB;AAEd,MAAI,QAAQ,KAAM,QAAO,CAAA;AAGzB,QAAM;AAAA,IACJ,eAAe;AAAA,IACf,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,EAAA,IACjB;AAEJ,QAAM,2BAAW,IAAA;AACjB,QAAM,4BAAY,IAAA;AAElB,QAAM,mCAAmB,IAAA;AAEzB,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,KAAM;AACjB,eAAW,OAAO,OAAO,KAAK,GAAG,GAAG;AAClC,YAAM,MAAM,IAAI,GAAG;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AyB,MAChB;AACT,MAAI,OAAO,KAAM,QAAO;AACxB,MAAI,CAAC,cAAe,QAAO;AAC3B,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,IAAI,aAAa;AAC1B;AAEA,SAAS,yBAAyB,KAA4C;AAC5E,QAAM,EAAE,aAAa,MAAM,UAAU,CAAA,MAAO;AAC5C,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,IAAI,CAAC,MAAM,oBAAoB,KAAK,CAAC,CAAC;AACvD;"}
|
|
1
|
+
{"version":3,"file":"column-spec.js","sources":["../../src/provider/column-spec.ts"],"sourcesContent":["import React from \"react\";\nimport type { Placement } from \"@blueprintjs/core\";\nimport { enhanceColumnFilter, TableFilter } from \"../actions\";\n\nconst defaultRenderers = {\n string: (d) => d,\n number: (d) => d?.toFixed(2),\n boolean: (d) => (d ? \"T\" : \"F\"),\n object: (d) => JSON.stringify(d),\n integer: (d) => d?.toFixed(0),\n array: (d) => d?.join(\", \"),\n};\n\ninterface ColumnSpecGenerateOptions {\n calculateWidths?: boolean;\n defaultWidth?: number;\n getWidthForValue?: (value: any) => number;\n}\n\nconst defaultWidthForValue = (val) => String(val).length * 8;\n\n/** Inferred data type of a column, used to select appropriate\n * sort/filter operators. */\nexport type ColumnDataType =\n \"text\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\";\n\n/** Severity of a cell validation result. `warning` is soft (flagged, doesn't\n * block saving); `error` is hard (blocks saving). */\nexport type ValidationSeverity = \"warning\" | \"error\";\n\n/** The result of validating a cell. `null` means valid. */\nexport interface CellValidation {\n severity: ValidationSeverity;\n message?: string;\n}\n\n/**\n * Context handed to per-cell renderers (`valueRenderer`, and — as the\n * `cellContext` prop — a custom `cellComponent`). It lets a renderer draw\n * based on the row/column position and the cell's edit status, and, combined\n * with the editing API, write edits back for a specific cell.\n *\n * `rowIndex` is the underlying **data-row index** (the value edit methods\n * expect), so it stays stable when a sort or filter reorders the view.\n */\nexport interface CellRenderContext<T = any> {\n /** The cell's current value (the edited value if present, else the base). */\n value: any;\n /** Underlying data-row index — stable under sort/filter. */\n rowIndex: number;\n /** Column index within the active column spec. */\n colIndex: number;\n /** The full column spec for this cell's column. */\n column: ColumnSpec;\n /** The full row object backing this cell (may be undefined while loading). */\n row: T | null | undefined;\n /** Whether this cell has an uncommitted edit. */\n isEdited: boolean;\n /** Whether this cell's row is marked for deletion. */\n isDeleted: boolean;\n /** The row's status value (`RowStatusValue`) — `\"deleted\"` / `\"added\"` or a\n * consumer-defined status (e.g. `\"omitted\"`), or `undefined` for a normal\n * row. Lets a renderer style by arbitrary status, not just deletion. */\n status: string | undefined;\n /** Validation result for this cell, or `null` when valid. Orthogonal to the\n * edit status — a cell can be both edited and invalid. */\n validation: CellValidation | null;\n /** The cell's size in pixels, border and padding included, when it is a\n * grid cell — the column's width and the row's height, which the table\n * knows and a renderer would otherwise have to measure. Absent on surfaces\n * that aren't laid out in the cell (a popover, the row editor). A value\n * renderer that lays itself out to fit — a row of tags — can re-fit when\n * these change instead of observing its own size. */\n width?: number;\n height?: number;\n}\n\n/**\n * The editor configuration for a cell. Mirrors the static `dataEditor` /\n * `inlineEditor` column fields so a per-cell resolver (`editorForCell`) can\n * override either one for an individual cell.\n */\nexport interface CellEditors {\n dataEditor?: any;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n}\n\n/**\n * Context for a cell's detail surface (`cellDetail`). Extends the render\n * context with the edit affordances and controls a surface needs, so one\n * component can act as an editor (when `editable`) or a read-only viewer\n * (otherwise). This is the write side of the read/write contract, per-cell.\n */\nexport interface CellDetailContext<T = any> extends CellRenderContext<T> {\n /** Whether this cell is editable (column × table × not-deleted). */\n editable: boolean;\n /**\n * When the surface stands for several cells at once (the row editor over a\n * multi-row selection), the cells it stands for. `value` is then the value\n * they share, or `undefined` when they differ (`mixed`), and `onChange`\n * writes every one of them. Only offered to a column that declares\n * `multiCell`; absent for a single cell.\n */\n cells?: CellSelectionEntry<T>[];\n /** True when `cells` hold differing values. */\n mixed?: boolean;\n /** Where the surface is drawn: `\"cell\"`, the grid's own popover, modal or\n * in-cell surface; `\"row-editor\"`, a field of the sheet's row editor; or\n * `\"editor\"`, a field of a standalone `DataEditor` — so a surface can lay\n * itself out to suit (a picker nesting its own popovers only where it has\n * room). */\n surface?: \"cell\" | \"row-editor\" | \"editor\";\n /** Commit a new value for this cell — for every cell, when the surface\n * stands for several. */\n onChange: (value: any) => void;\n /** With `cells`, commit a value for each cell, aligned with them — for a\n * surface that changes each cell's own value (adding a tag to every row's\n * list) rather than setting them all to one. */\n onChangeCells?: (values: any[]) => void;\n /** Reset this cell (and selection) to its base value. */\n resetValue: () => void;\n /** Close the surface and return focus to the table. */\n close: () => void;\n}\n\n/** One of the cells a multi-cell surface stands for. */\nexport interface CellSelectionEntry<T = any> {\n rowIndex: number;\n row: T | null | undefined;\n value: any;\n}\n\n/** How a cell's detail surface is presented. Orthogonal to what it renders. */\nexport type DetailPresentation = \"popover\" | \"modal\" | \"inline\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n /** When true, an empty value is an error (sugar over `validate`). */\n required?: boolean;\n /** Validate a cell's value. Return a `{ severity, message }` for a\n * warning/error, or `null` when valid. Runs after the `required` check.\n * `warning` flags the cell but allows saving; `error` blocks saving. */\n validate?: (\n value: any,\n row: any,\n ctx: { rowIndex: number },\n ) => CellValidation | null;\n /** @deprecated Prefer `validate`, which carries severity + a message.\n * A falsy result maps to an `error`. */\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any, ctx?: CellRenderContext) => string | React.ReactNode;\n headerRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\n /**\n * Choose the editor for an individual cell from its render context,\n * overriding the static `dataEditor` / `inlineEditor` for that cell. Return\n * `undefined` (or omit a key) to fall back to the static configuration —\n * e.g. show a textarea only for cells whose value is long. A returned key is\n * respected even when its value is `false`/`null` (i.e. \"no editor here\").\n */\n editorForCell?: (ctx: CellRenderContext) => CellEditors | undefined;\n /**\n * Render a read-only detail panel for a cell. When set, selecting the cell\n * opens a popover with this content (following the table's `cellInteraction`\n * mode). The panel never takes keyboard focus, so arrow keys keep navigating\n * the table; Escape closes it. Mutually distinct from `dataEditor` — use this\n * for non-editable surfaces (previews, summaries, links).\n *\n * @deprecated Prefer `cellDetail`, which unifies editor and viewer.\n */\n detailRenderer?: (ctx: CellRenderContext) => React.ReactNode;\n /**\n * The unified cell surface (Workstream A): one renderer that acts as an\n * editor when `ctx.editable` and a read-only viewer otherwise, superseding\n * `dataEditor` / `detailRenderer` / `editorForCell`. Presentation is chosen\n * separately via `detailPresentation` (popover / modal / inline), so the\n * same component works in any container.\n */\n cellDetail?: (ctx: CellDetailContext) => React.ReactNode;\n /**\n * Whether this column's `cellDetail` can stand for several cells at once —\n * read the shared value (or `ctx.mixed`) and write every cell in\n * `ctx.cells` through one `onChange`. A surface that doesn't declare this\n * is shown read-only over a multi-row selection, with \"Multiple values\"\n * where they differ. The default editors (an input by `dataType`) always\n * can, since setting one value on every cell is what they do.\n */\n multiCell?: boolean;\n /** How `cellDetail` is presented. Defaults to `\"popover\"`. */\n detailPresentation?: DetailPresentation;\n /** What one cell of the column is called, for the selection indicator\n * (\"1 lithology\", \"3 lithologies\"). Defaults to the column's name. */\n cellLabel?: string;\n /** Where a popover `cellDetail` opens against its cell. Defaults to\n * `\"right-start\"`; a wide surface (a tag picker) reads better below, at\n * `\"bottom-start\"`. */\n detailPlacement?: Placement;\n cellComponent?: any;\n category?: string;\n editable?: boolean;\n /**\n * A **derived** column holds values computed from other data — a total, an\n * age that follows from an interval and a proportion — rather than values\n * anyone types. It is never writable, whatever `editable` or the table\n * says, and every write path (inline editing, fill, paste, the row editor)\n * leaves it alone; it is drawn dimmed so a reader can tell what is a record\n * and what is a restatement of one. Use it instead of `editable: false` when\n * the read-only-ness is a property of the *data* rather than of the view.\n */\n derived?: boolean;\n /**\n * A **hidden** column stays in the spec but is left out of the working\n * spec the table is built from: it isn't rendered, isn't part of a\n * selection, and isn't written by a fill or a paste. A consumer keeps one\n * spec and toggles this flag (\"show absolute ages\", \"show generated ids\")\n * rather than maintaining two arrays. Resolved by `postprocessColumnSpec`.\n */\n hidden?: boolean;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n style?: React.CSSProperties;\n width?: number;\n /** Column-specific table actions (TableAction[]). These appear in the\n * actions toolbar when this column is part of the current selection. */\n actions?: any[];\n /** Column-specific table filters (TableFilter[]). These appear in the\n * filter bar and apply to this column's values. */\n filters?: any[];\n /** Whether this column supports server-side sorting. */\n sortable?: boolean;\n /** Whether this column supports server-side filtering.\n * Set to `true` for default operators, or provide a config object\n * with a custom set of operators. */\n filterable?: boolean | { operators?: string[] };\n /** Inferred data type, used to select context-appropriate filter\n * operators when `filterable` is `true` without explicit operators. */\n dataType?: ColumnDataType;\n /** Whether this column may be drag-reordered. Defaults to `true`; set\n * `false` to pin a fixed/system column in place. Applied by the default\n * header renderer (requires table-level `enableColumnReordering`). */\n reorderable?: boolean;\n}\n\nexport interface ColumnSpecOptions<T> {\n overrides: Record<string, Partial<ColumnSpec> | string>;\n data?: T[]; // Data to use for type inference\n nRows?: number; // Number of rows to use for type inference\n omitColumns?: string[]; // Columns to omit. Takes precedence over includeColumns.\n includeColumns?: string[]; // Columns to include.\n}\n\nexport function generateDefaultColumnSpec<T>(\n data: Array<T>,\n options: ColumnSpecGenerateOptions = {},\n): ColumnSpec[] {\n /** Build a default column spec from a dataset based on the first n rows */\n if (data == null) return [];\n // Get the keys\n\n const {\n defaultWidth = 150,\n calculateWidths = true,\n getWidthForValue = defaultWidthForValue,\n } = options;\n\n const keys = new Set<string>();\n const types = new Map();\n\n const columnWidths = new Map<string, number>();\n\n for (const row of data) {\n if (row == null) continue;\n for (const key of Object.keys(row)) {\n const val = row[key];\n keys.add(key);\n\n if (val == null) continue;\n\n if (calculateWidths) {\n let width = getWidthForValue(val);\n if (width != null && width >= 0) {\n columnWidths.set(key, Math.max(width, columnWidths.get(key) ?? 0));\n }\n }\n\n let type: string = typeof val;\n // Special 'type' for integers\n if (Number.isInteger(val)) {\n type = \"integer\";\n }\n\n // Special 'type' for arrays of simple values\n if (\n Array.isArray(val) &&\n val.every((d) => typeof d === \"string\" || typeof d === \"number\")\n ) {\n type = \"array\";\n }\n\n // Check if it is strictly a string, if so, we can explicitly mark it as text\n if (type === \"string\") {\n type = \"text\";\n }\n\n if (types.has(key)) {\n if (types.get(key) !== type) {\n if (type === \"number\" && types.get(key) === \"integer\") {\n types.set(key, \"number\");\n }\n if (type === \"object\" && types.get(key) === \"array\") {\n types.set(key, \"object\");\n }\n\n types.set(key, \"string\");\n }\n } else {\n types.set(key, type);\n }\n }\n }\n\n // Build a column spec\n const spec: ColumnSpec[] = [];\n for (const key of keys) {\n let width: number | undefined = undefined;\n if (calculateWidths) {\n // If we are calculating widths, use the value lengths\n width = Math.min(\n Math.max(defaultWidth / 2, columnWidths.get(key) ?? defaultWidth),\n defaultWidth * 1.5,\n );\n }\n\n const dataType = (types.get(key) ?? \"string\") as ColumnDataType;\n\n // Auto-infer sortable/filterable based on data type.\n // Scalar types (string, number, integer, boolean) get sort/filter;\n // complex types (object, array) do not.\n const isScalar =\n dataType === \"text\" ||\n dataType === \"string\" ||\n dataType === \"number\" ||\n dataType === \"integer\" ||\n dataType === \"boolean\";\n\n spec.push({\n name: key,\n key,\n valueRenderer: defaultRenderers[types.get(key)],\n width,\n dataType,\n sortable: isScalar,\n filterable: isScalar,\n });\n }\n return spec;\n}\n\nexport function generateColumnSpec<T>(\n data: T[],\n options: Partial<ColumnSpecOptions<T>> = {},\n): ColumnSpec[] {\n /** Generate a column spec from a dataset */\n const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;\n\n if (data == null) return [];\n\n const _nRows = Math.min(nRows, data.length);\n\n let columnSpec = generateDefaultColumnSpec(data.slice(0, _nRows));\n let filteredSpec = columnSpec.filter((col) => {\n if (omitColumns != null && omitColumns.includes(col.key)) {\n return false;\n }\n if (includeColumns != null && !includeColumns.includes(col.key)) {\n return false;\n }\n return true;\n });\n\n // Apply overrides\n const improvedSpec = filteredSpec.map((col) => {\n let ovr = overrides[col.key];\n if (ovr == null) return col;\n if (typeof ovr === \"string\") {\n return { ...col, name: ovr };\n }\n return { ...col, ...ovr };\n });\n return postprocessColumnSpec(improvedSpec);\n}\n\nexport function postprocessColumnSpec(columnSpec: ColumnSpec[]) {\n /** Postprocess column spec to make sure that, e.g., column filters are\n * properly established, etc. Hidden columns are dropped here, so everything\n * downstream — the renderer, the selection, the edit paths — works with the\n * visible columns only and indexes into one array.\n */\n return columnSpec\n .filter((col) => !col.hidden)\n .map((col) => {\n return {\n ...col,\n filters: postprocessColumnFilters(col),\n actions: col.actions ?? [],\n };\n });\n}\n\n/**\n * Whether a column takes writes at all: the table is editable, the column\n * isn't locked (`editable: false`) and it isn't `derived`. This is the one\n * rule every write path consults — the inline editor, `onSelectionEdited`,\n * fill, clear, clipboard paste and the row editor — so a locked column is\n * locked however the edit arrives, not only when it is typed into.\n */\nexport function isColumnWritable(\n col: ColumnSpec | null | undefined,\n tableEditable: boolean = true,\n): boolean {\n if (col == null) return false;\n if (!tableEditable) return false;\n if (col.derived) return false;\n return col.editable !== false;\n}\n\nfunction postprocessColumnFilters(col: ColumnSpec): TableFilter[] | undefined {\n const { filterable = true, filters = [] } = col;\n if (!filterable) {\n return undefined;\n }\n return filters.map((f) => enhanceColumnFilter(col, f));\n}\n"],"names":[],"mappings":";AAIA,MAAM,mBAAmB;AAAA,EACvB,QAAQ,CAAC,MAAM;AAAA,EACf,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC3B,SAAS,CAAC,MAAO,IAAI,MAAM;AAAA,EAC3B,QAAQ,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/B,SAAS,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC5B,OAAO,CAAC,MAAM,GAAG,KAAK,IAAI;AAC5B;AAQA,MAAM,uBAAuB,CAA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