{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-history",
  "title": "Data Grid History",
  "author": "gridcn",
  "description": "Undo/redo add-on for the gridcn data grid: op-based, id-keyed history plus a useDataGridState quick-start wrapper.",
  "dependencies": [],
  "registryDependencies": [
    "@gridcn/data-grid"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-history/data-grid-history.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\n\nexport { useDataGridHistory, type HistorySkip, type RecordedChange, type UseDataGridHistoryOptions, type UseDataGridHistoryResult } from \"./use-data-grid-history\";\nexport { useDataGridState, type UseDataGridStateOptions, type UseDataGridStateResult } from \"./use-data-grid-state\";\n\n// Relative on purpose: the shadcn CLI rewrites import paths, never augmentation module names.\ndeclare module \"../data-grid/types\" {\n  interface GridActions {\n    undo: true;\n    redo: true;\n  }\n}\n\n/** Offers the `undo`/`redo` global-shortcut flags — this add-on is what makes them do anything. */\ndeclare module \"../data-grid/keyboard/global-shortcuts\" {\n  interface DataGridGlobalShortcutActions {\n    undo: boolean;\n    redo: boolean;\n  }\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-history/data-grid-history.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-history/history-keymap.ts",
      "content": "import type { Keymap } from \"@/registry/default/components/data-grid/data-grid\";\n\nexport const HISTORY_KEYMAP: Keymap = {\n  undo: [\"mod+z\"],\n  redo: [\"mod+y\", \"mod+shift+z\"],\n};\n",
      "type": "registry:component",
      "target": "components/data-grid-history/history-keymap.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-history/use-data-grid-history.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from \"react\";\nimport { useDataGridApi, useDataGridFilterState, useDataGridSearchText, useDataGridSortState, type DataChange, type DataGridApi, type DataGridPlugin, type ServerSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport { HISTORY_KEYMAP } from \"./history-keymap\";\nimport { isDev, createHistory, buildRollback, rebaseOntoCurrent, useDataGridAnnounce, useDataGridSelector } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\ntype RecordSources<TData> =\n  | readonly DataChange<TData>[\"source\"][]\n  | ((defaults: readonly DataChange<TData>[\"source\"][]) => readonly DataChange<TData>[\"source\"][]);\n\n/** Options for {@link useDataGridHistory}. */\nexport type UseDataGridHistoryOptions<TData> = {\n  /** Maximum number of entries kept on the undo stack (default `100`); oldest entries are dropped past this. A change between renders keeps the entries and trims to the new value. */\n  capacity?: number;\n  /**\n   * Identity of the dataset; a change between renders clears both stacks, so undo after a dataset\n   * swap cannot reinsert rows from the old dataset. A function receives the grid's sort, filters,\n   * and search text and returns the key, so `datasetKey: serverSpecKey` clears the stacks on every\n   * server spec change and needs no server hook result. Omit it and reset with `clear()` instead.\n   */\n  datasetKey?: string | number | ((spec: ServerSpec) => string | number);\n  /**\n   * Which `DataChange.source` values go on the undo stack. Defaults to\n   * `[\"edit\", \"paste\", \"fill\", \"delete\", \"cut\", \"row-operation\", \"import\", \"replace\", \"app\"]`: `\"stream\"` stays\n   * out because a 100-updates/s `updateCells` feed would otherwise evict the user's whole undo\n   * stack within seconds. Pass a list to replace the set, or a function of the defaults to edit it, for\n   * example `(defaults) => [...defaults, \"stream\"]` to record streams too. `\"history\"`, `\"rollback\"`,\n   * `\"merge\"`, and `\"id-swap\"` are never recorded, whatever the list says — that is what keeps an undo\n   * from pushing a second entry.\n   */\n  recordSources?: RecordSources<TData>;\n  /**\n   * Called when `undo` or `redo` finds a row its change needs missing from `data`, and applies nothing.\n   * `\"rows-not-loaded\"`: `data` has holes (scroll mode) or holds part of the result (`totalRowCount` above its length or `null`, such as one\n   * server page or a cursor source); the entry stays, so the same call works after the rows load.\n   * `\"rows-gone\"`: `data` holds the whole result and lacks the rows; the entry is dropped. The live region announces both.\n   * A throw is logged and does not stop the grid.\n   */\n  onSkip?: (ctx: HistorySkip) => void;\n};\n\n/** What {@link UseDataGridHistoryOptions.onSkip} receives. */\nexport type HistorySkip = {\n  direction: \"undo\" | \"redo\";\n  reason: \"rows-not-loaded\" | \"rows-gone\";\n  /** Ids of the rows the change needs and `data` lacks. */\n  rowIds: readonly string[];\n};\n\n/**\n * The ids `change` needs that `data` lacks (an insert needs none), and whether `data` has holes.\n * `Array.prototype.some` skips holes, so the scan tests indices.\n */\nfunction findMissingRows<TData>(\n  change: DataChange<TData>,\n  data: readonly unknown[],\n  getRowId: (row: never, index: number) => string,\n): { missing: string[]; hasHoles: boolean } {\n  const needed = new Set<string>();\n  for (const op of change.ops) if (op.type !== \"insert\") needed.add(op.rowId);\n  let hasHoles = false;\n  for (let i = 0; i < data.length; i++) {\n    const row = data[i];\n    if (!(i in data) || row === undefined) hasHoles = true;\n    else if (needed.size > 0) needed.delete(getRowId(row as never, i));\n  }\n  return { missing: [...needed], hasHoles };\n}\n\n/** Sources `useDataGridHistory` records when `recordSources` is omitted — everything a user did on purpose (`\"history\"` is skipped before the filter runs). */\nconst DEFAULT_RECORD_SOURCES: readonly DataChange<unknown>[\"source\"][] = [\n  \"edit\",\n  \"paste\",\n  \"fill\",\n  \"delete\",\n  \"cut\",\n  \"row-operation\",\n  \"import\",\n  \"replace\",\n  \"app\",\n];\n\nconst NOT_MOUNTED_CHECK_MS = 2000;\n\n/** Return value of {@link useDataGridHistory}. */\nexport type UseDataGridHistoryResult<TData> = {\n  /** One entry of the grid's `plugins` prop — the plugin's `onDataChange` observer records the grid's data changes, its `undo`/`redo` commands back the mod+Z/mod+Shift+Z bindings, and its `Mount` hands the grid's api handle to the imperative triggers below. Stable for the hook's lifetime. An inline `plugins={[plugin]}` is fine: re-resolution is gated on entry identity (name + member references), not on the array's. */\n  plugin: DataGridPlugin<TData>;\n  /** Imperative undo (a toolbar button outside the keyboard bindings); no-op when nothing to undo, the grid is not mounted yet, or the grid is read-only. Applies nothing and calls `onSkip` when a needed row is missing. */\n  undo: () => void;\n  /** Imperative redo; see {@link UseDataGridHistoryResult.undo}. */\n  redo: () => void;\n  /** `true` when `undo` would do something now: an entry exists and the grid is not `readOnly`. */\n  canUndo: boolean;\n  /** `true` when `redo` would do something now: an entry exists and the grid is not `readOnly`. */\n  canRedo: boolean;\n  /** Number of entries on the undo stack, also while the grid is `readOnly`; 0 when there is nothing to undo. */\n  historySize: number;\n  /** Clears both stacks. A dataset change clears them itself when `datasetKey` changes; use `clear` for an imperative reset. */\n  clear: () => void;\n  /**\n   * Reverts `change` (the object an `onDataChange` handler received) after its save failed: applies the\n   * inverse with `source: \"rollback\"` and drops the entry from the stacks, so no dead undo step remains.\n   * A cell reverts only while it still holds the change's value, so later edits survive. A change the\n   * user already undid is dropped without a write. A whole-row update reverts only while the row is shallow-equal to the change's row. No-op when the grid is not mounted yet or is read-only.\n   */\n  rollback: (change: DataChange<TData>) => void;\n  /**\n   * Applies a programmatic change (the consumer-built operation batch) to the grid as one write AND\n   * registers it as one undo entry — `commitChange` with `source: \"app\"`, which the observer\n   * records like any user gesture. Returns `false` when nothing is written (the grid is not mounted yet, is `readOnly`, or every operation was an insert of a row `data` already holds), `true` otherwise.\n   * `label` is an optional human-readable entry label.\n   */\n  record: (change: RecordedChange<TData>, label?: string) => boolean;\n};\n\n/** The change `record` takes. `source` is optional: `record` stores every entry as `\"app\"`. */\nexport type RecordedChange<TData> = Omit<DataChange<TData>, \"source\"> & { source?: DataChange<TData>[\"source\"] };\n\n/**\n * Operation-based undo/redo as a grid plugin. Records the grid's own `onDataChange` stream (the observer\n * runs after the store write and after the consumer's `onDataChange`), and undoes/redoes by\n * applying the inverted operation batch back through the grid's `commitChange` (an update with `cells` writes only those cells onto the current row) — one write, one emit,\n * so a controlled `data` prop sees the same change the user made.\n *\n * Design: the plugin does not take `data`/`setData` — the grid's store is the write target, and\n * the consumer's controlled-data echo (their `onDataChange` calling their own state setter)\n * stays exactly where it always was. `undo`/`redo` applied through the grid carry\n * `source: \"history\"`, which the observer skips, so each undo or redo records no second entry.\n */\nexport function useDataGridHistory<TData>(opts: UseDataGridHistoryOptions<TData> = {}): UseDataGridHistoryResult<TData> {\n  const { capacity, datasetKey, recordSources } = opts;\n  const onSkipRef = useRef(opts.onSkip);\n  onSkipRef.current = opts.onSkip;\n  const warnedSparseData = useRef(false);\n  const warnedNotMounted = useRef(false);\n  const history = useMemo(() => createHistory<TData>({ capacity }), []);\n  history.setCapacity(capacity ?? 100);\n  // history's canUndo/canRedo are getters on a mutable object; this forces a re-render\n  // after every mutating call so callers see them update even when nothing else re-renders\n  // this hook (e.g. `clear()`, or a consumer setter that dedupes identical arrays).\n  const [, forceUpdate] = useState(0);\n\n  // stale entries reference the old dataset: undo after a swap would resurrect dead rows\n  const fixedKey = typeof datasetKey === \"function\" ? undefined : datasetKey;\n  const prevDatasetKey = useRef(fixedKey);\n  useEffect(() => {\n    if (prevDatasetKey.current === fixedKey) return;\n    prevDatasetKey.current = fixedKey;\n    history.clear();\n    forceUpdate((n) => n + 1);\n  }, [fixedKey, history]);\n  const specKeyRef = useRef(typeof datasetKey === \"function\" ? datasetKey : null);\n  specKeyRef.current = typeof datasetKey === \"function\" ? datasetKey : null;\n  const historyRef = useRef(history);\n  historyRef.current = history;\n\n  const recorded = useMemo(\n    () =>\n      new Set<DataChange<TData>[\"source\"]>(\n        typeof recordSources === \"function\" ? recordSources(DEFAULT_RECORD_SOURCES) : (recordSources ?? DEFAULT_RECORD_SOURCES),\n      ),\n    [recordSources],\n  );\n  const recordedRef = useRef(recorded);\n  recordedRef.current = recorded;\n\n  // The grid's imperative handle, stashed by the plugin's Mount (and refreshed by every\n  // command/observer ctx): the imperative `undo`/`redo`/`record` triggers below run through it.\n  const apiRef = useRef<DataGridApi<TData> | null>(null);\n  const announceRef = useRef<ReturnType<typeof useDataGridAnnounce> | null>(null);\n  const readOnlyRef = useRef(false);\n\n  const warnNotMounted = useCallback((method: string) => {\n    if (warnedNotMounted.current || !isDev()) return;\n    warnedNotMounted.current = true;\n    console.warn(`[data-grid-history] ${method}() ran before the history plugin mounted, so it did nothing. Pass \"plugin\" (or \"plugins\" from useDataGridState) to the grid, and keep it in a plugins prop that you set after a spread.`);\n  }, []);\n\n  useEffect(() => {\n    if (!isDev()) return;\n    const timer = setTimeout(() => {\n      if (apiRef.current || warnedNotMounted.current) return;\n      warnedNotMounted.current = true;\n      console.warn(`[data-grid-history] The history plugin never mounted, so undo and redo do nothing. Pass \"plugin\" (or \"plugins\" from useDataGridState) to the grid's plugins prop.`);\n    }, NOT_MOUNTED_CHECK_MS);\n    return () => clearTimeout(timer);\n  }, []);\n\n  const applyHistoryChange = useCallback(\n    (direction: HistorySkip[\"direction\"]) => {\n      const api = apiRef.current;\n      if (!api) return warnNotMounted(direction);\n      const state = api.store.getState();\n      // A read-only grid refuses the revert, so popping the entry would only lose it.\n      if (state.readOnly) return;\n      const rebase = (entry: DataChange<TData>) => rebaseOntoCurrent(entry, state);\n      const change = direction === \"undo\" ? history.undo(rebase) : history.redo(rebase);\n      if (!change) return;\n      const { missing, hasHoles: holes } = findMissingRows(change, state.data, state.getRowId);\n      // an unknown count (`null`, a cursor source) or a count above the loaded rows means `data` holds a part of the result\n      const hasHoles = holes || state.totalRowCount === null || (typeof state.totalRowCount === \"number\" && state.totalRowCount > state.data.length);\n      if (!warnedSparseData.current && holes && missing.length > 0 && isDev()) {\n        warnedSparseData.current = true;\n        console.warn(\n          \"[data-grid-history] undo ran over a sparse (lazy) data array: unloaded rows are holes, so an undo that needs them is blocked and keeps its entry. Use a hole-tolerant getRowId and pass a datasetKey (or call clear()) when server.refresh() replaces the rows or the dataset changes.\",\n        );\n      }\n      if (missing.length === 0) {\n        api.actions.commitChange(change);\n        forceUpdate((n) => n + 1);\n        return;\n      }\n      if (hasHoles) history.restore(change);\n      else history.discard(change);\n      forceUpdate((n) => n + 1);\n      announceRef.current?.(\"historyBlocked\", missing.length, hasHoles);\n      try {\n        onSkipRef.current?.({ direction, reason: hasHoles ? \"rows-not-loaded\" : \"rows-gone\", rowIds: missing });\n      } catch (error) {\n        console.error(\"[data-grid-history] onSkip threw:\", error);\n      }\n    },\n    [history, warnNotMounted],\n  );\n\n  const undo = useCallback(() => applyHistoryChange(\"undo\"), [applyHistoryChange]);\n  const redo = useCallback(() => applyHistoryChange(\"redo\"), [applyHistoryChange]);\n\n  const clear = useCallback(() => {\n    history.clear();\n    forceUpdate((n) => n + 1);\n  }, [history]);\n\n  const rolledBack = useMemo(() => new WeakSet<DataChange<TData>>(), []);\n\n  const rollback = useCallback(\n    (change: DataChange<TData>) => {\n      const api = apiRef.current;\n      if (!api) return warnNotMounted(\"rollback\");\n      if (api.store.getState().readOnly) return;\n      rolledBack.add(change);\n      const undoSize = history.size;\n      const found = history.discard(change);\n      const alreadyUndone = found && history.size === undoSize;\n      if (!alreadyUndone) api.actions.commitChange(buildRollback(change, api.store.getState()));\n      forceUpdate((n) => n + 1);\n    },\n    [history, rolledBack, warnNotMounted],\n  );\n\n  const record = useCallback(\n    (change: RecordedChange<TData>, label?: string) => {\n      const api = apiRef.current;\n      if (!api) {\n        warnNotMounted(\"record\");\n        return false;\n      }\n      if (api.store.getState().readOnly) return false;\n      const fresh = withoutPresentInserts(api.store.getState(), { ...change, source: \"app\" });\n      if (fresh.ops.length === 0) return false;\n      // `source: \"app\"` tags the imperative entry (see DataChange.source); the observer records it\n      api.actions.commitChange({ ...fresh, source: \"app\", ...(label !== undefined ? { label } : {}) });\n      forceUpdate((n) => n + 1);\n      return true;\n    },\n    [history, warnNotMounted],\n  );\n\n  // The Mount must keep ONE identity for the hook's lifetime (a fresh component type per render\n  // would remount it); the api stash touches no hook state, so a once-created closure is safe.\n  const mountRef = useRef<ComponentType | null>(null);\n  if (mountRef.current === null) {\n    const ref = apiRef;\n    const announce = announceRef;\n    mountRef.current = function HistoryApiStash(): ReactNode {\n      ref.current = useDataGridApi<TData>();\n      announce.current = useDataGridAnnounce();\n      const readOnly = useDataGridSelector((s) => s.readOnly);\n      useEffect(() => {\n        if (readOnlyRef.current === readOnly) return;\n        readOnlyRef.current = readOnly;\n        forceUpdate((n) => n + 1);\n      }, [readOnly]);\n      const sorts = useDataGridSortState();\n      const filters = useDataGridFilterState();\n      const searchText = useDataGridSearchText();\n      const specKey = useMemo(() => specKeyRef.current?.({ sorts, filters, searchText }), [sorts, filters, searchText]);\n      const lastSpecKey = useRef(specKey);\n      useEffect(() => {\n        if (lastSpecKey.current === specKey) return;\n        lastSpecKey.current = specKey;\n        historyRef.current.clear();\n        forceUpdate((n) => n + 1);\n      }, [specKey]);\n      return null;\n    };\n  }\n\n  const plugin = useMemo<DataGridPlugin<TData>>(\n    () => ({\n      name: \"history\",\n      onDataChange: (next, change, ctx) => {\n        if (change.source === \"rollback\" || change.source === \"merge\") {\n          const { reverts, serverRowIds } = change;\n          const revertedEntry =\n            reverts !== undefined && (change.source === \"rollback\" ? history.restore(reverts) || history.discard(reverts) : history.discard(reverts));\n          const prunedEntries = serverRowIds !== undefined && history.dropRows(serverRowIds);\n          if (revertedEntry || prunedEntries) forceUpdate((n) => n + 1);\n          return;\n        }\n        if (change.source === \"id-swap\") {\n          const swapped = new Map<unknown, number>();\n          for (const op of change.ops) if (op.type === \"update\") swapped.set(op.row, -1);\n          next.forEach((row, index) => {\n            if (swapped.get(row) === -1) swapped.set(row, index);\n          });\n          const getRowId = ctx.api.store.getState().getRowId;\n          const swaps = change.ops.flatMap((op) =>\n            op.type === \"update\" ? [{ oldId: op.rowId, newId: getRowId(op.row, Math.max(0, swapped.get(op.row) ?? 0)), oldRow: op.prev, newRow: op.row }] : [],\n          );\n          if (history.replaceRowIds(swaps)) forceUpdate((n) => n + 1);\n          return;\n        }\n        if (change.source === \"history\") return;\n        if (recordedRef.current.has(change.source) && !rolledBack.has(change)) history.push(change);\n        forceUpdate((n) => n + 1);\n      },\n      commands: {\n        undo: {\n          when: (ctx) => !ctx.readOnly,\n          run: (ctx) => {\n            apiRef.current = ctx.api;\n            undo();\n          },\n        },\n        redo: {\n          when: (ctx) => !ctx.readOnly,\n          run: (ctx) => {\n            apiRef.current = ctx.api;\n            redo();\n          },\n        },\n      },\n      keymap: HISTORY_KEYMAP,\n      Mount: mountRef.current ?? undefined,\n    }),\n    [history, rolledBack, undo, redo, mountRef.current],\n  );\n\n  return {\n    plugin,\n    undo,\n    redo,\n    canUndo: history.canUndo && !readOnlyRef.current,\n    canRedo: history.canRedo && !readOnlyRef.current,\n    historySize: history.size,\n    clear,\n    rollback,\n    record,\n  };\n}\n\n/** Drops an insert whose row id `data` already holds (the caller applied it first), so `record` never writes a row twice; warns once in development. */\nfunction withoutPresentInserts<TData>(state: { data: readonly unknown[]; getRowId: (row: unknown, index: number) => string }, change: DataChange<TData>): DataChange<TData> {\n  if (!change.ops.some((op) => op.type === \"insert\")) return change;\n  const present = new Set(state.data.map((row, index) => (row === undefined ? \"\" : state.getRowId(row, index))));\n  const ops = change.ops.filter((op) => op.type !== \"insert\" || !present.has(op.rowId));\n  if (ops.length === change.ops.length) return change;\n  if (isDev()) console.warn(\"[data-grid-history] record() skipped an insert of a row that data already holds. record() writes the change itself, so the call is safe, but you do not need to apply it to your own array first.\");\n  return { ...change, ops };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-history/use-data-grid-history.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-history/use-data-grid-state.ts",
      "content": "\"use client\";\n\nimport { useCallback, useState } from \"react\";\nimport { type DataChange, type DataGridPlugin } from \"@/registry/default/components/data-grid/data-grid\";\nimport { useDataGridHistory, type RecordedChange, type UseDataGridHistoryOptions } from \"./use-data-grid-history\";\n\n/** Options for {@link useDataGridState}: every `useDataGridHistory` option, plus `getRowId` and `plugins`. */\nexport type UseDataGridStateOptions<TData> = UseDataGridHistoryOptions<TData> & {\n  /** Row identity; defaults to the row's `id` field, like `DataGrid`'s `getRowId`. */\n  getRowId?: (row: TData, index: number) => string;\n  /** Other plugins of the grid. The returned `plugins` holds them, then the history plugin, so the spread stays complete. An inline array is fine: equal entries keep the identity. An inline plugin object is a new plugin on every render, so define it at module scope or memoize it. */\n  plugins?: readonly DataGridPlugin<TData>[];\n};\n\n/** Return value of {@link useDataGridState}, spreadable straight onto `<DataGrid {...grid} />`. */\nexport type UseDataGridStateResult<TData> = {\n  data: readonly TData[];\n  getRowId?: (row: TData, index: number) => string;\n  /** Writes the grid's next array back into the hook-owned state — the controlled-data echo the undo/redo flow relies on. */\n  onDataChange: (next: readonly TData[], change: DataChange<TData>) => void;\n  /** The grid's `plugins` prop: the `plugins` option, then the history plugin (observer + `undo`/`redo` commands + api stash). */\n  plugins: readonly DataGridPlugin<TData>[];\n  /**\n   * For a toolbar's undo/redo buttons, outside the spreadable `DataGrid` props. `clear` empties\n   * both stacks for an imperative reset — it lives on this sub-object, not the\n   * spreadable top level, to avoid a future prop-name collision on the `<DataGrid {...grid} />`\n   * spread.\n   */\n  history: {\n    canUndo: boolean;\n    canRedo: boolean;\n    /** Number of entries on the undo stack; 0 when there is nothing to undo. */\n    historySize: number;\n    undo: () => void;\n    redo: () => void;\n    clear: () => void;\n    /**\n     * Applies a programmatic change (the consumer-built operation batch) to the grid AND registers it as\n     * one undo entry — one `commitChange` write, recorded by the history plugin's observer.\n     * Returns the same result as `useDataGridHistory`'s `record`.\n     */\n    record: (change: RecordedChange<TData>, label?: string) => boolean;\n    /** Reverts a change whose save failed; see `useDataGridHistory`'s `rollback`. */\n    rollback: (change: DataChange<TData>) => void;\n  };\n};\n\nconst NO_PLUGINS: readonly never[] = [];\n\nconst entryIds = new WeakMap<object, number>();\nlet nextEntryId = 0;\n\nfunction entryIdOf(entry: object): number {\n  let id = entryIds.get(entry);\n  if (id === undefined) entryIds.set(entry, (id = nextEntryId++));\n  return id;\n}\n\nclass EntriesHolder<T> {\n  private key: string | null = null;\n  private entries: readonly T[] = [];\n\n  /** The entries held for `key`: the last entries with an equal key, so a new array of equal entries keeps the identity. */\n  hold(key: string, entries: readonly T[]): readonly T[] {\n    if (key !== this.key) [this.key, this.entries] = [key, entries];\n    return this.entries;\n  }\n}\n\n// Keyed by entry identity and held outside state, so a new inline entry on every render gives a new array instead of a render loop.\nfunction useStableEntries<T extends object>(entries: readonly T[]): readonly T[] {\n  const [holder] = useState(() => new EntriesHolder<T>());\n  return holder.hold(entries.map(entryIdOf).join(\",\"), entries);\n}\n\n/**\n * Quick-start grid state with undo/redo: wires `useState` + {@link useDataGridHistory}\n * into one spreadable object.\n *\n * The hook owns the array between renders and spreads it into the grid as a controlled `data` prop.\n * Do not pass `defaultData` or your own `data` alongside the spread. `useDataGridHistory` alone\n * also gives undo/redo to a grid that owns `defaultData`. `defaultRows` seeds the state once; later\n * changes to it are ignored.\n *\n * ```tsx\n * const grid = useDataGridState(rows, { getRowId: (r) => r.id });\n * <DataGrid {...grid} columns={columns} />\n * ```\n */\nexport function useDataGridState<TData>(\n  defaultRows: readonly TData[],\n  opts: UseDataGridStateOptions<TData> = {},\n): UseDataGridStateResult<TData> {\n  const { getRowId, plugins: extraPlugins = NO_PLUGINS, ...historyOptions } = opts;\n  const [data, setData] = useState<readonly TData[]>(defaultRows);\n  const history = useDataGridHistory<TData>(historyOptions);\n  // stable identity: useDataGridRowIdToViewRow keys its O(n) Map build on getRowId identity.\n  const wrappedGetRowId = useCallback((row: TData, index: number) => getRowId!(row, index), [getRowId]);\n  const gridGetRowId = getRowId ? wrappedGetRowId : undefined;\n\n  const onDataChange = useCallback((next: readonly TData[]) => {\n    setData(next);\n  }, []);\n\n  const historyPlugin = history.plugin;\n  // the config phase keys its sync on array identity, so equal entries keep the last array\n  const plugins = useStableEntries([...extraPlugins, historyPlugin]);\n\n  return {\n    data,\n    getRowId: gridGetRowId,\n    onDataChange,\n    plugins,\n    history: {\n      canUndo: history.canUndo,\n      canRedo: history.canRedo,\n      historySize: history.historySize,\n      undo: history.undo,\n      redo: history.redo,\n      clear: history.clear,\n      record: history.record,\n      rollback: history.rollback,\n    },\n  };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-history/use-data-grid-state.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
