{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"select-menu","type":"registry:component","title":"Select menu","description":"Opens with your current choice sitting exactly on the button, macOS style.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/select-menu.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { AnimatePresence, motion, useIsPresent } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type SelectOption = { value: string; label: string; detail?: string };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst ENTER = { duration: 0.15, ease: EASE_OUT };\n// Leaves faster than it arrives, so choosing never waits on the list.\nconst EXIT = { duration: 0.1, ease: EASE_OUT };\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n\n// Geometry shared by the markup and the placement math below.\nconst ITEM = 36;\nconst PAD = 4;\nconst TRIGGER = 40;\nconst MAX_ROWS = 8;\n// Check column (16) + gap (8) + item padding (8) - trigger padding (12)\n// + panel padding (4): shifting the panel left by this lands every\n// option's text exactly on the trigger's text.\nconst TEXT_SHIFT = 24;\n// Keeps the panel this far inside the viewport.\nconst MARGIN = 8;\n// Letters typed within this window extend the search instead of restarting.\nconst TYPEAHEAD_RESET = 500;\n// Scroll-button speed while hovered, in px per second.\nconst SCROLL_SPEED = 280;\n\ntype Placement = {\n  top: number;\n  left: number;\n  width: number;\n  scroll: number;\n  originX: number;\n  originY: number;\n};\n\nconst clamp = (v: number, lo: number, hi: number) =>\n  Math.min(Math.max(v, lo), hi);\n\n// Puts the selected option exactly over the trigger, the way macOS does,\n// then trades list position for scroll position if that runs off screen.\nfunction place(trigger: HTMLElement, count: number, selected: number): Placement {\n  const box = trigger.getBoundingClientRect();\n  // The lab preview scales demos down; work in the element's own pixels.\n  const scale = box.height / trigger.offsetHeight || 1;\n  const rows = Math.min(count, MAX_ROWS);\n  const height = rows * ITEM + PAD * 2;\n  const maxScroll = (count - rows) * ITEM;\n\n  let scroll = clamp((selected - Math.floor(rows / 2)) * ITEM, 0, maxScroll);\n  let top = (TRIGGER - ITEM) / 2 - (PAD + selected * ITEM - scroll);\n\n  const minTop = (MARGIN - box.top) / scale;\n  const maxBottom = (window.innerHeight - MARGIN - box.top) / scale;\n  if (top < minTop) {\n    const d = minTop - top;\n    top += d;\n    scroll += Math.min(d, maxScroll - scroll);\n  }\n  if (top + height > maxBottom) {\n    const d = top + height - maxBottom;\n    top -= d;\n    scroll -= Math.min(d, scroll);\n  }\n\n  const width = trigger.offsetWidth + TEXT_SHIFT;\n  const minLeft = (MARGIN - box.left) / scale;\n  const maxRight = (window.innerWidth - MARGIN - box.left) / scale;\n  const left = Math.max(minLeft, Math.min(-TEXT_SHIFT, maxRight - width));\n\n  return {\n    top,\n    left,\n    width,\n    scroll,\n    // Grows out of the trigger itself, wherever it ended up in the panel.\n    originX: trigger.offsetWidth / 2 - left,\n    originY: TRIGGER / 2 - top,\n  };\n}\n\nexport function SelectMenu({\n  label,\n  options,\n  value,\n  onChange,\n  className,\n}: {\n  label: string;\n  options: SelectOption[];\n  value: string;\n  onChange: (value: string) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const id = useId();\n  const labelId = `${id}-label`;\n  const listId = `${id}-list`;\n  const optionId = (i: number) => `${id}-option-${i}`;\n\n  const [placement, setPlacement] = useState<Placement | null>(null);\n  const [active, setActive] = useState(0);\n  const open = placement !== null;\n\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const scrollerRef = useRef<HTMLDivElement>(null);\n  const typeahead = useRef({ query: \"\", timer: 0 });\n  const lastPointer = useRef({ x: -1, y: -1 });\n\n  const selected = Math.max(\n    0,\n    options.findIndex((o) => o.value === value),\n  );\n\n  useEffect(() => {\n    const state = typeahead.current;\n    return () => clearTimeout(state.timer);\n  }, []);\n\n  const openList = () => {\n    if (!triggerRef.current) return;\n    setActive(selected);\n    setPlacement(place(triggerRef.current, options.length, selected));\n  };\n\n  const close = () => setPlacement(null);\n\n  const choose = (index: number) => {\n    onChange(options[index].value);\n    close();\n  };\n\n  // Keyboard moves keep the highlight in view; pointer moves never scroll.\n  const highlight = (index: number) => {\n    const next = clamp(index, 0, options.length - 1);\n    setActive(next);\n    const el = scrollerRef.current;\n    if (!el) return;\n    const top = PAD + next * ITEM;\n    if (top < el.scrollTop + PAD) el.scrollTop = top - PAD;\n    else if (top + ITEM > el.scrollTop + el.clientHeight - PAD)\n      el.scrollTop = top + ITEM - el.clientHeight + PAD;\n  };\n\n  const search = (char: string) => {\n    const state = typeahead.current;\n    clearTimeout(state.timer);\n    state.query += char.toLowerCase();\n    state.timer = window.setTimeout(() => {\n      state.query = \"\";\n    }, TYPEAHEAD_RESET);\n\n    // Pressing the same letter again cycles through its matches.\n    const repeated = [...state.query].every((c) => c === state.query[0]);\n    const query = repeated ? state.query[0] : state.query;\n    const from = open ? active : selected;\n    const start = repeated ? from + 1 : from;\n    for (let n = 0; n < options.length; n++) {\n      const index = (start + n) % options.length;\n      if (options[index].label.toLowerCase().startsWith(query)) {\n        // Closed, it changes the value directly, like a native select.\n        if (open) highlight(index);\n        else onChange(options[index].value);\n        return;\n      }\n    }\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const typing = typeahead.current.query !== \"\";\n    if (!open) {\n      if ([\"Enter\", \" \", \"ArrowDown\", \"ArrowUp\"].includes(e.key) && !(e.key === \" \" && typing)) {\n        e.preventDefault();\n        openList();\n        return;\n      }\n    } else {\n      const page = MAX_ROWS - 1;\n      const moves: Record<string, number> = {\n        ArrowDown: active + 1,\n        ArrowUp: active - 1,\n        PageDown: active + page,\n        PageUp: active - page,\n        Home: 0,\n        End: options.length - 1,\n      };\n      if (e.key === \"ArrowUp\" && e.altKey) {\n        e.preventDefault();\n        choose(active);\n        return;\n      }\n      if (e.key in moves) {\n        e.preventDefault();\n        highlight(moves[e.key]);\n        return;\n      }\n      if (e.key === \"Enter\" || (e.key === \" \" && !typing)) {\n        e.preventDefault();\n        choose(active);\n        return;\n      }\n      if (e.key === \"Escape\") {\n        e.preventDefault();\n        close();\n        return;\n      }\n      // Tab commits the highlighted option and moves on, per the APG pattern.\n      if (e.key === \"Tab\") {\n        choose(active);\n        return;\n      }\n    }\n    if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {\n      e.preventDefault();\n      search(e.key);\n    }\n  };\n\n  return (\n    <div className={cn(\"relative w-[min(260px,100%)]\", className)}>\n      <span id={labelId} className=\"sr-only\">\n        {label}\n      </span>\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        role=\"combobox\"\n        aria-labelledby={`${labelId} ${id}-value`}\n        aria-haspopup=\"listbox\"\n        aria-expanded={open}\n        aria-controls={listId}\n        aria-activedescendant={open ? optionId(active) : undefined}\n        onClick={() => (open ? close() : openList())}\n        onKeyDown={onKeyDown}\n        onBlur={close}\n        className=\"flex h-10 w-full touch-manipulation items-center gap-2 rounded-lg bg-muted pr-2.5 pl-3 text-left text-sm text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n      >\n        <span id={`${id}-value`} className=\"flex-1 truncate\">\n          {options[selected]?.label}\n        </span>\n        <svg\n          viewBox=\"0 0 16 16\"\n          aria-hidden\n          className=\"size-4 shrink-0 text-muted-foreground\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n        >\n          <path d=\"m5 6.25 3-3 3 3M5 9.75l3 3 3-3\" />\n        </svg>\n      </button>\n\n      <AnimatePresence>\n        {placement && (\n          <Panel\n            key=\"panel\"\n            placement={placement}\n            reduceMotion={!!reduceMotion}\n            scrollerRef={scrollerRef}\n          >\n            <div role=\"listbox\" id={listId} aria-labelledby={labelId}>\n              {options.map((option, i) => {\n                const isSelected = i === selected;\n                return (\n                  <div\n                    key={option.value}\n                    id={optionId(i)}\n                    role=\"option\"\n                    aria-selected={isSelected}\n                    onPointerMove={(e) => {\n                      if (e.pointerType === \"touch\") return;\n                      // Scrolling under a still cursor can fire synthetic\n                      // moves; only real movement takes the highlight.\n                      const last = lastPointer.current;\n                      if (last.x === e.clientX && last.y === e.clientY) return;\n                      lastPointer.current = { x: e.clientX, y: e.clientY };\n                      if (active !== i) setActive(i);\n                    }}\n                    onClick={() => choose(i)}\n                    // No transition on the highlight: it follows every move,\n                    // so easing would read as lag.\n                    className={cn(\n                      \"flex h-9 cursor-default items-center gap-2 rounded-lg px-2 text-sm text-foreground select-none\",\n                      active === i && \"bg-foreground/[0.06]\",\n                    )}\n                  >\n                    <Check visible={isSelected} reduceMotion={!!reduceMotion} />\n                    <span className=\"flex-1 truncate\">{option.label}</span>\n                    {option.detail && (\n                      <span className=\"shrink-0 text-xs text-muted-foreground tabular-nums\">\n                        {option.detail}\n                      </span>\n                    )}\n                  </div>\n                );\n              })}\n            </div>\n          </Panel>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction Panel({\n  placement,\n  reduceMotion,\n  scrollerRef,\n  children,\n}: {\n  placement: Placement;\n  reduceMotion: boolean;\n  scrollerRef: React.RefObject<HTMLDivElement | null>;\n  children: React.ReactNode;\n}) {\n  // A closing list stops taking input at once, so it never eats the next click.\n  const isPresent = useIsPresent();\n  const panelRef = useRef<HTMLDivElement>(null);\n  const frame = useRef(0);\n\n  useEffect(() => () => cancelAnimationFrame(frame.current), []);\n\n  // Edge fades and scroll buttons follow the scroll position through the\n  // DOM directly, so scrolling never re-renders the list.\n  const updateEdges = (el: HTMLDivElement) => {\n    const up = el.scrollTop > 1;\n    const down = el.scrollTop < el.scrollHeight - el.clientHeight - 1;\n    // 24px is about two thirds of a row: enough to say \"more this way\"\n    // without hiding the option underneath.\n    el.style.maskImage = `linear-gradient(to bottom, transparent, black ${up ? 24 : 0}px, black calc(100% - ${down ? 24 : 0}px), transparent)`;\n    const panel = panelRef.current;\n    if (!panel) return;\n    panel.toggleAttribute(\"data-up\", up);\n    panel.toggleAttribute(\"data-down\", down);\n  };\n\n  const startScroll = (direction: 1 | -1, e: React.PointerEvent) => {\n    if (e.pointerType === \"touch\") return;\n    cancelAnimationFrame(frame.current);\n    let last = performance.now();\n    const tick = (now: number) => {\n      const el = scrollerRef.current;\n      if (!el) return;\n      el.scrollTop += (direction * SCROLL_SPEED * (now - last)) / 1000;\n      last = now;\n      frame.current = requestAnimationFrame(tick);\n    };\n    frame.current = requestAnimationFrame(tick);\n  };\n\n  const stopScroll = () => cancelAnimationFrame(frame.current);\n\n  const hidden = reduceMotion\n    ? { opacity: 0, transform: \"scale(1)\" }\n    : { opacity: 0, transform: \"scale(0.96)\" };\n\n  return (\n    <motion.div\n      ref={panelRef}\n      initial={hidden}\n      animate={{ opacity: 1, transform: \"scale(1)\" }}\n      exit={{ ...hidden, transition: EXIT }}\n      transition={ENTER}\n      // Keeps focus on the trigger, which owns the keyboard.\n      onMouseDown={(e) => e.preventDefault()}\n      onPointerEnter={(e) => {\n        if (e.pointerType !== \"touch\") panelRef.current?.setAttribute(\"data-hover\", \"\");\n      }}\n      onPointerLeave={() => {\n        panelRef.current?.removeAttribute(\"data-hover\");\n        stopScroll();\n      }}\n      style={{\n        top: placement.top,\n        left: placement.left,\n        width: placement.width,\n        transformOrigin: `${placement.originX}px ${placement.originY}px`,\n      }}\n      // 12px radius around 4px padding keeps the 8px options concentric.\n      className={cn(\n        \"group absolute z-50 overflow-hidden rounded-xl bg-muted shadow-raised\",\n        !isPresent && \"pointer-events-none\",\n      )}\n    >\n      <div\n        ref={(el) => {\n          scrollerRef.current = el;\n          if (!el || el.dataset.placed) return;\n          el.dataset.placed = \"true\";\n          el.scrollTop = placement.scroll;\n          updateEdges(el);\n        }}\n        onScroll={(e) => updateEdges(e.currentTarget)}\n        className=\"overscroll-contain overflow-y-auto p-1\"\n        style={{ maxHeight: MAX_ROWS * ITEM + PAD * 2 }}\n      >\n        {children}\n      </div>\n      <ScrollButton direction={-1} onEnter={startScroll} onLeave={stopScroll} />\n      <ScrollButton direction={1} onEnter={startScroll} onLeave={stopScroll} />\n    </motion.div>\n  );\n}\n\nfunction ScrollButton({\n  direction,\n  onEnter,\n  onLeave,\n}: {\n  direction: 1 | -1;\n  onEnter: (direction: 1 | -1, e: React.PointerEvent) => void;\n  onLeave: () => void;\n}) {\n  const up = direction === -1;\n  return (\n    <div\n      aria-hidden\n      onPointerEnter={(e) => onEnter(direction, e)}\n      onPointerLeave={onLeave}\n      // Only while hovering a list that can scroll that way; keyboard users\n      // scroll with the highlight instead.\n      className={cn(\n        \"pointer-events-none absolute inset-x-0 flex h-6 items-center justify-center text-muted-foreground opacity-0 transition-[opacity] duration-150 ease-out\",\n        up\n          ? \"top-0 group-data-[hover]:group-data-[up]:pointer-events-auto group-data-[hover]:group-data-[up]:opacity-100\"\n          : \"bottom-0 group-data-[hover]:group-data-[down]:pointer-events-auto group-data-[hover]:group-data-[down]:opacity-100\",\n      )}\n    >\n      <svg\n        viewBox=\"0 0 16 16\"\n        className=\"size-3.5\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      >\n        <path d={up ? \"m4.5 9.5 3.5-3.5 3.5 3.5\" : \"m4.5 6.5 3.5 3.5 3.5-3.5\"} />\n      </svg>\n    </div>\n  );\n}\n\nfunction Check({\n  visible,\n  reduceMotion,\n}: {\n  visible: boolean;\n  reduceMotion: boolean;\n}) {\n  const hidden = reduceMotion\n    ? { scale: 1, opacity: 0, filter: \"blur(0px)\" }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n  return (\n    <motion.svg\n      viewBox=\"0 0 16 16\"\n      aria-hidden\n      className=\"size-4 shrink-0\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      initial={false}\n      animate={visible ? { scale: 1, opacity: 1, filter: \"blur(0px)\" } : hidden}\n      transition={ICON_SWAP}\n    >\n      <path d=\"m3.5 8.5 3 3 6-7\" />\n    </motion.svg>\n  );\n}\n\nconst TIME_ZONES: SelectOption[] = [\n  { value: \"honolulu\", label: \"Honolulu\", detail: \"UTC-10\" },\n  { value: \"anchorage\", label: \"Anchorage\", detail: \"UTC-9\" },\n  { value: \"los-angeles\", label: \"Los Angeles\", detail: \"UTC-8\" },\n  { value: \"denver\", label: \"Denver\", detail: \"UTC-7\" },\n  { value: \"chicago\", label: \"Chicago\", detail: \"UTC-6\" },\n  { value: \"new-york\", label: \"New York\", detail: \"UTC-5\" },\n  { value: \"sao-paulo\", label: \"São Paulo\", detail: \"UTC-3\" },\n  { value: \"london\", label: \"London\", detail: \"UTC+0\" },\n  { value: \"berlin\", label: \"Berlin\", detail: \"UTC+1\" },\n  { value: \"dubai\", label: \"Dubai\", detail: \"UTC+4\" },\n  { value: \"kolkata\", label: \"Kolkata\", detail: \"UTC+5:30\" },\n  { value: \"tokyo\", label: \"Tokyo\", detail: \"UTC+9\" },\n];\n\nconst WEEK_STARTS: SelectOption[] = [\n  { value: \"saturday\", label: \"Saturday\" },\n  { value: \"sunday\", label: \"Sunday\" },\n  { value: \"monday\", label: \"Monday\" },\n];\n\nexport default function SelectMenuDemo() {\n  const [zone, setZone] = useState(\"kolkata\");\n  const [weekStart, setWeekStart] = useState(\"monday\");\n\n  const rows = [\n    { label: \"Time zone\", options: TIME_ZONES, value: zone, onChange: setZone },\n    { label: \"Week starts on\", options: WEEK_STARTS, value: weekStart, onChange: setWeekStart },\n  ];\n\n  return (\n    <div className=\"flex w-[min(440px,100%)] flex-col\">\n      {rows.map((row) => (\n        <div\n          key={row.label}\n          className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3 not-last:border-b not-last:border-border\"\n        >\n          <span aria-hidden className=\"text-sm font-medium text-foreground\">\n            {row.label}\n          </span>\n          <SelectMenu\n            label={row.label}\n            options={row.options}\n            value={row.value}\n            onChange={row.onChange}\n          />\n        </div>\n      ))}\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/select-menu"}