@macrostrat/data-sheet 4.8.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.
Files changed (95) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +60 -19
  3. package/dist/actions/context.cjs +10 -1
  4. package/dist/actions/context.cjs.map +1 -1
  5. package/dist/actions/context.js +10 -1
  6. package/dist/actions/context.js.map +1 -1
  7. package/dist/actions/types.d.ts +4 -0
  8. package/dist/components/data-editor.cjs +527 -0
  9. package/dist/components/data-editor.cjs.map +1 -0
  10. package/dist/components/data-editor.d.ts +142 -0
  11. package/dist/components/data-editor.js +524 -0
  12. package/dist/components/data-editor.js.map +1 -0
  13. package/dist/components/editor-actions.cjs +167 -0
  14. package/dist/components/editor-actions.cjs.map +1 -0
  15. package/dist/components/editor-actions.d.ts +37 -0
  16. package/dist/components/editor-actions.js +165 -0
  17. package/dist/components/editor-actions.js.map +1 -0
  18. package/dist/components/editor-popup.cjs +11 -1
  19. package/dist/components/editor-popup.cjs.map +1 -1
  20. package/dist/components/editor-popup.js +11 -1
  21. package/dist/components/editor-popup.js.map +1 -1
  22. package/dist/components/index.d.ts +3 -0
  23. package/dist/components/indicators/selection.cjs +10 -4
  24. package/dist/components/indicators/selection.cjs.map +1 -1
  25. package/dist/components/indicators/selection.js +10 -4
  26. package/dist/components/indicators/selection.js.map +1 -1
  27. package/dist/components/row-editor.cjs +351 -0
  28. package/dist/components/row-editor.cjs.map +1 -0
  29. package/dist/components/row-editor.d.ts +181 -0
  30. package/dist/components/row-editor.js +349 -0
  31. package/dist/components/row-editor.js.map +1 -0
  32. package/dist/components/row-editor.module.sass.cjs +51 -0
  33. package/dist/components/row-editor.module.sass.cjs.map +1 -0
  34. package/dist/components/row-editor.module.sass.js +49 -0
  35. package/dist/components/row-editor.module.sass.js.map +1 -0
  36. package/dist/components/toolbars/actions-toolbar.cjs +1 -1
  37. package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
  38. package/dist/components/toolbars/actions-toolbar.js +1 -1
  39. package/dist/components/toolbars/actions-toolbar.js.map +1 -1
  40. package/dist/data-sheet.css +208 -20
  41. package/dist/index.cjs +27 -0
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.js +29 -2
  44. package/dist/index.js.map +1 -1
  45. package/dist/main.module.sass.cjs +14 -13
  46. package/dist/main.module.sass.cjs.map +1 -1
  47. package/dist/main.module.sass.js +14 -13
  48. package/dist/main.module.sass.js.map +1 -1
  49. package/dist/provider/column-spec.cjs +8 -1
  50. package/dist/provider/column-spec.cjs.map +1 -1
  51. package/dist/provider/column-spec.d.ts +105 -1
  52. package/dist/provider/column-spec.js +8 -1
  53. package/dist/provider/column-spec.js.map +1 -1
  54. package/dist/provider/core.cjs +16 -4
  55. package/dist/provider/core.cjs.map +1 -1
  56. package/dist/provider/core.d.ts +4 -0
  57. package/dist/provider/core.js +16 -4
  58. package/dist/provider/core.js.map +1 -1
  59. package/dist/provider/types.cjs.map +1 -1
  60. package/dist/provider/types.d.ts +6 -1
  61. package/dist/provider/types.js.map +1 -1
  62. package/dist/provider/zustand-store.cjs +55 -33
  63. package/dist/provider/zustand-store.cjs.map +1 -1
  64. package/dist/provider/zustand-store.js +44 -22
  65. package/dist/provider/zustand-store.js.map +1 -1
  66. package/dist/renderers/cell-renderer.cjs +15 -4
  67. package/dist/renderers/cell-renderer.cjs.map +1 -1
  68. package/dist/renderers/cell-renderer.js +13 -4
  69. package/dist/renderers/cell-renderer.js.map +1 -1
  70. package/dist/renderers/column-header-cell.cjs +12 -1
  71. package/dist/renderers/column-header-cell.cjs.map +1 -1
  72. package/dist/renderers/column-header-cell.js +11 -1
  73. package/dist/renderers/column-header-cell.js.map +1 -1
  74. package/dist/types.cjs.map +1 -1
  75. package/dist/types.d.ts +5 -1
  76. package/dist/types.js.map +1 -1
  77. package/package.json +2 -2
  78. package/src/actions/context.ts +13 -2
  79. package/src/actions/types.ts +5 -0
  80. package/src/components/data-editor.ts +741 -0
  81. package/src/components/editor-actions.ts +228 -0
  82. package/src/components/editor-popup.ts +16 -3
  83. package/src/components/index.ts +3 -0
  84. package/src/components/indicators/selection.ts +12 -4
  85. package/src/components/row-editor.module.sass +161 -0
  86. package/src/components/row-editor.ts +620 -0
  87. package/src/components/toolbars/actions-toolbar.ts +3 -2
  88. package/src/main.module.sass +19 -0
  89. package/src/provider/column-spec.ts +94 -16
  90. package/src/provider/core.ts +19 -4
  91. package/src/provider/types.ts +6 -1
  92. package/src/provider/zustand-store.ts +78 -26
  93. package/src/renderers/cell-renderer.ts +18 -3
  94. package/src/renderers/column-header-cell.ts +10 -0
  95. package/src/types.ts +5 -1
@@ -227,7 +227,7 @@ function DataSheetProviderInner(props) {
227
227
  const rows = loadedData.filter((r) => r != null);
228
228
  if (rows.length === 0) return;
229
229
  derivedSpecFor.current = columnSpec$1;
230
- storeAPI.setState({ columnSpec: columnSpec$1(rows) });
230
+ storeAPI.setState({ columnSpec: columnSpec.postprocessColumnSpec(columnSpec$1(rows)) });
231
231
  }, [columnSpec$1, loadedData, storeAPI]);
232
232
  const bumpRefresh = ctx.useSet(tableData.dataRefreshTokenAtom);
233
233
  const firstRefreshToken = react.useRef(true);
@@ -374,10 +374,21 @@ function itemCount(n, dataKind) {
374
374
  return base + " " + pluralize(dataKind, n);
375
375
  }
376
376
  function pluralize(singularForm, n) {
377
- const pluralForm = singularForm + "s";
378
- if (n == 0) return `${pluralForm}`;
379
377
  if (n == 1) return singularForm;
380
- return pluralForm;
378
+ return pluralFormOf(singularForm);
379
+ }
380
+ function pluralFormOf(singularForm) {
381
+ const match = singularForm.match(/^(.*?)(\s*\([^)]*\))?$/);
382
+ const head = match?.[1] ?? singularForm;
383
+ const tail = match?.[2] ?? "";
384
+ if (head === "") return singularForm;
385
+ let plural = head + "s";
386
+ if (/(s|x|z|ch|sh)$/i.test(head)) {
387
+ plural = head + "es";
388
+ } else if (/[^aeiou]y$/i.test(head)) {
389
+ plural = head.slice(0, -1) + "ies";
390
+ }
391
+ return plural + tail;
381
392
  }
