@macrostrat/data-sheet 4.2.1 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/dist/actions/types.d.ts +10 -0
  3. package/dist/components/indicators/filter-and-sort.cjs +47 -6
  4. package/dist/components/indicators/filter-and-sort.cjs.map +1 -1
  5. package/dist/components/indicators/filter-and-sort.d.ts +28 -6
  6. package/dist/components/indicators/filter-and-sort.js +48 -7
  7. package/dist/components/indicators/filter-and-sort.js.map +1 -1
  8. package/dist/components/indicators/filter-and-sort.module.sass.cjs +5 -3
  9. package/dist/components/indicators/filter-and-sort.module.sass.cjs.map +1 -1
  10. package/dist/components/indicators/filter-and-sort.module.sass.js +5 -3
  11. package/dist/components/indicators/filter-and-sort.module.sass.js.map +1 -1
  12. package/dist/components/indicators/unified-filters.cjs +36 -22
  13. package/dist/components/indicators/unified-filters.cjs.map +1 -1
  14. package/dist/components/indicators/unified-filters.d.ts +10 -8
  15. package/dist/components/indicators/unified-filters.js +37 -23
  16. package/dist/components/indicators/unified-filters.js.map +1 -1
  17. package/dist/components/indicators/view-info.cjs +6 -0
  18. package/dist/components/indicators/view-info.cjs.map +1 -1
  19. package/dist/components/indicators/view-info.d.ts +2 -2
  20. package/dist/components/indicators/view-info.js +7 -1
  21. package/dist/components/indicators/view-info.js.map +1 -1
  22. package/dist/components/toolbars/actions-toolbar.cjs +7 -1
  23. package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
  24. package/dist/components/toolbars/actions-toolbar.js +7 -1
  25. package/dist/components/toolbars/actions-toolbar.js.map +1 -1
  26. package/dist/data-panel.cjs +51 -6
  27. package/dist/data-panel.cjs.map +1 -1
  28. package/dist/data-panel.d.ts +1 -1
  29. package/dist/data-panel.js +52 -7
  30. package/dist/data-panel.js.map +1 -1
  31. package/dist/data-panel.module.sass.cjs +24 -21
  32. package/dist/data-panel.module.sass.cjs.map +1 -1
  33. package/dist/data-panel.module.sass.js +24 -21
  34. package/dist/data-panel.module.sass.js.map +1 -1
  35. package/dist/data-sheet.cjs +3 -1
  36. package/dist/data-sheet.cjs.map +1 -1
  37. package/dist/data-sheet.css +56 -35
  38. package/dist/data-sheet.d.ts +1 -1
  39. package/dist/data-sheet.js +3 -1
  40. package/dist/data-sheet.js.map +1 -1
  41. package/dist/index.cjs +2 -0
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.js +3 -1
  44. package/dist/postgrest-table/data-loaders.cjs +20 -3
  45. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  46. package/dist/postgrest-table/data-loaders.d.ts +10 -0
  47. package/dist/postgrest-table/data-loaders.js +21 -4
  48. package/dist/postgrest-table/data-loaders.js.map +1 -1
  49. package/dist/provider/core.cjs +27 -56
  50. package/dist/provider/core.cjs.map +1 -1
  51. package/dist/provider/core.d.ts +7 -9
  52. package/dist/provider/core.js +19 -48
  53. package/dist/provider/core.js.map +1 -1
  54. package/dist/provider/interactions.d.ts +1 -1
  55. package/dist/provider/selection.d.ts +1 -1
  56. package/dist/types.cjs.map +1 -1
  57. package/dist/types.d.ts +4 -0
  58. package/dist/types.js.map +1 -1
  59. package/package.json +5 -6
  60. package/src/actions/types.ts +11 -0
  61. package/src/components/indicators/filter-and-sort.module.sass +7 -0
  62. package/src/components/indicators/filter-and-sort.ts +71 -11
  63. package/src/components/indicators/unified-filters.ts +66 -29
  64. package/src/components/indicators/view-info.ts +10 -0
  65. package/src/components/toolbars/actions-toolbar.ts +10 -1
  66. package/src/data-panel.module.sass +18 -1
  67. package/src/data-panel.ts +65 -6
  68. package/src/data-sheet.ts +2 -0
  69. package/src/postgrest-table/data-loaders.ts +40 -4
  70. package/src/provider/core.ts +29 -53
  71. package/src/types.ts +4 -0
