{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-find-replace",
  "title": "Data Grid Find and Replace",
  "author": "gridcn",
  "description": "Find-and-replace add-on for the gridcn data grid: useDataGridFindReplace returns a plugin that adds a panel (Mod+F finds, Ctrl+H replaces) sharing the quick search, with match case and whole cell options. Replace and Replace all write through each column's text codec and validation as one undoable change; planReplace is the pure planner behind them. Strings live under labels.findReplace.",
  "dependencies": [
    "lucide-react@^1.46.0"
  ],
  "registryDependencies": [
    "@gridcn/data-grid",
    "button",
    "input",
    "input-group",
    "@gridcn/use-debounce",
    "@gridcn/data-grid-pagination"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-find-replace/data-grid-find-replace.ts",
      "content": "/** Public entry point for the data-grid-find-replace add-on — the only module consumers should import from. */\r\n\r\nexport {\r\n  useDataGridFindReplace,\r\n  type UseDataGridFindReplaceOptions,\r\n  type UseDataGridFindReplaceResult,\r\n} from \"./use-data-grid-find-replace\";\r\nexport { planReplace, type ReplaceOptions, type ReplacePlan, type ReplaceSkipReason, type ReplaceState } from \"./plan-replace\";\r\n\n// Relative on purpose: the shadcn CLI rewrites import paths, never augmentation module names.\ndeclare module \"../data-grid/types\" {\n  interface GridActions {\n    openFindReplace: true;\n    openFind: true;\n  }\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-find-replace/data-grid-find-replace.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-find-replace/use-data-grid-find-replace.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useMemo, useState, type ComponentType } from \"react\";\nimport type { DataGridPlugin } from \"@/registry/default/components/data-grid/data-grid\";\nimport { FindReplacePanel, type PanelStore } from \"./find-replace-panel\";\nimport type { PanelOptions } from \"./find-replace-panel\";\nimport type { ReplaceOptions } from \"./plan-replace\";\n\nexport type UseDataGridFindReplaceOptions = Pick<ReplaceOptions, \"scope\" | \"replaceAllLimit\"> & {\n  /**\n   * Runs after the plan is built and before it is written. Return the plan to write (it may add, drop, or\n   * change patches), or `false` to cancel. The returned plan may hold at most `replaceAllLimit` patches;\n   * more cancels the replace. A string patch value for a cell that holds a non-string (a number cell, say) runs through the column's `fromText`; an unparseable one is skipped. Every other value is written as given. Each patch still goes through the column's `validate`.\n   * A patched row that changes or goes away, a `readOnly` grid, or an open cell editor also cancels. `signal` aborts when the find text, the replacement, or an option changes, a newer replace starts, or the panel closes; a late answer is dropped.\n   */\n  processReplace?: PanelOptions[\"processReplace\"];\n  /** Merged into the class list of the panel root. */\n  className?: string;\n  /**\n   * `\"loaded\"` (default) steps through the matches of the loaded rows. `\"result\"` states that the server narrows the result by `spec.searchText`:\n   * the count line shows the size of the result, and Next and Previous go on into rows that are not loaded (scroll scrolls there, pages asks for the next page).\n   * Replace and Replace all stay on loaded rows. A grid that holds every row behaves the same in both.\n   */\n  findScope?: \"loaded\" | \"result\";\n};\n\nexport type UseDataGridFindReplaceResult = {\n  /** One entry of the grid's `plugins` prop: the panel, the `openFindReplace` and `openFind` commands, and their `shift+alt+Enter` and `mod+f` bindings. */\n  plugin: DataGridPlugin<unknown>;\n  /** Opens the panel; `\"find\"` (default, as Mod+F) hides the Replace field until the user expands it, `\"replace\"` shows it. */\n  open: (mode?: \"find\" | \"replace\") => void;\n  close: () => void;\n};\n\nfunction createPanelStore(): PanelStore {\n  const listeners = new Set<() => void>();\n  let state = { open: false, mode: \"replace\" as \"find\" | \"replace\", openCount: 0 };\n  let options: PanelOptions = {};\n  return {\n    getOptions: () => options,\n    setOptions(next) {\n      const classNameChanged = options.className !== next.className || options.findScope !== next.findScope;\n      options = next;\n      if (!classNameChanged) return;\n      state = { ...state };\n      listeners.forEach((listener) => listener());\n    },\n    getState: () => state,\n    subscribe(listener) {\n      listeners.add(listener);\n      return () => listeners.delete(listener);\n    },\n    open(mode) {\n      state = { open: true, mode, openCount: state.openCount + 1 };\n      listeners.forEach((listener) => listener());\n    },\n    setMode(mode) {\n      if (!state.open || state.mode === mode) return;\n      state = { ...state, mode };\n      listeners.forEach((listener) => listener());\n    },\n    close() {\n      if (!state.open) return;\n      state = { ...state, open: false };\n      listeners.forEach((listener) => listener());\n    },\n  };\n}\n\n/**\n * Find and replace for a grid: a panel with Find and Replace fields that shares the quick search\n * (highlights, next/previous) and writes through each column's text codec as one undoable change.\n * Pass `plugin` in the grid's `plugins`; `shift+alt+Enter` opens it with Replace and `mod+f` opens it with Find only.\n */\nexport function useDataGridFindReplace(options: UseDataGridFindReplaceOptions = {}): UseDataGridFindReplaceResult {\n  const [panelStore] = useState(createPanelStore);\n  useEffect(() => {\n    panelStore.setOptions(options);\n  });\n\n  const plugin = useMemo<DataGridPlugin<unknown>>(() => {\n    const Mount: ComponentType = function FindReplaceMount() {\n      return <FindReplacePanel panelStore={panelStore} />;\n    };\n    return {\n      name: \"find-replace\",\n      Mount,\n      commands: {\n        openFindReplace: {\n          run: (ctx) => panelStore.open(ctx.readOnly ? \"find\" : \"replace\"),\n        },\n        openFind: {\n          run: () => panelStore.open(\"find\"),\n        },\n      },\n      keymap: { openFindReplace: [\"shift+alt+Enter\"], openFind: [\"mod+f\"] },\n    };\n  }, [panelStore]);\n\n  return useMemo(\n    () => ({ plugin, open: (mode = \"find\") => panelStore.open(mode), close: () => panelStore.close() }),\n    [plugin, panelStore],\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-find-replace/use-data-grid-find-replace.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-find-replace/find-replace-panel.tsx",
      "content": "\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type ChangeEvent,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type ReactNode,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { CaseSensitive, ChevronDown, ChevronRight, ChevronUp, Replace, ReplaceAll, WholeWord, X } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from \"@/components/ui/input-group\";\nimport { cn } from \"@/lib/utils\";\nimport { useDebouncedInput } from \"@/registry/default/components/gridcn/use-debounce\";\nimport {\n  useDataGridApi,\n  useDataGridLabels,\n  useDataGridReadOnly,\n  useDataGridScrollToCellAt,\n  useDataGridSearchText,\n} from \"@/registry/default/components/data-grid/data-grid\";\nimport {\n  GRID_ATTR,\n  type GateAbortReason,\n  type GateRun,\n  isComposingKey,\n  isDev,\n  useDataGridInputDebounce,\n  useDataGridInstanceId,\n  useDataGridGateTracker,\n  useDataGridSelector,\n  useDataGridSearchCapped,\n  useDataGridSearchMatches,\n  effectivePage,\n  dataIndexOf,\n  fullViewOf,\n  pageOfFullRow,\n  pageStartOf,\n  pageUnitsOf,\n} from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { useFindResultWalk } from \"./use-find-result-walk\";\nimport { MAX_REPLACE_INPUT_LENGTH, parseReturnedPatches, planReplace, resolveReplaceLimit, type ReplaceOptions, type ReplacePlan } from \"./plan-replace\";\n\nexport type PanelStore = {\n  getOptions(): PanelOptions;\n  setOptions(options: PanelOptions): void;\n  getState(): { open: boolean; mode: \"find\" | \"replace\"; openCount: number };\n  subscribe(listener: () => void): () => void;\n  open(mode: \"find\" | \"replace\"): void;\n  setMode(mode: \"find\" | \"replace\"): void;\n  close(): void;\n};\n\n/** Replace options plus the panel's own. */\nexport type PanelOptions = ReplaceOptions & {\n  processReplace?: (ctx: { plan: ReplacePlan; signal: AbortSignal }) => ReplacePlan | false | Promise<ReplacePlan | false>;\n  className?: string;\n  findScope?: \"loaded\" | \"result\";\n};\n\ntype PanelProps = { panelStore: PanelStore };\n\ntype Status = { kind: \"replaced\"; replaced: number; skipped: number; more: boolean } | { kind: \"validating\" } | { kind: \"cancelled\" } | null;\n\n\n/** True when a row the plan writes is gone or is another object since the plan was built. */\nfunction patchedRowsChanged(before: { data: readonly unknown[]; getRowId: (row: never, index: number) => string }, after: { data: readonly unknown[]; getRowId: (row: never, index: number) => string }, plan: ReplacePlan): boolean {\n  const ids = new Set(plan.patches.map((patch) => patch.rowId));\n  const rowsBefore = new Map<string, unknown>();\n  before.data.forEach((row, index) => {\n    if (row === undefined) return;\n    const id = before.getRowId(row as never, index);\n    if (ids.has(id)) rowsBefore.set(id, row);\n  });\n  let seen = 0;\n  for (let index = 0; index < after.data.length; index++) {\n    const row = after.data[index];\n    if (row === undefined) continue;\n    const id = after.getRowId(row as never, index);\n    if (!rowsBefore.has(id)) continue;\n    seen++;\n    if (rowsBefore.get(id) !== row) return true;\n  }\n  return seen < rowsBefore.size;\n}\n\nfunction isUsablePlan(plan: unknown, limit: number): plan is ReplacePlan {\n  if (typeof plan !== \"object\" || plan === null) return false;\n  const { patches } = plan as { patches?: unknown };\n  if (!Array.isArray(patches) || patches.length > limit) return false;\n  return patches.every((patch: unknown) => typeof patch === \"object\" && patch !== null && typeof (patch as { rowId?: unknown }).rowId === \"string\" && typeof (patch as { columnId?: unknown }).columnId === \"string\");\n}\n\nexport function FindReplacePanel({ panelStore }: PanelProps): ReactNode {\n  const { open, mode, openCount } = useSyncExternalStore(panelStore.subscribe, panelStore.getState, panelStore.getState);\n  if (!open) return null;\n  return createPortal(<PanelBody key={openCount} panelStore={panelStore} showReplace={mode === \"replace\"} />, document.body);\n}\n\nfunction PanelBody({ panelStore, showReplace }: PanelProps & { showReplace: boolean }): ReactNode {\n  const api = useDataGridApi();\n  const labels = useDataGridLabels().findReplace;\n  const readOnly = useDataGridReadOnly();\n  const instanceId = useDataGridInstanceId();\n  const replaceRowId = useId();\n  const matches = useDataGridSearchMatches();\n  const capped = useDataGridSearchCapped();\n  const searchedText = useDataGridSearchText();\n  const scrollToCell = useDataGridScrollToCellAt();\n  const resultExceedsLoaded = useDataGridSelector<unknown, boolean>((state) => state.totalRowCount !== undefined || state.sortMode === \"server\" || state.filterMode === \"server\");\n  const resultScope = resultExceedsLoaded && panelStore.getOptions().findScope === \"result\";\n  const scopeText = resultScope ? labels.scopeResult : labels.scopeLoadedRows;\n  const showScope = resultExceedsLoaded && scopeText !== \"\";\n  const totalRowCount = useDataGridSelector<unknown, number | null | undefined>((state) => state.totalRowCount);\n  const sortState = useDataGridSelector<unknown, unknown>((state) => state.sortState);\n  const filterState = useDataGridSelector<unknown, unknown>((state) => state.filterState);\n  const scopeId = useId();\n\n  const delayMs = useDataGridInputDebounce();\n  const [replacement, setReplacement] = useState(\"\");\n  const [searchOptions, setSearchOptions] = useState(() => api.store.getState().searchOptions);\n  const [storedCursor, setCursor] = useState(0);\n  const cursor = Math.max(0, Math.min(storedCursor, matches.length - 1));\n  // restart at the first hit during render when the query changes; a data change keeps the position\n  const queryKey = `${JSON.stringify(searchedText)}${searchOptions.matchCase}${searchOptions.wholeCell}`;\n  const [lastQueryKey, setLastQueryKey] = useState(queryKey);\n  if (lastQueryKey !== queryKey) {\n    setLastQueryKey(queryKey);\n    setCursor(0);\n  }\n  const [status, setStatus] = useState<Status>(null);\n  const [position, setPosition] = useState<{ top: number; end: number; rtl: boolean }>({ top: 8, end: 8, rtl: false });\n  const findRef = useRef<HTMLInputElement | null>(null);\n  const applyTokenRef = useRef(0);\n  const hookRunRef = useRef<GateRun | null>(null);\n  const gates = useDataGridGateTracker();\n  const abortHook = (reason?: GateAbortReason) => {\n    if (hookRunRef.current) gates.abortRun(hookRunRef.current, reason);\n  };\n  const replacedRef = useRef<Map<string, Set<string>>>(new Map());\n  const [opener] = useState(() => {\n    const grid = document.querySelector(`[${GRID_ATTR.instance}=\"${CSS.escape(instanceId)}\"]`);\n    return grid !== null && grid.contains(document.activeElement) ? (document.activeElement as HTMLElement) : null;\n  });\n\n  useEffect(() => {\n    findRef.current?.focus();\n    findRef.current?.select();\n    return () => {\n      applyTokenRef.current++;\n      abortHook(\"cancelled\");\n    };\n  }, []);\n\n  const findInput = useDebouncedInput(searchedText, (text) => api.actions.setSearch(text, searchOptions), { delayMs });\n  const find = findInput.inputValue;\n  const jumpOnCommitRef = useRef<string | null>(null);\n\n  useEffect(() => {\n    replacedRef.current.clear();\n    setStatus(null);\n    applyTokenRef.current++;\n    abortHook();\n  }, [searchedText, searchOptions]);\n\n  const closePanel = () => {\n    panelStore.close();\n    if (!opener) return;\n    if (opener.isConnected && opener.closest(\"[role='columnheader']\")) opener.focus();\n    else api.focus();\n  };\n\n  useLayoutEffect(() => {\n    const place = () => {\n      const grid = document.querySelector(`[${GRID_ATTR.instance}=\"${CSS.escape(instanceId)}\"]`);\n      if (!grid) return;\n      const rect = grid.getBoundingClientRect();\n      const top = Math.max(8, rect.top + 8);\n      const rtl = getComputedStyle(grid).direction === \"rtl\";\n      const end = Math.max(8, (rtl ? rect.left : window.innerWidth - rect.right) + 24);\n      setPosition((current) => (current.top === top && current.end === end && current.rtl === rtl ? current : { top, end, rtl }));\n    };\n    place();\n    window.addEventListener(\"resize\", place);\n    window.addEventListener(\"scroll\", place, true);\n    // the root settles its `dir` after the first paint\n    const grid = document.querySelector(`[${GRID_ATTR.instance}=\"${CSS.escape(instanceId)}\"]`);\n    const observer = new MutationObserver(place);\n    if (grid) observer.observe(grid, { attributes: true, attributeFilter: [\"dir\"] });\n    return () => {\n      window.removeEventListener(\"resize\", place);\n      window.removeEventListener(\"scroll\", place, true);\n      observer.disconnect();\n    };\n  }, [instanceId]);\n\n  const runSearch = (text: string, options: { matchCase: boolean; wholeCell: boolean }) => {\n    findInput.cancel();\n    api.actions.setSearch(text, options);\n  };\n\n  const goTo = useCallback(\n    (index: number) => {\n      const list = api.store.getState().searchMatches;\n      if (list.length === 0) return;\n      const wrapped = ((index % list.length) + list.length) % list.length;\n      setCursor(wrapped);\n      const match = list[wrapped]!;\n      const col = api.store.getState().visibleColumns.findIndex((c) => c.id === match.columnId);\n      if (col === -1) return;\n      const state = api.store.getState();\n      let row = match.row;\n      if (state.pageSize !== null) {\n        const full = fullViewOf(state.viewIndex);\n        const page = pageOfFullRow(full, match.row, state.pageSize);\n        if (effectivePage(state.page, pageUnitsOf(full), state.pageSize) !== page) api.actions.setPage(page);\n        if (api.store.getState().page !== page) return;\n        row = match.row - pageStartOf(api.store.getState().viewIndex);\n      }\n      api.actions.setActiveCellAt({ col, row });\n      scrollToCell({ col, row });\n    },\n    [api, scrollToCell],\n  );\n\n  const walkResetKey = useMemo(() => ({}), [queryKey, sortState, filterState]); // eslint-disable-line react-hooks/exhaustive-deps\n  const walk = useFindResultWalk({ enabled: resultScope, resetKey: walkResetKey, goTo });\n  const stepBy = (direction: 1 | -1) => {\n    if (!walk.step(direction, cursor)) goTo(cursor + direction);\n  };\n\n  // A controlled parent applies the committed text later, so the first match is known only once searchedText has caught up.\n  useEffect(() => {\n    if (jumpOnCommitRef.current === null || jumpOnCommitRef.current !== searchedText) return;\n    if (matches.length === 0) return;\n    jumpOnCommitRef.current = null;\n    goTo(0);\n  }, [searchedText, matches, goTo]);\n\n  const onFindChange = (event: ChangeEvent<HTMLInputElement>) => {\n    setStatus(null);\n    applyTokenRef.current++;\n    abortHook();\n    replacedRef.current.clear();\n    jumpOnCommitRef.current = null;\n    findInput.inputProps.onChange(event);\n  };\n\n  const toggle = (key: \"matchCase\" | \"wholeCell\") => {\n    const next = { ...searchOptions, [key]: !searchOptions[key] };\n    setSearchOptions(next);\n    setStatus(null);\n    replacedRef.current.clear();\n    runSearch(find, next);\n  };\n\n  const canReplace = !readOnly && find.trim() !== \"\";\n\n  const refOfIndex = (s: ReturnType<typeof api.store.getState>, index: number): { rowId: string; columnId: string } | null => {\n    const match = s.searchMatches[index];\n    if (!match) return null;\n    const dataIndex = dataIndexOf(fullViewOf(s.viewIndex), match.row);\n    const row = dataIndex === undefined ? undefined : s.data[dataIndex];\n    if (dataIndex === undefined || row === undefined) return null;\n    return { rowId: s.getRowId(row, dataIndex), columnId: match.columnId };\n  };\n\n  const refOfMatch = (): { ref: { rowId: string; columnId: string }; index: number } | null => {\n    const s = api.store.getState();\n    const active = s.activeCell;\n    const activeColumnId = active ? s.visibleColumns[active.col]?.id : undefined;\n    const start = pageStartOf(s.viewIndex);\n    const activeIndex = active ? s.searchMatches.findIndex((m) => m.row === active.row + start && m.columnId === activeColumnId) : -1;\n    const index = activeIndex === -1 ? cursor : activeIndex;\n    const ref = refOfIndex(s, index);\n    return ref ? { ref, index } : null;\n  };\n\n  const apply = (only: { rowId: string; columnId: string } | undefined, nextIndex = cursor) => {\n    const s = api.store.getState();\n    if (s.readOnly || s.editing !== null || find.trim() === \"\") return;\n    const replaced = replacedRef.current;\n    const replacedAt = only ? refOfIndex(s, nextIndex) : null;\n    const skip = only ? undefined : (ref: { rowId: string; columnId: string }) => replaced.get(ref.rowId)?.has(ref.columnId) === true;\n    const plan = planReplace(s, find, replacement, { ...panelStore.getOptions(), ...searchOptions, only, skip });\n    const run = (finalPlan: ReplacePlan) => {\n      if (!only) {\n        if (!finalPlan.remaining) replaced.clear();\n        else for (const { rowId, columnId } of finalPlan.patches) replaced.set(rowId, (replaced.get(rowId) ?? new Set()).add(columnId));\n      }\n      const verdict = finalPlan.patches.length === 0 ? null : api.actions.updateCells(finalPlan.patches, { source: \"replace\", reorder: \"defer\" });\n      const token = ++applyTokenRef.current;\n      const finish = (settled: { applied: number; skipped: readonly unknown[] } | null) => {\n        setStatus({\n          kind: \"replaced\",\n          replaced: settled?.applied ?? 0,\n          skipped: finalPlan.skipped.length + (settled?.skipped.length ?? 0),\n          more: finalPlan.remaining,\n        });\n        runSearch(find, searchOptions);\n        if (only) {\n          const after = api.store.getState();\n          const columnOrder = (columnId: string) => after.visibleColumns.findIndex((c) => c.id === columnId);\n          const afterView = fullViewOf(after.viewIndex);\n          const replacedRow = replacedAt ? afterView.findIndex((_, viewRow) => {\n            const dataIndex = dataIndexOf(afterView, viewRow);\n            const row = dataIndex === undefined ? undefined : after.data[dataIndex];\n            return dataIndex !== undefined && row !== undefined && after.getRowId(row, dataIndex) === replacedAt.rowId;\n          }) : -1;\n          const next =\n            replacedAt && replacedRow !== -1\n              ? after.searchMatches.findIndex((m) => m.row > replacedRow || (m.row === replacedRow && columnOrder(m.columnId) > columnOrder(replacedAt.columnId)))\n              : nextIndex;\n          goTo(next === -1 ? 0 : next);\n        }\n      };\n      if (verdict?.pending) {\n        setStatus({ kind: \"validating\" });\n        void verdict.settled?.then(\n          (settled) => {\n            if (token === applyTokenRef.current) finish(settled);\n          },\n          () => {\n            if (token === applyTokenRef.current) finish(null);\n          },\n        );\n        return;\n      }\n      finish(verdict);\n    };\n\n    const processReplace = panelStore.getOptions().processReplace;\n    if (!processReplace) {\n      run(plan);\n      return;\n    }\n    abortHook();\n    const hookRun = gates.begin(\"processReplace\", (now) => now.readOnly || now.editing !== null);\n    hookRunRef.current = hookRun;\n    const hookToken = ++applyTokenRef.current;\n    setStatus({ kind: \"validating\" });\n    const limit = resolveReplaceLimit(panelStore.getOptions().replaceAllLimit);\n    const current = () => hookToken === applyTokenRef.current && !hookRun.aborted;\n    hookRun.signal.addEventListener(\"abort\", () => {\n      if (hookToken === applyTokenRef.current) setStatus({ kind: \"cancelled\" });\n    });\n    gates.hold(hookRun);\n    void Promise.resolve()\n      .then(() => processReplace({ plan, signal: hookRun.signal }))\n      .then(\n        (result) => {\n          gates.settle(hookRun);\n          if (!current()) return;\n          const latest = api.store.getState();\n          if (latest.readOnly || latest.editing !== null || result === false) {\n            setStatus({ kind: \"cancelled\" });\n            return;\n          }\n          if (!isUsablePlan(result, limit)) {\n            if (isDev()) console.warn(\"[data-grid-find-replace] processReplace returned no plan or more patches than replaceAllLimit; the replace is cancelled\");\n            setStatus({ kind: \"cancelled\" });\n            return;\n          }\n          if (latest.data !== s.data && patchedRowsChanged(s, latest, result)) {\n            setStatus({ kind: \"cancelled\" });\n            return;\n          }\n          const visible = new Set(latest.visibleColumns.map((column) => column.id));\n          const hidden = result.patches.filter((patch) => !visible.has(patch.columnId));\n          const skipped = [...(Array.isArray(result.skipped) ? result.skipped : []), ...hidden.map(({ rowId, columnId }) => ({ ref: { rowId, columnId }, reason: \"hidden\" as const }))];\n          const shown = hidden.length > 0 ? result.patches.filter((patch) => visible.has(patch.columnId)) : result.patches;\n          const parsed = parseReturnedPatches(latest, shown);\n          run({ patches: parsed.patches, skipped: [...skipped, ...parsed.skipped], remaining: result.remaining === true });\n        },\n        (error: unknown) => {\n          gates.settle(hookRun);\n          if (!current()) return;\n          if (isDev()) console.warn(\"[data-grid-find-replace] processReplace threw; the replace is cancelled\", error);\n          setStatus({ kind: \"cancelled\" });\n        },\n      );\n  };\n\n  const replaceOne = () => {\n    const target = refOfMatch();\n    if (target) apply(target.ref, target.index);\n  };\n\n  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    event.stopPropagation();\n    if (isComposingKey(event)) return;\n    if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === \"f\") {\n      event.preventDefault();\n      findRef.current?.focus();\n      findRef.current?.select();\n      return;\n    }\n    if (event.key === \"Escape\") {\n      event.preventDefault();\n      findInput.cancel();\n      closePanel();\n    }\n  };\n\n  const onFindKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {\n    if (event.key !== \"Enter\" || isComposingKey(event)) return;\n    event.preventDefault();\n    if (findInput.inputValue !== searchedText) {\n      jumpOnCommitRef.current = findInput.inputValue;\n      findInput.flush();\n    } else stepBy(event.shiftKey ? -1 : 1);\n  };\n\n  const onReplaceKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {\n    if (event.key !== \"Enter\" || isComposingKey(event) || !canReplace) return;\n    event.preventDefault();\n    if (event.ctrlKey || event.metaKey) apply(undefined);\n    else replaceOne();\n  };\n\n  const hasMatches = matches.length > 0;\n  const resultHasRows = resultScope && typeof totalRowCount === \"number\" && totalRowCount > 0;\n  const canStep = hasMatches || (resultHasRows && find.trim() !== \"\" && searchedText === find);\n  const noResults = status === null && find.trim() !== \"\" && searchedText === find && !hasMatches && !resultHasRows;\n  const statusText = (() => {\n    if (status?.kind === \"validating\") return labels.validating;\n    if (status?.kind === \"cancelled\") return labels.replaceCancelled;\n    if (status?.kind === \"replaced\") return status.more ? labels.replacedAndMore(labels.replaced(status.replaced, status.skipped), labels.moreRemain) : labels.replaced(status.replaced, status.skipped);\n    if (find.trim() === \"\") return labels.typeToSearch;\n    if (searchedText !== find) return \"\";\n    if (resultScope && typeof totalRowCount === \"number\") return totalRowCount > 0 ? labels.resultRows(totalRowCount) : labels.noMatches;\n    return hasMatches ? labels.position(cursor + 1, matches.length, capped) : labels.noMatches;\n  })();\n\n  const optionToggle = (key: \"matchCase\" | \"wholeCell\", label: string, icon: ReactNode) => (\n    <Button\n      type=\"button\"\n      variant={searchOptions[key] ? \"default\" : \"ghost\"}\n      size=\"icon\"\n      title={label}\n      aria-label={label}\n      aria-pressed={searchOptions[key]}\n      data-state={searchOptions[key] ? \"on\" : \"off\"}\n      onClick={() => toggle(key)}\n      className={cn(\"shrink-0\", searchOptions[key] ? \"forced-colors:border-2 forced-colors:border-[Highlight] forced-colors:bg-[Highlight] forced-colors:text-[HighlightText]\" : \"text-muted-foreground\")}\n    >\n      {icon}\n    </Button>\n  );\n\n  // Not the Popover primitive: the panel docks to the grid corner without a trigger and keeps its own focus and Escape rules.\n  return (\n    <div\n      role=\"dialog\"\n      aria-label={labels.dialogLabel}\n      {...{ [GRID_ATTR.findReplacePanel]: \"\", [GRID_ATTR.keepFocus]: \"\" }}\n      onKeyDown={onKeyDown}\n      onCopy={(event) => event.stopPropagation()}\n      onCut={(event) => event.stopPropagation()}\n      onPaste={(event) => event.stopPropagation()}\n      // body-portaled: physical offsets and `dir` follow the grid, not the page\n      dir={position.rtl ? \"rtl\" : \"ltr\"}\n      style={{ position: \"fixed\", top: position.top, ...(position.rtl ? { left: position.end } : { right: position.end }), zIndex: 50, maxWidth: `calc(100vw - ${position.end}px - 8px)` }}\n      className={cn(\"flex w-80 flex-col gap-1 rounded-lg bg-popover p-2 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10\", panelStore.getOptions().className)}\n    >\n      <div className=\"flex items-center gap-1\">\n        {!readOnly && (\n          <Button\n            type=\"button\"\n            variant=\"ghost\"\n            size=\"icon-sm\"\n            className=\"size-8 shrink-0\"\n            aria-label={labels.toggleReplace}\n            aria-expanded={showReplace}\n            aria-controls={replaceRowId}\n            onClick={() => panelStore.setMode(showReplace ? \"find\" : \"replace\")}\n          >\n            <ChevronRight className={showReplace ? \"rotate-90\" : \"rtl:rotate-180\"} />\n          </Button>\n        )}\n        <div data-find-field=\"\" className=\"flex h-9 min-w-0 flex-1 items-center rounded-md border border-input bg-transparent pe-0.5 focus-within:ring-2 focus-within:ring-ring/50\">\n          <Input\n            ref={findRef}\n            maxLength={MAX_REPLACE_INPUT_LENGTH}\n            {...findInput.inputProps}\n            onChange={onFindChange}\n            onKeyDown={onFindKeyDown}\n            aria-label={labels.findLabel}\n            aria-describedby={showScope ? scopeId : undefined}\n            placeholder={labels.findLabel}\n            className=\"h-8 min-w-0 flex-1 border-0 bg-transparent shadow-none focus-visible:ring-0\"\n          />\n          {optionToggle(\"matchCase\", labels.matchCase, <CaseSensitive />)}\n          {optionToggle(\"wholeCell\", labels.wholeCell, <WholeWord />)}\n        </div>\n        <Button type=\"button\" variant=\"ghost\" size=\"icon-sm\" className=\"size-8 shrink-0\" aria-label={labels.previous} title={labels.previousTitle} disabled={!canStep} onClick={() => stepBy(-1)}>\n          <ChevronUp />\n        </Button>\n        <Button type=\"button\" variant=\"ghost\" size=\"icon-sm\" className=\"size-8 shrink-0\" aria-label={labels.next} title={labels.nextTitle} disabled={!canStep} onClick={() => stepBy(1)}>\n          <ChevronDown />\n        </Button>\n        <Button type=\"button\" variant=\"ghost\" size=\"icon-sm\" className=\"size-8 shrink-0\" aria-label={labels.close} title={labels.close} onClick={closePanel}>\n          <X />\n        </Button>\n      </div>\n      {showReplace && (\n        <div id={replaceRowId} className=\"flex items-center gap-1\">\n          {!readOnly && <span aria-hidden=\"true\" className=\"size-8 shrink-0\" />}\n          <InputGroup className=\"h-9 min-w-0 flex-1\">\n          <InputGroupInput\n            value={replacement}\n            maxLength={MAX_REPLACE_INPUT_LENGTH}\n            onChange={(event) => {\n              setReplacement(event.target.value);\n              replacedRef.current.clear();\n              applyTokenRef.current++;\n              abortHook();\n              setStatus(null);\n            }}\n            onKeyDown={onReplaceKeyDown}\n            aria-label={labels.replaceLabel}\n            placeholder={labels.replaceLabel}\n            disabled={readOnly}\n          />\n          <InputGroupAddon align=\"inline-end\">\n          <InputGroupButton size=\"icon-xs\" className=\"size-8\" aria-label={labels.replace} title={labels.replace} disabled={!canReplace || !hasMatches} onClick={replaceOne}>\n            <Replace />\n          </InputGroupButton>\n          <InputGroupButton size=\"icon-xs\" className=\"size-8\" aria-label={labels.replaceAll} aria-description={resultScope ? labels.replaceLoadedRows : undefined} title={resultScope ? labels.replaceLoadedRows : labels.replaceAll} disabled={!canReplace || !hasMatches} onClick={() => apply(undefined)}>\n            <ReplaceAll />\n          </InputGroupButton>\n          </InputGroupAddon>\n          </InputGroup>\n        </div>\n      )}\n      {showScope && (\n        <p id={scopeId} className=\"px-1 text-xs text-muted-foreground\">\n          {scopeText}\n        </p>\n      )}\n      <div role=\"status\" aria-live=\"polite\" aria-busy={walk.busy} title={statusText} className={cn(\"h-5 truncate px-1 font-mono text-xs tabular-nums\", noResults ? \"text-destructive\" : \"text-muted-foreground\")}>\n        {statusText}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-find-replace/find-replace-panel.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-find-replace/result-walk.ts",
      "content": "import { viewEntryAt } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\nexport type WalkDirection = 1 | -1;\n\ntype WalkView = { viewIndex: readonly number[]; data: readonly unknown[] };\n\n\n/** The first view row after `from` (before it for -1) whose data row is not loaded, or -1. */\nexport function nextHoleRow(s: WalkView, from: number, direction: WalkDirection): number {\n  for (let row = from + direction; row >= 0 && row < s.viewIndex.length; row += direction) {\n    if (viewEntryAt(s, row).kind === \"hole\") return row;\n  }\n  return -1;\n}\n\n/** The index of the first match past `origin` in `direction`, or -1; matches are in view order. */\nexport function matchPast(matches: readonly { row: number }[], origin: number, direction: WalkDirection): number {\n  if (direction === 1) return matches.findIndex((match) => match.row > origin);\n  for (let index = matches.length - 1; index >= 0; index--) if (matches[index]!.row < origin) return index;\n  return -1;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-find-replace/result-walk.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-find-replace/use-find-result-walk.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useDataGridApi, useDataGridScrollToCellAt } from \"@/registry/default/components/data-grid/data-grid\";\nimport { viewEntryAt } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { useStashedPager } from \"@/registry/default/components/data-grid-pagination/data-grid-pagination\";\nimport { matchPast, nextHoleRow, type WalkDirection } from \"./result-walk\";\n\nconst WAIT_LIMIT_MS = 15_000;\n\ntype Wait = { direction: WalkDirection; origin: number; hole: number; page: number; data: readonly unknown[] };\n\ntype Options = {\n  enabled: boolean;\n  /** A change of this key (find text, options, spec) drops a running wait. */\n  resetKey: unknown;\n  goTo: (index: number) => void;\n};\n\n/** Steps Next and Previous past the loaded rows of a server grid: scrolls to the next unloaded row, or asks for the next page, then activates the first match that arrives. */\nexport function useFindResultWalk({ enabled, resetKey, goTo }: Options) {\n  const api = useDataGridApi();\n  const scrollToCell = useDataGridScrollToCellAt();\n  const pager = useStashedPager();\n  const pagerRef = useRef(pager);\n  const goToRef = useRef(goTo);\n  useEffect(() => {\n    pagerRef.current = pager;\n    goToRef.current = goTo;\n  });\n  const waitRef = useRef<Wait | null>(null);\n  const stopRef = useRef<(() => void) | null>(null);\n  const [busy, setBusy] = useState(false);\n\n  const cancel = useCallback(() => {\n    stopRef.current?.();\n    stopRef.current = null;\n    waitRef.current = null;\n    setBusy(false);\n  }, []);\n\n  const request = useCallback(\n    (wait: Wait) => {\n      waitRef.current = wait;\n      if (wait.hole >= 0) scrollToCell({ col: 0, row: wait.hole });\n      else pagerRef.current?.onPageChange(wait.page);\n    },\n    [scrollToCell],\n  );\n\n  const check = useCallback(() => {\n    const wait = waitRef.current;\n    if (!wait) return;\n    const s = api.store.getState();\n    const byPage = wait.hole < 0;\n    if (byPage ? s.data === wait.data : viewEntryAt(s, wait.hole).kind === \"hole\") return;\n    const found = matchPast(s.searchMatches, wait.origin, wait.direction);\n    if (found >= 0) {\n      cancel();\n      goToRef.current(found);\n      return;\n    }\n    if (byPage) {\n      const next = wait.page + wait.direction;\n      const reachable = next >= 1 && next <= (pagerRef.current?.pageCount ?? 0);\n      if (!reachable) return cancel();\n      request({ ...wait, page: next, data: s.data });\n      return;\n    }\n    const hole = nextHoleRow(s, wait.hole, wait.direction);\n    if (hole === -1) return cancel();\n    request({ ...wait, hole });\n  }, [api, cancel, request]);\n\n  const step = useCallback(\n    (direction: WalkDirection, cursor: number): boolean => {\n      if (!enabled) return false;\n      if (waitRef.current) return true;\n      const s = api.store.getState();\n      const matches = s.searchMatches;\n      const atEdge = matches.length === 0 || (direction === 1 ? cursor >= matches.length - 1 : cursor <= 0);\n      if (!atEdge) return false;\n      const origin = matches.length > 0 ? matches[cursor]!.row : direction === 1 ? -1 : s.viewIndex.length;\n      const paged = s.pageSize === null && typeof s.totalRowCount === \"number\" && pagerRef.current !== null;\n      let wait: Wait;\n      if (paged) {\n        const page = pagerRef.current!.page + direction;\n        if (page < 1 || page > pagerRef.current!.pageCount) return false;\n        wait = { direction, origin: direction === 1 ? -1 : Number.MAX_SAFE_INTEGER, hole: -1, page, data: s.data };\n      } else {\n        const hole = nextHoleRow(s, origin, direction);\n        if (hole === -1) return false;\n        wait = { direction, origin, hole, page: 0, data: s.data };\n      }\n      request(wait);\n      setBusy(true);\n      const unsubscribe = api.store.subscribe(check);\n      const timer = setTimeout(cancel, WAIT_LIMIT_MS);\n      stopRef.current = () => {\n        unsubscribe();\n        clearTimeout(timer);\n      };\n      return true;\n    },\n    [api, enabled, request, check, cancel],\n  );\n\n  useEffect(() => cancel, [resetKey, cancel]);\n\n  return { step, busy };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-find-replace/use-find-result-walk.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-find-replace/plan-replace.ts",
      "content": "import { type AnyColumnDef, type CellPatch, type CellRef, type SearchOptions } from \"@/registry/default/components/data-grid/data-grid\";\nimport { createTextMatcher, dataIndexOf, fullViewOf, isColumnReadOnly, isUnparseable, safeFromText, selectionContainsCell, toSafeText, type DataGridReadState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/** Longest find or replacement text; longer input is cut. */\nexport const MAX_REPLACE_INPUT_LENGTH = 1_000;\n/** Longest text one replaced cell may reach. */\nexport const MAX_REPLACED_CELL_LENGTH = 100_000;\nconst DEFAULT_REPLACE_ALL_LIMIT = 10_000;\nconst MAX_REPLACE_ALL_LIMIT = 100_000;\n\n/** The most cells one plan may target after `replaceAllLimit` is applied: default 10,000, clamped to 1..100,000. */\nexport function resolveReplaceLimit(replaceAllLimit: number | undefined): number {\n  return Math.min(Math.max(Math.floor(replaceAllLimit ?? DEFAULT_REPLACE_ALL_LIMIT) || 1, 1), MAX_REPLACE_ALL_LIMIT);\n}\n\n/** What `planReplace` reads from the grid. */\nexport type ReplaceState = Pick<DataGridReadState, \"data\" | \"viewIndex\" | \"visibleColumns\" | \"cellTypes\" | \"getRowId\" | \"selection\">;\n\nexport type ReplaceOptions = SearchOptions & {\n  /** `\"view\"` (default) covers every visible column of the rows the sort and filter leave, every page of a paged grid; `\"selection\"` covers the selected cells. */\n  scope?: \"view\" | \"selection\";\n  /** Most cells one plan targets; default 10,000, clamped to 1..100,000. */\n  replaceAllLimit?: number;\n  /** Leaves out the cells it returns `true` for; a continuation passes the cells an earlier plan replaced. */\n  skip?: (ref: CellRef) => boolean;\n};\n\n/** Why a cell is not replaced; `\"hidden\"` marks a `processReplace` patch on a hidden column, which the panel never writes. */\nexport type ReplaceSkipReason = \"readonly\" | \"unparseable\" | \"too-long\" | \"no-occurrence\" | \"hidden\";\n\nexport type ReplacePlan = {\n  patches: CellPatch[];\n  skipped: { ref: CellRef; reason: ReplaceSkipReason }[];\n  /** True when the limit stopped the scan and more cells match. */\n  remaining: boolean;\n};\n\ntype ColumnPlan = {\n  column: AnyColumnDef;\n  readValue: (row: unknown) => unknown;\n  readText: (value: unknown) => string;\n  fromText: (text: string) => { value: unknown; unparseable: boolean };\n  isEmpty: (value: unknown) => boolean;\n};\n\nfunction planColumn(column: AnyColumnDef, cellTypes: ReplaceState[\"cellTypes\"]): ColumnPlan | null {\n  const cellType = cellTypes[column.type ?? \"text\"];\n  if (!cellType || cellType.activate) return null;\n  const toText = cellType.toSearchText ?? cellType.toText;\n  const options = column.options;\n  const { accessorFn, accessorKey } = column;\n  return {\n    column,\n    readValue: accessorFn ? (row) => accessorFn(row) : (row) => (row as Record<string, unknown>)[accessorKey as string],\n    readText: (value) => {\n      if (value == null) return \"\";\n      try {\n        return toSafeText(toText(value, options));\n      } catch {\n        return toSafeText(value);\n      }\n    },\n    fromText: (text) => {\n      const parsed = safeFromText(cellType, text, options, undefined);\n      return { value: parsed.value, unparseable: isUnparseable(parsed) };\n    },\n    isEmpty: (value) => cellType.isEmpty(value),\n  };\n}\n\n/** Lowercases `text` for matching; `sourceAt` maps each folded index to its source index when lowercasing changed the length. */\nfunction foldText(text: string, matchCase: boolean): { folded: string; sourceAt: number[] | null } {\n  const lower = matchCase ? text : text.toLowerCase();\n  if (lower.length === text.length) return { folded: lower, sourceAt: null };\n  const parts: string[] = [];\n  const sourceAt: number[] = [];\n  for (let i = 0; i < text.length; ) {\n    const char = String.fromCodePoint(text.codePointAt(i)!);\n    const lowered = char.toLowerCase();\n    parts.push(lowered);\n    for (let k = 0; k < lowered.length; k++) sourceAt.push(i);\n    i += char.length;\n  }\n  return { folded: parts.join(\"\"), sourceAt };\n}\n\n/** Replaces every occurrence of `needle` in `text`; `null` when the result would pass the cell cap, `found: false` when no whole-character occurrence exists. */\nfunction replaceOccurrences(text: string, needle: string, replacement: string, matchCase: boolean): { text: string; found: boolean } | null {\n  const target = matchCase ? needle : needle.toLowerCase();\n  const { folded, sourceAt } = foldText(text, matchCase);\n  const startsOnChar = (at: number) => at === 0 || at === folded.length || sourceAt![at - 1] !== sourceAt![at];\n  const spans: [number, number][] = [];\n  let projected = text.length;\n  for (let from = 0; ; ) {\n    const at = folded.indexOf(target, from);\n    if (at === -1) break;\n    const end = at + target.length;\n    if (sourceAt && !(startsOnChar(at) && startsOnChar(end))) {\n      from = at + 1;\n      continue;\n    }\n    const start = sourceAt ? sourceAt[at]! : at;\n    const stop = sourceAt ? (end === folded.length ? text.length : sourceAt[end]!) : end;\n    spans.push([start, stop]);\n    projected += replacement.length - (stop - start);\n    if (projected > MAX_REPLACED_CELL_LENGTH) return null;\n    from = end;\n  }\n  let out = \"\";\n  let cursor = 0;\n  for (const [start, stop] of spans) {\n    out += text.slice(cursor, start) + replacement;\n    cursor = stop;\n  }\n  return { text: out + text.slice(cursor), found: spans.length > 0 };\n}\n\n/**\n * Plans a replace over the grid: the cells whose search text matches `find`, each with the value\n * its type parses from the replaced text. Pure — the caller writes the patches. Hole rows, hidden\n * columns, and filtered-out rows never appear; read-only cells and results the type cannot parse\n * are reported in `skipped`.\n */\nexport function planReplace(\n  state: ReplaceState,\n  find: string,\n  replacement: string,\n  options: ReplaceOptions & { only?: CellRef } = {},\n): ReplacePlan {\n  const plan: ReplacePlan = { patches: [], skipped: [], remaining: false };\n  const needle = find.slice(0, MAX_REPLACE_INPUT_LENGTH).trim();\n  const isMatch = createTextMatcher(needle, options);\n  if (isMatch === null) return plan;\n\n  const { matchCase = false, wholeCell = false, scope = \"view\", only, skip } = options;\n  const to = replacement.slice(0, MAX_REPLACE_INPUT_LENGTH);\n  const limit = resolveReplaceLimit(options.replaceAllLimit);\n  const columns = state.visibleColumns.map((column) => planColumn(column, state.cellTypes));\n\n  const visit = (colIndex: number, rowId: string, row: unknown): boolean => {\n    const entry = columns[colIndex];\n    if (!entry) return true;\n    const text = entry.readText(entry.readValue(row));\n    if (!isMatch(text)) return true;\n    const ref = { rowId, columnId: entry.column.id };\n    if (skip?.(ref)) return true;\n    if (isColumnReadOnly(entry.column, row)) {\n      plan.skipped.push({ ref, reason: \"readonly\" });\n      return true;\n    }\n    const replaced = wholeCell ? { text: to, found: true } : replaceOccurrences(text, needle, to, matchCase);\n    if (replaced === null) {\n      plan.skipped.push({ ref, reason: \"too-long\" });\n      return true;\n    }\n    if (!replaced.found) {\n      plan.skipped.push({ ref, reason: \"no-occurrence\" });\n      return true;\n    }\n    const next = replaced.text;\n    if (next === text) return true;\n    const { value, unparseable } = entry.fromText(next);\n    if (unparseable || (next.trim() !== \"\" && entry.isEmpty(value))) {\n      plan.skipped.push({ ref, reason: \"unparseable\" });\n      return true;\n    }\n    if (plan.patches.length >= limit) {\n      plan.remaining = true;\n      return false;\n    }\n    plan.patches.push({ ...ref, value });\n    return true;\n  };\n\n  const { data } = state;\n  const onlySelected = scope === \"selection\";\n  const viewIndex = onlySelected ? state.viewIndex : fullViewOf(state.viewIndex);\n  for (let viewRow = 0; viewRow < viewIndex.length; viewRow++) {\n    const dataIndex = dataIndexOf(viewIndex, viewRow);\n    const row = dataIndex === undefined ? undefined : data[dataIndex];\n    if (dataIndex === undefined || row === undefined) continue;\n    const rowId = state.getRowId(row, dataIndex);\n    if (only && only.rowId !== rowId) continue;\n    for (let col = 0; col < columns.length; col++) {\n      if (only && only.columnId !== state.visibleColumns[col]!.id) continue;\n      if (onlySelected && !selectionContainsCell(state.selection, { row: viewRow, col })) continue;\n      if (!visit(col, rowId, row)) return plan;\n    }\n    if (only) return plan;\n  }\n  return plan;\n}\n\n/**\n * Parses each string patch value the `processReplace` hook returns for a cell that does not hold a string, with the\n * column's `fromText`. An unparseable value drops the patch and lands in `skipped`.\n */\nexport function parseReturnedPatches(\n  state: Pick<ReplaceState, \"data\" | \"visibleColumns\" | \"cellTypes\" | \"getRowId\">,\n  patches: readonly CellPatch[],\n): Pick<ReplacePlan, \"patches\" | \"skipped\"> {\n  const wanted = new Set(patches.filter((patch) => typeof patch.value === \"string\").map((patch) => patch.rowId));\n  const rows = new Map<string, unknown>();\n  if (wanted.size > 0) {\n    state.data.forEach((row, index) => {\n      if (row === undefined) return;\n      const id = state.getRowId(row as never, index);\n      if (wanted.has(id) && !rows.has(id)) rows.set(id, row);\n    });\n  }\n  const columns = new Map<string, ColumnPlan | null>();\n  const out: CellPatch[] = [];\n  const skipped: ReplacePlan[\"skipped\"] = [];\n  for (const patch of patches) {\n    if (typeof patch.value !== \"string\" || !rows.has(patch.rowId)) {\n      out.push(patch);\n      continue;\n    }\n    if (!columns.has(patch.columnId)) {\n      const column = state.visibleColumns.find((candidate) => candidate.id === patch.columnId);\n      columns.set(patch.columnId, column ? planColumn(column, state.cellTypes) : null);\n    }\n    const entry = columns.get(patch.columnId);\n    const current = entry?.readValue(rows.get(patch.rowId));\n    if (!entry || current == null || typeof current === \"string\") {\n      out.push(patch);\n      continue;\n    }\n    const { value, unparseable } = entry.fromText(patch.value);\n    if (unparseable) skipped.push({ ref: { rowId: patch.rowId, columnId: patch.columnId }, reason: \"unparseable\" });\n    else out.push({ ...patch, value });\n  }\n  return { patches: out, skipped };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-find-replace/plan-replace.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
