@macrostrat/data-sheet 4.6.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.
- package/CHANGELOG.md +24 -0
- package/dist/data-panel.cjs +36 -0
- package/dist/data-panel.cjs.map +1 -1
- package/dist/data-panel.d.ts +4 -2
- package/dist/data-panel.js +37 -1
- package/dist/data-panel.js.map +1 -1
- package/dist/data-panel.module.sass.cjs +28 -26
- package/dist/data-panel.module.sass.cjs.map +1 -1
- package/dist/data-panel.module.sass.js +28 -26
- package/dist/data-panel.module.sass.js.map +1 -1
- package/dist/data-sheet.css +59 -36
- package/dist/data-sheet.d.ts +3 -1
- package/dist/data-view.d.ts +2 -0
- package/dist/index.cjs +1 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2 -1
- package/dist/postgrest-table/data-loaders.cjs +24 -27
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.js +20 -23
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/provider/core.cjs +35 -6
- package/dist/provider/core.cjs.map +1 -1
- package/dist/provider/core.d.ts +1 -1
- package/dist/provider/core.js +35 -6
- package/dist/provider/core.js.map +1 -1
- package/dist/provider/loader-state.cjs +55 -0
- package/dist/provider/loader-state.cjs.map +1 -0
- package/dist/provider/loader-state.d.ts +40 -0
- package/dist/provider/loader-state.js +55 -0
- package/dist/provider/loader-state.js.map +1 -0
- package/dist/provider/table-data.cjs +10 -1
- package/dist/provider/table-data.cjs.map +1 -1
- package/dist/provider/table-data.d.ts +10 -0
- package/dist/provider/table-data.js +11 -2
- package/dist/provider/table-data.js.map +1 -1
- package/dist/provider/types.cjs.map +1 -1
- package/dist/provider/types.d.ts +8 -1
- package/dist/provider/types.js.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +25 -0
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/data-panel.module.sass +25 -0
- package/src/data-panel.ts +50 -1
- package/src/postgrest-table/data-loaders.ts +35 -41
- package/src/provider/core.ts +65 -6
- package/src/provider/loader-state.ts +95 -0
- package/src/provider/table-data.ts +23 -1
- package/src/provider/types.ts +8 -1
- package/src/types.ts +26 -0
package/dist/provider/core.cjs
CHANGED
|
@@ -10,6 +10,7 @@ const notifications = require("../notifications.cjs");
|
|
|
10
10
|
const tableData = require("./table-data.cjs");
|
|
11
11
|
const uiComponents = require("@macrostrat/ui-components");
|
|
12
12
|
const interactions = require("./interactions.cjs");
|
|
13
|
+
const loaderState = require("./loader-state.cjs");
|
|
13
14
|
const atoms = require("../utils/atoms.cjs");
|
|
14
15
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
|
15
16
|
const h__default = /* @__PURE__ */ _interopDefault(h);
|
|
@@ -72,22 +73,38 @@ function useResolvedProvider(props) {
|
|
|
72
73
|
return { data: _data, isLocalProvider, activeProvider, dataProvider };
|
|
73
74
|
}
|
|
74
75
|
function DataSheetStoreWrapper(props) {
|
|
75
|
-
const {
|
|
76
|
+
const {
|
|
77
|
+
toaster,
|
|
78
|
+
initialFilters,
|
|
79
|
+
initialSorts,
|
|
80
|
+
initialData,
|
|
81
|
+
startAfter,
|
|
82
|
+
...rest
|
|
83
|
+
} = props;
|
|
84
|
+
const seed = loaderState.resolveInitialData(initialData);
|
|
76
85
|
const initializeStore = (set, get) => ({
|
|
77
86
|
...zustandStore.createZustandStore(set, get),
|
|
78
|
-
...initialViewState({ initialFilters, initialSorts })
|
|
87
|
+
...initialViewState({ initialFilters, initialSorts }),
|
|
88
|
+
...initialDataState(seed)
|
|
79
89
|
});
|
|
80
90
|
return h__default.default(
|
|
81
91
|
scopedStore.ZustandStoreProvider,
|
|
82
92
|
{
|
|
83
93
|
ctx,
|
|
84
94
|
initializeStore,
|
|
85
|
-
atoms: [
|
|
95
|
+
atoms: [
|
|
96
|
+
[notifications.toasterAtom, toaster],
|
|
97
|
+
...loaderState.loaderSeedAtoms(initialData, startAfter)
|
|
98
|
+
],
|
|
86
99
|
debugName: "DataSheetProvider"
|
|
87
100
|
},
|
|
88
101
|
h__default.default(DataSheetProviderInner, rest)
|
|
89
102
|
);
|
|
90
103
|
}
|
|
104
|
+
function initialDataState(seed) {
|
|
105
|
+
if (seed == null) return {};
|
|
106
|
+
return { data: loaderState.seededRows(seed) };
|
|
107
|
+
}
|
|
91
108
|
function initialViewState({
|
|
92
109
|
initialFilters,
|
|
93
110
|
initialSorts
|
|
@@ -125,10 +142,18 @@ const dataProviderKeys = /* @__PURE__ */ new Set([
|
|
|
125
142
|
"interactionOptions"
|
|
126
143
|
]);
|
|
127
144
|
function splitDataProviderProps(props) {
|
|
128
|
-
|
|
145
|
+
const [providerProps, rendererProps] = atoms.splitProps(
|
|
129
146
|
props,
|
|
130
147
|
dataProviderKeys.union(interactions.interactionOptionsKeys).union(tableDataProviderKeys)
|
|
131
148
|
);
|
|
149
|
+
const { initialData, startAfter } = props;
|
|
150
|
+
if (initialData != null) {
|
|
151
|
+
providerProps.initialData = initialData;
|
|
152
|
+
}
|
|
153
|
+
if (startAfter != null) {
|
|
154
|
+
providerProps.startAfter = startAfter;
|
|
155
|
+
}
|
|
156
|
+
return [providerProps, rendererProps];
|
|
132
157
|
}
|
|
133
158
|
function DataSheetProvider(props) {
|
|
134
159
|
return h__default.default(
|
|
@@ -154,7 +179,7 @@ function DataSheetProviderInner(props) {
|
|
|
154
179
|
refreshToken,
|
|
155
180
|
identity
|
|
156
181
|
} = providerProps;
|
|
157
|
-
const { data, dataProvider } = useResolvedProvider(providerProps);
|
|
182
|
+
const { data, dataProvider, isLocalProvider } = useResolvedProvider(providerProps);
|
|
158
183
|
const initializeStore = ctx.useSet(initializeStoreAtom);
|
|
159
184
|
const storeAPI = useStoreAPI();
|
|
160
185
|
ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);
|
|
@@ -167,7 +192,12 @@ function DataSheetProviderInner(props) {
|
|
|
167
192
|
const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec$1;
|
|
168
193
|
const baseSpec = staticSpec ?? columnSpec.generateColumnSpec(data, columnSpecOptions);
|
|
169
194
|
react.useEffect(() => {
|
|
195
|
+
let localRows = {};
|
|
196
|
+
if (isLocalProvider) {
|
|
197
|
+
localRows = { data };
|
|
198
|
+
}
|
|
170
199
|
initializeStore({
|
|
200
|
+
...localRows,
|
|
171
201
|
columnSpec: columnSpec.postprocessColumnSpec(baseSpec),
|
|
172
202
|
// Suppress the loader's first-chunk auto-generation whenever the consumer
|
|
173
203
|
// provided a spec at all — a function (derived later in `_DataSheet`) OR
|
|
@@ -178,7 +208,6 @@ function DataSheetProviderInner(props) {
|
|
|
178
208
|
deferColumnSpec: columnSpec$1 != null,
|
|
179
209
|
editable: interactionOptions.enableEditing,
|
|
180
210
|
enableColumnReordering,
|
|
181
|
-
data,
|
|
182
211
|
defaultColumnWidth,
|
|
183
212
|
tableRef
|
|
184
213
|
});
|
|
@@ -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 { DataSheetProps, DataViewCoreProps } from \"../types.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, ...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 const initializeStore = (set: any, get: any) => ({\n ...createZustandStore<T>(set, get),\n ...initialViewState({ initialFilters, initialSorts }),\n });\n\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore,\n atoms: [[toasterAtom, toaster]],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\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 return splitProps<AnyDataSheetProps<T>, DataSheetProviderProps<T>>(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\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 } = 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 initializeStore({\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 data,\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","createZustandStore","h","ZustandStoreProvider","toasterAtom","splitProps","interactionOptionsKeys","ToasterContext","ErrorBoundary","useRef","resolveInteractionOptions","DataViewRendererType","columnSpec","interactionOptionsAtom","generateColumnSpec","useEffect","postprocessColumnSpec","dataRefreshTokenAtom","useZustandStoreAPI","useZustandSelector","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;;AA+CO,MAAM,MAAMA,YAAAA,kBAAA;AAEZ,MAAM,eAAeC,YAAAA;AAGrB,MAAM,YAAYC,YAAAA;AAIzB,MAAM,aAA2B,CAAA;AAEjC,MAAM,sBAAsBC,YAAAA;AAAAA,EAC1B;AAAA,EACA,CAAC,KAAK,KAAK,YAA0C;AACnD,QAAID,YAAAA,kBAAkB,CAAC,UAAU;AAC/B,aAAO;AAAA,QACL,GAAG;AAAA,QACH,GAAG;AAAA,MAAA;AAAA,IAEP,CAAC;AAAA,EACH;AACF;AAEO,MAAM,mBAAmBC,YAAAA,KAAoB,CAAA,CAAE;AAoBtD,MAAM,wBAA8C;AAAA,EAClD,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,YAAY;AACd;AAEO,MAAM,mBAAmBA,YAAAA;AAAAA,EAC9B;AACF;AAEA,MAAM,cAAqB,CAAA;AAOpB,SAAS,oBAAuB,OAUrC;AACA,QAAM,QAAQ,MAAM,QAAS;AAC7B,QAAM,kBAAkB,MAAM,YAAY,QAAQ,MAAM,aAAa;AACrE,QAAM,qBAAqB,MAAM,YAAY;AAC7C,QAAM,iBAAiB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,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;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"core.cjs","sources":["../../src/provider/core.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport {\n createScopedStore,\n zustandAPIAtom,\n zustandStoreAtom,\n atom,\n ZustandStoreProvider,\n useZustandSelector,\n useZustandStoreAPI,\n} from \"@macrostrat/scoped-store\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n TableDataProvider,\n} from \"./table-data.ts\";\nimport { ErrorBoundary, ToasterContext } from \"@macrostrat/ui-components\";\nimport {\n DataViewRendererType,\n InteractionOptions,\n interactionOptionsAtom,\n interactionOptionsKeys,\n resolveInteractionOptions,\n} from \"./interactions.ts\";\nimport { DataViewProps } from \"../data-view.ts\";\nimport {\n DataSheetProps,\n DataViewCoreProps,\n InitialDataChunk,\n} from \"../types.ts\";\nimport {\n loaderSeedAtoms,\n resolveInitialData,\n seededRows,\n} from \"./loader-state.ts\";\nimport { DataPanelProps } from \"../data-panel.ts\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = zustandAPIAtom;\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = zustandStoreAtom;\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<any>>) => {\n set(zustandStoreAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\n/** The resolved data source for the table, held in the provider layer (next to\n * the store) rather than resolved inside the render loop. `provider` is the\n * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local\n * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it\n * loads the whole array at once and shows no load progress). `isExplicitProvider`\n * distinguishes an explicit `provider` object from a loose `fetchData`/`data`\n * source — only an explicit provider without `deleteRows` disables row\n * deletion; loose sources keep the local delete overlay. */\nexport interface ResolvedDataProvider {\n provider: TableDataProvider<any> | null;\n isLocalProvider: boolean;\n isExplicitProvider: boolean;\n /** Row count of an in-memory (local) source, so a renderer can size the\n * loader's page to \"all of it\" without also receiving the `data` prop. `0`\n * for non-local sources. */\n localCount: number;\n}\n\nconst DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {\n provider: null,\n isLocalProvider: true,\n isExplicitProvider: false,\n localCount: 0,\n};\n\nexport const dataProviderAtom = atom<ResolvedDataProvider>(\n DEFAULT_DATA_PROVIDER,\n);\n\nconst EMPTY_ARRAY: any[] = [];\n\n/** Resolve a table's data source from the loose `provider` / `fetchData` /\n * `data` props (an explicit `provider` wins; else a loose `fetchData` (+\n * `identity`) is wrapped as one; else in-memory `data` becomes a local\n * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three\n * resolve identically. */\nexport function useResolvedProvider<T>(props: {\n provider?: TableDataProvider<T>;\n fetchData?: FetchData<T>;\n data?: T[];\n identity?: (row: T) => string | number | null | undefined;\n}): {\n data: T[];\n isLocalProvider: boolean;\n activeProvider: TableDataProvider<any> | null;\n dataProvider: ResolvedDataProvider;\n} {\n const _data = props.data ?? (EMPTY_ARRAY as T[]);\n const isLocalProvider = props.provider == null && props.fetchData == null;\n const isExplicitProvider = props.provider != null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (props.provider != null) return props.provider;\n if (props.fetchData != null) {\n return {\n fetchData: props.fetchData,\n identity: props.identity ?? ((r: any) => r?.id),\n } as TableDataProvider<any>;\n }\n if (_data.length > 0) {\n return createLocalProvider(\n _data,\n props.identity != null\n ? { identity: props.identity as (row: any) => string | number }\n : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.provider, props.fetchData, _data, props.identity]);\n const localCount = isLocalProvider ? _data.length : 0;\n const dataProvider = useMemo(\n () => ({\n provider: activeProvider,\n isLocalProvider,\n isExplicitProvider,\n localCount,\n }),\n [activeProvider, isLocalProvider, isExplicitProvider, localCount],\n );\n return { data: _data, isLocalProvider, activeProvider, dataProvider };\n}\n\nfunction DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {\n const {\n toaster,\n initialFilters,\n initialSorts,\n initialData,\n startAfter,\n ...rest\n } = props;\n\n // Initial view state is folded into the store's *creation*, not applied in an\n // effect: the loader mounts below this and its effects run first, so an\n // effect-applied filter would arrive after the first (unfiltered) fetch had\n // already gone out — and be immediately superseded. Creating the store with\n // the view already set means the first fetch is the right one.\n //\n // A seeded first window (`initialData`) is folded in the same way, for the\n // same reason and one more: rows placed at creation are in the first render,\n // so a server render carries them instead of the empty state the loader\n // shows until its first (asynchronous) page resolves.\n const seed = resolveInitialData(initialData);\n const initializeStore = (set: any, get: any) => ({\n ...createZustandStore<T>(set, get),\n ...initialViewState({ initialFilters, initialSorts }),\n ...initialDataState(seed),\n });\n\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore,\n atoms: [\n [toasterAtom, toaster],\n ...loaderSeedAtoms(initialData, startAfter),\n ],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\n/** The store's `data` for a seeded first window; nothing without a seed. */\nfunction initialDataState<T>(\n seed: InitialDataChunk<T> | null,\n): Partial<DataSheetState<T>> {\n if (seed == null) return {};\n return { data: seededRows(seed) as T[] };\n}\n\n/** The store fields that carry a caller-supplied starting view. Absent props\n * contribute nothing, so the store's own defaults stand. */\nfunction initialViewState<T>({\n initialFilters,\n initialSorts,\n}: Pick<DataViewCoreProps<T>, \"initialFilters\" | \"initialSorts\">): Partial<\n DataSheetState<T>\n> {\n const state: Partial<DataSheetState<T>> = {};\n if (initialFilters != null && initialFilters.length > 0) {\n state.activeFilters = new Map(\n initialFilters.map((entry) => [entry.filter.id, entry]),\n );\n }\n if (initialSorts != null && initialSorts.length > 0) {\n state.columnSorts = [...initialSorts];\n }\n return state;\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\n \"initialFilters\",\n \"initialSorts\",\n \"columnSpec\",\n \"columnSpecOptions\",\n \"name\",\n \"itemLabel\",\n \"enableColumnReordering\",\n \"defaultColumnWidth\",\n \"refreshToken\",\n \"identity\",\n \"toaster\",\n \"viewType\",\n \"interactionOptions\",\n]);\n\ntype AnyDataSheetProps<T> =\n DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;\n\nexport function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {\n /** Split provided props based on provider's needs */\n const [providerProps, rendererProps] = splitProps<\n AnyDataSheetProps<T>,\n DataSheetProviderProps<T>\n >(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\n // `initialData` and `startAfter` go to both sides: the provider creates the\n // store seeded with them, and the loader takes them as the first window it\n // needn't fetch and the cursor its chunks are counted from.\n const { initialData, startAfter } = props as {\n initialData?: any;\n startAfter?: string | number | null;\n };\n if (initialData != null) {\n providerProps.initialData = initialData;\n }\n if (startAfter != null) {\n providerProps.startAfter = startAfter;\n }\n return [providerProps, rendererProps] as const;\n}\n\nexport function DataSheetProvider<T>(\n props: DataSheetProviderProps<T> & { children: React.ReactNode },\n) {\n return h(\n ToasterContext,\n h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),\n );\n}\n\ntype DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {\n dataProvider?: ResolvedDataProvider;\n};\n\nexport function DataSheetProviderInner<T>(\n props: DataSheetProviderInnerProps<T>,\n) {\n const tableRef = useRef<Table>(null);\n\n const [interactionOptionsProps, providerProps] = splitProps<\n DataSheetProviderInnerProps<T>,\n InteractionOptions\n >(props, interactionOptionsKeys);\n const interactionOptions = resolveInteractionOptions(\n interactionOptionsProps,\n props.viewType ?? DataViewRendererType.TABLE,\n );\n\n const {\n children,\n columnSpec,\n columnSpecOptions,\n name,\n itemLabel,\n enableColumnReordering,\n defaultColumnWidth = 150,\n refreshToken,\n identity,\n } = providerProps;\n\n const { data, dataProvider, isLocalProvider } =\n useResolvedProvider<T>(providerProps);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n const storeAPI = useStoreAPI<T>();\n\n // The wrapper resolves the data source (see `DataSheet`); publish it into the\n // scoped atom so the loader/store read it, rather than the inner render\n // component resolving it each render. Kept updated as `data`/`provider`\n // changes.\n\n ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);\n ctx.useSync(interactionOptionsAtom, interactionOptions);\n\n const contentLabels = useMemo(() => {\n return { tableName: name, itemLabel };\n }, [name, itemLabel]);\n\n ctx.useSync(contentLabelsAtom, contentLabels);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n // Not sure how required this initialization is\n const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);\n\n useEffect(() => {\n // The store's `data` is the loader's for any fetched source (and may hold a\n // seeded first window from creation); only an in-memory `data` prop is\n // placed here.\n let localRows: Partial<DataSheetStore<T>> = {};\n if (isLocalProvider) {\n localRows = { data };\n }\n initializeStore({\n ...localRows,\n columnSpec: postprocessColumnSpec(baseSpec),\n // Suppress the loader's first-chunk auto-generation whenever the consumer\n // provided a spec at all — a function (derived later in `_DataSheet`) OR\n // an explicit array, *including an empty one*. An empty array means \"no\n // facet columns\" (e.g. a browse panel whose only control is a sheet-level\n // search), not \"please generate from the data\". Auto-gen runs only when\n // no `columnSpec` was passed.\n deferColumnSpec: columnSpec != null,\n editable: interactionOptions.enableEditing,\n enableColumnReordering,\n defaultColumnWidth,\n tableRef,\n });\n }, [\n data,\n interactionOptions.enableEditing,\n staticSpec,\n isFnSpec,\n columnSpecOptions,\n enableColumnReordering,\n ]);\n\n // Function `columnSpec`: derive the spec from the loaded rows (no separate\n // fetch of sample data), here at the provider level so BOTH renderers get it\n // — the sheet's cell grid and the panel's `FacetControls` read the same\n // derived spec. Derive once the first rows arrive, and re-derive when the\n // function's identity changes (a consumer memoizes it over its own view state\n // — hidden columns, order, overrides). Guarded by the function identity, so\n // it never re-runs as more rows page in (which would clobber in-store column\n // state on scroll).\n const loadedData = useSelector<T, T[]>((s) => s.data ?? []);\n const derivedSpecFor = useRef<unknown>(null);\n useEffect(() => {\n if (typeof columnSpec !== \"function\") return;\n if (derivedSpecFor.current === columnSpec) return;\n const rows = loadedData.filter((r) => r != null);\n if (rows.length === 0) return;\n derivedSpecFor.current = columnSpec;\n storeAPI.setState({ columnSpec: columnSpec(rows) });\n }, [columnSpec, loadedData, storeAPI]);\n\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.\n // after a save). Skips the initial mount (the loader does its own first\n // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one\n // provider-level `refreshToken`, whichever renderer is mounted.\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefresh((v) => v + 1);\n }, [refreshToken, bumpRefresh]);\n\n // Provider-backed, auto-refreshing row mutations on the action context\n // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and\n // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit\n // action persists through the active provider and then re-fetches. Only the\n // capabilities the provider supports are present.\n useEffect(() => {\n const p = dataProvider?.provider ?? null;\n const refresh = () => bumpRefresh((v) => v + 1);\n const withRefresh = <A extends any[]>(\n fn?: (...args: A) => Promise<void>,\n ) =>\n fn == null\n ? undefined\n : async (...args: A) => {\n await fn(...args);\n refresh();\n };\n storeAPI.setState({\n rowEditing: {\n saveRows: withRefresh(p?.saveRows?.bind(p)),\n deleteRows: withRefresh(p?.deleteRows?.bind(p)),\n insertRow: withRefresh(p?.insertRow?.bind(p)),\n refresh,\n },\n });\n }, [storeAPI, dataProvider, bumpRefresh]);\n\n // The active provider supplies the row identity for the edit overlay\n // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and\n // `_DataPanel` — falls back to the loose `identity` prop when the resolved\n // provider doesn't carry its own (e.g. before the first row loads).\n useEffect(() => {\n const id = dataProvider?.provider?.identity ?? identity;\n if (id != null) storeAPI.setState({ identity: id });\n }, [storeAPI, dataProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` (not a loose\n // `fetchData`/`data` source) without `deleteRows` disables deletion\n // entirely. Loose/local sources keep the in-table delete overlay. Shared by\n // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state\n // read by the shared `ActionsToolbar`.\n useEffect(() => {\n const canDeleteRows =\n !dataProvider?.isExplicitProvider ||\n dataProvider.provider?.deleteRows != null;\n storeAPI.setState({ canDeleteRows });\n }, [storeAPI, dataProvider]);\n\n return children;\n}\n\nexport function useStoreAPI<T>() {\n return useZustandStoreAPI<DataSheetStore<T>>(ctx);\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n return useZustandSelector<T, A>(ctx, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n // Auto-generate a plain column spec the first time real rows arrive — no\n // spec yet and none deferred to a function (a function spec is derived\n // separately). Keyed on \"spec still empty + a non-null row present\", NOT\n // on `data.length == 0`: the loader pre-fills `data` with a page of `null`\n // ghost rows on reset, so the array is non-empty before the first chunk.\n if (state.columnSpec.length == 0 && !state.deferColumnSpec) {\n const sample = newData.filter((row) => row != null);\n if (sample.length > 0) {\n next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);\n }\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n\ninterface ContentLabels {\n tableName: string | null | undefined;\n itemLabel: string | null | undefined;\n}\n\nconst contentLabelsAtom = atom<ContentLabels>({\n tableName: null,\n itemLabel: null,\n});\n\nexport const itemLabelAtom = atom<string>((get) => {\n return get(contentLabelsAtom).itemLabel ?? \"row\";\n});\nexport const tableNameAtom = atom<string | null>((get) => {\n let { tableName, itemLabel } = get(contentLabelsAtom);\n if (tableName != null) return tableName;\n if (itemLabel != null) capitalize(pluralize(itemLabel, 2));\n return \"Table\";\n});\n\nexport function useItemCount(n: number) {\n const dataKind = ctx.useValue(itemLabelAtom);\n return itemCount(n, dataKind ?? \"row\");\n}\n\nfunction itemCount(n: number, dataKind: string) {\n const base = n == 0 ? \"No\" : `${n}`;\n return base + \" \" + pluralize(dataKind, n);\n}\n\nexport function pluralize(singularForm: string, n: number) {\n const pluralForm = singularForm + \"s\";\n if (n == 0) return `${pluralForm}`;\n if (n == 1) return singularForm;\n return pluralForm;\n}\n\nexport function capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"names":["createScopedStore","zustandAPIAtom","zustandStoreAtom","atom","useMemo","createLocalProvider","resolveInitialData","createZustandStore","h","ZustandStoreProvider","toasterAtom","loaderSeedAtoms","seededRows","splitProps","interactionOptionsKeys","ToasterContext","ErrorBoundary","useRef","resolveInteractionOptions","DataViewRendererType","columnSpec","interactionOptionsAtom","generateColumnSpec","useEffect","postprocessColumnSpec","dataRefreshTokenAtom","useZustandStoreAPI","useZustandSelector","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;;;AAwDO,MAAM,MAAMA,YAAAA,kBAAA;AAEZ,MAAM,eAAeC,YAAAA;AAGrB,MAAM,YAAYC,YAAAA;AAIzB,MAAM,aAA2B,CAAA;AAEjC,MAAM,sBAAsBC,YAAAA;AAAAA,EAC1B;AAAA,EACA,CAAC,KAAK,KAAK,YAA0C;AACnD,QAAID,YAAAA,kBAAkB,CAAC,UAAU;AAC/B,aAAO;AAAA,QACL,GAAG;AAAA,QACH,GAAG;AAAA,MAAA;AAAA,IAEP,CAAC;AAAA,EACH;AACF;AAEO,MAAM,mBAAmBC,YAAAA,KAAoB,CAAA,CAAE;AAoBtD,MAAM,wBAA8C;AAAA,EAClD,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,YAAY;AACd;AAEO,MAAM,mBAAmBA,YAAAA;AAAAA,EAC9B;AACF;AAEA,MAAM,cAAqB,CAAA;AAOpB,SAAS,oBAAuB,OAUrC;AACA,QAAM,QAAQ,MAAM,QAAS;AAC7B,QAAM,kBAAkB,MAAM,YAAY,QAAQ,MAAM,aAAa;AACrE,QAAM,qBAAqB,MAAM,YAAY;AAC7C,QAAM,iBAAiBC,MAAAA,QAAuC,MAAM;AAClE,QAAI,MAAM,YAAY,KAAM,QAAO,MAAM;AACzC,QAAI,MAAM,aAAa,MAAM;AAC3B,aAAO;AAAA,QACL,WAAW,MAAM;AAAA,QACjB,UAAU,MAAM,aAAa,CAAC,MAAW,GAAG;AAAA,MAAA;AAAA,IAEhD;AACA,QAAI,MAAM,SAAS,GAAG;AAC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|
52
52
|
};
|
|
53
53
|
type AnyDataSheetProps<T> = DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;
|
|
54
|
-
export declare function splitDataProviderProps<T>(props: AnyDataSheetProps<T>): [DataSheetProviderProps<T>, Omit<AnyDataSheetProps<T>, "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>;
|
package/dist/provider/core.js
CHANGED
|
@@ -8,6 +8,7 @@ import { toasterAtom } from "../notifications.js";
|
|
|
8
8
|
import { dataRefreshTokenAtom, createLocalProvider } from "./table-data.js";
|
|
9
9
|
import { ToasterContext, ErrorBoundary } from "@macrostrat/ui-components";
|
|
10
10
|
import { resolveInteractionOptions, DataViewRendererType, interactionOptionsAtom, interactionOptionsKeys } from "./interactions.js";
|
|
11
|
+
import { resolveInitialData, loaderSeedAtoms, seededRows } from "./loader-state.js";
|
|
11
12
|
import { splitProps } from "../utils/atoms.js";
|
|
12
13
|
const ctx = createScopedStore();
|
|
13
14
|
const storeAPIAtom = zustandAPIAtom;
|
|
@@ -68,22 +69,38 @@ function useResolvedProvider(props) {
|
|
|
68
69
|
return { data: _data, isLocalProvider, activeProvider, dataProvider };
|
|
69
70
|
}
|
|
70
71
|
function DataSheetStoreWrapper(props) {
|
|
71
|
-
const {
|
|
72
|
+
const {
|
|
73
|
+
toaster,
|
|
74
|
+
initialFilters,
|
|
75
|
+
initialSorts,
|
|
76
|
+
initialData,
|
|
77
|
+
startAfter,
|
|
78
|
+
...rest
|
|
79
|
+
} = props;
|
|
80
|
+
const seed = resolveInitialData(initialData);
|
|
72
81
|
const initializeStore = (set, get) => ({
|
|
73
82
|
...createZustandStore(set, get),
|
|
74
|
-
...initialViewState({ initialFilters, initialSorts })
|
|
83
|
+
...initialViewState({ initialFilters, initialSorts }),
|
|
84
|
+
...initialDataState(seed)
|
|
75
85
|
});
|
|
76
86
|
return h(
|
|
77
87
|
ZustandStoreProvider,
|
|
78
88
|
{
|
|
79
89
|
ctx,
|
|
80
90
|
initializeStore,
|
|
81
|
-
atoms: [
|
|
91
|
+
atoms: [
|
|
92
|
+
[toasterAtom, toaster],
|
|
93
|
+
...loaderSeedAtoms(initialData, startAfter)
|
|
94
|
+
],
|
|
82
95
|
debugName: "DataSheetProvider"
|
|
83
96
|
},
|
|
84
97
|
h(DataSheetProviderInner, rest)
|
|
85
98
|
);
|
|
86
99
|
}
|
|
100
|
+
function initialDataState(seed) {
|
|
101
|
+
if (seed == null) return {};
|
|
102
|
+
return { data: seededRows(seed) };
|
|
103
|
+
}
|
|
87
104
|
function initialViewState({
|
|
88
105
|
initialFilters,
|
|
89
106
|
initialSorts
|
|
@@ -121,10 +138,18 @@ const dataProviderKeys = /* @__PURE__ */ new Set([
|
|
|
121
138
|
"interactionOptions"
|
|
122
139
|
]);
|
|
123
140
|
function splitDataProviderProps(props) {
|
|
124
|
-
|
|
141
|
+
const [providerProps, rendererProps] = splitProps(
|
|
125
142
|
props,
|
|
126
143
|
dataProviderKeys.union(interactionOptionsKeys).union(tableDataProviderKeys)
|
|
127
144
|
);
|
|
145
|
+
const { initialData, startAfter } = props;
|
|
146
|
+
if (initialData != null) {
|
|
147
|
+
providerProps.initialData = initialData;
|
|
148
|
+
}
|
|
149
|
+
if (startAfter != null) {
|
|
150
|
+
providerProps.startAfter = startAfter;
|
|
151
|
+
}
|
|
152
|
+
return [providerProps, rendererProps];
|
|
128
153
|
}
|
|
129
154
|
function DataSheetProvider(props) {
|
|
130
155
|
return h(
|
|
@@ -150,7 +175,7 @@ function DataSheetProviderInner(props) {
|
|
|
150
175
|
refreshToken,
|
|
151
176
|
identity
|
|
152
177
|
} = providerProps;
|
|
153
|
-
const { data, dataProvider } = useResolvedProvider(providerProps);
|
|
178
|
+
const { data, dataProvider, isLocalProvider } = useResolvedProvider(providerProps);
|
|
154
179
|
const initializeStore = ctx.useSet(initializeStoreAtom);
|
|
155
180
|
const storeAPI = useStoreAPI();
|
|
156
181
|
ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);
|
|
@@ -163,7 +188,12 @@ function DataSheetProviderInner(props) {
|
|
|
163
188
|
const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;
|
|
164
189
|
const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);
|
|
165
190
|
useEffect(() => {
|
|
191
|
+
let localRows = {};
|
|
192
|
+
if (isLocalProvider) {
|
|
193
|
+
localRows = { data };
|
|
194
|
+
}
|
|
166
195
|
initializeStore({
|
|
196
|
+
...localRows,
|
|
167
197
|
columnSpec: postprocessColumnSpec(baseSpec),
|
|
168
198
|
// Suppress the loader's first-chunk auto-generation whenever the consumer
|
|
169
199
|
// provided a spec at all — a function (derived later in `_DataSheet`) OR
|
|
@@ -174,7 +204,6 @@ function DataSheetProviderInner(props) {
|
|
|
174
204
|
deferColumnSpec: columnSpec != null,
|
|
175
205
|
editable: interactionOptions.enableEditing,
|
|
176
206
|
enableColumnReordering,
|
|
177
|
-
data,
|
|
178
207
|
defaultColumnWidth,
|
|
179
208
|
tableRef
|
|
180
209
|
});
|
|
@@ -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 { DataSheetProps, DataViewCoreProps } from \"../types.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, ...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 const initializeStore = (set: any, get: any) => ({\n ...createZustandStore<T>(set, get),\n ...initialViewState({ initialFilters, initialSorts }),\n });\n\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore,\n atoms: [[toasterAtom, toaster]],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\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 return splitProps<AnyDataSheetProps<T>, DataSheetProviderProps<T>>(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\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 } = 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 initializeStore({\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 data,\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":";;;;;;;;;;;AA+CO,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,EAC9B;AACF;AAEA,MAAM,cAAqB,CAAA;AAOpB,SAAS,oBAAuB,OAUrC;AACA,QAAM,QAAQ,MAAM,QAAS;AAC7B,QAAM,kBAAkB,MAAM,YAAY,QAAQ,MAAM,aAAa;AACrE,QAAM,qBAAqB,MAAM,YAAY;AAC7C,Q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Y,KAAK;AACvC;AAEA,SAAS,UAAU,GAAW,UAAkB;AAC9C,QAAM,OAAO,KAAK,IAAI,OAAO,GAAG,CAAC;AACjC,SAAO,OAAO,MAAM,UAAU,UAAU,CAAC;AAC3C;AAEO,SAAS,UAAU,cAAsB,GAAW;AACzD,QAAM,aAAa,eAAe;AAClC,MAAI,KAAK,EAAG,QAAO,GAAG,UAAU;AAChC,MAAI,KAAK,EAAG,QAAO;AACnB,SAAO;AACT;AAEO,SAAS,WAAW,GAAW;AACpC,SAAO,EAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC;AAC9C;"}
|
|
1
|
+
{"version":3,"file":"core.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,i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C;"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const jotai = require("jotai");
|
|
4
|
+
const DEFAULT_LOADER_CORE = {
|
|
5
|
+
loading: false,
|
|
6
|
+
error: null,
|
|
7
|
+
initialized: false,
|
|
8
|
+
totalCount: null,
|
|
9
|
+
fetchMode: "scroll",
|
|
10
|
+
pageSize: 100
|
|
11
|
+
};
|
|
12
|
+
const lazyLoaderCoreStateAtom = jotai.atom(DEFAULT_LOADER_CORE);
|
|
13
|
+
function resolveInitialData(initialData) {
|
|
14
|
+
if (initialData == null) return null;
|
|
15
|
+
if (Array.isArray(initialData)) {
|
|
16
|
+
if (initialData.length === 0) return null;
|
|
17
|
+
return { rows: initialData };
|
|
18
|
+
}
|
|
19
|
+
if ((initialData.rows ?? []).length === 0) return null;
|
|
20
|
+
return initialData;
|
|
21
|
+
}
|
|
22
|
+
function seededRows(seed) {
|
|
23
|
+
const rows = seed.rows ?? [];
|
|
24
|
+
const size = Math.max(seed.totalCount ?? rows.length, rows.length);
|
|
25
|
+
const data = new Array(size).fill(null);
|
|
26
|
+
for (let i = 0; i < rows.length; i++) data[i] = rows[i];
|
|
27
|
+
return data;
|
|
28
|
+
}
|
|
29
|
+
function seededLoaderCore(seed) {
|
|
30
|
+
return {
|
|
31
|
+
...DEFAULT_LOADER_CORE,
|
|
32
|
+
initialized: true,
|
|
33
|
+
totalCount: seed.totalCount ?? null
|
|
34
|
+
};
|
|
35
|
+
}
|
|
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
|
+
}
|
|
42
|
+
const seed = resolveInitialData(initialData);
|
|
43
|
+
if (seed != null) {
|
|
44
|
+
atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);
|
|
45
|
+
}
|
|
46
|
+
return atoms;
|
|
47
|
+
}
|
|
48
|
+
exports.DEFAULT_LOADER_CORE = DEFAULT_LOADER_CORE;
|
|
49
|
+
exports.lazyLoaderCoreStateAtom = lazyLoaderCoreStateAtom;
|
|
50
|
+
exports.loaderSeedAtoms = loaderSeedAtoms;
|
|
51
|
+
exports.resolveInitialData = resolveInitialData;
|
|
52
|
+
exports.seededLoaderCore = seededLoaderCore;
|
|
53
|
+
exports.seededRows = seededRows;
|
|
54
|
+
exports.startAfterAtom = startAfterAtom;
|
|
55
|
+
//# sourceMappingURL=loader-state.cjs.map
|
|
@@ -0,0 +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/** 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;;;;;;;;"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { AtomMap } from '@macrostrat/scoped-store';
|
|
2
|
+
import { FetchDataOptions, FetchMode, InitialDataChunk } from '../types.ts';
|
|
3
|
+
export interface LazyLoaderStateCore<T> {
|
|
4
|
+
loading: boolean;
|
|
5
|
+
error: Error | null;
|
|
6
|
+
initialized: boolean;
|
|
7
|
+
/** Reported source length when known (null = unknown / not reported). */
|
|
8
|
+
totalCount: number | null;
|
|
9
|
+
/** Windowing style: infinite-scroll windows, or one fixed page at a time. */
|
|
10
|
+
fetchMode: FetchMode;
|
|
11
|
+
/** Rows per chunk/page. */
|
|
12
|
+
pageSize: number;
|
|
13
|
+
}
|
|
14
|
+
export declare const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any>;
|
|
15
|
+
export declare const lazyLoaderCoreStateAtom: import('jotai').PrimitiveAtom<LazyLoaderStateCore<any>> & {
|
|
16
|
+
init: LazyLoaderStateCore<any>;
|
|
17
|
+
};
|
|
18
|
+
/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a
|
|
19
|
+
* total) to one. An empty seed is treated as no seed — there'd be nothing to
|
|
20
|
+
* show and nothing saved. */
|
|
21
|
+
export declare function resolveInitialData<T>(initialData: FetchDataOptions<T>["initialData"]): InitialDataChunk<T> | null;
|
|
22
|
+
/** The data array for a seeded first window: the rows in place, pre-sized to
|
|
23
|
+
* the reported total (with `null` for the rows not yet loaded) so the scrollbar
|
|
24
|
+
* and the counter are right immediately. */
|
|
25
|
+
export declare function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[];
|
|
26
|
+
/** The loader's core state for a seeded first window — the same shape as after
|
|
27
|
+
* a completed first fetch. `initialized` means the loader neither refetches the
|
|
28
|
+
* seeded window nor shows an empty state. */
|
|
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
|
+
};
|
|
37
|
+
/** Scoped-store atoms that make a store start out seeded. The store's own
|
|
38
|
+
* `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is
|
|
39
|
+
* no seed. */
|
|
40
|
+
export declare function loaderSeedAtoms<T>(initialData: FetchDataOptions<T>["initialData"], startAfter?: FetchDataOptions<T>["startAfter"]): AtomMap;
|