@macrostrat/data-sheet 4.4.1 → 4.5.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 +50 -0
- package/dist/data-panel.cjs +3 -1
- package/dist/data-panel.cjs.map +1 -1
- package/dist/data-panel.d.ts +1 -1
- package/dist/data-panel.js +3 -1
- package/dist/data-panel.js.map +1 -1
- package/dist/data-sheet.cjs +3 -1
- package/dist/data-sheet.cjs.map +1 -1
- package/dist/data-sheet.d.ts +1 -1
- package/dist/data-sheet.js +3 -1
- package/dist/data-sheet.js.map +1 -1
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/postgrest-table/data-loaders.cjs +67 -2
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.d.ts +8 -1
- package/dist/postgrest-table/data-loaders.js +67 -2
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/provider/core.cjs +23 -2
- package/dist/provider/core.cjs.map +1 -1
- package/dist/provider/core.d.ts +2 -2
- package/dist/provider/core.js +23 -2
- package/dist/provider/core.js.map +1 -1
- package/dist/provider/distinct-values.cjs +65 -0
- package/dist/provider/distinct-values.cjs.map +1 -0
- package/dist/provider/distinct-values.d.ts +21 -0
- package/dist/provider/distinct-values.js +65 -0
- package/dist/provider/distinct-values.js.map +1 -0
- package/dist/provider/index.d.ts +1 -0
- package/dist/provider/table-data.cjs +21 -0
- package/dist/provider/table-data.cjs.map +1 -1
- package/dist/provider/table-data.d.ts +22 -0
- package/dist/provider/table-data.js +21 -0
- package/dist/provider/table-data.js.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +27 -4
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/data-panel.ts +3 -1
- package/src/data-sheet.ts +3 -1
- package/src/postgrest-table/data-loaders.ts +106 -3
- package/src/provider/core.ts +36 -3
- package/src/provider/distinct-values.ts +127 -0
- package/src/provider/index.ts +1 -0
- package/src/provider/table-data.ts +51 -0
- package/src/types.ts +33 -4
package/dist/provider/core.js
CHANGED
|
@@ -68,18 +68,37 @@ function useResolvedProvider(props) {
|
|
|
68
68
|
return { data: _data, isLocalProvider, activeProvider, dataProvider };
|
|
69
69
|
}
|
|
70
70
|
function DataSheetStoreWrapper(props) {
|
|
71
|
-
const { toaster, ...rest } = props;
|
|
71
|
+
const { toaster, initialFilters, initialSorts, ...rest } = props;
|
|
72
|
+
const initializeStore = (set, get) => ({
|
|
73
|
+
...createZustandStore(set, get),
|
|
74
|
+
...initialViewState({ initialFilters, initialSorts })
|
|
75
|
+
});
|
|
72
76
|
return h(
|
|
73
77
|
ZustandStoreProvider,
|
|
74
78
|
{
|
|
75
79
|
ctx,
|
|
76
|
-
initializeStore
|
|
80
|
+
initializeStore,
|
|
77
81
|
atoms: [[toasterAtom, toaster]],
|
|
78
82
|
debugName: "DataSheetProvider"
|
|
79
83
|
},
|
|
80
84
|
h(DataSheetProviderInner, rest)
|
|
81
85
|
);
|
|
82
86
|
}
|
|
87
|
+
function initialViewState({
|
|
88
|
+
initialFilters,
|
|
89
|
+
initialSorts
|
|
90
|
+
}) {
|
|
91
|
+
const state = {};
|
|
92
|
+
if (initialFilters != null && initialFilters.length > 0) {
|
|
93
|
+
state.activeFilters = new Map(
|
|
94
|
+
initialFilters.map((entry) => [entry.filter.id, entry])
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
if (initialSorts != null && initialSorts.length > 0) {
|
|
98
|
+
state.columnSorts = [...initialSorts];
|
|
99
|
+
}
|
|
100
|
+
return state;
|
|
101
|
+
}
|
|
83
102
|
const tableDataProviderKeys = /* @__PURE__ */ new Set([
|
|
84
103
|
"provider",
|
|
85
104
|
"fetchData",
|
|
@@ -87,6 +106,8 @@ const tableDataProviderKeys = /* @__PURE__ */ new Set([
|
|
|
87
106
|
"identity"
|
|
88
107
|
]);
|
|
89
108
|
const dataProviderKeys = /* @__PURE__ */ new Set([
|
|
109
|
+
"initialFilters",
|
|
110
|
+
"initialSorts",
|
|
90
111
|
"columnSpec",
|
|
91
112
|
"columnSpecOptions",
|
|
92
113
|
"name",
|
|
@@ -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 } 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, ...rest } = props;\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore: createZustandStore,\n atoms: [[toasterAtom, toaster]],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\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,QAAM,iBAAiB,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,C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AA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,IACb,WAAW;AAAA,IACX;AAAA,EAAA;AAEJ;AAOA,MAAM,oBAAoB,KAAoB;AAAA,EAC5C,WAAW;AAAA,EACX,WAAW;AACb,CAAC;AAEM,MAAM,gBAAgB,KAAa,CAAC,QAAQ;AACjD,SAAO,IAAI,iBAAiB,EAAE,aAAa;AAC7C,CAAC;AACM,MAAM,gBAAgB,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.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,QAAM,iBAAiB,QAAu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A,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;"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const react = require("react");
|
|
4
|
+
const core = require("./core.cjs");
|
|
5
|
+
const tableData = require("./table-data.cjs");
|
|
6
|
+
const EMPTY = [];
|
|
7
|
+
function useDistinctValues(columnKey, options = {}) {
|
|
8
|
+
const { provider } = core.ctx.useValue(core.dataProviderAtom);
|
|
9
|
+
const refreshToken = core.ctx.useValue(tableData.dataRefreshTokenAtom);
|
|
10
|
+
const { limit } = options;
|
|
11
|
+
const supported = provider?.distinctValues != null && columnKey != null;
|
|
12
|
+
const [state, setState] = react.useState({
|
|
13
|
+
values: EMPTY,
|
|
14
|
+
loading: supported,
|
|
15
|
+
error: null,
|
|
16
|
+
supported
|
|
17
|
+
});
|
|
18
|
+
react.useEffect(() => {
|
|
19
|
+
if (!supported) {
|
|
20
|
+
setState({ values: EMPTY, loading: false, error: null, supported });
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
let active = true;
|
|
24
|
+
const controller = new AbortController();
|
|
25
|
+
setState((prev) => ({ ...prev, loading: true, supported }));
|
|
26
|
+
read(provider, columnKey, refreshToken, limit).then((values) => {
|
|
27
|
+
if (!active) return;
|
|
28
|
+
setState({ values, loading: false, error: null, supported: true });
|
|
29
|
+
}).catch((error) => {
|
|
30
|
+
if (!active || controller.signal.aborted) return;
|
|
31
|
+
setState({ values: EMPTY, loading: false, error, supported: true });
|
|
32
|
+
});
|
|
33
|
+
return () => {
|
|
34
|
+
active = false;
|
|
35
|
+
controller.abort();
|
|
36
|
+
};
|
|
37
|
+
}, [provider, columnKey, refreshToken, limit, supported]);
|
|
38
|
+
return state;
|
|
39
|
+
}
|
|
40
|
+
function useDistinctValueList(columnKey, options = {}) {
|
|
41
|
+
const { values } = useDistinctValues(columnKey, options);
|
|
42
|
+
return values.map((v) => v.value);
|
|
43
|
+
}
|
|
44
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
45
|
+
function read(provider, columnKey, refreshToken, limit) {
|
|
46
|
+
let byKey = cache.get(provider);
|
|
47
|
+
if (byKey == null) {
|
|
48
|
+
byKey = /* @__PURE__ */ new Map();
|
|
49
|
+
cache.set(provider, byKey);
|
|
50
|
+
}
|
|
51
|
+
const key = `${columnKey} ${refreshToken} ${limit ?? ""}`;
|
|
52
|
+
const cached = byKey.get(key);
|
|
53
|
+
if (cached != null) return cached;
|
|
54
|
+
const pending = provider.distinctValues(columnKey, { limit }).catch(
|
|
55
|
+
(error) => {
|
|
56
|
+
byKey.delete(key);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
);
|
|
60
|
+
byKey.set(key, pending);
|
|
61
|
+
return pending;
|
|
62
|
+
}
|
|
63
|
+
exports.useDistinctValueList = useDistinctValueList;
|
|
64
|
+
exports.useDistinctValues = useDistinctValues;
|
|
65
|
+
//# sourceMappingURL=distinct-values.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"distinct-values.cjs","sources":["../../src/provider/distinct-values.ts"],"sourcesContent":["/**\n * Reading a column's vocabulary — the distinct values it holds — so a filter\n * control can offer choices that actually match something.\n *\n * The provider answers the question (`TableDataProvider.distinctValues`); this\n * is the ergonomic half: one hook, one fetch per column per view, shared by\n * every control that asks. Without it every consumer hand-rolls a fetch and a\n * cache per facet, which is exactly what the ingestion list was doing three\n * times over.\n */\nimport { useEffect, useState } from \"react\";\nimport { ctx, dataProviderAtom } from \"./core.ts\";\nimport {\n dataRefreshTokenAtom,\n DistinctValue,\n DistinctValuesOptions,\n TableDataProvider,\n} from \"./table-data.ts\";\n\nexport interface DistinctValuesState<V = any> {\n /** The column's values, most useful first (frequency, then value). */\n values: DistinctValue<V>[];\n loading: boolean;\n error: Error | null;\n /** `false` when the source can't answer — a control should fall back to free\n * entry rather than showing an empty list. */\n supported: boolean;\n}\n\nconst EMPTY: DistinctValue[] = [];\n\n/**\n * The distinct values of `columnKey` in the enclosing view's source.\n *\n * Cached per (provider, column, refresh token): controls mount and unmount as\n * menus open, and shouldn't each pay for a request. A provider mutation bumps\n * the refresh token, so a newly-created value shows up without a manual\n * invalidation step.\n */\nexport function useDistinctValues<V = any>(\n columnKey: string | null | undefined,\n options: DistinctValuesOptions = {},\n): DistinctValuesState<V> {\n const { provider } = ctx.useValue(dataProviderAtom);\n const refreshToken = ctx.useValue(dataRefreshTokenAtom);\n const { limit } = options;\n\n const supported = provider?.distinctValues != null && columnKey != null;\n const [state, setState] = useState<DistinctValuesState<V>>({\n values: EMPTY,\n loading: supported,\n error: null,\n supported,\n });\n\n useEffect(() => {\n if (!supported) {\n setState({ values: EMPTY, loading: false, error: null, supported });\n return;\n }\n let active = true;\n const controller = new AbortController();\n setState((prev) => ({ ...prev, loading: true, supported }));\n\n read(provider!, columnKey!, refreshToken, limit)\n .then((values) => {\n if (!active) return;\n setState({ values, loading: false, error: null, supported: true });\n })\n .catch((error) => {\n if (!active || controller.signal.aborted) return;\n setState({ values: EMPTY, loading: false, error, supported: true });\n });\n\n return () => {\n active = false;\n controller.abort();\n };\n }, [provider, columnKey, refreshToken, limit, supported]);\n\n return state;\n}\n\n/** Just the values, for a control that doesn't care about counts or status. */\nexport function useDistinctValueList<V = any>(\n columnKey: string | null | undefined,\n options: DistinctValuesOptions = {},\n): V[] {\n const { values } = useDistinctValues<V>(columnKey, options);\n return values.map((v) => v.value);\n}\n\n// One in-flight-or-settled promise per (provider, column, token, limit). Keyed\n// weakly on the provider so a discarded view's cache goes with it.\nconst cache = new WeakMap<\n TableDataProvider<any>,\n Map<string, Promise<DistinctValue[]>>\n>();\n\nfunction read(\n provider: TableDataProvider<any>,\n columnKey: string,\n refreshToken: number,\n limit: number | undefined,\n): Promise<DistinctValue[]> {\n let byKey = cache.get(provider);\n if (byKey == null) {\n byKey = new Map();\n cache.set(provider, byKey);\n }\n const key = `${columnKey} ${refreshToken} ${limit ?? \"\"}`;\n const cached = byKey.get(key);\n if (cached != null) return cached;\n\n // The shared promise deliberately carries no abort signal: one unmounting\n // control must not cancel the fetch for the others. Each caller's own signal\n // only decides whether it still cares about the result.\n const pending = provider.distinctValues!(columnKey, { limit }).catch(\n (error) => {\n // Don't cache a failure — the next control to mount should retry.\n byKey!.delete(key);\n throw error;\n },\n );\n byKey.set(key, pending);\n return pending;\n}\n"],"names":["ctx","dataProviderAtom","dataRefreshTokenAtom","useState","useEffect"],"mappings":";;;;;AA6BA,MAAM,QAAyB,CAAA;AAUxB,SAAS,kBACd,WACA,UAAiC,IACT;AACxB,QAAM,EAAE,SAAA,IAAaA,SAAI,SAASC,KAAAA,gBAAgB;AAClD,QAAM,eAAeD,KAAAA,IAAI,SAASE,8BAAoB;AACtD,QAAM,EAAE,UAAU;AAElB,QAAM,YAAY,UAAU,kBAAkB,QAAQ,aAAa;AACnE,QAAM,CAAC,OAAO,QAAQ,IAAIC,eAAiC;AAAA,IACzD,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,OAAO;AAAA,IACP;AAAA,EAAA,CACD;AAEDC,QAAAA,UAAU,MAAM;AACd,QAAI,CAAC,WAAW;AACd,eAAS,EAAE,QAAQ,OAAO,SAAS,OAAO,OAAO,MAAM,WAAW;AAClE;AAAA,IACF;AACA,QAAI,SAAS;AACb,UAAM,aAAa,IAAI,gBAAA;AACvB,aAAS,CAAC,UAAU,EAAE,GAAG,MAAM,SAAS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
|
+
/** The column's values, most useful first (frequency, then value). */
|
|
4
|
+
values: DistinctValue<V>[];
|
|
5
|
+
loading: boolean;
|
|
6
|
+
error: Error | null;
|
|
7
|
+
/** `false` when the source can't answer — a control should fall back to free
|
|
8
|
+
* entry rather than showing an empty list. */
|
|
9
|
+
supported: boolean;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The distinct values of `columnKey` in the enclosing view's source.
|
|
13
|
+
*
|
|
14
|
+
* Cached per (provider, column, refresh token): controls mount and unmount as
|
|
15
|
+
* menus open, and shouldn't each pay for a request. A provider mutation bumps
|
|
16
|
+
* the refresh token, so a newly-created value shows up without a manual
|
|
17
|
+
* invalidation step.
|
|
18
|
+
*/
|
|
19
|
+
export declare function useDistinctValues<V = any>(columnKey: string | null | undefined, options?: DistinctValuesOptions): DistinctValuesState<V>;
|
|
20
|
+
/** Just the values, for a control that doesn't care about counts or status. */
|
|
21
|
+
export declare function useDistinctValueList<V = any>(columnKey: string | null | undefined, options?: DistinctValuesOptions): V[];
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { useState, useEffect } from "react";
|
|
2
|
+
import { ctx, dataProviderAtom } from "./core.js";
|
|
3
|
+
import { dataRefreshTokenAtom } from "./table-data.js";
|
|
4
|
+
const EMPTY = [];
|
|
5
|
+
function useDistinctValues(columnKey, options = {}) {
|
|
6
|
+
const { provider } = ctx.useValue(dataProviderAtom);
|
|
7
|
+
const refreshToken = ctx.useValue(dataRefreshTokenAtom);
|
|
8
|
+
const { limit } = options;
|
|
9
|
+
const supported = provider?.distinctValues != null && columnKey != null;
|
|
10
|
+
const [state, setState] = useState({
|
|
11
|
+
values: EMPTY,
|
|
12
|
+
loading: supported,
|
|
13
|
+
error: null,
|
|
14
|
+
supported
|
|
15
|
+
});
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!supported) {
|
|
18
|
+
setState({ values: EMPTY, loading: false, error: null, supported });
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
let active = true;
|
|
22
|
+
const controller = new AbortController();
|
|
23
|
+
setState((prev) => ({ ...prev, loading: true, supported }));
|
|
24
|
+
read(provider, columnKey, refreshToken, limit).then((values) => {
|
|
25
|
+
if (!active) return;
|
|
26
|
+
setState({ values, loading: false, error: null, supported: true });
|
|
27
|
+
}).catch((error) => {
|
|
28
|
+
if (!active || controller.signal.aborted) return;
|
|
29
|
+
setState({ values: EMPTY, loading: false, error, supported: true });
|
|
30
|
+
});
|
|
31
|
+
return () => {
|
|
32
|
+
active = false;
|
|
33
|
+
controller.abort();
|
|
34
|
+
};
|
|
35
|
+
}, [provider, columnKey, refreshToken, limit, supported]);
|
|
36
|
+
return state;
|
|
37
|
+
}
|
|
38
|
+
function useDistinctValueList(columnKey, options = {}) {
|
|
39
|
+
const { values } = useDistinctValues(columnKey, options);
|
|
40
|
+
return values.map((v) => v.value);
|
|
41
|
+
}
|
|
42
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
43
|
+
function read(provider, columnKey, refreshToken, limit) {
|
|
44
|
+
let byKey = cache.get(provider);
|
|
45
|
+
if (byKey == null) {
|
|
46
|
+
byKey = /* @__PURE__ */ new Map();
|
|
47
|
+
cache.set(provider, byKey);
|
|
48
|
+
}
|
|
49
|
+
const key = `${columnKey} ${refreshToken} ${limit ?? ""}`;
|
|
50
|
+
const cached = byKey.get(key);
|
|
51
|
+
if (cached != null) return cached;
|
|
52
|
+
const pending = provider.distinctValues(columnKey, { limit }).catch(
|
|
53
|
+
(error) => {
|
|
54
|
+
byKey.delete(key);
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
byKey.set(key, pending);
|
|
59
|
+
return pending;
|
|
60
|
+
}
|
|
61
|
+
export {
|
|
62
|
+
useDistinctValueList,
|
|
63
|
+
useDistinctValues
|
|
64
|
+
};
|
|
65
|
+
//# sourceMappingURL=distinct-values.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"distinct-values.js","sources":["../../src/provider/distinct-values.ts"],"sourcesContent":["/**\n * Reading a column's vocabulary — the distinct values it holds — so a filter\n * control can offer choices that actually match something.\n *\n * The provider answers the question (`TableDataProvider.distinctValues`); this\n * is the ergonomic half: one hook, one fetch per column per view, shared by\n * every control that asks. Without it every consumer hand-rolls a fetch and a\n * cache per facet, which is exactly what the ingestion list was doing three\n * times over.\n */\nimport { useEffect, useState } from \"react\";\nimport { ctx, dataProviderAtom } from \"./core.ts\";\nimport {\n dataRefreshTokenAtom,\n DistinctValue,\n DistinctValuesOptions,\n TableDataProvider,\n} from \"./table-data.ts\";\n\nexport interface DistinctValuesState<V = any> {\n /** The column's values, most useful first (frequency, then value). */\n values: DistinctValue<V>[];\n loading: boolean;\n error: Error | null;\n /** `false` when the source can't answer — a control should fall back to free\n * entry rather than showing an empty list. */\n supported: boolean;\n}\n\nconst EMPTY: DistinctValue[] = [];\n\n/**\n * The distinct values of `columnKey` in the enclosing view's source.\n *\n * Cached per (provider, column, refresh token): controls mount and unmount as\n * menus open, and shouldn't each pay for a request. A provider mutation bumps\n * the refresh token, so a newly-created value shows up without a manual\n * invalidation step.\n */\nexport function useDistinctValues<V = any>(\n columnKey: string | null | undefined,\n options: DistinctValuesOptions = {},\n): DistinctValuesState<V> {\n const { provider } = ctx.useValue(dataProviderAtom);\n const refreshToken = ctx.useValue(dataRefreshTokenAtom);\n const { limit } = options;\n\n const supported = provider?.distinctValues != null && columnKey != null;\n const [state, setState] = useState<DistinctValuesState<V>>({\n values: EMPTY,\n loading: supported,\n error: null,\n supported,\n });\n\n useEffect(() => {\n if (!supported) {\n setState({ values: EMPTY, loading: false, error: null, supported });\n return;\n }\n let active = true;\n const controller = new AbortController();\n setState((prev) => ({ ...prev, loading: true, supported }));\n\n read(provider!, columnKey!, refreshToken, limit)\n .then((values) => {\n if (!active) return;\n setState({ values, loading: false, error: null, supported: true });\n })\n .catch((error) => {\n if (!active || controller.signal.aborted) return;\n setState({ values: EMPTY, loading: false, error, supported: true });\n });\n\n return () => {\n active = false;\n controller.abort();\n };\n }, [provider, columnKey, refreshToken, limit, supported]);\n\n return state;\n}\n\n/** Just the values, for a control that doesn't care about counts or status. */\nexport function useDistinctValueList<V = any>(\n columnKey: string | null | undefined,\n options: DistinctValuesOptions = {},\n): V[] {\n const { values } = useDistinctValues<V>(columnKey, options);\n return values.map((v) => v.value);\n}\n\n// One in-flight-or-settled promise per (provider, column, token, limit). Keyed\n// weakly on the provider so a discarded view's cache goes with it.\nconst cache = new WeakMap<\n TableDataProvider<any>,\n Map<string, Promise<DistinctValue[]>>\n>();\n\nfunction read(\n provider: TableDataProvider<any>,\n columnKey: string,\n refreshToken: number,\n limit: number | undefined,\n): Promise<DistinctValue[]> {\n let byKey = cache.get(provider);\n if (byKey == null) {\n byKey = new Map();\n cache.set(provider, byKey);\n }\n const key = `${columnKey} ${refreshToken} ${limit ?? \"\"}`;\n const cached = byKey.get(key);\n if (cached != null) return cached;\n\n // The shared promise deliberately carries no abort signal: one unmounting\n // control must not cancel the fetch for the others. Each caller's own signal\n // only decides whether it still cares about the result.\n const pending = provider.distinctValues!(columnKey, { limit }).catch(\n (error) => {\n // Don't cache a failure — the next control to mount should retry.\n byKey!.delete(key);\n throw error;\n },\n );\n byKey.set(key, pending);\n return pending;\n}\n"],"names":[],"mappings":";;;AA6BA,MAAM,QAAyB,CAAA;AAUxB,SAAS,kBACd,WACA,UAAiC,IACT;AACxB,QAAM,EAAE,SAAA,IAAa,IAAI,SAAS,gBAAgB;AAClD,QAAM,eAAe,IAAI,SAAS,oBAAoB;AACtD,QAAM,EAAE,UAAU;AAElB,QAAM,YAAY,UAAU,kBAAkB,QAAQ,aAAa;AACnE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAiC;AAAA,IACzD,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,OAAO;AAAA,IACP;AAAA,EAAA,CACD;AAED,YAAU,MAAM;AACd,QAAI,CAAC,WAAW;AACd,eAAS,EAAE,QAAQ,OAAO,SAA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AACtB,SAAO;AACT;"}
|
package/dist/provider/index.d.ts
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const types = require("./types.cjs");
|
|
4
4
|
const jotai = require("jotai");
|
|
5
|
+
function distinctValuesOf(rows, columnKey, options = {}) {
|
|
6
|
+
const counts = /* @__PURE__ */ new Map();
|
|
7
|
+
for (const row of rows) {
|
|
8
|
+
const value = row?.[columnKey];
|
|
9
|
+
counts.set(value, (counts.get(value) ?? 0) + 1);
|
|
10
|
+
}
|
|
11
|
+
const values = [...counts.entries()].map(([value, count]) => ({
|
|
12
|
+
value,
|
|
13
|
+
count
|
|
14
|
+
}));
|
|
15
|
+
values.sort((a, b) => {
|
|
16
|
+
if (b.count !== a.count) return b.count - a.count;
|
|
17
|
+
return String(a.value).localeCompare(String(b.value));
|
|
18
|
+
});
|
|
19
|
+
if (options.limit != null) return values.slice(0, options.limit);
|
|
20
|
+
return values;
|
|
21
|
+
}
|
|
5
22
|
function createLocalProvider(data, options = {}) {
|
|
6
23
|
const identity = options.identity ?? defaultLocalIdentity;
|
|
7
24
|
return {
|
|
@@ -22,6 +39,9 @@ function createLocalProvider(data, options = {}) {
|
|
|
22
39
|
rows: rows.slice(offset, offset + limit),
|
|
23
40
|
totalCount: rows.length
|
|
24
41
|
};
|
|
42
|
+
},
|
|
43
|
+
async distinctValues(columnKey, opts) {
|
|
44
|
+
return distinctValuesOf(data, columnKey, opts);
|
|
25
45
|
}
|
|
26
46
|
};
|
|
27
47
|
}
|
|
@@ -88,5 +108,6 @@ async function persistViaProvider(provider, ctx) {
|
|
|
88
108
|
exports.compareRowsBySorts = compareRowsBySorts;
|
|
89
109
|
exports.createLocalProvider = createLocalProvider;
|
|
90
110
|
exports.dataRefreshTokenAtom = dataRefreshTokenAtom;
|
|
111
|
+
exports.distinctValuesOf = distinctValuesOf;
|
|
91
112
|
exports.persistViaProvider = persistViaProvider;
|
|
92
113
|
//# sourceMappingURL=table-data.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-data.cjs","sources":["../../src/provider/table-data.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n };\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n"],"names":["atom","TableElementStatus"],"mappings":";;;;AAuEO,SAAS,oBACd,MACA,UAAsD,IAChC;AACtB,QAAM,WAAgB,QAAQ,YAAY;AAE1C,SAAO;AAAA,IACL;AAAA,IACA,MAAM,UAAU,EAAE,QAAQ,OA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.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n /** The distinct values a column holds — the vocabulary a value picker offers,\n * so a filter can only be set to something that matches. Optional: a source\n * that can't answer it cheaply simply omits it, and pickers fall back to free\n * entry. See {@link useDistinctValues}. */\n distinctValues?(\n columnKey: string,\n options?: DistinctValuesOptions,\n ): Promise<DistinctValue[]>;\n}\n\n/** One value a column holds, with its frequency where the source reports it. */\nexport interface DistinctValue<V = any> {\n value: V;\n /** Rows carrying this value. Omitted when the source can't count cheaply. */\n count?: number;\n}\n\nexport interface DistinctValuesOptions {\n /** Aborts when the request is superseded (unmount, key change). */\n signal?: AbortSignal;\n /** Cap on how many values to return — a high-cardinality column shouldn't\n * become an unbounded fetch. */\n limit?: number;\n}\n\n/** Distinct values of an in-memory column, ordered by descending frequency then\n * value. Array cells are *not* flattened: the values of an array column are its\n * arrays, matching what a server-side `GROUP BY` would report. */\nexport function distinctValuesOf<T>(\n rows: T[],\n columnKey: string,\n options: DistinctValuesOptions = {},\n): DistinctValue[] {\n const counts = new Map<any, number>();\n for (const row of rows) {\n const value = (row as any)?.[columnKey];\n counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n const values = [...counts.entries()].map(([value, count]) => ({\n value,\n count,\n }));\n values.sort((a, b) => {\n if (b.count !== a.count) return b.count - a.count;\n return String(a.value).localeCompare(String(b.value));\n });\n if (options.limit != null) return values.slice(0, options.limit);\n return values;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n async distinctValues(columnKey, opts) {\n return distinctValuesOf(data, columnKey, opts);\n },\n };\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n"],"names":["atom","TableElementStatus"],"mappings":";;;;AA2FO,SAAS,iBACd,MACA,WACA,UAAiC,CAAA,GAChB;AACjB,QAAM,6BAAa,IAAA;AACnB,aAAW,OAAO,MAAM;AACtB,UAAM,QAAS,MAAc,SAAS;AACtC,WAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;AAAA,EAChD;AACA,QAAM,SAAS,CAAC,GAAG,OAAO,QAAA,CAAS,EAAE,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO;AAAA,IAC5D;AAAA,IACA;AAAA,EAAA,EACA;AACF,SAAO,KAAK,CAAC,GAAG,MAAM;AACpB,QAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,WAAO,OAAO,EAAE,KAAK,EAAE,cAAc,OAAO,EAAE,KAAK,CAAC;AAAA,EACtD,CAAC;AACD,MAAI,QAAQ,SAAS,KAAM,QAAO,OAAO,MAAM,GAAG,QAAQ,KAAK;A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,OAAO,UAAU;AAC1B,QAAI,SAAS,aAAa,KAAM,OAAM,SAAS,UAAU,GAAG;AAAA,EAC9D;AACA,MAAI,OAAO,SAAS,KAAK,SAAS,YAAY,MAAM;AAClD,UAAM,SAAS,SAAS,MAAM;AAAA,EAChC;AACF;;;;;;"}
|
|
@@ -56,7 +56,29 @@ export interface TableDataProvider<T = any> {
|
|
|
56
56
|
saveRows?(rows: T[]): Promise<void>;
|
|
57
57
|
deleteRows?(ids: Array<string | number>): Promise<void>;
|
|
58
58
|
insertRow?(row: Partial<T>): Promise<void>;
|
|
59
|
+
/** The distinct values a column holds — the vocabulary a value picker offers,
|
|
60
|
+
* so a filter can only be set to something that matches. Optional: a source
|
|
61
|
+
* that can't answer it cheaply simply omits it, and pickers fall back to free
|
|
62
|
+
* entry. See {@link useDistinctValues}. */
|
|
63
|
+
distinctValues?(columnKey: string, options?: DistinctValuesOptions): Promise<DistinctValue[]>;
|
|
59
64
|
}
|
|
65
|
+
/** One value a column holds, with its frequency where the source reports it. */
|
|
66
|
+
export interface DistinctValue<V = any> {
|
|
67
|
+
value: V;
|
|
68
|
+
/** Rows carrying this value. Omitted when the source can't count cheaply. */
|
|
69
|
+
count?: number;
|
|
70
|
+
}
|
|
71
|
+
export interface DistinctValuesOptions {
|
|
72
|
+
/** Aborts when the request is superseded (unmount, key change). */
|
|
73
|
+
signal?: AbortSignal;
|
|
74
|
+
/** Cap on how many values to return — a high-cardinality column shouldn't
|
|
75
|
+
* become an unbounded fetch. */
|
|
76
|
+
limit?: number;
|
|
77
|
+
}
|
|
78
|
+
/** Distinct values of an in-memory column, ordered by descending frequency then
|
|
79
|
+
* value. Array cells are *not* flattened: the values of an array column are its
|
|
80
|
+
* arrays, matching what a server-side `GROUP BY` would report. */
|
|
81
|
+
export declare function distinctValuesOf<T>(rows: T[], columnKey: string, options?: DistinctValuesOptions): DistinctValue[];
|
|
60
82
|
/**
|
|
61
83
|
* The degenerate provider: an in-memory array. `fetchChunk` applies the active
|
|
62
84
|
* filter predicates and sorts over the array and returns the requested slice
|
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
import { TableElementStatus } from "./types.js";
|
|
2
2
|
import { atom } from "jotai";
|
|
3
|
+
function distinctValuesOf(rows, columnKey, options = {}) {
|
|
4
|
+
const counts = /* @__PURE__ */ new Map();
|
|
5
|
+
for (const row of rows) {
|
|
6
|
+
const value = row?.[columnKey];
|
|
7
|
+
counts.set(value, (counts.get(value) ?? 0) + 1);
|
|
8
|
+
}
|
|
9
|
+
const values = [...counts.entries()].map(([value, count]) => ({
|
|
10
|
+
value,
|
|
11
|
+
count
|
|
12
|
+
}));
|
|
13
|
+
values.sort((a, b) => {
|
|
14
|
+
if (b.count !== a.count) return b.count - a.count;
|
|
15
|
+
return String(a.value).localeCompare(String(b.value));
|
|
16
|
+
});
|
|
17
|
+
if (options.limit != null) return values.slice(0, options.limit);
|
|
18
|
+
return values;
|
|
19
|
+
}
|
|
3
20
|
function createLocalProvider(data, options = {}) {
|
|
4
21
|
const identity = options.identity ?? defaultLocalIdentity;
|
|
5
22
|
return {
|
|
@@ -20,6 +37,9 @@ function createLocalProvider(data, options = {}) {
|
|
|
20
37
|
rows: rows.slice(offset, offset + limit),
|
|
21
38
|
totalCount: rows.length
|
|
22
39
|
};
|
|
40
|
+
},
|
|
41
|
+
async distinctValues(columnKey, opts) {
|
|
42
|
+
return distinctValuesOf(data, columnKey, opts);
|
|
23
43
|
}
|
|
24
44
|
};
|
|
25
45
|
}
|
|
@@ -87,6 +107,7 @@ export {
|
|
|
87
107
|
compareRowsBySorts,
|
|
88
108
|
createLocalProvider,
|
|
89
109
|
dataRefreshTokenAtom,
|
|
110
|
+
distinctValuesOf,
|
|
90
111
|
persistViaProvider
|
|
91
112
|
};
|
|
92
113
|
//# sourceMappingURL=table-data.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-data.js","sources":["../../src/provider/table-data.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n };\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n"],"names":[],"mappings":";;AAuEO,SAAS,oBACd,MACA,UAAsD,IAChC;AACtB,QAAM,WAAgB,QAAQ,YAAY;AAE1C,SAAO;AAAA,IACL;AAAA,IACA,MAAM,UAAU,EAAE,QAAQ,OAAO,OAAO,WAAW;AACjD,UAAI,OAAO;AACX,UAAI,WAAW,QAAQ,QAAQ,SAAS,GAAG;AACzC,eAAO,KAAK;AAAA,UAAO,CAAC,QAClB,QAAQ;AAAA,YAAM,CAAC,MACb,EAAE,aAAa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Ae,CAAA;AACpC,QAAM,SAAU,IAAI,aAAa,CAAA;AACjC,QAAM,IAAI,KAAK,IAAI,KAAK,QAAQ,QAAQ,QAAQ,OAAO,MAAM;AAC7D,QAAM,SAAc,CAAA;AACpB,QAAM,WAAgB,CAAA;AACtB,QAAM,WAAmC,CAAA;AACzC,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,QAAI,OAAO,CAAC,MAAM,mBAAmB,SAAS;AAC5C,YAAM,KAAK,SAAS,SAAS,KAAK,CAAC,CAAC;AACpC,UAAI,MAAM,KAAM,UAAS,KAAK,EAAE;AAChC;AAAA,IACF;AACA,UAAM,MAAM,QAAQ,CAAC;AACrB,UAAM,UACJ,OAAO,QAAQ,OAAO,QAAQ,YAAY,OAAO,KAAK,GAAG,EAAE,SAAS;AACtE,QAAI,OAAO,CAAC,MAAM,mBAAmB,OAAO;AAC1C,eAAS,KAAK,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,KAAU;AAAA,IAC3C,WAAW,SAAS;AAClB,aAAO,KAAK,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,KAAU;AAAA,IACzC;AAAA,EACF;AACA,MAAI,SAAS,SAAS,KAAK,SAAS,cAAc,MAAM;AACtD,UAAM,SAAS,WAAW,QAAQ;AAAA,EACpC;AACA,aAAW,OAAO,UAAU;AAC1B,QAAI,SAAS,aAAa,KAAM,OAAM,SAAS,UAAU,GAAG;AAAA,EAC9D;AACA,MAAI,OAAO,SAAS,KAAK,SAAS,YAAY,MAAM;AAClD,UAAM,SAAS,SAAS,MAAM;AAAA,EAChC;AACF;"}
|
|
1
|
+
{"version":3,"file":"table-data.js","sources":["../../src/provider/table-data.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n /** The distinct values a column holds — the vocabulary a value picker offers,\n * so a filter can only be set to something that matches. Optional: a source\n * that can't answer it cheaply simply omits it, and pickers fall back to free\n * entry. See {@link useDistinctValues}. */\n distinctValues?(\n columnKey: string,\n options?: DistinctValuesOptions,\n ): Promise<DistinctValue[]>;\n}\n\n/** One value a column holds, with its frequency where the source reports it. */\nexport interface DistinctValue<V = any> {\n value: V;\n /** Rows carrying this value. Omitted when the source can't count cheaply. */\n count?: number;\n}\n\nexport interface DistinctValuesOptions {\n /** Aborts when the request is superseded (unmount, key change). */\n signal?: AbortSignal;\n /** Cap on how many values to return — a high-cardinality column shouldn't\n * become an unbounded fetch. */\n limit?: number;\n}\n\n/** Distinct values of an in-memory column, ordered by descending frequency then\n * value. Array cells are *not* flattened: the values of an array column are its\n * arrays, matching what a server-side `GROUP BY` would report. */\nexport function distinctValuesOf<T>(\n rows: T[],\n columnKey: string,\n options: DistinctValuesOptions = {},\n): DistinctValue[] {\n const counts = new Map<any, number>();\n for (const row of rows) {\n const value = (row as any)?.[columnKey];\n counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n const values = [...counts.entries()].map(([value, count]) => ({\n value,\n count,\n }));\n values.sort((a, b) => {\n if (b.count !== a.count) return b.count - a.count;\n return String(a.value).localeCompare(String(b.value));\n });\n if (options.limit != null) return values.slice(0, options.limit);\n return values;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n async distinctValues(columnKey, opts) {\n return distinctValuesOf(data, columnKey, opts);\n },\n };\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n"],"names":[],"mappings":";;AA2FO,SAAS,iBACd,MACA,WACA,UAAiC,CAAA,GAChB;AACjB,QAAM,6BAAa,IAAA;AACnB,aAAW,OAAO,MAAM;AACtB,UAAM,QAAS,MAAc,SAAS;AACtC,WAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;AAAA,EAChD;AACA,QAAM,SAAS,CAAC,GAAG,OAAO,QAAA,CAAS,EAAE,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO;AAAA,IAC5D;AAAA,IACA;AAAA,EAAA,EACA;AACF,SAAO,KAAK,CAAC,GAAG,MAAM;AACpB,QAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,WAAO,OAAO,EAAE,KAAK,EAAE,cAAc,OAAO,EAAE,KAAK,CAAC;AAAA,EACtD,CAAC;AACD,MAAI,QAAQ,SAAS,KAAM,QAAO,OAAO,MAAM,GAAG,QAAQ,KAAK;AAC/D,SAAO;AACT;AAQO,SAAS,oBACd,MACA,UAAsD,IAChC;AACtB,QAAM,WAAgB,QAAQ,YAAY;AAE1C,SAAO;AAAA,IACL;AAAA,IACA,MAAM,UAAU,EAAE,QAAQ,OAAO,OAAO,WAAW;AACjD,UAAI,OAAO;AACX,UAAI,WAAW,QAAQ,QA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