{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pantograph",
  "type": "registry:ui",
  "title": "Pantograph",
  "description": "Morphing flyout nav where one shared dark-glass panel slides and resizes between triggers instead of closing and reopening — an anticipation-stretch morph with a caret that tracks the active trigger and content that crossfades in from the direction of travel. Hover-intent grace, full disclosure semantics (focus opens, Escape closes, arrow keys move triggers), and instant repositioning under reduced motion.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/default/navigation/pantograph/pantograph.tsx",
      "type": "registry:ui",
      "target": "components/crucible/pantograph.tsx",
      "content": "\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  useTransform,\n  type Variants,\n} from \"motion/react\";\nimport * as React from \"react\";\n\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface PantographItem {\n  /** Unique value identifying this trigger. */\n  value: string;\n  /** Trigger label shown in the bar. */\n  label: React.ReactNode;\n  /**\n   * Flyout panel content for this trigger. Omit for a plain trigger that\n   * navigates (via `href`) without opening a panel.\n   */\n  content?: React.ReactNode;\n  /** Optional href — renders the trigger as a link. */\n  href?: string;\n}\n\nexport interface PantographProps\n  extends Omit<\n    React.ComponentPropsWithoutRef<\"nav\">,\n    \"onChange\" | \"value\" | \"defaultValue\"\n  > {\n  /** Triggers to render, left to right. @default a small generic set */\n  items?: PantographItem[];\n  /** How a flyout opens on pointer devices. @default \"hover\" */\n  openOn?: \"hover\" | \"click\";\n  /** Show the caret that tracks the active trigger. @default true */\n  caret?: boolean;\n  /**\n   * Grace period in ms before the panel closes after the pointer leaves —\n   * the hover-intent forgiveness that stops flicker on diagonal travel.\n   * @default 150\n   */\n  closeDelay?: number;\n  /**\n   * Incoming content slides in from the direction of travel (`\"directional\"`)\n   * or simply crossfades in place (`\"crossfade\"`). @default \"directional\"\n   */\n  contentTransition?: \"directional\" | \"crossfade\";\n  /** Spring physics for the panel morph. */\n  spring?: { stiffness?: number; damping?: number; mass?: number };\n  /** Min panel width in px. @default 200 */\n  minWidth?: number;\n  /** Max panel width in px. @default 560 */\n  maxWidth?: number;\n  /** Controlled active trigger value; `null` means closed. */\n  value?: string | null;\n  /** Initial active trigger when uncontrolled. @default null (closed) */\n  defaultValue?: string | null;\n  /** Fires whenever the active trigger changes (a value, or `null` on close). */\n  onValueChange?: (value: string | null) => void;\n}\n\nconst DEFAULT_SPRING = { stiffness: 440, damping: 40, mass: 0.9 };\nconst CONTENT_SHIFT = 22;\nconst CARET_PAD = 20;\n\nfunction clamp(v: number, lo: number, hi: number): number {\n  return Math.min(Math.max(v, lo), hi);\n}\n\nfunction LinkList({\n  links,\n}: {\n  links: { label: string; hint?: string; href?: string }[];\n}) {\n  return (\n    <ul className=\"grid w-max min-w-52 gap-0.5\">\n      {links.map((l) => (\n        <li key={l.label}>\n          <a\n            href={l.href ?? \"#\"}\n            className=\"group/link flex flex-col rounded-lg px-3 py-2 transition-colors hover:bg-white/6 focus-visible:bg-white/6 focus-visible:outline-none\"\n          >\n            <span className=\"text-sm font-medium text-white/85 transition-colors group-hover/link:text-white\">\n              {l.label}\n            </span>\n            {l.hint ? (\n              <span className=\"text-xs text-white/45\">{l.hint}</span>\n            ) : null}\n          </a>\n        </li>\n      ))}\n    </ul>\n  );\n}\n\nconst DEFAULT_ITEMS: PantographItem[] = [\n  {\n    value: \"products\",\n    label: \"Products\",\n    content: (\n      <LinkList\n        links={[\n          { label: \"Overview\", hint: \"The whole platform at a glance\" },\n          { label: \"Automation\", hint: \"Rules that run themselves\" },\n          { label: \"Insights\", hint: \"Live dashboards and reports\" },\n        ]}\n      />\n    ),\n  },\n  {\n    value: \"pricing\",\n    label: \"Pricing\",\n    content: (\n      <LinkList\n        links={[\n          { label: \"Plans\", hint: \"Pick a tier that fits\" },\n          { label: \"Enterprise\", hint: \"Volume and SSO\" },\n        ]}\n      />\n    ),\n  },\n  {\n    value: \"company\",\n    label: \"Company\",\n    content: (\n      <LinkList\n        links={[\n          { label: \"About\", hint: \"Who we are\" },\n          { label: \"Careers\", hint: \"Join the team\" },\n          { label: \"Blog\", hint: \"News and writing\" },\n          { label: \"Contact\", hint: \"Talk to us\" },\n        ]}\n      />\n    ),\n  },\n];\n\n/**\n * Pantograph — a horizontal nav where hovering a trigger opens a single shared\n * flyout that *morphs* to the next trigger instead of closing and reopening:\n * the panel slides along the bar and resizes to fit each trigger's content\n * while the caret tracks the active trigger and the content crossfades in from\n * the direction of travel. The signature is an *anticipation stretch* — the\n * panel's leading edge extends toward the new trigger a beat before the body\n * follows and the trailing edge snaps in, so it reads as one window panning\n * over a continuous surface. Hover-intent grace prevents flicker on diagonal\n * travel. Full disclosure semantics: focus opens, Escape closes, arrow keys\n * move between triggers, `aria-expanded` reflects state. On coarse pointers it\n * opens on tap; under `prefers-reduced-motion` the panel repositions instantly\n * and the content simply crossfades.\n */\nexport function Pantograph({\n  items = DEFAULT_ITEMS,\n  openOn = \"hover\",\n  caret = true,\n  closeDelay = 150,\n  contentTransition = \"directional\",\n  spring,\n  minWidth = 200,\n  maxWidth = 560,\n  value,\n  defaultValue = null,\n  onValueChange,\n  className,\n  ...props\n}: PantographProps) {\n  const reducedMotion = useReducedMotion();\n  const baseId = React.useId();\n  const panelId = `${baseId}-panel`;\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const barRef = React.useRef<HTMLDivElement>(null);\n  const triggerRefs = React.useRef<Map<string, HTMLElement>>(new Map());\n  const measureRefs = React.useRef<Map<string, HTMLDivElement>>(new Map());\n  const closeTimer = React.useRef<number | null>(null);\n\n  const springCfg = { ...DEFAULT_SPRING, ...spring };\n\n  // ---- open / active state (controlled or not) -----------------------------\n  const [internalValue, setInternalValue] = React.useState<string | null>(\n    defaultValue\n  );\n  const activeValue = value !== undefined ? value : internalValue;\n  const [direction, setDirection] = React.useState(1);\n  const [focusValue, setFocusValue] = React.useState<string>(\n    items[0]?.value ?? \"\"\n  );\n  const [finePointer, setFinePointer] = React.useState(true);\n\n  const activeItem = items.find(\n    (i) => i.value === activeValue && i.content != null\n  );\n  const open = activeItem != null;\n\n  const setActive = React.useCallback(\n    (next: string | null) => {\n      if (next && activeValue && next !== activeValue) {\n        const a = triggerCentersRef.current[activeValue];\n        const b = triggerCentersRef.current[next];\n        if (a != null && b != null) setDirection(b > a ? 1 : -1);\n      }\n      if (value === undefined) setInternalValue(next);\n      onValueChange?.(next);\n    },\n    [activeValue, value, onValueChange]\n  );\n\n  // ---- layout measurement --------------------------------------------------\n  const [navWidth, setNavWidth] = React.useState(0);\n  const [dims, setDims] = React.useState<\n    Record<string, { w: number; h: number }>\n  >({});\n  const triggerCentersRef = React.useRef<Record<string, number>>({});\n\n  const measureTriggers = React.useCallback(() => {\n    const bar = barRef.current;\n    if (!bar) return;\n    const barRect = bar.getBoundingClientRect();\n    setNavWidth(barRect.width);\n    const centers: Record<string, number> = {};\n    for (const item of items) {\n      const el = triggerRefs.current.get(item.value);\n      if (el) {\n        const r = el.getBoundingClientRect();\n        centers[item.value] = r.left - barRect.left + r.width / 2;\n      }\n    }\n    triggerCentersRef.current = centers;\n  }, [items]);\n\n  React.useLayoutEffect(() => {\n    measureTriggers();\n    if (typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver(() => measureTriggers());\n    if (barRef.current) ro.observe(barRef.current);\n    return () => ro.disconnect();\n  }, [measureTriggers]);\n\n  // Measure each trigger's natural content size (padding included).\n  React.useLayoutEffect(() => {\n    if (typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver((entries) => {\n      setDims((prev) => {\n        let changed = false;\n        const next = { ...prev };\n        for (const entry of entries) {\n          const key = entry.target.getAttribute(\"data-measure-key\");\n          if (!key) continue;\n          const el = entry.target as HTMLElement;\n          const w = el.offsetWidth;\n          const h = el.offsetHeight;\n          if (!next[key] || next[key].w !== w || next[key].h !== h) {\n            next[key] = { w, h };\n            changed = true;\n          }\n        }\n        return changed ? next : prev;\n      });\n    });\n    for (const el of measureRefs.current.values()) ro.observe(el);\n    return () => ro.disconnect();\n  }, [items]);\n\n  // ---- morph motion values -------------------------------------------------\n  const leftMV = useMotionValue(0);\n  const rightMV = useMotionValue(0);\n  const heightMV = useMotionValue(0);\n  const caretCenterMV = useMotionValue(0);\n  const widthMV = useTransform([leftMV, rightMV], (latest: number[]) =>\n    Math.max(0, latest[1] - latest[0])\n  );\n  const caretX = useTransform(\n    [caretCenterMV, leftMV, rightMV],\n    (latest: number[]) => {\n      const [c, l, r] = latest;\n      return clamp(c - l, CARET_PAD, Math.max(CARET_PAD, r - l - CARET_PAD));\n    }\n  );\n\n  const wasOpenRef = React.useRef(false);\n\n  React.useEffect(() => {\n    if (!open || !activeValue) {\n      wasOpenRef.current = false;\n      return;\n    }\n    const dim = dims[activeValue];\n    const center = triggerCentersRef.current[activeValue];\n    if (!dim || center == null || !navWidth) return;\n\n    const w = clamp(dim.w, minWidth, maxWidth);\n    const h = dim.h;\n    let targetLeft: number;\n    if (w >= navWidth) targetLeft = (navWidth - w) / 2;\n    else targetLeft = clamp(center - w / 2, 0, navWidth - w);\n    const targetRight = targetLeft + w;\n\n    if (!wasOpenRef.current || reducedMotion) {\n      // Fresh open or reduced motion: seat the panel with no morph theatrics.\n      leftMV.set(targetLeft);\n      rightMV.set(targetRight);\n      heightMV.set(h);\n      caretCenterMV.set(center);\n    } else {\n      // Anticipation stretch: the leading edge (toward the new trigger) springs\n      // fast and arrives first; the trailing edge follows a beat behind, so the\n      // panel visibly stretches before it settles.\n      const movingRight = targetLeft > leftMV.get();\n      const lead = {\n        type: \"spring\" as const,\n        stiffness: springCfg.stiffness * 1.7,\n        damping: springCfg.damping * 1.05,\n        mass: springCfg.mass * 0.85,\n      };\n      const trail = {\n        type: \"spring\" as const,\n        stiffness: springCfg.stiffness * 0.85,\n        damping: springCfg.damping,\n        mass: springCfg.mass,\n        delay: 0.05,\n      };\n      if (movingRight) {\n        animate(rightMV, targetRight, lead);\n        animate(leftMV, targetLeft, trail);\n      } else {\n        animate(leftMV, targetLeft, lead);\n        animate(rightMV, targetRight, trail);\n      }\n      animate(heightMV, h, {\n        type: \"spring\",\n        stiffness: springCfg.stiffness,\n        damping: springCfg.damping,\n        mass: springCfg.mass,\n      });\n      animate(caretCenterMV, center, {\n        type: \"spring\",\n        stiffness: 700,\n        damping: 44,\n      });\n    }\n    wasOpenRef.current = true;\n    // springCfg is derived each render; deps below cover its inputs via `spring`.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, activeValue, dims, navWidth, reducedMotion, minWidth, maxWidth]);\n\n  // ---- pointer / focus intent ---------------------------------------------\n  React.useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mql = window.matchMedia(\"(pointer: fine)\");\n    const sync = () => setFinePointer(mql.matches);\n    sync();\n    mql.addEventListener(\"change\", sync);\n    return () => mql.removeEventListener(\"change\", sync);\n  }, []);\n\n  React.useEffect(\n    () => () => {\n      if (closeTimer.current != null) window.clearTimeout(closeTimer.current);\n    },\n    []\n  );\n\n  const cancelClose = React.useCallback(() => {\n    if (closeTimer.current != null) {\n      window.clearTimeout(closeTimer.current);\n      closeTimer.current = null;\n    }\n  }, []);\n\n  const scheduleClose = React.useCallback(() => {\n    cancelClose();\n    closeTimer.current = window.setTimeout(() => setActive(null), closeDelay);\n  }, [cancelClose, closeDelay, setActive]);\n\n  const hoverMode = openOn === \"hover\" && finePointer;\n\n  const handleTriggerEnter = (item: PantographItem) => {\n    if (!hoverMode) return;\n    cancelClose();\n    if (item.content != null) setActive(item.value);\n    else setActive(null);\n  };\n\n  const handleTriggerClick = (item: PantographItem) => {\n    if (item.content == null) return; // let the link/button do its thing\n    if (openOn === \"click\" || !finePointer) {\n      setActive(activeValue === item.value ? null : item.value);\n    }\n  };\n\n  // Click-away for click / touch open.\n  React.useEffect(() => {\n    if (!open || hoverMode) return;\n    const onDown = (e: PointerEvent) => {\n      if (!rootRef.current?.contains(e.target as Node)) setActive(null);\n    };\n    document.addEventListener(\"pointerdown\", onDown);\n    return () => document.removeEventListener(\"pointerdown\", onDown);\n  }, [open, hoverMode, setActive]);\n\n  // ---- keyboard: roving focus across triggers ------------------------------\n  const enabledItems = items;\n  const moveFocus = (fromValue: string, dir: 1 | -1 | \"home\" | \"end\") => {\n    const count = enabledItems.length;\n    if (count === 0) return;\n    let idx = enabledItems.findIndex((i) => i.value === fromValue);\n    if (idx < 0) idx = 0;\n    let nextIdx: number;\n    if (dir === \"home\") nextIdx = 0;\n    else if (dir === \"end\") nextIdx = count - 1;\n    else nextIdx = (idx + dir + count) % count;\n    const next = enabledItems[nextIdx];\n    if (!next) return;\n    setFocusValue(next.value);\n    triggerRefs.current.get(next.value)?.focus();\n    if (open) {\n      if (next.content != null) setActive(next.value);\n      else setActive(null);\n    }\n  };\n\n  const handleBarKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    const from = focusValue || items[0]?.value || \"\";\n    switch (e.key) {\n      case \"ArrowRight\":\n        e.preventDefault();\n        moveFocus(from, 1);\n        break;\n      case \"ArrowLeft\":\n        e.preventDefault();\n        moveFocus(from, -1);\n        break;\n      case \"Home\":\n        e.preventDefault();\n        moveFocus(from, \"home\");\n        break;\n      case \"End\":\n        e.preventDefault();\n        moveFocus(from, \"end\");\n        break;\n      case \"ArrowDown\": {\n        const item = items.find((i) => i.value === from);\n        if (item?.content != null) {\n          e.preventDefault();\n          setActive(from);\n        }\n        break;\n      }\n      case \"Escape\":\n        if (open) {\n          e.preventDefault();\n          setActive(null);\n        }\n        break;\n      default:\n        break;\n    }\n  };\n\n  const handleRootBlur = (e: React.FocusEvent<HTMLDivElement>) => {\n    if (!rootRef.current?.contains(e.relatedTarget as Node)) {\n      cancelClose();\n      setActive(null);\n    }\n  };\n\n  const directionalContent = contentTransition === \"directional\" && !reducedMotion;\n  const contentVariants: Variants = {\n    enter: (dir: number) =>\n      directionalContent\n        ? { opacity: 0, x: dir * CONTENT_SHIFT, filter: \"blur(5px)\" }\n        : { opacity: 0 },\n    center: { opacity: 1, x: 0, filter: \"blur(0px)\" },\n    exit: (dir: number) =>\n      directionalContent\n        ? { opacity: 0, x: -dir * CONTENT_SHIFT, filter: \"blur(5px)\" }\n        : { opacity: 0 },\n  };\n\n  return (\n    <nav\n      {...props}\n      aria-label={props[\"aria-label\"] ?? \"Main\"}\n      data-crucible=\"pantograph\"\n      className={cn(\"inline-block\", className)}\n    >\n      <div\n        ref={rootRef}\n        className=\"relative inline-block\"\n        onPointerLeave={hoverMode ? scheduleClose : undefined}\n        onPointerEnter={hoverMode ? cancelClose : undefined}\n        onBlur={handleRootBlur}\n      >\n        {/* The trigger bar. */}\n        <div\n          ref={barRef}\n          onKeyDown={handleBarKeyDown}\n          className=\"relative flex items-center gap-1 rounded-full border border-white/10 bg-neutral-900/70 p-1.5 backdrop-blur-md\"\n        >\n          {items.map((item) => {\n            const isActive = item.value === activeValue && item.content != null;\n            const hasPanel = item.content != null;\n            const commonProps = {\n              ref: (el: HTMLElement | null) => {\n                if (el) triggerRefs.current.set(item.value, el);\n                else triggerRefs.current.delete(item.value);\n              },\n              // Disclosure pattern (not an ARIA menu — the panel holds plain\n              // links): triggers expose aria-expanded / aria-controls only.\n              tabIndex: item.value === (focusValue || items[0]?.value) ? 0 : -1,\n              \"aria-expanded\": hasPanel ? isActive : undefined,\n              \"aria-controls\": hasPanel && isActive ? panelId : undefined,\n              onFocus: () => {\n                setFocusValue(item.value);\n                if (hasPanel) setActive(item.value);\n                else setActive(null);\n              },\n              onPointerEnter: () => handleTriggerEnter(item),\n              className: cn(\n                \"relative rounded-full px-3.5 py-1.5 text-sm font-medium whitespace-nowrap transition-colors\",\n                \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950\",\n                isActive ? \"text-white\" : \"text-white/60 hover:text-white/90\"\n              ),\n            };\n\n            const inner = (\n              <>\n                {isActive && (\n                  <motion.span\n                    layoutId={`${baseId}-trigger-glow`}\n                    aria-hidden\n                    className=\"absolute inset-0 -z-10 rounded-full bg-white/[0.07]\"\n                    transition={\n                      reducedMotion\n                        ? { duration: 0 }\n                        : { type: \"spring\", stiffness: 620, damping: 34 }\n                    }\n                  />\n                )}\n                <span className=\"relative\">{item.label}</span>\n              </>\n            );\n\n            return item.href ? (\n              <a\n                key={item.value}\n                href={item.href}\n                {...commonProps}\n                onClick={(e) => {\n                  if (hasPanel && (openOn === \"click\" || !finePointer)) {\n                    e.preventDefault();\n                    handleTriggerClick(item);\n                  }\n                }}\n              >\n                {inner}\n              </a>\n            ) : (\n              <button\n                key={item.value}\n                type=\"button\"\n                {...commonProps}\n                onClick={() => handleTriggerClick(item)}\n              >\n                {inner}\n              </button>\n            );\n          })}\n        </div>\n\n        {/* The single shared flyout that morphs between triggers. */}\n        <AnimatePresence>\n          {open && activeItem && (\n            <motion.div\n              id={panelId}\n              role=\"region\"\n              aria-label={\n                typeof activeItem.label === \"string\" ? activeItem.label : undefined\n              }\n              key=\"pantograph-panel\"\n              className=\"absolute top-full left-0 z-20 mt-3 origin-top\"\n              style={{ x: leftMV, width: widthMV, height: heightMV }}\n              initial={\n                reducedMotion\n                  ? { opacity: 0 }\n                  : { opacity: 0, scale: 0.96, y: -6 }\n              }\n              animate={\n                reducedMotion\n                  ? { opacity: 1 }\n                  : { opacity: 1, scale: 1, y: 0 }\n              }\n              exit={\n                reducedMotion\n                  ? { opacity: 0 }\n                  : { opacity: 0, scale: 0.97, y: -6 }\n              }\n              transition={\n                reducedMotion\n                  ? { duration: 0.12 }\n                  : { type: \"spring\", stiffness: 500, damping: 40, mass: 0.7 }\n              }\n              onPointerEnter={hoverMode ? cancelClose : undefined}\n              onPointerLeave={hoverMode ? scheduleClose : undefined}\n            >\n              <div className=\"relative h-full w-full overflow-hidden rounded-2xl border border-white/10 bg-neutral-900/85 shadow-[0_1px_0_rgba(255,255,255,0.06)_inset,0_24px_60px_-20px_rgba(0,0,0,0.8)] backdrop-blur-xl\">\n                {/* Top hairline sheen. */}\n                <div\n                  aria-hidden\n                  className=\"pointer-events-none absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-white/25 to-transparent\"\n                />\n                <AnimatePresence\n                  mode=\"popLayout\"\n                  initial={false}\n                  custom={direction}\n                >\n                  <motion.div\n                    key={activeItem.value}\n                    custom={direction}\n                    variants={contentVariants}\n                    initial=\"enter\"\n                    animate=\"center\"\n                    exit=\"exit\"\n                    transition={\n                      reducedMotion\n                        ? { duration: 0.14 }\n                        : {\n                            type: \"spring\",\n                            stiffness: 520,\n                            damping: 42,\n                            mass: 0.7,\n                          }\n                    }\n                    className=\"absolute inset-0 p-3\"\n                  >\n                    {activeItem.content}\n                  </motion.div>\n                </AnimatePresence>\n              </div>\n\n              {/* Caret — slides to track the active trigger, never teleports. */}\n              {caret && (\n                <motion.span\n                  aria-hidden\n                  className=\"pointer-events-none absolute -top-1.5 z-10 h-3 w-3 -translate-x-1/2 rotate-45 rounded-tl-[3px] border-t border-l border-white/10 bg-neutral-900/85 backdrop-blur-xl\"\n                  style={{ left: caretX }}\n                />\n              )}\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n\n      {/* Hidden measurers — natural content size drives the morph target. */}\n      <div\n        aria-hidden\n        className=\"pointer-events-none invisible fixed top-0 left-0 -z-50\"\n        style={{ visibility: \"hidden\" }}\n      >\n        {items.map((item) =>\n          item.content != null ? (\n            <div\n              key={item.value}\n              data-measure-key={item.value}\n              ref={(el) => {\n                if (el) measureRefs.current.set(item.value, el);\n                else measureRefs.current.delete(item.value);\n              }}\n              className=\"absolute w-max p-3\"\n            >\n              {item.content}\n            </div>\n          ) : null\n        )}\n      </div>\n    </nav>\n  );\n}\n"
    }
  ]
}