@macrostrat/data-sheet 4.11.0 → 4.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.11.1] - 2026-10-23 [_changes_](https://github.com/UW-Macrostrat/web-components/compare/@macrostrat/data-sheet-v4.11.0...@macrostrat/data-sheet-v4.11.1)
4
+
5
+ ### Patch Changes
6
+
7
+ - Stop `DataPanel`'s infinite-scroll sentinel from re-requesting a chunk that
8
+ failed to load (e.g. a 401), which looped without pause
9
+ [cbcd9eaa](https://github.com/UW-Macrostrat/web-components/commit/cbcd9eaaaae6136f9eca183b51df2bc36e1fe2da)
10
+ - Add a "Try again" button to `DataPanel`'s load-error state, which reloads the
11
+ view
12
+ [11e239dd](https://github.com/UW-Macrostrat/web-components/commit/11e239dda9e390cfe7d78e3a50330fc91f49aad7)
13
+
3
14
  ## [4.11.0] - 2026-10-01 [_changes_](https://github.com/UW-Macrostrat/web-components/compare/@macrostrat/data-sheet-v4.10.1...@macrostrat/data-sheet-v4.11.0)
4
15
 
5
16
  ### Minor Changes
@@ -14,6 +14,7 @@ const atoms = require("./utils/atoms.cjs");
14
14
  const core = require("./provider/core.cjs");
15
15
  const interactions = require("./provider/interactions.cjs");
16
16
  const actionsToolbar = require("./components/toolbars/actions-toolbar.cjs");
17
+ const tableData = require("./provider/table-data.cjs");
17
18
  const viewInfo = require("./components/indicators/view-info.cjs");
18
19
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
19
20
  const classNames__default = /* @__PURE__ */ _interopDefault(classNames);
@@ -111,11 +112,7 @@ function DataPanelRenderer({
111
112
  let emptyState = null;
112
113
  if (cards.length === 0) {
113
114
  if (error != null) {
114
- emptyState = dataPanel_module.default(core$1.NonIdealState, {
115
- icon: "error",
116
- title: "Couldn't load data",
117
- description: error.message ?? "The data source returned an error."
118
- });
115
+ emptyState = dataPanel_module.default(LoadErrorState, { error });
119
116
  } else if (initialized && !loading) {
120
117
  emptyState = dataPanel_module.default(core$1.NonIdealState, {
121
118
  icon: "search",
@@ -288,6 +285,19 @@ function modifiersOf(arg) {
288
285
  }
289
286
  return arg;
290
287
  }
288
+ function LoadErrorState({ error }) {
289
+ const bumpRefresh = core.ctx.useSet(tableData.dataRefreshTokenAtom);
290
+ return dataPanel_module.default(core$1.NonIdealState, {
291
+ icon: "error",
292
+ title: "Couldn't load data",
293
+ description: error.message ?? "The data source returned an error.",
294
+ action: dataPanel_module.default(
295
+ core$1.Button,
296
+ { icon: "refresh", onClick: () => bumpRefresh((v) => v + 1) },
297
+ "Try again"
298
+ )
299
+ });
300
+ }
291
301
  function useBottomSentinel(onVisible, deps) {
292
302
  const elRef = react.useRef(null);
293
303
  const observerRef = react.useRef(null);
@@ -1 +1 @@
1
- {"version":3,"file":"data-panel.cjs","sources":["../src/data-panel.ts"],"sourcesContent":["/**\n * DataPanel — a card/list renderer over the same headless core as `DataSheet`.\n *\n * The two components differ in only two dimensions: the **view** (cards vs. the\n * Blueprint cell grid) and **edit granularity** (immediate per-item vs. a\n * batched pending-ops stack). Everything else — provider-driven windowed\n * loading, `{sorts, filters}` view state, the selection set, and set-based\n * actions — is the shared substrate, reused here unchanged:\n *\n * - `DataSheetProvider` supplies the jotai+zustand store.\n * - `useDataLoader(provider.fetchData)` drives windowed loading and threads the\n * active store sorts/filters through so a server provider applies them.\n * - `ActionsToolbar` + `FilterBar` render selection-aware actions and the\n * active sort/filter tags — they read the store, not the table.\n *\n * The only list-specific pieces are: rows rendered as cards via a consumer\n * `itemComponent`; selection expressed as `FULL_ROWS` regions (so the existing\n * row-targeted `TableAction`s apply); an infinite-scroll sentinel that advances\n * the loader's visible region; and `FacetControls`, which stands in for the\n * column-header dropdown the list doesn't have (a menu to add a column filter /\n * sort from the column-declared `filterable` / `sortable` capabilities).\n *\n * See [[Data list editors]] in the Macrostrat workbench for the design.\n */\nimport type { ToolbarCollapse } from \"@macrostrat/ui-components\";\nimport h from \"./data-panel.module.sass\";\nimport {\n ComponentType,\n CSSProperties,\n MouseEvent as ReactMouseEvent,\n ReactNode,\n UIEvent as ReactUIEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n AnchorButton,\n Classes,\n Icon,\n NonIdealState,\n Spinner,\n} from \"@blueprintjs/core\";\nimport { startAfterAtom } from \"./provider/loader-state.ts\";\nimport {\n anchorRefAtom,\n ctx,\n dataProviderAtom,\n DataSheetProvider,\n DataViewRendererType,\n FetchData,\n enableSelectionAtom,\n interactionOptionsAtom,\n selectionAtom,\n splitDataProviderProps,\n useSelector,\n} from \"./provider\";\nimport {\n buildDataViewSelection,\n getSelectedRowIndices,\n rowIndicesToRegions,\n TableAction,\n} from \"./actions\";\nimport {\n autoLoadPagesAtom,\n useDataLoader,\n useLoadControls,\n} from \"./postgrest-table\";\nimport classNames from \"classnames\";\nimport {\n ActionsToolbar,\n LoadProgressIndicator,\n useDataPanelControls,\n type ViewControlsPresentation,\n} from \"./components\";\nimport { DataViewSharedProps, FetchDataOptions } from \"./types\";\nimport { atom } from \"jotai\";\nimport { passThroughSet } from \"./utils\";\n\nexport enum DataPanelToolbarStyle {\n BORDERED = \"bordered\",\n FADE = \"fade\",\n MINIMAL = \"minimal\",\n /** Toolbar (and footer) sized to their contents and lifted over the scroll\n * body, rather than occupying a full-width band. Pairs with\n * `viewControls: \"popover\"`, since inline controls cost real space here. */\n FLOATING = \"floating\",\n}\n\n/** Props for a custom scroll-body layout component. It receives the\n * already-rendered, selection-wrapped item cards and lays them out however it\n * likes (a grid, sections, sticky headers, its own windowing). The panel owns\n * the surrounding scroll container and the loading sentinel; the scroll body\n * only arranges the items. */\nexport interface ScrollBodyProps {\n /** The rendered item cards (each wrapped for selection styling). */\n children: ReactNode;\n /** Loading skeletons for the page currently being fetched, if any. Kept\n * separate from `children` because they are transient stand-ins, not items:\n * a layout that assigns a lasting position per item (e.g. the masonry body)\n * must not hand one to a placeholder. Render them after the items; a body\n * that ignores them simply shows no loading state. */\n placeholders?: ReactNode;\n}\n\n/** Props handed to a consumer's card renderer for one row. */\nexport interface ItemComponentProps<T = any> {\n /** The row's data. */\n data: T;\n /** Underlying data-row index (stable within a loaded window). */\n index: number;\n /** Whether this row is in the current selection. */\n selected: boolean;\n /** Whether the row can be selected */\n selectable: boolean;\n /** Select this row. Pass the click's `MouseEvent` (or `React.MouseEvent`) to\n * honor shift / cmd / ctrl automatically — the usual wiring is\n * `onClick: onSelect`. Or pass an explicit `SelectModifiers` object; no\n * argument means a plain (replace) select. */\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) => void;\n}\n\nexport interface DataPanelProps<T = any> extends DataViewSharedProps<T> {\n /** Renders one row as a card. */\n itemComponent: ComponentType<ItemComponentProps<T>>;\n /** Arbitrary nodes for the bottom status row (beside the loaded/total\n * counter). Pass `false` to drop the status row entirely — e.g. when the\n * counter is folded into an inline footer instead. */\n statusBar?: ReactNode | false;\n /** Custom header controls, replacing the default `FacetControls` +\n * `FilterBar`. Rendered inside the provider, so it can drive sort/filter via\n * the exported building blocks (`FacetControls`, `FilterBar`) and the store\n * hooks (`useStoreAPI` / `useSelector`). The selection `ActionsToolbar` still\n * renders above it. Omit for the sane default. */\n toolbar?: ReactNode;\n /** A filter/detail sidebar beside the scroll body (its own scroll). Rendered\n * inside the provider, so a custom filter panel drives sort/filter through\n * the store hooks — the alternative placement to the top `toolbar`. */\n sidebar?: ReactNode;\n /** Footer content. Rendered inside the provider, so it reads live load state\n * from the store via `useLoadControls()` (loadMore / loading / hasMore /\n * loaded / total / paused) rather than a passed-down contract — a footer, a\n * status line, or a \"Load more\" button all just call the hook. */\n contentFooter?: ReactNode;\n /** Auto-load this many pages per burst, then pause: a paused panel stops\n * fetching on scroll until `useLoadControls().loadMore()` starts the next\n * burst (e.g. a footer \"Load more\" button). Omit for unbounded auto-scroll. */\n // TODO: we may deprecate this for opt-in scrolling\n autoLoadPages?: number;\n /** Custom layout for the item cards — the seam for anything other than a\n * vertical list (a CSS grid for several per row, grouped sections, sticky\n * sub-headers, a windowed renderer). Receives the rendered cards as\n * `children`; the panel still owns the scroll container and the loading\n * sentinel, so paging and selection keep working. Defaults to a vertical\n * flex list. */\n scrollBody?: ComponentType<ScrollBodyProps>;\n className?: string;\n toolbarStyle?: DataPanelToolbarStyle | string;\n /** Where the built-in view controls (inline filters, Filter menu, Sort menu)\n * sit in the toolbar: `\"inline\"` (default) places each in the toolbar;\n * `\"popover\"` collapses all of them behind a single button — for a narrow or\n * deliberately chrome-light toolbar. Same controls and state either way.\n * Ignored while a modal view is selecting: the toolbar then carries a single\n * control that leaves select mode. */\n viewControls?: ViewControlsPresentation;\n /** How the toolbar sheds width (the shared `Toolbar`'s `collapse`): with\n * `\"narrow\"`, button labels drop to icons and then contextual controls fold\n * into a \"more\" popover as the panel narrows. Default `\"never\"`. */\n toolbarCollapse?: ToolbarCollapse;\n /** Arbitrary children rendered inside the provider, after the panel. */\n children?: ReactNode;\n}\n\n/**\n * Resolve the data source (shared with `DataSheet` / `DataView` via\n * `useResolvedProvider`), wrap in the shared provider, and render the inner\n * panel.\n */\nexport function DataPanel<T>(props: DataPanelProps<T>) {\n const [providerProps, rendererProps] = splitDataProviderProps({\n ...props,\n viewType: DataViewRendererType.CARDS,\n });\n return h(\n DataSheetProvider<T>,\n providerProps,\n h(DataPanelRenderer<any>, rendererProps),\n );\n}\n\n/** Selection modifier keys, following the familiar list idiom. */\nexport interface SelectModifiers {\n /** cmd/ctrl — toggle this row in/out of the selection (or extend a range). */\n additive?: boolean;\n /** shift — select the range from the anchor (last plain/cmd click) to here. */\n range?: boolean;\n}\n\n/** The card-list renderer. Assumes it is rendered inside a `DataSheetProvider`\n * (the `DataPanel` wrapper, or `DataView`). Exported so a shared-store\n * `DataView` can mount it directly alongside `_DataSheet`. */\nexport function DataPanelRenderer<T>({\n itemComponent,\n actions = [],\n filters = [],\n pageSize = 50,\n filterDebounce,\n initialData,\n name,\n // Bottom bar\n statusBar,\n toolbar,\n sidebar,\n // Footer within content flow\n contentFooter,\n autoLoadPages,\n scrollBody,\n pageLinks,\n className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\n toolbarCollapse = \"never\",\n children,\n}: Omit<DataPanelProps<T>, \"provider\" | \"fetchData\" | \"data\" | \"identity\">) {\n const {\n provider: activeProvider,\n isLocalProvider,\n localCount,\n } = ctx.useValue(dataProviderAtom);\n\n // The loader is mounted as a child component (below), NOT called as a hook\n // here, and only once `activeProvider` resolves. This mirrors `_DataSheet`:\n // `dataProviderAtom` is synced by a parent effect that fires *after* this\n // component's effects, so a hook call here would capture the placeholder\n // provider on first render and — since `fetchData` isn't one of its effect\n // deps — never re-fetch with the real one. A child that mounts with the real\n // `fetchData` already in hand sidesteps that entirely.\n // A local (in-memory) source loads all of its rows in one page; its count\n // rides on the resolved provider, so the renderer no longer takes a `data`\n // prop (the store is the single source of live rows).\n const loaderPageSize = isLocalProvider ? Math.max(localCount, 1) : pageSize;\n\n const data = useSelector((s) => s.data);\n\n // Load state + pause/resume live in the store, read via `useLoadControls`\n // (also available to the caller's `footer` via the same hook). The panel's\n // `autoLoadPages` prop is the store's configuration input.\n ctx.useSync(autoLoadPagesAtom, autoLoadPages ?? null);\n const {\n loading,\n initialized,\n error,\n hasMore,\n loaded,\n total,\n paused,\n canLoadMore,\n advance,\n } = useLoadControls();\n\n // Track whether the body is scrolled off the top, to gate the top fade.\n // `setState` with an unchanged value is a no-op, so this only re-renders on\n // the at-top ↔ scrolled transition.\n const [scrolled, setScrolled] = useState(false);\n const onScroll = useCallback((e: ReactUIEvent<HTMLDivElement>) => {\n setScrolled(e.currentTarget.scrollTop > 4);\n }, []);\n\n const enableSelection = ctx.useValue(enableSelectionAtom);\n const selectedIndices = ctx.useValue(selectedRowIndicesAtom);\n const select = ctx.useSet(updateSelectionAtom);\n\n const loadedCount = useMemo(() => {\n let n = 0;\n for (const r of data) if (r != null) n++;\n return n;\n }, [data]);\n\n // Refresh-token, rowEditing, and load controls (loadMore / pause) are all\n // store-managed (see `useLoadControls`), shared with `_DataSheet` — so both\n // renderers, and any footer, drive loading off one source.\n\n // Infinite scroll. A naive \"load a page when the bottom sentinel is visible\"\n // over-fetches: when a page's rows commit, this component re-renders\n // (loadedCount changed) *before* the IntersectionObserver has re-evaluated\n // the sentinel's new position, so a stale \"still visible\" fires a second\n // load. `useBottomSentinel` re-observes the sentinel whenever the pass-through\n // deps change, so every trigger reflects the *current* post-layout\n // visibility — it loads one page, and only loads another if the sentinel is\n // genuinely still on screen. `advance` (from the store) moves the loader one\n // page without resuming a paused auto-load.\n const sentinelRef = useBottomSentinel(canLoadMore ? advance : null, [\n loadedCount,\n canLoadMore,\n ]);\n\n const cards: ReactNode[] = data\n .filter((d) => d != null)\n .map((row: ReactNode, i) => {\n const selected = enableSelection && selectedIndices.has(i);\n return h(\n \"div.data-panel-item-container\",\n { key: `item-${i}`, className: classNames({ selected }) },\n h(itemComponent, {\n data: row,\n index: i,\n selected,\n selectable: enableSelection,\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) =>\n select(i, modifiersOf(arg)),\n }),\n );\n });\n\n // Body-level empty/error state: when nothing has loaded, show a clear message\n // instead of a blank list — an errored source (e.g. a 401 on the whole route)\n // degrades gracefully, and a genuinely empty result reads as \"no results\"\n // rather than a perpetual spinner.\n // A load is pending whenever a fetch is in flight OR the view was just reset\n // and hasn't fetched yet (`!initialized`) — the window that would otherwise\n // flash \"No results\" before the request starts.\n const loadPending = (loading || !initialized) && error == null;\n\n let emptyState: ReactNode = null;\n if (cards.length === 0) {\n if (error != null) {\n emptyState = h(NonIdealState, {\n icon: \"error\",\n title: \"Couldn't load data\",\n description: error.message ?? \"The data source returned an error.\",\n });\n } else if (initialized && !loading) {\n // Only after a fetch settled with no rows — not during the reset gap.\n emptyState = h(NonIdealState, {\n icon: \"search\",\n title: \"No results\",\n });\n }\n }\n\n // Skeleton placeholders for the page being fetched — on a view change (the\n // reset pre-sizes to a page of `null` slots) or the next scroll page — so the\n // body shows shimmer where rows will land instead of a blank flash or a\n // footer pinging up into the gap. Bounded to a viewport's worth of cards.\n const placeholderCards: ReactNode[] = [];\n if (loadPending) {\n const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);\n for (let i = 0; i < pending; i++) {\n placeholderCards.push(\n h(\n \"div.data-panel-item-container.is-skeleton\",\n { key: `skeleton-${i}`, \"aria-hidden\": true },\n h(\"div.data-panel-skeleton\", { className: Classes.SKELETON }),\n ),\n );\n }\n }\n let placeholders: ReactNode = null;\n if (placeholderCards.length > 0) {\n placeholders = placeholderCards;\n }\n\n // The default spinner sentinel (below-placement): hidden while paused so the\n // pinned footer's \"Load more\" takes over.\n const shouldLoadNextPage = (hasMore || loading) && !paused && error == null;\n\n // Mount the loader only once the provider resolves (see `PanelLoader`). Built\n // as a real conditional — `h.if(...)` evaluates its arguments eagerly, so\n // `activeProvider.fetchData` can't be referenced inside it while null.\n let loaderNode: ReactNode = null;\n if (activeProvider != null) {\n loaderNode = h(PanelLoader, {\n fetchData: activeProvider.fetchData,\n pageSize: loaderPageSize,\n fetchMode: isLocalProvider ? undefined : \"scroll\",\n filterDebounce,\n initialData,\n });\n }\n\n const coreActions = useDataPanelControls(filters, viewControls);\n\n // Merge consumer actions with the synthesized Filter/Sort controls, deduped\n // by id — consumer actions come first, so passing an action with id `filter`\n // or `sort` *replaces* the built-in one (a hybrid set keeps the others).\n // Mirrors the sheet's action registry contract (see `data-sheet.ts`).\n const _actions = useMemo(() => {\n const merged: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!merged.some((x) => x.id === a.id)) merged.push(a);\n }\n };\n add(actions);\n add(coreActions);\n return merged;\n }, [actions, coreActions]);\n\n const ScrollBody = scrollBody ?? DefaultScrollBody;\n\n // The panel owns the scroll container + the loading sentinel; the (custom or\n // default) scroll body only lays out the cards. So a grid / grouped / windowed\n // body composes without reimplementing paging or selection. The end-of-scroll\n // region is either the default spinner sentinel or the caller's inline\n // footer — both carry the sentinel ref that drives auto-load.\n // The top fade is gated on being scrolled (via `.is-scrolled`), so the first\n // item isn't clipped at rest.\n\n const showStatusBar = statusBar !== false;\n\n let defaultFooter: ReactNode = null;\n if (shouldLoadNextPage) {\n defaultFooter = h(\"div.sentinel\", [h(Spinner, { size: 16 }), \"Loading...\"]);\n } else if (!showStatusBar) {\n defaultFooter = h(\"div.sentinel\", [\n h(Icon, { size: 16, icon: \"tick\" }),\n \"Loaded\",\n ]);\n }\n\n const _contentFooter = h(\n \"div.content-footer-holder\",\n { ref: sentinelRef },\n contentFooter ?? defaultFooter,\n );\n\n // Crawlable paging (see `PageLinks`). Both are plain links, so they work in\n // the server-rendered HTML with no script: the next-page link is visually\n // hidden after the loaded rows and points past the last loaded row; the\n // \"Return to top\" notice heads the content while the view starts mid-list.\n const startAfter = ctx.useValue(startAfterAtom);\n const lastLoadedRow = useMemo(() => {\n for (let i = data.length - 1; i >= 0; i--) {\n if (data[i] != null) return data[i];\n }\n return null;\n }, [data]);\n // Gated on the counts rather than `hasMore`, which reads the resolved\n // provider — synced after mount, so absent in a server render.\n const moreToCome = total == null || loadedCount < total;\n let nextPageLink: ReactNode = null;\n if (pageLinks != null && lastLoadedRow != null && moreToCome) {\n nextPageLink = h(\n \"a.crawl-next-link\",\n {\n href: pageLinks.after(lastLoadedRow),\n rel: \"next\",\n tabIndex: -1,\n \"aria-hidden\": true,\n },\n \"Next page\",\n );\n }\n let viewStartNotice: ReactNode = null;\n if (startAfter != null && pageLinks?.top != null) {\n viewStartNotice = h(\"div.view-start-notice\", [\n h(\"span.view-start-text\", `Continued after #${startAfter}`),\n h(\n AnchorButton,\n { href: pageLinks.top, minimal: true, small: true, icon: \"arrow-up\" },\n pageLinks.topLabel ?? \"Return to top\",\n ),\n ]);\n }\n\n // Body + optional filter/detail sidebar share a horizontal row so each\n // scrolls independently.\n\n // Bottom status row (counter + extras). `statusBar === false` drops it — e.g.\n // when an inline footer carries the counter itself.\n let footer: ReactNode = null;\n let _statusBarContent = statusBar ?? h(DataPanelStatusBar);\n if (showStatusBar) {\n footer = h(\n \"div.data-panel-footer\",\n h(\"div.data-panel-footer-content\", [_statusBarContent]),\n );\n }\n\n const _toolbar = h(\n \"div.data-panel-top-area\",\n h(\n \"div.data-panel-toolbar\",\n h(\n ActionsToolbar,\n {\n actions: _actions,\n tableName: name,\n className: \"data-panel-toolbar-content\",\n // In the panel the title doubles as the modal-selection control,\n // so only render it when modal selection is toggle-able (or a\n // selection is active) — not as a bare label otherwise.\n compact: true,\n collapse: toolbarCollapse,\n },\n toolbar,\n ),\n ),\n );\n\n return h(\n \"div.data-panel\",\n { className: classNames(className, \"toolbar-style-\" + toolbarStyle) },\n [\n h(\"div.data-panel-main\", [\n loaderNode,\n _toolbar,\n h(\n \"div.data-panel-body\",\n {\n onScroll,\n className: classNames({ \"is-scrolled\": scrolled }),\n },\n [\n h(\"div.data-panel-body-content\", [\n viewStartNotice,\n emptyState ?? h(ScrollBody, { placeholders }, cards),\n nextPageLink,\n _contentFooter,\n ]),\n ],\n ),\n footer,\n ]),\n h.if(sidebar != null)(\"div.data-panel-sidebar-container\", sidebar),\n children,\n ],\n );\n}\n\nfunction DataPanelStatusBar({ children }) {\n /** Default status bar for the Data Panel */\n return h(\"div.data-panel-status-bar\", [children, h(LoadProgressIndicator)]);\n}\n\n/** Default scroll-body layout: a vertical flex list of cards, with any loading\n * placeholders appended in the same flow. */\nfunction DefaultScrollBody({ children, placeholders }: ScrollBodyProps) {\n return h(\"div.data-panel-list\", [children, placeholders]);\n}\n\n/** Runs the shared windowed loader from inside the panel (renders nothing).\n * Mounted only once the real provider is resolved, so `useDataLoader` captures\n * the real `fetchData` from the start (see `_DataPanel`). */\nfunction PanelLoader<T = any>({\n fetchData,\n ...options\n}: { fetchData: FetchData<T> } & FetchDataOptions<T>) {\n useDataLoader(fetchData, options);\n return null;\n}\n\n/** Resolve the selection modifiers from either a click event (reads shift /\n * cmd / ctrl) or an explicit modifier object; no argument ⇒ a plain select. */\nfunction modifiersOf(arg?: SelectModifiers | ReactMouseEvent): SelectModifiers {\n if (arg == null) return {};\n if (\"shiftKey\" in arg) {\n return { additive: arg.metaKey || arg.ctrlKey, range: arg.shiftKey };\n }\n return arg;\n}\n\n/**\n * Bottom-sentinel infinite-scroll hook (no `react-intersection-observer`\n * dependency). Calls `onVisible` when the observed element is on screen, and —\n * crucially — **re-observes on every `deps` change** so the callback reflects\n * the *current* post-layout visibility rather than the pre-load render.\n *\n * This is what avoids the double-load: a plain observer whose visibility is\n * mirrored into React state lags a render behind the DOM, so a load-driven\n * re-render fires a second `onVisible` before the observer catches up. By\n * re-arming after each load (`deps = [loadedCount, canLoadMore]`), the observer\n * emits a fresh callback for the settled layout: it fires again only if the\n * sentinel is *still* visible (viewport not yet filled), so it loads exactly\n * one page per bottom-reach and self-fills an underfull viewport without\n * overshooting. Pass `onVisible = null` to disarm (loading / no more data).\n */\nfunction useBottomSentinel<E extends HTMLElement>(\n onVisible: (() => void) | null,\n deps: unknown[],\n): (el: E | null) => void {\n const elRef = useRef<E | null>(null);\n const observerRef = useRef<IntersectionObserver | null>(null);\n const cbRef = useRef(onVisible);\n cbRef.current = onVisible;\n\n const setRef = useCallback((el: E | null) => {\n elRef.current = el;\n observerRef.current?.disconnect();\n observerRef.current = null;\n if (el == null) return;\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) cbRef.current?.();\n },\n { rootMargin: \"300px\" },\n );\n observer.observe(el);\n observerRef.current = observer;\n }, []);\n\n // Re-arm after each load so the observer re-checks the settled layout.\n useEffect(() => {\n const el = elRef.current;\n const observer = observerRef.current;\n if (el == null || observer == null) return;\n observer.disconnect();\n observer.observe(el);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n useEffect(() => () => observerRef.current?.disconnect(), []);\n return setRef;\n}\n\nconst rowSelectionAtom = atom((get) => {\n /** Coerce selection to full rows, for use with data panel instead of data sheet. */\n const selection = get(selectionAtom);\n if (selection.some((r) => r.cols != null)) {\n // A card list has no cells or columns. When the selection carries columns —\n // inherited from a shared store the sheet also drives (a `DataView` toggle) —\n // coerce it to the full rows it covers, so the toolbar shows row-scoped\n // actions rather than column/cell ones for a column that isn't visible here.\n // Column-only selections (no rows) collapse to nothing.\n return rowIndicesToRegions(new Set(getSelectedRowIndices(selection)));\n } else {\n return selection;\n }\n}, passThroughSet(selectionAtom));\n\nconst updateSelectionAtom = atom(\n null,\n (get, set, index: number, mods: SelectModifiers) => {\n /** Update selection from a row index and modifiers. */\n const { enableMultipleSelection, enableModalSelection } = get(\n interactionOptionsAtom,\n );\n let enableSelection = get(enableSelectionAtom);\n if (!enableSelection) {\n // Cmd/ctrl-click *enters* select mode on a modal view and selects the\n // row, the familiar list idiom — so a bulk action doesn't require finding\n // the Select control first. The flag is read back below rather than\n // trusted from this scope: the write goes through the store synchronously.\n if (!enableModalSelection || !mods.additive) return;\n set(enableSelectionAtom, true);\n enableSelection = get(enableSelectionAtom);\n if (!enableSelection) return;\n }\n const selection = get(rowSelectionAtom);\n const anchorRef = get(anchorRefAtom);\n const res = buildDataViewSelection(\n index,\n mods,\n selection,\n anchorRef,\n enableMultipleSelection,\n );\n set(selectionAtom, res);\n },\n);\n\nconst selectedRowIndicesAtom = atom((get) => {\n const sel = get(selectionAtom);\n return new Set(getSelectedRowIndices(sel));\n});\n\ntype ItemSelectionKeys = \"onSelect\" | \"selected\" | \"selectable\";\n\ntype DataCardProps = {\n children: ReactNode;\n className: string;\n style?: CSSProperties;\n} & Pick<ItemComponentProps, ItemSelectionKeys>;\n\nexport function DataCard<T = any>(props: DataCardProps) {\n /** A basic card that implements the data panel's selection behavior. */\n return h(\n \"div.data-card.data-panel-item\",\n {\n className: classNames(props.className, {\n selected: props.selected,\n selectable: props.selectable,\n }),\n onClick: props.onSelect,\n style: props.style,\n },\n props.children,\n );\n}\n\ntype DataCardInnerComponent<T> = (\n props: ItemComponentProps<T>,\n) => React.ReactNode;\n\nexport function createDataCard<T>(\n component: DataCardInnerComponent<T>,\n extraProps = {},\n) {\n return (props: ItemComponentProps<T>) => {\n const { selected, selectable, onSelect } = props;\n return h(\n DataCard,\n {\n selected,\n selectable,\n onSelect,\n ...extraProps,\n },\n h(component, props),\n );\n };\n}\n"],"names":["DataPanelToolbarStyle","splitDataProviderProps","DataViewRendererType","h","DataSheetProvider","ctx","dataProviderAtom","useSelector","autoLoadPagesAtom","useLoadControls","useState","useCallback","enableSelectionAtom","useMemo","classNames","NonIdealState","Classes","useDataPanelControls","Spinner","Icon","startAfterAtom","AnchorButton","ActionsToolbar","LoadProgressIndicator","useDataLoader","useRef","useEffect","atom","selection","selectionAtom","rowIndicesToRegions","getSelectedRowIndices","passThroughSet","interactionOptionsAtom","anchorRefAtom","buildDataViewSelection"],"mappings":";;;;;;;;;;;;;;;;;;;AAiFO,IAAK,0CAAAA,2BAAL;AACLA,yBAAA,UAAA,IAAW;AACXA,yBAAA,MAAA,IAAO;AACPA,yBAAA,SAAA,IAAU;AAIVA,yBAAA,UAAA,IAAW;AAPD,SAAAA;AAAA,GAAA,yBAAA,CAAA,CAAA;AAmGL,SAAS,UAAa,OAA0B;AACrD,QAAM,CAAC,eAAe,aAAa,IAAIC,4BAAuB;AAAA,IAC5D,GAAG;AAAA,IACH,UAAUC,aAAAA,qBAAqB;AAAA,EAAA,CAChC;AACD,SAAOC,iBAAAA;AAAAA,IACLC,KAAAA;AAAAA,IACA;AAAA,IACAD,iBAAAA,QAAE,mBAAwB,aAAa;AAAA,EAAA;AAE3C;AAaO,SAAS,kBAAqB;AAAA,EACnC;AAAA,EACA,UAAU,CAAA;AAAA,EACV,UAAU,CAAA;AAAA,EACV,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf,eAAe;AAAA,EACf,kBA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IACxB;AACA,UAAMgB,cAAY,IAAI,gBAAgB;AACtC,UAAM,YAAY,IAAIM,uBAAa;AACnC,UAAM,MAAMC,YAAAA;AAAAA,MACV;AAAA,MACA;AAAA,MACAP;AAAAA,MACA;AAAA,MACA;AAAA,IAAA;AAEF,QAAIC,UAAAA,eAAe,GAAG;AAAA,EACxB;AACF;AAEA,MAAM,yBAAyBF,MAAAA,KAAK,CAAC,QAAQ;AAC3C,QAAM,MAAM,IAAIE,uBAAa;AAC7B,SAAO,IAAI,IAAIE,kCAAsB,GAAG,CAAC;AAC3C,CAAC;AAUM,SAAS,SAAkB,OAAsB;AAEtD,SAAO5B,iBAAAA;AAAAA,IACL;AAAA,IACA;AAAA,MACE,WAAWW,oBAAAA,QAAW,MAAM,WAAW;AAAA,QACrC,UAAU,MAAM;AAAA,QAChB,YAAY,MAAM;AAAA,MAAA,CACnB;AAAA,MACD,SAAS,MAAM;AAAA,MACf,OAAO,MAAM;AAAA,IAAA;AAAA,IAEf,MAAM;AAAA,EAAA;AAEV;AAMO,SAAS,eACd,WACA,aAAa,IACb;AACA,SAAO,CAAC,UAAiC;AACvC,UAAM,EAAE,UAAU,YAAY,SAAA,IAAa;AAC3C,WAAOX,iBAAAA;AAAAA,MACL;AAAA,MACA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,QACA,GAAG;AAAA,MAAA;AAAA,MAELA,iBAAAA,QAAE,WAAW,KAAK;AAAA,IAAA;AAAA,EAEtB;AACF;;;;;;"}
1
+ {"version":3,"file":"data-panel.cjs","sources":["../src/data-panel.ts"],"sourcesContent":["/**\n * DataPanel — a card/list renderer over the same headless core as `DataSheet`.\n *\n * The two components differ in only two dimensions: the **view** (cards vs. the\n * Blueprint cell grid) and **edit granularity** (immediate per-item vs. a\n * batched pending-ops stack). Everything else — provider-driven windowed\n * loading, `{sorts, filters}` view state, the selection set, and set-based\n * actions — is the shared substrate, reused here unchanged:\n *\n * - `DataSheetProvider` supplies the jotai+zustand store.\n * - `useDataLoader(provider.fetchData)` drives windowed loading and threads the\n * active store sorts/filters through so a server provider applies them.\n * - `ActionsToolbar` + `FilterBar` render selection-aware actions and the\n * active sort/filter tags — they read the store, not the table.\n *\n * The only list-specific pieces are: rows rendered as cards via a consumer\n * `itemComponent`; selection expressed as `FULL_ROWS` regions (so the existing\n * row-targeted `TableAction`s apply); an infinite-scroll sentinel that advances\n * the loader's visible region; and `FacetControls`, which stands in for the\n * column-header dropdown the list doesn't have (a menu to add a column filter /\n * sort from the column-declared `filterable` / `sortable` capabilities).\n *\n * See [[Data list editors]] in the Macrostrat workbench for the design.\n */\nimport type { ToolbarCollapse } from \"@macrostrat/ui-components\";\nimport h from \"./data-panel.module.sass\";\nimport {\n ComponentType,\n CSSProperties,\n MouseEvent as ReactMouseEvent,\n ReactNode,\n UIEvent as ReactUIEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n AnchorButton,\n Button,\n Classes,\n Icon,\n NonIdealState,\n Spinner,\n} from \"@blueprintjs/core\";\nimport { startAfterAtom } from \"./provider/loader-state.ts\";\nimport {\n anchorRefAtom,\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n DataSheetProvider,\n DataViewRendererType,\n FetchData,\n enableSelectionAtom,\n interactionOptionsAtom,\n selectionAtom,\n splitDataProviderProps,\n useSelector,\n} from \"./provider\";\nimport {\n buildDataViewSelection,\n getSelectedRowIndices,\n rowIndicesToRegions,\n TableAction,\n} from \"./actions\";\nimport {\n autoLoadPagesAtom,\n useDataLoader,\n useLoadControls,\n} from \"./postgrest-table\";\nimport classNames from \"classnames\";\nimport {\n ActionsToolbar,\n LoadProgressIndicator,\n useDataPanelControls,\n type ViewControlsPresentation,\n} from \"./components\";\nimport { DataViewSharedProps, FetchDataOptions } from \"./types\";\nimport { atom } from \"jotai\";\nimport { passThroughSet } from \"./utils\";\n\nexport enum DataPanelToolbarStyle {\n BORDERED = \"bordered\",\n FADE = \"fade\",\n MINIMAL = \"minimal\",\n /** Toolbar (and footer) sized to their contents and lifted over the scroll\n * body, rather than occupying a full-width band. Pairs with\n * `viewControls: \"popover\"`, since inline controls cost real space here. */\n FLOATING = \"floating\",\n}\n\n/** Props for a custom scroll-body layout component. It receives the\n * already-rendered, selection-wrapped item cards and lays them out however it\n * likes (a grid, sections, sticky headers, its own windowing). The panel owns\n * the surrounding scroll container and the loading sentinel; the scroll body\n * only arranges the items. */\nexport interface ScrollBodyProps {\n /** The rendered item cards (each wrapped for selection styling). */\n children: ReactNode;\n /** Loading skeletons for the page currently being fetched, if any. Kept\n * separate from `children` because they are transient stand-ins, not items:\n * a layout that assigns a lasting position per item (e.g. the masonry body)\n * must not hand one to a placeholder. Render them after the items; a body\n * that ignores them simply shows no loading state. */\n placeholders?: ReactNode;\n}\n\n/** Props handed to a consumer's card renderer for one row. */\nexport interface ItemComponentProps<T = any> {\n /** The row's data. */\n data: T;\n /** Underlying data-row index (stable within a loaded window). */\n index: number;\n /** Whether this row is in the current selection. */\n selected: boolean;\n /** Whether the row can be selected */\n selectable: boolean;\n /** Select this row. Pass the click's `MouseEvent` (or `React.MouseEvent`) to\n * honor shift / cmd / ctrl automatically — the usual wiring is\n * `onClick: onSelect`. Or pass an explicit `SelectModifiers` object; no\n * argument means a plain (replace) select. */\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) => void;\n}\n\nexport interface DataPanelProps<T = any> extends DataViewSharedProps<T> {\n /** Renders one row as a card. */\n itemComponent: ComponentType<ItemComponentProps<T>>;\n /** Arbitrary nodes for the bottom status row (beside the loaded/total\n * counter). Pass `false` to drop the status row entirely — e.g. when the\n * counter is folded into an inline footer instead. */\n statusBar?: ReactNode | false;\n /** Custom header controls, replacing the default `FacetControls` +\n * `FilterBar`. Rendered inside the provider, so it can drive sort/filter via\n * the exported building blocks (`FacetControls`, `FilterBar`) and the store\n * hooks (`useStoreAPI` / `useSelector`). The selection `ActionsToolbar` still\n * renders above it. Omit for the sane default. */\n toolbar?: ReactNode;\n /** A filter/detail sidebar beside the scroll body (its own scroll). Rendered\n * inside the provider, so a custom filter panel drives sort/filter through\n * the store hooks — the alternative placement to the top `toolbar`. */\n sidebar?: ReactNode;\n /** Footer content. Rendered inside the provider, so it reads live load state\n * from the store via `useLoadControls()` (loadMore / loading / hasMore /\n * loaded / total / paused) rather than a passed-down contract — a footer, a\n * status line, or a \"Load more\" button all just call the hook. */\n contentFooter?: ReactNode;\n /** Auto-load this many pages per burst, then pause: a paused panel stops\n * fetching on scroll until `useLoadControls().loadMore()` starts the next\n * burst (e.g. a footer \"Load more\" button). Omit for unbounded auto-scroll. */\n // TODO: we may deprecate this for opt-in scrolling\n autoLoadPages?: number;\n /** Custom layout for the item cards — the seam for anything other than a\n * vertical list (a CSS grid for several per row, grouped sections, sticky\n * sub-headers, a windowed renderer). Receives the rendered cards as\n * `children`; the panel still owns the scroll container and the loading\n * sentinel, so paging and selection keep working. Defaults to a vertical\n * flex list. */\n scrollBody?: ComponentType<ScrollBodyProps>;\n className?: string;\n toolbarStyle?: DataPanelToolbarStyle | string;\n /** Where the built-in view controls (inline filters, Filter menu, Sort menu)\n * sit in the toolbar: `\"inline\"` (default) places each in the toolbar;\n * `\"popover\"` collapses all of them behind a single button — for a narrow or\n * deliberately chrome-light toolbar. Same controls and state either way.\n * Ignored while a modal view is selecting: the toolbar then carries a single\n * control that leaves select mode. */\n viewControls?: ViewControlsPresentation;\n /** How the toolbar sheds width (the shared `Toolbar`'s `collapse`): with\n * `\"narrow\"`, button labels drop to icons and then contextual controls fold\n * into a \"more\" popover as the panel narrows. Default `\"never\"`. */\n toolbarCollapse?: ToolbarCollapse;\n /** Arbitrary children rendered inside the provider, after the panel. */\n children?: ReactNode;\n}\n\n/**\n * Resolve the data source (shared with `DataSheet` / `DataView` via\n * `useResolvedProvider`), wrap in the shared provider, and render the inner\n * panel.\n */\nexport function DataPanel<T>(props: DataPanelProps<T>) {\n const [providerProps, rendererProps] = splitDataProviderProps({\n ...props,\n viewType: DataViewRendererType.CARDS,\n });\n return h(\n DataSheetProvider<T>,\n providerProps,\n h(DataPanelRenderer<any>, rendererProps),\n );\n}\n\n/** Selection modifier keys, following the familiar list idiom. */\nexport interface SelectModifiers {\n /** cmd/ctrl — toggle this row in/out of the selection (or extend a range). */\n additive?: boolean;\n /** shift — select the range from the anchor (last plain/cmd click) to here. */\n range?: boolean;\n}\n\n/** The card-list renderer. Assumes it is rendered inside a `DataSheetProvider`\n * (the `DataPanel` wrapper, or `DataView`). Exported so a shared-store\n * `DataView` can mount it directly alongside `_DataSheet`. */\nexport function DataPanelRenderer<T>({\n itemComponent,\n actions = [],\n filters = [],\n pageSize = 50,\n filterDebounce,\n initialData,\n name,\n // Bottom bar\n statusBar,\n toolbar,\n sidebar,\n // Footer within content flow\n contentFooter,\n autoLoadPages,\n scrollBody,\n pageLinks,\n className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\n toolbarCollapse = \"never\",\n children,\n}: Omit<DataPanelProps<T>, \"provider\" | \"fetchData\" | \"data\" | \"identity\">) {\n const {\n provider: activeProvider,\n isLocalProvider,\n localCount,\n } = ctx.useValue(dataProviderAtom);\n\n // The loader is mounted as a child component (below), NOT called as a hook\n // here, and only once `activeProvider` resolves. This mirrors `_DataSheet`:\n // `dataProviderAtom` is synced by a parent effect that fires *after* this\n // component's effects, so a hook call here would capture the placeholder\n // provider on first render and — since `fetchData` isn't one of its effect\n // deps — never re-fetch with the real one. A child that mounts with the real\n // `fetchData` already in hand sidesteps that entirely.\n // A local (in-memory) source loads all of its rows in one page; its count\n // rides on the resolved provider, so the renderer no longer takes a `data`\n // prop (the store is the single source of live rows).\n const loaderPageSize = isLocalProvider ? Math.max(localCount, 1) : pageSize;\n\n const data = useSelector((s) => s.data);\n\n // Load state + pause/resume live in the store, read via `useLoadControls`\n // (also available to the caller's `footer` via the same hook). The panel's\n // `autoLoadPages` prop is the store's configuration input.\n ctx.useSync(autoLoadPagesAtom, autoLoadPages ?? null);\n const {\n loading,\n initialized,\n error,\n hasMore,\n loaded,\n total,\n paused,\n canLoadMore,\n advance,\n } = useLoadControls();\n\n // Track whether the body is scrolled off the top, to gate the top fade.\n // `setState` with an unchanged value is a no-op, so this only re-renders on\n // the at-top ↔ scrolled transition.\n const [scrolled, setScrolled] = useState(false);\n const onScroll = useCallback((e: ReactUIEvent<HTMLDivElement>) => {\n setScrolled(e.currentTarget.scrollTop > 4);\n }, []);\n\n const enableSelection = ctx.useValue(enableSelectionAtom);\n const selectedIndices = ctx.useValue(selectedRowIndicesAtom);\n const select = ctx.useSet(updateSelectionAtom);\n\n const loadedCount = useMemo(() => {\n let n = 0;\n for (const r of data) if (r != null) n++;\n return n;\n }, [data]);\n\n // Refresh-token, rowEditing, and load controls (loadMore / pause) are all\n // store-managed (see `useLoadControls`), shared with `_DataSheet` — so both\n // renderers, and any footer, drive loading off one source.\n\n // Infinite scroll. A naive \"load a page when the bottom sentinel is visible\"\n // over-fetches: when a page's rows commit, this component re-renders\n // (loadedCount changed) *before* the IntersectionObserver has re-evaluated\n // the sentinel's new position, so a stale \"still visible\" fires a second\n // load. `useBottomSentinel` re-observes the sentinel whenever the pass-through\n // deps change, so every trigger reflects the *current* post-layout\n // visibility — it loads one page, and only loads another if the sentinel is\n // genuinely still on screen. `advance` (from the store) moves the loader one\n // page without resuming a paused auto-load.\n const sentinelRef = useBottomSentinel(canLoadMore ? advance : null, [\n loadedCount,\n canLoadMore,\n ]);\n\n const cards: ReactNode[] = data\n .filter((d) => d != null)\n .map((row: ReactNode, i) => {\n const selected = enableSelection && selectedIndices.has(i);\n return h(\n \"div.data-panel-item-container\",\n { key: `item-${i}`, className: classNames({ selected }) },\n h(itemComponent, {\n data: row,\n index: i,\n selected,\n selectable: enableSelection,\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) =>\n select(i, modifiersOf(arg)),\n }),\n );\n });\n\n // Body-level empty/error state: when nothing has loaded, show a clear message\n // instead of a blank list — an errored source (e.g. a 401 on the whole route)\n // degrades gracefully, and a genuinely empty result reads as \"no results\"\n // rather than a perpetual spinner.\n // A load is pending whenever a fetch is in flight OR the view was just reset\n // and hasn't fetched yet (`!initialized`) — the window that would otherwise\n // flash \"No results\" before the request starts.\n const loadPending = (loading || !initialized) && error == null;\n\n let emptyState: ReactNode = null;\n if (cards.length === 0) {\n if (error != null) {\n emptyState = h(LoadErrorState, { error });\n } else if (initialized && !loading) {\n // Only after a fetch settled with no rows — not during the reset gap.\n emptyState = h(NonIdealState, {\n icon: \"search\",\n title: \"No results\",\n });\n }\n }\n\n // Skeleton placeholders for the page being fetched — on a view change (the\n // reset pre-sizes to a page of `null` slots) or the next scroll page — so the\n // body shows shimmer where rows will land instead of a blank flash or a\n // footer pinging up into the gap. Bounded to a viewport's worth of cards.\n const placeholderCards: ReactNode[] = [];\n if (loadPending) {\n const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);\n for (let i = 0; i < pending; i++) {\n placeholderCards.push(\n h(\n \"div.data-panel-item-container.is-skeleton\",\n { key: `skeleton-${i}`, \"aria-hidden\": true },\n h(\"div.data-panel-skeleton\", { className: Classes.SKELETON }),\n ),\n );\n }\n }\n let placeholders: ReactNode = null;\n if (placeholderCards.length > 0) {\n placeholders = placeholderCards;\n }\n\n // The default spinner sentinel (below-placement): hidden while paused so the\n // pinned footer's \"Load more\" takes over.\n const shouldLoadNextPage = (hasMore || loading) && !paused && error == null;\n\n // Mount the loader only once the provider resolves (see `PanelLoader`). Built\n // as a real conditional — `h.if(...)` evaluates its arguments eagerly, so\n // `activeProvider.fetchData` can't be referenced inside it while null.\n let loaderNode: ReactNode = null;\n if (activeProvider != null) {\n loaderNode = h(PanelLoader, {\n fetchData: activeProvider.fetchData,\n pageSize: loaderPageSize,\n fetchMode: isLocalProvider ? undefined : \"scroll\",\n filterDebounce,\n initialData,\n });\n }\n\n const coreActions = useDataPanelControls(filters, viewControls);\n\n // Merge consumer actions with the synthesized Filter/Sort controls, deduped\n // by id — consumer actions come first, so passing an action with id `filter`\n // or `sort` *replaces* the built-in one (a hybrid set keeps the others).\n // Mirrors the sheet's action registry contract (see `data-sheet.ts`).\n const _actions = useMemo(() => {\n const merged: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!merged.some((x) => x.id === a.id)) merged.push(a);\n }\n };\n add(actions);\n add(coreActions);\n return merged;\n }, [actions, coreActions]);\n\n const ScrollBody = scrollBody ?? DefaultScrollBody;\n\n // The panel owns the scroll container + the loading sentinel; the (custom or\n // default) scroll body only lays out the cards. So a grid / grouped / windowed\n // body composes without reimplementing paging or selection. The end-of-scroll\n // region is either the default spinner sentinel or the caller's inline\n // footer — both carry the sentinel ref that drives auto-load.\n // The top fade is gated on being scrolled (via `.is-scrolled`), so the first\n // item isn't clipped at rest.\n\n const showStatusBar = statusBar !== false;\n\n let defaultFooter: ReactNode = null;\n if (shouldLoadNextPage) {\n defaultFooter = h(\"div.sentinel\", [h(Spinner, { size: 16 }), \"Loading...\"]);\n } else if (!showStatusBar) {\n defaultFooter = h(\"div.sentinel\", [\n h(Icon, { size: 16, icon: \"tick\" }),\n \"Loaded\",\n ]);\n }\n\n const _contentFooter = h(\n \"div.content-footer-holder\",\n { ref: sentinelRef },\n contentFooter ?? defaultFooter,\n );\n\n // Crawlable paging (see `PageLinks`). Both are plain links, so they work in\n // the server-rendered HTML with no script: the next-page link is visually\n // hidden after the loaded rows and points past the last loaded row; the\n // \"Return to top\" notice heads the content while the view starts mid-list.\n const startAfter = ctx.useValue(startAfterAtom);\n const lastLoadedRow = useMemo(() => {\n for (let i = data.length - 1; i >= 0; i--) {\n if (data[i] != null) return data[i];\n }\n return null;\n }, [data]);\n // Gated on the counts rather than `hasMore`, which reads the resolved\n // provider — synced after mount, so absent in a server render.\n const moreToCome = total == null || loadedCount < total;\n let nextPageLink: ReactNode = null;\n if (pageLinks != null && lastLoadedRow != null && moreToCome) {\n nextPageLink = h(\n \"a.crawl-next-link\",\n {\n href: pageLinks.after(lastLoadedRow),\n rel: \"next\",\n tabIndex: -1,\n \"aria-hidden\": true,\n },\n \"Next page\",\n );\n }\n let viewStartNotice: ReactNode = null;\n if (startAfter != null && pageLinks?.top != null) {\n viewStartNotice = h(\"div.view-start-notice\", [\n h(\"span.view-start-text\", `Continued after #${startAfter}`),\n h(\n AnchorButton,\n { href: pageLinks.top, minimal: true, small: true, icon: \"arrow-up\" },\n pageLinks.topLabel ?? \"Return to top\",\n ),\n ]);\n }\n\n // Body + optional filter/detail sidebar share a horizontal row so each\n // scrolls independently.\n\n // Bottom status row (counter + extras). `statusBar === false` drops it — e.g.\n // when an inline footer carries the counter itself.\n let footer: ReactNode = null;\n let _statusBarContent = statusBar ?? h(DataPanelStatusBar);\n if (showStatusBar) {\n footer = h(\n \"div.data-panel-footer\",\n h(\"div.data-panel-footer-content\", [_statusBarContent]),\n );\n }\n\n const _toolbar = h(\n \"div.data-panel-top-area\",\n h(\n \"div.data-panel-toolbar\",\n h(\n ActionsToolbar,\n {\n actions: _actions,\n tableName: name,\n className: \"data-panel-toolbar-content\",\n // In the panel the title doubles as the modal-selection control,\n // so only render it when modal selection is toggle-able (or a\n // selection is active) — not as a bare label otherwise.\n compact: true,\n collapse: toolbarCollapse,\n },\n toolbar,\n ),\n ),\n );\n\n return h(\n \"div.data-panel\",\n { className: classNames(className, \"toolbar-style-\" + toolbarStyle) },\n [\n h(\"div.data-panel-main\", [\n loaderNode,\n _toolbar,\n h(\n \"div.data-panel-body\",\n {\n onScroll,\n className: classNames({ \"is-scrolled\": scrolled }),\n },\n [\n h(\"div.data-panel-body-content\", [\n viewStartNotice,\n emptyState ?? h(ScrollBody, { placeholders }, cards),\n nextPageLink,\n _contentFooter,\n ]),\n ],\n ),\n footer,\n ]),\n h.if(sidebar != null)(\"div.data-panel-sidebar-container\", sidebar),\n children,\n ],\n );\n}\n\nfunction DataPanelStatusBar({ children }) {\n /** Default status bar for the Data Panel */\n return h(\"div.data-panel-status-bar\", [children, h(LoadProgressIndicator)]);\n}\n\n/** Default scroll-body layout: a vertical flex list of cards, with any loading\n * placeholders appended in the same flow. */\nfunction DefaultScrollBody({ children, placeholders }: ScrollBodyProps) {\n return h(\"div.data-panel-list\", [children, placeholders]);\n}\n\n/** Runs the shared windowed loader from inside the panel (renders nothing).\n * Mounted only once the real provider is resolved, so `useDataLoader` captures\n * the real `fetchData` from the start (see `_DataPanel`). */\nfunction PanelLoader<T = any>({\n fetchData,\n ...options\n}: { fetchData: FetchData<T> } & FetchDataOptions<T>) {\n useDataLoader(fetchData, options);\n return null;\n}\n\n/** Resolve the selection modifiers from either a click event (reads shift /\n * cmd / ctrl) or an explicit modifier object; no argument ⇒ a plain select. */\nfunction modifiersOf(arg?: SelectModifiers | ReactMouseEvent): SelectModifiers {\n if (arg == null) return {};\n if (\"shiftKey\" in arg) {\n return { additive: arg.metaKey || arg.ctrlKey, range: arg.shiftKey };\n }\n return arg;\n}\n\n/** A failed load, with a retry: auto-load stays off after an error, so\n * reloading is the user's call. */\nfunction LoadErrorState({ error }: { error: Error }) {\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n return h(NonIdealState, {\n icon: \"error\",\n title: \"Couldn't load data\",\n description: error.message ?? \"The data source returned an error.\",\n action: h(\n Button,\n { icon: \"refresh\", onClick: () => bumpRefresh((v) => v + 1) },\n \"Try again\",\n ),\n });\n}\n\n/**\n * Bottom-sentinel infinite-scroll hook (no `react-intersection-observer`\n * dependency). Calls `onVisible` when the observed element is on screen, and —\n * crucially — **re-observes on every `deps` change** so the callback reflects\n * the *current* post-layout visibility rather than the pre-load render.\n *\n * This is what avoids the double-load: a plain observer whose visibility is\n * mirrored into React state lags a render behind the DOM, so a load-driven\n * re-render fires a second `onVisible` before the observer catches up. By\n * re-arming after each load (`deps = [loadedCount, canLoadMore]`), the observer\n * emits a fresh callback for the settled layout: it fires again only if the\n * sentinel is *still* visible (viewport not yet filled), so it loads exactly\n * one page per bottom-reach and self-fills an underfull viewport without\n * overshooting. Pass `onVisible = null` to disarm (loading / no more data).\n */\nfunction useBottomSentinel<E extends HTMLElement>(\n onVisible: (() => void) | null,\n deps: unknown[],\n): (el: E | null) => void {\n const elRef = useRef<E | null>(null);\n const observerRef = useRef<IntersectionObserver | null>(null);\n const cbRef = useRef(onVisible);\n cbRef.current = onVisible;\n\n const setRef = useCallback((el: E | null) => {\n elRef.current = el;\n observerRef.current?.disconnect();\n observerRef.current = null;\n if (el == null) return;\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) cbRef.current?.();\n },\n { rootMargin: \"300px\" },\n );\n observer.observe(el);\n observerRef.current = observer;\n }, []);\n\n // Re-arm after each load so the observer re-checks the settled layout.\n useEffect(() => {\n const el = elRef.current;\n const observer = observerRef.current;\n if (el == null || observer == null) return;\n observer.disconnect();\n observer.observe(el);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n useEffect(() => () => observerRef.current?.disconnect(), []);\n return setRef;\n}\n\nconst rowSelectionAtom = atom((get) => {\n /** Coerce selection to full rows, for use with data panel instead of data sheet. */\n const selection = get(selectionAtom);\n if (selection.some((r) => r.cols != null)) {\n // A card list has no cells or columns. When the selection carries columns —\n // inherited from a shared store the sheet also drives (a `DataView` toggle) —\n // coerce it to the full rows it covers, so the toolbar shows row-scoped\n // actions rather than column/cell ones for a column that isn't visible here.\n // Column-only selections (no rows) collapse to nothing.\n return rowIndicesToRegions(new Set(getSelectedRowIndices(selection)));\n } else {\n return selection;\n }\n}, passThroughSet(selectionAtom));\n\nconst updateSelectionAtom = atom(\n null,\n (get, set, index: number, mods: SelectModifiers) => {\n /** Update selection from a row index and modifiers. */\n const { enableMultipleSelection, enableModalSelection } = get(\n interactionOptionsAtom,\n );\n let enableSelection = get(enableSelectionAtom);\n if (!enableSelection) {\n // Cmd/ctrl-click *enters* select mode on a modal view and selects the\n // row, the familiar list idiom — so a bulk action doesn't require finding\n // the Select control first. The flag is read back below rather than\n // trusted from this scope: the write goes through the store synchronously.\n if (!enableModalSelection || !mods.additive) return;\n set(enableSelectionAtom, true);\n enableSelection = get(enableSelectionAtom);\n if (!enableSelection) return;\n }\n const selection = get(rowSelectionAtom);\n const anchorRef = get(anchorRefAtom);\n const res = buildDataViewSelection(\n index,\n mods,\n selection,\n anchorRef,\n enableMultipleSelection,\n );\n set(selectionAtom, res);\n },\n);\n\nconst selectedRowIndicesAtom = atom((get) => {\n const sel = get(selectionAtom);\n return new Set(getSelectedRowIndices(sel));\n});\n\ntype ItemSelectionKeys = \"onSelect\" | \"selected\" | \"selectable\";\n\ntype DataCardProps = {\n children: ReactNode;\n className: string;\n style?: CSSProperties;\n} & Pick<ItemComponentProps, ItemSelectionKeys>;\n\nexport function DataCard<T = any>(props: DataCardProps) {\n /** A basic card that implements the data panel's selection behavior. */\n return h(\n \"div.data-card.data-panel-item\",\n {\n className: classNames(props.className, {\n selected: props.selected,\n selectable: props.selectable,\n }),\n onClick: props.onSelect,\n style: props.style,\n },\n props.children,\n );\n}\n\ntype DataCardInnerComponent<T> = (\n props: ItemComponentProps<T>,\n) => React.ReactNode;\n\nexport function createDataCard<T>(\n component: DataCardInnerComponent<T>,\n extraProps = {},\n) {\n return (props: ItemComponentProps<T>) => {\n const { selected, selectable, onSelect } = props;\n return h(\n DataCard,\n {\n selected,\n selectable,\n onSelect,\n ...extraProps,\n },\n h(component, props),\n );\n };\n}\n"],"names":["DataPanelToolbarStyle","splitDataProviderProps","DataViewRendererType","h","DataSheetProvider","ctx","dataProviderAtom","useSelector","autoLoadPagesAtom","useLoadControls","useState","useCallback","enableSelectionAtom","useMemo","classNames","NonIdealState","Classes","useDataPanelControls","Spinner","Icon","startAfterAtom","AnchorButton","ActionsToolbar","LoadProgressIndicator","useDataLoader","dataRefreshTokenAtom","Button","useRef","useEffect","atom","selection","selectionAtom","rowIndicesToRegions","getSelectedRowIndices","passThroughSet","interactionOptionsAtom","anchorRefAtom","buildDataViewSelection"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmFO,IAAK,0CAAAA,2BAAL;AACLA,yBAAA,UAAA,IAAW;AACXA,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AM,IAAIE,uBAAa;AAC7B,SAAO,IAAI,IAAIE,kCAAsB,GAAG,CAAC;AAC3C,CAAC;AAUM,SAAS,SAAkB,OAAsB;AAEtD,SAAO9B,iBAAAA;AAAAA,IACL;AAAA,IACA;AAAA,MACE,WAAWW,oBAAAA,QAAW,MAAM,WAAW;AAAA,QACrC,UAAU,MAAM;AAAA,QAChB,YAAY,MAAM;AAAA,MAAA,CACnB;AAAA,MACD,SAAS,MAAM;AAAA,MACf,OAAO,MAAM;AAAA,IAAA;AAAA,IAEf,MAAM;AAAA,EAAA;AAEV;AAMO,SAAS,eACd,WACA,aAAa,IACb;AACA,SAAO,CAAC,UAAiC;AACvC,UAAM,EAAE,UAAU,YAAY,SAAA,IAAa;AAC3C,WAAOX,iBAAAA;AAAAA,MACL;AAAA,MACA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,QACA,GAAG;AAAA,MAAA;AAAA,MAELA,iBAAAA,QAAE,WAAW,KAAK;AAAA,IAAA;AAAA,EAEtB;AACF;;;;;;"}
@@ -1,6 +1,6 @@
1
1
  import h from "./data-panel.module.sass.js";
2
2
  import { useState, useCallback, useMemo, useRef, useEffect } from "react";
3
- import { NonIdealState, Classes, Spinner, Icon, AnchorButton } from "@blueprintjs/core";
3
+ import { NonIdealState, Classes, Spinner, Icon, AnchorButton, Button } from "@blueprintjs/core";
4
4
  import { startAfterAtom } from "./provider/loader-state.js";
5
5
  import classNames from "classnames";
6
6
  import { atom } from "jotai";
@@ -12,6 +12,7 @@ import { passThroughSet } from "./utils/atoms.js";
12
12
  import { splitDataProviderProps, DataSheetProvider, ctx, dataProviderAtom, useSelector } from "./provider/core.js";
13
13
  import { DataViewRendererType, enableSelectionAtom, interactionOptionsAtom } from "./provider/interactions.js";
14
14
  import { ActionsToolbar } from "./components/toolbars/actions-toolbar.js";
15
+ import { dataRefreshTokenAtom } from "./provider/table-data.js";
15
16
  import { LoadProgressIndicator } from "./components/indicators/view-info.js";
16
17
  var DataPanelToolbarStyle = /* @__PURE__ */ ((DataPanelToolbarStyle2) => {
17
18
  DataPanelToolbarStyle2["BORDERED"] = "bordered";
@@ -107,11 +108,7 @@ function DataPanelRenderer({
107
108
  let emptyState = null;
108
109
  if (cards.length === 0) {
109
110
  if (error != null) {
110
- emptyState = h(NonIdealState, {
111
- icon: "error",
112
- title: "Couldn't load data",
113
- description: error.message ?? "The data source returned an error."
114
- });
111
+ emptyState = h(LoadErrorState, { error });
115
112
  } else if (initialized && !loading) {
116
113
  emptyState = h(NonIdealState, {
117
114
  icon: "search",
@@ -284,6 +281,19 @@ function modifiersOf(arg) {
284
281
  }
285
282
  return arg;
286
283
  }
284
+ function LoadErrorState({ error }) {
285
+ const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);
286
+ return h(NonIdealState, {
287
+ icon: "error",
288
+ title: "Couldn't load data",
289
+ description: error.message ?? "The data source returned an error.",
290
+ action: h(
291
+ Button,
292
+ { icon: "refresh", onClick: () => bumpRefresh((v) => v + 1) },
293
+ "Try again"
294
+ )
295
+ });
296
+ }
287
297
  function useBottomSentinel(onVisible, deps) {
288
298
  const elRef = useRef(null);
289
299
  const observerRef = useRef(null);
@@ -1 +1 @@
1
- {"version":3,"file":"data-panel.js","sources":["../src/data-panel.ts"],"sourcesContent":["/**\n * DataPanel — a card/list renderer over the same headless core as `DataSheet`.\n *\n * The two components differ in only two dimensions: the **view** (cards vs. the\n * Blueprint cell grid) and **edit granularity** (immediate per-item vs. a\n * batched pending-ops stack). Everything else — provider-driven windowed\n * loading, `{sorts, filters}` view state, the selection set, and set-based\n * actions — is the shared substrate, reused here unchanged:\n *\n * - `DataSheetProvider` supplies the jotai+zustand store.\n * - `useDataLoader(provider.fetchData)` drives windowed loading and threads the\n * active store sorts/filters through so a server provider applies them.\n * - `ActionsToolbar` + `FilterBar` render selection-aware actions and the\n * active sort/filter tags — they read the store, not the table.\n *\n * The only list-specific pieces are: rows rendered as cards via a consumer\n * `itemComponent`; selection expressed as `FULL_ROWS` regions (so the existing\n * row-targeted `TableAction`s apply); an infinite-scroll sentinel that advances\n * the loader's visible region; and `FacetControls`, which stands in for the\n * column-header dropdown the list doesn't have (a menu to add a column filter /\n * sort from the column-declared `filterable` / `sortable` capabilities).\n *\n * See [[Data list editors]] in the Macrostrat workbench for the design.\n */\nimport type { ToolbarCollapse } from \"@macrostrat/ui-components\";\nimport h from \"./data-panel.module.sass\";\nimport {\n ComponentType,\n CSSProperties,\n MouseEvent as ReactMouseEvent,\n ReactNode,\n UIEvent as ReactUIEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n AnchorButton,\n Classes,\n Icon,\n NonIdealState,\n Spinner,\n} from \"@blueprintjs/core\";\nimport { startAfterAtom } from \"./provider/loader-state.ts\";\nimport {\n anchorRefAtom,\n ctx,\n dataProviderAtom,\n DataSheetProvider,\n DataViewRendererType,\n FetchData,\n enableSelectionAtom,\n interactionOptionsAtom,\n selectionAtom,\n splitDataProviderProps,\n useSelector,\n} from \"./provider\";\nimport {\n buildDataViewSelection,\n getSelectedRowIndices,\n rowIndicesToRegions,\n TableAction,\n} from \"./actions\";\nimport {\n autoLoadPagesAtom,\n useDataLoader,\n useLoadControls,\n} from \"./postgrest-table\";\nimport classNames from \"classnames\";\nimport {\n ActionsToolbar,\n LoadProgressIndicator,\n useDataPanelControls,\n type ViewControlsPresentation,\n} from \"./components\";\nimport { DataViewSharedProps, FetchDataOptions } from \"./types\";\nimport { atom } from \"jotai\";\nimport { passThroughSet } from \"./utils\";\n\nexport enum DataPanelToolbarStyle {\n BORDERED = \"bordered\",\n FADE = \"fade\",\n MINIMAL = \"minimal\",\n /** Toolbar (and footer) sized to their contents and lifted over the scroll\n * body, rather than occupying a full-width band. Pairs with\n * `viewControls: \"popover\"`, since inline controls cost real space here. */\n FLOATING = \"floating\",\n}\n\n/** Props for a custom scroll-body layout component. It receives the\n * already-rendered, selection-wrapped item cards and lays them out however it\n * likes (a grid, sections, sticky headers, its own windowing). The panel owns\n * the surrounding scroll container and the loading sentinel; the scroll body\n * only arranges the items. */\nexport interface ScrollBodyProps {\n /** The rendered item cards (each wrapped for selection styling). */\n children: ReactNode;\n /** Loading skeletons for the page currently being fetched, if any. Kept\n * separate from `children` because they are transient stand-ins, not items:\n * a layout that assigns a lasting position per item (e.g. the masonry body)\n * must not hand one to a placeholder. Render them after the items; a body\n * that ignores them simply shows no loading state. */\n placeholders?: ReactNode;\n}\n\n/** Props handed to a consumer's card renderer for one row. */\nexport interface ItemComponentProps<T = any> {\n /** The row's data. */\n data: T;\n /** Underlying data-row index (stable within a loaded window). */\n index: number;\n /** Whether this row is in the current selection. */\n selected: boolean;\n /** Whether the row can be selected */\n selectable: boolean;\n /** Select this row. Pass the click's `MouseEvent` (or `React.MouseEvent`) to\n * honor shift / cmd / ctrl automatically — the usual wiring is\n * `onClick: onSelect`. Or pass an explicit `SelectModifiers` object; no\n * argument means a plain (replace) select. */\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) => void;\n}\n\nexport interface DataPanelProps<T = any> extends DataViewSharedProps<T> {\n /** Renders one row as a card. */\n itemComponent: ComponentType<ItemComponentProps<T>>;\n /** Arbitrary nodes for the bottom status row (beside the loaded/total\n * counter). Pass `false` to drop the status row entirely — e.g. when the\n * counter is folded into an inline footer instead. */\n statusBar?: ReactNode | false;\n /** Custom header controls, replacing the default `FacetControls` +\n * `FilterBar`. Rendered inside the provider, so it can drive sort/filter via\n * the exported building blocks (`FacetControls`, `FilterBar`) and the store\n * hooks (`useStoreAPI` / `useSelector`). The selection `ActionsToolbar` still\n * renders above it. Omit for the sane default. */\n toolbar?: ReactNode;\n /** A filter/detail sidebar beside the scroll body (its own scroll). Rendered\n * inside the provider, so a custom filter panel drives sort/filter through\n * the store hooks — the alternative placement to the top `toolbar`. */\n sidebar?: ReactNode;\n /** Footer content. Rendered inside the provider, so it reads live load state\n * from the store via `useLoadControls()` (loadMore / loading / hasMore /\n * loaded / total / paused) rather than a passed-down contract — a footer, a\n * status line, or a \"Load more\" button all just call the hook. */\n contentFooter?: ReactNode;\n /** Auto-load this many pages per burst, then pause: a paused panel stops\n * fetching on scroll until `useLoadControls().loadMore()` starts the next\n * burst (e.g. a footer \"Load more\" button). Omit for unbounded auto-scroll. */\n // TODO: we may deprecate this for opt-in scrolling\n autoLoadPages?: number;\n /** Custom layout for the item cards — the seam for anything other than a\n * vertical list (a CSS grid for several per row, grouped sections, sticky\n * sub-headers, a windowed renderer). Receives the rendered cards as\n * `children`; the panel still owns the scroll container and the loading\n * sentinel, so paging and selection keep working. Defaults to a vertical\n * flex list. */\n scrollBody?: ComponentType<ScrollBodyProps>;\n className?: string;\n toolbarStyle?: DataPanelToolbarStyle | string;\n /** Where the built-in view controls (inline filters, Filter menu, Sort menu)\n * sit in the toolbar: `\"inline\"` (default) places each in the toolbar;\n * `\"popover\"` collapses all of them behind a single button — for a narrow or\n * deliberately chrome-light toolbar. Same controls and state either way.\n * Ignored while a modal view is selecting: the toolbar then carries a single\n * control that leaves select mode. */\n viewControls?: ViewControlsPresentation;\n /** How the toolbar sheds width (the shared `Toolbar`'s `collapse`): with\n * `\"narrow\"`, button labels drop to icons and then contextual controls fold\n * into a \"more\" popover as the panel narrows. Default `\"never\"`. */\n toolbarCollapse?: ToolbarCollapse;\n /** Arbitrary children rendered inside the provider, after the panel. */\n children?: ReactNode;\n}\n\n/**\n * Resolve the data source (shared with `DataSheet` / `DataView` via\n * `useResolvedProvider`), wrap in the shared provider, and render the inner\n * panel.\n */\nexport function DataPanel<T>(props: DataPanelProps<T>) {\n const [providerProps, rendererProps] = splitDataProviderProps({\n ...props,\n viewType: DataViewRendererType.CARDS,\n });\n return h(\n DataSheetProvider<T>,\n providerProps,\n h(DataPanelRenderer<any>, rendererProps),\n );\n}\n\n/** Selection modifier keys, following the familiar list idiom. */\nexport interface SelectModifiers {\n /** cmd/ctrl — toggle this row in/out of the selection (or extend a range). */\n additive?: boolean;\n /** shift — select the range from the anchor (last plain/cmd click) to here. */\n range?: boolean;\n}\n\n/** The card-list renderer. Assumes it is rendered inside a `DataSheetProvider`\n * (the `DataPanel` wrapper, or `DataView`). Exported so a shared-store\n * `DataView` can mount it directly alongside `_DataSheet`. */\nexport function DataPanelRenderer<T>({\n itemComponent,\n actions = [],\n filters = [],\n pageSize = 50,\n filterDebounce,\n initialData,\n name,\n // Bottom bar\n statusBar,\n toolbar,\n sidebar,\n // Footer within content flow\n contentFooter,\n autoLoadPages,\n scrollBody,\n pageLinks,\n className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\n toolbarCollapse = \"never\",\n children,\n}: Omit<DataPanelProps<T>, \"provider\" | \"fetchData\" | \"data\" | \"identity\">) {\n const {\n provider: activeProvider,\n isLocalProvider,\n localCount,\n } = ctx.useValue(dataProviderAtom);\n\n // The loader is mounted as a child component (below), NOT called as a hook\n // here, and only once `activeProvider` resolves. This mirrors `_DataSheet`:\n // `dataProviderAtom` is synced by a parent effect that fires *after* this\n // component's effects, so a hook call here would capture the placeholder\n // provider on first render and — since `fetchData` isn't one of its effect\n // deps — never re-fetch with the real one. A child that mounts with the real\n // `fetchData` already in hand sidesteps that entirely.\n // A local (in-memory) source loads all of its rows in one page; its count\n // rides on the resolved provider, so the renderer no longer takes a `data`\n // prop (the store is the single source of live rows).\n const loaderPageSize = isLocalProvider ? Math.max(localCount, 1) : pageSize;\n\n const data = useSelector((s) => s.data);\n\n // Load state + pause/resume live in the store, read via `useLoadControls`\n // (also available to the caller's `footer` via the same hook). The panel's\n // `autoLoadPages` prop is the store's configuration input.\n ctx.useSync(autoLoadPagesAtom, autoLoadPages ?? null);\n const {\n loading,\n initialized,\n error,\n hasMore,\n loaded,\n total,\n paused,\n canLoadMore,\n advance,\n } = useLoadControls();\n\n // Track whether the body is scrolled off the top, to gate the top fade.\n // `setState` with an unchanged value is a no-op, so this only re-renders on\n // the at-top ↔ scrolled transition.\n const [scrolled, setScrolled] = useState(false);\n const onScroll = useCallback((e: ReactUIEvent<HTMLDivElement>) => {\n setScrolled(e.currentTarget.scrollTop > 4);\n }, []);\n\n const enableSelection = ctx.useValue(enableSelectionAtom);\n const selectedIndices = ctx.useValue(selectedRowIndicesAtom);\n const select = ctx.useSet(updateSelectionAtom);\n\n const loadedCount = useMemo(() => {\n let n = 0;\n for (const r of data) if (r != null) n++;\n return n;\n }, [data]);\n\n // Refresh-token, rowEditing, and load controls (loadMore / pause) are all\n // store-managed (see `useLoadControls`), shared with `_DataSheet` — so both\n // renderers, and any footer, drive loading off one source.\n\n // Infinite scroll. A naive \"load a page when the bottom sentinel is visible\"\n // over-fetches: when a page's rows commit, this component re-renders\n // (loadedCount changed) *before* the IntersectionObserver has re-evaluated\n // the sentinel's new position, so a stale \"still visible\" fires a second\n // load. `useBottomSentinel` re-observes the sentinel whenever the pass-through\n // deps change, so every trigger reflects the *current* post-layout\n // visibility — it loads one page, and only loads another if the sentinel is\n // genuinely still on screen. `advance` (from the store) moves the loader one\n // page without resuming a paused auto-load.\n const sentinelRef = useBottomSentinel(canLoadMore ? advance : null, [\n loadedCount,\n canLoadMore,\n ]);\n\n const cards: ReactNode[] = data\n .filter((d) => d != null)\n .map((row: ReactNode, i) => {\n const selected = enableSelection && selectedIndices.has(i);\n return h(\n \"div.data-panel-item-container\",\n { key: `item-${i}`, className: classNames({ selected }) },\n h(itemComponent, {\n data: row,\n index: i,\n selected,\n selectable: enableSelection,\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) =>\n select(i, modifiersOf(arg)),\n }),\n );\n });\n\n // Body-level empty/error state: when nothing has loaded, show a clear message\n // instead of a blank list — an errored source (e.g. a 401 on the whole route)\n // degrades gracefully, and a genuinely empty result reads as \"no results\"\n // rather than a perpetual spinner.\n // A load is pending whenever a fetch is in flight OR the view was just reset\n // and hasn't fetched yet (`!initialized`) — the window that would otherwise\n // flash \"No results\" before the request starts.\n const loadPending = (loading || !initialized) && error == null;\n\n let emptyState: ReactNode = null;\n if (cards.length === 0) {\n if (error != null) {\n emptyState = h(NonIdealState, {\n icon: \"error\",\n title: \"Couldn't load data\",\n description: error.message ?? \"The data source returned an error.\",\n });\n } else if (initialized && !loading) {\n // Only after a fetch settled with no rows — not during the reset gap.\n emptyState = h(NonIdealState, {\n icon: \"search\",\n title: \"No results\",\n });\n }\n }\n\n // Skeleton placeholders for the page being fetched — on a view change (the\n // reset pre-sizes to a page of `null` slots) or the next scroll page — so the\n // body shows shimmer where rows will land instead of a blank flash or a\n // footer pinging up into the gap. Bounded to a viewport's worth of cards.\n const placeholderCards: ReactNode[] = [];\n if (loadPending) {\n const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);\n for (let i = 0; i < pending; i++) {\n placeholderCards.push(\n h(\n \"div.data-panel-item-container.is-skeleton\",\n { key: `skeleton-${i}`, \"aria-hidden\": true },\n h(\"div.data-panel-skeleton\", { className: Classes.SKELETON }),\n ),\n );\n }\n }\n let placeholders: ReactNode = null;\n if (placeholderCards.length > 0) {\n placeholders = placeholderCards;\n }\n\n // The default spinner sentinel (below-placement): hidden while paused so the\n // pinned footer's \"Load more\" takes over.\n const shouldLoadNextPage = (hasMore || loading) && !paused && error == null;\n\n // Mount the loader only once the provider resolves (see `PanelLoader`). Built\n // as a real conditional — `h.if(...)` evaluates its arguments eagerly, so\n // `activeProvider.fetchData` can't be referenced inside it while null.\n let loaderNode: ReactNode = null;\n if (activeProvider != null) {\n loaderNode = h(PanelLoader, {\n fetchData: activeProvider.fetchData,\n pageSize: loaderPageSize,\n fetchMode: isLocalProvider ? undefined : \"scroll\",\n filterDebounce,\n initialData,\n });\n }\n\n const coreActions = useDataPanelControls(filters, viewControls);\n\n // Merge consumer actions with the synthesized Filter/Sort controls, deduped\n // by id — consumer actions come first, so passing an action with id `filter`\n // or `sort` *replaces* the built-in one (a hybrid set keeps the others).\n // Mirrors the sheet's action registry contract (see `data-sheet.ts`).\n const _actions = useMemo(() => {\n const merged: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!merged.some((x) => x.id === a.id)) merged.push(a);\n }\n };\n add(actions);\n add(coreActions);\n return merged;\n }, [actions, coreActions]);\n\n const ScrollBody = scrollBody ?? DefaultScrollBody;\n\n // The panel owns the scroll container + the loading sentinel; the (custom or\n // default) scroll body only lays out the cards. So a grid / grouped / windowed\n // body composes without reimplementing paging or selection. The end-of-scroll\n // region is either the default spinner sentinel or the caller's inline\n // footer — both carry the sentinel ref that drives auto-load.\n // The top fade is gated on being scrolled (via `.is-scrolled`), so the first\n // item isn't clipped at rest.\n\n const showStatusBar = statusBar !== false;\n\n let defaultFooter: ReactNode = null;\n if (shouldLoadNextPage) {\n defaultFooter = h(\"div.sentinel\", [h(Spinner, { size: 16 }), \"Loading...\"]);\n } else if (!showStatusBar) {\n defaultFooter = h(\"div.sentinel\", [\n h(Icon, { size: 16, icon: \"tick\" }),\n \"Loaded\",\n ]);\n }\n\n const _contentFooter = h(\n \"div.content-footer-holder\",\n { ref: sentinelRef },\n contentFooter ?? defaultFooter,\n );\n\n // Crawlable paging (see `PageLinks`). Both are plain links, so they work in\n // the server-rendered HTML with no script: the next-page link is visually\n // hidden after the loaded rows and points past the last loaded row; the\n // \"Return to top\" notice heads the content while the view starts mid-list.\n const startAfter = ctx.useValue(startAfterAtom);\n const lastLoadedRow = useMemo(() => {\n for (let i = data.length - 1; i >= 0; i--) {\n if (data[i] != null) return data[i];\n }\n return null;\n }, [data]);\n // Gated on the counts rather than `hasMore`, which reads the resolved\n // provider — synced after mount, so absent in a server render.\n const moreToCome = total == null || loadedCount < total;\n let nextPageLink: ReactNode = null;\n if (pageLinks != null && lastLoadedRow != null && moreToCome) {\n nextPageLink = h(\n \"a.crawl-next-link\",\n {\n href: pageLinks.after(lastLoadedRow),\n rel: \"next\",\n tabIndex: -1,\n \"aria-hidden\": true,\n },\n \"Next page\",\n );\n }\n let viewStartNotice: ReactNode = null;\n if (startAfter != null && pageLinks?.top != null) {\n viewStartNotice = h(\"div.view-start-notice\", [\n h(\"span.view-start-text\", `Continued after #${startAfter}`),\n h(\n AnchorButton,\n { href: pageLinks.top, minimal: true, small: true, icon: \"arrow-up\" },\n pageLinks.topLabel ?? \"Return to top\",\n ),\n ]);\n }\n\n // Body + optional filter/detail sidebar share a horizontal row so each\n // scrolls independently.\n\n // Bottom status row (counter + extras). `statusBar === false` drops it — e.g.\n // when an inline footer carries the counter itself.\n let footer: ReactNode = null;\n let _statusBarContent = statusBar ?? h(DataPanelStatusBar);\n if (showStatusBar) {\n footer = h(\n \"div.data-panel-footer\",\n h(\"div.data-panel-footer-content\", [_statusBarContent]),\n );\n }\n\n const _toolbar = h(\n \"div.data-panel-top-area\",\n h(\n \"div.data-panel-toolbar\",\n h(\n ActionsToolbar,\n {\n actions: _actions,\n tableName: name,\n className: \"data-panel-toolbar-content\",\n // In the panel the title doubles as the modal-selection control,\n // so only render it when modal selection is toggle-able (or a\n // selection is active) — not as a bare label otherwise.\n compact: true,\n collapse: toolbarCollapse,\n },\n toolbar,\n ),\n ),\n );\n\n return h(\n \"div.data-panel\",\n { className: classNames(className, \"toolbar-style-\" + toolbarStyle) },\n [\n h(\"div.data-panel-main\", [\n loaderNode,\n _toolbar,\n h(\n \"div.data-panel-body\",\n {\n onScroll,\n className: classNames({ \"is-scrolled\": scrolled }),\n },\n [\n h(\"div.data-panel-body-content\", [\n viewStartNotice,\n emptyState ?? h(ScrollBody, { placeholders }, cards),\n nextPageLink,\n _contentFooter,\n ]),\n ],\n ),\n footer,\n ]),\n h.if(sidebar != null)(\"div.data-panel-sidebar-container\", sidebar),\n children,\n ],\n );\n}\n\nfunction DataPanelStatusBar({ children }) {\n /** Default status bar for the Data Panel */\n return h(\"div.data-panel-status-bar\", [children, h(LoadProgressIndicator)]);\n}\n\n/** Default scroll-body layout: a vertical flex list of cards, with any loading\n * placeholders appended in the same flow. */\nfunction DefaultScrollBody({ children, placeholders }: ScrollBodyProps) {\n return h(\"div.data-panel-list\", [children, placeholders]);\n}\n\n/** Runs the shared windowed loader from inside the panel (renders nothing).\n * Mounted only once the real provider is resolved, so `useDataLoader` captures\n * the real `fetchData` from the start (see `_DataPanel`). */\nfunction PanelLoader<T = any>({\n fetchData,\n ...options\n}: { fetchData: FetchData<T> } & FetchDataOptions<T>) {\n useDataLoader(fetchData, options);\n return null;\n}\n\n/** Resolve the selection modifiers from either a click event (reads shift /\n * cmd / ctrl) or an explicit modifier object; no argument ⇒ a plain select. */\nfunction modifiersOf(arg?: SelectModifiers | ReactMouseEvent): SelectModifiers {\n if (arg == null) return {};\n if (\"shiftKey\" in arg) {\n return { additive: arg.metaKey || arg.ctrlKey, range: arg.shiftKey };\n }\n return arg;\n}\n\n/**\n * Bottom-sentinel infinite-scroll hook (no `react-intersection-observer`\n * dependency). Calls `onVisible` when the observed element is on screen, and —\n * crucially — **re-observes on every `deps` change** so the callback reflects\n * the *current* post-layout visibility rather than the pre-load render.\n *\n * This is what avoids the double-load: a plain observer whose visibility is\n * mirrored into React state lags a render behind the DOM, so a load-driven\n * re-render fires a second `onVisible` before the observer catches up. By\n * re-arming after each load (`deps = [loadedCount, canLoadMore]`), the observer\n * emits a fresh callback for the settled layout: it fires again only if the\n * sentinel is *still* visible (viewport not yet filled), so it loads exactly\n * one page per bottom-reach and self-fills an underfull viewport without\n * overshooting. Pass `onVisible = null` to disarm (loading / no more data).\n */\nfunction useBottomSentinel<E extends HTMLElement>(\n onVisible: (() => void) | null,\n deps: unknown[],\n): (el: E | null) => void {\n const elRef = useRef<E | null>(null);\n const observerRef = useRef<IntersectionObserver | null>(null);\n const cbRef = useRef(onVisible);\n cbRef.current = onVisible;\n\n const setRef = useCallback((el: E | null) => {\n elRef.current = el;\n observerRef.current?.disconnect();\n observerRef.current = null;\n if (el == null) return;\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) cbRef.current?.();\n },\n { rootMargin: \"300px\" },\n );\n observer.observe(el);\n observerRef.current = observer;\n }, []);\n\n // Re-arm after each load so the observer re-checks the settled layout.\n useEffect(() => {\n const el = elRef.current;\n const observer = observerRef.current;\n if (el == null || observer == null) return;\n observer.disconnect();\n observer.observe(el);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n useEffect(() => () => observerRef.current?.disconnect(), []);\n return setRef;\n}\n\nconst rowSelectionAtom = atom((get) => {\n /** Coerce selection to full rows, for use with data panel instead of data sheet. */\n const selection = get(selectionAtom);\n if (selection.some((r) => r.cols != null)) {\n // A card list has no cells or columns. When the selection carries columns —\n // inherited from a shared store the sheet also drives (a `DataView` toggle) —\n // coerce it to the full rows it covers, so the toolbar shows row-scoped\n // actions rather than column/cell ones for a column that isn't visible here.\n // Column-only selections (no rows) collapse to nothing.\n return rowIndicesToRegions(new Set(getSelectedRowIndices(selection)));\n } else {\n return selection;\n }\n}, passThroughSet(selectionAtom));\n\nconst updateSelectionAtom = atom(\n null,\n (get, set, index: number, mods: SelectModifiers) => {\n /** Update selection from a row index and modifiers. */\n const { enableMultipleSelection, enableModalSelection } = get(\n interactionOptionsAtom,\n );\n let enableSelection = get(enableSelectionAtom);\n if (!enableSelection) {\n // Cmd/ctrl-click *enters* select mode on a modal view and selects the\n // row, the familiar list idiom — so a bulk action doesn't require finding\n // the Select control first. The flag is read back below rather than\n // trusted from this scope: the write goes through the store synchronously.\n if (!enableModalSelection || !mods.additive) return;\n set(enableSelectionAtom, true);\n enableSelection = get(enableSelectionAtom);\n if (!enableSelection) return;\n }\n const selection = get(rowSelectionAtom);\n const anchorRef = get(anchorRefAtom);\n const res = buildDataViewSelection(\n index,\n mods,\n selection,\n anchorRef,\n enableMultipleSelection,\n );\n set(selectionAtom, res);\n },\n);\n\nconst selectedRowIndicesAtom = atom((get) => {\n const sel = get(selectionAtom);\n return new Set(getSelectedRowIndices(sel));\n});\n\ntype ItemSelectionKeys = \"onSelect\" | \"selected\" | \"selectable\";\n\ntype DataCardProps = {\n children: ReactNode;\n className: string;\n style?: CSSProperties;\n} & Pick<ItemComponentProps, ItemSelectionKeys>;\n\nexport function DataCard<T = any>(props: DataCardProps) {\n /** A basic card that implements the data panel's selection behavior. */\n return h(\n \"div.data-card.data-panel-item\",\n {\n className: classNames(props.className, {\n selected: props.selected,\n selectable: props.selectable,\n }),\n onClick: props.onSelect,\n style: props.style,\n },\n props.children,\n );\n}\n\ntype DataCardInnerComponent<T> = (\n props: ItemComponentProps<T>,\n) => React.ReactNode;\n\nexport function createDataCard<T>(\n component: DataCardInnerComponent<T>,\n extraProps = {},\n) {\n return (props: ItemComponentProps<T>) => {\n const { selected, selectable, onSelect } = props;\n return h(\n DataCard,\n {\n selected,\n selectable,\n onSelect,\n ...extraProps,\n },\n h(component, props),\n );\n };\n}\n"],"names":["DataPanelToolbarStyle"],"mappings":";;;;;;;;;;;;;;;AAiFO,IAAK,0CAAAA,2BAAL;AACLA,yBAAA,UAAA,IAAW;AACXA,yBAAA,MAAA,IAAO;AACPA,yBAAA,SAAA,IAAU;AAIVA,yBAAA,UAAA,IAAW;AAPD,SAAAA;AAAA,GAAA,yBAAA,CAAA,CAAA;AAmGL,SAAS,UAAa,OAA0B;AACrD,QAAM,CAAC,eAAe,aAAa,IAAI,uBAAuB;AAAA,IAC5D,GAAG;AAAA,IACH,UAAU,qBAAqB;AAAA,EAAA,CAChC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,EAAE,mBAAwB,aAAa;AAAA,EAAA;AAE3C;AAaO,SAAS,kBAAqB;AAAA,EACnC;AAAA,EACA,UAAU,CAAA;AAAA,EACV,UAAU,CAAA;AAAA,EACV,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB;AACF,GAA4E;AAC1E,QAAM;AAAA,IACJ,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EAAA,IACE,IAAI,SAAS,gBAAgB;AAYjC,QAAM,iBAAiB,k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AA;AAAA,MAEL,EAAE,WAAW,KAAK;AAAA,IAAA;AAAA,EAEtB;AACF;"}
1
+ {"version":3,"file":"data-panel.js","sources":["../src/data-panel.ts"],"sourcesContent":["/**\n * DataPanel — a card/list renderer over the same headless core as `DataSheet`.\n *\n * The two components differ in only two dimensions: the **view** (cards vs. the\n * Blueprint cell grid) and **edit granularity** (immediate per-item vs. a\n * batched pending-ops stack). Everything else — provider-driven windowed\n * loading, `{sorts, filters}` view state, the selection set, and set-based\n * actions — is the shared substrate, reused here unchanged:\n *\n * - `DataSheetProvider` supplies the jotai+zustand store.\n * - `useDataLoader(provider.fetchData)` drives windowed loading and threads the\n * active store sorts/filters through so a server provider applies them.\n * - `ActionsToolbar` + `FilterBar` render selection-aware actions and the\n * active sort/filter tags — they read the store, not the table.\n *\n * The only list-specific pieces are: rows rendered as cards via a consumer\n * `itemComponent`; selection expressed as `FULL_ROWS` regions (so the existing\n * row-targeted `TableAction`s apply); an infinite-scroll sentinel that advances\n * the loader's visible region; and `FacetControls`, which stands in for the\n * column-header dropdown the list doesn't have (a menu to add a column filter /\n * sort from the column-declared `filterable` / `sortable` capabilities).\n *\n * See [[Data list editors]] in the Macrostrat workbench for the design.\n */\nimport type { ToolbarCollapse } from \"@macrostrat/ui-components\";\nimport h from \"./data-panel.module.sass\";\nimport {\n ComponentType,\n CSSProperties,\n MouseEvent as ReactMouseEvent,\n ReactNode,\n UIEvent as ReactUIEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n AnchorButton,\n Button,\n Classes,\n Icon,\n NonIdealState,\n Spinner,\n} from \"@blueprintjs/core\";\nimport { startAfterAtom } from \"./provider/loader-state.ts\";\nimport {\n anchorRefAtom,\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n DataSheetProvider,\n DataViewRendererType,\n FetchData,\n enableSelectionAtom,\n interactionOptionsAtom,\n selectionAtom,\n splitDataProviderProps,\n useSelector,\n} from \"./provider\";\nimport {\n buildDataViewSelection,\n getSelectedRowIndices,\n rowIndicesToRegions,\n TableAction,\n} from \"./actions\";\nimport {\n autoLoadPagesAtom,\n useDataLoader,\n useLoadControls,\n} from \"./postgrest-table\";\nimport classNames from \"classnames\";\nimport {\n ActionsToolbar,\n LoadProgressIndicator,\n useDataPanelControls,\n type ViewControlsPresentation,\n} from \"./components\";\nimport { DataViewSharedProps, FetchDataOptions } from \"./types\";\nimport { atom } from \"jotai\";\nimport { passThroughSet } from \"./utils\";\n\nexport enum DataPanelToolbarStyle {\n BORDERED = \"bordered\",\n FADE = \"fade\",\n MINIMAL = \"minimal\",\n /** Toolbar (and footer) sized to their contents and lifted over the scroll\n * body, rather than occupying a full-width band. Pairs with\n * `viewControls: \"popover\"`, since inline controls cost real space here. */\n FLOATING = \"floating\",\n}\n\n/** Props for a custom scroll-body layout component. It receives the\n * already-rendered, selection-wrapped item cards and lays them out however it\n * likes (a grid, sections, sticky headers, its own windowing). The panel owns\n * the surrounding scroll container and the loading sentinel; the scroll body\n * only arranges the items. */\nexport interface ScrollBodyProps {\n /** The rendered item cards (each wrapped for selection styling). */\n children: ReactNode;\n /** Loading skeletons for the page currently being fetched, if any. Kept\n * separate from `children` because they are transient stand-ins, not items:\n * a layout that assigns a lasting position per item (e.g. the masonry body)\n * must not hand one to a placeholder. Render them after the items; a body\n * that ignores them simply shows no loading state. */\n placeholders?: ReactNode;\n}\n\n/** Props handed to a consumer's card renderer for one row. */\nexport interface ItemComponentProps<T = any> {\n /** The row's data. */\n data: T;\n /** Underlying data-row index (stable within a loaded window). */\n index: number;\n /** Whether this row is in the current selection. */\n selected: boolean;\n /** Whether the row can be selected */\n selectable: boolean;\n /** Select this row. Pass the click's `MouseEvent` (or `React.MouseEvent`) to\n * honor shift / cmd / ctrl automatically — the usual wiring is\n * `onClick: onSelect`. Or pass an explicit `SelectModifiers` object; no\n * argument means a plain (replace) select. */\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) => void;\n}\n\nexport interface DataPanelProps<T = any> extends DataViewSharedProps<T> {\n /** Renders one row as a card. */\n itemComponent: ComponentType<ItemComponentProps<T>>;\n /** Arbitrary nodes for the bottom status row (beside the loaded/total\n * counter). Pass `false` to drop the status row entirely — e.g. when the\n * counter is folded into an inline footer instead. */\n statusBar?: ReactNode | false;\n /** Custom header controls, replacing the default `FacetControls` +\n * `FilterBar`. Rendered inside the provider, so it can drive sort/filter via\n * the exported building blocks (`FacetControls`, `FilterBar`) and the store\n * hooks (`useStoreAPI` / `useSelector`). The selection `ActionsToolbar` still\n * renders above it. Omit for the sane default. */\n toolbar?: ReactNode;\n /** A filter/detail sidebar beside the scroll body (its own scroll). Rendered\n * inside the provider, so a custom filter panel drives sort/filter through\n * the store hooks — the alternative placement to the top `toolbar`. */\n sidebar?: ReactNode;\n /** Footer content. Rendered inside the provider, so it reads live load state\n * from the store via `useLoadControls()` (loadMore / loading / hasMore /\n * loaded / total / paused) rather than a passed-down contract — a footer, a\n * status line, or a \"Load more\" button all just call the hook. */\n contentFooter?: ReactNode;\n /** Auto-load this many pages per burst, then pause: a paused panel stops\n * fetching on scroll until `useLoadControls().loadMore()` starts the next\n * burst (e.g. a footer \"Load more\" button). Omit for unbounded auto-scroll. */\n // TODO: we may deprecate this for opt-in scrolling\n autoLoadPages?: number;\n /** Custom layout for the item cards — the seam for anything other than a\n * vertical list (a CSS grid for several per row, grouped sections, sticky\n * sub-headers, a windowed renderer). Receives the rendered cards as\n * `children`; the panel still owns the scroll container and the loading\n * sentinel, so paging and selection keep working. Defaults to a vertical\n * flex list. */\n scrollBody?: ComponentType<ScrollBodyProps>;\n className?: string;\n toolbarStyle?: DataPanelToolbarStyle | string;\n /** Where the built-in view controls (inline filters, Filter menu, Sort menu)\n * sit in the toolbar: `\"inline\"` (default) places each in the toolbar;\n * `\"popover\"` collapses all of them behind a single button — for a narrow or\n * deliberately chrome-light toolbar. Same controls and state either way.\n * Ignored while a modal view is selecting: the toolbar then carries a single\n * control that leaves select mode. */\n viewControls?: ViewControlsPresentation;\n /** How the toolbar sheds width (the shared `Toolbar`'s `collapse`): with\n * `\"narrow\"`, button labels drop to icons and then contextual controls fold\n * into a \"more\" popover as the panel narrows. Default `\"never\"`. */\n toolbarCollapse?: ToolbarCollapse;\n /** Arbitrary children rendered inside the provider, after the panel. */\n children?: ReactNode;\n}\n\n/**\n * Resolve the data source (shared with `DataSheet` / `DataView` via\n * `useResolvedProvider`), wrap in the shared provider, and render the inner\n * panel.\n */\nexport function DataPanel<T>(props: DataPanelProps<T>) {\n const [providerProps, rendererProps] = splitDataProviderProps({\n ...props,\n viewType: DataViewRendererType.CARDS,\n });\n return h(\n DataSheetProvider<T>,\n providerProps,\n h(DataPanelRenderer<any>, rendererProps),\n );\n}\n\n/** Selection modifier keys, following the familiar list idiom. */\nexport interface SelectModifiers {\n /** cmd/ctrl — toggle this row in/out of the selection (or extend a range). */\n additive?: boolean;\n /** shift — select the range from the anchor (last plain/cmd click) to here. */\n range?: boolean;\n}\n\n/** The card-list renderer. Assumes it is rendered inside a `DataSheetProvider`\n * (the `DataPanel` wrapper, or `DataView`). Exported so a shared-store\n * `DataView` can mount it directly alongside `_DataSheet`. */\nexport function DataPanelRenderer<T>({\n itemComponent,\n actions = [],\n filters = [],\n pageSize = 50,\n filterDebounce,\n initialData,\n name,\n // Bottom bar\n statusBar,\n toolbar,\n sidebar,\n // Footer within content flow\n contentFooter,\n autoLoadPages,\n scrollBody,\n pageLinks,\n className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\n toolbarCollapse = \"never\",\n children,\n}: Omit<DataPanelProps<T>, \"provider\" | \"fetchData\" | \"data\" | \"identity\">) {\n const {\n provider: activeProvider,\n isLocalProvider,\n localCount,\n } = ctx.useValue(dataProviderAtom);\n\n // The loader is mounted as a child component (below), NOT called as a hook\n // here, and only once `activeProvider` resolves. This mirrors `_DataSheet`:\n // `dataProviderAtom` is synced by a parent effect that fires *after* this\n // component's effects, so a hook call here would capture the placeholder\n // provider on first render and — since `fetchData` isn't one of its effect\n // deps — never re-fetch with the real one. A child that mounts with the real\n // `fetchData` already in hand sidesteps that entirely.\n // A local (in-memory) source loads all of its rows in one page; its count\n // rides on the resolved provider, so the renderer no longer takes a `data`\n // prop (the store is the single source of live rows).\n const loaderPageSize = isLocalProvider ? Math.max(localCount, 1) : pageSize;\n\n const data = useSelector((s) => s.data);\n\n // Load state + pause/resume live in the store, read via `useLoadControls`\n // (also available to the caller's `footer` via the same hook). The panel's\n // `autoLoadPages` prop is the store's configuration input.\n ctx.useSync(autoLoadPagesAtom, autoLoadPages ?? null);\n const {\n loading,\n initialized,\n error,\n hasMore,\n loaded,\n total,\n paused,\n canLoadMore,\n advance,\n } = useLoadControls();\n\n // Track whether the body is scrolled off the top, to gate the top fade.\n // `setState` with an unchanged value is a no-op, so this only re-renders on\n // the at-top ↔ scrolled transition.\n const [scrolled, setScrolled] = useState(false);\n const onScroll = useCallback((e: ReactUIEvent<HTMLDivElement>) => {\n setScrolled(e.currentTarget.scrollTop > 4);\n }, []);\n\n const enableSelection = ctx.useValue(enableSelectionAtom);\n const selectedIndices = ctx.useValue(selectedRowIndicesAtom);\n const select = ctx.useSet(updateSelectionAtom);\n\n const loadedCount = useMemo(() => {\n let n = 0;\n for (const r of data) if (r != null) n++;\n return n;\n }, [data]);\n\n // Refresh-token, rowEditing, and load controls (loadMore / pause) are all\n // store-managed (see `useLoadControls`), shared with `_DataSheet` — so both\n // renderers, and any footer, drive loading off one source.\n\n // Infinite scroll. A naive \"load a page when the bottom sentinel is visible\"\n // over-fetches: when a page's rows commit, this component re-renders\n // (loadedCount changed) *before* the IntersectionObserver has re-evaluated\n // the sentinel's new position, so a stale \"still visible\" fires a second\n // load. `useBottomSentinel` re-observes the sentinel whenever the pass-through\n // deps change, so every trigger reflects the *current* post-layout\n // visibility — it loads one page, and only loads another if the sentinel is\n // genuinely still on screen. `advance` (from the store) moves the loader one\n // page without resuming a paused auto-load.\n const sentinelRef = useBottomSentinel(canLoadMore ? advance : null, [\n loadedCount,\n canLoadMore,\n ]);\n\n const cards: ReactNode[] = data\n .filter((d) => d != null)\n .map((row: ReactNode, i) => {\n const selected = enableSelection && selectedIndices.has(i);\n return h(\n \"div.data-panel-item-container\",\n { key: `item-${i}`, className: classNames({ selected }) },\n h(itemComponent, {\n data: row,\n index: i,\n selected,\n selectable: enableSelection,\n onSelect: (arg?: SelectModifiers | ReactMouseEvent) =>\n select(i, modifiersOf(arg)),\n }),\n );\n });\n\n // Body-level empty/error state: when nothing has loaded, show a clear message\n // instead of a blank list — an errored source (e.g. a 401 on the whole route)\n // degrades gracefully, and a genuinely empty result reads as \"no results\"\n // rather than a perpetual spinner.\n // A load is pending whenever a fetch is in flight OR the view was just reset\n // and hasn't fetched yet (`!initialized`) — the window that would otherwise\n // flash \"No results\" before the request starts.\n const loadPending = (loading || !initialized) && error == null;\n\n let emptyState: ReactNode = null;\n if (cards.length === 0) {\n if (error != null) {\n emptyState = h(LoadErrorState, { error });\n } else if (initialized && !loading) {\n // Only after a fetch settled with no rows — not during the reset gap.\n emptyState = h(NonIdealState, {\n icon: \"search\",\n title: \"No results\",\n });\n }\n }\n\n // Skeleton placeholders for the page being fetched — on a view change (the\n // reset pre-sizes to a page of `null` slots) or the next scroll page — so the\n // body shows shimmer where rows will land instead of a blank flash or a\n // footer pinging up into the gap. Bounded to a viewport's worth of cards.\n const placeholderCards: ReactNode[] = [];\n if (loadPending) {\n const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);\n for (let i = 0; i < pending; i++) {\n placeholderCards.push(\n h(\n \"div.data-panel-item-container.is-skeleton\",\n { key: `skeleton-${i}`, \"aria-hidden\": true },\n h(\"div.data-panel-skeleton\", { className: Classes.SKELETON }),\n ),\n );\n }\n }\n let placeholders: ReactNode = null;\n if (placeholderCards.length > 0) {\n placeholders = placeholderCards;\n }\n\n // The default spinner sentinel (below-placement): hidden while paused so the\n // pinned footer's \"Load more\" takes over.\n const shouldLoadNextPage = (hasMore || loading) && !paused && error == null;\n\n // Mount the loader only once the provider resolves (see `PanelLoader`). Built\n // as a real conditional — `h.if(...)` evaluates its arguments eagerly, so\n // `activeProvider.fetchData` can't be referenced inside it while null.\n let loaderNode: ReactNode = null;\n if (activeProvider != null) {\n loaderNode = h(PanelLoader, {\n fetchData: activeProvider.fetchData,\n pageSize: loaderPageSize,\n fetchMode: isLocalProvider ? undefined : \"scroll\",\n filterDebounce,\n initialData,\n });\n }\n\n const coreActions = useDataPanelControls(filters, viewControls);\n\n // Merge consumer actions with the synthesized Filter/Sort controls, deduped\n // by id — consumer actions come first, so passing an action with id `filter`\n // or `sort` *replaces* the built-in one (a hybrid set keeps the others).\n // Mirrors the sheet's action registry contract (see `data-sheet.ts`).\n const _actions = useMemo(() => {\n const merged: TableAction[] = [];\n const add = (list: TableAction[]) => {\n for (const a of list) {\n if (!merged.some((x) => x.id === a.id)) merged.push(a);\n }\n };\n add(actions);\n add(coreActions);\n return merged;\n }, [actions, coreActions]);\n\n const ScrollBody = scrollBody ?? DefaultScrollBody;\n\n // The panel owns the scroll container + the loading sentinel; the (custom or\n // default) scroll body only lays out the cards. So a grid / grouped / windowed\n // body composes without reimplementing paging or selection. The end-of-scroll\n // region is either the default spinner sentinel or the caller's inline\n // footer — both carry the sentinel ref that drives auto-load.\n // The top fade is gated on being scrolled (via `.is-scrolled`), so the first\n // item isn't clipped at rest.\n\n const showStatusBar = statusBar !== false;\n\n let defaultFooter: ReactNode = null;\n if (shouldLoadNextPage) {\n defaultFooter = h(\"div.sentinel\", [h(Spinner, { size: 16 }), \"Loading...\"]);\n } else if (!showStatusBar) {\n defaultFooter = h(\"div.sentinel\", [\n h(Icon, { size: 16, icon: \"tick\" }),\n \"Loaded\",\n ]);\n }\n\n const _contentFooter = h(\n \"div.content-footer-holder\",\n { ref: sentinelRef },\n contentFooter ?? defaultFooter,\n );\n\n // Crawlable paging (see `PageLinks`). Both are plain links, so they work in\n // the server-rendered HTML with no script: the next-page link is visually\n // hidden after the loaded rows and points past the last loaded row; the\n // \"Return to top\" notice heads the content while the view starts mid-list.\n const startAfter = ctx.useValue(startAfterAtom);\n const lastLoadedRow = useMemo(() => {\n for (let i = data.length - 1; i >= 0; i--) {\n if (data[i] != null) return data[i];\n }\n return null;\n }, [data]);\n // Gated on the counts rather than `hasMore`, which reads the resolved\n // provider — synced after mount, so absent in a server render.\n const moreToCome = total == null || loadedCount < total;\n let nextPageLink: ReactNode = null;\n if (pageLinks != null && lastLoadedRow != null && moreToCome) {\n nextPageLink = h(\n \"a.crawl-next-link\",\n {\n href: pageLinks.after(lastLoadedRow),\n rel: \"next\",\n tabIndex: -1,\n \"aria-hidden\": true,\n },\n \"Next page\",\n );\n }\n let viewStartNotice: ReactNode = null;\n if (startAfter != null && pageLinks?.top != null) {\n viewStartNotice = h(\"div.view-start-notice\", [\n h(\"span.view-start-text\", `Continued after #${startAfter}`),\n h(\n AnchorButton,\n { href: pageLinks.top, minimal: true, small: true, icon: \"arrow-up\" },\n pageLinks.topLabel ?? \"Return to top\",\n ),\n ]);\n }\n\n // Body + optional filter/detail sidebar share a horizontal row so each\n // scrolls independently.\n\n // Bottom status row (counter + extras). `statusBar === false` drops it — e.g.\n // when an inline footer carries the counter itself.\n let footer: ReactNode = null;\n let _statusBarContent = statusBar ?? h(DataPanelStatusBar);\n if (showStatusBar) {\n footer = h(\n \"div.data-panel-footer\",\n h(\"div.data-panel-footer-content\", [_statusBarContent]),\n );\n }\n\n const _toolbar = h(\n \"div.data-panel-top-area\",\n h(\n \"div.data-panel-toolbar\",\n h(\n ActionsToolbar,\n {\n actions: _actions,\n tableName: name,\n className: \"data-panel-toolbar-content\",\n // In the panel the title doubles as the modal-selection control,\n // so only render it when modal selection is toggle-able (or a\n // selection is active) — not as a bare label otherwise.\n compact: true,\n collapse: toolbarCollapse,\n },\n toolbar,\n ),\n ),\n );\n\n return h(\n \"div.data-panel\",\n { className: classNames(className, \"toolbar-style-\" + toolbarStyle) },\n [\n h(\"div.data-panel-main\", [\n loaderNode,\n _toolbar,\n h(\n \"div.data-panel-body\",\n {\n onScroll,\n className: classNames({ \"is-scrolled\": scrolled }),\n },\n [\n h(\"div.data-panel-body-content\", [\n viewStartNotice,\n emptyState ?? h(ScrollBody, { placeholders }, cards),\n nextPageLink,\n _contentFooter,\n ]),\n ],\n ),\n footer,\n ]),\n h.if(sidebar != null)(\"div.data-panel-sidebar-container\", sidebar),\n children,\n ],\n );\n}\n\nfunction DataPanelStatusBar({ children }) {\n /** Default status bar for the Data Panel */\n return h(\"div.data-panel-status-bar\", [children, h(LoadProgressIndicator)]);\n}\n\n/** Default scroll-body layout: a vertical flex list of cards, with any loading\n * placeholders appended in the same flow. */\nfunction DefaultScrollBody({ children, placeholders }: ScrollBodyProps) {\n return h(\"div.data-panel-list\", [children, placeholders]);\n}\n\n/** Runs the shared windowed loader from inside the panel (renders nothing).\n * Mounted only once the real provider is resolved, so `useDataLoader` captures\n * the real `fetchData` from the start (see `_DataPanel`). */\nfunction PanelLoader<T = any>({\n fetchData,\n ...options\n}: { fetchData: FetchData<T> } & FetchDataOptions<T>) {\n useDataLoader(fetchData, options);\n return null;\n}\n\n/** Resolve the selection modifiers from either a click event (reads shift /\n * cmd / ctrl) or an explicit modifier object; no argument ⇒ a plain select. */\nfunction modifiersOf(arg?: SelectModifiers | ReactMouseEvent): SelectModifiers {\n if (arg == null) return {};\n if (\"shiftKey\" in arg) {\n return { additive: arg.metaKey || arg.ctrlKey, range: arg.shiftKey };\n }\n return arg;\n}\n\n/** A failed load, with a retry: auto-load stays off after an error, so\n * reloading is the user's call. */\nfunction LoadErrorState({ error }: { error: Error }) {\n const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);\n return h(NonIdealState, {\n icon: \"error\",\n title: \"Couldn't load data\",\n description: error.message ?? \"The data source returned an error.\",\n action: h(\n Button,\n { icon: \"refresh\", onClick: () => bumpRefresh((v) => v + 1) },\n \"Try again\",\n ),\n });\n}\n\n/**\n * Bottom-sentinel infinite-scroll hook (no `react-intersection-observer`\n * dependency). Calls `onVisible` when the observed element is on screen, and —\n * crucially — **re-observes on every `deps` change** so the callback reflects\n * the *current* post-layout visibility rather than the pre-load render.\n *\n * This is what avoids the double-load: a plain observer whose visibility is\n * mirrored into React state lags a render behind the DOM, so a load-driven\n * re-render fires a second `onVisible` before the observer catches up. By\n * re-arming after each load (`deps = [loadedCount, canLoadMore]`), the observer\n * emits a fresh callback for the settled layout: it fires again only if the\n * sentinel is *still* visible (viewport not yet filled), so it loads exactly\n * one page per bottom-reach and self-fills an underfull viewport without\n * overshooting. Pass `onVisible = null` to disarm (loading / no more data).\n */\nfunction useBottomSentinel<E extends HTMLElement>(\n onVisible: (() => void) | null,\n deps: unknown[],\n): (el: E | null) => void {\n const elRef = useRef<E | null>(null);\n const observerRef = useRef<IntersectionObserver | null>(null);\n const cbRef = useRef(onVisible);\n cbRef.current = onVisible;\n\n const setRef = useCallback((el: E | null) => {\n elRef.current = el;\n observerRef.current?.disconnect();\n observerRef.current = null;\n if (el == null) return;\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) cbRef.current?.();\n },\n { rootMargin: \"300px\" },\n );\n observer.observe(el);\n observerRef.current = observer;\n }, []);\n\n // Re-arm after each load so the observer re-checks the settled layout.\n useEffect(() => {\n const el = elRef.current;\n const observer = observerRef.current;\n if (el == null || observer == null) return;\n observer.disconnect();\n observer.observe(el);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n useEffect(() => () => observerRef.current?.disconnect(), []);\n return setRef;\n}\n\nconst rowSelectionAtom = atom((get) => {\n /** Coerce selection to full rows, for use with data panel instead of data sheet. */\n const selection = get(selectionAtom);\n if (selection.some((r) => r.cols != null)) {\n // A card list has no cells or columns. When the selection carries columns —\n // inherited from a shared store the sheet also drives (a `DataView` toggle) —\n // coerce it to the full rows it covers, so the toolbar shows row-scoped\n // actions rather than column/cell ones for a column that isn't visible here.\n // Column-only selections (no rows) collapse to nothing.\n return rowIndicesToRegions(new Set(getSelectedRowIndices(selection)));\n } else {\n return selection;\n }\n}, passThroughSet(selectionAtom));\n\nconst updateSelectionAtom = atom(\n null,\n (get, set, index: number, mods: SelectModifiers) => {\n /** Update selection from a row index and modifiers. */\n const { enableMultipleSelection, enableModalSelection } = get(\n interactionOptionsAtom,\n );\n let enableSelection = get(enableSelectionAtom);\n if (!enableSelection) {\n // Cmd/ctrl-click *enters* select mode on a modal view and selects the\n // row, the familiar list idiom — so a bulk action doesn't require finding\n // the Select control first. The flag is read back below rather than\n // trusted from this scope: the write goes through the store synchronously.\n if (!enableModalSelection || !mods.additive) return;\n set(enableSelectionAtom, true);\n enableSelection = get(enableSelectionAtom);\n if (!enableSelection) return;\n }\n const selection = get(rowSelectionAtom);\n const anchorRef = get(anchorRefAtom);\n const res = buildDataViewSelection(\n index,\n mods,\n selection,\n anchorRef,\n enableMultipleSelection,\n );\n set(selectionAtom, res);\n },\n);\n\nconst selectedRowIndicesAtom = atom((get) => {\n const sel = get(selectionAtom);\n return new Set(getSelectedRowIndices(sel));\n});\n\ntype ItemSelectionKeys = \"onSelect\" | \"selected\" | \"selectable\";\n\ntype DataCardProps = {\n children: ReactNode;\n className: string;\n style?: CSSProperties;\n} & Pick<ItemComponentProps, ItemSelectionKeys>;\n\nexport function DataCard<T = any>(props: DataCardProps) {\n /** A basic card that implements the data panel's selection behavior. */\n return h(\n \"div.data-card.data-panel-item\",\n {\n className: classNames(props.className, {\n selected: props.selected,\n selectable: props.selectable,\n }),\n onClick: props.onSelect,\n style: props.style,\n },\n props.children,\n );\n}\n\ntype DataCardInnerComponent<T> = (\n props: ItemComponentProps<T>,\n) => React.ReactNode;\n\nexport function createDataCard<T>(\n component: DataCardInnerComponent<T>,\n extraProps = {},\n) {\n return (props: ItemComponentProps<T>) => {\n const { selected, selectable, onSelect } = props;\n return h(\n DataCard,\n {\n selected,\n selectable,\n onSelect,\n ...extraProps,\n },\n h(component, props),\n );\n };\n}\n"],"names":["DataPanelToolbarStyle"],"mappings":";;;;;;;;;;;;;;;;AAmF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AK,KAAK,OAAe,SAA0B;AAElD,UAAM,EAAE,yBAAyB,qBAAA,IAAyB;AAAA,MACxD;AAAA,IAAA;AAEF,QAAI,kBAAkB,IAAI,mBAAmB;AAC7C,QAAI,CAAC,iBAAiB;AAKpB,UAAI,CAAC,wBAAwB,CAAC,KAAK,SAAU;AAC7C,UAAI,qBAAqB,IAAI;AAC7B,wBAAkB,IAAI,mBAAmB;AACzC,UAAI,CAAC,gBAAiB;AAAA,IACxB;AACA,UAAM,YAAY,IAAI,gBAAgB;AACtC,UAAM,YAAY,IAAI,aAAa;AACnC,UAAM,MAAM;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAEF,QAAI,eAAe,GAAG;AAAA,EACxB;AACF;AAEA,MAAM,yBAAyB,KAAK,CAAC,QAAQ;AAC3C,QAAM,MAAM,IAAI,aAAa;AAC7B,SAAO,IAAI,IAAI,sBAAsB,GAAG,CAAC;AAC3C,CAAC;AAUM,SAAS,SAAkB,OAAsB;AAEtD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,WAAW,WAAW,MAAM,WAAW;AAAA,QACrC,UAAU,MAAM;AAAA,QAChB,YAAY,MAAM;AAAA,MAAA,CACnB;AAAA,MACD,SAAS,MAAM;AAAA,MACf,OAAO,MAAM;AAAA,IAAA;AAAA,IAEf,MAAM;AAAA,EAAA;AAEV;AAMO,SAAS,eACd,WACA,aAAa,IACb;AACA,SAAO,CAAC,UAAiC;AACvC,UAAM,EAAE,UAAU,YAAY,SAAA,IAAa;AAC3C,WAAO;AAAA,MACL;AAAA,MACA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,QACA,GAAG;AAAA,MAAA;AAAA,MAEL,EAAE,WAAW,KAAK;AAAA,IAAA;AAAA,EAEtB;AACF;"}
@@ -222,7 +222,7 @@ function useLoadControls() {
222
222
  const dataLength = data.length;
223
223
  const hasMore = !isLocalProvider && loadedCount < dataLength;
224
224
  const paused = autoLoadPages != null && loadedCount - resumeBaseline >= autoLoadPages * pageSize;
225
- const canLoadMore = hasMore && !footer.loading && !paused;
225
+ const canLoadMore = hasMore && !footer.loading && !paused && footer.error == null;
226
226
  const advance = react.useCallback(() => {
227
227
  setVisibleRegion({
228
228
  rowIndexStart: 0,
@@ -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\";\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":["update","adjustArraySize","data","seededRows","atom","core","lazyLoaderCoreStateAtom","tableDataAtom","ctx","dataProviderAtom","useCallback","useRef","debounce","dataRefreshTokenAtom","startAfterAtom","useSelector","useMemo","useEffect","resolveInitialData","useAsyncEffect","useState","PostgrestClient"],"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;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M,MAAA,IAAU,MAAM;AAC9B,UAAI,SAAS,KAAM,OAAM;AACzB,cAAQ,QAAQ,CAAA,GAAI,IAAI,CAAC,SAAc;AAAA,QACrC,OAAO,IAAI,SAAS;AAAA,QACpB,OAAO,IAAI;AAAA,MAAA,EACX;AAAA,IACJ;AAAA,IACA,MAAM,SAAS,MAAM;AACnB,YAAM,MAAW,MAAM,OAAO,OAAO,MAAe;AAAA,QAClD,eAAe;AAAA,MAAA,CAChB;AACD,UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,IACA,MAAM,WAAW,KAAK;AACpB,YAAM,MAAW,MAAM,OAAO,SAAS,GAAG,OAAO,aAAa,GAAG;AACjE,UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,EAAA;AAEJ;AAKA,SAAS,qBAAqB,GAA4C;AACxE,QAAM,IAAI,EAAE;AACZ,MAAI,KAAK,KAAM,QAAO;AACtB,QAAM,MAAM,EAAE,aAAa,EAAE;AAC7B,MAAI,OAAO,QAAQ,EAAE,YAAY,QAAQ,EAAE,SAAS,QAAQ,EAAE,UAAU,IAAI;AAC1E,WAAO,kBAAkB,EAAE,KAAK,UAAU,EAAE,UAAU,OAAO,EAAE,OAAO;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,yBACP,MACA,QACe;AAMf,QAAM,MAAM,KAAK,IAAI,OAAO,aAAa,KAAK,MAAM;AACpD,WAAS,IAAI,OAAO,eAAe,IAAI,KAAK,KAAK;AAC/C,QAAI,KAAK,CAAC,KAAK,MAAM;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;;;;;;;;;;;;;"}
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\";\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`, 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\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":["update","adjustArraySize","data","seededRows","atom","core","lazyLoaderCoreStateAtom","tableDataAtom","ctx","dataProviderAtom","useCallback","useRef","debounce","dataRefreshTokenAtom","startAfterAtom","useSelector","useMemo","useEffect","resolveInitialData","useAsyncEffect","useState","PostgrestClient"],"mappings":";;;;;;;;;;;;;;AAgFO,SAAS,k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UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,IACA,MAAM,WAAW,KAAK;AACpB,YAAM,MAAW,MAAM,OAAO,SAAS,GAAG,OAAO,aAAa,GAAG;AACjE,UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,EAAA;AAEJ;AAKA,SAAS,qBAAqB,GAA4C;AACxE,QAAM,IAAI,EAAE;AACZ,MAAI,KAAK,KAAM,QAAO;AACtB,QAAM,MAAM,EAAE,aAAa,EAAE;AAC7B,MAAI,OAAO,QAAQ,EAAE,YAAY,QAAQ,EAAE,SAAS,QAAQ,EAAE,UAAU,IAAI;AAC1E,WAAO,kBAAkB,EAAE,KAAK,UAAU,EAAE,UAAU,OAAO,EAAE,OAAO;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,yBACP,MACA,QACe;AAMf,QAAM,MAAM,KAAK,IAAI,OAAO,aAAa,KAAK,MAAM;AACpD,WAAS,IAAI,OAAO,eAAe,IAAI,KAAK,KAAK;AAC/C,QAAI,KAAK,CAAC,KAAK,MAAM;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;;;;;;;;;;;;;"}
@@ -82,7 +82,8 @@ export interface LoadControls {
82
82
  total: number | null;
83
83
  /** Auto-load is paused at the `autoLoadPages` checkpoint. */
84
84
  paused: boolean;
85
- /** Auto-load is currently permitted (`hasMore && !loading && !paused`) —
85
+ /** Auto-load is currently permitted (`hasMore && !loading && !paused`, and
86
+ * no load error) —
86
87
  * used to gate an infinite-scroll sentinel. */
87
88
  canLoadMore: boolean;
88
89
  /** Advance one page *without* resuming a paused auto-load (the sentinel
@@ -218,7 +218,7 @@ function useLoadControls() {
218
218
  const dataLength = data.length;
219
219
  const hasMore = !isLocalProvider && loadedCount < dataLength;
220
220
  const paused = autoLoadPages != null && loadedCount - resumeBaseline >= autoLoadPages * pageSize;
221
- const canLoadMore = hasMore && !footer.loading && !paused;
221
+ const canLoadMore = hasMore && !footer.loading && !paused && footer.error == null;
222
222
  const advance = useCallback(() => {
223
223
  setVisibleRegion({
224
224
  rowIndexStart: 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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B,EAAE,KAAK,UAAU,EAAE,UAAU,OAAO,EAAE,OAAO;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,yBACP,MACA,QACe;AAMf,QAAM,MAAM,KAAK,IAAI,OAAO,aAAa,KAAK,MAAM;AACpD,WAAS,IAAI,OAAO,eAAe,IAAI,KAAK,KAAK;AAC/C,QAAI,KAAK,CAAC,KAAK,MAAM;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;"}
1
+ {"version":3,"file":"data-loaders.js","sources":["../../src/postgrest-table/data-loaders.ts"],"sourcesContent":["/** Lazy loading of data from a PostgREST endpoint */\n\nimport { useAsyncEffect } from \"@macrostrat/ui-components\";\nimport { debounce } from \"underscore\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n ClientServerOptions,\n PostgrestClient,\n PostgrestFilterBuilder,\n PostgrestQueryBuilder,\n} from \"@supabase/postgrest-js\";\nimport { adjustArraySize, RowRegion } from \"./loading-utils.ts\";\nimport {\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataFilter,\n tableDataAtom,\n TableDataProvider,\n useSelector,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { FetchDataOptions, FetchMode } from \"../types.ts\";\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`, 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\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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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;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macrostrat/data-sheet",
3
- "version": "4.11.0",
3
+ "version": "4.11.1",
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.8.0",
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.3.0",
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",
package/src/data-panel.ts CHANGED
@@ -38,6 +38,7 @@ import {
38
38
  } from "react";
39
39
  import {
40
40
  AnchorButton,
41
+ Button,
41
42
  Classes,
42
43
  Icon,
43
44
  NonIdealState,
@@ -48,6 +49,7 @@ import {
48
49
  anchorRefAtom,
49
50
  ctx,
50
51
  dataProviderAtom,
52
+ dataRefreshTokenAtom,
51
53
  DataSheetProvider,
52
54
  DataViewRendererType,
53
55
  FetchData,
@@ -326,11 +328,7 @@ export function DataPanelRenderer<T>({
326
328
  let emptyState: ReactNode = null;
327
329
  if (cards.length === 0) {
328
330
  if (error != null) {
329
- emptyState = h(NonIdealState, {
330
- icon: "error",
331
- title: "Couldn't load data",
332
- description: error.message ?? "The data source returned an error.",
333
- });
331
+ emptyState = h(LoadErrorState, { error });
334
332
  } else if (initialized && !loading) {
335
333
  // Only after a fetch settled with no rows — not during the reset gap.
336
334
  emptyState = h(NonIdealState, {
@@ -562,6 +560,22 @@ function modifiersOf(arg?: SelectModifiers | ReactMouseEvent): SelectModifiers {
562
560
  return arg;
563
561
  }
564
562
 
563
+ /** A failed load, with a retry: auto-load stays off after an error, so
564
+ * reloading is the user's call. */
565
+ function LoadErrorState({ error }: { error: Error }) {
566
+ const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);
567
+ return h(NonIdealState, {
568
+ icon: "error",
569
+ title: "Couldn't load data",
570
+ description: error.message ?? "The data source returned an error.",
571
+ action: h(
572
+ Button,
573
+ { icon: "refresh", onClick: () => bumpRefresh((v) => v + 1) },
574
+ "Try again",
575
+ ),
576
+ });
577
+ }
578
+
565
579
  /**
566
580
  * Bottom-sentinel infinite-scroll hook (no `react-intersection-observer`
567
581
  * dependency). Calls `onVisible` when the observed element is on screen, and —
@@ -447,7 +447,8 @@ export interface LoadControls {
447
447
  total: number | null;
448
448
  /** Auto-load is paused at the `autoLoadPages` checkpoint. */
449
449
  paused: boolean;
450
- /** Auto-load is currently permitted (`hasMore && !loading && !paused`) —
450
+ /** Auto-load is currently permitted (`hasMore && !loading && !paused`, and
451
+ * no load error) —
451
452
  * used to gate an infinite-scroll sentinel. */
452
453
  canLoadMore: boolean;
453
454
  /** Advance one page *without* resuming a paused auto-load (the sentinel
@@ -482,7 +483,10 @@ export function useLoadControls(): LoadControls {
482
483
  const paused =
483
484
  autoLoadPages != null &&
484
485
  loadedCount - resumeBaseline >= autoLoadPages * pageSize;
485
- const canLoadMore = hasMore && !footer.loading && !paused;
486
+ // A failed chunk leaves its rows null, so without the error check the
487
+ // sentinel re-requests it forever.
488
+ const canLoadMore =
489
+ hasMore && !footer.loading && !paused && footer.error == null;
486
490
 
487
491
  const advance = useCallback(() => {
488
492
  setVisibleRegion({