@macrostrat/data-sheet 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/data-panel.cjs +36 -0
  3. package/dist/data-panel.cjs.map +1 -1
  4. package/dist/data-panel.d.ts +3 -2
  5. package/dist/data-panel.js +37 -1
  6. package/dist/data-panel.js.map +1 -1
  7. package/dist/data-panel.module.sass.cjs +28 -26
  8. package/dist/data-panel.module.sass.cjs.map +1 -1
  9. package/dist/data-panel.module.sass.js +28 -26
  10. package/dist/data-panel.module.sass.js.map +1 -1
  11. package/dist/data-sheet.css +59 -36
  12. package/dist/data-sheet.d.ts +2 -1
  13. package/dist/data-view.d.ts +1 -0
  14. package/dist/index.cjs +1 -0
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.js +2 -1
  17. package/dist/postgrest-table/data-loaders.cjs +8 -1
  18. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  19. package/dist/postgrest-table/data-loaders.js +9 -2
  20. package/dist/postgrest-table/data-loaders.js.map +1 -1
  21. package/dist/provider/core.cjs +16 -3
  22. package/dist/provider/core.cjs.map +1 -1
  23. package/dist/provider/core.d.ts +1 -1
  24. package/dist/provider/core.js +16 -3
  25. package/dist/provider/core.js.map +1 -1
  26. package/dist/provider/loader-state.cjs +11 -3
  27. package/dist/provider/loader-state.cjs.map +1 -1
  28. package/dist/provider/loader-state.d.ts +8 -1
  29. package/dist/provider/loader-state.js +12 -4
  30. package/dist/provider/loader-state.js.map +1 -1
  31. package/dist/provider/table-data.cjs +10 -1
  32. package/dist/provider/table-data.cjs.map +1 -1
  33. package/dist/provider/table-data.d.ts +10 -0
  34. package/dist/provider/table-data.js +11 -2
  35. package/dist/provider/table-data.js.map +1 -1
  36. package/dist/provider/types.cjs.map +1 -1
  37. package/dist/provider/types.d.ts +3 -0
  38. package/dist/provider/types.js.map +1 -1
  39. package/dist/types.cjs.map +1 -1
  40. package/dist/types.d.ts +25 -0
  41. package/dist/types.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/data-panel.module.sass +25 -0
  44. package/src/data-panel.ts +50 -1
  45. package/src/postgrest-table/data-loaders.ts +13 -0
  46. package/src/provider/core.ts +22 -5
  47. package/src/provider/loader-state.ts +15 -2
  48. package/src/provider/table-data.ts +23 -1
  49. package/src/provider/types.ts +3 -0
  50. package/src/types.ts +26 -0