382
393
  function capitalize(s) {
383
394
  return s.charAt(0).toUpperCase() + s.slice(1);
@@ -389,6 +400,7 @@ exports.columnSpecAtom = columnSpecAtom;
389
400
  exports.ctx = ctx;
390
401
  exports.dataProviderAtom = dataProviderAtom;
391
402
  exports.itemLabelAtom = itemLabelAtom;
403
+ exports.pluralFormOf = pluralFormOf;
392
404
  exports.pluralize = pluralize;
393
405
  exports.splitDataProviderProps = splitDataProviderProps;
394
406
  exports.storeAPIAtom = storeAPIAtom;
@@ -1 +1 @@
1
- {"version":3,"file":"core.cjs","sources":["../../src/provider/core.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport {\n createScopedStore,\n zustandAPIAtom,\n zustandStoreAtom,\n atom,\n ZustandStoreProvider,\n useZustandSelector,\n useZustandStoreAPI,\n} from \"@macrostrat/scoped-store\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n TableDataProvider,\n} from \"./table-data.ts\";\nimport { ErrorBoundary, ToasterContext } from \"@macrostrat/ui-components\";\nimport {\n DataViewRendererType,\n InteractionOptions,\n interactionOptionsAtom,\n interactionOptionsKeys,\n resolveInteractionOptions,\n} from \"./interactions.ts\";\nimport { DataViewProps } from \"../data-view.ts\";\nimport {\n DataSheetProps,\n DataViewCoreProps,\n InitialDataChunk,\n} from \"../types.ts\";\nimport {\n loaderSeedAtoms,\n resolveInitialData,\n seededRows,\n} from \"./loader-state.ts\";\nimport { DataPanelProps } from \"../data-panel.ts\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = zustandAPIAtom;\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = zustandStoreAtom;\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<any>>) => {\n set(zustandStoreAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\n/** The resolved data source for the table, held in the provider layer (next to\n * the store) rather than resolved inside the render loop. `provider` is the\n * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local\n * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it\n * loads the whole array at once and shows no load progress). `isExplicitProvider`\n * distinguishes an explicit `provider` object from a loose `fetchData`/`data`\n * source — only an explicit provider without `deleteRows` disables row\n * deletion; loose sources keep the local delete overlay. */\nexport interface ResolvedDataProvider {\n provider: TableDataProvider<any> | null;\n isLocalProvider: boolean;\n isExplicitProvider: boolean;\n /** Row count of an in-memory (local) source, so a renderer can size the\n * loader's page to \"all of it\" without also receiving the `data` prop. `0`\n * for non-local sources. */\n localCount: number;\n}\n\nconst DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {\n provider: null,\n isLocalProvider: true,\n isExplicitProvider: false,\n localCount: 0,\n};\n\nexport const dataProviderAtom = atom<ResolvedDataProvider>(\n DEFAULT_DATA_PROVIDER,\n);\n\nconst EMPTY_ARRAY: any[] = [];\n\n/** Resolve a table's data source from the loose `provider` / `fetchData` /\n * `data` props (an explicit `provider` wins; else a loose `fetchData` (+\n * `identity`) is wrapped as one; else in-memory `data` becomes a local\n * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three\n * resolve identically. */\nexport function useResolvedProvider<T>(props: {\n provider?: TableDataProvider<T>;\n fetchData?: FetchData<T>;\n data?: T[];\n identity?: (row: T) => string | number | null | undefined;\n}): {\n data: T[];\n isLocalProvider: boolean;\n activeProvider: TableDataProvider<any> | null;\n dataProvider: ResolvedDataProvider;\n} {\n const _data = props.data ?? (EMPTY_ARRAY as T[]);\n const isLocalProvider = props.provider == null && props.fetchData == null;\n const isExplicitProvider = props.provider != null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (props.provider != null) return props.provider;\n if (props.fetchData != null) {\n return {\n fetchData: props.fetchData,\n identity: props.identity ?? ((r: any) => r?.id),\n } as TableDataProvider<any>;\n }\n if (_data.length > 0) {\n return createLocalProvider(\n _data,\n props.identity != null\n ? { identity: props.identity as (row: any) => string | number }\n : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.provider, props.fetchData, _data, props.identity]);\n const localCount = isLocalProvider ? _data.length : 0;\n const dataProvider = useMemo(\n () => ({\n provider: activeProvider,\n isLocalProvider,\n isExplicitProvider,\n localCount,\n }),\n [activeProvider, isLocalProvider, isExplicitProvider, localCount],\n );\n return { data: _data, isLocalProvider, activeProvider, dataProvider };\n}\n\nfunction DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {\n const {\n toaster,\n initialFilters,\n initialSorts,\n initialData,\n startAfter,\n ...rest\n } = props;\n\n // Initial view state is folded into the store's *creation*, not applied in an\n // effect: the loader mounts below this and its effects run first, so an\n // effect-applied filter would arrive after the first (unfiltered) fetch had\n // already gone out — and be immediately superseded. Creating the store with\n // the view already set means the first fetch is the right one.\n //\n // A seeded first window (`initialData`) is folded in the same way, for the\n // same reason and one more: rows placed at creation are in the first render,\n // so a server render carries them instead of the empty state the loader\n // shows until its first (asynchronous) page resolves.\n const seed = resolveInitialData(initialData);\n const initializeStore = (set: any, get: any) => ({\n ...createZustandStore<T>(set, get),\n ...initialViewState({ initialFilters, initialSorts }),\n ...initialDataState(seed),\n });\n\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore,\n atoms: [\n [toasterAtom, toaster],\n ...loaderSeedAtoms(initialData, startAfter),\n ],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\n/** The store's `data` for a seeded first window; nothing without a seed. */\nfunction initialDataState<T>(\n seed: InitialDataChunk<T> | null,\n): Partial<DataSheetState<T>> {\n if (seed == null) return {};\n return { data: seededRows(seed) as T[] };\n}\n\n/** The store fields that carry a caller-supplied starting view. Absent props\n * contribute nothing, so the store's own defaults stand. */\nfunction initialViewState<T>({\n initialFilters,\n initialSorts,\n}: Pick<DataViewCoreProps<T>, \"initialFilters\" | \"initialSorts\">): Partial<\n DataSheetState<T>\n> {\n const state: Partial<DataSheetState<T>> = {};\n if (initialFilters != null && initialFilters.length > 0) {\n state.activeFilters = new Map(\n initialFilters.map((entry) => [entry.filter.id, entry]),\n );\n }\n if (initialSorts != null && initialSorts.length > 0) {\n state.columnSorts = [...initialSorts];\n }\n return state;\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\n \"initialFilters\",\n \"initialSorts\",\n \"columnSpec\",\n \"columnSpecOptions\",\n \"name\",\n \"itemLabel\",\n \"enableColumnReordering\",\n \"defaultColumnWidth\",\n \"refreshToken\",\n \"identity\",\n \"toaster\",\n \"viewType\",\n \"interactionOptions\",\n]);\n\ntype AnyDataSheetProps<T> =\n DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;\n\nexport function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {\n /** Split provided props based on provider's needs */\n const [providerProps, rendererProps] = splitProps<\n AnyDataSheetProps<T>,\n DataSheetProviderProps<T>\n >(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\n // `initialData` and `startAfter` go to both sides: the provider creates the\n // store seeded with them, and the loader takes them as the first window it\n // needn't fetch and the cursor its chunks are counted from.\n const { initialData, startAfter } = props as {\n initialData?: any;\n startAfter?: string | number | null;\n };\n if (initialData != null) {\n providerProps.initialData = initialData;\n }\n if (startAfter != null) {\n providerProps.startAfter = startAfter;\n }\n return [providerProps, rendererProps] as const;\n}\n\nexport function DataSheetProvider<T>(\n props: DataSheetProviderProps<T> & { children: React.ReactNode },\n) {\n return h(\n ToasterContext,\n h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),\n );\n}\n\ntype DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {\n dataProvider?: ResolvedDataProvider;\n};\n\nexport function DataSheetProviderInner<T>(\n props: DataSheetProviderInnerProps<T>,\n) {\n const tableRef = useRef<Table>(null);\n\n const [interactionOptionsProps, providerProps] = splitProps<\n DataSheetProviderInnerProps<T>,\n InteractionOptions\n >(props, interactionOptionsKeys);\n const interactionOptions = resolveInteractionOptions(\n interactionOptionsProps,\n props.viewType ?? DataViewRendererType.TABLE,\n );\n\n const {\n children,\n columnSpec,\n columnSpecOptions,\n name,\n itemLabel,\n enableColumnReordering,\n defaultColumnWidth = 150,\n refreshToken,\n identity,\n } = providerProps;\n\n const { data, dataProvider, isLocalProvider } =\n useResolvedProvider<T>(providerProps);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n const storeAPI = useStoreAPI<T>();\n\n // The wrapper resolves the data source (see `DataSheet`); publish it into the\n // scoped atom so the loader/store read it, rather than the inner render\n // component resolving it each render. Kept updated as `data`/`provider`\n // changes.\n\n ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);\n ctx.useSync(interactionOptionsAtom, interactionOptions);\n\n const contentLabels = useMemo(() => {\n return { tableName: name, itemLabel };\n }, [name, itemLabel]);\n\n ctx.useSync(contentLabelsAtom, contentLabels);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n // Not sure how required this initialization is\n const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);\n\n useEffect(() => {\n // The store's `data` is the loader's for any fetched source (and may hold a\n // seeded first window from creation); only an in-memory `data` prop is\n // placed here.\n let localRows: Partial<DataSheetStore<T>> = {};\n if (isLocalProvider) {\n localRows = { data };\n }\n initializeStore({\n ...localRows,\n columnSpec: postprocessColumnSpec(baseSpec),\n // Suppress the loader's first-chunk auto-generation whenever the consumer\n // provided a spec at all — a function (derived later in `_DataSheet`) OR\n // an explicit array, *including an empty one*. An empty array means \"no\n // facet columns\" (e.g. a browse panel whose only control is a sheet-level\n // search), not \"please generate from the data\". Auto-gen runs only when\n // no `columnSpec` was passed.\n deferColumnSpec: columnSpec != null,\n editable: interactionOptions.enableEditing,\n enableColumnReordering,\n defaultColumnWidth,\n tableRef,\n });\n }, [\n data,\n interactionOptions.enableEditing,\n staticSpec,\n isFnSpec,\n columnSpecOptions,\n enableColumnReordering,\n ]);\n\n // Function `columnSpec`: derive the spec from the loaded rows (no separate\n // fetch of sample data), here at the provider level so BOTH renderers get it\n // — the sheet's cell grid and the panel's `FacetControls` read the same\n // derived spec. Derive once the first rows arrive, and re-derive when the\n // function's identity changes (a consumer memoizes it over its own view state\n // — hidden columns, order, overrides). Guarded by the function identity, so\n // it never re-runs as more rows page in (which would clobber in-store column\n // state on scroll).\n const loadedData = useSelector<T, T[]>((s) => s.data ?? []);\n const derivedSpecFor = useRef<unknown>(null);\n useEffect(() => {\n if (typeof columnSpec !== \"function\") return;\n if (derivedSpecFor.current === columnSpec) return;\n const rows = loadedData.filter((r) => r != null);\n if (rows.length === 0) return;\n derivedSpecFor.current = columnSpec;\n storeAPI.setState({ columnSpec: columnSpec(rows) });\n }, [columnSpec, loadedData, storeAPI]);\n\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.\n // after a save). Skips the initial mount (the loader does its own first\n // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one\n // provider-level `refreshToken`, whichever renderer is mounted.\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefresh((v) => v + 1);\n }, [refreshToken, bumpRefresh]);\n\n // Provider-backed, auto-refreshing row mutations on the action context\n // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and\n // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit\n // action persists through the active provider and then re-fetches. Only the\n // capabilities the provider supports are present.\n useEffect(() => {\n const p = dataProvider?.provider ?? null;\n const refresh = () => bumpRefresh((v) => v + 1);\n const withRefresh = <A extends any[]>(\n fn?: (...args: A) => Promise<void>,\n ) =>\n fn == null\n ? undefined\n : async (...args: A) => {\n await fn(...args);\n refresh();\n };\n storeAPI.setState({\n rowEditing: {\n saveRows: withRefresh(p?.saveRows?.bind(p)),\n deleteRows: withRefresh(p?.deleteRows?.bind(p)),\n insertRow: withRefresh(p?.insertRow?.bind(p)),\n refresh,\n },\n });\n }, [storeAPI, dataProvider, bumpRefresh]);\n\n // The active provider supplies the row identity for the edit overlay\n // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and\n // `_DataPanel` — falls back to the loose `identity` prop when the resolved\n // provider doesn't carry its own (e.g. before the first row loads).\n useEffect(() => {\n const id = dataProvider?.provider?.identity ?? identity;\n if (id != null) storeAPI.setState({ identity: id });\n }, [storeAPI, dataProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` (not a loose\n // `fetchData`/`data` source) without `deleteRows` disables deletion\n // entirely. Loose/local sources keep the in-table delete overlay. Shared by\n // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state\n // read by the shared `ActionsToolbar`.\n useEffect(() => {\n const canDeleteRows =\n !dataProvider?.isExplicitProvider ||\n dataProvider.provider?.deleteRows != null;\n storeAPI.setState({ canDeleteRows });\n }, [storeAPI, dataProvider]);\n\n return children;\n}\n\nexport function useStoreAPI<T>() {\n return useZustandStoreAPI<DataSheetStore<T>>(ctx);\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n return useZustandSelector<T, A>(ctx, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n // Auto-generate a plain column spec the first time real rows arrive — no\n // spec yet and none deferred to a function (a function spec is derived\n // separately). Keyed on \"spec still empty + a non-null row present\", NOT\n // on `data.length == 0`: the loader pre-fills `data` with a page of `null`\n // ghost rows on reset, so the array is non-empty before the first chunk.\n if (state.columnSpec.length == 0 && !state.deferColumnSpec) {\n const sample = newData.filter((row) => row != null);\n if (sample.length > 0) {\n next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);\n }\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n\ninterface ContentLabels {\n tableName: string | null | undefined;\n itemLabel: string | null | undefined;\n}\n\nconst contentLabelsAtom = atom<ContentLabels>({\n tableName: null,\n itemLabel: null,\n});\n\nexport const itemLabelAtom = atom<string>((get) => {\n return get(contentLabelsAtom).itemLabel ?? \"row\";\n});\nexport const tableNameAtom = atom<string | null>((get) => {\n let { tableName, itemLabel } = get(contentLabelsAtom);\n if (tableName != null) return tableName;\n if (itemLabel != null) capitalize(pluralize(itemLabel, 2));\n return \"Table\";\n});\n\nexport function useItemCount(n: number) {\n const dataKind = ctx.useValue(itemLabelAtom);\n return itemCount(n, dataKind ?? \"row\");\n}\n\nfunction itemCount(n: number, dataKind: string) {\n const base = n == 0 ? \"No\" : `${n}`;\n return base + \" \" + pluralize(dataKind, n);\n}\n\nexport function pluralize(singularForm: string, n: number) {\n const pluralForm = singularForm + \"s\";\n if (n == 0) return `${pluralForm}`;\n if (n == 1) return singularForm;\n return pluralForm;\n}\n\nexport function capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"names":["createScopedStore","zustandAPIAtom","zustandStoreAtom","atom","useMemo","createLocalProvider","resolveInitialData","createZustandStore","h","ZustandStoreProvider","toasterAtom","loaderSeedAtoms","seededRows","splitProps","interactionOptionsKeys","ToasterContext","ErrorBoundary","useRef","resolveInteractionOptions","DataViewRendererType","columnSpec","interactionOptionsAtom","generateColumnSpec","useEffect","postprocessColumnSpec","dataRefreshTokenAtom","useZustandStoreAPI","useZustandSelector","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;;;AAwDO,MAAM,MAAMA,YAAAA,kBAAA;AAEZ,MAAM,eAAeC,YAAAA;AAGrB,MAAM,YAAYC,YAAAA;AAIzB,MAAM,aAA2B,CAAA;AAEjC,MA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aAAa;AAC7C,CAAC;AACM,MAAM,gBAAgBA,YAAAA,KAAoB,CAAC,QAAQ;AACxD,MAAI,EAAE,WAAW,cAAc,IAAI,iBAAiB;AACpD,MAAI,aAAa,KAAM,QAAO;AAC9B,MAAI,aAAa,KAAM,YAAW,UAAU,WAAW,CAAC,CAAC;AACzD,SAAO;AACT,CAAC;AAEM,SAAS,aAAa,GAAW;AACtC,QAAM,WAAW,IAAI,SAAS,aAAa;AAC3C,SAAO,UAAU,GAAG,YAAY,KAAK;AACvC;AAEA,SAAS,UAAU,GAAW,UAAkB;AAC9C,QAAM,OAAO,KAAK,IAAI,OAAO,GAAG,CAAC;AACjC,SAAO,OAAO,MAAM,UAAU,UAAU,CAAC;AAC3C;AAEO,SAAS,UAAU,cAAsB,GAAW;AACzD,QAAM,aAAa,eAAe;AAClC,MAAI,KAAK,EAAG,QAAO,GAAG,UAAU;AAChC,MAAI,KAAK,EAAG,QAAO;AACnB,SAAO;AACT;AAEO,SAAS,WAAW,GAAW;AACpC,SAAO,EAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC;AAC9C;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"core.cjs","sources":["../../src/provider/core.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport {\n createScopedStore,\n zustandAPIAtom,\n zustandStoreAtom,\n atom,\n ZustandStoreProvider,\n useZustandSelector,\n useZustandStoreAPI,\n} from \"@macrostrat/scoped-store\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n TableDataProvider,\n} from \"./table-data.ts\";\nimport { ErrorBoundary, ToasterContext } from \"@macrostrat/ui-components\";\nimport {\n DataViewRendererType,\n InteractionOptions,\n interactionOptionsAtom,\n interactionOptionsKeys,\n resolveInteractionOptions,\n} from \"./interactions.ts\";\nimport { DataViewProps } from \"../data-view.ts\";\nimport {\n DataSheetProps,\n DataViewCoreProps,\n InitialDataChunk,\n} from \"../types.ts\";\nimport {\n loaderSeedAtoms,\n resolveInitialData,\n seededRows,\n} from \"./loader-state.ts\";\nimport { DataPanelProps } from \"../data-panel.ts\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = zustandAPIAtom;\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = zustandStoreAtom;\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<any>>) => {\n set(zustandStoreAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\n/** The resolved data source for the table, held in the provider layer (next to\n * the store) rather than resolved inside the render loop. `provider` is the\n * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local\n * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it\n * loads the whole array at once and shows no load progress). `isExplicitProvider`\n * distinguishes an explicit `provider` object from a loose `fetchData`/`data`\n * source — only an explicit provider without `deleteRows` disables row\n * deletion; loose sources keep the local delete overlay. */\nexport interface ResolvedDataProvider {\n provider: TableDataProvider<any> | null;\n isLocalProvider: boolean;\n isExplicitProvider: boolean;\n /** Row count of an in-memory (local) source, so a renderer can size the\n * loader's page to \"all of it\" without also receiving the `data` prop. `0`\n * for non-local sources. */\n localCount: number;\n}\n\nconst DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {\n provider: null,\n isLocalProvider: true,\n isExplicitProvider: false,\n localCount: 0,\n};\n\nexport const dataProviderAtom = atom<ResolvedDataProvider>(\n DEFAULT_DATA_PROVIDER,\n);\n\nconst EMPTY_ARRAY: any[] = [];\n\n/** Resolve a table's data source from the loose `provider` / `fetchData` /\n * `data` props (an explicit `provider` wins; else a loose `fetchData` (+\n * `identity`) is wrapped as one; else in-memory `data` becomes a local\n * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three\n * resolve identically. */\nexport function useResolvedProvider<T>(props: {\n provider?: TableDataProvider<T>;\n fetchData?: FetchData<T>;\n data?: T[];\n identity?: (row: T) => string | number | null | undefined;\n}): {\n data: T[];\n isLocalProvider: boolean;\n activeProvider: TableDataProvider<any> | null;\n dataProvider: ResolvedDataProvider;\n} {\n const _data = props.data ?? (EMPTY_ARRAY as T[]);\n const isLocalProvider = props.provider == null && props.fetchData == null;\n const isExplicitProvider = props.provider != null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (props.provider != null) return props.provider;\n if (props.fetchData != null) {\n return {\n fetchData: props.fetchData,\n identity: props.identity ?? ((r: any) => r?.id),\n } as TableDataProvider<any>;\n }\n if (_data.length > 0) {\n return createLocalProvider(\n _data,\n props.identity != null\n ? { identity: props.identity as (row: any) => string | number }\n : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.provider, props.fetchData, _data, props.identity]);\n const localCount = isLocalProvider ? _data.length : 0;\n const dataProvider = useMemo(\n () => ({\n provider: activeProvider,\n isLocalProvider,\n isExplicitProvider,\n localCount,\n }),\n [activeProvider, isLocalProvider, isExplicitProvider, localCount],\n );\n return { data: _data, isLocalProvider, activeProvider, dataProvider };\n}\n\nfunction DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {\n const {\n toaster,\n initialFilters,\n initialSorts,\n initialData,\n startAfter,\n ...rest\n } = props;\n\n // Initial view state is folded into the store's *creation*, not applied in an\n // effect: the loader mounts below this and its effects run first, so an\n // effect-applied filter would arrive after the first (unfiltered) fetch had\n // already gone out — and be immediately superseded. Creating the store with\n // the view already set means the first fetch is the right one.\n //\n // A seeded first window (`initialData`) is folded in the same way, for the\n // same reason and one more: rows placed at creation are in the first render,\n // so a server render carries them instead of the empty state the loader\n // shows until its first (asynchronous) page resolves.\n const seed = resolveInitialData(initialData);\n const initializeStore = (set: any, get: any) => ({\n ...createZustandStore<T>(set, get),\n ...initialViewState({ initialFilters, initialSorts }),\n ...initialDataState(seed),\n });\n\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore,\n atoms: [\n [toasterAtom, toaster],\n ...loaderSeedAtoms(initialData, startAfter),\n ],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\n/** The store's `data` for a seeded first window; nothing without a seed. */\nfunction initialDataState<T>(\n seed: InitialDataChunk<T> | null,\n): Partial<DataSheetState<T>> {\n if (seed == null) return {};\n return { data: seededRows(seed) as T[] };\n}\n\n/** The store fields that carry a caller-supplied starting view. Absent props\n * contribute nothing, so the store's own defaults stand. */\nfunction initialViewState<T>({\n initialFilters,\n initialSorts,\n}: Pick<DataViewCoreProps<T>, \"initialFilters\" | \"initialSorts\">): Partial<\n DataSheetState<T>\n> {\n const state: Partial<DataSheetState<T>> = {};\n if (initialFilters != null && initialFilters.length > 0) {\n state.activeFilters = new Map(\n initialFilters.map((entry) => [entry.filter.id, entry]),\n );\n }\n if (initialSorts != null && initialSorts.length > 0) {\n state.columnSorts = [...initialSorts];\n }\n return state;\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\n \"initialFilters\",\n \"initialSorts\",\n \"columnSpec\",\n \"columnSpecOptions\",\n \"name\",\n \"itemLabel\",\n \"enableColumnReordering\",\n \"defaultColumnWidth\",\n \"refreshToken\",\n \"identity\",\n \"toaster\",\n \"viewType\",\n \"interactionOptions\",\n]);\n\ntype AnyDataSheetProps<T> =\n DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;\n\nexport function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {\n /** Split provided props based on provider's needs */\n const [providerProps, rendererProps] = splitProps<\n AnyDataSheetProps<T>,\n DataSheetProviderProps<T>\n >(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\n // `initialData` and `startAfter` go to both sides: the provider creates the\n // store seeded with them, and the loader takes them as the first window it\n // needn't fetch and the cursor its chunks are counted from.\n const { initialData, startAfter } = props as {\n initialData?: any;\n startAfter?: string | number | null;\n };\n if (initialData != null) {\n providerProps.initialData = initialData;\n }\n if (startAfter != null) {\n providerProps.startAfter = startAfter;\n }\n return [providerProps, rendererProps] as const;\n}\n\nexport function DataSheetProvider<T>(\n props: DataSheetProviderProps<T> & { children: React.ReactNode },\n) {\n return h(\n ToasterContext,\n h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),\n );\n}\n\ntype DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {\n dataProvider?: ResolvedDataProvider;\n};\n\nexport function DataSheetProviderInner<T>(\n props: DataSheetProviderInnerProps<T>,\n) {\n const tableRef = useRef<Table>(null);\n\n const [interactionOptionsProps, providerProps] = splitProps<\n DataSheetProviderInnerProps<T>,\n InteractionOptions\n >(props, interactionOptionsKeys);\n const interactionOptions = resolveInteractionOptions(\n interactionOptionsProps,\n props.viewType ?? DataViewRendererType.TABLE,\n );\n\n const {\n children,\n columnSpec,\n columnSpecOptions,\n name,\n itemLabel,\n enableColumnReordering,\n defaultColumnWidth = 150,\n refreshToken,\n identity,\n } = providerProps;\n\n const { data, dataProvider, isLocalProvider } =\n useResolvedProvider<T>(providerProps);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n const storeAPI = useStoreAPI<T>();\n\n // The wrapper resolves the data source (see `DataSheet`); publish it into the\n // scoped atom so the loader/store read it, rather than the inner render\n // component resolving it each render. Kept updated as `data`/`provider`\n // changes.\n\n ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);\n ctx.useSync(interactionOptionsAtom, interactionOptions);\n\n const contentLabels = useMemo(() => {\n return { tableName: name, itemLabel };\n }, [name, itemLabel]);\n\n ctx.useSync(contentLabelsAtom, contentLabels);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n // Not sure how required this initialization is\n const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);\n\n useEffect(() => {\n // The store's `data` is the loader's for any fetched source (and may hold a\n // seeded first window from creation); only an in-memory `data` prop is\n // placed here.\n let localRows: Partial<DataSheetStore<T>> = {};\n if (isLocalProvider) {\n localRows = { data };\n }\n initializeStore({\n ...localRows,\n columnSpec: postprocessColumnSpec(baseSpec),\n // Suppress the loader's first-chunk auto-generation whenever the consumer\n // provided a spec at all — a function (derived later in `_DataSheet`) OR\n // an explicit array, *including an empty one*. An empty array means \"no\n // facet columns\" (e.g. a browse panel whose only control is a sheet-level\n // search), not \"please generate from the data\". Auto-gen runs only when\n // no `columnSpec` was passed.\n deferColumnSpec: columnSpec != null,\n editable: interactionOptions.enableEditing,\n enableColumnReordering,\n defaultColumnWidth,\n tableRef,\n });\n }, [\n data,\n interactionOptions.enableEditing,\n staticSpec,\n isFnSpec,\n columnSpecOptions,\n enableColumnReordering,\n ]);\n\n // Function `columnSpec`: derive the spec from the loaded rows (no separate\n // fetch of sample data), here at the provider level so BOTH renderers get it\n // — the sheet's cell grid and the panel's `FacetControls` read the same\n // derived spec. Derive once the first rows arrive, and re-derive when the\n // function's identity changes (a consumer memoizes it over its own view state\n // — hidden columns, order, overrides). Guarded by the function identity, so\n // it never re-runs as more rows page in (which would clobber in-store column\n // state on scroll).\n const loadedData = useSelector<T, T[]>((s) => s.data ?? []);\n const derivedSpecFor = useRef<unknown>(null);\n useEffect(() => {\n if (typeof columnSpec !== \"function\") return;\n if (derivedSpecFor.current === columnSpec) return;\n const rows = loadedData.filter((r) => r != null);\n if (rows.length === 0) return;\n derivedSpecFor.current = columnSpec;\n storeAPI.setState({ columnSpec: postprocessColumnSpec(columnSpec(rows)) });\n }, [columnSpec, loadedData, storeAPI]);\n\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.\n // after a save). Skips the initial mount (the loader does its own first\n // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one\n // provider-level `refreshToken`, whichever renderer is mounted.\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefresh((v) => v + 1);\n }, [refreshToken, bumpRefresh]);\n\n // Provider-backed, auto-refreshing row mutations on the action context\n // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and\n // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit\n // action persists through the active provider and then re-fetches. Only the\n // capabilities the provider supports are present.\n useEffect(() => {\n const p = dataProvider?.provider ?? null;\n const refresh = () => bumpRefresh((v) => v + 1);\n const withRefresh = <A extends any[]>(\n fn?: (...args: A) => Promise<void>,\n ) =>\n fn == null\n ? undefined\n : async (...args: A) => {\n await fn(...args);\n refresh();\n };\n storeAPI.setState({\n rowEditing: {\n saveRows: withRefresh(p?.saveRows?.bind(p)),\n deleteRows: withRefresh(p?.deleteRows?.bind(p)),\n insertRow: withRefresh(p?.insertRow?.bind(p)),\n refresh,\n },\n });\n }, [storeAPI, dataProvider, bumpRefresh]);\n\n // The active provider supplies the row identity for the edit overlay\n // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and\n // `_DataPanel` — falls back to the loose `identity` prop when the resolved\n // provider doesn't carry its own (e.g. before the first row loads).\n useEffect(() => {\n const id = dataProvider?.provider?.identity ?? identity;\n if (id != null) storeAPI.setState({ identity: id });\n }, [storeAPI, dataProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` (not a loose\n // `fetchData`/`data` source) without `deleteRows` disables deletion\n // entirely. Loose/local sources keep the in-table delete overlay. Shared by\n // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state\n // read by the shared `ActionsToolbar`.\n useEffect(() => {\n const canDeleteRows =\n !dataProvider?.isExplicitProvider ||\n dataProvider.provider?.deleteRows != null;\n storeAPI.setState({ canDeleteRows });\n }, [storeAPI, dataProvider]);\n\n return children;\n}\n\nexport function useStoreAPI<T>() {\n return useZustandStoreAPI<DataSheetStore<T>>(ctx);\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n return useZustandSelector<T, A>(ctx, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n // Auto-generate a plain column spec the first time real rows arrive — no\n // spec yet and none deferred to a function (a function spec is derived\n // separately). Keyed on \"spec still empty + a non-null row present\", NOT\n // on `data.length == 0`: the loader pre-fills `data` with a page of `null`\n // ghost rows on reset, so the array is non-empty before the first chunk.\n if (state.columnSpec.length == 0 && !state.deferColumnSpec) {\n const sample = newData.filter((row) => row != null);\n if (sample.length > 0) {\n next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);\n }\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n\ninterface ContentLabels {\n tableName: string | null | undefined;\n itemLabel: string | null | undefined;\n}\n\nconst contentLabelsAtom = atom<ContentLabels>({\n tableName: null,\n itemLabel: null,\n});\n\nexport const itemLabelAtom = atom<string>((get) => {\n return get(contentLabelsAtom).itemLabel ?? \"row\";\n});\nexport const tableNameAtom = atom<string | null>((get) => {\n let { tableName, itemLabel } = get(contentLabelsAtom);\n if (tableName != null) return tableName;\n if (itemLabel != null) capitalize(pluralize(itemLabel, 2));\n return \"Table\";\n});\n\nexport function useItemCount(n: number) {\n const dataKind = ctx.useValue(itemLabelAtom);\n return itemCount(n, dataKind ?? \"row\");\n}\n\nfunction itemCount(n: number, dataKind: string) {\n const base = n == 0 ? \"No\" : `${n}`;\n return base + \" \" + pluralize(dataKind, n);\n}\n\nexport function pluralize(singularForm: string, n: number) {\n if (n == 1) return singularForm;\n return pluralFormOf(singularForm);\n}\n\n/** An English plural, well enough for the nouns a sheet uses: \"row\" → \"rows\",\n * \"lithology\" → \"lithologies\", \"thickness (m)\" → \"thicknesses (m)\" — a\n * trailing parenthetical (a unit, say) stays as it is. */\nexport function pluralFormOf(singularForm: string): string {\n const match = singularForm.match(/^(.*?)(\\s*\\([^)]*\\))?$/);\n const head = match?.[1] ?? singularForm;\n const tail = match?.[2] ?? \"\";\n if (head === \"\") return singularForm;\n let plural = head + \"s\";\n if (/(s|x|z|ch|sh)$/i.test(head)) {\n plural = head + \"es\";\n } else if (/[^aeiou]y$/i.test(head)) {\n plural = head.slice(0, -1) + \"ies\";\n }\n return plural + tail;\n}\n\nexport function capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"names":["createScopedStore","zustandAPIAtom","zustandStoreAtom","atom","useMemo","createLocalProvider","resolveInitialData","createZustandStore","h","ZustandStoreProvider","toasterAtom","loaderSeedAtoms","seededRows","splitProps","interactionOptionsKeys","ToasterContext","ErrorBoundary","useRef","resolveInteractionOptions","DataViewRendererType","columnSpec","interactionOptionsAtom","generateColumnSpec","useEffect","postprocessColumnSpec","dataRefreshTokenAtom","useZustandStoreAPI","useZustandSelector","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;;;AAwDO,MAAM,MAAMA,YAAAA,kBAAA;AAEZ,MAAM,eAAeC,YAAAA;AAGrB,MAAM,YAAYC,YAAAA;AAIzB,MAAM,aAA2B,CAAA;AAEjC,MAAM,sBAAsBC,YAAAA;AAAAA,EAC1B;AAAA,EACA,CAAC,KAAK,KAAK,YAA0C;AACnD,QAAID,YAAAA,kBAAkB,CAAC,UAAU;AAC/B,aAAO;AAAA,QACL,GAAG;AAAA,QACH,GAAG;AAAA,MAAA;AAAA,IAEP,CAAC;AAAA,EACH;AACF;AAEO,MAAM,mBAAmBC,YAAAA,KAAoB,CAAA,CAAE;AAoBtD,MAAM,wBAA8C;AAAA,EAClD,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,YAAY;AACd;AAEO,MAAM,mBAAmBA,YAAAA;AAAAA,EAC9B;AACF;AAEA,MAAM,cAAqB,CAAA;AAOpB,SAAS,oBAAuB,OAUrC;AACA,QAAM,QAAQ,MAAM,QA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,SAAS,UAAU,cAAsB,GAAW;AACzD,MAAI,KAAK,EAAG,QAAO;AACnB,SAAO,aAAa,YAAY;AAClC;AAKO,SAAS,aAAa,cAA8B;AACzD,QAAM,QAAQ,aAAa,MAAM,wBAAwB;AACzD,QAAM,OAAO,QAAQ,CAAC,KAAK;AAC3B,QAAM,OAAO,QAAQ,CAAC,KAAK;AAC3B,MAAI,SAAS,GAAI,QAAO;AACxB,MAAI,SAAS,OAAO;AACpB,MAAI,kBAAkB,KAAK,IAAI,GAAG;AAChC,aAAS,OAAO;AAAA,EAClB,WAAW,cAAc,KAAK,IAAI,GAAG;AACnC,aAAS,KAAK,MAAM,GAAG,EAAE,IAAI;AAAA,EAC/B;AACA,SAAO,SAAS;AAClB;AAEO,SAAS,WAAW,GAAW;AACpC,SAAO,EAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC;AAC9C;;;;;;;;;;;;;;;;;;;;"}
@@ -68,5 +68,9 @@ export declare const itemLabelAtom: import('jotai').Atom<string>;
68
68
  export declare const tableNameAtom: import('jotai').Atom<string | null>;
69
69
  export declare function useItemCount(n: number): string;
70
70
  export declare function pluralize(singularForm: string, n: number): string;
71
+ /** An English plural, well enough for the nouns a sheet uses: "row" → "rows",
72
+ * "lithology" → "lithologies", "thickness (m)" → "thicknesses (m)" — a
73
+ * trailing parenthetical (a unit, say) stays as it is. */
74
+ export declare function pluralFormOf(singularForm: string): string;
71
75
  export declare function capitalize(s: string): string;
72
76
  export {};
@@ -223,7 +223,7 @@ function DataSheetProviderInner(props) {
223
223
  const rows = loadedData.filter((r) => r != null);
224
224
  if (rows.length === 0) return;
225
225
  derivedSpecFor.current = columnSpec;
226
- storeAPI.setState({ columnSpec: columnSpec(rows) });
226
+ storeAPI.setState({ columnSpec: postprocessColumnSpec(columnSpec(rows)) });
227
227
  }, [columnSpec, loadedData, storeAPI]);
228
228
  const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);
229
229
  const firstRefreshToken = useRef(true);
@@ -370,10 +370,21 @@ function itemCount(n, dataKind) {
370
370
  return base + " " + pluralize(dataKind, n);
371
371
  }
372
372
  function pluralize(singularForm, n) {
373
- const pluralForm = singularForm + "s";
374
- if (n == 0) return `${pluralForm}`;
375
373
  if (n == 1) return singularForm;
376
- return pluralForm;
374
+ return pluralFormOf(singularForm);
375
+ }
376
+ function pluralFormOf(singularForm) {
377
+ const match = singularForm.match(/^(.*?)(\s*\([^)]*\))?$/);
378
+ const head = match?.[1] ?? singularForm;
379
+ const tail = match?.[2] ?? "";
380
+ if (head === "") return singularForm;
381
+ let plural = head + "s";
382
+ if (/(s|x|z|ch|sh)$/i.test(head)) {
383
+ plural = head + "es";
384
+ } else if (/[^aeiou]y$/i.test(head)) {
385
+ plural = head.slice(0, -1) + "ies";
386
+ }
387
+ return plural + tail;
377
388
  }
378
389
  function capitalize(s) {
379
390
  return s.charAt(0).toUpperCase() + s.slice(1);
@@ -386,6 +397,7 @@ export {
386
397
  ctx,
387
398
  dataProviderAtom,
388
399
  itemLabelAtom,
400
+ pluralFormOf,
389
401
  pluralize,
390
402
  splitDataProviderProps,
391
403
  storeAPIAtom,
@@ -1 +1 @@
1
- {"version":3,"file":"core.js","sources":["../../src/provider/core.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport {\n createScopedStore,\n zustandAPIAtom,\n zustandStoreAtom,\n atom,\n ZustandStoreProvider,\n useZustandSelector,\n useZustandStoreAPI,\n} from \"@macrostrat/scoped-store\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n TableDataProvider,\n} from \"./table-data.ts\";\nimport { ErrorBoundary, ToasterContext } from \"@macrostrat/ui-components\";\nimport {\n DataViewRendererType,\n InteractionOptions,\n interactionOptionsAtom,\n interactionOptionsKeys,\n resolveInteractionOptions,\n} from \"./interactions.ts\";\nimport { DataViewProps } from \"../data-view.ts\";\nimport {\n DataSheetProps,\n DataViewCoreProps,\n InitialDataChunk,\n} from \"../types.ts\";\nimport {\n loaderSeedAtoms,\n resolveInitialData,\n seededRows,\n} from \"./loader-state.ts\";\nimport { DataPanelProps } from \"../data-panel.ts\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = zustandAPIAtom;\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = zustandStoreAtom;\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<any>>) => {\n set(zustandStoreAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\n/** The resolved data source for the table, held in the provider layer (next to\n * the store) rather than resolved inside the render loop. `provider` is the\n * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local\n * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it\n * loads the whole array at once and shows no load progress). `isExplicitProvider`\n * distinguishes an explicit `provider` object from a loose `fetchData`/`data`\n * source — only an explicit provider without `deleteRows` disables row\n * deletion; loose sources keep the local delete overlay. */\nexport interface ResolvedDataProvider {\n provider: TableDataProvider<any> | null;\n isLocalProvider: boolean;\n isExplicitProvider: boolean;\n /** Row count of an in-memory (local) source, so a renderer can size the\n * loader's page to \"all of it\" without also receiving the `data` prop. `0`\n * for non-local sources. */\n localCount: number;\n}\n\nconst DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {\n provider: null,\n isLocalProvider: true,\n isExplicitProvider: false,\n localCount: 0,\n};\n\nexport const dataProviderAtom = atom<ResolvedDataProvider>(\n DEFAULT_DATA_PROVIDER,\n);\n\nconst EMPTY_ARRAY: any[] = [];\n\n/** Resolve a table's data source from the loose `provider` / `fetchData` /\n * `data` props (an explicit `provider` wins; else a loose `fetchData` (+\n * `identity`) is wrapped as one; else in-memory `data` becomes a local\n * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three\n * resolve identically. */\nexport function useResolvedProvider<T>(props: {\n provider?: TableDataProvider<T>;\n fetchData?: FetchData<T>;\n data?: T[];\n identity?: (row: T) => string | number | null | undefined;\n}): {\n data: T[];\n isLocalProvider: boolean;\n activeProvider: TableDataProvider<any> | null;\n dataProvider: ResolvedDataProvider;\n} {\n const _data = props.data ?? (EMPTY_ARRAY as T[]);\n const isLocalProvider = props.provider == null && props.fetchData == null;\n const isExplicitProvider = props.provider != null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (props.provider != null) return props.provider;\n if (props.fetchData != null) {\n return {\n fetchData: props.fetchData,\n identity: props.identity ?? ((r: any) => r?.id),\n } as TableDataProvider<any>;\n }\n if (_data.length > 0) {\n return createLocalProvider(\n _data,\n props.identity != null\n ? { identity: props.identity as (row: any) => string | number }\n : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.provider, props.fetchData, _data, props.identity]);\n const localCount = isLocalProvider ? _data.length : 0;\n const dataProvider = useMemo(\n () => ({\n provider: activeProvider,\n isLocalProvider,\n isExplicitProvider,\n localCount,\n }),\n [activeProvider, isLocalProvider, isExplicitProvider, localCount],\n );\n return { data: _data, isLocalProvider, activeProvider, dataProvider };\n}\n\nfunction DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {\n const {\n toaster,\n initialFilters,\n initialSorts,\n initialData,\n startAfter,\n ...rest\n } = props;\n\n // Initial view state is folded into the store's *creation*, not applied in an\n // effect: the loader mounts below this and its effects run first, so an\n // effect-applied filter would arrive after the first (unfiltered) fetch had\n // already gone out — and be immediately superseded. Creating the store with\n // the view already set means the first fetch is the right one.\n //\n // A seeded first window (`initialData`) is folded in the same way, for the\n // same reason and one more: rows placed at creation are in the first render,\n // so a server render carries them instead of the empty state the loader\n // shows until its first (asynchronous) page resolves.\n const seed = resolveInitialData(initialData);\n const initializeStore = (set: any, get: any) => ({\n ...createZustandStore<T>(set, get),\n ...initialViewState({ initialFilters, initialSorts }),\n ...initialDataState(seed),\n });\n\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore,\n atoms: [\n [toasterAtom, toaster],\n ...loaderSeedAtoms(initialData, startAfter),\n ],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\n/** The store's `data` for a seeded first window; nothing without a seed. */\nfunction initialDataState<T>(\n seed: InitialDataChunk<T> | null,\n): Partial<DataSheetState<T>> {\n if (seed == null) return {};\n return { data: seededRows(seed) as T[] };\n}\n\n/** The store fields that carry a caller-supplied starting view. Absent props\n * contribute nothing, so the store's own defaults stand. */\nfunction initialViewState<T>({\n initialFilters,\n initialSorts,\n}: Pick<DataViewCoreProps<T>, \"initialFilters\" | \"initialSorts\">): Partial<\n DataSheetState<T>\n> {\n const state: Partial<DataSheetState<T>> = {};\n if (initialFilters != null && initialFilters.length > 0) {\n state.activeFilters = new Map(\n initialFilters.map((entry) => [entry.filter.id, entry]),\n );\n }\n if (initialSorts != null && initialSorts.length > 0) {\n state.columnSorts = [...initialSorts];\n }\n return state;\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\n \"initialFilters\",\n \"initialSorts\",\n \"columnSpec\",\n \"columnSpecOptions\",\n \"name\",\n \"itemLabel\",\n \"enableColumnReordering\",\n \"defaultColumnWidth\",\n \"refreshToken\",\n \"identity\",\n \"toaster\",\n \"viewType\",\n \"interactionOptions\",\n]);\n\ntype AnyDataSheetProps<T> =\n DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;\n\nexport function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {\n /** Split provided props based on provider's needs */\n const [providerProps, rendererProps] = splitProps<\n AnyDataSheetProps<T>,\n DataSheetProviderProps<T>\n >(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\n // `initialData` and `startAfter` go to both sides: the provider creates the\n // store seeded with them, and the loader takes them as the first window it\n // needn't fetch and the cursor its chunks are counted from.\n const { initialData, startAfter } = props as {\n initialData?: any;\n startAfter?: string | number | null;\n };\n if (initialData != null) {\n providerProps.initialData = initialData;\n }\n if (startAfter != null) {\n providerProps.startAfter = startAfter;\n }\n return [providerProps, rendererProps] as const;\n}\n\nexport function DataSheetProvider<T>(\n props: DataSheetProviderProps<T> & { children: React.ReactNode },\n) {\n return h(\n ToasterContext,\n h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),\n );\n}\n\ntype DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {\n dataProvider?: ResolvedDataProvider;\n};\n\nexport function DataSheetProviderInner<T>(\n props: DataSheetProviderInnerProps<T>,\n) {\n const tableRef = useRef<Table>(null);\n\n const [interactionOptionsProps, providerProps] = splitProps<\n DataSheetProviderInnerProps<T>,\n InteractionOptions\n >(props, interactionOptionsKeys);\n const interactionOptions = resolveInteractionOptions(\n interactionOptionsProps,\n props.viewType ?? DataViewRendererType.TABLE,\n );\n\n const {\n children,\n columnSpec,\n columnSpecOptions,\n name,\n itemLabel,\n enableColumnReordering,\n defaultColumnWidth = 150,\n refreshToken,\n identity,\n } = providerProps;\n\n const { data, dataProvider, isLocalProvider } =\n useResolvedProvider<T>(providerProps);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n const storeAPI = useStoreAPI<T>();\n\n // The wrapper resolves the data source (see `DataSheet`); publish it into the\n // scoped atom so the loader/store read it, rather than the inner render\n // component resolving it each render. Kept updated as `data`/`provider`\n // changes.\n\n ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);\n ctx.useSync(interactionOptionsAtom, interactionOptions);\n\n const contentLabels = useMemo(() => {\n return { tableName: name, itemLabel };\n }, [name, itemLabel]);\n\n ctx.useSync(contentLabelsAtom, contentLabels);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n // Not sure how required this initialization is\n const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);\n\n useEffect(() => {\n // The store's `data` is the loader's for any fetched source (and may hold a\n // seeded first window from creation); only an in-memory `data` prop is\n // placed here.\n let localRows: Partial<DataSheetStore<T>> = {};\n if (isLocalProvider) {\n localRows = { data };\n }\n initializeStore({\n ...localRows,\n columnSpec: postprocessColumnSpec(baseSpec),\n // Suppress the loader's first-chunk auto-generation whenever the consumer\n // provided a spec at all — a function (derived later in `_DataSheet`) OR\n // an explicit array, *including an empty one*. An empty array means \"no\n // facet columns\" (e.g. a browse panel whose only control is a sheet-level\n // search), not \"please generate from the data\". Auto-gen runs only when\n // no `columnSpec` was passed.\n deferColumnSpec: columnSpec != null,\n editable: interactionOptions.enableEditing,\n enableColumnReordering,\n defaultColumnWidth,\n tableRef,\n });\n }, [\n data,\n interactionOptions.enableEditing,\n staticSpec,\n isFnSpec,\n columnSpecOptions,\n enableColumnReordering,\n ]);\n\n // Function `columnSpec`: derive the spec from the loaded rows (no separate\n // fetch of sample data), here at the provider level so BOTH renderers get it\n // — the sheet's cell grid and the panel's `FacetControls` read the same\n // derived spec. Derive once the first rows arrive, and re-derive when the\n // function's identity changes (a consumer memoizes it over its own view state\n // — hidden columns, order, overrides). Guarded by the function identity, so\n // it never re-runs as more rows page in (which would clobber in-store column\n // state on scroll).\n const loadedData = useSelector<T, T[]>((s) => s.data ?? []);\n const derivedSpecFor = useRef<unknown>(null);\n useEffect(() => {\n if (typeof columnSpec !== \"function\") return;\n if (derivedSpecFor.current === columnSpec) return;\n const rows = loadedData.filter((r) => r != null);\n if (rows.length === 0) return;\n derivedSpecFor.current = columnSpec;\n storeAPI.setState({ columnSpec: columnSpec(rows) });\n }, [columnSpec, loadedData, storeAPI]);\n\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.\n // after a save). Skips the initial mount (the loader does its own first\n // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one\n // provider-level `refreshToken`, whichever renderer is mounted.\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefresh((v) => v + 1);\n }, [refreshToken, bumpRefresh]);\n\n // Provider-backed, auto-refreshing row mutations on the action context\n // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and\n // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit\n // action persists through the active provider and then re-fetches. Only the\n // capabilities the provider supports are present.\n useEffect(() => {\n const p = dataProvider?.provider ?? null;\n const refresh = () => bumpRefresh((v) => v + 1);\n const withRefresh = <A extends any[]>(\n fn?: (...args: A) => Promise<void>,\n ) =>\n fn == null\n ? undefined\n : async (...args: A) => {\n await fn(...args);\n refresh();\n };\n storeAPI.setState({\n rowEditing: {\n saveRows: withRefresh(p?.saveRows?.bind(p)),\n deleteRows: withRefresh(p?.deleteRows?.bind(p)),\n insertRow: withRefresh(p?.insertRow?.bind(p)),\n refresh,\n },\n });\n }, [storeAPI, dataProvider, bumpRefresh]);\n\n // The active provider supplies the row identity for the edit overlay\n // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and\n // `_DataPanel` — falls back to the loose `identity` prop when the resolved\n // provider doesn't carry its own (e.g. before the first row loads).\n useEffect(() => {\n const id = dataProvider?.provider?.identity ?? identity;\n if (id != null) storeAPI.setState({ identity: id });\n }, [storeAPI, dataProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` (not a loose\n // `fetchData`/`data` source) without `deleteRows` disables deletion\n // entirely. Loose/local sources keep the in-table delete overlay. Shared by\n // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state\n // read by the shared `ActionsToolbar`.\n useEffect(() => {\n const canDeleteRows =\n !dataProvider?.isExplicitProvider ||\n dataProvider.provider?.deleteRows != null;\n storeAPI.setState({ canDeleteRows });\n }, [storeAPI, dataProvider]);\n\n return children;\n}\n\nexport function useStoreAPI<T>() {\n return useZustandStoreAPI<DataSheetStore<T>>(ctx);\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n return useZustandSelector<T, A>(ctx, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n // Auto-generate a plain column spec the first time real rows arrive — no\n // spec yet and none deferred to a function (a function spec is derived\n // separately). Keyed on \"spec still empty + a non-null row present\", NOT\n // on `data.length == 0`: the loader pre-fills `data` with a page of `null`\n // ghost rows on reset, so the array is non-empty before the first chunk.\n if (state.columnSpec.length == 0 && !state.deferColumnSpec) {\n const sample = newData.filter((row) => row != null);\n if (sample.length > 0) {\n next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);\n }\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n\ninterface ContentLabels {\n tableName: string | null | undefined;\n itemLabel: string | null | undefined;\n}\n\nconst contentLabelsAtom = atom<ContentLabels>({\n tableName: null,\n itemLabel: null,\n});\n\nexport const itemLabelAtom = atom<string>((get) => {\n return get(contentLabelsAtom).itemLabel ?? \"row\";\n});\nexport const tableNameAtom = atom<string | null>((get) => {\n let { tableName, itemLabel } = get(contentLabelsAtom);\n if (tableName != null) return tableName;\n if (itemLabel != null) capitalize(pluralize(itemLabel, 2));\n return \"Table\";\n});\n\nexport function useItemCount(n: number) {\n const dataKind = ctx.useValue(itemLabelAtom);\n return itemCount(n, dataKind ?? \"row\");\n}\n\nfunction itemCount(n: number, dataKind: string) {\n const base = n == 0 ? \"No\" : `${n}`;\n return base + \" \" + pluralize(dataKind, n);\n}\n\nexport function pluralize(singularForm: string, n: number) {\n const pluralForm = singularForm + \"s\";\n if (n == 0) return `${pluralForm}`;\n if (n == 1) return singularForm;\n return pluralForm;\n}\n\nexport function capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAwDO,MAAM,MAAM,kBAAA;AAEZ,MAAM,eAAe;AAGrB,MA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AM,OAAO,KAAK,IAAI,OAAO,GAAG,CAAC;AACjC,SAAO,OAAO,MAAM,UAAU,UAAU,CAAC;AAC3C;AAEO,SAAS,UAAU,cAAsB,GAAW;AACzD,QAAM,aAAa,eAAe;AAClC,MAAI,KAAK,EAAG,QAAO,GAAG,UAAU;AAChC,MAAI,KAAK,EAAG,QAAO;AACnB,SAAO;AACT;AAEO,SAAS,WAAW,GAAW;AACpC,SAAO,EAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC;AAC9C;"}
1
+ {"version":3,"file":"core.js","sources":["../../src/provider/core.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport {\n createScopedStore,\n zustandAPIAtom,\n zustandStoreAtom,\n atom,\n ZustandStoreProvider,\n useZustandSelector,\n useZustandStoreAPI,\n} from \"@macrostrat/scoped-store\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n TableDataProvider,\n} from \"./table-data.ts\";\nimport { ErrorBoundary, ToasterContext } from \"@macrostrat/ui-components\";\nimport {\n DataViewRendererType,\n InteractionOptions,\n interactionOptionsAtom,\n interactionOptionsKeys,\n resolveInteractionOptions,\n} from \"./interactions.ts\";\nimport { DataViewProps } from \"../data-view.ts\";\nimport {\n DataSheetProps,\n DataViewCoreProps,\n InitialDataChunk,\n} from \"../types.ts\";\nimport {\n loaderSeedAtoms,\n resolveInitialData,\n seededRows,\n} from \"./loader-state.ts\";\nimport { DataPanelProps } from \"../data-panel.ts\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = zustandAPIAtom;\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = zustandStoreAtom;\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<any>>) => {\n set(zustandStoreAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\n/** The resolved data source for the table, held in the provider layer (next to\n * the store) rather than resolved inside the render loop. `provider` is the\n * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local\n * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it\n * loads the whole array at once and shows no load progress). `isExplicitProvider`\n * distinguishes an explicit `provider` object from a loose `fetchData`/`data`\n * source — only an explicit provider without `deleteRows` disables row\n * deletion; loose sources keep the local delete overlay. */\nexport interface ResolvedDataProvider {\n provider: TableDataProvider<any> | null;\n isLocalProvider: boolean;\n isExplicitProvider: boolean;\n /** Row count of an in-memory (local) source, so a renderer can size the\n * loader's page to \"all of it\" without also receiving the `data` prop. `0`\n * for non-local sources. */\n localCount: number;\n}\n\nconst DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {\n provider: null,\n isLocalProvider: true,\n isExplicitProvider: false,\n localCount: 0,\n};\n\nexport const dataProviderAtom = atom<ResolvedDataProvider>(\n DEFAULT_DATA_PROVIDER,\n);\n\nconst EMPTY_ARRAY: any[] = [];\n\n/** Resolve a table's data source from the loose `provider` / `fetchData` /\n * `data` props (an explicit `provider` wins; else a loose `fetchData` (+\n * `identity`) is wrapped as one; else in-memory `data` becomes a local\n * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three\n * resolve identically. */\nexport function useResolvedProvider<T>(props: {\n provider?: TableDataProvider<T>;\n fetchData?: FetchData<T>;\n data?: T[];\n identity?: (row: T) => string | number | null | undefined;\n}): {\n data: T[];\n isLocalProvider: boolean;\n activeProvider: TableDataProvider<any> | null;\n dataProvider: ResolvedDataProvider;\n} {\n const _data = props.data ?? (EMPTY_ARRAY as T[]);\n const isLocalProvider = props.provider == null && props.fetchData == null;\n const isExplicitProvider = props.provider != null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (props.provider != null) return props.provider;\n if (props.fetchData != null) {\n return {\n fetchData: props.fetchData,\n identity: props.identity ?? ((r: any) => r?.id),\n } as TableDataProvider<any>;\n }\n if (_data.length > 0) {\n return createLocalProvider(\n _data,\n props.identity != null\n ? { identity: props.identity as (row: any) => string | number }\n : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.provider, props.fetchData, _data, props.identity]);\n const localCount = isLocalProvider ? _data.length : 0;\n const dataProvider = useMemo(\n () => ({\n provider: activeProvider,\n isLocalProvider,\n isExplicitProvider,\n localCount,\n }),\n [activeProvider, isLocalProvider, isExplicitProvider, localCount],\n );\n return { data: _data, isLocalProvider, activeProvider, dataProvider };\n}\n\nfunction DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {\n const {\n toaster,\n initialFilters,\n initialSorts,\n initialData,\n startAfter,\n ...rest\n } = props;\n\n // Initial view state is folded into the store's *creation*, not applied in an\n // effect: the loader mounts below this and its effects run first, so an\n // effect-applied filter would arrive after the first (unfiltered) fetch had\n // already gone out — and be immediately superseded. Creating the store with\n // the view already set means the first fetch is the right one.\n //\n // A seeded first window (`initialData`) is folded in the same way, for the\n // same reason and one more: rows placed at creation are in the first render,\n // so a server render carries them instead of the empty state the loader\n // shows until its first (asynchronous) page resolves.\n const seed = resolveInitialData(initialData);\n const initializeStore = (set: any, get: any) => ({\n ...createZustandStore<T>(set, get),\n ...initialViewState({ initialFilters, initialSorts }),\n ...initialDataState(seed),\n });\n\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore,\n atoms: [\n [toasterAtom, toaster],\n ...loaderSeedAtoms(initialData, startAfter),\n ],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\n/** The store's `data` for a seeded first window; nothing without a seed. */\nfunction initialDataState<T>(\n seed: InitialDataChunk<T> | null,\n): Partial<DataSheetState<T>> {\n if (seed == null) return {};\n return { data: seededRows(seed) as T[] };\n}\n\n/** The store fields that carry a caller-supplied starting view. Absent props\n * contribute nothing, so the store's own defaults stand. */\nfunction initialViewState<T>({\n initialFilters,\n initialSorts,\n}: Pick<DataViewCoreProps<T>, \"initialFilters\" | \"initialSorts\">): Partial<\n DataSheetState<T>\n> {\n const state: Partial<DataSheetState<T>> = {};\n if (initialFilters != null && initialFilters.length > 0) {\n state.activeFilters = new Map(\n initialFilters.map((entry) => [entry.filter.id, entry]),\n );\n }\n if (initialSorts != null && initialSorts.length > 0) {\n state.columnSorts = [...initialSorts];\n }\n return state;\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\n \"initialFilters\",\n \"initialSorts\",\n \"columnSpec\",\n \"columnSpecOptions\",\n \"name\",\n \"itemLabel\",\n \"enableColumnReordering\",\n \"defaultColumnWidth\",\n \"refreshToken\",\n \"identity\",\n \"toaster\",\n \"viewType\",\n \"interactionOptions\",\n]);\n\ntype AnyDataSheetProps<T> =\n DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;\n\nexport function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {\n /** Split provided props based on provider's needs */\n const [providerProps, rendererProps] = splitProps<\n AnyDataSheetProps<T>,\n DataSheetProviderProps<T>\n >(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\n // `initialData` and `startAfter` go to both sides: the provider creates the\n // store seeded with them, and the loader takes them as the first window it\n // needn't fetch and the cursor its chunks are counted from.\n const { initialData, startAfter } = props as {\n initialData?: any;\n startAfter?: string | number | null;\n };\n if (initialData != null) {\n providerProps.initialData = initialData;\n }\n if (startAfter != null) {\n providerProps.startAfter = startAfter;\n }\n return [providerProps, rendererProps] as const;\n}\n\nexport function DataSheetProvider<T>(\n props: DataSheetProviderProps<T> & { children: React.ReactNode },\n) {\n return h(\n ToasterContext,\n h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),\n );\n}\n\ntype DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {\n dataProvider?: ResolvedDataProvider;\n};\n\nexport function DataSheetProviderInner<T>(\n props: DataSheetProviderInnerProps<T>,\n) {\n const tableRef = useRef<Table>(null);\n\n const [interactionOptionsProps, providerProps] = splitProps<\n DataSheetProviderInnerProps<T>,\n InteractionOptions\n >(props, interactionOptionsKeys);\n const interactionOptions = resolveInteractionOptions(\n interactionOptionsProps,\n props.viewType ?? DataViewRendererType.TABLE,\n );\n\n const {\n children,\n columnSpec,\n columnSpecOptions,\n name,\n itemLabel,\n enableColumnReordering,\n defaultColumnWidth = 150,\n refreshToken,\n identity,\n } = providerProps;\n\n const { data, dataProvider, isLocalProvider } =\n useResolvedProvider<T>(providerProps);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n const storeAPI = useStoreAPI<T>();\n\n // The wrapper resolves the data source (see `DataSheet`); publish it into the\n // scoped atom so the loader/store read it, rather than the inner render\n // component resolving it each render. Kept updated as `data`/`provider`\n // changes.\n\n ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);\n ctx.useSync(interactionOptionsAtom, interactionOptions);\n\n const contentLabels = useMemo(() => {\n return { tableName: name, itemLabel };\n }, [name, itemLabel]);\n\n ctx.useSync(contentLabelsAtom, contentLabels);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n // Not sure how required this initialization is\n const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);\n\n useEffect(() => {\n // The store's `data` is the loader's for any fetched source (and may hold a\n // seeded first window from creation); only an in-memory `data` prop is\n // placed here.\n let localRows: Partial<DataSheetStore<T>> = {};\n if (isLocalProvider) {\n localRows = { data };\n }\n initializeStore({\n ...localRows,\n columnSpec: postprocessColumnSpec(baseSpec),\n // Suppress the loader's first-chunk auto-generation whenever the consumer\n // provided a spec at all — a function (derived later in `_DataSheet`) OR\n // an explicit array, *including an empty one*. An empty array means \"no\n // facet columns\" (e.g. a browse panel whose only control is a sheet-level\n // search), not \"please generate from the data\". Auto-gen runs only when\n // no `columnSpec` was passed.\n deferColumnSpec: columnSpec != null,\n editable: interactionOptions.enableEditing,\n enableColumnReordering,\n defaultColumnWidth,\n tableRef,\n });\n }, [\n data,\n interactionOptions.enableEditing,\n staticSpec,\n isFnSpec,\n columnSpecOptions,\n enableColumnReordering,\n ]);\n\n // Function `columnSpec`: derive the spec from the loaded rows (no separate\n // fetch of sample data), here at the provider level so BOTH renderers get it\n // — the sheet's cell grid and the panel's `FacetControls` read the same\n // derived spec. Derive once the first rows arrive, and re-derive when the\n // function's identity changes (a consumer memoizes it over its own view state\n // — hidden columns, order, overrides). Guarded by the function identity, so\n // it never re-runs as more rows page in (which would clobber in-store column\n // state on scroll).\n const loadedData = useSelector<T, T[]>((s) => s.data ?? []);\n const derivedSpecFor = useRef<unknown>(null);\n useEffect(() => {\n if (typeof columnSpec !== \"function\") return;\n if (derivedSpecFor.current === columnSpec) return;\n const rows = loadedData.filter((r) => r != null);\n if (rows.length === 0) return;\n derivedSpecFor.current = columnSpec;\n storeAPI.setState({ columnSpec: postprocessColumnSpec(columnSpec(rows)) });\n }, [columnSpec, loadedData, storeAPI]);\n\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.\n // after a save). Skips the initial mount (the loader does its own first\n // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one\n // provider-level `refreshToken`, whichever renderer is mounted.\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefresh((v) => v + 1);\n }, [refreshToken, bumpRefresh]);\n\n // Provider-backed, auto-refreshing row mutations on the action context\n // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and\n // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit\n // action persists through the active provider and then re-fetches. Only the\n // capabilities the provider supports are present.\n useEffect(() => {\n const p = dataProvider?.provider ?? null;\n const refresh = () => bumpRefresh((v) => v + 1);\n const withRefresh = <A extends any[]>(\n fn?: (...args: A) => Promise<void>,\n ) =>\n fn == null\n ? undefined\n : async (...args: A) => {\n await fn(...args);\n refresh();\n };\n storeAPI.setState({\n rowEditing: {\n saveRows: withRefresh(p?.saveRows?.bind(p)),\n deleteRows: withRefresh(p?.deleteRows?.bind(p)),\n insertRow: withRefresh(p?.insertRow?.bind(p)),\n refresh,\n },\n });\n }, [storeAPI, dataProvider, bumpRefresh]);\n\n // The active provider supplies the row identity for the edit overlay\n // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and\n // `_DataPanel` — falls back to the loose `identity` prop when the resolved\n // provider doesn't carry its own (e.g. before the first row loads).\n useEffect(() => {\n const id = dataProvider?.provider?.identity ?? identity;\n if (id != null) storeAPI.setState({ identity: id });\n }, [storeAPI, dataProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` (not a loose\n // `fetchData`/`data` source) without `deleteRows` disables deletion\n // entirely. Loose/local sources keep the in-table delete overlay. Shared by\n // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state\n // read by the shared `ActionsToolbar`.\n useEffect(() => {\n const canDeleteRows =\n !dataProvider?.isExplicitProvider ||\n dataProvider.provider?.deleteRows != null;\n storeAPI.setState({ canDeleteRows });\n }, [storeAPI, dataProvider]);\n\n return children;\n}\n\nexport function useStoreAPI<T>() {\n return useZustandStoreAPI<DataSheetStore<T>>(ctx);\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n return useZustandSelector<T, A>(ctx, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n // Auto-generate a plain column spec the first time real rows arrive — no\n // spec yet and none deferred to a function (a function spec is derived\n // separately). Keyed on \"spec still empty + a non-null row present\", NOT\n // on `data.length == 0`: the loader pre-fills `data` with a page of `null`\n // ghost rows on reset, so the array is non-empty before the first chunk.\n if (state.columnSpec.length == 0 && !state.deferColumnSpec) {\n const sample = newData.filter((row) => row != null);\n if (sample.length > 0) {\n next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);\n }\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n\ninterface ContentLabels {\n tableName: string | null | undefined;\n itemLabel: string | null | undefined;\n}\n\nconst contentLabelsAtom = atom<ContentLabels>({\n tableName: null,\n itemLabel: null,\n});\n\nexport const itemLabelAtom = atom<string>((get) => {\n return get(contentLabelsAtom).itemLabel ?? \"row\";\n});\nexport const tableNameAtom = atom<string | null>((get) => {\n let { tableName, itemLabel } = get(contentLabelsAtom);\n if (tableName != null) return tableName;\n if (itemLabel != null) capitalize(pluralize(itemLabel, 2));\n return \"Table\";\n});\n\nexport function useItemCount(n: number) {\n const dataKind = ctx.useValue(itemLabelAtom);\n return itemCount(n, dataKind ?? \"row\");\n}\n\nfunction itemCount(n: number, dataKind: string) {\n const base = n == 0 ? \"No\" : `${n}`;\n return base + \" \" + pluralize(dataKind, n);\n}\n\nexport function pluralize(singularForm: string, n: number) {\n if (n == 1) return singularForm;\n return pluralFormOf(singularForm);\n}\n\n/** An English plural, well enough for the nouns a sheet uses: \"row\" → \"rows\",\n * \"lithology\" → \"lithologies\", \"thickness (m)\" → \"thicknesses (m)\" — a\n * trailing parenthetical (a unit, say) stays as it is. */\nexport function pluralFormOf(singularForm: string): string {\n const match = singularForm.match(/^(.*?)(\\s*\\([^)]*\\))?$/);\n const head = match?.[1] ?? singularForm;\n const tail = match?.[2] ?? \"\";\n if (head === \"\") return singularForm;\n let plural = head + \"s\";\n if (/(s|x|z|ch|sh)$/i.test(head)) {\n plural = head + \"es\";\n } else if (/[^aeiou]y$/i.test(head)) {\n plural = head.slice(0, -1) + \"ies\";\n }\n return plural + tail;\n}\n\nexport function capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAwDO,MAAM,MAAM,kBAAA;AAEZ,MAAM,eAAe;AAGrB,MAAM,YAA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AC9C,QAAM,OAAO,KAAK,IAAI,OAAO,GAAG,CAAC;AACjC,SAAO,OAAO,MAAM,UAAU,UAAU,CAAC;AAC3C;AAEO,SAAS,UAAU,cAAsB,GAAW;AACzD,MAAI,KAAK,EAAG,QAAO;AACnB,SAAO,aAAa,YAAY;AAClC;AAKO,SAAS,aAAa,cAA8B;AACzD,QAAM,QAAQ,aAAa,MAAM,wBAAwB;AACzD,QAAM,OAAO,QAAQ,CAAC,KAAK;AAC3B,QAAM,OAAO,QAAQ,CAAC,KAAK;AAC3B,MAAI,SAAS,GAAI,QAAO;AACxB,MAAI,SAAS,OAAO;AACpB,MAAI,kBAAkB,KAAK,IAAI,GAAG;AAChC,aAAS,OAAO;AAAA,EAClB,WAAW,cAAc,KAAK,IAAI,GAAG;AACnC,aAAS,KAAK,MAAM,GAAG,EAAE,IAAI;AAAA,EAC/B;AACA,SAAO,SAAS;AAClB;AAEO,SAAS,WAAW,GAAW;AACpC,SAAO,EAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC;AAC9C;"}
@@ -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\";\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
  /**
@@ -136,7 +139,7 @@ export interface DataSheetState<T> {
136
139
  /** Whether selecting a cell automatically activates its surface (opens an
137
140
  * editor/detail panel and, for editors, focuses it). `"manual"` opens only
138
141
  * on click. */
139
- cellInteraction: "auto" | "manual";
142
+ cellInteraction: "auto" | "manual" | "second-click";
140
143
  /** Runtime override of `cellInteraction`: while `false`, auto-activation is
141
144
  * suppressed (set by pressing Escape, re-armed by clicking a cell) so the
142
145
  * keyboard prioritizes navigation. */
@@ -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\";\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;"}