{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-sort-list",
  "title": "Data Grid Sort List",
  "author": "gridcn",
  "description": "Toolbar sort add-on for the gridcn data grid: a sort button + popover listing applied sorts as editable, aligned rows (column / direction / remove / drag handle), with add/clear-all and precedence reordering via @dnd-kit/react drag or ArrowUp/ArrowDown on the grip (array order in SortSpec[]). New user-facing strings live under labels.sort (see data-grid/labels.ts DataGridSortLabels). Zero core changes — purely additive.",
  "dependencies": [
    "@dnd-kit/dom@~0.5.0",
    "@dnd-kit/react@~0.5.0",
    "lucide-react@^1.46.0"
  ],
  "registryDependencies": [
    "@gridcn/data-grid",
    "popover",
    "button-group",
    "button",
    "badge",
    "select"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-sort-list/data-grid-sort-list.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\r\n\r\nexport { DataGridSortList, type DataGridSortListProps } from \"./sort-list\";\r\n",
      "type": "registry:component",
      "target": "components/data-grid-sort-list/data-grid-sort-list.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-sort-list/sort-list.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from \"react\";\nimport { AutoScroller } from \"@dnd-kit/dom\";\nimport { DragDropProvider } from \"@dnd-kit/react\";\nimport { useSortable } from \"@dnd-kit/react/sortable\";\nimport { ArrowUpDown, GripVertical, Trash2 } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport { Button } from \"@/components/ui/button\";\nimport { ButtonGroup } from \"@/components/ui/button-group\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@/components/ui/popover\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport {\n  useDataGridActions,\n  useDataGridAllColumns,\n  useDataGridLabels,\n  useDataGridSortState,\n  useDataGridVisibleColumns,\n  type DataGridLabels,\n  type SortSpec,\n} from \"@/registry/default/components/data-grid/data-grid\";\nimport { columnLabelText } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/** Props for {@link DataGridSortList}. */\nexport type DataGridSortListProps = {\n  className?: string;\n  /**\n   * Offer every column (including hidden ones) when adding or changing a sort instead of only the\n   * visible columns; default false. A sort row on a hidden column always shows that column,\n   * whatever this flag says.\n   */\n  allColumns?: boolean;\n};\n\n/** dnd-kit drag payload for a sort row: compiler-checked in place of `Record<string, any>`. */\ntype SortRowDragData = { index: number; columnId: string };\n\n/** Moves the item at `fromIndex` to `toIndex`, returning a new array (no mutation of `list`). */\nfunction moveItem<T>(list: T[], fromIndex: number, toIndex: number): T[] {\n  const next = list.slice();\n  const [moved] = next.splice(fromIndex, 1);\n  if (moved === undefined) return list;\n  next.splice(toIndex, 0, moved);\n  return next;\n}\n\n/**\n * Popover listing active sorts as one aligned grid row per sort (field select, direction select,\n * trash icon-button, drag handle; footer \"Add sort\"/\"Reset sorting\" buttons), built from this\n * repo's own Base UI components. Reordering uses `@dnd-kit/react`'s\n * sortable primitives (handle-initiated pointer drag with a lifted-row feel via `isDragSource`),\n * plus a plain ArrowUp/ArrowDown-on-drag handle fallback that always wins over the library's own keyboard\n * sensor (see {@link SortRow}'s `onKeyDown`). Precedence is array order in `SortSpec[]`; a\n * reorder round-trips through `setSorts` in the new order. Rows are keyed by index (not a stable\n * id, unlike `FilterSpec`) since a column can appear at most once in the list.\n */\nexport function DataGridSortList(props: DataGridSortListProps): ReactNode {\n  const { className, allColumns = false } = props;\n  const actions = useDataGridActions();\n  const sorts = useDataGridSortState();\n  const visibleColumns = useDataGridVisibleColumns();\n  const gridColumns = useDataGridAllColumns();\n  const columns = allColumns ? gridColumns : visibleColumns;\n  const labels = useDataGridLabels();\n  const sortableColumns = columns.filter((c) => c.sortable !== false);\n  const sortedColumnIds = useMemo(() => new Set(sorts.map((s) => s.columnId)), [sorts]);\n\n  const [announcement, setAnnouncement] = useState(\"\");\n  const gripRefs = useRef(new Map<string, HTMLButtonElement | null>());\n  const addButtonRef = useRef<HTMLButtonElement>(null);\n  const pendingFocusColumnIdRef = useRef<string | null>(null);\n\n  // ponytail: lock root scroll during a drag - at drag end the browser re-focuses the drag handle and natively re-centers it in the viewport, jumping the page\n  const rootScrollLockRef = useRef<(() => void) | null>(null);\n  const lockRootScroll = useCallback(() => {\n    if (rootScrollLockRef.current) return;\n    const y = window.scrollY;\n    const onScroll = () => {\n      if (window.scrollY !== y) window.scrollTo(0, y);\n    };\n    document.addEventListener(\"scroll\", onScroll, true);\n    rootScrollLockRef.current = () => {\n      document.removeEventListener(\"scroll\", onScroll, true);\n      rootScrollLockRef.current = null;\n    };\n  }, []);\n  const unlockRootScroll = useCallback(() => rootScrollLockRef.current?.(), []);\n\n  useEffect(() => {\n    const pendingId = pendingFocusColumnIdRef.current;\n    if (!pendingId) return;\n    pendingFocusColumnIdRef.current = null;\n    gripRefs.current.get(pendingId)?.focus({ preventScroll: true });\n  }, [sorts]);\n\n  useEffect(() => unlockRootScroll, [unlockRootScroll]);\n\n  const updateSort = useCallback(\n    (index: number, next: Partial<SortSpec>) => {\n      actions.setSorts(sorts.map((s, i) => (i === index ? { ...s, ...next } : s)));\n    },\n    [actions, sorts],\n  );\n\n  const removeSort = useCallback(\n    (index: number) => {\n      actions.setSorts(sorts.filter((_, i) => i !== index));\n      const nextFocusId = sorts[index + 1]?.columnId ?? sorts[index - 1]?.columnId;\n      if (nextFocusId) pendingFocusColumnIdRef.current = nextFocusId;\n      else requestAnimationFrame(() => addButtonRef.current?.focus({ preventScroll: true }));\n    },\n    [actions, sorts],\n  );\n\n  const announceMove = useCallback(\n    (columnId: string, toIndex: number, total: number) => {\n      const column = gridColumns.find((c) => c.id === columnId);\n      const label = column ? columnLabelText(column) : columnId;\n      setAnnouncement(labels.sort.sortReorderAnnouncement(label, toIndex + 1, total));\n    },\n    [gridColumns, labels],\n  );\n\n  const reorderSorts = useCallback(\n    (fromIndex: number, toIndex: number, columnId: string) => {\n      if (fromIndex === toIndex) return;\n      const next = moveItem(sorts, fromIndex, toIndex);\n      actions.setSorts(next);\n      pendingFocusColumnIdRef.current = columnId;\n      announceMove(columnId, toIndex, next.length);\n    },\n    [actions, sorts, announceMove],\n  );\n\n  const addSort = useCallback(() => {\n    const first = sortableColumns.find((c) => !sortedColumnIds.has(c.id));\n    if (!first) return;\n    actions.setSorts([...sorts, { columnId: first.id, direction: \"asc\" }]);\n  }, [actions, sortableColumns, sortedColumnIds, sorts]);\n\n  const resetSorting = useCallback(() => {\n    actions.setSorts([]);\n  }, [actions]);\n\n  const canAddSort = sortableColumns.some((c) => !sortedColumnIds.has(c.id));\n\n  return (\n    <Popover>\n      <PopoverTrigger\n        render={\n          <Button type=\"button\" variant=\"outline\" size=\"sm\" className={cn(\"relative\", className)} aria-label={labels.sort.sortAriaLabel}>\n            <ArrowUpDown />\n            {labels.sort.sort}\n            {sorts.length > 0 && (\n              <Badge data-grid-sort-count=\"\" variant=\"secondary\" className=\"ms-1\">\n                {sorts.length}\n              </Badge>\n            )}\n          </Button>\n        }\n      />\n      <PopoverContent align=\"start\" className=\"flex w-full min-w-95 flex-col gap-3.5 p-4\">\n        <div data-grid-sort-list=\"\" className=\"flex flex-col gap-3.5\">\n          <h4 className=\"font-medium leading-none text-muted-foreground\">{labels.sort.sort}</h4>\n          {sorts.length === 0 && <p className=\"text-sm text-muted-foreground\">{labels.sort.noSortsApplied}</p>}\n          <div aria-live=\"polite\" role=\"status\" className=\"sr-only\">\n            {announcement}\n          </div>\n          {sorts.length > 0 && (\n            <DragDropProvider<SortRowDragData>\n              // ponytail: drop AutoScroller — the popover portals to body, so the page is a scrollable\n              // ancestor and dragging near a viewport edge scrolls the page; re-add it if the list\n              // (max-h-75) overflows often enough that mid-drag auto-scrolling is needed\n              plugins={(defaults) => defaults.filter((p) => p !== AutoScroller)}\n              onDragStart={lockRootScroll}\n              onDragEnd={(event) => {\n                unlockRootScroll();\n                if (event.canceled) return;\n                const sourceData = event.operation.source?.data;\n                const targetData = event.operation.target?.data;\n                const fromIndex = sourceData?.index;\n                const toIndex = targetData?.index;\n                const columnId = sourceData?.columnId;\n                if (fromIndex === undefined || toIndex === undefined || !columnId) return;\n                reorderSorts(fromIndex, toIndex, columnId);\n              }}\n            >\n              <div role=\"list\" className=\"flex max-h-75 flex-col gap-2 overflow-y-auto p-1\">\n                {sorts.map((sort, index) => {\n                  // a column already used by another row is excluded from this row's own options, not from every row.\n                  const offered = sortableColumns.filter((c) => c.id === sort.columnId || !sortedColumnIds.has(c.id));\n                  const own = gridColumns.find((c) => c.id === sort.columnId);\n                  const availableColumns = own && !offered.includes(own) ? [...offered, own] : offered;\n                  return (\n                    <SortRow\n                      key={index}\n                      sort={sort}\n                      index={index}\n                      total={sorts.length}\n                      availableColumns={availableColumns}\n                      labels={labels}\n                      onUpdate={updateSort}\n                      onRemove={removeSort}\n                      onArrowReorder={(toIndex) => reorderSorts(index, toIndex, sort.columnId)}\n                      gripRef={(el) => {\n                        gripRefs.current.set(sort.columnId, el);\n                      }}\n                    />\n                  );\n                })}\n              </div>\n            </DragDropProvider>\n          )}\n          <div className=\"flex w-full items-center gap-2\">\n            <Button type=\"button\" ref={addButtonRef} onClick={addSort} disabled={!canAddSort}>\n              {labels.sort.addSort}\n            </Button>\n            {sorts.length > 0 && (\n              <Button type=\"button\" variant=\"outline\" onClick={resetSorting}>\n                {labels.sort.clearSorts}\n              </Button>\n            )}\n          </div>\n        </div>\n      </PopoverContent>\n    </Popover>\n  );\n}\n\ntype SortRowProps = {\n  sort: SortSpec;\n  index: number;\n  total: number;\n  availableColumns: { id: string; header: string | ReactNode; headerText?: string }[];\n  labels: DataGridLabels;\n  onUpdate: (index: number, next: Partial<SortSpec>) => void;\n  onRemove: (index: number) => void;\n  onArrowReorder: (toIndex: number) => void;\n  gripRef: (el: HTMLButtonElement | null) => void;\n};\n\n/** One sort row: `useSortable` wires pointer-drag reorder via `@dnd-kit/react`; the drag handle's `onKeyDown` implements the ArrowUp/ArrowDown fallback, which always takes precedence over dnd-kit's own keyboard sensor (checked first, `stopPropagation`'d). */\nfunction SortRow(props: SortRowProps): ReactNode {\n  const { sort, index, total, availableColumns, labels, onUpdate, onRemove, onArrowReorder, gripRef } = props;\n  // No plugins: dnd-kit's optimistic DOM moves fight React's re-render after a drop; `onGripKeyDown` is the keyboard path.\n  const { ref, handleRef, isDragSource } = useSortable<SortRowDragData>({\n    id: sort.columnId,\n    index,\n    data: { index, columnId: sort.columnId },\n    plugins: [],\n  });\n\n  const onGripKeyDown = useCallback(\n    (event: ReactKeyboardEvent<HTMLButtonElement>) => {\n      if (event.key === \"Backspace\" || event.key === \"Delete\") {\n        event.preventDefault();\n        event.stopPropagation(); // wins over dnd-kit's keyboard sensor regardless of library support\n        onRemove(index);\n        return;\n      }\n      if (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\") return;\n      event.preventDefault();\n      event.stopPropagation(); // wins over dnd-kit's keyboard sensor regardless of library support\n      const target = index + (event.key === \"ArrowUp\" ? -1 : 1);\n      if (target < 0 || target >= total) return;\n      onArrowReorder(target);\n    },\n    [index, total, onArrowReorder, onRemove],\n  );\n\n  return (\n    <div\n      ref={ref}\n      data-grid-sort-row=\"\"\n      role=\"listitem\"\n      className={cn(\n        \"flex items-center gap-1.5 transition-transform\",\n        isDragSource && \"z-10 scale-[1.01] opacity-90 shadow-lg\",\n      )}\n    >\n      <ButtonGroup className=\"min-w-0 flex-1\">\n      <Select\n        value={sort.columnId}\n        onValueChange={(value) => {\n          // Base UI calls setValue(null) when the selected item disappears from the rendered items.\n          if (value === null) return;\n          onUpdate(index, { columnId: value });\n        }}\n      >\n        <SelectTrigger className=\"h-8 min-w-0 flex-[0_0_55%] bg-muted dark:bg-muted dark:hover:bg-muted/80\" aria-label={labels.sort.columnAriaLabel}>\n          {/* explicit label lookup: SelectValue only resolves a mounted SelectItem's label, which\n              the popup content isn't until first opened — this control's own trigger text must be\n              correct on first render (no open required), same rationale as the filter menu's group select. */}\n          <SelectValue className=\"truncate\">{(value: string) => { const c = availableColumns.find((col) => col.id === value); return c ? columnLabelText(c) : value; }}</SelectValue>\n        </SelectTrigger>\n        <SelectContent>\n          {availableColumns.map((c) => (\n            <SelectItem key={c.id} value={c.id}>\n              {columnLabelText(c)}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n      <Select\n        value={sort.direction}\n        onValueChange={(value) => {\n          if (value === null) return;\n          onUpdate(index, { direction: value as SortSpec[\"direction\"] });\n        }}\n      >\n        <SelectTrigger className=\"h-8 min-w-0 flex-1 bg-muted dark:bg-muted dark:hover:bg-muted/80\" aria-label={labels.sort.directionAriaLabel}>\n          {/* explicit label lookup, same rationale as the column select above. */}\n          <SelectValue className=\"truncate\">{(value: SortSpec[\"direction\"]) => (value === \"desc\" ? labels.sort.descending : labels.sort.ascending)}</SelectValue>\n        </SelectTrigger>\n        <SelectContent>\n          <SelectItem value=\"asc\">{labels.sort.ascending}</SelectItem>\n          <SelectItem value=\"desc\">{labels.sort.descending}</SelectItem>\n        </SelectContent>\n      </Select>\n      <Button type=\"button\" variant=\"outline\" size=\"icon\" className=\"size-8 shrink-0\" aria-label={labels.sort.removeSortAriaLabel} onClick={() => onRemove(index)}>\n        <Trash2 />\n      </Button>\n      </ButtonGroup>\n      <Button\n        type=\"button\"\n        variant=\"outline\"\n        size=\"icon\"\n        ref={(el) => {\n          handleRef(el);\n          gripRef(el);\n        }}\n        className={cn(\"size-8 shrink-0 cursor-grab touch-none\", isDragSource && \"cursor-grabbing\")}\n        aria-label={labels.sort.reorderSortAriaLabel}\n        // prevent native mousedown focus: Chromium re-centers the focused drag handle in the viewport mid-drag and the page jumps\n        onMouseDown={(e) => e.preventDefault()}\n        onKeyDown={onGripKeyDown}\n      >\n        <GripVertical />\n      </Button>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-sort-list/sort-list.tsx"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
