{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "glitch-text",
  "title": "Glitch Text",
  "description": "A short stepped burst that ends in clean text: colour fringes, shifting bands, dropped letters or a jumping line, and it never loops.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://miseui.junsu4621.workers.dev/r/split-text.json"
  ],
  "files": [
    {
      "path": "registry/miseui/ui/glitch-text.tsx",
      "content": "import type * as React from \"react\"\nimport { useEffect, useMemo, useRef } from \"react\"\nimport { useInView, useReducedMotion } from \"motion/react\"\nimport { BANDS, glitchBurst, type GlitchTextVariant } from \"@/registry/miseui/ui/glitch-math\"\nimport { useBurst, useHoverReplay } from \"@/registry/miseui/ui/glitch-play\"\nimport { splitText } from \"@/registry/miseui/ui/split-text-math\"\nimport { cn } from \"@/registry/miseui/lib/utils\"\n\ntype GlitchTextEffect = \"hover\"\ntype GlitchTextTrigger = \"view\" | \"mount\"\ntype GlitchTextTag = \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"p\" | \"span\" | \"div\"\n\nconst DEFAULT_SEED = 3\nconst VIEW_MARGIN = \"0px 0px -10% 0px\"\n/** Copies of the text exist only for the burst: hidden at rest so find in page counts the sentence once. */\nconst LAYER = \"pointer-events-none invisible absolute inset-0 block select-none\"\n/** Fixed hues, since the accent may be anything. Multiply on light and screen on dark make the overlap land back on the text colour. */\nconst FRINGE = \"mix-blend-multiply dark:mix-blend-screen\"\n\nfunction FringeLayers({ text }: { text: string }) {\n  return (\n    <>\n      <span aria-hidden=\"true\" data-slot=\"glitch-text-fringe\" className={cn(LAYER, FRINGE, \"text-red-500\")}>\n        {text}\n      </span>\n      <span aria-hidden=\"true\" data-slot=\"glitch-text-fringe\" className={cn(LAYER, FRINGE, \"text-cyan-500\")}>\n        {text}\n      </span>\n    </>\n  )\n}\n\nfunction BandLayers({ text }: { text: string }) {\n  return BANDS.map(([top, bottom]) => (\n    <span\n      key={top}\n      aria-hidden=\"true\"\n      data-slot=\"glitch-text-band\"\n      className={LAYER}\n      // The side insets are open, so a shifted band keeps glyphs that overhang the box.\n      style={{ clipPath: `inset(${top}% -1em ${100 - bottom}% -1em)` }}\n    >\n      {text}\n    </span>\n  ))\n}\n\nfunction FlickerLetters({ text }: { text: string }) {\n  const words = splitText(text, \"chars\")\n  return (\n    <span aria-hidden=\"true\" data-slot=\"glitch-text-visual\" className=\"block\">\n      {words.map((word, position) => (\n        <span key={word.key}>\n          <span className=\"inline-block whitespace-nowrap\">\n            {word.pieces.map((piece) => (\n              <span key={piece.index} data-slot=\"glitch-text-letter\" className=\"inline-block\">\n                {piece.text}\n              </span>\n            ))}\n          </span>\n          {position < words.length - 1 ? \" \" : null}\n        </span>\n      ))}\n    </span>\n  )\n}\n\nfunction GlitchBody({ text, variant }: { text: string; variant: GlitchTextVariant }) {\n  if (variant === \"flicker\") {\n    return (\n      <>\n        {/* Letters split apart would be read one by one, so assistive tech gets the sentence once. */}\n        <span className=\"sr-only select-none\">{text}</span>\n        <FlickerLetters text={text} />\n      </>\n    )\n  }\n  return (\n    <>\n      <span data-slot=\"glitch-text-content\" className=\"block\">\n        {text}\n      </span>\n      {variant === \"split\" ? <FringeLayers text={text} /> : null}\n      {variant === \"slice\" ? <BandLayers text={text} /> : null}\n    </>\n  )\n}\n\ntype GlitchTextProps = Omit<React.HTMLAttributes<HTMLElement>, \"children\"> & {\n  text: string\n  /** The element to render. A heading stays a heading. */\n  as?: GlitchTextTag\n  /** `split` offset colour fringes, `slice` horizontal bands shift, `flicker` letters drop out like a sign starting, `skew` the line jumps in steps. */\n  variant?: GlitchTextVariant\n  /** `hover` plays only on hover and focus. Listens on the nearest link or button around it. */\n  effect?: GlitchTextEffect\n  /** `view` plays once when first seen, `mount` plays right away. */\n  trigger?: GlitchTextTrigger\n  /** The same seed gives the same burst. */\n  seed?: number\n}\n\nfunction GlitchText({ text, as: Tag = \"span\", variant = \"split\", effect, trigger = \"view\", seed = DEFAULT_SEED, className, ...props }: GlitchTextProps) {\n  const reduceMotion = useReducedMotion() ?? false\n  const anchorRef = useRef<HTMLSpanElement>(null)\n  const seen = useInView(anchorRef, { once: true, margin: VIEW_MARGIN })\n  const letterCount = useMemo(() => splitText(text, \"chars\").reduce((sum, word) => sum + word.pieces.length, 0), [text])\n  const burst = useMemo(() => glitchBurst(variant, seed, letterCount), [variant, seed, letterCount])\n  const { play, stop } = useBurst({ anchor: anchorRef, variant, burst })\n  const auto = effect !== \"hover\" && !reduceMotion\n  const due = trigger === \"mount\" || seen\n\n  useEffect(() => {\n    if (!auto || !due) return\n    play()\n    return stop\n  }, [auto, due, play, stop])\n\n  useHoverReplay(anchorRef, effect === \"hover\" && !reduceMotion, play)\n\n  return (\n    <Tag {...props} data-slot=\"glitch-text\" data-variant={variant} data-effect={effect} className={cn(\"relative isolate inline-block max-w-full\", className)}>\n      {/* Inline-block so the copies share the box and wrap exactly like the text under them. */}\n      <span ref={anchorRef} data-slot=\"glitch-text-stage\" className=\"relative block\">\n        {/* The key sits inside the observed element, because useInView keeps watching the node it first got. */}\n        <GlitchBody key={`${variant}:${reduceMotion}:${text}`} text={text} variant={variant} />\n      </span>\n    </Tag>\n  )\n}\n\nexport { GlitchText, type GlitchTextProps, type GlitchTextVariant, type GlitchTextEffect, type GlitchTextTrigger }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/glitch-play.ts",
      "content": "import type * as React from \"react\"\nimport { useCallback, useEffect, useRef } from \"react\"\nimport { BANDS, MIN_REPLAY_MS, frameAt, type GlitchBurst, type GlitchFrame, type GlitchTextVariant } from \"@/registry/miseui/ui/glitch-math\"\n\nconst OFF_OPACITY = \"0.12\"\n\ntype Painter = (frame: GlitchFrame | null) => void\n\nfunction all(root: HTMLElement, slot: string) {\n  return Array.from(root.querySelectorAll<HTMLElement>(`[data-slot='${slot}']`))\n}\n\nfunction paintFringes(root: HTMLElement): Painter {\n  const [red, cyan] = all(root, \"glitch-text-fringe\")\n  return (frame) => {\n    const offset = frame?.fringe ?? 0\n    red.style.visibility = frame ? \"visible\" : \"\"\n    cyan.style.visibility = frame ? \"visible\" : \"\"\n    red.style.transform = frame ? `translateX(${offset}em)` : \"\"\n    cyan.style.transform = frame ? `translateX(${-offset}em)` : \"\"\n  }\n}\n\n/** The whole line is rebuilt from bands during the burst, so the real text is only hidden for those few frames. */\nfunction paintBands(root: HTMLElement): Painter {\n  const bands = all(root, \"glitch-text-band\")\n  const content = root.querySelector<HTMLElement>(\"[data-slot='glitch-text-content']\")\n  return (frame) => {\n    if (content) content.style.opacity = frame ? \"0\" : \"\"\n    bands.forEach((band, index) => {\n      band.style.visibility = frame ? \"visible\" : \"\"\n      band.style.transform = frame ? `translateX(${frame.bands[index % BANDS.length]}em)` : \"\"\n    })\n  }\n}\n\nfunction paintLetters(root: HTMLElement): Painter {\n  const letters = all(root, \"glitch-text-letter\")\n  return (frame) => {\n    letters.forEach((letter, index) => {\n      letter.style.opacity = frame?.off.includes(index) ? OFF_OPACITY : \"\"\n    })\n  }\n}\n\nfunction paintSkew(root: HTMLElement): Painter {\n  const content = root.querySelector<HTMLElement>(\"[data-slot='glitch-text-content']\")\n  return (frame) => {\n    if (content) content.style.transform = frame ? `translateX(${frame.shift}em) skewX(${frame.skew}deg)` : \"\"\n  }\n}\n\nconst PAINTERS: Record<GlitchTextVariant, (root: HTMLElement) => Painter> = {\n  split: paintFringes,\n  slice: paintBands,\n  flicker: paintLetters,\n  skew: paintSkew,\n}\n\ninterface BurstOptions {\n  anchor: React.RefObject<HTMLElement | null>\n  variant: GlitchTextVariant\n  burst: GlitchBurst\n}\n\n/** One frame loop per component, ending in a clean element with nothing left behind. */\nfunction useBurst({ anchor, variant, burst }: BurstOptions) {\n  const frame = useRef(0)\n  const lastStart = useRef(Number.NEGATIVE_INFINITY)\n  const painter = useRef<Painter | null>(null)\n\n  const stop = useCallback(() => {\n    if (frame.current === 0) return\n    cancelAnimationFrame(frame.current)\n    frame.current = 0\n    // A burst cut short showed nothing worth a cool-down (StrictMode cuts the first one), and it must not leave a pose behind.\n    lastStart.current = Number.NEGATIVE_INFINITY\n    painter.current?.(null)\n  }, [])\n\n  const play = useCallback(() => {\n    const root = anchor.current\n    const moment = performance.now()\n    if (!root || frame.current !== 0 || moment - lastStart.current < MIN_REPLAY_MS) return\n    lastStart.current = moment\n    const paint = PAINTERS[variant](root)\n    painter.current = paint\n    let origin: number | null = null\n    let held: GlitchFrame | null = null\n    const tick = (now: number) => {\n      origin = origin ?? now\n      const current = frameAt(burst, now - origin)\n      // Only on a new pose: the point is that it jumps, and the frames between have nothing to do.\n      if (current !== held) paint(current)\n      held = current\n      frame.current = current ? requestAnimationFrame(tick) : 0\n    }\n    frame.current = requestAnimationFrame(tick)\n  }, [anchor, variant, burst])\n\n  useEffect(() => stop, [stop])\n  return { play, stop }\n}\n\nconst REPLAY_HOST = \"a, button, [role='link'], [role='button']\"\n\n/** Listens on the link or button around the text, since text cannot take focus and the control is usually bigger. */\nfunction useHoverReplay(anchor: React.RefObject<HTMLElement | null>, enabled: boolean, play: () => void) {\n  useEffect(() => {\n    const root = anchor.current\n    if (!enabled || !root) return\n    const host = root.closest<HTMLElement>(REPLAY_HOST) ?? root\n    const onFocus = (event: FocusEvent) => {\n      if (event.target instanceof Element && event.target.matches(\":focus-visible\")) play()\n    }\n    host.addEventListener(\"mouseenter\", play)\n    host.addEventListener(\"focusin\", onFocus)\n    return () => {\n      host.removeEventListener(\"mouseenter\", play)\n      host.removeEventListener(\"focusin\", onFocus)\n    }\n  }, [anchor, enabled, play])\n}\n\nexport { useBurst, useHoverReplay }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/glitch-math.ts",
      "content": "type GlitchTextVariant = \"split\" | \"slice\" | \"flicker\" | \"skew\"\n\n/** One held pose. Offsets are in em so the burst scales with the type. */\ninterface GlitchFrame {\n  at: number\n  fringe: number\n  /** Sideways shift of each band. */\n  bands: readonly number[]\n  /** Letters that have dropped out. */\n  off: readonly number[]\n  skew: number\n  shift: number\n}\n\ninterface GlitchBurst {\n  frames: readonly GlitchFrame[]\n  durationMs: number\n}\n\n/** Top and bottom of each band, in percent. They overlap a hair so a seam never shows between them. */\nconst BANDS = [\n  [0, 28],\n  [27.5, 53],\n  [52.5, 79],\n  [78.5, 100],\n] as const\n\n/** Start to start. With at most three drop-outs per burst, no second can hold more than three flashes (WCAG 2.3.1). */\nconst MIN_REPLAY_MS = 1000\nconst FLICKER_OFF_RATIO = [0.45, 0.25, 0.6] as const\nconst FLICKER_TIMES = [0, 70, 170, 260, 420, 520] as const\nconst FLICKER_END_MS = 640\n\nfunction glitchUnit(seed: number, a: number, b = 0) {\n  const mixed = Math.imul((seed + 1) ^ Math.imul(a + 1, 0x9e3779b1) ^ Math.imul(b + 1, 0x85ebca77), 0xc2b2ae3d)\n  return (((mixed ^ (mixed >>> 15)) >>> 0) % 10000) / 10000\n}\n\nfunction signed(seed: number, a: number, b = 0) {\n  return glitchUnit(seed, a, b) < 0.5 ? -1 : 1\n}\n\nconst CLEAN: Omit<GlitchFrame, \"at\"> = { fringe: 0, bands: [0, 0, 0, 0], off: [], skew: 0, shift: 0 }\n\nfunction round(value: number) {\n  return Math.round(value * 1000) / 1000\n}\n\nfunction splitBurst(seed: number): GlitchBurst {\n  const sizes = [0.05, 0.022, 0.07, 0.03, 0.014]\n  const frames = sizes.map((size, index) => ({ ...CLEAN, at: index * 70, fringe: round(size * signed(seed, index)) }))\n  return { frames, durationMs: sizes.length * 70 }\n}\n\nfunction sliceBurst(seed: number): GlitchBurst {\n  const moves = [2, 2, 1, 2, 1, 0]\n  const frames = moves.map((count, index) => {\n    const pick = Math.floor(glitchUnit(seed, index, 9) * BANDS.length)\n    const bands = BANDS.map((_, band) => {\n      const hit = (band - pick + BANDS.length) % BANDS.length < count\n      return hit ? round((0.05 + glitchUnit(seed, index, band) * 0.11) * signed(seed, index, band)) : 0\n    })\n    return { ...CLEAN, at: index * 60, bands }\n  })\n  return { frames, durationMs: moves.length * 60 }\n}\n\n/** Off frames alternate with clean ones, so a letter can drop out at most three times in a burst. */\nfunction flickerBurst(seed: number, letterCount: number): GlitchBurst {\n  const frames = FLICKER_TIMES.map((at, index) => {\n    if (index % 2 === 1) return { ...CLEAN, at }\n    const ratio = FLICKER_OFF_RATIO[index / 2]\n    const off = Array.from({ length: letterCount }, (_, letter) => letter).filter((letter) => glitchUnit(seed, letter, index) < ratio)\n    return { ...CLEAN, at, off }\n  })\n  return { frames, durationMs: FLICKER_END_MS }\n}\n\nfunction skewBurst(seed: number): GlitchBurst {\n  const direction = signed(seed, 0)\n  const poses = [\n    [8, 0.03],\n    [-5, -0.02],\n    [3, 0.014],\n    [-2, -0.008],\n  ]\n  const frames = poses.map(([skew, shift], index) => ({ ...CLEAN, at: index * 65, skew: skew * direction, shift: shift * direction }))\n  return { frames, durationMs: poses.length * 65 }\n}\n\nfunction glitchBurst(variant: GlitchTextVariant, seed: number, letterCount: number): GlitchBurst {\n  if (variant === \"split\") return splitBurst(seed)\n  if (variant === \"slice\") return sliceBurst(seed)\n  if (variant === \"flicker\") return flickerBurst(seed, letterCount)\n  return skewBurst(seed)\n}\n\n/** The pose held at a moment, or null once the text is clean again. Stepped by design: nothing tweens between frames. */\nfunction frameAt(burst: GlitchBurst, elapsed: number) {\n  if (elapsed >= burst.durationMs) return null\n  return burst.frames.reduce<GlitchFrame | null>((held, frame) => (frame.at <= elapsed ? frame : held), null)\n}\n\n/** How many times a letter goes from lit to dropped within a burst. */\nfunction dropOuts(burst: GlitchBurst, letter: number) {\n  return burst.frames.filter((frame) => frame.off.includes(letter)).length\n}\n\nexport { BANDS, MIN_REPLAY_MS, dropOuts, frameAt, glitchBurst, type GlitchBurst, type GlitchFrame, type GlitchTextVariant }\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "text"
  ],
  "type": "registry:ui"
}