@@ -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 { toaster, initialFilters, initialSorts, initialData, ...rest } = 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: [[toasterAtom, toaster], ...loaderSeedAtoms(initialData)],\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` goes to both sides: the provider creates the store seeded\n // with it, and the loader takes it as the first window it needn't fetch.\n const initialData = (props as { initialData?: any }).initialData;\n if (initialData != null) {\n providerProps.initialData = initialData;\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,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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K;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: 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,MAA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,KAAa,CAAC,QAAQ;AACjD,SAAO,IAAI,iBAAiB,EAAE,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;;;;;;;;;;;;;;;;;;;"}
@@ -51,7 +51,7 @@ export declare function useResolvedProvider<T>(props: {
51
51
  dataProvider: ResolvedDataProvider;
52
52
  };
53
53
  type AnyDataSheetProps<T> = DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;
54
- export declare function splitDataProviderProps<T>(props: AnyDataSheetProps<T>): readonly [DataSheetProviderProps<T>, Omit<AnyDataSheetProps<T>, "initialData" | "children" | "toaster" | "viewType" | keyof DataViewCoreProps<T>>];
54
+ export declare function splitDataProviderProps<T>(props: AnyDataSheetProps<T>): readonly [DataSheetProviderProps<T>, Omit<AnyDataSheetProps<T>, "initialData" | "startAfter" | "children" | "toaster" | "viewType" | keyof DataViewCoreProps<T>>];
55
55
  export declare function DataSheetProvider<T>(props: DataSheetProviderProps<T> & {
56
56
  children: React.ReactNode;
57
57
  }): import('react').FunctionComponentElement<import('@macrostrat/ui-components').ToasterContextProps>;
@@ -69,7 +69,14 @@ function useResolvedProvider(props) {
69
69
  return { data: _data, isLocalProvider, activeProvider, dataProvider };
70
70
  }
71
71
  function DataSheetStoreWrapper(props) {
72
- const { toaster, initialFilters, initialSorts, initialData, ...rest } = props;
72
+ const {
73
+ toaster,
74
+ initialFilters,
75
+ initialSorts,
76
+ initialData,
77
+ startAfter,
78
+ ...rest
79
+ } = props;
73
80
  const seed = resolveInitialData(initialData);
74
81
  const initializeStore = (set, get) => ({
75
82
  ...createZustandStore(set, get),
@@ -81,7 +88,10 @@ function DataSheetStoreWrapper(props) {
81
88
  {
82
89
  ctx,
83
90
  initializeStore,
84
- atoms: [[toasterAtom, toaster], ...loaderSeedAtoms(initialData)],
91
+ atoms: [
92
+ [toasterAtom, toaster],
93
+ ...loaderSeedAtoms(initialData, startAfter)
94
+ ],
85
95
  debugName: "DataSheetProvider"
86
96
  },
87
97
  h(DataSheetProviderInner, rest)
@@ -132,10 +142,13 @@ function splitDataProviderProps(props) {
132
142
  props,
133
143
  dataProviderKeys.union(interactionOptionsKeys).union(tableDataProviderKeys)
134
144
  );
135
- const initialData = props.initialData;
145
+ const { initialData, startAfter } = props;
136
146
  if (initialData != null) {
137
147
  providerProps.initialData = initialData;
138
148
  }
149
+ if (startAfter != null) {
150
+ providerProps.startAfter = startAfter;
151
+ }
139
152
  return [providerProps, rendererProps];
140
153
  }
141
154
  function DataSheetProvider(props) {
@@ -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 { toaster, initialFilters, initialSorts, initialData, ...rest } = 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: [[toasterAtom, toaster], ...loaderSeedAtoms(initialData)],\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` goes to both sides: the provider creates the store seeded\n // with it, and the loader takes it as the first window it needn't fetch.\n const initialData = (props as { initialData?: any }).initialData;\n if (initialData != null) {\n providerProps.initialData = initialData;\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) {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K,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: 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,MAAM,YAAY;AAIzB,MAAM,aAA2B,CAAA;AAEjC,MAAM,sBAAsB;AAAA,EAC1B;AAAA,EACA,CAAC,KAAK,KAAK,YAA0C;AACnD,QAAI,kBAAkB,CAAC,UAAU;AAC/B,aAAO;AAAA,QACL,GAAG;AAAA,QACH,GAAG;AAAA,MAAA;AAAA,IAEP,CAAC;AAAA,EACH;AACF;AAEO,MAAM,mBAAmB,KAAoB,CAAA,CAAE;AAoBtD,MAAM,wBAA8C;AAAA,EAClD,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,YAAY;AACd;AAEO,MAAM,mBAAmB;AAAA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};
35
35
  }
36
- function loaderSeedAtoms(initialData) {
36
+ const startAfterAtom = jotai.atom(null);
37
+ function loaderSeedAtoms(initialData, startAfter = null) {
38
+ const atoms = [];
39
+ if (startAfter != null) {
40
+ atoms.push([startAfterAtom, startAfter]);
41
+ }
37
42
  const seed = resolveInitialData(initialData);
38
- if (seed == null) return [];
39
- return [[lazyLoaderCoreStateAtom, seededLoaderCore(seed)]];
43
+ if (seed != null) {
44
+ atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);
45
+ }
46
+ return atoms;
40
47
  }
41
48
  exports.DEFAULT_LOADER_CORE = DEFAULT_LOADER_CORE;
42
49
  exports.lazyLoaderCoreStateAtom = lazyLoaderCoreStateAtom;
