@macrostrat/data-sheet 4.5.2 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.6.0] - 2026-09-02 [_changes_](https://github.com/UW-Macrostrat/web-components/compare/@macrostrat/data-sheet-v4.5.2...@macrostrat/data-sheet-v4.6.0)
4
+
5
+ ### Minor Changes
6
+
7
+ - Hoist `MasonryScrollBody` into the library (measured, append-only column
8
+ balancing, optional responsive columns), and stop counting loading skeletons
9
+ as layout items — `ScrollBodyProps` now carries them as `placeholders`.
10
+
3
11
  ## [4.5.2] - 2026-08-27 [_changes_](https://github.com/UW-Macrostrat/web-components/compare/@macrostrat/data-sheet-v4.5.1...@macrostrat/data-sheet-v4.5.2)
4
12
 
5
13
  ### Patch Changes
@@ -120,10 +120,11 @@ function DataPanelRenderer({
120
120
  });
121
121
  }
122
122
  }
123
+ const placeholderCards = [];
123
124
  if (loadPending) {
124
125
  const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);
125
126
  for (let i = 0; i < pending; i++) {
126
- cards.push(
127
+ placeholderCards.push(
127
128
  dataPanel_module.default(
128
129
  "div.data-panel-item-container.is-skeleton",
129
130
  { key: `skeleton-${i}`, "aria-hidden": true },
@@ -132,6 +133,10 @@ function DataPanelRenderer({
132
133
  );
133
134
  }
134
135
  }
136
+ let placeholders = null;
137
+ if (placeholderCards.length > 0) {
138
+ placeholders = placeholderCards;
139
+ }
135
140
  const shouldLoadNextPage = (hasMore || loading) && !paused && error == null;
136
141
  let loaderNode = null;
137
142
  if (activeProvider != null) {
@@ -213,7 +218,7 @@ function DataPanelRenderer({
213
218
  },
214
219
  [
215
220
  dataPanel_module.default("div.data-panel-body-content", [
216
- emptyState ?? dataPanel_module.default(ScrollBody, cards),
221
+ emptyState ?? dataPanel_module.default(ScrollBody, { placeholders }, cards),
217
222
  _contentFooter
218
223
  ])
219
224
  ]
@@ -228,8 +233,8 @@ function DataPanelRenderer({
228
233
  function DataPanelStatusBar({ children }) {
229
234
  return dataPanel_module.default("div.data-panel-status-bar", [children, dataPanel_module.default(viewInfo.LoadProgressIndicator)]);
230
235
  }
231
- function DefaultScrollBody({ children }) {
232
- return dataPanel_module.default("div.data-panel-list", children);
236
+ function DefaultScrollBody({ children, placeholders }) {
237
+ return dataPanel_module.default("div.data-panel-list", [children, placeholders]);
233
238
  }
234
239
  function PanelLoader({
235
240
  fetchData,
@@ -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 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 { Classes, Icon, NonIdealState, Spinner } from \"@blueprintjs/core\";\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}\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 /** 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 className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\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 if (loadPending) {\n const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);\n for (let i = 0; i < pending; i++) {\n cards.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\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 // 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 },\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 emptyState ?? h(ScrollBody, cards),\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. */\nfunction DefaultScrollBody({ children }: { children: ReactNode }) {\n return h(\"div.data-panel-list\", children);\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","ActionsToolbar","LoadProgressIndicator","useDataLoader","useRef","useEffect","atom","selection","selectionAtom","rowIndicesToRegions","getSelectedRowIndices","passThroughSet","interactionOptionsAtom","anchorRefAtom","buildDataViewSelection"],"mappings":";;;;;;;;;;;;;;;;;;AAyEO,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;AAyFL,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,eAAe;AAAA,EACf,eAAe;AAAA,EACf;AACF,GAA4E;AAC1E,QAAM;AAAA,IACJ,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EAAA,IACEE,KAAAA,IAAI,SAASC,qBAAgB;AAYjC,QAAM,iBAAiB,kBAAkB,KAAK,IAAI,YAAY,CAAC,IAAI;AAEnE,QAAM,OAAOC,KAAAA,YAAY,CAAC,MAAM,EAAE,IAAI;AAKtCF,OAAAA,IAAI,QAAQG,+BAAmB,iBAAiB,IAAI;AACpD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IAC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AAAA,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,SAAO1B,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 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 { Classes, Icon, NonIdealState, Spinner } from \"@blueprintjs/core\";\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 /** 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 className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\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 // 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 },\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 emptyState ?? h(ScrollBody, { placeholders }, cards),\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","ActionsToolbar","LoadProgressIndicator","useDataLoader","useRef","useEffect","atom","selection","selectionAtom","rowIndicesToRegions","getSelectedRowIndices","passThroughSet","interactionOptionsAtom","anchorRefAtom","buildDataViewSelection"],"mappings":";;;;;;;;;;;;;;;;;;AAyEO,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;AA+FL,SAAS,UAAa,OAA0B;AACrD,QAAM,CAAC,eAAe,aAAa,IAAIC,4BAAuB;AAAA,IAC5D,GAAG;AAAA,IACH,UAAUC,aAAAA,qBAAqB;AAAA,EAAA,CAChC;AACD,SA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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;;;;;;"}
@@ -19,6 +19,12 @@ export declare enum DataPanelToolbarStyle {
19
19
  export interface ScrollBodyProps {
20
20
  /** The rendered item cards (each wrapped for selection styling). */
21
21
  children: ReactNode;
22
+ /** Loading skeletons for the page currently being fetched, if any. Kept
23
+ * separate from `children` because they are transient stand-ins, not items:
24
+ * a layout that assigns a lasting position per item (e.g. the masonry body)
25
+ * must not hand one to a placeholder. Render them after the items; a body
26
+ * that ignores them simply shows no loading state. */
27
+ placeholders?: ReactNode;
22
28
  }
23
29
  /** Props handed to a consumer's card renderer for one row. */
24
30
  export interface ItemComponentProps<T = any> {
@@ -116,10 +116,11 @@ function DataPanelRenderer({
116
116
  });
117
117
  }
118
118
  }
119
+ const placeholderCards = [];
119
120
  if (loadPending) {
120
121
  const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);
121
122
  for (let i = 0; i < pending; i++) {
122
- cards.push(
123
+ placeholderCards.push(
123
124
  h(
124
125
  "div.data-panel-item-container.is-skeleton",
125
126
  { key: `skeleton-${i}`, "aria-hidden": true },
@@ -128,6 +129,10 @@ function DataPanelRenderer({
128
129
  );
129
130
  }
130
131
  }
132
+ let placeholders = null;
133
+ if (placeholderCards.length > 0) {
134
+ placeholders = placeholderCards;
135
+ }
131
136
  const shouldLoadNextPage = (hasMore || loading) && !paused && error == null;
132
137
  let loaderNode = null;
133
138
  if (activeProvider != null) {
@@ -209,7 +214,7 @@ function DataPanelRenderer({
209
214
  },
210
215
  [
211
216
  h("div.data-panel-body-content", [
212
- emptyState ?? h(ScrollBody, cards),
217
+ emptyState ?? h(ScrollBody, { placeholders }, cards),
213
218
  _contentFooter
214
219
  ])
215
220
  ]
@@ -224,8 +229,8 @@ function DataPanelRenderer({
224
229
  function DataPanelStatusBar({ children }) {
225
230
  return h("div.data-panel-status-bar", [children, h(LoadProgressIndicator)]);
226
231
  }
227
- function DefaultScrollBody({ children }) {
228
- return h("div.data-panel-list", children);
232
+ function DefaultScrollBody({ children, placeholders }) {
233
+ return h("div.data-panel-list", [children, placeholders]);
229
234
  }
230
235
  function PanelLoader({
231
236
  fetchData,
@@ -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 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 { Classes, Icon, NonIdealState, Spinner } from \"@blueprintjs/core\";\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}\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 /** 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 className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\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 if (loadPending) {\n const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);\n for (let i = 0; i < pending; i++) {\n cards.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\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 // 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 },\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 emptyState ?? h(ScrollBody, cards),\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. */\nfunction DefaultScrollBody({ children }: { children: ReactNode }) {\n return h(\"div.data-panel-list\", children);\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":";;;;;;;;;;;;;;AAy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BAAA,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;"}
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 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 { Classes, Icon, NonIdealState, Spinner } from \"@blueprintjs/core\";\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 /** 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 className,\n toolbarStyle = DataPanelToolbarStyle.BORDERED,\n viewControls = \"inline\",\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 // 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 },\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 emptyState ?? h(ScrollBody, { placeholders }, cards),\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":";;;;;;;;;;;;;;AAyEO,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;AA+FL,SAAS,UAAa,OAA0B;AACrD,QAAM,CAAC,eAAe,aAAa,IAAI,uBAAuB;AAAA,IAC5D,GAAG;AAAA,IACH,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wB,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;"}
@@ -1688,4 +1688,29 @@ span._sep_1r3aw_9:first-child, span._sep_1r3aw_9:last-child {
1688
1688
 
1689
1689
  ._collapsed-controls_dd90z_213 {
1690
1690
  max-width: 360px;
1691
+ }._data-panel-masonry-body_1oiqg_1 {
1692
+ display: flex;
1693
+ flex-direction: column;
1694
+ flex-grow: 1;
1695
+ }
1696
+
1697
+ ._data-panel-masonry_1oiqg_1 {
1698
+ display: flex;
1699
+ align-items: flex-start;
1700
+ gap: var(--data-panel-item-gap, 8px);
1701
+ }
1702
+
1703
+ ._data-panel-masonry-column_1oiqg_13 {
1704
+ flex: 1 1 0;
1705
+ min-width: 0;
1706
+ display: flex;
1707
+ flex-direction: column;
1708
+ gap: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px));
1709
+ }
1710
+
1711
+ ._data-panel-masonry-placeholders_1oiqg_21 {
1712
+ display: flex;
1713
+ flex-direction: column;
1714
+ gap: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px));
1715
+ margin-top: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px));
1691
1716
  }
package/dist/index.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const dataSheet = require("./data-sheet.cjs");
4
4
  const dataPanel = require("./data-panel.cjs");
5
+ const masonry = require("./masonry.cjs");
5
6
  const dataView = require("./data-view.cjs");
6
7
  const index = require("./postgrest-table/index.cjs");
7
8
  const operators = require("./filters/operators.cjs");
@@ -45,6 +46,8 @@ exports.DataPanel = dataPanel.DataPanel;
45
46
  exports.DataPanelRenderer = dataPanel.DataPanelRenderer;
46
47
  exports.DataPanelToolbarStyle = dataPanel.DataPanelToolbarStyle;
47
48
  exports.createDataCard = dataPanel.createDataCard;
49
+ exports.MasonryScrollBody = masonry.MasonryScrollBody;
50
+ exports.createMasonryScrollBody = masonry.createMasonryScrollBody;
48
51
  exports.DataView = dataView.DataView;
49
52
  exports.ExpandedLithologies = index.ExpandedLithologies;
50
53
  exports.IntervalCell = index.IntervalCell;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './data-sheet.ts';
2
2
  export * from './data-panel.ts';
3
+ export * from './masonry.ts';
3
4
  export * from './data-view';
4
5
  export * from './postgrest-table';
5
6
  export * from './components';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { DataSheet, DataSheetRenderer } from "./data-sheet.js";
2
2
  import { DataCard, DataPanel, DataPanelRenderer, DataPanelToolbarStyle, createDataCard } from "./data-panel.js";
3
+ import { MasonryScrollBody, createMasonryScrollBody } from "./masonry.js";
3
4
  import { DataView } from "./data-view.js";
4
5
  import { ExpandedLithologies, IntervalCell, LongTextViewer, PostgRESTTableView, SearchAction, fullTextSearchAction, lithologyRenderer, notifyOnError, wrapWithErrorHandling } from "./postgrest-table/index.js";
5
6
  import { DEFAULT_FILTER_OPERATORS, OPERATOR_LABELS, getOperatorsForColumn, testFilterOperator } from "./filters/operators.js";
@@ -74,6 +75,7 @@ export {
74
75
  LoadProgressIndicator,
75
76
  LoadProgressLabel,
76
77
  LongTextViewer,
78
+ MasonryScrollBody,
77
79
  MenuDropdown,
78
80
  MenuFormItem,
79
81
  MenuInlineFilterItem,
@@ -107,6 +109,7 @@ export {
107
109
  copyAction,
108
110
  createDataCard,
109
111
  createLocalProvider,
112
+ createMasonryScrollBody,
110
113
  createPostgRESTFetchChunk,
111
114
  createPostgRESTProvider,
112
115
  createSaveAction,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const masonry_module = require("./masonry.module.sass.cjs");
4
+ const react = require("react");
5
+ const FALLBACK_ITEM_HEIGHT = 160;
6
+ function MasonryScrollBody(props) {
7
+ const { children, placeholders, columns = 2, minColumnWidth } = props;
8
+ const containerRef = react.useRef(null);
9
+ const nCols = useColumnCount(containerRef, columns, minColumnWidth);
10
+ const stateRef = react.useRef(null);
11
+ stateRef.current ??= {
12
+ columns: nCols,
13
+ assign: /* @__PURE__ */ new Map(),
14
+ heights: /* @__PURE__ */ new Map(),
15
+ els: /* @__PURE__ */ new Map(),
16
+ refs: /* @__PURE__ */ new Map()
17
+ };
18
+ const state = stateRef.current;
19
+ const [, bump] = react.useReducer((x) => x + 1, 0);
20
+ const items = react.Children.toArray(children).filter(
21
+ react.isValidElement
22
+ );
23
+ react.useLayoutEffect(() => {
24
+ if (state.columns !== nCols) {
25
+ state.columns = nCols;
26
+ state.assign.clear();
27
+ }
28
+ for (const [key, el] of state.els) state.heights.set(key, el.offsetHeight);
29
+ const present = new Set(items.map(keyOf));
30
+ for (const key of [...state.assign.keys()]) {
31
+ if (!present.has(key)) state.assign.delete(key);
32
+ }
33
+ for (const key of [...state.heights.keys()]) {
34
+ if (!present.has(key)) state.heights.delete(key);
35
+ }
36
+ const unassigned = items.filter((c) => !state.assign.has(keyOf(c)));
37
+ if (unassigned.length === 0) return;
38
+ const colHeights = new Array(nCols).fill(0);
39
+ for (const [key, col] of state.assign) {
40
+ colHeights[col] += state.heights.get(key) ?? 0;
41
+ }
42
+ for (const child of unassigned) {
43
+ const key = keyOf(child);
44
+ let col = 0;
45
+ for (let c = 1; c < nCols; c++) {
46
+ if (colHeights[c] < colHeights[col]) col = c;
47
+ }
48
+ state.assign.set(key, col);
49
+ colHeights[col] += state.heights.get(key) ?? FALLBACK_ITEM_HEIGHT;
50
+ }
51
+ bump();
52
+ });
53
+ const stale = state.columns !== nCols;
54
+ const columnItems = Array.from({ length: nCols }, () => []);
55
+ items.forEach((child, i) => {
56
+ const key = keyOf(child);
57
+ let assigned = void 0;
58
+ if (!stale) {
59
+ assigned = state.assign.get(key);
60
+ }
61
+ const col = assigned ?? i % nCols;
62
+ columnItems[col].push(
63
+ react.cloneElement(child, { ref: refFor(state, key) })
64
+ );
65
+ });
66
+ return masonry_module("div.data-panel-masonry-body", [
67
+ masonry_module(
68
+ "div.data-panel-masonry",
69
+ { ref: containerRef },
70
+ columnItems.map(
71
+ (col, c) => masonry_module("div.data-panel-masonry-column", { key: c }, col)
72
+ )
73
+ ),
74
+ masonry_module.if(placeholders != null)(
75
+ "div.data-panel-masonry-placeholders",
76
+ placeholders
77
+ )
78
+ ]);
79
+ }
80
+ function createMasonryScrollBody(options = {}) {
81
+ return function MasonryScrollBodyWithOptions(props) {
82
+ return masonry_module(MasonryScrollBody, { ...options, ...props });
83
+ };
84
+ }
85
+ function keyOf(child) {
86
+ return String(child.key);
87
+ }
88
+ function refFor(state, key) {
89
+ let cb = state.refs.get(key);
90
+ if (cb == null) {
91
+ cb = (el) => {
92
+ if (el == null) {
93
+ state.els.delete(key);
94
+ } else {
95
+ state.els.set(key, el);
96
+ }
97
+ };
98
+ state.refs.set(key, cb);
99
+ }
100
+ return cb;
101
+ }
102
+ function useColumnCount(ref, columns, minColumnWidth) {
103
+ const [width, setWidth] = react.useState(null);
104
+ react.useEffect(() => {
105
+ const el = ref.current;
106
+ if (minColumnWidth == null || el == null) return;
107
+ const obs = new ResizeObserver(([entry]) => {
108
+ setWidth(entry.contentRect.width);
109
+ });
110
+ obs.observe(el);
111
+ return () => obs.disconnect();
112
+ }, [minColumnWidth]);
113
+ if (minColumnWidth == null || width == null) return Math.max(1, columns);
114
+ return Math.max(1, Math.min(columns, Math.floor(width / minColumnWidth)));
115
+ }
116
+ exports.MasonryScrollBody = MasonryScrollBody;
117
+ exports.createMasonryScrollBody = createMasonryScrollBody;
118
+ //# sourceMappingURL=masonry.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"masonry.cjs","sources":["../src/masonry.ts"],"sourcesContent":["/**\n * Masonry scroll body for the `DataPanel` — variable-height cards laid out in\n * equal-width columns, balanced by *measured* height rather than a flat\n * estimate or CSS multi-column.\n *\n * The problem it solves is paging: CSS `columns` re-flows the whole list every\n * time a page is appended, so the cards under the user's cursor move. Here each\n * item is placed in the running-shortest column **once**, keyed by its React\n * key, and then frozen — appending a page never reshuffles what is on screen.\n *\n * Placement is measured: a freshly-appended batch mounts in provisional\n * columns, a `useLayoutEffect` reads each card's real `offsetHeight`, then the\n * batch is greedily assigned from those real heights and re-rendered — all\n * before paint, so only the balanced result is seen.\n *\n * Two things keep the balance honest over many pages:\n *\n * - **Placeholders are not items.** The panel's loading skeletons arrive as\n * `placeholders`, not `children`, and render below the columns. Freezing a\n * column assignment for a skeleton (measured at skeleton height, then\n * replaced by real content) is what makes a masonry drift, one page at a\n * time, into \"this whole page went into one column\".\n * - **Identity is the React key, not the array index.** A sort, filter or\n * refresh replaces the keys, and assignments for keys that are gone are\n * pruned — so column heights are always recomputed from items that are\n * actually on screen.\n */\nimport h from \"./masonry.module.sass\";\nimport {\n Children,\n cloneElement,\n isValidElement,\n ReactElement,\n ReactNode,\n useEffect,\n useLayoutEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport type { ScrollBodyProps } from \"./data-panel\";\n\n/** Height assumed for an item that hasn't been measured yet (it always is, by\n * the time it matters — this only guards a torn-down/hidden container). */\nconst FALLBACK_ITEM_HEIGHT = 160;\n\nexport interface MasonryOptions {\n /** Number of columns (the maximum, when `minColumnWidth` is set). Default 2. */\n columns?: number;\n /** If set, the column count drops below `columns` when the container is too\n * narrow to give every column at least this many pixels. */\n minColumnWidth?: number;\n}\n\ninterface MasonryState {\n /** Column count the current assignments were computed for. */\n columns: number;\n /** Frozen key → column. */\n assign: Map<string, number>;\n /** Last measured height per key. */\n heights: Map<string, number>;\n /** Mounted element per key, for measurement. */\n els: Map<string, HTMLElement>;\n /** Stable ref callbacks, so an item isn't detached/reattached every render. */\n refs: Map<string, (el: HTMLElement | null) => void>;\n}\n\n/**\n * A `scrollBody` component for `DataPanel` with the default two columns. For\n * anything else — a different column count, or responsive columns — build one\n * with `createMasonryScrollBody`.\n */\nexport function MasonryScrollBody(props: ScrollBodyProps & MasonryOptions) {\n const { children, placeholders, columns = 2, minColumnWidth } = props;\n\n const containerRef = useRef<HTMLDivElement | null>(null);\n const nCols = useColumnCount(containerRef, columns, minColumnWidth);\n\n const stateRef = useRef<MasonryState | null>(null);\n stateRef.current ??= {\n columns: nCols,\n assign: new Map(),\n heights: new Map(),\n els: new Map(),\n refs: new Map(),\n };\n const state = stateRef.current;\n const [, bump] = useReducer((x: number) => x + 1, 0);\n\n const items = Children.toArray(children).filter(\n isValidElement,\n ) as ReactElement[];\n\n // Runs on every commit (no deps): measurement has to see the layout that was\n // just produced, including one caused by a resize or a card's own content\n // settling. It is cheap when nothing is unassigned, and re-renders only when\n // it actually assigns something — so there's no render loop.\n useLayoutEffect(() => {\n // A column-count change invalidates every assignment (a column may no\n // longer exist). Handled here, not in render, so render stays pure.\n if (state.columns !== nCols) {\n state.columns = nCols;\n state.assign.clear();\n }\n\n for (const [key, el] of state.els) state.heights.set(key, el.offsetHeight);\n\n const present = new Set(items.map(keyOf));\n for (const key of [...state.assign.keys()]) {\n if (!present.has(key)) state.assign.delete(key);\n }\n for (const key of [...state.heights.keys()]) {\n if (!present.has(key)) state.heights.delete(key);\n }\n\n const unassigned = items.filter((c) => !state.assign.has(keyOf(c)));\n if (unassigned.length === 0) return;\n\n // Column heights from the items already frozen into them…\n const colHeights = new Array(nCols).fill(0);\n for (const [key, col] of state.assign) {\n colHeights[col] += state.heights.get(key) ?? 0;\n }\n // …then greedily place the new batch by its just-measured real heights.\n for (const child of unassigned) {\n const key = keyOf(child);\n let col = 0;\n for (let c = 1; c < nCols; c++) {\n if (colHeights[c] < colHeights[col]) col = c;\n }\n state.assign.set(key, col);\n colHeights[col] += state.heights.get(key) ?? FALLBACK_ITEM_HEIGHT;\n }\n bump(); // move the new batch into its balanced columns, before paint\n });\n\n // Items without an assignment yet render in a provisional column so they\n // mount and can be measured; the layout effect above then places them.\n const stale = state.columns !== nCols;\n const columnItems: ReactNode[][] = Array.from({ length: nCols }, () => []);\n items.forEach((child, i) => {\n const key = keyOf(child);\n let assigned: number | undefined = undefined;\n if (!stale) {\n assigned = state.assign.get(key);\n }\n const col = assigned ?? i % nCols;\n columnItems[col].push(\n cloneElement(child, { ref: refFor(state, key) } as any),\n );\n });\n\n return h(\"div.data-panel-masonry-body\", [\n h(\n \"div.data-panel-masonry\",\n { ref: containerRef },\n columnItems.map((col, c) =>\n h(\"div.data-panel-masonry-column\", { key: c }, col),\n ),\n ),\n h.if(placeholders != null)(\n \"div.data-panel-masonry-placeholders\",\n placeholders,\n ),\n ]);\n}\n\n/** Build a `scrollBody` masonry component with a fixed or responsive column\n * count: `scrollBody: createMasonryScrollBody({ columns: 3 })`. */\nexport function createMasonryScrollBody(options: MasonryOptions = {}) {\n return function MasonryScrollBodyWithOptions(props: ScrollBodyProps) {\n return h(MasonryScrollBody, { ...options, ...props });\n };\n}\n\nfunction keyOf(child: ReactElement): string {\n return String(child.key);\n}\n\n/** One stable ref callback per key — a fresh closure each render would detach\n * and reattach every card on every render. */\nfunction refFor(state: MasonryState, key: string) {\n let cb = state.refs.get(key);\n if (cb == null) {\n cb = (el: HTMLElement | null) => {\n if (el == null) {\n state.els.delete(key);\n } else {\n state.els.set(key, el);\n }\n };\n state.refs.set(key, cb);\n }\n return cb;\n}\n\n/** The effective column count: `columns`, reduced to fit `minColumnWidth`. */\nfunction useColumnCount(\n ref: { current: HTMLElement | null },\n columns: number,\n minColumnWidth: number | undefined,\n): number {\n const [width, setWidth] = useState<number | null>(null);\n\n useEffect(() => {\n const el = ref.current;\n if (minColumnWidth == null || el == null) return;\n const obs = new ResizeObserver(([entry]) => {\n setWidth(entry.contentRect.width);\n });\n obs.observe(el);\n return () => obs.disconnect();\n }, [minColumnWidth]);\n\n if (minColumnWidth == null || width == null) return Math.max(1, columns);\n return Math.max(1, Math.min(columns, Math.floor(width / minColumnWidth)));\n}\n"],"names":["useRef","useReducer","Children","isValidElement","useLayoutEffect","cloneElement","h","useState","useEffect"],"mappings":";;;;AA4CA,MAAM,uBAAuB;AA4BtB,SAAS,kBAAkB,OAAyC;AACzE,QAAM,EAAE,UAAU,cAAc,UAAU,GAAG,mBAAmB;AAEhE,QAAM,eAAeA,MAAAA,OAA8B,IAAI;AACvD,QAAM,QAAQ,eAAe,cAAc,SAAS,cAAc;AAElE,QAAM,WAAWA,MAAAA,OAA4B,IAAI;AACjD,WAAS,YAAY;AAAA,IACnB,SAAS;AAAA,IACT,4BAAY,IAAA;AAAA,IACZ,6BAAa,IAAA;AAAA,IACb,yBAAS,IAAA;AAAA,IACT,0BAAU,IAAA;AAAA,EAAI;AAEhB,QAAM,QAAQ,SAAS;AACvB,QAAM,CAAA,EAAG,IAAI,IAAIC,MAAAA,WAAW,CAAC,MAAc,IAAI,GAAG,CAAC;AAEnD,QAAM,QAAQC,MAAAA,SAAS,QAAQ,QAAQ,EAAE;AAAA,IACvCC,MAAAA;AAAAA,EAAA;AAOFC,QAAAA,gBAAgB,MAAM;AAGpB,QAAI,MAAM,YAAY,OAAO;AAC3B,YAAM,UAAU;AAChB,YAAM,OAAO,MAAA;AAAA,IACf;AAEA,eAAW,CAAC,KAAK,EAAE,KAAK,MAAM,IAAK,OAAM,QAAQ,IAAI,KAAK,GAAG,YAAY;AAEzE,UAAM,UAAU,IAAI,IAAI,MAAM,I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AI,WAAA;AAAA,EACnB,GAAG,CAAC,cAAc,CAAC;AAEnB,MAAI,kBAAkB,QAAQ,SAAS,aAAa,KAAK,IAAI,GAAG,OAAO;AACvE,SAAO,KAAK,IAAI,GAAG,KAAK,IAAI,SAAS,KAAK,MAAM,QAAQ,cAAc,CAAC,CAAC;AAC1E;;;"}
@@ -0,0 +1,17 @@
1
+ import { ScrollBodyProps } from './data-panel';
2
+ export interface MasonryOptions {
3
+ /** Number of columns (the maximum, when `minColumnWidth` is set). Default 2. */
4
+ columns?: number;
5
+ /** If set, the column count drops below `columns` when the container is too
6
+ * narrow to give every column at least this many pixels. */
7
+ minColumnWidth?: number;
8
+ }
9
+ /**
10
+ * A `scrollBody` component for `DataPanel` with the default two columns. For
11
+ * anything else — a different column count, or responsive columns — build one
12
+ * with `createMasonryScrollBody`.
13
+ */
14
+ export declare function MasonryScrollBody(props: ScrollBodyProps & MasonryOptions): import('react').DOMElement<import('react').DOMAttributes<Element>, Element>;
15
+ /** Build a `scrollBody` masonry component with a fixed or responsive column
16
+ * count: `scrollBody: createMasonryScrollBody({ columns: 3 })`. */
17
+ export declare function createMasonryScrollBody(options?: MasonryOptions): (props: ScrollBodyProps) => import('react').FunctionComponentElement<ScrollBodyProps & MasonryOptions>;
@@ -0,0 +1,118 @@
1
+ import h from "./masonry.module.sass.js";
2
+ import { useRef, useReducer, Children, isValidElement, useLayoutEffect, cloneElement, useState, useEffect } from "react";
3
+ const FALLBACK_ITEM_HEIGHT = 160;
4
+ function MasonryScrollBody(props) {
5
+ const { children, placeholders, columns = 2, minColumnWidth } = props;
6
+ const containerRef = useRef(null);
7
+ const nCols = useColumnCount(containerRef, columns, minColumnWidth);
8
+ const stateRef = useRef(null);
9
+ stateRef.current ??= {
10
+ columns: nCols,
11
+ assign: /* @__PURE__ */ new Map(),
12
+ heights: /* @__PURE__ */ new Map(),
13
+ els: /* @__PURE__ */ new Map(),
14
+ refs: /* @__PURE__ */ new Map()
15
+ };
16
+ const state = stateRef.current;
17
+ const [, bump] = useReducer((x) => x + 1, 0);
18
+ const items = Children.toArray(children).filter(
19
+ isValidElement
20
+ );
21
+ useLayoutEffect(() => {
22
+ if (state.columns !== nCols) {
23
+ state.columns = nCols;
24
+ state.assign.clear();
25
+ }
26
+ for (const [key, el] of state.els) state.heights.set(key, el.offsetHeight);
27
+ const present = new Set(items.map(keyOf));
28
+ for (const key of [...state.assign.keys()]) {
29
+ if (!present.has(key)) state.assign.delete(key);
30
+ }
31
+ for (const key of [...state.heights.keys()]) {
32
+ if (!present.has(key)) state.heights.delete(key);
33
+ }
34
+ const unassigned = items.filter((c) => !state.assign.has(keyOf(c)));
35
+ if (unassigned.length === 0) return;
36
+ const colHeights = new Array(nCols).fill(0);
37
+ for (const [key, col] of state.assign) {
38
+ colHeights[col] += state.heights.get(key) ?? 0;
39
+ }
40
+ for (const child of unassigned) {
41
+ const key = keyOf(child);
42
+ let col = 0;
43
+ for (let c = 1; c < nCols; c++) {
44
+ if (colHeights[c] < colHeights[col]) col = c;
45
+ }
46
+ state.assign.set(key, col);
47
+ colHeights[col] += state.heights.get(key) ?? FALLBACK_ITEM_HEIGHT;
48
+ }
49
+ bump();
50
+ });
51
+ const stale = state.columns !== nCols;
52
+ const columnItems = Array.from({ length: nCols }, () => []);
53
+ items.forEach((child, i) => {
54
+ const key = keyOf(child);
55
+ let assigned = void 0;
56
+ if (!stale) {
57
+ assigned = state.assign.get(key);
58
+ }
59
+ const col = assigned ?? i % nCols;
60
+ columnItems[col].push(
61
+ cloneElement(child, { ref: refFor(state, key) })
62
+ );
63
+ });
64
+ return h("div.data-panel-masonry-body", [
65
+ h(
66
+ "div.data-panel-masonry",
67
+ { ref: containerRef },
68
+ columnItems.map(
69
+ (col, c) => h("div.data-panel-masonry-column", { key: c }, col)
70
+ )
71
+ ),
72
+ h.if(placeholders != null)(
73
+ "div.data-panel-masonry-placeholders",
74
+ placeholders
75
+ )
76
+ ]);
77
+ }
78
+ function createMasonryScrollBody(options = {}) {
79
+ return function MasonryScrollBodyWithOptions(props) {
80
+ return h(MasonryScrollBody, { ...options, ...props });
81
+ };
82
+ }
83
+ function keyOf(child) {
84
+ return String(child.key);
85
+ }
86
+ function refFor(state, key) {
87
+ let cb = state.refs.get(key);
88
+ if (cb == null) {
89
+ cb = (el) => {
90
+ if (el == null) {
91
+ state.els.delete(key);
92
+ } else {
93
+ state.els.set(key, el);
94
+ }
95
+ };
96
+ state.refs.set(key, cb);
97
+ }
98
+ return cb;
99
+ }
100
+ function useColumnCount(ref, columns, minColumnWidth) {
101
+ const [width, setWidth] = useState(null);
102
+ useEffect(() => {
103
+ const el = ref.current;
104
+ if (minColumnWidth == null || el == null) return;
105
+ const obs = new ResizeObserver(([entry]) => {
106
+ setWidth(entry.contentRect.width);
107
+ });
108
+ obs.observe(el);
109
+ return () => obs.disconnect();
110
+ }, [minColumnWidth]);
111
+ if (minColumnWidth == null || width == null) return Math.max(1, columns);
112
+ return Math.max(1, Math.min(columns, Math.floor(width / minColumnWidth)));
113
+ }
114
+ export {
115
+ MasonryScrollBody,
116
+ createMasonryScrollBody
117
+ };
118
+ //# sourceMappingURL=masonry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"masonry.js","sources":["../src/masonry.ts"],"sourcesContent":["/**\n * Masonry scroll body for the `DataPanel` — variable-height cards laid out in\n * equal-width columns, balanced by *measured* height rather than a flat\n * estimate or CSS multi-column.\n *\n * The problem it solves is paging: CSS `columns` re-flows the whole list every\n * time a page is appended, so the cards under the user's cursor move. Here each\n * item is placed in the running-shortest column **once**, keyed by its React\n * key, and then frozen — appending a page never reshuffles what is on screen.\n *\n * Placement is measured: a freshly-appended batch mounts in provisional\n * columns, a `useLayoutEffect` reads each card's real `offsetHeight`, then the\n * batch is greedily assigned from those real heights and re-rendered — all\n * before paint, so only the balanced result is seen.\n *\n * Two things keep the balance honest over many pages:\n *\n * - **Placeholders are not items.** The panel's loading skeletons arrive as\n * `placeholders`, not `children`, and render below the columns. Freezing a\n * column assignment for a skeleton (measured at skeleton height, then\n * replaced by real content) is what makes a masonry drift, one page at a\n * time, into \"this whole page went into one column\".\n * - **Identity is the React key, not the array index.** A sort, filter or\n * refresh replaces the keys, and assignments for keys that are gone are\n * pruned — so column heights are always recomputed from items that are\n * actually on screen.\n */\nimport h from \"./masonry.module.sass\";\nimport {\n Children,\n cloneElement,\n isValidElement,\n ReactElement,\n ReactNode,\n useEffect,\n useLayoutEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport type { ScrollBodyProps } from \"./data-panel\";\n\n/** Height assumed for an item that hasn't been measured yet (it always is, by\n * the time it matters — this only guards a torn-down/hidden container). */\nconst FALLBACK_ITEM_HEIGHT = 160;\n\nexport interface MasonryOptions {\n /** Number of columns (the maximum, when `minColumnWidth` is set). Default 2. */\n columns?: number;\n /** If set, the column count drops below `columns` when the container is too\n * narrow to give every column at least this many pixels. */\n minColumnWidth?: number;\n}\n\ninterface MasonryState {\n /** Column count the current assignments were computed for. */\n columns: number;\n /** Frozen key → column. */\n assign: Map<string, number>;\n /** Last measured height per key. */\n heights: Map<string, number>;\n /** Mounted element per key, for measurement. */\n els: Map<string, HTMLElement>;\n /** Stable ref callbacks, so an item isn't detached/reattached every render. */\n refs: Map<string, (el: HTMLElement | null) => void>;\n}\n\n/**\n * A `scrollBody` component for `DataPanel` with the default two columns. For\n * anything else — a different column count, or responsive columns — build one\n * with `createMasonryScrollBody`.\n */\nexport function MasonryScrollBody(props: ScrollBodyProps & MasonryOptions) {\n const { children, placeholders, columns = 2, minColumnWidth } = props;\n\n const containerRef = useRef<HTMLDivElement | null>(null);\n const nCols = useColumnCount(containerRef, columns, minColumnWidth);\n\n const stateRef = useRef<MasonryState | null>(null);\n stateRef.current ??= {\n columns: nCols,\n assign: new Map(),\n heights: new Map(),\n els: new Map(),\n refs: new Map(),\n };\n const state = stateRef.current;\n const [, bump] = useReducer((x: number) => x + 1, 0);\n\n const items = Children.toArray(children).filter(\n isValidElement,\n ) as ReactElement[];\n\n // Runs on every commit (no deps): measurement has to see the layout that was\n // just produced, including one caused by a resize or a card's own content\n // settling. It is cheap when nothing is unassigned, and re-renders only when\n // it actually assigns something — so there's no render loop.\n useLayoutEffect(() => {\n // A column-count change invalidates every assignment (a column may no\n // longer exist). Handled here, not in render, so render stays pure.\n if (state.columns !== nCols) {\n state.columns = nCols;\n state.assign.clear();\n }\n\n for (const [key, el] of state.els) state.heights.set(key, el.offsetHeight);\n\n const present = new Set(items.map(keyOf));\n for (const key of [...state.assign.keys()]) {\n if (!present.has(key)) state.assign.delete(key);\n }\n for (const key of [...state.heights.keys()]) {\n if (!present.has(key)) state.heights.delete(key);\n }\n\n const unassigned = items.filter((c) => !state.assign.has(keyOf(c)));\n if (unassigned.length === 0) return;\n\n // Column heights from the items already frozen into them…\n const colHeights = new Array(nCols).fill(0);\n for (const [key, col] of state.assign) {\n colHeights[col] += state.heights.get(key) ?? 0;\n }\n // …then greedily place the new batch by its just-measured real heights.\n for (const child of unassigned) {\n const key = keyOf(child);\n let col = 0;\n for (let c = 1; c < nCols; c++) {\n if (colHeights[c] < colHeights[col]) col = c;\n }\n state.assign.set(key, col);\n colHeights[col] += state.heights.get(key) ?? FALLBACK_ITEM_HEIGHT;\n }\n bump(); // move the new batch into its balanced columns, before paint\n });\n\n // Items without an assignment yet render in a provisional column so they\n // mount and can be measured; the layout effect above then places them.\n const stale = state.columns !== nCols;\n const columnItems: ReactNode[][] = Array.from({ length: nCols }, () => []);\n items.forEach((child, i) => {\n const key = keyOf(child);\n let assigned: number | undefined = undefined;\n if (!stale) {\n assigned = state.assign.get(key);\n }\n const col = assigned ?? i % nCols;\n columnItems[col].push(\n cloneElement(child, { ref: refFor(state, key) } as any),\n );\n });\n\n return h(\"div.data-panel-masonry-body\", [\n h(\n \"div.data-panel-masonry\",\n { ref: containerRef },\n columnItems.map((col, c) =>\n h(\"div.data-panel-masonry-column\", { key: c }, col),\n ),\n ),\n h.if(placeholders != null)(\n \"div.data-panel-masonry-placeholders\",\n placeholders,\n ),\n ]);\n}\n\n/** Build a `scrollBody` masonry component with a fixed or responsive column\n * count: `scrollBody: createMasonryScrollBody({ columns: 3 })`. */\nexport function createMasonryScrollBody(options: MasonryOptions = {}) {\n return function MasonryScrollBodyWithOptions(props: ScrollBodyProps) {\n return h(MasonryScrollBody, { ...options, ...props });\n };\n}\n\nfunction keyOf(child: ReactElement): string {\n return String(child.key);\n}\n\n/** One stable ref callback per key — a fresh closure each render would detach\n * and reattach every card on every render. */\nfunction refFor(state: MasonryState, key: string) {\n let cb = state.refs.get(key);\n if (cb == null) {\n cb = (el: HTMLElement | null) => {\n if (el == null) {\n state.els.delete(key);\n } else {\n state.els.set(key, el);\n }\n };\n state.refs.set(key, cb);\n }\n return cb;\n}\n\n/** The effective column count: `columns`, reduced to fit `minColumnWidth`. */\nfunction useColumnCount(\n ref: { current: HTMLElement | null },\n columns: number,\n minColumnWidth: number | undefined,\n): number {\n const [width, setWidth] = useState<number | null>(null);\n\n useEffect(() => {\n const el = ref.current;\n if (minColumnWidth == null || el == null) return;\n const obs = new ResizeObserver(([entry]) => {\n setWidth(entry.contentRect.width);\n });\n obs.observe(el);\n return () => obs.disconnect();\n }, [minColumnWidth]);\n\n if (minColumnWidth == null || width == null) return Math.max(1, columns);\n return Math.max(1, Math.min(columns, Math.floor(width / minColumnWidth)));\n}\n"],"names":[],"mappings":";;AA4CA,MAAM,uBAAuB;AA4BtB,SAAS,kBAAkB,OAAyC;AACzE,QAAM,EAAE,UAAU,cAAc,UAAU,GAAG,mBAAmB;AAEhE,QAAM,eAAe,OAA8B,IAAI;AACvD,QAAM,QAAQ,eAAe,cAAc,SAAS,cAAc;AAElE,QAAM,WAAW,OAA4B,IAAI;AACjD,WAAS,YAAY;AAAA,IACnB,SAAS;AAAA,IACT,4BAAY,IAAA;AAAA,IACZ,6BAAa,IAAA;AAAA,IACb,yBAAS,IAAA;AAAA,IACT,0BAAU,IAAA;AAAA,EAAI;AAEhB,QAAM,QAAQ,SAAS;AACvB,QAAM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B;AACA,SAAO;AACT;AAGA,SAAS,eACP,KACA,SACA,gBACQ;AACR,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AAEtD,YAAU,MAAM;AACd,UAAM,KAAK,IAAI;AACf,QAAI,kBAAkB,QAAQ,MAAM,KAAM;AAC1C,UAAM,MAAM,IAAI,eAAe,CAAC,CAAC,KAAK,MAAM;AAC1C,eAAS,MAAM,YAAY,KAAK;AAAA,IAClC,CAAC;AACD,QAAI,QAAQ,EAAE;AACd,WAAO,MAAM,IAAI,WAAA;AAAA,EACnB,GAAG,CAAC,cAAc,CAAC;AAEnB,MAAI,kBAAkB,QAAQ,SAAS,aAAa,KAAK,IAAI,GAAG,OAAO;AACvE,SAAO,KAAK,IAAI,GAAG,KAAK,IAAI,SAAS,KAAK,MAAM,QAAQ,cAAc,CAAC,CAAC;AAC1E;"}
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ const h$1 = require("@macrostrat/hyper");
3
+ const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
4
+ const h__default = /* @__PURE__ */ _interopDefault(h$1);
5
+ const styles = {
6
+ "data-panel-masonry-body": "_data-panel-masonry-body_1oiqg_1",
7
+ "data-panel-masonry": "_data-panel-masonry_1oiqg_1",
8
+ "data-panel-masonry-column": "_data-panel-masonry-column_1oiqg_13",
9
+ "data-panel-masonry-placeholders": "_data-panel-masonry-placeholders_1oiqg_21"
10
+ };
11
+ let h = h__default.default.styled(styles);
12
+ Object.assign(h, styles);
13
+ module.exports = h;
14
+ //# sourceMappingURL=masonry.module.sass.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"masonry.module.sass.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;"}
@@ -0,0 +1,13 @@
1
+ import h$1 from "@macrostrat/hyper";
2
+ const styles = {
3
+ "data-panel-masonry-body": "_data-panel-masonry-body_1oiqg_1",
4
+ "data-panel-masonry": "_data-panel-masonry_1oiqg_1",
5
+ "data-panel-masonry-column": "_data-panel-masonry-column_1oiqg_13",
6
+ "data-panel-masonry-placeholders": "_data-panel-masonry-placeholders_1oiqg_21"
7
+ };
8
+ let h = h$1.styled(styles);
9
+ Object.assign(h, styles);
10
+ export {
11
+ h as default
12
+ };
13
+ //# sourceMappingURL=masonry.module.sass.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"masonry.module.sass.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macrostrat/data-sheet",
3
- "version": "4.5.2",
3
+ "version": "4.6.0",
4
4
  "description": "Scalable data sheet with optional editing capabilities",
5
5
  "repository": {
6
6
  "type": "git",
@@ -51,7 +51,7 @@
51
51
  "@macrostrat/color-utils": "^1.2.2",
52
52
  "@macrostrat/data-components": "^1.5.1",
53
53
  "@macrostrat/hyper": "^3.1.1",
54
- "@macrostrat/scoped-store": "^1.0.1",
54
+ "@macrostrat/scoped-store": "^1.1.0",
55
55
  "@macrostrat/ui-components": "^5.2.0",
56
56
  "@supabase/postgrest-js": "^1.17.7",
57
57
  "@types/underscore": "^1.13.0",
@@ -62,7 +62,7 @@
62
62
  },
63
63
  "devDependencies": {
64
64
  "@macrostrat/web-components-bundler": "1.0.1",
65
- "@storybook/react-vite": "10.5.2"
65
+ "@storybook/react-vite": "10.5.10"
66
66
  },
67
67
  "publishConfig": {
68
68
  "access": "public"
package/src/data-panel.ts CHANGED
@@ -89,6 +89,12 @@ export enum DataPanelToolbarStyle {
89
89
  export interface ScrollBodyProps {
90
90
  /** The rendered item cards (each wrapped for selection styling). */
91
91
  children: ReactNode;
92
+ /** Loading skeletons for the page currently being fetched, if any. Kept
93
+ * separate from `children` because they are transient stand-ins, not items:
94
+ * a layout that assigns a lasting position per item (e.g. the masonry body)
95
+ * must not hand one to a placeholder. Render them after the items; a body
96
+ * that ignores them simply shows no loading state. */
97
+ placeholders?: ReactNode;
92
98
  }
93
99
 
94
100
  /** Props handed to a consumer's card renderer for one row. */
@@ -324,10 +330,11 @@ export function DataPanelRenderer<T>({
324
330
  // reset pre-sizes to a page of `null` slots) or the next scroll page — so the
325
331
  // body shows shimmer where rows will land instead of a blank flash or a
326
332
  // footer pinging up into the gap. Bounded to a viewport's worth of cards.
333
+ const placeholderCards: ReactNode[] = [];
327
334
  if (loadPending) {
328
335
  const pending = Math.min(Math.max(data.length - loadedCount, 0), 24);
329
336
  for (let i = 0; i < pending; i++) {
330
- cards.push(
337
+ placeholderCards.push(
331
338
  h(
332
339
  "div.data-panel-item-container.is-skeleton",
333
340
  { key: `skeleton-${i}`, "aria-hidden": true },
@@ -336,6 +343,10 @@ export function DataPanelRenderer<T>({
336
343
  );
337
344
  }
338
345
  }
346
+ let placeholders: ReactNode = null;
347
+ if (placeholderCards.length > 0) {
348
+ placeholders = placeholderCards;
349
+ }
339
350
 
340
351
  // The default spinner sentinel (below-placement): hidden while paused so the
341
352
  // pinned footer's "Load more" takes over.
@@ -450,7 +461,7 @@ export function DataPanelRenderer<T>({
450
461
  },
451
462
  [
452
463
  h("div.data-panel-body-content", [
453
- emptyState ?? h(ScrollBody, cards),
464
+ emptyState ?? h(ScrollBody, { placeholders }, cards),
454
465
  _contentFooter,
455
466
  ]),
456
467
  ],
@@ -468,9 +479,10 @@ function DataPanelStatusBar({ children }) {
468
479
  return h("div.data-panel-status-bar", [children, h(LoadProgressIndicator)]);
469
480
  }
470
481
 
471
- /** Default scroll-body layout: a vertical flex list of cards. */
472
- function DefaultScrollBody({ children }: { children: ReactNode }) {
473
- return h("div.data-panel-list", children);
482
+ /** Default scroll-body layout: a vertical flex list of cards, with any loading
483
+ * placeholders appended in the same flow. */
484
+ function DefaultScrollBody({ children, placeholders }: ScrollBodyProps) {
485
+ return h("div.data-panel-list", [children, placeholders]);
474
486
  }
475
487
 
476
488
  /** Runs the shared windowed loader from inside the panel (renders nothing).
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./data-sheet.ts";
2
2
  export * from "./data-panel.ts";
3
+ export * from "./masonry.ts";
3
4
  export * from "./data-view";
4
5
  export * from "./postgrest-table";
5
6
  export * from "./components";
@@ -0,0 +1,29 @@
1
+ // Masonry scroll body for the DataPanel — a fixed set of equal-width columns
2
+ // that items are distributed across by measured height (see `masonry.ts`).
3
+ // Not CSS multi-column: real columns, so appending a page never reflows what
4
+ // is already on screen.
5
+
6
+ .data-panel-masonry-body
7
+ display: flex
8
+ flex-direction: column
9
+ flex-grow: 1
10
+
11
+ .data-panel-masonry
12
+ display: flex
13
+ align-items: flex-start
14
+ gap: var(--data-panel-item-gap, 8px)
15
+
16
+ .data-panel-masonry-column
17
+ flex: 1 1 0
18
+ min-width: 0
19
+ display: flex
20
+ flex-direction: column
21
+ gap: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px))
22
+
23
+ // Loading placeholders sit below the columns, outside the measured layout —
24
+ // they are transient, so they never take a (frozen) column assignment.
25
+ .data-panel-masonry-placeholders
26
+ display: flex
27
+ flex-direction: column
28
+ gap: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px))
29
+ margin-top: var(--data-panel-masonry-row-gap, var(--data-panel-item-gap, 8px))
package/src/masonry.ts ADDED
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Masonry scroll body for the `DataPanel` — variable-height cards laid out in
3
+ * equal-width columns, balanced by *measured* height rather than a flat
4
+ * estimate or CSS multi-column.
5
+ *
6
+ * The problem it solves is paging: CSS `columns` re-flows the whole list every
7
+ * time a page is appended, so the cards under the user's cursor move. Here each
8
+ * item is placed in the running-shortest column **once**, keyed by its React
9
+ * key, and then frozen — appending a page never reshuffles what is on screen.
10
+ *
11
+ * Placement is measured: a freshly-appended batch mounts in provisional
12
+ * columns, a `useLayoutEffect` reads each card's real `offsetHeight`, then the
13
+ * batch is greedily assigned from those real heights and re-rendered — all
14
+ * before paint, so only the balanced result is seen.
15
+ *
16
+ * Two things keep the balance honest over many pages:
17
+ *
18
+ * - **Placeholders are not items.** The panel's loading skeletons arrive as
19
+ * `placeholders`, not `children`, and render below the columns. Freezing a
20
+ * column assignment for a skeleton (measured at skeleton height, then
21
+ * replaced by real content) is what makes a masonry drift, one page at a
22
+ * time, into "this whole page went into one column".
23
+ * - **Identity is the React key, not the array index.** A sort, filter or
24
+ * refresh replaces the keys, and assignments for keys that are gone are
25
+ * pruned — so column heights are always recomputed from items that are
26
+ * actually on screen.
27
+ */
28
+ import h from "./masonry.module.sass";
29
+ import {
30
+ Children,
31
+ cloneElement,
32
+ isValidElement,
33
+ ReactElement,
34
+ ReactNode,
35
+ useEffect,
36
+ useLayoutEffect,
37
+ useReducer,
38
+ useRef,
39
+ useState,
40
+ } from "react";
41
+ import type { ScrollBodyProps } from "./data-panel";
42
+
43
+ /** Height assumed for an item that hasn't been measured yet (it always is, by
44
+ * the time it matters — this only guards a torn-down/hidden container). */
45
+ const FALLBACK_ITEM_HEIGHT = 160;
46
+
47
+ export interface MasonryOptions {
48
+ /** Number of columns (the maximum, when `minColumnWidth` is set). Default 2. */
49
+ columns?: number;
50
+ /** If set, the column count drops below `columns` when the container is too
51
+ * narrow to give every column at least this many pixels. */
52
+ minColumnWidth?: number;
53
+ }
54
+
55
+ interface MasonryState {
56
+ /** Column count the current assignments were computed for. */
57
+ columns: number;
58
+ /** Frozen key → column. */
59
+ assign: Map<string, number>;
60
+ /** Last measured height per key. */
61
+ heights: Map<string, number>;
62
+ /** Mounted element per key, for measurement. */
63
+ els: Map<string, HTMLElement>;
64
+ /** Stable ref callbacks, so an item isn't detached/reattached every render. */
65
+ refs: Map<string, (el: HTMLElement | null) => void>;
66
+ }
67
+
68
+ /**
69
+ * A `scrollBody` component for `DataPanel` with the default two columns. For
70
+ * anything else — a different column count, or responsive columns — build one
71
+ * with `createMasonryScrollBody`.
72
+ */
73
+ export function MasonryScrollBody(props: ScrollBodyProps & MasonryOptions) {
74
+ const { children, placeholders, columns = 2, minColumnWidth } = props;
75
+
76
+ const containerRef = useRef<HTMLDivElement | null>(null);
77
+ const nCols = useColumnCount(containerRef, columns, minColumnWidth);
78
+
79
+ const stateRef = useRef<MasonryState | null>(null);
80
+ stateRef.current ??= {
81
+ columns: nCols,
82
+ assign: new Map(),
83
+ heights: new Map(),
84
+ els: new Map(),
85
+ refs: new Map(),
86
+ };
87
+ const state = stateRef.current;
88
+ const [, bump] = useReducer((x: number) => x + 1, 0);
89
+
90
+ const items = Children.toArray(children).filter(
91
+ isValidElement,
92
+ ) as ReactElement[];
93
+
94
+ // Runs on every commit (no deps): measurement has to see the layout that was
95
+ // just produced, including one caused by a resize or a card's own content
96
+ // settling. It is cheap when nothing is unassigned, and re-renders only when
97
+ // it actually assigns something — so there's no render loop.
98
+ useLayoutEffect(() => {
99
+ // A column-count change invalidates every assignment (a column may no
100
+ // longer exist). Handled here, not in render, so render stays pure.
101
+ if (state.columns !== nCols) {
102
+ state.columns = nCols;
103
+ state.assign.clear();
104
+ }
105
+
106
+ for (const [key, el] of state.els) state.heights.set(key, el.offsetHeight);
107
+
108
+ const present = new Set(items.map(keyOf));
109
+ for (const key of [...state.assign.keys()]) {
110
+ if (!present.has(key)) state.assign.delete(key);
111
+ }
112
+ for (const key of [...state.heights.keys()]) {
113
+ if (!present.has(key)) state.heights.delete(key);
114
+ }
115
+
116
+ const unassigned = items.filter((c) => !state.assign.has(keyOf(c)));
117
+ if (unassigned.length === 0) return;
118
+
119
+ // Column heights from the items already frozen into them…
120
+ const colHeights = new Array(nCols).fill(0);
121
+ for (const [key, col] of state.assign) {
122
+ colHeights[col] += state.heights.get(key) ?? 0;
123
+ }
124
+ // …then greedily place the new batch by its just-measured real heights.
125
+ for (const child of unassigned) {
126
+ const key = keyOf(child);
127
+ let col = 0;
128
+ for (let c = 1; c < nCols; c++) {
129
+ if (colHeights[c] < colHeights[col]) col = c;
130
+ }
131
+ state.assign.set(key, col);
132
+ colHeights[col] += state.heights.get(key) ?? FALLBACK_ITEM_HEIGHT;
133
+ }
134
+ bump(); // move the new batch into its balanced columns, before paint
135
+ });
136
+
137
+ // Items without an assignment yet render in a provisional column so they
138
+ // mount and can be measured; the layout effect above then places them.
139
+ const stale = state.columns !== nCols;
140
+ const columnItems: ReactNode[][] = Array.from({ length: nCols }, () => []);
141
+ items.forEach((child, i) => {
142
+ const key = keyOf(child);
143
+ let assigned: number | undefined = undefined;
144
+ if (!stale) {
145
+ assigned = state.assign.get(key);
146
+ }
147
+ const col = assigned ?? i % nCols;
148
+ columnItems[col].push(
149
+ cloneElement(child, { ref: refFor(state, key) } as any),
150
+ );
151
+ });
152
+
153
+ return h("div.data-panel-masonry-body", [
154
+ h(
155
+ "div.data-panel-masonry",
156
+ { ref: containerRef },
157
+ columnItems.map((col, c) =>
158
+ h("div.data-panel-masonry-column", { key: c }, col),
159
+ ),
160
+ ),
161
+ h.if(placeholders != null)(
162
+ "div.data-panel-masonry-placeholders",
163
+ placeholders,
164
+ ),
165
+ ]);
166
+ }
167
+
168
+ /** Build a `scrollBody` masonry component with a fixed or responsive column
169
+ * count: `scrollBody: createMasonryScrollBody({ columns: 3 })`. */
170
+ export function createMasonryScrollBody(options: MasonryOptions = {}) {
171
+ return function MasonryScrollBodyWithOptions(props: ScrollBodyProps) {
172
+ return h(MasonryScrollBody, { ...options, ...props });
173
+ };
174
+ }
175
+
176
+ function keyOf(child: ReactElement): string {
177
+ return String(child.key);
178
+ }
179
+
180
+ /** One stable ref callback per key — a fresh closure each render would detach
181
+ * and reattach every card on every render. */
182
+ function refFor(state: MasonryState, key: string) {
183
+ let cb = state.refs.get(key);
184
+ if (cb == null) {
185
+ cb = (el: HTMLElement | null) => {
186
+ if (el == null) {
187
+ state.els.delete(key);
188
+ } else {
189
+ state.els.set(key, el);
190
+ }
191
+ };
192
+ state.refs.set(key, cb);
193
+ }
194
+ return cb;
195
+ }
196
+
197
+ /** The effective column count: `columns`, reduced to fit `minColumnWidth`. */
198
+ function useColumnCount(
199
+ ref: { current: HTMLElement | null },
200
+ columns: number,
201
+ minColumnWidth: number | undefined,
202
+ ): number {
203
+ const [width, setWidth] = useState<number | null>(null);
204
+
205
+ useEffect(() => {
206
+ const el = ref.current;
207
+ if (minColumnWidth == null || el == null) return;
208
+ const obs = new ResizeObserver(([entry]) => {
209
+ setWidth(entry.contentRect.width);
210
+ });
211
+ obs.observe(el);
212
+ return () => obs.disconnect();
213
+ }, [minColumnWidth]);
214
+
215
+ if (minColumnWidth == null || width == null) return Math.max(1, columns);
216
+ return Math.max(1, Math.min(columns, Math.floor(width / minColumnWidth)));
217
+ }