@macrostrat/data-sheet 4.0.1 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +11 -1
- package/dist/actions/column-controls.cjs +89 -0
- package/dist/actions/column-controls.cjs.map +1 -1
- package/dist/actions/column-controls.js +90 -1
- package/dist/actions/column-controls.js.map +1 -1
- package/dist/actions/selection.cjs +2 -1
- package/dist/actions/selection.cjs.map +1 -1
- package/dist/actions/selection.js +2 -1
- package/dist/actions/selection.js.map +1 -1
- package/dist/actions/table-controls.cjs +17 -0
- package/dist/actions/table-controls.cjs.map +1 -1
- package/dist/actions/table-controls.d.ts +4 -0
- package/dist/actions/table-controls.js +17 -0
- package/dist/actions/table-controls.js.map +1 -1
- package/dist/actions/toolbar.cjs +18 -2
- package/dist/actions/toolbar.cjs.map +1 -1
- package/dist/actions/toolbar.js +18 -2
- package/dist/actions/toolbar.js.map +1 -1
- package/dist/actions/types.d.ts +9 -0
- package/dist/cell-renderer.cjs +8 -6
- package/dist/cell-renderer.cjs.map +1 -1
- package/dist/cell-renderer.js +8 -6
- package/dist/cell-renderer.js.map +1 -1
- package/dist/core.cjs +59 -9
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.ts +28 -1
- package/dist/core.js +60 -10
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +4 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -2
- package/dist/renderers/column-header-cell.cjs +14 -28
- package/dist/renderers/column-header-cell.cjs.map +1 -1
- package/dist/renderers/column-header-cell.js +15 -29
- package/dist/renderers/column-header-cell.js.map +1 -1
- package/dist/types.cjs +11 -0
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +45 -1
- package/dist/types.js +11 -0
- package/dist/types.js.map +1 -1
- package/dist/utils/column-spec.cjs.map +1 -1
- package/dist/utils/column-spec.d.ts +4 -0
- package/dist/utils/column-spec.js.map +1 -1
- package/dist/zustand-store.cjs +6 -3
- package/dist/zustand-store.cjs.map +1 -1
- package/dist/zustand-store.js +7 -4
- package/dist/zustand-store.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/column-controls.ts +114 -0
- package/src/actions/selection.ts +1 -0
- package/src/actions/table-controls.ts +20 -0
- package/src/actions/toolbar.ts +30 -2
- package/src/actions/types.ts +10 -0
- package/src/cell-renderer.ts +17 -9
- package/src/core.ts +107 -12
- package/src/renderers/column-header-cell.ts +20 -32
- package/src/types.ts +56 -1
- package/src/utils/column-spec.ts +4 -0
- package/src/zustand-store.ts +11 -5
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","sources":["../src/core.ts"],"sourcesContent":["import { useHotkeys } from \"@blueprintjs/core\";\nimport {\n Column,\n Region,\n RegionCardinality,\n RowHeaderCell,\n Table,\n TableProps,\n} from \"@blueprintjs/table\";\nimport \"@blueprintjs/table/lib/css/table.css\";\nimport { ReactNode, useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { LoadProgressIndicator } from \"./components\";\nimport { renderColumnHeaderCell } from \"./renderers\";\nimport h from \"./main.module.sass\";\nimport {\n columnSpecAtom,\n ctx,\n DataSheetProvider,\n storeAtom,\n tableActionsAtom,\n useSelector,\n useStoreAPI,\n} from \"./provider\";\nimport { atom } from \"jotai\";\nimport {\n DataSheetProviderProps,\n EditEvent,\n TableElementStatus,\n VisibleCells,\n} from \"./types.ts\";\nimport { basicCellRenderer } from \"./cell-renderer.ts\";\nimport { CellRendererDebugOverlay, tableHotkeysAtom } from \"./utils\";\nimport {\n ActionsToolbar,\n clipboardActions,\n columnControlActions,\n createSaveAction,\n FilterBar,\n resetChangesAction,\n TableAction,\n TableActionContext,\n TableFilter,\n} from \"./actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataOptions,\n tableFooterAtom,\n TableDataProvider,\n useScrollHandler,\n useDataLoader,\n} from \"./postgrest-table\";\n\n// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args\n\n// TODO: add a \"copy to selection\" tool (the little square in the bottom right corner of a cell)\n// This should copy the value of a cell (or a set of cells in the same row) downwards.\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/** Approximate column-header + scrollbar allowance, used to size the table to\n * its content in paged mode. */\nconst COLUMN_HEADER_HEIGHT = 34;\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\ninterface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n // An optional table name that will be used in toolbars if given\n name?: string;\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n editable?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n}\n\ntype DataSheetProps<T> = DataSheetProviderProps<T> & DataSheetInternalProps<T>;\n\nconst emptyData: any[] = [];\n\nexport function DataSheet<T>(props: DataSheetProps<T>) {\n const {\n data,\n columnSpec,\n columnSpecOptions,\n editable = true,\n enableColumnReordering = false,\n enableFocusedCell = false,\n defaultColumnWidth = 150,\n children,\n ...rest\n } = props;\n\n return h(\n DataSheetProvider<T>,\n {\n data: data ?? emptyData,\n columnSpec,\n columnSpecOptions,\n enableColumnReordering,\n defaultColumnWidth,\n editable,\n ...rest,\n },\n h(_DataSheet<any>, {\n ...rest,\n data: data ?? emptyData,\n children,\n editable,\n enableColumnReordering,\n enableFocusedCell,\n }),\n );\n}\n\nconst deletedRowHeaderStyle = {\n opacity: 0.5,\n textDecoration: \"line-through\",\n};\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nasync function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n\nfunction _DataSheet<T>({\n data: sourceData,\n fetchData,\n provider,\n pageSize,\n fetchMode,\n onVisibleCellsChange,\n onUpdateData,\n onEdit,\n onSave,\n updatedData: updatedDataProp,\n rowStatus: rowStatusProp,\n identity,\n onDeleteRows,\n name,\n verbose = false,\n enableFocusedCell,\n autoFocusEditor = true,\n cellInteraction,\n enableClipboard = true,\n density = DataSheetDensity.HIGH,\n selectionModes,\n actions,\n filters,\n columnHeaderCellRenderer,\n children,\n ...rest\n}: DataSheetInternalProps<T>) {\n /**\n * @param data: The data to be displayed in the table\n * @param columnSpec: The specification for all columns in the table. If not provided, the column spec will be generated from the data.\n * @param columnSpecOptions: Options for generating a column spec from data\n */\n\n // Turn on debug features\n const debugMode = false;\n\n const editable = useSelector((state) => state.editable);\n\n // Resolve the active data provider: an explicit `provider` prop wins; else a\n // loose `fetchData` (+ identity) is wrapped as one; else in-memory `data`\n // becomes a local provider. Local and remote thus share one path, and the\n // provider is an explicit contract rather than a set of scattered props.\n const isLocalProvider = provider == null && fetchData == null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (provider != null) return provider;\n if (fetchData != null) {\n return { fetchData, identity: identity ?? ((r: any) => r?.id) };\n }\n if (sourceData != null && sourceData.length > 0) {\n return createLocalProvider(\n sourceData,\n identity != null ? { identity } : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [provider, fetchData, sourceData, identity]);\n\n // When an explicit provider owns persistence, its methods drive the built-in\n // Save (batch: edits→saveRows, added→insertRow, deleted→deleteRows), then a\n // refresh. Otherwise the loose `onSave` handler is used.\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n const providerSave = useMemo(() => {\n const p = provider;\n if (\n p == null ||\n (p.saveRows == null && p.deleteRows == null && p.insertRow == null)\n ) {\n return null;\n }\n return async (actionCtx: TableActionContext<T>) => {\n await persistViaProvider(p, actionCtx);\n bumpRefresh((v) => v + 1);\n };\n }, [provider, bumpRefresh]);\n const saveHandler = onSave ?? providerSave;\n\n // Sync table actions to atom. Consumer actions come first (they override a\n // built-in by reusing its id); the built-in column controls (sort/filter)\n // fill in the rest — so both the toolbar and the header dropdown source from\n // one registry. Built-ins self-gate (single sortable/filterable column).\n const _actions: TableAction[] = useMemo(() => {\n const _actions: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!_actions.some((x) => x.id === a.id)) _actions.push(a);\n }\n };\n if (actions != null) add(actions);\n add(columnControlActions);\n if (enableClipboard) add(clipboardActions);\n // Save/reset last — they're the most significant actions — and present for\n // every cardinality (editable), so the toolbar stays mounted regardless of\n // selection.\n if (editable) {\n if (saveHandler != null) add([createSaveAction(saveHandler)]);\n add([resetChangesAction]);\n }\n return _actions;\n }, [actions, enableClipboard, editable, saveHandler]);\n\n ctx.useSync(tableActionsAtom, _actions);\n\n const hotkeysConfig = ctx.useValue(tableHotkeysAtom);\n const { handleKeyDown, handleKeyUp } = useHotkeys(hotkeysConfig);\n\n // For now, we only consider a single cell \"focused\" when we have one cell selected.\n // Multi-cell selections have a different set of \"bulk\" actions.\n const selectedRegions = useSelector<T>((state) => state.selection ?? []);\n\n const data = useSelector((state) => state.data);\n\n const rowStatus = useSelector((state) => state.rowStatus);\n\n const focusedCell = useSelector((state) => state.focusedCell);\n\n const ref = useSelector((state) => state.tableRef);\n\n const columnSpec = useSelector((state) => state.columnSpec);\n\n // A sparse array to hold updates\n // TODO: create a \"changeset\" concept to facilitate undo/redo\n const updatedData = useSelector((state) => state.updatedData);\n\n const onSelection = useSelector((state) => state.onSelection);\n\n const storeAPI = useStoreAPI<T>();\n\n const onScroll = useScrollHandler();\n const _onVisibleCellsChange = useCallback(\n (visibleCells: VisibleCells) => {\n onScroll(visibleCells);\n onVisibleCellsChange?.(visibleCells);\n },\n [onVisibleCellsChange, onScroll],\n );\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Updated data\", updatedData);\n }, [updatedData]);\n\n useEffect(() => {\n onUpdateData?.(updatedData, data);\n }, [onUpdateData, data, updatedData]);\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Selected regions\", selectedRegions);\n }, [selectedRegions]);\n\n const tableElementRef = useRef<HTMLElement>(null);\n useEffect(() => {\n // Return the focus to the table\n tableElementRef.current?.focus();\n }, [focusedCell]);\n\n const columnWidths = ctx.useValue(columnWidthsAtom);\n\n // When filters are active, only show matching rows\n const filteredRowIndices = useSelector((state) => state.filteredRowIndices);\n const totalRows = Math.max(updatedData.length, data.length);\n const numRows =\n filteredRowIndices != null ? filteredRowIndices.length : totalRows;\n\n let className = `${density}-density`;\n\n const { rowHeight, style } = styleParamsForDensity(density);\n\n // In paged mode the row count is small and fixed, so let the table size to\n // its content (header + rows) instead of filling the viewport.\n const footerInfo = ctx.useValue(tableFooterAtom);\n const holderStyle =\n footerInfo.mode === \"paged\"\n ? {\n flex: \"0 0 auto\" as const,\n height: numRows * rowHeight + COLUMN_HEADER_HEIGHT,\n }\n : undefined;\n\n const onColumnsReordered = useSelector((state) => state.onColumnsReordered);\n\n // Auto-detect if any columns have sortable/filterable set.\n // If so and no explicit columnHeaderCellRenderer was provided,\n // use the built-in client-side sort/filter header.\n const hasSortableOrFilterable = useMemo(\n () =>\n columnSpec.some(\n (col) =>\n col.sortable ||\n col.filterable ||\n (Array.isArray(col.filters) && col.filters.length > 0),\n ),\n [columnSpec],\n );\n\n const columnSorts = useSelector((state) => state.columnSorts);\n const activeFilters = useSelector((state) => state.activeFilters);\n\n // Cell activation mode, defaulting from the legacy `autoFocusEditor` boolean\n // so existing consumers are unaffected. Synced into the store so the cell\n // renderer, editors, and key handlers all read it consistently.\n const cellInteractionMode: CellInteraction =\n cellInteraction ?? (autoFocusEditor ? \"auto\" : \"manual\");\n\n const storeState = storeAPI;\n useEffect(() => {\n storeState.setState({ cellInteraction: cellInteractionMode });\n }, [storeState, cellInteractionMode]);\n\n useEffect(() => {\n // Give the store a handle to the focusable holder so editors can return\n // keyboard focus to the table when the cursor leaves them.\n storeState.setState({ tableElement: tableElementRef.current });\n }, [storeState]);\n\n useEffect(() => {\n storeState.setState({ onEdit });\n }, [storeState, onEdit]);\n\n useEffect(() => {\n // Controlled overlay: mirror the caller's edited state into the store as\n // the source of truth. Optimistic in-table edits are superseded on the\n // next render when the caller passes an updated value back. When the caller\n // controls it, the loader-boundary identity remap steps aside.\n const controlled =\n updatedDataProp !== undefined || rowStatusProp !== undefined;\n const patch: Record<string, unknown> = { controlledOverlay: controlled };\n if (updatedDataProp !== undefined) patch.updatedData = updatedDataProp;\n if (rowStatusProp !== undefined) patch.rowStatus = rowStatusProp;\n storeState.setState(patch);\n }, [storeState, updatedDataProp, rowStatusProp]);\n\n // The active provider supplies the row identity for the edit overlay.\n useEffect(() => {\n const id = activeProvider?.identity ?? identity;\n if (id != null) storeState.setState({ identity: id });\n }, [storeState, activeProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` without\n // `deleteRows` disables deletion entirely. (Local / loose sources keep the\n // local delete overlay.)\n useEffect(() => {\n const canDeleteRows = provider == null || provider.deleteRows != null;\n storeState.setState({ canDeleteRows });\n }, [storeState, provider]);\n\n const realizedColumns = useMemo(() => {\n return columnSpec.map((col, colIndex) => {\n let fn =\n col.headerCellRenderer ??\n columnHeaderCellRenderer ??\n renderColumnHeaderCell;\n let activeSort = null;\n let activeFilter = null;\n if (col.sortable) {\n activeSort = columnSorts?.find((s) => s.key === col.key);\n }\n // The active filter for this column is whichever active filter targets\n // it (a rich `col.filters` filter or the generic operator filter) — match\n // by columnKey rather than a fixed id.\n for (const entry of activeFilters?.values() ?? []) {\n if ((entry as any)?.filter?.columnKey === col.key) {\n activeFilter = entry;\n break;\n }\n }\n\n const _columnHeaderCellRenderer = (colIndex) => {\n return fn({\n col,\n colIndex,\n activeSort,\n activeFilter,\n });\n };\n\n return h(Column, {\n id: col.key,\n name: col.name,\n columnHeaderCellRenderer: _columnHeaderCellRenderer,\n cellRenderer: (rowIndex) => {\n const state = storeAPI.getState();\n return basicCellRenderer<T>(\n rowIndex,\n colIndex,\n col,\n state,\n filteredRowIndices,\n );\n },\n });\n });\n }, [\n columnSpec,\n columnSorts,\n activeFilters,\n storeAPI,\n filteredRowIndices,\n columnHeaderCellRenderer,\n ]);\n\n const onColumnWidthChanged = useSelector(\n (state) => state.onColumnWidthChanged,\n );\n\n const rowHeaderCellRenderer = useCallback(\n (rowIndex: number) => {\n const dataRowIndex =\n filteredRowIndices != null\n ? (filteredRowIndices[rowIndex] ?? rowIndex)\n : rowIndex;\n const style =\n rowStatus[dataRowIndex] == TableElementStatus.DELETED\n ? deletedRowHeaderStyle\n : null;\n\n return h(RowHeaderCell, {\n enableRowReordering: false,\n index: rowIndex,\n name: `${dataRowIndex + 1}`,\n style,\n });\n },\n [rowStatus, filteredRowIndices],\n );\n\n let _selectionModes = selectionModes;\n if (\n editable &&\n _selectionModes != null &&\n !_selectionModes.includes(RegionCardinality.CELLS)\n ) {\n _selectionModes = [..._selectionModes, RegionCardinality.CELLS];\n // Ensure selection mode includes \"cells\"\n }\n\n const cellRendererDependencies = [\n data,\n updatedData,\n focusedCell,\n rowStatus,\n filteredRowIndices,\n ];\n\n // Drive the table from the active provider's `fetchData`. A local (in-memory)\n // provider loads the whole array at once; a remote one uses the `pageSize` /\n // `fetchMode` props and shows load progress.\n let _showLoadProgress: boolean = false;\n let dataLoader: ReactNode = null;\n if (activeProvider != null) {\n _showLoadProgress = !isLocalProvider;\n dataLoader = h(_DataLoaderManager, {\n key: \"__data_loader\",\n fetchData: activeProvider.fetchData,\n pageSize: isLocalProvider\n ? Math.max(sourceData?.length ?? 1, 1)\n : pageSize,\n fetchMode: isLocalProvider ? undefined : fetchMode,\n });\n }\n const showFilterBar =\n (filters != null && filters.length > 0) || hasSortableOrFilterable;\n\n let filterStatus: ReactNode = null;\n if (showFilterBar) {\n filterStatus = h(FilterBar, { filters: filters ?? [] });\n }\n\n return h(\"div.data-sheet-container\", { className, style }, [\n // The actions/tools toolbar (selection-modal). Table-scoped controls like\n // scroll-to-row / full-text search live here as ordinary actions.\n h(ActionsToolbar, { actions: _actions, tableName: name }),\n dataLoader,\n children,\n h(\n \"div.data-sheet-holder\",\n {\n tabIndex: 0,\n onKeyDown: handleKeyDown,\n onKeyUp: handleKeyUp,\n ref: tableElementRef,\n style: holderStyle,\n },\n h(\n Table,\n {\n ref,\n numRows,\n className: \"data-sheet\",\n enableFocusedCell,\n onColumnsReordered,\n focusedCell,\n selectedRegions,\n defaultRowHeight: rowHeight,\n minRowHeight: rowHeight,\n columnWidths,\n onColumnWidthChanged,\n onSelection,\n /** TODO: we could enable this, but we need a use-case first... */\n enableRowReordering: false,\n enableRowResizing: false,\n // The cell renderer is memoized internally based on these data dependencies\n cellRendererDependencies,\n onVisibleCellsChange: _onVisibleCellsChange,\n rowHeaderCellRenderer,\n selectionModes: _selectionModes,\n ...rest,\n getCellClipboardData: null,\n },\n realizedColumns,\n ),\n ),\n h(\"div.status-bar\", [\n filterStatus,\n h(\"div.spacer\"),\n h.if(_showLoadProgress)(LoadProgressIndicator),\n ]),\n h.if(debugMode)(CellRendererDebugOverlay, {\n cellRendererDependencies,\n names: [\n \"data\",\n \"updatedData\",\n \"focusedCell\",\n \"rowStatus\",\n \"filteredRowIndices\",\n ],\n }),\n ]);\n}\n\nconst columnWidthsIndexAtom = atom((get) => get(storeAtom).columnWidthsIndex);\nconst defaultColumnWidthAtom = atom((get) => get(storeAtom).defaultColumnWidth);\n\nconst columnWidthsAtom = atom((get) => {\n const ix = get(columnWidthsIndexAtom);\n return get(columnSpecAtom).map(\n (col) => ix.get(col.key) ?? col.width ?? get(defaultColumnWidthAtom),\n );\n});\n\nfunction styleParamsForDensity(density: DataSheetDensity) {\n switch (density) {\n case DataSheetDensity.MEDIUM:\n return {\n rowHeight: 24,\n style: {\n \"--data-sheet-row-height\": \"24px\",\n \"--data-sheet-font-size\": \"14px\",\n },\n };\n case DataSheetDensity.LOW:\n return {\n rowHeight: 30,\n style: {\n \"--data-sheet-row-height\": \"30px\",\n \"--data-sheet-font-size\": \"18px\",\n },\n };\n case DataSheetDensity.HIGH:\n default:\n return {\n rowHeight: 20,\n style: {\n \"--data-sheet-row-height\": \"20px\",\n \"--data-sheet-font-size\": \"12px\",\n },\n };\n }\n}\n\n/** Convenience component: runs `useChunkLoader` from inside a `DataSheet`.\n * Render as a child of `DataSheet` (it renders nothing itself). */\nfunction _DataLoaderManager<T = any>({\n fetchData,\n ...rest\n}: {\n fetchData: FetchData<T>;\n} & FetchDataOptions) {\n useDataLoader(fetchData, rest);\n return null;\n}\n\nexport function getRowsToDelete(selection) {\n let rowIndices: number[] = [];\n for (const sel of selection) {\n // This isn't a full-row selection\n if (sel.cols != null) continue;\n if (sel.rows == null) continue;\n const [startIndex, endIndex] = sel.rows;\n for (let i = startIndex; i <= endIndex; i++) {\n rowIndices.push(i);\n }\n }\n return rowIndices;\n}\n"],"names":["DataSheetDensity","ctx","_actions","colIndex","style"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2DO,IAAK,qCAAAA,sBAAL;AACLA,oBAAA,MAAA,IAAO;AACPA,oBAAA,QAAA,IAAS;AACTA,oBAAA,KAAA,IAAM;AAHI,SAAAA;AAAA,GAAA,oBAAA,CAAA,CAAA;AAQZ,MAAM,uBAAuB;AAgF7B,MAAM,YAAmB,CAAA;AAElB,SAAS,UAAa,OAA0B;AACrD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AAAA,IACX,yBAAyB;AAAA,IACzB,oBAAoB;AAAA,IACpB,qBAAqB;AAAA,IACrB;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAEJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,MAAM,QAAQ;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA;AAAA,IAEL,EAAE,YAAiB;AAAA,MACjB,GAAG;AAAA,MACH,MAAM,QAAQ;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA,CACD;AAAA,EAAA;AAEL;AAEA,MAAM,wBAAwB;AAAA,EAC5B,SAAS;AAAA,EACT,gBAAgB;AAClB;AAMA,eAAe,mBACb,UACAC,MACe;AACf,QAAM,OAAQA,KAAI,QAAQ,CAAA;AAC1B,QAAM,UAAWA,KAAI,eAAe,CAAA;AACpC,QAAM,SAAUA,KAAI,a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,IAAI,qBAAqB;AACpC,SAAO,IAAI,cAAc,EAAE;AAAA,IACzB,CAAC,QAAQ,GAAG,IAAI,IAAI,GAAG,KAAK,IAAI,SAAS,IAAI,sBAAsB;AAAA,EAAA;AAEvE,CAAC;AAED,SAAS,sBAAsB,SAA2B;AACxD,UAAQ,SAAA;AAAA,IACN,KAAK;AACH,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,IAEJ,KAAK;AACH,aAAO;AAAA,QACL,WAAW;AAAA,QACX,OAAO;AAAA,UACL,2BAA2B;AAAA,UAC3B,0BAA0B;AAAA,QAAA;AAAA,MAC5B;AAAA,IAEJ,KAAK;AAAA,IACL;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,GAEsB;AACpB,gBAAc,WAAW,IAAI;AAC7B,SAAO;AACT;AAEO,SAAS,gBAAgB,WAAW;AACzC,MAAI,aAAuB,CAAA;AAC3B,aAAW,OAAO,WAAW;AAE3B,QAAI,IAAI,QAAQ,KAAM;AACtB,QAAI,IAAI,QAAQ,KAAM;AACtB,UAAM,CAAC,YAAY,QAAQ,IAAI,IAAI;AACnC,aAAS,IAAI,YAAY,KAAK,UAAU,KAAK;AAC3C,iBAAW,KAAK,CAAC;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"core.js","sources":["../src/core.ts"],"sourcesContent":["import { useHotkeys } from \"@blueprintjs/core\";\nimport {\n Column,\n Region,\n RegionCardinality,\n RowHeaderCell,\n Table,\n TableProps,\n} from \"@blueprintjs/table\";\nimport \"@blueprintjs/table/lib/css/table.css\";\nimport { ReactNode, useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { LoadProgressIndicator } from \"./components\";\nimport { renderColumnHeaderCell } from \"./renderers\";\nimport h from \"./main.module.sass\";\nimport {\n columnSpecAtom,\n ctx,\n DataSheetProvider,\n storeAtom,\n tableActionsAtom,\n useSelector,\n useStoreAPI,\n} from \"./provider\";\nimport { atom } from \"jotai\";\nimport {\n DataSheetProviderProps,\n DEFAULT_ROW_STATUS_STYLES,\n EditEvent,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableElementStatus,\n VisibleCells,\n} from \"./types.ts\";\nimport { basicCellRenderer } from \"./cell-renderer.ts\";\nimport { CellRendererDebugOverlay, tableHotkeysAtom } from \"./utils\";\nimport {\n ActionsToolbar,\n clearSelectionAction,\n clipboardActions,\n columnControlActions,\n createSaveAction,\n FilterBar,\n resetChangesAction,\n TableAction,\n TableActionContext,\n TableFilter,\n} from \"./actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataOptions,\n tableFooterAtom,\n TableDataProvider,\n useScrollHandler,\n useDataLoader,\n} from \"./postgrest-table\";\n\n// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args\n\n// TODO: add a \"copy to selection\" tool (the little square in the bottom right corner of a cell)\n// This should copy the value of a cell (or a set of cells in the same row) downwards.\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/** Approximate column-header + scrollbar allowance, used to size the table to\n * its content in paged mode. */\nconst COLUMN_HEADER_HEIGHT = 34;\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\ninterface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n // An optional table name that will be used in toolbars if given\n name?: string;\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Derive the controlled edit overlay from the loaded rows, *inside* the\n * sheet. For provider-backed tables whose overlay is a function of the loaded\n * data plus external edit state (e.g. an ops stack): the library owns the\n * rows, so it calls this with them and uses the result as the controlled\n * overlay, re-deriving when the rows — or this function's identity (close it\n * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */\n deriveOverlay?: (rows: T[]) => {\n updatedData: T[];\n rowStatus: TableElementStatus[];\n };\n /** Bump to force the data provider to re-fetch from scratch (e.g. after a\n * save/delete that invalidated the loaded rows). */\n refreshToken?: number | string;\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n editable?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n /** Arbitrary nodes for the bottom status bar (left group), rendered beside\n * the active sort/filter tags — the home for view-state controls (show/hide\n * omitted rows/columns, a group-by indicator, etc.). */\n statusBar?: ReactNode;\n /** Presentation per row-status value, merged over the built-in defaults\n * (which style `\"deleted\"`). Supply styles for consumer-defined statuses\n * (e.g. `\"omitted\"`) and/or override the defaults. Each entry may set the\n * cells' style/intent and the row header's style. */\n rowStatusStyles?: RowStatusStyles;\n /** Render the content of a row's header cell (the left gutter). Receives the\n * row, its status, and the default 1-based label; return a node to use, or a\n * nullish value to keep the default. For group-key labels, omit indicators,\n * etc. Header-cell *styling* still comes from `rowStatusStyles`. */\n rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;\n}\n\ntype DataSheetProps<T> = DataSheetProviderProps<T> & DataSheetInternalProps<T>;\n\nconst emptyData: any[] = [];\n\nexport function DataSheet<T>(props: DataSheetProps<T>) {\n const {\n data,\n columnSpec,\n columnSpecOptions,\n editable = true,\n enableColumnReordering = false,\n enableFocusedCell = false,\n defaultColumnWidth = 150,\n children,\n ...rest\n } = props;\n\n return h(\n DataSheetProvider<T>,\n {\n data: data ?? emptyData,\n columnSpec,\n columnSpecOptions,\n enableColumnReordering,\n defaultColumnWidth,\n editable,\n ...rest,\n },\n h(_DataSheet<any>, {\n ...rest,\n data: data ?? emptyData,\n children,\n editable,\n enableColumnReordering,\n enableFocusedCell,\n }),\n );\n}\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nasync function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n\nfunction _DataSheet<T>({\n data: sourceData,\n fetchData,\n provider,\n pageSize,\n fetchMode,\n onVisibleCellsChange,\n onUpdateData,\n onEdit,\n onSave,\n updatedData: updatedDataProp,\n rowStatus: rowStatusProp,\n identity,\n deriveOverlay,\n refreshToken,\n onDeleteRows,\n name,\n verbose = false,\n enableFocusedCell,\n autoFocusEditor = true,\n cellInteraction,\n enableClipboard = true,\n density = DataSheetDensity.HIGH,\n selectionModes,\n actions,\n filters,\n columnHeaderCellRenderer,\n statusBar,\n rowStatusStyles,\n rowHeaderRenderer,\n children,\n ...rest\n}: DataSheetInternalProps<T>) {\n /**\n * @param data: The data to be displayed in the table\n * @param columnSpec: The specification for all columns in the table. If not provided, the column spec will be generated from the data.\n * @param columnSpecOptions: Options for generating a column spec from data\n */\n\n // Turn on debug features\n const debugMode = false;\n\n const editable = useSelector((state) => state.editable);\n\n // Resolve the active data provider: an explicit `provider` prop wins; else a\n // loose `fetchData` (+ identity) is wrapped as one; else in-memory `data`\n // becomes a local provider. Local and remote thus share one path, and the\n // provider is an explicit contract rather than a set of scattered props.\n const isLocalProvider = provider == null && fetchData == null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (provider != null) return provider;\n if (fetchData != null) {\n return { fetchData, identity: identity ?? ((r: any) => r?.id) };\n }\n if (sourceData != null && sourceData.length > 0) {\n return createLocalProvider(\n sourceData,\n identity != null ? { identity } : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [provider, fetchData, sourceData, identity]);\n\n // When an explicit provider owns persistence, its methods drive the built-in\n // Save (batch: edits→saveRows, added→insertRow, deleted→deleteRows), then a\n // refresh. Otherwise the loose `onSave` handler is used.\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n const providerSave = useMemo(() => {\n const p = provider;\n if (\n p == null ||\n (p.saveRows == null && p.deleteRows == null && p.insertRow == null)\n ) {\n return null;\n }\n return async (actionCtx: TableActionContext<T>) => {\n await persistViaProvider(p, actionCtx);\n bumpRefresh((v) => v + 1);\n };\n }, [provider, bumpRefresh]);\n const saveHandler = onSave ?? providerSave;\n\n // Sync table actions to atom. Consumer actions come first (they override a\n // built-in by reusing its id); the built-in column controls (sort/filter)\n // fill in the rest — so both the toolbar and the header dropdown source from\n // one registry. Built-ins self-gate (single sortable/filterable column).\n const _actions: TableAction[] = useMemo(() => {\n const _actions: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!_actions.some((x) => x.id === a.id)) _actions.push(a);\n }\n };\n if (actions != null) add(actions);\n add(columnControlActions);\n add([clearSelectionAction]);\n if (enableClipboard) add(clipboardActions);\n // Save/reset last — they're the most significant actions — and present for\n // every cardinality (editable), so the toolbar stays mounted regardless of\n // selection.\n if (editable) {\n if (saveHandler != null) add([createSaveAction(saveHandler)]);\n add([resetChangesAction]);\n }\n return _actions;\n }, [actions, enableClipboard, editable, saveHandler]);\n\n ctx.useSync(tableActionsAtom, _actions);\n\n const hotkeysConfig = ctx.useValue(tableHotkeysAtom);\n const { handleKeyDown, handleKeyUp } = useHotkeys(hotkeysConfig);\n\n // For now, we only consider a single cell \"focused\" when we have one cell selected.\n // Multi-cell selections have a different set of \"bulk\" actions.\n const selectedRegions = useSelector<T>((state) => state.selection ?? []);\n\n const data = useSelector((state) => state.data);\n\n const rowStatus = useSelector((state) => state.rowStatus);\n\n const focusedCell = useSelector((state) => state.focusedCell);\n\n const ref = useSelector((state) => state.tableRef);\n\n const columnSpec = useSelector((state) => state.columnSpec);\n\n // A sparse array to hold updates\n // TODO: create a \"changeset\" concept to facilitate undo/redo\n const updatedData = useSelector((state) => state.updatedData);\n\n const onSelection = useSelector((state) => state.onSelection);\n\n const storeAPI = useStoreAPI<T>();\n\n const onScroll = useScrollHandler();\n const _onVisibleCellsChange = useCallback(\n (visibleCells: VisibleCells) => {\n onScroll(visibleCells);\n onVisibleCellsChange?.(visibleCells);\n },\n [onVisibleCellsChange, onScroll],\n );\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Updated data\", updatedData);\n }, [updatedData]);\n\n useEffect(() => {\n onUpdateData?.(updatedData, data);\n }, [onUpdateData, data, updatedData]);\n\n useEffect(() => {\n if (!verbose) return;\n console.log(\"Selected regions\", selectedRegions);\n }, [selectedRegions]);\n\n const tableElementRef = useRef<HTMLElement>(null);\n useEffect(() => {\n // Return the focus to the table\n tableElementRef.current?.focus();\n }, [focusedCell]);\n\n const columnWidths = ctx.useValue(columnWidthsAtom);\n\n // When filters are active, only show matching rows\n const filteredRowIndices = useSelector((state) => state.filteredRowIndices);\n const totalRows = Math.max(updatedData.length, data.length);\n const numRows =\n filteredRowIndices != null ? filteredRowIndices.length : totalRows;\n\n let className = `${density}-density`;\n\n const { rowHeight, style } = styleParamsForDensity(density);\n\n // In paged mode the row count is small and fixed, so let the table size to\n // its content (header + rows) instead of filling the viewport.\n const footerInfo = ctx.useValue(tableFooterAtom);\n const holderStyle =\n footerInfo.mode === \"paged\"\n ? {\n flex: \"0 0 auto\" as const,\n height: numRows * rowHeight + COLUMN_HEADER_HEIGHT,\n }\n : undefined;\n\n const onColumnsReordered = useSelector((state) => state.onColumnsReordered);\n\n // Auto-detect if any columns have sortable/filterable set.\n // If so and no explicit columnHeaderCellRenderer was provided,\n // use the built-in client-side sort/filter header.\n const hasSortableOrFilterable = useMemo(\n () =>\n columnSpec.some(\n (col) =>\n col.sortable ||\n col.filterable ||\n (Array.isArray(col.filters) && col.filters.length > 0),\n ),\n [columnSpec],\n );\n\n const columnSorts = useSelector((state) => state.columnSorts);\n const activeFilters = useSelector((state) => state.activeFilters);\n\n // Cell activation mode, defaulting from the legacy `autoFocusEditor` boolean\n // so existing consumers are unaffected. Synced into the store so the cell\n // renderer, editors, and key handlers all read it consistently.\n const cellInteractionMode: CellInteraction =\n cellInteraction ?? (autoFocusEditor ? \"auto\" : \"manual\");\n\n const storeState = storeAPI;\n useEffect(() => {\n storeState.setState({ cellInteraction: cellInteractionMode });\n }, [storeState, cellInteractionMode]);\n\n useEffect(() => {\n // Give the store a handle to the focusable holder so editors can return\n // keyboard focus to the table when the cursor leaves them.\n storeState.setState({ tableElement: tableElementRef.current });\n }, [storeState]);\n\n useEffect(() => {\n storeState.setState({ onEdit });\n }, [storeState, onEdit]);\n\n useEffect(() => {\n // Controlled overlay: mirror the caller's edited state into the store as\n // the source of truth. Optimistic in-table edits are superseded on the\n // next render when the caller passes an updated value back. When the caller\n // controls it, the loader-boundary identity remap steps aside.\n const controlled =\n updatedDataProp !== undefined ||\n rowStatusProp !== undefined ||\n deriveOverlay != null;\n const patch: Record<string, unknown> = { controlledOverlay: controlled };\n if (updatedDataProp !== undefined) patch.updatedData = updatedDataProp;\n if (rowStatusProp !== undefined) patch.rowStatus = rowStatusProp;\n storeState.setState(patch);\n }, [storeState, updatedDataProp, rowStatusProp, deriveOverlay]);\n\n // Derived controlled overlay: the library owns the loaded rows, so it runs\n // the consumer's `deriveOverlay(rows)` here and pushes the result. Re-derives\n // when the rows load/change or the function's identity changes (close it over\n // your external edit state). The `controlledOverlay` flag above suppresses the\n // loader-boundary identity remap so this derivation is authoritative.\n const loadedData = useSelector((state) => state.data);\n useEffect(() => {\n if (deriveOverlay == null) return;\n const overlay = deriveOverlay(loadedData);\n storeState.setState({\n updatedData: overlay.updatedData,\n rowStatus: overlay.rowStatus,\n });\n }, [deriveOverlay, loadedData, storeState]);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g. after\n // a save). Skips the initial mount (the loader does its own first fetch).\n const bumpRefreshFromToken = ctx.useSet(dataRefreshTokenAtom);\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefreshFromToken((v) => v + 1);\n }, [refreshToken, bumpRefreshFromToken]);\n\n // The active provider supplies the row identity for the edit overlay.\n useEffect(() => {\n const id = activeProvider?.identity ?? identity;\n if (id != null) storeState.setState({ identity: id });\n }, [storeState, activeProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` without\n // `deleteRows` disables deletion entirely. (Local / loose sources keep the\n // local delete overlay.)\n useEffect(() => {\n const canDeleteRows = provider == null || provider.deleteRows != null;\n storeState.setState({ canDeleteRows });\n }, [storeState, provider]);\n\n // Merge consumer `rowStatusStyles` over the built-in defaults and hand the\n // result to the store, where the cell renderer and row-header renderer read\n // it. Merged (not replaced) so overriding one status doesn't drop the rest.\n const mergedRowStatusStyles = useMemo<RowStatusStyles>(\n () => ({ ...DEFAULT_ROW_STATUS_STYLES, ...rowStatusStyles }),\n [rowStatusStyles],\n );\n useEffect(() => {\n storeState.setState({ rowStatusStyles: mergedRowStatusStyles });\n }, [storeState, mergedRowStatusStyles]);\n\n const realizedColumns = useMemo(() => {\n return columnSpec.map((col, colIndex) => {\n let fn =\n col.headerCellRenderer ??\n columnHeaderCellRenderer ??\n renderColumnHeaderCell;\n let activeSort = null;\n let activeFilter = null;\n if (col.sortable) {\n activeSort = columnSorts?.find((s) => s.key === col.key);\n }\n // The active filter for this column is whichever active filter targets\n // it (a rich `col.filters` filter or the generic operator filter) — match\n // by columnKey rather than a fixed id.\n for (const entry of activeFilters?.values() ?? []) {\n if ((entry as any)?.filter?.columnKey === col.key) {\n activeFilter = entry;\n break;\n }\n }\n\n const _columnHeaderCellRenderer = (colIndex) => {\n return fn({\n col,\n colIndex,\n activeSort,\n activeFilter,\n });\n };\n\n return h(Column, {\n id: col.key,\n name: col.name,\n columnHeaderCellRenderer: _columnHeaderCellRenderer,\n cellRenderer: (rowIndex) => {\n const state = storeAPI.getState();\n return basicCellRenderer<T>(\n rowIndex,\n colIndex,\n col,\n state,\n filteredRowIndices,\n );\n },\n });\n });\n }, [\n columnSpec,\n columnSorts,\n activeFilters,\n storeAPI,\n filteredRowIndices,\n columnHeaderCellRenderer,\n ]);\n\n const onColumnWidthChanged = useSelector(\n (state) => state.onColumnWidthChanged,\n );\n\n const rowHeaderCellRenderer = useCallback(\n (rowIndex: number) => {\n const dataRowIndex =\n filteredRowIndices != null\n ? (filteredRowIndices[rowIndex] ?? rowIndex)\n : rowIndex;\n const statusVal = rowStatus[dataRowIndex];\n const style =\n (statusVal != null\n ? mergedRowStatusStyles[statusVal]?.headerStyle\n : null) ?? null;\n\n const defaultLabel = `${dataRowIndex + 1}`;\n let name: ReactNode = defaultLabel;\n if (rowHeaderRenderer != null) {\n const custom = rowHeaderRenderer({\n rowIndex: dataRowIndex,\n visibleIndex: rowIndex,\n row: data[dataRowIndex] ?? updatedData[dataRowIndex],\n status: statusVal,\n isDeleted: statusVal === TableElementStatus.DELETED,\n defaultLabel,\n });\n if (custom != null) name = custom;\n }\n\n return h(RowHeaderCell, {\n enableRowReordering: false,\n index: rowIndex,\n name,\n style,\n });\n },\n [\n rowStatus,\n filteredRowIndices,\n mergedRowStatusStyles,\n rowHeaderRenderer,\n data,\n updatedData,\n ],\n );\n\n let _selectionModes = selectionModes;\n if (\n editable &&\n _selectionModes != null &&\n !_selectionModes.includes(RegionCardinality.CELLS)\n ) {\n _selectionModes = [..._selectionModes, RegionCardinality.CELLS];\n // Ensure selection mode includes \"cells\"\n }\n\n const cellRendererDependencies = [\n data,\n updatedData,\n focusedCell,\n rowStatus,\n filteredRowIndices,\n ];\n\n // Drive the table from the active provider's `fetchData`. A local (in-memory)\n // provider loads the whole array at once; a remote one uses the `pageSize` /\n // `fetchMode` props and shows load progress.\n let _showLoadProgress: boolean = false;\n let dataLoader: ReactNode = null;\n if (activeProvider != null) {\n _showLoadProgress = !isLocalProvider;\n dataLoader = h(_DataLoaderManager, {\n key: \"__data_loader\",\n fetchData: activeProvider.fetchData,\n pageSize: isLocalProvider\n ? Math.max(sourceData?.length ?? 1, 1)\n : pageSize,\n fetchMode: isLocalProvider ? undefined : fetchMode,\n });\n }\n const showFilterBar =\n (filters != null && filters.length > 0) || hasSortableOrFilterable;\n\n let filterStatus: ReactNode = null;\n if (showFilterBar) {\n filterStatus = h(FilterBar, { filters: filters ?? [] });\n }\n\n return h(\"div.data-sheet-container\", { className, style }, [\n // The actions/tools toolbar (selection-modal). Table-scoped controls like\n // scroll-to-row / full-text search live here as ordinary actions.\n h(ActionsToolbar, { actions: _actions, tableName: name }),\n dataLoader,\n children,\n h(\n \"div.data-sheet-holder\",\n {\n tabIndex: 0,\n onKeyDown: handleKeyDown,\n onKeyUp: handleKeyUp,\n ref: tableElementRef,\n style: holderStyle,\n },\n h(\n Table,\n {\n ref,\n numRows,\n className: \"data-sheet\",\n enableFocusedCell,\n onColumnsReordered,\n focusedCell,\n selectedRegions,\n defaultRowHeight: rowHeight,\n minRowHeight: rowHeight,\n columnWidths,\n onColumnWidthChanged,\n onSelection,\n /** TODO: we could enable this, but we need a use-case first... */\n enableRowReordering: false,\n enableRowResizing: false,\n // The cell renderer is memoized internally based on these data dependencies\n cellRendererDependencies,\n onVisibleCellsChange: _onVisibleCellsChange,\n rowHeaderCellRenderer,\n selectionModes: _selectionModes,\n ...rest,\n getCellClipboardData: null,\n },\n realizedColumns,\n ),\n ),\n h(\"div.status-bar\", [\n filterStatus,\n statusBar,\n h(\"div.spacer\"),\n h.if(_showLoadProgress)(LoadProgressIndicator),\n ]),\n h.if(debugMode)(CellRendererDebugOverlay, {\n cellRendererDependencies,\n names: [\n \"data\",\n \"updatedData\",\n \"focusedCell\",\n \"rowStatus\",\n \"filteredRowIndices\",\n ],\n }),\n ]);\n}\n\nconst columnWidthsIndexAtom = atom((get) => get(storeAtom).columnWidthsIndex);\nconst defaultColumnWidthAtom = atom((get) => get(storeAtom).defaultColumnWidth);\n\nconst columnWidthsAtom = atom((get) => {\n const ix = get(columnWidthsIndexAtom);\n return get(columnSpecAtom).map(\n (col) => ix.get(col.key) ?? col.width ?? get(defaultColumnWidthAtom),\n );\n});\n\nfunction styleParamsForDensity(density: DataSheetDensity) {\n switch (density) {\n case DataSheetDensity.MEDIUM:\n return {\n rowHeight: 24,\n style: {\n \"--data-sheet-row-height\": \"24px\",\n \"--data-sheet-font-size\": \"14px\",\n },\n };\n case DataSheetDensity.LOW:\n return {\n rowHeight: 30,\n style: {\n \"--data-sheet-row-height\": \"30px\",\n \"--data-sheet-font-size\": \"18px\",\n },\n };\n case DataSheetDensity.HIGH:\n default:\n return {\n rowHeight: 20,\n style: {\n \"--data-sheet-row-height\": \"20px\",\n \"--data-sheet-font-size\": \"12px\",\n },\n };\n }\n}\n\n/** Convenience component: runs `useChunkLoader` from inside a `DataSheet`.\n * Render as a child of `DataSheet` (it renders nothing itself). */\nfunction _DataLoaderManager<T = any>({\n fetchData,\n ...rest\n}: {\n fetchData: FetchData<T>;\n} & FetchDataOptions) {\n useDataLoader(fetchData, rest);\n return null;\n}\n\nexport function getRowsToDelete(selection) {\n let rowIndices: number[] = [];\n for (const sel of selection) {\n // This isn't a full-row selection\n if (sel.cols != null) continue;\n if (sel.rows == null) continue;\n const [startIndex, endIndex] = sel.rows;\n for (let i = startIndex; i <= endIndex; i++) {\n rowIndices.push(i);\n }\n }\n return rowIndices;\n}\n"],"names":["DataSheetDensity","ctx","_actions","colIndex","style","name"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+DO,IAAK,qCAAAA,sBAAL;AACLA,oBAAA,MAAA,IAAO;AACPA,oBAAA,QAAA,IAAS;AACTA,oBAAA,KAAA,IAAM;AAHI,SAAAA;AAAA,GAAA,oBAAA,CAAA,CAAA;AAQZ,MAAM,uBAAuB;AA2G7B,MAAM,YAAmB,CAAA;AAElB,SAAS,UAAa,OAA0B;AACrD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AAAA,IACX,yBAAyB;AAAA,IACzB,oBAAoB;AAAA,IACpB,qBAAqB;AAAA,IACrB;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAEJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,MAAM,QAAQ;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA;AAAA,IAEL,EAAE,YAAiB;AAAA,MACjB,GAAG;AAAA,MACH,MAAM,QAAQ;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA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20
20
|
const builtin = require("./actions/builtin.cjs");
|
|
21
21
|
const dataLoaders = require("./postgrest-table/data-loaders.cjs");
|
|
22
22
|
const selection = require("./actions/selection.cjs");
|
|
23
|
+
const tableControls = require("./actions/table-controls.cjs");
|
|
23
24
|
const validation = require("./utils/validation.cjs");
|
|
24
25
|
const columnControls = require("./actions/column-controls.cjs");
|
|
25
26
|
const columnFilter = require("./actions/column-filter.cjs");
|
|
26
27
|
const keyHandling = require("./utils/key-handling.cjs");
|
|
27
28
|
const columnSpec = require("./utils/column-spec.cjs");
|
|
28
|
-
const tableControls = require("./actions/table-controls.cjs");
|
|
29
29
|
exports.DataSheet = core.DataSheet;
|
|
30
30
|
exports.DataSheetDensity = core.DataSheetDensity;
|
|
31
31
|
exports.getRowsToDelete = core.getRowsToDelete;
|
|
@@ -49,6 +49,7 @@ exports.tableDataAtom = provider.tableDataAtom;
|
|
|
49
49
|
exports.useSelector = provider.useSelector;
|
|
50
50
|
exports.useStoreAPI = provider.useStoreAPI;
|
|
51
51
|
exports.range = index$1.range;
|
|
52
|
+
exports.DEFAULT_ROW_STATUS_STYLES = types.DEFAULT_ROW_STATUS_STYLES;
|
|
52
53
|
exports.DS_ROW_ID = types.DS_ROW_ID;
|
|
53
54
|
exports.TableElementStatus = types.TableElementStatus;
|
|
54
55
|
exports.DEFAULT_FILTER_OPERATORS = operators.DEFAULT_FILTER_OPERATORS;
|
|
@@ -104,6 +105,8 @@ exports.getSelectedColumnKeys = selection.getSelectedColumnKeys;
|
|
|
104
105
|
exports.getSelectedRowIndices = selection.getSelectedRowIndices;
|
|
105
106
|
exports.getSelectionCardinality = selection.getSelectionCardinality;
|
|
106
107
|
exports.mergeColumnActions = selection.mergeColumnActions;
|
|
108
|
+
exports.clearSelectionAction = tableControls.clearSelectionAction;
|
|
109
|
+
exports.scrollToRowAction = tableControls.scrollToRowAction;
|
|
107
110
|
exports.collectValidationErrors = validation.collectValidationErrors;
|
|
108
111
|
exports.validateCell = validation.validateCell;
|
|
109
112
|
exports.columnControlActions = columnControls.columnControlActions;
|
|
@@ -117,5 +120,4 @@ exports.multiLineTextKeyHandler = keyHandling.multiLineTextKeyHandler;
|
|
|
117
120
|
exports.tableHotkeysAtom = keyHandling.tableHotkeysAtom;
|
|
118
121
|
exports.generateColumnSpec = columnSpec.generateColumnSpec;
|
|
119
122
|
exports.generateDefaultColumnSpec = columnSpec.generateDefaultColumnSpec;
|
|
120
|
-
exports.scrollToRowAction = tableControls.scrollToRowAction;
|
|
121
123
|
//# sourceMappingURL=index.cjs.map
|
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
|
@@ -2,7 +2,7 @@ import { DataSheet, DataSheetDensity, getRowsToDelete } from "./core.js";
|
|
|
2
2
|
import { ExpandedLithologies, IntervalCell, LongTextViewer, PostgRESTTableView, SearchAction, fullTextSearchAction, lithologyRenderer, notifyOnError, wrapWithErrorHandling } from "./postgrest-table/index.js";
|
|
3
3
|
import { DataSheetProvider, DataSheetProviderInner, columnSpecAtom, ctx, storeAPIAtom, storeAtom, tableActionsAtom, tableDataAtom, useSelector, useStoreAPI } from "./provider.js";
|
|
4
4
|
import { range } from "./utils/index.js";
|
|
5
|
-
import { DS_ROW_ID, TableElementStatus } from "./types.js";
|
|
5
|
+
import { DEFAULT_ROW_STATUS_STYLES, DS_ROW_ID, TableElementStatus } from "./types.js";
|
|
6
6
|
import { DEFAULT_FILTER_OPERATORS, OPERATOR_LABELS, getOperatorsForColumn, testFilterOperator } from "./filters/operators.js";
|
|
7
7
|
import { Cell } from "@blueprintjs/table";
|
|
8
8
|
import { ALL_CARDINALITIES, createSaveAction, hasPendingChanges } from "./actions/edit-actions.js";
|
|
@@ -18,12 +18,12 @@ import { PasteShape, clipboardActions, copyAction, cutAction, pasteAction, seria
|
|
|
18
18
|
import { addRowAction, defaultTableActions, deleteRowsAction, resetChangesAction } from "./actions/builtin.js";
|
|
19
19
|
import { applyColumnFilters, chunkPageAtom, compareRowsBySorts, createLocalProvider, createPostgRESTFetchChunk, createPostgRESTProvider, dataRefreshTokenAtom, standardizeFilter, tableFooterAtom, useDataLoader, useScrollHandler, viewInfoAtom } from "./postgrest-table/data-loaders.js";
|
|
20
20
|
import { buildActionContext, collectAllFilters, computeFilteredRowIndices, computeSelectionShape, getApplicableActions, getSelectedColumnKeys, getSelectedRowIndices, getSelectionCardinality, mergeColumnActions } from "./actions/selection.js";
|
|
21
|
+
import { clearSelectionAction, scrollToRowAction } from "./actions/table-controls.js";
|
|
21
22
|
import { collectValidationErrors, validateCell } from "./utils/validation.js";
|
|
22
23
|
import { columnControlActions, columnFilterAction, columnSortAction, isColumnFilterable } from "./actions/column-controls.js";
|
|
23
24
|
import { columnFilter, columnFilterId } from "./actions/column-filter.js";
|
|
24
25
|
import { editorKeyHandlerAtom, multiLineTextKeyHandler, tableHotkeysAtom } from "./utils/key-handling.js";
|
|
25
26
|
import { generateColumnSpec, generateDefaultColumnSpec } from "./utils/column-spec.js";
|
|
26
|
-
import { scrollToRowAction } from "./actions/table-controls.js";
|
|
27
27
|
export {
|
|
28
28
|
ALL_CARDINALITIES,
|
|
29
29
|
ActionsToolbar,
|
|
@@ -33,6 +33,7 @@ export {
|
|
|
33
33
|
ColorCell,
|
|
34
34
|
ColorPicker,
|
|
35
35
|
DEFAULT_FILTER_OPERATORS,
|
|
36
|
+
DEFAULT_ROW_STATUS_STYLES,
|
|
36
37
|
DS_ROW_ID,
|
|
37
38
|
DataSheet,
|
|
38
39
|
DataSheetDensity,
|
|
@@ -54,6 +55,7 @@ export {
|
|
|
54
55
|
applyColumnFilters,
|
|
55
56
|
buildActionContext,
|
|
56
57
|
chunkPageAtom,
|
|
58
|
+
clearSelectionAction,
|
|
57
59
|
clipboardActions,
|
|
58
60
|
collectAllFilters,
|
|
59
61
|
collectValidationErrors,
|
|
@@ -88,36 +88,22 @@ function ColumnHeaderControls({ colIndex }) {
|
|
|
88
88
|
const controls = actions.filter(
|
|
89
89
|
(a) => a.targets.includes(table.RegionCardinality.FULL_COLUMNS) && (a.appliesTo?.(actionCtx) ?? true)
|
|
90
90
|
);
|
|
91
|
-
const
|
|
92
|
-
(a
|
|
93
|
-
|
|
94
|
-
{
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
).filter(Boolean);
|
|
105
|
-
if (rendered.length === 0) {
|
|
91
|
+
const items = controls.map((a, i) => {
|
|
92
|
+
if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);
|
|
93
|
+
if (a.render != null)
|
|
94
|
+
return h__default.default("li.column-header-control", { key: a.id ?? i }, a.render(actionCtx));
|
|
95
|
+
return h__default.default(core.MenuItem, {
|
|
96
|
+
key: a.id ?? i,
|
|
97
|
+
icon: a.icon,
|
|
98
|
+
intent: a.intent,
|
|
99
|
+
text: a.name,
|
|
100
|
+
onClick: () => a.run?.(actionCtx)
|
|
101
|
+
});
|
|
102
|
+
}).filter(Boolean);
|
|
103
|
+
if (items.length === 0) {
|
|
106
104
|
return h__default.default(core.Menu, [h__default.default(core.MenuItem, { text: "No options", disabled: true })]);
|
|
107
105
|
}
|
|
108
|
-
return h__default.default(
|
|
109
|
-
"div.column-header-controls",
|
|
110
|
-
{
|
|
111
|
-
style: {
|
|
112
|
-
padding: "8px",
|
|
113
|
-
display: "flex",
|
|
114
|
-
flexDirection: "column",
|
|
115
|
-
gap: "6px",
|
|
116
|
-
alignItems: "flex-start"
|
|
117
|
-
}
|
|
118
|
-
},
|
|
119
|
-
rendered
|
|
120
|
-
);
|
|
106
|
+
return h__default.default(core.Menu, { className: "column-header-controls" }, items);
|
|
121
107
|
}
|
|
122
108
|
exports.renderColumnHeaderCell = renderColumnHeaderCell;
|
|
123
109
|
//# sourceMappingURL=column-header-cell.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-header-cell.cjs","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport {
|
|
1
|
+
{"version":3,"file":"column-header-cell.cjs","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport { Icon, Menu, MenuItem } from \"@blueprintjs/core\";\nimport { ctx, tableActionsAtom, useStoreAPI } from \"../provider\";\nimport { buildActionContext } from \"../actions/selection\";\nimport type { ColumnSpec } from \"../utils/column-spec\";\nimport type {\n PostgrestColumnFilter,\n ColumnSortEntry,\n} from \"../postgrest-table\";\n\nexport interface ColumnActionsConfig {\n activeSort?: ColumnSortEntry | null;\n activeFilter?: PostgrestColumnFilter | null;\n}\n\nexport interface ColumnHeaderRendererProps extends ColumnActionsConfig {\n col: ColumnSpec;\n colIndex: number;\n //actions: ColumnHeaderActions;\n}\n\n// ---- Column header cell ----\n\n/** Column header cell whose dropdown renders the `FULL_COLUMNS` controls\n * (sort/filter + any custom column actions) from the shared action registry,\n * scoped to this column. */\nexport function renderColumnHeaderCell({\n col,\n colIndex,\n activeSort,\n activeFilter,\n}: ColumnHeaderRendererProps) {\n const isSortable = col.sortable === true;\n const isFilterable =\n col.filterable === true ||\n typeof col.filterable === \"object\" ||\n (Array.isArray(col.filters) && col.filters.length > 0);\n const hasCustomActions =\n Array.isArray((col as any).actions) && (col as any).actions.length > 0;\n\n if (!isSortable && !isFilterable && !hasCustomActions) {\n return h(ColumnHeaderCell, { name: col.name });\n }\n\n // `activeFilter` is the active store entry targeting this column (any filter\n // type), or null — so the indicator lights for rich and operator filters.\n const hasFilterActive = activeFilter != null;\n const hasSortActive = activeSort != null;\n\n return h(ColumnHeaderCell, {\n name: col.name,\n // Persistent interaction bar so the menu caret is always clickable — the\n // hover-triggered caret was blocked by the selection overlay when the\n // column was selected.\n enableColumnInteractionBar: true,\n nameRenderer: () =>\n h(ColumnHeaderName, { col, hasSortActive, hasFilterActive, activeSort }),\n menuRenderer: () => h(ColumnHeaderControls, { colIndex }),\n });\n}\n\n/** Column name with active sort/filter indicator icons. */\nfunction ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {\n return h(\n \"div\",\n { style: { display: \"flex\", alignItems: \"center\", width: \"100%\" } },\n [\n h(\n \"span\",\n {\n style: {\n flex: 1,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n },\n },\n col.name,\n ),\n h.if(hasSortActive || hasFilterActive)(\n \"span\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"2px\",\n marginLeft: \"4px\",\n flexShrink: 0,\n },\n },\n [\n h.if(hasSortActive)(Icon, {\n icon: activeSort?.ascending ? \"sort-asc\" : \"sort-desc\",\n size: 12,\n style: { color: \"var(--intent-primary, #2965cc)\" },\n }),\n h.if(hasFilterActive)(Icon, {\n icon: \"filter\",\n size: 12,\n style: { color: \"var(--intent-warning, #d99e0b)\" },\n }),\n ],\n ),\n ],\n );\n}\n\n/** Dropdown content: the `FULL_COLUMNS` controls for this column, sourced from\n * the shared action registry and scoped to the column via a synthetic\n * single-column selection context — so the header and toolbar render the same\n * sort/filter (and custom column) controls. */\nfunction ColumnHeaderControls({ colIndex }: { colIndex: number }) {\n const storeAPI = useStoreAPI();\n const actions = ctx.useValue(tableActionsAtom);\n\n // Scope the action context to this column (as if it were the selection).\n const actionCtx = buildActionContext(\n {\n ...storeAPI.getState(),\n selection: [{ cols: [colIndex, colIndex], rows: undefined }],\n } as any,\n storeAPI.setState,\n );\n\n const controls = actions.filter(\n (a) =>\n a.targets.includes(RegionCardinality.FULL_COLUMNS) &&\n (a.appliesTo?.(actionCtx) ?? true),\n );\n\n // Prefer menu-native rendering (`renderMenuItem`) — sort/filter render as\n // items with submenus, so the whole dropdown is one Blueprint `Menu`. A\n // control that only has `render` (a live toolbar control) is embedded as-is;\n // a plain `run` action becomes a clickable item.\n const items = controls\n .map((a, i) => {\n if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);\n if (a.render != null)\n return h(\"li.column-header-control\", { key: a.id ?? i }, a.render(actionCtx));\n return h(MenuItem, {\n key: a.id ?? i,\n icon: a.icon,\n intent: a.intent,\n text: a.name,\n onClick: () => a.run?.(actionCtx),\n });\n })\n .filter(Boolean);\n\n if (items.length === 0) {\n return h(Menu, [h(MenuItem, { text: \"No options\", disabled: true })]);\n }\n\n return h(Menu, { className: \"column-header-controls\" }, items);\n}\n"],"names":["h","ColumnHeaderCell","Icon","useStoreAPI","ctx","tableActionsAtom","buildActionContext","RegionCardinality","MenuItem","Menu"],"mappings":";;;;;;;;;AAmCO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA8B;AAC5B,QAAM,aAAa,IAAI,aAAa;AACpC,QAAM,eACJ,IAAI,eAAe,QACnB,OAAO,IAAI,eAAe,YACzB,MAAM,QAAQ,IAAI,OAAO,KAAK,IAAI,QAAQ,SAAS;A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EACtE;AAEA,SAAOR,WAAAA,QAAES,KAAAA,MAAM,EAAE,WAAW,yBAAA,GAA4B,KAAK;AAC/D;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import h from "@macrostrat/hyper";
|
|
2
2
|
import { ColumnHeaderCell, RegionCardinality } from "@blueprintjs/table";
|
|
3
|
-
import {
|
|
3
|
+
import { MenuItem, Menu, Icon } from "@blueprintjs/core";
|
|
4
4
|
import { useStoreAPI, ctx, tableActionsAtom } from "../provider.js";
|
|
5
5
|
import { buildActionContext } from "../actions/selection.js";
|
|
6
6
|
function renderColumnHeaderCell({
|
|
@@ -84,36 +84,22 @@ function ColumnHeaderControls({ colIndex }) {
|
|
|
84
84
|
const controls = actions.filter(
|
|
85
85
|
(a) => a.targets.includes(RegionCardinality.FULL_COLUMNS) && (a.appliesTo?.(actionCtx) ?? true)
|
|
86
86
|
);
|
|
87
|
-
const
|
|
88
|
-
(a
|
|
89
|
-
|
|
90
|
-
{
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
).filter(Boolean);
|
|
101
|
-
if (rendered.length === 0) {
|
|
87
|
+
const items = controls.map((a, i) => {
|
|
88
|
+
if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);
|
|
89
|
+
if (a.render != null)
|
|
90
|
+
return h("li.column-header-control", { key: a.id ?? i }, a.render(actionCtx));
|
|
91
|
+
return h(MenuItem, {
|
|
92
|
+
key: a.id ?? i,
|
|
93
|
+
icon: a.icon,
|
|
94
|
+
intent: a.intent,
|
|
95
|
+
text: a.name,
|
|
96
|
+
onClick: () => a.run?.(actionCtx)
|
|
97
|
+
});
|
|
98
|
+
}).filter(Boolean);
|
|
99
|
+
if (items.length === 0) {
|
|
102
100
|
return h(Menu, [h(MenuItem, { text: "No options", disabled: true })]);
|
|
103
101
|
}
|
|
104
|
-
return h(
|
|
105
|
-
"div.column-header-controls",
|
|
106
|
-
{
|
|
107
|
-
style: {
|
|
108
|
-
padding: "8px",
|
|
109
|
-
display: "flex",
|
|
110
|
-
flexDirection: "column",
|
|
111
|
-
gap: "6px",
|
|
112
|
-
alignItems: "flex-start"
|
|
113
|
-
}
|
|
114
|
-
},
|
|
115
|
-
rendered
|
|
116
|
-
);
|
|
102
|
+
return h(Menu, { className: "column-header-controls" }, items);
|
|
117
103
|
}
|
|
118
104
|
export {
|
|
119
105
|
renderColumnHeaderCell
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-header-cell.js","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport {
|
|
1
|
+
{"version":3,"file":"column-header-cell.js","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport { Icon, Menu, MenuItem } from \"@blueprintjs/core\";\nimport { ctx, tableActionsAtom, useStoreAPI } from \"../provider\";\nimport { buildActionContext } from \"../actions/selection\";\nimport type { ColumnSpec } from \"../utils/column-spec\";\nimport type {\n PostgrestColumnFilter,\n ColumnSortEntry,\n} from \"../postgrest-table\";\n\nexport interface ColumnActionsConfig {\n activeSort?: ColumnSortEntry | null;\n activeFilter?: PostgrestColumnFilter | null;\n}\n\nexport interface ColumnHeaderRendererProps extends ColumnActionsConfig {\n col: ColumnSpec;\n colIndex: number;\n //actions: ColumnHeaderActions;\n}\n\n// ---- Column header cell ----\n\n/** Column header cell whose dropdown renders the `FULL_COLUMNS` controls\n * (sort/filter + any custom column actions) from the shared action registry,\n * scoped to this column. */\nexport function renderColumnHeaderCell({\n col,\n colIndex,\n activeSort,\n activeFilter,\n}: ColumnHeaderRendererProps) {\n const isSortable = col.sortable === true;\n const isFilterable =\n col.filterable === true ||\n typeof col.filterable === \"object\" ||\n (Array.isArray(col.filters) && col.filters.length > 0);\n const hasCustomActions =\n Array.isArray((col as any).actions) && (col as any).actions.length > 0;\n\n if (!isSortable && !isFilterable && !hasCustomActions) {\n return h(ColumnHeaderCell, { name: col.name });\n }\n\n // `activeFilter` is the active store entry targeting this column (any filter\n // type), or null — so the indicator lights for rich and operator filters.\n const hasFilterActive = activeFilter != null;\n const hasSortActive = activeSort != null;\n\n return h(ColumnHeaderCell, {\n name: col.name,\n // Persistent interaction bar so the menu caret is always clickable — the\n // hover-triggered caret was blocked by the selection overlay when the\n // column was selected.\n enableColumnInteractionBar: true,\n nameRenderer: () =>\n h(ColumnHeaderName, { col, hasSortActive, hasFilterActive, activeSort }),\n menuRenderer: () => h(ColumnHeaderControls, { colIndex }),\n });\n}\n\n/** Column name with active sort/filter indicator icons. */\nfunction ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {\n return h(\n \"div\",\n { style: { display: \"flex\", alignItems: \"center\", width: \"100%\" } },\n [\n h(\n \"span\",\n {\n style: {\n flex: 1,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n },\n },\n col.name,\n ),\n h.if(hasSortActive || hasFilterActive)(\n \"span\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"2px\",\n marginLeft: \"4px\",\n flexShrink: 0,\n },\n },\n [\n h.if(hasSortActive)(Icon, {\n icon: activeSort?.ascending ? \"sort-asc\" : \"sort-desc\",\n size: 12,\n style: { color: \"var(--intent-primary, #2965cc)\" },\n }),\n h.if(hasFilterActive)(Icon, {\n icon: \"filter\",\n size: 12,\n style: { color: \"var(--intent-warning, #d99e0b)\" },\n }),\n ],\n ),\n ],\n );\n}\n\n/** Dropdown content: the `FULL_COLUMNS` controls for this column, sourced from\n * the shared action registry and scoped to the column via a synthetic\n * single-column selection context — so the header and toolbar render the same\n * sort/filter (and custom column) controls. */\nfunction ColumnHeaderControls({ colIndex }: { colIndex: number }) {\n const storeAPI = useStoreAPI();\n const actions = ctx.useValue(tableActionsAtom);\n\n // Scope the action context to this column (as if it were the selection).\n const actionCtx = buildActionContext(\n {\n ...storeAPI.getState(),\n selection: [{ cols: [colIndex, colIndex], rows: undefined }],\n } as any,\n storeAPI.setState,\n );\n\n const controls = actions.filter(\n (a) =>\n a.targets.includes(RegionCardinality.FULL_COLUMNS) &&\n (a.appliesTo?.(actionCtx) ?? true),\n );\n\n // Prefer menu-native rendering (`renderMenuItem`) — sort/filter render as\n // items with submenus, so the whole dropdown is one Blueprint `Menu`. A\n // control that only has `render` (a live toolbar control) is embedded as-is;\n // a plain `run` action becomes a clickable item.\n const items = controls\n .map((a, i) => {\n if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);\n if (a.render != null)\n return h(\"li.column-header-control\", { key: a.id ?? i }, a.render(actionCtx));\n return h(MenuItem, {\n key: a.id ?? i,\n icon: a.icon,\n intent: a.intent,\n text: a.name,\n onClick: () => a.run?.(actionCtx),\n });\n })\n .filter(Boolean);\n\n if (items.length === 0) {\n return h(Menu, [h(MenuItem, { text: \"No options\", disabled: true })]);\n }\n\n return h(Menu, { className: \"column-header-controls\" }, items);\n}\n"],"names":[],"mappings":";;;;;AAmCO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA8B;AAC5B,QAAM,aAAa,IAAI,aAAa;AACpC,QAAM,eACJ,IAAI,eAAe,QACnB,OAAO,IAAI,eAAe,YACzB,MAAM,QAAQ,I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__PURE__ */ ((TableElementStatus2) => {
|
|
|
5
5
|
TableElementStatus2["ADDED"] = "added";
|
|
6
6
|
return TableElementStatus2;
|
|
7
7
|
})(TableElementStatus || {});
|
|
8
|
+
const DEFAULT_ROW_STATUS_STYLES = {
|
|
9
|
+
[
|
|
10
|
+
"deleted"
|
|
11
|
+
/* DELETED */
|
|
12
|
+
]: {
|
|
13
|
+
cellStyle: { opacity: 0.5, textDecoration: "line-through" },
|
|
14
|
+
headerStyle: { opacity: 0.5, textDecoration: "line-through" },
|
|
15
|
+
intent: "danger"
|
|
16
|
+
}
|
|
17
|
+
};
|
|
8
18
|
const DS_ROW_ID = "__dsRowId";
|
|
19
|
+
exports.DEFAULT_ROW_STATUS_STYLES = DEFAULT_ROW_STATUS_STYLES;
|
|
9
20
|
exports.DS_ROW_ID = DS_ROW_ID;
|
|
10
21
|
exports.TableElementStatus = TableElementStatus;
|
|
11
22
|
//# sourceMappingURL=types.cjs.map
|
package/dist/types.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sources":["../src/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport { ColumnSpec, ColumnSpecOptions } from \"./utils\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport type { CellEdit } from \"./actions\";\n\n/** A single column sort entry for client-side sorting.\n * Defined here (rather than in actions/types) to avoid circular imports. */\nexport interface ColumnSort {\n key: string;\n ascending: boolean;\n}\n\n/** Direction of keyboard navigation between cells. */\nexport type NavDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/**\n * A structured, revertible description of a user edit. Emitted via the\n * `onEdit` hook so a consumer can capture edits as operations (and, with the\n * controlled-overlay API, own the edited state) instead of diffing\n * `updatedData`. This is the write half of the data-sheet's read/write\n * contract — the mirror of how data flows in.\n */\nexport type EditEvent<T = any> =\n | { type: \"setCells\"; cells: CellEdit[] }\n | { type: \"deleteRows\"; rowIndices: number[] }\n | { type: \"restoreRows\"; rowIndices: number[] }\n | { type: \"addRow\"; rowIndex: number; value: Partial<T> }\n | { type: \"resetChanges\" };\n\nexport interface DataSheetCoreProps<T> {\n data: T[];\n columnSpec?: ColumnSpec[];\n editable?: boolean;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n}\n\nexport enum TableElementStatus {\n DELETED = \"deleted\",\n ADDED = \"added\",\n}\n\n/** Property key holding a stable synthetic id on rows added in-table. Added\n * rows aren't in the data provider, so they need their own identity to survive\n * a provider re-fetch; it's carried on the row and preserved through edits. */\nexport const DS_ROW_ID = \"__dsRowId\";\n\n/** Proxy stored during a copy operation, enabling backend-mediated paste\n * for lazy-loaded tables where not all data is available locally. */\nexport interface ClipboardProxy {\n cardinality: RegionCardinality;\n /** Source row indices (for row/cell copies) */\n rowIndices?: number[];\n /** Source column keys (for column/cell copies) */\n columnKeys?: string[];\n /** The plain text written to the clipboard, used to verify the proxy\n * is still valid on paste (i.e., clipboard hasn't been overwritten). */\n text: string;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n /**\n * Set of row indices that have been added to the table,\n * but not yet committed to the underlying data array.\n *\n * This is used to track which rows should be reverted when\n * a \"reset\" action is performed.\n */\n rowStatus: TableElementStatus[];\n // Sparse data structure for updated data\n updatedData: T[];\n initialized: boolean;\n columnWidthsIndex: Map<string, number>;\n /** Active column/table filters. Keys are filter IDs, values carry the\n * filter definition and its current configuration state. */\n activeFilters: Map<string, { filter: any; state: any }>;\n /** Clipboard proxy from the last copy operation */\n clipboardProxy: ClipboardProxy | null;\n /** Visible row indices when filters are active. `null` means show all rows. */\n filteredRowIndices: number[] | null;\n /** Active column sort entries for client-side sorting. */\n columnSorts: ColumnSort[];\n /** Whether selecting a cell automatically activates its surface (opens an\n * editor/detail panel and, for editors, focuses it). `\"manual\"` opens only\n * on click. */\n cellInteraction: \"auto\" | \"manual\";\n /** Runtime override of `cellInteraction`: while `false`, auto-activation is\n * suppressed (set by pressing Escape, re-armed by clicking a cell) so the\n * keyboard prioritizes navigation. */\n autoActivateArmed: boolean;\n /** Direction of the last keyboard navigation, used to place an editor's\n * cursor on the side the user is travelling toward. `null` after a click. */\n lastNavDirection: NavDirection | null;\n /** The table's focusable holder element; editors return focus here when the\n * cursor leaves them so arrow-key navigation resumes. */\n tableElement: HTMLElement | null;\n /** Whether the focused cell's surface (editor or detail panel) is open.\n * Owned by the store — not per-popover — so navigation, clicks, and the\n * Escape handler all agree on it. */\n cellSurfaceOpen: boolean;\n /** Optional observer called for every user edit as a structured\n * `EditEvent`, in addition to the built-in `updatedData` overlay. Lets a\n * consumer capture edits as revertible operations. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Row identity for the edit overlay — stable across a provider re-sort,\n * unlike an array index. Defaults to `(row) => row?.id`; a data provider\n * supplies its own (e.g. a PostgREST identity key). Used to re-attach edits\n * when the loader replaces `data` with a re-ordered window. */\n identity: (row: any) => string | number | null | undefined;\n /** Edits/statuses held by identity for rows not currently loaded (server\n * sources), re-attached when their row next arrives. */\n pendingOverlayById: Map<\n string | number,\n { edit?: any; status?: TableElementStatus }\n >;\n /** True when the consumer controls the `updatedData`/`rowStatus` overlay; the\n * loader-boundary identity remap is skipped (the consumer owns it). */\n controlledOverlay: boolean;\n /** Whether row deletion is available. Set from the data provider: an explicit\n * `provider` without `deleteRows` disables deletion entirely (the delete\n * affordance greys out and the delete key is a no-op). Defaults to `true`. */\n canDeleteRows: boolean;\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<T>;\nexport type StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStoreMain<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(event: MouseEvent): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onSelectionEdited(value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n onColumnWidthChanged(columnIndex: number, newWidth: number): void;\n moveFocusedCell(direction: NavDirection): void;\n /** Suppress auto-activation until the next click (Escape enters nav mode). */\n suppressAutoActivate(): void;\n /** Re-arm auto-activation (a click re-enables auto-focus). */\n armAutoActivate(): void;\n /** Open the focused cell's surface (editor or detail panel). */\n openCellSurface(): void;\n /** Close the focused cell's surface. When `suppress` is true (the default,\n * as for Escape), auto mode also enters navigation mode (auto-activation is\n * suppressed until the next click). A click-dismiss passes `suppress: false`\n * so it just closes without changing the global mode. */\n closeCellSurface(opts?: { suppress?: boolean }): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n /** Activate or update a column/table filter.\n * Filter is any object satisfying `TableFilter` from the actions module. */\n setFilter(filterId: string, filter: any, filterState: any): void;\n /** Remove a filter by ID */\n removeFilter(filterId: string): void;\n /** Remove all active filters */\n clearFilters(): void;\n /** Set or clear a column sort. Pass `null` for ascending to clear. */\n setColumnSort(key: string, ascending: boolean | null): void;\n /** Remove all active column sorts */\n clearColumnSorts(): void;\n /** Store a clipboard proxy for potential backend-mediated paste */\n setClipboardProxy(proxy: ClipboardProxy | null): void;\n initialize(props: Partial<DataSheetStoreMain<T>>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2>;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n}\n\nexport type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {\n children: React.ReactNode;\n columnSpecOptions?: ColumnSpecOptions<T>;\n toaster?: OverlayToaster;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n"],"names":["TableElementStatus"],"mappings":";;AA0CO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,SAAA,IAAU;AACVA,sBAAA,OAAA,IAAQ;AAFE,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AAQL,MAAM,YAAY;;;"}
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":["../src/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport { ColumnSpec, ColumnSpecOptions } from \"./utils\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport type { CellEdit } from \"./actions\";\n\n/** A single column sort entry for client-side sorting.\n * Defined here (rather than in actions/types) to avoid circular imports. */\nexport interface ColumnSort {\n key: string;\n ascending: boolean;\n}\n\n/** Direction of keyboard navigation between cells. */\nexport type NavDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/**\n * A structured, revertible description of a user edit. Emitted via the\n * `onEdit` hook so a consumer can capture edits as operations (and, with the\n * controlled-overlay API, own the edited state) instead of diffing\n * `updatedData`. This is the write half of the data-sheet's read/write\n * contract — the mirror of how data flows in.\n */\nexport type EditEvent<T = any> =\n | { type: \"setCells\"; cells: CellEdit[] }\n | { type: \"deleteRows\"; rowIndices: number[] }\n | { type: \"restoreRows\"; rowIndices: number[] }\n | { type: \"addRow\"; rowIndex: number; value: Partial<T> }\n | { type: \"resetChanges\" };\n\nexport interface DataSheetCoreProps<T> {\n data: T[];\n columnSpec?: ColumnSpec[];\n editable?: boolean;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n}\n\nexport enum TableElementStatus {\n DELETED = \"deleted\",\n ADDED = \"added\",\n}\n\n/** A row's status value. The built-in `TableElementStatus` members\n * (`\"deleted\"` / `\"added\"`) plus any consumer-defined status string (e.g.\n * `\"omitted\"`). The `(string & {})` keeps autocomplete for the enum members\n * while still accepting arbitrary strings. */\nexport type RowStatusValue = TableElementStatus | (string & {});\n\n/** Presentation for a row status: applied to the row's cells and its header\n * cell. Keyed by status value in `rowStatusStyles`. The library ships a\n * default for `\"deleted\"` (dimmed + struck through, danger intent); consumers\n * merge in styles for their own statuses (and may override the defaults). */\nexport interface RowStatusStyle {\n /** Style merged onto each cell in a row with this status. */\n cellStyle?: import(\"react\").CSSProperties;\n /** Style applied to the row's header cell. */\n headerStyle?: import(\"react\").CSSProperties;\n /** Blueprint intent applied to the row's cells (precedence: validation >\n * this > edited-green). */\n intent?: import(\"@blueprintjs/core\").Intent;\n}\n\nexport type RowStatusStyles = Record<string, RowStatusStyle>;\n\n/** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged\n * over this, so `\"deleted\"` keeps its look unless explicitly overridden. */\nexport const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles = {\n [TableElementStatus.DELETED]: {\n cellStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n headerStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n intent: \"danger\",\n },\n};\n\n/** Context passed to a custom `rowHeaderRenderer`, so it can label and style\n * the row header from the row's data and status (group-key labels, an\n * omit indicator, etc.). Return a node to use as the header's name, or a\n * nullish value to fall back to the default (1-based row number). */\nexport interface RowHeaderRenderContext<T = any> {\n /** Data-row index (stable under sort/filter). */\n rowIndex: number;\n /** Visible (display) row index. */\n visibleIndex: number;\n /** The row's data (base, overlaid with edits if present). */\n row: T | undefined;\n /** The row's status, if any. */\n status: RowStatusValue | undefined;\n /** Convenience: `status === TableElementStatus.DELETED`. */\n isDeleted: boolean;\n /** The default label (`\"${rowIndex + 1}\"`). */\n defaultLabel: string;\n}\n\n/** Property key holding a stable synthetic id on rows added in-table. Added\n * rows aren't in the data provider, so they need their own identity to survive\n * a provider re-fetch; it's carried on the row and preserved through edits. */\nexport const DS_ROW_ID = \"__dsRowId\";\n\n/** Proxy stored during a copy operation, enabling backend-mediated paste\n * for lazy-loaded tables where not all data is available locally. */\nexport interface ClipboardProxy {\n cardinality: RegionCardinality;\n /** Source row indices (for row/cell copies) */\n rowIndices?: number[];\n /** Source column keys (for column/cell copies) */\n columnKeys?: string[];\n /** The plain text written to the clipboard, used to verify the proxy\n * is still valid on paste (i.e., clipboard hasn't been overwritten). */\n text: string;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n /**\n * Set of row indices that have been added to the table,\n * but not yet committed to the underlying data array.\n *\n * This is used to track which rows should be reverted when\n * a \"reset\" action is performed.\n */\n rowStatus: RowStatusValue[];\n /** Presentation per row-status value (merged: defaults + the\n * `rowStatusStyles` prop). Read by the cell renderer and row-header renderer\n * to style rows by status. */\n rowStatusStyles: RowStatusStyles;\n // Sparse data structure for updated data\n updatedData: T[];\n initialized: boolean;\n columnWidthsIndex: Map<string, number>;\n /** Active column/table filters. Keys are filter IDs, values carry the\n * filter definition and its current configuration state. */\n activeFilters: Map<string, { filter: any; state: any }>;\n /** Clipboard proxy from the last copy operation */\n clipboardProxy: ClipboardProxy | null;\n /** Visible row indices when filters are active. `null` means show all rows. */\n filteredRowIndices: number[] | null;\n /** Active column sort entries for client-side sorting. */\n columnSorts: ColumnSort[];\n /** Whether selecting a cell automatically activates its surface (opens an\n * editor/detail panel and, for editors, focuses it). `\"manual\"` opens only\n * on click. */\n cellInteraction: \"auto\" | \"manual\";\n /** Runtime override of `cellInteraction`: while `false`, auto-activation is\n * suppressed (set by pressing Escape, re-armed by clicking a cell) so the\n * keyboard prioritizes navigation. */\n autoActivateArmed: boolean;\n /** Direction of the last keyboard navigation, used to place an editor's\n * cursor on the side the user is travelling toward. `null` after a click. */\n lastNavDirection: NavDirection | null;\n /** The table's focusable holder element; editors return focus here when the\n * cursor leaves them so arrow-key navigation resumes. */\n tableElement: HTMLElement | null;\n /** Whether the focused cell's surface (editor or detail panel) is open.\n * Owned by the store — not per-popover — so navigation, clicks, and the\n * Escape handler all agree on it. */\n cellSurfaceOpen: boolean;\n /** Optional observer called for every user edit as a structured\n * `EditEvent`, in addition to the built-in `updatedData` overlay. Lets a\n * consumer capture edits as revertible operations. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Row identity for the edit overlay — stable across a provider re-sort,\n * unlike an array index. Defaults to `(row) => row?.id`; a data provider\n * supplies its own (e.g. a PostgREST identity key). Used to re-attach edits\n * when the loader replaces `data` with a re-ordered window. */\n identity: (row: any) => string | number | null | undefined;\n /** Edits/statuses held by identity for rows not currently loaded (server\n * sources), re-attached when their row next arrives. */\n pendingOverlayById: Map<\n string | number,\n { edit?: any; status?: TableElementStatus }\n >;\n /** True when the consumer controls the `updatedData`/`rowStatus` overlay; the\n * loader-boundary identity remap is skipped (the consumer owns it). */\n controlledOverlay: boolean;\n /** Whether row deletion is available. Set from the data provider: an explicit\n * `provider` without `deleteRows` disables deletion entirely (the delete\n * affordance greys out and the delete key is a no-op). Defaults to `true`. */\n canDeleteRows: boolean;\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<T>;\nexport type StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStoreMain<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(event: MouseEvent): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onSelectionEdited(value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n onColumnWidthChanged(columnIndex: number, newWidth: number): void;\n moveFocusedCell(direction: NavDirection): void;\n /** Suppress auto-activation until the next click (Escape enters nav mode). */\n suppressAutoActivate(): void;\n /** Re-arm auto-activation (a click re-enables auto-focus). */\n armAutoActivate(): void;\n /** Open the focused cell's surface (editor or detail panel). */\n openCellSurface(): void;\n /** Close the focused cell's surface. When `suppress` is true (the default,\n * as for Escape), auto mode also enters navigation mode (auto-activation is\n * suppressed until the next click). A click-dismiss passes `suppress: false`\n * so it just closes without changing the global mode. */\n closeCellSurface(opts?: { suppress?: boolean }): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n /** Activate or update a column/table filter.\n * Filter is any object satisfying `TableFilter` from the actions module. */\n setFilter(filterId: string, filter: any, filterState: any): void;\n /** Remove a filter by ID */\n removeFilter(filterId: string): void;\n /** Remove all active filters */\n clearFilters(): void;\n /** Set or clear a column sort. Pass `null` for ascending to clear. */\n setColumnSort(key: string, ascending: boolean | null): void;\n /** Remove all active column sorts */\n clearColumnSorts(): void;\n /** Store a clipboard proxy for potential backend-mediated paste */\n setClipboardProxy(proxy: ClipboardProxy | null): void;\n initialize(props: Partial<DataSheetStoreMain<T>>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2>;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n}\n\nexport type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {\n children: React.ReactNode;\n columnSpecOptions?: ColumnSpecOptions<T>;\n toaster?: OverlayToaster;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n"],"names":["TableElementStatus"],"mappings":";;AA0CO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,SAAA,IAAU;AACVA,sBAAA,OAAA,IAAQ;AAFE,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AA6BL,MAAM,4BAA6C;AAAA,EACxD;AAAA,IAAC;AAAA;AAAA,KAA6B;AAAA,IAC5B,WAAW,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC3C,aAAa,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC7C,QAAQ;AAAA,EAAA;AAEZ;AAwBO,MAAM,YAAY;;;;"}
|
package/dist/types.d.ts
CHANGED
|
@@ -44,6 +44,46 @@ export declare enum TableElementStatus {
|
|
|
44
44
|
DELETED = "deleted",
|
|
45
45
|
ADDED = "added"
|
|
46
46
|
}
|
|
47
|
+
/** A row's status value. The built-in `TableElementStatus` members
|
|
48
|
+
* (`"deleted"` / `"added"`) plus any consumer-defined status string (e.g.
|
|
49
|
+
* `"omitted"`). The `(string & {})` keeps autocomplete for the enum members
|
|
50
|
+
* while still accepting arbitrary strings. */
|
|
51
|
+
export type RowStatusValue = TableElementStatus | (string & {});
|
|
52
|
+
/** Presentation for a row status: applied to the row's cells and its header
|
|
53
|
+
* cell. Keyed by status value in `rowStatusStyles`. The library ships a
|
|
54
|
+
* default for `"deleted"` (dimmed + struck through, danger intent); consumers
|
|
55
|
+
* merge in styles for their own statuses (and may override the defaults). */
|
|
56
|
+
export interface RowStatusStyle {
|
|
57
|
+
/** Style merged onto each cell in a row with this status. */
|
|
58
|
+
cellStyle?: import('react').CSSProperties;
|
|
59
|
+
/** Style applied to the row's header cell. */
|
|
60
|
+
headerStyle?: import('react').CSSProperties;
|
|
61
|
+
/** Blueprint intent applied to the row's cells (precedence: validation >
|
|
62
|
+
* this > edited-green). */
|
|
63
|
+
intent?: import('@blueprintjs/core').Intent;
|
|
64
|
+
}
|
|
65
|
+
export type RowStatusStyles = Record<string, RowStatusStyle>;
|
|
66
|
+
/** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged
|
|
67
|
+
* over this, so `"deleted"` keeps its look unless explicitly overridden. */
|
|
68
|
+
export declare const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles;
|
|
69
|
+
/** Context passed to a custom `rowHeaderRenderer`, so it can label and style
|
|
70
|
+
* the row header from the row's data and status (group-key labels, an
|
|
71
|
+
* omit indicator, etc.). Return a node to use as the header's name, or a
|
|
72
|
+
* nullish value to fall back to the default (1-based row number). */
|
|
73
|
+
export interface RowHeaderRenderContext<T = any> {
|
|
74
|
+
/** Data-row index (stable under sort/filter). */
|
|
75
|
+
rowIndex: number;
|
|
76
|
+
/** Visible (display) row index. */
|
|
77
|
+
visibleIndex: number;
|
|
78
|
+
/** The row's data (base, overlaid with edits if present). */
|
|
79
|
+
row: T | undefined;
|
|
80
|
+
/** The row's status, if any. */
|
|
81
|
+
status: RowStatusValue | undefined;
|
|
82
|
+
/** Convenience: `status === TableElementStatus.DELETED`. */
|
|
83
|
+
isDeleted: boolean;
|
|
84
|
+
/** The default label (`"${rowIndex + 1}"`). */
|
|
85
|
+
defaultLabel: string;
|
|
86
|
+
}
|
|
47
87
|
/** Property key holding a stable synthetic id on rows added in-table. Added
|
|
48
88
|
* rows aren't in the data provider, so they need their own identity to survive
|
|
49
89
|
* a provider re-fetch; it's carried on the row and preserved through edits. */
|
|
@@ -73,7 +113,11 @@ export interface DataSheetState<T> {
|
|
|
73
113
|
* This is used to track which rows should be reverted when
|
|
74
114
|
* a "reset" action is performed.
|
|
75
115
|
*/
|
|
76
|
-
rowStatus:
|
|
116
|
+
rowStatus: RowStatusValue[];
|
|
117
|
+
/** Presentation per row-status value (merged: defaults + the
|
|
118
|
+
* `rowStatusStyles` prop). Read by the cell renderer and row-header renderer
|
|
119
|
+
* to style rows by status. */
|
|
120
|
+
rowStatusStyles: RowStatusStyles;
|
|
77
121
|
updatedData: T[];
|
|
78
122
|
initialized: boolean;
|
|
79
123
|
columnWidthsIndex: Map<string, number>;
|