@@ -44,4 +51,5 @@ exports.loaderSeedAtoms = loaderSeedAtoms;
44
51
  exports.resolveInitialData = resolveInitialData;
45
52
  exports.seededLoaderCore = seededLoaderCore;
46
53
  exports.seededRows = seededRows;
54
+ exports.startAfterAtom = startAfterAtom;
47
55
  //# sourceMappingURL=loader-state.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"loader-state.cjs","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): AtomMap {\n const seed = resolveInitialData(initialData);\n if (seed == null) return [];\n return [[lazyLoaderCoreStateAtom, seededLoaderCore(seed)]];\n}\n"],"names":["atom"],"mappings":";;;AAqBO,MAAM,sBAAgD;AAAA,EAC3D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AACZ;AAEO,MAAM,0BACXA,MAAAA,KAA+B,mBAAmB;AAK7C,SAAS,mBACd,aAC4B;AAC5B,MAAI,eAAe,KAAM,QAAO;AAChC,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,QAAI,YAAY,WAAW,EAAG,QAAO;AACrC,WAAO,EAAE,MAAM,YAAA;AAAA,EACjB;AACA,OAAK,YAAY,QAAQ,CAAA,GAAI,WAAW,EAAG,QAAO;AAClD,SAAO;AACT;AAKO,SAAS,WAAc,MAAyC;AACrE,QAAM,OAAO,KAAK,QAAQ,CAAA;AAC1B,QAAM,OAAO,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ,KAAK,MAAM;AACjE,QAAM,OAAqB,IAAI,MAAM,IAAI,EAAE,KAAK,IAAI;AACpD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,CAAC,IAAI,KAAK,CAAC;AACtD,SAAO;AACT;AAKO,SAAS,iBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa;AAAA,IACb,YAAY,KAAK,cAAc;AAAA,EAAA;AAEnC;AAKO,SAAS,gBACd,aACS;AACT,QAAM,OAAO,mBAAmB,WAAW;AAC3C,MAAI,QAAQ,KAAM,QAAO,CAAA;AACzB,SAAO,CAAC,CAAC,yBAAyB,iBAAiB,IAAI,CAAC,CAAC;AAC3D;;;;;;;"}
1
+ {"version":3,"file":"loader-state.cjs","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** The identity of the row the current view starts after (`startAfter`), or\n * `null` for a view that starts at the top. Set at store creation so a server\n * render shows the \"Return to top\" link; the loader clears it on the first view\n * change. */\nexport const startAfterAtom = atom<string | number | null>(null);\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n startAfter: FetchDataOptions<T>[\"startAfter\"] = null,\n): AtomMap {\n const atoms: AtomMap = [];\n if (startAfter != null) {\n atoms.push([startAfterAtom, startAfter]);\n }\n const seed = resolveInitialData(initialData);\n if (seed != null) {\n atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);\n }\n return atoms;\n}\n"],"names":["atom"],"mappings":";;;AAqBO,MAAM,sBAAgD;AAAA,EAC3D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AACZ;AAEO,MAAM,0BACXA,MAAAA,KAA+B,mBAAmB;AAK7C,SAAS,mBACd,aAC4B;AAC5B,MAAI,eAAe,KAAM,QAAO;AAChC,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,QAAI,YAAY,WAAW,EAAG,QAAO;AACrC,WAAO,EAAE,MAAM,YAAA;AAAA,EACjB;AACA,OAAK,YAAY,QAAQ,CAAA,GAAI,WAAW,EAAG,QAAO;AAClD,SAAO;AACT;AAKO,SAAS,WAAc,MAAyC;AACrE,QAAM,OAAO,KAAK,QAAQ,CAAA;AAC1B,QAAM,OAAO,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ,KAAK,MAAM;AACjE,QAAM,OAAqB,IAAI,MAAM,IAAI,EAAE,KAAK,IAAI;AACpD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,CAAC,IAAI,KAAK,CAAC;AACtD,SAAO;AACT;AAKO,SAAS,iBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa;AAAA,IACb,YAAY,KAAK,cAAc;AAAA,EAAA;AAEnC;AAMO,MAAM,iBAAiBA,MAAAA,KAA6B,IAAI;AAKxD,SAAS,gBACd,aACA,aAAgD,MACvC;AACT,QAAM,QAAiB,CAAA;AACvB,MAAI,cAAc,MAAM;AACtB,UAAM,KAAK,CAAC,gBAAgB,UAAU,CAAC;AAAA,EACzC;AACA,QAAM,OAAO,mBAAmB,WAAW;AAC3C,MAAI,QAAQ,MAAM;AAChB,UAAM,KAAK,CAAC,yBAAyB,iBAAiB,IAAI,CAAC,CAAC;AAAA,EAC9D;AACA,SAAO;AACT;;;;;;;;"}
@@ -27,7 +27,14 @@ export declare function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[];
27
27
  * a completed first fetch. `initialized` means the loader neither refetches the
