{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-status-bar",
  "title": "Data Grid Status Bar",
  "author": "gridcn",
  "description": "Status-bar add-on for the gridcn data grid: <DataGridStatusBar /> shows count, sum, avg, min, and max of the selected cells under the grid (useDataGridSelectionStats is the headless hook). Numbers are detected by value (finite numbers), sums use Neumaier-compensated summation, a single-column selection formats through that column's toDisplayText, and above 200,000 cells the walk caps and flags the values with ≈. New user-facing strings live under labels.statusBar (see data-grid/labels.ts DataGridStatusBarLabels). Zero core changes — purely additive.",
  "registryDependencies": [
    "@gridcn/data-grid",
    "button"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-status-bar/data-grid-status-bar.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\n\nexport {\n  DataGridStatusBar,\n  type DataGridStatusBarProps,\n  type StatusBarAggregate,\n} from \"./status-bar\";\nexport { useDataGridSelectionStats } from \"./use-data-grid-selection-stats\";\nexport { MAX_STATUS_CELLS, type SelectionStats } from \"./compute-selection-stats\";\n",
      "type": "registry:component",
      "target": "components/data-grid-status-bar/data-grid-status-bar.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-status-bar/status-bar.tsx",
      "content": "\"use client\";\n\nimport { Children, useMemo, type ReactNode } from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  DEFAULT_LABELS,\n  useDataGridActions,\n  useDataGridCellTypes,\n  useDataGridHiddenCheckedCount,\n  useDataGridLabels,\n  useDataGridSelectedRows,\n  useDataGridVisibleColumns,\n  numberCellType,\n  type DataGridStatusBarLabels,\n} from \"@/registry/default/components/data-grid/data-grid\";\nimport { forEachDataIndex, matchingRowTotal, mergeLabelLayers, useDataGridSelector, type DataGridStoreState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { MAX_STATUS_CELLS } from \"./compute-selection-stats\";\nimport { useDataGridSelectionStats } from \"./use-data-grid-selection-stats\";\n\nconst dataRowCounts = new WeakMap<object, number>();\n\n/** The rows of the shown view; the group rows of a grouped view are not rows. */\nfunction dataRowsInView(s: Pick<DataGridStoreState, \"viewIndex\" | \"groupLayout\">): number {\n  if (!s.groupLayout) return s.viewIndex.length;\n  const cached = dataRowCounts.get(s.viewIndex);\n  if (cached !== undefined) return cached;\n  let count = 0;\n  forEachDataIndex(s.viewIndex, () => {\n    count++;\n  });\n  dataRowCounts.set(s.viewIndex, count);\n  return count;\n}\n\n/** One of the aggregates the bar can show. */\nexport type StatusBarAggregate = \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n\n/** Props for {@link DataGridStatusBar}. */\nexport type DataGridStatusBarProps = {\n  /** Which aggregates to show, and in which order. Default: all five, `count`, `sum`, `avg`, `min`, `max`. */\n  aggregates?: readonly StatusBarAggregate[];\n  /**\n   * Formats the shown aggregate values. When omitted, the single-column rule applies: if every\n   * numeric cell comes from one column, its `toDisplayText` formats sum/avg/min/max (a `number`\n   * column needs `options.format`, such as currency or percent, or `options.decimals`, which rounds with `Intl.NumberFormat(locale, { maximumFractionDigits: decimals })`); otherwise `Intl.NumberFormat(locale, { maximumFractionDigits: 4 })`.\n   */\n  formatValue?: (value: number, aggregate: StatusBarAggregate) => string;\n  /** i18n overrides for this bar's strings, merged over `labels.statusBar`. */\n  labels?: Partial<DataGridStatusBarLabels>;\n  className?: string;\n  /** Extra items, rendered after the aggregates. The bar renders while it has children, even with nothing selected. */\n  children?: ReactNode;\n};\n\nconst DEFAULT_AGGREGATES: readonly StatusBarAggregate[] = [\"count\", \"sum\", \"avg\", \"min\", \"max\"];\n\n/**\n * Aggregate bar for the selected cells: count of non-empty cells plus sum/avg/min/max of numeric\n * cells, computed by {@link useDataGridSelectionStats}. Place it inside `DataGridProvider`, next\n * to `DataGridRoot`, like the pagination bar. Shows the number of hidden checked rows when `checkedRowsLifetime=\"across-filters\"` remembers any, and the\n * select-all banner: with `totalRowCount` and `checkedRowsLifetime=\"across-filters\"`, \"Select all matching\" while every\n * row of a partial view is checked, \"Clear selection\" after `selectAllMatching`. Renders nothing while fewer than 2 selected cells have a value other than `undefined`, no\n * hidden checked row exists, and no banner shows.\n */\nexport function DataGridStatusBar({\n  aggregates = DEFAULT_AGGREGATES,\n  formatValue,\n  labels,\n  className,\n  children,\n}: DataGridStatusBarProps) {\n  const locale = useDataGridSelector((s) => s.locale);\n  const stats = useDataGridSelectionStats();\n  const hiddenChecked = useDataGridHiddenCheckedCount();\n  const storeLabels = useDataGridLabels();\n  const mergedLabels = mergeLabelLayers<DataGridStatusBarLabels>(DEFAULT_LABELS.statusBar, storeLabels.statusBar, labels);\n  const visibleColumns = useDataGridVisibleColumns();\n  const cellTypes = useDataGridCellTypes();\n  const fallbackFormat = useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 4 }), [locale]);\n\n  const displayText = useMemo(() => {\n    if (stats.numericColumnId === null) return null;\n    const column = visibleColumns.find((c) => c.id === stats.numericColumnId);\n    const cellType = column ? (cellTypes[column.type ?? \"text\"] ?? cellTypes[\"text\"]) : undefined;\n    const toDisplayText = cellType?.toDisplayText;\n    if (!column || !toDisplayText) return null;\n    const options = column.options as { format?: unknown; decimals?: unknown } | undefined;\n    if (toDisplayText === numberCellType.toDisplayText && !options?.format) {\n      const decimals = options?.decimals;\n      if (decimals === undefined) return null;\n      if (typeof decimals === \"number\" && Number.isInteger(decimals) && decimals >= 0 && decimals <= 20) {\n        const rounded = new Intl.NumberFormat(locale, { maximumFractionDigits: decimals });\n        return (value: number) => rounded.format(value);\n      }\n    }\n    return (value: number) => toDisplayText(value, column.options);\n  }, [stats.numericColumnId, visibleColumns, cellTypes, locale]);\n\n  const showStats = stats.cells >= 2;\n  const total = useDataGridSelector(matchingRowTotal);\n  const canSelectAllMatching = useDataGridSelector((s) => s.checkedRowsLifetime === \"across-filters\");\n  const allMatching = useDataGridSelector((s) => s.allMatching);\n  const pageRows = useDataGridSelector(dataRowsInView);\n  const pageChecked = useDataGridSelector((s) => s.viewIndex.length > 0 && s.selection.rows.hasAll([0, s.viewIndex.length]));\n  const actions = useDataGridActions();\n  const escalate = canSelectAllMatching && !allMatching && pageChecked && total !== undefined && (total === null || total > pageRows);\n  if (!showStats && hiddenChecked === 0 && !allMatching && !escalate && Children.toArray(children).length === 0) return null;\n\n  const format = (value: number, aggregate: StatusBarAggregate) =>\n    formatValue ? formatValue(value, aggregate) : aggregate !== \"count\" && displayText ? displayText(value) : fallbackFormat.format(value);\n\n  return (\n    <div\n      role=\"status\"\n      aria-live=\"polite\"\n      aria-atomic=\"true\"\n      title={stats.approximate ? mergedLabels.approximate(MAX_STATUS_CELLS) : undefined}\n      className={cn(\"flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border bg-background px-2 py-1.5 text-xs text-muted-foreground\", className)}\n    >\n      {(showStats ? aggregates : []).map((aggregate) => {\n        const value = aggregate === \"count\" ? stats.count : stats[aggregate];\n        if (value === null) return null;\n        return (\n          <span key={aggregate}>\n            <span className=\"text-muted-foreground\">{mergedLabels[aggregate]}</span>{\" \"}\n            <span className=\"tabular-nums text-foreground\">\n              {stats.approximate ? \"≈\" : \"\"}\n              {format(value, aggregate)}\n            </span>\n          </span>\n        );\n      })}\n      {hiddenChecked > 0 && <span>{showStats ? mergedLabels.hiddenChecked(hiddenChecked) : mergedLabels.hiddenCheckedOnly(hiddenChecked)}</span>}\n      {escalate && (\n        <span data-grid-select-all-banner=\"\" className=\"flex items-center gap-1\">\n          <span>{mergedLabels.pageSelected(pageRows)}</span>\n          <Button type=\"button\" variant=\"link\" size=\"xs\" onClick={() => actions.selectAllMatching()}>\n            {mergedLabels.selectAllMatching(total ?? null)}\n          </Button>\n        </span>\n      )}\n      {allMatching && (\n        <span data-grid-select-all-banner=\"\" className=\"flex items-center gap-1\">\n          <AllSelectedText allSelected={mergedLabels.allSelected} />\n          <Button type=\"button\" variant=\"link\" size=\"xs\" onClick={() => actions.clearSelection()}>\n            {mergedLabels.clearSelection}\n          </Button>\n        </span>\n      )}\n      {children}\n    </div>\n  );\n}\n\n/** The count after \"select all matching\"; it reads the selection value, so it mounts only while that mode is on. */\nfunction AllSelectedText({ allSelected }: { allSelected: (count: number | null) => string }): ReactNode {\n  const selected = useDataGridSelectedRows();\n  return <span>{allSelected(selected.count)}</span>;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-status-bar/status-bar.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-status-bar/use-data-grid-selection-stats.ts",
      "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport {\n  getCellValue,\n  useDataGridCellTypes,\n  useDataGridSelection,\n  useDataGridViewIndex,\n  useDataGridVisibleColumns,\n  type AnyColumnDef,\n} from \"@/registry/default/components/data-grid/data-grid\";\nimport { rowAtViewRow, selectionRects, useDataGridSelector } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { computeSelectionStats, EMPTY_SELECTION_STATS, type SelectionStats } from \"./compute-selection-stats\";\n\n/** Total rect area up to which the walk runs at once; above it, the settle timer defers it. */\nexport const IMMEDIATE_SELECTION_CELL_LIMIT = 5_000;\n/** Trailing delay in ms before a large selection's walk runs, after the last selection change. */\nexport const SELECTION_STATS_SETTLE_MS = 150;\n\n/**\n * Aggregates (count, sum, avg, min, max) over the selected cells, recomputed after the selection\n * settles: at once for up to {@link IMMEDIATE_SELECTION_CELL_LIMIT} cells, else on a\n * {@link SELECTION_STATS_SETTLE_MS} ms trailing timer. Stops at `MAX_STATUS_CELLS` and flags\n * `approximate`. See {@link computeSelectionStats} for the field semantics.\n */\nexport function useDataGridSelectionStats(): SelectionStats {\n  const selection = useDataGridSelection();\n  const viewIndex = useDataGridViewIndex();\n  const visibleColumns = useDataGridVisibleColumns();\n  const cellTypes = useDataGridCellTypes();\n  const data = useDataGridSelector((s) => s.data);\n  const [stats, setStats] = useState(EMPTY_SELECTION_STATS);\n\n  useEffect(() => {\n    const columns = visibleColumns as readonly AnyColumnDef[];\n    const rects = selectionRects(selection, viewIndex.length, columns.length);\n    let area = 0;\n    for (const rect of rects) area += rect.width * rect.height;\n    if (area === 0) {\n      setStats(EMPTY_SELECTION_STATS);\n      return;\n    }\n    const compute = () => {\n      setStats(\n        computeSelectionStats({\n          rects,\n          rowCount: viewIndex.length,\n          colCount: columns.length,\n          valueAt: (viewRow, viewCol) => {\n            const row = rowAtViewRow({ viewIndex, data }, viewRow);\n            if (row === undefined) return undefined;\n            return getCellValue<unknown, AnyColumnDef>(row, columns[viewCol]!);\n          },\n          isEmptyAt: (viewCol, value) => {\n            const column = columns[viewCol]!;\n            const cellType = cellTypes[column.type ?? \"text\"] ?? cellTypes[\"text\"]!;\n            return cellType.isEmpty(value);\n          },\n          columnIdAt: (viewCol) => columns[viewCol]!.id,\n        }),\n      );\n    };\n    // Rect area is an upper bound on the union, so overlapping selections can defer to\n    // the timer with a small real walk; an exact union count would cost the walk itself.\n    if (area <= IMMEDIATE_SELECTION_CELL_LIMIT) {\n      compute();\n      return;\n    }\n    const timer = window.setTimeout(compute, SELECTION_STATS_SETTLE_MS);\n    return () => window.clearTimeout(timer);\n  }, [selection, viewIndex, visibleColumns, cellTypes, data]);\n\n  return stats;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-status-bar/use-data-grid-selection-stats.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-status-bar/compute-selection-stats.ts",
      "content": "import type { GridRect } from \"@/registry/default/components/data-grid/data-grid\";\n\n/** Walk cap for one status-bar aggregation, in visited cells (same cap as the clipboard's `MAX_COPY_CELLS`). */\nexport const MAX_STATUS_CELLS = 200_000;\n\nexport type SelectionStats = {\n  /** Selected cells whose value is not `undefined` (an unloaded row or a missing field), each counted once across overlapping rects. */\n  cells: number;\n  /** Cells whose column's cell type `isEmpty` is false. */\n  count: number;\n  /** Cells whose raw value is a finite number. */\n  numeric: number;\n  /** Neumaier-compensated sum of the numeric values; `null` when `numeric === 0`. */\n  sum: number | null;\n  /** `null` when `numeric === 0` or the sum is not finite. */\n  avg: number | null;\n  min: number | null;\n  max: number | null;\n  /** The single column id all numeric cells came from; `null` when they span several columns. */\n  numericColumnId: string | null;\n  /** The walk stopped at `maxCells` before seeing the whole selection. */\n  approximate: boolean;\n};\n\n/** All-zero stats: nothing selected (also the hook's initial state). */\nexport const EMPTY_SELECTION_STATS: SelectionStats = {\n  cells: 0,\n  count: 0,\n  numeric: 0,\n  sum: null,\n  avg: null,\n  min: null,\n  max: null,\n  numericColumnId: null,\n  approximate: false,\n};\n\nexport type SelectionStatsInput = {\n  /** The selection regions in apply order; a cell in two rects counts once. */\n  rects: readonly GridRect[];\n  /** Visible rows the rects index into (`viewIndex.length`). */\n  rowCount: number;\n  /** Visible columns the rects index into. */\n  colCount: number;\n  /** The cell value at a view position; `undefined` for an unloaded (lazy) hole. */\n  valueAt: (viewRow: number, viewCol: number) => unknown;\n  /** Whether `value` is empty for the column at `viewCol` (that column's cell type `isEmpty`). */\n  isEmptyAt: (viewCol: number, value: unknown) => boolean;\n  /** The id of the visible column at `viewCol`. */\n  columnIdAt: (viewCol: number) => string;\n  /** Stop the walk once this many cells were visited, lazy holes included (default {@link MAX_STATUS_CELLS}). */\n  maxCells?: number;\n};\n\nexport function computeSelectionStats(input: SelectionStatsInput): SelectionStats {\n  const { rects, rowCount, colCount, valueAt, isEmptyAt, columnIdAt } = input;\n  const maxCells = input.maxCells ?? MAX_STATUS_CELLS;\n  const seen = rects.length > 1 ? new Set<number>() : null;\n  let visited = 0;\n  let cells = 0;\n  let count = 0;\n  let numeric = 0;\n  let sum = 0;\n  // Neumaier compensation term; the plain sum of ten 0.1 values is 0.9999999999999999, the compensated one is 1.\n  let compensation = 0;\n  let min = Infinity;\n  let max = -Infinity;\n  let numericColumnId: string | null = null;\n  let mixedColumns = false;\n  let approximate = false;\n  let stopped = false;\n\n  for (const rect of rects) {\n    if (stopped) break;\n    const x1 = Math.min(rect.x + rect.width, colCount);\n    const y1 = Math.min(rect.y + rect.height, rowCount);\n    for (let y = Math.max(rect.y, 0); y < y1 && !stopped; y++) {\n      for (let x = Math.max(rect.x, 0); x < x1; x++) {\n        const key = y * colCount + x;\n        if (seen?.has(key)) continue;\n        if (visited === maxCells) {\n          // cap reached: the first `maxCells` visited cells (holes included) are in, the rest is not read\n          approximate = true;\n          stopped = true;\n          break;\n        }\n        seen?.add(key);\n        visited += 1;\n        const value = valueAt(y, x);\n        if (value === undefined) continue;\n        cells += 1;\n        if (!isEmptyAt(x, value)) count += 1;\n        if (typeof value === \"number\" && Number.isFinite(value)) {\n          numeric += 1;\n          const t = sum + value;\n          compensation += Math.abs(sum) >= Math.abs(value) ? (sum - t) + value : (value - t) + sum;\n          sum = t;\n          if (value < min) min = value;\n          if (value > max) max = value;\n          const id = columnIdAt(x);\n          if (numericColumnId === null) numericColumnId = id;\n          else if (numericColumnId !== id) mixedColumns = true;\n        }\n      }\n    }\n  }\n\n  const total = Number.isFinite(sum) ? sum + compensation : sum;\n  return {\n    cells,\n    count,\n    numeric,\n    sum: numeric > 0 ? total : null,\n    avg: numeric > 0 && Number.isFinite(total) ? total / numeric : null,\n    min: numeric > 0 ? min : null,\n    max: numeric > 0 ? max : null,\n    numericColumnId: numeric > 0 && !mixedColumns ? numericColumnId : null,\n    approximate,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-status-bar/compute-selection-stats.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
