@macrostrat/data-sheet 4.2.1 → 4.3.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 +83 -0
- package/dist/actions/types.d.ts +10 -0
- package/dist/components/indicators/filter-and-sort.cjs +47 -6
- package/dist/components/indicators/filter-and-sort.cjs.map +1 -1
- package/dist/components/indicators/filter-and-sort.d.ts +28 -6
- package/dist/components/indicators/filter-and-sort.js +48 -7
- package/dist/components/indicators/filter-and-sort.js.map +1 -1
- package/dist/components/indicators/filter-and-sort.module.sass.cjs +5 -3
- package/dist/components/indicators/filter-and-sort.module.sass.cjs.map +1 -1
- package/dist/components/indicators/filter-and-sort.module.sass.js +5 -3
- package/dist/components/indicators/filter-and-sort.module.sass.js.map +1 -1
- package/dist/components/indicators/unified-filters.cjs +36 -22
- package/dist/components/indicators/unified-filters.cjs.map +1 -1
- package/dist/components/indicators/unified-filters.d.ts +10 -8
- package/dist/components/indicators/unified-filters.js +37 -23
- package/dist/components/indicators/unified-filters.js.map +1 -1
- package/dist/components/indicators/view-info.cjs +6 -0
- package/dist/components/indicators/view-info.cjs.map +1 -1
- package/dist/components/indicators/view-info.d.ts +2 -2
- package/dist/components/indicators/view-info.js +7 -1
- package/dist/components/indicators/view-info.js.map +1 -1
- package/dist/components/toolbars/actions-toolbar.cjs +7 -1
- package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
- package/dist/components/toolbars/actions-toolbar.js +7 -1
- package/dist/components/toolbars/actions-toolbar.js.map +1 -1
- package/dist/data-panel.cjs +51 -6
- package/dist/data-panel.cjs.map +1 -1
- package/dist/data-panel.d.ts +1 -1
- package/dist/data-panel.js +52 -7
- package/dist/data-panel.js.map +1 -1
- package/dist/data-panel.module.sass.cjs +24 -21
- package/dist/data-panel.module.sass.cjs.map +1 -1
- package/dist/data-panel.module.sass.js +24 -21
- package/dist/data-panel.module.sass.js.map +1 -1
- package/dist/data-sheet.cjs +3 -1
- package/dist/data-sheet.cjs.map +1 -1
- package/dist/data-sheet.css +56 -35
- 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 +2 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -1
- package/dist/postgrest-table/data-loaders.cjs +20 -3
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.d.ts +10 -0
- package/dist/postgrest-table/data-loaders.js +21 -4
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/provider/core.cjs +27 -56
- package/dist/provider/core.cjs.map +1 -1
- package/dist/provider/core.d.ts +7 -9
- package/dist/provider/core.js +19 -48
- package/dist/provider/core.js.map +1 -1
- package/dist/provider/interactions.d.ts +1 -1
- package/dist/provider/selection.d.ts +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +4 -0
- package/dist/types.js.map +1 -1
- package/package.json +5 -6
- package/src/actions/types.ts +11 -0
- package/src/components/indicators/filter-and-sort.module.sass +7 -0
- package/src/components/indicators/filter-and-sort.ts +71 -11
- package/src/components/indicators/unified-filters.ts +66 -29
- package/src/components/indicators/view-info.ts +10 -0
- package/src/components/toolbars/actions-toolbar.ts +10 -1
- package/src/data-panel.module.sass +18 -1
- package/src/data-panel.ts +65 -6
- package/src/data-sheet.ts +2 -0
- package/src/postgrest-table/data-loaders.ts +40 -4
- package/src/provider/core.ts +29 -53
- package/src/types.ts +4 -0
package/dist/provider/core.js
CHANGED
|
@@ -1,47 +1,22 @@
|
|
|
1
|
-
import { useRef, useMemo, useEffect
|
|
1
|
+
import { useRef, useMemo, useEffect } from "react";
|
|
2
2
|
import h from "@macrostrat/hyper";
|
|
3
|
-
import { useStore, createStore } from "zustand";
|
|
4
3
|
import { generateColumnSpec, postprocessColumnSpec } from "./column-spec.js";
|
|
5
|
-
import { createScopedStore } from "@macrostrat/
|
|
4
|
+
import { zustandAPIAtom, zustandStoreAtom, atom, createScopedStore, useZustandSelector, useZustandStoreAPI, ZustandStoreProvider } from "@macrostrat/scoped-store";
|
|
6
5
|
import { TableElementStatus, DS_ROW_ID } from "./types.js";
|
|
7
6
|
import { createZustandStore } from "./zustand-store.js";
|
|
8
|
-
import { atomWithStore } from "jotai-zustand";
|
|
9
7
|
import { toasterAtom } from "../notifications.js";
|
|
10
|
-
import { atom } from "jotai";
|
|
11
8
|
import { dataRefreshTokenAtom, createLocalProvider } from "./table-data.js";
|
|
12
9
|
import { ToasterContext, ErrorBoundary } from "@macrostrat/ui-components";
|
|
13
10
|
import { resolveInteractionOptions, DataViewRendererType, interactionOptionsAtom, interactionOptionsKeys } from "./interactions.js";
|
|
14
11
|
import { splitProps } from "../utils/atoms.js";
|
|
15
12
|
const ctx = createScopedStore();
|
|
16
|
-
const storeAPIAtom =
|
|
17
|
-
const
|
|
18
|
-
const _storeAPIAtom = get(storeAPIAtom);
|
|
19
|
-
if (_storeAPIAtom == null) {
|
|
20
|
-
return void 0;
|
|
21
|
-
}
|
|
22
|
-
return atomWithStore(_storeAPIAtom);
|
|
23
|
-
});
|
|
24
|
-
const storeAtom = atom(
|
|
25
|
-
(get) => {
|
|
26
|
-
const storeWrapper = get(storeWrapperAtom);
|
|
27
|
-
if (storeWrapper == null) {
|
|
28
|
-
return void 0;
|
|
29
|
-
}
|
|
30
|
-
return get(storeWrapper);
|
|
31
|
-
},
|
|
32
|
-
(get, set, action) => {
|
|
33
|
-
const storeWrapper = get(storeWrapperAtom);
|
|
34
|
-
if (storeWrapper == null) {
|
|
35
|
-
throw new Error("Missing DataSheetProvider");
|
|
36
|
-
}
|
|
37
|
-
return set(storeWrapper, action);
|
|
38
|
-
}
|
|
39
|
-
);
|
|
13
|
+
const storeAPIAtom = zustandAPIAtom;
|
|
14
|
+
const storeAtom = zustandStoreAtom;
|
|
40
15
|
const EMPTY_SPEC = [];
|
|
41
16
|
const initializeStoreAtom = atom(
|
|
42
17
|
null,
|
|
43
18
|
(get, set, payload) => {
|
|
44
|
-
set(
|
|
19
|
+
set(zustandStoreAtom, (state) => {
|
|
45
20
|
return {
|
|
46
21
|
...state,
|
|
47
22
|
...payload
|
|
@@ -94,16 +69,13 @@ function useResolvedProvider(props) {
|
|
|
94
69
|
}
|
|
95
70
|
function DataSheetStoreWrapper(props) {
|
|
96
71
|
const { toaster, ...rest } = props;
|
|
97
|
-
const [store] = useState(() => {
|
|
98
|
-
return createStore(createZustandStore);
|
|
99
|
-
});
|
|
100
72
|
return h(
|
|
101
|
-
|
|
73
|
+
ZustandStoreProvider,
|
|
102
74
|
{
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
75
|
+
ctx,
|
|
76
|
+
initializeStore: createZustandStore,
|
|
77
|
+
atoms: [[toasterAtom, toaster]],
|
|
78
|
+
debugName: "DataSheetProvider"
|
|
107
79
|
},
|
|
108
80
|
h(DataSheetProviderInner, rest)
|
|
109
81
|
);
|
|
@@ -172,9 +144,13 @@ function DataSheetProviderInner(props) {
|
|
|
172
144
|
useEffect(() => {
|
|
173
145
|
initializeStore({
|
|
174
146
|
columnSpec: postprocessColumnSpec(baseSpec),
|
|
175
|
-
//
|
|
176
|
-
//
|
|
177
|
-
|
|
147
|
+
// Suppress the loader's first-chunk auto-generation whenever the consumer
|
|
148
|
+
// provided a spec at all — a function (derived later in `_DataSheet`) OR
|
|
149
|
+
// an explicit array, *including an empty one*. An empty array means "no
|
|
150
|
+
// facet columns" (e.g. a browse panel whose only control is a sheet-level
|
|
151
|
+
// search), not "please generate from the data". Auto-gen runs only when
|
|
152
|
+
// no `columnSpec` was passed.
|
|
153
|
+
deferColumnSpec: columnSpec != null,
|
|
178
154
|
editable: interactionOptions.enableEditing,
|
|
179
155
|
enableColumnReordering,
|
|
180
156
|
data,
|
|
@@ -235,15 +211,10 @@ function DataSheetProviderInner(props) {
|
|
|
235
211
|
return children;
|
|
236
212
|
}
|
|
237
213
|
function useStoreAPI() {
|
|
238
|
-
|
|
239
|
-
if (!store) {
|
|
240
|
-
throw new Error("Missing DataSheetProvider");
|
|
241
|
-
}
|
|
242
|
-
return store;
|
|
214
|
+
return useZustandStoreAPI(ctx);
|
|
243
215
|
}
|
|
244
216
|
function useSelector(selector) {
|
|
245
|
-
|
|
246
|
-
return useStore(store, selector);
|
|
217
|
+
return useZustandSelector(ctx, selector);
|
|
247
218
|
}
|
|
248
219
|
const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);
|
|
249
220
|
const tableDataAtom = atom(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","sources":["../../src/provider/core.ts"],"sourcesContent":["import { SetStateAction, useEffect, useMemo, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport { createScopedStore } from \"@macrostrat/data-components\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { atomWithStore } from \"jotai-zustand\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport { atom } from \"jotai\";\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 = atom<StoreApi<DataSheetStore<any>>>();\n\nconst storeWrapperAtom = atom((get) => {\n const _storeAPIAtom = get(storeAPIAtom);\n if (_storeAPIAtom == null) {\n return undefined;\n }\n return atomWithStore(_storeAPIAtom);\n});\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = atom(\n (get) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n return undefined;\n }\n return get(storeWrapper);\n },\n (get, set, action: SetStateAction<any>) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return set(storeWrapper, action);\n },\n);\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(storeAtom, (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 const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(createZustandStore);\n });\n return h(\n ctx.Provider,\n {\n atoms: [\n [storeAPIAtom, store],\n [toasterAtom, toaster],\n ],\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>\n | DataPanelProps<T>\n | 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 // A function spec is derived from the loaded rows in `_DataSheet`; tell\n // the loader not to auto-generate a plain spec from the first chunk.\n deferColumnSpec: isFnSpec,\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>(): StoreApi<DataSheetStore<T>> {\n const store = ctx.useValue(storeAPIAtom);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, 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":";;;;;;;;;;;;;;AA0CO,MAAM,MAAM,kBAAA;AAEZ,MAAM,eAAe,KAAA;AAE5B,MAAM,mBAAmB,KAAK,CAAC,QAAQ;AACrC,QAAM,gBAAgB,IAAI,YAAY;AACtC,MAAI,iBAAiB,MAAM;AACzB,WAAO;AAAA,EACT;AACA,SAAO,cAAc,aAAa;AACpC,CAAC;AAGM,MAAM,YAAY;AAAA,EACvB,CAAC,QAAQ;AACP,UAAM,eAAe,IAAI,gBAAgB;AACzC,QAAI,gBAAgB,MAAM;AACxB,aAAO;AAAA,IACT;AACA,WA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AM,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 } 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,Y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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;"}
|
|
@@ -36,4 +36,4 @@ export declare const interactionOptionsKeys: Set<keyof InteractionOptions>;
|
|
|
36
36
|
/** Resolve the granular interaction options for a particular editing domain */
|
|
37
37
|
export declare function resolveInteractionOptions(opts: InteractionOptions, renderer: DataViewRendererType): InteractionOptionsResolved;
|
|
38
38
|
export declare const enableDragValueAtom: import('jotai').Atom<boolean>;
|
|
39
|
-
export declare const dragValueHandlerAtom: import('jotai').Atom<
|
|
39
|
+
export declare const dragValueHandlerAtom: import('jotai').Atom<any>;
|
|
@@ -6,4 +6,4 @@ export declare const anchorRefAtom: import('jotai').PrimitiveAtom<{
|
|
|
6
6
|
current: number | null;
|
|
7
7
|
};
|
|
8
8
|
};
|
|
9
|
-
export declare const selectionAtom: import('jotai').WritableAtom<
|
|
9
|
+
export declare const selectionAtom: import('jotai').WritableAtom<any, [regions?: Region[] | undefined], void>;
|
package/dist/types.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sources":["../src/types.ts"],"sourcesContent":["import {\n EditEvent,\n FetchData,\n InteractionOptions,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableDataProvider,\n TableElementStatus,\n VisibleCells,\n} from \"./provider\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./provider\";\nimport { ReactNode } from \"react\";\nimport { TableAction, TableActionContext, TableFilter } from \"./actions\";\nimport { Region, TableProps } from \"@blueprintjs/table\";\n\nexport type FetchMode = \"scroll\" | \"paged\";\n\nexport interface FetchDataOptions {\n pageSize?: number;\n fetchMode?: FetchMode;\n}\n\n/** Props shared between the wrapper components and the provider */\nexport interface DataViewCoreProps<T> extends InteractionOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n /** Column definitions. Either a static array, or a function derived from the\n * loaded rows — invoked once the first rows arrive (and re-invoked when the\n * function's identity changes), so a data-shaped spec needs no separate fetch\n * of sample data. Omit entirely to auto-generate a plain spec via\n * `columnSpecOptions`. */\n columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);\n columnSpecOptions?: ColumnSpecOptions<T>;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Shown as the toolbar's leading label when nothing is selected. */\n name?: string;\n // itemLabel (e.g., \"row\", \"item\")\n itemLabel?: string;\n /** Bump to force a re-fetch from scratch (e.g. after an immediate edit that\n * mutated rows through the provider). */\n refreshToken?: number | string;\n}\n\nexport interface DataViewSharedProps<T = any>\n extends FetchDataOptions, DataViewCoreProps<T> {\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n //enableSelection?: boolean;\n}\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\nexport interface DataSheetRendererProps<T = any>\n extends TableProps, DataViewSharedProps<T> {\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n\n /** Derive the controlled edit overlay from the loaded rows, *inside* the\n * sheet. For provider-backed tables whose overlay is a function of the loaded\n * data plus external edit state (e.g. an ops stack): the library owns the\n * rows, so it calls this with them and uses the result as the controlled\n * overlay, re-deriving when the rows — or this function's identity (close it\n * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */\n deriveOverlay?: (rows: T[]) => {\n updatedData: T[];\n rowStatus: TableElementStatus[];\n };\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n /** Arbitrary nodes for the bottom status bar (left group), rendered beside\n * the active sort/filter tags — the home for view-state controls (show/hide\n * omitted rows/columns, a group-by indicator, etc.). */\n statusBar?: ReactNode;\n /** Presentation per row-status value, merged over the built-in defaults\n * (which style `\"deleted\"`). Supply styles for consumer-defined statuses\n * (e.g. `\"omitted\"`) and/or override the defaults. Each entry may set the\n * cells' style/intent and the row header's style. */\n rowStatusStyles?: RowStatusStyles;\n /** Render the content of a row's header cell (the left gutter). Receives the\n * row, its status, and the default 1-based label; return a node to use, or a\n * nullish value to keep the default. For group-key labels, omit indicators,\n * etc. Header-cell *styling* still comes from `rowStatusStyles`. */\n rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;\n minRowHeight: number;\n defaultColumnWidth: number;\n debug: boolean;\n}\n\nexport type DataSheetProps<T> = DataViewCoreProps<T> &\n DataSheetRendererProps<T>;\n"],"names":["DataSheetDensity"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":["../src/types.ts"],"sourcesContent":["import {\n EditEvent,\n FetchData,\n InteractionOptions,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableDataProvider,\n TableElementStatus,\n VisibleCells,\n} from \"./provider\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./provider\";\nimport { ReactNode } from \"react\";\nimport { TableAction, TableActionContext, TableFilter } from \"./actions\";\nimport { Region, TableProps } from \"@blueprintjs/table\";\n\nexport type FetchMode = \"scroll\" | \"paged\";\n\nexport interface FetchDataOptions {\n pageSize?: number;\n fetchMode?: FetchMode;\n /** Debounce (ms) applied to view-state → refetch, so rapid changes (typing a\n * text filter) collapse into one fetch once the view settles. The input stays\n * instant; only the fetch waits. `0` (default) keeps immediate refetching. */\n filterDebounce?: number;\n}\n\n/** Props shared between the wrapper components and the provider */\nexport interface DataViewCoreProps<T> extends InteractionOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n /** Column definitions. Either a static array, or a function derived from the\n * loaded rows — invoked once the first rows arrive (and re-invoked when the\n * function's identity changes), so a data-shaped spec needs no separate fetch\n * of sample data. Omit entirely to auto-generate a plain spec via\n * `columnSpecOptions`. */\n columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);\n columnSpecOptions?: ColumnSpecOptions<T>;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Shown as the toolbar's leading label when nothing is selected. */\n name?: string;\n // itemLabel (e.g., \"row\", \"item\")\n itemLabel?: string;\n /** Bump to force a re-fetch from scratch (e.g. after an immediate edit that\n * mutated rows through the provider). */\n refreshToken?: number | string;\n}\n\nexport interface DataViewSharedProps<T = any>\n extends FetchDataOptions, DataViewCoreProps<T> {\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n //enableSelection?: boolean;\n}\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\nexport interface DataSheetRendererProps<T = any>\n extends TableProps, DataViewSharedProps<T> {\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n\n /** Derive the controlled edit overlay from the loaded rows, *inside* the\n * sheet. For provider-backed tables whose overlay is a function of the loaded\n * data plus external edit state (e.g. an ops stack): the library owns the\n * rows, so it calls this with them and uses the result as the controlled\n * overlay, re-deriving when the rows — or this function's identity (close it\n * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */\n deriveOverlay?: (rows: T[]) => {\n updatedData: T[];\n rowStatus: TableElementStatus[];\n };\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n /** Arbitrary nodes for the bottom status bar (left group), rendered beside\n * the active sort/filter tags — the home for view-state controls (show/hide\n * omitted rows/columns, a group-by indicator, etc.). */\n statusBar?: ReactNode;\n /** Presentation per row-status value, merged over the built-in defaults\n * (which style `\"deleted\"`). Supply styles for consumer-defined statuses\n * (e.g. `\"omitted\"`) and/or override the defaults. Each entry may set the\n * cells' style/intent and the row header's style. */\n rowStatusStyles?: RowStatusStyles;\n /** Render the content of a row's header cell (the left gutter). Receives the\n * row, its status, and the default 1-based label; return a node to use, or a\n * nullish value to keep the default. For group-key labels, omit indicators,\n * etc. Header-cell *styling* still comes from `rowStatusStyles`. */\n rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;\n minRowHeight: number;\n defaultColumnWidth: number;\n debug: boolean;\n}\n\nexport type DataSheetProps<T> = DataViewCoreProps<T> &\n DataSheetRendererProps<T>;\n"],"names":["DataSheetDensity"],"mappings":";;AAyEO,IAAK,qCAAAA,sBAAL;AACLA,oBAAA,MAAA,IAAO;AACPA,oBAAA,QAAA,IAAS;AACTA,oBAAA,KAAA,IAAM;AAHI,SAAAA;AAAA,GAAA,oBAAA,CAAA,CAAA;;"}
|
package/dist/types.d.ts
CHANGED
|
@@ -6,6 +6,10 @@ export type FetchMode = "scroll" | "paged";
|
|
|
6
6
|
export interface FetchDataOptions {
|
|
7
7
|
pageSize?: number;
|
|
8
8
|
fetchMode?: FetchMode;
|
|
9
|
+
/** Debounce (ms) applied to view-state → refetch, so rapid changes (typing a
|
|
10
|
+
* text filter) collapse into one fetch once the view settles. The input stays
|
|
11
|
+
* instant; only the fetch waits. `0` (default) keeps immediate refetching. */
|
|
12
|
+
filterDebounce?: number;
|
|
9
13
|
}
|
|
10
14
|
/** Props shared between the wrapper components and the provider */
|
|
11
15
|
export interface DataViewCoreProps<T> extends InteractionOptions {
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import {\n EditEvent,\n FetchData,\n InteractionOptions,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableDataProvider,\n TableElementStatus,\n VisibleCells,\n} from \"./provider\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./provider\";\nimport { ReactNode } from \"react\";\nimport { TableAction, TableActionContext, TableFilter } from \"./actions\";\nimport { Region, TableProps } from \"@blueprintjs/table\";\n\nexport type FetchMode = \"scroll\" | \"paged\";\n\nexport interface FetchDataOptions {\n pageSize?: number;\n fetchMode?: FetchMode;\n}\n\n/** Props shared between the wrapper components and the provider */\nexport interface DataViewCoreProps<T> extends InteractionOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n /** Column definitions. Either a static array, or a function derived from the\n * loaded rows — invoked once the first rows arrive (and re-invoked when the\n * function's identity changes), so a data-shaped spec needs no separate fetch\n * of sample data. Omit entirely to auto-generate a plain spec via\n * `columnSpecOptions`. */\n columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);\n columnSpecOptions?: ColumnSpecOptions<T>;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Shown as the toolbar's leading label when nothing is selected. */\n name?: string;\n // itemLabel (e.g., \"row\", \"item\")\n itemLabel?: string;\n /** Bump to force a re-fetch from scratch (e.g. after an immediate edit that\n * mutated rows through the provider). */\n refreshToken?: number | string;\n}\n\nexport interface DataViewSharedProps<T = any>\n extends FetchDataOptions, DataViewCoreProps<T> {\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n //enableSelection?: boolean;\n}\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\nexport interface DataSheetRendererProps<T = any>\n extends TableProps, DataViewSharedProps<T> {\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n\n /** Derive the controlled edit overlay from the loaded rows, *inside* the\n * sheet. For provider-backed tables whose overlay is a function of the loaded\n * data plus external edit state (e.g. an ops stack): the library owns the\n * rows, so it calls this with them and uses the result as the controlled\n * overlay, re-deriving when the rows — or this function's identity (close it\n * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */\n deriveOverlay?: (rows: T[]) => {\n updatedData: T[];\n rowStatus: TableElementStatus[];\n };\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n /** Arbitrary nodes for the bottom status bar (left group), rendered beside\n * the active sort/filter tags — the home for view-state controls (show/hide\n * omitted rows/columns, a group-by indicator, etc.). */\n statusBar?: ReactNode;\n /** Presentation per row-status value, merged over the built-in defaults\n * (which style `\"deleted\"`). Supply styles for consumer-defined statuses\n * (e.g. `\"omitted\"`) and/or override the defaults. Each entry may set the\n * cells' style/intent and the row header's style. */\n rowStatusStyles?: RowStatusStyles;\n /** Render the content of a row's header cell (the left gutter). Receives the\n * row, its status, and the default 1-based label; return a node to use, or a\n * nullish value to keep the default. For group-key labels, omit indicators,\n * etc. Header-cell *styling* still comes from `rowStatusStyles`. */\n rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;\n minRowHeight: number;\n defaultColumnWidth: number;\n debug: boolean;\n}\n\nexport type DataSheetProps<T> = DataViewCoreProps<T> &\n DataSheetRendererProps<T>;\n"],"names":["DataSheetDensity"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import {\n EditEvent,\n FetchData,\n InteractionOptions,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableDataProvider,\n TableElementStatus,\n VisibleCells,\n} from \"./provider\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./provider\";\nimport { ReactNode } from \"react\";\nimport { TableAction, TableActionContext, TableFilter } from \"./actions\";\nimport { Region, TableProps } from \"@blueprintjs/table\";\n\nexport type FetchMode = \"scroll\" | \"paged\";\n\nexport interface FetchDataOptions {\n pageSize?: number;\n fetchMode?: FetchMode;\n /** Debounce (ms) applied to view-state → refetch, so rapid changes (typing a\n * text filter) collapse into one fetch once the view settles. The input stays\n * instant; only the fetch waits. `0` (default) keeps immediate refetching. */\n filterDebounce?: number;\n}\n\n/** Props shared between the wrapper components and the provider */\nexport interface DataViewCoreProps<T> extends InteractionOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n /** Column definitions. Either a static array, or a function derived from the\n * loaded rows — invoked once the first rows arrive (and re-invoked when the\n * function's identity changes), so a data-shaped spec needs no separate fetch\n * of sample data. Omit entirely to auto-generate a plain spec via\n * `columnSpecOptions`. */\n columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);\n columnSpecOptions?: ColumnSpecOptions<T>;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Shown as the toolbar's leading label when nothing is selected. */\n name?: string;\n // itemLabel (e.g., \"row\", \"item\")\n itemLabel?: string;\n /** Bump to force a re-fetch from scratch (e.g. after an immediate edit that\n * mutated rows through the provider). */\n refreshToken?: number | string;\n}\n\nexport interface DataViewSharedProps<T = any>\n extends FetchDataOptions, DataViewCoreProps<T> {\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n //enableSelection?: boolean;\n}\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\nexport interface DataSheetRendererProps<T = any>\n extends TableProps, DataViewSharedProps<T> {\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n\n /** Derive the controlled edit overlay from the loaded rows, *inside* the\n * sheet. For provider-backed tables whose overlay is a function of the loaded\n * data plus external edit state (e.g. an ops stack): the library owns the\n * rows, so it calls this with them and uses the result as the controlled\n * overlay, re-deriving when the rows — or this function's identity (close it\n * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */\n deriveOverlay?: (rows: T[]) => {\n updatedData: T[];\n rowStatus: TableElementStatus[];\n };\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n /** Arbitrary nodes for the bottom status bar (left group), rendered beside\n * the active sort/filter tags — the home for view-state controls (show/hide\n * omitted rows/columns, a group-by indicator, etc.). */\n statusBar?: ReactNode;\n /** Presentation per row-status value, merged over the built-in defaults\n * (which style `\"deleted\"`). Supply styles for consumer-defined statuses\n * (e.g. `\"omitted\"`) and/or override the defaults. Each entry may set the\n * cells' style/intent and the row header's style. */\n rowStatusStyles?: RowStatusStyles;\n /** Render the content of a row's header cell (the left gutter). Receives the\n * row, its status, and the default 1-based label; return a node to use, or a\n * nullish value to keep the default. For group-key labels, omit indicators,\n * etc. Header-cell *styling* still comes from `rowStatusStyles`. */\n rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;\n minRowHeight: number;\n defaultColumnWidth: number;\n debug: boolean;\n}\n\nexport type DataSheetProps<T> = DataViewCoreProps<T> &\n DataSheetRendererProps<T>;\n"],"names":["DataSheetDensity"],"mappings":"AAyEO,IAAK,qCAAAA,sBAAL;AACLA,oBAAA,MAAA,IAAO;AACPA,oBAAA,QAAA,IAAS;AACTA,oBAAA,KAAA,IAAM;AAHI,SAAAA;AAAA,GAAA,oBAAA,CAAA,CAAA;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@macrostrat/data-sheet",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.0",
|
|
4
4
|
"description": "Scalable data sheet with optional editing capabilities",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -49,17 +49,16 @@
|
|
|
49
49
|
"@blueprintjs/core": "^6.14.0",
|
|
50
50
|
"@blueprintjs/table": "^6.1.0",
|
|
51
51
|
"@macrostrat/color-utils": "^1.2.2",
|
|
52
|
-
"@macrostrat/data-components": "^1.
|
|
52
|
+
"@macrostrat/data-components": "^1.3.0",
|
|
53
53
|
"@macrostrat/hyper": "^3.1.1",
|
|
54
|
-
"@macrostrat/
|
|
54
|
+
"@macrostrat/scoped-store": "^1.0.0",
|
|
55
|
+
"@macrostrat/ui-components": "^5.1.0",
|
|
55
56
|
"@supabase/postgrest-js": "^1.17.7",
|
|
56
57
|
"@types/underscore": "^1.13.0",
|
|
57
58
|
"classnames": "^2.5.1",
|
|
58
59
|
"immutability-helper": "^3.1.1",
|
|
59
60
|
"jotai": "^2.20.0",
|
|
60
|
-
"
|
|
61
|
-
"underscore": "^1.13.7",
|
|
62
|
-
"zustand": "^5.0.2"
|
|
61
|
+
"underscore": "^1.13.7"
|
|
63
62
|
},
|
|
64
63
|
"devDependencies": {
|
|
65
64
|
"@macrostrat/web-components-bundler": "1.0.1",
|
package/src/actions/types.ts
CHANGED
|
@@ -35,8 +35,19 @@ export interface TableFilter<T = any, S = any> {
|
|
|
35
35
|
/** Row predicate: return `true` if the row should be visible.
|
|
36
36
|
* Receives the merged row (updatedData overlaid on data). */
|
|
37
37
|
predicate(row: T, state: S): boolean;
|
|
38
|
+
/** How this filter surfaces in the UI — progressive enhancement over the
|
|
39
|
+
* same `filterForm`:
|
|
40
|
+
* - `"menu"` (default): a menu item whose submenu holds the form.
|
|
41
|
+
* - `"menu-inline"`: the form renders directly in the filter menu (no
|
|
42
|
+
* submenu) — good for a compact control like a segmented picker.
|
|
43
|
+
* - `"inline"`: the form renders as an always-visible toolbar control (no
|
|
44
|
+
* menu) — good for a common, always-on control like a text search.
|
|
45
|
+
* The state/wiring is identical in every case; only placement changes. */
|
|
46
|
+
presentation?: FilterPresentation;
|
|
38
47
|
}
|
|
39
48
|
|
|
49
|
+
export type FilterPresentation = "menu" | "menu-inline" | "inline";
|
|
50
|
+
|
|
40
51
|
export interface ColumnFilter<T = any, S = any> extends Omit<
|
|
41
52
|
TableFilter<T, S>,
|
|
42
53
|
"columnKey"
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
HTMLSelect,
|
|
12
12
|
InputGroup,
|
|
13
13
|
Menu,
|
|
14
|
+
MenuDivider,
|
|
14
15
|
MenuItem,
|
|
15
16
|
PopoverNext,
|
|
16
17
|
Tag,
|
|
@@ -31,6 +32,22 @@ export function resolveColumnFilter(col: ColumnSpec): TableFilter {
|
|
|
31
32
|
return buildMultiOperatorColumnFilter(col);
|
|
32
33
|
}
|
|
33
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Render a filter's `filterForm` as an always-visible inline control — rather
|
|
37
|
+
* than behind a menu dropdown — wired to the shared filter state. Lets any
|
|
38
|
+
* `TableFilter` (e.g. an open text search spanning several columns) live
|
|
39
|
+
* directly in a toolbar while still flowing through the standard filter model:
|
|
40
|
+
* store `activeFilters` → the provider's `translateFilter`, identical to the
|
|
41
|
+
* menu-driven controls. The form clears the filter when its state goes empty
|
|
42
|
+
* (`state.value === ""`), matching the rest of the filter UI.
|
|
43
|
+
*/
|
|
44
|
+
export function InlineFilterControl({ filter }: { filter: TableFilter }) {
|
|
45
|
+
const [state, setState] = useFilterAtom(filter);
|
|
46
|
+
const Form = filter.filterForm;
|
|
47
|
+
if (Form == null) return null;
|
|
48
|
+
return h(Form, { state: state ?? filter.defaultState, setState });
|
|
49
|
+
}
|
|
50
|
+
|
|
34
51
|
/** Shows an active column filter in the top menu */
|
|
35
52
|
export function ColumnFilterControl({ col }: { col: ColumnSpec }) {
|
|
36
53
|
// Same `TableFilter` the FilterBar and any provider consume, so the header,
|
|
@@ -187,6 +204,25 @@ export function ColumnFilterMenuItem({
|
|
|
187
204
|
);
|
|
188
205
|
}
|
|
189
206
|
|
|
207
|
+
/** A filter rendered *inside* a menu but without a submenu — its name as a
|
|
208
|
+
* section header, its form directly below. For `presentation: "menu-inline"`
|
|
209
|
+
* (e.g. a compact segmented control that doesn't warrant a submenu hop). */
|
|
210
|
+
export function MenuInlineFilterItem({
|
|
211
|
+
filter,
|
|
212
|
+
label,
|
|
213
|
+
}: {
|
|
214
|
+
filter: TableFilter;
|
|
215
|
+
label?: string;
|
|
216
|
+
}) {
|
|
217
|
+
const { filterForm, valueText } = useFilterProps(filter);
|
|
218
|
+
return h("li.menu-inline-filter", [
|
|
219
|
+
h(MenuDivider, { title: label ?? filter.name }),
|
|
220
|
+
h("div.menu-inline-filter-body", { "data-filter-value": valueText }, [
|
|
221
|
+
filterForm,
|
|
222
|
+
]),
|
|
223
|
+
]);
|
|
224
|
+
}
|
|
225
|
+
|
|
190
226
|
function useFilterProps(filter: TableFilter) {
|
|
191
227
|
const [state, setState] = useFilterAtom(filter);
|
|
192
228
|
|
|
@@ -399,13 +435,14 @@ export function ColumnSortIndicator({
|
|
|
399
435
|
);
|
|
400
436
|
}
|
|
401
437
|
|
|
402
|
-
/** Menu-native sort
|
|
403
|
-
*
|
|
404
|
-
*
|
|
405
|
-
*
|
|
406
|
-
*
|
|
438
|
+
/** Menu-native sort as a **single, flat** item — no submenu. The item shows the
|
|
439
|
+
* field name with a direction icon (↑/↓); an active sort reads through the
|
|
440
|
+
* `primary` intent, and clicking the item toggles the direction (unsorted →
|
|
441
|
+
* ascending → descending → …). A right-aligned ✕ clears it. `text` is the
|
|
442
|
+
* field's display label (the `DataPanel` lists one item per sortable field). */
|
|
407
443
|
export function ColumnSortMenu({
|
|
408
444
|
columnKey,
|
|
445
|
+
text,
|
|
409
446
|
defaultLabel,
|
|
410
447
|
}: {
|
|
411
448
|
columnKey: string;
|
|
@@ -413,12 +450,35 @@ export function ColumnSortMenu({
|
|
|
413
450
|
defaultLabel?: string;
|
|
414
451
|
}) {
|
|
415
452
|
const [sort, setSort] = useSortAtom(columnKey);
|
|
416
|
-
const
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
453
|
+
const isActive = sort != null;
|
|
454
|
+
const icon =
|
|
455
|
+
sort == null ? "sort" : sort.ascending ? "sort-asc" : "sort-desc";
|
|
456
|
+
const name = text ?? defaultLabel ?? columnKey;
|
|
457
|
+
|
|
458
|
+
let clearButton: ReactNode = undefined;
|
|
459
|
+
if (isActive) {
|
|
460
|
+
clearButton = h(Button, {
|
|
461
|
+
icon: "cross",
|
|
462
|
+
minimal: true,
|
|
463
|
+
small: true,
|
|
464
|
+
onClick: (e: any) => {
|
|
465
|
+
e.stopPropagation();
|
|
466
|
+
setSort(null);
|
|
467
|
+
},
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return h(MenuItem, {
|
|
472
|
+
icon,
|
|
473
|
+
text: name,
|
|
474
|
+
intent: isActive ? "primary" : undefined,
|
|
475
|
+
active: isActive,
|
|
476
|
+
labelElement: clearButton,
|
|
477
|
+
shouldDismissPopover: false,
|
|
478
|
+
// Toggle direction; `setSort` never receives the current direction (so its
|
|
479
|
+
// click-same-to-clear path doesn't fire) — clearing is the ✕'s job.
|
|
480
|
+
onClick: () => setSort(sort == null ? true : !sort.ascending),
|
|
481
|
+
});
|
|
422
482
|
}
|
|
423
483
|
|
|
424
484
|
const setFilterAtom = atom(null, (get, set, filter: TableFilter, next: any) => {
|