28
28
  * seeded window nor shows an empty state. */
29
29
  export declare function seededLoaderCore<T>(seed: InitialDataChunk<T>): LazyLoaderStateCore<T>;
30
+ /** The identity of the row the current view starts after (`startAfter`), or
31
+ * `null` for a view that starts at the top. Set at store creation so a server
32
+ * render shows the "Return to top" link; the loader clears it on the first view
33
+ * change. */
34
+ export declare const startAfterAtom: import('jotai').PrimitiveAtom<string | number | null> & {
35
+ init: string | number | null;
36
+ };
30
37
  /** Scoped-store atoms that make a store start out seeded. The store's own
31
38
  * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is
32
39
  * no seed. */
33
- export declare function loaderSeedAtoms<T>(initialData: FetchDataOptions<T>["initialData"]): AtomMap;
40
+ export declare function loaderSeedAtoms<T>(initialData: FetchDataOptions<T>["initialData"], startAfter?: FetchDataOptions<T>["startAfter"]): AtomMap;
@@ -31,10 +31,17 @@ function seededLoaderCore(seed) {
31
31
  totalCount: seed.totalCount ?? null
32
32
  };
33
33
  }
34
- function loaderSeedAtoms(initialData) {
34
+ const startAfterAtom = atom(null);
35
+ function loaderSeedAtoms(initialData, startAfter = null) {
36
+ const atoms = [];
37
+ if (startAfter != null) {
38
+ atoms.push([startAfterAtom, startAfter]);
39
+ }
35
40
  const seed = resolveInitialData(initialData);
36
- if (seed == null) return [];
37
- return [[lazyLoaderCoreStateAtom, seededLoaderCore(seed)]];
41
+ if (seed != null) {
42
+ atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);
43
+ }
44
+ return atoms;
38
45
  }
