{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "use-reading-prefs",
  "type": "registry:lib",
  "title": "useReadingPrefs hook",
  "description": "@interlace/ui — reads and writes the reader's text size (`data-text-size`) and contrast (`data-contrast`) on <html>, persists both, and follows `prefers-contrast` when no choice is stored.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "foundation",
    "util"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/theme-script.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/lib/use-reading-prefs.ts",
      "target": "hooks/use-reading-prefs.ts",
      "type": "registry:lib",
      "content": "'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\n\n// @interlace/use-reading-prefs v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/use-reading-prefs\n// What changed since: https://ds.interlace.tools/c/use-reading-prefs#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — useReadingPrefs.\n *\n * The two reading-comfort axes, beside the theme and scheme that `useTheme`\n * owns:\n *\n *   text size → `data-text-size=\"lg\" | \"xl\" | \"2xl\"`  (absent = 100%)\n *   contrast  → `data-contrast=\"more\" | \"normal\"`      (absent = follow the OS)\n *\n * Both are written to `<html>`. Text size has to be: it sets the ROOT font\n * size, and every rem in the system (type, spacing, control heights,\n * containers) reads the root. On any other element it would grow the text\n * and leave every box the same size, which is how text ends up clipped.\n *\n * Same shape as `useTheme`, for the same reasons: no provider (the `<html>`\n * element is the shared state), a module-level subscriber list so two\n * controls in one document agree, the `storage` event so two tabs agree,\n * and storage access that cannot throw. `THEME_SCRIPT` applies both axes\n * before first paint, so the page never reflows on hydration; only the\n * control's own state settles a frame late, which is what `mounted` is for.\n */\n\nimport {\n  CONTRAST_STORAGE_KEY,\n  isTextSize,\n  TEXT_SIZE_STORAGE_KEY,\n  TEXT_SIZES,\n  type TextSize,\n} from '@/lib/theme-script';\n\n/** `'system'` follows `prefers-contrast: more`; the others override it. */\nexport type ContrastPreference = 'more' | 'normal' | 'system';\n\nconst MORE_QUERY = '(prefers-contrast: more)';\n\nfunction readStorage(key: string): string | null {\n  try {\n    return window.localStorage.getItem(key);\n  } catch {\n    return null;\n  }\n}\n\nfunction writeStorage(key: string, value: string | null): void {\n  try {\n    if (value === null) window.localStorage.removeItem(key);\n    else window.localStorage.setItem(key, value);\n  } catch {\n    /* Private mode or blocked storage: the choice still applies to this\n     * page, it just will not survive a reload. */\n  }\n}\n\n/** The persisted text size. Absent or unregistered reads as `'default'`. */\nexport function readStoredTextSize(): TextSize {\n  const stored = readStorage(TEXT_SIZE_STORAGE_KEY);\n  return isTextSize(stored) ? stored : 'default';\n}\n\n/** The persisted contrast preference. Absent or corrupt reads as `'system'`. */\nexport function readStoredContrast(): ContrastPreference {\n  const stored = readStorage(CONTRAST_STORAGE_KEY);\n  return stored === 'more' || stored === 'normal' ? stored : 'system';\n}\n\n/** Project both axes onto `<html>`. The defaults are written as absence. Client only. */\nexport function applyReadingPrefs(\n  textSize: TextSize,\n  contrast: ContrastPreference,\n): void {\n  const root = document.documentElement;\n  if (textSize === 'default') root.removeAttribute('data-text-size');\n  else root.setAttribute('data-text-size', textSize);\n  if (contrast === 'system') root.removeAttribute('data-contrast');\n  else root.setAttribute('data-contrast', contrast);\n}\n\nconst textSizeSubscribers = new Set<(size: TextSize) => void>();\nconst contrastSubscribers = new Set<(level: ContrastPreference) => void>();\n\nexport interface UseReadingPrefsResult {\n  /** The active text size. */\n  textSize: TextSize;\n  /** Choose a text size. Persists, and resizes the page. */\n  setTextSize: (size: TextSize) => void;\n  /** One step smaller (`-1`) or larger (`1`), held at the ends. */\n  stepTextSize: (direction: -1 | 1) => void;\n  /** The registered sizes, smallest first, for rendering a picker. */\n  textSizes: typeof TEXT_SIZES;\n  /** What the user chose; `'system'` follows `prefers-contrast`. */\n  contrastPreference: ContrastPreference;\n  /** Whether more contrast is on screen right now, from either source. */\n  moreContrast: boolean;\n  /** Choose a contrast preference. `'system'` clears the stored override. */\n  setContrast: (level: ContrastPreference) => void;\n  /** `false` until the first client effect has read storage. */\n  mounted: boolean;\n}\n\nexport function useReadingPrefs(): UseReadingPrefsResult {\n  const [textSize, setTextSizeState] = useState<TextSize>('default');\n  const [contrastPreference, setContrastState] =\n    useState<ContrastPreference>('system');\n  const [systemMore, setSystemMore] = useState(false);\n  const [mounted, setMounted] = useState(false);\n\n  useEffect(() => {\n    setTextSizeState(readStoredTextSize());\n    setContrastState(readStoredContrast());\n    setSystemMore(Boolean(window.matchMedia?.(MORE_QUERY).matches));\n    setMounted(true);\n  }, []);\n\n  useEffect(() => {\n    if (!window.matchMedia) return;\n    const query = window.matchMedia(MORE_QUERY);\n    const onChange = (event: MediaQueryListEvent) => setSystemMore(event.matches);\n    query.addEventListener('change', onChange);\n    return () => query.removeEventListener('change', onChange);\n  }, []);\n\n  useEffect(() => {\n    textSizeSubscribers.add(setTextSizeState);\n    contrastSubscribers.add(setContrastState);\n    return () => {\n      textSizeSubscribers.delete(setTextSizeState);\n      contrastSubscribers.delete(setContrastState);\n    };\n  }, []);\n\n  useEffect(() => {\n    const onStorage = (event: StorageEvent) => {\n      if (event.key === TEXT_SIZE_STORAGE_KEY) setTextSizeState(readStoredTextSize());\n      else if (event.key === CONTRAST_STORAGE_KEY) setContrastState(readStoredContrast());\n    };\n    window.addEventListener('storage', onStorage);\n    return () => window.removeEventListener('storage', onStorage);\n  }, []);\n\n  // Only after storage is read: applying the defaults first would undo what\n  // THEME_SCRIPT set and reflow the page for a frame.\n  useEffect(() => {\n    if (!mounted) return;\n    applyReadingPrefs(textSize, contrastPreference);\n  }, [mounted, textSize, contrastPreference]);\n\n  const setTextSize = useCallback((next: TextSize) => {\n    writeStorage(TEXT_SIZE_STORAGE_KEY, next === 'default' ? null : next);\n    for (const notify of textSizeSubscribers) notify(next);\n  }, []);\n\n  const stepTextSize = useCallback(\n    (direction: -1 | 1) => {\n      const index = TEXT_SIZES.findIndex((size) => size.value === textSize);\n      const next = TEXT_SIZES[Math.min(TEXT_SIZES.length - 1, Math.max(0, index + direction))];\n      if (next && next.value !== textSize) setTextSize(next.value);\n    },\n    [textSize, setTextSize],\n  );\n\n  const setContrast = useCallback((next: ContrastPreference) => {\n    writeStorage(CONTRAST_STORAGE_KEY, next === 'system' ? null : next);\n    for (const notify of contrastSubscribers) notify(next);\n  }, []);\n\n  const moreContrast =\n    contrastPreference === 'more' || (contrastPreference === 'system' && systemMore);\n\n  return {\n    textSize,\n    setTextSize,\n    stepTextSize,\n    textSizes: TEXT_SIZES,\n    contrastPreference,\n    moreContrast,\n    setContrast,\n    mounted,\n  };\n}\n"
    }
  ],
  "meta": {
    "tier": "util",
    "client": true,
    "minViewport": null,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/use-reading-prefs\n\nInstalled to `hooks/use-reading-prefs.ts`.\n\n```tsx\nimport { /* … */ } from '@/hooks/use-reading-prefs';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/use-reading-prefs"
}
