{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"directional-underline","type":"registry:component","title":"Directional underline","description":"The underline comes in from the side your cursor entered and leaves toward the side it left.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":[],"registryDependencies":["utils"],"files":[{"path":"components/directional-underline.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState, type ComponentProps } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\ntype Side = \"left\" | \"right\";\n\n// Clip insets (left, right) for each resting place of the line. Hidden\n// \"at\" a side means collapsed against that edge, so drawing from there\n// grows away from it and hiding toward it shrinks into it.\nconst HIDDEN_AT: Record<Side, [string, string]> = {\n  left: [\"0%\", \"100%\"],\n  right: [\"100%\", \"0%\"],\n};\nconst SHOWN: [string, string] = [\"0%\", \"0%\"];\n\nfunction set(el: HTMLElement, [l, r]: [string, string]) {\n  el.style.setProperty(\"--ul-l\", l);\n  el.style.setProperty(\"--ul-r\", r);\n}\n\n// hidden: whether the line is fully gone. Only then is it safe to teleport\n// it to the other edge; mid-exit it just reverses from where it is.\nfunction draw(el: HTMLElement, hidden: { current: boolean }, from: Side) {\n  if (hidden.current) {\n    el.dataset.instant = \"\";\n    set(el, HIDDEN_AT[from]);\n    // Commits the start position before the transition is restored.\n    void el.offsetWidth;\n    delete el.dataset.instant;\n  }\n  hidden.current = false;\n  delete el.dataset.leaving;\n  el.dataset.on = \"\";\n  set(el, SHOWN);\n}\n\nfunction erase(el: HTMLElement, toward: Side) {\n  el.dataset.leaving = \"\";\n  delete el.dataset.on;\n  set(el, HIDDEN_AT[toward]);\n}\n\nfunction sideOf(el: HTMLElement, clientX: number): Side {\n  const r = el.getBoundingClientRect();\n  return clientX < r.left + r.width / 2 ? \"left\" : \"right\";\n}\n\nexport function DirectionalLink({\n  className,\n  rest = false,\n  simulate,\n  children,\n  onPointerEnter,\n  onPointerLeave,\n  onFocus,\n  onBlur,\n  ...props\n}: ComponentProps<\"a\"> & {\n  /** Keeps a faint line under the link at rest, for links inside prose. */\n  rest?: boolean;\n  /** Acts out a pointer without one: over, and the side it came in from\n   * (or, once no longer over, the side it left by). For demos. */\n  simulate?: { over: boolean; side: Side };\n}) {\n  const ref = useRef<HTMLAnchorElement>(null);\n  const hidden = useRef(true);\n  const hovered = useRef(false);\n\n  const simOver = simulate?.over;\n  const simSide = simulate?.side;\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || simOver === undefined || simSide === undefined) return;\n    if (simOver) draw(el, hidden, simSide);\n    else if (!hidden.current) erase(el, simSide);\n  }, [simOver, simSide]);\n\n  return (\n    <a\n      ref={ref}\n      {...props}\n      onPointerEnter={(e) => {\n        onPointerEnter?.(e);\n        if (e.pointerType === \"touch\") return;\n        hovered.current = true;\n        draw(e.currentTarget, hidden, sideOf(e.currentTarget, e.clientX));\n      }}\n      onPointerLeave={(e) => {\n        onPointerLeave?.(e);\n        if (e.pointerType === \"touch\") return;\n        hovered.current = false;\n        // Keyboard focus still owns the line.\n        if (e.currentTarget.matches(\":focus-visible\")) return;\n        erase(e.currentTarget, sideOf(e.currentTarget, e.clientX));\n      }}\n      onFocus={(e) => {\n        onFocus?.(e);\n        // Reading order: a focused link underlines from the start of the text.\n        if (e.currentTarget.matches(\":focus-visible\")) draw(e.currentTarget, hidden, \"left\");\n      }}\n      onBlur={(e) => {\n        onBlur?.(e);\n        if (!hovered.current) erase(e.currentTarget, \"right\");\n      }}\n      // A pseudo-element's transitionend is dispatched on its host, so\n      // target === currentTarget here means the line itself settled.\n      onTransitionEnd={(e) => {\n        if (e.target !== e.currentTarget || e.propertyName !== \"clip-path\") return;\n        const l = e.currentTarget.style.getPropertyValue(\"--ul-l\");\n        const r = e.currentTarget.style.getPropertyValue(\"--ul-r\");\n        hidden.current = l === \"100%\" || r === \"100%\";\n      }}\n      className={cn(\n        \"relative inline-block rounded-[2px] leading-tight whitespace-nowrap text-foreground outline-hidden focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground\",\n        // The resting hairline, for prose where a link must look like one.\n        rest &&\n          \"before:pointer-events-none before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-border\",\n        // The drawn line. Clip, not scaleX: its origin can't jump mid-flight,\n        // and it can reverse from any partial state. Enter 240ms, leave 180ms.\n        \"after:pointer-events-none after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-foreground after:[clip-path:inset(0_var(--ul-r,100%)_0_var(--ul-l,0%))]\",\n        \"after:transition-[clip-path] after:duration-[240ms] after:ease-[cubic-bezier(0.23,1,0.32,1)]\",\n        \"data-leaving:after:duration-[180ms] data-instant:after:transition-none\",\n        // Reduced motion: the line fades in whole instead of travelling.\n        \"motion-reduce:after:[clip-path:none] motion-reduce:after:opacity-0 motion-reduce:after:transition-[opacity] motion-reduce:hover:after:opacity-100 motion-reduce:focus-visible:after:opacity-100 motion-reduce:data-on:after:opacity-100\",\n        className,\n      )}\n    >\n      {children}\n    </a>\n  );\n}\n\nconst NAV = [\"Work\", \"Writing\", \"About\", \"Contact\"];\n// The index card's show: a cursor glides along the nav one way, then back\n// the other, so each line arrives from the side the cursor did. Each link\n// is crossed in ENTER_TO_LEAVE ms, with STRIDE ms between link entries.\nconst STRIDE = 320;\nconst ENTER_TO_LEAVE = 220;\nconst SHOW_START = 300;\n// The beat between passes, and before the show repeats.\nconst SHOW_TURN = 900;\nconst SHOW_REST = 1600;\ntype Sim = { over: boolean; side: Side } | undefined;\n\nexport default function DirectionalUnderlineDemo() {\n  const play = usePreviewPlay();\n  const [sims, setSims] = useState<Sim[]>(() => NAV.map(() => undefined));\n\n  useEffect(() => {\n    if (play !== true) return;\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    const at = (t: number, fn: () => void) => timers.push(setTimeout(fn, t));\n    const patch = (i: number, sim: Sim) =>\n      setSims((prev) => prev.map((s, j) => (j === i ? sim : s)));\n\n    const pass = (start: number, from: Side) => {\n      const exitTo: Side = from === \"left\" ? \"right\" : \"left\";\n      const order = from === \"left\" ? NAV.map((_, i) => i) : NAV.map((_, i) => NAV.length - 1 - i);\n      order.forEach((i, n) => {\n        at(start + n * STRIDE, () => patch(i, { over: true, side: from }));\n        at(start + n * STRIDE + ENTER_TO_LEAVE, () => patch(i, { over: false, side: exitTo }));\n      });\n      return start + (NAV.length - 1) * STRIDE + ENTER_TO_LEAVE;\n    };\n    const loop = (start: number) => {\n      const back = pass(start, \"left\") + SHOW_TURN;\n      const end = pass(back, \"right\");\n      at(end + SHOW_REST, () => {\n        timers.length = 0;\n        loop(0);\n      });\n    };\n    loop(SHOW_START);\n    // Unhovering lets any drawn line leave the way it was heading.\n    return () => {\n      timers.forEach(clearTimeout);\n      setSims((prev) =>\n        prev.map((s) =>\n          s?.over ? { over: false, side: s.side === \"left\" ? \"right\" : \"left\" } : s,\n        ),\n      );\n    };\n  }, [play]);\n\n  return (\n    <div className=\"flex w-[min(400px,100%)] flex-col gap-8\">\n      <p className=\"text-[15px] leading-7 text-muted-foreground\">\n        I build interfaces at{\" \"}\n        <DirectionalLink rest href=\"#studio\">\n          a small studio\n        </DirectionalLink>\n        , write about{\" \"}\n        <DirectionalLink rest href=\"#motion\">\n          motion\n        </DirectionalLink>{\" \"}\n        on weekends, and keep{\" \"}\n        <DirectionalLink rest href=\"#reading\">\n          a reading list\n        </DirectionalLink>{\" \"}\n        of the good stuff.\n      </p>\n      <nav aria-label=\"Main\" className=\"flex gap-5 text-sm font-medium\">\n        {NAV.map((item, i) => (\n          <DirectionalLink\n            key={item}\n            href={`#${item.toLowerCase()}`}\n            simulate={sims[i]}\n            className=\"py-0.5\"\n          >\n            {item}\n          </DirectionalLink>\n        ))}\n      </nav>\n    </div>\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"categories":["text"],"docs":"From ui lab: https://lab.xevrion.dev/lab/directional-underline"}