@macrostrat/data-sheet 4.5.2 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/data-panel.cjs +9 -4
  3. package/dist/data-panel.cjs.map +1 -1
  4. package/dist/data-panel.d.ts +7 -0
  5. package/dist/data-panel.js +9 -4
  6. package/dist/data-panel.js.map +1 -1
  7. package/dist/data-sheet.css +25 -0
  8. package/dist/data-sheet.d.ts +1 -0
  9. package/dist/data-view.d.ts +1 -0
  10. package/dist/index.cjs +3 -0
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +3 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/masonry.cjs +118 -0
  16. package/dist/masonry.cjs.map +1 -0
  17. package/dist/masonry.d.ts +17 -0
  18. package/dist/masonry.js +118 -0
  19. package/dist/masonry.js.map +1 -0
  20. package/dist/masonry.module.sass.cjs +14 -0
  21. package/dist/masonry.module.sass.cjs.map +1 -0
  22. package/dist/masonry.module.sass.js +13 -0
  23. package/dist/masonry.module.sass.js.map +1 -0
  24. package/dist/postgrest-table/data-loaders.cjs +16 -26
  25. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  26. package/dist/postgrest-table/data-loaders.js +12 -22
  27. package/dist/postgrest-table/data-loaders.js.map +1 -1
  28. package/dist/provider/core.cjs +22 -6
  29. package/dist/provider/core.cjs.map +1 -1
  30. package/dist/provider/core.d.ts +1 -1
  31. package/dist/provider/core.js +22 -6
  32. package/dist/provider/core.js.map +1 -1
  33. package/dist/provider/loader-state.cjs +47 -0
  34. package/dist/provider/loader-state.cjs.map +1 -0
  35. package/dist/provider/loader-state.d.ts +33 -0
  36. package/dist/provider/loader-state.js +47 -0
  37. package/dist/provider/loader-state.js.map +1 -0
  38. package/dist/provider/types.cjs.map +1 -1
  39. package/dist/provider/types.d.ts +5 -1
  40. package/dist/provider/types.js.map +1 -1
  41. package/package.json +3 -3
  42. package/src/data-panel.ts +17 -5
  43. package/src/index.ts +1 -0
  44. package/src/masonry.module.sass +29 -0
  45. package/src/masonry.ts +217 -0
  46. package/src/postgrest-table/data-loaders.ts +22 -41
  47. package/src/provider/core.ts +48 -6
  48. package/src/provider/loader-state.ts +82 -0
  49. package/src/provider/types.ts +5 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader-state.js","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): AtomMap {\n const seed = resolveInitialData(initialData);\n if (seed == null) return [];\n return [[lazyLoaderCoreStateAtom, seededLoaderCore(seed)]];\n}\n"],"names":[],"mappings":";AAqBO,MAAM,sBAAgD;AAAA,EAC3D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AACZ;AAEO,MAAM,0BACX,KAA+B,mBAAmB;AAK7C,SAAS,mBACd,aAC4B;AAC5B,MAAI,eAAe,KAAM,QAAO;AAChC,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,QAAI,YAAY,WAAW,EAAG,QAAO;AACrC,WAAO,EAAE,MAAM,YAAA;AAAA,EACjB;AACA,OAAK,YAAY,QAAQ,CAAA,GAAI,WAAW,EAAG,QAAO;AAClD,SAAO;AACT;AAKO,SAAS,WAAc,MAAyC;AACrE,QAAM,OAAO,KAAK,QAAQ,CAAA;AAC1B,QAAM,OAAO,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ,KAAK,MAAM;AACjE,QAAM,OAAqB,IAAI,MAAM,IAAI,EAAE,KAAK,IAAI;AACpD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,CAAC,IAAI,KAAK,CAAC;AACtD,SAAO;AACT;AAKO,SAAS,iBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa;AAAA,IACb,YAAY,KAAK,cAAc;AAAA,EAAA;AAEnC;AAKO,SAAS,gBACd,aACS;AACT,QAAM,OAAO,mBAAmB,WAAW;AAC3C,MAAI,QAAQ,KAAM,QAAO,CAAA;AACzB,SAAO,CAAC,CAAC,yBAAyB,iBAAiB,IAAI,CAAC,CAAC;AAC3D;"}
