{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"asterisk-type-headline","type":"registry:component","title":"Asterisk Type Headline","description":"A headline typed out by an asterisk: the caret spins fast while it types, opens an inline pill when it reaches one, then parks in the slot you mark with * (by default just after the last word) and keeps turning slowly.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/asterisk-type-headline.tsx","content":"\"use client\";\n\nimport { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from \"react\";\n\n/* ============================================================================\n * SHARED PIECES\n * ========================================================================== */\n\n/** The kit's face. Urbanist is set at 300 for the quiet line, 700 for the loud one. */\nexport const HG_FONT = 'var(--font-urbanist, \"Urbanist\"), \"Outfit\", ui-sans-serif, system-ui, sans-serif';\n\nexport function hgReducedMotion(): boolean {\n  return typeof window !== \"undefined\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/** True once the element has come within `margin` of the viewport. Never goes back. */\nexport function useHgSeen<T extends HTMLElement>(ref: RefObject<T | null>, margin = \"200px\"): boolean {\n  const [seen, setSeen] = useState(false);\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || seen) return;\n    if (typeof IntersectionObserver === \"undefined\") {\n      // No observer to wait for: count it as seen on the next frame.\n      const id = requestAnimationFrame(() => setSeen(true));\n      return () => cancelAnimationFrame(id);\n    }\n    // Watch against the box that scrolls the element when there is one: the\n    // margin only reaches ahead inside its own root, so against the window\n    // it would do nothing for a page living in a scrolling preview.\n    const io = new IntersectionObserver(\n      (es) => {\n        if (es.some((e) => e.isIntersecting)) {\n          setSeen(true);\n          io.disconnect();\n        }\n      },\n      { root: hgScrollParent(el), rootMargin: margin },\n    );\n    io.observe(el);\n    return () => io.disconnect();\n  }, [ref, margin, seen]);\n  return seen;\n}\n\n/**\n * The scrolling box an element lives in: the nearest ancestor that actually\n * scrolls, or null for the window. Resolved lazily on every scroll, because a\n * scroller only becomes one once its content is taller than it.\n */\nexport function hgScrollParent(el: Element | null): HTMLElement | null {\n  let n = el?.parentElement ?? null;\n  while (n && n !== document.body && n !== document.documentElement) {\n    const oy = getComputedStyle(n).overflowY;\n    if ((oy === \"auto\" || oy === \"scroll\" || oy === \"overlay\") && n.scrollHeight > n.clientHeight + 1) return n;\n    n = n.parentElement;\n  }\n  return null;\n}\n\n/** The eight-spoke asterisk the kit uses as caret, bullet and spinner. */\nexport function HgAsterisk({ className, style, stroke = 1.6 }: { className?: string; style?: CSSProperties; stroke?: number }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" aria-hidden className={className} style={style} fill=\"none\" stroke=\"currentColor\" strokeWidth={stroke} strokeLinecap=\"round\">\n      <path d=\"M12 3v18M3 12h18M5.6 5.6l12.8 12.8M18.4 5.6 5.6 18.4\" />\n    </svg>\n  );\n}\n\n/* ============================================================================\n * NAV + ASTERISK HEADLINE\n * ========================================================================== */\n\nconst HG_NAV_CSS = `\n.hg-pill{position:relative;overflow:hidden;isolation:isolate;transition:color .45s cubic-bezier(.2,.7,.2,1),border-color .45s,background-color .45s}\n.hg-pill::before{content:\"\";position:absolute;inset:0;z-index:-1;border-radius:inherit;background:var(--hg-pill-fill);transform:translateY(102%);transition:transform .5s cubic-bezier(.2,.7,.2,1)}\n.hg-pill:hover::before,.hg-pill:focus-visible::before{transform:none}\n.hg-pill:hover,.hg-pill:focus-visible{color:var(--hg-pill-on)}\n.hg-pill .hg-pill-star{width:0;opacity:0;margin-left:0;transition:width .45s cubic-bezier(.2,.7,.2,1),opacity .3s,margin .45s}\n.hg-pill:hover .hg-pill-star,.hg-pill:focus-visible .hg-pill-star{width:.8em;opacity:1;margin-left:.45em;animation:hg-spin 2.4s linear infinite}\n.hg-pill:focus-visible{outline:2px solid var(--hg-ring) !important;outline-offset:3px}\n@keyframes hg-spin{to{transform:rotate(360deg)}}\n@media (prefers-reduced-motion: reduce){.hg-pill::before,.hg-pill .hg-pill-star{transition:none}.hg-pill:hover .hg-pill-star{animation:none}}\n`;\n\ntype HgToken = { k: \"ch\"; ch: string; bold: boolean } | { k: \"star\"; bold: boolean } | { k: \"pill\" } | { k: \"br\" };\n\n/**\n * Parse the headline markup: lines split on a newline, **bold** runs, a lone\n * * is the asterisk slot (where the caret parks), [pill] is the inline pill.\n */\nexport function hgParseHeadline(text: string): HgToken[] {\n  const out: HgToken[] = [];\n  let bold = false;\n  for (let i = 0; i < text.length; i++) {\n    const c = text[i]!;\n    if (c === \"*\" && text[i + 1] === \"*\") {\n      bold = !bold;\n      i++;\n      continue;\n    }\n    if (c === \"*\") {\n      out.push({ k: \"star\", bold });\n      continue;\n    }\n    if (c === \"[\" && text.startsWith(\"[pill]\", i)) {\n      out.push({ k: \"pill\" });\n      i += 5;\n      continue;\n    }\n    if (c === \"\\n\") {\n      out.push({ k: \"br\" });\n      continue;\n    }\n    out.push({ k: \"ch\", ch: c, bold });\n  }\n  return out;\n}\n\nconst HG_TYPE_CSS = `\n.hg-tw [data-c]{opacity:0;transition:opacity .18s linear}\n.hg-tw [data-c][data-on]{opacity:1}\n.hg-tw .hg-tw-pill{display:inline-block;vertical-align:-0.06em;height:.72em;width:0;border-radius:999px;overflow:hidden;transition:width .9s cubic-bezier(.2,.75,.15,1),margin .9s cubic-bezier(.2,.75,.15,1)}\n.hg-tw .hg-tw-pill[data-on]{width:var(--hg-pill-w,4.4em);margin:0 .12em 0 .28em}\n.hg-tw .hg-tw-caret{position:absolute;left:0;top:0;width:.56em;height:.56em;color:var(--hg-caret,currentColor);pointer-events:none;transition:transform .32s cubic-bezier(.2,.7,.2,1),opacity .3s}\n.hg-tw .hg-tw-caret svg{width:100%;height:100%;display:block;animation:hg-spin 12s linear infinite}\n.hg-tw .hg-tw-caret[data-typing] svg{animation-duration:1.6s}\n@media (prefers-reduced-motion: reduce){.hg-tw [data-c]{transition:none}.hg-tw .hg-tw-pill{transition:none}.hg-tw .hg-tw-caret{transition:none}.hg-tw .hg-tw-caret svg{animation:none}}\n`;\n\n/**\n * A headline typed out by an asterisk. The asterisk is the caret: it runs\n * ahead of the letters, spinning fast while it types, then settles into the\n * slot marked * (by default just after the last word, like a footnote mark)\n * and keeps turning slowly. A [pill] in the markup opens to its width when\n * the caret reaches it. Every letter of the copy is typed: the asterisk only\n * ever takes a slot of its own, never a letter's place.\n *\n * Every letter is laid out from the first frame and only its opacity\n * changes, so the line never reflows while it types.\n */\nexport function AsteriskTypeHeadline({\n  text = \"Switch up to [pill]\\n**next generation** of interfaces.*\",\n  pill,\n  pillWidth = \"4.4em\",\n  as: Tag = \"h1\",\n  speed = 46,\n  delay = 450,\n  play = true,\n  caretColor,\n  className,\n  style,\n}: {\n  text?: string;\n  pill?: ReactNode;\n  pillWidth?: string;\n  as?: \"h1\" | \"h2\" | \"h3\" | \"p\";\n  /** Milliseconds per letter. */\n  speed?: number;\n  delay?: number;\n  /** Set false to hold the headline blank (for example until a loader ends). */\n  play?: boolean;\n  caretColor?: string;\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const tokens = useMemo(() => hgParseHeadline(text), [text]);\n  const root = useRef<HTMLHeadingElement>(null);\n  const caret = useRef<HTMLSpanElement>(null);\n  const seen = useHgSeen(root, \"0px\");\n  const plain = tokens.map((t) => (t.k === \"ch\" ? t.ch : t.k === \"star\" ? \"\" : t.k === \"br\" ? \" \" : \"\")).join(\"\").replace(/\\s+/g, \" \").trim();\n  useEffect(() => {\n    const el = root.current;\n    const cr = caret.current;\n    if (!el || !cr) return;\n    const items = Array.from(el.querySelectorAll<HTMLElement>(\"[data-c],[data-pill],[data-star]\"));\n    const place = (target: HTMLElement | null, after: boolean) => {\n      if (!target) return;\n      const a = el.getBoundingClientRect();\n      const b = target.getBoundingClientRect();\n      // The slot and the pill have no glyph box of their own, so the line's\n      // vertical metrics come from the nearest letter.\n      const line = target.closest(\"span.block\") ?? target;\n      const ref = line.querySelector<HTMLElement>(\"[data-c]\") ?? target;\n      const v = ref.getBoundingClientRect();\n      const s = cr.offsetWidth;\n      // Rects are in screen pixels, the caret moves in the headline's own:\n      // divide by the scale an ancestor transform applies (a scaled preview\n      // card, a zoomed stage) so the caret lands on its slot at any size.\n      const k = el.offsetWidth > 0 && a.width > 0 ? a.width / el.offsetWidth : 1;\n      const x = after ? (b.right - a.left) / k + s * 0.2 : (b.left - a.left + b.width / 2) / k - s / 2;\n      // Centre on the x-height: a little below the middle of the glyph box.\n      const y = (v.top - a.top + v.height * 0.56) / k - s / 2;\n      cr.style.transform = \"translate(\" + x + \"px,\" + y + \"px)\";\n    };\n    const star = el.querySelector<HTMLElement>(\"[data-star]\");\n    if (hgReducedMotion() || !play || !seen) {\n      const show = hgReducedMotion();\n      items.forEach((n) => (show ? n.setAttribute(\"data-on\", \"\") : n.removeAttribute(\"data-on\")));\n      cr.style.opacity = show ? \"1\" : \"0\";\n      cr.removeAttribute(\"data-typing\");\n      if (show) place(star ?? items[items.length - 1] ?? null, !star);\n      return;\n    }\n    items.forEach((n) => n.removeAttribute(\"data-on\"));\n    cr.style.transition = \"none\";\n    place(items[0] ?? null, false);\n    cr.style.opacity = \"1\";\n    void cr.offsetWidth;\n    cr.style.transition = \"\";\n    cr.setAttribute(\"data-typing\", \"\");\n    let i = 0;\n    let timer = 0;\n    const tick = () => {\n      const n = items[i];\n      if (!n) {\n        cr.removeAttribute(\"data-typing\");\n        place(star ?? items[items.length - 1] ?? null, !star);\n        return;\n      }\n      n.setAttribute(\"data-on\", \"\");\n      // The caret sits just after what has been typed. A pill takes longer\n      // to open, so the caret waits for it.\n      place(n, true);\n      i++;\n      const ch = n.textContent ?? \"\";\n      timer = window.setTimeout(tick, n.hasAttribute(\"data-pill\") ? 520 : ch === \" \" ? speed * 0.6 : speed * (0.7 + Math.random() * 0.6));\n    };\n    timer = window.setTimeout(tick, delay);\n    // The headline's box can change without the window changing (a\n    // container query, a font swap), so watch the element itself.\n    const onResize = () => {\n      if (i >= items.length) place(star ?? items[items.length - 1] ?? null, !star);\n    };\n    const ro = typeof ResizeObserver !== \"undefined\" ? new ResizeObserver(onResize) : null;\n    ro?.observe(el);\n    document.fonts?.ready.then(onResize);\n    return () => {\n      window.clearTimeout(timer);\n      ro?.disconnect();\n    };\n  }, [tokens, play, seen, speed, delay]);\n  let line: ReactNode[] = [];\n  const lines: ReactNode[][] = [];\n  tokens.forEach((t, i) => {\n    if (t.k === \"br\") {\n      lines.push(line);\n      line = [];\n      return;\n    }\n    if (t.k === \"pill\") {\n      line.push(\n        <span key={i} data-pill className=\"hg-tw-pill\" style={{ \"--hg-pill-w\": pillWidth } as CSSProperties}>\n          {pill}\n        </span>,\n      );\n      return;\n    }\n    if (t.k === \"star\") {\n      line.push(<span key={i} data-star style={{ display: \"inline-block\", width: \"0.6em\", fontWeight: t.bold ? 700 : 300 }} />);\n      return;\n    }\n    line.push(\n      <span key={i} data-c style={{ fontWeight: t.bold ? 700 : 300 }}>\n        {t.ch === \" \" ? String.fromCharCode(160) : t.ch}\n      </span>,\n    );\n  });\n  lines.push(line);\n  return (\n    <Tag\n      ref={root as RefObject<HTMLHeadingElement>}\n      aria-label={plain}\n      className={\"hg-tw relative \" + (className ?? \"\")}\n      style={{ fontFamily: HG_FONT, letterSpacing: \"-0.035em\", lineHeight: 1.12, ...style }}\n    >\n      <style>{HG_NAV_CSS + HG_TYPE_CSS}</style>\n      {lines.map((l, i) => (\n        <span key={i} aria-hidden className=\"block whitespace-nowrap\">\n          {l}\n        </span>\n      ))}\n      <span ref={caret} aria-hidden className=\"hg-tw-caret\" style={{ opacity: 0, ...(caretColor ? ({ \"--hg-caret\": caretColor } as CSSProperties) : null) }}>\n        <HgAsterisk stroke={2.4} />\n      </span>\n    </Tag>\n  );\n}\n","type":"registry:component","target":"components/viberdy/asterisk-type-headline.tsx"}],"meta":{"tier":"free","tags":["typewriter","text animation","headline","caret","asterisk","inline pill","hero text"],"href":"https://viberdy.dev/library/asterisk-type-headline","aiPrompt":"Build a React + Tailwind headline, `AsteriskTypeHeadline`, in one \"use client\" file with no dependencies. The headline is typed out by an asterisk: the asterisk is the caret, it runs just ahead of the letters spinning fast while it types, then settles into a marked slot of its own, by default just after the last word like a footnote mark, and keeps turning slowly. Every letter of the copy is typed: the asterisk never takes a letter's place. An optional inline pill in the middle of a line opens to its width when the caret reaches it.\n\nMarkup language for the `text` prop, parsed by an exported `hgParseHeadline(text)` that returns tokens: a newline starts a new line; `**` toggles bold; a lone `*` is the asterisk slot (an empty span the caret docks into); the literal `[pill]` is the inline pill; every other character is a letter token carrying its bold flag. Default text: \"Switch up to [pill]\\n**next generation** of interfaces.*\" (the slot sits after the full stop, in the weight of the surrounding text).\n\nLayout. The root element is the `as` tag (h1 by default; h1, h2, h3 or p), `relative`, font-family `var(--font-urbanist, \"Urbanist\"), \"Outfit\", ui-sans-serif, system-ui, sans-serif`, letter-spacing -0.035em, line-height 1.12, font size supplied by the host. It carries `aria-label` set to a plain-text version (letters only; the slot contributes nothing, the pill contributes nothing, line breaks become spaces, whitespace is collapsed and trimmed, so the default reads \"Switch up to next generation of interfaces.\") and each visual line is `aria-hidden`, so a screen reader hears the whole sentence at once rather than letter by letter. Each line is a `block whitespace-nowrap` span. Letters are individual spans (`data-c`), weight 700 when bold and 300 otherwise; spaces are rendered as non-breaking spaces. The slot is an inline-block 0.6em wide with the same weight rule. The pill is an inline-block with `vertical-align: -0.06em`, height 0.72em, fully rounded, `overflow:hidden`, and it holds the optional `pill` ReactNode (an image or gradient). Every letter is laid out from the first frame and only opacity changes, so the line never reflows while typing.\n\nStyling in an inline `<style>`: letters rest at opacity 0 and become 1 with `[data-on]` over .18s linear. The pill rests at width 0 and, when on, takes `width: var(--hg-pill-w, 4.4em)` and margin `0 .12em 0 .28em`, both transitioned .9s on `cubic-bezier(.2,.75,.15,1)`. The caret is an absolutely positioned (left 0, top 0) span 0.56em square, coloured `var(--hg-caret, currentColor)`, `pointer-events:none`, transitioning `transform .32s cubic-bezier(.2,.7,.2,1)` and opacity .3s. It contains the eight-spoke asterisk SVG (24 by 24 viewBox, stroke currentColor, stroke width 2.4, round caps, path `M12 3v18M3 12h18M5.6 5.6l12.8 12.8M18.4 5.6 5.6 18.4`) which spins with the `hg-spin` keyframes (360 degrees, linear, infinite) at 12s when idle and 1.6s while the caret has `data-typing`.\n\nTyping engine (a single effect). It collects the typeable items in document order (`[data-c]`, `[data-pill]`, `[data-star]`). A `place(target, after)` helper moves the caret by writing an inline `translate(x px, y px)`: x is the target's right edge plus 20% of the caret width when `after` (typing) or the target's centre minus half the caret when docking, measured relative to the root's box and divided by the scale an ancestor transform applies (a scaled preview card), so the caret lands on its slot at any size; y centres the caret on the x-height at 56% of the glyph box height of the nearest letter on that line (the slot and pill have no glyph box of their own). Start: after `delay` ms (default 450), with transitions disabled for the first placement at the first item, then enabled, the caret is shown and a `setTimeout` chain begins. Each tick turns the next item on, places the caret after it, and schedules the next tick: the pill waits 520 ms, a space waits `speed * 0.6`, a letter waits `speed * (0.7 + random * 0.6)` (default speed 46 ms), so the rhythm is slightly human. When items run out the typing flag is removed and the caret docks into the slot (or after the last item if no slot exists). A `ResizeObserver` on the root and `document.fonts.ready` re-dock the caret once typing is done, because container queries and font swaps change layout without a window resize.\n\nTriggering: typing starts only once the headline has entered the viewport, using an exported `useHgSeen(ref, margin)` hook (an IntersectionObserver that flips to true once and disconnects, rooted at the nearest ancestor that actually scrolls when there is one so it also works inside a scrolling preview; if IntersectionObserver is missing it flips to true on the next frame). The headline uses margin \"0px\". `play={false}` holds it blank (for example until a loader ends): all items off and the caret hidden.\n\nReduced motion: under `prefers-reduced-motion: reduce` every letter and the pill are shown at once, transitions and the caret spin are disabled, and the caret is placed statically in the slot.\n\nProps: `text` (default above), `pill` (ReactNode, default none), `pillWidth` (\"4.4em\"), `as` (\"h1\"), `speed` (46, ms per letter), `delay` (450, ms), `play` (true), `caretColor` (currentColor), `className`, `style`.","license":"https://viberdy.dev/license"}}