@@ -1 +1 @@
1
- {"version":3,"file":"data-loaders.js","sources":["../../src/postgrest-table/data-loaders.ts"],"sourcesContent":["/** Lazy loading of data from a PostgREST endpoint */\n\nimport { useAsyncEffect } from \"@macrostrat/ui-components\";\nimport { debounce } from \"underscore\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n ClientServerOptions,\n PostgrestClient,\n PostgrestFilterBuilder,\n PostgrestQueryBuilder,\n} from \"@supabase/postgrest-js\";\nimport { adjustArraySize, RowRegion } from \"./loading-utils.ts\";\nimport {\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataFilter,\n tableDataAtom,\n TableDataProvider,\n useSelector,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { FetchDataOptions, FetchMode } from \"../types.ts\";\n\ninterface 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\ninterface LazyLoaderState<T> extends LazyLoaderStateCore<T> {\n data: (T | null)[];\n visibleRegion: RowRegion;\n}\n\nexport interface PostgrestOrder<T> {\n key: string;\n ascending?: boolean;\n nullsFirst?: boolean;\n}\n\n/** Operators available for server-side column filtering via PostgREST.\n * `cs`/`ov` target array columns (contains / overlaps). */\nexport type PostgrestFilterOperator =\n | \"eq\"\n | \"neq\"\n | \"like\"\n | \"ilike\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"is\"\n | \"cs\"\n | \"ov\";\n\n/** A single column sort entry. */\nexport interface ColumnSortEntry {\n key: string;\n ascending: boolean;\n}\n\n/** A single column filter entry. */\nexport interface PostgrestColumnFilter {\n key: string;\n operator: PostgrestFilterOperator;\n value: string;\n}\n\nexport interface PostgrestFilter {\n id?: string;\n type: \"filter\";\n apply(\n req: PostgrestFilterBuilder<any, any, any, any>,\n ): PostgrestFilterBuilder<any, any, any, any>;\n}\n\nexport function standardizeFilter(\n columnFilter: PostgrestColumnFilter,\n): PostgrestFilter {\n return {\n type: \"filter\",\n apply(req) {\n return applyColumnFilters(req, [columnFilter]);\n },\n };\n}\n\nexport function applyColumnFilters(\n req: PostgrestFilterBuilder<any, any, any, any>,\n filters: PostgrestColumnFilter[],\n) {\n for (const cf of filters) {\n if (cf.value === \"\" || cf.value == null) continue;\n // Array-column operators need a list value and postgrest-js's dedicated\n // builders (which emit the `{…}` array literal), not a scalar `.filter`.\n if (cf.operator === \"cs\") {\n req = req.contains(cf.key, splitFilterList(cf.value));\n continue;\n }\n if (cf.operator === \"ov\") {\n req = req.overlaps(cf.key, splitFilterList(cf.value));\n continue;\n }\n const val =\n cf.operator === \"like\" || cf.operator === \"ilike\"\n ? `*${cf.value}*`\n : cf.value;\n req = req.filter(cf.key, cf.operator, val);\n }\n return req;\n}\n\n/** Split a comma-separated filter value into trimmed, non-empty tokens (the set\n * for `cs`/`ov`); a single value yields a one-element list. */\nfunction splitFilterList(value: any): string[] {\n return String(value)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n}\n\ntype LazyLoaderAction<T> =\n | { type: \"start-loading\" }\n | {\n type: \"loaded\";\n data: T[];\n offset: number;\n totalSize: number;\n totalCount?: number | null;\n }\n | { type: \"error\"; error: Error }\n | { type: \"update-data\"; changes: Spec<T[]> }\n | { type: \"reset\" }\n | { type: \"configure\"; fetchMode: FetchMode; pageSize: number };\n\nfunction lazyLoadingReducer<T>(\n state: LazyLoaderState<T>,\n action: LazyLoaderAction<T>,\n): LazyLoaderState<T> {\n switch (action.type) {\n case \"start-loading\":\n return {\n ...state,\n loading: true,\n initialized: true,\n };\n case \"update-data\":\n return {\n ...state,\n loading: false,\n data: update(state.data, action.changes as any),\n };\n case \"loaded\":\n let data = adjustArraySize(state.data, action.totalSize);\n const newData = action.data ?? [];\n const offset = action.offset ?? 0;\n data = [\n ...data.slice(0, offset),\n ...newData,\n ...data.slice(offset + newData.length),\n ];\n return {\n ...state,\n data,\n loading: false,\n totalCount:\n action.totalCount !== undefined\n ? action.totalCount\n : state.totalCount,\n };\n case \"configure\":\n return {\n ...state,\n fetchMode: action.fetchMode,\n pageSize: action.pageSize,\n };\n case \"reset\":\n // A view change (or initial load) re-fetches from scratch. Rather than\n // blanking the table (which reads as a jarring empty flash while the\n // request is in flight — very visible on sort/filter), pre-size to a page\n // of `null` ghost/skeleton rows so the body stays populated and the load\n // is legible. `loaded` then adjusts the array to the real size.\n return {\n visibleRegion: defaultVisibleRegion,\n data: new Array(Math.max(state.pageSize, 0)).fill(null),\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: state.fetchMode,\n pageSize: state.pageSize,\n };\n case \"error\":\n return {\n ...state,\n error: action.error,\n loading: false,\n };\n default:\n return state;\n }\n}\n\ntype SortAndFilterOptions = {\n /** Column-level sort state, managed externally. When provided, overrides\n * the `order` prop for query building. */\n order?: PostgrestOrder<any>[];\n filters?: PostgrestFilter[];\n};\n\ninterface QueryConfig extends SortAndFilterOptions {\n columns?: string | string[];\n count?: \"exact\" | \"estimated\";\n limit?: number;\n identityKey: string;\n /** The identity column's default ordering (used when nothing in `order`\n * already sorts it). A string ⇒ ascending; pass a `PostgrestOrder` to set the\n * direction (e.g. `source_id` descending). */\n identityOrder?: PostgrestOrder<any>;\n lastLoadedRow?: any;\n lastLoadedRowIndex: number;\n}\n\n/** Format a value for a PostgREST logic-tree condition. Reserved characters\n * (`, . : ( )`), spaces, quotes, and backslashes require the value to be\n * double-quoted, with `\"` and `\\` backslash-escaped inside — otherwise a map\n * name containing a comma would break the `or=(...)` parse. */\nfunction formatKeysetValue(v: any): string {\n const s = String(v);\n if (s === \"\" || /[,.:()\"\\\\ ]/.test(s)) {\n return `\"${s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n }\n return s;\n}\n\n/** An equality condition for the cursor prefix (`col.eq.v`, or `col.is.null`). */\nfunction keysetEq(key: string, v: any): string {\n return v == null ? `${key}.is.null` : `${key}.eq.${formatKeysetValue(v)}`;\n}\n\n/**\n * Build the compound keyset predicate (the body of an `or=(...)`) selecting\n * rows strictly after `lastRow` under `clauses` (lexicographic, last clause is\n * the identity tiebreaker):\n *\n * (c1 OP1 v1)\n * OR (c1 = v1 AND c2 OP2 v2)\n * OR (c1 = v1 AND c2 = v2 AND c3 OP3 v3) …\n *\n * `OPi` is `gt` for an ascending clause, `lt` for descending. Nulls-last: a\n * null pivot value has no strictly-ordered non-null successor at its level, so\n * that term is skipped and the tie defers to deeper clauses (the identity key\n * is non-null, so at least its term is always emitted). Returns `null` if no\n * term applies. (Known limit: rows whose *sort* column is null aren't picked up\n * across the non-null→null boundary — an edge for nullable sort columns; the\n * non-null identity tiebreaker keeps pagination from stalling.)\n */\nfunction buildKeysetPredicate(\n clauses: PostgrestOrder<any>[],\n lastRow: any,\n): string | null {\n const terms: string[] = [];\n for (let i = 0; i < clauses.length; i++) {\n const v = lastRow[clauses[i].key];\n if (v == null) continue;\n const conds: string[] = [];\n for (let j = 0; j < i; j++) {\n conds.push(keysetEq(clauses[j].key, lastRow[clauses[j].key]));\n }\n const op = (clauses[i].ascending ?? true) ? \"gt\" : \"lt\";\n conds.push(`${clauses[i].key}.${op}.${formatKeysetValue(v)}`);\n terms.push(conds.length === 1 ? conds[0] : `and(${conds.join(\",\")})`);\n }\n return terms.length > 0 ? terms.join(\",\") : null;\n}\n\nfunction buildQuery<T>(\n client: PostgrestQueryBuilder<any, any, any>,\n config: QueryConfig,\n) {\n const { columns = \"*\", count, lastLoadedRowIndex } = config;\n const opts = { count };\n\n let cols: string;\n if (Array.isArray(columns)) {\n cols = columns.join(\", \");\n } else {\n cols = columns ?? \"*\";\n }\n\n let query = client.select(cols, opts);\n\n const filters = config.filters ?? [];\n for (const filter of filters) {\n query = filter.apply(query);\n }\n\n const orderClauses = buildPostgrestOrderClauses(\n config.order ?? [],\n config.identityOrder ?? config.identityKey,\n );\n\n let hasOrdering = false;\n for (const clause of orderClauses) {\n query = query.order(clause.key, clause);\n hasOrdering = true;\n }\n\n // Keyset cursor: rows strictly after the last loaded row under the active\n // ordering. This MUST be a compound predicate, not an independent `gt`/`lt`\n // per column: with a leading low-cardinality sort (e.g. `state`), a plain\n // `state.gt.X AND source_id.lt.Y` drops every row sharing the cursor's\n // `state` (`state.gt.X` is false for them). The lexicographic form keeps the\n // tie broken by the next column, ending on the non-null identity key.\n if (config.lastLoadedRow != null && hasOrdering) {\n const pred = buildKeysetPredicate(orderClauses, config.lastLoadedRow);\n if (pred != null) query = query.or(pred);\n }\n\n let offset: number | null = null;\n if (!hasOrdering && lastLoadedRowIndex > 0) {\n // We need to load based on offsets\n offset = lastLoadedRowIndex + 1;\n }\n\n if (config.limit != null) {\n if (offset != null) {\n query = query.range(offset, offset + config.limit - 1);\n console.log(`Random seek from ${offset}, this will be slow`);\n } else {\n query = query.limit(config.limit);\n }\n }\n\n return query;\n}\n\nconst defaultVisibleRegion: RowRegion = {\n rowIndexStart: 0,\n rowIndexEnd: 0,\n};\n\n/** Atom to house the current visible region of the table */\nconst visibleRegionAtom = atom<RowRegion>(defaultVisibleRegion);\n\nconst lazyLoaderCoreStateAtom = atom<LazyLoaderStateCore<any>>({\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n});\n\n/** Current page index (0-based) for paged fetch mode. */\nexport const chunkPageAtom = atom(0);\n\n/** Footer state for the optional bottom-of-table indicator: rows loaded, the\n * source total when known, load status, and — in paged mode — the current\n * page and total pages. */\nexport interface TableFooterInfo {\n mode: FetchMode;\n loaded: number;\n total: number | null;\n loading: boolean;\n page: number;\n pageSize: number;\n totalPages: number | null;\n}\n\nexport const tableFooterAtom = atom<TableFooterInfo>((get) => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom) ?? [];\n let loaded = 0;\n let hasGaps = false;\n for (const row of data) {\n if (row != null) loaded++;\n else hasGaps = true;\n }\n // Total is known when the source reported it, or (scroll mode) when the array\n // is fully populated — otherwise it's still being discovered.\n const total = core.totalCount ?? (hasGaps ? null : data.length);\n const totalPages =\n core.totalCount != null ? Math.ceil(core.totalCount / core.pageSize) : null;\n return {\n mode: core.fetchMode,\n loaded,\n total,\n loading: core.loading,\n page: get(chunkPageAtom),\n pageSize: core.pageSize,\n totalPages,\n };\n});\n\n/** Auto-load this many pages per burst, then pause (null ⇒ unbounded). Set by\n * a consumer (e.g. `DataPanel`'s `autoLoadPages` prop). */\nexport const autoLoadPagesAtom = atom<number | null>(null);\n\n/** Row count at the last manual \"load more\" — the point auto-load resumes\n * counting a fresh burst from. */\nexport const resumeBaselineAtom = atom(0);\n\n/** Live loading controls, read from the store rather than passed down a\n * boundary contract. Any component inside the provider can call\n * `useLoadControls()` — a footer, a toolbar button, a status line — without the\n * renderer wiring a specific prop shape to it. */\nexport interface LoadControls {\n /** Load the next page and resume auto-loading (clears a paused state). */\n loadMore: () => void;\n /** A fetch is in flight. */\n loading: boolean;\n /** More rows remain to load. */\n hasMore: boolean;\n /** Rows loaded so far. */\n loaded: number;\n /** Source total when known, else `null`. */\n total: number | null;\n /** Auto-load is paused at the `autoLoadPages` checkpoint. */\n paused: boolean;\n /** Auto-load is currently permitted (`hasMore && !loading && !paused`) —\n * used to gate an infinite-scroll sentinel. */\n canLoadMore: boolean;\n /** Advance one page *without* resuming a paused auto-load (the sentinel\n * uses this; `loadMore` is the manual, un-pausing variant). */\n advance: () => void;\n}\n\n/** Store-managed load controls (see `LoadControls`). Reads the loader's footer\n * state, the loaded rows, and the pause atoms; `loadMore`/`advance` set the\n * visible region so the loader fetches the next chunk. */\nexport function useLoadControls(): LoadControls {\n const footer = ctx.useValue(tableFooterAtom);\n const data = ctx.useValue(tableDataAtom) ?? [];\n const { isLocalProvider } = ctx.useValue(dataProviderAtom);\n const resumeBaseline = ctx.useValue(resumeBaselineAtom);\n const autoLoadPages = ctx.useValue(autoLoadPagesAtom);\n const setResumeBaseline = ctx.useSet(resumeBaselineAtom);\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n let loadedCount = 0;\n for (const row of data) if (row != null) loadedCount++;\n const pageSize = footer.pageSize || 100;\n const dataLength = data.length;\n const hasMore = !isLocalProvider && loadedCount < dataLength;\n const paused =\n autoLoadPages != null &&\n loadedCount - resumeBaseline >= autoLoadPages * pageSize;\n const canLoadMore = hasMore && !footer.loading && !paused;\n\n const advance = useCallback(() => {\n setVisibleRegion({\n rowIndexStart: 0,\n rowIndexEnd: Math.min(loadedCount + pageSize, dataLength),\n });\n }, [setVisibleRegion, loadedCount, pageSize, dataLength]);\n\n const loadMore = useCallback(() => {\n setResumeBaseline(loadedCount);\n advance();\n }, [setResumeBaseline, loadedCount, advance]);\n\n return {\n loadMore,\n loading: footer.loading,\n hasMore,\n loaded: footer.loaded,\n total: footer.total,\n paused,\n canLoadMore,\n advance,\n };\n}\n\nexport interface ViewInfo {\n visibleRegion: RowRegion;\n totalCount: number | null;\n loading: boolean;\n error: Error | null;\n}\n\nexport const viewInfoAtom = atom<ViewInfo>((get) => {\n const state = get(lazyLoaderStateAtom);\n return {\n visibleRegion: state.visibleRegion,\n loading: state.loading,\n error: state.error,\n totalCount: state.data.length,\n };\n});\n\n/** Temporary passthrough atom to allow visible region to be separated from the rest\n * of the lazy loader state\n */\nconst lazyLoaderStateAtom = atom(\n (get): LazyLoaderState<any> => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom);\n const visibleRegion = get(visibleRegionAtom);\n return {\n ...core,\n data,\n visibleRegion,\n };\n },\n (get, set, update: any) => {\n // Split the state between several places\n if (typeof update === \"function\") {\n update = update(get(lazyLoaderStateAtom));\n }\n const { visibleRegion, data, ...rest } = update;\n if (visibleRegion != null) {\n set(visibleRegionAtom, visibleRegion);\n }\n // Propagate the data array even when empty — a `reset` (view change) must\n // clear the stale rows so the re-fetch rebuilds a correctly-sized array\n // (otherwise a filtered/sorted result splices over a stale, larger array).\n if (data != null) {\n set(tableDataAtom, data);\n }\n if (Object.keys(rest).length > 1) {\n set(lazyLoaderCoreStateAtom, (v) => ({ ...v, ...rest }));\n }\n },\n);\n\nfunction useLazyLoaderReducer() {\n const [state, setState] = ctx.use(lazyLoaderStateAtom);\n const dispatch = useCallback(\n (action: LazyLoaderAction<any>) =>\n setState((prev) => lazyLoadingReducer(prev, action)),\n [setState],\n );\n return [state, dispatch] as const;\n}\n\nfunction buildPostgrestOrderClauses(\n sorts: (ColumnSortEntry | PostgrestOrder<any>)[],\n identityOrder: PostgrestOrder<any> | string,\n): PostgrestOrder<any>[] {\n // Build the ORDER BY for a PostgREST query. Two invariants:\n // 1. Each column appears at most once. Keyset pagination adds a `gt`/`lt`\n // cursor predicate per order clause, so a duplicated column (e.g. the\n // identity key present in both a base order and an active sort, with\n // opposite directions) would emit contradictory `col=lt.X&col=gt.X`\n // bounds that match nothing — an infinite empty-result reload. First\n // occurrence wins (active sorts should be passed ahead of base order).\n // 2. The identity key is ordered last (a stable tiebreaker for the cursor),\n // appended with its default direction only if no clause already sorts it.\n const identitySort =\n typeof identityOrder == \"string\"\n ? { key: identityOrder, ascending: true }\n : identityOrder;\n const identityKey = identitySort.key;\n\n const seen = new Set<string>();\n const clauses: PostgrestOrder<any>[] = [];\n for (const sort of sorts) {\n if (seen.has(sort.key)) continue;\n seen.add(sort.key);\n clauses.push({\n key: sort.key,\n ascending: sort.ascending,\n nullsFirst: \"nullsFirst\" in sort ? sort.nullsFirst : false,\n });\n }\n\n if (seen.has(identityKey)) {\n // Move the (already-deduped) identity clause to the end, keeping the\n // direction the active sort chose.\n const idx = clauses.findIndex((c) => c.key === identityKey);\n const [idClause] = clauses.splice(idx, 1);\n clauses.push(idClause);\n } else {\n clauses.push({\n key: identitySort.key,\n ascending: identitySort.ascending ?? true,\n nullsFirst: (identitySort as any).nullsFirst ?? false,\n });\n }\n return clauses;\n}\n\nexport function useScrollHandler() {\n /** A standardized approach to holding onto the scroll position for the table */\n // Reference to hold onto the scroll position\n const ref = useRef<RowRegion>(null);\n\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n return useCallback(\n debounce((visibleCells: RowRegion) => {\n if (\n visibleCells.rowIndexEnd == ref.current?.rowIndexEnd &&\n visibleCells.rowIndexStart == ref.current?.rowIndexStart\n ) {\n return;\n }\n setVisibleRegion(visibleCells);\n ref.current = visibleCells;\n }, 500),\n [setVisibleRegion],\n );\n}\n\n/**\n * A generic, backend-agnostic windowed data source. Give it a `fetchChunk`\n * function and it drives the sheet's lazy loading: it loads the chunk covering\n * the first unloaded visible row, pre-sizes the sparse array from `totalCount`,\n * threads the active sorts/filters through so the source can apply them\n * server-side, and re-fetches from scratch when the view state changes. This\n * is the unified seam that upstreams bespoke loaders (`fetchChunk` receives the\n * view state; there's no separate adapter object).\n *\n * Call it from a component rendered inside `DataSheet` (see `ChunkLoaderManager`).\n */\nexport function useDataLoader<T = any>(\n fetchChunk: FetchData<T>,\n options: FetchDataOptions = {},\n) {\n const { pageSize = 100, fetchMode = \"scroll\" } = options;\n const [state, dispatch] = useLazyLoaderReducer();\n\n const { isLocalProvider, provider } = ctx.useValue(dataProviderAtom);\n\n const visibleRegion = ctx.useValue(visibleRegionAtom);\n const page = ctx.useValue(chunkPageAtom);\n const setPage = ctx.useSet(chunkPageAtom);\n const refreshToken = ctx.useValue(dataRefreshTokenAtom);\n const columnSorts = useSelector((s) => s.columnSorts);\n const activeFilters = useSelector((s) => s.activeFilters);\n const abortRef = useRef<AbortController | null>(null);\n // Tracks the (page, viewKey) already loaded in paged mode, so the effect\n // doesn't re-fetch on unrelated re-renders.\n const loadedRef = useRef<{ page: number; viewKey: string }>({\n page: -1,\n viewKey: \"\",\n });\n\n const filters: FetchDataFilter[] = useMemo(\n () =>\n (Array.from(activeFilters.entries()) as [any, any][]).map(\n ([id, entry]) => ({\n id,\n columnKey: entry.filter?.columnKey,\n state: entry.state,\n predicate: entry.filter?.predicate,\n }),\n ),\n [activeFilters],\n );\n\n // Publish the windowing config so the footer/pager can read it.\n useEffect(() => {\n dispatch({ type: \"configure\", fetchMode, pageSize: pageSize });\n }, [fetchMode, pageSize]);\n\n // Reset (re-fetch from scratch) when sorts/filters change, or when the fetch\n // mode switches (paged holds a dense page; scroll needs to re-initialize and\n // pre-size) — so a table can flip between modes cleanly.\n const viewKey = useMemo(\n () => JSON.stringify({ sorts: columnSorts, filters }),\n [columnSorts, filters],\n );\n useEffect(() => {\n dispatch({ type: \"reset\" });\n setPage(0);\n }, [viewKey, fetchMode, refreshToken]);\n\n useAsyncEffect(async () => {\n if (state.loading) return;\n\n // Determine the chunk offset to fetch, and (scroll mode) a keyset cursor:\n // the already-loaded row just before the chunk, so keyset sources can page\n // from it instead of a slow OFFSET.\n let offset: number;\n let cursor: { row: any; index: number } | null = null;\n if (fetchMode === \"paged\") {\n // Fetch the current page once; skip if already loaded for this view.\n if (\n loadedRef.current.page === page &&\n loadedRef.current.viewKey === viewKey\n ) {\n return;\n }\n offset = page * pageSize;\n } else {\n const rowIndex = indexOfFirstNullInRegion(state.data, visibleRegion);\n if (rowIndex == null && state.initialized) return;\n offset = Math.floor((rowIndex ?? 0) / pageSize) * pageSize;\n const prev = offset > 0 ? state.data[offset - 1] : null;\n if (prev != null) cursor = { row: prev, index: offset - 1 };\n }\n\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n dispatch({ type: \"start-loading\" });\n try {\n const result = await fetchChunk({\n offset,\n limit: pageSize,\n signal: controller.signal,\n sorts: columnSorts,\n filters,\n cursor,\n });\n if (controller.signal.aborted) return;\n const rows = result.rows ?? [];\n if (fetchMode === \"paged\") {\n loadedRef.current = { page, viewKey };\n // The sheet shows just this page's rows (dense, from index 0); the\n // real source length is tracked separately for the pager.\n dispatch({\n type: \"loaded\",\n data: rows,\n offset: 0,\n totalSize: rows.length,\n totalCount: result.totalCount ?? null,\n });\n } else {\n // Size the (sparse) array. With a known total, size to it. Without one\n // (keyset / infinite scroll), use the short-chunk heuristic: a chunk\n // smaller than the page size means we've hit the end — size exactly to\n // the loaded rows; otherwise pad one more page of nulls so scrolling\n // into them triggers the next fetch. So an unknown-length source never\n // needs a count — it grows a page at a time until a short chunk.\n const loadedEnd = offset + rows.length;\n let totalSize: number;\n if (result.totalCount != null) {\n totalSize = result.totalCount;\n } else {\n const reachedEnd = rows.length < pageSize;\n totalSize = reachedEnd ? loadedEnd : loadedEnd + pageSize;\n }\n dispatch({\n type: \"loaded\",\n data: rows,\n offset,\n totalSize,\n // Preserve a previously-known total when a chunk omits it (undefined):\n // keyset pages can't re-count (the cursor filter would skew it), so\n // only the initial cursorless fetch reports the total.\n totalCount: result.totalCount,\n });\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n dispatch({ type: \"error\", error: err as Error });\n }\n }\n }, [state.data, visibleRegion, viewKey, page, fetchMode]);\n\n return { data: state.data, loading: state.loading, error: state.error };\n}\n\n/**\n * Build a `fetchChunk` backed by a PostgREST endpoint, for use with\n * `useChunkLoader` / `ChunkLoaderManager`. It reuses `buildQuery`, so it pages\n * with **keyset pagination** (via the loader's `cursor`) whenever the query is\n * ordered — falling back to `OFFSET` only when it isn't — and threads the\n * active store sorts/filters into the query. The total count is requested only\n * on the initial (cursorless) fetch, since a keyset cursor filter would skew it.\n */\nexport function createPostgRESTFetchChunk<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (applied when no active\n * sort targets it). `false` ⇒ the table defaults to identity-descending\n * (e.g. newest `source_id` first) without a redundant `baseOrder` entry that\n * would otherwise collide with the identity tiebreaker. Defaults to `true`. */\n identityAscending?: boolean;\n columns?: string | string[];\n /** Order applied before the active column sorts (identity key appended last). */\n baseOrder?: PostgrestOrder<any>[];\n /** A transform over the query builder, applied as a base filter (the `filter` prop). */\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n /** Translate a stored filter entry to a `PostgrestFilter` (return `null` to\n * skip). Defaults to the `{ key, operator, value }` column-filter shape. */\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): FetchData<T> {\n const translate = config.translateFilter ?? standardColumnFilter;\n return async ({ limit, signal, sorts, filters, cursor }) => {\n const client = new PostgrestClient(config.endpoint).from(config.table);\n\n // Active sorts first so they win the by-key dedupe in\n // `buildPostgrestOrderClauses` (a user sort on the identity column\n // overrides its default direction rather than colliding with it).\n const order: PostgrestOrder<any>[] = [\n ...sorts.map((s) => ({ key: s.key, ascending: s.ascending })),\n ...(config.baseOrder ?? []),\n ];\n\n const pgFilters: PostgrestFilter[] = [];\n if (config.baseFilter != null) {\n const apply = config.baseFilter;\n pgFilters.push({ type: \"filter\", apply });\n }\n for (const f of filters) {\n const pf = translate(f);\n if (pf != null) pgFilters.push(pf);\n }\n\n const query = buildQuery(client, {\n columns: config.columns,\n // Only the initial (cursorless) fetch reports an accurate total.\n count: cursor == null ? \"exact\" : undefined,\n limit,\n identityKey: config.identityKey,\n identityOrder: {\n key: config.identityKey,\n ascending: config.identityAscending ?? true,\n },\n order,\n filters: pgFilters,\n lastLoadedRow: cursor?.row ?? null,\n lastLoadedRowIndex: cursor?.index ?? -1,\n });\n\n const res: any = await query;\n if (signal.aborted) return { rows: [] };\n if (res?.error != null) throw res.error;\n const rows = res?.data ?? [];\n return res?.count != null ? { rows, totalCount: res.count } : { rows };\n };\n}\n\n/**\n * A full PostgREST `TableDataProvider`: the read side (`fetchData` + row\n * `identity`) plus persistence — `saveRows` (upsert) and `deleteRows` (by\n * identity). Pass it to `DataSheet`'s `provider` prop. The mutation methods\n * throw on error so the Save action surfaces it.\n */\nexport function createPostgRESTProvider<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (see\n * `createPostgRESTFetchChunk`). `false` ⇒ identity-descending by default. */\n identityAscending?: boolean;\n columns?: string | string[];\n baseOrder?: PostgrestOrder<any>[];\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): TableDataProvider<T> {\n const from = () => new PostgrestClient(config.endpoint).from(config.table);\n return {\n fetchData: createPostgRESTFetchChunk<T>(config),\n identity: (row: any) => row?.[config.identityKey],\n async saveRows(rows) {\n const res: any = await from().upsert(rows as any[], {\n defaultToNull: false,\n });\n if (res?.error != null) throw res.error;\n },\n async deleteRows(ids) {\n const res: any = await from().delete().in(config.identityKey, ids);\n if (res?.error != null) throw res.error;\n },\n };\n}\n\n/** Default filter translation for the built-in operator `columnFilter`: its\n * column is `f.columnKey`, its state is `{ operator, value }`. (Also accepts a\n * `key` in state for hand-rolled filters.) */\nfunction standardColumnFilter(f: FetchDataFilter): PostgrestFilter | null {\n const s = f.state;\n if (s == null) return null;\n const key = f.columnKey ?? s.key;\n if (key != null && s.operator != null && s.value != null && s.value !== \"\") {\n return standardizeFilter({ key, operator: s.operator, value: s.value });\n }\n return null;\n}\n\nfunction indexOfFirstNullInRegion(\n data: any[],\n region: RowRegion,\n): number | null {\n // Clamp to the array length: a visible region can outlast the data it was\n // set against (e.g. a keyset page hits the end of a filtered set and the\n // array shrinks below a region end set before the shrink). Scanning past\n // `data.length` reads `undefined` as a fillable null and re-fetches the same\n // now-out-of-range offset forever — the tail-of-filtered-set reload loop.\n const end = Math.min(region.rowIndexEnd, data.length);\n for (let i = region.rowIndexStart; i < end; i++) {\n if (data[i] == null) {\n return i;\n }\n }\n return null;\n}\n"],"names":["update"],"mappings":";;;;;;;;;AAqFO,SAAS,kBACd,cACiB;AACjB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AACT,aAAO,mBAAmB,KAAK,CAAC,YAAY,CAAC;AAAA,IAC/C;AAAA,EAAA;AAEJ;AAEO,SAAS,mBACd,KACA,SACA;AACA,aAAW,MAAM,SAAS;AACxB,QAAI,GAAG,UAAU,MAAM,GAAG,SAAS,KAAM;AAGzC,QAAI,GAAG,aAAa,MAAM;AACxB,YAAM,IAAI,SAAS,GAAG,KAAK,gBAAgB,GAAG,KAAK,CAAC;AACpD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QAAM,MAAM,EAAE,aAAa,EAAE;AAC7B,MAAI,OAAO,QAAQ,EAAE,YAAY,QAAQ,EAAE,SAAS,QAAQ,EAAE,UAAU,IAAI;AAC1E,WAAO,kBAAkB,EAAE,KAAK,UAAU,EAAE,UAAU,OAAO,EAAE,OAAO;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,yBACP,MACA,QACe;AAMf,QAAM,MAAM,KAAK,IAAI,OAAO,aAAa,KAAK,MAAM;AACpD,WAAS,IAAI,OAAO,eAAe,IAAI,KAAK,KAAK;AAC/C,QAAI,KAAK,CAAC,KAAK,MAAM;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;"}
1
+ {"version":3,"file":"data-loaders.js","sources":["../../src/postgrest-table/data-loaders.ts"],"sourcesContent":["/** Lazy loading of data from a PostgREST endpoint */\n\nimport { useAsyncEffect } from \"@macrostrat/ui-components\";\nimport { debounce } from \"underscore\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n ClientServerOptions,\n PostgrestClient,\n PostgrestFilterBuilder,\n PostgrestQueryBuilder,\n} from \"@supabase/postgrest-js\";\nimport { adjustArraySize, RowRegion } from \"./loading-utils.ts\";\nimport {\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataFilter,\n tableDataAtom,\n TableDataProvider,\n useSelector,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { FetchDataOptions, FetchMode } from \"../types.ts\";\n\ninterface 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\ninterface LazyLoaderState<T> extends LazyLoaderStateCore<T> {\n data: (T | null)[];\n visibleRegion: RowRegion;\n}\n\nexport interface PostgrestOrder<T> {\n key: string;\n ascending?: boolean;\n nullsFirst?: boolean;\n}\n\n/** Operators available for server-side column filtering via PostgREST.\n * `cs`/`ov` target array columns (contains / overlaps). */\nexport type PostgrestFilterOperator =\n | \"eq\"\n | \"neq\"\n | \"like\"\n | \"ilike\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"is\"\n | \"cs\"\n | \"ov\";\n\n/** A single column sort entry. */\nexport interface ColumnSortEntry {\n key: string;\n ascending: boolean;\n}\n\n/** A single column filter entry. */\nexport interface PostgrestColumnFilter {\n key: string;\n operator: PostgrestFilterOperator;\n value: string;\n}\n\nexport interface PostgrestFilter {\n id?: string;\n type: \"filter\";\n apply(\n req: PostgrestFilterBuilder<any, any, any, any>,\n ): PostgrestFilterBuilder<any, any, any, any>;\n}\n\nexport function standardizeFilter(\n columnFilter: PostgrestColumnFilter,\n): PostgrestFilter {\n return {\n type: \"filter\",\n apply(req) {\n return applyColumnFilters(req, [columnFilter]);\n },\n };\n}\n\nexport function applyColumnFilters(\n req: PostgrestFilterBuilder<any, any, any, any>,\n filters: PostgrestColumnFilter[],\n) {\n for (const cf of filters) {\n if (cf.value === \"\" || cf.value == null) continue;\n // Array-column operators need a list value and postgrest-js's dedicated\n // builders (which emit the `{…}` array literal), not a scalar `.filter`.\n if (cf.operator === \"cs\") {\n req = req.contains(cf.key, splitFilterList(cf.value));\n continue;\n }\n if (cf.operator === \"ov\") {\n req = req.overlaps(cf.key, splitFilterList(cf.value));\n continue;\n }\n const val =\n cf.operator === \"like\" || cf.operator === \"ilike\"\n ? `*${cf.value}*`\n : cf.value;\n req = req.filter(cf.key, cf.operator, val);\n }\n return req;\n}\n\n/** Split a comma-separated filter value into trimmed, non-empty tokens (the set\n * for `cs`/`ov`); a single value yields a one-element list. */\nfunction splitFilterList(value: any): string[] {\n return String(value)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n}\n\ntype LazyLoaderAction<T> =\n | { type: \"start-loading\" }\n | {\n type: \"loaded\";\n data: T[];\n offset: number;\n totalSize: number;\n totalCount?: number | null;\n }\n | { type: \"error\"; error: Error }\n | { type: \"update-data\"; changes: Spec<T[]> }\n | { type: \"reset\" }\n | { type: \"configure\"; fetchMode: FetchMode; pageSize: number };\n\nfunction lazyLoadingReducer<T>(\n state: LazyLoaderState<T>,\n action: LazyLoaderAction<T>,\n): LazyLoaderState<T> {\n switch (action.type) {\n case \"start-loading\":\n return {\n ...state,\n loading: true,\n initialized: true,\n };\n case \"update-data\":\n return {\n ...state,\n loading: false,\n data: update(state.data, action.changes as any),\n };\n case \"loaded\":\n let data = adjustArraySize(state.data, action.totalSize);\n const newData = action.data ?? [];\n const offset = action.offset ?? 0;\n data = [\n ...data.slice(0, offset),\n ...newData,\n ...data.slice(offset + newData.length),\n ];\n return {\n ...state,\n data,\n loading: false,\n totalCount:\n action.totalCount !== undefined\n ? action.totalCount\n : state.totalCount,\n };\n case \"configure\":\n return {\n ...state,\n fetchMode: action.fetchMode,\n pageSize: action.pageSize,\n };\n case \"reset\":\n // A view change (or initial load) re-fetches from scratch. Rather than\n // blanking the table (which reads as a jarring empty flash while the\n // request is in flight — very visible on sort/filter), pre-size to a page\n // of `null` ghost/skeleton rows so the body stays populated and the load\n // is legible. `loaded` then adjusts the array to the real size.\n return {\n visibleRegion: defaultVisibleRegion,\n data: new Array(Math.max(state.pageSize, 0)).fill(null),\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: state.fetchMode,\n pageSize: state.pageSize,\n };\n case \"error\":\n return {\n ...state,\n error: action.error,\n loading: false,\n };\n default:\n return state;\n }\n}\n\ntype SortAndFilterOptions = {\n /** Column-level sort state, managed externally. When provided, overrides\n * the `order` prop for query building. */\n order?: PostgrestOrder<any>[];\n filters?: PostgrestFilter[];\n};\n\ninterface QueryConfig extends SortAndFilterOptions {\n columns?: string | string[];\n count?: \"exact\" | \"estimated\";\n limit?: number;\n identityKey: string;\n /** The identity column's default ordering (used when nothing in `order`\n * already sorts it). A string ⇒ ascending; pass a `PostgrestOrder` to set the\n * direction (e.g. `source_id` descending). */\n identityOrder?: PostgrestOrder<any>;\n lastLoadedRow?: any;\n lastLoadedRowIndex: number;\n}\n\n/** Format a value for a PostgREST logic-tree condition. Reserved characters\n * (`, . : ( )`), spaces, quotes, and backslashes require the value to be\n * double-quoted, with `\"` and `\\` backslash-escaped inside — otherwise a map\n * name containing a comma would break the `or=(...)` parse. */\nfunction formatKeysetValue(v: any): string {\n const s = String(v);\n if (s === \"\" || /[,.:()\"\\\\ ]/.test(s)) {\n return `\"${s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n }\n return s;\n}\n\n/** An equality condition for the cursor prefix (`col.eq.v`, or `col.is.null`). */\nfunction keysetEq(key: string, v: any): string {\n return v == null ? `${key}.is.null` : `${key}.eq.${formatKeysetValue(v)}`;\n}\n\n/**\n * Build the compound keyset predicate (the body of an `or=(...)`) selecting\n * rows strictly after `lastRow` under `clauses` (lexicographic, last clause is\n * the identity tiebreaker):\n *\n * (c1 OP1 v1)\n * OR (c1 = v1 AND c2 OP2 v2)\n * OR (c1 = v1 AND c2 = v2 AND c3 OP3 v3) …\n *\n * `OPi` is `gt` for an ascending clause, `lt` for descending. Nulls-last: a\n * null pivot value has no strictly-ordered non-null successor at its level, so\n * that term is skipped and the tie defers to deeper clauses (the identity key\n * is non-null, so at least its term is always emitted). Returns `null` if no\n * term applies. (Known limit: rows whose *sort* column is null aren't picked up\n * across the non-null→null boundary — an edge for nullable sort columns; the\n * non-null identity tiebreaker keeps pagination from stalling.)\n */\nfunction buildKeysetPredicate(\n clauses: PostgrestOrder<any>[],\n lastRow: any,\n): string | null {\n const terms: string[] = [];\n for (let i = 0; i < clauses.length; i++) {\n const v = lastRow[clauses[i].key];\n if (v == null) continue;\n const conds: string[] = [];\n for (let j = 0; j < i; j++) {\n conds.push(keysetEq(clauses[j].key, lastRow[clauses[j].key]));\n }\n const op = (clauses[i].ascending ?? true) ? \"gt\" : \"lt\";\n conds.push(`${clauses[i].key}.${op}.${formatKeysetValue(v)}`);\n terms.push(conds.length === 1 ? conds[0] : `and(${conds.join(\",\")})`);\n }\n return terms.length > 0 ? terms.join(\",\") : null;\n}\n\nfunction buildQuery<T>(\n client: PostgrestQueryBuilder<any, any, any>,\n config: QueryConfig,\n) {\n const { columns = \"*\", count, lastLoadedRowIndex } = config;\n const opts = { count };\n\n let cols: string;\n if (Array.isArray(columns)) {\n cols = columns.join(\", \");\n } else {\n cols = columns ?? \"*\";\n }\n\n let query = client.select(cols, opts);\n\n const filters = config.filters ?? [];\n for (const filter of filters) {\n query = filter.apply(query);\n }\n\n const orderClauses = buildPostgrestOrderClauses(\n config.order ?? [],\n config.identityOrder ?? config.identityKey,\n );\n\n let hasOrdering = false;\n for (const clause of orderClauses) {\n query = query.order(clause.key, clause);\n hasOrdering = true;\n }\n\n // Keyset cursor: rows strictly after the last loaded row under the active\n // ordering. This MUST be a compound predicate, not an independent `gt`/`lt`\n // per column: with a leading low-cardinality sort (e.g. `state`), a plain\n // `state.gt.X AND source_id.lt.Y` drops every row sharing the cursor's\n // `state` (`state.gt.X` is false for them). The lexicographic form keeps the\n // tie broken by the next column, ending on the non-null identity key.\n if (config.lastLoadedRow != null && hasOrdering) {\n const pred = buildKeysetPredicate(orderClauses, config.lastLoadedRow);\n if (pred != null) query = query.or(pred);\n }\n\n let offset: number | null = null;\n if (!hasOrdering && lastLoadedRowIndex > 0) {\n // We need to load based on offsets\n offset = lastLoadedRowIndex + 1;\n }\n\n if (config.limit != null) {\n if (offset != null) {\n query = query.range(offset, offset + config.limit - 1);\n console.log(`Random seek from ${offset}, this will be slow`);\n } else {\n query = query.limit(config.limit);\n }\n }\n\n return query;\n}\n\nconst defaultVisibleRegion: RowRegion = {\n rowIndexStart: 0,\n rowIndexEnd: 0,\n};\n\n/** Atom to house the current visible region of the table */\nconst visibleRegionAtom = atom<RowRegion>(defaultVisibleRegion);\n\nconst lazyLoaderCoreStateAtom = atom<LazyLoaderStateCore<any>>({\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: \"scroll\",\n pageSize: 100,\n});\n\n/** Current page index (0-based) for paged fetch mode. */\nexport const chunkPageAtom = atom(0);\n\n/** Footer state for the optional bottom-of-table indicator: rows loaded, the\n * source total when known, load status, and — in paged mode — the current\n * page and total pages. */\nexport interface TableFooterInfo {\n mode: FetchMode;\n loaded: number;\n total: number | null;\n loading: boolean;\n /** A fetch has been attempted since the last view reset — so `loaded === 0`\n * can be told apart from \"not loaded yet\" (avoids an empty-state flash). */\n initialized: boolean;\n error: Error | null;\n page: number;\n pageSize: number;\n totalPages: number | null;\n}\n\nexport const tableFooterAtom = atom<TableFooterInfo>((get) => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom) ?? [];\n let loaded = 0;\n let hasGaps = false;\n for (const row of data) {\n if (row != null) loaded++;\n else hasGaps = true;\n }\n // Total is known when the source reported it, or (scroll mode) when the array\n // is fully populated — otherwise it's still being discovered.\n const total = core.totalCount ?? (hasGaps ? null : data.length);\n const totalPages =\n core.totalCount != null ? Math.ceil(core.totalCount / core.pageSize) : null;\n return {\n mode: core.fetchMode,\n loaded,\n total,\n loading: core.loading,\n initialized: core.initialized,\n error: core.error,\n page: get(chunkPageAtom),\n pageSize: core.pageSize,\n totalPages,\n };\n});\n\n/** Auto-load this many pages per burst, then pause (null ⇒ unbounded). Set by\n * a consumer (e.g. `DataPanel`'s `autoLoadPages` prop). */\nexport const autoLoadPagesAtom = atom<number | null>(null);\n\n/** Row count at the last manual \"load more\" — the point auto-load resumes\n * counting a fresh burst from. */\nexport const resumeBaselineAtom = atom(0);\n\n/** Live loading controls, read from the store rather than passed down a\n * boundary contract. Any component inside the provider can call\n * `useLoadControls()` — a footer, a toolbar button, a status line — without the\n * renderer wiring a specific prop shape to it. */\nexport interface LoadControls {\n /** Load the next page and resume auto-loading (clears a paused state). */\n loadMore: () => void;\n /** A fetch is in flight. */\n loading: boolean;\n /** A fetch has been attempted since the last view reset (so an empty result\n * can be told apart from \"not loaded yet\"). */\n initialized: boolean;\n /** The most recent load error (cleared on the next successful load), else\n * `null` — so a footer/consumer can degrade gracefully instead of hanging. */\n error: Error | null;\n /** More rows remain to load. */\n hasMore: boolean;\n /** Rows loaded so far. */\n loaded: number;\n /** Source total when known, else `null`. */\n total: number | null;\n /** Auto-load is paused at the `autoLoadPages` checkpoint. */\n paused: boolean;\n /** Auto-load is currently permitted (`hasMore && !loading && !paused`) —\n * used to gate an infinite-scroll sentinel. */\n canLoadMore: boolean;\n /** Advance one page *without* resuming a paused auto-load (the sentinel\n * uses this; `loadMore` is the manual, un-pausing variant). */\n advance: () => void;\n}\n\n/** Store-managed load controls (see `LoadControls`). Reads the loader's footer\n * state, the loaded rows, and the pause atoms; `loadMore`/`advance` set the\n * visible region so the loader fetches the next chunk. */\nexport function useLoadControls(): LoadControls {\n const footer = ctx.useValue(tableFooterAtom);\n const data = ctx.useValue(tableDataAtom) ?? [];\n const { isLocalProvider } = ctx.useValue(dataProviderAtom);\n const resumeBaseline = ctx.useValue(resumeBaselineAtom);\n const autoLoadPages = ctx.useValue(autoLoadPagesAtom);\n const setResumeBaseline = ctx.useSet(resumeBaselineAtom);\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n let loadedCount = 0;\n for (const row of data) if (row != null) loadedCount++;\n const pageSize = footer.pageSize || 100;\n const dataLength = data.length;\n const hasMore = !isLocalProvider && loadedCount < dataLength;\n const paused =\n autoLoadPages != null &&\n loadedCount - resumeBaseline >= autoLoadPages * pageSize;\n const canLoadMore = hasMore && !footer.loading && !paused;\n\n const advance = useCallback(() => {\n setVisibleRegion({\n rowIndexStart: 0,\n rowIndexEnd: Math.min(loadedCount + pageSize, dataLength),\n });\n }, [setVisibleRegion, loadedCount, pageSize, dataLength]);\n\n const loadMore = useCallback(() => {\n setResumeBaseline(loadedCount);\n advance();\n }, [setResumeBaseline, loadedCount, advance]);\n\n return {\n loadMore,\n loading: footer.loading,\n initialized: footer.initialized,\n error: footer.error,\n hasMore,\n loaded: footer.loaded,\n total: footer.total,\n paused,\n canLoadMore,\n advance,\n };\n}\n\nexport interface ViewInfo {\n visibleRegion: RowRegion;\n totalCount: number | null;\n loading: boolean;\n error: Error | null;\n}\n\nexport const viewInfoAtom = atom<ViewInfo>((get) => {\n const state = get(lazyLoaderStateAtom);\n return {\n visibleRegion: state.visibleRegion,\n loading: state.loading,\n error: state.error,\n totalCount: state.data.length,\n };\n});\n\n/** Temporary passthrough atom to allow visible region to be separated from the rest\n * of the lazy loader state\n */\nconst lazyLoaderStateAtom = atom(\n (get): LazyLoaderState<any> => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom);\n const visibleRegion = get(visibleRegionAtom);\n return {\n ...core,\n data,\n visibleRegion,\n };\n },\n (get, set, update: any) => {\n // Split the state between several places\n if (typeof update === \"function\") {\n update = update(get(lazyLoaderStateAtom));\n }\n const { visibleRegion, data, ...rest } = update;\n if (visibleRegion != null) {\n set(visibleRegionAtom, visibleRegion);\n }\n // Propagate the data array even when empty — a `reset` (view change) must\n // clear the stale rows so the re-fetch rebuilds a correctly-sized array\n // (otherwise a filtered/sorted result splices over a stale, larger array).\n if (data != null) {\n set(tableDataAtom, data);\n }\n if (Object.keys(rest).length > 1) {\n set(lazyLoaderCoreStateAtom, (v) => ({ ...v, ...rest }));\n }\n },\n);\n\nfunction useLazyLoaderReducer() {\n const [state, setState] = ctx.use(lazyLoaderStateAtom);\n const dispatch = useCallback(\n (action: LazyLoaderAction<any>) =>\n setState((prev) => lazyLoadingReducer(prev, action)),\n [setState],\n );\n return [state, dispatch] as const;\n}\n\nfunction buildPostgrestOrderClauses(\n sorts: (ColumnSortEntry | PostgrestOrder<any>)[],\n identityOrder: PostgrestOrder<any> | string,\n): PostgrestOrder<any>[] {\n // Build the ORDER BY for a PostgREST query. Two invariants:\n // 1. Each column appears at most once. Keyset pagination adds a `gt`/`lt`\n // cursor predicate per order clause, so a duplicated column (e.g. the\n // identity key present in both a base order and an active sort, with\n // opposite directions) would emit contradictory `col=lt.X&col=gt.X`\n // bounds that match nothing — an infinite empty-result reload. First\n // occurrence wins (active sorts should be passed ahead of base order).\n // 2. The identity key is ordered last (a stable tiebreaker for the cursor),\n // appended with its default direction only if no clause already sorts it.\n const identitySort =\n typeof identityOrder == \"string\"\n ? { key: identityOrder, ascending: true }\n : identityOrder;\n const identityKey = identitySort.key;\n\n const seen = new Set<string>();\n const clauses: PostgrestOrder<any>[] = [];\n for (const sort of sorts) {\n if (seen.has(sort.key)) continue;\n seen.add(sort.key);\n clauses.push({\n key: sort.key,\n ascending: sort.ascending,\n nullsFirst: \"nullsFirst\" in sort ? sort.nullsFirst : false,\n });\n }\n\n if (seen.has(identityKey)) {\n // Move the (already-deduped) identity clause to the end, keeping the\n // direction the active sort chose.\n const idx = clauses.findIndex((c) => c.key === identityKey);\n const [idClause] = clauses.splice(idx, 1);\n clauses.push(idClause);\n } else {\n clauses.push({\n key: identitySort.key,\n ascending: identitySort.ascending ?? true,\n nullsFirst: (identitySort as any).nullsFirst ?? false,\n });\n }\n return clauses;\n}\n\nexport function useScrollHandler() {\n /** A standardized approach to holding onto the scroll position for the table */\n // Reference to hold onto the scroll position\n const ref = useRef<RowRegion>(null);\n\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n return useCallback(\n debounce((visibleCells: RowRegion) => {\n if (\n visibleCells.rowIndexEnd == ref.current?.rowIndexEnd &&\n visibleCells.rowIndexStart == ref.current?.rowIndexStart\n ) {\n return;\n }\n setVisibleRegion(visibleCells);\n ref.current = visibleCells;\n }, 500),\n [setVisibleRegion],\n );\n}\n\n/**\n * A generic, backend-agnostic windowed data source. Give it a `fetchChunk`\n * function and it drives the sheet's lazy loading: it loads the chunk covering\n * the first unloaded visible row, pre-sizes the sparse array from `totalCount`,\n * threads the active sorts/filters through so the source can apply them\n * server-side, and re-fetches from scratch when the view state changes. This\n * is the unified seam that upstreams bespoke loaders (`fetchChunk` receives the\n * view state; there's no separate adapter object).\n *\n * Call it from a component rendered inside `DataSheet` (see `ChunkLoaderManager`).\n */\nexport function useDataLoader<T = any>(\n fetchChunk: FetchData<T>,\n options: FetchDataOptions = {},\n) {\n const { pageSize = 100, fetchMode = \"scroll\", filterDebounce = 0 } = options;\n const [state, dispatch] = useLazyLoaderReducer();\n\n const { isLocalProvider, provider } = ctx.useValue(dataProviderAtom);\n\n const visibleRegion = ctx.useValue(visibleRegionAtom);\n const page = ctx.useValue(chunkPageAtom);\n const setPage = ctx.useSet(chunkPageAtom);\n const refreshToken = ctx.useValue(dataRefreshTokenAtom);\n const columnSorts = useSelector((s) => s.columnSorts);\n const activeFilters = useSelector((s) => s.activeFilters);\n const abortRef = useRef<AbortController | null>(null);\n // Tracks the (page, viewKey) already loaded in paged mode, so the effect\n // doesn't re-fetch on unrelated re-renders.\n const loadedRef = useRef<{ page: number; viewKey: string }>({\n page: -1,\n viewKey: \"\",\n });\n\n const filters: FetchDataFilter[] = useMemo(\n () =>\n (Array.from(activeFilters.entries()) as [any, any][]).map(\n ([id, entry]) => ({\n id,\n columnKey: entry.filter?.columnKey,\n state: entry.state,\n predicate: entry.filter?.predicate,\n }),\n ),\n [activeFilters],\n );\n\n // Publish the windowing config so the footer/pager can read it.\n useEffect(() => {\n dispatch({ type: \"configure\", fetchMode, pageSize: pageSize });\n }, [fetchMode, pageSize]);\n\n // Reset (re-fetch from scratch) when sorts/filters change, or when the fetch\n // mode switches (paged holds a dense page; scroll needs to re-initialize and\n // pre-size) — so a table can flip between modes cleanly.\n const viewKey = useMemo(\n () => JSON.stringify({ sorts: columnSorts, filters }),\n [columnSorts, filters],\n );\n // Debounce the view-state → refetch: rapid changes (typing in a text filter)\n // otherwise reset + refetch on every keystroke, flashing the list. The store\n // (and so the filter input) still updates instantly; only the *fetch* waits\n // for the view to settle. Scroll paging is unaffected — it's driven by\n // `visibleRegion`/`data`, not this key. `filterDebounce: 0` (default) keeps\n // the immediate behavior.\n const debouncedViewKey = useDebouncedValue(viewKey, filterDebounce);\n useEffect(() => {\n dispatch({ type: \"reset\" });\n setPage(0);\n }, [debouncedViewKey, fetchMode, refreshToken]);\n\n useAsyncEffect(async () => {\n if (state.loading) return;\n\n // Determine the chunk offset to fetch, and (scroll mode) a keyset cursor:\n // the already-loaded row just before the chunk, so keyset sources can page\n // from it instead of a slow OFFSET.\n let offset: number;\n let cursor: { row: any; index: number } | null = null;\n if (fetchMode === \"paged\") {\n // Fetch the current page once; skip if already loaded for this view.\n if (\n loadedRef.current.page === page &&\n loadedRef.current.viewKey === viewKey\n ) {\n return;\n }\n offset = page * pageSize;\n } else {\n const rowIndex = indexOfFirstNullInRegion(state.data, visibleRegion);\n if (rowIndex == null && state.initialized) return;\n offset = Math.floor((rowIndex ?? 0) / pageSize) * pageSize;\n const prev = offset > 0 ? state.data[offset - 1] : null;\n if (prev != null) cursor = { row: prev, index: offset - 1 };\n }\n\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n dispatch({ type: \"start-loading\" });\n try {\n const result = await fetchChunk({\n offset,\n limit: pageSize,\n signal: controller.signal,\n sorts: columnSorts,\n filters,\n cursor,\n });\n if (controller.signal.aborted) return;\n const rows = result.rows ?? [];\n if (fetchMode === \"paged\") {\n loadedRef.current = { page, viewKey };\n // The sheet shows just this page's rows (dense, from index 0); the\n // real source length is tracked separately for the pager.\n dispatch({\n type: \"loaded\",\n data: rows,\n offset: 0,\n totalSize: rows.length,\n totalCount: result.totalCount ?? null,\n });\n } else {\n // Size the (sparse) array. With a known total, size to it. Without one\n // (keyset / infinite scroll), use the short-chunk heuristic: a chunk\n // smaller than the page size means we've hit the end — size exactly to\n // the loaded rows; otherwise pad one more page of nulls so scrolling\n // into them triggers the next fetch. So an unknown-length source never\n // needs a count — it grows a page at a time until a short chunk.\n const loadedEnd = offset + rows.length;\n let totalSize: number;\n if (result.totalCount != null) {\n totalSize = result.totalCount;\n } else {\n const reachedEnd = rows.length < pageSize;\n totalSize = reachedEnd ? loadedEnd : loadedEnd + pageSize;\n }\n dispatch({\n type: \"loaded\",\n data: rows,\n offset,\n totalSize,\n // Preserve a previously-known total when a chunk omits it (undefined):\n // keyset pages can't re-count (the cursor filter would skew it), so\n // only the initial cursorless fetch reports the total.\n totalCount: result.totalCount,\n });\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n dispatch({ type: \"error\", error: err as Error });\n }\n }\n }, [state.data, visibleRegion, debouncedViewKey, page, fetchMode]);\n\n return { data: state.data, loading: state.loading, error: state.error };\n}\n\n/** A value that trails `value` by `delay` ms of stability — the first value is\n * returned immediately, and `delay <= 0` disables debouncing entirely. */\nfunction useDebouncedValue<T>(value: T, delay: number): T {\n const [debounced, setDebounced] = useState(value);\n useEffect(() => {\n if (delay <= 0) {\n setDebounced(value);\n return;\n }\n const t = setTimeout(() => setDebounced(value), delay);\n return () => clearTimeout(t);\n }, [value, delay]);\n return debounced;\n}\n\n/**\n * Build a `fetchChunk` backed by a PostgREST endpoint, for use with\n * `useChunkLoader` / `ChunkLoaderManager`. It reuses `buildQuery`, so it pages\n * with **keyset pagination** (via the loader's `cursor`) whenever the query is\n * ordered — falling back to `OFFSET` only when it isn't — and threads the\n * active store sorts/filters into the query. The total count is requested only\n * on the initial (cursorless) fetch, since a keyset cursor filter would skew it.\n */\nexport function createPostgRESTFetchChunk<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (applied when no active\n * sort targets it). `false` ⇒ the table defaults to identity-descending\n * (e.g. newest `source_id` first) without a redundant `baseOrder` entry that\n * would otherwise collide with the identity tiebreaker. Defaults to `true`. */\n identityAscending?: boolean;\n columns?: string | string[];\n /** Order applied before the active column sorts (identity key appended last). */\n baseOrder?: PostgrestOrder<any>[];\n /** A transform over the query builder, applied as a base filter (the `filter` prop). */\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n /** Translate a stored filter entry to a `PostgrestFilter` (return `null` to\n * skip). Defaults to the `{ key, operator, value }` column-filter shape. */\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): FetchData<T> {\n const translate = config.translateFilter ?? standardColumnFilter;\n return async ({ limit, signal, sorts, filters, cursor }) => {\n const client = new PostgrestClient(config.endpoint).from(config.table);\n\n // Active sorts first so they win the by-key dedupe in\n // `buildPostgrestOrderClauses` (a user sort on the identity column\n // overrides its default direction rather than colliding with it).\n const order: PostgrestOrder<any>[] = [\n ...sorts.map((s) => ({ key: s.key, ascending: s.ascending })),\n ...(config.baseOrder ?? []),\n ];\n\n const pgFilters: PostgrestFilter[] = [];\n if (config.baseFilter != null) {\n const apply = config.baseFilter;\n pgFilters.push({ type: \"filter\", apply });\n }\n for (const f of filters) {\n const pf = translate(f);\n if (pf != null) pgFilters.push(pf);\n }\n\n const query = buildQuery(client, {\n columns: config.columns,\n // Only the initial (cursorless) fetch reports an accurate total.\n count: cursor == null ? \"exact\" : undefined,\n limit,\n identityKey: config.identityKey,\n identityOrder: {\n key: config.identityKey,\n ascending: config.identityAscending ?? true,\n },\n order,\n filters: pgFilters,\n lastLoadedRow: cursor?.row ?? null,\n lastLoadedRowIndex: cursor?.index ?? -1,\n });\n\n const res: any = await query;\n if (signal.aborted) return { rows: [] };\n if (res?.error != null) throw res.error;\n const rows = res?.data ?? [];\n return res?.count != null ? { rows, totalCount: res.count } : { rows };\n };\n}\n\n/**\n * A full PostgREST `TableDataProvider`: the read side (`fetchData` + row\n * `identity`) plus persistence — `saveRows` (upsert) and `deleteRows` (by\n * identity). Pass it to `DataSheet`'s `provider` prop. The mutation methods\n * throw on error so the Save action surfaces it.\n */\nexport function createPostgRESTProvider<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (see\n * `createPostgRESTFetchChunk`). `false` ⇒ identity-descending by default. */\n identityAscending?: boolean;\n columns?: string | string[];\n baseOrder?: PostgrestOrder<any>[];\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): TableDataProvider<T> {\n const from = () => new PostgrestClient(config.endpoint).from(config.table);\n return {\n fetchData: createPostgRESTFetchChunk<T>(config),\n identity: (row: any) => row?.[config.identityKey],\n async saveRows(rows) {\n const res: any = await from().upsert(rows as any[], {\n defaultToNull: false,\n });\n if (res?.error != null) throw res.error;\n },\n async deleteRows(ids) {\n const res: any = await from().delete().in(config.identityKey, ids);\n if (res?.error != null) throw res.error;\n },\n };\n}\n\n/** Default filter translation for the built-in operator `columnFilter`: its\n * column is `f.columnKey`, its state is `{ operator, value }`. (Also accepts a\n * `key` in state for hand-rolled filters.) */\nfunction standardColumnFilter(f: FetchDataFilter): PostgrestFilter | null {\n const s = f.state;\n if (s == null) return null;\n const key = f.columnKey ?? s.key;\n if (key != null && s.operator != null && s.value != null && s.value !== \"\") {\n return standardizeFilter({ key, operator: s.operator, value: s.value });\n }\n return null;\n}\n\nfunction indexOfFirstNullInRegion(\n data: any[],\n region: RowRegion,\n): number | null {\n // Clamp to the array length: a visible region can outlast the data it was\n // set against (e.g. a keyset page hits the end of a filtered set and the\n // array shrinks below a region end set before the shrink). Scanning past\n // `data.length` reads `undefined` as a fillable null and re-fetches the same\n // now-out-of-range offset forever — the tail-of-filtered-set reload loop.\n const end = Math.min(region.rowIndexEnd, data.length);\n for (let i = region.rowIndexStart; i < end; i++) {\n if (data[i] == null) {\n return i;\n }\n }\n return null;\n}\n"],"names":["update"],"mappings":";;;;;;;;;AAqFO,SAAS,kBACd,cACiB;AACjB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AACT,aAAO,mBAAmB,KAAK,CAAC,YAAY,CAAC;AAAA,IAC/C;AAAA,EAAA;AAEJ;AAEO,SAAS,mBACd,KACA,SACA;AACA,aAAW,MAAM,SAAS;AACxB,QAAI,GAAG,UAAU,MAAM,GAAG,SAAS,KAAM;A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,IAAI,gBAAgB,OAAO,QAAQ,EAAE,KAAK,OAAO,KAAK;AACzE,SAAO;AAAA,IACL,WAAW,0BAA6B,MAAM;AAAA,IAC9C,UAAU,CAAC,QAAa,MAAM,OAAO,WAAW;AAAA,IAChD,MAAM,SAAS,MAAM;AACnB,YAAM,MAAW,MAAM,OAAO,OAAO,MAAe;AAAA,QAClD,eAAe;AAAA,MAAA,CAChB;AACD,UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,IACA,MAAM,WAAW,KAAK;AACpB,YAAM,MAAW,MAAM,OAAO,SAAS,GAAG,OAAO,aAAa,GAAG;AACjE,UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,EAAA;AAEJ;AAKA,SAAS,qBAAqB,GAA4C;AACxE,QAAM,IAAI,EAAE;AACZ,MAAI,KAAK,KAAM,QAAO;AACtB,QAAM,MAAM,EAAE,aAAa,EAAE;AAC7B,MAAI,OAAO,QAAQ,EAAE,YAAY,QAAQ,EAAE,SAAS,QAAQ,EAAE,UAAU,IAAI;AAC1E,WAAO,kBAAkB,EAAE,KAAK,UAAU,EAAE,UAAU,OAAO,EAAE,OAAO;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,yBACP,MACA,QACe;AAMf,QAAM,MAAM,KAAK,IAAI,OAAO,aAAa,KAAK,MAAM;AACpD,WAAS,IAAI,OAAO,eAAe,IAAI,KAAK,KAAK;AAC/C,QAAI,KAAK,CAAC,KAAK,MAAM;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;"}
@@ -2,50 +2,25 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const react = require("react");
4
4
  const h = require("@macrostrat/hyper");
