{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sort-builder",
  "title": "Sort Builder",
  "description": "The multi-key sort editor: an ordered list of \"key, direction\" rows — sort by status A → Z, then by created newest first — that a person builds, reorders and shares, plus the pure functions that turn that list into a comparator, a URL parameter, server JSON and a sentence. Reach for it wherever one sort arrow on one column has stopped being enough: the sort panel of an admin or data table, a saved or shared view, the order of a report or a CSV/Excel export, a scheduled or emailed report, the \"order by\" a person composes for an API or a query builder, a leaderboard or ranking screen, a kanban or backlog whose rows need priority then due date, a search-results ordering control, a pricing or product grid sorted by two things at once, a log or audit viewer, a file or media browser (name sorted naturally, so step-9 comes before step-10), and anywhere a list must look the same on every refresh instead of quietly reshuffling. Different from this registry's sort-header, which is the table heading you click to sort by one column in three states — that one is a single column's ascending/descending/off, this one is the panel where several keys are stacked in priority order, each with its own direction, and the order of the keys is the meaning. What it gets right that a hand-rolled comparator usually does not: a key can only appear once (a second row on the same key cannot change the order, so it is never offered); text is compared through a cached Intl.Collator rather than with <, because codepoint order files every lowercase word after every uppercase one and sends Ähre and ångström past Zebra, and because the locale genuinely changes the answer (Swedish puts å ä ö after z); natural ordering for digits inside strings is opt-in per key (item9 before item10); missing values are partitioned out before any comparison, since Array.prototype.sort pins undefined to the end without ever calling the comparator — so a blanks-first setting drawn on screen would silently do nothing — and null left to < sorts where the word \"null\" falls; the blanks position is held separately from the direction and is deliberately not flipped by it, because SQL engines disagree (PostgreSQL treats null as largest, MySQL as smallest) and reversing a sort should not throw every empty row to the other end of the table; a value that cannot be read as a date or a number is treated as blank rather than fed to a subtraction, because a NaN from a comparator does not throw and does not sort, it leaves the whole table in the order it arrived with no error anywhere; and there is a tie-break key applied last, which is not about sort stability — Array.prototype.sort has been stable since ES2019 — but because stability preserves the order the rows arrived in, and two fetches of the same equal-ranked rows do not arrive in the same order. Four outputs, so the same list can drive the client and the server: sortRows/sortComparator for sorting in the browser (with per-key accessors, so a column showing \"3 days ago\" sorts on the timestamp); buildSortQuery for the JSON to send, which resolves each key's blanks position and hands back every term it had to drop (unfinished, unknown or duplicated) instead of silently skipping it; toSortParam/parseSortParam for the URL, in the ?sort=-created,name form JSON:API specifies, escaped so a key containing a comma or starting with a hyphen round-trips, and returning null for a parameter it cannot fully read rather than applying half an order; and describeSort for the live region, the summary line or a chip. Accessible by construction: an ordered list so position is conveyed rather than implied, a named control per row (\"Direction for sort key 2\"), direction wording that follows the kind (newest first / largest first / A → Z), move-earlier and move-later buttons that use aria-disabled rather than disabled so the tab order does not shift and focus is not dropped when a key reaches the end, a polite live region for added, removed and moved, and a stale key kept visible and flagged instead of being silently re-pointed at another column. Common asks it answers: \"multi sort react\", \"multiple column sort react\", \"sort builder react\", \"multi key sort component\", \"shadcn sort builder\", \"shadcn multi sort\", \"order by builder ui\", \"sort panel react table\", \"tanstack table multi sort ui\", \"secondary sort react\", \"sort by then by ui\", \"priority sort list react\", \"reorder sort keys ui\", \"drag sort priority react\", \"sort state in url\", \"serialize sort to query string\", \"parse sort query param\", \"json api sort parameter\", \"?sort=-created\", \"shareable sorted link\", \"send sort to api json\", \"sort to order by sql\", \"nulls first nulls last react\", \"where do empty values go when sorting\", \"blank rows sort to top\", \"intl collator react sort\", \"localeCompare vs Intl.Collator\", \"accented characters sort wrong javascript\", \"natural sort react\", \"sort item10 before item9\", \"alphanumeric natural order javascript\", \"stable sort react table\", \"rows reshuffle on refresh sort\", \"tie breaker sort javascript\", \"sort by date newest first react\", \"invalid date sort nan\", \"sort not working silently javascript\", \"sort comparator returns nan\". Styled entirely with shadcn tokens (input, ring, accent, destructive, muted-foreground, background) so it follows light and dark mode, controlled or uncontrolled, and its only npm dependency is lucide-react for the four icons — no table library, no sort library, one file.",
  "dependencies": [
    "lucide-react"
  ],
  "files": [
    {
      "path": "registry/ui/sort-builder.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { ArrowDown, ArrowUp, Plus, Trash2 } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/* ---------------------------------------------------------------- the model\n\n   A sort is an *ordered list* of keys, and the order is the whole meaning: \"status, then newest\n   first\" and \"newest first, then status\" are different reports. That is why this is a list with\n   move-up/move-down rather than a set of toggles, and why the list — not a comparator, not a\n   sorted array — is what the component holds and what a caller saves.\n*/\n\nexport type SortDirection = \"asc\" | \"desc\"\n\n/**\n * Where the rows with no value for a key go.\n *\n * Held separately from `direction` and deliberately *not* flipped by it. SQL engines disagree\n * about this (PostgreSQL treats null as the largest value, so ascending puts blanks last and\n * descending puts them first; MySQL treats it as the smallest and does the opposite), which means\n * a person who reverses a sort watches every empty row jump from one end to the other. Reversing\n * \"oldest first\" into \"newest first\" is a statement about the rows that have a date; it is not a\n * request to move the ones that do not.\n */\nexport type SortNulls = \"first\" | \"last\"\n\n/**\n * What kind of value a key holds, which decides how two of them are compared.\n *\n * Short on purpose, like `filter-builder`'s `FilterFieldKind`: the only question a comparison asks\n * is which of the four comparisons to run, and `varchar` / `text` / `uuid` all answer \"text\".\n */\nexport type SortValueKind = \"text\" | \"number\" | \"date\" | \"boolean\"\n\nexport interface SortField<Row = Record<string, unknown>> {\n  /** Sent to the server, written into the URL. Stable; not shown to anyone. */\n  name: string\n  /** Shown in the key menu. Falls back to `name`. */\n  label?: string\n  /** Defaults to `\"text\"`, the kind with the fewest assumptions baked in. */\n  kind?: SortValueKind\n  /** Where this key's blanks go when a term does not say. Defaults to `\"last\"`. */\n  nulls?: SortNulls\n  /**\n   * Text only: compare embedded digit runs as numbers, so `item9` precedes `item10`.\n   *\n   * Off by default because it is not free of surprises — it also makes `1.5` precede `1.10`, which\n   * is right for version strings and wrong for decimals written as text.\n   */\n  numeric?: boolean\n  /**\n   * Pulls the comparable value out of a row. Defaults to reading `row[name]`.\n   *\n   * Worth setting whenever the thing shown and the thing compared differ: a column rendering\n   * `user.displayName` sorts on a nested value that `row[\"user\"]` cannot reach, and a column\n   * showing \"3 days ago\" has to sort on the timestamp rather than on that sentence.\n   */\n  accessor?: (row: Row) => unknown\n}\n\nexport interface SortTerm {\n  id: string\n  /** A `SortField[\"name\"]`, or `\"\"` for a row whose key has not been chosen yet. */\n  field: string\n  direction: SortDirection\n  /** Overrides the field's own `nulls`. `undefined` means \"whatever the field says\". */\n  nulls?: SortNulls\n}\n\nlet idCounter = 0\n\n/**\n * Mints a term id.\n *\n * Exactly the reason `filter-builder` has one: keying a row by its index makes the row below move\n * up into the state of the row that was removed, and in a list whose order *is* the meaning, that\n * shows a direction against a key nobody chose. Module-level so two builders cannot collide.\n */\nexport function createSortId(): string {\n  idCounter += 1\n  return `sb-${idCounter}`\n}\n\nexport function sortFieldKind<Row>(field: SortField<Row> | undefined): SortValueKind {\n  return field?.kind ?? \"text\"\n}\n\nexport function sortFieldLabel<Row>(field: SortField<Row> | undefined): string {\n  if (!field) return \"\"\n  return field.label ?? field.name\n}\n\nexport function findSortField<Row>(\n  fields: readonly SortField<Row>[],\n  name: string\n): SortField<Row> | undefined {\n  return fields.find((candidate) => candidate.name === name)\n}\n\n/** The direction a key starts at: the one a person means when they first reach for it. */\nexport function defaultDirection(kind: SortValueKind): SortDirection {\n  // Dates descend. \"Sort by created\" means the newest, every time — a list of records opened at\n  // the oldest row is the one case where the obvious default is the opposite of ascending.\n  return kind === \"date\" ? \"desc\" : \"asc\"\n}\n\nexport function effectiveNulls<Row>(\n  term: SortTerm,\n  field: SortField<Row> | undefined\n): SortNulls {\n  return term.nulls ?? field?.nulls ?? \"last\"\n}\n\nexport function createSortTerm<Row>(\n  field: SortField<Row> | undefined,\n  generateId: () => string = createSortId\n): SortTerm {\n  return {\n    id: generateId(),\n    field: field?.name ?? \"\",\n    direction: defaultDirection(sortFieldKind(field)),\n  }\n}\n\n/* --------------------------------------------------- one key, at most one term\n\n   The invariant that gives the component its shape. A second term on a key already in the list\n   can never change the order — by the time it is consulted, every pair it could have separated\n   has already been separated by the earlier one — so it is not a refinement, it is a row that\n   looks like it does something and does nothing.\n*/\n\n/** The fields a term may choose: the unused ones, plus the one it already holds. */\nexport function availableSortFields<Row>(\n  fields: readonly SortField<Row>[],\n  terms: readonly SortTerm[],\n  exceptId?: string\n): SortField<Row>[] {\n  const taken = new Set(\n    terms.filter((term) => term.id !== exceptId && term.field !== \"\").map((term) => term.field)\n  )\n  return fields.filter((field) => !taken.has(field.name))\n}\n\nexport function canAddSortTerm<Row>(\n  fields: readonly SortField<Row>[],\n  terms: readonly SortTerm[],\n  maxTerms?: number\n): boolean {\n  if (maxTerms !== undefined && terms.length >= maxTerms) return false\n  return availableSortFields(fields, terms).length > 0\n}\n\n/**\n * Drops repeats of a key, keeping the first.\n *\n * The editor cannot produce one; a URL can — hand-edited, concatenated by something, carried over\n * from a version of the fields where the duplicate was two different keys. The first occurrence is\n * kept because it is the one that decides the order.\n */\nexport function dedupeSortTerms(terms: readonly SortTerm[]): SortTerm[] {\n  const seen = new Set<string>()\n  const kept: SortTerm[] = []\n  for (const term of terms) {\n    if (term.field !== \"\" && seen.has(term.field)) continue\n    if (term.field !== \"\") seen.add(term.field)\n    kept.push(term)\n  }\n  return kept\n}\n\nexport function moveSortTerm(terms: readonly SortTerm[], from: number, to: number): SortTerm[] {\n  if (from === to || from < 0 || to < 0 || from >= terms.length || to >= terms.length) {\n    return [...terms]\n  }\n  const next = [...terms]\n  const [moved] = next.splice(from, 1)\n  next.splice(to, 0, moved)\n  return next\n}\n\n/* ------------------------------------------------------------- reading values */\n\nfunction readProperty(row: unknown, name: string): unknown {\n  if (row === null || typeof row !== \"object\") return undefined\n  return (row as Record<string, unknown>)[name]\n}\n\nexport function readSortValue<Row>(row: Row, field: SortField<Row>): unknown {\n  return field.accessor ? field.accessor(row) : readProperty(row, field.name)\n}\n\nfunction toNumber(value: unknown): number {\n  if (typeof value === \"number\") return value\n  if (typeof value === \"boolean\") return value ? 1 : 0\n  if (typeof value === \"string\") {\n    const trimmed = value.trim()\n    // `Number(\"\")` is 0, which would file every blank cell under zero.\n    return trimmed === \"\" ? Number.NaN : Number(trimmed)\n  }\n  return Number.NaN\n}\n\nfunction toTime(value: unknown): number {\n  if (value instanceof Date) return value.getTime()\n  if (typeof value === \"number\") return value\n  if (typeof value === \"string\") {\n    const trimmed = value.trim()\n    return trimmed === \"\" ? Number.NaN : Date.parse(trimmed)\n  }\n  return Number.NaN\n}\n\n/**\n * Whether a value is simply absent.\n *\n * An empty string counts. A blank cell and a missing field are the same thing to the person\n * reading the table, and filing one under \"\" while the other goes to the end splits the blanks\n * into two groups for a reason nobody can see.\n */\nexport function isMissingValue(value: unknown): boolean {\n  if (value === null || value === undefined) return true\n  if (typeof value === \"number\") return Number.isNaN(value)\n  if (typeof value === \"string\") return value.trim() === \"\"\n  if (value instanceof Date) return Number.isNaN(value.getTime())\n  return false\n}\n\n/**\n * Whether a value is absent *for this kind of comparison*.\n *\n * The kind-aware half exists to close a hole that is silent rather than loud. A comparator that\n * returns `NaN` does not throw and does not sort: `[3, 1, 2].sort(() => NaN)` answers `[3, 1, 2]`\n * — measured — so one unparseable date in a column leaves the whole table in the order it arrived,\n * with no error anywhere and the sort control showing a direction. Classifying \"not a date\" as\n * absent, here, is what keeps `compareSortValues` from ever being handed a value it can only\n * answer `NaN` about.\n */\nexport function isMissingForKind(value: unknown, kind: SortValueKind): boolean {\n  if (isMissingValue(value)) return true\n  switch (kind) {\n    case \"number\":\n      return Number.isNaN(toNumber(value))\n    case \"date\":\n      return Number.isNaN(toTime(value))\n    default:\n      return false\n  }\n}\n\n/* ----------------------------------------------------------- comparing values */\n\nexport type SortSensitivity = \"base\" | \"accent\" | \"case\" | \"variant\"\n\nexport interface SortCompareOptions {\n  /** Passed to `Intl.Collator`. `undefined` uses the runtime's default locale. */\n  locale?: string\n  /** Defaults to `\"variant\"`, the collator's own default: accents and case both count. */\n  sensitivity?: SortSensitivity\n}\n\nconst collators = new Map<string, Intl.Collator>()\n\n/**\n * A collator per distinct configuration, built once.\n *\n * Not the usual \"constructing one is expensive\" advice, which measured the other way round here:\n * with no options at all, `a.localeCompare(b)` sorted 2,000 strings twenty times in 5.8ms against\n * a cached collator's 15.1ms. The reason to hold one is what happens as soon as options are\n * involved, which for this component is always — `a.localeCompare(b, locale, options)` re-resolves\n * the collator on every single comparison and took **671.7ms** for the same work, 14.9x the cached\n * collator's 45.1ms, in the same range as constructing a fresh `Intl.Collator` per comparison\n * (641.1ms). All four figures are medians of ten interleaved runs on node v26.\n */\nexport function collatorFor(\n  locale: string | undefined,\n  numeric: boolean,\n  sensitivity: SortSensitivity\n): Intl.Collator {\n  const key = `${locale ?? \"\"}|${numeric}|${sensitivity}`\n  const found = collators.get(key)\n  if (found) return found\n  const made = new Intl.Collator(locale, { numeric, sensitivity })\n  collators.set(key, made)\n  return made\n}\n\n/**\n * Compares two values of one kind, ascending. Never returns `NaN`.\n *\n * Callers must have ruled out `isMissingForKind` on both sides first; `sortComparator` does.\n */\nexport function compareSortValues(\n  a: unknown,\n  b: unknown,\n  kind: SortValueKind,\n  options: SortCompareOptions & { numeric?: boolean } = {}\n): number {\n  switch (kind) {\n    case \"number\":\n      return numberOrder(toNumber(a), toNumber(b))\n    case \"date\":\n      return numberOrder(toTime(a), toTime(b))\n    case \"boolean\":\n      // false before true, the order the two words are in.\n      return numberOrder(booleanRank(a), booleanRank(b))\n    default: {\n      // Text goes through a collator, never through `<`. Measured with plain `<`:\n      // [\"Banana\",\"Zebra\",\"apple\",\"Ähre\",\"Öl\",\"ångström\"] — every lowercase word after every\n      // uppercase one, and every accented word after both, because that is codepoint order and\n      // not an alphabet. The same six through `Intl.Collator(\"en\")`:\n      // [\"Ähre\",\"ångström\",\"apple\",\"Banana\",\"Öl\",\"Zebra\"].\n      const collator = collatorFor(\n        options.locale,\n        options.numeric ?? false,\n        options.sensitivity ?? \"variant\"\n      )\n      return collator.compare(String(a), String(b))\n    }\n  }\n}\n\n/**\n * Which side of a boolean key a value falls on.\n *\n * `value === true` would be the whole function if rows came from the same place the type did. A\n * boolean over the wire is a `1`, a `0`, `\"true\"` or `\"false\"` as often as it is a boolean, and\n * ranking all four of those as \"not true\" would answer 0 for every pair — a column that silently\n * does not sort, which is the failure this file spends `isMissingForKind` avoiding elsewhere.\n */\nfunction booleanRank(value: unknown): number {\n  if (typeof value === \"boolean\") return value ? 1 : 0\n  if (typeof value === \"number\") return value === 0 ? 0 : 1\n  if (typeof value === \"string\") {\n    const lowered = value.trim().toLowerCase()\n    if (lowered === \"false\" || lowered === \"0\") return 0\n    if (lowered === \"true\" || lowered === \"1\") return 1\n  }\n  return value ? 1 : 0\n}\n\nfunction numberOrder(a: number, b: number): number {\n  // Written as comparisons rather than `a - b`: subtraction answers `NaN` for `Infinity - Infinity`,\n  // and a `NaN` from a comparator is the silent no-op described on `isMissingForKind`.\n  if (a < b) return -1\n  if (a > b) return 1\n  return 0\n}\n\n/** Compares two values of unknown kind — used for the tie-break, which has no declared field. */\nfunction compareUnknown(a: unknown, b: unknown, options: SortCompareOptions): number {\n  const aMissing = isMissingValue(a)\n  const bMissing = isMissingValue(b)\n  if (aMissing || bMissing) return aMissing && bMissing ? 0 : aMissing ? 1 : -1\n  if (typeof a === \"number\" && typeof b === \"number\") return numberOrder(a, b)\n  return compareSortValues(a, b, \"text\", { ...options, numeric: true })\n}\n\n/* --------------------------------------------------------------- the comparator */\n\nexport interface SortRunOptions<Row> extends SortCompareOptions {\n  /**\n   * The last key, always ascending, applied after every term: a row id, a slug, anything unique.\n   *\n   * This is not about `Array.prototype.sort` being unstable. It is stable, and required to be\n   * since ES2019 — measured on node v26: twelve rows sorted by `i % 3` keep their input order\n   * inside each group. The problem is what that guarantee is a guarantee *about*. Stability\n   * preserves the order the array arrived in, and the order an array of rows arrives in is not a\n   * property of the rows: two fetches of the same three equal-ranked records, `[3,1,2]` and\n   * `[1,2,3]`, sorted with the same comparator, measured as `[3,1,2]` and `[1,2,3]` — a list that\n   * reshuffles itself on refresh while the sort control says nothing changed. Without a tie-break\n   * the view is only as deterministic as whatever produced the input.\n   */\n  tieBreak?: string | ((row: Row) => unknown)\n}\n\n/**\n * The comparator for a list of terms.\n *\n * Terms naming a field that no longer exists are skipped rather than guessed at — see\n * `buildSortQuery`, which reports them — because a URL outliving a column should drop that key,\n * not reorder the table by a value it cannot read.\n */\nexport function sortComparator<Row>(\n  terms: readonly SortTerm[],\n  fields: readonly SortField<Row>[],\n  options: SortRunOptions<Row> = {}\n): (a: Row, b: Row) => number {\n  const compiled = terms\n    .map((term) => {\n      const field = term.field === \"\" ? undefined : findSortField(fields, term.field)\n      if (!field) return null\n      return {\n        field,\n        kind: sortFieldKind(field),\n        sign: term.direction === \"desc\" ? -1 : 1,\n        missingSign: effectiveNulls(term, field) === \"first\" ? -1 : 1,\n        numeric: field.numeric ?? false,\n      }\n    })\n    .filter((entry): entry is NonNullable<typeof entry> => entry !== null)\n\n  const tieBreak = options.tieBreak\n  const readTieBreak =\n    typeof tieBreak === \"function\"\n      ? tieBreak\n      : typeof tieBreak === \"string\"\n        ? (row: Row) => readProperty(row, tieBreak)\n        : null\n\n  return (a: Row, b: Row) => {\n    for (const entry of compiled) {\n      const left = readSortValue(a, entry.field)\n      const right = readSortValue(b, entry.field)\n      const leftMissing = isMissingForKind(left, entry.kind)\n      const rightMissing = isMissingForKind(right, entry.kind)\n      if (leftMissing || rightMissing) {\n        if (leftMissing && rightMissing) continue\n        // Not multiplied by `sign`. Reversing the direction reverses the rows that have a value;\n        // it does not move the ones that do not. See `SortNulls`.\n        return leftMissing ? entry.missingSign : -entry.missingSign\n      }\n      const order = compareSortValues(left, right, entry.kind, {\n        locale: options.locale,\n        sensitivity: options.sensitivity,\n        numeric: entry.numeric,\n      })\n      if (order !== 0) return order * entry.sign\n    }\n    if (readTieBreak) {\n      const order = compareUnknown(readTieBreak(a), readTieBreak(b), options)\n      if (order !== 0) return order\n    }\n    return 0\n  }\n}\n\n/** Sorts a copy. The input is never touched: it is usually props or a fetch result. */\nexport function sortRows<Row>(\n  rows: readonly Row[],\n  terms: readonly SortTerm[],\n  fields: readonly SortField<Row>[],\n  options: SortRunOptions<Row> = {}\n): Row[] {\n  return [...rows].sort(sortComparator(terms, fields, options))\n}\n\n/* --------------------------------------------------------- output: server JSON */\n\nexport interface SortQueryTerm {\n  field: string\n  direction: SortDirection\n  /** Resolved, never `undefined`: a server cannot look up the field's default. */\n  nulls: SortNulls\n}\n\nexport type SortTermIssue = \"no_field\" | \"unknown_field\" | \"duplicate_field\"\n\nexport interface SortDropped {\n  id: string\n  field: string\n  issue: SortTermIssue\n}\n\n/**\n * The order to send, and every term left out of it.\n *\n * The second half for the same reason `filter-builder` returns its dropped rows: a builder that\n * quietly skips what it cannot use produces a list whose order does not match the editor above it,\n * and that reads as the sort being broken rather than as a row nobody finished.\n *\n * `null` means there is nothing to sort by, which is not the same as an empty result — a caller\n * handed `null` should fall back to its own default order.\n */\nexport function buildSortQuery<Row>(\n  terms: readonly SortTerm[],\n  fields: readonly SortField<Row>[]\n): { query: SortQueryTerm[] | null; dropped: SortDropped[] } {\n  const dropped: SortDropped[] = []\n  const query: SortQueryTerm[] = []\n  const seen = new Set<string>()\n  for (const term of terms) {\n    if (term.field === \"\") {\n      dropped.push({ id: term.id, field: \"\", issue: \"no_field\" })\n      continue\n    }\n    const field = findSortField(fields, term.field)\n    if (!field) {\n      dropped.push({ id: term.id, field: term.field, issue: \"unknown_field\" })\n      continue\n    }\n    if (seen.has(term.field)) {\n      dropped.push({ id: term.id, field: term.field, issue: \"duplicate_field\" })\n      continue\n    }\n    seen.add(term.field)\n    query.push({\n      field: term.field,\n      direction: term.direction,\n      nulls: effectiveNulls(term, field),\n    })\n  }\n  return { query: query.length > 0 ? query : null, dropped }\n}\n\n/* ---------------------------------------------------------- output: URL string\n\n   `?sort=-created,name` — a leading `-` for descending, comma between keys, in priority order.\n   The form JSON:API specifies, which is the point: it is the one encoding of a sort that servers\n   already read, so the shared link, the bookmark and the bug report all carry something the\n   backend can act on rather than a blob it has to be taught.\n\n   Two characters are structural and both can occur in a key, so they are escaped rather than\n   trusted — a field literally named `a,b`, or one starting with `-`, round-trips.\n\n   What this form cannot carry is the nulls position, and that is a deliberate loss rather than an\n   oversight: a suffix for it would be read by no server on earth, and inventing one would turn the\n   one widely-understood sort encoding into a private one. `buildSortQuery` is the lossless output;\n   a term parsed back from a URL falls back to its field's own `nulls`.\n*/\n\nexport function escapeSortSegment(text: string): string {\n  return text.replace(/[\\\\,]/g, (match) => `\\\\${match}`).replace(/^-/, \"\\\\-\")\n}\n\nexport function toSortParam(terms: readonly SortTerm[]): string {\n  return terms\n    .filter((term) => term.field !== \"\")\n    .map((term) => `${term.direction === \"desc\" ? \"-\" : \"\"}${escapeSortSegment(term.field)}`)\n    .join(\",\")\n}\n\n/**\n * Reads what `toSortParam` wrote, with fresh ids.\n *\n * `null` for anything it cannot read, rather than the half it could. A URL is the one input here\n * that arrives from outside, and half an order applied silently is worse than an order that did\n * not load: the rows are in *some* sequence either way, and only one of the two tells the person\n * that what they shared is not what they are looking at.\n */\nexport function parseSortParam(\n  text: string,\n  generateId: () => string = createSortId\n): SortTerm[] | null {\n  if (text === \"\") return []\n  const terms: SortTerm[] = []\n  let field = \"\"\n  let direction: SortDirection = \"asc\"\n  let atSegmentStart = true\n  let i = 0\n\n  const endSegment = (): boolean => {\n    if (field === \"\") return false\n    terms.push({ id: generateId(), field, direction })\n    field = \"\"\n    direction = \"asc\"\n    atSegmentStart = true\n    return true\n  }\n\n  while (i < text.length) {\n    const char = text[i]\n    if (char === \"\\\\\") {\n      // A trailing backslash escapes nothing, which means the string was cut short.\n      if (i + 1 >= text.length) return null\n      field += text[i + 1]\n      atSegmentStart = false\n      i += 2\n      continue\n    }\n    if (char === \",\") {\n      if (!endSegment()) return null\n      i += 1\n      continue\n    }\n    if (char === \"-\" && atSegmentStart) {\n      direction = \"desc\"\n      atSegmentStart = false\n      i += 1\n      continue\n    }\n    field += char\n    atSegmentStart = false\n    i += 1\n  }\n  if (!endSegment()) return null\n  return terms\n}\n\n/* ------------------------------------------------------------ output: a sentence */\n\n/** The words for a direction, which depend on what is being ordered. */\nexport function directionLabel(kind: SortValueKind, direction: SortDirection): string {\n  switch (kind) {\n    case \"number\":\n      return direction === \"asc\" ? \"smallest first\" : \"largest first\"\n    case \"date\":\n      return direction === \"asc\" ? \"oldest first\" : \"newest first\"\n    case \"boolean\":\n      return direction === \"asc\" ? \"no first\" : \"yes first\"\n    default:\n      return direction === \"asc\" ? \"A → Z\" : \"Z → A\"\n  }\n}\n\n/**\n * The order in words, for a live region, a summary line or a chip.\n *\n * Built from the same terms the editor draws, so it cannot drift from them, and it uses the field\n * labels — which is what makes \"Status A → Z, then Created newest first\" read as a sentence rather\n * than as `status asc, created desc`.\n */\nexport function describeSort<Row>(\n  terms: readonly SortTerm[],\n  fields: readonly SortField<Row>[],\n  labels: Pick<SortBuilderLabels, \"empty\" | \"then\" | \"blanksFirst\" | \"blanksLast\"> = {\n    empty: defaultSortBuilderLabels.empty,\n    then: defaultSortBuilderLabels.then,\n    blanksFirst: defaultSortBuilderLabels.blanksFirst,\n    blanksLast: defaultSortBuilderLabels.blanksLast,\n  },\n  options: { nulls?: boolean } = {}\n): string {\n  const parts: string[] = []\n  for (const term of terms) {\n    if (term.field === \"\") continue\n    const field = findSortField(fields, term.field)\n    if (!field) continue\n    const kind = sortFieldKind(field)\n    let part = `${sortFieldLabel(field)} ${directionLabel(kind, term.direction)}`\n    if (options.nulls) {\n      const nulls = effectiveNulls(term, field)\n      part += ` (${nulls === \"first\" ? labels.blanksFirst : labels.blanksLast})`\n    }\n    parts.push(part)\n  }\n  if (parts.length === 0) return labels.empty\n  return parts.join(`, ${labels.then} `)\n}\n\n/* ----------------------------------------------------------------- the editor */\n\nexport interface SortBuilderLabels {\n  sortBy: string\n  then: string\n  addSort: string\n  allKeysUsed: string\n  empty: string\n  blanksFirst: string\n  blanksLast: string\n  chooseKey: string\n  key: (position: number) => string\n  direction: (position: number) => string\n  nulls: (position: number) => string\n  moveUp: (position: number) => string\n  moveDown: (position: number) => string\n  remove: (position: number) => string\n  added: (position: number) => string\n  removed: (position: number, left: number) => string\n  moved: (field: string, position: number, total: number) => string\n}\n\nexport const defaultSortBuilderLabels: SortBuilderLabels = {\n  sortBy: \"Sort by\",\n  then: \"then\",\n  addSort: \"Add sort\",\n  allKeysUsed: \"Every key is already in the list.\",\n  empty: \"No sort order yet.\",\n  blanksFirst: \"blanks first\",\n  blanksLast: \"blanks last\",\n  chooseKey: \"Choose a key\",\n  key: (position) => `Sort key ${position}`,\n  direction: (position) => `Direction for sort key ${position}`,\n  nulls: (position) => `Where blanks go for sort key ${position}`,\n  moveUp: (position) => `Move sort key ${position} earlier`,\n  moveDown: (position) => `Move sort key ${position} later`,\n  remove: (position) => `Remove sort key ${position}`,\n  added: (position) => `Sort key ${position} added`,\n  removed: (position, left) =>\n    `Sort key ${position} removed, ${left} ${left === 1 ? \"key\" : \"keys\"} left`,\n  moved: (field, position, total) => `${field} moved to position ${position} of ${total}`,\n}\n\nexport type SortChange =\n  | { type: \"add\"; id: string }\n  | { type: \"remove\"; id: string }\n  | { type: \"update\"; id: string }\n  | { type: \"move\"; id: string }\n\nexport interface SortBuilderProps<Row = Record<string, unknown>>\n  extends Omit<\n    React.ComponentPropsWithoutRef<\"fieldset\">,\n    \"children\" | \"onChange\" | \"defaultValue\"\n  > {\n  /** The keys a sort can be built on. The first unused one is what a new row starts with. */\n  fields: readonly SortField<Row>[]\n  /** Controlled list. Pair with `onChange`. */\n  value?: readonly SortTerm[]\n  /** Starting list when uncontrolled. */\n  defaultValue?: readonly SortTerm[]\n  onChange?: (next: SortTerm[], change: SortChange) => void\n  /** Optional cap. There is already an implicit one: a key cannot be used twice. */\n  maxTerms?: number\n  /**\n   * Draw the blanks-first/blanks-last control on each row.\n   *\n   * Off by default. It is the right answer for a report or an export, where someone is deciding\n   * what the output looks like, and it is noise on a list page where the rows with no value are\n   * not the point.\n   */\n  showNulls?: boolean\n  legend?: React.ReactNode\n  labels?: Partial<SortBuilderLabels>\n  disabled?: boolean\n  generateId?: () => string\n}\n\nconst SELECT_CLASS =\n  \"h-9 min-w-0 rounded-md border border-input bg-transparent px-2 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50\"\n\nconst ICON_BUTTON_CLASS =\n  \"inline-flex size-9 flex-none items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50\"\n\nconst REMOVE_BUTTON_CLASS =\n  \"inline-flex size-9 flex-none items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50\"\n\nconst GHOST_BUTTON_CLASS =\n  \"inline-flex h-9 items-center justify-center gap-2 rounded-md border border-input bg-background px-3 text-sm font-medium shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50\"\n\nexport function SortBuilder<Row = Record<string, unknown>>({\n  fields,\n  value,\n  defaultValue,\n  onChange,\n  maxTerms,\n  showNulls = false,\n  legend,\n  labels: labelOverrides,\n  disabled,\n  generateId = createSortId,\n  className,\n  ...props\n}: SortBuilderProps<Row>) {\n  const labels = React.useMemo(\n    () => ({ ...defaultSortBuilderLabels, ...labelOverrides }),\n    [labelOverrides]\n  )\n  const controlled = value !== undefined\n  const [internal, setInternal] = React.useState<SortTerm[]>(() => [...(defaultValue ?? [])])\n  const terms = controlled ? value : internal\n  const [message, setMessage] = React.useState(\"\")\n\n  const commit = (next: SortTerm[], change: SortChange) => {\n    if (!controlled) setInternal(next)\n    onChange?.(next, change)\n  }\n\n  const canAdd = canAddSortTerm(fields, terms, maxTerms)\n\n  const addTerm = () => {\n    if (!canAdd) return\n    const term = createSortTerm(availableSortFields(fields, terms)[0], generateId)\n    commit([...terms, term], { type: \"add\", id: term.id })\n    setMessage(labels.added(terms.length + 1))\n  }\n\n  const removeTerm = (index: number) => {\n    const term = terms[index]\n    const next = terms.filter((_, at) => at !== index)\n    commit(next, { type: \"remove\", id: term.id })\n    setMessage(labels.removed(index + 1, next.length))\n  }\n\n  const updateTerm = (index: number, patch: Partial<SortTerm>) => {\n    const term = terms[index]\n    const next = terms.map((current, at) => (at === index ? { ...current, ...patch } : current))\n    commit(next, { type: \"update\", id: term.id })\n  }\n\n  const changeField = (index: number, name: string) => {\n    const term = terms[index]\n    const field = findSortField(fields, name)\n    // The direction is re-defaulted rather than carried: \"newest first\" moved onto a text key\n    // would sit there as Z → A, which is not what the person who picked a date meant by it.\n    const previousKind = sortFieldKind(findSortField(fields, term.field))\n    const nextKind = sortFieldKind(field)\n    const direction =\n      previousKind === nextKind ? term.direction : defaultDirection(nextKind)\n    // The nulls override is dropped with the key it was chosen for: it was a statement about that\n    // column's blanks, and the new key's own default is a better guess than the old key's override.\n    updateTerm(index, { field: name, direction, nulls: undefined })\n  }\n\n  const move = (index: number, to: number) => {\n    if (to < 0 || to >= terms.length) return\n    const term = terms[index]\n    const next = moveSortTerm(terms, index, to)\n    commit(next, { type: \"move\", id: term.id })\n    const field = findSortField(fields, term.field)\n    setMessage(\n      labels.moved(sortFieldLabel(field) || term.field || labels.chooseKey, to + 1, next.length)\n    )\n  }\n\n  return (\n    <fieldset\n      className={cn(\"flex min-w-0 flex-col gap-2\", className)}\n      disabled={disabled}\n      {...props}\n    >\n      {legend ? <legend className=\"mb-1 text-sm font-medium\">{legend}</legend> : null}\n\n      {terms.length === 0 ? (\n        <p className=\"text-sm text-muted-foreground\">{labels.empty}</p>\n      ) : (\n        // An ordered list, because the position of a row is its meaning and not its styling: the\n        // list conveys \"2 of 3\" to a screen reader without the component saying it, and the number\n        // beside each row is the same fact for everyone else.\n        <ol className=\"flex min-w-0 flex-col gap-2\">\n          {terms.map((term, index) => {\n            const field = findSortField(fields, term.field)\n            const kind = sortFieldKind(field)\n            const position = index + 1\n            const options = availableSortFields(fields, terms, term.id)\n            const unknownField = term.field !== \"\" && !field\n            return (\n              <li key={term.id} className=\"flex min-w-0 flex-wrap items-center gap-2\">\n                <span className=\"w-14 flex-none text-sm text-muted-foreground\">\n                  {index === 0 ? labels.sortBy : labels.then}\n                </span>\n\n                <select\n                  aria-label={labels.key(position)}\n                  aria-invalid={unknownField || undefined}\n                  disabled={disabled}\n                  className={cn(\n                    SELECT_CLASS,\n                    \"flex-1\",\n                    unknownField && \"border-destructive focus-visible:ring-destructive\"\n                  )}\n                  value={term.field}\n                  onChange={(event) => changeField(index, event.target.value)}\n                >\n                  {term.field === \"\" ? <option value=\"\">{labels.chooseKey}</option> : null}\n                  {/* A key the fields no longer offer is kept as an option rather than silently\n                      re-pointed at something else: a select whose value is absent from its options\n                      shows the first one, so the row would read as a key nobody chose. */}\n                  {unknownField ? <option value={term.field}>{term.field}</option> : null}\n                  {options.map((candidate) => (\n                    <option key={candidate.name} value={candidate.name}>\n                      {sortFieldLabel(candidate)}\n                    </option>\n                  ))}\n                </select>\n\n                <select\n                  aria-label={labels.direction(position)}\n                  disabled={disabled}\n                  className={cn(SELECT_CLASS, \"flex-none\")}\n                  value={term.direction}\n                  onChange={(event) =>\n                    updateTerm(index, { direction: event.target.value as SortDirection })\n                  }\n                >\n                  <option value=\"asc\">{directionLabel(kind, \"asc\")}</option>\n                  <option value=\"desc\">{directionLabel(kind, \"desc\")}</option>\n                </select>\n\n                {showNulls ? (\n                  <select\n                    aria-label={labels.nulls(position)}\n                    disabled={disabled}\n                    className={cn(SELECT_CLASS, \"flex-none\")}\n                    value={effectiveNulls(term, field)}\n                    onChange={(event) =>\n                      updateTerm(index, { nulls: event.target.value as SortNulls })\n                    }\n                  >\n                    <option value=\"first\">{labels.blanksFirst}</option>\n                    <option value=\"last\">{labels.blanksLast}</option>\n                  </select>\n                ) : null}\n\n                {/* `aria-disabled` rather than `disabled`, the answer `column-visibility` already\n                    settled for the same two buttons: the first row's \"earlier\" button becoming\n                    unfocusable shifts the tab order for every row, and a key moved to the end with\n                    the keyboard takes the focus down with its own button — the press lands, the\n                    control vanishes from the tab order, and focus falls to the document. */}\n                <button\n                  type=\"button\"\n                  aria-label={labels.moveUp(position)}\n                  aria-disabled={index === 0 || undefined}\n                  disabled={disabled}\n                  onClick={() => move(index, index - 1)}\n                  className={cn(ICON_BUTTON_CLASS, index === 0 && \"pointer-events-none opacity-50\")}\n                >\n                  <ArrowUp className=\"size-4\" aria-hidden=\"true\" />\n                </button>\n                <button\n                  type=\"button\"\n                  aria-label={labels.moveDown(position)}\n                  aria-disabled={index === terms.length - 1 || undefined}\n                  disabled={disabled}\n                  onClick={() => move(index, index + 1)}\n                  className={cn(\n                    ICON_BUTTON_CLASS,\n                    index === terms.length - 1 && \"pointer-events-none opacity-50\"\n                  )}\n                >\n                  <ArrowDown className=\"size-4\" aria-hidden=\"true\" />\n                </button>\n                <button\n                  type=\"button\"\n                  aria-label={labels.remove(position)}\n                  disabled={disabled}\n                  onClick={() => removeTerm(index)}\n                  className={REMOVE_BUTTON_CLASS}\n                >\n                  <Trash2 className=\"size-4\" aria-hidden=\"true\" />\n                </button>\n              </li>\n            )\n          })}\n        </ol>\n      )}\n\n      <div className=\"flex min-w-0 items-center gap-2\">\n        <button\n          type=\"button\"\n          aria-disabled={!canAdd || undefined}\n          disabled={disabled}\n          onClick={addTerm}\n          className={cn(GHOST_BUTTON_CLASS, !canAdd && \"pointer-events-none opacity-50\")}\n        >\n          <Plus className=\"size-4\" aria-hidden=\"true\" />\n          {labels.addSort}\n        </button>\n        {!canAdd && terms.length > 0 ? (\n          <p className=\"text-sm text-muted-foreground\">{labels.allKeysUsed}</p>\n        ) : null}\n      </div>\n\n      {/* Polite: adding, removing and reordering change no value, and a run of move presses should\n          report where the key landed rather than every position it passed through. */}\n      <div aria-live=\"polite\" className=\"sr-only\">\n        {message}\n      </div>\n    </fieldset>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui",
  "docs": "Install any pulld component by name: add \"@pulld\": \"https://pulld.pages.dev/r/{name}.json\" to the registries block in components.json, then `npx shadcn add @pulld/<name>`. All 149 components: https://pulld.pages.dev/?utm_source=cli"
}
