{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-pinned-rows",
  "title": "Data Grid Pinned Rows",
  "author": "gridcn",
  "description": "Pinned top/bottom row bands add-on for the gridcn data grid: useDataGridPinnedRows registers a rowBands spec (e.g. a totals row) that stays sticky under the header or at the viewport's bottom edge, pixel-aligned with data rows and pinned columns. useDataGridAggregate computes filter-aware sum/avg/min/max/count for those bands, and useDataGridServerAggregate shows values a server computes for the whole result.",
  "dependencies": [
    "zustand@^5.0.15"
  ],
  "registryDependencies": [
    "@gridcn/data-grid"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/data-grid-pinned-rows.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\r\nexport { useDataGridPinnedRows, type UseDataGridPinnedRowsOptions, type UseDataGridPinnedRowsResult } from \"./use-data-grid-pinned-rows\";\r\nexport {\r\n  aggregateRow,\r\n  serverAggregateRow,\r\n  type AggregateRowOptions,\r\n  type PinnedRowSource,\r\n  type ServerAggregateRowOptions,\r\n} from \"./pinned-row-source\";\r\nexport {\r\n  useDataGridAggregate,\r\n  DataGridAggregateReporter,\r\n  type AggregateReducer,\r\n  type AggregateSpecs,\r\n  type UseDataGridAggregateOptions,\r\n  type DataGridAggregateReporterProps,\r\n} from \"./use-data-grid-aggregate\";\r\nexport {\r\n  useDataGridServerAggregate,\r\n  DataGridServerAggregateReporter,\r\n  PENDING_SERVER_AGGREGATE,\r\n  type FetchAggregatesRequest,\r\n  type ServerAggregateResult,\r\n  type ServerAggregateStatus,\r\n  type UseDataGridServerAggregateOptions,\r\n  type DataGridServerAggregateReporterProps,\r\n} from \"./use-data-grid-server-aggregate\";\r\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/data-grid-pinned-rows.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/use-data-grid-pinned-rows.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { DataGridPlugin, RowBandRenderCtx } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { DataGridPinnedRowBand } from \"./pinned-row-band\";\nimport { forwardSource, isPinnedRowSource, type PinnedRowSource } from \"./pinned-row-source\";\nimport { PENDING_SERVER_AGGREGATE, type ServerAggregateResult, type ServerAggregateStatus } from \"./use-data-grid-server-aggregate\";\n\n/** Options for {@link useDataGridPinnedRows}. */\nexport type UseDataGridPinnedRowsOptions = {\n  /** Rows pinned in a sticky band directly under the header, a SEPARATE array from `data`, not indices into it. An `aggregateRow` or `serverAggregateRow` entry shows computed totals; any other entry is a row object. Omit (or pass `[]`) for no top band. */\n  topRows?: readonly unknown[];\n  /** Rows pinned in a sticky band at the viewport's bottom edge; see {@link UseDataGridPinnedRowsOptions.topRows}. */\n  bottomRows?: readonly unknown[];\n  /** Marks both bands while server values load, go stale, or fail: the bands dim and set `data-status`, and set `aria-busy` only while values load or go stale. Default: the status of the band's `serverAggregateRow` entries, else `\"ready\"`. */\n  status?: ServerAggregateStatus;\n};\n\n/** Return value of {@link useDataGridPinnedRows}. */\nexport type UseDataGridPinnedRowsResult = {\n  /** Pass this into the grid's `plugins` prop (`plugins={[pinnedRows.plugin]}`). Stable across renders while `topRows` and `bottomRows` keep the same entries (a plain row object by its own values, an `aggregateRow` or `serverAggregateRow` by its content, so an inline array, an inline `aggregateRow`, and an inline `serverAggregateRow` are fine, also with inline functions) and `status` stays the same. */\n  plugin: DataGridPlugin<unknown>;\n  /** The result of each `serverAggregateRow` entry (`row`, `status`, `error`, `loading`, `refresh()`, `retry()`), top band first, in entry order. Empty without such an entry. Each result starts as `PENDING_SERVER_AGGREGATE` until the band mounts. */\n  serverAggregates: readonly ServerAggregateResult[];\n};\n\n/** Holds the results that the bands report as an immutable map; a result is cleared when its row unmounts. */\nclass ServerResults {\n  private results: ReadonlyMap<PinnedRowSource, ServerAggregateResult> = new Map();\n  private listeners = new Set<() => void>();\n\n  subscribe = (listener: () => void) => {\n    this.listeners.add(listener);\n    return () => void this.listeners.delete(listener);\n  };\n  getSnapshot = () => this.results;\n  report = (source: PinnedRowSource, result: ServerAggregateResult | undefined) => {\n    if (this.results.get(source) === result) return;\n    const next = new Map(this.results);\n    if (result) next.set(source, result);\n    else next.delete(source);\n    this.results = next;\n    this.listeners.forEach((listener) => listener());\n  };\n}\n\nconst EMPTY_ROWS: readonly never[] = [];\n\nconst valueIds = new WeakMap<object, number>();\nlet nextValueId = 0;\n\nfunction valueKey(value: unknown): string {\n  if (typeof value === \"string\") return JSON.stringify(value);\n  if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return `${typeof value}:${String(value)}`;\n  let id = valueIds.get(value);\n  if (id === undefined) valueIds.set(value, (id = nextValueId++));\n  return `#${id}`;\n}\n\n/** Equal own keys and values give equal keys; with `skipFunctions`, every function gives the same key. */\nfunction shallowKey(record: object | undefined, skipFunctions = false): string {\n  if (record === undefined) return \"-\";\n  const parts = Object.entries(record).map(([key, value]) => `${JSON.stringify(key)}=${skipFunctions && typeof value === \"function\" ? \"fn\" : valueKey(value)}`);\n  return `{${parts.sort().join(\",\")}}`;\n}\n\nfunction entryKey(entry: unknown): string {\n  if (!isPinnedRowSource(entry)) return typeof entry === \"object\" && entry !== null && Object.getPrototypeOf(entry) === Object.prototype ? `row${shallowKey(entry)}` : valueKey(entry);\n  if (entry.kind === \"aggregate\") return `aggregate${JSON.stringify(entry.scope)}${shallowKey(entry.cells)}${shallowKey(entry.specs, true)}`;\n  return `server${shallowKey(entry.cells)}${shallowKey(entry.options, true)}`;\n}\n\nclass EntriesHolder {\n  private key: string | null = null;\n  private rows: readonly unknown[] = EMPTY_ROWS;\n\n  /** The rows held for `key`: the last rows with an equal key, so a new array of equal entries keeps the identity. */\n  hold(key: string, rows: readonly unknown[]): readonly unknown[] {\n    if (key !== this.key) [this.key, this.rows] = [key, rows];\n    return this.rows;\n  }\n}\n\n// Keyed by content and held outside state, so an entry that changes on every render gives a new array instead of a render loop.\nfunction useStableEntries(rows: readonly unknown[]): readonly unknown[] {\n  const [holder] = useState(() => new EntriesHolder());\n  const held = holder.hold(rows.map(entryKey).join(\"|\"), rows);\n  useLayoutEffect(() => {\n    held.forEach((entry, i) => {\n      if (isPinnedRowSource(entry) && isPinnedRowSource(rows[i])) forwardSource(entry, rows[i]);\n    });\n  });\n  return held;\n}\n\nfunction useWarnSharedServerRow(topRows: readonly unknown[], bottomRows: readonly unknown[]): void {\n  const warned = useRef(false);\n  useEffect(() => {\n    if (!isDev() || warned.current) return;\n    const seen = new Set<unknown>();\n    for (const entry of [...topRows, ...bottomRows]) {\n      if (!isPinnedRowSource(entry) || entry.kind !== \"server-aggregate\") continue;\n      if (seen.has(entry)) {\n        warned.current = true;\n        console.warn(\"[data-grid-pinned-rows] one serverAggregateRow is pinned more than once, so it fetches once per place. Create a second serverAggregateRow, or pin it once.\");\n        return;\n      }\n      seen.add(entry);\n    }\n  }, [topRows, bottomRows]);\n}\n\n/**\n * Pinned top/bottom row bands, as a single hook. Row bands affect layout height and `aria-rowcount`,\n * so the grid resolves the band row counts synchronously at first render (root.tsx keeps all of\n * that arithmetic and calls this plugin's `rowBands.render` per band segment). Cells render via the\n * same `DataGridCell`/cell-type pipeline as data rows (same columns, alignment, formatting) but\n * never edit: they have no pointer, click, or double-click handlers and no tab stop, so they are not\n * keyboard-navigable. A column's `readOnly: false` changes only their `data-readonly` attribute, unless the column has no `accessorKey` and no `setValue`.\n */\nexport function useDataGridPinnedRows(options: UseDataGridPinnedRowsOptions = {}): UseDataGridPinnedRowsResult {\n  const { status } = options;\n  const topRows = useStableEntries(options.topRows ?? EMPTY_ROWS);\n  const bottomRows = useStableEntries(options.bottomRows ?? EMPTY_ROWS);\n  useWarnSharedServerRow(topRows, bottomRows);\n  const [serverResults] = useState(() => new ServerResults());\n  const results = useSyncExternalStore(serverResults.subscribe, serverResults.getSnapshot, serverResults.getSnapshot);\n  const serverAggregates = useMemo(\n    () => [...topRows, ...bottomRows].filter(isPinnedRowSource).flatMap((entry) => (entry.kind === \"server-aggregate\" ? [results.get(entry) ?? PENDING_SERVER_AGGREGATE] : [])),\n    [topRows, bottomRows, results],\n  );\n  const plugin = useMemo<DataGridPlugin<unknown>>(\n    () => ({\n      name: \"pinned-rows\",\n      rowBands: {\n        top: topRows,\n        bottom: bottomRows,\n        render: (ctx: RowBandRenderCtx) => renderPinnedRowBand(ctx, status, serverResults.report),\n      },\n    }),\n    [topRows, bottomRows, status, serverResults],\n  );\n\n  return { plugin, serverAggregates };\n}\n\nfunction renderPinnedRowBand(ctx: RowBandRenderCtx, status: ServerAggregateStatus | undefined, onServerResult: (source: PinnedRowSource, result: ServerAggregateResult | undefined) => void) {\n  const { position, rows, renderedColumns, layout, rowHeight, template, headerHeight, ariaRowIndexBase } = ctx;\n  return (\n    <DataGridPinnedRowBand\n      position={position}\n      rows={rows}\n      renderedColumns={renderedColumns}\n      layout={layout}\n      rowHeight={rowHeight}\n      template={template}\n      headerHeight={headerHeight}\n      ariaRowIndexBase={ariaRowIndexBase}\n      status={status}\n      onServerResult={onServerResult}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/use-data-grid-pinned-rows.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/pinned-row.tsx",
      "content": "\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { DataGridCell } from \"@/registry/default/components/data-grid/data-grid\";\nimport type { GridColumnLayout, RenderedColumn } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { useDataGridSelector, type DataGridStoreState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\nexport type DataGridPinnedRowProps = {\n  /** The band this row belongs to; part of the fallback row id. */\n  position: \"top\" | \"bottom\";\n  /** The consumer-supplied pinned row object (from `useDataGridPinnedRows`'s `topRows`/`bottomRows` options — never a member of `data`). */\n  row: unknown;\n  /** Position within its own band, 0-based — the `data-grid-pinned-row-index` marker and the `getRowId` index argument of the row's resolved id; never `ViewCoord`/`aria-colindex` (pinned rows aren't in the data index space). */\n  bandIndex: number;\n  renderedColumns: readonly RenderedColumn[];\n  layout: GridColumnLayout;\n  gridRowStart: number;\n  /** Root's aria index layout: header rows, pinned-top next, then data rows, pinned-bottom last. */\n  ariaRowIndex: number;\n  /** Read each cell from `row[column.id]` instead of the column's accessor. Default `false`. */\n  byColumnId?: boolean;\n  className?: string;\n};\n\nconst byIdColumns = new WeakMap<object, RenderedColumn[\"column\"]>();\n\nfunction readByColumnId(column: RenderedColumn[\"column\"]): RenderedColumn[\"column\"] {\n  let derived = byIdColumns.get(column);\n  if (!derived) {\n    derived = { ...column, accessorKey: column.id, accessorFn: undefined } as RenderedColumn[\"column\"];\n    byIdColumns.set(column, derived);\n  }\n  return derived;\n}\n\nfunction resolvePinnedRowId(getRowId: DataGridStoreState[\"getRowId\"], row: unknown, bandIndex: number, position: \"top\" | \"bottom\"): string {\n  let id: unknown;\n  try {\n    id = getRowId(row, bandIndex);\n  } catch {\n    id = undefined;\n  }\n  return typeof id === \"string\" && id !== \"\" ? id : `__pinned-${position}-${bandIndex}`;\n}\n\n/**\n * A pinned top/bottom band row: reuses\n  * `DataGridCell` in its `pinnedRow` mode for identical cell-type rendering/alignment/column tracks as\n * data rows, but bypasses `DataGridRow`'s `useDataGridRow(viewRowIndex)` store lookup entirely —\n * pinned rows are a separate array the consumer supplies to `useDataGridPinnedRows`, not indices\n * into `data`/`viewIndex`, so they never sort, filter, or participate in range selection or the\n * rows-channel (documented v1 scope). Not memoized like `DataGridRow`: pinned bands are always\n * fully rendered (never virtualized — a handful of totals/frozen rows, not tens of\n * thousands), so there's no window-shift-driven re-render pressure to protect against.\n */\nexport function DataGridPinnedRow(props: DataGridPinnedRowProps): ReactNode {\n  const { position, row, bandIndex, renderedColumns, layout, gridRowStart, ariaRowIndex, byColumnId = false, className } = props;\n  const getRowId = useDataGridSelector((s) => s.getRowId);\n  // Pinned rows such as aggregates often carry no id, so a throwing or empty getRowId falls back to a band id.\n  const rowId = resolvePinnedRowId(getRowId, row, bandIndex, position);\n  const markerColOffset = layout.markerWidth > 0 ? 2 : 1;\n  return (\n    <div\n      role=\"row\"\n      aria-rowindex={ariaRowIndex}\n      data-grid-pinned-row-index={bandIndex}\n      className={cn(\"group/row\", className)}\n      style={{\n        display: \"grid\",\n        gridTemplateColumns: \"subgrid\",\n        gridColumn: \"1 / -1\",\n        gridRowStart,\n      }}\n    >\n      {renderedColumns.map(({ column, index }) => (\n        <DataGridCell\n          key={column.id}\n          row={row}\n          rowId={rowId}\n          viewRowIndex={bandIndex}\n          column={byColumnId ? readByColumnId(column) : column}\n          viewColumnIndex={index}\n          gridColOffset={markerColOffset}\n          pinnedRow\n        />\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/pinned-row.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/pinned-row-band.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useState, type CSSProperties, type ReactNode } from \"react\";\nimport { GRID_LAYER, type GridColumnLayout, type RenderedColumn } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { cn } from \"@/lib/utils\";\nimport { DataGridPinnedRow } from \"./pinned-row\";\nimport { isPinnedRowSource, type PinnedRowSource } from \"./pinned-row-source\";\nimport { DataGridPinnedSourceRow } from \"./pinned-source-row\";\nimport type { ServerAggregateResult, ServerAggregateStatus } from \"./use-data-grid-server-aggregate\";\n\nconst NO_STATUSES: ReadonlyMap<number, ServerAggregateStatus> = new Map();\nconst STATUS_PRECEDENCE: readonly ServerAggregateStatus[] = [\"loading\", \"stale\", \"error\"];\n\nfunction worstStatus(statuses: ReadonlyMap<number, ServerAggregateStatus>): ServerAggregateStatus {\n  const values = new Set(statuses.values());\n  return STATUS_PRECEDENCE.find((s) => values.has(s)) ?? \"ready\";\n}\n\n/** Props for {@link DataGridPinnedRowBand}. */\nexport type DataGridPinnedRowBandProps = {\n  position: \"top\" | \"bottom\";\n  rows: readonly unknown[];\n  renderedColumns: readonly RenderedColumn[];\n  layout: GridColumnLayout;\n  rowHeight: number;\n  template: string;\n  /** The sticky header track's own height (not including this or any pinned band) — where the top band's `insetBlockStart` lands, directly under the header. */\n  headerHeight: number;\n  /**\n   * `aria-rowindex` base for this band's rows (root's aria index layout: header rows, pinned-top\n   * next, then data rows, pinned-bottom last). Top band: `1 + headerRowCount` (right after the header\n   * rows, `2` without column groups), plus the rows of earlier top bands. Bottom band: after every\n   * pinned-top and data row — root computes both bases and passes them through `RowBandRenderCtx`.\n   */\n  ariaRowIndexBase: number;\n  /** Server value state: anything but `\"ready\"` dims the band; `\"loading\"` and `\"stale\"` set `aria-busy`. Default: the status of the band's `serverAggregateRow` entries, else `\"ready\"`. */\n  status?: ServerAggregateStatus;\n  /** Receives the result of each `serverAggregateRow` entry, and `undefined` when its row unmounts. */\n  onServerResult?: (source: PinnedRowSource, result: ServerAggregateResult | undefined) => void;\n};\n\n/**\n * A pinned-row sticky band: same layering as core's header layer — absolutely positioned inside\n * the sticky Viewport, counter-translated horizontally by the live scroll var so its cells track\n * the column canvas 1:1, but never moves vertically (rows canvas is the only vertically-scrolling\n * layer). The top band sits directly under the header; the bottom band sits flush with the\n * viewport's bottom edge (`insetBlockEnd: 0`) — both stay \"in place\" while data rows scroll\n * underneath, which is what core's frozen-edge shadow (root.tsx) keys off of.\n * `useDataGridPinnedRows`'s `rowBands.render` calls this once per non-empty band.\n */\nexport function DataGridPinnedRowBand(props: DataGridPinnedRowBandProps): ReactNode {\n  const { position, rows, renderedColumns, layout, rowHeight, template, headerHeight, ariaRowIndexBase } = props;\n  const [sourceStatuses, setSourceStatuses] = useState(NO_STATUSES);\n  const reportStatus = useCallback((bandIndex: number, next: ServerAggregateStatus | undefined) => {\n    setSourceStatuses((prev) => {\n      if (prev.get(bandIndex) === next) return prev;\n      const map = new Map(prev);\n      if (next === undefined) map.delete(bandIndex);\n      else map.set(bandIndex, next);\n      return map;\n    });\n  }, []);\n  const status = props.status ?? worstStatus(sourceStatuses);\n  if (rows.length === 0) return null;\n\n  const bandHeight = rows.length * rowHeight;\n  const layerStyle: CSSProperties = {\n    position: \"absolute\",\n    insetInlineStart: 0,\n    display: \"grid\",\n    gridTemplateColumns: template,\n    gridAutoRows: `${rowHeight}px`,\n    height: bandHeight,\n    // stacking context, same reasoning as header.tsx's own zIndex comment — must paint above the\n    // rows canvas in DOM order regardless of scroll-driven transforms; below the header (zIndex 4).\n    zIndex: GRID_LAYER.pinnedRowBand,\n    // --grid-dir (-1 LTR, 1 RTL) signs the horizontal term, same as core's header/canvas layers:\n    // the grid tracks mirror themselves under dir=rtl but transforms stay physical.\n    transform: \"translate3d(calc(var(--grid-dir, -1) * var(--grid-scroll-left, 0px)), 0, 0)\",\n    ...(position === \"top\" ? { insetBlockStart: headerHeight } : { insetBlockEnd: 0 }),\n  };\n\n  return (\n    <div\n      role=\"rowgroup\"\n      data-grid-pinned-row-band={position}\n      data-status={status}\n      aria-busy={status === \"loading\" || status === \"stale\" ? true : undefined}\n      className={cn(status !== \"ready\" && \"opacity-60\", status === \"loading\" && \"motion-safe:animate-pulse\")}\n      style={layerStyle}\n    >\n      {rows.map((row, i) => {\n        const rowProps = {\n          position,\n          bandIndex: i,\n          renderedColumns,\n          layout,\n          gridRowStart: i + 1,\n          ariaRowIndex: ariaRowIndexBase + i,\n          className: position === \"bottom\" ? \"border-t border-border\" : undefined,\n        };\n        // oxlint-disable-next-line react/no-array-index-key -- a pinned row id can be a band id; band position is a stable key for a small consumer array.\n        return isPinnedRowSource(row) ? <DataGridPinnedSourceRow key={i} {...rowProps} source={row} onStatus={reportStatus} onResult={props.onServerResult} /> : <DataGridPinnedRow key={i} {...rowProps} row={row} />;\n      })}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/pinned-row-band.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/pinned-row-source.ts",
      "content": "import type { AggregateSpecs, UseDataGridAggregateOptions } from \"./use-data-grid-aggregate\";\nimport type { UseDataGridServerAggregateOptions } from \"./use-data-grid-server-aggregate\";\n\n/** Options of {@link aggregateRow}. */\nexport type AggregateRowOptions = UseDataGridAggregateOptions & {\n  /** Fixed cell values by column id, such as the row id and a label. Aggregated values replace a cell of the same column id. */\n  cells?: Record<string, unknown>;\n};\n\n/** Options of {@link serverAggregateRow}. */\nexport type ServerAggregateRowOptions = UseDataGridServerAggregateOptions & {\n  /** Fixed cell values by column id, such as the row id and a label. Fetched values replace a cell of the same column id. */\n  cells?: Record<string, unknown>;\n};\n\n/** A pinned row whose values the band computes inside the grid. Build one with {@link aggregateRow} or {@link serverAggregateRow}. */\nexport type PinnedRowSource =\n  | Readonly<{ kind: \"aggregate\"; specs: AggregateSpecs<never>; scope: NonNullable<UseDataGridAggregateOptions[\"scope\"]>; cells: Readonly<Record<string, unknown>> | undefined }>\n  | Readonly<{ kind: \"server-aggregate\"; options: ServerAggregateRowOptions; cells: Readonly<Record<string, unknown>> | undefined }>;\n\n/** Equal own keys and values; with `skipFunctions`, any two functions count as equal. */\nexport function shallowEqual(a: object | undefined, b: object | undefined, skipFunctions = false): boolean {\n  if (a === b) return true;\n  if (a === undefined || b === undefined) return false;\n  const keysA = Object.keys(a);\n  const keysB = Object.keys(b);\n  return (\n    keysA.length === keysB.length &&\n    keysA.every((key) => {\n      const [valueA, valueB] = [(a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]];\n      return Object.hasOwn(b, key) && (Object.is(valueA, valueB) || (skipFunctions && typeof valueA === \"function\" && typeof valueB === \"function\"));\n    })\n  );\n}\n\nconst SOURCES = new WeakSet<object>();\n\n/** The newest equal source of a held one, so an inline source with new function identities keeps its band and calls the newest functions. */\nconst LATEST_SOURCE = new WeakMap<object, PinnedRowSource>();\n\nconst REDUCER_VERSIONS = new WeakMap<object, number>();\nconst REDUCER_LISTENERS = new WeakMap<object, Set<() => void>>();\n\nfunction reducerChanged(a: AggregateSpecs<never>, b: AggregateSpecs<never>): boolean {\n  return Object.keys(b).some((key) => typeof b[key] === \"function\" && a[key] !== b[key]);\n}\n\n/** Points `held` at `next`, an equal source from a later render; a new reducer function makes the band reduce again. */\nexport function forwardSource(held: PinnedRowSource, next: PinnedRowSource): void {\n  if (held === next || held.kind !== next.kind) return;\n  const previous = latestOf(held);\n  LATEST_SOURCE.set(held, next);\n  if (previous.kind !== \"aggregate\" || next.kind !== \"aggregate\" || !reducerChanged(previous.specs, next.specs)) return;\n  REDUCER_VERSIONS.set(held, (REDUCER_VERSIONS.get(held) ?? 0) + 1);\n  REDUCER_LISTENERS.get(held)?.forEach((listener) => listener());\n}\n\n/** Counts the reducer function changes forwarded to `source`. */\nexport function reducerVersion(source: PinnedRowSource): number {\n  return REDUCER_VERSIONS.get(source) ?? 0;\n}\n\n/** Calls `listener` after a reducer function of `source` changes; returns the unsubscribe. */\nexport function subscribeReducers(source: PinnedRowSource, listener: () => void): () => void {\n  let listeners = REDUCER_LISTENERS.get(source);\n  if (!listeners) {\n    listeners = new Set();\n    REDUCER_LISTENERS.set(source, listeners);\n  }\n  listeners.add(listener);\n  return () => listeners.delete(listener);\n}\n\nfunction latestOf<K extends PinnedRowSource[\"kind\"]>(source: Extract<PinnedRowSource, { kind: K }>): Extract<PinnedRowSource, { kind: K }> {\n  return (LATEST_SOURCE.get(source) as Extract<PinnedRowSource, { kind: K }> | undefined) ?? source;\n}\n\n/** The options of `source` with `fetchAggregates` and `onError` that call the newest ones. */\nexport function liveServerOptions(source: Extract<PinnedRowSource, { kind: \"server-aggregate\" }>): UseDataGridServerAggregateOptions {\n  return { ...source.options, fetchAggregates: (request) => latestOf(source).options.fetchAggregates(request), onError: (error) => latestOf(source).options.onError?.(error) };\n}\n\n/** The specs of `source` with each reducer function calling the newest one; a new `version` gives new function identities, so the aggregate reduces again. */\nexport function liveSpecs(source: Extract<PinnedRowSource, { kind: \"aggregate\" }>, _version = 0): AggregateSpecs<never> {\n  return Object.fromEntries(\n    Object.entries(source.specs).map(([key, reducer]) => [\n      key,\n      typeof reducer === \"function\" ? (values: readonly unknown[], rows: readonly never[]) => (latestOf(source).specs[key] as typeof reducer)(values, rows) : reducer,\n    ]),\n  );\n}\n\nfunction register<T extends PinnedRowSource>(source: T): T {\n  Object.freeze(source);\n  SOURCES.add(source);\n  return source;\n}\n\n/** True for a value built by {@link aggregateRow} or {@link serverAggregateRow}. */\nexport function isPinnedRowSource(value: unknown): value is PinnedRowSource {\n  return typeof value === \"object\" && value !== null && SOURCES.has(value);\n}\n\n/**\n * A pinned totals row that reduces `specs` over the grid's rows (see {@link useDataGridAggregate}). Put it in\n * `useDataGridPinnedRows`'s `topRows` or `bottomRows`. The band reads each value by column id, so it needs no\n * `accessorKey` that matches the id. An inline call is fine: equal specs, `scope`, and `cells` keep the band. A reducer\n * function with a new identity keeps the band but reduces again, so define the reducer at module scope or memoize it.\n */\nexport function aggregateRow<TData = unknown>(specs: AggregateSpecs<TData>, options: AggregateRowOptions = {}): PinnedRowSource {\n  const { scope = \"view\", cells } = options;\n  // Boundary cast: the source keeps specs for any row type; the band hands them back to the aggregate engine untouched.\n  return register({ kind: \"aggregate\", specs: specs as AggregateSpecs<never>, scope, cells: cells && Object.freeze({ ...cells }) });\n}\n\n/**\n * A pinned totals row whose values come from a server (see {@link useDataGridServerAggregate}). Put it in one band\n * of `useDataGridPinnedRows`. The band dims while values load, and fetches again after pending saves settle.\n * An inline call is fine: equal options and `cells` keep the band, and the band calls the newest `fetchAggregates` and `onError`.\n */\nexport function serverAggregateRow(options: ServerAggregateRowOptions): PinnedRowSource {\n  const { cells, ...rest } = options;\n  return register({ kind: \"server-aggregate\", options: rest, cells: cells && Object.freeze({ ...cells }) });\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/pinned-row-source.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/pinned-source-row.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useLayoutEffect, useMemo, useSyncExternalStore, type ReactNode } from \"react\";\nimport { DataGridPinnedRow, type DataGridPinnedRowProps } from \"./pinned-row\";\nimport { liveServerOptions, liveSpecs, reducerVersion, subscribeReducers, type PinnedRowSource } from \"./pinned-row-source\";\nimport { useDataGridAggregate } from \"./use-data-grid-aggregate\";\nimport { useDataGridServerAggregate, type ServerAggregateResult, type ServerAggregateStatus } from \"./use-data-grid-server-aggregate\";\n\ntype SourceRowProps = Omit<DataGridPinnedRowProps, \"row\" | \"byColumnId\"> & {\n  source: PinnedRowSource;\n  /** Reports the source's server status to the band; clears it on unmount. */\n  onStatus: (bandIndex: number, status: ServerAggregateStatus | undefined) => void;\n  /** Reports the full server result to `useDataGridPinnedRows`; clears it on unmount. */\n  onResult?: (source: PinnedRowSource, result: ServerAggregateResult | undefined) => void;\n};\n\nfunction withCells(cells: Readonly<Record<string, unknown>> | undefined, values: Record<string, unknown>): Record<string, unknown> {\n  return cells ? { ...cells, ...values } : values;\n}\n\nfunction AggregateSourceRow(props: SourceRowProps & { source: Extract<PinnedRowSource, { kind: \"aggregate\" }> }): ReactNode {\n  const { source, onStatus: _onStatus, onResult: _onResult, ...rowProps } = props;\n  const subscribe = useCallback((listener: () => void) => subscribeReducers(source, listener), [source]);\n  const version = useSyncExternalStore(subscribe, () => reducerVersion(source), () => reducerVersion(source));\n  const specs = useMemo(() => liveSpecs(source, version), [source, version]);\n  const values = useDataGridAggregate(specs, { scope: source.scope });\n  const row = useMemo(() => withCells(source.cells, values), [source.cells, values]);\n  return <DataGridPinnedRow {...rowProps} row={row} byColumnId />;\n}\n\nfunction ServerAggregateSourceRow(props: SourceRowProps & { source: Extract<PinnedRowSource, { kind: \"server-aggregate\" }> }): ReactNode {\n  const { source, onStatus, onResult, ...rowProps } = props;\n  const options = useMemo(() => liveServerOptions(source), [source]);\n  const result = useDataGridServerAggregate(options);\n  const row = useMemo(() => withCells(source.cells, result.row), [source.cells, result.row]);\n\n  const { bandIndex } = rowProps;\n  useLayoutEffect(() => {\n    onStatus(bandIndex, result.status);\n  }, [onStatus, bandIndex, result.status]);\n  useLayoutEffect(() => () => onStatus(bandIndex, undefined), [onStatus, bandIndex]);\n  useLayoutEffect(() => {\n    onResult?.(source, result);\n  }, [onResult, source, result]);\n  useLayoutEffect(() => () => onResult?.(source, undefined), [onResult, source]);\n\n  return <DataGridPinnedRow {...rowProps} row={row} byColumnId />;\n}\n\n/** One pinned band entry built by `aggregateRow` or `serverAggregateRow`; resolves its values inside the grid provider. */\nexport function DataGridPinnedSourceRow(props: SourceRowProps): ReactNode {\n  const { source } = props;\n  return source.kind === \"aggregate\" ? <AggregateSourceRow {...props} source={source} /> : <ServerAggregateSourceRow {...props} source={source} />;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/pinned-source-row.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/use-data-grid-aggregate.ts",
      "content": "\"use client\";\n\nimport { useLayoutEffect, useRef, type ReactNode } from \"react\";\nimport { useStore } from \"zustand\";\nimport { getCellValue, type AnyColumnDef } from \"@/registry/default/components/data-grid/data-grid\";\nimport { aggregateValues, isDev, leafViewOf, useDataGridStoreApi, type AggregateReducer, type AggregateSpecs, type DataGridReadState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { shallowEqual } from \"./pinned-row-source\";\n\nexport type { AggregateReducer, AggregateSpecs };\n\n/** Options for {@link useDataGridAggregate}. */\nexport type UseDataGridAggregateOptions = {\n  /** `\"view\"` (default) reduces over every row the sort and filter leave, all pages of a paged grid. `\"page\"` reduces over the shown page only. `\"all\"` reduces over the full `data` array, ignoring any active filter. */\n  scope?: \"view\" | \"page\" | \"all\";\n};\n\nfunction aggregateColumn<TData>(reducer: AggregateReducer<TData>, column: AnyColumnDef, rows: readonly unknown[]): unknown {\n  // Boundary cast: the store keeps rows as unknown[], the user's reducer gets them typed.\n  return aggregateValues(reducer, rows.map((row) => getCellValue(row, column)), rows as readonly TData[]);\n}\n\nconst warnedKinds = new WeakMap<object, Set<string>>();\n\n/** Dev-only warning, once per grid instance and kind. */\nfunction warnOnce(owner: object, kind: string, message: string): void {\n  if (!isDev()) return;\n  const kinds = warnedKinds.get(owner) ?? new Set<string>();\n  warnedKinds.set(owner, kinds);\n  if (kinds.has(kind)) return;\n  kinds.add(kind);\n  console.warn(message);\n}\n\nfunction warnSparseData(owner: object, scope: \"view\" | \"page\" | \"all\", holes: number): void {\n  warnOnce(\n    owner,\n    \"sparse\",\n    `[data-grid-pinned-rows] useDataGridAggregate (scope \"${scope}\") skipped ${holes} unloaded row(s): the data array is sparse (lazy loading), so the result covers loaded rows only. Use server-side totals or compute them outside the grid.`,\n  );\n}\n\nfunction warnUnknownSpecKey(owner: object, columnId: string): void {\n  warnOnce(\n    owner,\n    \"spec-key\",\n    `[data-grid-pinned-rows] useDataGridAggregate: spec key \"${columnId}\" matches no column id and is ignored (check for a typo)`,\n  );\n}\n\nfunction computeAggregate<TData>(owner: object, state: DataGridReadState, specs: AggregateSpecs<TData>, scope: \"view\" | \"page\" | \"all\"): Record<string, unknown> {\n  const byId = new Map(state.columns.map((c) => [c.id, c] as const));\n  const scoped = scope === \"all\" ? state.data : (scope === \"page\" ? state.viewIndex : leafViewOf(state)).filter((i) => i >= 0).map((i) => state.data[i]);\n  // group rows (entries below 0) are dropped above; undefined rows are unloaded holes of a lazy grid\n  const rows = scoped.filter((row) => row !== undefined);\n  if (rows.length !== scoped.length) warnSparseData(owner, scope, scoped.length - rows.length);\n  const result: [string, unknown][] = [];\n  for (const [columnId, reducer] of Object.entries(specs)) {\n    const column = byId.get(columnId);\n    if (!column) {\n      warnUnknownSpecKey(owner, columnId);\n      continue;\n    }\n    result.push([columnId, aggregateColumn(reducer, column, rows)]);\n  }\n  return Object.fromEntries(result);\n}\n\n/**\n * Filter-aware aggregation for pinned totals/summary rows: reduces `specs` over the\n * grid's own state and returns a plain `{ [columnId]: value }` object, usable as a\n * `useDataGridPinnedRows` `topRows`/`bottomRows` entry. Pinned cells read it through each column's\n * `accessorKey`/`accessorFn` like a data row, so a total shows only where `accessorKey` equals the\n * column id; remap it for other columns. The object carries no row id, so\n * a pinned band gives it a band id when `getRowId` cannot resolve one. Values are resolved through\n * `getCellValue`, so `accessorFn` columns aggregate correctly, not just plain fields. Defaults to\n * `scope: \"view\"`, every row the sort and filter leave across all pages; `\"page\"` reduces over the\n * shown page only, and `\"all\"` over the raw `data`, ignoring the active filter. Recomputes only when `viewIndex`, `data`,\n * `scope`, or an entry of `specs` changes (a named reducer by name, a function by identity), so\n * scrolling never recomputes and an inline `specs` object of named reducers is fine. A reducer\n * function defined in the render recomputes on every render; define it at module scope or memoize it.\n * `undefined` rows (unloaded holes of a lazy grid) are skipped and a dev warning fires once per grid — on a\n * lazy grid the result covers loaded rows only. A spec key that matches no column id is ignored\n * and a dev warning fires once per grid. `TData` types `rows` in custom reducers (see {@link AggregateReducer}).\n */\nexport function useDataGridAggregate<TData = unknown>(specs: AggregateSpecs<TData>, options: UseDataGridAggregateOptions = {}): Record<string, unknown> {\n  const { scope = \"view\" } = options;\n  const storeApi = useDataGridStoreApi();\n  const cache = useRef<{ viewIndex: number[]; data: readonly unknown[]; scope: string; specs: AggregateSpecs<TData>; result: Record<string, unknown> } | null>(null);\n\n  return useStore(storeApi, (state) => {\n    const c = cache.current;\n    if (c && c.viewIndex === state.viewIndex && c.data === state.data && c.scope === scope && shallowEqual(c.specs, specs)) {\n      return c.result;\n    }\n    const result = computeAggregate(storeApi, state, specs, scope);\n    cache.current = { viewIndex: state.viewIndex, data: state.data, scope, specs, result };\n    return result;\n  });\n}\n\n/** Props for {@link DataGridAggregateReporter}. */\nexport type DataGridAggregateReporterProps<TData = unknown> = {\n  specs: AggregateSpecs<TData>;\n  options?: UseDataGridAggregateOptions;\n  /** Called with the aggregated row whenever it changes — feed it into a `useState` that becomes a pinned band's `topRows`/`bottomRows` entry. */\n  onChange: (row: Record<string, unknown>) => void;\n};\n\n/**\n * Bridges {@link useDataGridAggregate} out of the store. The pinned rows reach the grid as a\n * plugin's `rowBands` through the `plugins` prop — evaluated in the PARENT before the store exists — so a component that needs the live, filter-aware\n * aggregate to feed back into it must sit INSIDE the provider and report out. Render this as a plain\n * child anywhere under `<DataGridProvider>` (e.g. next to `<DataGridRoot>`) and hold its `onChange`\n * result in the parent's own state; that state is what you pass into `useDataGridPinnedRows`'s\n * `topRows`/`bottomRows`. A layout effect (not a passive one) reports the result before the browser paints,\n * so the parent's second render lands in the same frame as the first — no flash of an empty band.\n * Renders nothing.\n */\nexport function DataGridAggregateReporter<TData = unknown>(props: DataGridAggregateReporterProps<TData>): ReactNode {\n  const { specs, options, onChange } = props;\n  const row = useDataGridAggregate(specs, options);\n  // Hold the latest callback in a ref and key the effect on `row` alone: an inline `onChange`\n  // (fresh identity every parent render) would otherwise re-fire the effect on every render, and\n  // a parent that stores the row with a spread (`{ ...prev, ...row }`) loops that forever.\n  const onChangeRef = useRef(onChange);\n  onChangeRef.current = onChange;\n  useLayoutEffect(() => {\n    onChangeRef.current(row);\n  }, [row]);\n  return null;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/use-data-grid-aggregate.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-pinned-rows/use-data-grid-server-aggregate.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { useStore } from \"zustand\";\nimport { serverSpecKey, type ServerSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev, serverSpecOf, useDataGridStoreApi } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/** Longest text a server value keeps; longer strings are cut. */\nconst MAX_SERVER_AGGREGATE_TEXT = 1000;\n\n/** What `fetchAggregates` receives. */\nexport type FetchAggregatesRequest = {\n  /** The sort, filters, and quick-search text the grid holds now. */\n  spec: ServerSpec;\n  /** The column ids whose values the band shows. */\n  columnIds: readonly string[];\n  /** Aborted when a newer request replaces this one, and on unmount. */\n  signal: AbortSignal;\n};\n\n/** `\"loading\"`: no values yet. `\"stale\"`: old values stay while a newer request runs. `\"error\"`: the last request failed; old values stay. */\nexport type ServerAggregateStatus = \"loading\" | \"stale\" | \"ready\" | \"error\";\n\n/** Options for {@link useDataGridServerAggregate}. */\nexport type UseDataGridServerAggregateOptions = {\n  /** Resolves `{ [columnId]: value }` for the whole result of `spec`, not for the rows the grid holds. */\n  fetchAggregates: (request: FetchAggregatesRequest) => Promise<Record<string, unknown>>;\n  /** Columns to ask for. Default: every column. */\n  columnIds?: readonly string[];\n  /** Wait in ms before each request starts: on mount, after a filter, quick-search, or `columnIds` change, and after `refresh()` and `retry()`. `0` starts at once. Default `150`. */\n  debounceMs?: number;\n  /** Called once per failed request. */\n  onError?: (error: unknown) => void;\n  /** The `false | \"settled\"` subset of the server hooks' `refreshAfterSave` policy. `\"settled\"` (default) requests again once every save in flight has settled. `false` never does; call `refresh()` yourself. */\n  refreshAfterSave?: false | \"settled\";\n};\n\n/** Return value of {@link useDataGridServerAggregate}. */\nexport type ServerAggregateResult = {\n  /** Sanitized values, ready for a pinned band's `topRows` or `bottomRows`. Identity changes only when a request lands. */\n  row: Record<string, unknown>;\n  status: ServerAggregateStatus;\n  error: unknown;\n  /** Requests the values again and keeps the old ones on screen until the answer lands. */\n  refresh: () => void;\n  /** True while the status is `\"loading\"` or `\"stale\"`. */\n  loading: boolean;\n  /** Requests again after a failure; does nothing without an error. */\n  retry: () => void;\n};\n\nconst EMPTY_ROW: Record<string, unknown> = {};\n\n/** The result before the first request settles; start parent state from it. */\nexport const PENDING_SERVER_AGGREGATE: ServerAggregateResult = { row: EMPTY_ROW, status: \"loading\", error: null, loading: true, refresh: () => {}, retry: () => {} };\n\nfunction aggregateKey(spec: ServerSpec): string {\n  return serverSpecKey({ sorts: [], filters: spec.filters, ...(spec.filterJoin ? { filterJoin: spec.filterJoin } : null), searchText: spec.searchText });\n}\n\nfunction reportChange(onChange: (result: ServerAggregateResult) => void, result: ServerAggregateResult): void {\n  try {\n    onChange(result);\n  } catch (error) {\n    console.error(\"[data-grid-pinned-rows] onChange threw\", error);\n  }\n}\n\nfunction notifyError(onError: ((error: unknown) => void) | undefined, error: unknown): void {\n  try {\n    onError?.(error);\n  } catch {\n    // a throwing consumer callback must not break the grid\n  }\n}\n\nfunction sanitizeAnswer(answer: unknown, columnIds: readonly string[], warnDropped: (columnId: string) => void): Record<string, unknown> {\n  if (typeof answer !== \"object\" || answer === null || Array.isArray(answer)) {\n    throw new TypeError(\"fetchAggregates must resolve an object of { [columnId]: value }\");\n  }\n  const row: [string, unknown][] = [];\n  for (const id of columnIds) {\n    if (!Object.prototype.hasOwnProperty.call(answer, id)) continue;\n    const value = (answer as Record<string, unknown>)[id];\n    if (typeof value === \"string\") row.push([id, value.length > MAX_SERVER_AGGREGATE_TEXT ? value.slice(0, MAX_SERVER_AGGREGATE_TEXT) : value]);\n    else if ((typeof value === \"number\" && Number.isFinite(value)) || typeof value === \"boolean\" || value === null) row.push([id, value]);\n    else warnDropped(id);\n  }\n  return Object.fromEntries(row);\n}\n\n/**\n * Pinned-row values from a server. Calls `fetchAggregates` with the current spec on mount and again\n * after each filter, quick-search, or `columnIds` change (a sort never changes the aggregated rows) and after the saves in flight settle, aborts the\n * request a newer one replaces, and drops its late answer. Pagination, scroll, and own-API grids\n * use it alike, because the request carries the spec and not the rows the grid holds. Answer\n * values are untrusted: unknown column ids are ignored, text is cut at 1000 characters,\n * and anything but text, finite numbers, booleans, and null is dropped.\n * Must run inside the grid provider; see {@link DataGridServerAggregateReporter}.\n */\nexport function useDataGridServerAggregate(options: UseDataGridServerAggregateOptions): ServerAggregateResult {\n  const { debounceMs = 150, refreshAfterSave = \"settled\" } = options;\n  const storeApi = useDataGridStoreApi();\n  const filters = useStore(storeApi, (s) => s.filterState);\n  const filterJoin = useStore(storeApi, (s) => s.filterJoin);\n  const sorts = useStore(storeApi, (s) => s.sortState);\n  const searchText = useStore(storeApi, (s) => s.searchText);\n  const columns = useStore(storeApi, (s) => s.columns);\n\n  const spec = useMemo<ServerSpec>(() => serverSpecOf({ sortState: sorts, filterState: filters, filterJoin, searchText }), [sorts, filters, filterJoin, searchText]);\n  const key = aggregateKey(spec);\n  const columnIds = useMemo(() => options.columnIds ?? columns.map((c) => c.id), [options.columnIds, columns]);\n  const columnKey = columnIds.join(\"\\u0000\");\n\n  const latest = useRef({ options, spec, columnIds });\n  useLayoutEffect(() => {\n    latest.current = { options, spec, columnIds };\n  });\n\n  const [state, setState] = useState<{ row: Record<string, unknown>; status: ServerAggregateStatus; error: unknown }>({\n    row: EMPTY_ROW,\n    status: \"loading\",\n    error: null,\n  });\n  const hasValues = useRef(false);\n  const warned = useRef(false);\n  const warnDropped = useCallback((id: string) => {\n    if (!isDev() || warned.current) return;\n    warned.current = true;\n    console.warn(`[data-grid-pinned-rows] useDataGridServerAggregate dropped the value of column \"${id}\": only text, finite numbers, booleans, and null are shown.`);\n  }, []);\n  const statusRef = useRef<ServerAggregateStatus>(\"loading\");\n  const [tick, setTick] = useState(0);\n\n  useEffect(() => {\n    const controller = new AbortController();\n    setState((prev) => (prev.status === (hasValues.current ? \"stale\" : \"loading\") ? prev : { ...prev, status: hasValues.current ? \"stale\" : \"loading\", error: null }));\n    const start = () => {\n      const { options: o, spec: s, columnIds: ids } = latest.current;\n      void new Promise<unknown>((resolve) => resolve(o.fetchAggregates({ spec: s, columnIds: ids, signal: controller.signal })))\n        .then((answer) => {\n          if (controller.signal.aborted) return;\n          const row = sanitizeAnswer(answer, ids, warnDropped);\n          hasValues.current = true;\n          setState({ row, status: \"ready\", error: null });\n        })\n        .catch((error: unknown) => {\n          if (controller.signal.aborted) return;\n          setState((prev) => ({ ...prev, status: \"error\", error }));\n          notifyError(latest.current.options.onError, error);\n        });\n    };\n    if (debounceMs <= 0) {\n      start();\n      return () => controller.abort();\n    }\n    const timer = setTimeout(start, debounceMs);\n    return () => {\n      clearTimeout(timer);\n      controller.abort();\n    };\n  }, [key, columnKey, tick, debounceMs, warnDropped]);\n\n  const refresh = useCallback(() => setTick((t) => t + 1), []);\n\n  const pendingSaves = useStore(storeApi, (s) => s.pendingSaveCount);\n  const previousPending = useRef(pendingSaves);\n  useEffect(() => {\n    const settled = previousPending.current > 0 && pendingSaves === 0;\n    previousPending.current = pendingSaves;\n    if (settled && refreshAfterSave !== false) refresh();\n  }, [pendingSaves, refreshAfterSave, refresh]);\n  useLayoutEffect(() => {\n    statusRef.current = state.status;\n  });\n  const retry = useCallback(() => {\n    if (statusRef.current === \"error\") setTick((t) => t + 1);\n  }, []);\n  const loading = state.status === \"loading\" || state.status === \"stale\";\n\n  return useMemo(() => ({ ...state, loading, refresh, retry }), [state, loading, refresh, retry]);\n}\n\n/** Props for {@link DataGridServerAggregateReporter}. */\nexport type DataGridServerAggregateReporterProps = UseDataGridServerAggregateOptions & {\n  /** Called when the row, status, or error changes; hold the result in the parent's state and pass its `row` to a pinned band. */\n  onChange: (result: ServerAggregateResult) => void;\n};\n\n/**\n * Bridges {@link useDataGridServerAggregate} out of the grid provider, like\n * `DataGridAggregateReporter`: render it as a child of the grid and keep the reported result in the\n * parent's state. Renders nothing.\n */\nexport function DataGridServerAggregateReporter(props: DataGridServerAggregateReporterProps): ReactNode {\n  const { onChange, ...options } = props;\n  const result = useDataGridServerAggregate(options);\n  const onChangeRef = useRef(onChange);\n  useLayoutEffect(() => {\n    onChangeRef.current = onChange;\n  });\n  useLayoutEffect(() => {\n    reportChange(onChangeRef.current, result);\n  }, [result]);\n  return null;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-pinned-rows/use-data-grid-server-aggregate.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
