{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"phrase","title":"Phrase","description":"Settings written as one sentence. Only the words you can change are dark: tap a word to pick another, drag a number sideways to dial it, and the line under it says what your choice means.","type":"registry:component","author":"Detent","dependencies":["motion"],"registryDependencies":["https://detentui.com/r/theme.json"],"files":[{"path":"components/detent/components/phrase/Phrase.tsx","target":"components/detent/components/phrase/Phrase.tsx","type":"registry:component","content":"'use client'\n\nimport { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react'\nimport type { KeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from 'react'\nimport { AnimatePresence, motion, useReducedMotion } from 'motion/react'\n\nexport type PhraseChoice = { id: string; options: string[]; label?: string }\nexport type PhraseNumber = { id: string; label: string; min: number; max: number; step?: number; format?: (n: number) => string }\nexport type PhrasePart = string | PhraseChoice | PhraseNumber\nexport type PhraseValues = Record<string, string | number>\n\nconst EASE = [0.3, 0, 0.2, 1] as const\nconst MUTE = 'text-[color-mix(in_oklch,var(--ink)_42%,transparent)]'\nconst PX = 7\nconst MENU = 'absolute top-[calc(100%+8px)] z-30 rounded-[12px] bg-[light-dark(#ffffff,#26262a)] p-1 text-[13.5px] leading-normal tracking-normal shadow-[0_0_0_0.5px_light-dark(rgb(0_0_0/.14),rgb(255_255_255/.12)),0_2px_4px_rgb(0_0_0/.04),0_16px_36px_-12px_rgb(0_0_0/.25)]'\nconst MARK = 'ring-focus relative -mx-1 rounded-[6px] px-1 text-ink underline decoration-dotted decoration-[1.5px] underline-offset-[5px] transition-colors ease-detent'\nconst OPEN = 'bg-[light-dark(rgb(0_0_0/.05),rgb(255_255_255/.08))] decoration-transparent'\nconst SHUT = 'decoration-[color-mix(in_oklch,var(--ink)_30%,transparent)] hover:decoration-[color-mix(in_oklch,var(--ink)_70%,transparent)]'\n\nconst isChoice = (p: PhrasePart): p is PhraseChoice => typeof p !== 'string' && 'options' in p\n\nfunction useOutside(open: boolean, box: React.RefObject<HTMLElement | null>, close: () => void) {\n  useEffect(() => {\n    if (!open) return\n    const off = (e: PointerEvent) => {\n      if (!box.current?.contains(e.target as Node)) close()\n    }\n    document.addEventListener('pointerdown', off)\n    return () => document.removeEventListener('pointerdown', off)\n  }, [open, box, close])\n}\n\nconst fit = (base: string) => (el: HTMLElement | null) => {\n  if (!el) return\n  el.style.translate = `${base} 0`\n  const r = el.getBoundingClientRect()\n  const over = r.right - (window.innerWidth - 8)\n  const under = 8 - r.left\n  const dx = over > 0 ? -Math.min(over, r.left - 8) : under > 0 ? under : 0\n  if (dx) el.style.translate = `calc(${base} + ${dx}px) 0`\n}\nconst fitLeft = fit('0px')\nconst fitMiddle = fit('-50%')\n\nfunction Word({ part, value, onPick, reduce }: { part: PhraseChoice; value: string; onPick: (v: string) => void; reduce: boolean }) {\n  const at = Math.max(0, part.options.indexOf(value))\n  const [open, setOpen] = useState(false)\n  const [hi, setHi] = useState(at)\n  const [w, setW] = useState<number | null>(null)\n  const box = useRef<HTMLSpanElement>(null)\n  const btn = useRef<HTMLButtonElement>(null)\n  const sizer = useRef<HTMLSpanElement>(null)\n  const [close] = useState(() => () => setOpen(false))\n  useOutside(open, box, close)\n\n  useLayoutEffect(() => {\n    const el = sizer.current\n    if (!el) return\n    const ro = new ResizeObserver(() => setW(el.offsetWidth))\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [])\n\n  const pick = (n: number) => {\n    onPick(part.options[n])\n    setOpen(false)\n    btn.current?.focus()\n  }\n\n  const onKey = (e: KeyboardEvent) => {\n    const last = part.options.length\n    if (!open) {\n      if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Enter' && e.key !== ' ') return\n      e.preventDefault()\n      setHi(at)\n      setOpen(true)\n      return\n    }\n    if (e.key === 'ArrowDown') setHi((h) => (h + 1) % last)\n    else if (e.key === 'ArrowUp') setHi((h) => (h - 1 + last) % last)\n    else if (e.key === 'Home') setHi(0)\n    else if (e.key === 'End') setHi(last - 1)\n    else if (e.key === 'Enter' || e.key === ' ') pick(hi)\n    else if (e.key === 'Escape' || e.key === 'Tab') {\n      setOpen(false)\n      if (e.key === 'Tab') return\n    } else return\n    e.preventDefault()\n  }\n\n  return (\n    <span ref={box} className=\"relative inline-block\">\n      <button\n        ref={btn}\n        type=\"button\"\n        aria-haspopup=\"listbox\"\n        aria-expanded={open}\n        aria-label={part.label ? `${part.label}: ${part.options[at]}` : undefined}\n        onClick={() => {\n          setHi(at)\n          setOpen((o) => !o)\n        }}\n        onKeyDown={onKey}\n        className={`${MARK} ${open ? OPEN : SHUT}`}\n      >\n        <span ref={sizer} aria-hidden className=\"invisible absolute whitespace-nowrap\">\n          {part.options[at]}\n        </span>\n        <motion.span className=\"relative inline-block whitespace-nowrap align-bottom [overflow-x:clip]\" initial={false} animate={{ width: w ?? 'auto' }} transition={reduce ? { duration: 0 } : { duration: 0.3, ease: EASE }}>\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            <motion.span\n              key={at}\n              className=\"inline-block\"\n              initial={reduce ? false : { opacity: 0, y: 8, filter: 'blur(3px)' }}\n              animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}\n              exit={reduce ? undefined : { opacity: 0, y: -8, filter: 'blur(3px)' }}\n              transition={{ duration: 0.28, ease: EASE }}\n            >\n              {part.options[at]}\n            </motion.span>\n          </AnimatePresence>\n        </motion.span>\n      </button>\n      <AnimatePresence>\n        {open && (\n          <motion.ul\n            ref={fitLeft}\n            role=\"listbox\"\n            aria-label={part.label ?? part.id}\n            className={`${MENU} left-[-10px] min-w-[190px]`}\n            style={{ transformOrigin: '24px 0' }}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: -4 }}\n            animate={{ opacity: 1, scale: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: -2, transition: { duration: 0.12 } }}\n            transition={{ duration: 0.2, ease: EASE }}\n          >\n            {part.options.map((o, n) => (\n              <li\n                key={o}\n                role=\"option\"\n                aria-selected={n === at}\n                onPointerEnter={() => setHi(n)}\n                onClick={() => pick(n)}\n                className={`flex h-8 cursor-pointer items-center gap-2 whitespace-nowrap rounded-[8px] px-2.5 pointer-coarse:h-10 ${n === hi ? 'bg-[light-dark(rgb(0_0_0/.045),rgb(255_255_255/.07))] text-ink' : 'text-ink-2'}`}\n              >\n                <span className=\"flex-1\">{o}</span>\n                {n === at && (\n                  <svg viewBox=\"0 0 14 14\" className=\"size-3.5 text-ink\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n                    <path d=\"m3.2 7.4 2.5 2.4 5.1-5.6\" />\n                  </svg>\n                )}\n              </li>\n            ))}\n          </motion.ul>\n        )}\n      </AnimatePresence>\n    </span>\n  )\n}\n\nfunction Roll({ text, dir, reduce }: { text: string; dir: number; reduce: boolean }) {\n  const chars = text.split('')\n  return (\n    <span className=\"tnum relative inline-flex overflow-hidden\">\n      <AnimatePresence mode=\"popLayout\" initial={false} custom={dir}>\n        {chars.map((c, i) => (\n          <motion.span\n            key={`${chars.length - i}-${c}`}\n            custom={dir}\n            className=\"inline-block\"\n            variants={{ in: (d: number) => ({ y: reduce ? 0 : d > 0 ? '70%' : '-70%', opacity: 0 }), at: { y: 0, opacity: 1 }, out: (d: number) => ({ y: reduce ? 0 : d > 0 ? '-70%' : '70%', opacity: 0 }) }}\n            initial=\"in\"\n            animate=\"at\"\n            exit=\"out\"\n            transition={{ duration: 0.22, ease: EASE }}\n          >\n            {c}\n          </motion.span>\n        ))}\n      </AnimatePresence>\n    </span>\n  )\n}\n\nfunction Dial({ part, value, onChange, reduce }: { part: PhraseNumber; value: number; onChange: (n: number) => void; reduce: boolean }) {\n  const { min, max, step = 1, label } = part\n  const [dir, setDir] = useState(1)\n  const [held, setHeld] = useState(false)\n  const [open, setOpen] = useState(false)\n  const from = useRef({ x: 0, v: 0, moved: false })\n  const box = useRef<HTMLSpanElement>(null)\n  const [close] = useState(() => () => setOpen(false))\n  useOutside(open, box, close)\n\n  const set = (n: number) => {\n    const c = Math.min(max, Math.max(min, Math.round(n / step) * step))\n    if (c === value) return\n    setDir(c > value ? 1 : -1)\n    onChange(c)\n  }\n\n  const down = (e: ReactPointerEvent<HTMLSpanElement>) => {\n    e.currentTarget.setPointerCapture(e.pointerId)\n    from.current = { x: e.clientX, v: value, moved: false }\n    setHeld(true)\n  }\n  const move = (e: ReactPointerEvent<HTMLSpanElement>) => {\n    if (!held) return\n    if (Math.abs(e.clientX - from.current.x) > 3) from.current.moved = true\n    set(from.current.v + Math.round((e.clientX - from.current.x) / PX) * step)\n  }\n  const up = () => {\n    setHeld(false)\n    if (!from.current.moved) setOpen((o) => !o)\n  }\n\n  const onKey = (e: KeyboardEvent) => {\n    const big = e.shiftKey ? 10 : 1\n    if (e.key === 'ArrowRight' || e.key === 'ArrowUp') set(value + step * big)\n    else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') set(value - step * big)\n    else if (e.key === 'Home') set(min)\n    else if (e.key === 'End') set(max)\n    else if (e.key === 'Escape') setOpen(false)\n    else return\n    e.preventDefault()\n  }\n\n  const shown = part.format ? part.format(value) : value.toLocaleString('en-US')\n\n  const nudge = (d: number) => (\n    <motion.button\n      type=\"button\"\n      whileTap={reduce ? undefined : { scale: 0.92 }}\n      aria-label={d < 0 ? `Less ${label.toLowerCase()}` : `More ${label.toLowerCase()}`}\n      disabled={d < 0 ? value <= min : value >= max}\n      onClick={() => set(value + d * step)}\n      className=\"ring-focus grid size-8 place-items-center rounded-[8px] text-ink-2 hover:bg-[light-dark(rgb(0_0_0/.045),rgb(255_255_255/.07))] hover:text-ink disabled:opacity-30 pointer-coarse:size-10\"\n    >\n      <svg viewBox=\"0 0 12 12\" className=\"size-3\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" aria-hidden>\n        <path d={d < 0 ? 'M3 6h6' : 'M3 6h6M6 3v6'} />\n      </svg>\n    </motion.button>\n  )\n\n  return (\n    <span ref={box} className=\"relative inline-block\">\n      <span\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-valuenow={value}\n        aria-valuetext={shown}\n        aria-valuemin={min}\n        aria-valuemax={max}\n        onPointerDown={down}\n        onPointerMove={move}\n        onPointerUp={up}\n        onPointerCancel={() => setHeld(false)}\n        onKeyDown={onKey}\n        className={`${MARK} inline-block cursor-ew-resize touch-none select-none ${held || open ? OPEN : SHUT}`}\n      >\n        <Roll text={shown} dir={dir} reduce={reduce} />\n      </span>\n      <AnimatePresence>\n        {open && (\n          <motion.span\n            ref={fitMiddle}\n            className={`${MENU} left-1/2 flex items-center gap-1`}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: -4 }}\n            animate={{ opacity: 1, scale: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: -2, transition: { duration: 0.12 } }}\n            transition={{ duration: 0.2, ease: EASE }}\n          >\n            {nudge(-1)}\n            <span className=\"tnum min-w-[56px] text-center text-[13px] text-ink\">{shown}</span>\n            {nudge(1)}\n          </motion.span>\n        )}\n      </AnimatePresence>\n    </span>\n  )\n}\n\nconst first = (parts: PhrasePart[]) =>\n  Object.fromEntries(parts.filter((p) => typeof p !== 'string').map((p) => [p.id, isChoice(p) ? p.options[0] : p.min])) as PhraseValues\n\nexport function Phrase({\n  parts,\n  value,\n  defaultValue,\n  onChange,\n  title,\n  aside,\n  says,\n  className = '',\n}: {\n  parts: PhrasePart[]\n  value?: PhraseValues\n  defaultValue?: PhraseValues\n  onChange?: (values: PhraseValues) => void\n  title?: ReactNode\n  aside?: ReactNode\n  says?: (values: PhraseValues) => ReactNode\n  className?: string\n}) {\n  const reduce = !!useReducedMotion()\n  const [own, setOwn] = useState<PhraseValues>(() => ({ ...first(parts), ...defaultValue }))\n  const values = value ? { ...own, ...value } : own\n  const set = (id: string) => (v: string | number) => {\n    const next = { ...values, [id]: v }\n    if (!value) setOwn(next)\n    onChange?.(next)\n  }\n  const line = says?.(values)\n  const lineKey = parts\n    .filter((p) => typeof p !== 'string')\n    .map((p) => values[p.id])\n    .join('|')\n\n  const sentence = useRef<HTMLDivElement>(null)\n  const [h, setH] = useState<number | 'auto'>('auto')\n  const [moving, setMoving] = useState(false)\n  useLayoutEffect(() => {\n    const el = sentence.current\n    if (!el) return\n    const ro = new ResizeObserver(() => setH(el.offsetHeight))\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [])\n\n  return (\n    <section className={`w-full rounded-[16px] bg-[light-dark(#ffffff,#1a1a1c)] p-1 shadow-[0_0_0_0.5px_light-dark(rgb(0_0_0/.12),rgb(255_255_255/.1)),0_1px_2px_rgb(0_0_0/.04),0_12px_32px_-20px_rgb(0_0_0/.22)] ${className}`}>\n      {(title || aside) && (\n        <header className=\"flex h-10 items-center gap-2 px-4\">\n          {title && <h3 className=\"text-[13px] font-medium text-ink-2\">{title}</h3>}\n          <span className=\"flex-1\" />\n          {aside && <span className={`text-[12.5px] ${MUTE}`}>{aside}</span>}\n        </header>\n      )}\n      <div className=\"rounded-[12px] bg-[light-dark(#f6f6f5,#222225)] px-4\">\n        <motion.div\n          className={moving ? 'overflow-hidden' : ''}\n          onAnimationStart={() => setMoving(true)}\n          onAnimationComplete={() => setMoving(false)}\n          initial={false}\n          animate={{ height: h }}\n          transition={reduce ? { duration: 0 } : { duration: 0.3, ease: EASE }}\n        >\n          <div ref={sentence} className={`py-5 text-[19px] leading-[1.6] tracking-[-0.022em] ${MUTE}`}>\n            {parts.map((p, n) =>\n              typeof p === 'string' ? (\n                <Fragment key={n}>{p}</Fragment>\n              ) : isChoice(p) ? (\n                <Word key={p.id} part={p} value={String(values[p.id])} onPick={set(p.id)} reduce={reduce} />\n              ) : (\n                <Dial key={p.id} part={p} value={Number(values[p.id])} onChange={set(p.id)} reduce={reduce} />\n              ),\n            )}\n          </div>\n        </motion.div>\n        {says && (\n          <div aria-live=\"polite\" className=\"flex min-h-10 items-center overflow-hidden text-[12.5px] shadow-[inset_0_1px_0_light-dark(rgb(0_0_0/.07),rgb(255_255_255/.07))]\">\n            <AnimatePresence mode=\"popLayout\" initial={false}>\n              <motion.span\n                key={lineKey}\n                className=\"tnum py-2.5 text-ink-3\"\n                initial={reduce ? false : { opacity: 0, y: 4 }}\n                animate={{ opacity: 1, y: 0 }}\n                exit={reduce ? undefined : { opacity: 0, y: -4 }}\n                transition={{ duration: 0.22, ease: EASE }}\n              >\n                {line}\n              </motion.span>\n            </AnimatePresence>\n          </div>\n        )}\n      </div>\n    </section>\n  )\n}\n"}]}