{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"month-picker","type":"registry:component","title":"Date Picker Month Picker","description":"Twelve-month grid with a gliding selection pill, year slides and a zoom-out year grid, single or range mode, min/max and full keyboard navigation, plus a popover month field.","author":"kara <ztzyrant@gmail.com>","dependencies":["clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":[],"files":[{"path":"components/motion/month-picker.tsx","type":"registry:component","target":"@components/motion/month-picker.tsx","content":"\"use client\";\n// karaui.kamisama-v0.my.id/components/motion/date-picker\n\nimport { CalendarDays, ChevronDown, ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport {\n  MorphPopover,\n  MorphPopoverContent,\n  MorphPopoverTrigger,\n} from \"@/components/motion/popover-morph\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n/** A span of months; both ends are the first of their month. */\nexport type MonthRange = { from: Date; to?: Date };\n\ntype MonthPickerBaseProps = {\n  /** Earliest selectable month (any day inside it). */\n  minDate?: Date;\n  /** Latest selectable month (any day inside it). */\n  maxDate?: Date;\n  /** Extra per-month rule; receives the first of the month. */\n  isMonthDisabled?: (month: Date) => boolean;\n  /** Year shown first when nothing is selected. Pass it explicitly for SSR —\n   * without it the current year is read after mount. */\n  defaultYear?: number;\n  /** BCP 47 locale for month names. Default \"en-US\". */\n  locale?: string;\n  className?: string;\n  \"aria-label\"?: string;\n};\n\nexport type MonthPickerSingleProps = MonthPickerBaseProps & {\n  mode?: \"single\";\n  /** First of the selected month. */\n  value?: Date | null;\n  defaultValue?: Date | null;\n  /** Called with the first of the picked month. */\n  onValueChange?: (month: Date) => void;\n};\n\nexport type MonthPickerRangeProps = MonthPickerBaseProps & {\n  mode: \"range\";\n  value?: MonthRange | null;\n  defaultValue?: MonthRange | null;\n  onValueChange?: (range: MonthRange) => void;\n};\n\nexport type MonthPickerProps = MonthPickerSingleProps | MonthPickerRangeProps;\n\n// ── month helpers (local time, month precision) ───────────────────────────\n\nconst startOfMonth = (d: Date) => new Date(d.getFullYear(), d.getMonth(), 1);\nconst addMonths = (d: Date, n: number) =>\n  new Date(d.getFullYear(), d.getMonth() + n, 1);\nconst sameMonth = (a?: Date | null, b?: Date | null) =>\n  !!a &&\n  !!b &&\n  a.getFullYear() === b.getFullYear() &&\n  a.getMonth() === b.getMonth();\nconst monthKey = (d: Date) =>\n  `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \"0\")}`;\n/** First year of the 12-year page that holds `year`. */\nconst pageStart = (year: number) => Math.floor(year / 12) * 12;\n\nconst COLS = 3;\n\n// Year/page swaps reuse the calendar's directional slide: a short travel in\n// the direction you move, with the exit quicker than the entry. Switching\n// between the month and year grids zooms instead, since it changes depth\n// rather than position. Transform + opacity only.\nconst SLIDE_ENTER = { duration: 0.26, ease: EASE_OUT } as const;\nconst SLIDE_EXIT = { duration: 0.16, ease: EASE_OUT } as const;\n\ntype Motion = { dir: number; zoom: number; reduce: boolean };\nconst gridVariants = {\n  enter: ({ dir, zoom, reduce }: Motion) => ({\n    opacity: 0,\n    x: reduce || zoom ? 0 : dir * 28,\n    scale: reduce || !zoom ? 1 : zoom > 0 ? 0.92 : 1.08,\n  }),\n  center: { opacity: 1, x: 0, scale: 1, transition: SLIDE_ENTER },\n  exit: ({ dir, zoom, reduce }: Motion) => ({\n    opacity: 0,\n    x: reduce || zoom ? 0 : dir * -28,\n    scale: reduce || !zoom ? 1 : zoom > 0 ? 1.08 : 0.92,\n    transition: SLIDE_EXIT,\n  }),\n};\n\n/**\n * Month grid for one year (3 × 4), with a selection pill that glides between\n * months on a shared-layout spring. Prev/next slide to neighbouring years;\n * clicking the year zooms out to a 12-year grid. Single month or month range,\n * min/max and per-month disabling, roving-focus keyboard navigation (arrows,\n * Home/End per row, PageUp/PageDown by year — by 12 years in the year grid,\n * Escape back to months). Values are the first of the month. Controlled or\n * uncontrolled; reduced-motion safe.\n */\nexport function MonthPicker(props: MonthPickerProps) {\n  const {\n    minDate,\n    maxDate,\n    isMonthDisabled,\n    defaultYear,\n    locale = \"en-US\",\n    className,\n    \"aria-label\": ariaLabel = \"Choose month\",\n  } = props;\n  const isRange = props.mode === \"range\";\n  const uid = useId();\n  const reduce = useReducedMotion() ?? false;\n\n  // ── selection ──\n  const [internalValue, setInternalValue] = useState<\n    Date | MonthRange | null\n  >(props.defaultValue ?? null);\n  const valueControlled = props.value !== undefined;\n  const value = valueControlled ? (props.value ?? null) : internalValue;\n  const single = isRange ? null : (value as Date | null);\n  const rawRange = isRange ? (value as MonthRange | null) : null;\n  // Compare at month precision even if a caller hands in mid-month dates.\n  const range = rawRange\n    ? {\n        from: startOfMonth(rawRange.from),\n        to: rawRange.to ? startOfMonth(rawRange.to) : undefined,\n      }\n    : null;\n  const anchor = single ?? range?.from ?? null;\n\n  // ── visible year ──\n  // Without a selection or `defaultYear` the year is unknown until mount, so\n  // the server and the first client render agree; the grid then shows the\n  // viewer's current year.\n  const [year, setYearState] = useState<number | null>(\n    anchor?.getFullYear() ?? defaultYear ?? null,\n  );\n  const [today, setToday] = useState<Date | null>(null);\n  useEffect(() => {\n    const now = startOfMonth(new Date());\n    setToday(now);\n    setYearState((y) => y ?? now.getFullYear());\n  }, []);\n  const shownYear = year ?? defaultYear ?? 2026;\n\n  const [view, setView] = useState<\"months\" | \"years\">(\"months\");\n  const [page, setPage] = useState(() => pageStart(shownYear));\n  const [motionState, setMotionState] = useState({ dir: 1, zoom: 0 });\n\n  // ── roving focus ──\n  const [focused, setFocused] = useState<Date>(() =>\n    anchor ? startOfMonth(anchor) : new Date(shownYear, 0, 1),\n  );\n  const [focusedYear, setFocusedYear] = useState(shownYear);\n  const gridRef = useRef<HTMLDivElement>(null);\n  const shouldFocus = useRef(false);\n  const [hovered, setHovered] = useState<Date | null>(null);\n\n  const focusMonth =\n    focused.getFullYear() === shownYear\n      ? focused\n      : anchor && anchor.getFullYear() === shownYear\n        ? startOfMonth(anchor)\n        : new Date(shownYear, 0, 1);\n  const focusYear =\n    focusedYear >= page && focusedYear < page + 12 ? focusedYear : page;\n\n  useEffect(() => {\n    if (!shouldFocus.current) return;\n    shouldFocus.current = false;\n    const sel =\n      view === \"months\"\n        ? `[data-month=\"${monthKey(focusMonth)}\"]`\n        : `[data-year=\"${focusYear}\"]`;\n    gridRef.current?.querySelector<HTMLButtonElement>(sel)?.focus();\n  });\n\n  const minMonth = minDate ? startOfMonth(minDate) : null;\n  const maxMonth = maxDate ? startOfMonth(maxDate) : null;\n  const isDisabled = (m: Date) =>\n    (!!minMonth && m < minMonth) ||\n    (!!maxMonth && m > maxMonth) ||\n    !!isMonthDisabled?.(m);\n  const yearDisabled = (y: number) =>\n    (!!minMonth && y < minMonth.getFullYear()) ||\n    (!!maxMonth && y > maxMonth.getFullYear());\n\n  const goYear = (next: number) => {\n    if (next === shownYear) return;\n    setMotionState({ dir: next > shownYear ? 1 : -1, zoom: 0 });\n    setYearState(next);\n  };\n  const goPage = (next: number) => {\n    if (next === page) return;\n    setMotionState({ dir: next > page ? 1 : -1, zoom: 0 });\n    setPage(next);\n  };\n  const openYears = () => {\n    setMotionState({ dir: 1, zoom: 1 });\n    setPage(pageStart(shownYear));\n    setFocusedYear(shownYear);\n    setView(\"years\");\n    shouldFocus.current = true;\n  };\n  const closeYears = (y: number) => {\n    setMotionState({ dir: 1, zoom: -1 });\n    setYearState(y);\n    setFocused(new Date(y, focusMonth.getMonth(), 1));\n    setView(\"months\");\n    shouldFocus.current = true;\n  };\n\n  const select = (m: Date) => {\n    if (isDisabled(m)) return;\n    setFocused(m);\n    if (!isRange) {\n      if (!valueControlled) setInternalValue(m);\n      (props as MonthPickerSingleProps).onValueChange?.(m);\n      return;\n    }\n    // First click starts a range; a later month closes it; an earlier month\n    // or a click on a finished range starts over.\n    const next: MonthRange =\n      range && !range.to && m >= range.from\n        ? { from: range.from, to: m }\n        : { from: m };\n    if (!valueControlled) setInternalValue(next);\n    (props as MonthPickerRangeProps).onValueChange?.(next);\n  };\n\n  const onMonthKeyDown = (e: KeyboardEvent) => {\n    const base = focusMonth;\n    const col = base.getMonth() % COLS;\n    const delta: Record<string, number> = {\n      ArrowLeft: -1,\n      ArrowRight: 1,\n      ArrowUp: -COLS,\n      ArrowDown: COLS,\n      Home: -col,\n      End: COLS - 1 - col,\n      PageUp: -12,\n      PageDown: 12,\n    };\n    if (!(e.key in delta)) return;\n    e.preventDefault();\n    const next = addMonths(base, delta[e.key]);\n    shouldFocus.current = true;\n    setFocused(next);\n    goYear(next.getFullYear());\n  };\n\n  const onYearKeyDown = (e: KeyboardEvent) => {\n    if (e.key === \"Escape\") {\n      // Stop the surrounding popover (if any) from closing as well.\n      e.preventDefault();\n      e.stopPropagation();\n      e.nativeEvent.stopImmediatePropagation();\n      closeYears(shownYear);\n      return;\n    }\n    const col = (focusYear - page) % COLS;\n    const delta: Record<string, number> = {\n      ArrowLeft: -1,\n      ArrowRight: 1,\n      ArrowUp: -COLS,\n      ArrowDown: COLS,\n      Home: -col,\n      End: COLS - 1 - col,\n      PageUp: -12,\n      PageDown: 12,\n    };\n    if (!(e.key in delta)) return;\n    e.preventDefault();\n    const next = focusYear + delta[e.key];\n    shouldFocus.current = true;\n    setFocusedYear(next);\n    goPage(pageStart(next));\n  };\n\n  // ── labels ──\n  const monthNames = useMemo(() => {\n    const short = new Intl.DateTimeFormat(locale, { month: \"short\" });\n    const long = new Intl.DateTimeFormat(locale, {\n      month: \"long\",\n      year: \"numeric\",\n    });\n    return {\n      short: (d: Date) => short.format(d),\n      long: (d: Date) => long.format(d),\n    };\n  }, [locale]);\n\n  const prevDisabled =\n    view === \"months\"\n      ? !!minMonth && minMonth.getFullYear() >= shownYear\n      : !!minMonth && minMonth.getFullYear() >= page;\n  const nextDisabled =\n    view === \"months\"\n      ? !!maxMonth && maxMonth.getFullYear() <= shownYear\n      : !!maxMonth && maxMonth.getFullYear() <= page + 11;\n\n  const bandEnd =\n    range && !range.to && hovered && hovered > range.from\n      ? hovered\n      : range?.to;\n\n  const navButton =\n    \"inline-flex size-8 items-center justify-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40\";\n  const cell =\n    \"relative isolate flex h-10 w-full items-center justify-center rounded-lg text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring\";\n\n  const gridKey = view === \"months\" ? `m-${shownYear}` : `y-${page}`;\n  const custom: Motion = { ...motionState, reduce };\n  const headerLabel =\n    view === \"months\" ? String(shownYear) : `${page} – ${page + 11}`;\n\n  return (\n    <div\n      className={cn(\n        \"w-72 rounded-2xl border border-border bg-card p-3 text-foreground\",\n        className,\n      )}\n    >\n      <div className=\"mb-2 flex items-center justify-between gap-2\">\n        <button\n          type=\"button\"\n          aria-label={view === \"months\" ? \"Previous year\" : \"Previous years\"}\n          disabled={prevDisabled}\n          onClick={() =>\n            view === \"months\" ? goYear(shownYear - 1) : goPage(page - 12)\n          }\n          className={navButton}\n        >\n          <ChevronLeft className=\"h-4 w-4\" />\n        </button>\n        <button\n          type=\"button\"\n          aria-label={\n            view === \"months\"\n              ? `${shownYear}, choose year`\n              : `${headerLabel}, back to months`\n          }\n          onClick={() => (view === \"months\" ? openYears() : closeYears(shownYear))}\n          className=\"inline-flex h-8 items-center gap-1 rounded-lg px-2 text-sm font-medium tabular-nums outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring\"\n        >\n          <span aria-live=\"polite\" className={cn(year === null && \"invisible\")}>\n            {headerLabel}\n          </span>\n          <motion.span\n            aria-hidden\n            animate={{ rotate: view === \"years\" ? 180 : 0 }}\n            transition={reduce ? { duration: 0 } : SPRING_PRESS}\n            className=\"inline-flex text-muted-foreground\"\n          >\n            <ChevronDown className=\"h-3.5 w-3.5\" />\n          </motion.span>\n        </button>\n        <button\n          type=\"button\"\n          aria-label={view === \"months\" ? \"Next year\" : \"Next years\"}\n          disabled={nextDisabled}\n          onClick={() =>\n            view === \"months\" ? goYear(shownYear + 1) : goPage(page + 12)\n          }\n          className={navButton}\n        >\n          <ChevronRight className=\"h-4 w-4\" />\n        </button>\n      </div>\n\n      <div\n        ref={gridRef}\n        // Padded so focus rings on edge cells aren't clipped by the slide mask.\n        className=\"relative -m-1 overflow-hidden p-1\"\n        onPointerLeave={() => setHovered(null)}\n      >\n        <AnimatePresence initial={false} mode=\"popLayout\" custom={custom}>\n          <motion.div\n            key={gridKey}\n            custom={custom}\n            variants={gridVariants}\n            initial=\"enter\"\n            animate=\"center\"\n            exit=\"exit\"\n            role=\"group\"\n            aria-label={\n              view === \"months\" ? `${ariaLabel}, ${shownYear}` : \"Choose year\"\n            }\n            onKeyDown={view === \"months\" ? onMonthKeyDown : onYearKeyDown}\n            className={cn(\n              \"grid grid-cols-3 gap-1\",\n              // Unknown year until mount (see above): hold the grid back\n              // rather than flash a placeholder year.\n              year === null && \"invisible\",\n            )}\n          >\n            {view === \"months\"\n              ? Array.from({ length: 12 }, (_, i) => {\n                  const m = new Date(shownYear, i, 1);\n                  const disabled = isDisabled(m);\n                  const isFrom = sameMonth(m, range?.from);\n                  const isTo = sameMonth(m, bandEnd);\n                  const inBand =\n                    !!range?.from && !!bandEnd && m > range.from && m < bandEnd;\n                  const selected = isRange\n                    ? isFrom || (isTo && !!range?.to)\n                    : sameMonth(m, single);\n                  const isNow = sameMonth(m, today);\n                  return (\n                    <button\n                      key={monthKey(m)}\n                      type=\"button\"\n                      data-month={monthKey(m)}\n                      tabIndex={sameMonth(m, focusMonth) ? 0 : -1}\n                      aria-label={monthNames.long(m)}\n                      aria-pressed={selected}\n                      aria-disabled={disabled || undefined}\n                      aria-current={isNow ? \"date\" : undefined}\n                      onClick={() => select(m)}\n                      onFocus={() => setFocused(m)}\n                      onPointerEnter={() => isRange && setHovered(m)}\n                      className={cn(\n                        cell,\n                        inBand && \"bg-primary/10\",\n                        !selected && !inBand && !disabled && \"hover:bg-muted\",\n                        selected ? \"text-primary-foreground\" : \"text-foreground\",\n                        isTo && !range?.to && \"text-foreground\",\n                        disabled &&\n                          \"cursor-not-allowed text-muted-foreground/40 line-through\",\n                      )}\n                    >\n                      {selected &&\n                        (isRange ? (\n                          <motion.span\n                            aria-hidden\n                            initial={reduce ? false : { scale: 0.7 }}\n                            animate={{ scale: 1 }}\n                            transition={SPRING_PRESS}\n                            className=\"absolute inset-0 -z-10 rounded-lg bg-primary\"\n                          />\n                        ) : (\n                          <motion.span\n                            aria-hidden\n                            // Scoped per year so the pill glides between\n                            // months but never across the sliding grids.\n                            layoutId={`${uid}-${shownYear}-month`}\n                            transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                            className=\"absolute inset-0 -z-10 rounded-lg bg-primary\"\n                          />\n                        ))}\n                      {isTo && !range?.to && (\n                        <span\n                          aria-hidden\n                          className=\"absolute inset-0 -z-10 rounded-lg border border-primary/40\"\n                        />\n                      )}\n                      {monthNames.short(m)}\n                      {isNow && (\n                        <span\n                          aria-hidden\n                          className={cn(\n                            \"absolute bottom-1.5 size-1 rounded-full\",\n                            selected ? \"bg-primary-foreground\" : \"bg-primary\",\n                          )}\n                        />\n                      )}\n                    </button>\n                  );\n                })\n              : Array.from({ length: 12 }, (_, i) => {\n                  const y = page + i;\n                  const disabled = yearDisabled(y);\n                  const selected = y === shownYear;\n                  return (\n                    <button\n                      key={y}\n                      type=\"button\"\n                      data-year={y}\n                      tabIndex={y === focusYear ? 0 : -1}\n                      aria-pressed={selected}\n                      aria-disabled={disabled || undefined}\n                      aria-current={today?.getFullYear() === y ? \"date\" : undefined}\n                      onClick={() => !disabled && closeYears(y)}\n                      onFocus={() => setFocusedYear(y)}\n                      className={cn(\n                        cell,\n                        \"tabular-nums\",\n                        selected ? \"text-primary-foreground\" : \"text-foreground\",\n                        !selected && !disabled && \"hover:bg-muted\",\n                        disabled &&\n                          \"cursor-not-allowed text-muted-foreground/40 line-through\",\n                      )}\n                    >\n                      {selected && (\n                        <motion.span\n                          aria-hidden\n                          layoutId={`${uid}-${page}-year`}\n                          transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                          className=\"absolute inset-0 -z-10 rounded-lg bg-primary\"\n                        />\n                      )}\n                      {y}\n                    </button>\n                  );\n                })}\n          </motion.div>\n        </AnimatePresence>\n      </div>\n    </div>\n  );\n}\n\nconst MONTH_YEAR: Intl.DateTimeFormatOptions = {\n  month: \"long\",\n  year: \"numeric\",\n};\n\nexport interface MonthFieldProps\n  extends Omit<\n    MonthPickerSingleProps,\n    \"mode\" | \"value\" | \"defaultValue\" | \"onValueChange\" | \"className\"\n  > {\n  value?: Date | null;\n  defaultValue?: Date | null;\n  onValueChange?: (month: Date) => void;\n  placeholder?: string;\n  /** Intl options for the trigger label. Default \"October 2026\". */\n  formatOptions?: Intl.DateTimeFormatOptions;\n  align?: \"start\" | \"end\";\n  disabled?: boolean;\n  className?: string;\n}\n\n/**\n * Month field whose month grid morphs open from the trigger corner and closes\n * as soon as a month is picked. Controlled or uncontrolled.\n */\nexport function MonthField({\n  value: controlledValue,\n  defaultValue = null,\n  onValueChange,\n  placeholder = \"Pick a month\",\n  formatOptions = MONTH_YEAR,\n  locale = \"en-US\",\n  align = \"start\",\n  disabled,\n  className,\n  \"aria-label\": ariaLabel = \"Choose month\",\n  ...pickerProps\n}: MonthFieldProps) {\n  const [open, setOpen] = useState(false);\n  const [internal, setInternal] = useState<Date | null>(defaultValue);\n  const value = controlledValue !== undefined ? controlledValue : internal;\n\n  const label = useMemo(\n    () =>\n      value ? new Intl.DateTimeFormat(locale, formatOptions).format(value) : null,\n    [value, locale, formatOptions],\n  );\n\n  return (\n    <MorphPopover open={open} onOpenChange={setOpen}>\n      <MorphPopoverTrigger>\n        <button\n          type=\"button\"\n          disabled={disabled}\n          aria-label={label ? `${ariaLabel}, ${label}` : ariaLabel}\n          className={cn(\n            \"inline-flex h-10 min-w-44 items-center gap-2 rounded-xl border border-border bg-background px-3 text-left text-sm outline-none transition-colors hover:border-border-strong focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50\",\n            label ? \"text-foreground\" : \"text-muted-foreground\",\n            className,\n          )}\n        >\n          <CalendarDays className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n          <span className=\"flex-1 truncate tabular-nums\">\n            {label ?? placeholder}\n          </span>\n        </button>\n      </MorphPopoverTrigger>\n\n      <MorphPopoverContent align={align} className=\"p-0\">\n        <MonthPicker\n          {...pickerProps}\n          aria-label={ariaLabel}\n          locale={locale}\n          value={value}\n          onValueChange={(m) => {\n            if (controlledValue === undefined) setInternal(m);\n            onValueChange?.(m);\n            setOpen(false);\n          }}\n          className=\"border-0 bg-transparent\"\n        />\n      </MorphPopoverContent>\n    </MorphPopover>\n  );\n}\n"},{"path":"components/motion/popover-morph.tsx","type":"registry:component","target":"@components/motion/popover-morph.tsx","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  toggle: () => void;\n  triggerId: string;\n  contentId: string;\n  /** The element the panel measures against — see `registerTrigger`. */\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  registerTrigger: (node: HTMLElement | null) => void;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n  const ctx = useContext(MorphContext);\n  if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n  return ctx;\n}\n\nexport interface MorphPopoverProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  className?: string;\n}\n\n/**\n * A popover whose panel morphs open from the trigger corner: it's laid out at\n * full size but clipped to the corner nearest the trigger, then unclips as one\n * piece. Closes on outside pointer / Escape. Controlled or uncontrolled.\n */\nexport function MorphPopover({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: MorphPopoverProps) {\n  const baseId = useId();\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n  const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n  // A trigger normally registers itself through MorphPopoverTrigger. It can't\n  // when something else already clones the element — a Tooltip wrapping the\n  // button, say — and an unregistered trigger leaves the panel with nothing to\n  // measure against, so it renders permanently invisible. The root boxes the\n  // trigger exactly (the content portals out of it), so it stands in until a\n  // real trigger registers, and stands in again if that one unmounts. Both are\n  // state, so a trigger arriving while the panel is open re-anchors it.\n  const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n    () => ({ current: trigger ?? root }),\n    [root, trigger],\n  );\n\n  // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n  // focus cannot be left sitting inside it: a dismissal hands it back to the\n  // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n  // the focus onward itself when it lands on something focusable — this only\n  // catches the case where it would otherwise be stranded. When no trigger has\n  // registered, the root anchor stands in only if it can actually hold focus;\n  // there is nowhere better than where the keyboard already is, so leave it.\n  const close = useCallback(() => {\n    setOpen(false);\n    const focused = document.activeElement;\n    const inPanel =\n      focused instanceof HTMLElement && contentRef.current?.contains(focused);\n    if (!inPanel) return;\n    const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n    restore?.focus();\n  }, [root, setOpen, trigger]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onKey = (e: KeyboardEvent) => e.key === \"Escape\" && close();\n    const onPointer = (e: PointerEvent) => {\n      const target = e.target as Node;\n      if (\n        root &&\n        !root.contains(target) &&\n        !contentRef.current?.contains(target)\n      )\n        close();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    window.addEventListener(\"pointerdown\", onPointer);\n    return () => {\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer);\n    };\n  }, [open, root, close]);\n\n  const ctx = useMemo<MorphContextValue>(\n    () => ({\n      open,\n      setOpen,\n      toggle,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef: anchorRef,\n      registerTrigger: setTrigger,\n      contentRef,\n    }),\n    [open, setOpen, toggle, baseId, anchorRef],\n  );\n\n  return (\n    <MorphContext.Provider value={ctx}>\n      <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n        {children}\n      </div>\n    </MorphContext.Provider>\n  );\n}\n\nexport interface MorphPopoverTriggerProps {\n  children: ReactElement;\n}\n\nfunction mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref && typeof ref === \"object\")\n        (ref as React.MutableRefObject<T | null>).current = node;\n    }\n  };\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n  const ctx = useMorphContext(\"MorphPopoverTrigger\");\n  if (!isValidElement(children)) return children;\n\n  const child = children as ReactElement<Record<string, unknown>>;\n  const childOnClick = child.props.onClick as\n    | ((e: unknown) => void)\n    | undefined;\n  const childRef = (child.props as { ref?: Ref<HTMLElement> }).ref;\n\n  return cloneElement(child, {\n    id: ctx.triggerId,\n    ref: mergeRefs(childRef, ctx.registerTrigger),\n    onClick: (e: unknown) => {\n      childOnClick?.(e);\n      ctx.toggle();\n    },\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": ctx.open,\n    \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n  });\n}\n\nconst originFor = (side: Side, align: Align) =>\n  `${side === \"bottom\" ? \"top\" : \"bottom\"} ${align === \"end\" ? \"right\" : \"left\"}`;\n\n// A clip that hides everything but the corner nearest the trigger, so the\n// panel appears to grow out of it. inset(top right bottom left).\nfunction clipHidden(side: Side, align: Align, radius: number) {\n  const top = side === \"bottom\" ? \"0%\" : \"92%\";\n  const bottom = side === \"bottom\" ? \"92%\" : \"0%\";\n  const right = align === \"end\" ? \"0%\" : \"92%\";\n  const left = align === \"end\" ? \"92%\" : \"0%\";\n  return `inset(${top} ${right} ${bottom} ${left} round ${radius}px)`;\n}\nconst clipShown = (radius: number) => `inset(0% 0% 0% 0% round ${radius}px)`;\n\n// Preserve the original spring character on the wrapper, but tween the complex\n// clip-path so it cannot snap when the spring resolves its final distance.\nconst MORPH_CLIP_TRANSITION = { duration: 0.32, ease: EASE_OUT } as const;\n\nexport interface MorphPopoverContentProps {\n  children: ReactNode;\n  side?: Side;\n  align?: Align;\n  /** Gap between trigger and panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Panel corner radius, in px. Default 16. */\n  radius?: number;\n  className?: string;\n}\n\nexport function MorphPopoverContent({\n  children,\n  side = \"bottom\",\n  align = \"end\",\n  sideOffset = 8,\n  radius = 16,\n  className,\n}: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const reduce = useReducedMotion() ?? false;\n  const [portalReady, setPortalReady] = useState(false);\n  const layout = usePopoverPortalPosition(\n    ctx.triggerRef,\n    ctx.contentRef,\n    portalReady && ctx.open,\n  );\n\n  useEffect(() => setPortalReady(true), []);\n  const left = layout\n    ? align === \"end\"\n      ? layout.trigger.left + layout.trigger.width - layout.content.width\n      : layout.trigger.left\n    : 0;\n  const top = layout\n    ? side === \"bottom\"\n      ? layout.trigger.top + layout.trigger.height + sideOffset\n      : layout.trigger.top - layout.content.height - sideOffset\n    : 0;\n\n  // Both directions travel between the exact same hidden/show states. Exit\n  // targets \"hidden\" directly instead of introducing separate choreography.\n  const wrap = reduce\n    ? undefined\n    : {\n        hidden: { opacity: 0, scale: 0.96, transition: SPRING_PANEL },\n        show: { opacity: 1, scale: 1, transition: SPRING_PANEL },\n      };\n  const clip = reduce\n    ? undefined\n    : {\n        hidden: {\n          clipPath: clipHidden(side, align, radius),\n          transition: MORPH_CLIP_TRANSITION,\n        },\n        show: {\n          clipPath: clipShown(radius),\n          transition: MORPH_CLIP_TRANSITION,\n        },\n      };\n\n  // Keep the server and first client render identical, then mount the portal.\n  if (!portalReady) return null;\n\n  return createPortal(\n    <AnimatePresence>\n      {ctx.open ? (\n        <motion.div\n          data-morph-popover-portal=\"\"\n          // Wrapper carries the shadow as a drop-shadow filter, which hugs the\n          // clipped shape below (box-shadow would just get clipped away).\n          variants={wrap}\n          initial={reduce ? { opacity: 0 } : \"hidden\"}\n          animate={reduce ? { opacity: 1 } : \"show\"}\n          exit={reduce ? { opacity: 0 } : \"hidden\"}\n          transition={reduce ? { duration: 0.12 } : undefined}\n          style={{\n            left,\n            top,\n            visibility: layout ? \"visible\" : \"hidden\",\n            transformOrigin: originFor(side, align),\n          }}\n          className=\"fixed z-[9999] [filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\"\n        >\n          <motion.div\n            ref={ctx.contentRef}\n            id={ctx.contentId}\n            role=\"dialog\"\n            aria-labelledby={ctx.triggerId}\n            variants={clip}\n            style={{ borderRadius: radius }}\n            className={cn(\n              \"overflow-hidden border border-border bg-background\",\n              className,\n            )}\n          >\n            {children}\n          </motion.div>\n        </motion.div>\n      ) : null}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps — label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances — modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides — pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) — critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/motion/popover-position.ts","type":"registry:component","target":"@components/motion/popover-position.ts","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"}]}