@macrostrat/data-sheet 4.7.0 → 4.9.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 +47 -0
- package/README.md +60 -19
- package/dist/actions/context.cjs +10 -1
- package/dist/actions/context.cjs.map +1 -1
- package/dist/actions/context.js +10 -1
- package/dist/actions/context.js.map +1 -1
- package/dist/actions/types.d.ts +4 -0
- package/dist/components/data-editor.cjs +527 -0
- package/dist/components/data-editor.cjs.map +1 -0
- package/dist/components/data-editor.d.ts +142 -0
- package/dist/components/data-editor.js +524 -0
- package/dist/components/data-editor.js.map +1 -0
- package/dist/components/editor-actions.cjs +167 -0
- package/dist/components/editor-actions.cjs.map +1 -0
- package/dist/components/editor-actions.d.ts +37 -0
- package/dist/components/editor-actions.js +165 -0
- package/dist/components/editor-actions.js.map +1 -0
- package/dist/components/editor-popup.cjs +11 -1
- package/dist/components/editor-popup.cjs.map +1 -1
- package/dist/components/editor-popup.js +11 -1
- package/dist/components/editor-popup.js.map +1 -1
- package/dist/components/index.d.ts +3 -0
- package/dist/components/indicators/selection.cjs +10 -4
- package/dist/components/indicators/selection.cjs.map +1 -1
- package/dist/components/indicators/selection.js +10 -4
- package/dist/components/indicators/selection.js.map +1 -1
- package/dist/components/row-editor.cjs +351 -0
- package/dist/components/row-editor.cjs.map +1 -0
- package/dist/components/row-editor.d.ts +181 -0
- package/dist/components/row-editor.js +349 -0
- package/dist/components/row-editor.js.map +1 -0
- package/dist/components/row-editor.module.sass.cjs +51 -0
- package/dist/components/row-editor.module.sass.cjs.map +1 -0
- package/dist/components/row-editor.module.sass.js +49 -0
- package/dist/components/row-editor.module.sass.js.map +1 -0
- package/dist/components/toolbars/actions-toolbar.cjs +1 -1
- package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
- package/dist/components/toolbars/actions-toolbar.js +1 -1
- package/dist/components/toolbars/actions-toolbar.js.map +1 -1
- package/dist/data-panel.cjs +36 -0
- package/dist/data-panel.cjs.map +1 -1
- package/dist/data-panel.d.ts +3 -2
- package/dist/data-panel.js +37 -1
- package/dist/data-panel.js.map +1 -1
- package/dist/data-panel.module.sass.cjs +28 -26
- package/dist/data-panel.module.sass.cjs.map +1 -1
- package/dist/data-panel.module.sass.js +28 -26
- package/dist/data-panel.module.sass.js.map +1 -1
- package/dist/data-sheet.css +267 -56
- package/dist/data-sheet.d.ts +2 -1
- package/dist/data-view.d.ts +1 -0
- package/dist/index.cjs +28 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +31 -3
- package/dist/index.js.map +1 -1
- package/dist/main.module.sass.cjs +14 -13
- package/dist/main.module.sass.cjs.map +1 -1
- package/dist/main.module.sass.js +14 -13
- package/dist/main.module.sass.js.map +1 -1
- package/dist/postgrest-table/data-loaders.cjs +8 -1
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.js +9 -2
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/provider/column-spec.cjs +8 -1
- package/dist/provider/column-spec.cjs.map +1 -1
- package/dist/provider/column-spec.d.ts +105 -1
- package/dist/provider/column-spec.js +8 -1
- package/dist/provider/column-spec.js.map +1 -1
- package/dist/provider/core.cjs +32 -7
- package/dist/provider/core.cjs.map +1 -1
- package/dist/provider/core.d.ts +5 -1
- package/dist/provider/core.js +32 -7
- package/dist/provider/core.js.map +1 -1
- package/dist/provider/loader-state.cjs +11 -3
- package/dist/provider/loader-state.cjs.map +1 -1
- package/dist/provider/loader-state.d.ts +8 -1
- package/dist/provider/loader-state.js +12 -4
- package/dist/provider/loader-state.js.map +1 -1
- package/dist/provider/table-data.cjs +10 -1
- package/dist/provider/table-data.cjs.map +1 -1
- package/dist/provider/table-data.d.ts +10 -0
- package/dist/provider/table-data.js +11 -2
- package/dist/provider/table-data.js.map +1 -1
- package/dist/provider/types.cjs.map +1 -1
- package/dist/provider/types.d.ts +4 -1
- package/dist/provider/types.js.map +1 -1
- package/dist/provider/zustand-store.cjs +26 -13
- package/dist/provider/zustand-store.cjs.map +1 -1
- package/dist/provider/zustand-store.js +14 -1
- package/dist/provider/zustand-store.js.map +1 -1
- package/dist/renderers/cell-renderer.cjs +15 -4
- package/dist/renderers/cell-renderer.cjs.map +1 -1
- package/dist/renderers/cell-renderer.js +13 -4
- package/dist/renderers/cell-renderer.js.map +1 -1
- package/dist/renderers/column-header-cell.cjs +12 -1
- package/dist/renderers/column-header-cell.cjs.map +1 -1
- package/dist/renderers/column-header-cell.js +11 -1
- package/dist/renderers/column-header-cell.js.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +30 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/src/actions/context.ts +13 -2
- package/src/actions/types.ts +5 -0
- package/src/components/data-editor.ts +741 -0
- package/src/components/editor-actions.ts +228 -0
- package/src/components/editor-popup.ts +16 -3
- package/src/components/index.ts +3 -0
- package/src/components/indicators/selection.ts +12 -4
- package/src/components/row-editor.module.sass +161 -0
- package/src/components/row-editor.ts +620 -0
- package/src/components/toolbars/actions-toolbar.ts +3 -2
- package/src/data-panel.module.sass +25 -0
- package/src/data-panel.ts +50 -1
- package/src/main.module.sass +19 -0
- package/src/postgrest-table/data-loaders.ts +13 -0
- package/src/provider/column-spec.ts +94 -16
- package/src/provider/core.ts +41 -9
- package/src/provider/loader-state.ts +15 -2
- package/src/provider/table-data.ts +23 -1
- package/src/provider/types.ts +4 -1
- package/src/provider/zustand-store.ts +30 -1
- package/src/renderers/cell-renderer.ts +18 -3
- package/src/renderers/column-header-cell.ts +10 -0
- package/src/types.ts +31 -1
|
@@ -33,10 +33,17 @@ function seededLoaderCore(seed) {
|
|
|
33
33
|
totalCount: seed.totalCount ?? null
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
|
-
|
|
36
|
+
const startAfterAtom = jotai.atom(null);
|
|
37
|
+
function loaderSeedAtoms(initialData, startAfter = null) {
|
|
38
|
+
const atoms = [];
|
|
39
|
+
if (startAfter != null) {
|
|
40
|
+
atoms.push([startAfterAtom, startAfter]);
|
|
41
|
+
}
|
|
37
42
|
const seed = resolveInitialData(initialData);
|
|
38
|
-
if (seed
|
|
39
|
-
|
|
43
|
+
if (seed != null) {
|
|
44
|
+
atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);
|
|
45
|
+
}
|
|
46
|
+
return atoms;
|
|
40
47
|
}
|
|
41
48
|
exports.DEFAULT_LOADER_CORE = DEFAULT_LOADER_CORE;
|
|
42
49
|
exports.lazyLoaderCoreStateAtom = lazyLoaderCoreStateAtom;
|
|
@@ -44,4 +51,5 @@ exports.loaderSeedAtoms = loaderSeedAtoms;
|
|
|
44
51
|
exports.resolveInitialData = resolveInitialData;
|
|
45
52
|
exports.seededLoaderCore = seededLoaderCore;
|
|
46
53
|
exports.seededRows = seededRows;
|
|
54
|
+
exports.startAfterAtom = startAfterAtom;
|
|
47
55
|
//# sourceMappingURL=loader-state.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-state.cjs","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): AtomMap {\n const seed = resolveInitialData(initialData);\n if (seed
|
|
1
|
+
{"version":3,"file":"loader-state.cjs","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** The identity of the row the current view starts after (`startAfter`), or\n * `null` for a view that starts at the top. Set at store creation so a server\n * render shows the \"Return to top\" link; the loader clears it on the first view\n * change. */\nexport const startAfterAtom = atom<string | number | null>(null);\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n startAfter: FetchDataOptions<T>[\"startAfter\"] = null,\n): AtomMap {\n const atoms: AtomMap = [];\n if (startAfter != null) {\n atoms.push([startAfterAtom, startAfter]);\n }\n const seed = resolveInitialData(initialData);\n if (seed != null) {\n atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);\n }\n return atoms;\n}\n"],"names":["atom"],"mappings":";;;AAqBO,MAAM,sBAAgD;AAAA,EAC3D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AACZ;AAEO,MAAM,0BACXA,MAAAA,KAA+B,mBAAmB;AAK7C,SAAS,mBACd,aAC4B;AAC5B,MAAI,eAAe,KAAM,QAAO;AAChC,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,QAAI,YAAY,WAAW,EAAG,QAAO;AACrC,WAAO,EAAE,MAAM,YAAA;AAAA,EACjB;AACA,OAAK,YAAY,QAAQ,CAAA,GAAI,WAAW,EAAG,QAAO;AAClD,SAAO;AACT;AAKO,SAAS,WAAc,MAAyC;AACrE,QAAM,OAAO,KAAK,QAAQ,CAAA;AAC1B,QAAM,OAAO,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ,KAAK,MAAM;AACjE,QAAM,OAAqB,IAAI,MAAM,IAAI,EAAE,KAAK,IAAI;AACpD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,CAAC,IAAI,KAAK,CAAC;AACtD,SAAO;AACT;AAKO,SAAS,iBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa;AAAA,IACb,YAAY,KAAK,cAAc;AAAA,EAAA;AAEnC;AAMO,MAAM,iBAAiBA,MAAAA,KAA6B,IAAI;AAKxD,SAAS,gBACd,aACA,aAAgD,MACvC;AACT,QAAM,QAAiB,CAAA;AACvB,MAAI,cAAc,MAAM;AACtB,UAAM,KAAK,CAAC,gBAAgB,UAAU,CAAC;AAAA,EACzC;AACA,QAAM,OAAO,mBAAmB,WAAW;AAC3C,MAAI,QAAQ,MAAM;AAChB,UAAM,KAAK,CAAC,yBAAyB,iBAAiB,IAAI,CAAC,CAAC;AAAA,EAC9D;AACA,SAAO;AACT;;;;;;;;"}
|
|
@@ -27,7 +27,14 @@ export declare function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[];
|
|
|
27
27
|
* a completed first fetch. `initialized` means the loader neither refetches the
|
|
28
28
|
* seeded window nor shows an empty state. */
|
|
29
29
|
export declare function seededLoaderCore<T>(seed: InitialDataChunk<T>): LazyLoaderStateCore<T>;
|
|
30
|
+
/** The identity of the row the current view starts after (`startAfter`), or
|
|
31
|
+
* `null` for a view that starts at the top. Set at store creation so a server
|
|
32
|
+
* render shows the "Return to top" link; the loader clears it on the first view
|
|
33
|
+
* change. */
|
|
34
|
+
export declare const startAfterAtom: import('jotai').PrimitiveAtom<string | number | null> & {
|
|
35
|
+
init: string | number | null;
|
|
36
|
+
};
|
|
30
37
|
/** Scoped-store atoms that make a store start out seeded. The store's own
|
|
31
38
|
* `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is
|
|
32
39
|
* no seed. */
|
|
33
|
-
export declare function loaderSeedAtoms<T>(initialData: FetchDataOptions<T>["initialData"]): AtomMap;
|
|
40
|
+
export declare function loaderSeedAtoms<T>(initialData: FetchDataOptions<T>["initialData"], startAfter?: FetchDataOptions<T>["startAfter"]): AtomMap;
|
|
@@ -31,10 +31,17 @@ function seededLoaderCore(seed) {
|
|
|
31
31
|
totalCount: seed.totalCount ?? null
|
|
32
32
|
};
|
|
33
33
|
}
|
|
34
|
-
|
|
34
|
+
const startAfterAtom = atom(null);
|
|
35
|
+
function loaderSeedAtoms(initialData, startAfter = null) {
|
|
36
|
+
const atoms = [];
|
|
37
|
+
if (startAfter != null) {
|
|
38
|
+
atoms.push([startAfterAtom, startAfter]);
|
|
39
|
+
}
|
|
35
40
|
const seed = resolveInitialData(initialData);
|
|
36
|
-
if (seed
|
|
37
|
-
|
|
41
|
+
if (seed != null) {
|
|
42
|
+
atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);
|
|
43
|
+
}
|
|
44
|
+
return atoms;
|
|
38
45
|
}
|
|
39
46
|
export {
|
|
40
47
|
DEFAULT_LOADER_CORE,
|
|
@@ -42,6 +49,7 @@ export {
|
|
|
42
49
|
loaderSeedAtoms,
|
|
43
50
|
resolveInitialData,
|
|
44
51
|
seededLoaderCore,
|
|
45
|
-
seededRows
|
|
52
|
+
seededRows,
|
|
53
|
+
startAfterAtom
|
|
46
54
|
};
|
|
47
55
|
//# sourceMappingURL=loader-state.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-state.js","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): AtomMap {\n const seed = resolveInitialData(initialData);\n if (seed
|
|
1
|
+
{"version":3,"file":"loader-state.js","sources":["../../src/provider/loader-state.ts"],"sourcesContent":["/** The loader's core state and the seeding of a first window.\n *\n * Kept apart from the loader (`postgrest-table/data-loaders.ts`) so the\n * provider can seed the store at creation without a circular import.\n */\nimport { atom } from \"jotai\";\nimport type { AtomMap } from \"@macrostrat/scoped-store\";\nimport type { FetchDataOptions, FetchMode, InitialDataChunk } from \"../types.ts\";\n\nexport interface LazyLoaderStateCore<T> {\n loading: boolean;\n error: Error | null;\n initialized: boolean;\n /** Reported source length when known (null = unknown / not reported). */\n totalCount: number | null;\n /** Windowing style: infinite-scroll windows, or one fixed page at a time. */\n fetchMode: FetchMode;\n /** Rows per chunk/page. */\n pageSize: number;\n}\n\nexport const DEFAULT_LOADER_CORE: LazyLoaderStateCore<any> = {\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n};\n\nexport const lazyLoaderCoreStateAtom =\n atom<LazyLoaderStateCore<any>>(DEFAULT_LOADER_CORE);\n\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nexport function resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\n/** The data array for a seeded first window: the rows in place, pre-sized to\n * the reported total (with `null` for the rows not yet loaded) so the scrollbar\n * and the counter are right immediately. */\nexport function seededRows<T>(seed: InitialDataChunk<T>): (T | null)[] {\n const rows = seed.rows ?? [];\n const size = Math.max(seed.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return data;\n}\n\n/** The loader's core state for a seeded first window — the same shape as after\n * a completed first fetch. `initialized` means the loader neither refetches the\n * seeded window nor shows an empty state. */\nexport function seededLoaderCore<T>(\n seed: InitialDataChunk<T>,\n): LazyLoaderStateCore<T> {\n return {\n ...DEFAULT_LOADER_CORE,\n initialized: true,\n totalCount: seed.totalCount ?? null,\n };\n}\n\n/** The identity of the row the current view starts after (`startAfter`), or\n * `null` for a view that starts at the top. Set at store creation so a server\n * render shows the \"Return to top\" link; the loader clears it on the first view\n * change. */\nexport const startAfterAtom = atom<string | number | null>(null);\n\n/** Scoped-store atoms that make a store start out seeded. The store's own\n * `data` is seeded alongside (see `DataSheetStoreWrapper`). Empty when there is\n * no seed. */\nexport function loaderSeedAtoms<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n startAfter: FetchDataOptions<T>[\"startAfter\"] = null,\n): AtomMap {\n const atoms: AtomMap = [];\n if (startAfter != null) {\n atoms.push([startAfterAtom, startAfter]);\n }\n const seed = resolveInitialData(initialData);\n if (seed != null) {\n atoms.push([lazyLoaderCoreStateAtom, seededLoaderCore(seed)]);\n }\n return atoms;\n}\n"],"names":[],"mappings":";AAqBO,MAAM,sBAAgD;AAAA,EAC3D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,UAAU;AACZ;AAEO,MAAM,0BACX,KAA+B,mBAAmB;AAK7C,SAAS,mBACd,aAC4B;AAC5B,MAAI,eAAe,KAAM,QAAO;AAChC,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,QAAI,YAAY,WAAW,EAAG,QAAO;AACrC,WAAO,EAAE,MAAM,YAAA;AAAA,EACjB;AACA,OAAK,YAAY,QAAQ,CAAA,GAAI,WAAW,EAAG,QAAO;AAClD,SAAO;AACT;AAKO,SAAS,WAAc,MAAyC;AACrE,QAAM,OAAO,KAAK,QAAQ,CAAA;AAC1B,QAAM,OAAO,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ,KAAK,MAAM;AACjE,QAAM,OAAqB,IAAI,MAAM,IAAI,EAAE,KAAK,IAAI;AACpD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,CAAC,IAAI,KAAK,CAAC;AACtD,SAAO;AACT;AAKO,SAAS,iBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa;AAAA,IACb,YAAY,KAAK,cAAc;AAAA,EAAA;AAEnC;AAMO,MAAM,iBAAiB,KAA6B,IAAI;AAKxD,SAAS,gBACd,aACA,aAAgD,MACvC;AACT,QAAM,QAAiB,CAAA;AACvB,MAAI,cAAc,MAAM;AACtB,UAAM,KAAK,CAAC,gBAAgB,UAAU,CAAC;AAAA,EACzC;AACA,QAAM,OAAO,mBAAmB,WAAW;AAC3C,MAAI,QAAQ,MAAM;AAChB,UAAM,KAAK,CAAC,yBAAyB,iBAAiB,IAAI,CAAC,CAAC;AAAA,EAC9D;AACA,SAAO;AACT;"}
|
|
@@ -23,7 +23,7 @@ function createLocalProvider(data, options = {}) {
|
|
|
23
23
|
const identity = options.identity ?? defaultLocalIdentity;
|
|
24
24
|
return {
|
|
25
25
|
identity,
|
|
26
|
-
async fetchData({ offset, limit, sorts, filters }) {
|
|
26
|
+
async fetchData({ offset, limit, sorts, filters, after }) {
|
|
27
27
|
let rows = data;
|
|
28
28
|
if (filters != null && filters.length > 0) {
|
|
29
29
|
rows = rows.filter(
|
|
@@ -35,6 +35,7 @@ function createLocalProvider(data, options = {}) {
|
|
|
35
35
|
if (sorts != null && sorts.length > 0) {
|
|
36
36
|
rows = [...rows].sort(compareRowsBySorts(sorts));
|
|
37
37
|
}
|
|
38
|
+
rows = rowsAfter(rows, after, identity);
|
|
38
39
|
return {
|
|
39
40
|
rows: rows.slice(offset, offset + limit),
|
|
40
41
|
totalCount: rows.length
|
|
@@ -45,6 +46,13 @@ function createLocalProvider(data, options = {}) {
|
|
|
45
46
|
}
|
|
46
47
|
};
|
|
47
48
|
}
|
|
49
|
+
function rowsAfter(rows, after, identity) {
|
|
50
|
+
if (after == null) return rows;
|
|
51
|
+
const key = String(after);
|
|
52
|
+
const index = rows.findIndex((row) => String(identity(row)) === key);
|
|
53
|
+
if (index < 0) return rows;
|
|
54
|
+
return rows.slice(index + 1);
|
|
55
|
+
}
|
|
48
56
|
const _syntheticRowIds = /* @__PURE__ */ new WeakMap();
|
|
49
57
|
let _syntheticRowCounter = 0;
|
|
50
58
|
function defaultLocalIdentity(row) {
|
|
@@ -110,4 +118,5 @@ exports.createLocalProvider = createLocalProvider;
|
|
|
110
118
|
exports.dataRefreshTokenAtom = dataRefreshTokenAtom;
|
|
111
119
|
exports.distinctValuesOf = distinctValuesOf;
|
|
112
120
|
exports.persistViaProvider = persistViaProvider;
|
|
121
|
+
exports.rowsAfter = rowsAfter;
|
|
113
122
|
//# sourceMappingURL=table-data.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-data.cjs","sources":["../../src/provider/table-data.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n /** The distinct values a column holds — the vocabulary a value picker offers,\n * so a filter can only be set to something that matches. Optional: a source\n * that can't answer it cheaply simply omits it, and pickers fall back to free\n * entry. See {@link useDistinctValues}. */\n distinctValues?(\n columnKey: string,\n options?: DistinctValuesOptions,\n ): Promise<DistinctValue[]>;\n}\n\n/** One value a column holds, with its frequency where the source reports it. */\nexport interface DistinctValue<V = any> {\n value: V;\n /** Rows carrying this value. Omitted when the source can't count cheaply. */\n count?: number;\n}\n\nexport interface DistinctValuesOptions {\n /** Aborts when the request is superseded (unmount, key change). */\n signal?: AbortSignal;\n /** Cap on how many values to return — a high-cardinality column shouldn't\n * become an unbounded fetch. */\n limit?: number;\n}\n\n/** Distinct values of an in-memory column, ordered by descending frequency then\n * value. Array cells are *not* flattened: the values of an array column are its\n * arrays, matching what a server-side `GROUP BY` would report. */\nexport function distinctValuesOf<T>(\n rows: T[],\n columnKey: string,\n options: DistinctValuesOptions = {},\n): DistinctValue[] {\n const counts = new Map<any, number>();\n for (const row of rows) {\n const value = (row as any)?.[columnKey];\n counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n const values = [...counts.entries()].map(([value, count]) => ({\n value,\n count,\n }));\n values.sort((a, b) => {\n if (b.count !== a.count) return b.count - a.count;\n return String(a.value).localeCompare(String(b.value));\n });\n if (options.limit != null) return values.slice(0, options.limit);\n return values;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n async distinctValues(columnKey, opts) {\n return distinctValuesOf(data, columnKey, opts);\n },\n };\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.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,E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AK,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,KAAU;AAAA,IAC3C,WAAW,SAAS;AAClB,aAAO,KAAK,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,KAAU;AAAA,IACzC;AAAA,EACF;AACA,MAAI,SAAS,SAAS,KAAK,SAAS,cAAc,MAAM;AACtD,UAAM,SAAS,WAAW,QAAQ;AAAA,EACpC;AACA,aAAW,OAAO,UAAU;AAC1B,QAAI,SAAS,aAAa,KAAM,OAAM,SAAS,UAAU,GAAG;AAAA,EAC9D;AACA,MAAI,OAAO,SAAS,KAAK,SAAS,YAAY,MAAM;AAClD,UAAM,SAAS,SAAS,MAAM;AAAA,EAChC;AACF;;;;;;"}
|
|
1
|
+
{"version":3,"file":"table-data.cjs","sources":["../../src/provider/table-data.ts"],"sourcesContent":["import { ColumnSort, TableElementStatus } from \"./types.ts\";\nimport { atom } from \"jotai\";\nimport { TableActionContext } from \"../actions\";\n\n/** The active view state (a filter's id / column / config), passed to a\n * `fetchChunk`. A server provider translates `columnKey` + `state` into a\n * query; a local (in-memory) provider applies `predicate` directly. Both come\n * from the same `TableFilter`, so one filter definition serves either target. */\nexport interface FetchDataFilter {\n id: string;\n columnKey?: string;\n state: any;\n /** Client-side row predicate (from the `TableFilter`). Server providers\n * ignore it and translate `columnKey` + `state` instead. */\n predicate?: (row: any, state: any) => boolean;\n}\n\n/** Parameters passed to a `fetchChunk` implementation for one window. */\nexport interface FetchDataParams {\n /** Row offset of the requested chunk (chunk-aligned). */\n offset: number;\n /** Maximum rows to return. */\n limit: number;\n /** Aborts when the request is superseded (view change / unmount). */\n signal: AbortSignal;\n /** Active sorts, in priority order. */\n sorts: ColumnSort[];\n /** Active filters (id + column + config). */\n filters: FetchDataFilter[];\n /** In scroll mode, the already-loaded row immediately before this chunk\n * (and its data-array index), or `null` at the start / in paged mode. Keyset\n * sources can page from this cursor (e.g. `WHERE key > cursor`) instead of a\n * slow `OFFSET`; offset-based sources can ignore it. */\n cursor?: { row: any; index: number } | null;\n /** Identity of the row the view is counted from: `offset` 0 is the first\n * row *after* it. Set while a view starts mid-list (see `startAfter` in\n * `FetchDataOptions`); absent or `null` when it starts at the top. Keyset\n * sources translate it to `WHERE key > after`; the local provider slices past\n * the row. `totalCount` then reports the rows after it. */\n after?: string | number | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n /** The distinct values a column holds — the vocabulary a value picker offers,\n * so a filter can only be set to something that matches. Optional: a source\n * that can't answer it cheaply simply omits it, and pickers fall back to free\n * entry. See {@link useDistinctValues}. */\n distinctValues?(\n columnKey: string,\n options?: DistinctValuesOptions,\n ): Promise<DistinctValue[]>;\n}\n\n/** One value a column holds, with its frequency where the source reports it. */\nexport interface DistinctValue<V = any> {\n value: V;\n /** Rows carrying this value. Omitted when the source can't count cheaply. */\n count?: number;\n}\n\nexport interface DistinctValuesOptions {\n /** Aborts when the request is superseded (unmount, key change). */\n signal?: AbortSignal;\n /** Cap on how many values to return — a high-cardinality column shouldn't\n * become an unbounded fetch. */\n limit?: number;\n}\n\n/** Distinct values of an in-memory column, ordered by descending frequency then\n * value. Array cells are *not* flattened: the values of an array column are its\n * arrays, matching what a server-side `GROUP BY` would report. */\nexport function distinctValuesOf<T>(\n rows: T[],\n columnKey: string,\n options: DistinctValuesOptions = {},\n): DistinctValue[] {\n const counts = new Map<any, number>();\n for (const row of rows) {\n const value = (row as any)?.[columnKey];\n counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n const values = [...counts.entries()].map(([value, count]) => ({\n value,\n count,\n }));\n values.sort((a, b) => {\n if (b.count !== a.count) return b.count - a.count;\n return String(a.value).localeCompare(String(b.value));\n });\n if (options.limit != null) return values.slice(0, options.limit);\n return values;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters, after }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n rows = rowsAfter(rows, after, identity);\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n async distinctValues(columnKey, opts) {\n return distinctValuesOf(data, columnKey, opts);\n },\n };\n}\n\n/** The rows past the one with identity `after` in the (filtered, sorted) view;\n * the whole view when `after` is absent or names no row. Identities are compared\n * as strings, since a cursor read from a URL arrives as one. */\nexport function rowsAfter<T>(\n rows: T[],\n after: string | number | null | undefined,\n identity: (row: T) => string | number | null | undefined,\n): T[] {\n if (after == null) return rows;\n const key = String(after);\n const index = rows.findIndex((row) => String(identity(row)) === key);\n if (index < 0) return rows;\n return rows.slice(index + 1);\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n"],"names":["atom","TableElementStatus"],"mappings":";;;;AAiGO,SAAS,iBACd,MACA,WACA,UAAiC,CAAA,GAChB;AACjB,QAAM,6BAAa,IAAA;AACnB,aAAW,OAAO,MAAM;AACtB,UAAM,QAAS,MAAc,SAAS;AACtC,WAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;AAAA,EAChD;AACA,QAAM,SAAS,CAAC,GAAG,OAAO,QAAA,CAAS,EAAE,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO;AAAA,IAC5D;AAAA,IACA;AAAA,EAAA,EACA;AACF,SAAO,KAAK,CAAC,GAAG,MAAM;AACpB,QAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,WAAO,OAAO,EAAE,KAAK,EAAE,cAAc,OAAO,EAAE,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,SAAS,SAAS;AACxD,UAAI,OAAO;AACX,UAAI,WAAW,QAAQ,QAAQ,SAAS,GAAG;AACzC,eAAO,KAAK;AAAA,UAAO,CAAC,QACl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AAA,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;;;;;;;"}
|
|
@@ -32,6 +32,12 @@ export interface FetchDataParams {
|
|
|
32
32
|
row: any;
|
|
33
33
|
index: number;
|
|
34
34
|
} | null;
|
|
35
|
+
/** Identity of the row the view is counted from: `offset` 0 is the first
|
|
36
|
+
* row *after* it. Set while a view starts mid-list (see `startAfter` in
|
|
37
|
+
* `FetchDataOptions`); absent or `null` when it starts at the top. Keyset
|
|
38
|
+
* sources translate it to `WHERE key > after`; the local provider slices past
|
|
39
|
+
* the row. `totalCount` then reports the rows after it. */
|
|
40
|
+
after?: string | number | null;
|
|
35
41
|
}
|
|
36
42
|
/** Result of a `fetchChunk` call. `totalCount` reports the source length when
|
|
37
43
|
* known (drives sparse-array pre-sizing and a proportional scrollbar); omit it
|
|
@@ -88,6 +94,10 @@ export declare function distinctValuesOf<T>(rows: T[], columnKey: string, option
|
|
|
88
94
|
export declare function createLocalProvider<T = any>(data: T[], options?: {
|
|
89
95
|
identity?: (row: T) => string | number;
|
|
90
96
|
}): TableDataProvider<T>;
|
|
97
|
+
/** The rows past the one with identity `after` in the (filtered, sorted) view;
|
|
98
|
+
* the whole view when `after` is absent or names no row. Identities are compared
|
|
99
|
+
* as strings, since a cursor read from a URL arrives as one. */
|
|
100
|
+
export declare function rowsAfter<T>(rows: T[], after: string | number | null | undefined, identity: (row: T) => string | number | null | undefined): T[];
|
|
91
101
|
/** Multi-key row comparator (priority order; nulls first when ascending),
|
|
92
102
|
* shared by the local provider and any other in-memory sort. */
|
|
93
103
|
export declare function compareRowsBySorts(sorts: ColumnSort[]): (a: any, b: any) => number;
|
|
@@ -21,7 +21,7 @@ function createLocalProvider(data, options = {}) {
|
|
|
21
21
|
const identity = options.identity ?? defaultLocalIdentity;
|
|
22
22
|
return {
|
|
23
23
|
identity,
|
|
24
|
-
async fetchData({ offset, limit, sorts, filters }) {
|
|
24
|
+
async fetchData({ offset, limit, sorts, filters, after }) {
|
|
25
25
|
let rows = data;
|
|
26
26
|
if (filters != null && filters.length > 0) {
|
|
27
27
|
rows = rows.filter(
|
|
@@ -33,6 +33,7 @@ function createLocalProvider(data, options = {}) {
|
|
|
33
33
|
if (sorts != null && sorts.length > 0) {
|
|
34
34
|
rows = [...rows].sort(compareRowsBySorts(sorts));
|
|
35
35
|
}
|
|
36
|
+
rows = rowsAfter(rows, after, identity);
|
|
36
37
|
return {
|
|
37
38
|
rows: rows.slice(offset, offset + limit),
|
|
38
39
|
totalCount: rows.length
|
|
@@ -43,6 +44,13 @@ function createLocalProvider(data, options = {}) {
|
|
|
43
44
|
}
|
|
44
45
|
};
|
|
45
46
|
}
|
|
47
|
+
function rowsAfter(rows, after, identity) {
|
|
48
|
+
if (after == null) return rows;
|
|
49
|
+
const key = String(after);
|
|
50
|
+
const index = rows.findIndex((row) => String(identity(row)) === key);
|
|
51
|
+
if (index < 0) return rows;
|
|
52
|
+
return rows.slice(index + 1);
|
|
53
|
+
}
|
|
46
54
|
const _syntheticRowIds = /* @__PURE__ */ new WeakMap();
|
|
47
55
|
let _syntheticRowCounter = 0;
|
|
48
56
|
function defaultLocalIdentity(row) {
|
|
@@ -108,6 +116,7 @@ export {
|
|
|
108
116
|
createLocalProvider,
|
|
109
117
|
dataRefreshTokenAtom,
|
|
110
118
|
distinctValuesOf,
|
|
111
|
-
persistViaProvider
|
|
119
|
+
persistViaProvider,
|
|
120
|
+
rowsAfter
|
|
112
121
|
};
|
|
113
122
|
//# 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 /** 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;A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AM;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 /** Identity of the row the view is counted from: `offset` 0 is the first\n * row *after* it. Set while a view starts mid-list (see `startAfter` in\n * `FetchDataOptions`); absent or `null` when it starts at the top. Keyset\n * sources translate it to `WHERE key > after`; the local provider slices past\n * the row. `totalCount` then reports the rows after it. */\n after?: string | number | null;\n}\n\n/** Result of a `fetchChunk` call. `totalCount` reports the source length when\n * known (drives sparse-array pre-sizing and a proportional scrollbar); omit it\n * for unknown-length sources (the array grows as chunks arrive). */\nexport interface FetchDataResult<T = any> {\n rows: T[];\n totalCount?: number | null;\n}\n\nexport type FetchData<T = any> = (\n params: FetchDataParams,\n) => Promise<FetchDataResult<T>>;\n\n/**\n * A table's data source, addressed uniformly whether it's an in-memory array or\n * a remote backend. `fetchChunk` returns a window with the active sorts/filters\n * already applied (in memory by the local provider, in SQL by a server one);\n * `identity` addresses a row for edits/mutations — stable across re-sorts,\n * unlike an array index. The mutation ops are present only for editable /\n * persisting sources. The in-memory case (`createLocalProvider`) is just the\n * degenerate implementation, so local and server tables share one path.\n */\nexport interface TableDataProvider<T = any> {\n fetchData(params: FetchDataParams): Promise<FetchDataResult<T>>;\n identity(row: T): string | number;\n saveRows?(rows: T[]): Promise<void>;\n deleteRows?(ids: Array<string | number>): Promise<void>;\n insertRow?(row: Partial<T>): Promise<void>;\n /** The distinct values a column holds — the vocabulary a value picker offers,\n * so a filter can only be set to something that matches. Optional: a source\n * that can't answer it cheaply simply omits it, and pickers fall back to free\n * entry. See {@link useDistinctValues}. */\n distinctValues?(\n columnKey: string,\n options?: DistinctValuesOptions,\n ): Promise<DistinctValue[]>;\n}\n\n/** One value a column holds, with its frequency where the source reports it. */\nexport interface DistinctValue<V = any> {\n value: V;\n /** Rows carrying this value. Omitted when the source can't count cheaply. */\n count?: number;\n}\n\nexport interface DistinctValuesOptions {\n /** Aborts when the request is superseded (unmount, key change). */\n signal?: AbortSignal;\n /** Cap on how many values to return — a high-cardinality column shouldn't\n * become an unbounded fetch. */\n limit?: number;\n}\n\n/** Distinct values of an in-memory column, ordered by descending frequency then\n * value. Array cells are *not* flattened: the values of an array column are its\n * arrays, matching what a server-side `GROUP BY` would report. */\nexport function distinctValuesOf<T>(\n rows: T[],\n columnKey: string,\n options: DistinctValuesOptions = {},\n): DistinctValue[] {\n const counts = new Map<any, number>();\n for (const row of rows) {\n const value = (row as any)?.[columnKey];\n counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n const values = [...counts.entries()].map(([value, count]) => ({\n value,\n count,\n }));\n values.sort((a, b) => {\n if (b.count !== a.count) return b.count - a.count;\n return String(a.value).localeCompare(String(b.value));\n });\n if (options.limit != null) return values.slice(0, options.limit);\n return values;\n}\n\n/**\n * The degenerate provider: an in-memory array. `fetchChunk` applies the active\n * filter predicates and sorts over the array and returns the requested slice\n * plus the (fully-known) total — the same view engine used for client-side\n * tables, expressed as a provider.\n */\nexport function createLocalProvider<T = any>(\n data: T[],\n options: { identity?: (row: T) => string | number } = {},\n): TableDataProvider<T> {\n const identity: any = options.identity ?? defaultLocalIdentity;\n\n return {\n identity,\n async fetchData({ offset, limit, sorts, filters, after }) {\n let rows = data;\n if (filters != null && filters.length > 0) {\n rows = rows.filter((row) =>\n filters.every((f) =>\n f.predicate != null ? f.predicate(row, f.state) : true,\n ),\n );\n }\n if (sorts != null && sorts.length > 0) {\n rows = [...rows].sort(compareRowsBySorts(sorts));\n }\n rows = rowsAfter(rows, after, identity);\n return {\n rows: rows.slice(offset, offset + limit),\n totalCount: rows.length,\n };\n },\n async distinctValues(columnKey, opts) {\n return distinctValuesOf(data, columnKey, opts);\n },\n };\n}\n\n/** The rows past the one with identity `after` in the (filtered, sorted) view;\n * the whole view when `after` is absent or names no row. Identities are compared\n * as strings, since a cursor read from a URL arrives as one. */\nexport function rowsAfter<T>(\n rows: T[],\n after: string | number | null | undefined,\n identity: (row: T) => string | number | null | undefined,\n): T[] {\n if (after == null) return rows;\n const key = String(after);\n const index = rows.findIndex((row) => String(identity(row)) === key);\n if (index < 0) return rows;\n return rows.slice(index + 1);\n}\n\n// Stable synthetic identity for in-memory rows lacking a natural `id`. Keyed by\n// object reference (a local data array keeps the same row objects across\n// re-sorts), so edits survive re-ordering even without an id field.\nconst _syntheticRowIds = new WeakMap<object, string>();\nlet _syntheticRowCounter = 0;\n\nfunction defaultLocalIdentity(row: any): string | number | undefined {\n if (row == null) return undefined;\n if (row.id != null) return row.id;\n if (typeof row !== \"object\") return row;\n let id = _syntheticRowIds.get(row);\n if (id == null) {\n id = `__row_${_syntheticRowCounter++}`;\n _syntheticRowIds.set(row, id);\n }\n return id;\n}\n\n/** Multi-key row comparator (priority order; nulls first when ascending),\n * shared by the local provider and any other in-memory sort. */\nexport function compareRowsBySorts(sorts: ColumnSort[]) {\n return (a: any, b: any): number => {\n for (const sort of sorts) {\n const av = a?.[sort.key];\n const bv = b?.[sort.key];\n if (av == null && bv == null) continue;\n if (av == null) return sort.ascending ? -1 : 1;\n if (bv == null) return sort.ascending ? 1 : -1;\n const cmp = av < bv ? -1 : av > bv ? 1 : 0;\n if (cmp !== 0) return sort.ascending ? cmp : -cmp;\n }\n return 0;\n };\n}\n\n/** Bump this to force the active chunk loader to reset and re-fetch from\n * scratch — e.g. after a mutation (save/delete) that invalidates loaded rows. */\nexport const dataRefreshTokenAtom = atom(0);\n\n/** Persist all pending changes through a data provider: added rows via\n * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`\n * (addressed by `provider.identity`). Used by the built-in Save action when an\n * explicit provider owns persistence. */\nexport async function persistViaProvider<T>(\n provider: TableDataProvider<T>,\n ctx: TableActionContext<T>,\n): Promise<void> {\n const base = (ctx.data ?? []) as any[];\n const updates = (ctx.updatedData ?? []) as any[];\n const status = (ctx.rowStatus ?? []) as any[];\n const n = Math.max(base.length, updates.length, status.length);\n const toSave: T[] = [];\n const toInsert: T[] = [];\n const toDelete: Array<string | number> = [];\n for (let i = 0; i < n; i++) {\n if (status[i] === TableElementStatus.DELETED) {\n const id = provider.identity(base[i]);\n if (id != null) toDelete.push(id);\n continue;\n }\n const upd = updates[i];\n const hasEdit =\n upd != null && typeof upd === \"object\" && Object.keys(upd).length > 0;\n if (status[i] === TableElementStatus.ADDED) {\n toInsert.push({ ...base[i], ...upd } as T);\n } else if (hasEdit) {\n toSave.push({ ...base[i], ...upd } as T);\n }\n }\n if (toDelete.length > 0 && provider.deleteRows != null) {\n await provider.deleteRows(toDelete);\n }\n for (const row of toInsert) {\n if (provider.insertRow != null) await provider.insertRow(row);\n }\n if (toSave.length > 0 && provider.saveRows != null) {\n await provider.saveRows(toSave);\n }\n}\n"],"names":[],"mappings":";;AAiGO,SAAS,iBACd,MACA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AW,IAAI,eAAe,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\n\n/** A single column sort entry for client-side sorting.\n * Defined here (rather than in actions/types) to avoid circular imports. */\nexport interface ColumnSort {\n key: string;\n ascending: boolean;\n}\n\n/** Direction of keyboard navigation between cells. */\nexport type NavDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/**\n * A structured, revertible description of a user edit. Emitted via the\n * `onEdit` hook so a consumer can capture edits as operations (and, with the\n * controlled-overlay API, own the edited state) instead of diffing\n * `updatedData`. This is the write half of the data-sheet's read/write\n * contract — the mirror of how data flows in.\n */\nexport type EditEvent<T = any> =\n | { type: \"setCells\"; cells: CellEdit[] }\n | { type: \"deleteRows\"; rowIndices: number[] }\n | { type: \"restoreRows\"; rowIndices: number[] }\n | { type: \"addRow\"; rowIndex: number; value: Partial<T> }\n | { type: \"resetChanges\" };\n\nexport enum TableElementStatus {\n DELETED = \"deleted\",\n ADDED = \"added\",\n}\n\n/** A row's status value. The built-in `TableElementStatus` members\n * (`\"deleted\"` / `\"added\"`) plus any consumer-defined status string (e.g.\n * `\"omitted\"`). The `(string & {})` keeps autocomplete for the enum members\n * while still accepting arbitrary strings. */\nexport type RowStatusValue = TableElementStatus | (string & {});\n\n/** Presentation for a row status: applied to the row's cells and its header\n * cell. Keyed by status value in `rowStatusStyles`. The library ships a\n * default for `\"deleted\"` (dimmed + struck through, danger intent); consumers\n * merge in styles for their own statuses (and may override the defaults). */\nexport interface RowStatusStyle {\n /** Style merged onto each cell in a row with this status. */\n cellStyle?: import(\"react\").CSSProperties;\n /** Style applied to the row's header cell. */\n headerStyle?: import(\"react\").CSSProperties;\n /** Blueprint intent applied to the row's cells (precedence: validation >\n * this > edited-green). */\n intent?: import(\"@blueprintjs/core\").Intent;\n}\n\nexport type RowStatusStyles = Record<string, RowStatusStyle>;\n\n/** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged\n * over this, so `\"deleted\"` keeps its look unless explicitly overridden. */\nexport const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles = {\n [TableElementStatus.DELETED]: {\n cellStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n headerStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n intent: \"danger\",\n },\n};\n\n/** Context passed to a custom `rowHeaderRenderer`, so it can label and style\n * the row header from the row's data and status (group-key labels, an\n * omit indicator, etc.). Return a node to use as the header's name, or a\n * nullish value to fall back to the default (1-based row number). */\nexport interface RowHeaderRenderContext<T = any> {\n /** Data-row index (stable under sort/filter). */\n rowIndex: number;\n /** Visible (display) row index. */\n visibleIndex: number;\n /** The row's data (base, overlaid with edits if present). */\n row: T | undefined;\n /** The row's status, if any. */\n status: RowStatusValue | undefined;\n /** Convenience: `status === TableElementStatus.DELETED`. */\n isDeleted: boolean;\n /** The default label (`\"${rowIndex + 1}\"`). */\n defaultLabel: string;\n}\n\n/** Property key holding a stable synthetic id on rows added in-table. Added\n * rows aren't in the data provider, so they need their own identity to survive\n * a provider re-fetch; it's carried on the row and preserved through edits. */\nexport const DS_ROW_ID = \"__dsRowId\";\n\n/** Proxy stored during a copy operation, enabling backend-mediated paste\n * for lazy-loaded tables where not all data is available locally. */\nexport interface ClipboardProxy {\n cardinality: RegionCardinality;\n /** Source row indices (for row/cell copies) */\n rowIndices?: number[];\n /** Source column keys (for column/cell copies) */\n columnKeys?: string[];\n /** The plain text written to the clipboard, used to verify the proxy\n * is still valid on paste (i.e., clipboard hasn't been overwritten). */\n text: string;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n /**\n * Set of row indices that have been added to the table,\n * but not yet committed to the underlying data array.\n *\n * This is used to track which rows should be reverted when\n * a \"reset\" action is performed.\n */\n rowStatus: (RowStatusValue | undefined)[];\n /** Presentation per row-status value (merged: defaults + the\n * `rowStatusStyles` prop). Read by the cell renderer and row-header renderer\n * to style rows by status. */\n rowStatusStyles: RowStatusStyles;\n // Sparse data structure for updated data\n updatedData: (T | null | undefined)[];\n data: T[];\n initialized: boolean;\n columnWidthsIndex: Map<string, number>;\n /** Active column/table filters. Keys are filter IDs, values carry the\n * filter definition and its current configuration state. */\n activeFilters: Map<string, { filter: any; state: any }>;\n /** Clipboard proxy from the last copy operation */\n clipboardProxy: ClipboardProxy | null;\n /** Visible row indices when filters are active. `null` means show all rows. */\n filteredRowIndices: number[] | null;\n /** Active column sort entries for client-side sorting. */\n columnSorts: ColumnSort[];\n /** Whether selecting a cell automatically activates its surface (opens an\n * editor/detail panel and, for editors, focuses it). `\"manual\"` opens only\n * on click. */\n cellInteraction: \"auto\" | \"manual\";\n /** Runtime override of `cellInteraction`: while `false`, auto-activation is\n * suppressed (set by pressing Escape, re-armed by clicking a cell) so the\n * keyboard prioritizes navigation. */\n autoActivateArmed: boolean;\n /** Direction of the last keyboard navigation, used to place an editor's\n * cursor on the side the user is travelling toward. `null` after a click. */\n lastNavDirection: NavDirection | null;\n /** The table's focusable holder element; editors return focus here when the\n * cursor leaves them so arrow-key navigation resumes. */\n tableElement: HTMLElement | null;\n /** Whether the focused cell's surface (editor or detail panel) is open.\n * Owned by the store — not per-popover — so navigation, clicks, and the\n * Escape handler all agree on it. */\n cellSurfaceOpen: boolean;\n /** Optional observer called for every user edit as a structured\n * `EditEvent`, in addition to the built-in `updatedData` overlay. Lets a\n * consumer capture edits as revertible operations. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Row identity for the edit overlay — stable across a provider re-sort,\n * unlike an array index. Defaults to `(row) => row?.id`; a data provider\n * supplies its own (e.g. a PostgREST identity key). Used to re-attach edits\n * when the loader replaces `data` with a re-ordered window. */\n identity: (row: any) => string | number | null | undefined;\n /** Edits/statuses held by identity for rows not currently loaded (server\n * sources), re-attached when their row next arrives. */\n pendingOverlayById: Map<\n string | number,\n { edit?: any; status?: TableElementStatus }\n >;\n /** True when the consumer controls the `updatedData`/`rowStatus` overlay; the\n * loader-boundary identity remap is skipped (the consumer owns it). */\n controlledOverlay: boolean;\n /** Whether row deletion is available. Set from the data provider: an explicit\n * `provider` without `deleteRows` disables deletion entirely (the delete\n * affordance greys out and the delete key is a no-op). Defaults to `true`. */\n canDeleteRows: boolean;\n /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<T>;\nexport type StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStoreMain<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(event: MouseEvent): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onSelectionEdited(value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n onColumnWidthChanged(columnIndex: number, newWidth: number): void;\n moveFocusedCell(direction: NavDirection): void;\n /** Suppress auto-activation until the next click (Escape enters nav mode). */\n suppressAutoActivate(): void;\n /** Re-arm auto-activation (a click re-enables auto-focus). */\n armAutoActivate(): void;\n /** Open the focused cell's surface (editor or detail panel). */\n openCellSurface(): void;\n /** Close the focused cell's surface. When `suppress` is true (the default,\n * as for Escape), auto mode also enters navigation mode (auto-activation is\n * suppressed until the next click). A click-dismiss passes `suppress: false`\n * so it just closes without changing the global mode. */\n closeCellSurface(opts?: { suppress?: boolean }): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n /** Activate or update a column/table filter.\n * Filter is any object satisfying `TableFilter` from the actions module. */\n setFilter(filterId: string, filter: any, filterState: any): void;\n /** Remove a filter by ID */\n removeFilter(filterId: string): void;\n /** Remove all active filters */\n clearFilters(): void;\n /** Set or clear a column sort. Pass `null` for ascending to clear. */\n setColumnSort(key: string, ascending: boolean | null): void;\n /** Remove all active column sorts */\n clearColumnSorts(): void;\n /** Store a clipboard proxy for potential backend-mediated paste */\n setClipboardProxy(proxy: ClipboardProxy | null): void;\n //initialize(props: Partial<DataSheetStoreMain<T>>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":";;AAmCO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,SAAA,IAAU;AACVA,sBAAA,OAAA,IAAQ;AAFE,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AA6BL,MAAM,4BAA6C;AAAA,EACxD;AAAA,IAAC;AAAA;AAAA,KAA6B;AAAA,IAC5B,WAAW,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC3C,aAAa,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC7C,QAAQ;AAAA,EAAA;AAEZ;AAwBO,MAAM,YAAY;;;;"}
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\n\n/** A single column sort entry for client-side sorting.\n * Defined here (rather than in actions/types) to avoid circular imports. */\nexport interface ColumnSort {\n key: string;\n ascending: boolean;\n}\n\n/** Direction of keyboard navigation between cells. */\nexport type NavDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/**\n * A structured, revertible description of a user edit. Emitted via the\n * `onEdit` hook so a consumer can capture edits as operations (and, with the\n * controlled-overlay API, own the edited state) instead of diffing\n * `updatedData`. This is the write half of the data-sheet's read/write\n * contract — the mirror of how data flows in.\n */\nexport type EditEvent<T = any> =\n | { type: \"setCells\"; cells: CellEdit[] }\n | { type: \"deleteRows\"; rowIndices: number[] }\n | { type: \"restoreRows\"; rowIndices: number[] }\n | { type: \"addRow\"; rowIndex: number; value: Partial<T> }\n | { type: \"resetChanges\" };\n\nexport enum TableElementStatus {\n DELETED = \"deleted\",\n ADDED = \"added\",\n}\n\n/** A row's status value. The built-in `TableElementStatus` members\n * (`\"deleted\"` / `\"added\"`) plus any consumer-defined status string (e.g.\n * `\"omitted\"`). The `(string & {})` keeps autocomplete for the enum members\n * while still accepting arbitrary strings. */\nexport type RowStatusValue = TableElementStatus | (string & {});\n\n/** Presentation for a row status: applied to the row's cells and its header\n * cell. Keyed by status value in `rowStatusStyles`. The library ships a\n * default for `\"deleted\"` (dimmed + struck through, danger intent); consumers\n * merge in styles for their own statuses (and may override the defaults). */\nexport interface RowStatusStyle {\n /** Style merged onto each cell in a row with this status. */\n cellStyle?: import(\"react\").CSSProperties;\n /** Style applied to the row's header cell. */\n headerStyle?: import(\"react\").CSSProperties;\n /** Blueprint intent applied to the row's cells (precedence: validation >\n * this > edited-green). */\n intent?: import(\"@blueprintjs/core\").Intent;\n}\n\nexport type RowStatusStyles = Record<string, RowStatusStyle>;\n\n/** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged\n * over this, so `\"deleted\"` keeps its look unless explicitly overridden. */\nexport const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles = {\n [TableElementStatus.DELETED]: {\n cellStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n headerStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n intent: \"danger\",\n },\n};\n\n/** Context passed to a custom `rowHeaderRenderer`, so it can label and style\n * the row header from the row's data and status (group-key labels, an\n * omit indicator, etc.). Return a node to use as the header's name, or a\n * nullish value to fall back to the default (1-based row number). */\nexport interface RowHeaderRenderContext<T = any> {\n /** Data-row index (stable under sort/filter). */\n rowIndex: number;\n /** Visible (display) row index. */\n visibleIndex: number;\n /** The row's data (base, overlaid with edits if present). */\n row: T | undefined;\n /** The row's status, if any. */\n status: RowStatusValue | undefined;\n /** Convenience: `status === TableElementStatus.DELETED`. */\n isDeleted: boolean;\n /** The default label (`\"${rowIndex + 1}\"`). */\n defaultLabel: string;\n}\n\n/** Property key holding a stable synthetic id on rows added in-table. Added\n * rows aren't in the data provider, so they need their own identity to survive\n * a provider re-fetch; it's carried on the row and preserved through edits. */\nexport const DS_ROW_ID = \"__dsRowId\";\n\n/** Proxy stored during a copy operation, enabling backend-mediated paste\n * for lazy-loaded tables where not all data is available locally. */\nexport interface ClipboardProxy {\n cardinality: RegionCardinality;\n /** Source row indices (for row/cell copies) */\n rowIndices?: number[];\n /** Source column keys (for column/cell copies) */\n columnKeys?: string[];\n /** The plain text written to the clipboard, used to verify the proxy\n * is still valid on paste (i.e., clipboard hasn't been overwritten). */\n text: string;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n /**\n * Set of row indices that have been added to the table,\n * but not yet committed to the underlying data array.\n *\n * This is used to track which rows should be reverted when\n * a \"reset\" action is performed.\n */\n rowStatus: (RowStatusValue | undefined)[];\n /** Presentation per row-status value (merged: defaults + the\n * `rowStatusStyles` prop). Read by the cell renderer and row-header renderer\n * to style rows by status. */\n rowStatusStyles: RowStatusStyles;\n // Sparse data structure for updated data\n updatedData: (T | null | undefined)[];\n data: T[];\n initialized: boolean;\n columnWidthsIndex: Map<string, number>;\n /** Active column/table filters. Keys are filter IDs, values carry the\n * filter definition and its current configuration state. */\n activeFilters: Map<string, { filter: any; state: any }>;\n /** Clipboard proxy from the last copy operation */\n clipboardProxy: ClipboardProxy | null;\n /** Visible row indices when filters are active. `null` means show all rows. */\n filteredRowIndices: number[] | null;\n /** Active column sort entries for client-side sorting. */\n columnSorts: ColumnSort[];\n /** Whether selecting a cell automatically activates its surface (opens an\n * editor/detail panel and, for editors, focuses it). `\"manual\"` opens only\n * on click. */\n cellInteraction: \"auto\" | \"manual\" | \"second-click\";\n /** Runtime override of `cellInteraction`: while `false`, auto-activation is\n * suppressed (set by pressing Escape, re-armed by clicking a cell) so the\n * keyboard prioritizes navigation. */\n autoActivateArmed: boolean;\n /** Direction of the last keyboard navigation, used to place an editor's\n * cursor on the side the user is travelling toward. `null` after a click. */\n lastNavDirection: NavDirection | null;\n /** The table's focusable holder element; editors return focus here when the\n * cursor leaves them so arrow-key navigation resumes. */\n tableElement: HTMLElement | null;\n /** Whether the focused cell's surface (editor or detail panel) is open.\n * Owned by the store — not per-popover — so navigation, clicks, and the\n * Escape handler all agree on it. */\n cellSurfaceOpen: boolean;\n /** Optional observer called for every user edit as a structured\n * `EditEvent`, in addition to the built-in `updatedData` overlay. Lets a\n * consumer capture edits as revertible operations. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Row identity for the edit overlay — stable across a provider re-sort,\n * unlike an array index. Defaults to `(row) => row?.id`; a data provider\n * supplies its own (e.g. a PostgREST identity key). Used to re-attach edits\n * when the loader replaces `data` with a re-ordered window. */\n identity: (row: any) => string | number | null | undefined;\n /** Edits/statuses held by identity for rows not currently loaded (server\n * sources), re-attached when their row next arrives. */\n pendingOverlayById: Map<\n string | number,\n { edit?: any; status?: TableElementStatus }\n >;\n /** True when the consumer controls the `updatedData`/`rowStatus` overlay; the\n * loader-boundary identity remap is skipped (the consumer owns it). */\n controlledOverlay: boolean;\n /** Whether row deletion is available. Set from the data provider: an explicit\n * `provider` without `deleteRows` disables deletion entirely (the delete\n * affordance greys out and the delete key is a no-op). Defaults to `true`. */\n canDeleteRows: boolean;\n /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<T>;\nexport type StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStoreMain<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(event: MouseEvent): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onSelectionEdited(value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n onColumnWidthChanged(columnIndex: number, newWidth: number): void;\n moveFocusedCell(direction: NavDirection): void;\n /** Suppress auto-activation until the next click (Escape enters nav mode). */\n suppressAutoActivate(): void;\n /** Re-arm auto-activation (a click re-enables auto-focus). */\n armAutoActivate(): void;\n /** Open the focused cell's surface (editor or detail panel). */\n openCellSurface(): void;\n /** Close the focused cell's surface. When `suppress` is true (the default,\n * as for Escape), auto mode also enters navigation mode (auto-activation is\n * suppressed until the next click). A click-dismiss passes `suppress: false`\n * so it just closes without changing the global mode. */\n closeCellSurface(opts?: { suppress?: boolean }): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n /** Activate or update a column/table filter.\n * Filter is any object satisfying `TableFilter` from the actions module. */\n setFilter(filterId: string, filter: any, filterState: any): void;\n /** Remove a filter by ID */\n removeFilter(filterId: string): void;\n /** Remove all active filters */\n clearFilters(): void;\n /** Set or clear a column sort. Pass `null` for ascending to clear. */\n setColumnSort(key: string, ascending: boolean | null): void;\n /** Remove all active column sorts */\n clearColumnSorts(): void;\n /** Store a clipboard proxy for potential backend-mediated paste */\n setClipboardProxy(proxy: ClipboardProxy | null): void;\n //initialize(props: Partial<DataSheetStoreMain<T>>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n /** The row the view starts after (see `FetchDataOptions`). Seeded into the\n * store at creation alongside `initialData`. */\n startAfter?: FetchDataOptions<T>[\"startAfter\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":";;AAmCO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,SAAA,IAAU;AACVA,sBAAA,OAAA,IAAQ;AAFE,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AA6BL,MAAM,4BAA6C;AAAA,EACxD;AAAA,IAAC;AAAA;AAAA,KAA6B;AAAA,IAC5B,WAAW,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC3C,aAAa,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC7C,QAAQ;AAAA,EAAA;AAEZ;AAwBO,MAAM,YAAY;;;;"}
|
package/dist/provider/types.d.ts
CHANGED
|
@@ -136,7 +136,7 @@ export interface DataSheetState<T> {
|
|
|
136
136
|
/** Whether selecting a cell automatically activates its surface (opens an
|
|
137
137
|
* editor/detail panel and, for editors, focuses it). `"manual"` opens only
|
|
138
138
|
* on click. */
|
|
139
|
-
cellInteraction: "auto" | "manual";
|
|
139
|
+
cellInteraction: "auto" | "manual" | "second-click";
|
|
140
140
|
/** Runtime override of `cellInteraction`: while `false`, auto-activation is
|
|
141
141
|
* suppressed (set by pressing Escape, re-armed by clicking a cell) so the
|
|
142
142
|
* keyboard prioritizes navigation. */
|
|
@@ -240,6 +240,9 @@ export type DataSheetProviderProps<T> = DataViewCoreProps<T> & {
|
|
|
240
240
|
* The provider creates the store seeded with it, so the rows are in the very
|
|
241
241
|
* first render — a server render included. */
|
|
242
242
|
initialData?: FetchDataOptions<T>["initialData"];
|
|
243
|
+
/** The row the view starts after (see `FetchDataOptions`). Seeded into the
|
|
244
|
+
* store at creation alongside `initialData`. */
|
|
245
|
+
startAfter?: FetchDataOptions<T>["startAfter"];
|
|
243
246
|
viewType?: DataViewRendererType;
|
|
244
247
|
children?: React.ReactNode;
|
|
245
248
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\n\n/** A single column sort entry for client-side sorting.\n * Defined here (rather than in actions/types) to avoid circular imports. */\nexport interface ColumnSort {\n key: string;\n ascending: boolean;\n}\n\n/** Direction of keyboard navigation between cells. */\nexport type NavDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/**\n * A structured, revertible description of a user edit. Emitted via the\n * `onEdit` hook so a consumer can capture edits as operations (and, with the\n * controlled-overlay API, own the edited state) instead of diffing\n * `updatedData`. This is the write half of the data-sheet's read/write\n * contract — the mirror of how data flows in.\n */\nexport type EditEvent<T = any> =\n | { type: \"setCells\"; cells: CellEdit[] }\n | { type: \"deleteRows\"; rowIndices: number[] }\n | { type: \"restoreRows\"; rowIndices: number[] }\n | { type: \"addRow\"; rowIndex: number; value: Partial<T> }\n | { type: \"resetChanges\" };\n\nexport enum TableElementStatus {\n DELETED = \"deleted\",\n ADDED = \"added\",\n}\n\n/** A row's status value. The built-in `TableElementStatus` members\n * (`\"deleted\"` / `\"added\"`) plus any consumer-defined status string (e.g.\n * `\"omitted\"`). The `(string & {})` keeps autocomplete for the enum members\n * while still accepting arbitrary strings. */\nexport type RowStatusValue = TableElementStatus | (string & {});\n\n/** Presentation for a row status: applied to the row's cells and its header\n * cell. Keyed by status value in `rowStatusStyles`. The library ships a\n * default for `\"deleted\"` (dimmed + struck through, danger intent); consumers\n * merge in styles for their own statuses (and may override the defaults). */\nexport interface RowStatusStyle {\n /** Style merged onto each cell in a row with this status. */\n cellStyle?: import(\"react\").CSSProperties;\n /** Style applied to the row's header cell. */\n headerStyle?: import(\"react\").CSSProperties;\n /** Blueprint intent applied to the row's cells (precedence: validation >\n * this > edited-green). */\n intent?: import(\"@blueprintjs/core\").Intent;\n}\n\nexport type RowStatusStyles = Record<string, RowStatusStyle>;\n\n/** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged\n * over this, so `\"deleted\"` keeps its look unless explicitly overridden. */\nexport const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles = {\n [TableElementStatus.DELETED]: {\n cellStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n headerStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n intent: \"danger\",\n },\n};\n\n/** Context passed to a custom `rowHeaderRenderer`, so it can label and style\n * the row header from the row's data and status (group-key labels, an\n * omit indicator, etc.). Return a node to use as the header's name, or a\n * nullish value to fall back to the default (1-based row number). */\nexport interface RowHeaderRenderContext<T = any> {\n /** Data-row index (stable under sort/filter). */\n rowIndex: number;\n /** Visible (display) row index. */\n visibleIndex: number;\n /** The row's data (base, overlaid with edits if present). */\n row: T | undefined;\n /** The row's status, if any. */\n status: RowStatusValue | undefined;\n /** Convenience: `status === TableElementStatus.DELETED`. */\n isDeleted: boolean;\n /** The default label (`\"${rowIndex + 1}\"`). */\n defaultLabel: string;\n}\n\n/** Property key holding a stable synthetic id on rows added in-table. Added\n * rows aren't in the data provider, so they need their own identity to survive\n * a provider re-fetch; it's carried on the row and preserved through edits. */\nexport const DS_ROW_ID = \"__dsRowId\";\n\n/** Proxy stored during a copy operation, enabling backend-mediated paste\n * for lazy-loaded tables where not all data is available locally. */\nexport interface ClipboardProxy {\n cardinality: RegionCardinality;\n /** Source row indices (for row/cell copies) */\n rowIndices?: number[];\n /** Source column keys (for column/cell copies) */\n columnKeys?: string[];\n /** The plain text written to the clipboard, used to verify the proxy\n * is still valid on paste (i.e., clipboard hasn't been overwritten). */\n text: string;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n /**\n * Set of row indices that have been added to the table,\n * but not yet committed to the underlying data array.\n *\n * This is used to track which rows should be reverted when\n * a \"reset\" action is performed.\n */\n rowStatus: (RowStatusValue | undefined)[];\n /** Presentation per row-status value (merged: defaults + the\n * `rowStatusStyles` prop). Read by the cell renderer and row-header renderer\n * to style rows by status. */\n rowStatusStyles: RowStatusStyles;\n // Sparse data structure for updated data\n updatedData: (T | null | undefined)[];\n data: T[];\n initialized: boolean;\n columnWidthsIndex: Map<string, number>;\n /** Active column/table filters. Keys are filter IDs, values carry the\n * filter definition and its current configuration state. */\n activeFilters: Map<string, { filter: any; state: any }>;\n /** Clipboard proxy from the last copy operation */\n clipboardProxy: ClipboardProxy | null;\n /** Visible row indices when filters are active. `null` means show all rows. */\n filteredRowIndices: number[] | null;\n /** Active column sort entries for client-side sorting. */\n columnSorts: ColumnSort[];\n /** Whether selecting a cell automatically activates its surface (opens an\n * editor/detail panel and, for editors, focuses it). `\"manual\"` opens only\n * on click. */\n cellInteraction: \"auto\" | \"manual\";\n /** Runtime override of `cellInteraction`: while `false`, auto-activation is\n * suppressed (set by pressing Escape, re-armed by clicking a cell) so the\n * keyboard prioritizes navigation. */\n autoActivateArmed: boolean;\n /** Direction of the last keyboard navigation, used to place an editor's\n * cursor on the side the user is travelling toward. `null` after a click. */\n lastNavDirection: NavDirection | null;\n /** The table's focusable holder element; editors return focus here when the\n * cursor leaves them so arrow-key navigation resumes. */\n tableElement: HTMLElement | null;\n /** Whether the focused cell's surface (editor or detail panel) is open.\n * Owned by the store — not per-popover — so navigation, clicks, and the\n * Escape handler all agree on it. */\n cellSurfaceOpen: boolean;\n /** Optional observer called for every user edit as a structured\n * `EditEvent`, in addition to the built-in `updatedData` overlay. Lets a\n * consumer capture edits as revertible operations. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Row identity for the edit overlay — stable across a provider re-sort,\n * unlike an array index. Defaults to `(row) => row?.id`; a data provider\n * supplies its own (e.g. a PostgREST identity key). Used to re-attach edits\n * when the loader replaces `data` with a re-ordered window. */\n identity: (row: any) => string | number | null | undefined;\n /** Edits/statuses held by identity for rows not currently loaded (server\n * sources), re-attached when their row next arrives. */\n pendingOverlayById: Map<\n string | number,\n { edit?: any; status?: TableElementStatus }\n >;\n /** True when the consumer controls the `updatedData`/`rowStatus` overlay; the\n * loader-boundary identity remap is skipped (the consumer owns it). */\n controlledOverlay: boolean;\n /** Whether row deletion is available. Set from the data provider: an explicit\n * `provider` without `deleteRows` disables deletion entirely (the delete\n * affordance greys out and the delete key is a no-op). Defaults to `true`. */\n canDeleteRows: boolean;\n /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<T>;\nexport type StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStoreMain<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(event: MouseEvent): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onSelectionEdited(value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n onColumnWidthChanged(columnIndex: number, newWidth: number): void;\n moveFocusedCell(direction: NavDirection): void;\n /** Suppress auto-activation until the next click (Escape enters nav mode). */\n suppressAutoActivate(): void;\n /** Re-arm auto-activation (a click re-enables auto-focus). */\n armAutoActivate(): void;\n /** Open the focused cell's surface (editor or detail panel). */\n openCellSurface(): void;\n /** Close the focused cell's surface. When `suppress` is true (the default,\n * as for Escape), auto mode also enters navigation mode (auto-activation is\n * suppressed until the next click). A click-dismiss passes `suppress: false`\n * so it just closes without changing the global mode. */\n closeCellSurface(opts?: { suppress?: boolean }): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n /** Activate or update a column/table filter.\n * Filter is any object satisfying `TableFilter` from the actions module. */\n setFilter(filterId: string, filter: any, filterState: any): void;\n /** Remove a filter by ID */\n removeFilter(filterId: string): void;\n /** Remove all active filters */\n clearFilters(): void;\n /** Set or clear a column sort. Pass `null` for ascending to clear. */\n setColumnSort(key: string, ascending: boolean | null): void;\n /** Remove all active column sorts */\n clearColumnSorts(): void;\n /** Store a clipboard proxy for potential backend-mediated paste */\n setClipboardProxy(proxy: ClipboardProxy | null): void;\n //initialize(props: Partial<DataSheetStoreMain<T>>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":"AAmCO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,SAAA,IAAU;AACVA,sBAAA,OAAA,IAAQ;AAFE,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AA6BL,MAAM,4BAA6C;AAAA,EACxD;AAAA,IAAC;AAAA;AAAA,KAA6B;AAAA,IAC5B,WAAW,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC3C,aAAa,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC7C,QAAQ;AAAA,EAAA;AAEZ;AAwBO,MAAM,YAAY;"}
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../src/provider/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./column-spec\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport { DataViewCoreProps, FetchDataOptions } from \"../types\";\nimport { DataViewRendererType } from \"./interactions.ts\";\n\n/** A single column sort entry for client-side sorting.\n * Defined here (rather than in actions/types) to avoid circular imports. */\nexport interface ColumnSort {\n key: string;\n ascending: boolean;\n}\n\n/** Direction of keyboard navigation between cells. */\nexport type NavDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/**\n * A structured, revertible description of a user edit. Emitted via the\n * `onEdit` hook so a consumer can capture edits as operations (and, with the\n * controlled-overlay API, own the edited state) instead of diffing\n * `updatedData`. This is the write half of the data-sheet's read/write\n * contract — the mirror of how data flows in.\n */\nexport type EditEvent<T = any> =\n | { type: \"setCells\"; cells: CellEdit[] }\n | { type: \"deleteRows\"; rowIndices: number[] }\n | { type: \"restoreRows\"; rowIndices: number[] }\n | { type: \"addRow\"; rowIndex: number; value: Partial<T> }\n | { type: \"resetChanges\" };\n\nexport enum TableElementStatus {\n DELETED = \"deleted\",\n ADDED = \"added\",\n}\n\n/** A row's status value. The built-in `TableElementStatus` members\n * (`\"deleted\"` / `\"added\"`) plus any consumer-defined status string (e.g.\n * `\"omitted\"`). The `(string & {})` keeps autocomplete for the enum members\n * while still accepting arbitrary strings. */\nexport type RowStatusValue = TableElementStatus | (string & {});\n\n/** Presentation for a row status: applied to the row's cells and its header\n * cell. Keyed by status value in `rowStatusStyles`. The library ships a\n * default for `\"deleted\"` (dimmed + struck through, danger intent); consumers\n * merge in styles for their own statuses (and may override the defaults). */\nexport interface RowStatusStyle {\n /** Style merged onto each cell in a row with this status. */\n cellStyle?: import(\"react\").CSSProperties;\n /** Style applied to the row's header cell. */\n headerStyle?: import(\"react\").CSSProperties;\n /** Blueprint intent applied to the row's cells (precedence: validation >\n * this > edited-green). */\n intent?: import(\"@blueprintjs/core\").Intent;\n}\n\nexport type RowStatusStyles = Record<string, RowStatusStyle>;\n\n/** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged\n * over this, so `\"deleted\"` keeps its look unless explicitly overridden. */\nexport const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles = {\n [TableElementStatus.DELETED]: {\n cellStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n headerStyle: { opacity: 0.5, textDecoration: \"line-through\" },\n intent: \"danger\",\n },\n};\n\n/** Context passed to a custom `rowHeaderRenderer`, so it can label and style\n * the row header from the row's data and status (group-key labels, an\n * omit indicator, etc.). Return a node to use as the header's name, or a\n * nullish value to fall back to the default (1-based row number). */\nexport interface RowHeaderRenderContext<T = any> {\n /** Data-row index (stable under sort/filter). */\n rowIndex: number;\n /** Visible (display) row index. */\n visibleIndex: number;\n /** The row's data (base, overlaid with edits if present). */\n row: T | undefined;\n /** The row's status, if any. */\n status: RowStatusValue | undefined;\n /** Convenience: `status === TableElementStatus.DELETED`. */\n isDeleted: boolean;\n /** The default label (`\"${rowIndex + 1}\"`). */\n defaultLabel: string;\n}\n\n/** Property key holding a stable synthetic id on rows added in-table. Added\n * rows aren't in the data provider, so they need their own identity to survive\n * a provider re-fetch; it's carried on the row and preserved through edits. */\nexport const DS_ROW_ID = \"__dsRowId\";\n\n/** Proxy stored during a copy operation, enabling backend-mediated paste\n * for lazy-loaded tables where not all data is available locally. */\nexport interface ClipboardProxy {\n cardinality: RegionCardinality;\n /** Source row indices (for row/cell copies) */\n rowIndices?: number[];\n /** Source column keys (for column/cell copies) */\n columnKeys?: string[];\n /** The plain text written to the clipboard, used to verify the proxy\n * is still valid on paste (i.e., clipboard hasn't been overwritten). */\n text: string;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n columnSpecOptions?: ColumnSpecOptions<T>;\n /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is\n * suppressed — a function `columnSpec` derives it from the loaded rows\n * instead (in `_DataSheet`). Set at init from the prop's shape. */\n deferColumnSpec: boolean;\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n /**\n * Set of row indices that have been added to the table,\n * but not yet committed to the underlying data array.\n *\n * This is used to track which rows should be reverted when\n * a \"reset\" action is performed.\n */\n rowStatus: (RowStatusValue | undefined)[];\n /** Presentation per row-status value (merged: defaults + the\n * `rowStatusStyles` prop). Read by the cell renderer and row-header renderer\n * to style rows by status. */\n rowStatusStyles: RowStatusStyles;\n // Sparse data structure for updated data\n updatedData: (T | null | undefined)[];\n data: T[];\n initialized: boolean;\n columnWidthsIndex: Map<string, number>;\n /** Active column/table filters. Keys are filter IDs, values carry the\n * filter definition and its current configuration state. */\n activeFilters: Map<string, { filter: any; state: any }>;\n /** Clipboard proxy from the last copy operation */\n clipboardProxy: ClipboardProxy | null;\n /** Visible row indices when filters are active. `null` means show all rows. */\n filteredRowIndices: number[] | null;\n /** Active column sort entries for client-side sorting. */\n columnSorts: ColumnSort[];\n /** Whether selecting a cell automatically activates its surface (opens an\n * editor/detail panel and, for editors, focuses it). `\"manual\"` opens only\n * on click. */\n cellInteraction: \"auto\" | \"manual\" | \"second-click\";\n /** Runtime override of `cellInteraction`: while `false`, auto-activation is\n * suppressed (set by pressing Escape, re-armed by clicking a cell) so the\n * keyboard prioritizes navigation. */\n autoActivateArmed: boolean;\n /** Direction of the last keyboard navigation, used to place an editor's\n * cursor on the side the user is travelling toward. `null` after a click. */\n lastNavDirection: NavDirection | null;\n /** The table's focusable holder element; editors return focus here when the\n * cursor leaves them so arrow-key navigation resumes. */\n tableElement: HTMLElement | null;\n /** Whether the focused cell's surface (editor or detail panel) is open.\n * Owned by the store — not per-popover — so navigation, clicks, and the\n * Escape handler all agree on it. */\n cellSurfaceOpen: boolean;\n /** Optional observer called for every user edit as a structured\n * `EditEvent`, in addition to the built-in `updatedData` overlay. Lets a\n * consumer capture edits as revertible operations. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Row identity for the edit overlay — stable across a provider re-sort,\n * unlike an array index. Defaults to `(row) => row?.id`; a data provider\n * supplies its own (e.g. a PostgREST identity key). Used to re-attach edits\n * when the loader replaces `data` with a re-ordered window. */\n identity: (row: any) => string | number | null | undefined;\n /** Edits/statuses held by identity for rows not currently loaded (server\n * sources), re-attached when their row next arrives. */\n pendingOverlayById: Map<\n string | number,\n { edit?: any; status?: TableElementStatus }\n >;\n /** True when the consumer controls the `updatedData`/`rowStatus` overlay; the\n * loader-boundary identity remap is skipped (the consumer owns it). */\n controlledOverlay: boolean;\n /** Whether row deletion is available. Set from the data provider: an explicit\n * `provider` without `deleteRows` disables deletion entirely (the delete\n * affordance greys out and the delete key is a no-op). Defaults to `true`. */\n canDeleteRows: boolean;\n /** Provider-backed, auto-refreshing row mutations for immediate-edit consumers\n * (chiefly `DataPanel`). Each persists through the data provider and then\n * re-fetches. Wired by the consumer that owns the provider + loader; exposed\n * on the action context as `saveRows` / `deleteRows` / `insertRow` /\n * `refresh`, so a selection action can edit without hand-wiring persistence.\n * Absent when no persisting provider. */\n rowEditing?: {\n saveRows?: (rows: any[]) => Promise<void>;\n deleteRows?: (ids: Array<string | number>) => Promise<void>;\n insertRow?: (row: any) => Promise<void>;\n refresh?: () => void;\n };\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataViewCoreProps<T>;\nexport type StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStoreMain<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(event: MouseEvent): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onSelectionEdited(value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n onColumnWidthChanged(columnIndex: number, newWidth: number): void;\n moveFocusedCell(direction: NavDirection): void;\n /** Suppress auto-activation until the next click (Escape enters nav mode). */\n suppressAutoActivate(): void;\n /** Re-arm auto-activation (a click re-enables auto-focus). */\n armAutoActivate(): void;\n /** Open the focused cell's surface (editor or detail panel). */\n openCellSurface(): void;\n /** Close the focused cell's surface. When `suppress` is true (the default,\n * as for Escape), auto mode also enters navigation mode (auto-activation is\n * suppressed until the next click). A click-dismiss passes `suppress: false`\n * so it just closes without changing the global mode. */\n closeCellSurface(opts?: { suppress?: boolean }): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n /** Activate or update a column/table filter.\n * Filter is any object satisfying `TableFilter` from the actions module. */\n setFilter(filterId: string, filter: any, filterState: any): void;\n /** Remove a filter by ID */\n removeFilter(filterId: string): void;\n /** Remove all active filters */\n clearFilters(): void;\n /** Set or clear a column sort. Pass `null` for ascending to clear. */\n setColumnSort(key: string, ascending: boolean | null): void;\n /** Remove all active column sorts */\n clearColumnSorts(): void;\n /** Store a clipboard proxy for potential backend-mediated paste */\n setClipboardProxy(proxy: ClipboardProxy | null): void;\n //initialize(props: Partial<DataSheetStoreMain<T>>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2> | null;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n // Editable is not optional on store\n editable: boolean;\n}\n\nexport type DataSheetProviderProps<T> = DataViewCoreProps<T> & {\n toaster?: OverlayToaster;\n /** A first window of rows the caller already has (see `FetchDataOptions`).\n * The provider creates the store seeded with it, so the rows are in the very\n * first render — a server render included. */\n initialData?: FetchDataOptions<T>[\"initialData\"];\n /** The row the view starts after (see `FetchDataOptions`). Seeded into the\n * store at creation alongside `initialData`. */\n startAfter?: FetchDataOptions<T>[\"startAfter\"];\n viewType?: DataViewRendererType;\n children?: React.ReactNode;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n\n/** A single cell edit, used with `editCells` for batch updates. */\nexport interface CellEdit {\n rowIndex: number;\n column: string;\n value: any;\n /** The underlying row (base data). Populated on emitted `onEdit` events so a\n * handler can address the row (identity) without reaching into the store. */\n row?: any;\n}\n"],"names":["TableElementStatus"],"mappings":"AAmCO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,SAAA,IAAU;AACVA,sBAAA,OAAA,IAAQ;AAFE,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AA6BL,MAAM,4BAA6C;AAAA,EACxD;AAAA,IAAC;AAAA;AAAA,KAA6B;AAAA,IAC5B,WAAW,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC3C,aAAa,EAAE,SAAS,KAAK,gBAAgB,eAAA;AAAA,IAC7C,QAAQ;AAAA,EAAA;AAEZ;AAwBO,MAAM,YAAY;"}
|