39
46
  export {
40
47
  DEFAULT_LOADER_CORE,
@@ -42,6 +49,7 @@ export {
42
49
  loaderSeedAtoms,
43
50
  resolveInitialData,
44
51
  seededLoaderCore,
45
- seededRows
52
+ seededRows,
53
+ startAfterAtom
46
54
  };
47
55
  //# sourceMappingURL=loader-state.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loader-state.js","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): AtomMap {\n const seed = resolveInitialData(initialData);\n if (seed == null) return [];\n return [[lazyLoaderCoreStateAtom, seededLoaderCore(seed)]];\n}\n"],"names":[],"mappings":";AAqBO,MAAM,sBAAgD;AAAA,EAC3D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AACZ;AAEO,MAAM,0BACX,KAA+B,mBAAmB;AAK7C,SAAS,mBACd,aAC4B;AAC5B,MAAI,eAAe,KAAM,QAAO;AAChC,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,QAAI,YAAY,WAAW,EAAG,QAAO;AACrC,WAAO,EAAE,MAAM,YAAA;AAAA,EACjB;AACA,OAAK,YAAY,QAAQ,CAAA,GAAI,WAAW,EAAG,QAAO;AAClD,SAAO;AACT;AAKO,SAAS,WAAc,MAAyC;AACrE,QAAM,OAAO,KAAK,QAAQ,CAAA;AAC1B,QAAM,OAAO,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ,KAAK,MAAM;AACjE,QAAM,OAAqB,IAAI,MAAM,IAAI,EAAE,KAAK,IAAI;AACpD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,CAAC,IAAI,KAAK,CAAC;AACtD,SAAO;AACT;AAKO,SAAS,iBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa;AAAA,IACb,YAAY,KAAK,cAAc;AAAA,EAAA;AAEnC;AAKO,SAAS,gBACd,aACS;AACT,QAAM,OAAO,mBAAmB,WAAW;AAC3C,MAAI,QAAQ,KAAM,QAAO,CAAA;AACzB,SAAO,CAAC,CAAC,yBAAyB,iBAAiB,IAAI,CAAC,CAAC;AAC3D;"}
1
+ {"version":3,"file":"loader-state.js","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** The identity of the row the current view starts after (`startAfter`), or\n * `null` for a view that starts at the top. Set at store creation so a server\n * render shows the \"Return to top\" link; the loader clears it on the first view\n * change. */\nexport const startAfterAtom = atom<string | number | null>(null);\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n startAfter: FetchDataOptions<T>[\"startAfter\"] = null,\n): AtomMap {\n const atoms: AtomMap = [];\n if (startAfter != null) {\n atoms.push([startAfterAtom, startAfter]);\n }\n const seed = resolveInitialData(initialData);\n if (seed != null) {\n atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);\n }\n return atoms;\n}\n"],"names":[],"mappings":";AAqBO,MAAM,sBAAgD;AAAA,EAC3D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AACZ;AAEO,MAAM,0BACX,KAA+B,mBAAmB;AAK7C,SAAS,mBACd,aAC4B;AAC5B,MAAI,eAAe,KAAM,QAAO;AAChC,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,QAAI,YAAY,WAAW,EAAG,QAAO;AACrC,WAAO,EAAE,MAAM,YAAA;AAAA,EACjB;AACA,OAAK,YAAY,QAAQ,CAAA,GAAI,WAAW,EAAG,QAAO;AAClD,SAAO;AACT;AAKO,SAAS,WAAc,MAAyC;AACrE,QAAM,OAAO,KAAK,QAAQ,CAAA;AAC1B,QAAM,OAAO,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ,KAAK,MAAM;AACjE,QAAM,OAAqB,IAAI,MAAM,IAAI,EAAE,KAAK,IAAI;AACpD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,CAAC,IAAI,KAAK,CAAC;AACtD,SAAO;AACT;AAKO,SAAS,iBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa;AAAA,IACb,YAAY,KAAK,cAAc;AAAA,EAAA;AAEnC;AAMO,MAAM,iBAAiB,KAA6B,IAAI;AAKxD,SAAS,gBACd,aACA,aAAgD,MACvC;AACT,QAAM,QAAiB,CAAA;AACvB,MAAI,cAAc,MAAM;AACtB,UAAM,KAAK,CAAC,gBAAgB,UAAU,CAAC;AAAA,EACzC;AACA,QAAM,OAAO,mBAAmB,WAAW;AAC3C,MAAI,QAAQ,MAAM;AAChB,UAAM,KAAK,CAAC,yBAAyB,iBAAiB,IAAI,CAAC,CAAC;AAAA,EAC9D;AACA,SAAO;AACT;"}
@@ -23,7 +23,7 @@ function createLocalProvider(data, options = {}) {
23
23
  const identity = options.identity ?? defaultLocalIdentity;
24
24
  return {
25
25
  identity,
26
- async fetchData({ offset, limit, sorts, filters }) {
26
+ async fetchData({ offset, limit, sorts, filters, after }) {
27
27
  let rows = data;
28
28
  if (filters != null && filters.length > 0) {
29
29
  rows = rows.filter(
@@ -35,6 +35,7 @@ function createLocalProvider(data, options = {}) {
35
35
  if (sorts != null && sorts.length > 0) {
36
36
  rows = [...rows].sort(compareRowsBySorts(sorts));
37
37
  }
38
+ rows = rowsAfter(rows, after, identity);
38
39
  return {
39
40
  rows: rows.slice(offset, offset + limit),
40
41
  totalCount: rows.length
@@ -45,6 +46,13 @@ function createLocalProvider(data, options = {}) {
45
46
  }
46
47
  };
47
48
  }
49
+ function rowsAfter(rows, after, identity) {
50
+ if (after == null) return rows;
51
+ const key = String(after);
52
+ const index = rows.findIndex((row) => String(identity(row)) === key);
53
+ if (index < 0) return rows;
54
+ return rows.slice(index + 1);
55
+ }
48
56
  const _syntheticRowIds = /* @__PURE__ */ new WeakMap();
49
57
  let _syntheticRowCounter = 0;
50
58
  function defaultLocalIdentity(row) {
@@ -110,4 +118,5 @@ exports.createLocalProvider = createLocalProvider;
110
118
  exports.dataRefreshTokenAtom = dataRefreshTokenAtom;
111
119
  exports.distinctValuesOf = distinctValuesOf;
112
120
  exports.persistViaProvider = persistViaProvider;
121
+ exports.rowsAfter = rowsAfter;
113
122
  //# sourceMappingURL=table-data.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"table-data.cjs","sources":["../../src/provider/table-data.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n /** The distinct values a column holds — the vocabulary a value picker offers,\n * so a filter can only be set to something that matches. Optional: a source\n * that can't answer it cheaply simply omits it, and pickers fall back to free\n * entry. See {@link useDistinctValues}. */\n distinctValues?(\n columnKey: string,\n options?: DistinctValuesOptions,\n ): Promise<DistinctValue[]>;\n}\n\n/** One value a column holds, with its frequency where the source reports it. */\nexport interface DistinctValue<V = any> {\n value: V;\n /** Rows carrying this value. Omitted when the source can't count cheaply. */\n count?: number;\n}\n\nexport interface DistinctValuesOptions {\n /** Aborts when the request is superseded (unmount, key change). */\n signal?: AbortSignal;\n /** Cap on how many values to return — a high-cardinality column shouldn't\n * become an unbounded fetch. */\n limit?: number;\n}\n\n/** Distinct values of an in-memory column, ordered by descending frequency then\n * value. Array cells are *not* flattened: the values of an array column are its\n * arrays, matching what a server-side `GROUP BY` would report. */\nexport function distinctValuesOf<T>(\n rows: T[],\n columnKey: string,\n options: DistinctValuesOptions = {},\n): DistinctValue[] {\n const counts = new Map<any, number>();\n for (const row of rows) {\n const value = (row as any)?.[columnKey];\n counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n const values = [...counts.entries()].map(([value, count]) => ({\n value,\n count,\n }));\n values.sort((a, b) => {\n if (b.count !== a.count) return b.count - a.count;\n return String(a.value).localeCompare(String(b.value));\n });\n if (options.limit != null) return values.slice(0, options.limit);\n return values;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n async distinctValues(columnKey, opts) {\n return distinctValuesOf(data, columnKey, opts);\n },\n };\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.save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WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,QAAI,OAAO,CAAC,MAAMC,MAAAA,mBAAmB,SAAS;AAC5C,YAAM,KAAK,SAAS,SAAS,KAAK,CAAC,CAAC;AACpC,UAAI,MAAM,KAAM,UAAS,KAAK,EAAE;AAChC;AAAA,IACF;AACA,UAAM,MAAM,QAAQ,CAAC;AACrB,UAAM,UACJ,OAAO,QAAQ,OAAO,QAAQ,YAAY,OAAO,KAAK,GAAG,EAAE,SAAS;AACtE,QAAI,OAAO,CAAC,MAAMA,MAAAA,mBAAmB,OAAO;AAC1C,eAAS,KAAK,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,KAAU;AAAA,IAC3C,WAAW,SAAS;AAClB,aAAO,KAAK,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,KAAU;AAAA,IACzC;AAAA,EACF;AACA,MAAI,SAAS,SAAS,KAAK,SAAS,cAAc,MAAM;AACtD,UAAM,SAAS,WAAW,QAAQ;AAAA,EACpC;AACA,aAAW,OAAO,UAAU;AAC1B,QAAI,SAAS,aAAa,KAAM,OAAM,SAAS,UAAU,GAAG;AAAA,EAC9D;AACA,MAAI,OAAO,SAAS,KAAK,SAAS,YAAY,MAAM;AAClD,UAAM,SAAS,SAAS,MAAM;AAAA,EAChC;AACF;;;;;;"}
1
+ {"version":3,"file":"table-data.cjs","sources":["../../src/provider/table-data.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n /** Identity of the row the view is counted from: `offset` 0 is the first\n * row *after* it. Set while a view starts mid-list (see `startAfter` in\n * `FetchDataOptions`); absent or `null` when it starts at the top. Keyset\n * sources translate it to `WHERE key > after`; the local provider slices past\n * the row. `totalCount` then reports the rows after it. */\n after?: string | number | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n /** The distinct values a column holds — the vocabulary a value picker offers,\n * so a filter can only be set to something that matches. Optional: a source\n * that can't answer it cheaply simply omits it, and pickers fall back to free\n * entry. See {@link useDistinctValues}. */\n distinctValues?(\n columnKey: string,\n options?: DistinctValuesOptions,\n ): Promise<DistinctValue[]>;\n}\n\n/** One value a column holds, with its frequency where the source reports it. */\nexport interface DistinctValue<V = any> {\n value: V;\n /** Rows carrying this value. Omitted when the source can't count cheaply. */\n count?: number;\n}\n\nexport interface DistinctValuesOptions {\n /** Aborts when the request is superseded (unmount, key change). */\n signal?: AbortSignal;\n /** Cap on how many values to return — a high-cardinality column shouldn't\n * become an unbounded fetch. */\n limit?: number;\n}\n\n/** Distinct values of an in-memory column, ordered by descending frequency then\n * value. Array cells are *not* flattened: the values of an array column are its\n * arrays, matching what a server-side `GROUP BY` would report. */\nexport function distinctValuesOf<T>(\n rows: T[],\n columnKey: string,\n options: DistinctValuesOptions = {},\n): DistinctValue[] {\n const counts = new Map<any, number>();\n for (const row of rows) {\n const value = (row as any)?.[columnKey];\n counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n const values = [...counts.entries()].map(([value, count]) => ({\n value,\n count,\n }));\n values.sort((a, b) => {\n if (b.count !== a.count) return b.count - a.count;\n return String(a.value).localeCompare(String(b.value));\n });\n if (options.limit != null) return values.slice(0, options.limit);\n return values;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters, after }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n rows = rowsAfter(rows, after, identity);\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n async distinctValues(columnKey, opts) {\n return distinctValuesOf(data, columnKey, opts);\n },\n };\n}\n\n/** The rows past the one with identity `after` in the (filtered, sorted) view;\n * the whole view when `after` is absent or names no row. Identities are compared\n * as strings, since a cursor read from a URL arrives as one. */\nexport function rowsAfter<T>(\n rows: T[],\n after: string | number | null | undefined,\n identity: (row: T) => string | number | null | undefined,\n): T[] {\n if (after == null) return rows;\n const key = String(after);\n const index = rows.findIndex((row) => String(identity(row)) === key);\n if (index < 0) return rows;\n return rows.slice(index + 1);\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n"],"names":["atom","TableElementStatus"],"mappings":";;;;AAiGO,SAAS,iBACd,MACA,WACA,UAAiC,CAAA,GAChB;AACjB,QAAM,6BAAa,IAAA;AACnB,aAAW,OAAO,MAAM;AACtB,UAAM,QAAS,MAAc,SAAS;AACtC,WAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;AAAA,EAChD;AACA,QAAM,SAAS,CAAC,GAAG,OAAO,QAAA,CAAS,EAAE,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO;AAAA,IAC5D;AAAA,IACA;AAAA,EAAA,EACA;AACF,SAAO,KAAK,CAAC,GAAG,MAAM;AACpB,QAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,WAAO,OAAO,EAAE,KAAK,EAAE,cAAc,OAAO,EAAE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