{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-table-url-state",
  "title": "Data Table URL State",
  "description": "useState replacement that syncs the data table query to the URL with history.replaceState.",
  "registryDependencies": [
    "https://dentil.dev/r/data-table.json?via=data-table-url-state"
  ],
  "files": [
    {
      "path": "components/dentil/data-table/use-table-query-state.ts",
      "content": "'use client';\n\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\n\nimport type { TableQuery } from './types';\n\n/** `true` syncs with no prefix; `{ prefix }` namespaces params when several tables share a page. */\nexport type UrlStateConfig = boolean | { prefix?: string };\n\nexport interface UseTableQueryStateOptions {\n  /** Defaults to `false` (plain `useState`). */\n  urlState?: UrlStateConfig;\n  /** Keys whose URL values are read back as numbers. Defaults to `['offset', 'limit']`. */\n  numericKeys?: string[];\n  /**\n   * The current search string (e.g. `useSearchParams().toString()` in Next.js). Pass it when the table renders on\n   * the server to apply URL params on the very first render. Without it, SSR apps start from `initialQuery` and apply\n   * URL params right after hydration; client-only apps read `window.location.search` immediately.\n   */\n  search?: string;\n}\n\nconst DEFAULT_NUMERIC_KEYS = ['offset', 'limit'];\n\nfunction resolveUrlState(urlState: UrlStateConfig | undefined): { enabled: boolean; prefix: string } {\n  if (!urlState) return { enabled: false, prefix: '' };\n  if (urlState === true) return { enabled: true, prefix: '' };\n  return { enabled: true, prefix: urlState.prefix ?? '' };\n}\n\nfunction isEmpty(value: unknown): boolean {\n  if (value === undefined || value === null || value === '') return true;\n  if (Array.isArray(value)) return value.length === 0;\n  return false;\n}\n\nexport function serializeTableQuery(query: TableQuery, prefix = ''): URLSearchParams {\n  const params = new URLSearchParams();\n  for (const [key, value] of Object.entries(query)) {\n    if (isEmpty(value)) continue;\n    const k = `${prefix}${key}`;\n    if (Array.isArray(value)) {\n      value.forEach((v) => params.append(k, String(v)));\n    } else if (typeof value === 'object') {\n      params.set(k, JSON.stringify(value));\n    } else if (typeof value === 'number') {\n      // Skip default pagination zeros so `?offset=0` doesn't clutter the URL, but keep meaningful zeros.\n      if (value === 0 && (key === 'offset' || key === 'limit')) continue;\n      params.set(k, String(value));\n    } else {\n      params.set(k, String(value));\n    }\n  }\n  return params;\n}\n\nexport function deserializeTableQuery(\n  searchParams: URLSearchParams,\n  prefix = '',\n  numericKeys: string[] = DEFAULT_NUMERIC_KEYS\n): TableQuery {\n  const grouped = new Map<string, string[]>();\n  for (const [k, v] of searchParams.entries()) {\n    if (prefix && !k.startsWith(prefix)) continue;\n    const key = prefix ? k.slice(prefix.length) : k;\n    grouped.set(key, [...(grouped.get(key) ?? []), v]);\n  }\n  const out: TableQuery = {};\n  for (const [key, values] of grouped) {\n    const raw: string | string[] = values.length > 1 ? values : values[0]!;\n    if (numericKeys.includes(key) && typeof raw === 'string') {\n      const n = Number(raw);\n      out[key] = Number.isNaN(n) ? raw : n;\n    } else if (typeof raw === 'string' && (raw.startsWith('{') || raw.startsWith('['))) {\n      try {\n        out[key] = JSON.parse(raw);\n      } catch {\n        out[key] = raw;\n      }\n    } else {\n      out[key] = raw;\n    }\n  }\n  return out;\n}\n\n/**\n * Drop-in replacement for `useState<TableQuery>` that can sync the query to the URL, so filters, sort and\n * pagination survive reloads, shared links and Back navigation.\n *\n * Writes use `history.replaceState`, so they don't add history entries or trigger router navigations.\n * On mount, URL params win over `initialQuery`.\n *\n * @example\n * const [query, setQuery] = useTableQueryState({ sort: 'descending' }, { urlState: true });\n */\nconst noopSubscribe = () => () => {};\n\n/** `true` on the server and during hydration, `false` for every client render after it (and in client-only apps). */\nfunction useIsHydrating() {\n  return useSyncExternalStore(\n    noopSubscribe,\n    () => false,\n    () => true\n  );\n}\n\nexport function useTableQueryState(\n  initialQuery: TableQuery = {},\n  { urlState, numericKeys = DEFAULT_NUMERIC_KEYS, search }: UseTableQueryStateOptions = {}\n): [TableQuery, (next: TableQuery) => void] {\n  const { enabled, prefix } = resolveUrlState(urlState);\n  const isHydrating = useIsHydrating();\n\n  const readUrl = (source: string) => {\n    const fromUrl = deserializeTableQuery(new URLSearchParams(source), prefix, numericKeys);\n    return Object.keys(fromUrl).length > 0 ? { ...initialQuery, ...fromUrl } : initialQuery;\n  };\n\n  // Read the URL up front when it's safe: a `search` the server also saw, or a client render that isn't hydrating.\n  // While hydrating without `search`, start from `initialQuery` so the markup matches, and read the URL after mount.\n  const deferUrlRead = enabled && search === undefined && isHydrating;\n  const [query, setQueryState] = useState<TableQuery>(() => {\n    if (!enabled) return initialQuery;\n    if (search !== undefined) return readUrl(search);\n    return isHydrating ? initialQuery : readUrl(window.location.search);\n  });\n\n  const shouldReadAfterMount = useRef(deferUrlRead);\n  useEffect(() => {\n    if (!shouldReadAfterMount.current) return;\n    shouldReadAfterMount.current = false;\n    // Syncing from an external source (the URL) once after hydration.\n    // eslint-disable-next-line react-hooks/set-state-in-effect\n    if (window.location.search) setQueryState(readUrl(window.location.search));\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  const config = useRef({ enabled, prefix });\n  useEffect(() => {\n    config.current = { enabled, prefix };\n  });\n\n  const setQuery = useCallback((next: TableQuery) => {\n    setQueryState(next);\n\n    const { enabled, prefix } = config.current;\n    if (!enabled || typeof window === 'undefined') return;\n\n    const current = new URLSearchParams(window.location.search);\n    for (const key of Array.from(current.keys())) {\n      if (!prefix || key.startsWith(prefix)) current.delete(key);\n    }\n    serializeTableQuery(next, prefix).forEach((v, k) => current.append(k, v));\n\n    const qs = current.toString();\n    const url = `${window.location.pathname}${qs ? `?${qs}` : ''}${window.location.hash}`;\n    window.history.replaceState(window.history.state, '', url);\n  }, []);\n\n  return [query, setQuery];\n}\n",
      "type": "registry:hook",
      "target": "components/dentil/data-table/use-table-query-state.ts"
    }
  ],
  "type": "registry:hook"
}
