{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid",
  "title": "Data grid",
  "description": "A spreadsheet-style grid: pinned first column, sortable and reorderable columns, inline cell editing (a bottom sheet on phones), selection and add-row.",
  "dependencies": [
    "@dnd-kit/core@^6.3.1",
    "@dnd-kit/sortable@^10.0.0",
    "@dnd-kit/utilities@^3.2.2",
    "@keyline-icons/react@^2.2.0"
  ],
  "registryDependencies": [
    "@khaeli/checkbox",
    "@khaeli/date-picker",
    "@khaeli/fancy-button",
    "@khaeli/format",
    "@khaeli/loader",
    "@khaeli/utils"
  ],
  "files": [
    {
      "path": "registry/khaeli/ui/data-grid.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { createPortal, flushSync } from \"react-dom\"\nimport {\n  closestCenter,\n  DndContext,\n  DragOverlay,\n  KeyboardSensor,\n  MouseSensor,\n  TouchSensor,\n  useSensor,\n  useSensors,\n  type DraggableAttributes,\n  type DraggableSyntheticListeners,\n  type Modifier,\n} from \"@dnd-kit/core\"\nimport {\n  arrayMove,\n  SortableContext,\n  sortableKeyboardCoordinates,\n  useSortable,\n  verticalListSortingStrategy,\n} from \"@dnd-kit/sortable\"\nimport { CSS, type Transform } from \"@dnd-kit/utilities\"\nimport {\n  ArrowUpIcon,\n  GripVerticalIcon,\n  PlusIcon,\n  XIcon,\n} from \"@keyline-icons/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nimport { Checkbox } from \"@/components/ui/checkbox\"\nimport { Loader } from \"@/components/ui/loader\"\nimport {\n  DataGridCellEditor,\n  type DataGridEditorConfig,\n} from \"@/components/ui/data-grid-editor\"\nimport {\n  nextSort,\n  sortAnnouncement,\n  sortButtonLabel,\n  sortRows,\n  type DataGridSort,\n  type DataGridSortValue,\n} from \"@/components/ui/data-grid-sort\"\nimport { plainText } from \"@/lib/format\"\n\n// --- Types ---\n\nexport type DataGridOption = {\n  value: string\n  label: string\n  /** Rendered in the option list (and nothing else); e.g. <StatusBadge status=\"lead\" />. Defaults to label. */\n  render?: React.ReactNode\n}\n\ntype EditorBase<T> = {\n  /** Current raw value for an existing row; null/\"\" = empty. */\n  value: (row: T) => string | null\n  /** Shown in subtle text in empty draft cells and as the input placeholder. */\n  placeholder?: string\n  /** Empty input is rejected with \"{header} is required.\" (draft + existing rows). */\n  required?: boolean\n  /** Existing rows only; default true. Draft rows ignore this. */\n  editable?: (row: T) => boolean\n  /**\n   * Persist one cell of an existing row. MUST resolve only after the react-query cache\n   * holds the server's updated row, so `rows` already carries the new value and revision;\n   * reject with Error(message) to keep the editor open with the message. Omit for\n   * draft-only columns.\n   */\n  onSave?: (row: T, next: string) => Promise<void>\n}\n\nexport type DataGridEditor<T> =\n  | (EditorBase<T> & { kind: \"text\" | \"email\" | \"url\" })\n  | (EditorBase<T> & { kind: \"number\"; min?: number; step?: string })\n  | (EditorBase<T> & {\n      kind: \"select\"\n      /** row is null for the draft row */\n      options: (row: T | null) => DataGridOption[]\n      searchPlaceholder?: string\n    })\n  | (EditorBase<T> & { kind: \"date\" }) // value/next are \"YYYY-MM-DD\"\n\nexport interface DataGridColumn<T> {\n  id: string\n  header: React.ReactNode\n  /** Leads the column's \"Edit …\" row in the phone long-press menu; desktop headers are text-only. */\n  icon?: React.ReactNode\n  /** px; default 180 */\n  width?: number\n  align?: \"left\" | \"right\"\n  cell: (row: T) => React.ReactNode\n  edit?: DataGridEditor<T>\n  /** The column's aggregate in the footer row (e.g. a sum), over the rows in view. */\n  footer?: (rows: readonly T[]) => React.ReactNode\n  /** Makes the desktop header a sort button; the value rows are ordered by (null / \"\" / NaN last). */\n  sortValue?: (row: T) => DataGridSortValue\n  /** Plain-text column name for the sort button's label and announcements; default: the header when it is a string. */\n  sortLabel?: string\n}\n\n/**\n * A phone list row's parts (Underlay list-group row): a leading mark (a 36px\n * initial avatar), the title, one secondary line and a trailing fact. Each\n * part given replaces the one the grid derives from the columns.\n */\nexport interface DataGridListItem {\n  leading?: React.ReactNode\n  title?: React.ReactNode\n  secondary?: React.ReactNode\n  trailing?: React.ReactNode\n}\n\nexport interface DataGridCreate {\n  /** Add-row label, e.g. \"New client\". */\n  label: string\n  /** Column ids (pinned included) that must hold a value before onCreate runs. */\n  required: string[]\n  /** Initial draft values keyed by column id. */\n  defaults?: Record<string, string>\n  /**\n   * Called once, right after a draft commit leaves every required id filled. Resolve with\n   * the new row's key only after that row is present in `rows`; reject with Error(message)\n   * to keep the draft and show the message.\n   */\n  onCreate: (values: Record<string, string>) => Promise<string>\n}\n\nexport interface DataGridProps<T> {\n  \"aria-label\": string\n  /** scrolling columns */\n  columns: DataGridColumn<T>[]\n  /** first column, sticky left, width 250 unless pinned.width */\n  pinned: DataGridColumn<T>\n  rows: readonly T[]\n  rowKey: (row: T) => string\n  /** makes the pinned cell content an <a>; clicking it navigates */\n  rowHref?: (row: T) => string\n  onRowClick?: (row: T) => void\n  /** checkbox column inside the pinned cell (16px, inset 16px) */\n  selectable?: boolean\n  selected?: ReadonlySet<string>\n  onSelectedChange?: (next: Set<string>) => void\n  /** inline draft \"add row\" + quick-create lifecycle */\n  create?: DataGridCreate\n  /**\n   * Manual order is the default: the person places each row where they want\n   * it and `rows` draws as given. Choosing a sort (`sort`) turns reordering\n   * off: while a sort is active the grid behaves exactly as if this were\n   * undefined. Otherwise, when set, every body row gets a grip in the pinned\n   * cell's leading gutter (drag it: mouse past 6px, touch after a 200ms hold)\n   * and Alt+ArrowUp / Alt+ArrowDown moves the focused cell's row one place.\n   * Called once per completed move that changed the order, never for hover\n   * previews or cancelled drags, with every row key in the new order and the\n   * moved row's key. The caller owns the order: it should pass `rows` back in\n   * the new order; until a new `rows` arrives the grid holds the dropped\n   * order so the row never flashes back. The draft row and footer never move.\n   * Undefined = no drag affordance at all.\n   */\n  onReorder?: (keys: string[], movedKey: string) => void\n  /**\n   * The chosen sort. When it names a shown column (pinned or scrolling) with\n   * `sortValue`, both the desktop grid and the phone list draw the rows\n   * sorted; otherwise (null, or an unknown column) they draw in manual order.\n   */\n  sort?: DataGridSort | null\n  /** Called when a desktop header sort button is pressed (none -> ascending -> descending -> none). */\n  onSortChange?: (next: DataGridSort | null) => void\n  /** default `${rows.length} count` in the footer's leading cell */\n  footer?: React.ReactNode\n  /** Phones: the list row's parts, when the derived ones don't read right (`DataGridListItem`). */\n  listItem?: (row: T) => DataGridListItem\n  className?: string\n}\n\n// --- Sizes (38px header, 42px rows, 12px cell inset) ---\n\nconst DEFAULT_COLUMN_WIDTH = 180\nconst DEFAULT_PINNED_WIDTH = 250\nconst HEADER_HEIGHT = 38\nconst DRAFT_KEY = \"__draft__\"\n/**\n * A body row's height: 42px plus its 1px rule (`h-[43px]`). Every row is the\n * same height, so the body draws only the rows in view and stands in for the\n * rest with spacers of exactly their height.\n */\nconst ROW_HEIGHT = 43\n/** Rows drawn past each edge of the viewport, so a fast scroll or a held arrow key never meets a gap. */\nconst OVERSCAN = 12\n/** Rows drawn before the first measurement: the server render and the first paint. */\nconst INITIAL_ROWS = 40\n\n// The desktop grid shows from Tailwind's md breakpoint up; below it, the phone list.\nconst DESKTOP_QUERY = \"(min-width: 768px)\"\n\nfunction subscribeDesktop(onChange: () => void) {\n  const media = window.matchMedia(DESKTOP_QUERY)\n  media.addEventListener(\"change\", onChange)\n  return () => media.removeEventListener(\"change\", onChange)\n}\n\n/**\n * Whether the desktop grid shows rather than the phone list. Null on the\n * server and while hydrating: both render then, and CSS shows the right one\n * until the client knows the viewport and drops the other.\n */\nfunction useDesktopLayout(): boolean | null {\n  return React.useSyncExternalStore(\n    subscribeDesktop,\n    () => window.matchMedia(DESKTOP_QUERY).matches,\n    () => null\n  )\n}\n\n// Columns read through whitespace, not rules: rows keep their hairline, cells\n// carry no vertical divider. Body text is regular; the pinned record name\n// stays 500 so the row's subject leads.\nconst cellClass =\n  \"flex h-[42px] shrink-0 items-center px-3 text-base truncate max-md:h-full max-md:px-[13px]\"\n// The sticky column only draws its edge once the grid has scrolled sideways\n// (`data-x-scrolled` on the container); at rest it reads as an ordinary column.\nconst pinnedClass =\n  \"sticky left-0 z-10 flex h-[42px] shrink-0 items-center gap-3 bg-background px-3 text-base font-medium truncate group-data-[x-scrolled]/grid:shadow-[1px_0_0_var(--border)] max-md:h-full max-md:px-[13px]\"\n/** Column labels: 12px regular in the secondary grey on the whisper ground, no icons. */\nconst headerTextClass = \"h-[38px] bg-row-hover text-xs font-normal text-muted-foreground\"\n// The active cell: a 1px --primary ring inset into the cell, above row hover,\n// below the sticky header (and below the sticky pinned column when scrolled).\nconst activeRingClass =\n  \"rounded-[4px] [outline:1px_solid_var(--primary)] [outline-offset:-1px]\"\n\nfunction columnStyle(width: number): React.CSSProperties {\n  // M4: phones cap every column at half the viewport; 50vw ≥ any configured\n  // width at ≥ 768px, so desktop keeps the exact px value.\n  const clamped = `min(${width}px, 50vw)`\n  return { width: clamped, minWidth: clamped }\n}\n\n// --- State machine ---\n\ntype GridCell = { rowKey: string; columnId: string }\n\ninterface GridState {\n  active: GridCell | null\n  editing: boolean\n  /** non-null overrides the editor's initial input text (printable key / Backspace) */\n  seed: string | null\n  draft: Record<string, string> | null\n  creating: boolean\n  createError: string | null\n}\n\ntype GridAction =\n  | { type: \"activate\"; cell: GridCell }\n  | { type: \"clearActive\" }\n  | { type: \"openEditor\"; cell: GridCell; seed: string | null }\n  | { type: \"closeEditor\" }\n  | { type: \"openDraft\"; draft: Record<string, string>; cell: GridCell | null }\n  | { type: \"setDraftValue\"; columnId: string; value: string }\n  | { type: \"discardDraft\" }\n  | { type: \"createStart\" }\n  | { type: \"createError\"; message: string }\n  | { type: \"createSuccess\"; cell: GridCell }\n\nconst initialGridState: GridState = {\n  active: null,\n  editing: false,\n  seed: null,\n  draft: null,\n  creating: false,\n  createError: null,\n}\n\nfunction gridReducer(state: GridState, action: GridAction): GridState {\n  switch (action.type) {\n    case \"activate\":\n      return { ...state, active: action.cell, editing: false, seed: null }\n    case \"clearActive\":\n      return { ...state, active: null, editing: false, seed: null }\n    case \"openEditor\":\n      return { ...state, active: action.cell, editing: true, seed: action.seed }\n    case \"closeEditor\":\n      return { ...state, editing: false, seed: null }\n    case \"openDraft\":\n      return {\n        ...state,\n        draft: action.draft,\n        creating: false,\n        createError: null,\n        active: action.cell,\n        editing: action.cell !== null,\n        seed: null,\n      }\n    case \"setDraftValue\":\n      return state.draft\n        ? { ...state, draft: { ...state.draft, [action.columnId]: action.value } }\n        : state\n    case \"discardDraft\":\n      return {\n        ...state,\n        draft: null,\n        creating: false,\n        createError: null,\n        editing: false,\n        seed: null,\n        active: state.active?.rowKey === DRAFT_KEY ? null : state.active,\n      }\n    case \"createStart\":\n      return { ...state, creating: true, createError: null, editing: false, seed: null }\n    case \"createError\":\n      return { ...state, creating: false, createError: action.message }\n    case \"createSuccess\":\n      return {\n        ...state,\n        draft: null,\n        creating: false,\n        createError: null,\n        active: action.cell,\n        editing: false,\n        seed: null,\n      }\n  }\n}\n\n/**\n * The nearest ancestor (or the container itself) that scrolls vertically and\n * has something to scroll; null when the window scrolls the page.\n */\nfunction verticalScroller(container: HTMLElement): HTMLElement | null {\n  let scroller: HTMLElement | null = container\n  while (scroller && scroller !== document.body) {\n    const { overflowY } = getComputedStyle(scroller)\n    if (\n      (overflowY === \"auto\" || overflowY === \"scroll\") &&\n      scroller.scrollHeight > scroller.clientHeight\n    )\n      return scroller\n    scroller = scroller.parentElement\n  }\n  return null\n}\n\n/**\n * Scrolls a cell sideways into view inside the horizontally scrolling grid\n * container, keeping it clear of the sticky pinned column.\n */\nfunction scrollColumnIntoView(\n  container: HTMLElement,\n  cell: HTMLElement,\n  isPinnedColumn: boolean\n): void {\n  if (isPinnedColumn) return\n  const containerRect = container.getBoundingClientRect()\n  // min(px, 50vw) widths make the rendered sizes viewport-dependent, so\n  // measure instead of trusting the constants.\n  const pinnedWidth =\n    container\n      .querySelector<HTMLElement>('[data-slot=\"data-grid-pinned\"]')\n      ?.getBoundingClientRect().width ?? 0\n  const rect = cell.getBoundingClientRect()\n  const leftEdge = containerRect.left + pinnedWidth\n  if (rect.left < leftEdge) container.scrollLeft -= leftEdge - rect.left\n  else if (rect.right > containerRect.right)\n    container.scrollLeft += rect.right - containerRect.right\n}\n\n/**\n * Scrolls a cell into view inside the horizontally scrolling grid container,\n * keeping it clear of the sticky pinned column, then nudges the nearest\n * vertical scroller (or the window) so the cell clears the sticky header.\n */\nfunction scrollCellIntoView(\n  container: HTMLElement,\n  cell: HTMLElement,\n  isPinnedColumn: boolean\n): void {\n  // max-md heights make the rendered sizes viewport-dependent, so measure\n  // instead of trusting the constants.\n  const headerHeight =\n    container\n      .querySelector<HTMLElement>('[data-slot=\"data-grid-header\"]')\n      ?.getBoundingClientRect().height ?? HEADER_HEIGHT\n  scrollColumnIntoView(container, cell, isPinnedColumn)\n  const scroller = verticalScroller(container)\n  const rect = cell.getBoundingClientRect()\n  if (scroller) {\n    const scrollerRect = scroller.getBoundingClientRect()\n    const top = scrollerRect.top + headerHeight\n    if (rect.top < top) scroller.scrollTop -= top - rect.top\n    else if (rect.bottom > scrollerRect.bottom)\n      scroller.scrollTop += rect.bottom - scrollerRect.bottom\n  } else {\n    if (rect.top < headerHeight) window.scrollBy(0, rect.top - headerHeight)\n    else if (rect.bottom > window.innerHeight)\n      window.scrollBy(0, rect.bottom - window.innerHeight)\n  }\n}\n\n// --- Manual order (onReorder) ---\n\n/** Rows only travel up and down; the lifted copy never drifts sideways. */\nconst restrictToVerticalAxis: Modifier = ({ transform }) => ({ ...transform, x: 0 })\n\n/** The click that ends a drag lands on whatever is under the pointer; swallow it so a dropped row never follows its link or starts a cell edit. A touch's synthetic click arrives after touchend, so it gets a longer window. */\nfunction swallowNextClick(ms: number) {\n  const stop = (event: Event) => {\n    event.preventDefault()\n    event.stopPropagation()\n  }\n  window.addEventListener(\"click\", stop, { capture: true, once: true })\n  setTimeout(() => window.removeEventListener(\"click\", stop, { capture: true }), ms)\n}\n\n/** The slice of useSortable a body row draws with. */\ninterface SortableRowState {\n  setNodeRef: (element: HTMLElement | null) => void\n  setActivatorNodeRef: (element: HTMLElement | null) => void\n  attributes: DraggableAttributes\n  listeners: DraggableSyntheticListeners\n  transform: Transform | null\n  transition: string | undefined\n  isDragging: boolean\n}\n\n/** useSortable needs a component per row; the row's markup stays in DataGrid. */\nfunction SortableRow({\n  id,\n  children,\n}: {\n  id: string\n  children: (sortable: SortableRowState) => React.ReactNode\n}) {\n  return <>{children(useSortable({ id }))}</>\n}\n\n/**\n * The row being dragged. The lifted copy is clipped to the grid's visible\n * width at the grid's sideways scroll, so it matches the row it left.\n */\ntype RowLift = {\n  key: string\n  via: \"pointer\" | \"keyboard\"\n  scrollLeft: number\n  width: number\n}\n\n// --- DataGrid ---\n\nexport function DataGrid<T>(props: DataGridProps<T>): React.JSX.Element | null {\n  const {\n    \"aria-label\": ariaLabel,\n    columns,\n    pinned,\n    rows,\n    rowKey,\n    rowHref,\n    onRowClick,\n    selectable,\n    selected,\n    onSelectedChange,\n    create,\n    footer,\n    onReorder,\n    sort,\n    onSortChange,\n    listItem,\n    className,\n  } = props\n\n  const [state, dispatch] = React.useReducer(gridReducer, initialGridState)\n  const containerRef = React.useRef<HTMLDivElement | null>(null)\n  const cellRefs = React.useRef(new Map<string, HTMLElement>())\n  const refCallbacks = React.useRef(\n    new Map<string, (el: HTMLElement | null) => void>()\n  )\n  // Mirrors state.draft synchronously so commit → close handlers in the same\n  // event tick see the just-committed values before React re-renders.\n  const draftRef = React.useRef<Record<string, string> | null>(null)\n  const lastCommittedColumnRef = React.useRef<string | null>(null)\n  /** Whether the pressed cell was active before mousedown's focus re-render. */\n  const mouseWasActiveRef = React.useRef(false)\n  /**\n   * The order drawn between a completed move and the caller's reordered\n   * `rows`, so the moved row never flashes back. A new `rows` identity means\n   * the caller has caught up (or moved on) and its order wins.\n   */\n  const [heldOrder, setHeldOrder] = React.useState<{\n    rows: readonly T[]\n    keys: string[]\n  } | null>(null)\n  const [lift, setLift] = React.useState<RowLift | null>(null)\n  // dnd-kit's own ids come from a module counter, which differs between server and client.\n  const dndId = React.useId()\n  // As the board's cards: mouse past 6px, touch after a 200ms hold, and the\n  // keyboard through the grip.\n  const sensors = useSensors(\n    useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),\n    useSensor(TouchSensor, { activationConstraint: { delay: 200, tolerance: 6 } }),\n    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })\n  )\n  // One of the desktop grid and the phone list renders, never both once the viewport is known.\n  const desktop = useDesktopLayout()\n\n  const allColumns = React.useMemo(() => [pinned, ...columns], [pinned, columns])\n  const pinnedWidth = pinned.width ?? DEFAULT_PINNED_WIDTH\n\n  // The sort applies only while it names a shown column that can sort.\n  const sortColumn = sort\n    ? allColumns.find((column) => column.id === sort.columnId && column.sortValue)\n    : undefined\n  const activeSort: DataGridSort | null = sortColumn && sort ? sort : null\n  // A chosen sort turns manual order off: no grips, no drag, no Alt+Arrow moves.\n  const reorder = activeSort ? undefined : onReorder\n  const sortValue = sortColumn?.sortValue\n  const sortDirection = activeSort?.direction\n  const sortedRows = React.useMemo(\n    () =>\n      sortValue && sortDirection ? sortRows(rows, sortValue, sortDirection) : null,\n    [rows, sortValue, sortDirection]\n  )\n\n  const sourceKeys = rows.map(rowKey)\n  const rowByKey = new Map<string, T>()\n  rows.forEach((row, index) => rowByKey.set(sourceKeys[index]!, row))\n  // Rows in the order drawn: sorted, the caller's, or the held order of the last move.\n  const rowKeys = sortedRows\n    ? sortedRows.map(rowKey)\n    : heldOrder !== null && heldOrder.rows === rows\n      ? heldOrder.keys\n      : sourceKeys\n  const orderedRows =\n    sortedRows ??\n    (rowKeys === sourceKeys ? rows : rowKeys.map((key) => rowByKey.get(key)!))\n  const navRowKeys = state.draft ? [...rowKeys, DRAFT_KEY] : rowKeys\n\n  // --- Sortable headers (Arc sortable-data-table pattern) ---\n\n  const sortableColumns = allColumns.filter((column) => column.sortValue)\n  const headerButtonRefs = React.useRef(new Map<string, HTMLButtonElement>())\n  /** The header row's one tab stop: the last focused sort button. */\n  const [headerStop, setHeaderStop] = React.useState<string | null>(null)\n  /** Said once after a person changes the sort, never on mount or restore. */\n  const [sortMessage, setSortMessage] = React.useState(\"\")\n  const headerTabId = sortableColumns.some((column) => column.id === headerStop)\n    ? headerStop\n    : (activeSort?.columnId ?? sortableColumns[0]?.id ?? null)\n  const sortLabelOf = (column: DataGridColumn<T>): string =>\n    column.sortLabel ?? plainText(column.header) ?? column.id\n\n  const cellKey = (rk: string, columnId: string) => `${rk}\\u0000${columnId}`\n  const activeCellKey = state.active\n    ? cellKey(state.active.rowKey, state.active.columnId)\n    : null\n  const firstCellKey =\n    rowKeys.length > 0\n      ? cellKey(rowKeys[0]!, pinned.id)\n      : state.draft\n        ? cellKey(DRAFT_KEY, pinned.id)\n        : null\n\n  const editableOf = (rk: string, column: DataGridColumn<T>): boolean => {\n    const edit = column.edit\n    if (!edit) return false\n    if (rk === DRAFT_KEY) return true\n    const row = rowByKey.get(rk)\n    if (!row) return false\n    return edit.editable ? edit.editable(row) : true\n  }\n\n  const setCellRef = (key: string) => {\n    let callback = refCallbacks.current.get(key)\n    if (!callback) {\n      callback = (el) => {\n        if (el) cellRefs.current.set(key, el)\n        else cellRefs.current.delete(key)\n      }\n      refCallbacks.current.set(key, callback)\n    }\n    return callback\n  }\n\n  // Roving focus: whenever the active cell changes outside an editing session,\n  // scroll it into view (sticky pinned column + header) and focus it. This also\n  // restores focus to the cell when the editor closes.\n  React.useEffect(() => {\n    if (!activeCellKey || state.editing) return\n    const el = cellRefs.current.get(activeCellKey)\n    const container = containerRef.current\n    if (!el || !container) return\n    scrollCellIntoView(container, el, state.active!.columnId === pinned.id)\n    el.focus({ preventScroll: true })\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [activeCellKey, state.editing])\n\n  // Tablets: while more columns remain to the right, the container\n  // carries data-h-scroll=\"more\" and foundation.css fades the trailing edge as a\n  // scroll affordance (regular tier and coarse pointers only; no layout\n  // shift). `data-x-scrolled` marks any sideways offset so the pinned column\n  // shows its edge only while content passes under it. Re-measured on scroll,\n  // resize and data changes.\n  React.useEffect(() => {\n    const container = containerRef.current\n    if (!container) return\n    const update = () => {\n      const more =\n        container.scrollLeft + container.clientWidth < container.scrollWidth - 1\n      container.setAttribute(\"data-h-scroll\", more ? \"more\" : \"end\")\n      container.toggleAttribute(\"data-x-scrolled\", container.scrollLeft > 0)\n    }\n    update()\n    container.addEventListener(\"scroll\", update, { passive: true })\n    const observer = new ResizeObserver(update)\n    observer.observe(container)\n    return () => {\n      container.removeEventListener(\"scroll\", update)\n      observer.disconnect()\n    }\n  }, [rows, columns, desktop])\n\n  // --- Row windowing: only the rows in view (plus OVERSCAN) are drawn ---\n\n  /** Marks where the body rows begin, so the rows in view follow from its offset. */\n  const bodyRef = React.useRef<HTMLDivElement | null>(null)\n  const [rowWindow, setRowWindow] = React.useState({ start: 0, end: INITIAL_ROWS })\n  const rowCount = rowKeys.length\n  // Re-measured on any scroll (captured: the scroller may be any ancestor),\n  // on resize and when the row count changes; renders only when the window moves.\n  React.useLayoutEffect(() => {\n    const container = containerRef.current\n    const body = bodyRef.current\n    if (!container || !body) return\n    const measure = () => {\n      const scroller = verticalScroller(container)\n      const bounds = scroller?.getBoundingClientRect()\n      const top = Math.max(0, bounds?.top ?? 0)\n      const bottom = Math.min(window.innerHeight, bounds?.bottom ?? window.innerHeight)\n      const bodyTop = body.getBoundingClientRect().top\n      const start = Math.min(rowCount, Math.max(0, Math.floor((top - bodyTop) / ROW_HEIGHT) - OVERSCAN))\n      const end = Math.min(rowCount, Math.max(start, Math.ceil((bottom - bodyTop) / ROW_HEIGHT) + OVERSCAN))\n      setRowWindow((previous) =>\n        previous.start === start && previous.end === end ? previous : { start, end }\n      )\n    }\n    measure()\n    window.addEventListener(\"scroll\", measure, { capture: true, passive: true })\n    window.addEventListener(\"resize\", measure)\n    const observer = new ResizeObserver(measure)\n    observer.observe(container)\n    return () => {\n      window.removeEventListener(\"scroll\", measure, { capture: true })\n      window.removeEventListener(\"resize\", measure)\n      observer.disconnect()\n    }\n  }, [rowCount, desktop])\n\n  /**\n   * The row indexes drawn, ascending: the window, plus the first row (the\n   * grid's tab stop until a cell is active), the active cell's row (so focus\n   * and an open editor survive scrolling it out of view) and a lifted row.\n   */\n  const drawnIndexes = (() => {\n    const end = Math.min(rowWindow.end, rowCount)\n    const indexes = new Set<number>()\n    for (let index = Math.min(rowWindow.start, end); index < end; index++) indexes.add(index)\n    const kept = [\n      0,\n      state.active ? rowKeys.indexOf(state.active.rowKey) : -1,\n      lift ? rowKeys.indexOf(lift.key) : -1,\n    ]\n    for (const index of kept) if (index >= 0 && index < rowCount) indexes.add(index)\n    return [...indexes].sort((a, b) => a - b)\n  })()\n\n  /** The drawn rows in order, with a spacer of the skipped rows' height in each gap. */\n  const windowedRows = (draw: (row: T, key: string, index: number) => React.ReactNode) => {\n    const out: React.ReactNode[] = []\n    const gap = (from: number, to: number) => (\n      <div\n        key={`\\u0000gap${from}`}\n        aria-hidden\n        role=\"presentation\"\n        data-slot=\"data-grid-spacer\"\n        style={{ height: (to - from) * ROW_HEIGHT }}\n      />\n    )\n    let next = 0\n    for (const index of drawnIndexes) {\n      if (index > next) out.push(gap(next, index))\n      out.push(draw(orderedRows[index]!, rowKeys[index]!, index))\n      next = index + 1\n    }\n    if (rowCount > next) out.push(gap(next, rowCount))\n    return out\n  }\n\n  // --- Phone list (Mail/Messages grammar) ---\n\n  const listRowRefs = React.useRef(new Map<string, HTMLDivElement>())\n  const listPressRef = React.useRef<{ x: number; y: number; timer: number } | null>(null)\n  const suppressListClickRef = React.useRef(false)\n  const [listMenu, setListMenu] = React.useState<{\n    rowKey: string\n    rect: { top: number; left: number; width: number; height: number }\n  } | null>(null)\n  const [listMenuShown, setListMenuShown] = React.useState(false)\n  const [listMenuClosing, setListMenuClosing] = React.useState(false)\n\n  // Exit: closing drops listMenuShown so the scrim, lifted row\n  // and menu transition back; the portal stays mounted until the menu's\n  // scale transition ends (350ms safety fallback).\n  const listMenuRef = React.useRef<HTMLDivElement | null>(null)\n  const closeListMenu = () => {\n    // Focus inside the menu goes back to its row before the menu leaves.\n    if (listMenu && listMenuRef.current?.contains(document.activeElement))\n      listRowRefs.current.get(listMenu.rowKey)?.focus({ preventScroll: true })\n    setListMenuShown(false)\n    setListMenuClosing(true)\n  }\n  const unmountListMenu = React.useCallback(() => {\n    setListMenu(null)\n    setListMenuClosing(false)\n  }, [])\n  React.useEffect(() => {\n    if (!listMenuClosing) return\n    const timer = window.setTimeout(unmountListMenu, 350)\n    return () => window.clearTimeout(timer)\n  }, [listMenuClosing, unmountListMenu])\n\n  // Lift-in transition + scroll lock while the context menu is up (Mail's\n  // long-press: the screen behind freezes under the scrim).\n  React.useEffect(() => {\n    if (!listMenu) return\n    const raf = requestAnimationFrame(() => setListMenuShown(true))\n    // The menu takes focus, so the keyboard and a screen reader are in it.\n    listMenuRef.current\n      ?.querySelector<HTMLElement>('[role=\"menuitem\"]')\n      ?.focus({ preventScroll: true })\n    const previous = document.body.style.overflow\n    document.body.style.overflow = \"hidden\"\n    return () => {\n      cancelAnimationFrame(raf)\n      setListMenuShown(false)\n      document.body.style.overflow = previous\n    }\n  }, [listMenu])\n\n  // Some placeholder cells only reveal themselves once their component\n  // renders (a DateText without a value prints a subtle fallback marked\n  // [data-placeholder], a FitBadge without a score the subtle \"—\" span), so\n  // they cannot be filtered when the parts are chosen. Mark them after every\n  // render; the part/divider CSS keys on [data-empty].\n  const listRef = React.useRef<HTMLDivElement>(null)\n  React.useLayoutEffect(() => {\n    const parts = listRef.current?.querySelectorAll<HTMLElement>(\"[data-list-part]\") ?? []\n    for (const part of parts) {\n      const text = part.textContent?.trim() ?? \"\"\n      const placeholder = part.querySelector(\"[data-placeholder]\")?.textContent?.trim()\n      if (text === \"\" || text === \"—\" || placeholder === text) part.setAttribute(\"data-empty\", \"\")\n      else part.removeAttribute(\"data-empty\")\n    }\n  })\n\n  const moveFrom = (cell: GridCell, dRow: number, dCol: number): GridCell | null => {\n    const rowIndex = navRowKeys.indexOf(cell.rowKey)\n    const colIndex = allColumns.findIndex((c) => c.id === cell.columnId)\n    if (rowIndex < 0 || colIndex < 0) return null\n    const r = Math.min(Math.max(rowIndex + dRow, 0), navRowKeys.length - 1)\n    const c = Math.min(Math.max(colIndex + dCol, 0), allColumns.length - 1)\n    return { rowKey: navRowKeys[r]!, columnId: allColumns[c]!.id }\n  }\n\n  const tabTarget = (cell: GridCell, dir: \"next\" | \"prev\"): GridCell | null => {\n    const rowIndex = navRowKeys.indexOf(cell.rowKey)\n    const colIndex = allColumns.findIndex((c) => c.id === cell.columnId)\n    if (rowIndex < 0 || colIndex < 0) return null\n    const index =\n      rowIndex * allColumns.length + colIndex + (dir === \"next\" ? 1 : -1)\n    if (index < 0 || index >= navRowKeys.length * allColumns.length) return null\n    return {\n      rowKey: navRowKeys[Math.floor(index / allColumns.length)]!,\n      columnId: allColumns[index % allColumns.length]!.id,\n    }\n  }\n\n  const openRecord = (rk: string) => {\n    const row = rowByKey.get(rk)\n    if (!row) return\n    if (onRowClick) {\n      onRowClick(row)\n      return\n    }\n    if (!rowHref) return\n    const anchor = cellRefs.current\n      .get(cellKey(rk, pinned.id))\n      ?.querySelector<HTMLAnchorElement>(\"[data-grid-anchor]\")\n    if (anchor) anchor.click()\n    else window.location.assign(rowHref(row))\n  }\n\n  const addRowRef = React.useRef<HTMLButtonElement | null>(null)\n  const discardDraft = () => {\n    // The draft row unmounts with whatever holds focus inside it, which would\n    // drop focus to the page: it goes to the button that opened the row.\n    const held =\n      containerRef.current\n        ?.querySelector(\"[data-draft]\")\n        ?.contains(document.activeElement) ?? false\n    draftRef.current = null\n    flushSync(() => dispatch({ type: \"discardDraft\" }))\n    if (held) addRowRef.current?.focus({ preventScroll: true })\n  }\n\n  const openDraft = () => {\n    if (!create || state.creating) return\n    if (state.draft) {\n      const values = draftRef.current ?? {}\n      const target =\n        allColumns.find(\n          (c) =>\n            c.edit &&\n            create.required.includes(c.id) &&\n            (values[c.id] ?? \"\").trim() === \"\"\n        ) ?? allColumns.find((c) => c.edit)\n      if (target)\n        dispatch({\n          type: \"openEditor\",\n          cell: { rowKey: DRAFT_KEY, columnId: target.id },\n          seed: null,\n        })\n      return\n    }\n    const defaults = { ...(create.defaults ?? {}) }\n    draftRef.current = defaults\n    lastCommittedColumnRef.current = null\n    const first =\n      allColumns.find((c) => c.edit && create.required.includes(c.id)) ??\n      allColumns.find((c) => c.edit)\n    dispatch({\n      type: \"openDraft\",\n      draft: defaults,\n      cell: first ? { rowKey: DRAFT_KEY, columnId: first.id } : null,\n    })\n  }\n\n  const runCreate = async (values: Record<string, string>) => {\n    if (!create) return\n    dispatch({ type: \"createStart\" })\n    try {\n      const key = await create.onCreate(values)\n      const lastId = lastCommittedColumnRef.current\n      const lastIndex = lastId\n        ? allColumns.findIndex((c) => c.id === lastId)\n        : -1\n      const nextIndex = Math.min(lastIndex + 1, allColumns.length - 1)\n      draftRef.current = null\n      dispatch({\n        type: \"createSuccess\",\n        cell: { rowKey: key, columnId: allColumns[nextIndex]!.id },\n      })\n    } catch (err) {\n      dispatch({\n        type: \"createError\",\n        message:\n          err instanceof Error && err.message ? err.message : \"Could not create.\",\n      })\n    }\n  }\n\n  /**\n   * Grid-side commit semantics: unchanged → resolve without\n   * saving; required + empty → reject; draft cells store into the draft;\n   * existing cells persist through edit.onSave.\n   */\n  const commitCell = async (\n    cell: GridCell,\n    column: DataGridColumn<T>,\n    next: string\n  ): Promise<void> => {\n    const edit = column.edit\n    if (!edit) return\n    const header = plainText(column.header) ?? column.id\n    if (edit.required && next.trim() === \"\")\n      throw new Error(`${header} is required.`)\n    if (cell.rowKey === DRAFT_KEY) {\n      draftRef.current = { ...(draftRef.current ?? {}), [column.id]: next }\n      lastCommittedColumnRef.current = column.id\n      dispatch({ type: \"setDraftValue\", columnId: column.id, value: next })\n      return\n    }\n    const row = rowByKey.get(cell.rowKey)\n    if (!row) return\n    const current = edit.value(row) ?? \"\"\n    if (next === current) return\n    await edit.onSave?.(row, next)\n  }\n\n  const handleEditorClose = (\n    cell: GridCell,\n    committed: boolean,\n    nav?: \"next\" | \"prev\" | \"auto\"\n  ) => {\n    dispatch({ type: \"closeEditor\" })\n    if (!committed) return\n    if (cell.rowKey === DRAFT_KEY && create) {\n      const values = draftRef.current ?? {}\n      const filled = create.required.every(\n        (id) => (values[id] ?? \"\").trim() !== \"\"\n      )\n      if (filled) {\n        void runCreate(values)\n        return\n      }\n      if (nav === \"auto\") {\n        const next = allColumns.find(\n          (c) =>\n            c.edit &&\n            create.required.includes(c.id) &&\n            (values[c.id] ?? \"\").trim() === \"\"\n        )\n        if (next)\n          dispatch({\n            type: \"openEditor\",\n            cell: { rowKey: DRAFT_KEY, columnId: next.id },\n            seed: null,\n          })\n        return\n      }\n    }\n    if (nav === \"next\" || nav === \"prev\") {\n      const target = tabTarget(cell, nav)\n      if (target) dispatch({ type: \"activate\", cell: target })\n    }\n  }\n\n  /** A row's name for its grip and announcements: the pinned column's text, when it has one. */\n  const rowLabel = (key: string): string | undefined => {\n    const row = rowByKey.get(key)\n    if (row === undefined) return undefined\n    const text = pinned.edit?.value(row) ?? plainText(pinned.cell(row))\n    return text?.trim() || undefined\n  }\n\n  /** Holds the new order until the caller's reordered `rows` arrive, then reports it. */\n  const commitOrder = (next: string[], movedKey: string) => {\n    setHeldOrder({ rows, keys: next })\n    reorder?.(next, movedKey)\n  }\n\n  const handleCellKeyDown =\n    (cell: GridCell, column: DataGridColumn<T>) =>\n    (event: React.KeyboardEvent<HTMLDivElement>) => {\n      if (event.target !== event.currentTarget || state.editing) return\n      // Shift+Space selects the focused cell's row, the grid pattern's key:\n      // Tab walks the cells and never stops on a row's checkbox.\n      if (selectable && event.shiftKey && event.key === \" \" && cell.rowKey !== DRAFT_KEY) {\n        event.preventDefault()\n        toggleRow(cell.rowKey, !(selected?.has(cell.rowKey) ?? false))\n        return\n      }\n      // Alt+ArrowUp / Alt+ArrowDown moves the row one place at once. React\n      // moves the row's node to reorder it, which drops focus, so the new\n      // order renders synchronously and the same cell takes focus back.\n      if (\n        reorder &&\n        event.altKey &&\n        (event.key === \"ArrowUp\" || event.key === \"ArrowDown\") &&\n        cell.rowKey !== DRAFT_KEY\n      ) {\n        event.preventDefault()\n        const from = rowKeys.indexOf(cell.rowKey)\n        const to = from + (event.key === \"ArrowUp\" ? -1 : 1)\n        if (from < 0 || to < 0 || to >= rowKeys.length) return\n        const next = arrayMove(rowKeys, from, to)\n        flushSync(() => setHeldOrder({ rows, keys: next }))\n        const el = cellRefs.current.get(cellKey(cell.rowKey, cell.columnId))\n        const container = containerRef.current\n        if (el && container) {\n          scrollCellIntoView(container, el, cell.columnId === pinned.id)\n          el.focus({ preventScroll: true })\n        }\n        reorder(next, cell.rowKey)\n        return\n      }\n      const edit = column.edit\n      const editable = editableOf(cell.rowKey, column)\n      const move = (dRow: number, dCol: number) => {\n        event.preventDefault()\n        const target = moveFrom(cell, dRow, dCol)\n        if (target) dispatch({ type: \"activate\", cell: target })\n      }\n      switch (event.key) {\n        case \"ArrowUp\":\n          move(-1, 0)\n          return\n        case \"ArrowDown\":\n          move(1, 0)\n          return\n        case \"ArrowLeft\":\n          move(0, -1)\n          return\n        case \"ArrowRight\":\n          move(0, 1)\n          return\n        case \"Home\":\n          event.preventDefault()\n          dispatch({\n            type: \"activate\",\n            cell: { rowKey: cell.rowKey, columnId: allColumns[0]!.id },\n          })\n          return\n        case \"End\":\n          event.preventDefault()\n          dispatch({\n            type: \"activate\",\n            cell: {\n              rowKey: cell.rowKey,\n              columnId: allColumns[allColumns.length - 1]!.id,\n            },\n          })\n          return\n        case \"Tab\": {\n          const target = tabTarget(cell, event.shiftKey ? \"prev\" : \"next\")\n          if (target) {\n            event.preventDefault()\n            dispatch({ type: \"activate\", cell: target })\n          }\n          // At the grid's ends: let focus leave.\n          return\n        }\n        case \"Enter\":\n        case \"F2\":\n          event.preventDefault()\n          if (editable) dispatch({ type: \"openEditor\", cell, seed: null })\n          else if (cell.rowKey !== DRAFT_KEY && (rowHref || onRowClick))\n            openRecord(cell.rowKey)\n          return\n        case \"Backspace\":\n        case \"Delete\":\n          if (editable && !edit?.required) {\n            event.preventDefault()\n            dispatch({ type: \"openEditor\", cell, seed: \"\" })\n          }\n          return\n        case \"Escape\":\n          if (cell.rowKey === DRAFT_KEY) discardDraft()\n          else dispatch({ type: \"clearActive\" })\n          return\n      }\n      if (\n        event.key.length === 1 &&\n        !event.metaKey &&\n        !event.ctrlKey &&\n        !event.altKey &&\n        editable &&\n        edit\n      ) {\n        event.preventDefault()\n        dispatch({\n          type: \"openEditor\",\n          cell,\n          seed: edit.kind === \"date\" ? null : event.key,\n        })\n      }\n    }\n\n  /**\n   * Shared gridcell wiring: roving tabIndex, active ring, click/double-click/\n   * keyboard handling, data-active / data-editing attributes.\n   */\n  const gridCellProps = (\n    cell: GridCell,\n    column: DataGridColumn<T>,\n    kind: \"pinned\" | \"cell\",\n    extraClass?: string\n  ) => {\n    const key = cellKey(cell.rowKey, column.id)\n    const isActive = activeCellKey === key\n    const editable = editableOf(cell.rowKey, column)\n    return {\n      role: \"gridcell\" as const,\n      \"data-slot\": kind === \"pinned\" ? \"data-grid-pinned\" : \"data-grid-cell\",\n      \"data-active\": isActive ? \"\" : undefined,\n      \"data-editing\": isActive && state.editing ? \"\" : undefined,\n      \"aria-selected\": isActive || undefined,\n      \"aria-readonly\": editable ? undefined : true,\n      tabIndex: key === (activeCellKey ?? firstCellKey) ? 0 : -1,\n      ref: setCellRef(key),\n      style: columnStyle(\n        kind === \"pinned\" ? pinnedWidth : (column.width ?? DEFAULT_COLUMN_WIDTH)\n      ),\n      className: cn(\n        kind === \"pinned\" ? pinnedClass : cellClass,\n        kind === \"cell\" && column.align === \"right\" && \"justify-end text-right\",\n        isActive ? cn(activeRingClass, kind === \"cell\" && \"z-[5]\") : \"outline-none\",\n        extraClass\n      ),\n      // mousedown fires before the focus-driven \"activate\" re-render, so it\n      // records whether the cell was already active before this press; the\n      // click handler of the re-rendered cell would otherwise see itself as\n      // active and open the editor on a plain first click.\n      onMouseDown: (event: React.MouseEvent<HTMLDivElement>) => {\n        const target = event.target as HTMLElement\n        if (target.closest(\"a,button,input,textarea,select,label\")) return\n        mouseWasActiveRef.current = isActive\n      },\n      onClick: (event: React.MouseEvent<HTMLDivElement>) => {\n        const target = event.target as HTMLElement\n        if (target.closest(\"a,button,input,textarea,select,label\")) return\n        const wasActive = mouseWasActiveRef.current\n        mouseWasActiveRef.current = false\n        // Touch has no hover-then-click ritual: one tap edits. The pinned\n        // anchor/button bailed out above, so tapping content still navigates.\n        const coarse = window.matchMedia(\"(pointer: coarse)\").matches\n        if ((wasActive || coarse) && !state.editing && editable)\n          dispatch({ type: \"openEditor\", cell, seed: null })\n        else dispatch({ type: \"activate\", cell })\n      },\n      onDoubleClick: (event: React.MouseEvent<HTMLDivElement>) => {\n        const target = event.target as HTMLElement\n        if (target.closest(\"a,button,input,textarea,select,label\")) return\n        if (editable && !state.editing)\n          dispatch({ type: \"openEditor\", cell, seed: null })\n      },\n      onKeyDown: handleCellKeyDown(cell, column),\n      onFocus: (event: React.FocusEvent<HTMLDivElement>) => {\n        if (event.target !== event.currentTarget) return\n        if (state.editing || isActive) return\n        dispatch({ type: \"activate\", cell })\n      },\n    }\n  }\n\n  const draftCellContent = (column: DataGridColumn<T>): React.ReactNode => {\n    const edit = column.edit\n    if (!edit || !state.draft) return null\n    const value = state.draft[column.id] ?? \"\"\n    if (value.trim() === \"\")\n      return edit.placeholder ? (\n        <span className=\"truncate text-subtle-foreground\">{edit.placeholder}</span>\n      ) : null\n    if (edit.kind === \"select\") {\n      const option = edit.options(null).find((o) => o.value === value)\n      return (\n        <span className=\"flex min-w-0 items-center gap-2 overflow-hidden whitespace-nowrap\">\n          {option ? (option.render ?? option.label) : value}\n        </span>\n      )\n    }\n    return <span className=\"truncate\">{value}</span>\n  }\n\n  if (rows.length === 0 && !state.draft) return null\n\n  const allSelected =\n    rows.length > 0 && rows.every((row) => selected?.has(rowKey(row)) ?? false)\n  const someSelected = rows.some((row) => selected?.has(rowKey(row)) ?? false)\n\n  const toggleAll = (checked: boolean) => {\n    onSelectedChange?.(checked ? new Set(rowKeys) : new Set())\n  }\n\n  const toggleRow = (key: string, checked: boolean) => {\n    const next = new Set(selected ?? [])\n    if (checked) next.add(key)\n    else next.delete(key)\n    onSelectedChange?.(next)\n  }\n\n  // --- Header sort buttons: one tab stop for the row, Arrow keys between them ---\n\n  const focusHeaderButton = (column: DataGridColumn<T>) => {\n    const button = headerButtonRefs.current.get(column.id)\n    const container = containerRef.current\n    if (!button) return\n    setHeaderStop(column.id)\n    if (container)\n      scrollColumnIntoView(\n        container,\n        button.closest<HTMLElement>('[role=\"columnheader\"]') ?? button,\n        column.id === pinned.id\n      )\n    button.focus({ preventScroll: true })\n  }\n\n  const sortHeaderButton = (column: DataGridColumn<T>, extraClass: string) => {\n    const direction = activeSort?.columnId === column.id ? activeSort.direction : null\n    const label = sortLabelOf(column)\n    const alignRight = column !== pinned && column.align === \"right\"\n    // The arrow flips for descending; unsorted columns show it on hover only.\n    const glyph = (\n      <ArrowUpIcon\n        aria-hidden\n        className={cn(\n          \"size-3.5 shrink-0 motion-safe:transition-[rotate,opacity]\",\n          direction === \"descending\" && \"rotate-180\",\n          direction === null && \"opacity-0 group-hover/sort:opacity-100\"\n        )}\n      />\n    )\n    return (\n      <button\n        type=\"button\"\n        ref={(el) => {\n          if (el) headerButtonRefs.current.set(column.id, el)\n          else headerButtonRefs.current.delete(column.id)\n        }}\n        tabIndex={column.id === headerTabId ? 0 : -1}\n        aria-label={sortButtonLabel(label, direction)}\n        data-slot=\"data-grid-sort-button\"\n        onFocus={() => setHeaderStop(column.id)}\n        onClick={() => {\n          const next = nextSort(activeSort, column.id)\n          onSortChange?.(next)\n          setSortMessage(sortAnnouncement(next ? label : null, next))\n        }}\n        onKeyDown={(event) => {\n          const index = sortableColumns.findIndex((c) => c.id === column.id)\n          let target: number\n          if (event.key === \"ArrowLeft\") target = index - 1\n          else if (event.key === \"ArrowRight\") target = index + 1\n          else if (event.key === \"Home\") target = 0\n          else if (event.key === \"End\") target = sortableColumns.length - 1\n          else return\n          event.preventDefault()\n          const next = sortableColumns[target]\n          if (next && next.id !== column.id) focusHeaderButton(next)\n        }}\n        className={cn(\n          \"group/sort focus-ring-inset flex min-w-0 flex-1 cursor-pointer items-center gap-1 self-stretch\",\n          alignRight && \"justify-end text-right\",\n          extraClass\n        )}\n      >\n        {alignRight ? glyph : null}\n        <span className=\"min-w-0 truncate\" title={plainText(column.header)}>\n          {column.header}\n        </span>\n        {alignRight ? null : glyph}\n      </button>\n    )\n  }\n\n  // --- Editor overlay ---\n\n  let editorOverlay: React.ReactNode = null\n  if (state.editing && state.active) {\n    const activeCell = state.active\n    const column = allColumns.find((c) => c.id === activeCell.columnId)\n    const edit = column?.edit\n    const isDraft = activeCell.rowKey === DRAFT_KEY\n    const row = isDraft ? null : rowByKey.get(activeCell.rowKey)\n    if (column && edit && (isDraft || row !== undefined)) {\n      let config: DataGridEditorConfig\n      if (edit.kind === \"select\")\n        config = {\n          kind: \"select\",\n          options: edit.options(isDraft ? null : row!),\n          searchPlaceholder: edit.searchPlaceholder,\n        }\n      else if (edit.kind === \"number\")\n        config = { kind: \"number\", min: edit.min, step: edit.step }\n      else if (edit.kind === \"date\")\n        config = { kind: \"date\", clearable: !edit.required }\n      else config = { kind: edit.kind }\n      const key = cellKey(activeCell.rowKey, column.id)\n      const initial = isDraft\n        ? (state.draft?.[column.id] ?? \"\")\n        : (edit.value(row!) ?? \"\")\n      editorOverlay = (\n        <DataGridCellEditor\n          key={key}\n          config={config}\n          initial={initial}\n          seed={state.seed}\n          placeholder={edit.placeholder}\n          header={plainText(column.header) ?? column.id}\n          align={column.align}\n          // The phone list renders without the grid: its sheet anchors to the list row.\n          getAnchor={() => cellRefs.current.get(key) ?? listRowRefs.current.get(activeCell.rowKey) ?? null}\n          commit={(next) => commitCell(activeCell, column, next)}\n          onClose={(committed, nav) => handleEditorClose(activeCell, committed, nav)}\n        />\n      )\n    }\n  }\n\n  // --- Phone list (md:hidden): no spreadsheets on a phone. Rows follow\n  // Underlay's list group: an optional leading mark, a 16pt title from the\n  // pinned cell over one 14pt secondary line, and a trailing fact centred on\n  // the right. Long-press lifts the row and opens a context menu with one\n  // \"Edit {header}\" item per editable column.\n\n  /**\n   * Worth a Mail preview slot? Skips the pages' empty placeholders: a span\n   * marked `data-placeholder` (\"None\", \"Not set\"), or a bare dash some pages\n   * still render.\n   */\n  const hasListContent = (node: React.ReactNode): boolean => {\n    if (node === null || node === undefined || node === false || node === \"\") return false\n    if (node === \"\\u2014\") return false\n    if (React.isValidElement(node) && node.props && typeof node.props === \"object\") {\n      if (\"data-placeholder\" in node.props) return false\n      if (\"children\" in node.props && node.props.children === \"\\u2014\") return false\n    }\n    return true\n  }\n\n  /** Trailing value = first contentful scrolling column; secondary line = the next two. */\n  const listParts = (row: T) => {\n    const parts: { column: DataGridColumn<T>; node: React.ReactNode }[] = []\n    for (const column of columns) {\n      if (parts.length === 3) break\n      const node = column.cell(row)\n      if (hasListContent(node)) parts.push({ column, node })\n    }\n    return { trailing: parts[0], secondary: parts.slice(1) }\n  }\n\n  // Shared by the list row and its lifted copy under the context menu. Links\n  // and buttons inside cells lose pointer events: the whole row is one tap\n  // target; openListRow still clicks the pinned link programmatically.\n  const listRowContent = (row: T) => {\n    const custom = listItem?.(row)\n    const derived = listParts(row)\n    const trailing = custom && \"trailing\" in custom ? custom.trailing : derived.trailing?.node\n    return (\n      <div className=\"flex min-w-0 flex-1 items-center gap-3 [&_a]:pointer-events-none [&_button]:pointer-events-none\">\n        {custom?.leading ? (\n          <span data-slot=\"data-grid-list-leading\" className=\"flex shrink-0 items-center\">\n            {custom.leading}\n          </span>\n        ) : null}\n        <div className=\"min-w-0 flex-1\">\n          {/* The ObjectTile repeats the same generic glyph on every row, so\n              at list scale it is noise: hidden. */}\n          <span\n            data-slot=\"data-grid-list-title\"\n            className=\"flex min-w-0 items-center gap-2 overflow-hidden text-base whitespace-nowrap text-foreground [&_[data-slot=object-tile]]:hidden\"\n          >\n            {custom?.title ?? pinned.cell(row)}\n          </span>\n          {custom && \"secondary\" in custom ? (\n            custom.secondary ? (\n              <div\n                data-slot=\"data-grid-list-subtitle\"\n                className=\"mt-0.5 flex min-w-0 items-center overflow-hidden text-sm whitespace-nowrap text-subtle-foreground\"\n              >\n                {custom.secondary}\n              </div>\n            ) : null\n          ) : derived.secondary.length > 0 ? (\n            // Hidden placeholder parts keep their DOM slot, so the \"·\" divider\n            // only precedes a part that follows a visible one.\n            <div\n              data-slot=\"data-grid-list-subtitle\"\n              className=\"mt-0.5 flex min-w-0 items-center overflow-hidden text-sm whitespace-nowrap text-subtle-foreground [&>[data-empty]]:hidden [&>[data-list-part]:not([data-empty])~[data-list-part]]:before:mx-1 [&>[data-list-part]:not([data-empty])~[data-list-part]]:before:shrink-0 [&>[data-list-part]:not([data-empty])~[data-list-part]]:before:content-['·']\"\n            >\n              {derived.secondary.map((part) => (\n                <span\n                  key={part.column.id}\n                  data-list-part=\"\"\n                  className=\"flex min-w-0 items-center overflow-hidden\"\n                >\n                  {part.node}\n                </span>\n              ))}\n            </div>\n          ) : null}\n        </div>\n        {trailing ? (\n          <span\n            data-slot=\"data-grid-list-trailing\"\n            // A derived part can still turn out empty after render (see listRef).\n            {...(custom && \"trailing\" in custom ? {} : { \"data-list-part\": \"\" })}\n            className=\"flex max-w-[45%] shrink-0 items-center gap-1 overflow-hidden text-sm whitespace-nowrap text-muted-foreground data-[empty]:hidden [&_svg]:size-4 [&_svg]:shrink-0\"\n          >\n            {trailing}\n          </span>\n        ) : null}\n      </div>\n    )\n  }\n\n  const openListMenu = (key: string) => {\n    if (!allColumns.some((column) => editableOf(key, column))) return\n    const el = listRowRefs.current.get(key)\n    if (!el) return\n    const rect = el.getBoundingClientRect()\n    navigator.vibrate?.(10)\n    setListMenuClosing(false)\n    setListMenu({\n      rowKey: key,\n      rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },\n    })\n  }\n\n  // Tap: the pinned cell's link if it has one (rowHref renders a stretched\n  // anchor; Touchpoints links the client inside the cell), then the desktop\n  // row-click handler, then the first editable cell's editor.\n  const openListRow = (row: T, key: string) => {\n    const anchor = listRowRefs.current\n      .get(key)\n      ?.querySelector<HTMLAnchorElement>(\"a[href]\")\n    if (anchor) {\n      anchor.click()\n      return\n    }\n    if (onRowClick) {\n      onRowClick(row)\n      return\n    }\n    const first = allColumns.find((column) => editableOf(key, column))\n    if (first)\n      dispatch({ type: \"openEditor\", cell: { rowKey: key, columnId: first.id }, seed: null })\n  }\n\n  // Long-press (480ms, cancelled by >8px movement) or a contextmenu event\n  // opens the menu; the click that trails a long-press is swallowed.\n  const listPressHandlers = (key: string) => ({\n    onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => {\n      if (event.pointerType === \"mouse\" && event.button !== 0) return\n      suppressListClickRef.current = false\n      const timer = window.setTimeout(() => {\n        listPressRef.current = null\n        suppressListClickRef.current = true\n        openListMenu(key)\n      }, 480)\n      listPressRef.current = { x: event.clientX, y: event.clientY, timer }\n    },\n    onPointerMove: (event: React.PointerEvent<HTMLDivElement>) => {\n      const press = listPressRef.current\n      if (press && Math.hypot(event.clientX - press.x, event.clientY - press.y) > 8) {\n        window.clearTimeout(press.timer)\n        listPressRef.current = null\n      }\n    },\n    onPointerUp: () => {\n      if (listPressRef.current) {\n        window.clearTimeout(listPressRef.current.timer)\n        listPressRef.current = null\n      }\n    },\n    onPointerCancel: () => {\n      if (listPressRef.current) {\n        window.clearTimeout(listPressRef.current.timer)\n        listPressRef.current = null\n      }\n    },\n    onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => {\n      event.preventDefault()\n      suppressListClickRef.current = true\n      openListMenu(key)\n    },\n    onClickCapture: (event: React.MouseEvent<HTMLDivElement>) => {\n      if (!suppressListClickRef.current) return\n      suppressListClickRef.current = false\n      event.preventDefault()\n      event.stopPropagation()\n    },\n  })\n\n  let listMenuOverlay: React.ReactNode = null\n  if (listMenu) {\n    const menuRow = rowByKey.get(listMenu.rowKey)\n    const editableColumns = allColumns.filter((column) =>\n      editableOf(listMenu.rowKey, column)\n    )\n    if (menuRow && editableColumns.length > 0) {\n      // Menu grammar: the popover surface, 250px wide, 8px\n      // padding, 48px rows, icon at x=36 / text at x=61 — below the lifted\n      // row when it fits, above it otherwise.\n      const menuHeight = 16 + editableColumns.length * 48\n      const belowTop = listMenu.rect.top + listMenu.rect.height + 12\n      const menuTop =\n        belowTop + menuHeight <= window.innerHeight - 24\n          ? belowTop\n          : Math.max(24, listMenu.rect.top - 12 - menuHeight)\n      listMenuOverlay = createPortal(\n        <div data-slot=\"data-grid-context\" className=\"fixed inset-0 z-50 md:hidden\">\n          {/* The rest of the screen falls behind the 20% scrim (no blur in product UI). */}\n          <div\n            aria-hidden\n            onClick={closeListMenu}\n            className={cn(\n              \"absolute inset-0 bg-[var(--scrim)] transition-opacity duration-200\",\n              listMenuShown ? \"opacity-100\" : \"opacity-0\"\n            )}\n          />\n          {/* Lifted copy of the pressed row: scale 1.02 on the popover shadow, 12px corners. */}\n          <div\n            aria-hidden\n            style={{\n              top: listMenu.rect.top,\n              left: listMenu.rect.left,\n              width: listMenu.rect.width,\n            }}\n            className={cn(\n              \"absolute flex rounded-xl bg-background px-4 py-3 shadow-popover transition-transform duration-200\",\n              listMenuShown ? \"scale-[1.02]\" : \"scale-100\"\n            )}\n          >\n            {listRowContent(menuRow)}\n          </div>\n          <div\n            ref={listMenuRef}\n            role=\"menu\"\n            data-slot=\"data-grid-context-menu\"\n            style={{ top: menuTop, left: 16 }}\n            onTransitionEnd={(event) => {\n              if (!listMenuClosing) return\n              if (event.target !== event.currentTarget) return\n              unmountListMenu()\n            }}\n            onKeyDown={(event) => {\n              if (event.key === \"Escape\" || event.key === \"Tab\") {\n                event.preventDefault()\n                event.stopPropagation()\n                closeListMenu()\n                return\n              }\n              const items = Array.from(\n                event.currentTarget.querySelectorAll<HTMLElement>('[role=\"menuitem\"]')\n              )\n              const at = items.indexOf(document.activeElement as HTMLElement)\n              let to: number\n              if (event.key === \"ArrowDown\") to = (at + 1) % items.length\n              else if (event.key === \"ArrowUp\") to = (at - 1 + items.length) % items.length\n              else if (event.key === \"Home\") to = 0\n              else if (event.key === \"End\") to = items.length - 1\n              else return\n              event.preventDefault()\n              items[to]?.focus({ preventScroll: true })\n            }}\n            className={cn(\n              \"absolute w-[250px] origin-top-left rounded-xl bg-popover p-2 text-popover-foreground shadow-popover transition-[scale,opacity] [transition-duration:280ms,150ms] [transition-timing-function:var(--ease-spring-soft),ease-out]\",\n              listMenuShown ? \"scale-100 opacity-100\" : \"motion-safe:scale-90 opacity-0\"\n            )}\n          >\n            {editableColumns.map((column) => (\n              <button\n                key={column.id}\n                type=\"button\"\n                role=\"menuitem\"\n                data-slot=\"data-grid-context-menu-item\"\n                onClick={() => {\n                  const cell = { rowKey: listMenu.rowKey, columnId: column.id }\n                  closeListMenu()\n                  dispatch({ type: \"openEditor\", cell, seed: null })\n                }}\n                className=\"focus-ring-inset flex h-12 w-full cursor-pointer items-center rounded-lg pl-[18px] text-left text-base active:bg-accent\"\n              >\n                <span className=\"flex w-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-5\">\n                  {column.icon}\n                </span>\n                <span className=\"ml-[15px] truncate pr-3\">\n                  Edit {plainText(column.header) ?? column.id}\n                </span>\n              </button>\n            ))}\n          </div>\n        </div>,\n        document.body\n      )\n    }\n  }\n\n  // --- Manual order: one body row, drawn plain or as a sortable row with its\n  // grip. While lifted, the row leaves a dashed slot of its own height and a\n  // raised copy rides the overlay, with no drop animation; a keyboard lift\n  // never animates.\n\n  const bodyRow = (row: T, key: string, index: number, sortable?: SortableRowState) => {\n    const href = rowHref?.(row)\n\n    return (\n      <div\n        key={key}\n        ref={sortable?.setNodeRef}\n        style={\n          sortable\n            ? {\n                transform: CSS.Translate.toString(sortable.transform),\n                transition: lift?.via === \"keyboard\" ? undefined : sortable.transition,\n              }\n            : undefined\n        }\n        role=\"row\"\n        aria-rowindex={index + 2}\n        aria-selected={selectable ? (selected?.has(key) ?? false) : undefined}\n        data-slot=\"data-grid-row\"\n        className={\n          sortable?.isDragging\n            ? \"group/row flex h-[43px] w-max min-w-full rounded-[4px] border border-dashed border-border bg-secondary/60 max-md:h-11 [&>*]:invisible\"\n            : \"group/row flex h-[43px] w-max min-w-full border-b border-border hover:bg-row-hover aria-selected:bg-row-selected max-md:h-11\"\n        }\n      >\n        <div\n          {...gridCellProps(\n            { rowKey: key, columnId: pinned.id },\n            pinned,\n            \"pinned\",\n            \"group-hover/row:bg-row-hover group-aria-selected/row:bg-row-selected\"\n          )}\n        >\n          {/* The grip stays out of the tab order, as the grid keeps one tab\n              stop; keyboard users move rows with Alt+ArrowUp/Down instead. It\n              shows on row hover or focus, and always on touch. */}\n          {sortable ? (\n            <button\n              type=\"button\"\n              ref={sortable.setActivatorNodeRef}\n              {...sortable.attributes}\n              {...sortable.listeners}\n              tabIndex={-1}\n              aria-label={`Move ${rowLabel(key) ?? \"row\"}`}\n              data-slot=\"data-grid-row-grip\"\n              className=\"focus-ring-inset -mr-1 flex h-5 w-4 shrink-0 cursor-grab touch-manipulation items-center justify-center rounded-[4px] text-subtle-foreground opacity-0 transition-opacity select-none [-webkit-touch-callout:none] group-focus-within/row:opacity-100 group-hover/row:opacity-100 hover:text-foreground focus-visible:opacity-100 pointer-coarse:opacity-100\"\n            >\n              <GripVerticalIcon className=\"size-4\" />\n            </button>\n          ) : null}\n          {selectable ? (\n            <Checkbox\n              className=\"max-md:hidden\"\n              aria-label=\"Select row\"\n              checked={selected?.has(key) ?? false}\n              onCheckedChange={(checked) => toggleRow(key, checked === true)}\n            />\n          ) : null}\n          {/* The record link hugs its content: clicking the cell's empty area\n              activates the cell instead of navigating. */}\n          {href ? (\n            <a\n              data-grid-anchor\n              href={href}\n              tabIndex={-1}\n              className=\"flex max-w-full min-w-0 items-center gap-2 self-stretch overflow-hidden whitespace-nowrap outline-none\"\n            >\n              {pinned.cell(row)}\n            </a>\n          ) : onRowClick ? (\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              onClick={() => onRowClick(row)}\n              className=\"flex max-w-full min-w-0 cursor-pointer items-center gap-2 self-stretch overflow-hidden whitespace-nowrap text-left outline-none\"\n            >\n              {pinned.cell(row)}\n            </button>\n          ) : (\n            <span className=\"flex max-w-full min-w-0 items-center gap-2 overflow-hidden whitespace-nowrap\">\n              {pinned.cell(row)}\n            </span>\n          )}\n        </div>\n        {columns.map((column) => (\n          <div\n            key={column.id}\n            {...gridCellProps({ rowKey: key, columnId: column.id }, column, \"cell\")}\n          >\n            {column.cell(row)}\n          </div>\n        ))}\n      </div>\n    )\n  }\n\n  // The overlay box spans the whole row; the copy shows only the part in\n  // view, at the grid's sideways scroll, with the pinned cell held at its\n  // left edge as in the grid.\n  const liftedRow = lift ? rowByKey.get(lift.key) : undefined\n  const liftedCopy =\n    lift && liftedRow !== undefined ? (\n      <div\n        aria-hidden\n        inert\n        data-slot=\"data-grid-row-lift\"\n        style={{ marginLeft: lift.scrollLeft, width: lift.width }}\n        className={cn(\n          \"pointer-events-none h-[43px] overflow-hidden rounded-[4px] bg-surface-raised shadow-card-lift max-md:h-11\",\n          lift.via === \"pointer\" && \"animate-card-lift motion-reduce:animate-none\"\n        )}\n      >\n        <div\n          className=\"flex h-full w-max min-w-full\"\n          style={{ marginLeft: -lift.scrollLeft }}\n        >\n          <div className={cn(pinnedClass, \"bg-surface-raised\")} style={columnStyle(pinnedWidth)}>\n            <span className=\"-mr-1 flex h-5 w-4 shrink-0 items-center justify-center text-foreground\">\n              <GripVerticalIcon className=\"size-4\" />\n            </span>\n            {selectable ? (\n              <Checkbox className=\"max-md:hidden\" checked={selected?.has(lift.key) ?? false} />\n            ) : null}\n            <span className=\"flex max-w-full min-w-0 items-center gap-2 overflow-hidden whitespace-nowrap\">\n              {pinned.cell(liftedRow)}\n            </span>\n          </div>\n          {columns.map((column) => (\n            <div\n              key={column.id}\n              className={cn(cellClass, column.align === \"right\" && \"justify-end text-right\")}\n              style={columnStyle(column.width ?? DEFAULT_COLUMN_WIDTH)}\n            >\n              {column.cell(liftedRow)}\n            </div>\n          ))}\n        </div>\n      </div>\n    ) : null\n\n  const settleDrag = (event: { activatorEvent: Event }) => {\n    setLift(null)\n    document.body.style.removeProperty(\"cursor\")\n    const type = event.activatorEvent.type\n    if (type === \"mousedown\") swallowNextClick(0)\n    else if (type === \"touchstart\") swallowNextClick(400)\n  }\n\n  // aria-rowindex across the windowed body: header 1, body rows from 2, then\n  // the draft row, the add row and the footer.\n  const draftRowIndex = rowCount + 2\n  const addRowIndex = draftRowIndex + (state.draft ? 1 : 0)\n  const footerRowIndex = addRowIndex + (create ? 1 : 0)\n\n  return (\n    <>\n    {desktop === false ? null : (\n    <div\n      ref={containerRef}\n      role=\"grid\"\n      aria-label={ariaLabel}\n      aria-multiselectable={selectable ? true : undefined}\n      aria-rowcount={footerRowIndex}\n      data-slot=\"data-grid\"\n      className={cn(\"group/grid relative w-full overflow-x-auto max-md:hidden\", className)}\n    >\n      {/* Header */}\n      <div\n        role=\"row\"\n        aria-rowindex={1}\n        data-slot=\"data-grid-header\"\n        className=\"sticky top-0 z-20 flex h-[39px] w-max min-w-full border-b border-border bg-row-hover\"\n      >\n        <div\n          role=\"columnheader\"\n          aria-sort={activeSort?.columnId === pinned.id ? activeSort.direction : undefined}\n          data-slot=\"data-grid-pinned\"\n          className={cn(pinnedClass, headerTextClass)}\n          style={columnStyle(pinnedWidth)}\n        >\n          {reorder ? <span aria-hidden className=\"-mr-1 w-4 shrink-0\" /> : null}\n          {selectable ? (\n            <Checkbox\n              className=\"max-md:hidden\"\n              aria-label=\"Select all rows\"\n              checked={allSelected}\n              indeterminate={someSelected && !allSelected}\n              onCheckedChange={(checked) => toggleAll(checked === true)}\n            />\n          ) : null}\n          {pinned.sortValue ? (\n            sortHeaderButton(\n              pinned,\n              cn(\"-mr-3 pr-3\", !reorder && !selectable && \"-ml-3 pl-3\")\n            )\n          ) : (\n            <span className=\"min-w-0 truncate\" title={plainText(pinned.header)}>\n              {pinned.header}\n            </span>\n          )}\n        </div>\n        {columns.map((column) => (\n          <div\n            key={column.id}\n            role=\"columnheader\"\n            aria-sort={activeSort?.columnId === column.id ? activeSort.direction : undefined}\n            data-slot=\"data-grid-cell\"\n            className={cn(\n              cellClass,\n              headerTextClass,\n              column.align === \"right\" && \"justify-end text-right\"\n            )}\n            style={columnStyle(column.width ?? DEFAULT_COLUMN_WIDTH)}\n          >\n            {column.sortValue ? (\n              sortHeaderButton(column, \"-mx-3 px-3\")\n            ) : (\n              <span className=\"min-w-0 truncate\" title={plainText(column.header)}>\n                {column.header}\n              </span>\n            )}\n          </div>\n        ))}\n      </div>\n\n      {/* Body: the rows in view, spacers for the rest */}\n      <div ref={bodyRef} aria-hidden role=\"presentation\" data-slot=\"data-grid-body-start\" />\n      {reorder ? (\n        <DndContext\n          id={dndId}\n          sensors={sensors}\n          collisionDetection={closestCenter}\n          modifiers={[restrictToVerticalAxis]}\n          onDragStart={({ active, activatorEvent }) => {\n            const container = containerRef.current\n            setLift({\n              key: String(active.id),\n              via: activatorEvent.type === \"keydown\" ? \"keyboard\" : \"pointer\",\n              scrollLeft: container?.scrollLeft ?? 0,\n              width: container?.clientWidth ?? 0,\n            })\n            if (activatorEvent.type === \"mousedown\")\n              document.body.style.cursor = \"grabbing\"\n          }}\n          onDragCancel={settleDrag}\n          onDragEnd={(event) => {\n            settleDrag(event)\n            const { active, over } = event\n            if (!over || active.id === over.id) return\n            const from = rowKeys.indexOf(String(active.id))\n            const to = rowKeys.indexOf(String(over.id))\n            if (from < 0 || to < 0) return\n            commitOrder(arrayMove(rowKeys, from, to), String(active.id))\n          }}\n          accessibility={{\n            // dnd-kit's instructions and live region are not rows, and a grid\n            // may own nothing else: they render in the body, like the overlay.\n            container: typeof document === \"undefined\" ? undefined : document.body,\n            announcements: {\n              onDragStart: ({ active }) =>\n                `Picked up ${rowLabel(String(active.id)) ?? \"row\"}. Use the arrow keys to move, space to drop, Escape to cancel.`,\n              onDragOver: ({ over }) =>\n                over\n                  ? `Position ${rowKeys.indexOf(String(over.id)) + 1} of ${rowKeys.length}`\n                  : \"Outside the list\",\n              onDragEnd: () => \"Move completed\",\n              onDragCancel: () => \"Move cancelled\",\n            },\n          }}\n        >\n          <SortableContext items={rowKeys} strategy={verticalListSortingStrategy}>\n            {windowedRows((row, key, index) => (\n              <SortableRow key={key} id={key}>\n                {(sortable) => bodyRow(row, key, index, sortable)}\n              </SortableRow>\n            ))}\n          </SortableContext>\n          {typeof window !== \"undefined\" &&\n            createPortal(\n              <DragOverlay dropAnimation={null} zIndex={80}>\n                {liftedCopy}\n              </DragOverlay>,\n              document.body\n            )}\n        </DndContext>\n      ) : (\n        windowedRows((row, key, index) => bodyRow(row, key, index))\n      )}\n\n      {/* Draft row */}\n      {state.draft ? (\n        <div\n          role=\"row\"\n          aria-rowindex={draftRowIndex}\n          data-slot=\"data-grid-row\"\n          data-draft=\"\"\n          className=\"group/row flex h-[43px] w-max min-w-full border-b border-border hover:bg-row-hover max-md:h-11\"\n        >\n          <div\n            {...gridCellProps(\n              { rowKey: DRAFT_KEY, columnId: pinned.id },\n              pinned,\n              \"pinned\",\n              \"group-hover/row:bg-row-hover\"\n            )}\n          >\n            {reorder ? <span aria-hidden className=\"-mr-1 w-4 shrink-0\" /> : null}\n            {selectable ? (\n              <span aria-hidden className=\"size-4 shrink-0 max-md:hidden\" />\n            ) : null}\n            <span className=\"flex max-w-full min-w-0 flex-1 items-center gap-2 overflow-hidden whitespace-nowrap\">\n              {draftCellContent(pinned)}\n            </span>\n            <span className=\"flex shrink-0 items-center\">\n              {state.creating ? (\n                <Loader size={14} />\n              ) : (\n                <button\n                  type=\"button\"\n                  aria-label=\"Discard new row\"\n                  onClick={discardDraft}\n                  className=\"focus-ring-inset flex size-5 cursor-pointer items-center justify-center rounded-[4px] text-muted-foreground hover:bg-accent hover:text-foreground\"\n                >\n                  <XIcon className=\"size-4\" />\n                </button>\n              )}\n            </span>\n            {state.createError ? (\n              <div className=\"absolute top-full left-3 z-30 mt-0.5 rounded-md bg-popover px-2 py-1 text-xs whitespace-normal text-destructive shadow-popover\">\n                {state.createError}\n              </div>\n            ) : null}\n          </div>\n          {columns.map((column) => (\n            <div\n              key={column.id}\n              {...gridCellProps({ rowKey: DRAFT_KEY, columnId: column.id }, column, \"cell\")}\n            >\n              {draftCellContent(column)}\n            </div>\n          ))}\n        </div>\n      ) : null}\n\n      {/* Add row */}\n      {create ? (\n        <div\n          role=\"row\"\n          aria-rowindex={addRowIndex}\n          data-slot=\"data-grid-add-row\"\n          className=\"flex h-[43px] w-max min-w-full border-b border-border hover:bg-row-hover max-md:hidden\"\n        >\n          {/* A row may own only cells: the button sits in one that spans the row. */}\n          <div role=\"gridcell\" aria-colspan={allColumns.length} className=\"h-full w-full\">\n            <button\n              type=\"button\"\n              ref={addRowRef}\n              onClick={openDraft}\n              disabled={state.creating}\n              className=\"group/add focus-ring-inset flex h-full w-full cursor-pointer items-center disabled:cursor-default\"\n            >\n              <span className=\"sticky left-0 flex items-center gap-2 px-3 text-base text-subtle-foreground group-hover/add:text-foreground\">\n                <PlusIcon className=\"size-4\" />\n                {create.label}\n              </span>\n            </button>\n          </div>\n        </div>\n      ) : null}\n\n      {/* Footer */}\n      <div\n        role=\"row\"\n        aria-rowindex={footerRowIndex}\n        data-slot=\"data-grid-footer\"\n        className=\"flex h-[38px] w-max min-w-full text-xs text-muted-foreground max-md:h-[43px]\"\n      >\n        <div\n          role=\"gridcell\"\n          data-slot=\"data-grid-pinned\"\n          className={cn(pinnedClass, \"h-[38px] text-xs font-normal\")}\n          style={columnStyle(pinnedWidth)}\n        >\n          <span className=\"truncate tabular-nums\" title={plainText(footer)}>\n            {footer ?? `${rows.length} count`}\n          </span>\n        </div>\n        {columns.map((column) => {\n          const aggregate = column.footer?.(rows)\n          return (\n            <div\n              key={column.id}\n              role=\"gridcell\"\n              data-slot=\"data-grid-cell\"\n              className={cn(cellClass, \"h-[38px] text-xs\", column.align === \"right\" && \"justify-end text-right\")}\n              style={columnStyle(column.width ?? DEFAULT_COLUMN_WIDTH)}\n            >\n              {aggregate == null ? null : (\n                <span className=\"truncate tabular-nums\" title={plainText(aggregate)}>\n                  {aggregate}\n                </span>\n              )}\n            </div>\n          )\n        })}\n      </div>\n\n      {editorOverlay}\n    </div>\n    )}\n    {/* Sort changes a person makes, said politely; mount and restore stay silent. */}\n    {sortableColumns.length > 0 ? (\n      <div role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {sortMessage}\n      </div>\n    ) : null}\n\n    {/* Phone list (Underlay list-group): one white group with a hairline\n        ring and 12px corners, hairline rows, a centred 13px count under it. */}\n    {desktop === true ? null : (\n    <div ref={listRef} data-slot=\"data-grid-list\" aria-label={ariaLabel} className=\"px-4 pt-1 md:hidden\">\n      <div role=\"list\" className=\"overflow-hidden rounded-xl bg-background ring-1 ring-border\">\n        {orderedRows.map((row, index) => {\n          const key = rowKeys[index]!\n          const href = rowHref?.(row)\n          return (\n            <div\n              key={key}\n              role=\"listitem\"\n              data-slot=\"data-grid-list-row\"\n              ref={(el) => {\n                if (el) listRowRefs.current.set(key, el)\n                else listRowRefs.current.delete(key)\n              }}\n              onClick={(event) => {\n                if ((event.target as HTMLElement).closest(\"a\")) return\n                openListRow(row, key)\n              }}\n              // The row is the tap target, so it is the keyboard's too: Enter\n              // or Space opens it, and the context-menu key opens its menu\n              // (the browser sends `contextmenu` to the focused row).\n              tabIndex={0}\n              onKeyDown={(event) => {\n                if (event.target !== event.currentTarget) return\n                if (event.key !== \"Enter\" && event.key !== \" \") return\n                event.preventDefault()\n                // A menu opened from the keyboard is followed by no click to swallow.\n                suppressListClickRef.current = false\n                openListRow(row, key)\n              }}\n              {...listPressHandlers(key)}\n              className=\"row-press focus-ring-inset relative flex min-h-[60px] cursor-pointer touch-manipulation items-center border-b border-border px-4 py-3 select-none [-webkit-touch-callout:none] last:border-b-0 has-data-[slot=data-grid-list-leading]:min-h-[72px]\"\n            >\n              {listRowContent(row)}\n              {href ? (\n                // Stretched link: the whole row is the record link (Mail row).\n                <a data-grid-anchor aria-hidden href={href} tabIndex={-1} className=\"absolute inset-0\" />\n              ) : null}\n            </div>\n          )\n        })}\n      </div>\n      <div\n        data-slot=\"data-grid-list-footer\"\n        className=\"pt-4 pb-2 text-center text-xs text-muted-foreground\"\n      >\n        <span className=\"tabular-nums\" title={plainText(footer)}>\n          {footer ?? `${rows.length} count`}\n        </span>\n      </div>\n    </div>\n    )}\n    {/* Without the grid, the phone list's editor (a sheet) renders here. */}\n    {desktop === false ? editorOverlay : null}\n    {listMenuOverlay}\n    </>\n  )\n}\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/khaeli/ui/data-grid-editor.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { createPortal } from \"react-dom\"\nimport { CheckIcon, XIcon } from \"@keyline-icons/react\"\nimport { cn } from \"@/lib/utils\"\n\nimport { Calendar } from \"@/components/ui/date-picker\"\nimport { FancyButton, FancyButtonIcon } from \"@/components/ui/fancy-button\"\nimport { Loader } from \"@/components/ui/loader\"\nimport type { DataGridOption } from \"@/components/ui/data-grid\"\n\n// --- DataGridCellEditor ---\n// A fixed-position box anchored to the active cell's rect,\n// repositioned on scroll (capture) / resize via rAF. On phones (< 768px,\n// decided once when the session opens) the same session renders as a\n// bottom sheet instead: scrim, 76px header [round ✕ ·\n// title · primary check], a 44pt field, option rows in a white list group,\n// native date input. The grid owns\n// commit semantics (unchanged → no-op, required → reject, onSave); this\n// component owns the session UI: input text, pending Loader, error line,\n// select search + highlight, date calendar + typed YYYY-MM-DD.\n\nexport type DataGridEditorConfig =\n  | { kind: \"text\" | \"email\" | \"url\" }\n  | { kind: \"number\"; min?: number; step?: string }\n  | { kind: \"select\"; options: DataGridOption[]; searchPlaceholder?: string }\n  | { kind: \"date\"; clearable: boolean }\n\nexport interface DataGridCellEditorProps {\n  config: DataGridEditorConfig\n  /** committed value of the cell; \"\" = empty */\n  initial: string\n  /** non-null replaces the initial input text (printable-key open; \"\" for Backspace/Delete) */\n  seed: string | null\n  placeholder?: string\n  /** plain-text column header; the phone sheet titles itself \"Edit {header}\" */\n  header: string\n  align?: \"left\" | \"right\"\n  getAnchor: () => HTMLElement | null\n  /** resolves → close; rejects with Error(message) → stay open with the message */\n  commit: (next: string) => Promise<void>\n  onClose: (committed: boolean, nav?: \"next\" | \"prev\" | \"auto\") => void\n}\n\nconst VIEWPORT_INSET = 8\n\ntype AnchorRect = { top: number; left: number; width: number; height: number }\n\nfunction measureAnchor(el: HTMLElement, minWidth: number): AnchorRect {\n  const rect = el.getBoundingClientRect()\n  const width = Math.max(rect.width + 20, minWidth)\n  const left = Math.min(\n    Math.max(rect.left, VIEWPORT_INSET),\n    Math.max(window.innerWidth - width - VIEWPORT_INSET, VIEWPORT_INSET)\n  )\n  return { top: rect.top, left, width, height: rect.height }\n}\n\nfunction parseIsoDate(text: string): Date | null {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n  if (!match) return null\n  const year = Number(match[1])\n  const month = Number(match[2])\n  const day = Number(match[3])\n  const date = new Date(year, month - 1, day)\n  return date.getFullYear() === year &&\n    date.getMonth() === month - 1 &&\n    date.getDate() === day\n    ? date\n    : null\n}\n\nexport function DataGridCellEditor(props: DataGridCellEditorProps) {\n  const { config, initial, seed, placeholder, header, align, getAnchor, commit, onClose } =\n    props\n  const textual =\n    config.kind === \"text\" ||\n    config.kind === \"email\" ||\n    config.kind === \"url\" ||\n    config.kind === \"number\"\n  const minWidth = textual ? 200 : 240\n  // M8: phones swap the anchored box for a bottom sheet. Read once per\n  // session — the editor opens from a user event, never on first paint.\n  const [sheet] = React.useState(\n    () =>\n      typeof window !== \"undefined\" &&\n      window.matchMedia(\"(max-width: 767px)\").matches\n  )\n  // Distance the sheet must sit above the layout viewport's bottom edge so\n  // the on-screen keyboard never covers it.\n  const [keyboardOffset, setKeyboardOffset] = React.useState(0)\n\n  const [anchor, setAnchor] = React.useState<AnchorRect | null>(null)\n  const [value, setValue] = React.useState(() =>\n    config.kind === \"select\" ? (seed ?? \"\") : (seed ?? initial)\n  )\n  const [pending, setPending] = React.useState(false)\n  const [error, setError] = React.useState<string | null>(null)\n  const [highlight, setHighlight] = React.useState(() => {\n    if (config.kind !== \"select\") return 0\n    const search = (seed ?? \"\").trim().toLowerCase()\n    const visible = config.options.filter((o) =>\n      o.label.toLowerCase().includes(search)\n    )\n    const index = initial === \"\" ? -1 : visible.findIndex((o) => o.value === initial)\n    return Math.max(0, index)\n  })\n  const [month, setMonth] = React.useState<Date>(\n    () => parseIsoDate((seed ?? initial).trim()) ?? new Date()\n  )\n\n  const boxRef = React.useRef<HTMLDivElement | null>(null)\n  const inputRef = React.useRef<HTMLInputElement | null>(null)\n  const listboxId = React.useId()\n  const doneRef = React.useRef(false)\n  const pendingRef = React.useRef(false)\n  const focusedRef = React.useRef(false)\n  const valueRef = React.useRef(value)\n  valueRef.current = value\n\n  const search = config.kind === \"select\" ? value.trim().toLowerCase() : \"\"\n  const filtered =\n    config.kind === \"select\"\n      ? config.options.filter((o) => o.label.toLowerCase().includes(search))\n      : []\n  const highlighted = filtered.length\n    ? Math.min(highlight, filtered.length - 1)\n    : -1\n\n  // Phone sheet lifecycle: the sheet stays mounted while it\n  // slides out. data-starting-style is dropped on the first frame so the\n  // 380ms drawer transition runs; finish() flips to data-ending-style and\n  // onClose fires once the 250ms exit transition ends (320ms fallback).\n  const [sheetPhase, setSheetPhase] = React.useState<\n    \"starting\" | \"open\" | \"ending\"\n  >(\"starting\")\n  const closeArgsRef = React.useRef<\n    [boolean, (\"next\" | \"prev\" | \"auto\")?]\n  >([false, undefined])\n  const closedRef = React.useRef(false)\n  const completeClose = () => {\n    if (closedRef.current) return\n    closedRef.current = true\n    onClose(...closeArgsRef.current)\n  }\n  const completeCloseRef = React.useRef(completeClose)\n  completeCloseRef.current = completeClose\n  React.useEffect(() => {\n    if (!sheet) return\n    const raf = requestAnimationFrame(() =>\n      setSheetPhase((p) => (p === \"starting\" ? \"open\" : p))\n    )\n    return () => cancelAnimationFrame(raf)\n  }, [sheet])\n  React.useEffect(() => {\n    if (!sheet || sheetPhase !== \"ending\") return\n    const timer = window.setTimeout(() => completeCloseRef.current(), 320)\n    return () => window.clearTimeout(timer)\n  }, [sheet, sheetPhase])\n\n  const finish = (committed: boolean, nav?: \"next\" | \"prev\" | \"auto\") => {\n    if (doneRef.current) return\n    doneRef.current = true\n    if (sheet) {\n      closeArgsRef.current = [committed, nav]\n      setSheetPhase(\"ending\")\n      return\n    }\n    onClose(committed, nav)\n  }\n\n  const tryCommit = async (next: string, nav?: \"next\" | \"prev\" | \"auto\") => {\n    if (pendingRef.current || doneRef.current) return\n    pendingRef.current = true\n    setPending(true)\n    setError(null)\n    try {\n      await commit(next)\n      pendingRef.current = false\n      finish(true, nav)\n    } catch (err) {\n      pendingRef.current = false\n      setPending(false)\n      setError(err instanceof Error && err.message ? err.message : \"Could not save.\")\n    }\n  }\n  const tryCommitRef = React.useRef(tryCommit)\n  tryCommitRef.current = tryCommit\n\n  // Anchor to the cell; reposition on scroll/resize; commit+close if the cell unmounts.\n  React.useLayoutEffect(() => {\n    const el = getAnchor()\n    if (!el) {\n      finish(false)\n      return\n    }\n    setAnchor(measureAnchor(el, minWidth))\n    let raf = 0\n    const update = () => {\n      raf = 0\n      const anchorEl = getAnchor()\n      if (!anchorEl || !anchorEl.isConnected) {\n        if (textual && !doneRef.current && !pendingRef.current)\n          void commit(valueRef.current).catch(() => undefined)\n        finish(false)\n        return\n      }\n      setAnchor(measureAnchor(anchorEl, minWidth))\n    }\n    const schedule = () => {\n      if (!raf) raf = requestAnimationFrame(update)\n    }\n    window.addEventListener(\"scroll\", schedule, true)\n    window.addEventListener(\"resize\", schedule)\n    return () => {\n      if (raf) cancelAnimationFrame(raf)\n      window.removeEventListener(\"scroll\", schedule, true)\n      window.removeEventListener(\"resize\", schedule)\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [])\n\n  // Click outside: commit for text kinds, close for select/date.\n  React.useEffect(() => {\n    const onPointerDown = (event: PointerEvent) => {\n      const box = boxRef.current\n      if (box && event.target instanceof Node && box.contains(event.target)) return\n      if (textual) void tryCommitRef.current(valueRef.current)\n      else finish(false)\n    }\n    document.addEventListener(\"pointerdown\", onPointerDown, true)\n    return () => document.removeEventListener(\"pointerdown\", onPointerDown, true)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [])\n\n  // The keyboard shrinks/offsets the visual viewport while fixed positioning\n  // keeps tracking the layout viewport; lift the sheet by the difference.\n  React.useEffect(() => {\n    if (!sheet) return\n    const vv = window.visualViewport\n    if (!vv) return\n    const update = () =>\n      setKeyboardOffset(\n        Math.max(0, window.innerHeight - (vv.height + vv.offsetTop))\n      )\n    update()\n    vv.addEventListener(\"resize\", update)\n    vv.addEventListener(\"scroll\", update)\n    return () => {\n      vv.removeEventListener(\"resize\", update)\n      vv.removeEventListener(\"scroll\", update)\n    }\n  }, [sheet])\n\n  React.useLayoutEffect(() => {\n    if (!anchor || focusedRef.current) return\n    focusedRef.current = true\n    // Sheet select/date: focusing would pop the keyboard / native picker\n    // over the option rows, so only text-like fields autofocus there.\n    if (sheet && !textual) return\n    const input = inputRef.current\n    if (!input) return\n    input.focus()\n    if (config.kind !== \"number\") {\n      const end = input.value.length\n      try {\n        input.setSelectionRange(end, end)\n      } catch {\n        // number-like inputs reject selection ranges\n      }\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [anchor])\n\n  const commitDateInput = (nav?: \"next\" | \"prev\" | \"auto\") => {\n    const text = value.trim()\n    if (text === \"\") {\n      void tryCommit(\"\", nav)\n      return\n    }\n    if (!parseIsoDate(text)) {\n      setError(\"Use YYYY-MM-DD.\")\n      return\n    }\n    void tryCommit(text, nav)\n  }\n\n  const inputType =\n    config.kind === \"email\"\n      ? \"email\"\n      : config.kind === \"url\"\n        ? \"url\"\n        : config.kind === \"number\"\n          ? \"number\"\n          : \"text\"\n  // Addresses are typed exactly: no capitalisation, correction or spellcheck.\n  const literal = config.kind === \"email\" || config.kind === \"url\"\n\n  const saveSheet = () => {\n    if (config.kind === \"select\") {\n      // No staged selection on the sheet — rows commit on tap; Save just\n      // confirms the current value (a no-op commit) and closes.\n      void tryCommit(initial)\n      return\n    }\n    void tryCommit(config.kind === \"date\" ? value.trim() : value)\n  }\n\n  const onInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {\n    if (event.key === \"Escape\") {\n      event.preventDefault()\n      event.stopPropagation()\n      finish(false)\n      return\n    }\n    if (event.key === \"Tab\") {\n      event.preventDefault()\n      event.stopPropagation()\n      const nav = event.shiftKey ? \"prev\" : \"next\"\n      if (config.kind === \"select\") {\n        const option = highlighted >= 0 ? filtered[highlighted] : undefined\n        void tryCommit(option ? option.value : initial, nav)\n      } else if (config.kind === \"date\") {\n        commitDateInput(nav)\n      } else {\n        void tryCommit(value, nav)\n      }\n      return\n    }\n    if (event.key === \"Enter\") {\n      event.preventDefault()\n      event.stopPropagation()\n      if (config.kind === \"select\") {\n        const option = highlighted >= 0 ? filtered[highlighted] : undefined\n        if (option) void tryCommit(option.value, \"auto\")\n        return\n      }\n      if (config.kind === \"date\") {\n        commitDateInput(\"auto\")\n        return\n      }\n      void tryCommit(value, \"auto\")\n      return\n    }\n    if (config.kind === \"select\") {\n      if (event.key === \"ArrowDown\") {\n        event.preventDefault()\n        setHighlight((h) => Math.min(h + 1, Math.max(filtered.length - 1, 0)))\n      } else if (event.key === \"ArrowUp\") {\n        event.preventDefault()\n        setHighlight((h) => Math.max(h - 1, 0))\n      }\n    }\n  }\n\n  if (!anchor) return null\n\n  // --- Phone bottom sheet (M8) ---\n  if (sheet) {\n    const title = `Edit ${header}`\n    const sheetState = {\n      \"data-starting-style\": sheetPhase === \"starting\" ? \"\" : undefined,\n      \"data-ending-style\": sheetPhase === \"ending\" ? \"\" : undefined,\n    }\n    // Phone field: 44pt, white with the control\n    // ring, 10px corners; focus = the shared keyboard focus ring.\n    const sheetInputClass =\n      \"focus-ring h-11 w-full min-w-0 rounded-[10px] bg-background px-4 text-base ring-1 ring-input placeholder:text-subtle-foreground\"\n    return createPortal(\n      <div ref={boxRef} className=\"fixed inset-0 z-50 md:hidden\">\n        <div\n          aria-hidden\n          data-slot=\"sheet-overlay\"\n          {...sheetState}\n          className=\"absolute inset-0 bg-[var(--scrim)]\"\n          onPointerDown={() => finish(false)}\n        />\n        <div\n          role=\"dialog\"\n          aria-modal=\"true\"\n          aria-label={title}\n          data-slot=\"data-grid-editor-sheet\"\n          {...sheetState}\n          onTransitionEnd={(event) => {\n            if (sheetPhase !== \"ending\") return\n            if (event.target !== event.currentTarget) return\n            completeClose()\n          }}\n          className=\"absolute inset-x-0 flex flex-col rounded-t-tray bg-background pb-[max(env(safe-area-inset-bottom),16px)] shadow-popover\"\n          style={{\n            bottom: keyboardOffset,\n            maxHeight: `min(60svh, calc(100svh - ${keyboardOffset}px - env(safe-area-inset-top) - 10px))`,\n          }}\n        >\n          <div className=\"grid h-[76px] shrink-0 grid-cols-[1fr_auto_1fr] items-center px-4\">\n            <button\n              type=\"button\"\n              aria-label=\"Cancel\"\n              onClick={() => finish(false)}\n              className=\"focus-ring flex size-10 cursor-pointer items-center justify-center justify-self-start rounded-full bg-secondary active:bg-accent\"\n            >\n              <XIcon className=\"size-5\" />\n            </button>\n            <span className=\"min-w-0 truncate px-1 text-center text-lg\">\n              {title}\n            </span>\n            <FancyButton\n              variant=\"primary\"\n              iconOnly\n              aria-label=\"Save\"\n              onClick={saveSheet}\n              pending={pending}\n              className=\"size-11 justify-self-end rounded-full\"\n            >\n              <FancyButtonIcon as={CheckIcon} className=\"size-6\" />\n            </FancyButton>\n          </div>\n          {error ? (\n            <div className=\"shrink-0 px-8 pb-2 text-sm text-destructive\">\n              {error}\n            </div>\n          ) : null}\n          {textual ? (\n            <div className=\"shrink-0 px-4 pb-2\">\n              <input\n                ref={inputRef}\n                type={inputType}\n                aria-label={header}\n                enterKeyHint=\"done\"\n                autoCapitalize={literal ? \"none\" : undefined}\n                autoCorrect={literal ? \"off\" : undefined}\n                spellCheck={literal ? false : undefined}\n                min={config.kind === \"number\" ? config.min : undefined}\n                step={config.kind === \"number\" ? config.step : undefined}\n                value={value}\n                readOnly={pending}\n                placeholder={placeholder}\n                onChange={(event) => {\n                  setValue(event.target.value)\n                  setError(null)\n                }}\n                onKeyDown={onInputKeyDown}\n                className={cn(sheetInputClass, align === \"right\" && \"text-right\")}\n              />\n            </div>\n          ) : null}\n          {config.kind === \"select\" ? (\n            <>\n              {config.searchPlaceholder ? (\n                <div className=\"shrink-0 px-4 pb-2\">\n                  <input\n                    ref={inputRef}\n                    type=\"text\"\n                    enterKeyHint=\"done\"\n                    value={value}\n                    readOnly={pending}\n                    placeholder={config.searchPlaceholder}\n                    onChange={(event) => {\n                      setValue(event.target.value)\n                      setError(null)\n                      setHighlight(0)\n                    }}\n                    onKeyDown={onInputKeyDown}\n                    className={sheetInputClass}\n                  />\n                </div>\n              ) : null}\n              {/* Underlay list group: 52px rows, hairlines between them,\n                * current value checked in the link colour. */}\n              <div\n                role=\"listbox\"\n                className=\"mx-4 mb-1 min-h-0 flex-1 overflow-y-auto overscroll-contain rounded-xl bg-background ring-1 ring-border\"\n              >\n                {filtered.length === 0 ? (\n                  <div className=\"flex h-[52px] items-center px-4 text-base text-subtle-foreground\">\n                    No matches\n                  </div>\n                ) : (\n                  filtered.map((option, index) => (\n                    <button\n                      key={option.value}\n                      type=\"button\"\n                      role=\"option\"\n                      aria-selected={initial !== \"\" && option.value === initial}\n                      disabled={pending}\n                      onClick={() => void tryCommit(option.value, \"auto\")}\n                      className={cn(\n                        \"row-press focus-ring-inset relative flex h-[52px] w-full cursor-pointer items-center gap-2 px-4 text-left text-base\",\n                        index > 0 && \"border-t border-border\"\n                      )}\n                    >\n                      <span className=\"flex min-w-0 flex-1 items-center gap-2 overflow-hidden whitespace-nowrap\">\n                        {option.render ?? option.label}\n                      </span>\n                      {initial !== \"\" && option.value === initial ? (\n                        <CheckIcon className=\"size-5 shrink-0 text-link\" />\n                      ) : null}\n                    </button>\n                  ))\n                )}\n              </div>\n            </>\n          ) : null}\n          {config.kind === \"date\" ? (\n            <div className=\"flex shrink-0 flex-col gap-2 px-4 pb-2\">\n              <input\n                ref={inputRef}\n                type=\"date\"\n                aria-label={header}\n                value={value.trim()}\n                readOnly={pending}\n                onChange={(event) => {\n                  setValue(event.target.value)\n                  setError(null)\n                }}\n                onKeyDown={(event) => {\n                  if (event.key === \"Escape\") {\n                    event.preventDefault()\n                    event.stopPropagation()\n                    finish(false)\n                  } else if (event.key === \"Enter\") {\n                    event.preventDefault()\n                    void tryCommit(value.trim())\n                  }\n                }}\n                className={sheetInputClass}\n              />\n              {config.clearable ? (\n                <button\n                  type=\"button\"\n                  disabled={pending}\n                  onClick={() => void tryCommit(\"\")}\n                  className=\"row-press focus-ring flex h-11 w-full cursor-pointer items-center rounded-xl bg-background px-4 text-left text-base text-destructive ring-1 ring-border\"\n                >\n                  Clear\n                </button>\n              ) : null}\n            </div>\n          ) : null}\n        </div>\n      </div>,\n      document.body\n    )\n  }\n\n  const inputHeight = Math.max(anchor.height - 2, 20)\n\n  return createPortal(\n    <div\n      ref={boxRef}\n      data-slot=\"data-grid-editor\"\n      className=\"fixed z-50 rounded-[4px] border border-primary bg-popover shadow-popover\"\n      style={{\n        top: anchor.top,\n        left: anchor.left,\n        width: anchor.width,\n        minHeight: anchor.height,\n      }}\n    >\n      <div className=\"flex items-center\" style={{ height: inputHeight }}>\n        <input\n          ref={inputRef}\n          type={inputType}\n          // Named by its column: a placeholder is a hint, and most columns have none.\n          aria-label={header}\n          enterKeyHint=\"done\"\n          autoCapitalize={literal ? \"none\" : undefined}\n          autoCorrect={literal ? \"off\" : undefined}\n          spellCheck={literal ? false : undefined}\n          min={config.kind === \"number\" ? config.min : undefined}\n          step={config.kind === \"number\" ? config.step : undefined}\n          value={value}\n          role={config.kind === \"select\" ? \"combobox\" : undefined}\n          aria-expanded={config.kind === \"select\" ? true : undefined}\n          aria-controls={config.kind === \"select\" ? listboxId : undefined}\n          aria-activedescendant={\n            config.kind === \"select\" && highlighted >= 0\n              ? `${listboxId}-${highlighted}`\n              : undefined\n          }\n          readOnly={pending}\n          placeholder={\n            config.kind === \"select\"\n              ? (config.searchPlaceholder ?? \"Search…\")\n              : config.kind === \"date\"\n                ? (placeholder ?? \"YYYY-MM-DD\")\n                : placeholder\n          }\n          onChange={(event) => {\n            const next = event.target.value\n            setValue(next)\n            setError(null)\n            if (config.kind === \"select\") setHighlight(0)\n            if (config.kind === \"date\") {\n              const parsed = parseIsoDate(next.trim())\n              if (parsed) setMonth(parsed)\n            }\n          }}\n          onKeyDown={onInputKeyDown}\n          className={cn(\n            \"h-full w-full min-w-0 bg-transparent px-[15px] text-base font-medium outline-none placeholder:text-subtle-foreground\",\n            align === \"right\" && \"text-right\"\n          )}\n        />\n        {pending ? (\n          <span className=\"flex shrink-0 items-center pr-[15px]\">\n            <Loader size={14} />\n          </span>\n        ) : null}\n      </div>\n      {error ? (\n        <div className=\"px-[15px] pb-2 text-xs text-destructive\">\n          {error}\n        </div>\n      ) : null}\n      {config.kind === \"select\" ? (\n        <div className=\"border-t border-border\">\n          <div id={listboxId} role=\"listbox\" className=\"max-h-[256px] overflow-y-auto overscroll-contain p-1\">\n            {filtered.length === 0 ? (\n              <div className=\"flex h-8 items-center px-2 text-xs text-subtle-foreground\">\n                No matches\n              </div>\n            ) : (\n              filtered.map((option, index) => (\n                <button\n                  key={option.value}\n                  id={`${listboxId}-${index}`}\n                  type=\"button\"\n                  role=\"option\"\n                  aria-selected={index === highlighted}\n                  tabIndex={-1}\n                  className={cn(\n                    \"flex h-8 w-full cursor-pointer items-center gap-2 rounded-[6px] px-2 text-left text-base font-medium\",\n                    index === highlighted && \"bg-accent\"\n                  )}\n                  onMouseEnter={() => setHighlight(index)}\n                  onClick={() => void tryCommit(option.value, \"auto\")}\n                >\n                  <span className=\"flex min-w-0 flex-1 items-center gap-2 overflow-hidden whitespace-nowrap\">\n                    {option.render ?? option.label}\n                  </span>\n                  {initial !== \"\" && option.value === initial ? (\n                    <CheckIcon className=\"size-4 shrink-0 text-link\" />\n                  ) : null}\n                </button>\n              ))\n            )}\n          </div>\n        </div>\n      ) : null}\n      {config.kind === \"date\" ? (\n        <div className=\"border-t border-border\">\n          <Calendar\n            value={value.trim()}\n            month={month}\n            onMonthChange={setMonth}\n            onValueChange={(iso) => void tryCommit(iso, \"auto\")}\n            className=\"p-2\"\n          />\n          {config.clearable ? (\n            <div className=\"p-1 pt-0\">\n              <button\n                type=\"button\"\n                className=\"flex h-8 w-full cursor-pointer items-center rounded-[6px] px-2 text-left text-base font-medium text-muted-foreground hover:bg-accent\"\n                onClick={() => void tryCommit(\"\", \"auto\")}\n              >\n                Clear\n              </button>\n            </div>\n          ) : null}\n        </div>\n      ) : null}\n    </div>,\n    document.body\n  )\n}\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/khaeli/ui/data-grid-sort.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nexport type DataGridSortDirection = \"ascending\" | \"descending\"\n\nexport interface DataGridSort {\n  columnId: string\n  direction: DataGridSortDirection\n}\n\nexport type DataGridSortValue = string | number | null\n\n/** Header click cycle: none -> ascending -> descending -> none (manual order). Another column starts at ascending. */\nexport function nextSort(\n  current: DataGridSort | null,\n  columnId: string\n): DataGridSort | null {\n  if (current === null || current.columnId !== columnId)\n    return { columnId, direction: \"ascending\" }\n  if (current.direction === \"ascending\")\n    return { columnId, direction: \"descending\" }\n  return null\n}\n\nconst collator = new Intl.Collator(undefined, {\n  numeric: true,\n  sensitivity: \"base\",\n})\n\n/** Empty values sort last whatever the direction. */\nfunction isEmpty(value: DataGridSortValue): boolean {\n  return (\n    value === null ||\n    value === \"\" ||\n    (typeof value === \"number\" && Number.isNaN(value))\n  )\n}\n\n/** Stable sort, returns a new array. null / \"\" / NaN always last in both directions; strings compare with Intl.Collator(undefined, { numeric: true, sensitivity: \"base\" }). */\nexport function sortRows<T>(\n  rows: readonly T[],\n  value: (row: T) => DataGridSortValue,\n  direction: DataGridSortDirection\n): T[] {\n  const sign = direction === \"ascending\" ? 1 : -1\n  const entries = rows.map((row, index) => ({ row, index, value: value(row) }))\n  entries.sort((a, b) => {\n    const aEmpty = isEmpty(a.value)\n    const bEmpty = isEmpty(b.value)\n    if (aEmpty || bEmpty) {\n      if (aEmpty && bEmpty) return a.index - b.index\n      return aEmpty ? 1 : -1\n    }\n    const order =\n      (typeof a.value === \"number\" && typeof b.value === \"number\"\n        ? a.value - b.value\n        : collator.compare(String(a.value), String(b.value))) * sign\n    return order === 0 ? a.index - b.index : order\n  })\n  return entries.map((entry) => entry.row)\n}\n\n/** Header button accessible name: \"Sort by Budget\" when unsorted, \"Sort by Budget, currently ascending\" / \"..., currently descending\". */\nexport function sortButtonLabel(\n  label: string,\n  direction: DataGridSortDirection | null\n): string {\n  return direction === null\n    ? `Sort by ${label}`\n    : `Sort by ${label}, currently ${direction}`\n}\n\n/** Polite announcement after a change: \"Sorted by Budget, ascending\" / \"Sorted by Budget, descending\" / \"Manual order\". */\nexport function sortAnnouncement(\n  label: string | null,\n  sort: DataGridSort | null\n): string {\n  if (sort === null || label === null) return \"Manual order\"\n  return `Sorted by ${label}, ${sort.direction}`\n}\n\n// --- Per-device sort choice ---\n\n/** Same-tab writers notify here; other tabs arrive through the storage event. */\nconst listeners = new Set<() => void>()\n\nfunction subscribe(onChange: () => void): () => void {\n  listeners.add(onChange)\n  window.addEventListener(\"storage\", onChange)\n  return () => {\n    listeners.delete(onChange)\n    window.removeEventListener(\"storage\", onChange)\n  }\n}\n\nfunction readStored(storageKey: string): string | null {\n  try {\n    return window.localStorage.getItem(storageKey)\n  } catch {\n    return null\n  }\n}\n\nfunction parseSort(\n  raw: string | null,\n  columnIds: readonly string[]\n): DataGridSort | null {\n  if (raw === null) return null\n  try {\n    const parsed: unknown = JSON.parse(raw)\n    if (typeof parsed !== \"object\" || parsed === null) return null\n    const { columnId, direction } = parsed as Record<string, unknown>\n    if (typeof columnId !== \"string\" || !columnIds.includes(columnId))\n      return null\n    if (direction !== \"ascending\" && direction !== \"descending\") return null\n    return { columnId, direction }\n  } catch {\n    return null\n  }\n}\n\n/** Per-person (per-device localStorage, like View options column prefs) sort choice for one grid. Server snapshot and first client render read null (no hydration mismatch, use useSyncExternalStore with a storage-event subscription plus same-tab notify); a stored columnId not in `columnIds` reads as null; private mode just doesn't persist. */\nexport function useDataGridSort(\n  storageKey: string,\n  columnIds: readonly string[]\n): [DataGridSort | null, (next: DataGridSort | null) => void] {\n  // The raw string is the snapshot: stable between reads, so no render loop.\n  const raw = React.useSyncExternalStore(\n    subscribe,\n    () => readStored(storageKey),\n    () => null\n  )\n  // Without storage (private mode) the choice still holds for this visit.\n  const [memory, setMemory] = React.useState<{\n    key: string\n    raw: string | null\n  } | null>(null)\n  const effective =\n    memory !== null && memory.key === storageKey ? memory.raw : raw\n  const idsKey = columnIds.join(\"\\u0000\")\n  const sort = React.useMemo(\n    () => parseSort(effective, columnIds),\n    // columnIds is read through its joined key, so a fresh array of the same ids keeps the result.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [effective, idsKey]\n  )\n  const setSort = React.useCallback(\n    (next: DataGridSort | null) => {\n      const value = next === null ? null : JSON.stringify(next)\n      let stored = true\n      try {\n        if (value === null) window.localStorage.removeItem(storageKey)\n        else window.localStorage.setItem(storageKey, value)\n      } catch {\n        // Storage full or blocked: the choice lasts this visit only.\n        stored = false\n      }\n      setMemory(stored ? null : { key: storageKey, raw: value })\n      for (const listener of listeners) listener()\n    },\n    [storageKey]\n  )\n  return [sort, setSort]\n}\n",
      "type": "registry:ui"
    }
  ],
  "css": {
    "@layer components": {
      "[data-slot=\"data-grid-cell\"] a, [data-slot=\"data-grid-pinned\"] a": {
        "display": "inline-flex",
        "align-items": "center",
        "min-height": "24px"
      },
      "@media (pointer: coarse)": {
        ":is([data-slot=\"data-grid-cell\"], [data-slot=\"data-grid-pinned\"]) a": {
          "position": "relative"
        },
        ":is([data-slot=\"data-grid-cell\"], [data-slot=\"data-grid-pinned\"]) a::before": {
          "content": "\"\"",
          "position": "absolute",
          "inset": "min(0px, calc((100% - 44px) / 2)) 0"
        }
      },
      "@media (min-width: 768px) and (max-width: 1023.98px), (pointer: coarse) and (min-width: 1024px)": {
        "[data-slot=\"data-grid\"][data-h-scroll=\"more\"]": {
          "-webkit-mask-image": "linear-gradient( to right, black calc(100% - 40px), transparent )",
          "mask-image": "linear-gradient(to right, black calc(100% - 40px), transparent)"
        }
      },
      "@media (pointer: coarse) and (min-width: 768px)": {
        "[data-slot=\"data-grid-header\"]": {
          "height": "40px !important"
        },
        "[data-slot=\"data-grid-row\"], [data-slot=\"data-grid-add-row\"], [data-slot=\"data-grid-footer\"]": {
          "height": "44px !important"
        },
        ":is([data-slot=\"data-grid-cell\"], [data-slot=\"data-grid-pinned\"])": {
          "height": "100% !important"
        },
        "[data-slot=\"data-grid-add-row\"] > button": {
          "height": "100%"
        },
        "[data-slot=\"data-grid-row\"]:active": {
          "background-color": "var(--secondary)"
        }
      }
    }
  },
  "docs": "Install @khaeli/foundation first: this item's styling lives in its tokens and [data-slot] rules.",
  "type": "registry:ui"
}