@macrostrat/data-sheet 4.4.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/dist/components/indicators/unified-filters.cjs +30 -10
- package/dist/components/indicators/unified-filters.cjs.map +1 -1
- package/dist/components/indicators/unified-filters.js +30 -10
- package/dist/components/indicators/unified-filters.js.map +1 -1
- package/dist/data-panel.cjs +3 -1
- package/dist/data-panel.cjs.map +1 -1
- package/dist/data-panel.d.ts +1 -1
- package/dist/data-panel.js +3 -1
- package/dist/data-panel.js.map +1 -1
- package/dist/data-panel.module.sass.cjs +25 -25
- package/dist/data-panel.module.sass.js +25 -25
- package/dist/data-sheet.cjs +3 -1
- package/dist/data-sheet.cjs.map +1 -1
- package/dist/data-sheet.css +37 -38
- package/dist/data-sheet.d.ts +1 -1
- package/dist/data-sheet.js +3 -1
- package/dist/data-sheet.js.map +1 -1
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/postgrest-table/data-loaders.cjs +67 -2
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.d.ts +8 -1
- package/dist/postgrest-table/data-loaders.js +67 -2
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/provider/core.cjs +23 -2
- package/dist/provider/core.cjs.map +1 -1
- package/dist/provider/core.d.ts +2 -2
- package/dist/provider/core.js +23 -2
- package/dist/provider/core.js.map +1 -1
- package/dist/provider/distinct-values.cjs +65 -0
- package/dist/provider/distinct-values.cjs.map +1 -0
- package/dist/provider/distinct-values.d.ts +21 -0
- package/dist/provider/distinct-values.js +65 -0
- package/dist/provider/distinct-values.js.map +1 -0
- package/dist/provider/index.d.ts +1 -0
- package/dist/provider/table-data.cjs +21 -0
- package/dist/provider/table-data.cjs.map +1 -1
- package/dist/provider/table-data.d.ts +22 -0
- package/dist/provider/table-data.js +21 -0
- package/dist/provider/table-data.js.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +27 -4
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/components/indicators/unified-filters.ts +40 -10
- package/src/data-panel.module.sass +2 -3
- package/src/data-panel.ts +3 -1
- package/src/data-sheet.ts +3 -1
- package/src/postgrest-table/data-loaders.ts +106 -3
- package/src/provider/core.ts +36 -3
- package/src/provider/distinct-values.ts +127 -0
- package/src/provider/index.ts +1 -0
- package/src/provider/table-data.ts +51 -0
- package/src/types.ts +33 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-loaders.cjs","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","adjustArraySize","atom","core","tableDataAtom","ctx","dataProviderAtom","useCallback","useRef","debounce","dataRefreshTokenAtom","useSelector","useMemo","useEffect","useAsyncEffect","useState","PostgrestClient"],"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,K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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.cjs","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, InitialDataChunk } 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 | { type: \"seed\"; data: T[]; totalCount?: number | null }\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 \"seed\": {\n // Rows the caller already had (a server render, say). Same shape as a\n // completed first fetch: pre-size to the reported total so the scrollbar\n // and counter are right immediately, and mark the loader `initialized` so\n // it neither refetches the seeded window nor flashes an empty state.\n const rows = action.data ?? [];\n const size = Math.max(action.totalCount ?? rows.length, rows.length);\n const data: (T | null)[] = new Array(size).fill(null);\n for (let i = 0; i < rows.length; i++) data[i] = rows[i];\n return {\n visibleRegion: defaultVisibleRegion,\n data: data as T[],\n loading: false,\n error: null,\n initialized: true,\n totalCount: action.totalCount ?? null,\n fetchMode: state.fetchMode,\n pageSize: state.pageSize,\n };\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 /** Rows per page. */\n pageSize: number;\n /** Current page index (0-based). Only meaningful in `\"paged\"` fetch mode —\n * scroll mode accumulates windows rather than sitting on a page. */\n page: number;\n /** Total pages when the source reported a total, else `null`. */\n totalPages: number | null;\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 pageSize,\n page: footer.page,\n totalPages: footer.totalPages,\n // Page addressing is exposed so a footer can render a real link to the next\n // page, not just a button that calls `loadMore`. That's the difference\n // between a list a crawler (or a JS-less client) can follow and one it\n // can't — see the note on crawlable pagination in the Data list editors\n // feature doc.\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<T> = {},\n) {\n const {\n pageSize = 100,\n fetchMode = \"scroll\",\n filterDebounce = 0,\n initialData,\n } = 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 // A caller-supplied first window (`initialData`) stands in for the mount-time\n // reset+fetch. It's consumed once: any later view change resets normally,\n // since the seed only describes the view it was fetched for.\n const seedRef = useRef(resolveInitialData(initialData));\n // Gate on the seed until it's actually in state (see the fetch effect).\n const awaitingSeedRef = useRef(seedRef.current != null);\n useEffect(() => {\n const seed = seedRef.current;\n seedRef.current = null;\n if (seed != null) {\n dispatch({ type: \"seed\", data: seed.rows, totalCount: seed.totalCount });\n setPage(0);\n // Paged mode tracks which (page, view) it has in hand separately from the\n // array; record the seed there too, or it would immediately re-fetch the\n // page it was just handed.\n loadedRef.current = { page: 0, viewKey };\n return;\n }\n dispatch({ type: \"reset\" });\n setPage(0);\n }, [debouncedViewKey, fetchMode, refreshToken]);\n\n useAsyncEffect(async () => {\n if (state.loading) return;\n\n // A seed hasn't landed in state yet. Every effect in a commit sees the\n // render's snapshot, so this one runs *before* the seed it was mounted\n // alongside is visible — and would issue exactly the request the seed\n // exists to avoid. Skip until the seeded state arrives.\n if (awaitingSeedRef.current) {\n if (state.initialized) awaitingSeedRef.current = false;\n return;\n }\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. */\n/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a\n * total) to one. An empty seed is treated as no seed — there'd be nothing to\n * show and nothing saved. */\nfunction resolveInitialData<T>(\n initialData: FetchDataOptions<T>[\"initialData\"],\n): InitialDataChunk<T> | null {\n if (initialData == null) return null;\n if (Array.isArray(initialData)) {\n if (initialData.length === 0) return null;\n return { rows: initialData };\n }\n if ((initialData.rows ?? []).length === 0) return null;\n return initialData;\n}\n\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 distinctValues(columnKey, options = {}) {\n // PostgREST derives a GROUP BY from a `select` that mixes a plain column\n // with an aggregate, so one small request returns the whole vocabulary\n // *with* frequencies — rather than paging the table and deduplicating\n // client-side. Ordered by the value so the picker's list is stable.\n //\n // `baseFilter` applies (it defines the rows this view is *about*), but the\n // *active* filters deliberately don't: a picker whose options disappear as\n // you narrow the view can't be used to widen it again.\n let req: any = from().select(`${columnKey},count()`);\n if (config.baseFilter != null) req = config.baseFilter(req);\n req = req.order(columnKey, { ascending: true, nullsFirst: false });\n if (options.limit != null) req = req.limit(options.limit);\n if (options.signal != null) req = req.abortSignal(options.signal);\n const { data, error } = await req;\n if (error != null) throw error;\n return (data ?? []).map((row: any) => ({\n value: row[columnKey],\n count: row.count,\n }));\n },\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","adjustArraySize","data","atom","core","tableDataAtom","ctx","dataProviderAtom","useCallback","useRef","debounce","dataRefreshTokenAtom","useSelector","useMemo","useEffect","useAsyncEffect","useState","PostgrestClient"],"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;AAAA,IACF;AACA,QAAI,GAAG,aAAa,MAAM;AACxB,YAAM,IAAI,SAAS,GAAG,KAAK,gBAAgB,GAAG,KAAK,CAAC;AACpD;AAAA,IACF;AACA,UAAM,MACJ,GAAG,aAAa,UAAU,GAAG,aAAa,UACtC,IAAI,GAAG,KAAK,MACZ,GAAG;AACT,UAAM,IAAI,OAAO,GAAG,KAAK,GAAG,UAAU,GAAG;AAAA,EAC3C;AACA,SAAO;AACT;AAIA,SAAS,gBAAgB,OAAsB;AAC7C,SAAO,OAAO,KAAK,EAChB,MAAM,GAAG,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AAO;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;;;;;;;;;;;;;"}
|
|
@@ -88,6 +88,13 @@ export interface LoadControls {
|
|
|
88
88
|
/** Advance one page *without* resuming a paused auto-load (the sentinel
|
|
89
89
|
* uses this; `loadMore` is the manual, un-pausing variant). */
|
|
90
90
|
advance: () => void;
|
|
91
|
+
/** Rows per page. */
|
|
92
|
+
pageSize: number;
|
|
93
|
+
/** Current page index (0-based). Only meaningful in `"paged"` fetch mode —
|
|
94
|
+
* scroll mode accumulates windows rather than sitting on a page. */
|
|
95
|
+
page: number;
|
|
96
|
+
/** Total pages when the source reported a total, else `null`. */
|
|
97
|
+
totalPages: number | null;
|
|
91
98
|
}
|
|
92
99
|
/** Store-managed load controls (see `LoadControls`). Reads the loader's footer
|
|
93
100
|
* state, the loaded rows, and the pause atoms; `loadMore`/`advance` set the
|
|
@@ -112,7 +119,7 @@ export declare function useScrollHandler(): ((visibleCells: RowRegion) => void)
|
|
|
112
119
|
*
|
|
113
120
|
* Call it from a component rendered inside `DataSheet` (see `ChunkLoaderManager`).
|
|
114
121
|
*/
|
|
115
|
-
export declare function useDataLoader<T = any>(fetchChunk: FetchData<T>, options?: FetchDataOptions): {
|
|
122
|
+
export declare function useDataLoader<T = any>(fetchChunk: FetchData<T>, options?: FetchDataOptions<T>): {
|
|
116
123
|
data: any;
|
|
117
124
|
loading: any;
|
|
118
125
|
error: any;
|
|
@@ -80,6 +80,22 @@ function lazyLoadingReducer(state, action) {
|
|
|
80
80
|
fetchMode: state.fetchMode,
|
|
81
81
|
pageSize: state.pageSize
|
|
82
82
|
};
|
|
83
|
+
case "seed": {
|
|
84
|
+
const rows = action.data ?? [];
|
|
85
|
+
const size = Math.max(action.totalCount ?? rows.length, rows.length);
|
|
86
|
+
const data2 = new Array(size).fill(null);
|
|
87
|
+
for (let i = 0; i < rows.length; i++) data2[i] = rows[i];
|
|
88
|
+
return {
|
|
89
|
+
visibleRegion: defaultVisibleRegion,
|
|
90
|
+
data: data2,
|
|
91
|
+
loading: false,
|
|
92
|
+
error: null,
|
|
93
|
+
initialized: true,
|
|
94
|
+
totalCount: action.totalCount ?? null,
|
|
95
|
+
fetchMode: state.fetchMode,
|
|
96
|
+
pageSize: state.pageSize
|
|
97
|
+
};
|
|
98
|
+
}
|
|
83
99
|
case "error":
|
|
84
100
|
return {
|
|
85
101
|
...state,
|
|
@@ -230,7 +246,15 @@ function useLoadControls() {
|
|
|
230
246
|
total: footer.total,
|
|
231
247
|
paused,
|
|
232
248
|
canLoadMore,
|
|
233
|
-
advance
|
|
249
|
+
advance,
|
|
250
|
+
pageSize,
|
|
251
|
+
page: footer.page,
|
|
252
|
+
totalPages: footer.totalPages
|
|
253
|
+
// Page addressing is exposed so a footer can render a real link to the next
|
|
254
|
+
// page, not just a button that calls `loadMore`. That's the difference
|
|
255
|
+
// between a list a crawler (or a JS-less client) can follow and one it
|
|
256
|
+
// can't — see the note on crawlable pagination in the Data list editors
|
|
257
|
+
// feature doc.
|
|
234
258
|
};
|
|
235
259
|
}
|
|
236
260
|
const viewInfoAtom = atom((get) => {
|
|
@@ -319,7 +343,12 @@ function useScrollHandler() {
|
|
|
319
343
|
);
|
|
320
344
|
}
|
|
321
345
|
function useDataLoader(fetchChunk, options = {}) {
|
|
322
|
-
const {
|
|
346
|
+
const {
|
|
347
|
+
pageSize = 100,
|
|
348
|
+
fetchMode = "scroll",
|
|
349
|
+
filterDebounce = 0,
|
|
350
|
+
initialData
|
|
351
|
+
} = options;
|
|
323
352
|
const [state, dispatch] = useLazyLoaderReducer();
|
|
324
353
|
const { isLocalProvider, provider } = ctx.useValue(dataProviderAtom);
|
|
325
354
|
const visibleRegion = ctx.useValue(visibleRegionAtom);
|
|
@@ -352,12 +381,26 @@ function useDataLoader(fetchChunk, options = {}) {
|
|
|
352
381
|
[columnSorts, filters]
|
|
353
382
|
);
|
|
354
383
|
const debouncedViewKey = useDebouncedValue(viewKey, filterDebounce);
|
|
384
|
+
const seedRef = useRef(resolveInitialData(initialData));
|
|
385
|
+
const awaitingSeedRef = useRef(seedRef.current != null);
|
|
355
386
|
useEffect(() => {
|
|
387
|
+
const seed = seedRef.current;
|
|
388
|
+
seedRef.current = null;
|
|
389
|
+
if (seed != null) {
|
|
390
|
+
dispatch({ type: "seed", data: seed.rows, totalCount: seed.totalCount });
|
|
391
|
+
setPage(0);
|
|
392
|
+
loadedRef.current = { page: 0, viewKey };
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
356
395
|
dispatch({ type: "reset" });
|
|
357
396
|
setPage(0);
|
|
358
397
|
}, [debouncedViewKey, fetchMode, refreshToken]);
|
|
359
398
|
useAsyncEffect(async () => {
|
|
360
399
|
if (state.loading) return;
|
|
400
|
+
if (awaitingSeedRef.current) {
|
|
401
|
+
if (state.initialized) awaitingSeedRef.current = false;
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
361
404
|
let offset;
|
|
362
405
|
let cursor = null;
|
|
363
406
|
if (fetchMode === "paged") {
|
|
@@ -424,6 +467,15 @@ function useDataLoader(fetchChunk, options = {}) {
|
|
|
424
467
|
}, [state.data, visibleRegion, debouncedViewKey, page, fetchMode]);
|
|
425
468
|
return { data: state.data, loading: state.loading, error: state.error };
|
|
426
469
|
}
|
|
470
|
+
function resolveInitialData(initialData) {
|
|
471
|
+
if (initialData == null) return null;
|
|
472
|
+
if (Array.isArray(initialData)) {
|
|
473
|
+
if (initialData.length === 0) return null;
|
|
474
|
+
return { rows: initialData };
|
|
475
|
+
}
|
|
476
|
+
if ((initialData.rows ?? []).length === 0) return null;
|
|
477
|
+
return initialData;
|
|
478
|
+
}
|
|
427
479
|
function useDebouncedValue(value, delay) {
|
|
428
480
|
const [debounced, setDebounced] = useState(value);
|
|
429
481
|
useEffect(() => {
|
|
@@ -480,6 +532,19 @@ function createPostgRESTProvider(config) {
|
|
|
480
532
|
return {
|
|
481
533
|
fetchData: createPostgRESTFetchChunk(config),
|
|
482
534
|
identity: (row) => row?.[config.identityKey],
|
|
535
|
+
async distinctValues(columnKey, options = {}) {
|
|
536
|
+
let req = from().select(`${columnKey},count()`);
|
|
537
|
+
if (config.baseFilter != null) req = config.baseFilter(req);
|
|
538
|
+
req = req.order(columnKey, { ascending: true, nullsFirst: false });
|
|
539
|
+
if (options.limit != null) req = req.limit(options.limit);
|
|
540
|
+
if (options.signal != null) req = req.abortSignal(options.signal);
|
|
541
|
+
const { data, error } = await req;
|
|
542
|
+
if (error != null) throw error;
|
|
543
|
+
return (data ?? []).map((row) => ({
|
|
544
|
+
value: row[columnKey],
|
|
545
|
+
count: row.count
|
|
546
|
+
}));
|
|
547
|
+
},
|
|
483
548
|
async saveRows(rows) {
|
|
484
549
|
const res = await from().upsert(rows, {
|
|
485
550
|
defaultToNull: false
|