@@ -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 } 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\";\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 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 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\";\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 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,7 +1,7 @@
1
1
  import { FocusedCellCoordinates, Region, RegionCardinality, Table2 } from '@blueprintjs/table';
2
2
  import { ColumnSpec, ColumnSpecOptions } from './column-spec';
3
3
  import { OverlayToaster } from '@blueprintjs/core';
4
- import { DataViewCoreProps } from '../types';
4
+ import { DataViewCoreProps, FetchDataOptions } from '../types';
5
5
  import { DataViewRendererType } from './interactions.ts';
6
6
  /** A single column sort entry for client-side sorting.
7
7
  * Defined here (rather than in actions/types) to avoid circular imports. */
@@ -236,6 +236,10 @@ export interface DataSheetStoreMain<T> extends DataSheetVals<T> {
236
236
  }
237
237
  export type DataSheetProviderProps<T> = DataViewCoreProps<T> & {
238
238
  toaster?: OverlayToaster;
239
+ /** A first window of rows the caller already has (see `FetchDataOptions`).
240
+ * The provider creates the store seeded with it, so the rows are in the very
241
+ * first render — a server render included. */
242
+ initialData?: FetchDataOptions<T>["initialData"];
239
243
  viewType?: DataViewRendererType;
240
244
  children?: React.ReactNode;
241
245
  };
@@ -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 } 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\";\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 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 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\";\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 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;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macrostrat/data-sheet",
3
- "version": "4.5.2",
3
+ "version": "4.7.0",
4
4
  "description": "Scalable data sheet with optional editing capabilities",
5
5
  "repository": {
6
6
  "type": "git",
@@ -51,7 +51,7 @@
51
51
  "@macrostrat/color-utils": "^1.2.2",
52
52
  "@macrostrat/data-components": "^1.5.1",
53
53
  "@macrostrat/hyper": "^3.1.1",
54
- "@macrostrat/scoped-store": "^1.0.1",
54
+ "@macrostrat/scoped-store": "^1.1.0",
55
55
  "@macrostrat/ui-components": "^5.2.0",
56
56
  "@supabase/postgrest-js": "^1.17.7",
57
57
  "@types/underscore": "^1.13.0",
@@ -62,7 +62,7 @@
62
62
  },
63
63
  "devDependencies": {
64
64
  "@macrostrat/web-components-bundler": "1.0.1",
65
- "@storybook/react-vite": "10.5.2"
65
+ "@storybook/react-vite": "10.5.10"
66
66
  },
