@macrostrat/data-sheet 4.11.0 → 4.11.2
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 +23 -0
- package/dist/components/indicators/index.d.ts +1 -0
- package/dist/components/indicators/load-error.cjs +28 -0
- package/dist/components/indicators/load-error.cjs.map +1 -0
- package/dist/components/indicators/load-error.d.ts +10 -0
- package/dist/components/indicators/load-error.js +28 -0
- package/dist/components/indicators/load-error.js.map +1 -0
- package/dist/data-panel.cjs +2 -5
- package/dist/data-panel.cjs.map +1 -1
- package/dist/data-panel.js +2 -5
- package/dist/data-panel.js.map +1 -1
- package/dist/data-sheet.cjs +34 -29
- package/dist/data-sheet.cjs.map +1 -1
- package/dist/data-sheet.css +54 -40
- package/dist/data-sheet.js +34 -29
- package/dist/data-sheet.js.map +1 -1
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/main.module.sass.cjs +14 -14
- package/dist/main.module.sass.js +14 -14
- package/dist/postgrest-table/data-loaders.cjs +2 -1
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.d.ts +2 -1
- package/dist/postgrest-table/data-loaders.js +2 -1
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/postgrest-table/main.module.sass.cjs +15 -14
- package/dist/postgrest-table/main.module.sass.cjs.map +1 -1
- package/dist/postgrest-table/main.module.sass.js +15 -14
- package/dist/postgrest-table/main.module.sass.js.map +1 -1
- package/package.json +3 -3
- package/src/components/indicators/index.ts +1 -0
- package/src/components/indicators/load-error.ts +28 -0
- package/src/data-panel.ts +2 -5
- package/src/data-sheet.ts +33 -28
- package/src/main.module.sass +4 -0
- package/src/postgrest-table/data-loaders.ts +10 -3
- package/src/postgrest-table/main.module.sass +9 -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, 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\";\nimport {\n lazyLoaderCoreStateAtom,\n resolveInitialData,\n seededRows,\n startAfterAtom,\n type LazyLoaderStateCore,\n} from \"../provider/loader-state.ts\";\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 data = seededRows({\n rows: action.data ?? [],\n totalCount: action.totalCount,\n });\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\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 // The keyset cursor of a view that starts mid-list. Seeded at store creation\n // (`startAfter`); cleared below on the first view change, since it describes\n // only the view it arrived with.\n const [startAfter, setStartAfter] = ctx.use(startAfterAtom);\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 //\n // The store is normally created already seeded (`DataSheetStoreWrapper`), so\n // the rows are in the very first render — including a server render. The\n // dispatch below is the fallback for a store that wasn't.\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 const firstResetRef = useRef(true);\n useEffect(() => {\n const seed = seedRef.current;\n seedRef.current = null;\n // A view change (not the mount) ends a mid-list start: the cursor only\n // described the view it arrived with.\n if (!firstResetRef.current) {\n setStartAfter(null);\n }\n firstResetRef.current = false;\n if (seed != null) {\n if (!state.initialized) {\n dispatch({\n type: \"seed\",\n data: seed.rows,\n totalCount: seed.totalCount,\n });\n }\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 after: startAfter,\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 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":["data","update"],"mappings":";;;;;;;;;;AAgFO,SAAS,kBACd,cACiB;AACjB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AACT,aAAO,m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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\";\nimport {\n lazyLoaderCoreStateAtom,\n resolveInitialData,\n seededRows,\n startAfterAtom,\n type LazyLoaderStateCore,\n} from \"../provider/loader-state.ts\";\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 data = seededRows({\n rows: action.data ?? [],\n totalCount: action.totalCount,\n });\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\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`, and\n * no load error) —\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 // A failed chunk leaves its rows null, so without the error check the\n // sentinel re-requests it forever.\n const canLoadMore =\n hasMore && !footer.loading && !paused && footer.error == null;\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 // The keyset cursor of a view that starts mid-list. Seeded at store creation\n // (`startAfter`); cleared below on the first view change, since it describes\n // only the view it arrived with.\n const [startAfter, setStartAfter] = ctx.use(startAfterAtom);\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 //\n // The store is normally created already seeded (`DataSheetStoreWrapper`), so\n // the rows are in the very first render — including a server render. The\n // dispatch below is the fallback for a store that wasn't.\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 const firstResetRef = useRef(true);\n useEffect(() => {\n const seed = seedRef.current;\n seedRef.current = null;\n // A view change (not the mount) ends a mid-list start: the cursor only\n // described the view it arrived with.\n if (!firstResetRef.current) {\n setStartAfter(null);\n }\n firstResetRef.current = false;\n if (seed != null) {\n if (!state.initialized) {\n dispatch({\n type: \"seed\",\n data: seed.rows,\n totalCount: seed.totalCount,\n });\n }\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 // A failed load is final until the view is reset (a sort or filter change,\n // or a refresh). Without this, whatever re-runs the effect requests the\n // same chunk again, for as long as the source keeps failing.\n if (state.error != null) 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 after: startAfter,\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 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":["data","update"],"mappings":";;;;;;;;;;AAgFO,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,EACT,IAAI,CAAC,MAAM,EAAE,MAAM,EACnB,OAAO,CAAC,MAAM,MAAM,EAAE;AAC3B;AAiBA,SAAS,mBACP,OACA,QACoB;AACpB,UAAQ,OAAO,MAAA;AAAA,IACb,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,SAAS;AAAA,QACT,aAAa;AAAA,MAAA;AAAA,IAEjB,KAAK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ACjE,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;"}
|
|
@@ -3,25 +3,26 @@ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toString
|
|
|
3
3
|
const h$1 = require("@macrostrat/hyper");
|
|
4
4
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
|
5
5
|
const h__default = /* @__PURE__ */ _interopDefault(h$1);
|
|
6
|
-
const lithology = "
|
|
7
|
-
const description = "
|
|
8
|
-
const liths = "
|
|
9
|
-
const toolbar = "
|
|
6
|
+
const lithology = "_lithology_18ejy_1";
|
|
7
|
+
const description = "_description_18ejy_34";
|
|
8
|
+
const liths = "_liths_18ejy_49";
|
|
9
|
+
const toolbar = "_toolbar_18ejy_61";
|
|
10
10
|
const styles = {
|
|
11
11
|
lithology,
|
|
12
|
-
"inline-lithology": "_inline-
|
|
13
|
-
"basis-panel": "_basis-
|
|
14
|
-
"long-text": "_long-
|
|
12
|
+
"inline-lithology": "_inline-lithology_18ejy_8",
|
|
13
|
+
"basis-panel": "_basis-panel_18ejy_12",
|
|
14
|
+
"long-text": "_long-text_18ejy_26",
|
|
15
15
|
description,
|
|
16
|
-
"tag-header": "_tag-
|
|
17
|
-
"basis-col": "_basis-
|
|
16
|
+
"tag-header": "_tag-header_18ejy_38",
|
|
17
|
+
"basis-col": "_basis-col_18ejy_45",
|
|
18
18
|
liths,
|
|
19
|
-
"data-sheet-outer": "_data-sheet-
|
|
19
|
+
"data-sheet-outer": "_data-sheet-outer_18ejy_53",
|
|
20
20
|
toolbar,
|
|
21
|
-
"info-bar": "_info-
|
|
22
|
-
"server-filter-bar": "_server-filter-
|
|
23
|
-
"load-progress": "_load-
|
|
24
|
-
"tag-cell-content": "_tag-cell-
|
|
21
|
+
"info-bar": "_info-bar_18ejy_61",
|
|
22
|
+
"server-filter-bar": "_server-filter-bar_18ejy_61",
|
|
23
|
+
"load-progress": "_load-progress_18ejy_73",
|
|
24
|
+
"tag-cell-content": "_tag-cell-content_18ejy_85",
|
|
25
|
+
"load-error-overlay": "_load-error-overlay_18ejy_89"
|
|
25
26
|
};
|
|
26
27
|
let h = h__default.default.styled(styles);
|
|
27
28
|
Object.assign(h, styles);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.module.sass.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.module.sass.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1,23 +1,24 @@
|
|
|
1
1
|
import h$1 from "@macrostrat/hyper";
|
|
2
|
-
const lithology = "
|
|
3
|
-
const description = "
|
|
4
|
-
const liths = "
|
|
5
|
-
const toolbar = "
|
|
2
|
+
const lithology = "_lithology_18ejy_1";
|
|
3
|
+
const description = "_description_18ejy_34";
|
|
4
|
+
const liths = "_liths_18ejy_49";
|
|
5
|
+
const toolbar = "_toolbar_18ejy_61";
|
|
6
6
|
const styles = {
|
|
7
7
|
lithology,
|
|
8
|
-
"inline-lithology": "_inline-
|
|
9
|
-
"basis-panel": "_basis-
|
|
10
|
-
"long-text": "_long-
|
|
8
|
+
"inline-lithology": "_inline-lithology_18ejy_8",
|
|
9
|
+
"basis-panel": "_basis-panel_18ejy_12",
|
|
10
|
+
"long-text": "_long-text_18ejy_26",
|
|
11
11
|
description,
|
|
12
|
-
"tag-header": "_tag-
|
|
13
|
-
"basis-col": "_basis-
|
|
12
|
+
"tag-header": "_tag-header_18ejy_38",
|
|
13
|
+
"basis-col": "_basis-col_18ejy_45",
|
|
14
14
|
liths,
|
|
15
|
-
"data-sheet-outer": "_data-sheet-
|
|
15
|
+
"data-sheet-outer": "_data-sheet-outer_18ejy_53",
|
|
16
16
|
toolbar,
|
|
17
|
-
"info-bar": "_info-
|
|
18
|
-
"server-filter-bar": "_server-filter-
|
|
19
|
-
"load-progress": "_load-
|
|
20
|
-
"tag-cell-content": "_tag-cell-
|
|
17
|
+
"info-bar": "_info-bar_18ejy_61",
|
|
18
|
+
"server-filter-bar": "_server-filter-bar_18ejy_61",
|
|
19
|
+
"load-progress": "_load-progress_18ejy_73",
|
|
20
|
+
"tag-cell-content": "_tag-cell-content_18ejy_85",
|
|
21
|
+
"load-error-overlay": "_load-error-overlay_18ejy_89"
|
|
21
22
|
};
|
|
22
23
|
let h = h$1.styled(styles);
|
|
23
24
|
Object.assign(h, styles);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.module.sass.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.module.sass.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@macrostrat/data-sheet",
|
|
3
|
-
"version": "4.11.
|
|
3
|
+
"version": "4.11.2",
|
|
4
4
|
"description": "Scalable data sheet with optional editing capabilities",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -49,10 +49,10 @@
|
|
|
49
49
|
"@blueprintjs/core": "^6.14.0",
|
|
50
50
|
"@blueprintjs/table": "^6.1.0",
|
|
51
51
|
"@macrostrat/color-utils": "^1.2.2",
|
|
52
|
-
"@macrostrat/data-components": "^1.
|
|
52
|
+
"@macrostrat/data-components": "^1.10.0",
|
|
53
53
|
"@macrostrat/hyper": "^3.1.1",
|
|
54
54
|
"@macrostrat/scoped-store": "^1.1.0",
|
|
55
|
-
"@macrostrat/ui-components": "^5.
|
|
55
|
+
"@macrostrat/ui-components": "^5.5.0",
|
|
56
56
|
"@supabase/postgrest-js": "^1.17.7",
|
|
57
57
|
"@types/underscore": "^1.13.0",
|
|
58
58
|
"classnames": "^2.5.1",
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import h from "../../postgrest-table/main.module.sass";
|
|
2
|
+
import { Button, NonIdealState } from "@blueprintjs/core";
|
|
3
|
+
import { useLoadControls } from "../../postgrest-table";
|
|
4
|
+
import { ctx, dataRefreshTokenAtom } from "../../provider";
|
|
5
|
+
|
|
6
|
+
/** A failed load, with a retry: loading stays off after an error, so
|
|
7
|
+
* reloading is the user's call. */
|
|
8
|
+
export function LoadErrorState({ error }: { error: Error }) {
|
|
9
|
+
const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);
|
|
10
|
+
return h(NonIdealState, {
|
|
11
|
+
icon: "error",
|
|
12
|
+
title: "Couldn't load data",
|
|
13
|
+
description: error.message ?? "The data source returned an error.",
|
|
14
|
+
action: h(
|
|
15
|
+
Button,
|
|
16
|
+
{ icon: "refresh", onClick: () => bumpRefresh((v) => v + 1) },
|
|
17
|
+
"Try again",
|
|
18
|
+
),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** `LoadErrorState` over a table body that has no rows to show. Once rows are
|
|
23
|
+
* loaded, a later failure is reported by the footer instead. */
|
|
24
|
+
export function LoadErrorOverlay() {
|
|
25
|
+
const { error, loaded } = useLoadControls();
|
|
26
|
+
if (error == null || loaded > 0) return null;
|
|
27
|
+
return h("div.load-error-overlay", h(LoadErrorState, { error }));
|
|
28
|
+
}
|
package/src/data-panel.ts
CHANGED
|
@@ -71,6 +71,7 @@ import {
|
|
|
71
71
|
import classNames from "classnames";
|
|
72
72
|
import {
|
|
73
73
|
ActionsToolbar,
|
|
74
|
+
LoadErrorState,
|
|
74
75
|
LoadProgressIndicator,
|
|
75
76
|
useDataPanelControls,
|
|
76
77
|
type ViewControlsPresentation,
|
|
@@ -326,11 +327,7 @@ export function DataPanelRenderer<T>({
|
|
|
326
327
|
let emptyState: ReactNode = null;
|
|
327
328
|
if (cards.length === 0) {
|
|
328
329
|
if (error != null) {
|
|
329
|
-
emptyState = h(
|
|
330
|
-
icon: "error",
|
|
331
|
-
title: "Couldn't load data",
|
|
332
|
-
description: error.message ?? "The data source returned an error.",
|
|
333
|
-
});
|
|
330
|
+
emptyState = h(LoadErrorState, { error });
|
|
334
331
|
} else if (initialized && !loading) {
|
|
335
332
|
// Only after a fetch settled with no rows — not during the reset gap.
|
|
336
333
|
emptyState = h(NonIdealState, {
|
package/src/data-sheet.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
useRef,
|
|
16
16
|
} from "react";
|
|
17
17
|
import {
|
|
18
|
+
LoadErrorOverlay,
|
|
18
19
|
LoadProgressIndicator,
|
|
19
20
|
ActionsToolbar,
|
|
20
21
|
ActiveFiltersList,
|
|
@@ -574,34 +575,38 @@ export function DataSheetRenderer<T>({
|
|
|
574
575
|
ref: tableElementRef,
|
|
575
576
|
style: holderStyle,
|
|
576
577
|
},
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
578
|
+
[
|
|
579
|
+
// Inside the holder, so the toolbar and filters stay reachable.
|
|
580
|
+
h.if(_showLoadProgress)(LoadErrorOverlay),
|
|
581
|
+
h(
|
|
582
|
+
Table as any, // Some sort of hyperscript type error
|
|
583
|
+
{
|
|
584
|
+
ref,
|
|
585
|
+
numRows,
|
|
586
|
+
className: "data-sheet",
|
|
587
|
+
enableFocusedCell,
|
|
588
|
+
enableColumnReordering,
|
|
589
|
+
onColumnsReordered,
|
|
590
|
+
focusedCell,
|
|
591
|
+
selectedRegions,
|
|
592
|
+
defaultRowHeight: rowHeight,
|
|
593
|
+
columnWidths,
|
|
594
|
+
onColumnWidthChanged,
|
|
595
|
+
onSelection,
|
|
596
|
+
/** TODO: we could enable this if we had a use-case */
|
|
597
|
+
enableRowReordering: false,
|
|
598
|
+
enableRowResizing: false,
|
|
599
|
+
// The cell renderer is memoized internally based on these data dependencies
|
|
600
|
+
cellRendererDependencies,
|
|
601
|
+
onVisibleCellsChange: _onVisibleCellsChange,
|
|
602
|
+
rowHeaderCellRenderer,
|
|
603
|
+
selectionModes: _selectionModes,
|
|
604
|
+
...tableProps,
|
|
605
|
+
getCellClipboardData: null,
|
|
606
|
+
},
|
|
607
|
+
realizedColumns,
|
|
608
|
+
),
|
|
609
|
+
],
|
|
605
610
|
),
|
|
606
611
|
h("div.status-bar", [
|
|
607
612
|
filterStatus,
|
package/src/main.module.sass
CHANGED
|
@@ -368,7 +368,6 @@ const defaultVisibleRegion: RowRegion = {
|
|
|
368
368
|
/** Atom to house the current visible region of the table */
|
|
369
369
|
const visibleRegionAtom = atom<RowRegion>(defaultVisibleRegion);
|
|
370
370
|
|
|
371
|
-
|
|
372
371
|
/** Current page index (0-based) for paged fetch mode. */
|
|
373
372
|
export const chunkPageAtom = atom(0);
|
|
374
373
|
|
|
@@ -447,7 +446,8 @@ export interface LoadControls {
|
|
|
447
446
|
total: number | null;
|
|
448
447
|
/** Auto-load is paused at the `autoLoadPages` checkpoint. */
|
|
449
448
|
paused: boolean;
|
|
450
|
-
/** Auto-load is currently permitted (`hasMore && !loading && !paused
|
|
449
|
+
/** Auto-load is currently permitted (`hasMore && !loading && !paused`, and
|
|
450
|
+
* no load error) —
|
|
451
451
|
* used to gate an infinite-scroll sentinel. */
|
|
452
452
|
canLoadMore: boolean;
|
|
453
453
|
/** Advance one page *without* resuming a paused auto-load (the sentinel
|
|
@@ -482,7 +482,10 @@ export function useLoadControls(): LoadControls {
|
|
|
482
482
|
const paused =
|
|
483
483
|
autoLoadPages != null &&
|
|
484
484
|
loadedCount - resumeBaseline >= autoLoadPages * pageSize;
|
|
485
|
-
|
|
485
|
+
// A failed chunk leaves its rows null, so without the error check the
|
|
486
|
+
// sentinel re-requests it forever.
|
|
487
|
+
const canLoadMore =
|
|
488
|
+
hasMore && !footer.loading && !paused && footer.error == null;
|
|
486
489
|
|
|
487
490
|
const advance = useCallback(() => {
|
|
488
491
|
setVisibleRegion({
|
|
@@ -765,6 +768,10 @@ export function useDataLoader<T = any>(
|
|
|
765
768
|
|
|
766
769
|
useAsyncEffect(async () => {
|
|
767
770
|
if (state.loading) return;
|
|
771
|
+
// A failed load is final until the view is reset (a sort or filter change,
|
|
772
|
+
// or a refresh). Without this, whatever re-runs the effect requests the
|
|
773
|
+
// same chunk again, for as long as the source keeps failing.
|
|
774
|
+
if (state.error != null) return;
|
|
768
775
|
|
|
769
776
|
// A seed hasn't landed in state yet. Every effect in a commit sees the
|
|
770
777
|
// render's snapshot, so this one runs *before* the seed it was mounted
|
|
@@ -79,3 +79,12 @@
|
|
|
79
79
|
.tag-cell-content
|
|
80
80
|
line-height: 1
|
|
81
81
|
|
|
82
|
+
// Covers a table body that has nothing to show after a failed load.
|
|
83
|
+
.load-error-overlay
|
|
84
|
+
position: absolute
|
|
85
|
+
inset: 0
|
|
86
|
+
z-index: 30
|
|
87
|
+
display: flex
|
|
88
|
+
align-items: center
|
|
89
|
+
justify-content: center
|
|
90
|
+
background-color: var(--data-sheet-cell-background-color-internal, var(--background-color))
|