5
- const zustand = require("zustand");
6
5
  const columnSpec = require("./column-spec.cjs");
7
- const dataComponents = require("@macrostrat/data-components");
6
+ const scopedStore = require("@macrostrat/scoped-store");
8
7
  const types = require("./types.cjs");
9
8
  const zustandStore = require("./zustand-store.cjs");
10
- const jotaiZustand = require("jotai-zustand");
11
9
  const notifications = require("../notifications.cjs");
12
- const jotai = require("jotai");
13
10
  const tableData = require("./table-data.cjs");
14
11
  const uiComponents = require("@macrostrat/ui-components");
15
12
  const interactions = require("./interactions.cjs");
16
13
  const atoms = require("../utils/atoms.cjs");
17
14
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
18
15
  const h__default = /* @__PURE__ */ _interopDefault(h);
19
- const ctx = dataComponents.createScopedStore();
20
- const storeAPIAtom = jotai.atom();
21
- const storeWrapperAtom = jotai.atom((get) => {
22
- const _storeAPIAtom = get(storeAPIAtom);
23
- if (_storeAPIAtom == null) {
24
- return void 0;
25
- }
26
- return jotaiZustand.atomWithStore(_storeAPIAtom);
27
- });
28
- const storeAtom = jotai.atom(
29
- (get) => {
30
- const storeWrapper = get(storeWrapperAtom);
31
- if (storeWrapper == null) {
32
- return void 0;
33
- }
34
- return get(storeWrapper);
35
- },
36
- (get, set, action) => {
37
- const storeWrapper = get(storeWrapperAtom);
38
- if (storeWrapper == null) {
39
- throw new Error("Missing DataSheetProvider");
40
- }
41
- return set(storeWrapper, action);
42
- }
43
- );
16
+ const ctx = scopedStore.createScopedStore();
17
+ const storeAPIAtom = scopedStore.zustandAPIAtom;
18
+ const storeAtom = scopedStore.zustandStoreAtom;
44
19
  const EMPTY_SPEC = [];
