{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"hairline-morph-nav","type":"registry:component","title":"Hairline Morph Nav","description":"A nav whose single hairline stretches toward the next link and settles under it: its leading edge runs ahead on a quick spring while its trailing edge follows on a slower one, and the active label steps up a weight without shifting.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/hairline-morph-nav.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, ReactNode } from \"react\";\n\n/**\n * HairlineMorphNav — a nav whose one hairline stretches toward the next link and settles.\n *\n * Choose another link and the line's leading edge runs ahead on a quick\n * spring while its trailing edge follows on a slower one, so it stretches\n * across the gap and gathers under its new link; the active label steps up\n * a weight without shifting anything. Hover previews the target with a faint\n * line. Controlled or not; folds into a menu on narrow containers.\n *\n * Part of the Modern Minimal kit: a paper-white room (#f5f5f2, surfaces\n * #ffffff, ink #141412) and one light, dawn #ffa64d, only ever as light.\n * Two-layer shadows from one light above; scroll binds values directly,\n * with no easing. Inter Tight through var(--font-inter-tight) for display\n * over Geist. Respects prefers-reduced-motion. No dependencies beyond React.\n * Paste it as its own file: it repeats the kit's small helpers, which would\n * clash in one module. Load Inter Tight with next/font (variable:\n * \"--font-inter-tight\") on a parent, or from Google Fonts or @fontsource.\n * Needs Tailwind v4 (on v3.4, add the @tailwindcss/container-queries plugin).\n */\n\nconst SANS = 'var(--font-sans, \"Geist\", \"Inter\", ui-sans-serif, system-ui, sans-serif)';\n\nconst DISPLAY = 'var(--font-inter-tight, \"Inter Tight\", var(--font-sans, \"Geist\"), ui-sans-serif, system-ui, sans-serif)';\n\nconst EASE = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** A paper-white room and one light. */\nconst PAPER = {\n  ground: \"#f5f5f2\",\n  surface: \"#ffffff\",\n  well: \"#ecebe6\",\n  solid: \"#141412\",\n  ink: \"rgba(20,20,18,0.92)\",\n  ink2: \"rgba(20,20,18,0.6)\",\n  ink3: \"rgba(20,20,18,0.38)\",\n  line: \"rgba(20,20,18,0.08)\",\n  line2: \"rgba(20,20,18,0.14)\",\n  dawn: \"#ffa64d\",\n  night: \"#0e0f11\",\n} as const;\n\n/** Light from above: a 1px contact shadow and a soft ambient one, both falling the same way. */\nconst SHADOW = \"0 1px 2px rgba(20,20,18,0.06), 0 24px 48px -12px rgba(20,20,18,0.1)\";\n\n/** Links: strip tabs and newlines, refuse backslashes, allow http(s), mailto, tel and same-site paths. */\nfunction safeHref(raw: string): string {\n  const v = raw.replace(/[\\t\\n\\r]/g, \"\").trim();\n  if (!v || v.includes(\"\\\\\")) return \"#\";\n  if (/^(https?:|mailto:|tel:)/i.test(v)) return v;\n  if (/^[/#?]/.test(v) && !/^\\/\\//.test(v)) return v;\n  return \"#\";\n}\n\nfunction subscribeMotion(cb: () => void) {\n  const m = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  m.addEventListener(\"change\", cb);\n  return () => m.removeEventListener(\"change\", cb);\n}\n\n/** True when the visitor asked for reduced motion. False on the server. */\nfunction useReducedMotion(): boolean {\n  return useSyncExternalStore(\n    subscribeMotion,\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** A spring for one number; returns the new value and velocity. */\nfunction spring(x: number, v: number, target: number, dt: number, k = 260, c = 26): [number, number] {\n  const steps = dt > 1 / 60 ? 2 : 1;\n  const h = dt / steps;\n  for (let i = 0; i < steps; i++) {\n    v += (k * (target - x) - c * v) * h;\n    x += v * h;\n  }\n  return [x, v];\n}\n\n// Each part carries only the CSS it needs, so any one of them works on its own.\n// revert-layer keeps an element's own rounded corners when a host page's focus rule flattens them.\nconst FOCUS_CSS = \".mm-scope :focus-visible,.mm-scope:focus-visible{outline:2px solid var(--mm-ring,#141412)!important;outline-offset:3px;border-radius:revert-layer}\";\n\nconst MM_BUTTON_INK = {\n  solid: { bg: PAPER.solid, fg: \"#f5f5f2\", border: \"transparent\", shadow: true },\n  light: { bg: PAPER.surface, fg: PAPER.solid, border: \"rgba(20,20,18,0.08)\", shadow: true },\n  outline: { bg: \"transparent\", fg: PAPER.solid, border: \"rgba(20,20,18,0.22)\", shadow: false },\n} as const;\n\nexport type MmButtonVariant = keyof typeof MM_BUTTON_INK;\n\n/**\n * WeightPressButton — a button whose press you can see in its type.\n *\n * A pill in Inter Tight. Hover and the label thickens a step and the button\n * lifts a pixel as its ambient shadow widens; press and the label goes bold\n * under your finger while the button sinks, the ambient shadow collapsing to\n * the contact one, then springs back past rest on release. Both shadows fall\n * from one light above. Solid, light and outline; a link when given an href.\n * CSS transitions on a variable weight, no animation library.\n */\nexport function WeightPressButton({\n  children,\n  href,\n  onClick,\n  type = \"button\",\n  variant = \"solid\",\n  size = \"lg\",\n  disabled = false,\n  ariaLabel,\n  ariaPressed,\n  className = \"\",\n}: {\n  children: ReactNode;\n  href?: string;\n  onClick?: () => void;\n  type?: \"button\" | \"submit\";\n  variant?: MmButtonVariant;\n  size?: \"lg\" | \"md\" | \"sm\";\n  disabled?: boolean;\n  ariaLabel?: string;\n  ariaPressed?: boolean;\n  className?: string;\n}) {\n  const ink = MM_BUTTON_INK[variant] ?? MM_BUTTON_INK.solid;\n  const [state, setState] = useState<\"rest\" | \"hover\" | \"down\">(\"rest\");\n  const reduced = useReducedMotion();\n  const weight = state === \"down\" ? 680 : state === \"hover\" ? 560 : 500;\n  const shadow = !ink.shadow\n    ? \"none\"\n    : state === \"down\"\n      ? \"0 1px 1px rgba(20,20,18,0.1), 0 6px 12px -8px rgba(20,20,18,0.14)\"\n      : state === \"hover\"\n        ? \"0 1px 2px rgba(20,20,18,0.06), 0 30px 56px -14px rgba(20,20,18,0.16)\"\n        : SHADOW;\n  const pad = size === \"sm\" ? \"h-9 px-4 text-[13px]\" : size === \"md\" ? \"h-11 px-5 text-[14px]\" : \"h-[52px] px-7 text-[15px]\";\n  const common = {\n    \"aria-label\": ariaLabel,\n    className: \"mm-scope relative inline-flex select-none items-center justify-center rounded-full no-underline outline-none \" + pad + (disabled ? \" pointer-events-none opacity-40 \" : \" \") + className,\n    style: {\n      background: ink.bg,\n      color: ink.fg,\n      border: `1px solid ${ink.border}`,\n      boxShadow: shadow,\n      fontFamily: DISPLAY,\n      fontWeight: weight,\n      letterSpacing: \"-0.01em\",\n      transform: state === \"down\" ? \"translateY(1px) scale(0.985)\" : state === \"hover\" ? \"translateY(-1px)\" : \"none\",\n      transition: reduced\n        ? \"none\"\n        : state === \"rest\"\n          ? `transform 300ms cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 260ms ${EASE}, font-weight 220ms ${EASE}`\n          : `transform 160ms ${EASE}, box-shadow 160ms ${EASE}, font-weight 160ms ${EASE}`,\n    } as CSSProperties,\n    onPointerEnter: () => setState(\"hover\"),\n    onPointerLeave: () => setState(\"rest\"),\n    onPointerDown: () => setState(\"down\"),\n    onPointerUp: () => setState(\"hover\"),\n    onPointerCancel: () => setState(\"rest\"),\n    onFocus: () => setState((s) => (s === \"rest\" ? \"hover\" : s)),\n    onBlur: () => setState(\"rest\"),\n    onKeyDown: (e: ReactKeyboardEvent) => {\n      if (e.key === \"Enter\" || (e.key === \" \" && !href)) setState(\"down\");\n    },\n    onKeyUp: () => setState(\"hover\"),\n  };\n  // The label is laid out at the boldest weight too, invisibly, so the button never changes width.\n  const label = (\n    <span className=\"relative inline-grid\">\n      <span aria-hidden className=\"invisible col-start-1 row-start-1 whitespace-nowrap\" style={{ fontWeight: 680 }}>\n        {children}\n      </span>\n      <span className=\"col-start-1 row-start-1 whitespace-nowrap text-center\">{children}</span>\n    </span>\n  );\n  if (href) {\n    return (\n      <>\n        <style>{FOCUS_CSS}</style>\n        <a href={safeHref(href)} onClick={onClick} {...common}>\n          {label}\n        </a>\n      </>\n    );\n  }\n  return (\n    <>\n      <style>{FOCUS_CSS}</style>\n      <button type={type} onClick={onClick} disabled={disabled} aria-pressed={ariaPressed} {...common}>\n        {label}\n      </button>\n    </>\n  );\n}\n\nexport type MmLink = { label: string; href: string };\n\n/**\n * HairlineMorphNav — a nav whose one hairline stretches toward the next link\n * and settles under it.\n *\n * The active link is marked by a single 1.5px ink line. Choose another and\n * its leading edge runs ahead on a quick spring while its trailing edge\n * follows on a slower one, so the line stretches across the gap and then\n * gathers under its new link; the active label steps up a weight (laid out\n * at the heavier weight too, so nothing shifts). Hover or focus previews the\n * target with a faint line. `tone` turns it over for a night section.\n * Controlled or not; folds into a menu on narrow containers.\n */\nexport function HairlineMorphNav({\n  brand = \"Halden\",\n  links,\n  cta,\n  active,\n  defaultActive,\n  onNavigate,\n  tone = \"light\",\n  className = \"\",\n  style,\n}: {\n  brand?: string;\n  links: MmLink[];\n  cta?: MmLink | null;\n  /** The active link's href, controlled. */\n  active?: string;\n  defaultActive?: string;\n  onNavigate?: (href: string) => void;\n  /** \"dark\" over a night section: the bar, the type and the line turn over. */\n  tone?: \"light\" | \"dark\";\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const [own, setOwn] = useState(defaultActive ?? links[0]?.href ?? \"\");\n  const current = active ?? own;\n  const [open, setOpen] = useState(false);\n  const [hover, setHover] = useState(-1);\n  const menuId = useId();\n  const reduced = useReducedMotion();\n  const rowRef = useRef<HTMLDivElement>(null);\n  const lineRef = useRef<HTMLSpanElement>(null);\n  const ghostRef = useRef<HTMLSpanElement>(null);\n  const linkRefs = useRef<(HTMLAnchorElement | null)[]>([]);\n  const menuBtn = useRef<HTMLButtonElement>(null);\n  const panelRef = useRef<HTMLDivElement>(null);\n  const edges = useRef({ l: -1, r: -1, vl: 0, vr: 0, raf: 0, last: 0 });\n  const idx = Math.max(0, links.findIndex((l) => l.href === current));\n  const dark = tone === \"dark\";\n  const fg = dark ? \"#f5f5f2\" : PAPER.solid;\n  const fg2 = dark ? \"rgba(245,245,242,0.62)\" : PAPER.ink2;\n  const turn = `background 300ms ${EASE}, color 300ms ${EASE}, border-color 300ms ${EASE}`;\n\n  // The line's two edges: the one moving forward is quick (stiffness 420), the one behind is slower (170).\n  useEffect(() => {\n    const row = rowRef.current;\n    const line = lineRef.current;\n    const ghost = ghostRef.current;\n    if (!row || !line || !ghost) return;\n    const e = edges.current;\n    const at = (i: number) => {\n      const a = linkRefs.current[i];\n      if (!a) return null;\n      const r0 = row.getBoundingClientRect();\n      const r = a.getBoundingClientRect();\n      const k = row.offsetWidth ? r0.width / row.offsetWidth : 1;\n      return { l: (r.left - r0.left) / k + 14, r: (r.right - r0.left) / k - 14 };\n    };\n    const tick = (now: number) => {\n      e.raf = 0;\n      const dt = e.last ? Math.min(0.05, (now - e.last) / 1000) : 1 / 60;\n      e.last = now;\n      const t = at(idx);\n      if (!t) return;\n      if (e.l < 0 || reduced) {\n        e.l = t.l;\n        e.r = t.r;\n      } else {\n        const right = t.r > e.r;\n        [e.l, e.vl] = spring(e.l, e.vl, t.l, dt, right ? 170 : 420, right ? 25 : 34);\n        [e.r, e.vr] = spring(e.r, e.vr, t.r, dt, right ? 420 : 170, right ? 34 : 25);\n      }\n      line.style.transform = `translateX(${e.l}px) scaleX(${Math.max(1, e.r - e.l)})`;\n      const h = hover >= 0 && hover !== idx ? at(hover) : null;\n      ghost.style.opacity = h ? \"1\" : \"0\";\n      if (h) ghost.style.transform = `translateX(${h.l}px) scaleX(${Math.max(1, h.r - h.l)})`;\n      const moving = Math.abs(t.l - e.l) + Math.abs(t.r - e.r) > 0.3 || Math.abs(e.vl) + Math.abs(e.vr) > 1;\n      if (moving) e.raf = requestAnimationFrame(tick);\n      else e.last = 0;\n    };\n    const ro = new ResizeObserver(() => {\n      if (!e.raf) e.raf = requestAnimationFrame(tick);\n    });\n    ro.observe(row);\n    if (!e.raf) e.raf = requestAnimationFrame(tick);\n    return () => {\n      ro.disconnect();\n      cancelAnimationFrame(e.raf);\n      e.raf = 0;\n    };\n  }, [idx, hover, reduced, links.length]);\n\n  // The menu closes on Escape (focus back to its button) and on a click outside.\n  useEffect(() => {\n    if (!open) return;\n    const onKey = (ev: KeyboardEvent) => {\n      if (ev.key === \"Escape\") {\n        setOpen(false);\n        menuBtn.current?.focus();\n      }\n    };\n    const onDown = (ev: PointerEvent) => {\n      const t = ev.target as Node;\n      if (!panelRef.current?.contains(t) && !menuBtn.current?.contains(t)) setOpen(false);\n    };\n    document.addEventListener(\"keydown\", onKey);\n    document.addEventListener(\"pointerdown\", onDown);\n    return () => {\n      document.removeEventListener(\"keydown\", onKey);\n      document.removeEventListener(\"pointerdown\", onDown);\n    };\n  }, [open]);\n\n  const go = (href: string) => {\n    if (active === undefined) setOwn(href);\n    onNavigate?.(href);\n    setOpen(false);\n  };\n\n  return (\n    <header className={\"mm-scope relative w-full @container \" + className} style={{ fontFamily: SANS, color: PAPER.ink, [\"--mm-ring\" as string]: dark ? \"#f5f5f2\" : \"#141412\", ...style } as CSSProperties}>\n      <style>{FOCUS_CSS}</style>\n      <nav\n        aria-label=\"Main\"\n        className=\"flex h-16 items-center gap-6 px-5 @3xl:px-8\"\n        style={{ background: dark ? \"rgba(14,15,17,0.55)\" : \"rgba(245,245,242,0.78)\", backdropFilter: \"saturate(1.4) blur(16px)\", WebkitBackdropFilter: \"saturate(1.4) blur(16px)\", borderBottom: `1px solid ${dark ? \"rgba(245,245,242,0.08)\" : PAPER.line}`, transition: turn }}\n      >\n        <a href={safeHref(links[0]?.href ?? \"#\")} onClick={() => go(links[0]?.href ?? \"#\")} className=\"flex shrink-0 items-center gap-2.5 no-underline\" style={{ color: fg, transition: turn }}>\n          <span aria-hidden className=\"h-[14px] w-[14px] rounded-full\" style={{ background: `radial-gradient(circle at 50% 40%, #fff7ea, ${PAPER.dawn})`, boxShadow: \"0 0 10px 1px rgba(255,166,77,0.45)\" }} />\n          <span className=\"text-[17px] font-semibold\" style={{ fontFamily: DISPLAY, letterSpacing: \"-0.02em\" }}>\n            {brand}\n          </span>\n        </a>\n        <div ref={rowRef} className=\"relative mx-auto hidden h-full min-w-0 flex-1 @3xl:block\">\n          <ul className=\"m-0 flex h-full list-none items-center justify-center gap-1 p-0\">\n            {links.map((l, i) => {\n              const on = l.href === current;\n              return (\n                <li key={l.href}>\n                  <a\n                    ref={(el) => void (linkRefs.current[i] = el)}\n                    href={safeHref(l.href)}\n                    aria-current={on ? \"page\" : undefined}\n                    onClick={() => go(l.href)}\n                    onPointerEnter={() => setHover(i)}\n                    onPointerLeave={() => setHover(-1)}\n                    onFocus={() => setHover(i)}\n                    onBlur={() => setHover(-1)}\n                    className=\"relative inline-grid px-3.5 py-2 text-[14px] no-underline\"\n                    style={{ color: on ? fg : fg2, transition: `color 200ms ${EASE}` }}\n                  >\n                    <span aria-hidden className=\"invisible col-start-1 row-start-1 whitespace-nowrap\" style={{ fontWeight: 600 }}>\n                      {l.label}\n                    </span>\n                    <span className=\"col-start-1 row-start-1 whitespace-nowrap text-center\" style={{ fontWeight: on ? 600 : 450, transition: `font-weight 220ms ${EASE}` }}>\n                      {l.label}\n                    </span>\n                  </a>\n                </li>\n              );\n            })}\n          </ul>\n          <span ref={ghostRef} aria-hidden className=\"pointer-events-none absolute bottom-[14px] left-0 block h-px w-px origin-left\" style={{ background: dark ? \"rgba(245,245,242,0.38)\" : PAPER.ink3, opacity: 0, transition: `opacity 200ms ${EASE}` }} />\n          <span ref={lineRef} aria-hidden className=\"pointer-events-none absolute bottom-[13px] left-0 block h-[1.5px] w-px origin-left\" style={{ background: fg, transition: turn }} />\n        </div>\n        <div className=\"ml-auto flex shrink-0 items-center gap-2 @3xl:ml-0\">\n          {cta ? (\n            <WeightPressButton href={cta.href} size=\"sm\" variant={dark ? \"light\" : \"solid\"} onClick={() => go(cta.href)}>\n              {cta.label}\n            </WeightPressButton>\n          ) : null}\n          <button\n            ref={menuBtn}\n            type=\"button\"\n            aria-expanded={open}\n            aria-controls={menuId}\n            onClick={() => setOpen((v) => !v)}\n            className=\"grid h-9 w-9 place-items-center rounded-full @3xl:hidden\"\n            style={{ border: `1px solid ${PAPER.line2}`, background: PAPER.surface, color: PAPER.solid }}\n          >\n            <span className=\"sr-only\">Menu</span>\n            <span aria-hidden className=\"flex flex-col gap-[4px]\">\n              <span className=\"block h-px w-3.5\" style={{ background: \"currentColor\", transform: open ? \"translateY(2.5px) rotate(45deg)\" : \"none\", transition: `transform 220ms ${EASE}` }} />\n              <span className=\"block h-px w-3.5\" style={{ background: \"currentColor\", transform: open ? \"translateY(-2.5px) rotate(-45deg)\" : \"none\", transition: `transform 220ms ${EASE}` }} />\n            </span>\n          </button>\n        </div>\n      </nav>\n      {open ? (\n        <div ref={panelRef} id={menuId} className=\"absolute inset-x-3 top-[70px] z-20 rounded-[20px] p-2 @3xl:hidden\" style={{ background: PAPER.surface, border: `1px solid ${PAPER.line}`, boxShadow: SHADOW }}>\n          <ul className=\"m-0 list-none p-0\">\n            {links.map((l) => (\n              <li key={l.href}>\n                <a\n                  href={safeHref(l.href)}\n                  aria-current={l.href === current ? \"page\" : undefined}\n                  onClick={() => go(l.href)}\n                  className=\"flex items-center justify-between rounded-[12px] px-3 py-2.5 text-[15px] no-underline\"\n                  style={{ color: l.href === current ? PAPER.solid : PAPER.ink2, fontWeight: l.href === current ? 600 : 450 }}\n                >\n                  {l.label}\n                  {l.href === current ? <span aria-hidden className=\"h-px w-5\" style={{ background: PAPER.solid }} /> : null}\n                </a>\n              </li>\n            ))}\n          </ul>\n        </div>\n      ) : null}\n    </header>\n  );\n}\n","type":"registry:component","target":"components/viberdy/hairline-morph-nav.tsx"}],"meta":{"tier":"free","tags":["navigation","navbar","underline","spring","indicator","scroll spy"],"href":"https://viberdy.dev/library/hairline-morph-nav","aiPrompt":"Build a React + Tailwind nav, `HairlineMorphNav({ brand, links, cta, active, defaultActive, onNavigate, className, style })`.\n\nFrom @3xl, the links in a centred row; beneath the active one, a 1.5px ink line drawn as a 1px element with translateX(left) scaleX(width), inset 14px from the link's edges. Its left and right edges each follow their target on a spring; the edge in the direction of travel is quick (stiffness 420, damping 34), the other slow (140, 22), so it stretches and settles; a requestAnimationFrame loop runs only while they move. A faint 38% line previews a hovered or focused link. Labels render twice in one grid cell (the hidden copy at 600) so the weight change from 450 to 600 never shifts the row. A paper bar at 78% with saturate(1.4) blur(16px), a hairline under it, a brand with a small glowing orb, the kit's WeightPressButton as the call to action, and below @3xl a Menu disclosure.\n\nModern Minimal grammar: a paper-white room, ground #f5f5f2 (surfaces #ffffff that lift, a recessed well #ecebe6), ink #141412 at 92/60/38% (never grey-400 body copy), hairlines at 8% and 14%; one light, dawn #ffa64d, only ever as light (the lamp's glow, a lit state), never as a fill. Shadows come from one light above in two layers: a contact 0 1px 2px rgba(20,20,18,0.06) and an ambient 0 24px 48px -12px rgba(20,20,18,0.1), both falling the same way; a pressed thing loses the ambient, a lifted one widens it. Type: Inter Tight through var(--font-inter-tight, \"Inter Tight\", ...) for display at 600 with -0.035em tracking and 0.98 leading (tracking tightens only at display sizes), Geist for reading at 16-17px/1.55, Geist Mono uppercase at 11-12px for readouts. Radii 12px controls (pills for buttons), 20px cards, 28px media. Motion: scroll binds values directly with no easing (a value moves exactly with the scroll, like scrubbing film); discrete hover and press states take 150-260ms with a spring back past rest; ambient loops 40s or more. Respect prefers-reduced-motion (ambient scenes hold still; scroll-bound values still follow the scroll, which the visitor drives). No dependencies beyond React.","license":"https://viberdy.dev/license"}}