@macrostrat/data-sheet 4.9.0 → 4.9.1

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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.9.1] - 2026-09-25 [_changes_](https://github.com/UW-Macrostrat/web-components/compare/@macrostrat/data-sheet-v4.9.0...@macrostrat/data-sheet-v4.9.1)
4
+
5
+ ### Patch Changes
6
+
7
+ - A fill-drag ends when the mouse button is released: the anchor no longer fills
8
+ later selections, the fill is reported through `onEdit`, and shrinking a drag
9
+ restores the rows it leaves
10
+ [bdcb8223](https://github.com/UW-Macrostrat/web-components/commit/bdcb82232b87da5b1dbb922c9258b24eba66529c)
11
+
3
12
  ## [4.9.0] - 2026-09-25 [_changes_](https://github.com/UW-Macrostrat/web-components/compare/@macrostrat/data-sheet-v4.8.0...@macrostrat/data-sheet-v4.9.0)
4
13
 
5
14
  ### Minor Changes
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\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 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 columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\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 | undefined)[];\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 | null | undefined)[];\n data: 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\" | \"second-click\";\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 /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<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> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n /** The row the view starts after (see `FetchDataOptions`). Seeded into the\n * store at creation alongside `initialData`. */\n startAfter?: FetchDataOptions<T>[\"startAfter\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":";;AAmCO,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;;;;"}
1
+ {"version":3,"file":"types.cjs","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\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 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 columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\n /** The cell a fill-drag copies from, while the drag lasts. */\n fillValueBaseCell: FocusedCellCoordinates | null;\n /** The overlay as it stood when the fill-drag began. */\n fillBaseData: T[] | 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 | undefined)[];\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 | null | undefined)[];\n data: 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\" | \"second-click\";\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 /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<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 /** End a fill-drag: report the cells it wrote and disarm the anchor. */\n finishFill(): 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> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n /** The row the view starts after (see `FetchDataOptions`). Seeded into the\n * store at creation alongside `initialData`. */\n startAfter?: FetchDataOptions<T>[\"startAfter\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":";;AAmCO,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;;;;"}
@@ -102,7 +102,10 @@ export interface DataSheetState<T> {
102
102
  * suppressed — a function `columnSpec` derives it from the loaded rows
103
103
  * instead (in `_DataSheet`). Set at init from the prop's shape. */
104
104
  deferColumnSpec: boolean;
105
+ /** The cell a fill-drag copies from, while the drag lasts. */
105
106
  fillValueBaseCell: FocusedCellCoordinates | null;
107
+ /** The overlay as it stood when the fill-drag began. */
108
+ fillBaseData: T[] | null;
106
109
  focusedCell: FocusedCellCoordinates | null;
107
110
  topLeftCell: FocusedCellCoordinates | null;
108
111
  /**
@@ -191,6 +194,8 @@ export type StateUpdater<T> = T[] | ((state: T[]) => T[]);
191
194
  export interface DataSheetStoreMain<T> extends DataSheetVals<T> {
192
195
  setSelection(selection: Region[]): void;
193
196
  onDragValue(event: MouseEvent): void;
197
+ /** End a fill-drag: report the cells it wrote and disarm the anchor. */
198
+ finishFill(): void;
194
199
  setUpdatedData(data: StateUpdater<T>): void;
195
200
  onCellEdited(rowIndex: number, columnName: string, value: any): void;
196
201
  onSelectionEdited(value: any): void;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\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 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 columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\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 | undefined)[];\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 | null | undefined)[];\n data: 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\" | \"second-click\";\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 /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<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> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n /** The row the view starts after (see `FetchDataOptions`). Seeded into the\n * store at creation alongside `initialData`. */\n startAfter?: FetchDataOptions<T>[\"startAfter\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":"AAmCO,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;"}
1
+ {"version":3,"file":"types.js","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\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 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 columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\n /** The cell a fill-drag copies from, while the drag lasts. */\n fillValueBaseCell: FocusedCellCoordinates | null;\n /** The overlay as it stood when the fill-drag began. */\n fillBaseData: T[] | 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 | undefined)[];\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 | null | undefined)[];\n data: 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\" | \"second-click\";\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 /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<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 /** End a fill-drag: report the cells it wrote and disarm the anchor. */\n finishFill(): 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> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n /** The row the view starts after (see `FetchDataOptions`). Seeded into the\n * store at creation alongside `initialData`. */\n startAfter?: FetchDataOptions<T>[\"startAfter\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":"AAmCO,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;"}
@@ -21,6 +21,7 @@ function createZustandStore(set, get) {
21
21
  editable: false,
22
22
  selection: [],
23
23
  fillValueBaseCell: null,
24
+ fillBaseData: null,
24
25
  focusedCell: null,
25
26
  topLeftCell: null,
26
27
  initialized: false,
@@ -184,10 +185,20 @@ function createZustandStore(set, get) {
184
185
  });
185
186
  },
186
187
  onDragValue(event) {
187
- set((state) => {
188
- return { fillValueBaseCell: state.focusedCell };
189
- });
190
188
  event.preventDefault();
189
+ const { focusedCell, updatedData } = get();
190
+ if (focusedCell == null) return;
191
+ set({ fillValueBaseCell: focusedCell, fillBaseData: updatedData });
192
+ window.addEventListener("mouseup", () => get().finishFill(), {
193
+ once: true
194
+ });
195
+ },
196
+ finishFill() {
197
+ const state = get();
198
+ if (state.fillValueBaseCell == null) return;
199
+ const { cells } = fillSelection(state, state.selection);
200
+ set({ fillValueBaseCell: null, fillBaseData: null });
201
+ if (cells.length > 0) get().onEdit?.({ type: "setCells", cells });
191
202
  },
192
203
  onCellEdited(rowIndex, columnName, value) {
193
204
  const targetColumn = get().columnSpec.find((c) => c.key === columnName);
@@ -276,7 +287,7 @@ function createZustandStore(set, get) {
276
287
  }
277
288
  let spec = updateSelection(selection2);
278
289
  if (state.fillValueBaseCell != null) {
279
- spec.updatedData = fillValues(state, selection2);
290
+ spec.updatedData = fillSelection(state, selection2).updatedData;
280
291
  }
281
292
  spec.autoActivateArmed = true;
282
293
  spec.lastNavDirection = null;
@@ -403,9 +414,6 @@ function updateSelection(selection2) {
403
414
  focusedCell,
404
415
  topLeftCell: topLeftCell(selection2)
405
416
  };
406
- if (focusedCell != null) {
407
- spec.fillValueBaseCell = null;
408
- }
409
417
  return spec;
410
418
  }