67
67
  "publishConfig": {
68
68
  "access": "public"
package/src/data-panel.ts CHANGED
@@ -89,6 +89,12 @@ export enum DataPanelToolbarStyle {
89
89
  export interface ScrollBodyProps {
90
90
  /** The rendered item cards (each wrapped for selection styling). */
91
91
  children: ReactNode;
92
+ /** Loading skeletons for the page currently being fetched, if any. Kept
93
+ * separate from `children` because they are transient stand-ins, not items:
94
+ * a layout that assigns a lasting position per item (e.g. the masonry body)
95
+ * must not hand one to a placeholder. Render them after the items; a body
96
+ * that ignores them simply shows no loading state. */
97
+ placeholders?: ReactNode;
92
98
  }
93
99
 
94
100
  /** Props handed to a consumer's card renderer for one row. */
@@ -324,10 +330,11 @@ export function DataPanelRenderer<T>({
324
330
  // reset pre-sizes to a page of `null` slots) or the next scroll page — so the
325
331
  // body shows shimmer where rows will land instead of a blank flash or a
326
332
  // footer pinging up into the gap. Bounded to a viewport's worth of cards.
333
+ const placeholderCards: ReactNode[] = [];
327
334
  if (loadPending) {
328
335
  const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);
329
336
  for (let i = 0; i < pending; i++) {
330
- cards.push(
337
+ placeholderCards.push(
331
338
  h(
332
339
  "div.data-panel-item-container.is-skeleton",
333
340
  { key: `skeleton-${i}`, "aria-hidden": true },
@@ -336,6 +343,10 @@ export function DataPanelRenderer<T>({
336
343
  );
337
344
  }
338
345
  }
346
+ let placeholders: ReactNode = null;
347
+ if (placeholderCards.length > 0) {
348
+ placeholders = placeholderCards;
349
+ }
339
350
 
340
351
  // The default spinner sentinel (below-placement): hidden while paused so the
341
352
  // pinned footer's "Load more" takes over.
@@ -450,7 +461,7 @@ export function DataPanelRenderer<T>({
450
461
  },
451
462
  [
452
463
  h("div.data-panel-body-content", [
453
- emptyState ?? h(ScrollBody, cards),
464
+ emptyState ?? h(ScrollBody, { placeholders }, cards),
454
465
  _contentFooter,
455
466
  ]),
456
467
  ],
@@ -468,9 +479,10 @@ function DataPanelStatusBar({ children }) {
468
479
  return h("div.data-panel-status-bar", [children, h(LoadProgressIndicator)]);
469
480
  }
470
481
 
471
- /** Default scroll-body layout: a vertical flex list of cards. */
472
- function DefaultScrollBody({ children }: { children: ReactNode }) {
473
- return h("div.data-panel-list", children);
482
+ /** Default scroll-body layout: a vertical flex list of cards, with any loading
483
+ * placeholders appended in the same flow. */
484
+ function DefaultScrollBody({ children, placeholders }: ScrollBodyProps) {
485
+ return h("div.data-panel-list", [children, placeholders]);
474
486
  }
475
487
 
476
488
  /** Runs the shared windowed loader from inside the panel (renders nothing).
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./data-sheet.ts";
2
2
  export * from "./data-panel.ts";
3
+ export * from "./masonry.ts";
3
4
  export * from "./data-view";
4
5
  export * from "./postgrest-table";
5
6
  export * from "./components";
@@ -0,0 +1,29 @@
1
+ // Masonry scroll body for the DataPanel — a fixed set of equal-width columns
2
+ // that items are distributed across by measured height (see `masonry.ts`).
3
+ // Not CSS multi-column: real columns, so appending a page never reflows what
4
+ // is already on screen.
5
+
6
+ .data-panel-masonry-body
7
+ display: flex
8
+ flex-direction: column
9
+ flex-grow: 1
10
+
11
+ .data-panel-masonry
12
+ display: flex
13
+ align-items: flex-start
14
+ gap: var(--data-panel-item-gap, 8px)
15
+
16
+ .data-panel-masonry-column
17
+ flex: 1 1 0
18
+ min-width: 0
19
+ display: flex
20
+ flex-direction: column
21
+ gap: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px))
22
+
23
+ // Loading placeholders sit below the columns, outside the measured layout —
24
+ // they are transient, so they never take a (frozen) column assignment.
25
+ .data-panel-masonry-placeholders
26
+ display: flex
27
+ flex-direction: column
28
+ gap: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px))
29
+ margin-top: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px))
package/src/masonry.ts ADDED
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Masonry scroll body for the `DataPanel` — variable-height cards laid out in
3
+ * equal-width columns, balanced by *measured* height rather than a flat
4
+ * estimate or CSS multi-column.
5
+ *
6
+ * The problem it solves is paging: CSS `columns` re-flows the whole list every
7
+ * time a page is appended, so the cards under the user's cursor move. Here each
8
+ * item is placed in the running-shortest column **once**, keyed by its React
9
+ * key, and then frozen — appending a page never reshuffles what is on screen.
10
+ *
11
+ * Placement is measured: a freshly-appended batch mounts in provisional
12
+ * columns, a `useLayoutEffect` reads each card's real `offsetHeight`, then the
13
+ * batch is greedily assigned from those real heights and re-rendered — all
14
+ * before paint, so only the balanced result is seen.
15
+ *
16
+ * Two things keep the balance honest over many pages:
17
+ *
18
+ * - **Placeholders are not items.** The panel's loading skeletons arrive as
19
+ * `placeholders`, not `children`, and render below the columns. Freezing a
20
+ * column assignment for a skeleton (measured at skeleton height, then
21
+ * replaced by real content) is what makes a masonry drift, one page at a
22
+ * time, into "this whole page went into one column".
23
+ * - **Identity is the React key, not the array index.** A sort, filter or
24
+ * refresh replaces the keys, and assignments for keys that are gone are
25
+ * pruned — so column heights are always recomputed from items that are
26
+ * actually on screen.
27
+ */
28
+ import h from "./masonry.module.sass";
29
+ import {
30
+ Children,
31
+ cloneElement,
32
+ isValidElement,
33
+ ReactElement,
34
+ ReactNode,
35
+ useEffect,
36
+ useLayoutEffect,
37
+ useReducer,
38
+ useRef,
39
+ useState,
40
+ } from "react";
41
+ import type { ScrollBodyProps } from "./data-panel";
42
+
43
+ /** Height assumed for an item that hasn't been measured yet (it always is, by
44
+ * the time it matters — this only guards a torn-down/hidden container). */
45
+ const FALLBACK_ITEM_HEIGHT = 160;
46
+
47
+ export interface MasonryOptions {
48
+ /** Number of columns (the maximum, when `minColumnWidth` is set). Default 2. */
49
+ columns?: number;
50
+ /** If set, the column count drops below `columns` when the container is too
51
+ * narrow to give every column at least this many pixels. */
52
+ minColumnWidth?: number;
53
+ }
54
+
55
+ interface MasonryState {
56
+ /** Column count the current assignments were computed for. */
57
+ columns: number;
58
+ /** Frozen key → column. */
59
+ assign: Map<string, number>;
60
+ /** Last measured height per key. */
61
+ heights: Map<string, number>;
62
+ /** Mounted element per key, for measurement. */
63
+ els: Map<string, HTMLElement>;
64
+ /** Stable ref callbacks, so an item isn't detached/reattached every render. */
65
+ refs: Map<string, (el: HTMLElement | null) => void>;
66
+ }
67
+
68
+ /**
69
+ * A `scrollBody` component for `DataPanel` with the default two columns. For
70
+ * anything else — a different column count, or responsive columns — build one
71
+ * with `createMasonryScrollBody`.
72
+ */
73
+ export function MasonryScrollBody(props: ScrollBodyProps & MasonryOptions) {
74
+ const { children, placeholders, columns = 2, minColumnWidth } = props;
75
+
76
+ const containerRef = useRef<HTMLDivElement | null>(null);
77
+ const nCols = useColumnCount(containerRef, columns, minColumnWidth);
78
+
79
+ const stateRef = useRef<MasonryState | null>(null);
80
+ stateRef.current ??= {
81
+ columns: nCols,
82
+ assign: new Map(),
83
+ heights: new Map(),
84
+ els: new Map(),
85
+ refs: new Map(),
86
+ };
87
+ const state = stateRef.current;
88
+ const [, bump] = useReducer((x: number) => x + 1, 0);
89
+
90
+ const items = Children.toArray(children).filter(
91
+ isValidElement,
92
+ ) as ReactElement[];
93
+
94
+ // Runs on every commit (no deps): measurement has to see the layout that was
95
+ // just produced, including one caused by a resize or a card's own content
96
+ // settling. It is cheap when nothing is unassigned, and re-renders only when
97
+ // it actually assigns something — so there's no render loop.
98
+ useLayoutEffect(() => {
99
+ // A column-count change invalidates every assignment (a column may no
100
+ // longer exist). Handled here, not in render, so render stays pure.
101
+ if (state.columns !== nCols) {
102
+ state.columns = nCols;
103
+ state.assign.clear();
104
+ }
105
+
106
+ for (const [key, el] of state.els) state.heights.set(key, el.offsetHeight);
107
+
108
+ const present = new Set(items.map(keyOf));
109
+ for (const key of [...state.assign.keys()]) {
110
+ if (!present.has(key)) state.assign.delete(key);
111
+ }
112
+ for (const key of [...state.heights.keys()]) {
113
+ if (!present.has(key)) state.heights.delete(key);
114
+ }
115
+
116
+ const unassigned = items.filter((c) => !state.assign.has(keyOf(c)));
117
+ if (unassigned.length === 0) return;
118
+
119
+ // Column heights from the items already frozen into them…
120
+ const colHeights = new Array(nCols).fill(0);
121
+ for (const [key, col] of state.assign) {
122
+ colHeights[col] += state.heights.get(key) ?? 0;
123
+ }
124
+ // …then greedily place the new batch by its just-measured real heights.
125
+ for (const child of unassigned) {
126
+ const key = keyOf(child);
127
+ let col = 0;
128
+ for (let c = 1; c < nCols; c++) {
129
+ if (colHeights[c] < colHeights[col]) col = c;
130
+ }
131
+ state.assign.set(key, col);
132
+ colHeights[col] += state.heights.get(key) ?? FALLBACK_ITEM_HEIGHT;
133
+ }
134
+ bump(); // move the new batch into its balanced columns, before paint
135
+ });
136
+
137
+ // Items without an assignment yet render in a provisional column so they
138
+ // mount and can be measured; the layout effect above then places them.
139
+ const stale = state.columns !== nCols;
140
+ const columnItems: ReactNode[][] = Array.from({ length: nCols }, () => []);
141
+ items.forEach((child, i) => {
142
+ const key = keyOf(child);
143
+ let assigned: number | undefined = undefined;
144
+ if (!stale) {
145
+ assigned = state.assign.get(key);
146
+ }
147
+ const col = assigned ?? i % nCols;
148
+ columnItems[col].push(
149
+ cloneElement(child, { ref: refFor(state, key) } as any),
150
+ );
151
+ });
152
+
153
+ return h("div.data-panel-masonry-body", [
154
+ h(
155
+ "div.data-panel-masonry",
156
+ { ref: containerRef },
157
+ columnItems.map((col, c) =>
158
+ h("div.data-panel-masonry-column", { key: c }, col),
159
+ ),
160
+ ),
161
+ h.if(placeholders != null)(
162
+ "div.data-panel-masonry-placeholders",
163
+ placeholders,
164
+ ),
165
+ ]);
166
+ }
167
+
168
+ /** Build a `scrollBody` masonry component with a fixed or responsive column
169
+ * count: `scrollBody: createMasonryScrollBody({ columns: 3 })`. */
170
+ export function createMasonryScrollBody(options: MasonryOptions = {}) {
171
+ return function MasonryScrollBodyWithOptions(props: ScrollBodyProps) {
172
+ return h(MasonryScrollBody, { ...options, ...props });
173
+ };
174
+ }
175
+
176
+ function keyOf(child: ReactElement): string {
177
+ return String(child.key);
178
+ }
179
+
180
+ /** One stable ref callback per key — a fresh closure each render would detach
181
+ * and reattach every card on every render. */
182
+ function refFor(state: MasonryState, key: string) {
183
+ let cb = state.refs.get(key);
184
+ if (cb == null) {
185
+ cb = (el: HTMLElement | null) => {
186
+ if (el == null) {
187
+ state.els.delete(key);
188
+ } else {
189
+ state.els.set(key, el);
190
+ }
191
+ };
192
+ state.refs.set(key, cb);
193
+ }
194
+ return cb;
195
+ }
196
+
197
+ /** The effective column count: `columns`, reduced to fit `minColumnWidth`. */
198
+ function useColumnCount(
199
+ ref: { current: HTMLElement | null },
200
+ columns: number,
201
+ minColumnWidth: number | undefined,
202
+ ): number {
203
+ const [width, setWidth] = useState<number | null>(null);
204
+
205
+ useEffect(() => {
206
+ const el = ref.current;
207
+ if (minColumnWidth == null || el == null) return;
208
+ const obs = new ResizeObserver(([entry]) => {
209
+ setWidth(entry.contentRect.width);
210
+ });
211
+ obs.observe(el);
212
+ return () => obs.disconnect();
213
+ }, [minColumnWidth]);
214
+
215
+ if (minColumnWidth == null || width == null) return Math.max(1, columns);
216
+ return Math.max(1, Math.min(columns, Math.floor(width / minColumnWidth)));
217
+ }
@@ -22,19 +22,13 @@ import {
22
22
  useSelector,
23
23
  } from "../provider";
24
24
  import { atom } from "jotai";
25
- import { FetchDataOptions, FetchMode, InitialDataChunk } from "../types.ts";
26
-
27
- interface LazyLoaderStateCore<T> {
28
- loading: boolean;
29
- error: Error | null;
30
- initialized: boolean;
31
- /** Reported source length when known (null = unknown / not reported). */
32
- totalCount: number | null;
33
- /** Windowing style: infinite-scroll windows, or one fixed page at a time. */
34
- fetchMode: FetchMode;
35
- /** Rows per chunk/page. */
36
- pageSize: number;
37
- }
25
+ import { FetchDataOptions, FetchMode } from "../types.ts";
26
+ import {
27
+ lazyLoaderCoreStateAtom,
28
+ resolveInitialData,
29
+ seededRows,
30
+ type LazyLoaderStateCore,
31
+ } from "../provider/loader-state.ts";
38
32
 
39
33
  interface LazyLoaderState<T> extends LazyLoaderStateCore<T> {
40
34
  data: (T | null)[];
@@ -205,10 +199,10 @@ function lazyLoadingReducer<T>(
205
199
  // completed first fetch: pre-size to the reported total so the scrollbar
206
200
  // and counter are right immediately, and mark the loader `initialized` so
207
201
  // it neither refetches the seeded window nor flashes an empty state.
208
- const rows = action.data ?? [];
209
- const size = Math.max(action.totalCount ?? rows.length, rows.length);
210
- const data: (T | null)[] = new Array(size).fill(null);
211
- for (let i = 0; i < rows.length; i++) data[i] = rows[i];
202
+ const data = seededRows({
203
+ rows: action.data ?? [],
204
+ totalCount: action.totalCount,
205
+ });
212
206
  return {
213
207
  visibleRegion: defaultVisibleRegion,
214
208
  data: data as T[],
@@ -373,14 +367,6 @@ const defaultVisibleRegion: RowRegion = {
373
367
  /** Atom to house the current visible region of the table */
374
368
  const visibleRegionAtom = atom<RowRegion>(defaultVisibleRegion);
375
369
 
376
- const lazyLoaderCoreStateAtom = atom<LazyLoaderStateCore<any>>({
377
- loading: false,
378
- error: null,
379
- initialized: false,
380
- totalCount: null,
381
- fetchMode: "scroll",
382
- pageSize: 100,
383
- });
384
370
 
385
371
  /** Current page index (0-based) for paged fetch mode. */
386
372
  export const chunkPageAtom = atom(0);
@@ -736,6 +722,10 @@ export function useDataLoader<T = any>(
736
722
  // A caller-supplied first window (`initialData`) stands in for the mount-time
737
723
  // reset+fetch. It's consumed once: any later view change resets normally,
738
724
  // since the seed only describes the view it was fetched for.
725
+ //
726
+ // The store is normally created already seeded (`DataSheetStoreWrapper`), so
727
+ // the rows are in the very first render — including a server render. The
728
+ // dispatch below is the fallback for a store that wasn't.
739
729
  const seedRef = useRef(resolveInitialData(initialData));
740
730
  // Gate on the seed until it's actually in state (see the fetch effect).
741
731
  const awaitingSeedRef = useRef(seedRef.current != null);
@@ -743,7 +733,13 @@ export function useDataLoader<T = any>(
743
733
  const seed = seedRef.current;
744
734
  seedRef.current = null;
745
735
  if (seed != null) {
746
- dispatch({ type: "seed", data: seed.rows, totalCount: seed.totalCount });
736
+ if (!state.initialized) {
737
+ dispatch({
738
+ type: "seed",
739
+ data: seed.rows,
740
+ totalCount: seed.totalCount,
741
+ });
742
+ }
747
743
  setPage(0);
748
744
  // Paged mode tracks which (page, view) it has in hand separately from the
749
745
  // array; record the seed there too, or it would immediately re-fetch the
@@ -854,21 +850,6 @@ export function useDataLoader<T = any>(
854
850
 
855
851
  /** A value that trails `value` by `delay` ms of stability — the first value is
856
852
  * returned immediately, and `delay <= 0` disables debouncing entirely. */
857
- /** Normalize the two accepted `initialData` shapes (bare rows, or rows with a
858
- * total) to one. An empty seed is treated as no seed — there'd be nothing to
859
- * show and nothing saved. */
860
- function resolveInitialData<T>(
861
- initialData: FetchDataOptions<T>["initialData"],
862
- ): InitialDataChunk<T> | null {
863
- if (initialData == null) return null;
864
- if (Array.isArray(initialData)) {
865
- if (initialData.length === 0) return null;
866
- return { rows: initialData };
867
- }
868
- if ((initialData.rows ?? []).length === 0) return null;
869
- return initialData;
870
- }
871
-
872
853
  function useDebouncedValue<T>(value: T, delay: number): T {
873
854
  const [debounced, setDebounced] = useState(value);
874
855
  useEffect(() => {