{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-fill",
  "title": "Data Grid Fill",
  "author": "gridcn",
  "description": "Fill-handle add-on for the gridcn data grid: drag-to-tile with series inference (arithmetic runs, zero-padded numbers, prefix+number sequences), mod+D/mod+R keyboard fill, via the overlay-plugin seam, with zero core re-renders.",
  "dependencies": [
    "zustand@^5.0.15"
  ],
  "registryDependencies": [
    "@gridcn/data-grid"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-fill/compute-fill-target.ts",
      "content": "import type { ViewCoord, GridRect } from \"@/registry/default/components/data-grid/data-grid\";\r\n\r\n/** Which axes a fill-handle drag is permitted to snap to. */\r\nexport type AllowedFillDirections = \"orthogonal\" | \"horizontal\" | \"vertical\" | \"any\";\r\n\r\n/** Options for {@link computeFillTarget}. */\r\nexport type ComputeFillTargetOptions = {\r\n  allowedDirections: AllowedFillDirections;\r\n  rowCount: number;\r\n  colCount: number;\r\n};\r\n\r\nfunction isInside(rect: GridRect, x: number, y: number): boolean {\r\n  return x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;\r\n}\r\n\r\nfunction clampRect(rect: GridRect, colCount: number, rowCount: number): GridRect | null {\r\n  const x0 = Math.max(0, rect.x);\r\n  const y0 = Math.max(0, rect.y);\r\n  const x1 = Math.min(colCount, rect.x + rect.width);\r\n  const y1 = Math.min(rowCount, rect.y + rect.height);\r\n  if (x1 <= x0 || y1 <= y0) return null;\r\n  return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };\r\n}\r\n\r\n/**\r\n * Computes the fill-handle drag highlight: the strip extending `source` toward\r\n * `cursor` on a single axis (see `getClosestRect`). For `allowedDirections: \"any\"` this is instead the combined rect\r\n * (including `source`), covering the diagonal. Returns `null`\r\n * when the cursor is inside `source` (no fill) or when the resulting rect\r\n * clamps to nothing at the grid bounds.\r\n */\r\nexport function computeFillTarget(\r\n  source: GridRect,\r\n  cursor: ViewCoord,\r\n  opts: ComputeFillTargetOptions\r\n): GridRect | null {\r\n  let px = cursor.col;\r\n  let py = cursor.row;\r\n  const { allowedDirections } = opts;\r\n\r\n  if (allowedDirections === \"any\") {\r\n    if (isInside(source, px, py)) return null;\r\n    const x = Math.min(source.x, px);\r\n    const y = Math.min(source.y, py);\r\n    const width = Math.max(source.x + source.width, px + 1) - x;\r\n    const height = Math.max(source.y + source.height, py + 1) - y;\r\n    return clampRect({ x, y, width, height }, opts.colCount, opts.rowCount);\r\n  }\r\n\r\n  if (allowedDirections === \"vertical\") px = source.x;\r\n  if (allowedDirections === \"horizontal\") py = source.y;\r\n\r\n  if (isInside(source, px, py)) return null;\r\n\r\n  const distanceToLeft = px - source.x;\r\n  const distanceToRight = source.x + source.width - px;\r\n  const distanceToTop = py - source.y + 1;\r\n  const distanceToBottom = source.y + source.height - py;\r\n\r\n  const minDistance = Math.min(\r\n    allowedDirections === \"vertical\" ? Number.MAX_SAFE_INTEGER : distanceToLeft,\r\n    allowedDirections === \"vertical\" ? Number.MAX_SAFE_INTEGER : distanceToRight,\r\n    allowedDirections === \"horizontal\" ? Number.MAX_SAFE_INTEGER : distanceToTop,\r\n    allowedDirections === \"horizontal\" ? Number.MAX_SAFE_INTEGER : distanceToBottom\r\n  );\r\n\r\n  let strip: GridRect;\r\n  if (minDistance === distanceToBottom) {\r\n    strip = { x: source.x, y: source.y + source.height, width: source.width, height: py - source.y - source.height + 1 };\r\n  } else if (minDistance === distanceToTop) {\r\n    strip = { x: source.x, y: py, width: source.width, height: source.y - py };\r\n  } else if (minDistance === distanceToRight) {\r\n    strip = { x: source.x + source.width, y: source.y, width: px - source.x - source.width + 1, height: source.height };\r\n  } else {\r\n    strip = { x: px, y: source.y, width: source.x - px, height: source.height };\r\n  }\r\n\r\n  return clampRect(strip, opts.colCount, opts.rowCount);\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/compute-fill-target.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/data-grid-fill.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\r\nexport { useDataGridFill, type UseDataGridFillOptions, type UseDataGridFillResult, type ProcessFillContext } from \"./use-data-grid-fill\";\r\nexport { detectSeries, type SeriesDescriptor } from \"./fill\";\r\n\r\n// Relative on purpose: the shadcn CLI rewrites import paths, never augmentation module names.\r\ndeclare module \"../data-grid/types\" {\r\n  interface GridActions {\r\n    fillDown: true;\r\n    fillRight: true;\r\n  }\r\n}\r\n\r\n/** Offers the `fillDown`/`fillRight` global-shortcut flags — this add-on is what makes them do anything. */\r\ndeclare module \"../data-grid/keyboard/global-shortcuts\" {\r\n  interface DataGridGlobalShortcutActions {\r\n    fillDown: boolean;\r\n    fillRight: boolean;\r\n  }\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/data-grid-fill.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/fill-keymap.ts",
      "content": "import type { Keymap } from \"@/registry/default/components/data-grid/data-grid\";\n\nexport const FILL_KEYMAP: Keymap = {\n  fillDown: [\"mod+d\"],\n  fillRight: [\"mod+r\"],\n};\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/fill-keymap.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/detect-series.ts",
      "content": "/** Extrapolates a detected series to any index; `null` for a non-series (falls back to tiling). */\nexport type SeriesDescriptor = {\n  extrapolate(index: number): string;\n};\n\nconst NUMERIC_RE = /^-?\\d+(\\.\\d+)?$/;\nconst PADDED_INT_RE = /^\\d+$/;\nconst EPSILON = 1e-9;\nconst ISO_DATE_PREFIX_RE = /^[0-9]{4}-[0-9]{2}-$/;\n/** Longest digit run a double holds exactly; longer ids would extrapolate to wrong digits, so they tile. */\nconst MAX_EXACT_DIGITS = 15;\n\n/** Tile fallback for an index whose extrapolated number left the safe integer range. */\nfunction tile(values: readonly string[], index: number): string {\n  return values[((index % values.length) + values.length) % values.length]!;\n}\n\nfunction exceedsExactDigits(value: string): boolean {\n  return value.replace(/\\D/g, \"\").length > MAX_EXACT_DIGITS;\n}\n\n/**\n * Splits `value` into the maximal trailing digit run plus everything before/after it, by a linear\n * scan — a capture regex backtracks quadratically on a long digit run before a trailing digit.\n * `null` when `value` has no digit run.\n */\nfunction splitPrefixNumber(value: string): { prefix: string; digits: string; suffix: string } | null {\n  let suffixStart = value.length;\n  while (suffixStart > 0 && !/\\d/.test(value[suffixStart - 1]!)) suffixStart--;\n  let digitsStart = suffixStart;\n  while (digitsStart > 0 && /\\d/.test(value[digitsStart - 1]!)) digitsStart--;\n  if (digitsStart === suffixStart) return null;\n  return {\n    prefix: value.slice(0, digitsStart),\n    digits: value.slice(digitsStart, suffixStart),\n    suffix: value.slice(suffixStart),\n  };\n}\n\nfunction decimalPlaces(value: string): number {\n  const dotIndex = value.indexOf(\".\");\n  return dotIndex === -1 ? 0 : value.length - dotIndex - 1;\n}\n\nfunction detectArithmetic(values: readonly string[]): SeriesDescriptor | null {\n  // callers only reach here via detectSeries, which requires values.length >= 2\n  if (values.length < 2) return null;\n  const trimmed = values.map((v) => v.trim());\n  const nums = trimmed.map((v) => (NUMERIC_RE.test(v) ? Number(v) : null));\n  if (nums.some((n) => n === null) || trimmed.some(exceedsExactDigits)) return null;\n  const numbers = nums as number[];\n  const first = numbers[0]!;\n  const delta = numbers[1]! - first;\n  for (let i = 2; i < numbers.length; i++) {\n    if (Math.abs(numbers[i]! - numbers[i - 1]! - delta) > EPSILON) return null;\n  }\n  const precision = trimmed.reduce((max, v) => Math.max(max, decimalPlaces(v)), 0);\n  return {\n    extrapolate: (index: number) => {\n      const formatted = (first + delta * index).toFixed(precision);\n      return exceedsExactDigits(formatted) ? tile(values, index) : formatted;\n    },\n  };\n}\n\nfunction detectPaddedNumeric(values: readonly string[]): SeriesDescriptor | null {\n  if (values.length < 2) return null;\n  const trimmed = values.map((v) => v.trim());\n  if (!trimmed.every((v) => PADDED_INT_RE.test(v)) || trimmed.some(exceedsExactDigits)) return null;\n  if (!trimmed.some((v) => v.length > 1 && v.startsWith(\"0\"))) return null;\n  const width = trimmed[0]!.length;\n  if (!trimmed.every((v) => v.length === width)) return null;\n  const numbers = trimmed.map((v) => Number(v));\n  const first = numbers[0]!;\n  const delta = numbers[1]! - first;\n  for (let i = 2; i < numbers.length; i++) {\n    if (numbers[i]! - numbers[i - 1]! !== delta) return null;\n  }\n  return {\n    extrapolate: (index: number) => {\n      const n = first + delta * index;\n      if (!Number.isSafeInteger(n)) return tile(values, index);\n      const sign = n < 0 ? \"-\" : \"\";\n      const digits = String(Math.abs(n)).padStart(width, \"0\");\n      return sign + digits;\n    },\n  };\n}\n\nfunction detectPrefixNumber(values: readonly string[]): SeriesDescriptor | null {\n  if (values.length < 2) return null;\n  const splits = values.map((v) => splitPrefixNumber(v.trim()));\n  if (splits.some((s) => s === null)) return null;\n  const parsed = splits as { prefix: string; digits: string; suffix: string }[];\n  const prefix = parsed[0]!.prefix;\n  const suffix = parsed[0]!.suffix;\n  if (!parsed.every((p) => p.prefix === prefix && p.suffix === suffix)) return null;\n  if (parsed.some((p) => p.digits.length > MAX_EXACT_DIGITS)) return null;\n  if (parsed.every((p) => p.digits.length === 2 && ISO_DATE_PREFIX_RE.test(p.prefix.slice(-8)))) return null;\n\n  const numStrings = parsed.map((p) => p.digits);\n  const numbers = numStrings.map((n) => Number(n));\n  const width = numStrings[0]!.length;\n  const uniformWidth = numStrings.every((n) => n.length === width) && numStrings.some((n) => n.startsWith(\"0\"));\n\n  const first = numbers[0]!;\n  const delta = numbers[1]! - first;\n  for (let i = 2; i < numbers.length; i++) {\n    if (numbers[i]! - numbers[i - 1]! !== delta) return null;\n  }\n  return {\n    extrapolate: (index: number) => {\n      const n = first + delta * index;\n      if (!Number.isSafeInteger(n)) return tile(values, index);\n      const digits = uniformWidth && n >= 0 ? String(n).padStart(width, \"0\") : String(n);\n      return prefix + digits + suffix;\n    },\n  };\n}\n\n/**\n * Detects a fillable series in `values` (source cells along the fill axis, in\n * source order): arithmetic progressions, zero-padded numeric strings (pad\n * width preserved), or shared-prefix/suffix + arithmetic numeric part\n * (\"Item 1\", \"Item 2\"); an ISO date is no series, because its day would pass the end of the month. Requires at least 2 values with a consistent delta;\n * returns `null` when no pattern applies (caller falls back to tiling).\n */\nexport function detectSeries(values: readonly string[]): SeriesDescriptor | null {\n  if (values.length < 2) return null;\n  // padded numerics (\"001\") also match plain arithmetic, so check padding first or the leading zero is lost\n  return detectPaddedNumeric(values) ?? detectArithmetic(values) ?? detectPrefixNumber(values);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/detect-series.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/fill-direction.ts",
      "content": "import type { GridRect } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport type { FillDirection } from \"./generate-fill\";\r\n\r\n/**\r\n * Resolves the {@link FillDirection} implied by `strip`'s position relative to `source` — the\r\n * strip returned by `computeFillTarget` (or the collapsed top-row/left-column for fillDown/fillRight)\r\n * always extends `source` on exactly one axis, one side.\r\n */\r\nexport function fillDirection(source: GridRect, strip: GridRect): FillDirection {\r\n  if (strip.y + strip.height <= source.y) return \"up\";\r\n  if (strip.y >= source.y + source.height) return \"down\";\r\n  if (strip.x + strip.width <= source.x) return \"left\";\r\n  return \"right\";\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/fill-direction.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/fill-overlay.tsx",
      "content": "\"use client\";\r\n\r\nimport type { CSSProperties, ReactNode } from \"react\";\r\nimport type { GridRect, OverlayPluginCtx } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport { GRID_LAYER, hasAnyPin } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport type { FillHandleHandlers } from \"./use-fill-handle\";\r\n\r\n/** The dashed fill-drag preview rect, window-relative, grid-line placed like core's own RangeOverlay; pinned segments add their zone's counter-offset + z-index 2 (above pinned cells' z1). */\r\nfunction FillPreviewOverlay({ rect, windowStart, colOffset, pinStyle }: { rect: GridRect; windowStart: number; colOffset: number; pinStyle?: CSSProperties }) {\r\n  return (\r\n    <div\r\n      data-grid-fill-preview=\"\"\r\n      data-pinned={pinStyle ? \"\" : undefined}\r\n      aria-hidden=\"true\"\r\n      className=\"pointer-events-none border border-dashed border-primary bg-primary/5\"\r\n      style={{\r\n        // positioned: cells are position:relative, so a static overlay would paint below them;\r\n        // out-of-flow when unpinned, so moving it does not re-lay out the canvas grid\r\n        position: \"absolute\",\r\n        inset: 0,\r\n        gridColumnStart: rect.x + colOffset,\r\n        gridColumnEnd: rect.x + rect.width + colOffset,\r\n        gridRowStart: rect.y - windowStart + 1,\r\n        gridRowEnd: rect.y + rect.height - windowStart + 1,\r\n        ...(pinStyle ? { inset: undefined, ...pinStyle, zIndex: GRID_LAYER.pinnedOverlaySegment } : {}),\r\n      }}\r\n    />\r\n  );\r\n}\r\n\r\n/** The small draggable square at a range's bottom-right corner that starts a fill drag; adds the corner column's pin offset when it falls in a pinned zone. */\r\nfunction FillHandle({\r\n  rect,\r\n  windowStart,\r\n  colOffset,\r\n  pinStyle,\r\n  onPointerDown,\r\n}: {\r\n  rect: GridRect;\r\n  windowStart: number;\r\n  colOffset: number;\r\n  pinStyle?: CSSProperties;\r\n  onPointerDown: FillHandleHandlers[\"onPointerDown\"];\r\n}) {\r\n  return (\r\n    <div\r\n      data-grid-fill-handle=\"\"\r\n      // mouse-only drag affordance (Ctrl+D/Ctrl+R cover the keyboard-equivalent fill actions) — not\r\n      // focusable/operable via keyboard or AT, so it's hidden from the accessibility tree entirely.\r\n      aria-hidden=\"true\"\r\n      // grid-placed on the cell holding the range's bottom-right corner, self-aligned into that\r\n      // cell's own corner so it reads as sitting \"on\" the selection edge rather than centered in it.\r\n      className=\"pointer-events-auto relative z-20 size-2 place-self-end cursor-crosshair border border-background bg-primary before:absolute before:left-1/2 before:top-1/2 before:size-6 before:-translate-x-1/2 before:-translate-y-1/2 before:content-['']\"\r\n      style={{\r\n        gridColumnStart: rect.x + rect.width + colOffset - 1,\r\n        gridColumnEnd: rect.x + rect.width + colOffset,\r\n        gridRowStart: rect.y + rect.height - windowStart,\r\n        gridRowEnd: rect.y + rect.height - windowStart + 1,\r\n        ...pinStyle,\r\n      }}\r\n      onPointerDown={onPointerDown}\r\n    />\r\n  );\r\n}\r\n\r\n/**\r\n * Everything {@link renderFillOverlay} needs beyond the plugin `ctx` — the live selection/editing\r\n * state and drag preview, plus `onPointerDown` itself (sourced from the add-on's `fillStore`,\r\n * since the real handler is produced by the plugin's `Mount`, which renders in a different part of\r\n * the tree than this overlay — see fill-store.ts's doc comment on `onPointerDown`).\r\n */\r\nexport type FillOverlayState = {\r\n  fillPreview: GridRect | null;\r\n  /** Primary selection range (view-index), or `null` when there's no current range (row/column-channel-only selection, or a clear). */\r\n  primaryRange: GridRect | null;\r\n  /** True while a cell is being edited — hides the handle. */\r\n  editing: boolean;\r\n  /** Fill is disabled (grid readOnly or the add-on's `disabled: true` option), so the handle would be dead UI — hidden. */\r\n  disabled: boolean;\r\n  /** `null` before the plugin's `Mount` mounts — hides the handle. */\r\n  onPointerDown: FillHandleHandlers[\"onPointerDown\"] | null;\r\n};\r\n\r\n/**\r\n * Renders the fill-preview strip and the fill handle into the overlay layer using the SAME\r\n * window-clamp + pin-zone segmentation pipeline core's own built-in overlays use (via `ctx`).\r\n * The fill plugin's `Overlay` component is this render: preview before the active-cell ring (the\r\n * ring is core's own concern — see the ctx's doc comment on plugin placement), so DOM order\r\n * matches the built-in layers.\r\n */\r\nexport function renderFillOverlay(state: FillOverlayState, ctx: OverlayPluginCtx): ReactNode {\r\n  const { windowStart, clampRowStart, clampRowEnd, colCount, colOffset, pinTrack, selectionPointer, splitRectByPinZones, clampRectToWindow } = ctx;\r\n  const pinned = hasAnyPin(pinTrack) ? pinTrack : undefined;\r\n  const segment = (rect: GridRect) => (pinned ? splitRectByPinZones(rect, pinned) : [{ rect, pinStyle: undefined }]);\r\n\r\n  const clampedFillPreview = state.fillPreview ? clampRectToWindow(state.fillPreview, clampRowStart, clampRowEnd, colCount) : null;\r\n\r\n  // hidden while editing, when disabled (the fill would be dead UI), when selection is\r\n  // rows/columns-channel only (no `current` range), or before the plugin's `Mount` has registered a\r\n  // handler — the same guard the built-in layer uses.\r\n  const onPointerDown = state.onPointerDown;\r\n  const showFillHandle = onPointerDown && !state.editing && state.primaryRange && !state.disabled && selectionPointer !== \"touch\";\r\n  const clampedPrimary = state.primaryRange ? clampRectToWindow(state.primaryRange, clampRowStart, clampRowEnd, colCount) : null;\r\n  const cornerCol = state.primaryRange ? state.primaryRange.x + state.primaryRange.width - 1 : null;\r\n  const fillHandlePinStyle =\r\n    cornerCol !== null && pinned && pinned.pins[cornerCol] ? segment({ x: cornerCol, y: 0, width: 1, height: 1 })[0]?.pinStyle : undefined;\r\n\r\n  return (\r\n    <>\r\n      {clampedFillPreview &&\r\n        segment(clampedFillPreview).map((seg, j) => (\r\n          <FillPreviewOverlay key={`fill-preview-${j}`} rect={seg.rect} windowStart={windowStart} colOffset={colOffset} pinStyle={seg.pinStyle} />\r\n        ))}\r\n      {showFillHandle && clampedPrimary && state.primaryRange &&\r\n        clampedPrimary.y + clampedPrimary.height === state.primaryRange.y + state.primaryRange.height &&\r\n        clampedPrimary.x + clampedPrimary.width === state.primaryRange.x + state.primaryRange.width && (\r\n          <FillHandle\r\n            rect={state.primaryRange}\r\n            windowStart={windowStart}\r\n            colOffset={colOffset}\r\n            pinStyle={fillHandlePinStyle}\r\n            onPointerDown={onPointerDown}\r\n          />\r\n        )}\r\n    </>\r\n  );\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/fill-overlay.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/fill-store.ts",
      "content": "\"use client\";\r\n\r\nimport { createStore, type StoreApi } from \"zustand/vanilla\";\r\nimport { useStore } from \"zustand\";\r\nimport type { GridRect } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport type { FillHandleHandlers, UseFillHandleOptions } from \"./use-fill-handle\";\r\n\r\n/**\r\n * This add-on's own state slice: the in-progress drag preview rect, plus the live handlers the\r\n * plugin's `Overlay` and `commands` wire on (the pointerdown for the rendered handle square, the\r\n * mod+D/mod+R fill runs). Deliberately NOT part of the core store — core knows nothing about fill\r\n * past the generic `plugins` seam. The handlers are registered here (not read directly by the\r\n * plugin closures) because the plugin is created by `useDataGridFill` ABOVE `DataGridProvider`,\r\n * while the real handlers come from the plugin's `Mount`, which renders INSIDE `DataGridRoot`'s\r\n * own subtree (see fill-mount.tsx) — the store is what bridges them.\r\n */\r\nexport type FillStoreOptions = Pick<UseFillHandleOptions, \"disabled\" | \"processFill\" | \"detectSeries\">;\r\n\r\nexport type FillStoreState = {\r\n  /** The hook's latest options; a store field, so the overlay and mount update when a compiled consumer changes them. */\r\n  options: FillStoreOptions;\r\n  setOptions(options: FillStoreOptions): void;\r\n  fillPreview: GridRect | null;\r\n  setFillPreview(rect: GridRect | null): void;\r\n  onPointerDown: FillHandleHandlers[\"onPointerDown\"] | null;\r\n  setOnPointerDown(handler: FillHandleHandlers[\"onPointerDown\"] | null): void;\r\n  /** The mod+D/mod+R fill runs, registered by the plugin's `Mount`; `null` before it mounts. */\r\n  fillDown: (() => void) | null;\r\n  fillRight: (() => void) | null;\r\n  setFillShortcuts(shortcuts: { fillDown: () => void; fillRight: () => void } | null): void;\r\n};\r\n\r\nexport type FillStoreApi = StoreApi<FillStoreState>;\r\n\r\n/** One store instance per `useDataGridFill()` call, mirroring core's one-store-per-grid pattern and `data-grid-presence`'s own local store. */\r\nexport function createFillStore(options: FillStoreOptions = {}): FillStoreApi {\r\n  return createStore<FillStoreState>((set, get) => ({\r\n    options,\r\n    setOptions(next) {\r\n      const current = get().options;\r\n      if (current.disabled !== next.disabled || current.processFill !== next.processFill || current.detectSeries !== next.detectSeries) set({ options: next });\r\n    },\r\n    fillPreview: null,\r\n    setFillPreview(rect) {\r\n      set({ fillPreview: rect });\r\n    },\r\n    onPointerDown: null,\r\n    setOnPointerDown(handler) {\r\n      set({ onPointerDown: handler });\r\n    },\r\n    fillDown: null,\r\n    fillRight: null,\r\n    setFillShortcuts(shortcuts) {\r\n      set(shortcuts ? { fillDown: shortcuts.fillDown, fillRight: shortcuts.fillRight } : { fillDown: null, fillRight: null });\r\n    },\r\n  }));\r\n}\r\n\r\n/** The in-progress fill-drag preview rect, or `null` when no drag is active. Consumed by the overlay plugin — never by row/cell subscriptions. */\r\nexport function useFillPreview(store: FillStoreApi): GridRect | null {\r\n  return useStore(store, (s) => s.fillPreview);\r\n}\r\n\r\n/** The live pointerdown handler for the rendered fill handle, or `null` before the plugin's `Mount` mounts. */\r\nexport function useFillOnPointerDown(store: FillStoreApi): FillHandleHandlers[\"onPointerDown\"] | null {\r\n  return useStore(store, (s) => s.onPointerDown);\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/fill-store.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/fill-mount.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useMemo, useRef, type ReactNode } from \"react\";\nimport { useDataGridReadOnly } from \"@/registry/default/components/data-grid/data-grid\";\nimport { useDataGridRootContext, type InteractionLayout } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { useFillHandle, type UseFillHandleOptions } from \"./use-fill-handle\";\nimport type { FillStoreApi } from \"./fill-store\";\n\n/** Reconstructs the `InteractionLayout` `useGridInteraction`/pointer math needs from the shared root context — `DataGridRoot` computes the same shape internally (root.tsx's own `interactionLayout`) but doesn't expose it directly, since only this mount (and root itself) need it. */\nfunction useInteractionLayoutFromContext(): InteractionLayout {\n  const ctx = useDataGridRootContext();\n  const { layout, rowHeight, headerHeight, pinnedTopHeight, pinnedBottomHeight } = ctx;\n  return useMemo(() => {\n    // the marker column (when present) is always pinned-left before every data column — same\n    // derivation as root.tsx's own interactionLayout memo.\n    let pinnedLeftWidth = layout.markerWidth;\n    let pinnedRightWidth = 0;\n    for (let i = 0; i < layout.widths.length; i++) {\n      if (layout.pins[i] === \"start\") pinnedLeftWidth += layout.widths[i]!;\n      if (layout.pins[i] === \"end\") pinnedRightWidth += layout.widths[i]!;\n    }\n    return {\n      trackLefts: layout.trackLefts,\n      trackRights: layout.trackRights,\n      rowHeight,\n      dataRowTop: headerHeight + pinnedTopHeight,\n      pinnedBottomHeight,\n      pinnedLeftWidth,\n      pinnedRightWidth,\n      pins: layout.pins,\n    };\n  }, [layout, rowHeight, headerHeight, pinnedTopHeight, pinnedBottomHeight]);\n}\n\n/** Props for {@link FillMount} — everything `useFillHandle` needs except `scrollRef`/`layout` (read from context here, only available inside `DataGridRoot`'s own subtree). */\nexport type FillMountProps = Pick<UseFillHandleOptions, \"disabled\" | \"processFill\" | \"detectSeries\"> & {\n  fillStore: FillStoreApi;\n};\n\n/**\n * The fill engine, rendered inside `DataGridRoot` as the fill plugin's `Mount` (alongside its\n * children, by the core root itself — no consumer rendering required), because `scrollRef` and\n * the column layout `useFillHandle` needs for pointer math only exist inside `DataGridRoot`'s own\n * subtree. It registers the mod+D/mod+R runs into the add-on's own `fillStore` (the plugin's\n * `commands`, created above `DataGridProvider`, read them back) and cancels an in-progress drag\n * on an Escape keydown captured on the grid root. Renders nothing itself — the plugin's `Overlay`\n * paints the actual preview/handle DOM.\n */\nexport function FillMount(props: FillMountProps): ReactNode {\n  const layout = useInteractionLayoutFromContext();\n  const { scrollRef } = useDataGridRootContext();\n  // the grid's own readOnly disables fill too: core's write actions no-op there, so the handle,\n  // the drag, and the mod+D/mod+R shortcuts would all be dead UI without this.\n  const gridReadOnly = useDataGridReadOnly();\n  const disabled = props.disabled === true || gridReadOnly;\n  const handlers = useFillHandle({ ...props, disabled, scrollRef, layout });\n\n  // The plugin's `fillDown`/`fillRight` commands (merged into the grid's command map above it)\n  // run through this slot — the commands are created above `DataGridProvider`, the engine here.\n  useEffect(() => {\n    props.fillStore.getState().setFillShortcuts({ fillDown: handlers.fillDown, fillRight: handlers.fillRight });\n    return () => props.fillStore.getState().setFillShortcuts(null);\n  }, [props.fillStore, handlers.fillDown, handlers.fillRight]);\n\n  // The plugin's rendered handle square reads the live pointerdown handler from the SAME store —\n  // the only way the two ends meet (see fill-store.ts).\n  useEffect(() => {\n    props.fillStore.getState().setOnPointerDown(handlers.onPointerDown);\n    return () => props.fillStore.getState().setOnPointerDown(null);\n  }, [props.fillStore, handlers.onPointerDown]);\n\n  // Escape mid-drag cancels the drag before the grid's own keydown handling; the grid's `cancel`\n  // action still clears the selection.\n  const cancelDragRef = useRef(handlers.cancelFillDrag);\n  cancelDragRef.current = handlers.cancelFillDrag;\n  useEffect(() => {\n    const scrollElement = scrollRef.current;\n    if (!scrollElement) return;\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (event.key !== \"Escape\") return;\n      // no drag in progress: the Escape is the grid's own to handle\n      if (props.fillStore.getState().fillPreview === null) return;\n      cancelDragRef.current();\n    };\n    scrollElement.addEventListener(\"keydown\", onKeyDown, true);\n    return () => scrollElement.removeEventListener(\"keydown\", onKeyDown, true);\n  }, [scrollRef, props.fillStore]);\n\n  return null;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/fill-mount.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/fill.ts",
      "content": "import type { GridRect } from \"@/registry/default/components/data-grid/data-grid\";\r\n\r\nexport { computeFillTarget, type AllowedFillDirections, type ComputeFillTargetOptions } from \"./compute-fill-target\";\r\nexport { detectSeries, type SeriesDescriptor } from \"./detect-series\";\r\nexport { generateFill, type FillDirection, type GenerateFillOptions } from \"./generate-fill\";\r\nexport { fillDirection } from \"./fill-direction\";\r\n\r\n/** Re-expresses `rect` relative to `origin`'s top-left — `generateFill`'s `target` contract. */\r\nexport function rectRelativeTo(rect: GridRect, origin: GridRect): GridRect {\r\n  return { x: rect.x - origin.x, y: rect.y - origin.y, width: rect.width, height: rect.height };\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/fill.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/generate-fill.ts",
      "content": "import type { GridRect } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport { detectSeries, type SeriesDescriptor } from \"./detect-series\";\r\n\r\n/** Direction a fill drag or extrapolation extends in. */\r\nexport type FillDirection = \"up\" | \"down\" | \"left\" | \"right\";\r\n\r\n/** Options for {@link generateFill}. */\r\nexport type GenerateFillOptions = {\r\n  /** Forces modulo tiling even when a series is detected; the fill handle sets it when Alt (Option) is held at release. */\r\n  forceCopy?: boolean;\r\n  /**\r\n   * Series detector replacing the built-in `detectSeries` (arithmetic, zero-padded,\r\n   * prefix+number). Called per source row/column along the fill axis; `null` falls back to\r\n   * tiling.\r\n   */\r\n  detect?: (values: readonly string[]) => SeriesDescriptor | null;\r\n};\r\n\r\nfunction directionAxis(direction: FillDirection): \"vertical\" | \"horizontal\" {\r\n  return direction === \"up\" || direction === \"down\" ? \"vertical\" : \"horizontal\";\r\n}\r\n\r\nfunction fillCell(\r\n  source: string[][],\r\n  series: (SeriesDescriptor | null)[],\r\n  axis: \"vertical\" | \"horizontal\",\r\n  absCol: number,\r\n  absRow: number,\r\n  srcW: number,\r\n  srcH: number\r\n): string {\r\n  if (axis === \"vertical\") {\r\n    const s = series[absCol];\r\n    // absRow is already source-relative (0 = source's first row), so it doubles as the series index\r\n    if (s) return s.extrapolate(absRow);\r\n    const wrappedRow = ((absRow % srcH) + srcH) % srcH;\r\n    // source is rectangular (srcH x srcW) by contract; wrappedRow/absCol are both in-bounds mod srcH/srcW\r\n    return source[wrappedRow]![absCol]!;\r\n  }\r\n  const s = series[absRow];\r\n  if (s) return s.extrapolate(absCol);\r\n  const wrappedCol = ((absCol % srcW) + srcW) % srcW;\r\n  return source[absRow]![wrappedCol]!;\r\n}\r\n\r\n/**\r\n * Generates fill values for `target` (a rect relative to `source`'s own\r\n * top-left, i.e. `target.x/y` may be negative for up/left fills or `>=\r\n * source width/height` for down/right fills) by extending `source` in\r\n * `direction`. Vertical fills detect a series per source column; horizontal\r\n * fills detect a series per source row. `forceCopy` or an undetected series\r\n * falls back to modulo tiling, wrapping so an upward/leftward fill tiles from\r\n * the far edge of the source.\r\n */\r\nexport function generateFill(\r\n  source: string[][],\r\n  target: GridRect,\r\n  direction: FillDirection,\r\n  opts: GenerateFillOptions = {}\r\n): string[][] {\r\n  const srcH = source.length;\r\n  const srcW = source[0]?.length ?? 0;\r\n  const axis = directionAxis(direction);\r\n  const forceCopy = opts.forceCopy === true;\r\n  const detect = opts.detect ?? detectSeries;\r\n\r\n  // source is rectangular (srcH x srcW) by contract, so row/col indices below are always in-bounds\r\n  const series: (SeriesDescriptor | null)[] =\r\n    axis === \"vertical\"\r\n      ? Array.from({ length: srcW }, (_, col) =>\r\n          forceCopy ? null : detect(Array.from({ length: srcH }, (_, row) => source[row]![col]!))\r\n        )\r\n      : Array.from({ length: srcH }, (_, row) => (forceCopy ? null : detect(source[row]!)));\r\n\r\n  const result: string[][] = [];\r\n  for (let row = 0; row < target.height; row++) {\r\n    const absRow = target.y + row;\r\n    const rowValues: string[] = [];\r\n    for (let col = 0; col < target.width; col++) {\r\n      const absCol = target.x + col;\r\n      rowValues.push(fillCell(source, series, axis, absCol, absRow, srcW, srcH));\r\n    }\r\n    result.push(rowValues);\r\n  }\r\n  return result;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/generate-fill.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/use-data-grid-fill.tsx",
      "content": "\"use client\";\n\nimport { useLayoutEffect, useMemo, useState, type ComponentType, type ReactNode } from \"react\";\nimport { useStore } from \"zustand\";\nimport { useDataGridEditing, useDataGridReadOnly, useDataGridSelection, type DataGridPlugin, type OverlayPluginCtx } from \"@/registry/default/components/data-grid/data-grid\";\nimport { createFillStore, useFillOnPointerDown, useFillPreview, type FillStoreApi } from \"./fill-store\";\nimport { renderFillOverlay } from \"./fill-overlay\";\nimport { FillMount } from \"./fill-mount\";\nimport { FILL_KEYMAP } from \"./fill-keymap\";\nimport { detectSeries as detectSeriesBuiltIn } from \"./detect-series\";\nimport type { ProcessFillContext, UseFillHandleOptions } from \"./use-fill-handle\";\n\n/** Options for {@link useDataGridFill} — the parts of `useFillHandle`'s options that don't need `scrollRef`/`layout` (only available inside `DataGridRoot`'s own subtree, where the plugin's `Mount` reads them). */\nexport type UseDataGridFillOptions = Pick<UseFillHandleOptions, \"disabled\" | \"processFill\" | \"detectSeries\">;\n\n/** Return value of {@link useDataGridFill}. */\nexport type UseDataGridFillResult = {\n  /** One entry of the grid's `plugins` prop — the plugin's `Overlay` paints the fill preview/handle, its `Mount` runs the pointer engine inside `DataGridRoot`, and its `fillDown`/`fillRight` commands back mod+D/mod+R. Stable for the component'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<unknown>;\n};\n\n/**\n * The fill handle, as a single hook. Owns its own store — a plain Zustand vanilla store local to\n * this hook instance, NOT part of the grid's own store, for the in-progress drag-preview rect and\n * the live handlers: the plugin's `Overlay` (pure rendering, painted by the core overlay layer)\n * and the plugin's `Mount` (the pointer engine, which needs `scrollRef` and column layout — only\n * available inside `DataGridRoot`'s own subtree, a level below where `plugins` is wired, on\n * `DataGridProvider`) both read/write that local store, which is what bridges the two ends.\n */\nexport function useDataGridFill(options: UseDataGridFillOptions = {}): UseDataGridFillResult {\n  const [fillStore] = useState(() => createFillStore(options));\n\n  useLayoutEffect(() => fillStore.getState().setOptions(options));\n\n  const plugin = useMemo<DataGridPlugin<unknown>>(\n    () => ({\n      name: \"fill\",\n      Overlay: createFillOverlay(fillStore),\n      Mount: createFillMount(fillStore),\n      commands: {\n        fillDown: {\n          when: (ctx) => !ctx.readOnly && fillStore.getState().options.disabled !== true,\n          run: () => fillStore.getState().fillDown?.(),\n        },\n        fillRight: {\n          when: (ctx) => !ctx.readOnly && fillStore.getState().options.disabled !== true,\n          run: () => fillStore.getState().fillRight?.(),\n        },\n      },\n      keymap: FILL_KEYMAP,\n    }),\n    [fillStore],\n  );\n\n  return { plugin };\n}\n\n/** The plugin's overlay component, closed over the add-on's local store (the hooks run inside `DataGridOverlays`' own fiber — a separate component, so only it re-renders on fill state). */\nfunction createFillOverlay(fillStore: FillStoreApi): ComponentType<OverlayPluginCtx> {\n  function FillOverlay(ctx: OverlayPluginCtx): ReactNode {\n    const fillPreview = useFillPreview(fillStore);\n    const onPointerDown = useFillOnPointerDown(fillStore);\n    const selection = useDataGridSelection();\n    const editing = useDataGridEditing();\n    const optionsDisabled = useStore(fillStore, (s) => s.options.disabled === true);\n    // either disable source vetoes the fill, so the handle must vanish with it\n    const disabled = useDataGridReadOnly() || optionsDisabled;\n    const state = { fillPreview, onPointerDown, primaryRange: selection.current?.range ?? null, editing: editing !== null, disabled };\n    return renderFillOverlay(state, ctx);\n  }\n  return FillOverlay;\n}\n\n/** The plugin's mount component: a fixed-identity wrapper over {@link FillMount} that reads the live options from the fill store. */\nfunction createFillMount(fillStore: FillStoreApi): ComponentType {\n  // stable callbacks that call the latest options, so an inline processFill does not re-render the mount\n  const processFill: NonNullable<UseDataGridFillOptions[\"processFill\"]> = (ctx) => fillStore.getState().options.processFill?.(ctx) ?? ctx.cells;\n  const detectSeries: NonNullable<UseDataGridFillOptions[\"detectSeries\"]> = (values) => (fillStore.getState().options.detectSeries ?? detectSeriesBuiltIn)(values);\n  function FillMountComponent(): ReactNode {\n    const disabled = useStore(fillStore, (s) => s.options.disabled);\n    const hasProcessFill = useStore(fillStore, (s) => s.options.processFill !== undefined);\n    const hasDetectSeries = useStore(fillStore, (s) => s.options.detectSeries !== undefined);\n    return <FillMount fillStore={fillStore} disabled={disabled} processFill={hasProcessFill ? processFill : undefined} detectSeries={hasDetectSeries ? detectSeries : undefined} />;\n  }\n  return FillMountComponent;\n}\n\nexport type { ProcessFillContext, UseFillHandleOptions };\nexport type { FillHandleHandlers } from \"./use-fill-handle\";\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/use-data-grid-fill.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-fill/use-fill-handle.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, type PointerEvent as ReactPointerEvent, type RefObject } from \"react\";\nimport { getCellValue, useDataGridActions, type CellRef, type GridRect } from \"@/registry/default/components/data-grid/data-grid\";\nimport {\n  applyInlineScrollDelta,\n  combineRects,\n  isColumnReadOnly,\n  isDev,\n  isThenable,\n  toSafeText,\n  inlineAutoScrollStep,\n  candidateRowIds,\n  gridAttrSelector,\n  pointerToCoord,\n  dataIndexAt,\n  rowAtViewRow,\n  rowIdAtViewRow,\n  safeSetPointerCapture,\n  resolveBulkWrites,\n  resolveColumnValidate,\n  safeFromText,\n  isRejectedText,\n  isUnparseable,\n  type ParsedCellText,\n  snapshotBulkBatch,\n  useBulkGeneration,\n  useDataGridStoreApi,\n  useDataGridGateTracker,\n  type BulkCandidate,\n  type GateRun,\n  type BulkResolution,\n  type InteractionLayout,\n  type DataGridReadState,\n  GRID_ROLE_SELECTOR,\n} from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { computeFillTarget, fillDirection, generateFill, rectRelativeTo, type FillDirection, type SeriesDescriptor } from \"./fill\";\nimport type { FillStoreApi } from \"./fill-store\";\n\nconst rowsOf = (rect: GridRect) => Array.from({ length: rect.height }, (_, i) => ({ viewRowIndex: rect.y + i }));\n\n/** Cells a fill is about to write, resolved before the write so a re-sort cannot shift them. */\nfunction flashCellsFor(s: DataGridReadState, writes: readonly { viewRowIndex: number; columnId: string }[]): CellRef[] {\n  return writes.flatMap((w) => {\n    const rowId = rowIdAtViewRow(s, w.viewRowIndex);\n    return rowId === undefined ? [] : [{ rowId, columnId: w.columnId }];\n  });\n}\n\n/** rAF-throttled auto-scroll step (px), matching `useGridInteraction`'s drag auto-scroll. */\nconst AUTO_SCROLL_STEP = 16;\n/** Distance (px) from a viewport edge at which drag auto-scroll kicks in. */\nconst AUTO_SCROLL_ZONE = 24;\n\n/** The context `processFill` receives. */\nexport type ProcessFillContext = {\n  /** The cells the fill extends. For Ctrl/Cmd+D it is the top row, for Ctrl/Cmd+R the left column. */\n  source: GridRect;\n  /** The new cells the fill writes. */\n  target: GridRect;\n  /** The fill text for `target`, before parsing and validation. */\n  cells: string[][];\n  /** Aborts when a newer fill supersedes this one, the grid turns read-only, or the grid unmounts. Pass it to the request an async `processFill` makes. */\n  signal: AbortSignal;\n};\n\n/** Options for {@link useFillHandle}. */\nexport type UseFillHandleOptions = {\n  scrollRef: RefObject<HTMLElement | null>;\n  layout: InteractionLayout;\n  /** Turns the whole fill feature off (handle hidden, `fillDown`/`fillRight` no-op). Default `false`; a read-only grid disables fill regardless of this option. */\n  disabled?: boolean;\n  /**\n   * Runs before a fill writes (drag release, fill down, fill right). Return the text grid to write, which goes through each column's `fromText` and `validate` like a paste, or `false` to veto the\n   * fill: nothing is written and the selection does not expand. A promise holds the fill as the `processFill` gate\n   * (`useDataGridGatePending`, `gateTimeoutMs`); the selection expands and the cells write once it resolves.\n   */\n  processFill?: (ctx: ProcessFillContext) => string[][] | false | Promise<string[][] | false>;\n  /** Replaces the built-in series detector (`detectSeries`) â€” the add-on's default remains the built-in one. */\n  detectSeries?: (values: readonly string[]) => SeriesDescriptor | null;\n  /** This add-on's local fill-preview store â€” owns the in-progress drag rect (kept out of core). */\n  fillStore: FillStoreApi;\n};\n\n/** Reads one cell's text value via its column's cell type `toText`, for use as a fill source. */\nfunction cellText(s: DataGridReadState, viewRow: number, colIndex: number): string {\n  const column = s.visibleColumns[colIndex];\n  if (!column) return \"\";\n  const row = rowAtViewRow(s, viewRow);\n  if (row === undefined) return \"\";\n  const cellType = s.cellTypes[column.type ?? \"text\"];\n  if (!cellType) return \"\";\n  // explicit TData=unknown: row's `undefined`-narrowed type ({} | null) would otherwise drive inference instead of column's own already-unknown TData.\n  const value = getCellValue<unknown, typeof column>(row, column);\n  return cellType.toText(value, column.options);\n}\n\n/** The source cell the plain copy puts at strip cell (`row`, `col`): its column and stored value. */\nfunction tiledSourceCell(\n  s: DataGridReadState,\n  source: GridRect,\n  relativeStrip: GridRect,\n  direction: FillDirection,\n  row: number,\n  col: number,\n): { columnId: string; value: unknown } | undefined {\n  const wrap = (index: number, size: number) => ((index % size) + size) % size;\n  const vertical = direction === \"up\" || direction === \"down\";\n  const sourceRow = vertical ? wrap(relativeStrip.y + row, source.height) : relativeStrip.y + row;\n  const sourceCol = vertical ? relativeStrip.x + col : wrap(relativeStrip.x + col, source.width);\n  const column = s.visibleColumns[source.x + sourceCol];\n  const dataRow = rowAtViewRow(s, source.y + sourceRow);\n  if (!column || dataRow === undefined) return undefined;\n  return { columnId: column.id, value: getCellValue<unknown, typeof column>(dataRow, column) };\n}\n\n/** Reads `rect` as a 2D string grid via each cell type's `toText` â€” the fill algorithm's raw input. */\nexport function readRectAsText(s: DataGridReadState, rect: GridRect): string[][] {\n  const out: string[][] = [];\n  for (let row = rect.y; row < rect.y + rect.height; row++) {\n    const line: string[] = [];\n    for (let col = rect.x; col < rect.x + rect.width; col++) line.push(cellText(s, row, col));\n    out.push(line);\n  }\n  return out;\n}\n\n/**\n * Generates the fill text for `strip` (the new cells only, absolute view coords) by extending\n * `source`: reads source text and runs `generateFill`. `processFill` sees this grid before any\n * parsing or validation. Exported for direct unit testing; not part of the public hook surface.\n */\nexport function generateFillText(\n  s: DataGridReadState,\n  source: GridRect,\n  strip: GridRect,\n  opts: { forceCopy?: boolean; detect?: (values: readonly string[]) => SeriesDescriptor | null } = {},\n): string[][] {\n  const sourceValues = readRectAsText(s, source);\n  return generateFill(sourceValues, rectRelativeTo(strip, source), fillDirection(source, strip), opts);\n}\n\n/** The plain-copy tiling of a fill: the strip as it reads when no series continues, and where each tile comes from. */\nexport type PlainFill = { source: GridRect; relativeStrip: GridRect; direction: FillDirection; tiled: string[][] };\n\nexport function plainFillOf(\n  s: DataGridReadState,\n  source: GridRect,\n  strip: GridRect,\n  opts: { detect?: (values: readonly string[]) => SeriesDescriptor | null } = {},\n): PlainFill {\n  const direction = fillDirection(source, strip);\n  const relativeStrip = rectRelativeTo(strip, source);\n  return { source, relativeStrip, direction, tiled: generateFill(readRectAsText(s, source), relativeStrip, direction, { ...opts, forceCopy: true }) };\n}\n\n/**\n * Builds the unvalidated candidate cells for `strip` from its fill text: converts each text back\n * through its own column's `fromText`, skipping readOnly columns, rows that don't resolve, and\n * cells the text grid does not cover. With `plain`, a run that continues no series, or whose\n * column rejects a generated text, copies the stored source values instead of their text.\n * Exported for direct unit testing; not part of the public hook surface.\n */\nexport function buildFillCandidatesFromText(s: DataGridReadState, strip: GridRect, filled: readonly (readonly string[])[], plain?: PlainFill): BulkCandidate[] {\n  const vertical = plain?.direction === \"up\" || plain?.direction === \"down\";\n  // a run is the strip column of a vertical fill and the strip row of a horizontal one\n  const runOf = (row: number, col: number) => (vertical ? col : row);\n  const seriesRuns = new Set<number>();\n  const rejectedRuns = new Set<number>();\n  const entries: { row: number; col: number; viewRow: number; column: (typeof s.visibleColumns)[number]; cellType: NonNullable<(typeof s.cellTypes)[string]>; dataRow: Exclude<(typeof s.data)[number], undefined>; rowId: string; parsed: ParsedCellText }[] = [];\n  let skippedHoleRows = 0;\n  for (let row = 0; row < strip.height; row++) {\n    const viewRow = strip.y + row;\n    const dataRowIndex = dataIndexAt(s, viewRow);\n    if (dataRowIndex === undefined) continue;\n    const dataRow = s.data[dataRowIndex];\n    if (dataRow === undefined) {\n      // an unloaded hole of a lazy grid: the row is real (in viewIndex) but has no row object\n      skippedHoleRows++;\n      continue;\n    }\n    const rowId = s.getRowId(dataRow, dataRowIndex);\n\n    for (let col = 0; col < strip.width; col++) {\n      const colIndex = strip.x + col;\n      const column = s.visibleColumns[colIndex];\n      if (!column) continue;\n      if (isColumnReadOnly(column, dataRow)) continue;\n\n      const cellType = s.cellTypes[column.type ?? \"text\"];\n      if (!cellType) continue;\n\n      const text = filled[row]?.[col];\n      if (text === undefined) continue;\n      const parsed = safeFromText(cellType, text, column.options, resolveColumnValidate(column, cellType));\n      if (plain && text !== plain.tiled[row]?.[col]) seriesRuns.add(runOf(row, col));\n      if (plain && text !== \"\" && (isRejectedText(parsed) || (!isUnparseable(parsed) && cellType.isEmpty(parsed.value)))) rejectedRuns.add(runOf(row, col));\n      entries.push({ row, col, viewRow, column, cellType, dataRow, rowId, parsed });\n    }\n  }\n\n  const candidates: BulkCandidate[] = entries.map((entry) => {\n    let { value, validate } = entry.parsed;\n    if (plain) {\n      const run = runOf(entry.row, entry.col);\n      const rejected = rejectedRuns.has(run);\n      if (rejected || !seriesRuns.has(run)) {\n        const sourceCell = tiledSourceCell(s, plain.source, plain.relativeStrip, plain.direction, entry.row, entry.col);\n        if (sourceCell?.columnId === entry.column.id) {\n          value = sourceCell.value;\n          validate = resolveColumnValidate(entry.column, entry.cellType);\n        } else if (rejected) {\n          ({ value, validate } = safeFromText(entry.cellType, plain.tiled[entry.row]![entry.col]!, entry.column.options, resolveColumnValidate(entry.column, entry.cellType)));\n        }\n      }\n    }\n    return { viewRowIndex: entry.viewRow, columnId: entry.column.id, value, validate, row: entry.dataRow, rowId: entry.rowId, warn: entry.column.validationMode === \"warn\" };\n  });\n  if (skippedHoleRows > 0 && isDev()) {\n    console.warn(\n      `[data-grid-fill] the fill target skipped ${skippedHoleRows} unloaded row(s) (lazy grid): unloaded cells are never filled and the selection still expands over them. Fill over a lazy grid covers loaded rows only.`,\n    );\n  }\n  return candidates;\n}\n\n/** The candidates and the fill text for `strip`; the composition of {@link generateFillText} and {@link buildFillCandidatesFromText}. */\nexport function buildFillCandidates(\n  s: DataGridReadState,\n  source: GridRect,\n  strip: GridRect,\n  opts: { forceCopy?: boolean; detect?: (values: readonly string[]) => SeriesDescriptor | null } = {},\n): { candidates: BulkCandidate[]; filled: string[][] } {\n  const filled = generateFillText(s, source, strip, opts);\n  return { candidates: buildFillCandidatesFromText(s, strip, filled, plainFillOf(s, source, strip, opts)), filled };\n}\n\n/**\n * The fill resolution (accepted writes plus rejected cells) plus `generateFill`'s raw text grid.\n * `resolution` is a Promise when a filled column's schema validates asynchronously â€” the hook holds\n * the batch until it resolves, then applies the passing cells as one `applyCellUpdates`.\n */\nexport function buildFillWrites(\n  s: DataGridReadState,\n  source: GridRect,\n  strip: GridRect,\n  opts: { forceCopy?: boolean; detect?: (values: readonly string[]) => SeriesDescriptor | null } = {},\n): { resolution: BulkResolution | Promise<BulkResolution>; filled: string[][] } {\n  const { candidates, filled } = buildFillCandidates(s, source, strip, opts);\n  return { resolution: resolveBulkWrites(candidates, s), filled };\n}\n\n/** Handlers for the fill-handle drag gesture (see fill-overlay.tsx's handle square) and the fillDown/fillRight shortcuts. */\nexport type FillHandleHandlers = {\n  onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;\n  /** mod+D: fills the selection's top row downward across the rest of the range (no-op when height <= 1). */\n  fillDown: () => void;\n  /** mod+R: fills the selection's left column rightward across the rest of the range (no-op when width <= 1). */\n  fillRight: () => void;\n  /** Escape: discards an in-progress drag without applying any writes; no-op when no drag is active. */\n  cancelFillDrag: () => void;\n};\n\n/**\n * Drives the fill-handle drag: pointerdown on the handle starts a document-level drag (capture +\n * rAF-throttled move + auto-scroll), live-updates\n * the add-on's local `fillStore` via `computeFillTarget` (orthogonal axis snap), and on release\n * runs the shared fill pipeline (`buildFillWrites`) as one `applyCellUpdates` batch, expanding the\n * selection to `combineRects(source, strip)`. Alt held at release forces plain-copy tiling over\n * series inference.\n */\nexport function useFillHandle(options: UseFillHandleOptions): FillHandleHandlers {\n  const { scrollRef, layout, processFill, detectSeries, fillStore } = options;\n  const disabled = options.disabled === true;\n  const actions = useDataGridActions();\n  const storeApi = useDataGridStoreApi();\n  // One counter for this add-on's fill surface: a newer fill supersedes a still-validating one.\n  const guard = useBulkGeneration();\n  const gates = useDataGridGateTracker();\n  const heldRun = useRef<GateRun | null>(null);\n\n  const layoutRef = useRef(layout);\n  layoutRef.current = layout;\n  const callbacksRef = useRef({ processFill, detectSeries });\n  callbacksRef.current = { processFill, detectSeries };\n\n  const dragRef = useRef<{ pointerId: number; source: GridRect } | null>(null);\n  const rafRef = useRef<number | null>(null);\n  const lastPointerRef = useRef<{ clientX: number; clientY: number; altKey: boolean } | null>(null);\n  const captureElementRef = useRef<Element | null>(null);\n  const documentListenersRef = useRef<(() => void) | null>(null);\n\n  const stopLoop = useCallback(() => {\n    if (rafRef.current !== null) {\n      cancelAnimationFrame(rafRef.current);\n      rafRef.current = null;\n    }\n  }, []);\n\n  const runFrame = useCallback(() => {\n    const scrollElement = scrollRef.current;\n    const pointer = lastPointerRef.current;\n    const drag = dragRef.current;\n    if (!scrollElement || !pointer || !drag) {\n      rafRef.current = null;\n      return;\n    }\n    const rect = scrollElement.getBoundingClientRect();\n\n    if (pointer.clientY < rect.top + AUTO_SCROLL_ZONE) scrollElement.scrollTop -= AUTO_SCROLL_STEP;\n    else if (pointer.clientY > rect.bottom - AUTO_SCROLL_ZONE) scrollElement.scrollTop += AUTO_SCROLL_STEP;\n    const direction = layoutRef.current.direction ?? \"ltr\";\n    const inlineStep = inlineAutoScrollStep(pointer.clientX, rect, AUTO_SCROLL_ZONE, direction);\n    if (inlineStep !== 0) applyInlineScrollDelta(scrollElement, inlineStep * AUTO_SCROLL_STEP, direction);\n\n    const s = storeApi.getState();\n    const rowCount = s.viewIndex.length;\n    const colCount = s.visibleColumns.length;\n    const coord = pointerToCoord(pointer.clientX, pointer.clientY, scrollElement, layoutRef.current, rowCount);\n\n    const strip = computeFillTarget(drag.source, coord, { allowedDirections: \"orthogonal\", rowCount, colCount });\n    fillStore.getState().setFillPreview(strip);\n\n    rafRef.current = requestAnimationFrame(runFrame);\n  }, [fillStore, scrollRef, storeApi]);\n\n  const finishFill = useCallback(\n    (s: ReturnType<typeof storeApi.getState>, source: GridRect, strip: GridRect, processed: string[][]) => {\n      const { detectSeries } = callbacksRef.current;\n      const candidates = buildFillCandidatesFromText(s, strip, processed, plainFillOf(s, source, strip, { detect: detectSeries }));\n\n      const resolution = resolveBulkWrites(candidates, s);\n      if (resolution instanceof Promise) {\n        const token = guard.begin();\n        const snapshot = snapshotBulkBatch(s, candidateRowIds(s, candidates));\n        if (heldRun.current && !heldRun.current.aborted) gates.abortRun(heldRun.current, \"superseded\");\n        const run = (heldRun.current = gates.begin(\"validate\", (now) => now.readOnly));\n        gates.hold(run);\n        const settle = () => {\n          gates.settle(run);\n          if (heldRun.current === run) heldRun.current = null;\n          return !run.aborted;\n        };\n        void resolution.then((resolved) => {\n          const current = storeApi.getState();\n          if (!settle() || current.readOnly || !guard.isCurrent(token, current, snapshot)) return;\n          const applied = guard.reresolve(current, resolved.writes);\n          const flashed = flashCellsFor(current, applied);\n          // rejected cells are reported by the write itself (same source, after the write's emit)\n          actions.applyCellUpdates(applied, \"fill\", resolved.rejected, resolved.warnings);\n          // Pulse the cells that actually landed — the re-resolved batch, not the held one.\n          actions.flashCells(flashed);\n        }, settle);\n      } else {\n        const flashed = flashCellsFor(storeApi.getState(), resolution.writes);\n        actions.applyCellUpdates(resolution.writes, \"fill\", resolution.rejected, resolution.warnings);\n        actions.flashCells(flashed);\n      }\n\n      // expand selection to combineRects(source, strip): re-derive via the plain selectCell/extendTo\n      // primitives (anchor at source's top-left corner, extend to the combined rect's far corner).\n      const combined = combineRects(source, strip);\n      actions.selectCellAt({ col: combined.x, row: combined.y });\n      actions.extendToAt({ col: combined.x + combined.width - 1, row: combined.y + combined.height - 1 });\n    },\n    [actions, gates, guard, storeApi],\n  );\n\n  /**\n   * Runs the shared fill pipeline: generates the fill text for `strip` (extending `source`), runs\n   * `processFill` (which can rewrite or veto, and may answer with a promise), parses, validates, applies one `applyCellUpdates` batch, and expands\n   * the selection to `combineRects(source, strip)`.\n   *\n   * With an async schema on a filled column the write batch is HELD: the selection still expands\n   * right away (the gesture's own feedback, unrelated to validation), and the cells commit in one\n   * batch once every validator resolves. `guard` drops that resolution when a newer fill has started\n   * or the rows it targeted are gone. An async `processFill` holds the whole fill, selection included, under the same rules.\n   */\n  const runFill = useCallback(\n    (source: GridRect, strip: GridRect, opts: { forceCopy?: boolean } = {}) => {\n      const s = storeApi.getState();\n      const { processFill, detectSeries } = callbacksRef.current;\n      const filled = generateFillText(s, source, strip, { ...opts, detect: detectSeries });\n      if (heldRun.current && !heldRun.current.aborted) gates.abortRun(heldRun.current, \"superseded\");\n      const run = gates.begin(\"processFill\", (now) => now.readOnly);\n      const processed = processFill ? processFill({ source, target: strip, cells: filled, signal: run.signal }) : filled;\n      if (!isThenable<string[][] | false>(processed)) {\n        if (processed !== false) finishFill(s, source, strip, processed);\n        return;\n      }\n\n      heldRun.current = run;\n      gates.hold(run);\n      const token = guard.begin();\n      const snapshot = snapshotBulkBatch(s, candidateRowIds(s, [...rowsOf(source), ...rowsOf(strip)]));\n      const settle = () => {\n        gates.settle(run);\n        if (heldRun.current === run) heldRun.current = null;\n        return !run.aborted;\n      };\n      void processed.then(\n        (final) => {\n          const current = storeApi.getState();\n          if (!settle() || final === false || current.readOnly || !guard.isCurrent(token, current, snapshot)) return;\n          finishFill(current, source, strip, final);\n        },\n        (error: unknown) => {\n          if (settle() && isDev()) console.warn(`[data-grid] processFill rejected, so the fill is cancelled: ${toSafeText(error)}`);\n        },\n      );\n    },\n    [finishFill, gates, guard, storeApi],\n  );\n\n  /** Releases pointer capture and clears all drag refs/listeners/rAF loop; returns the drag that was active, if any. */\n  const teardownDrag = useCallback(() => {\n    const drag = dragRef.current;\n    const pointerId = drag?.pointerId;\n    const captureEl = captureElementRef.current as (Element & { hasPointerCapture?: (id: number) => boolean; releasePointerCapture?: (id: number) => void }) | null;\n    if (captureEl && pointerId !== undefined && captureEl.hasPointerCapture?.(pointerId)) {\n      captureEl.releasePointerCapture?.(pointerId);\n    }\n    captureElementRef.current = null;\n    dragRef.current = null;\n    lastPointerRef.current = null;\n    stopLoop();\n    documentListenersRef.current?.();\n    documentListenersRef.current = null;\n    return drag;\n  }, [stopLoop]);\n\n  const endDrag = useCallback(() => {\n    const pointer = lastPointerRef.current;\n    const drag = teardownDrag();\n    if (!drag) return;\n    const strip = fillStore.getState().fillPreview;\n    fillStore.getState().setFillPreview(null);\n    if (!strip) return;\n\n    runFill(drag.source, strip, { forceCopy: pointer?.altKey === true });\n  }, [fillStore, runFill, teardownDrag]);\n\n  /** Escape mid-drag: tears down the drag and clears the preview without applying any writes. */\n  const cancelFillDrag = useCallback(() => {\n    const drag = teardownDrag();\n    if (!drag) return;\n    fillStore.getState().setFillPreview(null);\n  }, [fillStore, teardownDrag]);\n\n  const beginDrag = useCallback(\n    (source: GridRect, pointerId: number, captureElement?: Element) => {\n      dragRef.current = { pointerId, source };\n      captureElementRef.current = captureElement ?? null;\n      if (rafRef.current === null) rafRef.current = requestAnimationFrame(runFrame);\n\n      if (!documentListenersRef.current) {\n        const onMove = (event: PointerEvent) => {\n          if (!dragRef.current || dragRef.current.pointerId !== event.pointerId) return;\n          lastPointerRef.current = { clientX: event.clientX, clientY: event.clientY, altKey: event.altKey };\n        };\n        const onUp = (event: PointerEvent) => {\n          if (!dragRef.current || dragRef.current.pointerId !== event.pointerId) return;\n          if (lastPointerRef.current) lastPointerRef.current.altKey = event.altKey;\n          endDrag();\n        };\n        const onCancel = (event: PointerEvent) => {\n          if (!dragRef.current || dragRef.current.pointerId !== event.pointerId) return;\n          cancelFillDrag();\n        };\n        const onLostCapture = (event: PointerEvent) => {\n          if (event.target === captureElementRef.current) onCancel(event);\n        };\n        const onBlur = () => cancelFillDrag();\n        document.addEventListener(\"pointermove\", onMove);\n        document.addEventListener(\"pointerup\", onUp);\n        document.addEventListener(\"pointercancel\", onCancel);\n        document.addEventListener(\"lostpointercapture\", onLostCapture);\n        window.addEventListener(\"blur\", onBlur);\n        documentListenersRef.current = () => {\n          document.removeEventListener(\"pointermove\", onMove);\n          document.removeEventListener(\"pointerup\", onUp);\n          document.removeEventListener(\"pointercancel\", onCancel);\n          document.removeEventListener(\"lostpointercapture\", onLostCapture);\n          window.removeEventListener(\"blur\", onBlur);\n        };\n      }\n    },\n    [runFrame, endDrag, cancelFillDrag],\n  );\n\n  useEffect(() => () => documentListenersRef.current?.(), []);\n  useEffect(() => stopLoop, [stopLoop]);\n\n  const onPointerDown = useCallback(\n    (event: ReactPointerEvent<HTMLElement>) => {\n      if (event.button !== 0 || disabled) return;\n      const s = storeApi.getState();\n      if (!s.selection.current) return;\n      event.preventDefault();\n      event.stopPropagation();\n      // preventDefault above stops the native focus move, so undo shortcuts would miss the grid\n      const grid = scrollRef.current;\n      const active = grid && [...grid.querySelectorAll<HTMLElement>(gridAttrSelector(\"active\"))].find((cell) => cell.closest(GRID_ROLE_SELECTOR) === grid);\n      (active ?? grid)?.focus({ preventScroll: true });\n      lastPointerRef.current = { clientX: event.clientX, clientY: event.clientY, altKey: event.altKey };\n      // the handle unmounts when auto-scroll moves the source out of the window; the scroll element's capture outlives it\n      const captureElement = scrollRef.current ?? event.currentTarget;\n      safeSetPointerCapture(captureElement, event.pointerId);\n      beginDrag(s.selection.current.range, event.pointerId, captureElement);\n    },\n    [beginDrag, disabled, scrollRef, storeApi],\n  );\n\n  const fillDown = useCallback(() => {\n    if (disabled) return;\n    const range = storeApi.getState().selection.current?.range;\n    if (!range || range.height <= 1) return;\n    const source: GridRect = { x: range.x, y: range.y, width: range.width, height: 1 };\n    const strip: GridRect = { x: range.x, y: range.y + 1, width: range.width, height: range.height - 1 };\n    runFill(source, strip);\n  }, [disabled, runFill, storeApi]);\n\n  const fillRight = useCallback(() => {\n    if (disabled) return;\n    const range = storeApi.getState().selection.current?.range;\n    if (!range || range.width <= 1) return;\n    const source: GridRect = { x: range.x, y: range.y, width: 1, height: range.height };\n    const strip: GridRect = { x: range.x + 1, y: range.y, width: range.width - 1, height: range.height };\n    runFill(source, strip);\n  }, [disabled, runFill, storeApi]);\n\n  // Stable object identity when none of the four callbacks changed â€” the add-on's own plugin\n  // closure and DataGridRoot's context value depend on this reference, so a fresh literal here\n  // would defeat that memo on every render.\n  return useMemo(\n    () => ({ onPointerDown, fillDown, fillRight, cancelFillDrag }),\n    [onPointerDown, fillDown, fillRight, cancelFillDrag],\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-fill/use-fill-handle.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
