"use client";import * as React from "react";import { createSpring, useInteractionActivity, useInteractionReducedMotion, type Spring } from "./ui-interaction-motion";import { createTubeRenderer, resolveColors, type Rgb, type TubeRenderer, type TubeStroke } from "./light-writing-gl";import { SPACING, layoutText, pairDrawings, parsePath, penIndex, timeDrawing, type MorphPair, type TimedDrawing } from "./light-writing-path";/* ───────────────────────────────────────────────────────── * LIGHT WRITING: a word written in one line of light * * A glass tube writes the word the way a hand would, then the * same line bends into the next word or into your mark: * * writing a white-hot tip draws the letters in one stroke; * it slows in loops and runs on the straights * holding colour keeps flowing along the line * changing the line squeezes together and unfolds as the next * word or a logo, point by point, on a spring * erasing the tail chases the tip until nothing is left * * Words come from a single-line script (Latin letters with * accents); marks are any SVG path. Off screen or in a hidden tab * it stops, and its holds wait. * * Reduced motion: each item appears whole and still. * ───────────────────────────────────────────────────────── *//** A word to write, or a drawn mark: an SVG path `d` (any size; it is scaled to the lettering) and what it says. */export type LightWritingItem = string | { path: string; label: string };export interface LightWritingProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "children"> { /** One word or phrase to write. */ text?: string; /** Several, shown in turn: each one is written, held, then the line turns into the next. Wins over `text`. */ items?: LightWritingItem[]; /** The item showing, when you drive it (a launch screen that turns into the logo once the app is ready). */ index?: number; defaultIndex?: number; onIndexChange?: (index: number) => void; /** Whether it moves on by itself after `hold`. On by default when there is more than one item and no `index`. */ autoPlay?: boolean; /** Start again from the first item after the last. */ loop?: boolean; /** How long each item stays once written, in ms. */ hold?: number; /** How one item becomes the next: the line bends into it, or the first is erased and the next written. */ change?: "morph" | "rewrite"; /** Hide it by erasing; show it again by writing. */ show?: boolean; /** Pen speed; 1 writes "hello" in about 1.8 seconds. */ speed?: number; /** Tube thickness as a fraction of the letters' x-height. */ weight?: number; /** CSS colours that flow along the line; theme variables welcome. */ colors?: string[]; /** Light around the tube, 0 to 1. */ glow?: number; /** Called when an item has been written (or the line has finished turning into it). */ onWritten?: (index: number) => void; /** What it says, for screen readers. Defaults to the items' words. */ label?: string;}const COLORS = ["var(--chart-1, var(--primary))", "var(--chart-2, var(--primary))", "var(--chart-5, var(--primary))"];// A light needs colour: when the theme's chart colours are all grey (shadcn's neutral theme), the tube uses these.const VIVID: Rgb[] = [[0.26, 0.47, 1], [0.96, 0.32, 0.62], [1, 0.56, 0.18]];const ERASE = 1.5; // erasing runs faster than writingconst COOL = 0.35; // seconds for a finished stroke's tip to coolconst FLOW = 0.22; // colour bands per second flowing along the lineconst PERIOD = 6; // x-heights of line per colour bandconst MORPH = { stiffness: 64, damping: 15 };const WAVE = 0.3; // how far behind the end of a stroke starts moving, as a share of the morphconst SQUEEZE = 0.68; // how far the line pulls in sideways halfway through a morphconst BLEED = 0.3; // how far the canvas reaches past the box for the glow, as a share of the box's shorter sideconst labelOf = (item: LightWritingItem) => (typeof item === "string" ? item : item.label);type Placed = { timed: TimedDrawing; /** Strokes in canvas pixels. */ strokes: Float32Array[]; /** Where each stroke starts along the whole drawing, in pixels. */ orders: number[]; total: number; /** Pixels between points. */ step: number;};type Morph = { pairs: MorphPair[]; /** Interpolated points, one array per pair. */ live: Float32Array[]; lengthsFrom: number[]; lengthsTo: number[]; center: number; target: number;};type Phase = "blank" | "writing" | "shown" | "erasing" | "morphing";const lengthOf = (pts: Float32Array) => { let L = 0; for (let i = 2; i < pts.length; i += 2) L += Math.hypot(pts[i] - pts[i - 2], pts[i + 1] - pts[i - 1]); return L;};const smoothstep = (x: number) => (x <= 0 ? 0 : x >= 1 ? 1 : x * x * (3 - 2 * x));export function LightWriting({ text, items: itemsProp, index: indexProp, defaultIndex = 0, onIndexChange, autoPlay, loop = true, hold = 2000, change = "morph", show = true, speed = 1, weight = 0.36, colors = COLORS, glow = 1, onWritten, label, className = "", style, ...props}: LightWritingProps) { const items = React.useMemo<LightWritingItem[]>(() => itemsProp ?? (text !== undefined ? [text] : []), [itemsProp, text]); const itemsKey = items.map((i) => (typeof i === "string" ? `t:${i}` : `p:${i.label}:${i.path}`)).join("\u0001"); const reduced = useInteractionReducedMotion(); const { ref: activityRef, active } = useInteractionActivity<HTMLDivElement>(); const canvas = React.useRef<HTMLCanvasElement>(null); const fallback = React.useRef<SVGSVGElement>(null); const [failed, setFailed] = React.useState(false); const [ownIndex, setOwnIndex] = React.useState(defaultIndex); const controlled = indexProp !== undefined; const count = items.length; const index = count ? (((controlled ? indexProp : ownIndex) % count) + count) % count : 0; const playing = autoPlay ?? (!controlled && count > 1); const colorKey = colors.join("|"); // The latest props, for the frame loop. const advance = (to: number) => { if (!controlled) setOwnIndex(to); onIndexChange?.(to); }; const input = React.useRef({ index, playing, loop, hold, change, show, speed, glow, reduced, onWritten, advance, controlled, count }); React.useLayoutEffect(() => { input.current = { index, playing, loop, hold, change, show, speed, glow, reduced, onWritten, advance, controlled, count }; }); const engine = React.useRef<{ renderer: TubeRenderer | null; placed: Placed[]; scale: number; radius: number; palette: Rgb[]; dark: boolean; phase: Phase; /** The item on screen, or being written, erased or turned into. */ shown: number; clock: number; hold: number; shift: number; morph: Morph | null; spring: Spring | null; pending: number | null; frame: (dt: number) => boolean; draw: () => void; go: (to: number) => void; } | null>(null); const [layoutTick, setLayoutTick] = React.useState(0); // The renderer lives as long as the canvas. React.useEffect(() => { const el = canvas.current; if (!el) return; let renderer: TubeRenderer | null = null; try { renderer = createTubeRenderer(el); } catch { renderer = null; } if (!renderer) { const frame = requestAnimationFrame(() => setFailed(true)); return () => cancelAnimationFrame(frame); } const r = renderer; const e: NonNullable<typeof engine.current> = { renderer: r, placed: [], scale: 1, radius: 4, palette: [[0.19, 0.36, 0.87], [0.11, 0.69, 0.48], [0.88, 0.64, 0.11], [0.91, 0.45, 0.23]], dark: false, phase: "blank", shown: input.current.index, clock: 0, hold: 0, shift: 0, morph: null, spring: null, pending: null, frame: () => false, draw: () => {}, go: () => {}, }; const strokesNow: TubeStroke[] = []; const stroke = (i: number): TubeStroke => { if (!strokesNow[i]) strokesNow[i] = { points: new Float32Array(0), from: 0, to: 0, radius: 0, order: 0, step: 1, headHeat: 0, tailHeat: 0 }; return strokesNow[i]; }; /** The line as it is right now, as strokes for the renderer. */ const build = (): { list: TubeStroke[]; total: number } => { const p = e.placed[e.shown]; let n = 0; if (e.phase === "morphing" && e.morph) { const m = e.morph; const t = e.spring ? e.spring.get() : 1; // The line pulls in sideways and changes shape while it is narrow, so the change reads as one bundle unfolding. const pull = SQUEEZE * Math.pow(Math.sin(Math.PI * Math.min(1, Math.max(0, t))), 0.8); let order = 0; m.pairs.forEach((pair, k) => { const live = m.live[k]; const points = pair.from.length / 2; // A stroke with no partner melts away early in the morph, or grows late, all at once: never a long thin sliver. const melting = pair.toSize < pair.fromSize, growing = pair.toSize > pair.fromSize; const alone = melting ? smoothstep(t / 0.45) : growing ? smoothstep((t - 0.55) / 0.45) : -1; let size = 0; for (let i = 0; i < points; i++) { const u = points > 1 ? i / (points - 1) : 0; const local = alone >= 0 ? alone : smoothstep((t * (1 + WAVE) - WAVE * u - 0.15) / 0.7); const x = pair.from[i * 2] + (pair.to[i * 2] - pair.from[i * 2]) * local; const y = pair.from[i * 2 + 1] + (pair.to[i * 2 + 1] - pair.from[i * 2 + 1]) * local; live[i * 2] = m.center + (x - m.center) * (1 - pull); live[i * 2 + 1] = y; if (i === points >> 1) size = pair.fromSize + (pair.toSize - pair.fromSize) * local; } const length = m.lengthsFrom[k] + (m.lengthsTo[k] - m.lengthsFrom[k]) * Math.min(1, Math.max(0, t)); const s = stroke(n++); s.points = live; s.from = 0; s.to = points - 1; s.radius = e.radius * Math.max(0, size); s.order = order; s.step = length / Math.max(1, points - 1); s.headHeat = 0; s.tailHeat = 0; order += length; }); strokesNow.length = n; return { list: strokesNow, total: Math.max(1, order) }; } if (!p || e.phase === "blank") { strokesNow.length = 0; return { list: strokesNow, total: 1 }; } // While erasing, the tip stays where it stopped and `hold` is the tail's clock. const writtenTime = e.clock; const tailTime = e.phase === "erasing" ? e.hold : -Infinity; p.timed.strokes.forEach((ts, k) => { const last = ts.points.length / 2 - 1; const to = writtenTime === Infinity ? last : penIndex(ts, writtenTime); if (to < 0) return; const from = tailTime === -Infinity ? 0 : Math.max(0, penIndex(ts, tailTime)); if (tailTime !== -Infinity && tailTime >= ts.at[last]) return; const s = stroke(n++); s.points = p.strokes[k]; s.from = from; s.to = to; s.radius = e.radius; s.order = p.orders[k]; s.step = p.step; const end = ts.at[last]; s.headHeat = e.phase === "erasing" ? 0 : writtenTime < end ? 1 : Math.max(0, 1 - (writtenTime - end) / COOL); s.tailHeat = e.phase === "erasing" && tailTime > ts.at[0] ? 0.85 : 0; }); strokesNow.length = n; return { list: strokesNow, total: p.total }; }; e.draw = () => { const { list, total } = build(); const now = input.current; r.draw(list, { palette: e.palette, period: PERIOD * e.scale, shift: e.shift, total, glow: Math.max(0, Math.min(1, now.glow)) * (e.dark ? 1 : 0.3), dark: e.dark, }); }; const written = (i: number) => { e.phase = "shown"; e.hold = 0; input.current.onWritten?.(i); }; /** Move to another item the way `change` says; under reduced motion, at once. */ e.go = (to: number) => { const target = e.placed[to]; if (!target) return; const now = input.current; if (now.reduced) { e.shown = to; e.phase = now.show ? "shown" : "blank"; e.clock = Infinity; e.morph = null; e.spring?.stop(); e.draw(); if (now.show) now.onWritten?.(to); return; } if (e.phase === "blank") { e.shown = to; e.phase = "writing"; e.clock = 0; return; } if (now.change === "rewrite") { e.pending = to; if (e.phase !== "erasing") { if (e.phase === "morphing") e.clock = Infinity; e.phase = "erasing"; e.hold = 0; } return; } // Morph from whatever is on screen now: the drawing, or the line mid-way through another morph. const from: Float32Array[] = []; const midway = e.phase === "morphing" ? e.morph : null; if (midway) { const t = e.spring?.get() ?? 1; midway.pairs.forEach((pair, k) => { // Strokes that have almost melted away are left behind. if (pair.fromSize + (pair.toSize - pair.fromSize) * smoothstep(t) > 0.25) from.push(Float32Array.from(midway.live[k])); }); } else e.placed[e.shown]?.strokes.forEach((s) => from.push(s)); const pairs = pairDrawings(from, target.strokes); const left = Math.min(...[...from, ...target.strokes].map((s) => s.reduce((m, v, i) => (i % 2 === 0 ? Math.min(m, v) : m), Infinity))); const right = Math.max(...[...from, ...target.strokes].map((s) => s.reduce((m, v, i) => (i % 2 === 0 ? Math.max(m, v) : m), -Infinity))); e.morph = { pairs, live: pairs.map((pair) => new Float32Array(pair.from.length)), lengthsFrom: pairs.map((pair) => lengthOf(pair.from)), lengthsTo: pairs.map((pair) => lengthOf(pair.to)), center: (left + right) / 2, target: to, }; const velocity = e.phase === "morphing" && e.spring ? Math.max(0, e.spring.getVelocity()) * 0.5 : 0; e.phase = "morphing"; e.shown = to; if (!e.spring) e.spring = createSpring(0, MORPH, () => {}, 0.0005); e.spring.jump(0); e.spring.push(velocity); e.spring.set(1); }; /** One frame of time: returns whether anything still moves. */ e.frame = (dt: number) => { const now = input.current; e.shift += dt * FLOW; const p = e.placed[e.shown]; if (!p) return false; switch (e.phase) { case "blank": if (now.show && e.pending === null) { e.phase = "writing"; e.clock = 0; } else if (e.pending !== null && now.show) { e.shown = e.pending; e.pending = null; e.phase = "writing"; e.clock = 0; } break; case "writing": e.clock += dt * now.speed; if (!now.show) { e.phase = "erasing"; e.hold = 0; } else if (e.clock >= p.timed.duration) written(e.shown); break; case "shown": e.clock += dt * now.speed; if (!now.show) { e.phase = "erasing"; e.hold = 0; break; } if (now.index !== e.shown) { e.go(now.index); break; } e.hold += dt * 1000; if (now.playing && now.count > 1 && e.hold >= now.hold) { const next = e.shown + 1; if (next < now.count || now.loop) { const to = next % now.count; // When the index is yours, ask once per hold; the change starts when the new index arrives. e.hold = 0; now.advance(to); if (!now.controlled) e.go(to); } } break; case "erasing": // `hold` doubles as the tail's clock while erasing. e.hold += dt * now.speed * ERASE; if (e.hold >= Math.min(e.clock, p.timed.duration)) { e.phase = "blank"; e.hold = 0; if (e.pending !== null) { e.shown = e.pending; e.pending = null; if (now.show) { e.phase = "writing"; e.clock = 0; } } } break; case "morphing": if (!e.spring || Math.abs(e.spring.get() - 1) < 0.002 && Math.abs(e.spring.getVelocity()) < 0.01) { e.morph = null; e.clock = Infinity; written(e.shown); } break; } return true; }; engine.current = e; const lost = (event: Event) => { event.preventDefault(); setFailed(true); }; el.addEventListener("webglcontextlost", lost); return () => { el.removeEventListener("webglcontextlost", lost); e.spring?.stop(); r.dispose(); engine.current = null; }; }, []); // Lay the items out for the canvas's size: every word at one letter size and baseline, marks to the lettering's height. React.useEffect(() => { const el = canvas.current; const host = el?.parentElement; if (!el || !host) return; let width = 0, height = 0; const lay = () => { const box = host.getBoundingClientRect(); if (box.width < 2 || box.height < 2) return; if (Math.abs(box.width - width) < 0.5 && Math.abs(box.height - height) < 0.5) return; width = box.width; height = box.height; const dpr = Math.min(2, window.devicePixelRatio || 1); // The canvas reaches past the box on every side, so the light fades out on the page instead of stopping at an edge. const bleed = Math.round(Math.min(width, height) * BLEED); el.style.inset = `${-bleed}px`; el.style.width = `${width + bleed * 2}px`; el.style.height = `${height + bleed * 2}px`; el.width = Math.round((width + bleed * 2) * dpr); el.height = Math.round((height + bleed * 2) * dpr); const innerW = width * dpr, innerH = height * dpr; const e = engine.current; // Marks stand as tall as the lettering, from the top of the tallest letter to the bottom of the deepest. const words = items.map((item) => (typeof item === "string" ? layoutText(item) : null)); let markHeight = 0; words.forEach((w) => w && w.strokes.length && (markHeight = Math.max(markHeight, w.bounds[3] - w.bounds[1]))); const drawings = items.map((item, i) => timeDrawing(words[i] ?? parsePath((item as { path: string }).path, markHeight ? markHeight * 0.92 : 2.6))); // Room for the glow and the thickness of the tube. // Room inside the box for the tube's thickness. const pad = 0.06 * Math.min(innerW, innerH); let top = Infinity, bottom = -Infinity, widest = 0; drawings.forEach((d) => { top = Math.min(top, d.bounds[1]); bottom = Math.max(bottom, d.bounds[3]); widest = Math.max(widest, d.bounds[2] - d.bounds[0]); }); if (!Number.isFinite(top)) return; const scale = Math.max(1, Math.min((innerW - pad * 2) / Math.max(1e-3, widest + weight), (innerH - pad * 2) / Math.max(1e-3, bottom - top + weight))); const placed = drawings.map((d): Placed => { const ox = el.width / 2 - ((d.bounds[0] + d.bounds[2]) / 2) * scale; const oy = el.height / 2 - ((top + bottom) / 2) * scale; const strokes = d.strokes.map((s) => { const out = new Float32Array(s.points.length); for (let i = 0; i < out.length; i += 2) { out[i] = ox + s.points[i] * scale; out[i + 1] = oy + s.points[i + 1] * scale; } return out; }); const orders: number[] = []; let total = 0; d.strokes.forEach((s) => { orders.push(total); total += s.length * scale; }); return { timed: d, strokes, orders, total, step: SPACING * scale }; }); if (!e) return; e.placed = placed; e.scale = scale; e.radius = (weight * scale) / 2; // A new layout ends any morph in flight: its points belong to the old size. if (e.phase === "morphing") { e.morph = null; e.spring?.stop(); e.phase = "shown"; e.clock = Infinity; } if (e.shown >= placed.length) e.shown = 0; setLayoutTick((t) => t + 1); }; lay(); const observer = new ResizeObserver(lay); observer.observe(host); return () => observer.disconnect(); // itemsKey stands for items. // eslint-disable-next-line react-hooks/exhaustive-deps }, [itemsKey, weight, failed]); // Colours from the theme, again whenever the theme changes. React.useEffect(() => { const el = canvas.current; if (!el || failed) return; const apply = () => { const e = engine.current; if (!e) return; const resolved = resolveColors(el.parentElement ?? document.body, [...colorKey.split("|"), "var(--background, #fff)"]); const bg = resolved.pop()!; const grey = resolved.every(([r, g, b]) => Math.max(r, g, b) - Math.min(r, g, b) < 0.12); e.palette = !resolved.length ? e.palette : grey && colorKey === COLORS.join("|") ? VIVID : resolved; e.dark = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] < 0.45; e.draw(); }; apply(); const root = document.documentElement; let theme = `${root.className}|${root.dataset.theme ?? ""}`; const watch = new MutationObserver(() => { const next = `${root.className}|${root.dataset.theme ?? ""}`; if (next === theme) return; theme = next; apply(); }); watch.observe(root, { attributes: true, attributeFilter: ["class", "data-theme"] }); return () => watch.disconnect(); }, [colorKey, failed, layoutTick]); // Driven from outside: a new index (or showing and hiding) starts its change on the next frame; reduced motion shows it at once. React.useEffect(() => { const e = engine.current; if (!e || !e.placed.length) return; if (reduced) { if (e.shown !== index || e.phase !== (show ? "shown" : "blank")) { e.shown = index; e.phase = show ? "shown" : "blank"; e.clock = Infinity; e.morph = null; e.spring?.stop(); e.draw(); } return; } if (index === e.shown) return; if (e.phase === "blank") e.shown = index; else if (e.phase === "erasing") e.pending = index; else e.go(index); }, [index, show, reduced, layoutTick]); // Under reduced motion the items still take turns, each appearing whole. React.useEffect(() => { if (!reduced || !playing || count < 2 || !active) return; const timer = window.setTimeout(() => { const next = index + 1; if (next < count || loop) input.current.advance(next % count); }, hold + 1200); return () => window.clearTimeout(timer); }, [reduced, playing, count, active, index, loop, hold]); // The loop: only while on screen and the tab is visible. Reduced motion draws once and holds. React.useEffect(() => { const e = engine.current; if (!e || failed) return; if (reduced) { if (e.phase !== "blank") { e.phase = show ? "shown" : "blank"; e.clock = Infinity; } e.draw(); return; } if (!active) return; let frame = 0; let last = 0; const tick = (now: number) => { const dt = last ? Math.min(1 / 20, (now - last) / 1000) : 1 / 60; last = now; const cur = engine.current; if (!cur) return; cur.frame(dt); cur.draw(); frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); }, [active, reduced, failed, show, layoutTick]); // Without WebGL 2: the same line, still, as an SVG stroke with the colours along it. React.useEffect(() => { const svg = fallback.current; const host = svg?.parentElement; if (!failed || !svg || !host) return; const box = host.getBoundingClientRect(); const d = timeDrawing(typeof items[index] === "string" ? layoutText(items[index] as string) : parsePath((items[index] as { path: string }).path)); const [l, t, r, b] = d.bounds; const k = Math.min((box.width * 0.8) / Math.max(1e-3, r - l), (box.height * 0.7) / Math.max(1e-3, b - t)); const ox = box.width / 2 - ((l + r) / 2) * k, oy = box.height / 2 - ((t + b) / 2) * k; svg.setAttribute("viewBox", `0 0 ${box.width} ${box.height}`); const path = svg.querySelector("path"); if (!path) return; path.setAttribute( "d", d.strokes .map((s) => { let out = ""; for (let i = 0; i < s.points.length; i += 2) out += `${i ? "L" : "M"}${(ox + s.points[i] * k).toFixed(1)} ${(oy + s.points[i + 1] * k).toFixed(1)}`; return out; }) .join(""), ); path.setAttribute("stroke-width", String(weight * k)); }, [failed, itemsKey, index, weight, items]); const spoken = label ?? items.map(labelOf).join(", "); const gradientId = React.useId(); return ( <div ref={activityRef} role="img" aria-label={spoken} {...props} className={`relative block w-full ${className}`} style={{ aspectRatio: "12 / 5", ...style }} > <canvas ref={canvas} aria-hidden="true" className="pointer-events-none absolute inset-0 size-full" style={{ display: failed ? "none" : undefined }} /> {failed ? ( <svg ref={fallback} aria-hidden="true" className="absolute inset-0 size-full" fill="none"> <defs> <linearGradient id={gradientId} x1="0" x2="1" y1="0" y2="0"> {colors.map((c, i) => ( <stop key={i} offset={`${(i / Math.max(1, colors.length - 1)) * 100}%`} style={{ stopColor: c }} /> ))} </linearGradient> </defs> <path stroke={`url(#${gradientId})`} strokeLinecap="round" strokeLinejoin="round" /> </svg> ) : null} </div> );}export default LightWriting;