45
- const initializeStoreAtom = jotai.atom(
20
+ const initializeStoreAtom = scopedStore.atom(
46
21
  null,
47
22
  (get, set, payload) => {
48
- set(storeAtom, (state) => {
23
+ set(scopedStore.zustandStoreAtom, (state) => {
49
24
  return {
50
25
  ...state,
51
26
  ...payload
@@ -53,14 +28,14 @@ const initializeStoreAtom = jotai.atom(
53
28
  });
54
29
  }
55
30
  );
56
- const tableActionsAtom = jotai.atom([]);
31
+ const tableActionsAtom = scopedStore.atom([]);
57
32
  const DEFAULT_DATA_PROVIDER = {
58
33
  provider: null,
59
34
  isLocalProvider: true,
60
35
  isExplicitProvider: false,
61
36
  localCount: 0
62
37
  };
63
- const dataProviderAtom = jotai.atom(
38
+ const dataProviderAtom = scopedStore.atom(
64
39
  DEFAULT_DATA_PROVIDER
65
40
  );
66
41
  const EMPTY_ARRAY = [];
@@ -98,16 +73,13 @@ function useResolvedProvider(props) {
98
73
  }
99
74
  function DataSheetStoreWrapper(props) {
100
75
  const { toaster, ...rest } = props;
101
- const [store] = react.useState(() => {
102
- return zustand.createStore(zustandStore.createZustandStore);
103
- });
104
76
  return h__default.default(
105
- ctx.Provider,
77
+ scopedStore.ZustandStoreProvider,
106
78
  {
107
- atoms: [
108
- [storeAPIAtom, store],
109
- [notifications.toasterAtom, toaster]
110
- ]
79
+ ctx,
80
+ initializeStore: zustandStore.createZustandStore,
81
+ atoms: [[notifications.toasterAtom, toaster]],
82
+ debugName: "DataSheetProvider"
111
83
  },
112
84
  h__default.default(DataSheetProviderInner, rest)
113
85
  );
@@ -176,9 +148,13 @@ function DataSheetProviderInner(props) {
176
148
  react.useEffect(() => {
177
149
  initializeStore({
178
150
  columnSpec: columnSpec.postprocessColumnSpec(baseSpec),
179
- // A function spec is derived from the loaded rows in `_DataSheet`; tell
180
- // the loader not to auto-generate a plain spec from the first chunk.
181
- deferColumnSpec: isFnSpec,
151
+ // Suppress the loader's first-chunk auto-generation whenever the consumer
152
+ // provided a spec at all — a function (derived later in `_DataSheet`) OR
153
+ // an explicit array, *including an empty one*. An empty array means "no
154
+ // facet columns" (e.g. a browse panel whose only control is a sheet-level
155
+ // search), not "please generate from the data". Auto-gen runs only when
156
+ // no `columnSpec` was passed.
157
+ deferColumnSpec: columnSpec$1 != null,
182
158
  editable: interactionOptions.enableEditing,
183
159
  enableColumnReordering,
184
160
  data,
@@ -239,18 +215,13 @@ function DataSheetProviderInner(props) {
239
215
  return children;
240
216
  }
241
217
  function useStoreAPI() {
242
- const store = ctx.useValue(storeAPIAtom);
243
- if (!store) {
244
- throw new Error("Missing DataSheetProvider");
245
- }
246
- return store;
218
+ return scopedStore.useZustandStoreAPI(ctx);
247
219
  }
248
220
  function useSelector(selector) {
249
- const store = useStoreAPI();
250
- return zustand.useStore(store, selector);
221
+ return scopedStore.useZustandSelector(ctx, selector);
251
222
  }
252
- const columnSpecAtom = jotai.atom((get) => get(storeAtom)?.columnSpec ?? []);
253
- const tableDataAtom = jotai.atom(
223
+ const columnSpecAtom = scopedStore.atom((get) => get(storeAtom)?.columnSpec ?? []);
224
+ const tableDataAtom = scopedStore.atom(
254
225
  (get) => {
255
226
  return get(storeAtom)?.data ?? [];
256
227
  },
@@ -331,14 +302,14 @@ function remapOverlayByIdentity(state, newData) {
331
302
  pending
332
303
  };
333
304
  }
334
- const contentLabelsAtom = jotai.atom({
305
+ const contentLabelsAtom = scopedStore.atom({
335
306
  tableName: null,
336
307
  itemLabel: null
337
308
  });
338
- const itemLabelAtom = jotai.atom((get) => {
309
+ const itemLabelAtom = scopedStore.atom((get) => {
339
310
  return get(contentLabelsAtom).itemLabel ?? "row";
340
311
  });
341
- const tableNameAtom = jotai.atom((get) => {
312
+ const tableNameAtom = scopedStore.atom((get) => {
342
313
  let { tableName, itemLabel } = get(contentLabelsAtom);
343
314
  if (tableName != null) return tableName;
344
315
  if (itemLabel != null) capitalize(pluralize(itemLabel, 2));
@@ -1 +1 @@
1
- {"version":3,"file":"core.cjs","sources":["../../src/provider/core.ts"],"sourcesContent":["import { SetStateAction, useEffect, useMemo, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport { createScopedStore } from \"@macrostrat/data-components\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { atomWithStore } from \"jotai-zustand\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport { atom } from \"jotai\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n TableDataProvider,\n} from \"./table-data.ts\";\nimport { ErrorBoundary, ToasterContext } from \"@macrostrat/ui-components\";\nimport {\n DataViewRendererType,\n InteractionOptions,\n interactionOptionsAtom,\n interactionOptionsKeys,\n resolveInteractionOptions,\n} from \"./interactions.ts\";\nimport { DataViewProps } from \"../data-view.ts\";\nimport { DataSheetProps } from \"../types.ts\";\nimport { DataPanelProps } from \"../data-panel.ts\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();\n\nconst storeWrapperAtom = atom((get) => {\n const _storeAPIAtom = get(storeAPIAtom);\n if (_storeAPIAtom == null) {\n return undefined;\n }\n return atomWithStore(_storeAPIAtom);\n});\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = atom(\n (get) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n return undefined;\n }\n return get(storeWrapper);\n },\n (get, set, action: SetStateAction<any>) => {\n const storeWrapper = get(storeWrapperAtom);\n if (storeWrapper == null) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return set(storeWrapper, action);\n },\n);\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<any>>) => {\n set(storeAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\n/** The resolved data source for the table, held in the provider layer (next to\n * the store) rather than resolved inside the render loop. `provider` is the\n * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local\n * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it\n * loads the whole array at once and shows no load progress). `isExplicitProvider`\n * distinguishes an explicit `provider` object from a loose `fetchData`/`data`\n * source — only an explicit provider without `deleteRows` disables row\n * deletion; loose sources keep the local delete overlay. */\nexport interface ResolvedDataProvider {\n provider: TableDataProvider<any> | null;\n isLocalProvider: boolean;\n isExplicitProvider: boolean;\n /** Row count of an in-memory (local) source, so a renderer can size the\n * loader's page to \"all of it\" without also receiving the `data` prop. `0`\n * for non-local sources. */\n localCount: number;\n}\n\nconst DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {\n provider: null,\n isLocalProvider: true,\n isExplicitProvider: false,\n localCount: 0,\n};\n\nexport const dataProviderAtom = atom<ResolvedDataProvider>(\n DEFAULT_DATA_PROVIDER,\n);\n\nconst EMPTY_ARRAY: any[] = [];\n\n/** Resolve a table's data source from the loose `provider` / `fetchData` /\n * `data` props (an explicit `provider` wins; else a loose `fetchData` (+\n * `identity`) is wrapped as one; else in-memory `data` becomes a local\n * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three\n * resolve identically. */\nexport function useResolvedProvider<T>(props: {\n provider?: TableDataProvider<T>;\n fetchData?: FetchData<T>;\n data?: T[];\n identity?: (row: T) => string | number | null | undefined;\n}): {\n data: T[];\n isLocalProvider: boolean;\n activeProvider: TableDataProvider<any> | null;\n dataProvider: ResolvedDataProvider;\n} {\n const _data = props.data ?? (EMPTY_ARRAY as T[]);\n const isLocalProvider = props.provider == null && props.fetchData == null;\n const isExplicitProvider = props.provider != null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (props.provider != null) return props.provider;\n if (props.fetchData != null) {\n return {\n fetchData: props.fetchData,\n identity: props.identity ?? ((r: any) => r?.id),\n } as TableDataProvider<any>;\n }\n if (_data.length > 0) {\n return createLocalProvider(\n _data,\n props.identity != null\n ? { identity: props.identity as (row: any) => string | number }\n : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.provider, props.fetchData, _data, props.identity]);\n const localCount = isLocalProvider ? _data.length : 0;\n const dataProvider = useMemo(\n () => ({\n provider: activeProvider,\n isLocalProvider,\n isExplicitProvider,\n localCount,\n }),\n [activeProvider, isLocalProvider, isExplicitProvider, localCount],\n );\n return { data: _data, isLocalProvider, activeProvider, dataProvider };\n}\n\nfunction DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {\n const { toaster, ...rest } = props;\n const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(createZustandStore);\n });\n return h(\n ctx.Provider,\n {\n atoms: [\n [storeAPIAtom, store],\n [toasterAtom, toaster],\n ],\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\n \"columnSpec\",\n \"columnSpecOptions\",\n \"name\",\n \"itemLabel\",\n \"enableColumnReordering\",\n \"defaultColumnWidth\",\n \"refreshToken\",\n \"identity\",\n \"toaster\",\n \"viewType\",\n \"interactionOptions\",\n]);\n\ntype AnyDataSheetProps<T> =\n | DataViewProps<T>\n | DataPanelProps<T>\n | DataSheetProps<T>;\n\nexport function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {\n /** Split provided props based on provider's needs */\n return splitProps<AnyDataSheetProps<T>, DataSheetProviderProps<T>>(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\n}\n\nexport function DataSheetProvider<T>(\n props: DataSheetProviderProps<T> & { children: React.ReactNode },\n) {\n return h(\n ToasterContext,\n h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),\n );\n}\n\ntype DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {\n dataProvider?: ResolvedDataProvider;\n};\n\nexport function DataSheetProviderInner<T>(\n props: DataSheetProviderInnerProps<T>,\n) {\n const tableRef = useRef<Table>(null);\n\n const [interactionOptionsProps, providerProps] = splitProps<\n DataSheetProviderInnerProps<T>,\n InteractionOptions\n >(props, interactionOptionsKeys);\n const interactionOptions = resolveInteractionOptions(\n interactionOptionsProps,\n props.viewType ?? DataViewRendererType.TABLE,\n );\n\n const {\n children,\n columnSpec,\n columnSpecOptions,\n name,\n itemLabel,\n enableColumnReordering,\n defaultColumnWidth = 150,\n refreshToken,\n identity,\n } = providerProps;\n\n const { data, dataProvider } = useResolvedProvider<T>(providerProps);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n const storeAPI = useStoreAPI<T>();\n\n // The wrapper resolves the data source (see `DataSheet`); publish it into the\n // scoped atom so the loader/store read it, rather than the inner render\n // component resolving it each render. Kept updated as `data`/`provider`\n // changes.\n\n ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);\n ctx.useSync(interactionOptionsAtom, interactionOptions);\n\n const contentLabels = useMemo(() => {\n return { tableName: name, itemLabel };\n }, [name, itemLabel]);\n\n ctx.useSync(contentLabelsAtom, contentLabels);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n // Not sure how required this initialization is\n const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);\n\n useEffect(() => {\n initializeStore({\n columnSpec: postprocessColumnSpec(baseSpec),\n // A function spec is derived from the loaded rows in `_DataSheet`; tell\n // the loader not to auto-generate a plain spec from the first chunk.\n deferColumnSpec: isFnSpec,\n editable: interactionOptions.enableEditing,\n enableColumnReordering,\n data,\n defaultColumnWidth,\n tableRef,\n });\n }, [\n data,\n interactionOptions.enableEditing,\n staticSpec,\n isFnSpec,\n columnSpecOptions,\n enableColumnReordering,\n ]);\n\n // Function `columnSpec`: derive the spec from the loaded rows (no separate\n // fetch of sample data), here at the provider level so BOTH renderers get it\n // — the sheet's cell grid and the panel's `FacetControls` read the same\n // derived spec. Derive once the first rows arrive, and re-derive when the\n // function's identity changes (a consumer memoizes it over its own view state\n // — hidden columns, order, overrides). Guarded by the function identity, so\n // it never re-runs as more rows page in (which would clobber in-store column\n // state on scroll).\n const loadedData = useSelector<T, T[]>((s) => s.data ?? []);\n const derivedSpecFor = useRef<unknown>(null);\n useEffect(() => {\n if (typeof columnSpec !== \"function\") return;\n if (derivedSpecFor.current === columnSpec) return;\n const rows = loadedData.filter((r) => r != null);\n if (rows.length === 0) return;\n derivedSpecFor.current = columnSpec;\n storeAPI.setState({ columnSpec: columnSpec(rows) });\n }, [columnSpec, loadedData, storeAPI]);\n\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.\n // after a save). Skips the initial mount (the loader does its own first\n // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one\n // provider-level `refreshToken`, whichever renderer is mounted.\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefresh((v) => v + 1);\n }, [refreshToken, bumpRefresh]);\n\n // Provider-backed, auto-refreshing row mutations on the action context\n // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and\n // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit\n // action persists through the active provider and then re-fetches. Only the\n // capabilities the provider supports are present.\n useEffect(() => {\n const p = dataProvider?.provider ?? null;\n const refresh = () => bumpRefresh((v) => v + 1);\n const withRefresh = <A extends any[]>(\n fn?: (...args: A) => Promise<void>,\n ) =>\n fn == null\n ? undefined\n : async (...args: A) => {\n await fn(...args);\n refresh();\n };\n storeAPI.setState({\n rowEditing: {\n saveRows: withRefresh(p?.saveRows?.bind(p)),\n deleteRows: withRefresh(p?.deleteRows?.bind(p)),\n insertRow: withRefresh(p?.insertRow?.bind(p)),\n refresh,\n },\n });\n }, [storeAPI, dataProvider, bumpRefresh]);\n\n // The active provider supplies the row identity for the edit overlay\n // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and\n // `_DataPanel` — falls back to the loose `identity` prop when the resolved\n // provider doesn't carry its own (e.g. before the first row loads).\n useEffect(() => {\n const id = dataProvider?.provider?.identity ?? identity;\n if (id != null) storeAPI.setState({ identity: id });\n }, [storeAPI, dataProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` (not a loose\n // `fetchData`/`data` source) without `deleteRows` disables deletion\n // entirely. Loose/local sources keep the in-table delete overlay. Shared by\n // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state\n // read by the shared `ActionsToolbar`.\n useEffect(() => {\n const canDeleteRows =\n !dataProvider?.isExplicitProvider ||\n dataProvider.provider?.deleteRows != null;\n storeAPI.setState({ canDeleteRows });\n }, [storeAPI, dataProvider]);\n\n return children;\n}\n\nexport function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {\n const store = ctx.useValue(storeAPIAtom);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n // Auto-generate a plain column spec the first time real rows arrive — no\n // spec yet and none deferred to a function (a function spec is derived\n // separately). Keyed on \"spec still empty + a non-null row present\", NOT\n // on `data.length == 0`: the loader pre-fills `data` with a page of `null`\n // ghost rows on reset, so the array is non-empty before the first chunk.\n if (state.columnSpec.length == 0 && !state.deferColumnSpec) {\n const sample = newData.filter((row) => row != null);\n if (sample.length > 0) {\n next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);\n }\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n\ninterface ContentLabels {\n tableName: string | null | undefined;\n itemLabel: string | null | undefined;\n}\n\nconst contentLabelsAtom = atom<ContentLabels>({\n tableName: null,\n itemLabel: null,\n});\n\nexport const itemLabelAtom = atom<string>((get) => {\n return get(contentLabelsAtom).itemLabel ?? \"row\";\n});\nexport const tableNameAtom = atom<string | null>((get) => {\n let { tableName, itemLabel } = get(contentLabelsAtom);\n if (tableName != null) return tableName;\n if (itemLabel != null) capitalize(pluralize(itemLabel, 2));\n return \"Table\";\n});\n\nexport function useItemCount(n: number) {\n const dataKind = ctx.useValue(itemLabelAtom);\n return itemCount(n, dataKind ?? \"row\");\n}\n\nfunction itemCount(n: number, dataKind: string) {\n const base = n == 0 ? \"No\" : `${n}`;\n return base + \" \" + pluralize(dataKind, n);\n}\n\nexport function pluralize(singularForm: string, n: number) {\n const pluralForm = singularForm + \"s\";\n if (n == 0) return `${pluralForm}`;\n if (n == 1) return singularForm;\n return pluralForm;\n}\n\nexport function capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"names":["createScopedStore","atom","atomWithStore","useMemo","createLocalProvider","useState","createStore","createZustandStore","h","toasterAtom","splitProps","interactionOptionsKeys","ToasterContext","ErrorBoundary","useRef","resolveInteractionOptions","DataViewRendererType","columnSpec","interactionOptionsAtom","generateColumnSpec","useEffect","postprocessColumnSpec","dataRefreshTokenAtom","useStore","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;;;;;AA0CO,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,WAAgC;AACzC,UAAM,eAAe,IAAI,gBAAgB;AACzC,QAAI,gBAAgB,MAAM;AACxB,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AACA,WAAO,IAAI,cAAc,MAAM;AAAA,EACjC;AACF;AAIA,MAAM,aAA2B,CAAA;AAEjC,MAAM,sBAAsBA,MAAAA;AAAAA,EAC1B;AAAA,EACA,CAAC,KAAK,KAAK,YAA0C;AACnD,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;AAoBtD,MAAM,wB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,aAAa;AAC7C,CAAC;AACM,MAAM,gBAAgBA,MAAAA,KAAoB,CAAC,QAAQ;AACxD,MAAI,EAAE,WAAW,cAAc,IAAI,iBAAiB;AACpD,MAAI,aAAa,KAAM,QAAO;AAC9B,MAAI,aAAa,KAAM,YAAW,UAAU,WAAW,CAAC,CAAC;AACzD,SAAO;AACT,CAAC;AAEM,SAAS,aAAa,GAAW;AACtC,QAAM,WAAW,IAAI,SAAS,aAAa;AAC3C,SAAO,UAAU,GAAG,YAAY,KAAK;AACvC;AAEA,SAAS,UAAU,GAAW,UAAkB;AAC9C,QAAM,OAAO,KAAK,IAAI,OAAO,GAAG,CAAC;AACjC,SAAO,OAAO,MAAM,UAAU,UAAU,CAAC;AAC3C;AAEO,SAAS,UAAU,cAAsB,GAAW;AACzD,QAAM,aAAa,eAAe;AAClC,MAAI,KAAK,EAAG,QAAO,GAAG,UAAU;AAChC,MAAI,KAAK,EAAG,QAAO;AACnB,SAAO;AACT;AAEO,SAAS,WAAW,GAAW;AACpC,SAAO,EAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC;AAC9C;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"core.cjs","sources":["../../src/provider/core.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { Table } from \"@blueprintjs/table\";\nimport {\n type ColumnSpec,\n generateColumnSpec,\n postprocessColumnSpec,\n} from \"./column-spec.ts\";\nimport { splitProps } from \"../utils\";\nimport {\n createScopedStore,\n zustandAPIAtom,\n zustandStoreAtom,\n atom,\n ZustandStoreProvider,\n useZustandSelector,\n useZustandStoreAPI,\n} from \"@macrostrat/scoped-store\";\nimport {\n DataSheetProviderProps,\n DataSheetState,\n DataSheetStore,\n DS_ROW_ID,\n TableElementStatus,\n} from \"./types.ts\";\nimport { createZustandStore } from \"./zustand-store.ts\";\nimport { toasterAtom } from \"../notifications.ts\";\nimport { TableAction } from \"../actions\";\nimport {\n createLocalProvider,\n dataRefreshTokenAtom,\n FetchData,\n TableDataProvider,\n} from \"./table-data.ts\";\nimport { ErrorBoundary, ToasterContext } from \"@macrostrat/ui-components\";\nimport {\n DataViewRendererType,\n InteractionOptions,\n interactionOptionsAtom,\n interactionOptionsKeys,\n resolveInteractionOptions,\n} from \"./interactions.ts\";\nimport { DataViewProps } from \"../data-view.ts\";\nimport { DataSheetProps } from \"../types.ts\";\nimport { DataPanelProps } from \"../data-panel.ts\";\n\n/** Create a Jotai scoped store */\nexport const ctx = createScopedStore();\n\nexport const storeAPIAtom = zustandAPIAtom;\n\n/** This is the basis for all other atoms that manipulate the store. */\nexport const storeAtom = zustandStoreAtom;\n\n/** Stable empty spec so a function `columnSpec` yields a constant init value\n * (see `DataSheetProviderInner`). */\nconst EMPTY_SPEC: ColumnSpec[] = [];\n\nconst initializeStoreAtom = atom(\n null,\n (get, set, payload: Partial<DataSheetStore<any>>) => {\n set(zustandStoreAtom, (state) => {\n return {\n ...state,\n ...payload,\n };\n });\n },\n);\n\nexport const tableActionsAtom = atom<TableAction[]>([]);\n\n/** The resolved data source for the table, held in the provider layer (next to\n * the store) rather than resolved inside the render loop. `provider` is the\n * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local\n * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it\n * loads the whole array at once and shows no load progress). `isExplicitProvider`\n * distinguishes an explicit `provider` object from a loose `fetchData`/`data`\n * source — only an explicit provider without `deleteRows` disables row\n * deletion; loose sources keep the local delete overlay. */\nexport interface ResolvedDataProvider {\n provider: TableDataProvider<any> | null;\n isLocalProvider: boolean;\n isExplicitProvider: boolean;\n /** Row count of an in-memory (local) source, so a renderer can size the\n * loader's page to \"all of it\" without also receiving the `data` prop. `0`\n * for non-local sources. */\n localCount: number;\n}\n\nconst DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {\n provider: null,\n isLocalProvider: true,\n isExplicitProvider: false,\n localCount: 0,\n};\n\nexport const dataProviderAtom = atom<ResolvedDataProvider>(\n DEFAULT_DATA_PROVIDER,\n);\n\nconst EMPTY_ARRAY: any[] = [];\n\n/** Resolve a table's data source from the loose `provider` / `fetchData` /\n * `data` props (an explicit `provider` wins; else a loose `fetchData` (+\n * `identity`) is wrapped as one; else in-memory `data` becomes a local\n * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three\n * resolve identically. */\nexport function useResolvedProvider<T>(props: {\n provider?: TableDataProvider<T>;\n fetchData?: FetchData<T>;\n data?: T[];\n identity?: (row: T) => string | number | null | undefined;\n}): {\n data: T[];\n isLocalProvider: boolean;\n activeProvider: TableDataProvider<any> | null;\n dataProvider: ResolvedDataProvider;\n} {\n const _data = props.data ?? (EMPTY_ARRAY as T[]);\n const isLocalProvider = props.provider == null && props.fetchData == null;\n const isExplicitProvider = props.provider != null;\n const activeProvider = useMemo<TableDataProvider<any> | null>(() => {\n if (props.provider != null) return props.provider;\n if (props.fetchData != null) {\n return {\n fetchData: props.fetchData,\n identity: props.identity ?? ((r: any) => r?.id),\n } as TableDataProvider<any>;\n }\n if (_data.length > 0) {\n return createLocalProvider(\n _data,\n props.identity != null\n ? { identity: props.identity as (row: any) => string | number }\n : undefined,\n );\n }\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.provider, props.fetchData, _data, props.identity]);\n const localCount = isLocalProvider ? _data.length : 0;\n const dataProvider = useMemo(\n () => ({\n provider: activeProvider,\n isLocalProvider,\n isExplicitProvider,\n localCount,\n }),\n [activeProvider, isLocalProvider, isExplicitProvider, localCount],\n );\n return { data: _data, isLocalProvider, activeProvider, dataProvider };\n}\n\nfunction DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {\n const { toaster, ...rest } = props;\n return h(\n ZustandStoreProvider,\n {\n ctx,\n initializeStore: createZustandStore,\n atoms: [[toasterAtom, toaster]],\n debugName: \"DataSheetProvider\",\n },\n h(DataSheetProviderInner, rest),\n );\n}\n\nconst tableDataProviderKeys = new Set([\n \"provider\",\n \"fetchData\",\n \"data\",\n \"identity\",\n]);\n\nconst dataProviderKeys = new Set([\n \"columnSpec\",\n \"columnSpecOptions\",\n \"name\",\n \"itemLabel\",\n \"enableColumnReordering\",\n \"defaultColumnWidth\",\n \"refreshToken\",\n \"identity\",\n \"toaster\",\n \"viewType\",\n \"interactionOptions\",\n]);\n\ntype AnyDataSheetProps<T> =\n DataViewProps<T> | DataPanelProps<T> | DataSheetProps<T>;\n\nexport function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {\n /** Split provided props based on provider's needs */\n return splitProps<AnyDataSheetProps<T>, DataSheetProviderProps<T>>(\n props,\n dataProviderKeys\n .union(interactionOptionsKeys)\n .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,\n );\n}\n\nexport function DataSheetProvider<T>(\n props: DataSheetProviderProps<T> & { children: React.ReactNode },\n) {\n return h(\n ToasterContext,\n h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),\n );\n}\n\ntype DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {\n dataProvider?: ResolvedDataProvider;\n};\n\nexport function DataSheetProviderInner<T>(\n props: DataSheetProviderInnerProps<T>,\n) {\n const tableRef = useRef<Table>(null);\n\n const [interactionOptionsProps, providerProps] = splitProps<\n DataSheetProviderInnerProps<T>,\n InteractionOptions\n >(props, interactionOptionsKeys);\n const interactionOptions = resolveInteractionOptions(\n interactionOptionsProps,\n props.viewType ?? DataViewRendererType.TABLE,\n );\n\n const {\n children,\n columnSpec,\n columnSpecOptions,\n name,\n itemLabel,\n enableColumnReordering,\n defaultColumnWidth = 150,\n refreshToken,\n identity,\n } = providerProps;\n\n const { data, dataProvider } = useResolvedProvider<T>(providerProps);\n\n const initializeStore = ctx.useSet(initializeStoreAtom);\n const storeAPI = useStoreAPI<T>();\n\n // The wrapper resolves the data source (see `DataSheet`); publish it into the\n // scoped atom so the loader/store read it, rather than the inner render\n // component resolving it each render. Kept updated as `data`/`provider`\n // changes.\n\n ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);\n ctx.useSync(interactionOptionsAtom, interactionOptions);\n\n const contentLabels = useMemo(() => {\n return { tableName: name, itemLabel };\n }, [name, itemLabel]);\n\n ctx.useSync(contentLabelsAtom, contentLabels);\n\n // A function `columnSpec` is derived from the loaded rows later (in\n // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the\n // init effect's deps: re-running init also resets `data`, so re-initializing\n // when the function's identity changes (e.g. a consumer hiding a column)\n // would wipe the loaded rows. `staticSpec` is a stable value in that case.\n const isFnSpec = typeof columnSpec === \"function\";\n\n const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;\n // Not sure how required this initialization is\n const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);\n\n useEffect(() => {\n initializeStore({\n columnSpec: postprocessColumnSpec(baseSpec),\n // Suppress the loader's first-chunk auto-generation whenever the consumer\n // provided a spec at all — a function (derived later in `_DataSheet`) OR\n // an explicit array, *including an empty one*. An empty array means \"no\n // facet columns\" (e.g. a browse panel whose only control is a sheet-level\n // search), not \"please generate from the data\". Auto-gen runs only when\n // no `columnSpec` was passed.\n deferColumnSpec: columnSpec != null,\n editable: interactionOptions.enableEditing,\n enableColumnReordering,\n data,\n defaultColumnWidth,\n tableRef,\n });\n }, [\n data,\n interactionOptions.enableEditing,\n staticSpec,\n isFnSpec,\n columnSpecOptions,\n enableColumnReordering,\n ]);\n\n // Function `columnSpec`: derive the spec from the loaded rows (no separate\n // fetch of sample data), here at the provider level so BOTH renderers get it\n // — the sheet's cell grid and the panel's `FacetControls` read the same\n // derived spec. Derive once the first rows arrive, and re-derive when the\n // function's identity changes (a consumer memoizes it over its own view state\n // — hidden columns, order, overrides). Guarded by the function identity, so\n // it never re-runs as more rows page in (which would clobber in-store column\n // state on scroll).\n const loadedData = useSelector<T, T[]>((s) => s.data ?? []);\n const derivedSpecFor = useRef<unknown>(null);\n useEffect(() => {\n if (typeof columnSpec !== \"function\") return;\n if (derivedSpecFor.current === columnSpec) return;\n const rows = loadedData.filter((r) => r != null);\n if (rows.length === 0) return;\n derivedSpecFor.current = columnSpec;\n storeAPI.setState({ columnSpec: columnSpec(rows) });\n }, [columnSpec, loadedData, storeAPI]);\n\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n\n // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.\n // after a save). Skips the initial mount (the loader does its own first\n // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one\n // provider-level `refreshToken`, whichever renderer is mounted.\n const firstRefreshToken = useRef(true);\n useEffect(() => {\n if (firstRefreshToken.current) {\n firstRefreshToken.current = false;\n return;\n }\n bumpRefresh((v) => v + 1);\n }, [refreshToken, bumpRefresh]);\n\n // Provider-backed, auto-refreshing row mutations on the action context\n // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and\n // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit\n // action persists through the active provider and then re-fetches. Only the\n // capabilities the provider supports are present.\n useEffect(() => {\n const p = dataProvider?.provider ?? null;\n const refresh = () => bumpRefresh((v) => v + 1);\n const withRefresh = <A extends any[]>(\n fn?: (...args: A) => Promise<void>,\n ) =>\n fn == null\n ? undefined\n : async (...args: A) => {\n await fn(...args);\n refresh();\n };\n storeAPI.setState({\n rowEditing: {\n saveRows: withRefresh(p?.saveRows?.bind(p)),\n deleteRows: withRefresh(p?.deleteRows?.bind(p)),\n insertRow: withRefresh(p?.insertRow?.bind(p)),\n refresh,\n },\n });\n }, [storeAPI, dataProvider, bumpRefresh]);\n\n // The active provider supplies the row identity for the edit overlay\n // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and\n // `_DataPanel` — falls back to the loose `identity` prop when the resolved\n // provider doesn't carry its own (e.g. before the first row loads).\n useEffect(() => {\n const id = dataProvider?.provider?.identity ?? identity;\n if (id != null) storeAPI.setState({ identity: id });\n }, [storeAPI, dataProvider, identity]);\n\n // Row deletion is a provider capability: an explicit `provider` (not a loose\n // `fetchData`/`data` source) without `deleteRows` disables deletion\n // entirely. Loose/local sources keep the in-table delete overlay. Shared by\n // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state\n // read by the shared `ActionsToolbar`.\n useEffect(() => {\n const canDeleteRows =\n !dataProvider?.isExplicitProvider ||\n dataProvider.provider?.deleteRows != null;\n storeAPI.setState({ canDeleteRows });\n }, [storeAPI, dataProvider]);\n\n return children;\n}\n\nexport function useStoreAPI<T>() {\n return useZustandStoreAPI<DataSheetStore<T>>(ctx);\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T>) => A,\n): A {\n return useZustandSelector<T, A>(ctx, selector);\n}\n/** Atoms for efficient sub-selection of state */\n\nexport const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);\n\nexport const tableDataAtom = atom(\n (get) => {\n return get(storeAtom)?.data ?? [];\n },\n (get, set, newData: any[]) => {\n set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {\n let next: DataSheetState<any> = { ...state, data: newData };\n // Auto-generate a plain column spec the first time real rows arrive — no\n // spec yet and none deferred to a function (a function spec is derived\n // separately). Keyed on \"spec still empty + a non-null row present\", NOT\n // on `data.length == 0`: the loader pre-fills `data` with a page of `null`\n // ghost rows on reset, so the array is non-empty before the first chunk.\n if (state.columnSpec.length == 0 && !state.deferColumnSpec) {\n const sample = newData.filter((row) => row != null);\n if (sample.length > 0) {\n next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);\n }\n }\n\n // Re-attach the edit overlay by identity. The loader replaces `data` with\n // re-ordered windows on sort/filter, so an index-keyed overlay would\n // smear; keying by identity keeps edits (and deletes) on their rows, holds\n // edits for not-yet-loaded rows, and re-appends locally-added rows (which\n // aren't in the provider's data) after it. Skipped when the consumer\n // controls the overlay (they own reconciliation).\n if (!state.controlledOverlay) {\n const remap = remapOverlayByIdentity(state, newData);\n next.data = remap.data;\n next.updatedData = remap.updatedData;\n next.rowStatus = remap.rowStatus;\n next.pendingOverlayById = remap.pending;\n }\n\n return next;\n });\n },\n);\n\ntype OverlayEntry = { edit?: any; status?: any };\n\n/** Row identity used by the overlay: an in-table-added row's synthetic id\n * (stable across its edits), else the provider/consumer `identity`. */\nfunction overlayIdentity(\n state: DataSheetState<any>,\n row: any,\n): string | number | null | undefined {\n if (row == null) return undefined;\n const added = row[DS_ROW_ID];\n if (added != null) return added;\n return state.identity(row);\n}\n\n/** Re-project the (index-keyed) edit overlay from the old `data` order onto a\n * new one, matching rows by identity. Edits/statuses whose row is absent from\n * `newData` are held in `pending` and re-applied when the row loads; rows added\n * in-table (status `ADDED`) are re-appended after the provider data (they have\n * no provider row). Starts from the prior pending set so edits survive multiple\n * re-sorts. Returns the reconstructed data (provider rows + re-appended added\n * rows) alongside the re-aligned overlay. */\nfunction remapOverlayByIdentity(\n state: DataSheetState<any>,\n newData: any[],\n): {\n data: any[];\n updatedData: any[];\n rowStatus: any[];\n pending: Map<string | number, OverlayEntry>;\n} {\n const { data: oldData, updatedData, rowStatus } = state;\n\n // Collect current overlay entries by identity, seeded with prior pending.\n const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);\n const n = Math.max(\n oldData.length,\n updatedData?.length ?? 0,\n rowStatus?.length ?? 0,\n );\n for (let i = 0; i < n; i++) {\n const row = oldData[i];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const edit = updatedData?.[i];\n const status = rowStatus?.[i];\n if (edit != null || status != null) byId.set(id, { edit, status });\n }\n\n // Project onto the new data order.\n const resultData = newData.slice();\n const nextUpdated: any[] = [];\n const nextStatus: any[] = [];\n const attached = new Set<string | number>();\n for (let j = 0; j < resultData.length; j++) {\n const row = resultData[j];\n if (row == null) continue;\n const id = overlayIdentity(state, row);\n if (id == null) continue;\n const entry = byId.get(id);\n if (entry == null) continue;\n if (entry.edit != null) nextUpdated[j] = entry.edit;\n if (entry.status != null) nextStatus[j] = entry.status;\n attached.add(id);\n }\n\n // Re-append in-table-added rows (not present in the provider data), then hold\n // anything still unattached (rows not currently loaded) as pending.\n const pending = new Map<string | number, OverlayEntry>();\n for (const [id, entry] of byId) {\n if (attached.has(id)) continue;\n if (entry.status === TableElementStatus.ADDED) {\n const idx = resultData.length;\n resultData.push(entry.edit ?? {});\n nextUpdated[idx] = entry.edit;\n nextStatus[idx] = entry.status;\n } else {\n pending.set(id, entry);\n }\n }\n\n return {\n data: resultData,\n updatedData: nextUpdated,\n rowStatus: nextStatus,\n pending,\n };\n}\n\ninterface ContentLabels {\n tableName: string | null | undefined;\n itemLabel: string | null | undefined;\n}\n\nconst contentLabelsAtom = atom<ContentLabels>({\n tableName: null,\n itemLabel: null,\n});\n\nexport const itemLabelAtom = atom<string>((get) => {\n return get(contentLabelsAtom).itemLabel ?? \"row\";\n});\nexport const tableNameAtom = atom<string | null>((get) => {\n let { tableName, itemLabel } = get(contentLabelsAtom);\n if (tableName != null) return tableName;\n if (itemLabel != null) capitalize(pluralize(itemLabel, 2));\n return \"Table\";\n});\n\nexport function useItemCount(n: number) {\n const dataKind = ctx.useValue(itemLabelAtom);\n return itemCount(n, dataKind ?? \"row\");\n}\n\nfunction itemCount(n: number, dataKind: string) {\n const base = n == 0 ? \"No\" : `${n}`;\n return base + \" \" + pluralize(dataKind, n);\n}\n\nexport function pluralize(singularForm: string, n: number) {\n const pluralForm = singularForm + \"s\";\n if (n == 0) return `${pluralForm}`;\n if (n == 1) return singularForm;\n return pluralForm;\n}\n\nexport function capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"names":["createScopedStore","zustandAPIAtom","zustandStoreAtom","atom","useMemo","createLocalProvider","h","ZustandStoreProvider","createZustandStore","toasterAtom","splitProps","interactionOptionsKeys","ToasterContext","ErrorBoundary","useRef","resolveInteractionOptions","DataViewRendererType","columnSpec","interactionOptionsAtom","generateColumnSpec","useEffect","postprocessColumnSpec","dataRefreshTokenAtom","useZustandStoreAPI","useZustandSelector","DS_ROW_ID","TableElementStatus"],"mappings":";;;;;;;;;;;;;;;A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;AAAA,IACN,aAAa;AAAA,IACb,WAAW;AAAA,IACX;AAAA,EAAA;AAEJ;AAOA,MAAM,oBAAoBvB,YAAAA,KAAoB;AAAA,EAC5C,WAAW;AAAA,EACX,WAAW;AACb,CAAC;AAEM,MAAM,gBAAgBA,YAAAA,KAAa,CAAC,QAAQ;AACjD,SAAO,IAAI,iBAAiB,EAAE,aAAa;AAC7C,CAAC;AACM,MAAM,gBAAgBA,YAAAA,KAAoB,CAAC,QAAQ;AACxD,MAAI,EAAE,WAAW,cAAc,IAAI,iBAAiB;AACpD,MAAI,aAAa,KAAM,QAAO;AAC9B,MAAI,aAAa,KAAM,YAAW,UAAU,WAAW,CAAC,CAAC;AACzD,SAAO;AACT,CAAC;AAEM,SAAS,aAAa,GAAW;AACtC,QAAM,WAAW,IAAI,SAAS,aAAa;AAC3C,SAAO,UAAU,GAAG,YAAY,KAAK;AACvC;AAEA,SAAS,UAAU,GAAW,UAAkB;AAC9C,QAAM,OAAO,KAAK,IAAI,OAAO,GAAG,CAAC;AACjC,SAAO,OAAO,MAAM,UAAU,UAAU,CAAC;AAC3C;AAEO,SAAS,UAAU,cAAsB,GAAW;AACzD,QAAM,aAAa,eAAe;AAClC,MAAI,KAAK,EAAG,QAAO,GAAG,UAAU;AAChC,MAAI,KAAK,EAAG,QAAO;AACnB,SAAO;AACT;AAEO,SAAS,WAAW,GAAW;AACpC,SAAO,EAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC;AAC9C;;;;;;;;;;;;;;;;;;;"}
@@ -1,5 +1,3 @@
1
- import { StoreApi } from 'zustand';
2
- import { ColumnSpec } from './column-spec.ts';
3
1
  import { DataSheetProviderProps, DataSheetStore } from './types.ts';
4
2
  import { TableAction } from '../actions';
5
3
  import { FetchData, TableDataProvider } from './table-data.ts';
@@ -7,12 +5,12 @@ import { DataViewProps } from '../data-view.ts';
7
5
  import { DataSheetProps } from '../types.ts';
8
6
  import { DataPanelProps } from '../data-panel.ts';
9
7
  /** Create a Jotai scoped store */
10
- export declare const ctx: import('@macrostrat/data-components').StateIsolation;
11
- export declare const storeAPIAtom: import('jotai').PrimitiveAtom<StoreApi<DataSheetStore<any>> | undefined> & {
12
- init: StoreApi<DataSheetStore<any>> | undefined;
8
+ export declare const ctx: import('@macrostrat/scoped-store').StateIsolation;
9
+ export declare const storeAPIAtom: import('jotai').PrimitiveAtom<import('zustand').StoreApi<any> | undefined> & {
10
+ init: import('zustand').StoreApi<any> | undefined;
13
11
  };
14
12
  /** This is the basis for all other atoms that manipulate the store. */
15
- export declare const storeAtom: import('jotai').WritableAtom<DataSheetStore<any> | undefined, [action: any], void>;
13
+ export declare const storeAtom: import('jotai').WritableAtom<any, [action: any], void>;
16
14
  export declare const tableActionsAtom: import('jotai').PrimitiveAtom<TableAction<any, null>[]> & {
17
15
  init: TableAction<any, null>[];
18
16
  };
@@ -61,11 +59,11 @@ type DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {
61
59
  dataProvider?: ResolvedDataProvider;
62
60
  };
63
61
  export declare function DataSheetProviderInner<T>(props: DataSheetProviderInnerProps<T>): import('react').ReactNode;
64
- export declare function useStoreAPI<T>(): StoreApi<DataSheetStore<T>>;
62
+ export declare function useStoreAPI<T>(): import('zustand').StoreApi<DataSheetStore<T>>;
65
63
  export declare function useSelector<T = any, A = any>(selector: (state: DataSheetStore<T>) => A): A;
66
64
  /** Atoms for efficient sub-selection of state */
67
- export declare const columnSpecAtom: import('jotai').Atom<ColumnSpec[]>;
68
- export declare const tableDataAtom: import('jotai').WritableAtom<any[], [newData: any[]], void>;
65
+ export declare const columnSpecAtom: import('jotai').Atom<any>;
66
+ export declare const tableDataAtom: import('jotai').WritableAtom<any, [newData: any[]], void>;
69
67
  export declare const itemLabelAtom: import('jotai').Atom<string>;
70
68
  export declare const tableNameAtom: import('jotai').Atom<string | null>;
71
69
  export declare function useItemCount(n: number): string;