@macrostrat/data-sheet 4.0.1 → 4.1.1
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 +25 -0
- package/README.md +11 -1
- package/dist/actions/column-controls.cjs +102 -1
- package/dist/actions/column-controls.cjs.map +1 -1
- package/dist/actions/column-controls.js +104 -3
- package/dist/actions/column-controls.js.map +1 -1
- package/dist/actions/column-filter.cjs +48 -25
- package/dist/actions/column-filter.cjs.map +1 -1
- package/dist/actions/column-filter.js +50 -27
- package/dist/actions/column-filter.js.map +1 -1
- package/dist/actions/selection.cjs +2 -1
- package/dist/actions/selection.cjs.map +1 -1
- package/dist/actions/selection.js +2 -1
- package/dist/actions/selection.js.map +1 -1
- package/dist/actions/table-controls.cjs +21 -0
- package/dist/actions/table-controls.cjs.map +1 -1
- package/dist/actions/table-controls.d.ts +4 -0
- package/dist/actions/table-controls.js +21 -0
- package/dist/actions/table-controls.js.map +1 -1
- package/dist/actions/toolbar.cjs +34 -4
- package/dist/actions/toolbar.cjs.map +1 -1
- package/dist/actions/toolbar.js +35 -5
- package/dist/actions/toolbar.js.map +1 -1
- package/dist/actions/types.d.ts +9 -0
- package/dist/cell-renderer.cjs +9 -7
- package/dist/cell-renderer.cjs.map +1 -1
- package/dist/cell-renderer.js +9 -7
- package/dist/cell-renderer.js.map +1 -1
- package/dist/core.cjs +68 -9
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.ts +32 -1
- package/dist/core.js +69 -10
- package/dist/core.js.map +1 -1
- package/dist/filters/operators.cjs +2 -2
- package/dist/filters/operators.cjs.map +1 -1
- package/dist/filters/operators.d.ts +1 -1
- package/dist/filters/operators.js +2 -2
- package/dist/filters/operators.js.map +1 -1
- package/dist/index.cjs +4 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -2
- package/dist/postgrest-table/data-loaders.cjs +1 -8
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.js +1 -8
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/provider.cjs +9 -3
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.d.ts +2 -1
- package/dist/provider.js +9 -3
- package/dist/provider.js.map +1 -1
- package/dist/renderers/column-header-cell.cjs +33 -32
- package/dist/renderers/column-header-cell.cjs.map +1 -1
- package/dist/renderers/column-header-cell.d.ts +1 -2
- package/dist/renderers/column-header-cell.js +34 -33
- package/dist/renderers/column-header-cell.js.map +1 -1
- package/dist/types.cjs +11 -0
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +55 -2
- package/dist/types.js +11 -0
- package/dist/types.js.map +1 -1
- package/dist/utils/column-spec.cjs.map +1 -1
- package/dist/utils/column-spec.d.ts +8 -0
- package/dist/utils/column-spec.js.map +1 -1
- package/dist/zustand-store.cjs +7 -3
- package/dist/zustand-store.cjs.map +1 -1
- package/dist/zustand-store.js +8 -4
- package/dist/zustand-store.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/column-controls.ts +133 -2
- package/src/actions/column-filter.ts +59 -30
- package/src/actions/selection.ts +1 -0
- package/src/actions/table-controls.ts +24 -0
- package/src/actions/toolbar.ts +61 -5
- package/src/actions/types.ts +10 -0
- package/src/cell-renderer.ts +23 -10
- package/src/core.ts +131 -13
- package/src/filters/operators.ts +5 -3
- package/src/postgrest-table/data-loaders.ts +6 -10
- package/src/provider.ts +22 -5
- package/src/renderers/column-header-cell.ts +51 -36
- package/src/types.ts +66 -2
- package/src/utils/column-spec.ts +8 -0
- package/src/zustand-store.ts +12 -5
package/dist/provider.cjs
CHANGED
|
@@ -37,6 +37,7 @@ const storeAtom = jotai.atom(
|
|
|
37
37
|
return set(storeWrapper, action);
|
|
38
38
|
}
|
|
39
39
|
);
|
|
40
|
+
const EMPTY_SPEC = [];
|
|
40
41
|
const initializeStoreAtom = jotai.atom(
|
|
41
42
|
null,
|
|
42
43
|
(get, set, payload) => {
|
|
@@ -76,16 +77,21 @@ function DataSheetProviderInner({
|
|
|
76
77
|
}) {
|
|
77
78
|
const tableRef = react.useRef(null);
|
|
78
79
|
const initializeStore = ctx.useSet(initializeStoreAtom);
|
|
80
|
+
const isFnSpec = typeof columnSpec$1 === "function";
|
|
81
|
+
const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec$1;
|
|
79
82
|
react.useEffect(() => {
|
|
80
83
|
initializeStore({
|
|
81
|
-
columnSpec:
|
|
84
|
+
columnSpec: staticSpec ?? columnSpec.generateColumnSpec(data, columnSpecOptions),
|
|
85
|
+
// A function spec is derived from the loaded rows in `_DataSheet`; tell
|
|
86
|
+
// the loader not to auto-generate a plain spec from the first chunk.
|
|
87
|
+
deferColumnSpec: isFnSpec,
|
|
82
88
|
editable,
|
|
83
89
|
enableColumnReordering,
|
|
84
90
|
data,
|
|
85
91
|
defaultColumnWidth,
|
|
86
92
|
tableRef
|
|
87
93
|
});
|
|
88
|
-
}, [data, editable,
|
|
94
|
+
}, [data, editable, staticSpec, isFnSpec, columnSpecOptions, enableColumnReordering]);
|
|
89
95
|
return children;
|
|
90
96
|
}
|
|
91
97
|
function useStoreAPI() {
|
|
@@ -107,7 +113,7 @@ const tableDataAtom = jotai.atom(
|
|
|
107
113
|
(get, set, newData) => {
|
|
108
114
|
set(storeAtom, (state) => {
|
|
109
115
|
let next = { ...state, data: newData };
|
|
110
|
-
if (state.data.length == 0 && newData.length > 0 && state.columnSpec.length == 0) {
|
|
116
|
+
if (state.data.length == 0 && newData.length > 0 && state.columnSpec.length == 0 && !state.deferColumnSpec) {
|
|
111
117
|
next.columnSpec = columnSpec.generateColumnSpec(newData, state.columnSpecOptions);
|
|
112
118
|
}
|
|
113
119
|
if (!state.controlledOverlay) {
|
package/dist/provider.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.cjs","sources":["../src/provider.ts"],"sourcesContent":["import { SetStateAction, useEffect, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport type { Table } from \"@blueprintjs/table\";\nimport { generateColumnSpec } from \"./utils\";\nimport { createScopedStore } from \"@macrostrat/data-components\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { atomWithStore } from \"jotai-zustand\";\nimport { toasterAtom } from \"./notifications.ts\";\nimport { TableAction } from \"./actions\";\nimport { atom } from \"jotai\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();\n\nconst storeWrapperAtom = atom((get) => {\n const _storeAPIAtom = get(storeAPIAtom);\n if (_storeAPIAtom == null) {\n return undefined;\n }\n return atomWithStore(_storeAPIAtom);\n});\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = atom(\n (get) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n return undefined;\n }\n return get(storeWrapper);\n },\n (get, set, action: SetStateAction<T>) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return set(storeWrapper, action);\n },\n);\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<T>>) => {\n set(storeAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\nexport function DataSheetProvider<T>(props: DataSheetProviderProps<T>) {\n const { toaster, ...rest } = props;\n const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(createZustandStore);\n });\n return h(\n ctx.Provider,\n {\n atoms: [\n [storeAPIAtom, store],\n [toasterAtom, toaster],\n ],\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\nexport function DataSheetProviderInner<T>({\n children,\n data,\n columnSpec,\n columnSpecOptions,\n editable,\n enableColumnReordering,\n defaultColumnWidth = 150,\n}: DataSheetProviderProps<T>) {\n const tableRef = useRef<Table>(null);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n\n // Not sure how required this initialization is\n useEffect(() => {\n initializeStore({\n columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),\n editable,\n enableColumnReordering,\n data,\n defaultColumnWidth,\n tableRef,\n });\n }, [data, editable, columnSpec, columnSpecOptions, enableColumnReordering]);\n\n return children;\n}\n\nexport function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {\n const store = ctx.useValue(storeAPIAtom);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T> & DataSheetComputedVals) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n if (\n state.data.length == 0 &&\n newData.length > 0 &&\n state.columnSpec.length == 0\n ) {\n // We haven't yet generated the column spec, and we need to do so.\n next.columnSpec = generateColumnSpec(newData, state.columnSpecOptions);\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n"],"names":["createScopedStore","atom","atomWithStore","useState","createStore","createZustandStore","h","toasterAtom","columnSpec","useRef","useEffect","generateColumnSpec","useStore","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;AAoBO,MAAM,MAAMA,eAAAA,kBAAA;AAEZ,MAAM,eAAeC,MAAAA,KAAA;AAE5B,MAAM,mBAAmBA,MAAAA,KAAK,CAAC,QAAQ;AACrC,QAAM,gBAAgB,IAAI,YAAY;AACtC,MAAI,iBAAiB,MAAM;AACzB,WAAO;AAAA,EACT;AACA,SAAOC,aAAAA,cAAc,aAAa;AACpC,CAAC;AAGM,MAAM,YAAYD,MAAAA;AAAAA,EACvB,CAAC,QAAQ;AACP,UAAM,eAAe,IAAI,gBAAgB;AACzC,QAAI,gBAAgB,MAAM;AACxB,aAAO;AAAA,IACT;AACA,WAAO,IAAI,YAAY;AAAA,EACzB;AAAA,EACA,CAAC,KAAK,KAAK,WAA8B;AACvC,UAAM,eAAe,IAAI,gBAAgB;AACzC,QAAI,gBAAgB,MAAM;AACxB,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AACA,WAAO,IAAI,cAAc,MAAM;AAAA,EACjC;AACF;AAEA,MAAM,sBAAsBA,MAAAA;AAAAA,EAC1B;AAAA,EACA,CAAC,KAAK,KAAK,YAAwC;AACjD,QAAI,WAAW,CAAC,UAAU;AACxB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,GAAG;AAAA,MAAA;AAAA,IAEP,CAAC;AAAA,EACH;AACF;AAEO,MAAM,mBAAmBA,MAAAA,KAAoB,CAAA,CAAE;AAE/C,SAAS,kBAAqB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Aa,QAAQ,MAAA;AAC3B,QAAM,cAAqB,CAAA;AAC3B,QAAM,aAAoB,CAAA;AAC1B,QAAM,+BAAe,IAAA;AACrB,WAAS,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;AAC1C,UAAM,MAAM,WAAW,CAAC;AACxB,QAAI,OAAO,KAAM;AACjB,UAAM,KAAK,gBAAgB,OAAO,GAAG;AACrC,QAAI,MAAM,KAAM;AAChB,UAAM,QAAQ,KAAK,IAAI,EAAE;AACzB,QAAI,SAAS,KAAM;AACnB,QAAI,MAAM,QAAQ,KAAM,aAAY,CAAC,IAAI,MAAM;AAC/C,QAAI,MAAM,UAAU,KAAM,YAAW,CAAC,IAAI,MAAM;AAChD,aAAS,IAAI,EAAE;AAAA,EACjB;AAIA,QAAM,8BAAc,IAAA;AACpB,aAAW,CAAC,IAAI,KAAK,KAAK,MAAM;AAC9B,QAAI,SAAS,IAAI,EAAE,EAAG;AACtB,QAAI,MAAM,WAAWC,MAAAA,mBAAmB,OAAO;AAC7C,YAAM,MAAM,WAAW;AACvB,iBAAW,KAAK,MAAM,QAAQ,CAAA,CAAE;AAChC,kBAAY,GAAG,IAAI,MAAM;AACzB,iBAAW,GAAG,IAAI,MAAM;AAAA,IAC1B,OAAO;AACL,cAAQ,IAAI,IAAI,KAAK;AAAA,IACvB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,IACb,WAAW;AAAA,IACX;AAAA,EAAA;AAEJ;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"provider.cjs","sources":["../src/provider.ts"],"sourcesContent":["import { SetStateAction, useEffect, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport type { Table } from \"@blueprintjs/table\";\nimport { generateColumnSpec, type ColumnSpec } from \"./utils\";\nimport { createScopedStore } from \"@macrostrat/data-components\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { atomWithStore } from \"jotai-zustand\";\nimport { toasterAtom } from \"./notifications.ts\";\nimport { TableAction } from \"./actions\";\nimport { atom } from \"jotai\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();\n\nconst storeWrapperAtom = atom((get) => {\n const _storeAPIAtom = get(storeAPIAtom);\n if (_storeAPIAtom == null) {\n return undefined;\n }\n return atomWithStore(_storeAPIAtom);\n});\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = atom(\n (get) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n return undefined;\n }\n return get(storeWrapper);\n },\n (get, set, action: SetStateAction<T>) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return set(storeWrapper, action);\n },\n);\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<T>>) => {\n set(storeAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\nexport function DataSheetProvider<T>(props: DataSheetProviderProps<T>) {\n const { toaster, ...rest } = props;\n const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(createZustandStore);\n });\n return h(\n ctx.Provider,\n {\n atoms: [\n [storeAPIAtom, store],\n [toasterAtom, toaster],\n ],\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\nexport function DataSheetProviderInner<T>({\n children,\n data,\n columnSpec,\n columnSpecOptions,\n editable,\n enableColumnReordering,\n defaultColumnWidth = 150,\n}: DataSheetProviderProps<T>) {\n const tableRef = useRef<Table>(null);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n\n // Not sure how required this initialization is\n useEffect(() => {\n initializeStore({\n columnSpec: staticSpec ?? generateColumnSpec(data, columnSpecOptions),\n // A function spec is derived from the loaded rows in `_DataSheet`; tell\n // the loader not to auto-generate a plain spec from the first chunk.\n deferColumnSpec: isFnSpec,\n editable,\n enableColumnReordering,\n data,\n defaultColumnWidth,\n tableRef,\n });\n }, [data, editable, staticSpec, isFnSpec, columnSpecOptions, enableColumnReordering]);\n\n return children;\n}\n\nexport function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {\n const store = ctx.useValue(storeAPIAtom);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T> & DataSheetComputedVals) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n if (\n state.data.length == 0 &&\n newData.length > 0 &&\n state.columnSpec.length == 0 &&\n !state.deferColumnSpec\n ) {\n // No spec yet and none deferred to a function — auto-generate a plain\n // spec from the first chunk. (A function spec is derived separately.)\n next.columnSpec = generateColumnSpec(newData, state.columnSpecOptions);\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n"],"names":["createScopedStore","atom","atomWithStore","useState","createStore","createZustandStore","h","toasterAtom","columnSpec","useRef","useEffect","generateColumnSpec","useStore","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;AAoBO,MAAM,MAAMA,eAAAA,kBAAA;AAEZ,MAAM,eAAeC,MAAAA,KAAA;AAE5B,MAAM,mBAAmBA,MAAAA,KAAK,CAAC,QAAQ;AACrC,QAAM,gBAAgB,IAAI,YAAY;AACtC,MAAI,iBAAiB,MAAM;AACzB,WAAO;AAAA,EACT;AACA,SAAOC,aAAAA,cAAc,aAAa;AACpC,CAAC;AAGM,MAAM,YAAYD,MAAAA;AAAAA,EACvB,CAAC,QAAQ;AACP,UAAM,eAAe,IAAI,gBAAgB;AACzC,QAAI,gBAAgB,MAAM;AACxB,aAAO;AAAA,IACT;AACA,WAAO,IAAI,YAAY;AAAA,EACzB;AAAA,EACA,CAAC,KAAK,KAAK,WAA8B;AACvC,UAAM,eAAe,IAAI,gBAAgB;AACzC,QAAI,gBAAgB,MAAM;AACxB,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC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,OAAO;AACL,cAAQ,IAAI,IAAI,KAAK;AAAA,IACvB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,IACb,WAAW;AAAA,IACX;AAAA,EAAA;AAEJ;;;;;;;;;;;"}
|
package/dist/provider.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { StoreApi } from 'zustand';
|
|
2
|
+
import { ColumnSpec } from './utils';
|
|
2
3
|
import { DataSheetProviderProps, DataSheetStore } from './types.ts';
|
|
3
4
|
import { TableAction } from './actions';
|
|
4
5
|
/** Create a Jotai scoped store */
|
|
@@ -21,5 +22,5 @@ export declare function DataSheetProviderInner<T>({ children, data, columnSpec,
|
|
|
21
22
|
export declare function useStoreAPI<T>(): StoreApi<DataSheetStore<T>>;
|
|
22
23
|
export declare function useSelector<T = any, A = any>(selector: (state: DataSheetStore<T> & DataSheetComputedVals) => A): A;
|
|
23
24
|
/** Atoms for efficient sub-selection of state */
|
|
24
|
-
export declare const columnSpecAtom: import('jotai').Atom<
|
|
25
|
+
export declare const columnSpecAtom: import('jotai').Atom<ColumnSpec[]>;
|
|
25
26
|
export declare const tableDataAtom: import('jotai').WritableAtom<any[], [newData: any[]], void>;
|
package/dist/provider.js
CHANGED
|
@@ -33,6 +33,7 @@ const storeAtom = atom(
|
|
|
33
33
|
return set(storeWrapper, action);
|
|
34
34
|
}
|
|
35
35
|
);
|
|
36
|
+
const EMPTY_SPEC = [];
|
|
36
37
|
const initializeStoreAtom = atom(
|
|
37
38
|
null,
|
|
38
39
|
(get, set, payload) => {
|
|
@@ -72,16 +73,21 @@ function DataSheetProviderInner({
|
|
|
72
73
|
}) {
|
|
73
74
|
const tableRef = useRef(null);
|
|
74
75
|
const initializeStore = ctx.useSet(initializeStoreAtom);
|
|
76
|
+
const isFnSpec = typeof columnSpec === "function";
|
|
77
|
+
const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;
|
|
75
78
|
useEffect(() => {
|
|
76
79
|
initializeStore({
|
|
77
|
-
columnSpec:
|
|
80
|
+
columnSpec: staticSpec ?? generateColumnSpec(data, columnSpecOptions),
|
|
81
|
+
// A function spec is derived from the loaded rows in `_DataSheet`; tell
|
|
82
|
+
// the loader not to auto-generate a plain spec from the first chunk.
|
|
83
|
+
deferColumnSpec: isFnSpec,
|
|
78
84
|
editable,
|
|
79
85
|
enableColumnReordering,
|
|
80
86
|
data,
|
|
81
87
|
defaultColumnWidth,
|
|
82
88
|
tableRef
|
|
83
89
|
});
|
|
84
|
-
}, [data, editable,
|
|
90
|
+
}, [data, editable, staticSpec, isFnSpec, columnSpecOptions, enableColumnReordering]);
|
|
85
91
|
return children;
|
|
86
92
|
}
|
|
87
93
|
function useStoreAPI() {
|
|
@@ -103,7 +109,7 @@ const tableDataAtom = atom(
|
|
|
103
109
|
(get, set, newData) => {
|
|
104
110
|
set(storeAtom, (state) => {
|
|
105
111
|
let next = { ...state, data: newData };
|
|
106
|
-
if (state.data.length == 0 && newData.length > 0 && state.columnSpec.length == 0) {
|
|
112
|
+
if (state.data.length == 0 && newData.length > 0 && state.columnSpec.length == 0 && !state.deferColumnSpec) {
|
|
107
113
|
next.columnSpec = generateColumnSpec(newData, state.columnSpecOptions);
|
|
108
114
|
}
|
|
109
115
|
if (!state.controlledOverlay) {
|
package/dist/provider.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","sources":["../src/provider.ts"],"sourcesContent":["import { SetStateAction, useEffect, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport type { Table } from \"@blueprintjs/table\";\nimport { generateColumnSpec } from \"./utils\";\nimport { createScopedStore } from \"@macrostrat/data-components\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { atomWithStore } from \"jotai-zustand\";\nimport { toasterAtom } from \"./notifications.ts\";\nimport { TableAction } from \"./actions\";\nimport { atom } from \"jotai\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();\n\nconst storeWrapperAtom = atom((get) => {\n const _storeAPIAtom = get(storeAPIAtom);\n if (_storeAPIAtom == null) {\n return undefined;\n }\n return atomWithStore(_storeAPIAtom);\n});\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = atom(\n (get) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n return undefined;\n }\n return get(storeWrapper);\n },\n (get, set, action: SetStateAction<T>) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return set(storeWrapper, action);\n },\n);\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<T>>) => {\n set(storeAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\nexport function DataSheetProvider<T>(props: DataSheetProviderProps<T>) {\n const { toaster, ...rest } = props;\n const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(createZustandStore);\n });\n return h(\n ctx.Provider,\n {\n atoms: [\n [storeAPIAtom, store],\n [toasterAtom, toaster],\n ],\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\nexport function DataSheetProviderInner<T>({\n children,\n data,\n columnSpec,\n columnSpecOptions,\n editable,\n enableColumnReordering,\n defaultColumnWidth = 150,\n}: DataSheetProviderProps<T>) {\n const tableRef = useRef<Table>(null);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n\n // Not sure how required this initialization is\n useEffect(() => {\n initializeStore({\n columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),\n editable,\n enableColumnReordering,\n data,\n defaultColumnWidth,\n tableRef,\n });\n }, [data, editable, columnSpec, columnSpecOptions, enableColumnReordering]);\n\n return children;\n}\n\nexport function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {\n const store = ctx.useValue(storeAPIAtom);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T> & DataSheetComputedVals) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n if (\n state.data.length == 0 &&\n newData.length > 0 &&\n state.columnSpec.length == 0\n ) {\n // We haven't yet generated the column spec, and we need to do so.\n next.columnSpec = generateColumnSpec(newData, state.columnSpecOptions);\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;A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B,QAAI,SAAS,IAAI,EAAE,EAAG;AACtB,QAAI,MAAM,WAAW,mBAAmB,OAAO;AAC7C,YAAM,MAAM,WAAW;AACvB,iBAAW,KAAK,MAAM,QAAQ,CAAA,CAAE;AAChC,kBAAY,GAAG,IAAI,MAAM;AACzB,iBAAW,GAAG,IAAI,MAAM;AAAA,IAC1B,OAAO;AACL,cAAQ,IAAI,IAAI,KAAK;AAAA,IACvB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,IACb,WAAW;AAAA,IACX;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"provider.js","sources":["../src/provider.ts"],"sourcesContent":["import { SetStateAction, useEffect, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport type { Table } from \"@blueprintjs/table\";\nimport { generateColumnSpec, type ColumnSpec } from \"./utils\";\nimport { createScopedStore } from \"@macrostrat/data-components\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { atomWithStore } from \"jotai-zustand\";\nimport { toasterAtom } from \"./notifications.ts\";\nimport { TableAction } from \"./actions\";\nimport { atom } from \"jotai\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();\n\nconst storeWrapperAtom = atom((get) => {\n const _storeAPIAtom = get(storeAPIAtom);\n if (_storeAPIAtom == null) {\n return undefined;\n }\n return atomWithStore(_storeAPIAtom);\n});\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = atom(\n (get) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n return undefined;\n }\n return get(storeWrapper);\n },\n (get, set, action: SetStateAction<T>) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return set(storeWrapper, action);\n },\n);\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<T>>) => {\n set(storeAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\nexport function DataSheetProvider<T>(props: DataSheetProviderProps<T>) {\n const { toaster, ...rest } = props;\n const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(createZustandStore);\n });\n return h(\n ctx.Provider,\n {\n atoms: [\n [storeAPIAtom, store],\n [toasterAtom, toaster],\n ],\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\nexport function DataSheetProviderInner<T>({\n children,\n data,\n columnSpec,\n columnSpecOptions,\n editable,\n enableColumnReordering,\n defaultColumnWidth = 150,\n}: DataSheetProviderProps<T>) {\n const tableRef = useRef<Table>(null);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n\n // Not sure how required this initialization is\n useEffect(() => {\n initializeStore({\n columnSpec: staticSpec ?? generateColumnSpec(data, columnSpecOptions),\n // A function spec is derived from the loaded rows in `_DataSheet`; tell\n // the loader not to auto-generate a plain spec from the first chunk.\n deferColumnSpec: isFnSpec,\n editable,\n enableColumnReordering,\n data,\n defaultColumnWidth,\n tableRef,\n });\n }, [data, editable, staticSpec, isFnSpec, columnSpecOptions, enableColumnReordering]);\n\n return children;\n}\n\nexport function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {\n const store = ctx.useValue(storeAPIAtom);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T> & DataSheetComputedVals) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n if (\n state.data.length == 0 &&\n newData.length > 0 &&\n state.columnSpec.length == 0 &&\n !state.deferColumnSpec\n ) {\n // No spec yet and none deferred to a function — auto-generate a plain\n // spec from the first chunk. (A function spec is derived separately.)\n next.columnSpec = generateColumnSpec(newData, state.columnSpecOptions);\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n"],"names":[],"mappings":";;;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AAI,MAAM,UAAU,KAAM,YAAW,CAAC,IAAI,MAAM;AAChD,aAAS,IAAI,EAAE;AAAA,EACjB;AAIA,QAAM,8BAAc,IAAA;AACpB,aAAW,CAAC,IAAI,KAAK,KAAK,MAAM;AAC9B,QAAI,SAAS,IAAI,EAAE,EAAG;AACtB,QAAI,MAAM,WAAW,mBAAmB,OAAO;AAC7C,YAAM,MAAM,WAAW;AACvB,iBAAW,KAAK,MAAM,QAAQ,CAAA,CAAE;AAChC,kBAAY,GAAG,IAAI,MAAM;AACzB,iBAAW,GAAG,IAAI,MAAM;AAAA,IAC1B,OAAO;AACL,cAAQ,IAAI,IAAI,KAAK;AAAA,IACvB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,IACb,WAAW;AAAA,IACX;AAAA,EAAA;AAEJ;"}
|
|
@@ -16,13 +16,24 @@ function renderColumnHeaderCell({
|
|
|
16
16
|
const isSortable = col.sortable === true;
|
|
17
17
|
const isFilterable = col.filterable === true || typeof col.filterable === "object" || Array.isArray(col.filters) && col.filters.length > 0;
|
|
18
18
|
const hasCustomActions = Array.isArray(col.actions) && col.actions.length > 0;
|
|
19
|
+
const enableColumnReordering = col.reorderable !== false;
|
|
19
20
|
if (!isSortable && !isFilterable && !hasCustomActions) {
|
|
20
|
-
return h__default.default(table.ColumnHeaderCell, {
|
|
21
|
+
return h__default.default(table.ColumnHeaderCell, {
|
|
22
|
+
name: col.name,
|
|
23
|
+
enableColumnReordering,
|
|
24
|
+
nameRenderer: () => h__default.default(ColumnHeaderName, {
|
|
25
|
+
col,
|
|
26
|
+
hasSortActive: false,
|
|
27
|
+
hasFilterActive: false,
|
|
28
|
+
activeSort: null
|
|
29
|
+
})
|
|
30
|
+
});
|
|
21
31
|
}
|
|
22
32
|
const hasFilterActive = activeFilter != null;
|
|
23
33
|
const hasSortActive = activeSort != null;
|
|
24
34
|
return h__default.default(table.ColumnHeaderCell, {
|
|
25
35
|
name: col.name,
|
|
36
|
+
enableColumnReordering,
|
|
26
37
|
// Persistent interaction bar so the menu caret is always clickable — the
|
|
27
38
|
// hover-triggered caret was blocked by the selection overlay when the
|
|
28
39
|
// column was selected.
|
|
@@ -34,7 +45,10 @@ function renderColumnHeaderCell({
|
|
|
34
45
|
function ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {
|
|
35
46
|
return h__default.default(
|
|
36
47
|
"div",
|
|
37
|
-
{
|
|
48
|
+
{
|
|
49
|
+
"data-column-key": col.key,
|
|
50
|
+
style: { display: "flex", alignItems: "center", width: "100%" }
|
|
51
|
+
},
|
|
38
52
|
[
|
|
39
53
|
h__default.default(
|
|
40
54
|
"span",
|
|
@@ -68,7 +82,7 @@ function ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {
|
|
|
68
82
|
h__default.default.if(hasFilterActive)(core.Icon, {
|
|
69
83
|
icon: "filter",
|
|
70
84
|
size: 12,
|
|
71
|
-
style: { color: "var(--intent-
|
|
85
|
+
style: { color: "var(--intent-primary, #2965cc)" }
|
|
72
86
|
})
|
|
73
87
|
]
|
|
74
88
|
)
|
|
@@ -85,39 +99,26 @@ function ColumnHeaderControls({ colIndex }) {
|
|
|
85
99
|
},
|
|
86
100
|
storeAPI.setState
|
|
87
101
|
);
|
|
102
|
+
const isGlobal = (a) => a.targets.includes(table.RegionCardinality.FULL_TABLE) || a.targets.includes("none");
|
|
88
103
|
const controls = actions.filter(
|
|
89
|
-
(a) => a.targets.includes(table.RegionCardinality.FULL_COLUMNS) && (a.appliesTo?.(actionCtx) ?? true)
|
|
104
|
+
(a) => a.targets.includes(table.RegionCardinality.FULL_COLUMNS) && !isGlobal(a) && (a.appliesTo?.(actionCtx) ?? true)
|
|
90
105
|
);
|
|
91
|
-
const
|
|
92
|
-
(a
|
|
93
|
-
|
|
94
|
-
{
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
).filter(Boolean);
|
|
105
|
-
if (rendered.length === 0) {
|
|
106
|
+
const items = controls.map((a, i) => {
|
|
107
|
+
if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);
|
|
108
|
+
if (a.render != null)
|
|
109
|
+
return h__default.default("li.column-header-control", { key: a.id ?? i }, a.render(actionCtx));
|
|
110
|
+
return h__default.default(core.MenuItem, {
|
|
111
|
+
key: a.id ?? i,
|
|
112
|
+
icon: a.icon,
|
|
113
|
+
intent: a.intent,
|
|
114
|
+
text: a.name,
|
|
115
|
+
onClick: () => a.run?.(actionCtx)
|
|
116
|
+
});
|
|
117
|
+
}).filter(Boolean);
|
|
118
|
+
if (items.length === 0) {
|
|
106
119
|
return h__default.default(core.Menu, [h__default.default(core.MenuItem, { text: "No options", disabled: true })]);
|
|
107
120
|
}
|
|
108
|
-
return h__default.default(
|
|
109
|
-
"div.column-header-controls",
|
|
110
|
-
{
|
|
111
|
-
style: {
|
|
112
|
-
padding: "8px",
|
|
113
|
-
display: "flex",
|
|
114
|
-
flexDirection: "column",
|
|
115
|
-
gap: "6px",
|
|
116
|
-
alignItems: "flex-start"
|
|
117
|
-
}
|
|
118
|
-
},
|
|
119
|
-
rendered
|
|
120
|
-
);
|
|
121
|
+
return h__default.default(core.Menu, { className: "column-header-controls" }, items);
|
|
121
122
|
}
|
|
122
123
|
exports.renderColumnHeaderCell = renderColumnHeaderCell;
|
|
123
124
|
//# sourceMappingURL=column-header-cell.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-header-cell.cjs","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport {
|
|
1
|
+
{"version":3,"file":"column-header-cell.cjs","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport { Icon, Menu, MenuItem } from \"@blueprintjs/core\";\nimport { ctx, tableActionsAtom, useStoreAPI } from \"../provider\";\nimport { buildActionContext } from \"../actions/selection\";\nimport type { ColumnSpec } from \"../utils/column-spec\";\nimport type {\n PostgrestColumnFilter,\n ColumnSortEntry,\n} from \"../postgrest-table\";\n\nexport interface ColumnActionsConfig {\n activeSort?: ColumnSortEntry | null;\n activeFilter?: PostgrestColumnFilter | null;\n}\n\nexport interface ColumnHeaderRendererProps extends ColumnActionsConfig {\n col: ColumnSpec;\n colIndex: number;\n //actions: ColumnHeaderActions;\n}\n\n// ---- Column header cell ----\n\n/** Column header cell whose dropdown renders the `FULL_COLUMNS` controls\n * (sort/filter + any custom column actions) from the shared action registry,\n * scoped to this column. */\nexport function renderColumnHeaderCell({\n col,\n colIndex,\n activeSort,\n activeFilter,\n}: ColumnHeaderRendererProps) {\n const isSortable = col.sortable === true;\n const isFilterable =\n col.filterable === true ||\n typeof col.filterable === \"object\" ||\n (Array.isArray(col.filters) && col.filters.length > 0);\n const hasCustomActions =\n Array.isArray((col as any).actions) && (col as any).actions.length > 0;\n\n // A column may be pinned against drag-reordering via `reorderable: false`.\n const enableColumnReordering = col.reorderable !== false;\n\n if (!isSortable && !isFilterable && !hasCustomActions) {\n return h(ColumnHeaderCell, {\n name: col.name,\n enableColumnReordering,\n nameRenderer: () =>\n h(ColumnHeaderName, {\n col,\n hasSortActive: false,\n hasFilterActive: false,\n activeSort: null,\n }),\n });\n }\n\n // `activeFilter` is the active store entry targeting this column (any filter\n // type), or null — so the indicator lights for rich and operator filters.\n const hasFilterActive = activeFilter != null;\n const hasSortActive = activeSort != null;\n\n return h(ColumnHeaderCell, {\n name: col.name,\n enableColumnReordering,\n // Persistent interaction bar so the menu caret is always clickable — the\n // hover-triggered caret was blocked by the selection overlay when the\n // column was selected.\n enableColumnInteractionBar: true,\n nameRenderer: () =>\n h(ColumnHeaderName, { col, hasSortActive, hasFilterActive, activeSort }),\n menuRenderer: () => h(ColumnHeaderControls, { colIndex }),\n });\n}\n\n/** Column name with active sort/filter indicator icons. The column key is\n * exposed as `data-column-key` so consumers can target a specific header from\n * CSS (e.g. to tint a column) without a bespoke styling prop. */\nfunction ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {\n return h(\n \"div\",\n {\n \"data-column-key\": col.key,\n style: { display: \"flex\", alignItems: \"center\", width: \"100%\" },\n },\n [\n h(\n \"span\",\n {\n style: {\n flex: 1,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n },\n },\n col.name,\n ),\n h.if(hasSortActive || hasFilterActive)(\n \"span\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"2px\",\n marginLeft: \"4px\",\n flexShrink: 0,\n },\n },\n [\n h.if(hasSortActive)(Icon, {\n icon: activeSort?.ascending ? \"sort-asc\" : \"sort-desc\",\n size: 12,\n style: { color: \"var(--intent-primary, #2965cc)\" },\n }),\n h.if(hasFilterActive)(Icon, {\n icon: \"filter\",\n size: 12,\n style: { color: \"var(--intent-primary, #2965cc)\" },\n }),\n ],\n ),\n ],\n );\n}\n\n/** Dropdown content: the `FULL_COLUMNS` controls for this column, sourced from\n * the shared action registry and scoped to the column via a synthetic\n * single-column selection context — so the header and toolbar render the same\n * sort/filter (and custom column) controls. */\nfunction ColumnHeaderControls({ colIndex }: { colIndex: number }) {\n const storeAPI = useStoreAPI();\n const actions = ctx.useValue(tableActionsAtom);\n\n // Scope the action context to this column (as if it were the selection).\n const actionCtx = buildActionContext(\n {\n ...storeAPI.getState(),\n selection: [{ cols: [colIndex, colIndex], rows: undefined }],\n } as any,\n storeAPI.setState,\n );\n\n // Only actions *limited* to column scope belong in a column's dropdown —\n // sort/filter and column-specific actions. Global actions (Save / Reset /\n // Clear-selection, marked by a FULL_TABLE or \"none\" target) are confusing\n // here, so they're excluded even though they nominally apply to columns too.\n const isGlobal = (a: (typeof actions)[number]) =>\n a.targets.includes(RegionCardinality.FULL_TABLE) ||\n a.targets.includes(\"none\" as any);\n const controls = actions.filter(\n (a) =>\n a.targets.includes(RegionCardinality.FULL_COLUMNS) &&\n !isGlobal(a) &&\n (a.appliesTo?.(actionCtx) ?? true),\n );\n\n // Prefer menu-native rendering (`renderMenuItem`) — sort/filter render as\n // items with submenus, so the whole dropdown is one Blueprint `Menu`. A\n // control that only has `render` (a live toolbar control) is embedded as-is;\n // a plain `run` action becomes a clickable item.\n const items = controls\n .map((a, i) => {\n if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);\n if (a.render != null)\n return h(\"li.column-header-control\", { key: a.id ?? i }, a.render(actionCtx));\n return h(MenuItem, {\n key: a.id ?? i,\n icon: a.icon,\n intent: a.intent,\n text: a.name,\n onClick: () => a.run?.(actionCtx),\n });\n })\n .filter(Boolean);\n\n if (items.length === 0) {\n return h(Menu, [h(MenuItem, { text: \"No options\", disabled: true })]);\n }\n\n return h(Menu, { className: \"column-header-controls\" }, items);\n}\n"],"names":["h","ColumnHeaderCell","Icon","useStoreAPI","ctx","tableActionsAtom","buildActionContext","RegionCardinality","MenuItem","Menu"],"mappings":";;;;;;;;;AAmCO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA8B;AAC5B,QAAM,aAAa,IAAI,aAAa;AACpC,QAAM,eACJ,IAAI,eAAe,QACnB,OAAO,IAAI,eAAe,YACzB,MAAM,QAAQ,IAAI,OAAO,KAAK,IAAI,QAAQ,SAAS;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AEQ,KAAAA,UAAU;AAAA,MACjB,KAAK,EAAE,MAAM;AAAA,MACb,MAAM,EAAE;AAAA,MACR,QAAQ,EAAE;AAAA,MACV,MAAM,EAAE;AAAA,MACR,SAAS,MAAM,EAAE,MAAM,SAAS;AAAA,IAAA,CACjC;AAAA,EACH,CAAC,EACA,OAAO,OAAO;AAEjB,MAAI,MAAM,WAAW,GAAG;AACtB,WAAOR,mBAAES,KAAAA,MAAM,CAACT,WAAAA,QAAEQ,KAAAA,UAAU,EAAE,MAAM,cAAc,UAAU,KAAA,CAAM,CAAC,CAAC;AAAA,EACtE;AAEA,SAAOR,WAAAA,QAAES,KAAAA,MAAM,EAAE,WAAW,yBAAA,GAA4B,KAAK;AAC/D;;"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { ColumnHeaderCell } from '@blueprintjs/table';
|
|
2
1
|
import { ColumnSpec } from '../utils/column-spec';
|
|
3
2
|
import { PostgrestColumnFilter, ColumnSortEntry } from '../postgrest-table';
|
|
4
3
|
export interface ColumnActionsConfig {
|
|
@@ -12,4 +11,4 @@ export interface ColumnHeaderRendererProps extends ColumnActionsConfig {
|
|
|
12
11
|
/** Column header cell whose dropdown renders the `FULL_COLUMNS` controls
|
|
13
12
|
* (sort/filter + any custom column actions) from the shared action registry,
|
|
14
13
|
* scoped to this column. */
|
|
15
|
-
export declare function renderColumnHeaderCell({ col, colIndex, activeSort, activeFilter, }: ColumnHeaderRendererProps): import('react').DetailedReactHTMLElement<import('react').InputHTMLAttributes<HTMLInputElement>, HTMLInputElement
|
|
14
|
+
export declare function renderColumnHeaderCell({ col, colIndex, activeSort, activeFilter, }: ColumnHeaderRendererProps): import('react').DetailedReactHTMLElement<import('react').InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import h from "@macrostrat/hyper";
|
|
2
2
|
import { ColumnHeaderCell, RegionCardinality } from "@blueprintjs/table";
|
|
3
|
-
import {
|
|
3
|
+
import { Icon, MenuItem, Menu } from "@blueprintjs/core";
|
|
4
4
|
import { useStoreAPI, ctx, tableActionsAtom } from "../provider.js";
|
|
5
5
|
import { buildActionContext } from "../actions/selection.js";
|
|
6
6
|
function renderColumnHeaderCell({
|
|
@@ -12,13 +12,24 @@ function renderColumnHeaderCell({
|
|
|
12
12
|
const isSortable = col.sortable === true;
|
|
13
13
|
const isFilterable = col.filterable === true || typeof col.filterable === "object" || Array.isArray(col.filters) && col.filters.length > 0;
|
|
14
14
|
const hasCustomActions = Array.isArray(col.actions) && col.actions.length > 0;
|
|
15
|
+
const enableColumnReordering = col.reorderable !== false;
|
|
15
16
|
if (!isSortable && !isFilterable && !hasCustomActions) {
|
|
16
|
-
return h(ColumnHeaderCell, {
|
|
17
|
+
return h(ColumnHeaderCell, {
|
|
18
|
+
name: col.name,
|
|
19
|
+
enableColumnReordering,
|
|
20
|
+
nameRenderer: () => h(ColumnHeaderName, {
|
|
21
|
+
col,
|
|
22
|
+
hasSortActive: false,
|
|
23
|
+
hasFilterActive: false,
|
|
24
|
+
activeSort: null
|
|
25
|
+
})
|
|
26
|
+
});
|
|
17
27
|
}
|
|
18
28
|
const hasFilterActive = activeFilter != null;
|
|
19
29
|
const hasSortActive = activeSort != null;
|
|
20
30
|
return h(ColumnHeaderCell, {
|
|
21
31
|
name: col.name,
|
|
32
|
+
enableColumnReordering,
|
|
22
33
|
// Persistent interaction bar so the menu caret is always clickable — the
|
|
23
34
|
// hover-triggered caret was blocked by the selection overlay when the
|
|
24
35
|
// column was selected.
|
|
@@ -30,7 +41,10 @@ function renderColumnHeaderCell({
|
|
|
30
41
|
function ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {
|
|
31
42
|
return h(
|
|
32
43
|
"div",
|
|
33
|
-
{
|
|
44
|
+
{
|
|
45
|
+
"data-column-key": col.key,
|
|
46
|
+
style: { display: "flex", alignItems: "center", width: "100%" }
|
|
47
|
+
},
|
|
34
48
|
[
|
|
35
49
|
h(
|
|
36
50
|
"span",
|
|
@@ -64,7 +78,7 @@ function ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {
|
|
|
64
78
|
h.if(hasFilterActive)(Icon, {
|
|
65
79
|
icon: "filter",
|
|
66
80
|
size: 12,
|
|
67
|
-
style: { color: "var(--intent-
|
|
81
|
+
style: { color: "var(--intent-primary, #2965cc)" }
|
|
68
82
|
})
|
|
69
83
|
]
|
|
70
84
|
)
|
|
@@ -81,39 +95,26 @@ function ColumnHeaderControls({ colIndex }) {
|
|
|
81
95
|
},
|
|
82
96
|
storeAPI.setState
|
|
83
97
|
);
|
|
98
|
+
const isGlobal = (a) => a.targets.includes(RegionCardinality.FULL_TABLE) || a.targets.includes("none");
|
|
84
99
|
const controls = actions.filter(
|
|
85
|
-
(a) => a.targets.includes(RegionCardinality.FULL_COLUMNS) && (a.appliesTo?.(actionCtx) ?? true)
|
|
100
|
+
(a) => a.targets.includes(RegionCardinality.FULL_COLUMNS) && !isGlobal(a) && (a.appliesTo?.(actionCtx) ?? true)
|
|
86
101
|
);
|
|
87
|
-
const
|
|
88
|
-
(a
|
|
89
|
-
|
|
90
|
-
{
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
).filter(Boolean);
|
|
101
|
-
if (rendered.length === 0) {
|
|
102
|
+
const items = controls.map((a, i) => {
|
|
103
|
+
if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);
|
|
104
|
+
if (a.render != null)
|
|
105
|
+
return h("li.column-header-control", { key: a.id ?? i }, a.render(actionCtx));
|
|
106
|
+
return h(MenuItem, {
|
|
107
|
+
key: a.id ?? i,
|
|
108
|
+
icon: a.icon,
|
|
109
|
+
intent: a.intent,
|
|
110
|
+
text: a.name,
|
|
111
|
+
onClick: () => a.run?.(actionCtx)
|
|
112
|
+
});
|
|
113
|
+
}).filter(Boolean);
|
|
114
|
+
if (items.length === 0) {
|
|
102
115
|
return h(Menu, [h(MenuItem, { text: "No options", disabled: true })]);
|
|
103
116
|
}
|
|
104
|
-
return h(
|
|
105
|
-
"div.column-header-controls",
|
|
106
|
-
{
|
|
107
|
-
style: {
|
|
108
|
-
padding: "8px",
|
|
109
|
-
display: "flex",
|
|
110
|
-
flexDirection: "column",
|
|
111
|
-
gap: "6px",
|
|
112
|
-
alignItems: "flex-start"
|
|
113
|
-
}
|
|
114
|
-
},
|
|
115
|
-
rendered
|
|
116
|
-
);
|
|
117
|
+
return h(Menu, { className: "column-header-controls" }, items);
|
|
117
118
|
}
|
|
118
119
|
export {
|
|
119
120
|
renderColumnHeaderCell
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-header-cell.js","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport {
|
|
1
|
+
{"version":3,"file":"column-header-cell.js","sources":["../../src/renderers/column-header-cell.ts"],"sourcesContent":["/**\n * Column header with client-side sort and filter controls.\n *\n * Mirrors the PostgREST column header UX but operates on in-memory data.\n * Sort state is stored in the DataSheet zustand store; filtering uses the\n * existing `setFilter` / `removeFilter` mechanism with auto-generated\n * predicate filters for simple text search.\n */\nimport h from \"@macrostrat/hyper\";\nimport { ColumnHeaderCell, RegionCardinality } from \"@blueprintjs/table\";\nimport { Icon, Menu, MenuItem } from \"@blueprintjs/core\";\nimport { ctx, tableActionsAtom, useStoreAPI } from \"../provider\";\nimport { buildActionContext } from \"../actions/selection\";\nimport type { ColumnSpec } from \"../utils/column-spec\";\nimport type {\n PostgrestColumnFilter,\n ColumnSortEntry,\n} from \"../postgrest-table\";\n\nexport interface ColumnActionsConfig {\n activeSort?: ColumnSortEntry | null;\n activeFilter?: PostgrestColumnFilter | null;\n}\n\nexport interface ColumnHeaderRendererProps extends ColumnActionsConfig {\n col: ColumnSpec;\n colIndex: number;\n //actions: ColumnHeaderActions;\n}\n\n// ---- Column header cell ----\n\n/** Column header cell whose dropdown renders the `FULL_COLUMNS` controls\n * (sort/filter + any custom column actions) from the shared action registry,\n * scoped to this column. */\nexport function renderColumnHeaderCell({\n col,\n colIndex,\n activeSort,\n activeFilter,\n}: ColumnHeaderRendererProps) {\n const isSortable = col.sortable === true;\n const isFilterable =\n col.filterable === true ||\n typeof col.filterable === \"object\" ||\n (Array.isArray(col.filters) && col.filters.length > 0);\n const hasCustomActions =\n Array.isArray((col as any).actions) && (col as any).actions.length > 0;\n\n // A column may be pinned against drag-reordering via `reorderable: false`.\n const enableColumnReordering = col.reorderable !== false;\n\n if (!isSortable && !isFilterable && !hasCustomActions) {\n return h(ColumnHeaderCell, {\n name: col.name,\n enableColumnReordering,\n nameRenderer: () =>\n h(ColumnHeaderName, {\n col,\n hasSortActive: false,\n hasFilterActive: false,\n activeSort: null,\n }),\n });\n }\n\n // `activeFilter` is the active store entry targeting this column (any filter\n // type), or null — so the indicator lights for rich and operator filters.\n const hasFilterActive = activeFilter != null;\n const hasSortActive = activeSort != null;\n\n return h(ColumnHeaderCell, {\n name: col.name,\n enableColumnReordering,\n // Persistent interaction bar so the menu caret is always clickable — the\n // hover-triggered caret was blocked by the selection overlay when the\n // column was selected.\n enableColumnInteractionBar: true,\n nameRenderer: () =>\n h(ColumnHeaderName, { col, hasSortActive, hasFilterActive, activeSort }),\n menuRenderer: () => h(ColumnHeaderControls, { colIndex }),\n });\n}\n\n/** Column name with active sort/filter indicator icons. The column key is\n * exposed as `data-column-key` so consumers can target a specific header from\n * CSS (e.g. to tint a column) without a bespoke styling prop. */\nfunction ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {\n return h(\n \"div\",\n {\n \"data-column-key\": col.key,\n style: { display: \"flex\", alignItems: \"center\", width: \"100%\" },\n },\n [\n h(\n \"span\",\n {\n style: {\n flex: 1,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n },\n },\n col.name,\n ),\n h.if(hasSortActive || hasFilterActive)(\n \"span\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"2px\",\n marginLeft: \"4px\",\n flexShrink: 0,\n },\n },\n [\n h.if(hasSortActive)(Icon, {\n icon: activeSort?.ascending ? \"sort-asc\" : \"sort-desc\",\n size: 12,\n style: { color: \"var(--intent-primary, #2965cc)\" },\n }),\n h.if(hasFilterActive)(Icon, {\n icon: \"filter\",\n size: 12,\n style: { color: \"var(--intent-primary, #2965cc)\" },\n }),\n ],\n ),\n ],\n );\n}\n\n/** Dropdown content: the `FULL_COLUMNS` controls for this column, sourced from\n * the shared action registry and scoped to the column via a synthetic\n * single-column selection context — so the header and toolbar render the same\n * sort/filter (and custom column) controls. */\nfunction ColumnHeaderControls({ colIndex }: { colIndex: number }) {\n const storeAPI = useStoreAPI();\n const actions = ctx.useValue(tableActionsAtom);\n\n // Scope the action context to this column (as if it were the selection).\n const actionCtx = buildActionContext(\n {\n ...storeAPI.getState(),\n selection: [{ cols: [colIndex, colIndex], rows: undefined }],\n } as any,\n storeAPI.setState,\n );\n\n // Only actions *limited* to column scope belong in a column's dropdown —\n // sort/filter and column-specific actions. Global actions (Save / Reset /\n // Clear-selection, marked by a FULL_TABLE or \"none\" target) are confusing\n // here, so they're excluded even though they nominally apply to columns too.\n const isGlobal = (a: (typeof actions)[number]) =>\n a.targets.includes(RegionCardinality.FULL_TABLE) ||\n a.targets.includes(\"none\" as any);\n const controls = actions.filter(\n (a) =>\n a.targets.includes(RegionCardinality.FULL_COLUMNS) &&\n !isGlobal(a) &&\n (a.appliesTo?.(actionCtx) ?? true),\n );\n\n // Prefer menu-native rendering (`renderMenuItem`) — sort/filter render as\n // items with submenus, so the whole dropdown is one Blueprint `Menu`. A\n // control that only has `render` (a live toolbar control) is embedded as-is;\n // a plain `run` action becomes a clickable item.\n const items = controls\n .map((a, i) => {\n if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);\n if (a.render != null)\n return h(\"li.column-header-control\", { key: a.id ?? i }, a.render(actionCtx));\n return h(MenuItem, {\n key: a.id ?? i,\n icon: a.icon,\n intent: a.intent,\n text: a.name,\n onClick: () => a.run?.(actionCtx),\n });\n })\n .filter(Boolean);\n\n if (items.length === 0) {\n return h(Menu, [h(MenuItem, { text: \"No options\", disabled: true })]);\n }\n\n return h(Menu, { className: \"column-header-controls\" }, items);\n}\n"],"names":[],"mappings":";;;;;AAmCO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA8B;AAC5B,QAAM,aAAa,IAAI,aAAa;AACpC,QAAM,eACJ,IAAI,eAAe,QACnB,OAAO,IAAI,eAAe,YACzB,MAAM,QAAQ,IAAI,OAAO,KAAK,IAAI,QAAQ,SAAS;AACtD,QAAM,mBACJ,MAAM,QAAS,IAAY,OAAO,KAAM,IAAY,QAAQ,SAAS;AAGvE,QAAM,yBAAyB,IAAI,gBAAgB;AAEnD,MAAI,CAAC,cAAc,CAAC,gBAAgB,CAAC,kBAAkB;AACrD,WAAO,EAAE,kBAAkB;AAAA,MACzB,MAAM,IAAI;AAAA,MACV;AAAA,MACA,cAAc,MACZ,EAAE,kBAAkB;AAAA,QAClB;AAAA,QACA,eAAe;AAAA,QACf,iBAAiB;AAAA,QACjB,YAAY;AAAA,MAAA,CACb;AAAA,IAAA,CACJ;AAAA,EACH;AAIA,QAAM,kBAAkB,gBAAgB;AACxC,QAAM,gBAAgB,cAAc;AAEpC,SAAO,EAAE,kBAAkB;AAAA,IACzB,MAAM,IAAI;AAAA,IACV;AAAA;AAAA;AAAA;AAAA,IAIA,4BAA4B;AAAA,IAC5B,cAAc,MACZ,EAAE,kBAAkB,EAAE,KAAK,eAAe,iBAAiB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;AAAA,IAE7D,SAAS;AAAA,EAAA;AAOX,QAAM,WAAW,CAAC,MAChB,EAAE,QAAQ,SAAS,kBAAkB,UAAU,KAC/C,EAAE,QAAQ,SAAS,MAAa;AAClC,QAAM,WAAW,QAAQ;AAAA,IACvB,CAAC,MACC,EAAE,QAAQ,SAAS,kBAAkB,YAAY,KACjD,CAAC,SAAS,CAAC,MACV,EAAE,YAAY,SAAS,KAAK;AAAA,EAAA;AAOjC,QAAM,QAAQ,SACX,IAAI,CAAC,GAAG,MAAM;AACb,QAAI,EAAE,kBAAkB,KAAM,QAAO,EAAE,eAAe,SAAS;AAC/D,QAAI,EAAE,UAAU;AACd,aAAO,EAAE,4BAA4B,EAAE,KAAK,EAAE,MAAM,KAAK,EAAE,OAAO,SAAS,CAAC;AAC9E,WAAO,EAAE,UAAU;AAAA,MACjB,KAAK,EAAE,MAAM;AAAA,MACb,MAAM,EAAE;AAAA,MACR,QAAQ,EAAE;AAAA,MACV,MAAM,EAAE;AAAA,MACR,SAAS,MAAM,EAAE,MAAM,SAAS;AAAA,IAAA,CACjC;AAAA,EACH,CAAC,EACA,OAAO,OAAO;AAEjB,MAAI,MAAM,WAAW,GAAG;AACtB,WAAO,EAAE,MAAM,CAAC,EAAE,UAAU,EAAE,MAAM,cAAc,UAAU,KAAA,CAAM,CAAC,CAAC;AAAA,EACtE;AAEA,SAAO,EAAE,MAAM,EAAE,WAAW,yBAAA,GAA4B,KAAK;AAC/D;"}
|
package/dist/types.cjs
CHANGED
|
@@ -5,7 +5,18 @@ var TableElementStatus = /* @__PURE__ */ ((TableElementStatus2) => {
|
|
|
5
5
|
TableElementStatus2["ADDED"] = "added";
|
|
6
6
|
return TableElementStatus2;
|
|
7
7
|
})(TableElementStatus || {});
|
|
8
|
+
const DEFAULT_ROW_STATUS_STYLES = {
|
|
9
|
+
[
|
|
10
|
+
"deleted"
|
|
11
|
+
/* DELETED */
|
|
12
|
+
]: {
|
|
13
|
+
cellStyle: { opacity: 0.5, textDecoration: "line-through" },
|
|
14
|
+
headerStyle: { opacity: 0.5, textDecoration: "line-through" },
|
|
15
|
+
intent: "danger"
|
|
16
|
+
}
|
|
17
|
+
};
|
|
8
18
|
const DS_ROW_ID = "__dsRowId";
|
|
19
|
+
exports.DEFAULT_ROW_STATUS_STYLES = DEFAULT_ROW_STATUS_STYLES;
|
|
9
20
|
exports.DS_ROW_ID = DS_ROW_ID;
|
|
10
21
|
exports.TableElementStatus = TableElementStatus;
|
|
11
22
|
//# sourceMappingURL=types.cjs.map
|
package/dist/types.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sources":["../src/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport { ColumnSpec, ColumnSpecOptions } from \"./utils\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport type { CellEdit } from \"./actions\";\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 interface DataSheetCoreProps<T> {\n data: T[];\n columnSpec?: ColumnSpec[];\n editable?: boolean;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n}\n\nexport enum TableElementStatus {\n DELETED = \"deleted\",\n ADDED = \"added\",\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 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: TableElementStatus[];\n // Sparse data structure for updated data\n updatedData: 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}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<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>;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n}\n\nexport type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {\n children: React.ReactNode;\n columnSpecOptions?: ColumnSpecOptions<T>;\n toaster?: OverlayToaster;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n"],"names":["TableElementStatus"],"mappings":";;AA0CO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,SAAA,IAAU;AACVA,sBAAA,OAAA,IAAQ;AAFE,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AAQL,MAAM,YAAY;;;"}
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":["../src/types.ts"],"sourcesContent":["import type {\n FocusedCellCoordinates,\n Region,\n RegionCardinality,\n Table2,\n} from \"@blueprintjs/table\";\nimport { ColumnSpec, ColumnSpecOptions } from \"./utils\";\nimport { OverlayToaster } from \"@blueprintjs/core\";\nimport type { CellEdit } from \"./actions\";\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 interface DataSheetCoreProps<T> {\n data: T[];\n /** Column definitions. Either a static array, or a function derived from the\n * loaded rows — invoked once the first rows arrive (and re-invoked when the\n * function's identity changes), so a data-shaped spec needs no separate fetch\n * of sample data. Omit entirely to auto-generate a plain spec via\n * `columnSpecOptions`. */\n columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);\n editable?: boolean;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n}\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 /** 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[];\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[];\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}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<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>;\n columnWidthsIndex: Map<string, number>;\n defaultColumnWidth: number;\n}\n\nexport type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {\n children: React.ReactNode;\n columnSpecOptions?: ColumnSpecOptions<T>;\n toaster?: OverlayToaster;\n};\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nexport type DataSheetStore<T> = DataSheetStoreMain<T>;\n"],"names":["TableElementStatus"],"mappings":";;AA+CO,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;;;;"}
|