411
419
  function getLastRowIndex(regions) {
@@ -462,30 +470,31 @@ function singleFocusedCell(sel) {
462
470
  if (sel?.length !== 1) return null;
463
471
  return topLeftCell(sel, true);
464
472
  }
465
- function fillValues(state, selection$1) {
466
- const { updatedData, columnSpec: columnSpec$1, editable, fillValueBaseCell, data } = state;
467
- let regions = selection$1.map((region) => {
468
- const { cols, rows } = region;
469
- const [col2] = cols ?? [];
470
- return { cols: [col2, col2], rows };
471
- });
472
- if (!editable || fillValueBaseCell == null) return updatedData;
473
+ function fillSelection(state, selection$1) {
474
+ const { columnSpec: columnSpec$1, editable, fillValueBaseCell, data } = state;
475
+ const baseData = state.fillBaseData ?? state.updatedData;
476
+ const noFill = { updatedData: state.updatedData, cells: [] };
477
+ if (!editable || fillValueBaseCell == null) return noFill;
473
478
  const { col, row: baseVisibleRow } = fillValueBaseCell;
474
- if (!columnSpec.isColumnWritable(columnSpec$1[col], editable)) return updatedData;
479
+ if (!columnSpec.isColumnWritable(columnSpec$1[col], editable)) return noFill;
475
480
  const baseRow = toDataRowIndex(state, baseVisibleRow);
476
481
  const key = columnSpec$1[col].key;
477
- const value = updatedData[baseRow]?.[key] ?? data[baseRow]?.[key];
482
+ const value = baseData[baseRow]?.[key] ?? data[baseRow]?.[key];
478
483
  const spec = {};
479
- for (const region of regions) {
480
- const { rows } = region;
481
- for (const visibleRow of selection.range(rows ?? [])) {
484
+ const cells = [];
485
+ for (const region of selection$1) {
486
+ for (const visibleRow of selection.range(region.rows ?? [])) {
482
487
  const row = toDataRowIndex(state, visibleRow);
488
+ if (row === baseRow) continue;
483
489
  if (state.rowStatus[row] === types.TableElementStatus.DELETED) continue;
484
- let op = updatedData[row] == null ? "$set" : "$merge";
490
+ const current = baseData[row]?.[key] ?? data[row]?.[key];
491
+ if (valuesAreEquivalent(value, current)) continue;
492
+ let op = baseData[row] == null ? "$set" : "$merge";
485
493
  spec[row] = { [op]: { [key]: value } };
494
+ cells.push({ rowIndex: row, column: key, value, row: data[row] });
486
495
  }
487
496
  }
488
- return update__default.default(updatedData, spec);
497
+ return { updatedData: update__default.default(baseData, spec), cells };
489
498
  }
490
499
  function visibleRowCount(state) {
491
500
  const { filteredRowIndices, updatedData, data } = state;
@@ -1 +1 @@
1
- {"version":3,"file":"zustand-store.cjs","sources":["../../src/provider/zustand-store.ts"],"sourcesContent":["import {\n DataSheetState,\n DataSheetStore,\n DataSheetStoreMain,\n DEFAULT_ROW_STATUS_STYLES,\n DS_ROW_ID,\n StateUpdater,\n TableElementStatus,\n} from \"./types.ts\";\nimport {\n type FocusedCellCoordinates,\n type Region,\n RegionCardinality,\n} from \"@blueprintjs/table\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n getSelectedColumnKeys,\n getSelectedRowIndices,\n getSelectionCardinality,\n range,\n} from \"../actions\";\nimport { isColumnWritable } from \"./column-spec.ts\";\n\n/** Monotonic counter for synthetic ids on in-table-added rows. */\nlet _addedRowCounter = 0;\n\nexport function createZustandStore<T>(set, get): DataSheetStoreMain<T> {\n return {\n /** All the data in the table */\n data: [],\n updatedData: [],\n rowStatus: [],\n rowStatusStyles: DEFAULT_ROW_STATUS_STYLES,\n columnSpec: [],\n deferColumnSpec: false,\n defaultColumnWidth: 150,\n editable: false,\n selection: [],\n fillValueBaseCell: null,\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef: null,\n // This is a placeholder\n enableColumnReordering: false,\n activeFilters: new Map<string, { filter: any; state: any }>(),\n columnSorts: [],\n clipboardProxy: null,\n filteredRowIndices: null,\n cellInteraction: \"auto\",\n autoActivateArmed: true,\n lastNavDirection: null,\n tableElement: null,\n cellSurfaceOpen: false,\n identity: (row: any) => row?.id,\n pendingOverlayById: new Map(),\n controlledOverlay: false,\n canDeleteRows: true,\n setSelection(selection: Region[]) {\n set(updateSelection(selection));\n },\n columnWidthsIndex: new Map<string, number>(),\n suppressAutoActivate() {\n set({ autoActivateArmed: false });\n },\n armAutoActivate() {\n set({ autoActivateArmed: true });\n },\n openCellSurface() {\n set({ cellSurfaceOpen: true });\n },\n closeCellSurface(opts?: { suppress?: boolean }) {\n const suppress = opts?.suppress ?? true;\n set((state) => ({\n cellSurfaceOpen: false,\n // Escape (suppress) drops auto mode into navigation mode so surfaces\n // stop auto-opening until the next click. A click-dismiss doesn't.\n autoActivateArmed:\n suppress && state.cellInteraction === \"auto\"\n ? false\n : state.autoActivateArmed,\n }));\n },\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\") {\n set((state) => {\n const { topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col, row } = topLeftCell;\n switch (direction) {\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(\n row + 1,\n Math.max(state.data.length, state.updatedData.length) - 1,\n );\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region: Region = { cols: [col, col], rows: [row, row] };\n // Record the travel direction (so the next editor places its cursor on\n // the side we're moving toward) and open the new cell's surface only\n // when auto-activation is armed.\n return {\n ...updateSelection([region]),\n lastNavDirection: direction,\n cellSurfaceOpen:\n state.cellInteraction === \"auto\" && state.autoActivateArmed,\n };\n });\n },\n addRow(row: Partial<T> = {} as T) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */\n let newIndex = -1;\n set((state) => {\n const { updatedData, data, selection, rowStatus } = state;\n\n const lastRowIndex =\n getLastRowIndex(selection) ??\n Math.max(data.length, updatedData.length) - 1;\n // Use $set at a specific index to correctly extend the sparse array.\n // $splice fails when the target index exceeds the array length.\n newIndex = lastRowIndex + 1;\n\n // Stamp a stable synthetic id so the added row survives a provider\n // re-fetch (it has no provider row to match on). Its values live in the\n // overlay (`updatedData`), which the loader-boundary remap re-appends.\n const newRow = {\n ...(row as any),\n [DS_ROW_ID]: `__added_${_addedRowCounter++}`,\n } as T;\n\n return {\n updatedData: insertItemAtIndex(updatedData, newIndex, newRow),\n data: insertItemAtIndex(data, newIndex, newRow),\n rowStatus: insertItemAtIndex(\n rowStatus,\n newIndex,\n TableElementStatus.ADDED,\n ),\n };\n });\n get().onEdit?.({ type: \"addRow\", rowIndex: newIndex, value: row });\n },\n setUpdatedData(data: StateUpdater<T>) {\n if (Array.isArray(data)) {\n set({ updatedData: data });\n } else {\n set((state) => {\n return { updatedData: data(state.updatedData) };\n });\n }\n },\n deleteSelectedRows() {\n // Deletion is a provider capability: if the active data provider can't\n // delete (no `deleteRows`), the whole affordance is disabled.\n if (!get().canDeleteRows) return;\n // Remove selected rows from the data and updatedData arrays\n let deletedIndices: number[] = [];\n set((state) => {\n const { selection, deletedRows } = state;\n const rowIndices = getRowIndices(selection);\n deletedIndices = rowIndices;\n\n // Delete rows from both updatedData and data\n\n // If rows are in addedRows, we just delete them outright from the data and updatedData arrays\n const { addedRows } = state;\n\n const rowsNewlyDeleted = new Set(rowIndices);\n\n // We outright remove rows that have not been added to the data array\n const rowsToRemoveFromDataArrays = new Set(\n rowIndices.filter(\n (d) => state.rowStatus[d] == TableElementStatus.ADDED,\n ),\n );\n // ...otherwise we set them to 'deleted'\n const rowsToMarkAsDeleted = rowsNewlyDeleted.difference(\n rowsToRemoveFromDataArrays,\n );\n\n let data = state.data;\n let updatedData = state.updatedData;\n let rowStatus = state.rowStatus;\n if (rowsToMarkAsDeleted.size > 0) {\n let spec: Spec<TableElementStatus[]> = {};\n for (const ix of rowsToMarkAsDeleted) {\n spec[ix] = { $set: TableElementStatus.DELETED };\n }\n rowStatus = update(rowStatus, spec);\n }\n\n if (rowsToRemoveFromDataArrays.size > 0) {\n const filterFunc = (_, i) => !rowsToRemoveFromDataArrays.has(i);\n data = data.filter(filterFunc);\n updatedData = updatedData.filter(filterFunc);\n rowStatus = rowStatus.filter(filterFunc);\n }\n\n // Remove selected rows and reset selection\n return {\n selection: [],\n data,\n updatedData,\n rowStatus,\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n });\n if (deletedIndices.length > 0) {\n get().onEdit?.({ type: \"deleteRows\", rowIndices: deletedIndices });\n }\n },\n resetChanges(regions?: Region[]) {\n // Reset the updated data to the initial data\n set((state) => resetChangesForSelection(state, regions ?? []));\n get().onEdit?.({ type: \"resetChanges\" });\n },\n onColumnWidthChanged(columnIx: number, newWidth: number) {\n set((state) => {\n const { columnSpec, columnWidthsIndex } = state;\n const colKey = columnSpec[columnIx].key;\n const newColumnWidths = new Map(columnWidthsIndex);\n newColumnWidths.set(colKey, newWidth);\n return { columnWidthsIndex: newColumnWidths };\n });\n },\n onDragValue(event: MouseEvent) {\n set((state) => {\n return { fillValueBaseCell: state.focusedCell };\n });\n event.preventDefault();\n },\n onCellEdited(rowIndex: number, columnName: string, value: any) {\n // The column decides whether it takes writes (see `isColumnWritable`):\n // a locked or derived column is refused here as well as in the cell\n // renderer, so a programmatic caller — the row editor, say — can't\n // write what the grid wouldn't let you type.\n const targetColumn = get().columnSpec.find((c) => c.key === columnName);\n if (!isColumnWritable(targetColumn, get().editable)) return;\n set((state) => {\n const { editable, updatedData, data } = state;\n if (!editable) return {};\n let rowSpec: any;\n\n // Check to see if the new value is meaningfully different from the old\n // one. Empty string and null/undefined are treated as equivalent, so\n // focusing (and blurring) an empty cell doesn't record a phantom edit.\n const oldValue = data[rowIndex]?.[columnName];\n if (!valuesAreEquivalent(value, oldValue)) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = { [rowOp]: { [columnName]: value } };\n } else if (updatedData[rowIndex] != null) {\n // No change — drop any prior override for this cell.\n rowSpec = { $unset: [columnName] };\n } else {\n // No change and no prior override: nothing to do. (`$unset` on an\n // absent row would throw in immutability-helper.)\n return {};\n }\n const spec: Spec<T[]> = { [rowIndex]: rowSpec };\n return { updatedData: update(updatedData, spec) };\n });\n if (get().editable) {\n get().onEdit?.({\n type: \"setCells\",\n cells: [\n { rowIndex, column: columnName, value, row: get().data[rowIndex] },\n ],\n });\n }\n },\n clearSelection() {\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n // Delete all selected cells\n const { selection, updatedData, columnSpec, data } = state;\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // Don't clear row if it has been deleted\n const rowIsDeleted =\n state.rowStatus[row] === TableElementStatus.DELETED;\n if (rowIsDeleted) continue;\n let vals = {};\n for (const col of colRange) {\n // A locked or derived column is never cleared\n if (!isColumnWritable(columnSpec[col], state.editable)) continue;\n const key = columnSpec[col].key;\n const currentValue = updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") {\n vals[key] = \"\";\n edits.push({\n rowIndex: row,\n column: key,\n value: \"\",\n row: data[row],\n });\n }\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onSelection(selection: Region[]) {\n set((state) => {\n const isSameAsPrevSelection = selectionEquals(\n selection,\n state.selection,\n );\n if (\n isSameAsPrevSelection &&\n singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode\n ) {\n // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n cellSurfaceOpen: false,\n };\n }\n\n let spec = updateSelection(selection);\n if (state.fillValueBaseCell != null) {\n spec.updatedData = fillValues(state, selection);\n }\n // A click (user selection) re-arms auto-activation and clears the\n // travel direction so the editor opens with a default cursor.\n spec.autoActivateArmed = true;\n spec.lastNavDirection = null;\n // Only open when the selection actually MOVES to a (single) cell.\n // A click on the already-selected cell leaves open-state to the\n // target's click toggle — this avoids racing the selection event\n // (which fires on mousedown, possibly more than once) and is what\n // makes both re-focus-to-open and click-to-close reliable.\n // In \"second-click\" mode a new selection only selects; the click on\n // the already-selected cell opens it.\n if (!selectionEquals(selection, state.selection)) {\n spec.cellSurfaceOpen =\n state.cellInteraction !== \"second-click\" &&\n singleFocusedCell(selection) != null;\n }\n return spec;\n });\n },\n onSelectionEdited(value: any) {\n // Apply the same value to all selected cells\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n const { selection, updatedData, columnSpec, editable } = state;\n if (!editable) return {};\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // A deleted row takes no edits\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n let vals = {};\n for (const col of colRange) {\n // Only the columns that take writes — a selection spanning a\n // locked or derived column writes around it\n if (!isColumnWritable(columnSpec[col], editable)) continue;\n const key = columnSpec[col].key;\n vals[key] = value;\n edits.push({\n rowIndex: row,\n column: key,\n value,\n row: state.data[row],\n });\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onColumnsReordered(oldIndex: number, newIndex: number, length: number) {\n set((state) => {\n if (!state.enableColumnReordering) return {};\n const { columnSpec } = state;\n const newSpec = [...columnSpec];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return { columnSpec: newSpec };\n });\n },\n scrollToRow(rowIndex: number) {\n const tableRef = get().tableRef;\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [rowIndex, rowIndex],\n });\n },\n // Sort/filter state changes flow to the data provider (via the loader,\n // which reads `activeFilters`/`columnSorts` and re-fetches). The library no\n // longer computes a client-side `filteredRowIndices` view — `data` arrives\n // already ordered from the provider (in memory for a local source).\n setFilter(filterId: string, filter: any, filterState: any) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.set(filterId, { filter, state: filterState });\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n removeFilter(filterId: string) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.delete(filterId);\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n clearFilters() {\n set((state) => ({\n activeFilters: new Map<string, { filter: any; state: any }>(),\n ...dropRowSelection(state),\n }));\n },\n setColumnSort(key: string, ascending: boolean | null) {\n set((state) => {\n let newSorts;\n if (ascending == null) {\n newSorts = state.columnSorts.filter((s) => s.key !== key);\n } else {\n const without = state.columnSorts.filter((s) => s.key !== key);\n newSorts = [...without, { key, ascending }];\n }\n return { columnSorts: newSorts, ...dropRowSelection(state) };\n });\n },\n clearColumnSorts() {\n set((state) => ({ columnSorts: [], ...dropRowSelection(state) }));\n },\n setClipboardProxy(proxy) {\n set({ clipboardProxy: proxy });\n },\n };\n}\n\n/**\n * Drop the parts of a selection that are addressed by **row index**, because a\n * filter or sort change re-orders and re-filters the rows underneath them —\n * \"rows 3–5\" then means different records, and a set-action would silently act\n * on the wrong ones. Column selections are index-stable under a view change, so\n * they survive (and must: the sheet's sort/filter controls are themselves\n * column-scoped, and are invoked *from* that selection).\n */\nfunction dropRowSelection<T>(\n state: DataSheetState<T>,\n): Partial<DataSheetState<T>> {\n const selection = state.selection ?? [];\n const kept = selection.filter((region) => region.rows == null);\n if (kept.length === selection.length) return {};\n return { selection: kept, focusedCell: null, topLeftCell: null };\n}\n\nexport function updateSelection<T>(selection: Region[]) {\n const focusedCell = singleFocusedCell(selection);\n let spec: Partial<DataSheetState<T>> = {\n selection,\n focusedCell,\n topLeftCell: topLeftCell(selection),\n };\n if (focusedCell != null) {\n spec.fillValueBaseCell = null;\n }\n return spec;\n}\n\nfunction getLastRowIndex(regions: Region[]): number | null {\n /** Get the last row index from a selection of regions */\n if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) {\n /** If no valid rows are found, return null */\n return null;\n }\n return lastRow;\n}\n\nfunction getRowIndices(regions: Region[]): number[] {\n /** Get the row indices from a selection of regions */\n if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set<number>();\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for (let i = rows[0]; i <= rows[1]; i++) {\n rowIndices.add(i);\n }\n }\n return Array.from(rowIndices).sort((a, b) => a - b);\n}\n\nexport function topLeftCell(\n regions: Region[],\n requireSolitaryCell: boolean = false,\n): FocusedCellCoordinates | null {\n /** Top left cell of a ranged selection */\n if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols, rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))\n return null;\n return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };\n}\n\nfunction selectionEquals(a: Region[], b: Region[]): boolean {\n /** Check if two selections are equal */\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const regionA = a[i];\n const regionB = b[i];\n\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n\n if (\n colsA.length !== colsB.length ||\n rowsA.length !== rowsB.length ||\n colsA[0] !== colsB[0] ||\n colsA[1] !== colsB[1] ||\n rowsA[0] !== rowsB[0] ||\n rowsA[1] !== rowsB[1]\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function singleFocusedCell(\n sel: Region[],\n): FocusedCellCoordinates | null {\n /** Derive a single focused cell from a selected region, if possible */\n if (sel?.length !== 1) return null;\n return topLeftCell(sel, true);\n}\n\nfunction fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {\n const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;\n\n // Prepare regions by unnesting columns\n let regions = selection.map((region) => {\n const { cols, rows } = region;\n // Get the first column (maybe should be the last)\n const [col] = cols ?? [];\n return { cols: [col, col], rows };\n });\n\n // Fill values downwards\n if (!editable || fillValueBaseCell == null) return updatedData;\n const { col, row: baseVisibleRow } = fillValueBaseCell;\n // Dragging from a locked or derived column fills nothing\n if (!isColumnWritable(columnSpec[col], editable)) return updatedData;\n // The base cell and target rows are visible positions; map to data rows.\n const baseRow = toDataRowIndex(state, baseVisibleRow);\n const key = columnSpec[col].key;\n const value = updatedData[baseRow]?.[key] ?? data[baseRow]?.[key];\n const spec = {};\n for (const region of regions) {\n const { rows } = region;\n for (const visibleRow of range(rows ?? [])) {\n const row = toDataRowIndex(state, visibleRow);\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: { [key]: value } };\n }\n }\n return update(updatedData, spec);\n}\n\n/** Number of rows currently visible (post-filter/sort), or the full data\n * length when no view transform is active. Uses the max of `data` and\n * `updatedData` lengths because `updatedData` is sparse — keying off it alone\n * would stop a whole-column edit at the last already-edited row. */\nfunction visibleRowCount<T>(state: DataSheetStore<T>): number {\n const { filteredRowIndices, updatedData, data } = state;\n return filteredRowIndices != null\n ? filteredRowIndices.length\n : Math.max(data.length, updatedData.length);\n}\n\n/** Map a visible (post-filter/sort) row position to its underlying data\n * index. Edit methods receive selection indices in visible space, so they\n * must translate before writing to `updatedData`/`data`. */\nfunction toDataRowIndex<T>(\n state: DataSheetStore<T>,\n visibleRow: number,\n): number {\n const { filteredRowIndices } = state;\n if (filteredRowIndices == null) return visibleRow;\n return filteredRowIndices[visibleRow] ?? visibleRow;\n}\n\n/** Whether two cell values are equivalent for edit-tracking. Empty string and\n * null/undefined are equivalent (so clearing an empty cell is a no-op), and\n * non-blank values are compared by string form so a text editor's `\"42\"`\n * matches a numeric base `42` (otherwise the cell reads as edited when its\n * value didn't actually change). */\nfunction valuesAreEquivalent(a: any, b: any): boolean {\n if (a === b) return true;\n const aBlank = a == null || a === \"\";\n const bBlank = b == null || b === \"\";\n if (aBlank || bBlank) return aBlank && bBlank;\n // Structured values (an interval position, a list of lithologies) compare\n // by content: as strings, every object is \"[object Object]\", so any edit\n // to one — or to a list that keeps its length — read as no change\n if (typeof a === \"object\" || typeof b === \"object\") {\n return JSON.stringify(a) === JSON.stringify(b);\n }\n return String(a) === String(b);\n}\n\nfunction resetChangesForSelection<T>(\n state: DataSheetStore<T>,\n selection: Region[],\n): Partial<DataSheetStore<T>> {\n const emptySelection = {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n\n const { data } = state;\n const cardinality =\n getSelectionCardinality(selection ?? []) ?? RegionCardinality.FULL_TABLE;\n\n const rowStatus = [...state.rowStatus];\n const updatedData = [...state.updatedData];\n const addedRows = new Set<number>();\n\n // Global reset\n switch (cardinality) {\n case RegionCardinality.FULL_TABLE:\n for (let i = 0; i < rowStatus.length; i++) {\n if (rowStatus[i] === TableElementStatus.ADDED) {\n addedRows.add(i);\n }\n }\n\n return {\n updatedData: [],\n rowStatus: [],\n data: data.filter((_, i) => !addedRows.has(i)),\n ...emptySelection,\n };\n case RegionCardinality.FULL_COLUMNS:\n case RegionCardinality.CELLS:\n /** Columns or cells. Note, these only work the same because we don't\n * allow column deletion, only unsetting all values.\n */\n const columnKeys = getSelectedColumnKeys(selection, state.columnSpec);\n const spec: Spec<Record<string, any>[]> = {};\n const rowIndices =\n cardinality == RegionCardinality.FULL_COLUMNS\n ? Array.from({ length: updatedData.length }, (_, i) => i)\n : getSelectedRowIndices(selection);\n for (const row of rowIndices) {\n if (updatedData[row] == null) continue;\n spec[row] = { $unset: columnKeys };\n }\n // TODO: if we allow column addition/deletion, this will require more adjustment\n return {\n updatedData: update(updatedData, spec as any),\n ...emptySelection,\n };\n case RegionCardinality.FULL_ROWS:\n for (const row of getSelectedRowIndices(selection)) {\n updatedData[row] = undefined;\n if (state.rowStatus[row] === TableElementStatus.DELETED) {\n rowStatus[row] = undefined;\n } else if (state.rowStatus[row] === TableElementStatus.ADDED) {\n addedRows.add(row);\n }\n }\n\n const removeCandidateRows = (arr: any[]) => {\n return arr.filter((d, i) => !addedRows.has(i));\n };\n\n return {\n updatedData: removeCandidateRows(updatedData),\n data: removeCandidateRows(state.data),\n rowStatus: removeCandidateRows(rowStatus),\n ...emptySelection,\n };\n }\n}\n\nfunction insertItemAtIndex<T>(arr: T[], index: number, item: T) {\n if (arr.length < index) {\n const newArr = [...arr];\n newArr.length = index;\n newArr[index] = item;\n return newArr;\n }\n\n return [...arr.slice(0, index), item, ...arr.slice(index)];\n}\n"],"names":["DEFAULT_ROW_STATUS_STYLES","selection","topLeftCell","DS_ROW_ID","TableElementStatus","update","columnSpec","isColumnWritable","range","col","getSelectionCardinality","RegionCardinality","getSelectedColumnKeys","getSelectedRowIndices"],"mappings":";;;;;;;;;AAwBA,IAAI,mBAAmB;AAEhB,SAAS,mBAAsB,KAAK,KAA4B;AACrE,SAAO;AAAA;AAAA,IAEL,MAAM,CAAA;AAAA,IACN,aAAa,CAAA;AAAA,IACb,WAAW,CAAA;AAAA,IACX,iBAAiBA,MAAAA;AAAAA,IACjB,YAAY,CAAA;AAAA,IACZ,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,UAAU;AAAA,IACV,WAAW,CAAA;AAAA,IACX,mBAAmB;AAAA,IACnB,aAAa;AAAA,IACb,aAAa;AAAA,IACb,aAAa;AAAA,IACb,UAAU;AAAA;AAAA,IAEV,wBAAwB;AAAA,IACxB,mCAAmB,IAAA;AAAA,IACnB,aAAa,CAAA;AAAA,IACb,gBAAgB;AAAA,IAChB,oBAAoB;AAAA,IACpB,iBAAiB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,iBAAiB;AAA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AAC,IACtDE,UAAAA,sBAAsBZ,WAAS;AACrC,iBAAW,OAAO,YAAY;AAC5B,YAAI,YAAY,GAAG,KAAK,KAAM;AAC9B,aAAK,GAAG,IAAI,EAAE,QAAQ,WAAA;AAAA,MACxB;AAEA,aAAO;AAAA,QACL,aAAaI,gBAAAA,QAAO,aAAa,IAAW;AAAA,QAC5C,GAAG;AAAA,MAAA;AAAA,IAEP,KAAKM,MAAAA,kBAAkB;AACrB,iBAAW,OAAOE,gCAAsBZ,WAAS,GAAG;AAClD,oBAAY,GAAG,IAAI;AACnB,YAAI,MAAM,UAAU,GAAG,MAAMG,MAAAA,mBAAmB,SAAS;AACvD,oBAAU,GAAG,IAAI;AAAA,QACnB,WAAW,MAAM,UAAU,GAAG,MAAMA,MAAAA,mBAAmB,OAAO;AAC5D,oBAAU,IAAI,GAAG;AAAA,QACnB;AAAA,MACF;AAEA,YAAM,sBAAsB,CAAC,QAAe;AAC1C,eAAO,IAAI,OAAO,CAAC,GAAG,MAAM,CAAC,UAAU,IAAI,CAAC,CAAC;AAAA,MAC/C;AAEA,aAAO;AAAA,QACL,aAAa,oBAAoB,WAAW;AAAA,QAC5C,MAAM,oBAAoB,MAAM,IAAI;AAAA,QACpC,WAAW,oBAAoB,SAAS;AAAA,QACxC,GAAG;AAAA,MAAA;AAAA,EACL;AAEN;AAEA,SAAS,kBAAqB,KAAU,OAAe,MAAS;AAC9D,MAAI,IAAI,SAAS,OAAO;AACtB,UAAM,SAAS,CAAC,GAAG,GAAG;AACtB,WAAO,SAAS;AAChB,WAAO,KAAK,IAAI;AAChB,WAAO;AAAA,EACT;AAEA,SAAO,CAAC,GAAG,IAAI,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,IAAI,MAAM,KAAK,CAAC;AAC3D;;;;;"}
1
+ {"version":3,"file":"zustand-store.cjs","sources":["../../src/provider/zustand-store.ts"],"sourcesContent":["import {\n CellEdit,\n DataSheetState,\n DataSheetStore,\n DataSheetStoreMain,\n DEFAULT_ROW_STATUS_STYLES,\n DS_ROW_ID,\n StateUpdater,\n TableElementStatus,\n} from \"./types.ts\";\nimport {\n type FocusedCellCoordinates,\n type Region,\n RegionCardinality,\n} from \"@blueprintjs/table\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n getSelectedColumnKeys,\n getSelectedRowIndices,\n getSelectionCardinality,\n range,\n} from \"../actions\";\nimport { isColumnWritable } from \"./column-spec.ts\";\n\n/** Monotonic counter for synthetic ids on in-table-added rows. */\nlet _addedRowCounter = 0;\n\nexport function createZustandStore<T>(set, get): DataSheetStoreMain<T> {\n return {\n /** All the data in the table */\n data: [],\n updatedData: [],\n rowStatus: [],\n rowStatusStyles: DEFAULT_ROW_STATUS_STYLES,\n columnSpec: [],\n deferColumnSpec: false,\n defaultColumnWidth: 150,\n editable: false,\n selection: [],\n fillValueBaseCell: null,\n fillBaseData: null,\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef: null,\n // This is a placeholder\n enableColumnReordering: false,\n activeFilters: new Map<string, { filter: any; state: any }>(),\n columnSorts: [],\n clipboardProxy: null,\n filteredRowIndices: null,\n cellInteraction: \"auto\",\n autoActivateArmed: true,\n lastNavDirection: null,\n tableElement: null,\n cellSurfaceOpen: false,\n identity: (row: any) => row?.id,\n pendingOverlayById: new Map(),\n controlledOverlay: false,\n canDeleteRows: true,\n setSelection(selection: Region[]) {\n set(updateSelection(selection));\n },\n columnWidthsIndex: new Map<string, number>(),\n suppressAutoActivate() {\n set({ autoActivateArmed: false });\n },\n armAutoActivate() {\n set({ autoActivateArmed: true });\n },\n openCellSurface() {\n set({ cellSurfaceOpen: true });\n },\n closeCellSurface(opts?: { suppress?: boolean }) {\n const suppress = opts?.suppress ?? true;\n set((state) => ({\n cellSurfaceOpen: false,\n // Escape (suppress) drops auto mode into navigation mode so surfaces\n // stop auto-opening until the next click. A click-dismiss doesn't.\n autoActivateArmed:\n suppress && state.cellInteraction === \"auto\"\n ? false\n : state.autoActivateArmed,\n }));\n },\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\") {\n set((state) => {\n const { topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col, row } = topLeftCell;\n switch (direction) {\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(\n row + 1,\n Math.max(state.data.length, state.updatedData.length) - 1,\n );\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region: Region = { cols: [col, col], rows: [row, row] };\n // Record the travel direction (so the next editor places its cursor on\n // the side we're moving toward) and open the new cell's surface only\n // when auto-activation is armed.\n return {\n ...updateSelection([region]),\n lastNavDirection: direction,\n cellSurfaceOpen:\n state.cellInteraction === \"auto\" && state.autoActivateArmed,\n };\n });\n },\n addRow(row: Partial<T> = {} as T) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */\n let newIndex = -1;\n set((state) => {\n const { updatedData, data, selection, rowStatus } = state;\n\n const lastRowIndex =\n getLastRowIndex(selection) ??\n Math.max(data.length, updatedData.length) - 1;\n // Use $set at a specific index to correctly extend the sparse array.\n // $splice fails when the target index exceeds the array length.\n newIndex = lastRowIndex + 1;\n\n // Stamp a stable synthetic id so the added row survives a provider\n // re-fetch (it has no provider row to match on). Its values live in the\n // overlay (`updatedData`), which the loader-boundary remap re-appends.\n const newRow = {\n ...(row as any),\n [DS_ROW_ID]: `__added_${_addedRowCounter++}`,\n } as T;\n\n return {\n updatedData: insertItemAtIndex(updatedData, newIndex, newRow),\n data: insertItemAtIndex(data, newIndex, newRow),\n rowStatus: insertItemAtIndex(\n rowStatus,\n newIndex,\n TableElementStatus.ADDED,\n ),\n };\n });\n get().onEdit?.({ type: \"addRow\", rowIndex: newIndex, value: row });\n },\n setUpdatedData(data: StateUpdater<T>) {\n if (Array.isArray(data)) {\n set({ updatedData: data });\n } else {\n set((state) => {\n return { updatedData: data(state.updatedData) };\n });\n }\n },\n deleteSelectedRows() {\n // Deletion is a provider capability: if the active data provider can't\n // delete (no `deleteRows`), the whole affordance is disabled.\n if (!get().canDeleteRows) return;\n // Remove selected rows from the data and updatedData arrays\n let deletedIndices: number[] = [];\n set((state) => {\n const { selection, deletedRows } = state;\n const rowIndices = getRowIndices(selection);\n deletedIndices = rowIndices;\n\n // Delete rows from both updatedData and data\n\n // If rows are in addedRows, we just delete them outright from the data and updatedData arrays\n const { addedRows } = state;\n\n const rowsNewlyDeleted = new Set(rowIndices);\n\n // We outright remove rows that have not been added to the data array\n const rowsToRemoveFromDataArrays = new Set(\n rowIndices.filter(\n (d) => state.rowStatus[d] == TableElementStatus.ADDED,\n ),\n );\n // ...otherwise we set them to 'deleted'\n const rowsToMarkAsDeleted = rowsNewlyDeleted.difference(\n rowsToRemoveFromDataArrays,\n );\n\n let data = state.data;\n let updatedData = state.updatedData;\n let rowStatus = state.rowStatus;\n if (rowsToMarkAsDeleted.size > 0) {\n let spec: Spec<TableElementStatus[]> = {};\n for (const ix of rowsToMarkAsDeleted) {\n spec[ix] = { $set: TableElementStatus.DELETED };\n }\n rowStatus = update(rowStatus, spec);\n }\n\n if (rowsToRemoveFromDataArrays.size > 0) {\n const filterFunc = (_, i) => !rowsToRemoveFromDataArrays.has(i);\n data = data.filter(filterFunc);\n updatedData = updatedData.filter(filterFunc);\n rowStatus = rowStatus.filter(filterFunc);\n }\n\n // Remove selected rows and reset selection\n return {\n selection: [],\n data,\n updatedData,\n rowStatus,\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n });\n if (deletedIndices.length > 0) {\n get().onEdit?.({ type: \"deleteRows\", rowIndices: deletedIndices });\n }\n },\n resetChanges(regions?: Region[]) {\n // Reset the updated data to the initial data\n set((state) => resetChangesForSelection(state, regions ?? []));\n get().onEdit?.({ type: \"resetChanges\" });\n },\n onColumnWidthChanged(columnIx: number, newWidth: number) {\n set((state) => {\n const { columnSpec, columnWidthsIndex } = state;\n const colKey = columnSpec[columnIx].key;\n const newColumnWidths = new Map(columnWidthsIndex);\n newColumnWidths.set(colKey, newWidth);\n return { columnWidthsIndex: newColumnWidths };\n });\n },\n onDragValue(event: MouseEvent) {\n event.preventDefault();\n const { focusedCell, updatedData } = get();\n if (focusedCell == null) return;\n // The fill is drawn from the overlay as it stood when the drag began, so\n // shrinking the drag takes back the rows it leaves.\n set({ fillValueBaseCell: focusedCell, fillBaseData: updatedData });\n // A fill belongs to its drag alone, and the drag ends when the button is\n // released, wherever that is. Left armed, the anchor would fill every\n // later selection that isn't a single cell — a row picked by its header,\n // say — with the anchor's value.\n window.addEventListener(\"mouseup\", () => get().finishFill(), {\n once: true,\n });\n },\n finishFill() {\n const state = get();\n if (state.fillValueBaseCell == null) return;\n const { cells } = fillSelection(state, state.selection);\n set({ fillValueBaseCell: null, fillBaseData: null });\n // Reported like any other write, so a consumer that holds the edits\n // (a controlled overlay) records the fill rather than having it drawn\n // once and then overwritten.\n if (cells.length > 0) get().onEdit?.({ type: \"setCells\", cells });\n },\n onCellEdited(rowIndex: number, columnName: string, value: any) {\n // The column decides whether it takes writes (see `isColumnWritable`):\n // a locked or derived column is refused here as well as in the cell\n // renderer, so a programmatic caller — the row editor, say — can't\n // write what the grid wouldn't let you type.\n const targetColumn = get().columnSpec.find((c) => c.key === columnName);\n if (!isColumnWritable(targetColumn, get().editable)) return;\n set((state) => {\n const { editable, updatedData, data } = state;\n if (!editable) return {};\n let rowSpec: any;\n\n // Check to see if the new value is meaningfully different from the old\n // one. Empty string and null/undefined are treated as equivalent, so\n // focusing (and blurring) an empty cell doesn't record a phantom edit.\n const oldValue = data[rowIndex]?.[columnName];\n if (!valuesAreEquivalent(value, oldValue)) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = { [rowOp]: { [columnName]: value } };\n } else if (updatedData[rowIndex] != null) {\n // No change — drop any prior override for this cell.\n rowSpec = { $unset: [columnName] };\n } else {\n // No change and no prior override: nothing to do. (`$unset` on an\n // absent row would throw in immutability-helper.)\n return {};\n }\n const spec: Spec<T[]> = { [rowIndex]: rowSpec };\n return { updatedData: update(updatedData, spec) };\n });\n if (get().editable) {\n get().onEdit?.({\n type: \"setCells\",\n cells: [\n { rowIndex, column: columnName, value, row: get().data[rowIndex] },\n ],\n });\n }\n },\n clearSelection() {\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n // Delete all selected cells\n const { selection, updatedData, columnSpec, data } = state;\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // Don't clear row if it has been deleted\n const rowIsDeleted =\n state.rowStatus[row] === TableElementStatus.DELETED;\n if (rowIsDeleted) continue;\n let vals = {};\n for (const col of colRange) {\n // A locked or derived column is never cleared\n if (!isColumnWritable(columnSpec[col], state.editable)) continue;\n const key = columnSpec[col].key;\n const currentValue = updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") {\n vals[key] = \"\";\n edits.push({\n rowIndex: row,\n column: key,\n value: \"\",\n row: data[row],\n });\n }\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onSelection(selection: Region[]) {\n set((state) => {\n const isSameAsPrevSelection = selectionEquals(\n selection,\n state.selection,\n );\n if (\n isSameAsPrevSelection &&\n singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode\n ) {\n // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n cellSurfaceOpen: false,\n };\n }\n\n let spec = updateSelection(selection);\n if (state.fillValueBaseCell != null) {\n spec.updatedData = fillSelection(state, selection).updatedData;\n }\n // A click (user selection) re-arms auto-activation and clears the\n // travel direction so the editor opens with a default cursor.\n spec.autoActivateArmed = true;\n spec.lastNavDirection = null;\n // Only open when the selection actually MOVES to a (single) cell.\n // A click on the already-selected cell leaves open-state to the\n // target's click toggle — this avoids racing the selection event\n // (which fires on mousedown, possibly more than once) and is what\n // makes both re-focus-to-open and click-to-close reliable.\n // In \"second-click\" mode a new selection only selects; the click on\n // the already-selected cell opens it.\n if (!selectionEquals(selection, state.selection)) {\n spec.cellSurfaceOpen =\n state.cellInteraction !== \"second-click\" &&\n singleFocusedCell(selection) != null;\n }\n return spec;\n });\n },\n onSelectionEdited(value: any) {\n // Apply the same value to all selected cells\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n const { selection, updatedData, columnSpec, editable } = state;\n if (!editable) return {};\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // A deleted row takes no edits\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n let vals = {};\n for (const col of colRange) {\n // Only the columns that take writes — a selection spanning a\n // locked or derived column writes around it\n if (!isColumnWritable(columnSpec[col], editable)) continue;\n const key = columnSpec[col].key;\n vals[key] = value;\n edits.push({\n rowIndex: row,\n column: key,\n value,\n row: state.data[row],\n });\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onColumnsReordered(oldIndex: number, newIndex: number, length: number) {\n set((state) => {\n if (!state.enableColumnReordering) return {};\n const { columnSpec } = state;\n const newSpec = [...columnSpec];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return { columnSpec: newSpec };\n });\n },\n scrollToRow(rowIndex: number) {\n const tableRef = get().tableRef;\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [rowIndex, rowIndex],\n });\n },\n // Sort/filter state changes flow to the data provider (via the loader,\n // which reads `activeFilters`/`columnSorts` and re-fetches). The library no\n // longer computes a client-side `filteredRowIndices` view — `data` arrives\n // already ordered from the provider (in memory for a local source).\n setFilter(filterId: string, filter: any, filterState: any) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.set(filterId, { filter, state: filterState });\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n removeFilter(filterId: string) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.delete(filterId);\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n clearFilters() {\n set((state) => ({\n activeFilters: new Map<string, { filter: any; state: any }>(),\n ...dropRowSelection(state),\n }));\n },\n setColumnSort(key: string, ascending: boolean | null) {\n set((state) => {\n let newSorts;\n if (ascending == null) {\n newSorts = state.columnSorts.filter((s) => s.key !== key);\n } else {\n const without = state.columnSorts.filter((s) => s.key !== key);\n newSorts = [...without, { key, ascending }];\n }\n return { columnSorts: newSorts, ...dropRowSelection(state) };\n });\n },\n clearColumnSorts() {\n set((state) => ({ columnSorts: [], ...dropRowSelection(state) }));\n },\n setClipboardProxy(proxy) {\n set({ clipboardProxy: proxy });\n },\n };\n}\n\n/**\n * Drop the parts of a selection that are addressed by **row index**, because a\n * filter or sort change re-orders and re-filters the rows underneath them —\n * \"rows 3–5\" then means different records, and a set-action would silently act\n * on the wrong ones. Column selections are index-stable under a view change, so\n * they survive (and must: the sheet's sort/filter controls are themselves\n * column-scoped, and are invoked *from* that selection).\n */\nfunction dropRowSelection<T>(\n state: DataSheetState<T>,\n): Partial<DataSheetState<T>> {\n const selection = state.selection ?? [];\n const kept = selection.filter((region) => region.rows == null);\n if (kept.length === selection.length) return {};\n return { selection: kept, focusedCell: null, topLeftCell: null };\n}\n\nexport function updateSelection<T>(selection: Region[]) {\n const focusedCell = singleFocusedCell(selection);\n let spec: Partial<DataSheetState<T>> = {\n selection,\n focusedCell,\n topLeftCell: topLeftCell(selection),\n };\n return spec;\n}\n\nfunction getLastRowIndex(regions: Region[]): number | null {\n /** Get the last row index from a selection of regions */\n if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) {\n /** If no valid rows are found, return null */\n return null;\n }\n return lastRow;\n}\n\nfunction getRowIndices(regions: Region[]): number[] {\n /** Get the row indices from a selection of regions */\n if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set<number>();\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for (let i = rows[0]; i <= rows[1]; i++) {\n rowIndices.add(i);\n }\n }\n return Array.from(rowIndices).sort((a, b) => a - b);\n}\n\nexport function topLeftCell(\n regions: Region[],\n requireSolitaryCell: boolean = false,\n): FocusedCellCoordinates | null {\n /** Top left cell of a ranged selection */\n if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols, rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))\n return null;\n return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };\n}\n\nfunction selectionEquals(a: Region[], b: Region[]): boolean {\n /** Check if two selections are equal */\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const regionA = a[i];\n const regionB = b[i];\n\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n\n if (\n colsA.length !== colsB.length ||\n rowsA.length !== rowsB.length ||\n colsA[0] !== colsB[0] ||\n colsA[1] !== colsB[1] ||\n rowsA[0] !== rowsB[0] ||\n rowsA[1] !== rowsB[1]\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function singleFocusedCell(\n sel: Region[],\n): FocusedCellCoordinates | null {\n /** Derive a single focused cell from a selected region, if possible */\n if (sel?.length !== 1) return null;\n return topLeftCell(sel, true);\n}\n\n/** A fill-drag over `selection`: the anchor cell's value written down the\n * anchor's column in every selected row. Drawn from the overlay as it stood\n * when the drag began (`fillBaseData`), so the result is the fill alone, and\n * returned with the cells it changed. */\nfunction fillSelection<T>(\n state: DataSheetStore<T>,\n selection: Region[],\n): { updatedData: T[]; cells: CellEdit[] } {\n const { columnSpec, editable, fillValueBaseCell, data } = state;\n const baseData = state.fillBaseData ?? state.updatedData;\n const noFill = { updatedData: state.updatedData, cells: [] };\n\n if (!editable || fillValueBaseCell == null) return noFill;\n const { col, row: baseVisibleRow } = fillValueBaseCell;\n // Dragging from a locked or derived column fills nothing\n if (!isColumnWritable(columnSpec[col], editable)) return noFill;\n // The base cell and target rows are visible positions; map to data rows.\n const baseRow = toDataRowIndex(state, baseVisibleRow);\n const key = columnSpec[col].key;\n const value = baseData[baseRow]?.[key] ?? data[baseRow]?.[key];\n\n const spec = {};\n const cells: CellEdit[] = [];\n for (const region of selection) {\n for (const visibleRow of range(region.rows ?? [])) {\n const row = toDataRowIndex(state, visibleRow);\n if (row === baseRow) continue;\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n const current = baseData[row]?.[key] ?? data[row]?.[key];\n if (valuesAreEquivalent(value, current)) continue;\n let op = baseData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: { [key]: value } };\n cells.push({ rowIndex: row, column: key, value, row: data[row] });\n }\n }\n return { updatedData: update(baseData, spec), cells };\n}\n\n/** Number of rows currently visible (post-filter/sort), or the full data\n * length when no view transform is active. Uses the max of `data` and\n * `updatedData` lengths because `updatedData` is sparse — keying off it alone\n * would stop a whole-column edit at the last already-edited row. */\nfunction visibleRowCount<T>(state: DataSheetStore<T>): number {\n const { filteredRowIndices, updatedData, data } = state;\n return filteredRowIndices != null\n ? filteredRowIndices.length\n : Math.max(data.length, updatedData.length);\n}\n\n/** Map a visible (post-filter/sort) row position to its underlying data\n * index. Edit methods receive selection indices in visible space, so they\n * must translate before writing to `updatedData`/`data`. */\nfunction toDataRowIndex<T>(\n state: DataSheetStore<T>,\n visibleRow: number,\n): number {\n const { filteredRowIndices } = state;\n if (filteredRowIndices == null) return visibleRow;\n return filteredRowIndices[visibleRow] ?? visibleRow;\n}\n\n/** Whether two cell values are equivalent for edit-tracking. Empty string and\n * null/undefined are equivalent (so clearing an empty cell is a no-op), and\n * non-blank values are compared by string form so a text editor's `\"42\"`\n * matches a numeric base `42` (otherwise the cell reads as edited when its\n * value didn't actually change). */\nfunction valuesAreEquivalent(a: any, b: any): boolean {\n if (a === b) return true;\n const aBlank = a == null || a === \"\";\n const bBlank = b == null || b === \"\";\n if (aBlank || bBlank) return aBlank && bBlank;\n // Structured values (an interval position, a list of lithologies) compare\n // by content: as strings, every object is \"[object Object]\", so any edit\n // to one — or to a list that keeps its length — read as no change\n if (typeof a === \"object\" || typeof b === \"object\") {\n return JSON.stringify(a) === JSON.stringify(b);\n }\n return String(a) === String(b);\n}\n\nfunction resetChangesForSelection<T>(\n state: DataSheetStore<T>,\n selection: Region[],\n): Partial<DataSheetStore<T>> {\n const emptySelection = {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n\n const { data } = state;\n const cardinality =\n getSelectionCardinality(selection ?? []) ?? RegionCardinality.FULL_TABLE;\n\n const rowStatus = [...state.rowStatus];\n const updatedData = [...state.updatedData];\n const addedRows = new Set<number>();\n\n // Global reset\n switch (cardinality) {\n case RegionCardinality.FULL_TABLE:\n for (let i = 0; i < rowStatus.length; i++) {\n if (rowStatus[i] === TableElementStatus.ADDED) {\n addedRows.add(i);\n }\n }\n\n return {\n updatedData: [],\n rowStatus: [],\n data: data.filter((_, i) => !addedRows.has(i)),\n ...emptySelection,\n };\n case RegionCardinality.FULL_COLUMNS:\n case RegionCardinality.CELLS:\n /** Columns or cells. Note, these only work the same because we don't\n * allow column deletion, only unsetting all values.\n */\n const columnKeys = getSelectedColumnKeys(selection, state.columnSpec);\n const spec: Spec<Record<string, any>[]> = {};\n const rowIndices =\n cardinality == RegionCardinality.FULL_COLUMNS\n ? Array.from({ length: updatedData.length }, (_, i) => i)\n : getSelectedRowIndices(selection);\n for (const row of rowIndices) {\n if (updatedData[row] == null) continue;\n spec[row] = { $unset: columnKeys };\n }\n // TODO: if we allow column addition/deletion, this will require more adjustment\n return {\n updatedData: update(updatedData, spec as any),\n ...emptySelection,\n };\n case RegionCardinality.FULL_ROWS:\n for (const row of getSelectedRowIndices(selection)) {\n updatedData[row] = undefined;\n if (state.rowStatus[row] === TableElementStatus.DELETED) {\n rowStatus[row] = undefined;\n } else if (state.rowStatus[row] === TableElementStatus.ADDED) {\n addedRows.add(row);\n }\n }\n\n const removeCandidateRows = (arr: any[]) => {\n return arr.filter((d, i) => !addedRows.has(i));\n };\n\n return {\n updatedData: removeCandidateRows(updatedData),\n data: removeCandidateRows(state.data),\n rowStatus: removeCandidateRows(rowStatus),\n ...emptySelection,\n };\n }\n}\n\nfunction insertItemAtIndex<T>(arr: T[], index: number, item: T) {\n if (arr.length < index) {\n const newArr = [...arr];\n newArr.length = index;\n newArr[index] = item;\n return newArr;\n }\n\n return [...arr.slice(0, index), item, ...arr.slice(index)];\n}\n"],"names":["DEFAULT_ROW_STATUS_STYLES","selection","topLeftCell","DS_ROW_ID","TableElementStatus","update","columnSpec","isColumnWritable","range","getSelectionCardinality","RegionCardinality","getSelectedColumnKeys","getSelectedRowIndices"],"mappings":";;;;;;;;;AAyBA,IA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QACL,aAAaI,gBAAAA,QAAO,aAAa,IAAW;AAAA,QAC5C,GAAG;AAAA,MAAA;AAAA,IAEP,KAAKK,MAAAA,kBAAkB;AACrB,iBAAW,OAAOE,gCAAsBX,WAAS,GAAG;AAClD,oBAAY,GAAG,IAAI;AACnB,YAAI,MAAM,UAAU,GAAG,MAAMG,MAAAA,mBAAmB,SAAS;AACvD,oBAAU,GAAG,IAAI;AAAA,QACnB,WAAW,MAAM,UAAU,GAAG,MAAMA,MAAAA,mBAAmB,OAAO;AAC5D,oBAAU,IAAI,GAAG;AAAA,QACnB;AAAA,MACF;AAEA,YAAM,sBAAsB,CAAC,QAAe;AAC1C,eAAO,IAAI,OAAO,CAAC,GAAG,MAAM,CAAC,UAAU,IAAI,CAAC,CAAC;AAAA,MAC/C;AAEA,aAAO;AAAA,QACL,aAAa,oBAAoB,WAAW;AAAA,QAC5C,MAAM,oBAAoB,MAAM,IAAI;AAAA,QACpC,WAAW,oBAAoB,SAAS;AAAA,QACxC,GAAG;AAAA,MAAA;AAAA,EACL;AAEN;AAEA,SAAS,kBAAqB,KAAU,OAAe,MAAS;AAC9D,MAAI,IAAI,SAAS,OAAO;AACtB,UAAM,SAAS,CAAC,GAAG,GAAG;AACtB,WAAO,SAAS;AAChB,WAAO,KAAK,IAAI;AAChB,WAAO;AAAA,EACT;AAEA,SAAO,CAAC,GAAG,IAAI,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,IAAI,MAAM,KAAK,CAAC;AAC3D;;;;;"}
@@ -17,6 +17,7 @@ function createZustandStore(set, get) {
17
17
  editable: false,
18
18
  selection: [],
19
19
  fillValueBaseCell: null,
20
+ fillBaseData: null,
20
21
  focusedCell: null,
21
22
  topLeftCell: null,
22
23
  initialized: false,
@@ -180,10 +181,20 @@ function createZustandStore(set, get) {
180
181
  });
181
182
  },
182
183
  onDragValue(event) {
183
- set((state) => {
184
- return { fillValueBaseCell: state.focusedCell };
185
- });
186
184
  event.preventDefault();
185
+ const { focusedCell, updatedData } = get();
186
+ if (focusedCell == null) return;
187
+ set({ fillValueBaseCell: focusedCell, fillBaseData: updatedData });
188
+ window.addEventListener("mouseup", () => get().finishFill(), {
189
+ once: true
190
+ });
191
+ },
192
+ finishFill() {
193
+ const state = get();
194
+ if (state.fillValueBaseCell == null) return;
195
+ const { cells } = fillSelection(state, state.selection);
196
+ set({ fillValueBaseCell: null, fillBaseData: null });
197
+ if (cells.length > 0) get().onEdit?.({ type: "setCells", cells });
187
198
  },
188
199
  onCellEdited(rowIndex, columnName, value) {
189
200
  const targetColumn = get().columnSpec.find((c) => c.key === columnName);
@@ -272,7 +283,7 @@ function createZustandStore(set, get) {
272
283
  }
273
284
  let spec = updateSelection(selection);
274
285
  if (state.fillValueBaseCell != null) {
275
- spec.updatedData = fillValues(state, selection);
286
+ spec.updatedData = fillSelection(state, selection).updatedData;
276
287
  }
277
288
  spec.autoActivateArmed = true;
278
289
  spec.lastNavDirection = null;
@@ -399,9 +410,6 @@ function updateSelection(selection) {
399
410
  focusedCell,
400
411
  topLeftCell: topLeftCell(selection)
401
412
  };
402
- if (focusedCell != null) {
403
- spec.fillValueBaseCell = null;
404
- }
405
413
  return spec;
406
414
  }
407
415
  function getLastRowIndex(regions) {
@@ -458,30 +466,31 @@ function singleFocusedCell(sel) {
458
466
  if (sel?.length !== 1) return null;
459
467
  return topLeftCell(sel, true);
460
468
  }
461
- function fillValues(state, selection) {
462
- const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;
463
- let regions = selection.map((region) => {
464
- const { cols, rows } = region;
465
- const [col2] = cols ?? [];
466
- return { cols: [col2, col2], rows };
467
- });
468
- if (!editable || fillValueBaseCell == null) return updatedData;
469
+ function fillSelection(state, selection) {
470
+ const { columnSpec, editable, fillValueBaseCell, data } = state;
471
+ const baseData = state.fillBaseData ?? state.updatedData;
472
+ const noFill = { updatedData: state.updatedData, cells: [] };
473
+ if (!editable || fillValueBaseCell == null) return noFill;
469
474
  const { col, row: baseVisibleRow } = fillValueBaseCell;
470
- if (!isColumnWritable(columnSpec[col], editable)) return updatedData;
475
+ if (!isColumnWritable(columnSpec[col], editable)) return noFill;
471
476
  const baseRow = toDataRowIndex(state, baseVisibleRow);
472
477
  const key = columnSpec[col].key;
473
- const value = updatedData[baseRow]?.[key] ?? data[baseRow]?.[key];
478
+ const value = baseData[baseRow]?.[key] ?? data[baseRow]?.[key];
474
479
  const spec = {};
475
- for (const region of regions) {
476
- const { rows } = region;
477
- for (const visibleRow of range(rows ?? [])) {
480
+ const cells = [];
481
+ for (const region of selection) {
482
+ for (const visibleRow of range(region.rows ?? [])) {
478
483
  const row = toDataRowIndex(state, visibleRow);
484
+ if (row === baseRow) continue;
479
485
  if (state.rowStatus[row] === TableElementStatus.DELETED) continue;
480
- let op = updatedData[row] == null ? "$set" : "$merge";
486
+ const current = baseData[row]?.[key] ?? data[row]?.[key];
487
+ if (valuesAreEquivalent(value, current)) continue;
488
+ let op = baseData[row] == null ? "$set" : "$merge";
481
489
  spec[row] = { [op]: { [key]: value } };
490
+ cells.push({ rowIndex: row, column: key, value, row: data[row] });
482
491
  }
483
492
  }
484
- return update(updatedData, spec);
493
+ return { updatedData: update(baseData, spec), cells };
485
494
  }
486
495
  function visibleRowCount(state) {
487
496
  const { filteredRowIndices, updatedData, data } = state;
@@ -1 +1 @@
1
- {"version":3,"file":"zustand-store.js","sources":["../../src/provider/zustand-store.ts"],"sourcesContent":["import {\n DataSheetState,\n DataSheetStore,\n DataSheetStoreMain,\n DEFAULT_ROW_STATUS_STYLES,\n DS_ROW_ID,\n StateUpdater,\n TableElementStatus,\n} from \"./types.ts\";\nimport {\n type FocusedCellCoordinates,\n type Region,\n RegionCardinality,\n} from \"@blueprintjs/table\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n getSelectedColumnKeys,\n getSelectedRowIndices,\n getSelectionCardinality,\n range,\n} from \"../actions\";\nimport { isColumnWritable } from \"./column-spec.ts\";\n\n/** Monotonic counter for synthetic ids on in-table-added rows. */\nlet _addedRowCounter = 0;\n\nexport function createZustandStore<T>(set, get): DataSheetStoreMain<T> {\n return {\n /** All the data in the table */\n data: [],\n updatedData: [],\n rowStatus: [],\n rowStatusStyles: DEFAULT_ROW_STATUS_STYLES,\n columnSpec: [],\n deferColumnSpec: false,\n defaultColumnWidth: 150,\n editable: false,\n selection: [],\n fillValueBaseCell: null,\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef: null,\n // This is a placeholder\n enableColumnReordering: false,\n activeFilters: new Map<string, { filter: any; state: any }>(),\n columnSorts: [],\n clipboardProxy: null,\n filteredRowIndices: null,\n cellInteraction: \"auto\",\n autoActivateArmed: true,\n lastNavDirection: null,\n tableElement: null,\n cellSurfaceOpen: false,\n identity: (row: any) => row?.id,\n pendingOverlayById: new Map(),\n controlledOverlay: false,\n canDeleteRows: true,\n setSelection(selection: Region[]) {\n set(updateSelection(selection));\n },\n columnWidthsIndex: new Map<string, number>(),\n suppressAutoActivate() {\n set({ autoActivateArmed: false });\n },\n armAutoActivate() {\n set({ autoActivateArmed: true });\n },\n openCellSurface() {\n set({ cellSurfaceOpen: true });\n },\n closeCellSurface(opts?: { suppress?: boolean }) {\n const suppress = opts?.suppress ?? true;\n set((state) => ({\n cellSurfaceOpen: false,\n // Escape (suppress) drops auto mode into navigation mode so surfaces\n // stop auto-opening until the next click. A click-dismiss doesn't.\n autoActivateArmed:\n suppress && state.cellInteraction === \"auto\"\n ? false\n : state.autoActivateArmed,\n }));\n },\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\") {\n set((state) => {\n const { topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col, row } = topLeftCell;\n switch (direction) {\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(\n row + 1,\n Math.max(state.data.length, state.updatedData.length) - 1,\n );\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region: Region = { cols: [col, col], rows: [row, row] };\n // Record the travel direction (so the next editor places its cursor on\n // the side we're moving toward) and open the new cell's surface only\n // when auto-activation is armed.\n return {\n ...updateSelection([region]),\n lastNavDirection: direction,\n cellSurfaceOpen:\n state.cellInteraction === \"auto\" && state.autoActivateArmed,\n };\n });\n },\n addRow(row: Partial<T> = {} as T) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */\n let newIndex = -1;\n set((state) => {\n const { updatedData, data, selection, rowStatus } = state;\n\n const lastRowIndex =\n getLastRowIndex(selection) ??\n Math.max(data.length, updatedData.length) - 1;\n // Use $set at a specific index to correctly extend the sparse array.\n // $splice fails when the target index exceeds the array length.\n newIndex = lastRowIndex + 1;\n\n // Stamp a stable synthetic id so the added row survives a provider\n // re-fetch (it has no provider row to match on). Its values live in the\n // overlay (`updatedData`), which the loader-boundary remap re-appends.\n const newRow = {\n ...(row as any),\n [DS_ROW_ID]: `__added_${_addedRowCounter++}`,\n } as T;\n\n return {\n updatedData: insertItemAtIndex(updatedData, newIndex, newRow),\n data: insertItemAtIndex(data, newIndex, newRow),\n rowStatus: insertItemAtIndex(\n rowStatus,\n newIndex,\n TableElementStatus.ADDED,\n ),\n };\n });\n get().onEdit?.({ type: \"addRow\", rowIndex: newIndex, value: row });\n },\n setUpdatedData(data: StateUpdater<T>) {\n if (Array.isArray(data)) {\n set({ updatedData: data });\n } else {\n set((state) => {\n return { updatedData: data(state.updatedData) };\n });\n }\n },\n deleteSelectedRows() {\n // Deletion is a provider capability: if the active data provider can't\n // delete (no `deleteRows`), the whole affordance is disabled.\n if (!get().canDeleteRows) return;\n // Remove selected rows from the data and updatedData arrays\n let deletedIndices: number[] = [];\n set((state) => {\n const { selection, deletedRows } = state;\n const rowIndices = getRowIndices(selection);\n deletedIndices = rowIndices;\n\n // Delete rows from both updatedData and data\n\n // If rows are in addedRows, we just delete them outright from the data and updatedData arrays\n const { addedRows } = state;\n\n const rowsNewlyDeleted = new Set(rowIndices);\n\n // We outright remove rows that have not been added to the data array\n const rowsToRemoveFromDataArrays = new Set(\n rowIndices.filter(\n (d) => state.rowStatus[d] == TableElementStatus.ADDED,\n ),\n );\n // ...otherwise we set them to 'deleted'\n const rowsToMarkAsDeleted = rowsNewlyDeleted.difference(\n rowsToRemoveFromDataArrays,\n );\n\n let data = state.data;\n let updatedData = state.updatedData;\n let rowStatus = state.rowStatus;\n if (rowsToMarkAsDeleted.size > 0) {\n let spec: Spec<TableElementStatus[]> = {};\n for (const ix of rowsToMarkAsDeleted) {\n spec[ix] = { $set: TableElementStatus.DELETED };\n }\n rowStatus = update(rowStatus, spec);\n }\n\n if (rowsToRemoveFromDataArrays.size > 0) {\n const filterFunc = (_, i) => !rowsToRemoveFromDataArrays.has(i);\n data = data.filter(filterFunc);\n updatedData = updatedData.filter(filterFunc);\n rowStatus = rowStatus.filter(filterFunc);\n }\n\n // Remove selected rows and reset selection\n return {\n selection: [],\n data,\n updatedData,\n rowStatus,\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n });\n if (deletedIndices.length > 0) {\n get().onEdit?.({ type: \"deleteRows\", rowIndices: deletedIndices });\n }\n },\n resetChanges(regions?: Region[]) {\n // Reset the updated data to the initial data\n set((state) => resetChangesForSelection(state, regions ?? []));\n get().onEdit?.({ type: \"resetChanges\" });\n },\n onColumnWidthChanged(columnIx: number, newWidth: number) {\n set((state) => {\n const { columnSpec, columnWidthsIndex } = state;\n const colKey = columnSpec[columnIx].key;\n const newColumnWidths = new Map(columnWidthsIndex);\n newColumnWidths.set(colKey, newWidth);\n return { columnWidthsIndex: newColumnWidths };\n });\n },\n onDragValue(event: MouseEvent) {\n set((state) => {\n return { fillValueBaseCell: state.focusedCell };\n });\n event.preventDefault();\n },\n onCellEdited(rowIndex: number, columnName: string, value: any) {\n // The column decides whether it takes writes (see `isColumnWritable`):\n // a locked or derived column is refused here as well as in the cell\n // renderer, so a programmatic caller — the row editor, say — can't\n // write what the grid wouldn't let you type.\n const targetColumn = get().columnSpec.find((c) => c.key === columnName);\n if (!isColumnWritable(targetColumn, get().editable)) return;\n set((state) => {\n const { editable, updatedData, data } = state;\n if (!editable) return {};\n let rowSpec: any;\n\n // Check to see if the new value is meaningfully different from the old\n // one. Empty string and null/undefined are treated as equivalent, so\n // focusing (and blurring) an empty cell doesn't record a phantom edit.\n const oldValue = data[rowIndex]?.[columnName];\n if (!valuesAreEquivalent(value, oldValue)) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = { [rowOp]: { [columnName]: value } };\n } else if (updatedData[rowIndex] != null) {\n // No change — drop any prior override for this cell.\n rowSpec = { $unset: [columnName] };\n } else {\n // No change and no prior override: nothing to do. (`$unset` on an\n // absent row would throw in immutability-helper.)\n return {};\n }\n const spec: Spec<T[]> = { [rowIndex]: rowSpec };\n return { updatedData: update(updatedData, spec) };\n });\n if (get().editable) {\n get().onEdit?.({\n type: \"setCells\",\n cells: [\n { rowIndex, column: columnName, value, row: get().data[rowIndex] },\n ],\n });\n }\n },\n clearSelection() {\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n // Delete all selected cells\n const { selection, updatedData, columnSpec, data } = state;\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // Don't clear row if it has been deleted\n const rowIsDeleted =\n state.rowStatus[row] === TableElementStatus.DELETED;\n if (rowIsDeleted) continue;\n let vals = {};\n for (const col of colRange) {\n // A locked or derived column is never cleared\n if (!isColumnWritable(columnSpec[col], state.editable)) continue;\n const key = columnSpec[col].key;\n const currentValue = updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") {\n vals[key] = \"\";\n edits.push({\n rowIndex: row,\n column: key,\n value: \"\",\n row: data[row],\n });\n }\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onSelection(selection: Region[]) {\n set((state) => {\n const isSameAsPrevSelection = selectionEquals(\n selection,\n state.selection,\n );\n if (\n isSameAsPrevSelection &&\n singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode\n ) {\n // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n cellSurfaceOpen: false,\n };\n }\n\n let spec = updateSelection(selection);\n if (state.fillValueBaseCell != null) {\n spec.updatedData = fillValues(state, selection);\n }\n // A click (user selection) re-arms auto-activation and clears the\n // travel direction so the editor opens with a default cursor.\n spec.autoActivateArmed = true;\n spec.lastNavDirection = null;\n // Only open when the selection actually MOVES to a (single) cell.\n // A click on the already-selected cell leaves open-state to the\n // target's click toggle — this avoids racing the selection event\n // (which fires on mousedown, possibly more than once) and is what\n // makes both re-focus-to-open and click-to-close reliable.\n // In \"second-click\" mode a new selection only selects; the click on\n // the already-selected cell opens it.\n if (!selectionEquals(selection, state.selection)) {\n spec.cellSurfaceOpen =\n state.cellInteraction !== \"second-click\" &&\n singleFocusedCell(selection) != null;\n }\n return spec;\n });\n },\n onSelectionEdited(value: any) {\n // Apply the same value to all selected cells\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n const { selection, updatedData, columnSpec, editable } = state;\n if (!editable) return {};\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // A deleted row takes no edits\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n let vals = {};\n for (const col of colRange) {\n // Only the columns that take writes — a selection spanning a\n // locked or derived column writes around it\n if (!isColumnWritable(columnSpec[col], editable)) continue;\n const key = columnSpec[col].key;\n vals[key] = value;\n edits.push({\n rowIndex: row,\n column: key,\n value,\n row: state.data[row],\n });\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onColumnsReordered(oldIndex: number, newIndex: number, length: number) {\n set((state) => {\n if (!state.enableColumnReordering) return {};\n const { columnSpec } = state;\n const newSpec = [...columnSpec];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return { columnSpec: newSpec };\n });\n },\n scrollToRow(rowIndex: number) {\n const tableRef = get().tableRef;\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [rowIndex, rowIndex],\n });\n },\n // Sort/filter state changes flow to the data provider (via the loader,\n // which reads `activeFilters`/`columnSorts` and re-fetches). The library no\n // longer computes a client-side `filteredRowIndices` view — `data` arrives\n // already ordered from the provider (in memory for a local source).\n setFilter(filterId: string, filter: any, filterState: any) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.set(filterId, { filter, state: filterState });\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n removeFilter(filterId: string) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.delete(filterId);\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n clearFilters() {\n set((state) => ({\n activeFilters: new Map<string, { filter: any; state: any }>(),\n ...dropRowSelection(state),\n }));\n },\n setColumnSort(key: string, ascending: boolean | null) {\n set((state) => {\n let newSorts;\n if (ascending == null) {\n newSorts = state.columnSorts.filter((s) => s.key !== key);\n } else {\n const without = state.columnSorts.filter((s) => s.key !== key);\n newSorts = [...without, { key, ascending }];\n }\n return { columnSorts: newSorts, ...dropRowSelection(state) };\n });\n },\n clearColumnSorts() {\n set((state) => ({ columnSorts: [], ...dropRowSelection(state) }));\n },\n setClipboardProxy(proxy) {\n set({ clipboardProxy: proxy });\n },\n };\n}\n\n/**\n * Drop the parts of a selection that are addressed by **row index**, because a\n * filter or sort change re-orders and re-filters the rows underneath them —\n * \"rows 3–5\" then means different records, and a set-action would silently act\n * on the wrong ones. Column selections are index-stable under a view change, so\n * they survive (and must: the sheet's sort/filter controls are themselves\n * column-scoped, and are invoked *from* that selection).\n */\nfunction dropRowSelection<T>(\n state: DataSheetState<T>,\n): Partial<DataSheetState<T>> {\n const selection = state.selection ?? [];\n const kept = selection.filter((region) => region.rows == null);\n if (kept.length === selection.length) return {};\n return { selection: kept, focusedCell: null, topLeftCell: null };\n}\n\nexport function updateSelection<T>(selection: Region[]) {\n const focusedCell = singleFocusedCell(selection);\n let spec: Partial<DataSheetState<T>> = {\n selection,\n focusedCell,\n topLeftCell: topLeftCell(selection),\n };\n if (focusedCell != null) {\n spec.fillValueBaseCell = null;\n }\n return spec;\n}\n\nfunction getLastRowIndex(regions: Region[]): number | null {\n /** Get the last row index from a selection of regions */\n if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) {\n /** If no valid rows are found, return null */\n return null;\n }\n return lastRow;\n}\n\nfunction getRowIndices(regions: Region[]): number[] {\n /** Get the row indices from a selection of regions */\n if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set<number>();\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for (let i = rows[0]; i <= rows[1]; i++) {\n rowIndices.add(i);\n }\n }\n return Array.from(rowIndices).sort((a, b) => a - b);\n}\n\nexport function topLeftCell(\n regions: Region[],\n requireSolitaryCell: boolean = false,\n): FocusedCellCoordinates | null {\n /** Top left cell of a ranged selection */\n if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols, rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))\n return null;\n return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };\n}\n\nfunction selectionEquals(a: Region[], b: Region[]): boolean {\n /** Check if two selections are equal */\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const regionA = a[i];\n const regionB = b[i];\n\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n\n if (\n colsA.length !== colsB.length ||\n rowsA.length !== rowsB.length ||\n colsA[0] !== colsB[0] ||\n colsA[1] !== colsB[1] ||\n rowsA[0] !== rowsB[0] ||\n rowsA[1] !== rowsB[1]\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function singleFocusedCell(\n sel: Region[],\n): FocusedCellCoordinates | null {\n /** Derive a single focused cell from a selected region, if possible */\n if (sel?.length !== 1) return null;\n return topLeftCell(sel, true);\n}\n\nfunction fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {\n const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;\n\n // Prepare regions by unnesting columns\n let regions = selection.map((region) => {\n const { cols, rows } = region;\n // Get the first column (maybe should be the last)\n const [col] = cols ?? [];\n return { cols: [col, col], rows };\n });\n\n // Fill values downwards\n if (!editable || fillValueBaseCell == null) return updatedData;\n const { col, row: baseVisibleRow } = fillValueBaseCell;\n // Dragging from a locked or derived column fills nothing\n if (!isColumnWritable(columnSpec[col], editable)) return updatedData;\n // The base cell and target rows are visible positions; map to data rows.\n const baseRow = toDataRowIndex(state, baseVisibleRow);\n const key = columnSpec[col].key;\n const value = updatedData[baseRow]?.[key] ?? data[baseRow]?.[key];\n const spec = {};\n for (const region of regions) {\n const { rows } = region;\n for (const visibleRow of range(rows ?? [])) {\n const row = toDataRowIndex(state, visibleRow);\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: { [key]: value } };\n }\n }\n return update(updatedData, spec);\n}\n\n/** Number of rows currently visible (post-filter/sort), or the full data\n * length when no view transform is active. Uses the max of `data` and\n * `updatedData` lengths because `updatedData` is sparse — keying off it alone\n * would stop a whole-column edit at the last already-edited row. */\nfunction visibleRowCount<T>(state: DataSheetStore<T>): number {\n const { filteredRowIndices, updatedData, data } = state;\n return filteredRowIndices != null\n ? filteredRowIndices.length\n : Math.max(data.length, updatedData.length);\n}\n\n/** Map a visible (post-filter/sort) row position to its underlying data\n * index. Edit methods receive selection indices in visible space, so they\n * must translate before writing to `updatedData`/`data`. */\nfunction toDataRowIndex<T>(\n state: DataSheetStore<T>,\n visibleRow: number,\n): number {\n const { filteredRowIndices } = state;\n if (filteredRowIndices == null) return visibleRow;\n return filteredRowIndices[visibleRow] ?? visibleRow;\n}\n\n/** Whether two cell values are equivalent for edit-tracking. Empty string and\n * null/undefined are equivalent (so clearing an empty cell is a no-op), and\n * non-blank values are compared by string form so a text editor's `\"42\"`\n * matches a numeric base `42` (otherwise the cell reads as edited when its\n * value didn't actually change). */\nfunction valuesAreEquivalent(a: any, b: any): boolean {\n if (a === b) return true;\n const aBlank = a == null || a === \"\";\n const bBlank = b == null || b === \"\";\n if (aBlank || bBlank) return aBlank && bBlank;\n // Structured values (an interval position, a list of lithologies) compare\n // by content: as strings, every object is \"[object Object]\", so any edit\n // to one — or to a list that keeps its length — read as no change\n if (typeof a === \"object\" || typeof b === \"object\") {\n return JSON.stringify(a) === JSON.stringify(b);\n }\n return String(a) === String(b);\n}\n\nfunction resetChangesForSelection<T>(\n state: DataSheetStore<T>,\n selection: Region[],\n): Partial<DataSheetStore<T>> {\n const emptySelection = {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n\n const { data } = state;\n const cardinality =\n getSelectionCardinality(selection ?? []) ?? RegionCardinality.FULL_TABLE;\n\n const rowStatus = [...state.rowStatus];\n const updatedData = [...state.updatedData];\n const addedRows = new Set<number>();\n\n // Global reset\n switch (cardinality) {\n case RegionCardinality.FULL_TABLE:\n for (let i = 0; i < rowStatus.length; i++) {\n if (rowStatus[i] === TableElementStatus.ADDED) {\n addedRows.add(i);\n }\n }\n\n return {\n updatedData: [],\n rowStatus: [],\n data: data.filter((_, i) => !addedRows.has(i)),\n ...emptySelection,\n };\n case RegionCardinality.FULL_COLUMNS:\n case RegionCardinality.CELLS:\n /** Columns or cells. Note, these only work the same because we don't\n * allow column deletion, only unsetting all values.\n */\n const columnKeys = getSelectedColumnKeys(selection, state.columnSpec);\n const spec: Spec<Record<string, any>[]> = {};\n const rowIndices =\n cardinality == RegionCardinality.FULL_COLUMNS\n ? Array.from({ length: updatedData.length }, (_, i) => i)\n : getSelectedRowIndices(selection);\n for (const row of rowIndices) {\n if (updatedData[row] == null) continue;\n spec[row] = { $unset: columnKeys };\n }\n // TODO: if we allow column addition/deletion, this will require more adjustment\n return {\n updatedData: update(updatedData, spec as any),\n ...emptySelection,\n };\n case RegionCardinality.FULL_ROWS:\n for (const row of getSelectedRowIndices(selection)) {\n updatedData[row] = undefined;\n if (state.rowStatus[row] === TableElementStatus.DELETED) {\n rowStatus[row] = undefined;\n } else if (state.rowStatus[row] === TableElementStatus.ADDED) {\n addedRows.add(row);\n }\n }\n\n const removeCandidateRows = (arr: any[]) => {\n return arr.filter((d, i) => !addedRows.has(i));\n };\n\n return {\n updatedData: removeCandidateRows(updatedData),\n data: removeCandidateRows(state.data),\n rowStatus: removeCandidateRows(rowStatus),\n ...emptySelection,\n };\n }\n}\n\nfunction insertItemAtIndex<T>(arr: T[], index: number, item: T) {\n if (arr.length < index) {\n const newArr = [...arr];\n newArr.length = index;\n newArr[index] = item;\n return newArr;\n }\n\n return [...arr.slice(0, index), item, ...arr.slice(index)];\n}\n"],"names":["topLeftCell","col"],"mappings":";;;;;AAwBA,IAAI,mBAAmB;AAEhB,SAAS,mBAAsB,KAAK,KAA4B;AACrE,SAAO;AAAA;AAAA,IAEL,MAAM,CAAA;AAAA,IACN,aAAa,CAAA;AAAA,IACb,WAAW,CAAA;AAAA,IACX,iBAAiB;AAAA,IACjB,YAAY,CAAA;AAAA,IACZ,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,UAAU;AAAA,IACV,WAAW,CAAA;AAAA,IACX,mBAAmB;AAAA,IACnB,aAAa;AAAA,IACb,aAAa;AAAA,IACb,aAAa;AAAA,IACb,UAAU;AAAA;AAAA,IAEV,wBAAwB;AAAA,IACxB,mCAAmB,IAAA;AAAA,IACnB,aAAa,CAAA;AAAA,IACb,gBAAgB;AAAA,IAChB,oBAAoB;AAAA,IACpB,iBAAiB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,iBAAiB;AAAA,IACjB,UAAU,CAAC,QAAa,KAAK;AAAA,IAC7B,wCAAwB,IAAA;AAAA,IACxB,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,aAAa,WAAqB;AAChC,UAAI,gBAAgB,SAAS,CAAC;AAAA,IAChC;AAAA,IACA,uCAAuB,IAAA;AAAA,IACvB,uBAAuB;AACrB,UAAI,EAAE,mBAAmB,OAAO;AAAA,IAClC;AAAA,IACA,kBAAkB;AAChB,UAAI,EAAE,mBAAmB,MAAM;AAAA,IACjC;AAAA,IACA,kBAAkB;AAChB,UAAI,EAAE,iBAAiB,MAAM;AAAA,IAC/B;AAAA,IACA,iBAAiB,MAA+B;AAC9C,YAAM,WAAW,MAAM,YAAY;AACnC,UAAI,CAAC,WAAW;AAAA,QACd,iBAAiB;AAAA;AAAA;AAAA,QAGjB,m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AAS,CAAC,GAAG,GAAG;AACtB,WAAO,SAAS;AAChB,WAAO,KAAK,IAAI;AAChB,WAAO;AAAA,EACT;AAEA,SAAO,CAAC,GAAG,IAAI,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,IAAI,MAAM,KAAK,CAAC;AAC3D;"}
1
+ {"version":3,"file":"zustand-store.js","sources":["../../src/provider/zustand-store.ts"],"sourcesContent":["import {\n CellEdit,\n DataSheetState,\n DataSheetStore,\n DataSheetStoreMain,\n DEFAULT_ROW_STATUS_STYLES,\n DS_ROW_ID,\n StateUpdater,\n TableElementStatus,\n} from \"./types.ts\";\nimport {\n type FocusedCellCoordinates,\n type Region,\n RegionCardinality,\n} from \"@blueprintjs/table\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n getSelectedColumnKeys,\n getSelectedRowIndices,\n getSelectionCardinality,\n range,\n} from \"../actions\";\nimport { isColumnWritable } from \"./column-spec.ts\";\n\n/** Monotonic counter for synthetic ids on in-table-added rows. */\nlet _addedRowCounter = 0;\n\nexport function createZustandStore<T>(set, get): DataSheetStoreMain<T> {\n return {\n /** All the data in the table */\n data: [],\n updatedData: [],\n rowStatus: [],\n rowStatusStyles: DEFAULT_ROW_STATUS_STYLES,\n columnSpec: [],\n deferColumnSpec: false,\n defaultColumnWidth: 150,\n editable: false,\n selection: [],\n fillValueBaseCell: null,\n fillBaseData: null,\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef: null,\n // This is a placeholder\n enableColumnReordering: false,\n activeFilters: new Map<string, { filter: any; state: any }>(),\n columnSorts: [],\n clipboardProxy: null,\n filteredRowIndices: null,\n cellInteraction: \"auto\",\n autoActivateArmed: true,\n lastNavDirection: null,\n tableElement: null,\n cellSurfaceOpen: false,\n identity: (row: any) => row?.id,\n pendingOverlayById: new Map(),\n controlledOverlay: false,\n canDeleteRows: true,\n setSelection(selection: Region[]) {\n set(updateSelection(selection));\n },\n columnWidthsIndex: new Map<string, number>(),\n suppressAutoActivate() {\n set({ autoActivateArmed: false });\n },\n armAutoActivate() {\n set({ autoActivateArmed: true });\n },\n openCellSurface() {\n set({ cellSurfaceOpen: true });\n },\n closeCellSurface(opts?: { suppress?: boolean }) {\n const suppress = opts?.suppress ?? true;\n set((state) => ({\n cellSurfaceOpen: false,\n // Escape (suppress) drops auto mode into navigation mode so surfaces\n // stop auto-opening until the next click. A click-dismiss doesn't.\n autoActivateArmed:\n suppress && state.cellInteraction === \"auto\"\n ? false\n : state.autoActivateArmed,\n }));\n },\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\") {\n set((state) => {\n const { topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col, row } = topLeftCell;\n switch (direction) {\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(\n row + 1,\n Math.max(state.data.length, state.updatedData.length) - 1,\n );\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region: Region = { cols: [col, col], rows: [row, row] };\n // Record the travel direction (so the next editor places its cursor on\n // the side we're moving toward) and open the new cell's surface only\n // when auto-activation is armed.\n return {\n ...updateSelection([region]),\n lastNavDirection: direction,\n cellSurfaceOpen:\n state.cellInteraction === \"auto\" && state.autoActivateArmed,\n };\n });\n },\n addRow(row: Partial<T> = {} as T) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */\n let newIndex = -1;\n set((state) => {\n const { updatedData, data, selection, rowStatus } = state;\n\n const lastRowIndex =\n getLastRowIndex(selection) ??\n Math.max(data.length, updatedData.length) - 1;\n // Use $set at a specific index to correctly extend the sparse array.\n // $splice fails when the target index exceeds the array length.\n newIndex = lastRowIndex + 1;\n\n // Stamp a stable synthetic id so the added row survives a provider\n // re-fetch (it has no provider row to match on). Its values live in the\n // overlay (`updatedData`), which the loader-boundary remap re-appends.\n const newRow = {\n ...(row as any),\n [DS_ROW_ID]: `__added_${_addedRowCounter++}`,\n } as T;\n\n return {\n updatedData: insertItemAtIndex(updatedData, newIndex, newRow),\n data: insertItemAtIndex(data, newIndex, newRow),\n rowStatus: insertItemAtIndex(\n rowStatus,\n newIndex,\n TableElementStatus.ADDED,\n ),\n };\n });\n get().onEdit?.({ type: \"addRow\", rowIndex: newIndex, value: row });\n },\n setUpdatedData(data: StateUpdater<T>) {\n if (Array.isArray(data)) {\n set({ updatedData: data });\n } else {\n set((state) => {\n return { updatedData: data(state.updatedData) };\n });\n }\n },\n deleteSelectedRows() {\n // Deletion is a provider capability: if the active data provider can't\n // delete (no `deleteRows`), the whole affordance is disabled.\n if (!get().canDeleteRows) return;\n // Remove selected rows from the data and updatedData arrays\n let deletedIndices: number[] = [];\n set((state) => {\n const { selection, deletedRows } = state;\n const rowIndices = getRowIndices(selection);\n deletedIndices = rowIndices;\n\n // Delete rows from both updatedData and data\n\n // If rows are in addedRows, we just delete them outright from the data and updatedData arrays\n const { addedRows } = state;\n\n const rowsNewlyDeleted = new Set(rowIndices);\n\n // We outright remove rows that have not been added to the data array\n const rowsToRemoveFromDataArrays = new Set(\n rowIndices.filter(\n (d) => state.rowStatus[d] == TableElementStatus.ADDED,\n ),\n );\n // ...otherwise we set them to 'deleted'\n const rowsToMarkAsDeleted = rowsNewlyDeleted.difference(\n rowsToRemoveFromDataArrays,\n );\n\n let data = state.data;\n let updatedData = state.updatedData;\n let rowStatus = state.rowStatus;\n if (rowsToMarkAsDeleted.size > 0) {\n let spec: Spec<TableElementStatus[]> = {};\n for (const ix of rowsToMarkAsDeleted) {\n spec[ix] = { $set: TableElementStatus.DELETED };\n }\n rowStatus = update(rowStatus, spec);\n }\n\n if (rowsToRemoveFromDataArrays.size > 0) {\n const filterFunc = (_, i) => !rowsToRemoveFromDataArrays.has(i);\n data = data.filter(filterFunc);\n updatedData = updatedData.filter(filterFunc);\n rowStatus = rowStatus.filter(filterFunc);\n }\n\n // Remove selected rows and reset selection\n return {\n selection: [],\n data,\n updatedData,\n rowStatus,\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n });\n if (deletedIndices.length > 0) {\n get().onEdit?.({ type: \"deleteRows\", rowIndices: deletedIndices });\n }\n },\n resetChanges(regions?: Region[]) {\n // Reset the updated data to the initial data\n set((state) => resetChangesForSelection(state, regions ?? []));\n get().onEdit?.({ type: \"resetChanges\" });\n },\n onColumnWidthChanged(columnIx: number, newWidth: number) {\n set((state) => {\n const { columnSpec, columnWidthsIndex } = state;\n const colKey = columnSpec[columnIx].key;\n const newColumnWidths = new Map(columnWidthsIndex);\n newColumnWidths.set(colKey, newWidth);\n return { columnWidthsIndex: newColumnWidths };\n });\n },\n onDragValue(event: MouseEvent) {\n event.preventDefault();\n const { focusedCell, updatedData } = get();\n if (focusedCell == null) return;\n // The fill is drawn from the overlay as it stood when the drag began, so\n // shrinking the drag takes back the rows it leaves.\n set({ fillValueBaseCell: focusedCell, fillBaseData: updatedData });\n // A fill belongs to its drag alone, and the drag ends when the button is\n // released, wherever that is. Left armed, the anchor would fill every\n // later selection that isn't a single cell — a row picked by its header,\n // say — with the anchor's value.\n window.addEventListener(\"mouseup\", () => get().finishFill(), {\n once: true,\n });\n },\n finishFill() {\n const state = get();\n if (state.fillValueBaseCell == null) return;\n const { cells } = fillSelection(state, state.selection);\n set({ fillValueBaseCell: null, fillBaseData: null });\n // Reported like any other write, so a consumer that holds the edits\n // (a controlled overlay) records the fill rather than having it drawn\n // once and then overwritten.\n if (cells.length > 0) get().onEdit?.({ type: \"setCells\", cells });\n },\n onCellEdited(rowIndex: number, columnName: string, value: any) {\n // The column decides whether it takes writes (see `isColumnWritable`):\n // a locked or derived column is refused here as well as in the cell\n // renderer, so a programmatic caller — the row editor, say — can't\n // write what the grid wouldn't let you type.\n const targetColumn = get().columnSpec.find((c) => c.key === columnName);\n if (!isColumnWritable(targetColumn, get().editable)) return;\n set((state) => {\n const { editable, updatedData, data } = state;\n if (!editable) return {};\n let rowSpec: any;\n\n // Check to see if the new value is meaningfully different from the old\n // one. Empty string and null/undefined are treated as equivalent, so\n // focusing (and blurring) an empty cell doesn't record a phantom edit.\n const oldValue = data[rowIndex]?.[columnName];\n if (!valuesAreEquivalent(value, oldValue)) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = { [rowOp]: { [columnName]: value } };\n } else if (updatedData[rowIndex] != null) {\n // No change — drop any prior override for this cell.\n rowSpec = { $unset: [columnName] };\n } else {\n // No change and no prior override: nothing to do. (`$unset` on an\n // absent row would throw in immutability-helper.)\n return {};\n }\n const spec: Spec<T[]> = { [rowIndex]: rowSpec };\n return { updatedData: update(updatedData, spec) };\n });\n if (get().editable) {\n get().onEdit?.({\n type: \"setCells\",\n cells: [\n { rowIndex, column: columnName, value, row: get().data[rowIndex] },\n ],\n });\n }\n },\n clearSelection() {\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n // Delete all selected cells\n const { selection, updatedData, columnSpec, data } = state;\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // Don't clear row if it has been deleted\n const rowIsDeleted =\n state.rowStatus[row] === TableElementStatus.DELETED;\n if (rowIsDeleted) continue;\n let vals = {};\n for (const col of colRange) {\n // A locked or derived column is never cleared\n if (!isColumnWritable(columnSpec[col], state.editable)) continue;\n const key = columnSpec[col].key;\n const currentValue = updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") {\n vals[key] = \"\";\n edits.push({\n rowIndex: row,\n column: key,\n value: \"\",\n row: data[row],\n });\n }\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onSelection(selection: Region[]) {\n set((state) => {\n const isSameAsPrevSelection = selectionEquals(\n selection,\n state.selection,\n );\n if (\n isSameAsPrevSelection &&\n singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode\n ) {\n // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n cellSurfaceOpen: false,\n };\n }\n\n let spec = updateSelection(selection);\n if (state.fillValueBaseCell != null) {\n spec.updatedData = fillSelection(state, selection).updatedData;\n }\n // A click (user selection) re-arms auto-activation and clears the\n // travel direction so the editor opens with a default cursor.\n spec.autoActivateArmed = true;\n spec.lastNavDirection = null;\n // Only open when the selection actually MOVES to a (single) cell.\n // A click on the already-selected cell leaves open-state to the\n // target's click toggle — this avoids racing the selection event\n // (which fires on mousedown, possibly more than once) and is what\n // makes both re-focus-to-open and click-to-close reliable.\n // In \"second-click\" mode a new selection only selects; the click on\n // the already-selected cell opens it.\n if (!selectionEquals(selection, state.selection)) {\n spec.cellSurfaceOpen =\n state.cellInteraction !== \"second-click\" &&\n singleFocusedCell(selection) != null;\n }\n return spec;\n });\n },\n onSelectionEdited(value: any) {\n // Apply the same value to all selected cells\n const edits: {\n rowIndex: number;\n column: string;\n value: any;\n row?: any;\n }[] = [];\n set((state) => {\n const { selection, updatedData, columnSpec, editable } = state;\n if (!editable) return {};\n const numVisible = visibleRowCount(state);\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, numVisible - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const visibleRow of rowRange) {\n // Selection indices are visible positions; map to the data row.\n const row = toDataRowIndex(state, visibleRow);\n // A deleted row takes no edits\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n let vals = {};\n for (const col of colRange) {\n // Only the columns that take writes — a selection spanning a\n // locked or derived column writes around it\n if (!isColumnWritable(columnSpec[col], editable)) continue;\n const key = columnSpec[col].key;\n vals[key] = value;\n edits.push({\n rowIndex: row,\n column: key,\n value,\n row: state.data[row],\n });\n }\n if (Object.keys(vals).length === 0) continue;\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n if (edits.length > 0) {\n get().onEdit?.({ type: \"setCells\", cells: edits });\n }\n },\n onColumnsReordered(oldIndex: number, newIndex: number, length: number) {\n set((state) => {\n if (!state.enableColumnReordering) return {};\n const { columnSpec } = state;\n const newSpec = [...columnSpec];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return { columnSpec: newSpec };\n });\n },\n scrollToRow(rowIndex: number) {\n const tableRef = get().tableRef;\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [rowIndex, rowIndex],\n });\n },\n // Sort/filter state changes flow to the data provider (via the loader,\n // which reads `activeFilters`/`columnSorts` and re-fetches). The library no\n // longer computes a client-side `filteredRowIndices` view — `data` arrives\n // already ordered from the provider (in memory for a local source).\n setFilter(filterId: string, filter: any, filterState: any) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.set(filterId, { filter, state: filterState });\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n removeFilter(filterId: string) {\n set((state) => {\n const newFilters = new Map<string, { filter: any; state: any }>(\n state.activeFilters,\n );\n newFilters.delete(filterId);\n return { activeFilters: newFilters, ...dropRowSelection(state) };\n });\n },\n clearFilters() {\n set((state) => ({\n activeFilters: new Map<string, { filter: any; state: any }>(),\n ...dropRowSelection(state),\n }));\n },\n setColumnSort(key: string, ascending: boolean | null) {\n set((state) => {\n let newSorts;\n if (ascending == null) {\n newSorts = state.columnSorts.filter((s) => s.key !== key);\n } else {\n const without = state.columnSorts.filter((s) => s.key !== key);\n newSorts = [...without, { key, ascending }];\n }\n return { columnSorts: newSorts, ...dropRowSelection(state) };\n });\n },\n clearColumnSorts() {\n set((state) => ({ columnSorts: [], ...dropRowSelection(state) }));\n },\n setClipboardProxy(proxy) {\n set({ clipboardProxy: proxy });\n },\n };\n}\n\n/**\n * Drop the parts of a selection that are addressed by **row index**, because a\n * filter or sort change re-orders and re-filters the rows underneath them —\n * \"rows 3–5\" then means different records, and a set-action would silently act\n * on the wrong ones. Column selections are index-stable under a view change, so\n * they survive (and must: the sheet's sort/filter controls are themselves\n * column-scoped, and are invoked *from* that selection).\n */\nfunction dropRowSelection<T>(\n state: DataSheetState<T>,\n): Partial<DataSheetState<T>> {\n const selection = state.selection ?? [];\n const kept = selection.filter((region) => region.rows == null);\n if (kept.length === selection.length) return {};\n return { selection: kept, focusedCell: null, topLeftCell: null };\n}\n\nexport function updateSelection<T>(selection: Region[]) {\n const focusedCell = singleFocusedCell(selection);\n let spec: Partial<DataSheetState<T>> = {\n selection,\n focusedCell,\n topLeftCell: topLeftCell(selection),\n };\n return spec;\n}\n\nfunction getLastRowIndex(regions: Region[]): number | null {\n /** Get the last row index from a selection of regions */\n if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) {\n /** If no valid rows are found, return null */\n return null;\n }\n return lastRow;\n}\n\nfunction getRowIndices(regions: Region[]): number[] {\n /** Get the row indices from a selection of regions */\n if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set<number>();\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for (let i = rows[0]; i <= rows[1]; i++) {\n rowIndices.add(i);\n }\n }\n return Array.from(rowIndices).sort((a, b) => a - b);\n}\n\nexport function topLeftCell(\n regions: Region[],\n requireSolitaryCell: boolean = false,\n): FocusedCellCoordinates | null {\n /** Top left cell of a ranged selection */\n if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols, rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))\n return null;\n return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };\n}\n\nfunction selectionEquals(a: Region[], b: Region[]): boolean {\n /** Check if two selections are equal */\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const regionA = a[i];\n const regionB = b[i];\n\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n\n if (\n colsA.length !== colsB.length ||\n rowsA.length !== rowsB.length ||\n colsA[0] !== colsB[0] ||\n colsA[1] !== colsB[1] ||\n rowsA[0] !== rowsB[0] ||\n rowsA[1] !== rowsB[1]\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function singleFocusedCell(\n sel: Region[],\n): FocusedCellCoordinates | null {\n /** Derive a single focused cell from a selected region, if possible */\n if (sel?.length !== 1) return null;\n return topLeftCell(sel, true);\n}\n\n/** A fill-drag over `selection`: the anchor cell's value written down the\n * anchor's column in every selected row. Drawn from the overlay as it stood\n * when the drag began (`fillBaseData`), so the result is the fill alone, and\n * returned with the cells it changed. */\nfunction fillSelection<T>(\n state: DataSheetStore<T>,\n selection: Region[],\n): { updatedData: T[]; cells: CellEdit[] } {\n const { columnSpec, editable, fillValueBaseCell, data } = state;\n const baseData = state.fillBaseData ?? state.updatedData;\n const noFill = { updatedData: state.updatedData, cells: [] };\n\n if (!editable || fillValueBaseCell == null) return noFill;\n const { col, row: baseVisibleRow } = fillValueBaseCell;\n // Dragging from a locked or derived column fills nothing\n if (!isColumnWritable(columnSpec[col], editable)) return noFill;\n // The base cell and target rows are visible positions; map to data rows.\n const baseRow = toDataRowIndex(state, baseVisibleRow);\n const key = columnSpec[col].key;\n const value = baseData[baseRow]?.[key] ?? data[baseRow]?.[key];\n\n const spec = {};\n const cells: CellEdit[] = [];\n for (const region of selection) {\n for (const visibleRow of range(region.rows ?? [])) {\n const row = toDataRowIndex(state, visibleRow);\n if (row === baseRow) continue;\n if (state.rowStatus[row] === TableElementStatus.DELETED) continue;\n const current = baseData[row]?.[key] ?? data[row]?.[key];\n if (valuesAreEquivalent(value, current)) continue;\n let op = baseData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: { [key]: value } };\n cells.push({ rowIndex: row, column: key, value, row: data[row] });\n }\n }\n return { updatedData: update(baseData, spec), cells };\n}\n\n/** Number of rows currently visible (post-filter/sort), or the full data\n * length when no view transform is active. Uses the max of `data` and\n * `updatedData` lengths because `updatedData` is sparse — keying off it alone\n * would stop a whole-column edit at the last already-edited row. */\nfunction visibleRowCount<T>(state: DataSheetStore<T>): number {\n const { filteredRowIndices, updatedData, data } = state;\n return filteredRowIndices != null\n ? filteredRowIndices.length\n : Math.max(data.length, updatedData.length);\n}\n\n/** Map a visible (post-filter/sort) row position to its underlying data\n * index. Edit methods receive selection indices in visible space, so they\n * must translate before writing to `updatedData`/`data`. */\nfunction toDataRowIndex<T>(\n state: DataSheetStore<T>,\n visibleRow: number,\n): number {\n const { filteredRowIndices } = state;\n if (filteredRowIndices == null) return visibleRow;\n return filteredRowIndices[visibleRow] ?? visibleRow;\n}\n\n/** Whether two cell values are equivalent for edit-tracking. Empty string and\n * null/undefined are equivalent (so clearing an empty cell is a no-op), and\n * non-blank values are compared by string form so a text editor's `\"42\"`\n * matches a numeric base `42` (otherwise the cell reads as edited when its\n * value didn't actually change). */\nfunction valuesAreEquivalent(a: any, b: any): boolean {\n if (a === b) return true;\n const aBlank = a == null || a === \"\";\n const bBlank = b == null || b === \"\";\n if (aBlank || bBlank) return aBlank && bBlank;\n // Structured values (an interval position, a list of lithologies) compare\n // by content: as strings, every object is \"[object Object]\", so any edit\n // to one — or to a list that keeps its length — read as no change\n if (typeof a === \"object\" || typeof b === \"object\") {\n return JSON.stringify(a) === JSON.stringify(b);\n }\n return String(a) === String(b);\n}\n\nfunction resetChangesForSelection<T>(\n state: DataSheetStore<T>,\n selection: Region[],\n): Partial<DataSheetStore<T>> {\n const emptySelection = {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n\n const { data } = state;\n const cardinality =\n getSelectionCardinality(selection ?? []) ?? RegionCardinality.FULL_TABLE;\n\n const rowStatus = [...state.rowStatus];\n const updatedData = [...state.updatedData];\n const addedRows = new Set<number>();\n\n // Global reset\n switch (cardinality) {\n case RegionCardinality.FULL_TABLE:\n for (let i = 0; i < rowStatus.length; i++) {\n if (rowStatus[i] === TableElementStatus.ADDED) {\n addedRows.add(i);\n }\n }\n\n return {\n updatedData: [],\n rowStatus: [],\n data: data.filter((_, i) => !addedRows.has(i)),\n ...emptySelection,\n };\n case RegionCardinality.FULL_COLUMNS:\n case RegionCardinality.CELLS:\n /** Columns or cells. Note, these only work the same because we don't\n * allow column deletion, only unsetting all values.\n */\n const columnKeys = getSelectedColumnKeys(selection, state.columnSpec);\n const spec: Spec<Record<string, any>[]> = {};\n const rowIndices =\n cardinality == RegionCardinality.FULL_COLUMNS\n ? Array.from({ length: updatedData.length }, (_, i) => i)\n : getSelectedRowIndices(selection);\n for (const row of rowIndices) {\n if (updatedData[row] == null) continue;\n spec[row] = { $unset: columnKeys };\n }\n // TODO: if we allow column addition/deletion, this will require more adjustment\n return {\n updatedData: update(updatedData, spec as any),\n ...emptySelection,\n };\n case RegionCardinality.FULL_ROWS:\n for (const row of getSelectedRowIndices(selection)) {\n updatedData[row] = undefined;\n if (state.rowStatus[row] === TableElementStatus.DELETED) {\n rowStatus[row] = undefined;\n } else if (state.rowStatus[row] === TableElementStatus.ADDED) {\n addedRows.add(row);\n }\n }\n\n const removeCandidateRows = (arr: any[]) => {\n return arr.filter((d, i) => !addedRows.has(i));\n };\n\n return {\n updatedData: removeCandidateRows(updatedData),\n data: removeCandidateRows(state.data),\n rowStatus: removeCandidateRows(rowStatus),\n ...emptySelection,\n };\n }\n}\n\nfunction insertItemAtIndex<T>(arr: T[], index: number, item: T) {\n if (arr.length < index) {\n const newArr = [...arr];\n newArr.length = index;\n newArr[index] = item;\n return newArr;\n }\n\n return [...arr.slice(0, index), item, ...arr.slice(index)];\n}\n"],"names":["topLeftCell"],"mappings":";;;;;AAyBA,IAAI,mBAAmB;AAEhB,SAAS,mBAAsB,KAAK,KAA4B;AACrE,SAAO;AAAA;AAAA,IAEL,MAAM,CAAA;AAAA,IACN,aAAa,CAAA;AAAA,IACb,WAAW,CAAA;AAAA,IACX,iBAAiB;AAAA,IACjB,YAAY,CAAA;AAAA,IACZ,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,UAAU;AAAA,IACV,WAAW,CAAA;AAAA,IACX,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,aAAa;AAAA,IACb,aAAa;AAAA,IACb,aAAa;AAAA,IACb,UAAU;AAAA;AAAA,IAEV,wBAAwB;AAAA,IACxB,mCAAmB,IAAA;AAAA,IACnB,aAAa,CAAA;AAAA,IACb,gBAAgB;AAAA,IAChB,oBAAoB;AAAA,IACpB,iBAAiB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,iBAAiB;AAAA,IACjB,UAAU,CAAC,QAAa,KAAK;AAAA,IAC7B,wCAAwB,IAAA;AAAA,IACxB,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,aAAa,WAAqB;AAChC,UAAI,gBAAgB,SAAS,CAAC;AAAA,IAChC;AAAA,IACA,uCAAuB,IAAA;AAAA,IACvB,uBAAuB;AACrB,UAAI,EAAE,mBAAmB,OAAO;AAAA,IAClC;AAAA,IACA,kBAAkB;AAChB,UAAI,EAAE,mBAAmB,MAAM;AAAA,IACjC;AAAA,IACA,kBAAkB;AAChB,UAAI,EAAE,iBAAiB,MAAM;AAAA,IAC/B;AAAA,IACA,iBAAiB,MAA+B;AAC9C,YAAM,WAAW,MAAM,YAAY;AACnC,UAAI,CAA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AAG,MAAM,mBAAmB,SAAS;AACvD,oBAAU,GAAG,IAAI;AAAA,QACnB,WAAW,MAAM,UAAU,GAAG,MAAM,mBAAmB,OAAO;AAC5D,oBAAU,IAAI,GAAG;AAAA,QACnB;AAAA,MACF;AAEA,YAAM,sBAAsB,CAAC,QAAe;AAC1C,eAAO,IAAI,OAAO,CAAC,GAAG,MAAM,CAAC,UAAU,IAAI,CAAC,CAAC;AAAA,MAC/C;AAEA,aAAO;AAAA,QACL,aAAa,oBAAoB,WAAW;AAAA,QAC5C,MAAM,oBAAoB,MAAM,IAAI;AAAA,QACpC,WAAW,oBAAoB,SAAS;AAAA,QACxC,GAAG;AAAA,MAAA;AAAA,EACL;AAEN;AAEA,SAAS,kBAAqB,KAAU,OAAe,MAAS;AAC9D,MAAI,IAAI,SAAS,OAAO;AACtB,UAAM,SAAS,CAAC,GAAG,GAAG;AACtB,WAAO,SAAS;AAChB,WAAO,KAAK,IAAI;AAChB,WAAO;AAAA,EACT;AAEA,SAAO,CAAC,GAAG,IAAI,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,IAAI,MAAM,KAAK,CAAC;AAC3D;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macrostrat/data-sheet",
3
- "version": "4.9.0",
3
+ "version": "4.9.1",
4
4
  "description": "Scalable data sheet with optional editing capabilities",
5
5
  "repository": {
6
6
  "type": "git",
@@ -115,7 +115,10 @@ export interface DataSheetState<T> {
115
115
  * suppressed — a function `columnSpec` derives it from the loaded rows
116
116
  * instead (in `_DataSheet`). Set at init from the prop's shape. */
117
117
  deferColumnSpec: boolean;
118
+ /** The cell a fill-drag copies from, while the drag lasts. */
118
119
  fillValueBaseCell: FocusedCellCoordinates | null;
120
+ /** The overlay as it stood when the fill-drag began. */
121
+ fillBaseData: T[] | null;
119
122
  focusedCell: FocusedCellCoordinates | null;
120
123
  topLeftCell: FocusedCellCoordinates | null;
121
124
  /**
@@ -204,6 +207,8 @@ export type StateUpdater<T> = T[] | ((state: T[]) => T[]);
204
207
  export interface DataSheetStoreMain<T> extends DataSheetVals<T> {
205
208
  setSelection(selection: Region[]): void;
206
209
  onDragValue(event: MouseEvent): void;
210
+ /** End a fill-drag: report the cells it wrote and disarm the anchor. */
211
+ finishFill(): void;
207
212
  setUpdatedData(data: StateUpdater<T>): void;
208
213
  onCellEdited(rowIndex: number, columnName: string, value: any): void;
209
214
  onSelectionEdited(value: any): void;
@@ -1,4 +1,5 @@
1
1
  import {
2
+ CellEdit,
2
3
  DataSheetState,
3
4
  DataSheetStore,
4
5
  DataSheetStoreMain,
@@ -37,6 +38,7 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
37
38
  editable: false,
38
39
  selection: [],
39
40
  fillValueBaseCell: null,
41
+ fillBaseData: null,
40
42
  focusedCell: null,
41
43
  topLeftCell: null,
42
44
  initialized: false,
@@ -235,10 +237,29 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
235
237
  });
236
238
  },
237
239
  onDragValue(event: MouseEvent) {
238
- set((state) => {
239
- return { fillValueBaseCell: state.focusedCell };
240
- });
241
240
  event.preventDefault();
241
+ const { focusedCell, updatedData } = get();
242
+ if (focusedCell == null) return;
243
+ // The fill is drawn from the overlay as it stood when the drag began, so
244
+ // shrinking the drag takes back the rows it leaves.
245
+ set({ fillValueBaseCell: focusedCell, fillBaseData: updatedData });
246
+ // A fill belongs to its drag alone, and the drag ends when the button is
247
+ // released, wherever that is. Left armed, the anchor would fill every
248
+ // later selection that isn't a single cell — a row picked by its header,
249
+ // say — with the anchor's value.
250
+ window.addEventListener("mouseup", () => get().finishFill(), {
251
+ once: true,
252
+ });
253
+ },
254
+ finishFill() {
255
+ const state = get();
256
+ if (state.fillValueBaseCell == null) return;
257
+ const { cells } = fillSelection(state, state.selection);
258
+ set({ fillValueBaseCell: null, fillBaseData: null });
259
+ // Reported like any other write, so a consumer that holds the edits
260
+ // (a controlled overlay) records the fill rather than having it drawn
261
+ // once and then overwritten.
262
+ if (cells.length > 0) get().onEdit?.({ type: "setCells", cells });
242
263
  },
243
264
  onCellEdited(rowIndex: number, columnName: string, value: any) {
244
265
  // The column decides whether it takes writes (see `isColumnWritable`):
@@ -354,7 +375,7 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
354
375
 
355
376
  let spec = updateSelection(selection);
356
377
  if (state.fillValueBaseCell != null) {
357
- spec.updatedData = fillValues(state, selection);
378
+ spec.updatedData = fillSelection(state, selection).updatedData;
358
379
  }
359
380
  // A click (user selection) re-arms auto-activation and clears the
360
381
  // travel direction so the editor opens with a default cursor.
@@ -514,9 +535,6 @@ export function updateSelection<T>(selection: Region[]) {
514
535
  focusedCell,
515
536
  topLeftCell: topLeftCell(selection),
516
537
  };
517
- if (focusedCell != null) {
518
- spec.fillValueBaseCell = null;
519
- }
520
538
  return spec;
521
539
  }
522
540
 
@@ -600,37 +618,42 @@ export function singleFocusedCell(
600
618
  return topLeftCell(sel, true);
601
619
  }
602
620
 
603
- function fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {
604
- const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;
605
-
606
- // Prepare regions by unnesting columns
607
- let regions = selection.map((region) => {
608
- const { cols, rows } = region;
609
- // Get the first column (maybe should be the last)
610
- const [col] = cols ?? [];
611
- return { cols: [col, col], rows };
612
- });
621
+ /** A fill-drag over `selection`: the anchor cell's value written down the
622
+ * anchor's column in every selected row. Drawn from the overlay as it stood
623
+ * when the drag began (`fillBaseData`), so the result is the fill alone, and
624
+ * returned with the cells it changed. */
625
+ function fillSelection<T>(
626
+ state: DataSheetStore<T>,
627
+ selection: Region[],
628
+ ): { updatedData: T[]; cells: CellEdit[] } {
629
+ const { columnSpec, editable, fillValueBaseCell, data } = state;
630
+ const baseData = state.fillBaseData ?? state.updatedData;
631
+ const noFill = { updatedData: state.updatedData, cells: [] };
613
632
 
614
- // Fill values downwards
615
- if (!editable || fillValueBaseCell == null) return updatedData;
633
+ if (!editable || fillValueBaseCell == null) return noFill;
616
634
  const { col, row: baseVisibleRow } = fillValueBaseCell;
617
635
  // Dragging from a locked or derived column fills nothing
618
- if (!isColumnWritable(columnSpec[col], editable)) return updatedData;
636
+ if (!isColumnWritable(columnSpec[col], editable)) return noFill;
619
637
  // The base cell and target rows are visible positions; map to data rows.
620
638
  const baseRow = toDataRowIndex(state, baseVisibleRow);
621
639
  const key = columnSpec[col].key;
622
- const value = updatedData[baseRow]?.[key] ?? data[baseRow]?.[key];
640
+ const value = baseData[baseRow]?.[key] ?? data[baseRow]?.[key];
641
+
623
642
  const spec = {};
624
- for (const region of regions) {
625
- const { rows } = region;
626
- for (const visibleRow of range(rows ?? [])) {
643
+ const cells: CellEdit[] = [];
644
+ for (const region of selection) {
645
+ for (const visibleRow of range(region.rows ?? [])) {
627
646
  const row = toDataRowIndex(state, visibleRow);
647
+ if (row === baseRow) continue;
628
648
  if (state.rowStatus[row] === TableElementStatus.DELETED) continue;
629
- let op = updatedData[row] == null ? "$set" : "$merge";
649
+ const current = baseData[row]?.[key] ?? data[row]?.[key];
650
+ if (valuesAreEquivalent(value, current)) continue;
651
+ let op = baseData[row] == null ? "$set" : "$merge";
630
652
  spec[row] = { [op]: { [key]: value } };
653
+ cells.push({ rowIndex: row, column: key, value, row: data[row] });
631
654
  }
632
655
  }
633
- return update(updatedData, spec);
656
+ return { updatedData: update(baseData, spec), cells };
634
657
  }
635
658
 
636
659
  /** Number of rows currently visible (post-filter/sort), or the full data