{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-context-menu",
  "title": "Data Grid Context Menu",
  "author": "gridcn",
  "description": "Right-click context menus for the gridcn data grid: cut/copy/paste/clear/row operations on cells, sort/pin/hide/autosize on headers.",
  "dependencies": [
    "lucide-react@^1.46.0",
    "@base-ui/react@^1.8.0",
    "zustand@^5.0.15"
  ],
  "registryDependencies": [
    "@gridcn/data-grid",
    "context-menu",
    "dropdown-menu",
    "tooltip"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-context-menu/data-grid-context-menu.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\r\n\r\nexport { DataGridContextMenu, type DataGridContextMenuProps } from \"./context-menu\";\r\nexport { DataGridHeaderDropdown, type DataGridHeaderDropdownProps } from \"./header-dropdown\";\r\nexport { useDataGridRowOps } from \"./has-row-op\";\r\nexport type {\r\n  BuiltInMenuItemId,\r\n  CellMenuItemsCtx,\r\n  CellMenuItemsResolver,\r\n  GridMenuItemSpec,\r\n  HeaderMenuItemsCtx,\r\n  HeaderMenuItemsResolver,\r\n} from \"./menu-items\";\r\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/data-grid-context-menu.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-context-menu/context-menu.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useRef, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from \"react\";\nimport type { ContextMenu as ContextMenuPrimitive } from \"@base-ui/react/context-menu\";\nimport {\n  ContextMenu,\n  ContextMenuContent,\n  ContextMenuTrigger,\n} from \"@/components/ui/context-menu\";\nimport { useDataGridActions } from \"@/registry/default/components/data-grid/data-grid\";\nimport { GRID_ROLE_SELECTOR, dataIndexAt, gridAttrSelector, pluginCellMenuItems, rowAtViewRow, rowIdAtViewRow, useDataGridStoreApi, viewEntryAt, type DataGridReadState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { resolveContextMenuTarget, type ContextMenuTarget } from \"./resolve-context-menu-target\";\nimport { isCellInSelection } from \"./selection-queries\";\nimport {\n  DataGridHeaderMenuItemsContext,\n  renderContextMenuItems,\n  useDefaultCellMenuItems,\n  useDefaultGroupRowMenuItems,\n  useDefaultHeaderMenuItems,\n  useRowOperationTargets,\n  type CellMenuItemsResolver,\n  type GridMenuItemSpec,\n  type HeaderMenuItemsResolver,\n} from \"./menu-items\";\nimport { useHasCreateRow, useHasDuplicateRow } from \"./has-row-op\";\n\ntype CellTarget = Extract<ContextMenuTarget, { kind: \"cell\" }> & { rowId: string; group?: true };\ntype MenuTarget = CellTarget | Extract<ContextMenuTarget, { kind: \"header\" }>;\n\nconst TEXT_ENTRY_SELECTOR = `input, textarea, select, [contenteditable]:not([contenteditable=\"false\"]), ${gridAttrSelector(\"cellEditor\")}`;\n\nfunction rowIdsOfViewRows(state: DataGridReadState, viewRows: readonly number[]): string[] {\n  const ids: string[] = [];\n  for (const viewRow of viewRows) {\n    const dataIndex = dataIndexAt(state, viewRow);\n    const dataRow = rowAtViewRow(state, viewRow);\n    if (dataIndex !== undefined && dataRow !== undefined) ids.push(state.getRowId(dataRow, dataIndex));\n  }\n  return ids;\n}\n\n/** The items of a right-click on a group row: no row operation applies, so only the group items show. */\nfunction GroupRowMenuContent({ target }: { target: CellTarget }): ReactNode {\n  return renderContextMenuItems(useDefaultGroupRowMenuItems(target.row));\n}\n\n/**\n * The cell-surface items, mounted only while the menu content is open on a cell target — the\n * default set's store subscriptions (selection, clipboard, keymap, labels) and the `defaults`\n * build must not run on the wrapper's per-render path.\n */\nfunction CellMenuContent(props: {\n  target: CellTarget;\n  getCellMenuItems?: CellMenuItemsResolver;\n  pasteBlocked: boolean;\n  onPasteBlocked: () => void;\n  clipboardFailed: boolean;\n  onClipboardFailed: () => void;\n}): ReactNode {\n  const { target, getCellMenuItems, pasteBlocked, onPasteBlocked, clipboardFailed, onClipboardFailed } = props;\n  const canInsertRow = useHasCreateRow();\n  const canDuplicateRow = useHasDuplicateRow();\n  const actions = useDataGridActions();\n  const storeApi = useDataGridStoreApi();\n  const targets = useRowOperationTargets(target.row);\n  const defaultSpecs = useDefaultCellMenuItems({\n    row: target.row,\n    rowId: target.rowId,\n    canInsertRow,\n    canDuplicateRow,\n    pasteBlocked,\n    onPasteBlocked,\n    clipboardFailed,\n    onClipboardFailed,\n  });\n  const targetRowIds = rowIdsOfViewRows(storeApi.getState(), targets.rows);\n  const pluginItems = pluginCellMenuItems(storeApi.getState().plugins, { rowId: target.rowId, viewRowIndex: target.row, columnId: target.columnId, targetRowIds, actions });\n  const withPlugins: GridMenuItemSpec[] = pluginItems.length > 0 ? [...defaultSpecs, { id: \"sep-plugins\", separator: true }, ...pluginItems] : defaultSpecs;\n  const specs = getCellMenuItems\n    ? getCellMenuItems({ rowId: target.rowId, viewRowIndex: target.row, columnId: target.columnId, canInsertRow, canDuplicateRow, targetRowIds, actions }, withPlugins)\n    : withPlugins;\n  return renderContextMenuItems(specs);\n}\n\n/** The header-surface items for a right-click header target; see {@link CellMenuContent}. */\nfunction HeaderMenuContent(props: {\n  target: Extract<ContextMenuTarget, { kind: \"header\" }>;\n  scrollRoot: HTMLElement | null;\n  getHeaderMenuItems?: HeaderMenuItemsResolver;\n}): ReactNode {\n  const { target, scrollRoot, getHeaderMenuItems } = props;\n  const actions = useDataGridActions();\n  const defaultSpecs = useDefaultHeaderMenuItems({ columnId: target.columnId, scrollRoot });\n  const specs = getHeaderMenuItems ? getHeaderMenuItems({ columnId: target.columnId, scrollRoot, actions }, defaultSpecs) : defaultSpecs;\n  return renderContextMenuItems(specs);\n}\n\n/** Props for {@link DataGridContextMenu}. */\nexport type DataGridContextMenuProps = {\n  className?: string;\n  children?: ReactNode;\n  /**\n   * Resolves the cell-surface item set (Cut/Copy/Paste, Clear contents, Fill down/right on a touch\n   * selection with the fill add-on, Insert row above/below with `createRow`, Duplicate row(s) with\n   * `duplicateRow`, Delete row(s)). `defaults` is the built-in set as\n   * {@link GridMenuItemSpec} entries for the current state; return `defaults` unchanged, a\n   * filtered/reordered/extended array, or a fully custom set. The returned array is the complete\n   * item set — it owns the items, their order, and their gating. Runs during the menu content's\n   * render (a plain function call, not a component), so it must not call hooks. Omit for the\n   * built-in set.\n   */\n  getCellMenuItems?: CellMenuItemsResolver;\n  /**\n   * Resolves the header-surface item set (Sort asc/desc/clear, Pin to start/end/unpin, Hide column,\n   * Autosize column, Autosize all columns). `defaults` is the built-in set as {@link GridMenuItemSpec} entries for the\n   * current state; the return value is the complete item set. Applies to the right-click header\n   * menu AND every `DataGridHeaderDropdown` rendered inside this wrapper (it flows through\n   * {@link DataGridHeaderMenuItemsContext}). Runs during the menu content's render, so it must\n   * not call hooks. Omit for the built-in set.\n   */\n  getHeaderMenuItems?: HeaderMenuItemsResolver;\n};\n\n/**\n * Wraps `children` (the grid) with the shadcn `ContextMenu`. On `contextmenu`, inspects the event\n * target to decide the surface (cell vs. header) and, for a cell outside\n * the current selection, selects that cell first (Excel behavior) before the menu opens.\n *\n * A surface that resolves to neither (row markers, empty grid space below the last row, the\n * scrollbar gutter, a hole row, ...) has no grid menu: the handler skips Base UI's default so the\n * browser menu shows there, and `onOpenChange` cancels any open that still reaches it so no empty\n * popup appears.\n */\nexport function DataGridContextMenu(props: DataGridContextMenuProps): ReactNode {\n  const { className, children, getCellMenuItems, getHeaderMenuItems } = props;\n  const actions = useDataGridActions();\n  const storeApi = useDataGridStoreApi();\n  const [target, setTarget] = useState<MenuTarget | null>(null);\n  const targetRef = useRef<MenuTarget | null>(null);\n  // Lives here (not in the menu content) because the content portals and unmounts on close —\n  // a permission-denied paste result must survive the close/reopen cycle to keep showing the\n  // \"use Ctrl+V\" hint on the next open.\n  const [pasteBlocked, setPasteBlocked] = useState(false);\n  const [clipboardFailed, setClipboardFailed] = useState(false);\n  const [failureShown, setFailureShown] = useState(false);\n\n  // Captured at contextmenu time (not via useDataGridContainer): ContextMenuContent portals to\n  // document.body, outside DataGridRoot's subtree, so its children can't reach the root context.\n  // State, not a ref read in render (a ref read bails the compiler): set in the same handler as\n  // setTarget, so the render that opens the menu already carries it.\n  const [scrollRoot, setScrollRoot] = useState<HTMLElement | null>(null);\n\n  const onContextMenu = useCallback(\n    (event: ReactMouseEvent<HTMLDivElement> & { preventBaseUIHandler: () => void }) => {\n      // Portaled popups (find panel, filter popover) bubble contextmenu through the React tree; they and any text-entry target keep the browser menu.\n      const outsideGrid = !event.currentTarget.contains(event.target as Node);\n      // Base UI's trigger also cancels the native menu in a document listener, so the event stops at the React root.\n      const leaveToBrowser = () => {\n        event.preventBaseUIHandler();\n        event.nativeEvent.stopPropagation();\n      };\n      if (outsideGrid || (event.target instanceof Element && event.target.closest(TEXT_ENTRY_SELECTOR) !== null)) {\n        leaveToBrowser();\n        return;\n      }\n      const resolved = resolveContextMenuTarget(event.target);\n      // the DOM carries only view-index coords; the stable row id and the selection both come off\n      // the store at event time.\n      const s = storeApi.getState();\n      let next: MenuTarget | null = resolved?.kind === \"header\" ? resolved : null;\n      if (resolved?.kind === \"cell\") {\n        const entry = viewEntryAt(s, resolved.row);\n        if (entry.kind === \"group\") next = { ...resolved, rowId: rowIdAtViewRow(s, resolved.row)!, group: true };\n        else if (entry.kind === \"data\") next = { ...resolved, rowId: s.getRowId(s.data[entry.dataIndex]!, entry.dataIndex) };\n      }\n      targetRef.current = next;\n      if (next === null) {\n        leaveToBrowser();\n        return;\n      }\n      setTarget(next);\n      // explicit type parameter: consumer TypeScript doesn't infer `E = HTMLElement` from the\n      // setState context type and defaults `closest` to `Element`.\n      setScrollRoot(event.target instanceof Element ? event.target.closest<HTMLElement>(GRID_ROLE_SELECTOR) : null);\n      if (next.kind === \"cell\" && !isCellInSelection(s.selection, { row: next.row, col: next.col })) {\n        actions.selectCellAt({ row: next.row, col: next.col });\n      }\n    },\n    [actions, storeApi],\n  );\n\n  const onOpenChange = useCallback((open: boolean, eventDetails: ContextMenuPrimitive.Root.ChangeEventDetails) => {\n    if (open && targetRef.current === null) eventDetails.cancel();\n    if (!open) targetRef.current = null;\n    if (open) {\n      setFailureShown(clipboardFailed);\n    } else if (failureShown) {\n      setFailureShown(false);\n      setClipboardFailed(false);\n    }\n  }, [clipboardFailed, failureShown]);\n\n  return (\n    <DataGridHeaderMenuItemsContext.Provider value={getHeaderMenuItems ?? null}>\n      <ContextMenu onOpenChange={onOpenChange}>\n        {/* The grid's own long-press dispatches contextmenu; Base UI's touch long-press would open a menu without a target. */}\n        <ContextMenuTrigger className={className} onContextMenu={onContextMenu} onTouchStart={(event) => event.preventBaseUIHandler()}>\n          {children}\n        </ContextMenuTrigger>\n        <ContextMenuContent data-grid-context-menu=\"\">\n          {target?.kind === \"cell\" && target.group && <GroupRowMenuContent target={target} />}\n          {target?.kind === \"cell\" && !target.group && (\n            <CellMenuContent\n              target={target}\n              getCellMenuItems={getCellMenuItems}\n              pasteBlocked={pasteBlocked}\n              onPasteBlocked={() => setPasteBlocked(true)}\n              clipboardFailed={clipboardFailed}\n              onClipboardFailed={() => setClipboardFailed(true)}\n            />\n          )}\n          {target?.kind === \"header\" && (\n            <HeaderMenuContent target={target} scrollRoot={scrollRoot} getHeaderMenuItems={getHeaderMenuItems} />\n          )}\n        </ContextMenuContent>\n      </ContextMenu>\n    </DataGridHeaderMenuItemsContext.Provider>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/context-menu.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-context-menu/header-dropdown.tsx",
      "content": "\"use client\";\n\nimport { useContext, useRef, type ReactElement, type ReactNode } from \"react\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport type { AnyColumnDef } from \"@/registry/default/components/data-grid/data-grid\";\nimport { GRID_ATTR, useDataGridContainer } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { useDataGridActions, useDataGridApi } from \"@/registry/default/components/data-grid/data-grid\";\nimport {\n  DataGridHeaderMenuItemsContext,\n  renderDropdownMenuItems,\n  useDefaultHeaderMenuItems,\n  type HeaderMenuItemsResolver,\n} from \"./menu-items\";\n\n/** Props for {@link DataGridHeaderDropdown} — matches the core's `renderHeaderMenu` render-prop ctx exactly. */\nexport type DataGridHeaderDropdownProps = {\n  /** The header's column; the items act on it. */\n  column: AnyColumnDef;\n  /** The column's visible-column index. */\n  index: number;\n  /** The core's own ghost-chevron trigger element (styling/aria-label owned by `header-cell.tsx`). */\n  trigger: ReactElement;\n  /**\n   * Resolves this dropdown's item set the same way `DataGridContextMenu`'s `getHeaderMenuItems`\n   * does. When the dropdown renders inside a `DataGridContextMenu` wrapper, the wrapper's\n   * resolver applies automatically; this prop overrides it for this dropdown only.\n   */\n  getHeaderMenuItems?: HeaderMenuItemsResolver;\n  /** Merged into the classes of the menu content. */\n  className?: string;\n};\n\n/**\n * The header items for one column, mounted only while the dropdown is open — the default set's\n * store subscriptions and the `defaults` build must not run on the column header's per-render path.\n */\nfunction HeaderDropdownItems(props: {\n  columnId: string;\n  scrollRoot: HTMLElement | null;\n  getHeaderMenuItems?: HeaderMenuItemsResolver;\n  inheritedResolver: HeaderMenuItemsResolver | null;\n}): ReactNode {\n  const { columnId, scrollRoot, getHeaderMenuItems, inheritedResolver } = props;\n  const actions = useDataGridActions();\n  const defaultSpecs = useDefaultHeaderMenuItems({ columnId, scrollRoot });\n  const resolver = getHeaderMenuItems ?? inheritedResolver;\n  const specs = resolver ? resolver({ columnId, scrollRoot, actions }, defaultSpecs) : defaultSpecs;\n  return renderDropdownMenuItems(specs);\n}\n\n/**\n * The primary per-column pin/sort surface: a `DropdownMenu` wrapping the core's chevron trigger,\n * whose content resolves through the same header-item spec list as the header right-click context\n * menu. Wire via `<DataGridRoot renderHeaderMenu={(ctx) => <DataGridHeaderDropdown {...ctx} />}>`.\n */\nexport function DataGridHeaderDropdown(props: DataGridHeaderDropdownProps): ReactNode {\n  const { column, trigger, getHeaderMenuItems, className } = props;\n  // rendered inline inside DataGridRoot's subtree (not portaled like the context menu), so the\n  // container is reachable directly via the shared hook instead of a contextmenu-time ref capture.\n  const scrollRoot = useDataGridContainer();\n  const inheritedResolver = useContext(DataGridHeaderMenuItemsContext);\n  const api = useDataGridApi();\n  const keyboardOpenedRef = useRef(false);\n  const openerRef = useRef<HTMLElement | null>(null);\n\n  return (\n    <DropdownMenu\n      onOpenChange={(open, details) => {\n        if (!open) return;\n        keyboardOpenedRef.current = (details.event?.target as HTMLElement | null)?.hasAttribute(GRID_ATTR.keyboardOpen) ?? false;\n        const focused = document.activeElement as HTMLElement | null;\n        openerRef.current = keyboardOpenedRef.current && focused?.closest(\"[role='columnheader']\") ? focused : null;\n      }}\n    >\n      <DropdownMenuTrigger render={trigger} />\n      {/* data-grid-header-menu-popup marks this a portal (React-tree-only bubble target) so\n          header-cell.tsx's own pointerdown/click handlers can ignore events that originate here\n          (its label press otherwise reassigns e.g. a \"Hide column\" click into a column-select). */}\n      <DropdownMenuContent\n        data-grid-header-dropdown=\"\"\n        data-grid-header-menu-popup=\"\"\n        align=\"end\"\n        className={className}\n        // the trigger is a tab stop only at zero rows; openColumnMenu opens it from a focused header button or the active cell\n        finalFocus={() => {\n          if (!keyboardOpenedRef.current) return true;\n          const active = document.activeElement;\n          const focusIsFree = !active || active === document.body || active.closest(\"[data-grid-header-menu-popup], [\" + GRID_ATTR.headerMenuTrigger + \"]\") !== null;\n          if (focusIsFree) {\n            if (openerRef.current?.isConnected) openerRef.current.focus();\n            else api.focus();\n          }\n          return false;\n        }}\n      >\n        <HeaderDropdownItems columnId={column.id} scrollRoot={scrollRoot.current} getHeaderMenuItems={getHeaderMenuItems} inheritedResolver={inheritedResolver} />\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/header-dropdown.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-context-menu/menu-items.tsx",
      "content": "\"use client\";\n\nimport {\n  createContext,\n  Fragment,\n  useCallback,\n  type ReactNode,\n} from \"react\";\nimport {\n  ArrowDown,\n  ArrowLeftToLine,\n  ArrowRightToLine,\n  ArrowUp,\n  Clipboard,\n  Copy,\n  CopyPlus,\n  ChevronsDownUp,\n  ChevronsUpDown,\n  Eraser,\n  EyeOff,\n  Group,\n  Maximize2,\n  Minus,\n  MoveHorizontal,\n  Pin,\n  PinOff,\n  Plus,\n  Scissors,\n  Trash2,\n  Ungroup,\n  X,\n} from \"lucide-react\";\nimport { ContextMenuItem, ContextMenuSeparator } from \"@/components/ui/context-menu\";\nimport { DropdownMenuItem, DropdownMenuSeparator } from \"@/components/ui/dropdown-menu\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"@/components/ui/tooltip\";\nimport {\n  formatShortcut,\n  type DataGridActions,\n  type GridAction,\n  viewIndexes,\n  useDataGridActions,\n  useDataGridAllColumns,\n  useDataGridApi,\n  useDataGridClipboard,\n  useDataGridKeymap,\n  useDataGridLabels,\n  useDataGridReadOnly,\n  useDataGridSelection,\n  useDataGridColumnWidth,\n  useDataGridSortState,\n  useDataGridVisibleColumns,\n} from \"@/registry/default/components/data-grid/data-grid\";\nimport { MAX_GROUP_LEVELS, columnLabelText, rowIdAtViewRow, rowOperationTargets, useDataGridGroupRow, useDataGridStoreApi, useDataGridCommands, useDataGridSelector, useDataGridSelectionConfig, useDataGridSelectionPointer } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { MenuShortcut } from \"./menu-shortcut\";\nimport { COLUMN_WIDTH_STEP, shownColumnWidth, useDataGridColumnFeatureFlags } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/** Ids of the built-in menu items. */\nexport type BuiltInMenuItemId =\n  | \"cut\"\n  | \"copy\"\n  | \"paste\"\n  | \"clear-contents\"\n  | \"fill-down\"\n  | \"fill-right\"\n  | \"insert-row-above\"\n  | \"insert-row-below\"\n  | \"duplicate-rows\"\n  | \"delete-rows\"\n  | \"toggle-group\"\n  | \"expand-all\"\n  | \"collapse-all\"\n  | \"group-by\"\n  | \"ungroup\"\n  | \"sort-asc\"\n  | \"sort-desc\"\n  | \"clear-sort\"\n  | \"pin-start\"\n  | \"pin-end\"\n  | \"unpin\"\n  | \"hide-column\"\n  | \"autosize\"\n  | \"autosize-all\"\n  | \"move-toward-start\"\n  | \"move-toward-end\"\n  | \"widen-column\"\n  | \"narrow-column\"\n  | \"sep-clipboard\"\n  | \"sep-rows\"\n  | \"sep-sort\"\n  | \"sep-group\"\n  | \"sep-autosize\"\n  | \"sep-move\";\n\n/** An item id: a built-in id (the editor completes it) or your own string. */\nexport type MenuItemId = BuiltInMenuItemId | (string & {});\n\n/**\n * One context/dropdown menu entry, in display order. The built-in sets are these specs; a\n * resolver's return value is the complete item set (the consumer owns items, order, and gating).\n */\nexport type GridMenuItemSpec =\n  | {\n      /** Stable identity for locating and replacing a built-in item; see {@link BuiltInMenuItemId}. Separators use `sep-*` ids. */\n      id: MenuItemId;\n      /** Display label; i18n is the caller's (the built-ins use `labels.contextMenu`). */\n      label: string;\n      /** Leading icon element (lucide convention: `size-4 text-muted-foreground`). */\n      icon?: ReactNode;\n      /** Keymap binding rendered as a keycap hint at the item's end. */\n      shortcut?: string;\n      /** Renders the item inert. With a `tooltip`, it renders aria-disabled (hover still reaches it) so the hint stays reachable. */\n      disabled?: boolean;\n      /** Destructive (danger-red) item styling. */\n      destructive?: boolean;\n      /** Hover hint shown while the item is disabled; the built-ins use it for a blocked paste, a failed clipboard write, and blocked row actions. */\n      tooltip?: string;\n      /** Click handler; omit for a display-only item. */\n      onClick?: () => void;\n    }\n  | {\n      /** Stable identity; the built-in separators use ids like `sep-clipboard`. */\n      id: MenuItemId;\n      /** Marker for a separator entry (no label, no click). */\n      separator: true;\n    };\n\n/** The right-clicked cell's context, handed to a cell-menu resolver. */\nexport type CellMenuItemsCtx = {\n  /** The right-clicked row's stable `getRowId()` value. */\n  rowId: string;\n  /** The right-clicked cell's view row index (the same index the built-in set anchors Insert row at). */\n  viewRowIndex: number;\n  /** The right-clicked cell's column id. */\n  columnId: string;\n  /** Whether the grid was given a `createRow` prop — the flag the built-in set gates its Insert items on. */\n  canInsertRow: boolean;\n  /** Whether the grid was given a `duplicateRow` prop — the flag the built-in set gates its Duplicate item on. */\n  canDuplicateRow: boolean;\n  /** The row ids the row items act on: the checked rows, else the rows of the selected cells, else the clicked row. Empty while checked rows are hidden or all matching rows are selected, the cases where the built-in row items are off. */\n  readonly targetRowIds: readonly string[];\n  /** The grid's actions, for an item's `onClick`. A resolver cannot call hooks. */\n  actions: DataGridActions;\n};\n\n/** The right-clicked header's context, handed to a header-menu resolver. */\nexport type HeaderMenuItemsCtx = {\n  /** The right-clicked column's id. */\n  columnId: string;\n  /** The grid's scroll-container element (for autosize measurement), or null when the event target has no grid ancestor. */\n  scrollRoot: HTMLElement | null;\n  /** The grid's actions, for an item's `onClick`. A resolver cannot call hooks. */\n  actions: DataGridActions;\n};\n\n/** Resolves the cell-surface item set. Return `defaults` unchanged, a filtered/reordered/extended array, or a fully custom set. */\nexport type CellMenuItemsResolver = (ctx: CellMenuItemsCtx, defaults: GridMenuItemSpec[]) => GridMenuItemSpec[];\n\n/** Resolves the header-surface item set (right-click menu and `DataGridHeaderDropdown`). Return `defaults` unchanged, a filtered/reordered/extended array, or a fully custom set. */\nexport type HeaderMenuItemsResolver = (ctx: HeaderMenuItemsCtx, defaults: GridMenuItemSpec[]) => GridMenuItemSpec[];\n\n/**\n * Carries the `DataGridContextMenu` wrapper's `getHeaderMenuItems` resolver to\n * `DataGridHeaderDropdown`s rendered inside the wrapper's subtree, so one resolver covers both\n * header surfaces. `null` when no wrapper is mounted (the dropdown then uses its own prop).\n */\nexport const DataGridHeaderMenuItemsContext = createContext<HeaderMenuItemsResolver | null>(null);\n\n/** The view rows the row items act on for a menu opened on view row `row`. */\nexport function useRowOperationTargets(row: number) {\n  const selection = useDataGridSelection();\n  const { checkedRowsLifetime } = useDataGridSelectionConfig();\n  const hiddenCheckedRowIds = useDataGridSelector((s) => s.hiddenCheckedRowIds);\n  const allMatching = useDataGridSelector((s) => s.allMatching);\n  return rowOperationTargets({ checkedRowsLifetime, selection, hiddenCheckedRowIds, allMatching }, row);\n}\n\nfunction viewRowOfId(state: Parameters<typeof rowIdAtViewRow>[0], rowId: string): number {\n  for (let viewRow = 0; viewRow < state.viewIndex.length; viewRow++) if (rowIdAtViewRow(state, viewRow) === rowId) return viewRow;\n  return -1;\n}\n\n/** The items of a group row's menu: copy, open or close the group, open or close every group. */\nexport function useDefaultGroupRowMenuItems(row: number): GridMenuItemSpec[] {\n  const actions = useDataGridActions();\n  const clipboard = useDataGridClipboard();\n  const labels = useDataGridLabels();\n  const meta = useDataGridGroupRow(row);\n  const groupMode = useDataGridSelector((s) => s.groupMode);\n  const specs: GridMenuItemSpec[] = [{ id: \"copy\", label: labels.contextMenu.copy, icon: <Copy className=\"size-4 text-muted-foreground\" />, shortcut: \"mod+c\", onClick: () => void clipboard.copy() }];\n  if (!meta) return specs;\n  specs.push(\n    { id: \"sep-group\", separator: true },\n    { id: \"toggle-group\", label: meta.expanded ? labels.grouping.collapse(meta.node.label) : labels.grouping.expand(meta.node.label), icon: meta.expanded ? <ChevronsDownUp className=\"size-4 text-muted-foreground\" /> : <ChevronsUpDown className=\"size-4 text-muted-foreground\" />, onClick: () => actions.toggleGroup(meta.node.id) },\n  );\n  if (groupMode === \"client\") specs.push({ id: \"expand-all\", label: labels.grouping.expandAll, icon: <ChevronsUpDown className=\"size-4 text-muted-foreground\" />, onClick: () => void actions.expandAll() });\n  specs.push({ id: \"collapse-all\", label: labels.grouping.collapseAll, icon: <ChevronsDownUp className=\"size-4 text-muted-foreground\" />, onClick: () => void actions.collapseAll() });\n  return specs;\n}\n\n/** The built-in cell-surface set as specs, resolved for the current grid state (labels, keymap, selection, clipboard gating). */\nexport function useDefaultCellMenuItems(args: {\n  row: number;\n  /** The row's stable id; Insert row follows it if the view rebuilds before the click. */\n  rowId?: string;\n  canInsertRow: boolean;\n  canDuplicateRow: boolean;\n  pasteBlocked: boolean;\n  onPasteBlocked: () => void;\n  clipboardFailed?: boolean;\n  onClipboardFailed?: () => void;\n}): GridMenuItemSpec[] {\n  const { row, rowId, canInsertRow, canDuplicateRow, pasteBlocked, onPasteBlocked, clipboardFailed = false, onClipboardFailed } = args;\n  const actions = useDataGridActions();\n  const targets = useRowOperationTargets(row);\n  const clipboard = useDataGridClipboard();\n  const readOnly = useDataGridReadOnly();\n  const labels = useDataGridLabels();\n  const keymap = useDataGridKeymap();\n  const commands = useDataGridCommands();\n  const selectionPointer = useDataGridSelectionPointer();\n  const enableRowDelete = useDataGridSelector((s) => s.enableRowDelete);\n  const serverGroups = useDataGridSelector((s) => s.groupMode === \"server\" && s.groupBy.length > 0);\n  const api = useDataGridApi();\n  const storeApi = useDataGridStoreApi();\n  const insertRow = (position: \"above\" | \"below\") => {\n    const state = storeApi.getState();\n    const anchor = rowId === undefined ? row : viewRowOfId(state, rowId);\n    if (anchor !== -1) actions.insertRow(anchor, position);\n  };\n\n  // Row-op items act on every view row covered by the current selection, falling back to the\n  // right-clicked row (same rule as the keyboard/native-clipboard gating).\n  const rows = targets.rows;\n  const blockedTooltip = targets.reason === \"all-matching\" ? labels.contextMenu.rowActionAllMatching : targets.reason ? labels.contextMenu.rowActionHiddenChecked : undefined;\n  const rowActionsBlocked = targets.reason !== undefined;\n\n  const onPaste = useCallback(() => {\n    if (pasteBlocked || readOnly) return;\n    clipboard.pasteFromClipboard().then((result) => {\n      if (result === \"permission-denied\") onPasteBlocked();\n    });\n  }, [clipboard, onPasteBlocked, pasteBlocked, readOnly]);\n\n  const reportFailure = (write: () => Promise<string>) => () => {\n    write().then(\n      (result) => {\n        if (result === \"failed\") onClipboardFailed?.();\n      },\n      () => onClipboardFailed?.(),\n    );\n  };\n  const modifier = formatShortcut(\"mod\")[0]!;\n  const hint = (label: string | ((modifier: string) => string)) => (typeof label === \"function\" ? label(modifier) : label);\n  const clipboardTooltip = clipboardFailed ? hint(labels.contextMenu.clipboardFailed) : undefined;\n\n  const specs: GridMenuItemSpec[] = [\n    { id: \"cut\", label: labels.contextMenu.cut, icon: <Scissors className=\"size-4 text-muted-foreground\" />, shortcut: \"mod+x\", disabled: readOnly || clipboardFailed, tooltip: readOnly ? undefined : clipboardTooltip, onClick: reportFailure(clipboard.cut) },\n    { id: \"copy\", label: labels.contextMenu.copy, icon: <Copy className=\"size-4 text-muted-foreground\" />, shortcut: \"mod+c\", disabled: clipboardFailed || undefined, tooltip: clipboardTooltip, onClick: reportFailure(clipboard.copy) },\n    {\n      id: \"paste\",\n      label: labels.contextMenu.paste,\n      icon: <Clipboard className=\"size-4 text-muted-foreground\" />,\n      shortcut: \"mod+v\",\n      disabled: pasteBlocked || readOnly,\n      tooltip: pasteBlocked && !readOnly ? hint(labels.contextMenu.pasteBlocked) : undefined,\n      onClick: onPaste,\n    },\n    { id: \"sep-clipboard\", separator: true },\n    { id: \"clear-contents\", label: labels.contextMenu.clearContents, icon: <Eraser className=\"size-4 text-muted-foreground\" />, shortcut: keymap.clearContents?.[0], disabled: readOnly, onClick: () => actions.deleteSelection() },\n    { id: \"sep-rows\", separator: true },\n  ];\n  if (selectionPointer === \"touch\" && commands?.[\"fillDown\"] && commands[\"fillRight\"]) {\n    specs.splice(\n      specs.findIndex((spec) => spec.id === \"clear-contents\") + 1,\n      0,\n      { id: \"fill-down\", label: labels.contextMenu.fillDown, disabled: readOnly, onClick: () => api.runShortcut(\"fillDown\" as GridAction) },\n      { id: \"fill-right\", label: labels.contextMenu.fillRight, disabled: readOnly, onClick: () => api.runShortcut(\"fillRight\" as GridAction) },\n    );\n  }\n  if (canInsertRow && !serverGroups) {\n    specs.push(\n      { id: \"insert-row-above\", label: labels.contextMenu.insertRowAbove, icon: <Plus className=\"size-4 text-muted-foreground\" />, shortcut: keymap.insertRowAbove?.[0], tooltip: readOnly ? labels.contextMenu.rowActionReadOnly : undefined, disabled: readOnly, onClick: () => insertRow(\"above\") },\n      { id: \"insert-row-below\", label: labels.contextMenu.insertRowBelow, icon: <Plus className=\"size-4 text-muted-foreground\" />, shortcut: keymap.insertRowBelow?.[0], tooltip: readOnly ? labels.contextMenu.rowActionReadOnly : undefined, disabled: readOnly, onClick: () => insertRow(\"below\") },\n    );\n  }\n  if (canDuplicateRow && !serverGroups) {\n    specs.push({ id: \"duplicate-rows\", label: labels.contextMenu.duplicateRows(rows.length), icon: <CopyPlus className=\"size-4 text-muted-foreground\" />, shortcut: keymap.duplicateRow?.[0], tooltip: readOnly ? labels.contextMenu.rowActionReadOnly : blockedTooltip, disabled: readOnly || rowActionsBlocked, onClick: () => actions.duplicateRowsAt(viewIndexes(rows)) });\n  }\n  if (enableRowDelete && !serverGroups) specs.push({ id: \"delete-rows\", label: labels.contextMenu.deleteRows(rows.length), icon: <Trash2 className=\"size-4\" />, shortcut: keymap.deleteRows?.[0], tooltip: readOnly ? labels.contextMenu.rowActionReadOnly : blockedTooltip, disabled: readOnly || rowActionsBlocked, destructive: true, onClick: () => actions.deleteRowsAt(viewIndexes(rows)) });\n  return specs;\n}\n\n/** Pixels one \"Widen column\" or \"Narrow column\" step adds or removes; the store clamps to the column's limits. */\nexport { COLUMN_WIDTH_STEP };\n\n/** The built-in header-surface set as specs, resolved for the current grid state (sort, pin/resize flags, labels). */\nexport function useDefaultHeaderMenuItems(args: { columnId: string; scrollRoot: HTMLElement | null }): GridMenuItemSpec[] {\n  const { columnId, scrollRoot } = args;\n  const actions = useDataGridActions();\n  const sortState = useDataGridSortState();\n  const columns = useDataGridAllColumns();\n  const visibleColumns = useDataGridVisibleColumns();\n  const savedWidth = useDataGridColumnWidth(columnId);\n  const { enableColumnPinning, enableColumnResize, enableColumnReorder } = useDataGridColumnFeatureFlags();\n  const labels = useDataGridLabels();\n  const groupBy = useDataGridSelector((s) => s.groupBy);\n  const canGroup = useDataGridSelector((s) => s.groupingEnabled && (s.groupMode === \"server\" || (s.totalRowCount === undefined && s.sortMode !== \"server\")));\n\n  const column = columns.find((c) => c.id === columnId);\n  if (!column) return [];\n\n  const sortable = column.sortable !== false;\n  const pinnable = enableColumnPinning && column.pinnable !== false;\n  // Mirrors the core double-click autosize's gate: with either flag off the action does not\n  // exist, so the item is hidden (not disabled) to match the absent resize handle.\n  const resizable = enableColumnResize && (column.resizable ?? true);\n  const currentSort = sortState.find((s) => s.columnId === columnId)?.direction;\n\n  const specs: GridMenuItemSpec[] = [];\n  if (sortable) {\n    specs.push(\n      { id: \"sort-asc\", label: labels.contextMenu.sortAsc, icon: <ArrowUp className=\"size-4 text-muted-foreground\" />, onClick: () => actions.setSorts([{ columnId, direction: \"asc\" }]) },\n      { id: \"sort-desc\", label: labels.contextMenu.sortDesc, icon: <ArrowDown className=\"size-4 text-muted-foreground\" />, onClick: () => actions.setSorts([{ columnId, direction: \"desc\" }]) },\n    );\n    if (currentSort) {\n      specs.push({ id: \"clear-sort\", label: labels.contextMenu.clearSort, icon: <X className=\"size-4 text-muted-foreground\" />, onClick: () => actions.setSorts(sortState.filter((s) => s.columnId !== columnId)) });\n    }\n    specs.push({ id: \"sep-sort\", separator: true });\n  }\n  const grouped = groupBy.includes(columnId);\n  if (canGroup && (grouped || (column.groupable !== false && groupBy.length < MAX_GROUP_LEVELS))) {\n    const name = columnLabelText(column);\n    specs.push(\n      grouped\n        ? { id: \"ungroup\", label: labels.grouping.ungroup(name), icon: <Ungroup className=\"size-4 text-muted-foreground\" />, onClick: () => actions.toggleGroupBy(columnId) }\n        : { id: \"group-by\", label: labels.grouping.groupBy(name), icon: <Group className=\"size-4 text-muted-foreground\" />, onClick: () => actions.toggleGroupBy(columnId) },\n      { id: \"sep-group\", separator: true },\n    );\n  }\n  specs.push(\n    { id: \"pin-start\", label: labels.contextMenu.pinStart, icon: <Pin className=\"size-4 text-muted-foreground\" />, disabled: !pinnable, onClick: () => actions.setColumnPin(columnId, \"start\") },\n    { id: \"pin-end\", label: labels.contextMenu.pinEnd, icon: <Pin className=\"size-4 text-muted-foreground\" />, disabled: !pinnable, onClick: () => actions.setColumnPin(columnId, \"end\") },\n  );\n  if (column.pin != null) {\n    specs.push({ id: \"unpin\", label: labels.contextMenu.unpin, icon: <PinOff className=\"size-4 text-muted-foreground\" />, disabled: !pinnable, onClick: () => actions.setColumnPin(columnId, null) });\n  }\n  if (column.hideable !== false) {\n    specs.push({ id: \"hide-column\", label: labels.contextMenu.hideColumn, icon: <EyeOff className=\"size-4 text-muted-foreground\" />, onClick: () => actions.setColumnHidden(columnId, true) });\n  }\n  // The drag-free path to reorder and resize, for the keyboard (Shift+Alt+ArrowDown opens this menu) and single pointers.\n  const position = visibleColumns.findIndex((c) => c.id === columnId);\n  const neighbor = (step: -1 | 1) => {\n    const other = position === -1 ? undefined : visibleColumns[position + step];\n    return other && actions.canSetColumnOrder(columnId, other.id, step === -1 ? \"before\" : \"after\").ok ? other : undefined;\n  };\n  const before = neighbor(-1);\n  const after = neighbor(1);\n  if (enableColumnReorder && column.reorderable !== false && position !== -1) {\n    specs.push(\n      { id: \"sep-move\", separator: true },\n      { id: \"move-toward-start\", label: labels.contextMenu.moveTowardStart, icon: <ArrowLeftToLine className=\"size-4 text-muted-foreground rtl:-scale-x-100\" />, disabled: !before, onClick: () => before && actions.setColumnOrder(columnId, before.id, \"before\") },\n      { id: \"move-toward-end\", label: labels.contextMenu.moveTowardEnd, icon: <ArrowRightToLine className=\"size-4 text-muted-foreground rtl:-scale-x-100\" />, disabled: !after, onClick: () => after && actions.setColumnOrder(columnId, after.id, \"after\") },\n    );\n  }\n  if (resizable) {\n    // The rendered header width includes flex growth, which the saved width and the def do not hold.\n    const currentWidth = () => shownColumnWidth(scrollRoot, column, savedWidth === undefined ? {} : { [columnId]: savedWidth });\n    specs.push(\n      { id: \"sep-autosize\", separator: true },\n      { id: \"widen-column\", label: labels.contextMenu.widenColumn, icon: <Plus className=\"size-4 text-muted-foreground\" />, onClick: () => actions.setColumnWidth(columnId, currentWidth() + COLUMN_WIDTH_STEP) },\n      { id: \"narrow-column\", label: labels.contextMenu.narrowColumn, icon: <Minus className=\"size-4 text-muted-foreground\" />, onClick: () => actions.setColumnWidth(columnId, currentWidth() - COLUMN_WIDTH_STEP) },\n      { id: \"autosize\", label: labels.contextMenu.autosize, icon: <MoveHorizontal className=\"size-4 text-muted-foreground\" />, onClick: () => actions.autosizeColumns({ columnIds: [columnId] }) },\n      { id: \"autosize-all\", label: labels.contextMenu.autosizeAll, icon: <Maximize2 className=\"size-4 text-muted-foreground\" />, onClick: () => actions.autosizeColumns() },\n    );\n  }\n  return specs;\n}\n\n/** One spec entry as a `ContextMenuItem` (or `DropdownMenuItem`) node, with the disabled/tooltip gating the built-ins apply. */\nfunction surfaceItem(\n  spec: Exclude<GridMenuItemSpec, { separator: true }>,\n  Item: (props: {\n    variant?: \"default\" | \"destructive\";\n    disabled?: boolean;\n    \"aria-disabled\"?: boolean;\n    className?: string;\n    onClick?: () => void;\n    children?: ReactNode;\n  }) => ReactNode,\n): ReactNode {\n  // Not the `disabled` prop when a tooltip is present: it sets `pointer-events-none`, which would\n  // also block the tooltip's own hover detection. Visually disabled + click-guarded instead.\n  const tooltipDisabled = spec.tooltip != null && spec.disabled;\n  const item = (\n    <Item\n      variant={spec.destructive ? \"destructive\" : \"default\"}\n      disabled={tooltipDisabled ? undefined : spec.disabled || undefined}\n      aria-disabled={tooltipDisabled ? true : undefined}\n      className={tooltipDisabled ? \"opacity-50\" : undefined}\n      onClick={spec.disabled ? undefined : spec.onClick}\n    >\n      {spec.icon}\n      {spec.label}\n      {spec.shortcut && <MenuShortcut binding={spec.shortcut} />}\n    </Item>\n  );\n  if (!tooltipDisabled) return item;\n  return (\n    <Tooltip>\n      <TooltipTrigger render={item} />\n      <TooltipContent>{spec.tooltip}</TooltipContent>\n    </Tooltip>\n  );\n}\n\n/** Renders a spec list as the right-click context menu's item nodes. */\nexport function renderContextMenuItems(specs: GridMenuItemSpec[]): ReactNode {\n  return (\n    <Fragment>\n      {specs.map((spec) =>\n        \"separator\" in spec ? (\n          <ContextMenuSeparator key={spec.id} />\n        ) : (\n          <Fragment key={spec.id}>{surfaceItem(spec, ContextMenuItem)}</Fragment>\n        ),\n      )}\n    </Fragment>\n  );\n}\n\n/** Renders a spec list as the header dropdown's item nodes. */\nexport function renderDropdownMenuItems(specs: GridMenuItemSpec[]): ReactNode {\n  return (\n    <Fragment>\n      {specs.map((spec) =>\n        \"separator\" in spec ? (\n          <DropdownMenuSeparator key={spec.id} />\n        ) : (\n          <Fragment key={spec.id}>{surfaceItem(spec, DropdownMenuItem)}</Fragment>\n        ),\n      )}\n    </Fragment>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/menu-items.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-context-menu/menu-shortcut.tsx",
      "content": "\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { formatShortcut } from \"@/registry/default/components/data-grid/data-grid\";\nimport { Kbd, KbdGroup } from \"@/components/ui/kbd\";\n\n/** A menu item's shortcut hint as keycaps, pushed to the item's end; renders nothing for an unbound action. */\nexport function MenuShortcut({ binding }: { binding: string | undefined }): ReactNode {\n  if (!binding) return null;\n  return (\n    <KbdGroup className=\"ms-auto\">\n      {formatShortcut(binding).map((token, i) => (\n        // tokens within one binding have no other stable identity; index is fine, this list never reorders\n        <Kbd key={i}>{token}</Kbd>\n      ))}\n    </KbdGroup>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/menu-shortcut.tsx"
    },
    {
      "path": "components/ui/kbd.tsx",
      "content": "import { cn } from \"@/lib/utils\"\r\n\r\n/** Keycap treatment, owned by the component (not the prose typography plugin) so docs, the keybindings dialog, and consumer apps render identically. */\r\nconst KEYCAP =\r\n  \"rounded-sm border bg-muted shadow-[inset_0_-2px_0_0_color-mix(in_oklab,_currentColor_15%,_transparent)]\"\r\n\r\nfunction Kbd({ className, ...props }: React.ComponentProps<\"kbd\">) {\r\n  return (\r\n    <kbd\r\n      data-slot=\"kbd\"\r\n      className={cn(\r\n        // `not-prose`: the typography plugin's kbd rule (unlayered) would otherwise restyle component-owned keys\r\n        \"pointer-events-none not-prose inline-flex h-5 w-fit min-w-5 select-none items-center justify-center gap-1 px-1 font-sans text-xs font-medium text-muted-foreground\",\r\n        KEYCAP,\r\n        \"in-data-[slot=kbd-group]:min-w-0 in-data-[slot=kbd-group]:border-0 in-data-[slot=kbd-group]:bg-transparent in-data-[slot=kbd-group]:px-0.5 in-data-[slot=kbd-group]:shadow-none\",\r\n        \"in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10\",\r\n        \"[&_svg:not([class*='size-'])]:size-3\",\r\n        className\r\n      )}\r\n      {...props}\r\n    />\r\n  )\r\n}\r\n\r\n/** One keycap for a whole binding; inner `Kbd` chips flatten via `in-data-[slot=kbd-group]` and stay separated by the gap. */\r\nfunction KbdGroup({ className, ...props }: React.ComponentProps<\"span\">) {\r\n  return (\r\n    <span\r\n      data-slot=\"kbd-group\"\r\n      className={cn(\r\n        \"pointer-events-none inline-flex h-5 select-none items-center gap-1 px-1 font-sans text-xs font-medium text-muted-foreground\",\r\n        KEYCAP,\r\n        className\r\n      )}\r\n      {...props}\r\n    />\r\n  )\r\n}\r\n\r\nexport { Kbd, KbdGroup }\r\n",
      "type": "registry:component",
      "target": "components/ui/kbd.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-context-menu/has-row-op.ts",
      "content": "import { useStore } from \"zustand\";\r\nimport { useDataGridStoreApi } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport type { DataGridReadState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\n/** What the grid can do with rows: `canCreateRow` is true when the grid has a `createRow` prop, `canDuplicateRow` when it has a `duplicateRow` prop. Without the prop, `insertRow` or `duplicateRows` does nothing. */\r\nexport function useDataGridRowOps(): { canCreateRow: boolean; canDuplicateRow: boolean } {\r\n  return { canCreateRow: useHasCreateRow(), canDuplicateRow: useHasDuplicateRow() };\r\n}\r\n\r\n/** Whether the grid was given a `createRow` prop — Insert row above/below are hidden without one. */\r\nexport function useHasCreateRow(): boolean {\r\n  return useStore(useDataGridStoreApi(), (s: DataGridReadState) => s.createRow != null);\r\n}\r\n\r\n/** Whether the grid was given a `duplicateRow` prop — Duplicate row(s) is hidden without one (the store's `duplicateRows` is a dev-warning no-op otherwise). */\r\nexport function useHasDuplicateRow(): boolean {\r\n  return useStore(useDataGridStoreApi(), (s: DataGridReadState) => s.duplicateRow != null);\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/has-row-op.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-context-menu/resolve-context-menu-target.ts",
      "content": "import { GRID_ATTR, gridAttrSelector } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\n/**\r\n * Which surface a `contextmenu` event landed on, in view-index coordinates: a data cell (`row`\r\n * from `[role=row]`'s `data-grid-row-index`, `col` from the gridcell's `aria-colindex`), a header\r\n * (`col` from the columnheader's `aria-colindex`), or neither (e.g. empty-state, scrollbar gutter).\r\n */\r\nexport type ContextMenuTarget =\r\n  | { kind: \"cell\"; row: number; col: number; columnId: string }\r\n  | { kind: \"header\"; col: number; columnId: string };\r\n\r\n/** Reads a numeric aria attribute off `element`, or null when absent/non-numeric. */\r\nfunction ariaIndex(element: Element, attr: string): number | null {\r\n  const raw = element.getAttribute(attr);\r\n  if (raw == null) return null;\r\n  const n = Number(raw);\r\n  return Number.isFinite(n) ? n : null;\r\n}\r\n\r\n/**\r\n * The view row index for a data `[role=row]` element. Prefers `data-grid-row-index`, stamped\r\n * directly by row.tsx and immune to the pinned-top band shifting `aria-rowindex`; falls back to\r\n * `aria-rowindex - 2` (only correct with no pinned-top rows) for markup predating that attribute.\r\n */\r\nfunction resolveViewRow(rowEl: Element): number | null {\r\n  const stamped = ariaIndex(rowEl, GRID_ATTR.rowIndex);\r\n  if (stamped != null) return stamped;\r\n  const ariaRow = ariaIndex(rowEl, \"aria-rowindex\");\r\n  return ariaRow == null ? null : ariaRow - 2;\r\n}\r\n\r\n/**\r\n * Resolves the logical grid surface under `eventTarget`. Marker cells (`data-grid-marker-cell`)\r\n * carry no `aria-colindex` by design (outside the data column index space), pinned top/bottom row\r\n * cells (`data-grid-pinned-row`, from the `data-grid-pinned-rows` add-on) aren't part of\r\n * `data`/the selection model, and skeleton cells (`data-skeleton`) carry no row data — all are\r\n * excluded and resolve to `null` (no cell/header menu; add a marker- or pinned-row-specific menu\r\n * separately if ever needed).\r\n */\r\nexport function resolveContextMenuTarget(eventTarget: EventTarget | null): ContextMenuTarget | null {\r\n  if (!(eventTarget instanceof Element)) return null;\r\n\r\n  const headerCell = eventTarget.closest('[role=\"columnheader\"]');\r\n  if (headerCell) {\r\n    const col = ariaIndex(headerCell, \"aria-colindex\");\r\n    const columnId = headerCell.getAttribute(\"data-column-id\");\r\n    if (col == null || columnId == null) return null;\r\n    return { kind: \"header\", col: col - 1, columnId };\r\n  }\r\n\r\n  const gridCell = eventTarget.closest(\r\n    `[role=\"gridcell\"]:not(${gridAttrSelector(\"markerCell\")}):not(${gridAttrSelector(\"pinnedRow\")}):not(${gridAttrSelector(\"skeleton\")})`,\r\n  );\r\n  if (gridCell) {\r\n    const col = ariaIndex(gridCell, \"aria-colindex\");\r\n    const columnId = gridCell.getAttribute(\"data-column-id\");\r\n    const rowEl = gridCell.closest('[role=\"row\"]');\r\n    if (col == null || columnId == null || rowEl == null) return null;\r\n    const row = resolveViewRow(rowEl);\r\n    if (row == null) return null;\r\n    return { kind: \"cell\", row, col: col - 1, columnId };\r\n  }\r\n\r\n  return null;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/resolve-context-menu-target.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-context-menu/selection-queries.ts",
      "content": "import type { ViewCoord, GridSelection } from \"@/registry/default/components/data-grid/data-grid\";\r\n\r\n/** Whether `coord` falls inside `selection`'s primary range, any stacked range, or the row/column channels — used to decide the Excel \"right-click outside selection selects that cell first\" gesture. */\r\nexport function isCellInSelection(selection: GridSelection, coord: ViewCoord): boolean {\r\n  if (selection.rows.hasIndex(coord.row)) return true;\r\n  if (selection.columns.hasIndex(coord.col)) return true;\r\n  if (!selection.current) return false;\r\n  const inRect = (r: { x: number; y: number; width: number; height: number }) =>\r\n    coord.col >= r.x && coord.col < r.x + r.width && coord.row >= r.y && coord.row < r.y + r.height;\r\n  return inRect(selection.current.range) || selection.current.rangeStack.some(inRect);\r\n}\r\n\r\n/** Row-op target set — the core's own derivation of the selected view rows (see `getSelectedViewRows`), re-exported so the cell menu shares one code path with every other consumer. */\r\nexport { getSelectedViewRows as selectedViewRows } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n",
      "type": "registry:component",
      "target": "components/data-grid-context-menu/selection-queries.ts"
    }
  ],
  "docs": "Optional: wrap your app in TooltipProvider (components/ui/tooltip) so grid tooltips open at once. See https://gridcn.vercel.app/docs/terms-help/fix-install-problems#tooltips",
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
