{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-url-state",
  "title": "Data Grid URL State",
  "author": "gridcn",
  "description": "Syncs the gridcn data grid's sort/filter/search, pagination and column layout state with the URL via nuqs (router-agnostic — requires a NuqsAdapter above it). Mount <DataGridUrlState prefix?> inside the provider; the prefix option namespaces the URL keys for multiple grids on one page.",
  "dependencies": [
    "nuqs@^2.10.1"
  ],
  "registryDependencies": [
    "@gridcn/data-grid",
    "@gridcn/data-grid-pagination"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-url-state/data-grid-url-state.tsx",
      "content": "\"use client\";\r\n\r\nimport { Suspense, type ReactNode } from \"react\";\r\nimport { useDataGridUrlState, type UseDataGridUrlStateOptions } from \"./use-data-grid-url-state\";\r\n\r\n/** Public entry point — the only module consumers/docs should import from. */\r\nexport {\r\n  useDataGridUrlState,\r\n  type UseDataGridUrlStateOptions,\r\n  type UseDataGridUrlStateResult,\r\n} from \"./use-data-grid-url-state\";\r\nexport type { UrlLayoutPart } from \"./layout-param\";\r\nexport {\r\n  useDataGridUrlPagination,\r\n  type UseDataGridUrlPaginationOptions,\r\n  type UseDataGridUrlPaginationResult,\r\n} from \"./use-data-grid-url-pagination\";\r\n\r\n/** Props for {@link DataGridUrlState}. */\r\nexport type DataGridUrlStateProps = UseDataGridUrlStateOptions;\r\n\r\n/**\r\n * Renders nothing; syncs the grid's sort/filter/search state with the URL (see\r\n * {@link useDataGridUrlState}). Mount it once inside `<DataGridProvider>`, alongside\r\n * `<DataGridRoot>`/`<DataGridToolbar>`. Requires a nuqs adapter (`NuqsAdapter` from\r\n * `nuqs/adapters/react`, or your framework's) somewhere above it in the tree. It reads the URL\r\n * under its own `<Suspense>` boundary, so a statically prerendered page needs none for it.\r\n *\r\n * @example\r\n * <DataGridProvider data={rows} columns={columns} getRowId={(r) => r.id}>\r\n *   <DataGridUrlState prefix=\"orders\" />\r\n *   <DataGridToolbar><DataGridSearch /></DataGridToolbar>\r\n *   <DataGridRoot>...</DataGridRoot>\r\n * </DataGridProvider>\r\n */\r\nexport function DataGridUrlState(props: DataGridUrlStateProps): ReactNode {\r\n  return (\r\n    <Suspense fallback={null}>\r\n      <UrlStateSync {...props} />\r\n    </Suspense>\r\n  );\r\n}\r\n\r\nfunction UrlStateSync(props: DataGridUrlStateProps): ReactNode {\r\n  useDataGridUrlState(props);\r\n  return null;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/data-grid-url-state.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/filter-operators.ts",
      "content": "import type { BuiltInFilterOperator } from \"@/registry/default/components/data-grid/data-grid\";\r\n\r\n/** The closed set of built-in {@link BuiltInFilterOperator} values, for validating URL input against. */\r\nexport const FILTER_OPERATORS: ReadonlySet<BuiltInFilterOperator> = new Set([\r\n  \"contains\",\r\n  \"notContains\",\r\n  \"equals\",\r\n  \"notEquals\",\r\n  \"startsWith\",\r\n  \"endsWith\",\r\n  \"empty\",\r\n  \"notEmpty\",\r\n  \"gt\",\r\n  \"gte\",\r\n  \"lt\",\r\n  \"lte\",\r\n  \"isBetween\",\r\n  \"isAnyOf\",\r\n  \"isNoneOf\",\r\n] satisfies BuiltInFilterOperator[]);\r\n\r\n/** Narrows an untrusted (URL-decoded) string to {@link BuiltInFilterOperator}. */\r\nexport function isFilterOperator(value: string): value is BuiltInFilterOperator {\r\n  return FILTER_OPERATORS.has(value as BuiltInFilterOperator);\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/filter-operators.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/filter-param.ts",
      "content": "import type { FilterGroup, FilterNode, FilterOperatorInput, FilterSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport { MAX_FILTER_GROUP_DEPTH, filterOperatorInput, groupChildren, isFilterGroup } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { isFilterOperator } from \"./filter-operators\";\nimport { safeDecode } from \"./sort-param\";\n\n/** In-value separator for `isBetween`'s two-part value. `encodeURIComponent` leaves `~` in its unreserved set untouched, so a literal `~` inside a bound must be escaped separately (see {@link encodeRangePart}) to stay unambiguous against the separator. */\nconst RANGE_SEPARATOR = \"~\";\n\n/** In-value separator for the `isAnyOf` and `isNoneOf` choice lists. `encodeURIComponent` escapes a literal `|` inside a choice to `%7C`, so the raw separator can never collide with a choice's own characters. */\nconst ANYOF_SEPARATOR = \"|\";\n\n/** Token for an empty list entry (the \"(Blanks)\" value). `encodeURIComponent` never emits a lone `%`, so no encoded value collides with it, and a sole empty entry stays distinct from an empty list. */\nconst EMPTY_ENTRY_TOKEN = \"%\";\n\n/** A hand-edited URL must not express an unbounded view state; filter segments beyond the cap are dropped. */\nconst MAX_URL_FILTERS = 64;\n\n/** Groups kept from a URL; the `[` and `]` segments are bounded separately from the leaf rows. */\nconst MAX_URL_FILTER_GROUPS = 16;\n\n/** Raw comma-separated segments read before parsing stops; bounds the work a URL of empty segments can cost. */\nconst MAX_URL_FILTER_SEGMENTS = MAX_URL_FILTERS * 4;\n\nconst GROUP_CLOSE = \"]\";\n\n/** Longest decoded filter value (or choice, or range bound) a URL may carry; a segment above it is dropped, never cut, so a link cannot mean another filter. */\nconst MAX_URL_FILTER_VALUE_LENGTH = 1000;\n\n/** Bound for one `isAnyOf` or `isNoneOf` list parsed from a URL when the caller names no per-column limit. */\nconst DEFAULT_MAX_ANYOF_CHOICES = 1000;\n\n/** Options for {@link parseFilterState}. */\nexport type ParseFilterStateOptions = {\n  /** Most entries an `isAnyOf` or `isNoneOf` list of this column may hold, usually its number of `choices`. Returns `undefined` for the 1000 default. */\n  maxChoices?: (columnId: string) => number | undefined;\n  /** The value shape of a custom operator registered on the column, or `undefined` when the column does not register it; a segment with an unregistered operator is dropped. */\n  operatorInput?: (columnId: string, operator: string) => FilterOperatorInput | undefined;\n  /** The lowercased values an `isAnyOf` or `isNoneOf` list of the column may keep, or `undefined` to check nothing. An entry whose lowercased text is outside the set is dropped; the blank entry stays. */\n  choiceValues?: (columnId: string) => ReadonlySet<string> | undefined;\n  /** Receives the number of list entries dropped for falling outside {@link ParseFilterStateOptions.choiceValues}. */\n  onUnknownChoices?: (columnId: string, count: number) => void;\n};\n\n/** Options for {@link serializeFilterState}. */\nexport type SerializeFilterStateOptions = Pick<ParseFilterStateOptions, \"operatorInput\" | \"maxChoices\">;\n\n/** The entries of a set filter list that `choiceValues` allows, compared without case as `isAnyOf` matches; `null` when none of a non-empty list is left. */\nfunction knownChoices(columnId: string, operator: string, value: FilterSpec[\"value\"], options: ParseFilterStateOptions): FilterSpec[\"value\"] | null {\n  const allowed = (operator === \"isAnyOf\" || operator === \"isNoneOf\") && Array.isArray(value) ? options.choiceValues?.(columnId) : undefined;\n  if (!allowed || !Array.isArray(value)) return value;\n  const kept = value.filter((entry) => entry === \"\" || allowed.has(entry.toLowerCase()));\n  if (kept.length === value.length) return value;\n  options.onUnknownChoices?.(columnId, value.length - kept.length);\n  return kept.length === 0 ? null : kept;\n}\n\n/** `encodeURIComponent` plus escaping the one character it doesn't (`~`), so a literal tilde in a bound never collides with {@link RANGE_SEPARATOR}. */\nfunction encodeRangePart(part: string): string {\n  return encodeURIComponent(part).replace(/~/g, \"%7E\");\n}\n\nfunction encodeFilterValue(input: FilterOperatorInput, value: FilterSpec[\"value\"]): string {\n  if (value === undefined) return \"\";\n  if (Array.isArray(value) && input === \"range\") return `${encodeRangePart(value[0])}${RANGE_SEPARATOR}${encodeRangePart(value[1])}`;\n  if (Array.isArray(value)) return value.map((entry) => (entry === \"\" ? EMPTY_ENTRY_TOKEN : encodeURIComponent(entry))).join(ANYOF_SEPARATOR);\n  return encodeURIComponent(value);\n}\n\n/**\n * Compact URL encoding for a {@link FilterNode}[]: comma-separated `columnId:operator:value` triples\n * (`value` omitted for operators with none, e.g. `empty`/`notEmpty`), column id and value\n * percent-encoded. `isBetween`'s two-value range encodes as `min~max`, the `isAnyOf` and `isNoneOf` choice lists as\n * `a|b|c` (each choice percent-encoded, so the raw `|` separator can never collide) — both still\n * one `value` field, so every other operator's format — and any URL generated before those\n * operators existed — round-trips unchanged. An empty list entry encodes as the lone token `%`\n * (`a|%`), so `[\"\"]` differs from `[]`; a part left empty by hand-editing still reads as an empty entry. `filterId` is never serialized — it's a transient\n * list-rendering identity the store re-derives on parse, not part of the filter's meaning.\n * A {@link FilterGroup} is an open segment `[or` or `[and`, its children, and a closing `]` segment;\n * `encodeURIComponent` escapes `[` and `]`, so no id or value can imitate one. A group nests one more\n * group at most; deeper and empty groups are not written.\n *\n * @example serializeFilterState([{ columnId: \"age\", operator: \"gt\", value: \"30\" }])\n * // => \"age:gt:30\"\n * @example serializeFilterState([{ columnId: \"name\", operator: \"empty\" }])\n * // => \"name:empty:\"\n * @example serializeFilterState([{ columnId: \"age\", operator: \"isBetween\", value: [\"10\", \"30\"] }])\n * // => \"age:isBetween:10~30\"\n * @example serializeFilterState([{ columnId: \"status\", operator: \"isAnyOf\", value: [\"new\", \"open\"] }])\n * // => \"status:isAnyOf:new|open\"\n * @example serializeFilterState([{ join: \"or\", filters: [{ columnId: \"a\", operator: \"equals\", value: \"1\" }] }])\n * // => \"[or,a:equals:1,]\"\n * @example serializeFilterState([{ join: \"and\", not: true, filters: [{ columnId: \"a\", operator: \"equals\", value: \"1\" }] }])\n * // => \"[notand,a:equals:1,]\"\n */\nexport function serializeFilterState(filters: readonly FilterNode[], options: SerializeFilterStateOptions = {}): string {\n  const segments: string[] = [];\n  writeNodes(filters, 0, segments, options, false);\n  return segments.join(\",\");\n}\n\n/** Returns true when it skipped a node the reader would not keep. */\nfunction writeNodes(nodes: readonly FilterNode[], depth: number, segments: string[], options: SerializeFilterStateOptions, negated: boolean): boolean {\n  let lost = false;\n  for (const node of nodes) {\n    if (!isFilterGroup(node)) {\n      const input = isFilterOperator(node.operator) ? filterOperatorInput(node.operator) : (options.operatorInput?.(node.columnId, node.operator) ?? \"single\");\n      if (!readerKeeps(node, options, negated)) {\n        lost = true;\n        continue;\n      }\n      segments.push(`${encodeURIComponent(node.columnId)}:${encodeURIComponent(node.operator)}:${encodeFilterValue(input, node.value)}`);\n      continue;\n    }\n    const children = groupChildren(node);\n    if (depth >= MAX_FILTER_GROUP_DEPTH || children.length === 0) {\n      lost = true;\n      continue;\n    }\n    const start = segments.length;\n    const own = node.not === true;\n    segments.push(`[${own ? \"not\" : \"\"}${node.join === \"or\" ? \"or\" : \"and\"}`);\n    const childLost = writeNodes(children, depth + 1, segments, options, negated || own);\n    if (childLost) lost = true;\n    // a negated group missing a term would match other rows, so it is not written\n    if (segments.length === start + 1 || (own && childLost)) segments.length = start;\n    else segments.push(GROUP_CLOSE);\n  }\n  return lost;\n}\n\nfunction valueStrings(value: FilterSpec[\"value\"]): readonly string[] {\n  if (Array.isArray(value)) return value;\n  return typeof value === \"string\" ? [value] : [];\n}\n\n/** True unless {@link parseFilterState} would drop the leaf. An `isAnyOf` list over its bound stays and the reader cuts it. */\nfunction readerKeeps(node: FilterSpec, options: SerializeFilterStateOptions, negated: boolean): boolean {\n  if (valueStrings(node.value).some((part) => part.length > MAX_URL_FILTER_VALUE_LENGTH)) return false;\n  if ((node.operator !== \"isNoneOf\" && !(negated && node.operator === \"isAnyOf\")) || !Array.isArray(node.value)) return true;\n  return node.value.length <= (options.maxChoices?.(node.columnId) ?? DEFAULT_MAX_ANYOF_CHOICES);\n}\n\n/** Sentinel distinguishing \"decode failed, drop the segment\" from a legitimately-empty decoded value (`\"\"`). */\nconst DECODE_FAILED = Symbol(\"decode-failed\");\n\n/** Decodes a segment's value part per `operator`: `isBetween` splits on {@link RANGE_SEPARATOR} into a tuple, `isAnyOf` and `isNoneOf` split on {@link ANYOF_SEPARATOR} into a choice list (empty value = empty list), everything else stays a plain string. Malformed input (wrong tuple arity, bad percent-encoding) returns {@link DECODE_FAILED}. */\nfunction decodeFilterValue(operator: string, input: FilterOperatorInput, raw: string, maxChoices: number, negated: boolean): FilterSpec[\"value\"] | typeof DECODE_FAILED {\n  if (input === \"list\") {\n    if (raw === \"\") return [];\n    const parts: string[] = [];\n    // one entry past the bound tells an over-long list from an exact fit without splitting the whole value\n    for (const rawPart of raw.split(ANYOF_SEPARATOR, maxChoices + 1)) {\n      if (parts.length >= maxChoices) {\n        // a truncated exclusion list would match more rows than the link meant\n        if (operator === \"isNoneOf\" || negated) return DECODE_FAILED;\n        break;\n      }\n      const decoded = rawPart === EMPTY_ENTRY_TOKEN ? \"\" : safeDecode(rawPart);\n      if (decoded === null || decoded.length > MAX_URL_FILTER_VALUE_LENGTH) return DECODE_FAILED;\n      parts.push(decoded);\n    }\n    return parts;\n  }\n  if (input !== \"range\") {\n    const decoded = safeDecode(raw);\n    return decoded === null || decoded.length > MAX_URL_FILTER_VALUE_LENGTH ? DECODE_FAILED : decoded;\n  }\n  const parts = raw.split(RANGE_SEPARATOR);\n  if (parts.length !== 2) return DECODE_FAILED;\n  const [min, max] = parts.map(safeDecode);\n  if (min == null || max == null || min.length > MAX_URL_FILTER_VALUE_LENGTH || max.length > MAX_URL_FILTER_VALUE_LENGTH) return DECODE_FAILED;\n  return [min, max];\n}\n\n/**\n * Inverse of {@link serializeFilterState}. Malformed segments (unknown operator, empty/undecodable\n * column id, wrong field count, malformed `isBetween` range or `isAnyOf` / `isNoneOf` list) are dropped silently\n * rather than throwing — a corrupt/hand-edited URL degrades to fewer filters, never an error.\n * Parsing stops after 256 raw segments. The parsed tree is capped at 64 filter rows and 16 groups, and each `isAnyOf`\n * list at `options.maxChoices(columnId)` entries (1000 by default), and keeps only the list entries `options.choiceValues` allows; a segment whose decoded value, choice, or range bound\n * exceeds 1,000 characters is dropped; the first segments win, so a\n * hand-edited URL cannot express an unbounded filter set. A group opener deeper than the nesting cap,\n * with an unknown join, or over the group cap drops its whole subtree; a stray `]` is ignored, an\n * unclosed group closes at the end, and an empty group is dropped. An `isNoneOf` list over its bound drops\n * the whole segment. A negated group (`[notand`, `[notor`) that loses a child or is left unclosed is dropped whole.\n * Every filter parses without a `filterId`; the store backfills a fresh stable one on the next sync.\n *\n * @example parseFilterState(\"age:gt:30\") // => [{ columnId: \"age\", operator: \"gt\", value: \"30\" }]\n * @example parseFilterState(\"name:empty:\") // => [{ columnId: \"name\", operator: \"empty\", value: \"\" }]\n * @example parseFilterState(\"age:isBetween:10~30\") // => [{ columnId: \"age\", operator: \"isBetween\", value: [\"10\", \"30\"] }]\n * @example parseFilterState(\"status:isAnyOf:new|open\") // => [{ columnId: \"status\", operator: \"isAnyOf\", value: [\"new\", \"open\"] }]\n * @example parseFilterState(\"garbage\") // => []\n */\nexport function parseFilterState(raw: string, options: ParseFilterStateOptions = {}): FilterNode[] {\n  if (!raw) return [];\n  type Frame = { join: FilterGroup[\"join\"]; not: boolean; filters: FilterNode[]; dropped: boolean; lostChild: boolean };\n  const root: Frame = { join: \"and\", not: false, filters: [], dropped: false, lostChild: false };\n  const stack: Frame[] = [root];\n  let leaves = 0;\n  let groups = 0;\n  const loseChild = () => stack.forEach((frame) => (frame.lostChild = true));\n  const closeTop = (closed: boolean) => {\n    const frame = stack.pop()!;\n    // a negated group missing a term would match different rows, so it goes whole\n    if (frame.dropped || frame.filters.length === 0 || (frame.not && (frame.lostChild || !closed))) return loseChild();\n    stack[stack.length - 1]!.filters.push(frame.not ? { join: frame.join, not: true, filters: frame.filters } : { join: frame.join, filters: frame.filters });\n  };\n  let start = 0;\n  for (let read = 0; read < MAX_URL_FILTER_SEGMENTS && start <= raw.length && leaves < MAX_URL_FILTERS; read++) {\n    const comma = raw.indexOf(\",\", start);\n    const end = comma === -1 ? raw.length : comma;\n    const segment = raw.slice(start, end);\n    start = end + 1;\n    if (segment === GROUP_CLOSE) {\n      if (stack.length > 1) closeTop(true);\n      continue;\n    }\n    if (segment.startsWith(\"[\")) {\n      const join = segment === \"[or\" || segment === \"[notor\" ? \"or\" : segment === \"[and\" || segment === \"[notand\" ? \"and\" : undefined;\n      const parent = stack[stack.length - 1]!;\n      const dropped = parent.dropped || join === undefined || stack.length > MAX_FILTER_GROUP_DEPTH || groups >= MAX_URL_FILTER_GROUPS;\n      if (!dropped) groups++;\n      stack.push({ join: join ?? \"and\", not: segment.startsWith(\"[not\"), filters: [], dropped, lostChild: false });\n      continue;\n    }\n    const parts = segment.split(\":\");\n    if (parts.length !== 3) { loseChild(); continue; }\n    const [columnId, operator, rawValue] = parts;\n    if (!columnId || operator === undefined || rawValue === undefined) { loseChild(); continue; }\n    const decodedId = safeDecode(columnId);\n    const decodedOperator = safeDecode(operator);\n    if (decodedId === null || decodedId === \"\" || decodedOperator === null) { loseChild(); continue; }\n    const input = isFilterOperator(decodedOperator) ? filterOperatorInput(decodedOperator) : options.operatorInput?.(decodedId, decodedOperator);\n    if (input === undefined) { loseChild(); continue; }\n    const value = decodeFilterValue(decodedOperator, input, rawValue, options.maxChoices?.(decodedId) ?? DEFAULT_MAX_ANYOF_CHOICES, stack.some((open) => open.not));\n    if (value === DECODE_FAILED) { loseChild(); continue; }\n    const frame = stack[stack.length - 1]!;\n    if (frame.dropped) { loseChild(); continue; }\n    const known = knownChoices(decodedId, decodedOperator, value, options);\n    if (known === null) { loseChild(); continue; }\n    frame.filters.push({ columnId: decodedId, operator: decodedOperator, value: known });\n    leaves++;\n  }\n  while (stack.length > 1) closeTop(false);\n  return root.filters;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/filter-param.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/join-param.ts",
      "content": "import type { FilterJoinOperator } from \"@/registry/default/components/data-grid/data-grid\";\n\n/** Reads a legacy `join` URL param. Only exactly `\"or\"` means `\"or\"`; an absent, empty, or malformed value is `\"and\"`. */\nexport function parseLegacyJoin(raw: string): FilterJoinOperator {\n  return raw === \"or\" ? \"or\" : \"and\";\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/join-param.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/layout-param.ts",
      "content": "import type { ColumnLayout } from \"@/registry/default/components/data-grid/data-grid\";\nimport { safeDecode } from \"./sort-param\";\n\n/** The parts of a {@link ColumnLayout} the URL can carry. */\nexport type UrlLayoutPart = \"order\" | \"hidden\" | \"widths\" | \"pins\";\n\n/** Segments read from one layout param; a forged link cannot allocate past it. */\nexport const MAX_URL_LAYOUT_COLUMNS = 1024;\n\n/** A layout param longer than this is ignored as a whole. */\nexport const MAX_URL_LAYOUT_PARAM_LENGTH = 16_384;\n\nconst NONE = \"-\";\nconst WIDTH_PATTERN = /^\\d{1,5}$/;\n\nfunction encodeId(id: string): string {\n  return id === NONE ? \"%2D\" : encodeURIComponent(id);\n}\n\nfunction serializePair(id: string, value: string | number): string {\n  return `${encodeId(id)}:${value}`;\n}\n\n/**\n * Compact URL encoding of one {@link ColumnLayout} part: `order` and `hidden` are comma-separated\n * column ids, `widths` is `id:px` pairs, `pins` is `id:s` / `id:e` pairs (start / end; the legacy\n * `l` / `r` codes are read, not written). Ids are percent-encoded.\n * An empty `hidden` or `pins` part is written as `-`.\n *\n * @example serializeLayoutPart(\"widths\", { ...layout, widths: { name: 240 } }) // => \"name:240\"\n */\nexport function serializeLayoutPart(part: UrlLayoutPart, layout: ColumnLayout): string {\n  switch (part) {\n    case \"order\":\n      return layout.order.map(encodeId).join(\",\");\n    case \"hidden\":\n      return layout.hidden.length === 0 ? NONE : layout.hidden.map(encodeId).join(\",\");\n    case \"widths\":\n      return Object.entries(layout.widths)\n        .map(([id, width]) => serializePair(id, Math.round(width)))\n        .join(\",\");\n    case \"pins\": {\n      const pins = Object.entries(layout.pins);\n      return pins.length === 0 ? NONE : pins.map(([id, side]) => serializePair(id, side === \"start\" ? \"s\" : \"e\")).join(\",\");\n    }\n    default:\n      return \"\";\n  }\n}\n\nfunction decodeId(raw: string): string | null {\n  const id = raw === \"\" ? null : safeDecode(raw);\n  return id === \"\" ? null : id;\n}\n\nfunction parseIds(raw: string): string[] {\n  const seen = new Set<string>();\n  for (const segment of raw.split(\",\", MAX_URL_LAYOUT_COLUMNS)) {\n    const id = decodeId(segment);\n    if (id !== null) seen.add(id);\n  }\n  return [...seen];\n}\n\nfunction parsePairs<V>(raw: string, parseValue: (value: string) => V | null): [string, V][] {\n  const seen = new Set<string>();\n  const pairs: [string, V][] = [];\n  for (const segment of raw.split(\",\", MAX_URL_LAYOUT_COLUMNS)) {\n    const colon = segment.indexOf(\":\");\n    if (colon < 0 || segment.indexOf(\":\", colon + 1) >= 0) continue;\n    const id = decodeId(segment.slice(0, colon));\n    if (id === null || seen.has(id)) continue;\n    const value = parseValue(segment.slice(colon + 1));\n    if (value === null) continue;\n    seen.add(id);\n    pairs.push([id, value]);\n  }\n  return pairs;\n}\n\n/**\n * Inverse of {@link serializeLayoutPart}. Returns only the given part: `{}` when the param is\n * empty or longer than {@link MAX_URL_LAYOUT_PARAM_LENGTH}, an empty part (such as `{ order: [] }`)\n * when it holds nothing valid. Reads at most\n * {@link MAX_URL_LAYOUT_COLUMNS} segments; undecodable, empty, and repeated ids and malformed values\n * are dropped (the first segment of an id wins). Never throws.\n *\n * @example parseLayoutPart(\"pins\", \"name:s,age:e\") // => { pins: { name: \"start\", age: \"end\" } }\n */\nexport function parseLayoutPart(part: UrlLayoutPart, raw: string): Partial<ColumnLayout> {\n  if (raw === \"\" || raw.length > MAX_URL_LAYOUT_PARAM_LENGTH) return {};\n  switch (part) {\n    case \"order\":\n      return { order: parseIds(raw) };\n    case \"hidden\":\n      return { hidden: raw === NONE ? [] : parseIds(raw) };\n    case \"widths\":\n      return { widths: Object.fromEntries(parsePairs(raw, (v) => (WIDTH_PATTERN.test(v) ? Number(v) : null))) };\n    case \"pins\":\n      return {\n        pins: Object.fromEntries(parsePairs(raw, (v) => (v === \"l\" || v === \"s\" ? \"start\" : v === \"r\" || v === \"e\" ? \"end\" : null))) as ColumnLayout[\"pins\"],\n      };\n    default:\n      return {};\n  }\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/layout-param.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/page-param.ts",
      "content": "/** Absolute ceiling for the URL `page` param: a page number beyond it is a typo or an attack, and parses as 1 like any other invalid value. */\r\nexport const MAX_URL_PAGE = 1_000_000;\r\n\r\n/**\r\n * URL encoding for the 1-based `page` number: the plain decimal string, omitted entirely when\r\n * `page` is 1 (the default), matching `join`'s omit-at-default convention.\r\n *\r\n * @example serializePage(1) // => \"\" (the default; omitted from the URL)\r\n * @example serializePage(3) // => \"3\"\r\n */\r\nexport function serializePage(page: number): string {\r\n  return page <= 1 ? \"\" : String(page);\r\n}\r\n\r\n/**\r\n * Inverse of {@link serializePage}. Anything that isn't a positive integer (absent, empty,\r\n * negative, fractional, hand-edited garbage) parses as `1` — never throws.\r\n *\r\n * @example parsePage(\"3\") // => 3\r\n * @example parsePage(\"\") // => 1\r\n * @example parsePage(\"garbage\") // => 1\r\n */\r\nexport function parsePage(raw: string): number {\r\n  const n = Number(raw);\r\n  return raw !== \"\" && Number.isInteger(n) && n >= 1 && n <= MAX_URL_PAGE ? n : 1;\r\n}\r\n\r\n/**\r\n * URL encoding for `pageSize`: the plain decimal string, omitted when it equals `defaultPageSize`.\r\n *\r\n * @example serializePageSize(25, 25) // => \"\" (matches the default; omitted from the URL)\r\n * @example serializePageSize(50, 25) // => \"50\"\r\n */\r\nexport function serializePageSize(pageSize: number, defaultPageSize: number): string {\r\n  return pageSize === defaultPageSize ? \"\" : String(pageSize);\r\n}\r\n\r\n/**\r\n * Inverse of {@link serializePageSize}. Falls back to `defaultPageSize` for anything that isn't a\r\n * positive integer. When `allowedSizes` is given, a parsed value outside that list also falls back\r\n * to `defaultPageSize` — the URL cannot force a page size the consumer didn't offer.\r\n *\r\n * @example parsePageSize(\"50\", 25) // => 50\r\n * @example parsePageSize(\"\", 25) // => 25\r\n * @example parsePageSize(\"999\", 25, [10, 25, 50]) // => 25 (not in the allowed list)\r\n */\r\nexport function parsePageSize(raw: string, defaultPageSize: number, allowedSizes?: readonly number[]): number {\r\n  const n = Number(raw);\r\n  if (raw === \"\" || !Number.isInteger(n) || n < 1) return defaultPageSize;\r\n  if (allowedSizes && !allowedSizes.includes(n)) return defaultPageSize;\r\n  return n;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/page-param.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/group-param.ts",
      "content": "import { MAX_GROUP_LEVELS } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport { safeDecode } from \"./sort-param\";\r\n\r\n/** Comma-separated column ids, outermost group first, each percent-encoded (ids may contain `,`). */\r\nexport function serializeGroupBy(groupBy: readonly string[]): string {\r\n  return groupBy.map(encodeURIComponent).join(\",\");\r\n}\r\n\r\n/**\r\n * Inverse of {@link serializeGroupBy}. Reads at most the first 4 raw segments; an empty or\r\n * undecodable segment and a repeated id drop. Column checks belong to the caller.\r\n *\r\n * @example parseGroupBy(\"region,team\") // => [\"region\", \"team\"]\r\n */\r\nexport function parseGroupBy(raw: string): string[] {\r\n  const ids: string[] = [];\r\n  for (const segment of raw.split(\",\", MAX_GROUP_LEVELS)) {\r\n    const id = safeDecode(segment);\r\n    if (id && !ids.includes(id)) ids.push(id);\r\n  }\r\n  return ids;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/group-param.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/prefixed-key.ts",
      "content": "import { useEffect, useRef } from \"react\";\r\nimport { isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\n/** Namespaces a URL param key for multi-grid pages, e.g. `prefixedKey(\"orders\", \"sort\")` => `\"orders_sort\"`. */\r\nexport function prefixedKey(prefix: string | undefined, key: string): string {\r\n  return prefix ? `${prefix}_${key}` : key;\r\n}\r\n\r\nconst mountedByScope = new Map<string, number>();\r\n\r\n/** Warns once in development when a second mounted hook of the same kind uses the prefix: each instance applies the URL once on mount, so two grids on one key never stay linked. */\r\nexport function useWarnSharedPrefix(hook: \"useDataGridUrlState\" | \"useDataGridUrlPagination\", prefix: string | undefined): void {\r\n  const warned = useRef(false);\r\n  useEffect(() => {\r\n    const scope = `${hook}:${prefix ?? \"\"}`;\r\n    const others = mountedByScope.get(scope) ?? 0;\r\n    mountedByScope.set(scope, others + 1);\r\n    if (others > 0 && !warned.current && isDev()) {\r\n      warned.current = true;\r\n      console.warn(`[data-grid-url-state] two ${hook} instances use ${prefix ? `the prefix \"${prefix}\"` : \"no prefix\"}; give each grid its own prefix`);\r\n    }\r\n    return () => {\r\n      const left = (mountedByScope.get(scope) as number) - 1;\n      if (left > 0) mountedByScope.set(scope, left);\n      else mountedByScope.delete(scope);\r\n    };\r\n  }, [hook, prefix]);\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/prefixed-key.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/sort-param.ts",
      "content": "import type { SortSpec } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport { MAX_SPEC_SORTS } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\n/** A hand-edited URL must not express an unbounded sort list; segments beyond the cap are dropped. */\r\n/** Raw segments read from the param, so a forged link of millions of commas allocates nothing past this. */\r\nconst MAX_URL_SORT_SEGMENTS = 256;\r\n\r\n/**\r\n * Compact URL encoding for {@link SortSpec}[]: comma-separated `columnId:direction` pairs,\r\n * column id percent-encoded (ids are consumer-controlled and may contain `,`/`:`).\r\n *\r\n * @example serializeSortState([{ columnId: \"name\", direction: \"asc\" }, { columnId: \"age\", direction: \"desc\" }])\r\n * // => \"name:asc,age:desc\"\r\n */\r\nexport function serializeSortState(sorts: readonly SortSpec[]): string {\r\n  return sorts.map((s) => `${encodeURIComponent(s.columnId)}:${s.direction}`).join(\",\");\r\n}\r\n\r\n/** `decodeURIComponent` throws on malformed `%` sequences a hand-edited URL can contain — never let that surface. */\r\nexport function safeDecode(value: string): string | null {\r\n  try {\r\n    return decodeURIComponent(value);\r\n  } catch {\r\n    return null;\r\n  }\r\n}\r\n\r\n/**\r\n * Inverse of {@link serializeSortState}. Malformed segments (missing direction, bad direction\r\n * value, empty/undecodable column id) are dropped silently rather than throwing — a corrupt/hand-edited\r\n * URL degrades to fewer sorts, never an error. A column id repeated in the URL yields one sort entry\r\n * (the first segment wins), matching the grid's one-direction-per-column sort model. The parsed\r\n * list is capped at 64 sorts.\r\n *\r\n * @example parseSortState(\"name:asc,age:desc\") // => [{ columnId: \"name\", direction: \"asc\" }, { columnId: \"age\", direction: \"desc\" }]\r\n * @example parseSortState(\"garbage\") // => []\r\n */\r\nexport function parseSortState(raw: string): SortSpec[] {\r\n  if (!raw) return [];\r\n  const sorts: SortSpec[] = [];\r\n  // one sort entry per column (the grid's sort model) — a repeated column id keeps its first segment\r\n  const seenColumns = new Set<string>();\r\n  for (const segment of raw.split(\",\", MAX_URL_SORT_SEGMENTS)) {\r\n    if (sorts.length >= MAX_SPEC_SORTS) break;\r\n    const [columnId, direction] = segment.split(\":\");\r\n    if (!columnId || (direction !== \"asc\" && direction !== \"desc\")) continue;\r\n    const decoded = safeDecode(columnId);\r\n    if (decoded === null || decoded === \"\") continue;\r\n    if (seenColumns.has(decoded)) continue;\r\n    seenColumns.add(decoded);\r\n    sorts.push({ columnId: decoded, direction });\r\n  }\r\n  return sorts;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/sort-param.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/use-data-grid-url-pagination.ts",
      "content": "\"use client\";\n\nimport { useCallback, useMemo } from \"react\";\nimport { useQueryState } from \"nuqs\";\nimport { DEFAULT_PAGE_SIZES } from \"@/registry/default/components/data-grid-pagination/pagination-math\";\nimport { parsePage, parsePageSize, serializePage, serializePageSize } from \"./page-param\";\nimport { prefixedKey, useWarnSharedPrefix } from \"./prefixed-key\";\n\n/** Options for {@link useDataGridUrlPagination}. */\nexport type UseDataGridUrlPaginationOptions = {\n  /** Namespaces the `page`/`pageSize` URL keys as `<prefix>_<key>`, so multiple grids can coexist on one page. */\n  prefix?: string;\n  /** `pageSize` this many is omitted from the URL. Also the fallback for an invalid URL value. Default: the first of `pageSizeOptions` (10 with the default list). */\n  defaultPageSize?: number;\n  /** A `pageSize` URL value outside this list (default: the pager sizes 10, 25, 50, 100) falls back to `defaultPageSize`. */\n  pageSizeOptions?: readonly number[];\n};\n\n/** The controlled pair: spread it onto `DataGridProvider` (a grid that pages its view) or into `useDataGridServerPager`. */\nexport type UseDataGridUrlPaginationResult = {\n  page: number;\n  pageSize: number;\n  /** The `pageSizeOptions` the URL parsing enforces (`pageSizeOptions` or the pager default) — `DataGridProvider` takes it, so the bar's select and the URL allow-list never diverge. */\n  pageSizeOptions: readonly number[];\n  onPageChange: (page: number) => void;\n  /** `null` (a grid that turns paging off) returns the URL to `defaultPageSize`; the URL has no \"every row\" size. */\n  onPageSizeChange: (pageSize: number | null) => void;\n};\n\n/**\n * Syncs `page`/`pageSize` with the URL via nuqs, with no dependency on the grid's store (it\n * reads only the page math of `data-grid-pagination`) — it owns two URL-backed numbers and hands back the controlled pair that\n * `DataGridProvider` and `useDataGridServerPager` both accept.\n *\n * The hook bounds the URL values but not the page range: the pager that knows the row count clamps an\n * out-of-range `page` and reports it through `onPageChange`.\n *\n * `page` is 1-based and omitted from the URL at 1; `pageSize` is omitted when it equals\n * `defaultPageSize`. Both writes use `history: \"replace\"`, matching this add-on's sort/filter/\n * search params — paging through results never pollutes back/forward history. Invalid or\n * out-of-range URL values (negative, fractional, a `pageSize` outside `pageSizeOptions`) clamp to\n * the default rather than throwing, the same posture as this add-on's other parsers.\n *\n * @example\n * const url = useDataGridUrlPagination();\n * <DataGridProvider data={rows} {...url}><DataGridPaginationBar /></DataGridProvider>\n */\nexport function useDataGridUrlPagination(options: UseDataGridUrlPaginationOptions = {}): UseDataGridUrlPaginationResult {\n  const { prefix, pageSizeOptions } = options;\n  useWarnSharedPrefix(\"useDataGridUrlPagination\", prefix);\n  const resolvedPageSizeOptions: readonly number[] = pageSizeOptions ?? DEFAULT_PAGE_SIZES;\n  const defaultPageSize = options.defaultPageSize ?? resolvedPageSizeOptions[0]!;\n\n  const [pageParam, setPageParam] = useQueryState(prefixedKey(prefix, \"page\"), {\n    defaultValue: \"\",\n    parse: (v) => v,\n    serialize: (v) => v,\n    history: \"replace\",\n  });\n  const [pageSizeParam, setPageSizeParam] = useQueryState(prefixedKey(prefix, \"pageSize\"), {\n    defaultValue: \"\",\n    parse: (v) => v,\n    serialize: (v) => v,\n    history: \"replace\",\n  });\n\n  // the URL value is always gated by a size list, so ?pageSize=100000000 can never force an unbounded fetch\n  const page = parsePage(pageParam);\n  const pageSize = parsePageSize(pageSizeParam, defaultPageSize, resolvedPageSizeOptions);\n  const onPageChange = useCallback(\n    (next: number) => {\n      void setPageParam(serializePage(next) || null);\n    },\n    [setPageParam],\n  );\n\n  const onPageSizeChange = useCallback(\n    (next: number | null) => {\n      void setPageSizeParam(next === null ? null : serializePageSize(next, defaultPageSize) || null);\n      // A page number is only valid for the size it was chosen at: a page-size change resets the page to 1 (the URL composition's contract).\n      void setPageParam(null);\n    },\n    [setPageSizeParam, setPageParam, defaultPageSize],\n  );\n\n  return useMemo(\n    () => ({ page, pageSize, pageSizeOptions: resolvedPageSizeOptions, onPageChange, onPageSizeChange }),\n    [page, pageSize, resolvedPageSizeOptions, onPageChange, onPageSizeChange],\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/use-data-grid-url-pagination.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-url-state/use-data-grid-url-state.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useRef } from \"react\";\nimport { useQueryState } from \"nuqs\";\nimport {\n  useDataGridActions,\n  useDataGridAllColumns,\n  useDataGridFilterState,\n  useDataGridSearchText,\n  useDataGridSortState,\n} from \"@/registry/default/components/data-grid/data-grid\";\nimport { MAX_SPEC_SEARCH_LENGTH, isDev, pruneFilterSpecs, resolveCustomFilterOperators, setFilterListBound, setFilterValuesOf, useDataGridSelector, useDataGridStoreApi } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport type { ColumnLayout, FilterOperatorInput } from \"@/registry/default/components/data-grid/data-grid\";\nimport { serializeSortState, parseSortState } from \"./sort-param\";\nimport { serializeGroupBy, parseGroupBy } from \"./group-param\";\nimport { parseLayoutPart, serializeLayoutPart, type UrlLayoutPart } from \"./layout-param\";\nimport { serializeFilterState, parseFilterState } from \"./filter-param\";\nimport { parseLegacyJoin } from \"./join-param\";\nimport { prefixedKey, useWarnSharedPrefix } from \"./prefixed-key\";\n\ntype UrlSpecPart = \"sort\" | \"filter\" | \"search\" | \"group\";\n\ntype UrlParams = Record<\"sort\" | \"group\" | \"filter\" | \"join\" | \"q\" | UrlLayoutPart, string>;\n\n// Filter values and search text can hold personal data; a URL leaks them into history, logs, and Referer, so they sync only on request.\nconst DEFAULT_SPEC_PARTS: readonly UrlSpecPart[] = [\"sort\", \"group\"];\n\nfunction choiceBoundsOf(columns: readonly { id: string; options?: unknown }[], state: Parameters<typeof setFilterListBound>[0]): Map<string, number | undefined> {\n  return new Map(columns.map((c) => [c.id, setFilterListBound(state, c)]));\n}\n\nconst DEFAULT_LAYOUT_PARTS: readonly UrlLayoutPart[] = [\"order\", \"hidden\"];\n\nconst LAYOUT_KEYS: Record<UrlLayoutPart, string> = { order: \"cols\", hidden: \"hide\", widths: \"widths\", pins: \"pins\" };\n\nfunction readUrlParams(prefix: string | undefined): UrlParams {\n  const query = new URLSearchParams(window.location.search);\n  const read = (key: string) => query.get(prefixedKey(prefix, key)) ?? \"\";\n  return { sort: read(\"sort\"), group: read(\"group\"), filter: read(\"filter\"), join: read(\"join\"), q: read(\"q\"), order: read(LAYOUT_KEYS.order), hidden: read(LAYOUT_KEYS.hidden), widths: read(LAYOUT_KEYS.widths), pins: read(LAYOUT_KEYS.pins) };\n}\n\nfunction countUnknownLayoutIds(part: Partial<ColumnLayout>, known: ReadonlySet<string>): number {\n  const ids = part.order ?? part.hidden ?? Object.keys(part.widths ?? part.pins ?? {});\n  return ids.filter((id) => !known.has(id)).length;\n}\n\n/** Dev-only warning, core's `warnDev` pattern with this add-on's own prefix (import-boundary rule: add-ons import only from core's block-root barrel). */\nfunction warnDev(message: string): void {\n  if (isDev()) console.warn(`[data-grid-url-state] ${message}`);\n}\n\n/** Options for {@link useDataGridUrlState}. */\nexport type UseDataGridUrlStateOptions = {\n  /** Namespaces the `sort`/`group`/`filter`/`join`/`q` URL keys and the layout keys (`cols`, `hide`, `widths`, `pins`) as `<prefix>_<key>`, so multiple grids can coexist on one page. */\n  prefix?: string;\n  /**\n   * View-spec parts synced to the URL: `sort` (`sort`), `group` (`group`: the `groupBy` columns; expanded groups stay out), `filter` (`filter` and the top-level `join`), and `search` (`q`).\n   * `[]` turns spec sync off. Default `[\"sort\", \"group\"]`: filter values and search text reach the URL, browser history, server logs, and `Referer` only when you list `\"filter\"` and `\"search\"`.\n   */\n  spec?: readonly UrlSpecPart[];\n  /**\n   * Layout parts synced to the URL under `cols` (`order`), `hide` (`hidden`), `widths`, and `pins`.\n   * A part is written only while it differs from the layout the grid started with. `[]` turns\n   * layout sync off. Default `[\"order\", \"hidden\"]`.\n   */\n  layout?: readonly UrlLayoutPart[];\n  /**\n   * Applies the URL to the grid when the user navigates back or forward (`popstate`), as `applyFromUrl()` does.\n   * Set `false` to apply the URL yourself. Default `true`.\n   */\n  enableNavigationSync?: boolean;\n};\n\n/** Result of {@link useDataGridUrlState}. */\nexport type UseDataGridUrlStateResult = {\n  /**\n   * Re-applies the current URL params to the store, including the dropped-column warning. Unlike\n   * the mount apply, a param missing from the URL clears its sort, filter, or search, and a\n   * missing layout param resets that synced layout part to the layout the grid started with. Call\n   * it when the URL changed outside the grid's own writes —\n   * back/forward, a framework `setSearchParams`, or a query-only route change — since mount\n   * applies exactly once and the store is the source of truth afterwards. Back and forward call it\n   * already unless `enableNavigationSync` is `false`.\n   */\n  applyFromUrl: () => void;\n};\n\n/**\n * Syncs the grid store's `sortState`/`filterState`/`searchText` with the URL via\n * nuqs: applies any URL params to the store once on mount, then writes store changes back to the\n * URL (replacing, never pushing, history entries). Requires a `NuqsAdapter` (or the testing\n * adapter) above it in the tree — nuqs itself is router-agnostic. Writes are not delayed: the search\n * input debounces typing and nuqs coalesces the `history.replaceState` calls. A filter group lives inside the `filter` param. The join of the top-level\n * list is the `join` param: `join=or` when the list joins with \"or\", absent for \"and\".\n *\n * The URL→store direction runs on mount and on back/forward (`enableNavigationSync`); otherwise the store\n * wins. `applyFromUrl()` re-runs the apply when the URL changed outside the grid's own writes.\n */\nexport function useDataGridUrlState(options: UseDataGridUrlStateOptions = {}): UseDataGridUrlStateResult {\n  const { prefix, layout = DEFAULT_LAYOUT_PARTS, spec: specParts = DEFAULT_SPEC_PARTS, enableNavigationSync = true } = options;\n  const syncSort = specParts.includes(\"sort\");\n  const syncGroup = specParts.includes(\"group\");\n  const syncFilter = specParts.includes(\"filter\");\n  const syncSearch = specParts.includes(\"search\");\n  useWarnSharedPrefix(\"useDataGridUrlState\", prefix);\n  const layoutParts = layout.join(\",\");\n  const actions = useDataGridActions();\n  const storeApi = useDataGridStoreApi();\n  const allColumns = useDataGridAllColumns();\n  const warnedChoiceColumns = useRef(new Set<string>());\n  const operatorInput = useCallback(\n    (columnId: string, operator: string): FilterOperatorInput | undefined => {\n      const column = allColumns.find((c) => c.id === columnId);\n      if (!column) return undefined;\n      const custom = resolveCustomFilterOperators(column, column.type ? storeApi.getState().cellTypes[column.type] : undefined).get(operator);\n      return custom && (custom.input ?? \"single\");\n    },\n    [allColumns, storeApi],\n  );\n  const sortState = useDataGridSortState();\n  const groupBy = useDataGridSelector((s) => s.groupBy);\n  const filterState = useDataGridFilterState();\n  const filterJoin = useDataGridSelector((s) => s.filterJoin);\n  const searchText = useDataGridSearchText();\n  const columnLayout = useDataGridSelector((s) => s.columnLayout);\n\n  const [sortParam, setSortParam] = useQueryState(prefixedKey(prefix, \"sort\"), {\n    defaultValue: \"\",\n    parse: (v) => v,\n    serialize: (v) => v,\n    history: \"replace\",\n  });\n  const [groupParam, setGroupParam] = useQueryState(prefixedKey(prefix, \"group\"), {\n    defaultValue: \"\",\n    parse: (v) => v,\n    serialize: (v) => v,\n    history: \"replace\",\n  });\n  const [filterParam, setFilterParam] = useQueryState(prefixedKey(prefix, \"filter\"), {\n    defaultValue: \"\",\n    parse: (v) => v,\n    serialize: (v) => v,\n    history: \"replace\",\n  });\n  const [joinParam, setJoinParam] = useQueryState(prefixedKey(prefix, \"join\"), {\n    defaultValue: \"\",\n    parse: (v) => v,\n    serialize: (v) => v,\n    history: \"replace\",\n  });\n  const [searchParam, setSearchParam] = useQueryState(prefixedKey(prefix, \"q\"), {\n    defaultValue: \"\",\n    parse: (v) => v,\n    serialize: (v) => v,\n    history: \"replace\",\n  });\n  const layoutQueryOptions = { defaultValue: \"\", parse: (v: string) => v, serialize: (v: string) => v, history: \"replace\" } as const;\n  const [orderParam, setOrderParam] = useQueryState(prefixedKey(prefix, LAYOUT_KEYS.order), layoutQueryOptions);\n  const [hiddenParam, setHiddenParam] = useQueryState(prefixedKey(prefix, LAYOUT_KEYS.hidden), layoutQueryOptions);\n  const [widthsParam, setWidthsParam] = useQueryState(prefixedKey(prefix, LAYOUT_KEYS.widths), layoutQueryOptions);\n  const [pinsParam, setPinsParam] = useQueryState(prefixedKey(prefix, LAYOUT_KEYS.pins), layoutQueryOptions);\n  const currentParams: UrlParams = { sort: sortParam, group: groupParam, filter: filterParam, join: joinParam, q: searchParam, order: orderParam, hidden: hiddenParam, widths: widthsParam, pins: pinsParam };\n\n  // The nuqs setters are NOT stable across external URL changes (back/forward, setSearchParams,\n  // the testing adapter's searchParams prop) — the adapter re-renders and the query hook rebuilds\n  // its updater. They must stay out of the write-back effects' dep lists, or an external URL change\n  // re-triggers the write-back and stomps the new URL value before applyFromUrl can read it. The\n  // refs keep a live handle to the latest setter so the effects only re-run when the STORE state\n  // (the actual source of truth) changes.\n  const setSortParamRef = useRef(setSortParam);\n  const setGroupParamRef = useRef(setGroupParam);\n  const setFilterParamRef = useRef(setFilterParam);\n  const setJoinParamRef = useRef(setJoinParam);\n  const setSearchParamRef = useRef(setSearchParam);\n  const layoutSettersRef = useRef({ order: setOrderParam, hidden: setHiddenParam, widths: setWidthsParam, pins: setPinsParam });\n  // The query of the last popstate or of the last write: a popstate with the same query (a hash-only navigation) changes nothing.\n  const seenSearchRef = useRef<string | null>(null);\n  const noteWrite = (written: Promise<unknown>) => void written.then(() => (seenSearchRef.current = window.location.search), () => {});\n\n  // Reads the current URL params and applies them to the store. Runs once on mount (via the\n  // appliedRef guard below) and is exposed as applyFromUrl so a consumer can re-apply after an\n  // external URL change (back/forward, setSearchParams, query-only route change).\n  const applyUrl = useCallback((keepMountDefaults: boolean, params: UrlParams) => {\n    const initialLayout = storeApi.getInitialState().columnLayout;\n    const knownIds = new Set(allColumns.map((c) => c.id));\n    const layoutPatch: Partial<ColumnLayout> = {};\n    let unknownLayoutIds = 0;\n    for (const part of layoutParts ? (layoutParts.split(\",\") as UrlLayoutPart[]) : []) {\n      const parsed = parseLayoutPart(part, params[part]);\n      if (parsed[part] !== undefined) {\n        unknownLayoutIds += countUnknownLayoutIds(parsed, knownIds);\n        Object.assign(layoutPatch, parsed);\n      } else if (!keepMountDefaults) {\n        Object.assign(layoutPatch, { [part]: initialLayout[part] });\n      }\n    }\n    if (unknownLayoutIds > 0) warnDev(`dropped ${unknownLayoutIds} URL layout entries for removed columns`);\n    // Drop specs a shared link must not apply: a removed column, or one the integrator excluded from sorting/filtering or currently hides. Each drop dev-warns.\n    const hidden = new Set(layoutPatch.hidden ?? storeApi.getState().hiddenColumns);\n    const usable = (c: (typeof allColumns)[number]) => !hidden.has(c.id);\n    const sortableIds = new Set(allColumns.filter((c) => usable(c) && c.sortable !== false).map((c) => c.id));\n    const filterableIds = new Set(allColumns.filter((c) => usable(c) && c.filterable !== false).map((c) => c.id));\n    const parsedSorts = parseSortState(params.sort);\n    const sorts = parsedSorts.filter((spec) => {\n      if (sortableIds.has(spec.columnId)) return true;\n      warnDev(`dropped URL sort spec for removed, hidden, or unsortable column \"${spec.columnId}\"`);\n      return false;\n    });\n    const groupableIds = new Set(allColumns.filter((c) => usable(c) && c.groupable !== false).map((c) => c.id));\n    const groups = parseGroupBy(params.group).filter((id) => {\n      if (groupableIds.has(id)) return true;\n      warnDev(`dropped URL group for removed, hidden, or ungroupable column \"${id}\"`);\n      return false;\n    });\n    const choiceBounds = choiceBoundsOf(allColumns, storeApi.getState());\n    const unknownChoices = new Map<string, number>();\n    const parsedFilters = parseFilterState(params.filter, {\n      maxChoices: (columnId) => choiceBounds.get(columnId),\n      operatorInput,\n      choiceValues: setFilterValuesOf(storeApi.getState()),\n      onUnknownChoices: (columnId, count) => unknownChoices.set(columnId, (unknownChoices.get(columnId) ?? 0) + count),\n    });\n    for (const [columnId, count] of unknownChoices) {\n      if (warnedChoiceColumns.current.has(columnId)) continue;\n      warnedChoiceColumns.current.add(columnId);\n      warnDev(`dropped ${count} URL filter values outside the column choices and data values of \"${columnId}\"`);\n    }\n    const rootJoin = parseLegacyJoin(params.join);\n    const filters = pruneFilterSpecs(parsedFilters, (spec) => {\n      if (filterableIds.has(spec.columnId)) return true;\n      warnDev(`dropped URL filter spec for removed, hidden, or unfilterable column \"${spec.columnId}\"`);\n      return false;\n    }, true);\n    // On mount an absent param keeps the grid's initial state; a re-apply mirrors the URL, so a removed param clears its state.\n    if (syncSort && (sorts.length > 0 || !keepMountDefaults)) actions.setSorts(sorts);\n    if (syncGroup && storeApi.getState().groupingEnabled && (groups.length > 0 || !keepMountDefaults)) actions.setGroupBy(groups);\n    if (syncFilter && (filters.length > 0 || rootJoin === \"or\" || !keepMountDefaults)) {\n      actions.setFilters(filters);\n      actions.setFilterJoin(rootJoin);\n    }\n    if (syncSearch && (params.q || !keepMountDefaults)) actions.setSearch(params.q.slice(0, MAX_SPEC_SEARCH_LENGTH));\n\n    if (Object.keys(layoutPatch).length > 0) actions.setColumnLayout(layoutPatch);\n  }, [actions, allColumns, operatorInput, storeApi, syncSort, syncGroup, syncFilter, syncSearch, layoutParts]);\n  const applyUrlRef = useRef(applyUrl);\n  const currentParamsRef = useRef(currentParams);\n  useLayoutEffect(() => {\n    setSortParamRef.current = setSortParam;\n    setGroupParamRef.current = setGroupParam;\n    setFilterParamRef.current = setFilterParam;\n    setJoinParamRef.current = setJoinParam;\n    setSearchParamRef.current = setSearchParam;\n    layoutSettersRef.current = { order: setOrderParam, hidden: setHiddenParam, widths: setWidthsParam, pins: setPinsParam };\n    applyUrlRef.current = applyUrl;\n    currentParamsRef.current = currentParams;\n  });\n  const applyFromUrl = useCallback(() => applyUrlRef.current(false, currentParamsRef.current), []);\n\n  // apply URL -> store exactly once on mount; afterwards the store is the source of truth and\n  // this effect's own writes below must not be re-read back as if they were external URL edits.\n  const appliedRef = useRef(false);\n  useEffect(() => {\n    if (appliedRef.current) return;\n    appliedRef.current = true;\n    applyUrl(true, currentParams);\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  useEffect(() => {\n    if (!enableNavigationSync) return;\n    if (seenSearchRef.current === null) seenSearchRef.current = window.location.search;\n    const onPopState = () => {\n      if (window.location.search === seenSearchRef.current) return;\n      seenSearchRef.current = window.location.search;\n      applyUrlRef.current(false, readUrlParams(prefix));\n    };\n    window.addEventListener(\"popstate\", onPopState);\n    return () => window.removeEventListener(\"popstate\", onPopState);\n  }, [enableNavigationSync, prefix]);\n\n  useEffect(() => {\n    if (!appliedRef.current || !syncSort) return;\n    noteWrite(setSortParamRef.current(serializeSortState(sortState) || null));\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [sortState]);\n\n  useEffect(() => {\n    if (!appliedRef.current || !syncGroup) return;\n    noteWrite(setGroupParamRef.current(serializeGroupBy(groupBy) || null));\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [groupBy]);\n\n  useEffect(() => {\n    if (!appliedRef.current || !syncFilter) return;\n    const choiceBounds = choiceBoundsOf(allColumns, storeApi.getState());\n    noteWrite(setFilterParamRef.current(serializeFilterState(filterState, { operatorInput, maxChoices: (columnId) => choiceBounds.get(columnId) }) || null));\n    noteWrite(setJoinParamRef.current(filterJoin === \"or\" ? \"or\" : null));\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [filterState, filterJoin]);\n\n  const lastWrittenLayoutRef = useRef<Partial<Record<UrlLayoutPart, string>> | null>(null);\n  useEffect(() => {\n    if (!appliedRef.current) return;\n    const initialLayout = storeApi.getInitialState().columnLayout;\n    const previous = lastWrittenLayoutRef.current;\n    const next: Partial<Record<UrlLayoutPart, string>> = {};\n    for (const part of layoutParts ? (layoutParts.split(\",\") as UrlLayoutPart[]) : []) {\n      const value = serializeLayoutPart(part, columnLayout);\n      next[part] = value === serializeLayoutPart(part, initialLayout) ? \"\" : value;\n      if (previous && part in previous && previous[part] !== next[part]) noteWrite(layoutSettersRef.current[part](next[part] || null));\n    }\n    lastWrittenLayoutRef.current = next;\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [columnLayout, layoutParts]);\n\n  // The search text is already debounced by the input; the adapter coalesces the writes, so none is waited for here.\n  useEffect(() => {\n    if (!appliedRef.current || !syncSearch) return;\n    noteWrite(setSearchParamRef.current(searchText.slice(0, MAX_SPEC_SEARCH_LENGTH) || null));\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [searchText]);\n\n  return { applyFromUrl };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-url-state/use-data-grid-url-state.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
