|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { HAMLET_ACT_1 } from "@/app/scatter/content"; |
| 4 | +import { layoutWithLines, prepareWithSegments } from "@chenglou/pretext"; |
| 5 | +import { type CSSProperties, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; |
| 6 | + |
| 7 | +const graphemeSegmenter = |
| 8 | + typeof Intl !== "undefined" && "Segmenter" in Intl |
| 9 | + ? new Intl.Segmenter(undefined, { granularity: "grapheme" }) |
| 10 | + : null; |
| 11 | + |
| 12 | +function splitGraphemes(text: string): string[] { |
| 13 | + if (!graphemeSegmenter) { |
| 14 | + return [...text]; |
| 15 | + } |
| 16 | + return [...graphemeSegmenter.segment(text)].map((s) => s.segment); |
| 17 | +} |
| 18 | + |
| 19 | +const INFLUENCE_RADIUS = 140; |
| 20 | +const PUSH_STRENGTH = 28; |
| 21 | +const EASE = 0.22; |
| 22 | + |
| 23 | +type LineLayout = { |
| 24 | + lines: { text: string }[]; |
| 25 | + lineHeightPx: number; |
| 26 | +}; |
| 27 | + |
| 28 | +function usePrefersReducedMotion(): boolean { |
| 29 | + const [reduced, setReduced] = useState(false); |
| 30 | + |
| 31 | + useEffect(() => { |
| 32 | + const mq = window.matchMedia("(prefers-reduced-motion: reduce)"); |
| 33 | + const update = () => setReduced(mq.matches); |
| 34 | + update(); |
| 35 | + mq.addEventListener("change", update); |
| 36 | + return () => mq.removeEventListener("change", update); |
| 37 | + }, []); |
| 38 | + |
| 39 | + return reduced; |
| 40 | +} |
| 41 | + |
| 42 | +export function ScatterText() { |
| 43 | + const measureRef = useRef<HTMLDivElement>(null); |
| 44 | + const rootRef = useRef<HTMLDivElement>(null); |
| 45 | + const [layout, setLayout] = useState<LineLayout | null>(null); |
| 46 | + const reducedMotion = usePrefersReducedMotion(); |
| 47 | + |
| 48 | + const restCentersRef = useRef<{ x: number; y: number }[]>([]); |
| 49 | + const curRef = useRef<{ x: number; y: number }[]>([]); |
| 50 | + const mouseRef = useRef<{ x: number; y: number; active: boolean }>({ x: 0, y: 0, active: false }); |
| 51 | + const rafRef = useRef(0); |
| 52 | + |
| 53 | + const lineGraphemes = useMemo(() => { |
| 54 | + if (!layout) return null; |
| 55 | + return layout.lines.map((line) => { |
| 56 | + const raw = line.text || "\u00a0"; |
| 57 | + const parts = splitGraphemes(raw); |
| 58 | + return parts.length > 0 ? parts : ["\u00a0"]; |
| 59 | + }); |
| 60 | + }, [layout]); |
| 61 | + |
| 62 | + const captureRestPositions = useCallback(() => { |
| 63 | + const root = rootRef.current; |
| 64 | + if (!root) return; |
| 65 | + |
| 66 | + const spans = root.querySelectorAll<HTMLElement>("[data-scatter-glyph]"); |
| 67 | + const n = spans.length; |
| 68 | + if (n === 0) return; |
| 69 | + |
| 70 | + for (let i = 0; i < n; i++) { |
| 71 | + spans[i].style.transform = "translate(0px, 0px)"; |
| 72 | + } |
| 73 | + void root.offsetHeight; |
| 74 | + |
| 75 | + const next: { x: number; y: number }[] = []; |
| 76 | + for (let i = 0; i < n; i++) { |
| 77 | + const r = spans[i].getBoundingClientRect(); |
| 78 | + next.push({ x: r.left + r.width / 2, y: r.top + r.height / 2 }); |
| 79 | + } |
| 80 | + restCentersRef.current = next; |
| 81 | + curRef.current = Array.from({ length: n }, () => ({ x: 0, y: 0 })); |
| 82 | + }, []); |
| 83 | + |
| 84 | + useLayoutEffect(() => { |
| 85 | + const el = measureRef.current; |
| 86 | + if (!el) return; |
| 87 | + |
| 88 | + function measure() { |
| 89 | + const node = measureRef.current; |
| 90 | + if (!node) return; |
| 91 | + const width = node.clientWidth; |
| 92 | + if (width <= 0) return; |
| 93 | + |
| 94 | + const cs = getComputedStyle(node); |
| 95 | + const font = cs.font; |
| 96 | + const fontSize = parseFloat(cs.fontSize) || 16; |
| 97 | + const parsedLineHeight = parseFloat(cs.lineHeight); |
| 98 | + const lineHeightPx = |
| 99 | + Number.isFinite(parsedLineHeight) && !cs.lineHeight.includes("%") ? parsedLineHeight : fontSize * 1.45; |
| 100 | + |
| 101 | + const prepared = prepareWithSegments(HAMLET_ACT_1, font, { whiteSpace: "pre-wrap" }); |
| 102 | + const { lines } = layoutWithLines(prepared, width, lineHeightPx); |
| 103 | + setLayout({ lines, lineHeightPx }); |
| 104 | + } |
| 105 | + |
| 106 | + measure(); |
| 107 | + const ro = new ResizeObserver(measure); |
| 108 | + ro.observe(el); |
| 109 | + return () => ro.disconnect(); |
| 110 | + }, []); |
| 111 | + |
| 112 | + useLayoutEffect(() => { |
| 113 | + if (!layout || reducedMotion) return; |
| 114 | + captureRestPositions(); |
| 115 | + }, [layout, reducedMotion, captureRestPositions]); |
| 116 | + |
| 117 | + useEffect(() => { |
| 118 | + if (!layout || reducedMotion) return; |
| 119 | + |
| 120 | + const onScroll = () => { |
| 121 | + captureRestPositions(); |
| 122 | + }; |
| 123 | + |
| 124 | + window.addEventListener("scroll", onScroll, true); |
| 125 | + window.addEventListener("resize", captureRestPositions); |
| 126 | + return () => { |
| 127 | + window.removeEventListener("scroll", onScroll, true); |
| 128 | + window.removeEventListener("resize", captureRestPositions); |
| 129 | + }; |
| 130 | + }, [layout, reducedMotion, captureRestPositions]); |
| 131 | + |
| 132 | + useEffect(() => { |
| 133 | + if (!layout || reducedMotion) return; |
| 134 | + |
| 135 | + function tick() { |
| 136 | + const root = rootRef.current; |
| 137 | + if (!root) { |
| 138 | + rafRef.current = requestAnimationFrame(tick); |
| 139 | + return; |
| 140 | + } |
| 141 | + |
| 142 | + const spans = root.querySelectorAll<HTMLElement>("[data-scatter-glyph]"); |
| 143 | + const n = spans.length; |
| 144 | + const centers = restCentersRef.current; |
| 145 | + const cur = curRef.current; |
| 146 | + const { x: mx, y: my, active } = mouseRef.current; |
| 147 | + |
| 148 | + while (cur.length < n) { |
| 149 | + cur.push({ x: 0, y: 0 }); |
| 150 | + } |
| 151 | + |
| 152 | + for (let i = 0; i < n; i++) { |
| 153 | + const c = centers[i]; |
| 154 | + let tx = 0; |
| 155 | + let ty = 0; |
| 156 | + if (active && c) { |
| 157 | + const dx = c.x - mx; |
| 158 | + const dy = c.y - my; |
| 159 | + const d = Math.hypot(dx, dy); |
| 160 | + if (d > 0.5) { |
| 161 | + const influence = Math.max(0, 1 - d / INFLUENCE_RADIUS); |
| 162 | + const f = influence * PUSH_STRENGTH; |
| 163 | + tx = (dx / d) * f; |
| 164 | + ty = (dy / d) * f; |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + const p = cur[i] ?? { x: 0, y: 0 }; |
| 169 | + p.x += (tx - p.x) * EASE; |
| 170 | + p.y += (ty - p.y) * EASE; |
| 171 | + cur[i] = p; |
| 172 | + |
| 173 | + spans[i].style.transform = `translate(${p.x.toFixed(2)}px, ${p.y.toFixed(2)}px)`; |
| 174 | + } |
| 175 | + |
| 176 | + rafRef.current = requestAnimationFrame(tick); |
| 177 | + } |
| 178 | + |
| 179 | + rafRef.current = requestAnimationFrame(tick); |
| 180 | + return () => cancelAnimationFrame(rafRef.current); |
| 181 | + }, [layout, reducedMotion]); |
| 182 | + |
| 183 | + const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => { |
| 184 | + if (reducedMotion) return; |
| 185 | + mouseRef.current = { x: e.clientX, y: e.clientY, active: true }; |
| 186 | + }; |
| 187 | + |
| 188 | + const onPointerLeave = () => { |
| 189 | + mouseRef.current = { ...mouseRef.current, active: false }; |
| 190 | + }; |
| 191 | + |
| 192 | + return ( |
| 193 | + <div className="w-full min-w-0"> |
| 194 | + <p className="sr-only">{HAMLET_ACT_1}</p> |
| 195 | + <div |
| 196 | + ref={measureRef} |
| 197 | + className="font-sans text-lg leading-relaxed text-foreground invisible h-0 w-full overflow-hidden pointer-events-none" |
| 198 | + aria-hidden |
| 199 | + > |
| 200 | + |
| 201 | + </div> |
| 202 | + <div |
| 203 | + ref={rootRef} |
| 204 | + className="whitespace-pre-wrap font-sans text-lg leading-relaxed text-foreground select-none" |
| 205 | + onPointerMove={onPointerMove} |
| 206 | + onPointerLeave={onPointerLeave} |
| 207 | + aria-hidden |
| 208 | + > |
| 209 | + {layout?.lines.map((_, lineIndex) => { |
| 210 | + const glyphs = lineGraphemes?.[lineIndex] ?? ["\u00a0"]; |
| 211 | + return ( |
| 212 | + <div |
| 213 | + key={lineIndex} |
| 214 | + className="flex w-full flex-nowrap items-baseline" |
| 215 | + style={{ minHeight: layout.lineHeightPx } as CSSProperties} |
| 216 | + > |
| 217 | + {glyphs.map((g, j) => ( |
| 218 | + <span |
| 219 | + key={`${lineIndex}-${j}`} |
| 220 | + data-scatter-glyph |
| 221 | + className="inline-block shrink-0 will-change-transform" |
| 222 | + style={reducedMotion ? { transform: "none" } : undefined} |
| 223 | + > |
| 224 | + {g} |
| 225 | + </span> |
| 226 | + ))} |
| 227 | + </div> |
| 228 | + ); |
| 229 | + })} |
| 230 | + </div> |
| 231 | + </div> |
| 232 | + ); |
| 233 | +} |
0 commit comments