Decoding text scramble
A section head from Alert whose red word decodes out of width-matched cipher when you pick a chip and scrambles again under the pointer.
Build a React 19 + TypeScript component called TextScramble: a centred section head whose red word decodes out of cipher, changes when you pick one of four chips, and scrambles again under the pointer. Constraints - One .tsx file, "use client", imports from react only. CSS in a template string rendered as <style href="ui-text-scramble" precedence="ui">, every class prefixed "scr-". Default export; optional accent prop (default #ef3b2d). - The root fills its parent (relative, 100% x 100%, overflow hidden, isolation: isolate), paints #f9f9f9 and is an inline-size container; size things with container queries, never the window. - Fonts: var(--font-inter, Inter), system-ui, sans-serif; mono var(--font-mono, "JetBrains Mono"), ui-monospace, monospace. Layout (centred column, padding 40px 24px) - Badge: a 13px "One number" label with a 16px filled chat-bubble icon in the accent (padding 6px 10px, 1px #ececec bottom border), between "//" and "\\" in 11px mono #d0d0d0, 10px apart. - Title (h2): "Start <word> today", Inter 500, clamp(28px, 6.2cqi, 52px), line-height 1.08, letter-spacing -0.01em (-0.02em under 520px), text-wrap: balance, #262626, margin 22px 0 14px. The word is accent coloured and never wraps. - Sub: "One number to report problems, get answers" / "and get things done on campus.", 15.5px/1.55, #555. Drop the line break under 520px. - Chips, 28px below: a segmented control (rgba(0,0,0,.04), radius 10px, padding 3px) with Report, Fix, Ask, Urgent as 30px buttons, 13.5px, #8c8c8c (pressed #262626), padding 0 10px. Each starts with a 3x3 dot icon (3px squares, 2px gap, #cfcfcf; unlit dots 35% opacity), rows: Report 010111010, Fix 010111111, Ask 110101011, Urgent 101010101. The pressed chip's dots turn accent (unlit ones 38% accent on white) and pulse opacity 1 to 0.35 over 1.8s, staggered (column + row) x 90ms. 1 x 14px dividers between chips hide beside the pressed one. One white pill (radius 8px, hairline shadow) slides to the pressed chip over 0.35s cubic-bezier(.3,.7,.2,1), measured in a layout effect. Behaviour - The word starts as "texting" with Report pressed. Report, Fix, Ask and Urgent set it to reporting, fixing, asking and getting help. - Write the decode as a Scramble component: render each grapheme (Intl.Segmenter) as a span holding the real letter, plus a visually hidden copy for screen readers; the animated copy is aria-hidden. A scrambled letter gets -webkit-text-fill-color: transparent and an ::after with content: attr(data-g) centred over it at opacity var(--o). Cipher glyphs share the letter's case and sit within 12% of its canvas-measured width. - Timing: whole word 0.55s; S = min(0.45s, 60% of the total). Letter i starts at i / (n - 1) x (total - S), changes glyph 14 times a second and locks at start + S. Cipher opacity rises from 0.42 to 1 on p squared. The first word types in from blank; later words start fully scrambled. Begin when the text is half on screen. - Trail: on pointer move, letters within 0.6em of the pointer scramble again and stay in cipher for at least max(220ms, 0.7 x S). Touch: a tap scrambles where it lands, and touch-action: pan-y on the word lets a sideways drag trail. - Behind everything, a canvas of ASCII islands: 8px mono, #d4d4d4, 8fps, masked with radial-gradient(ellipse 46% 60% at center, transparent 40%, #000 85%). With value noise: blob = noise(9x + 0.02t, 6y); under 0.7 draw a rare dot, else noise(48x + 0.3t, 36y) > 0.56 gives 0.06 + (blob - 0.7) x 1.1. Map to " .:-=+*xX#" with slight jitter. Add 40 x the chip's index to t so each pick jumps the pattern. Good guest - Run the canvas only while on screen and the tab is visible, and pause the pulse with it. Cap DPR at 2; size from a ResizeObserver on the root. - prefers-reduced-motion: no decode or trail, one still frame, no pulse or pill transition. - Chips are buttons with aria-pressed in a role="group" labelled "What you're texting about", with a 2px accent focus ring.
"use client";
/*
* Decoding text scramble: the "How it works" section head from Alert (alert-bice.vercel.app).
*
* "Start texting today" types its red word in as cipher. Pick Report, Fix, Ask or Urgent and the word
* becomes reporting, fixing, asking or getting help, decoding out of scrambled glyphs. Run the mouse (or
* drag a finger) across it and the letters under the pointer re-encrypt, then decode again behind it. A faint
* field of ASCII dot islands drifts around the edges and jumps to a new pattern with each pick.
*
* How the decode works (the exported <Scramble>, usable on its own):
* - Every letter is rendered from the start as real text, so the line has its final shape before a glyph
* shows. A scrambled letter gets a transparent fill and a cipher glyph drawn over it as CSS generated
* content (::after { content: attr(data-g) }). Glyphs come from the same case as the letter and have an
* advance width within 12% of it (measured once per font on a canvas), so nothing around the word shifts,
* even in a proportional font.
* - The whole reveal takes `duration` seconds however long the text is. Each letter scrambles for `scramble`
* seconds (at most 60% of the total), changing glyph `rate` times a second, then locks. Cipher starts at
* `scrambleOpacity` and brightens on an ease-in curve as its letter locks.
* - Screen readers get the real text once from a visually hidden copy; the animated copy is aria-hidden.
* Because the cipher is generated content, copy and paste also get the real text.
*
* Usage:
* import TextScramble, { Scramble } from "./TextScramble";
*
* <div style={{ height: 440 }}><TextScramble /></div>
* <h1><Scramble text="Hello there" hover="trail" /></h1>
*
* Requirements: React 19 (for <style href precedence>), no other dependencies. TextScramble fills its parent,
* so give the parent a height. Fonts: Inter via --font-inter and JetBrains Mono via --font-mono if the page
* defines them, else the system fallbacks. With prefers-reduced-motion the text shows without decoding and
* the ASCII field holds still.
*/
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { CSSProperties, PointerEvent as ReactPointerEvent } from "react";
/* ------------------------------------------------------------------ scramble */
type Order = "left" | "right" | "center" | "random";
export type ScrambleProps = {
text: string;
/** External gate, on top of `trigger`. The reveal plays once both allow it. */
play?: boolean;
/** "view" waits until the text scrolls on screen; "mount" plays straight away. */
trigger?: "view" | "mount";
order?: Order;
/** "blank" types letters in as cipher; "scrambled" starts with the whole line in cipher. */
from?: "blank" | "scrambled";
/** Seconds for the whole line. Defaults to a length-based value between 0.6s and 1.4s. */
duration?: number;
/** Seconds each letter scrambles before it locks. */
scramble?: number;
/** Glyph changes per second while a letter is scrambled. */
rate?: number;
/** Opacity of cipher glyphs; they brighten to full as their letter locks. */
scrambleOpacity?: number;
/** "auto" matches case and width per letter. Any other string is used as-is. */
charset?: "auto" | (string & {});
/** "trail" re-encrypts the letters the pointer moves across, decoding them again behind it. */
hover?: "trail" | "none";
/** Reach of the hover trail, in em. */
hoverRadius?: number;
className?: string;
};
const coreCss = `
.scr-w{position:relative}
.scr-w[data-trail]{display:inline-block;touch-action:pan-y}
.scr-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;user-select:none}
.scr-c{position:relative}
.scr-c.scr-x{opacity:0}
.scr-c.scr-h{-webkit-text-fill-color:transparent}
.scr-c.scr-h::after{content:attr(data-g);content:attr(data-g) / "";position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);white-space:pre;-webkit-text-fill-color:currentColor;opacity:var(--o,.42);pointer-events:none}
@media (prefers-reduced-motion:no-preference){.scr-v[data-s=idle] .scr-c{opacity:0}}
`;
const SETS = { upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", lower: "abcdefghijklmnopqrstuvwxyz", digit: "0123456789" } as const;
type Kind = keyof typeof SETS;
const kindOf = (c: string): Kind | null => (/^[A-Z]$/.test(c) ? "upper" : /^[a-z]$/.test(c) ? "lower" : /^[0-9]$/.test(c) ? "digit" : null);
/* Glyph widths per font, measured once. Not cached until web fonts have loaded, or fallback metrics would stick. */
const widthCache = new Map<string, Map<string, number>>();
let measureCtx: CanvasRenderingContext2D | null | undefined;
function widths(font: string) {
const hit = widthCache.get(font);
if (hit) return hit;
if (measureCtx === undefined) measureCtx = document.createElement("canvas").getContext("2d");
const m = new Map<string, number>();
if (measureCtx) {
measureCtx.font = font;
for (const set of Object.values(SETS)) for (const g of set) m.set(g, measureCtx.measureText(g).width);
}
if (document.fonts?.status === "loaded") widthCache.set(font, m);
return m;
}
/** Same-case glyphs whose width is within 12% of `c` (at least the five closest), never `c` itself. */
function autoPool(c: string, k: Kind, w: Map<string, number>) {
const set = [...SETS[k]].filter((g) => g !== c);
const t = w.get(c);
if (!t) return set;
const ranked = set.map((g) => [g, Math.abs((w.get(g) ?? t) - t) / t] as const).sort((a, b) => a[1] - b[1]);
const close = ranked.filter(([, d]) => d <= 0.12);
return (close.length >= 5 ? close : ranked.slice(0, 5)).map(([g]) => g);
}
const segmenter = typeof Intl !== "undefined" && "Segmenter" in Intl ? new Intl.Segmenter(undefined, { granularity: "grapheme" }) : null;
const split = (s: string) => (segmenter ? Array.from(segmenter.segment(s), (x) => x.segment) : Array.from(s));
type Cell = {
el: HTMLSpanElement;
pool: string[] | null; // null: punctuation or emoji, shown as-is when its turn comes
blank: boolean; // invisible until `start` (from="blank")
s0: number; // when the current scramble began, for the brighten ramp
start: number;
lock: number;
tick: number;
phase: number;
state: "" | "x" | "h"; // "" decoded, "x" blank, "h" scrambling
o: string;
};
type Run = { cells: Cell[]; raf: number; kick: () => void; hold: number };
const reduced = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;
export function Scramble({
text, play = true, trigger = "view", order = "left", from = "blank", duration, scramble = 0.45, rate = 14,
scrambleOpacity = 0.42, charset = "auto", hover = "none", hoverRadius = 0.6, className,
}: ScrambleProps) {
const root = useRef<HTMLSpanElement>(null);
const vis = useRef<HTMLSpanElement>(null);
const [seen, setSeen] = useState(trigger === "mount");
const run = useRef<Run | null>(null);
// Letter centres relative to the root, measured on the first pointer event and again whenever the text changes.
const geo = useRef<{ run: Run; em: number; at: [number, number][] } | null>(null);
useEffect(() => {
if (seen) return;
const el = root.current;
if (!el) return;
const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold: 0.5 });
io.observe(el);
return () => io.disconnect();
}, [seen]);
const active = play && seen;
useEffect(() => {
const box = vis.current;
if (!box || !active) return;
if (reduced()) { box.dataset.s = "done"; return; }
const els = Array.from(box.querySelectorAll<HTMLSpanElement>(".scr-c"));
const cs = getComputedStyle(box);
const w = charset === "auto" ? widths(`${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`) : null;
const pools = new Map<string, string[]>();
const poolOf = (c: string) => {
const k = kindOf(c);
if (!k) return null;
if (charset !== "auto") return [...charset];
let p = pools.get(c);
if (!p) pools.set(c, (p = autoPool(c, k, w!)));
return p;
};
// Rank each letter by when it decodes, then spread the start times so the last one locks at `duration`.
const n = els.length;
const rank = els.map((_, i) => (order === "right" ? n - 1 - i : order === "center" ? Math.abs(i - (n - 1) / 2) : i));
if (order === "random") for (let i = n - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [rank[i], rank[j]] = [rank[j], rank[i]]; }
const top = Math.max(1, ...rank);
const D = (duration ?? Math.min(1.4, Math.max(0.6, 0.3 + n * 0.045))) * 1000;
const S = Math.min(scramble * 1000, D * 0.6);
const t0 = performance.now();
const cells: Cell[] = els.map((el, i) => {
const start = t0 + (rank[i] / top) * (D - S);
return {
el, pool: poolOf(el.textContent ?? ""), blank: from === "blank", s0: from === "blank" ? start : t0, start, lock: start + S,
tick: -1, phase: Math.random(), state: "" as const, o: "",
};
});
const set = (c: Cell, state: Cell["state"]) => { if (c.state !== state) { c.state = state; c.el.className = state ? `scr-c scr-${state}` : "scr-c"; } };
const frame = (now: number) => {
let busy = false;
for (const c of cells) {
if (now >= c.lock || (!c.pool && now >= c.start)) {
set(c, "");
continue;
}
busy = true;
if (now < c.start && c.blank) { set(c, "x"); continue; }
if (!c.pool) { set(c, "x"); continue; }
set(c, "h");
const tick = Math.floor(((now - c.s0) / 1000) * rate + c.phase);
if (tick !== c.tick) {
c.tick = tick;
const prev = c.el.dataset.g;
let g = c.pool[Math.floor(Math.random() * c.pool.length)];
if (g === prev && c.pool.length > 1) g = c.pool[(c.pool.indexOf(g) + 1) % c.pool.length];
c.el.dataset.g = g;
}
const p = Math.min(1, Math.max(0, (now - c.s0) / (c.lock - c.s0 || 1)));
const o = (scrambleOpacity + (1 - scrambleOpacity) * p * p).toFixed(2);
if (o !== c.o) { c.o = o; c.el.style.setProperty("--o", o); }
}
r.raf = busy ? requestAnimationFrame(frame) : 0;
};
const r: Run = {
cells, raf: 0, hold: Math.max(220, S * 0.7),
kick: () => { if (!r.raf) r.raf = requestAnimationFrame(frame); },
};
run.current = r;
box.dataset.s = "run";
frame(t0); // first frame now, so the idle state never shows for a frame
return () => { cancelAnimationFrame(r.raf); run.current = null; };
}, [text, active, order, from, duration, scramble, rate, scrambleOpacity, charset]);
const trail = hover === "trail";
// Re-encrypt every letter within `hoverRadius` em of the pointer and hold it in cipher a little longer.
const hit = (e: ReactPointerEvent<HTMLSpanElement>) => {
const r = run.current, el = root.current;
if (!r || !el) return;
const b = el.getBoundingClientRect();
let g = geo.current;
if (!g || g.run !== r) {
g = geo.current = {
run: r,
em: parseFloat(getComputedStyle(el).fontSize) || 16,
at: r.cells.map(({ el: c }) => { const q = c.getBoundingClientRect(); return [q.left - b.left + q.width / 2, q.top - b.top + q.height / 2]; }),
};
}
const x = e.clientX - b.left, y = e.clientY - b.top, R = hoverRadius * g.em, now = performance.now();
let any = false;
r.cells.forEach((c, i) => {
if (!c.pool) return;
const [cx, cy] = g.at[i];
if ((cx - x) ** 2 + (cy - y) ** 2 > R * R) return;
if (now >= c.lock) { c.s0 = now; c.start = now; c.tick = -1; }
c.blank = false;
c.lock = Math.max(c.lock, now + r.hold);
any = true;
});
if (any) r.kick();
};
const forget = () => { geo.current = null; };
return (
<span ref={root} className={`scr-w${className ? ` ${className}` : ""}`} data-trail={trail ? "" : undefined}
onPointerEnter={trail ? forget : undefined}
onPointerMove={trail ? hit : undefined}
// Touch and pen: a tap re-encrypts where it lands (measured fresh, the page may have scrolled), a sideways drag trails.
onPointerDown={trail ? (e) => { if (e.pointerType !== "mouse") { forget(); hit(e); } } : undefined}
onPointerLeave={trail ? forget : undefined}
onPointerCancel={trail ? forget : undefined}>
<style href="ui-text-scramble-core" precedence="ui">{coreCss}</style>
<span className="scr-sr">{text}</span>
<span key={text} ref={vis} className="scr-v" data-s="idle" aria-hidden="true">
{split(text).map((g, i) => (/^\s+$/.test(g) ? g : <span key={i} className="scr-c">{g}</span>))}
</span>
</span>
);
}
/* ---------------------------------------------------------------- ascii field */
// Small deterministic value noise, enough for organic ASCII shapes.
function hash(x: number, y: number) {
const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;
return s - Math.floor(s);
}
function noise(x: number, y: number) {
const xi = Math.floor(x), yi = Math.floor(y);
const xf = x - xi, yf = y - yi;
const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf);
const a = hash(xi, yi), b = hash(xi + 1, yi), c = hash(xi, yi + 1), d = hash(xi + 1, yi + 1);
return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
}
/** Sparse dotted islands scattered across the field. 0..1 coords + time to an intensity. */
function islands(x: number, y: number, t: number) {
const blob = noise(x * 9 + t * 0.02, y * 6);
if (blob < 0.7) return noise(x * 70, y * 50) > 0.985 ? 0.08 : 0;
return noise(x * 48 + t * 0.3, y * 36) > 0.56 ? 0.06 + (blob - 0.7) * 1.1 : 0;
}
const RAMP = " .:-=+*xX#";
const FIELD = { size: 8, fps: 8, color: "#d4d4d4" };
function drawField(ctx: CanvasRenderingContext2D, w: number, h: number, t: number, seed: number, font: string) {
ctx.clearRect(0, 0, w, h);
const cw = FIELD.size * 0.62, lh = FIELD.size * 1.12;
const cols = Math.floor(w / cw), rows = Math.floor(h / lh);
if (!cols || !rows) return;
ctx.font = font;
ctx.textBaseline = "top";
ctx.fillStyle = FIELD.color;
const step = Math.floor(t * FIELD.fps);
for (let r = 0; r < rows; r++) {
let line = "";
for (let c = 0; c < cols; c++) {
// Each seed is the same field 40 seconds further on, so a new seed jumps to a different pattern.
const v = islands(c / cols, r / rows, t + seed * 40);
if (v <= 0.04) { line += " "; continue; }
const jitter = noise(c * 1.7 + step * 0.37, r * 2.3) * 0.35;
line += RAMP[Math.min(RAMP.length - 1, Math.max(1, Math.floor((v + jitter - 0.1) * RAMP.length)))];
}
ctx.fillText(line, 0, r * lh);
}
}
/* ---------------------------------------------------------------- section head */
type Pick = "report" | "do" | "ask" | "urgent";
// Each pick's 3x3 dot icon, row by row ("1" is a lit dot).
const PICKS: { id: Pick; dots: string; title: string }[] = [
{ id: "report", dots: "010111010", title: "Report" },
{ id: "do", dots: "010111111", title: "Fix" },
{ id: "ask", dots: "110101011", title: "Ask" },
{ id: "urgent", dots: "101010101", title: "Urgent" },
];
const VERB: Record<Pick, string> = { report: "reporting", do: "fixing", ask: "asking", urgent: "getting help" };
/** 3x3 dot icon. The active one turns red and ripples. */
function Dots({ pattern, on }: { pattern: string; on: boolean }) {
return (
<span className={`scr-dots${on ? " scr-on" : ""}`} aria-hidden="true">
{pattern.split("").map((b, i) => <i key={i} className={b === "1" ? "scr-f" : undefined} style={{ animationDelay: `${((i % 3) + Math.floor(i / 3)) * 90}ms` }} />)}
</span>
);
}
const MONO = `var(--font-mono, "JetBrains Mono"), ui-monospace, monospace`;
const css = `
.scr{--scr-bg:#f9f9f9;--scr-ink:#262626;--scr-line:#ececec;--scr-ease:cubic-bezier(.3,.7,.2,1);
position:relative;width:100%;height:100%;overflow:hidden;isolation:isolate;container:scr/inline-size;
display:flex;align-items:center;justify-content:center;background:var(--scr-bg);color:var(--scr-ink);
font-family:var(--font-inter, Inter), system-ui, sans-serif;-webkit-font-smoothing:antialiased}
.scr *,.scr *::before,.scr *::after{box-sizing:border-box}
.scr-field{position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;font-family:${MONO};
-webkit-mask-image:radial-gradient(ellipse 46% 60% at center,transparent 40%,#000 85%);mask-image:radial-gradient(ellipse 46% 60% at center,transparent 40%,#000 85%)}
.scr-head{position:relative;display:flex;flex-direction:column;align-items:center;max-width:100%;padding:40px 24px;text-align:center}
.scr-badge{display:inline-flex;align-items:center;gap:10px;font-size:13px;line-height:1.2}
.scr-sl{font-family:${MONO};font-size:11px;color:#d0d0d0}
.scr-badge-in{display:inline-flex;align-items:center;gap:8px;padding:6px 10px;background:var(--scr-bg);border-bottom:1px solid var(--scr-line)}
.scr-badge-in svg{width:16px;height:16px;flex:none;color:var(--scr-accent)}
.scr-title{margin:22px 0 14px;font-size:44px;font-size:clamp(28px,6.2cqi,52px);line-height:1.08;font-weight:500;letter-spacing:-.01em;text-wrap:balance}
.scr-hot{color:var(--scr-accent);white-space:nowrap}
.scr-sub{margin:0;font-size:15.5px;line-height:1.55;color:#555}
.scr-tabs{position:relative;display:flex;align-items:center;margin-top:28px;padding:3px;border-radius:10px;background:rgba(0,0,0,.04)}
.scr-pill{position:absolute;top:3px;bottom:3px;left:0;border-radius:8px;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.08),0 0 0 .5px rgba(0,0,0,.05);transition:transform .35s var(--scr-ease),width .35s var(--scr-ease)}
.scr-tab-wrap{display:flex;align-items:center}
.scr-div{width:1px;height:14px;background:rgba(0,0,0,.1);transition:opacity .2s}
.scr-div.scr-hide{opacity:0}
.scr-tab{position:relative;z-index:1;display:flex;align-items:center;gap:7px;height:30px;margin:0;padding:0 10px;border:0;border-radius:8px;background:none;font:inherit;font-size:13.5px;color:#8c8c8c;white-space:nowrap;cursor:pointer;transition:color .2s;-webkit-tap-highlight-color:transparent}
.scr-tab:hover{color:#555}
.scr-tab[aria-pressed=true]{color:var(--scr-ink)}
.scr-tab:focus-visible{outline:2px solid var(--scr-accent);outline-offset:1px}
.scr-dots{display:inline-grid;grid-template-columns:repeat(3,3px);gap:2px;flex-shrink:0}
.scr-dots i{width:3px;height:3px;border-radius:.5px;background:#cfcfcf;opacity:.35}
.scr-dots i.scr-f{opacity:1}
.scr-dots.scr-on i{background:color-mix(in srgb,var(--scr-accent) 38%,#fff)}
.scr-dots.scr-on i.scr-f{background:var(--scr-accent);animation:scr-pulse 1.8s ease-in-out infinite}
.scr:not([data-live]) .scr-dots i{animation-play-state:paused}
@keyframes scr-pulse{0%,100%{opacity:1}50%{opacity:.35}}
@container scr (max-width:520px){
.scr-title{letter-spacing:-.02em}
.scr-sub{font-size:14.5px}
.scr-sub br{display:none}
}
@container scr (max-width:380px){
.scr-tab{gap:5px;padding:0 7px;font-size:12.5px}
}
@media (prefers-reduced-motion:reduce){
.scr-dots.scr-on i.scr-f{animation:none}
.scr-pill,.scr-tab,.scr-div{transition:none}
}
`;
export default function TextScramble({ accent = "#ef3b2d" }: { accent?: string }) {
const rootRef = useRef<HTMLDivElement>(null);
const fieldRef = useRef<HTMLCanvasElement>(null);
const tabsRef = useRef<HTMLDivElement>(null);
// The first card is picked but the word starts as "texting"; picking swaps it, as on the site.
const [pick, setPick] = useState<Pick>("report");
const [verb, setVerb] = useState("texting");
const [live, setLive] = useState(false);
const [pill, setPill] = useState<{ x: number; w: number } | null>(null);
const seed = PICKS.findIndex((p) => p.id === pick);
const seedRef = useRef(seed);
const repaint = useRef<() => void>(() => {});
const t0 = useRef(0);
const choose = (p: Pick) => { setPick(p); setVerb(VERB[p]); };
// One white pill slides to the picked chip.
useLayoutEffect(() => {
const wrap = tabsRef.current;
if (!wrap) return;
let alive = true;
const place = () => {
const b = wrap.querySelector<HTMLElement>(`[data-pick="${pick}"]`);
if (alive && b) setPill({ x: b.offsetLeft, w: b.offsetWidth });
};
place();
const ro = new ResizeObserver(place);
ro.observe(wrap);
document.fonts?.ready.then(place);
return () => { alive = false; ro.disconnect(); };
}, [pick]);
// Animate only while on screen and the tab is visible.
useEffect(() => {
const el = rootRef.current;
if (!el) return;
let inView = false;
const update = () => setLive(inView && document.visibilityState === "visible");
const io = new IntersectionObserver(([e]) => { inView = e.isIntersecting; update(); });
io.observe(el);
document.addEventListener("visibilitychange", update);
return () => { io.disconnect(); document.removeEventListener("visibilitychange", update); };
}, []);
// The ASCII field: a DPR-sized canvas redrawn `FIELD.fps` times a second. Reduced motion draws one frame.
useEffect(() => {
const el = rootRef.current, canvas = fieldRef.current;
const ctx = canvas?.getContext("2d");
if (!el || !canvas || !ctx) return;
if (!t0.current) t0.current = performance.now();
const still = reduced();
let w = 0, h = 0, raf = 0, last = 0, font = "", alive = true;
const size = () => {
const r = canvas.getBoundingClientRect(), dpr = Math.min(window.devicePixelRatio || 1, 2);
w = r.width; h = r.height;
canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
font = `${FIELD.size}px ${getComputedStyle(canvas).fontFamily}`;
};
const paint = () => drawField(ctx, w, h, (performance.now() - t0.current) / 1000, seedRef.current, font);
const loop = (now: number) => {
raf = requestAnimationFrame(loop);
if (now - last < 1000 / FIELD.fps) return;
last = now;
paint();
};
size();
paint();
repaint.current = paint;
const ro = new ResizeObserver(() => { size(); paint(); });
ro.observe(el);
document.fonts?.ready.then(() => { if (alive) { size(); paint(); } });
if (live && !still) raf = requestAnimationFrame(loop);
return () => { alive = false; cancelAnimationFrame(raf); ro.disconnect(); };
}, [live]);
// A new pick jumps the field to another pattern straight away.
useEffect(() => { seedRef.current = seed; repaint.current(); }, [seed]);
return (
<div ref={rootRef} className="scr" data-live={live ? "" : undefined} style={{ "--scr-accent": accent } as CSSProperties}>
<style href="ui-text-scramble" precedence="ui">{css}</style>
<canvas ref={fieldRef} className="scr-field" aria-hidden="true" />
<div className="scr-head">
<span className="scr-badge">
<span className="scr-sl">{"//"}</span>
<span className="scr-badge-in">
<svg viewBox="0 0 256 256" fill="currentColor" aria-hidden="true" focusable="false">
<path d="M128,24A104,104,0,0,0,36.18,176.88L24.83,210.93a16,16,0,0,0,20.24,20.24l34.05-11.35A104,104,0,1,0,128,24Zm32,128H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Zm0-32H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Z" />
</svg>
One number
</span>
<span className="scr-sl">{"\\\\"}</span>
</span>
<h2 className="scr-title">
Start <span className="scr-hot"><Scramble text={verb} from={verb === "texting" ? "blank" : "scrambled"} duration={0.55} hover="trail" /></span> today
</h2>
<p className="scr-sub">One number to report problems, get answers <br />and get things done on campus.</p>
<div ref={tabsRef} className="scr-tabs" role="group" aria-label="What you're texting about">
{pill && <span className="scr-pill" aria-hidden="true" style={{ transform: `translateX(${pill.x}px)`, width: pill.w }} />}
{PICKS.map((p, i) => (
<span key={p.id} className="scr-tab-wrap">
{i > 0 && <span className={`scr-div${pick === p.id || pick === PICKS[i - 1].id ? " scr-hide" : ""}`} aria-hidden="true" />}
<button type="button" className="scr-tab" data-pick={p.id} aria-pressed={pick === p.id} onClick={() => choose(p.id)}>
<Dots pattern={p.dots} on={pick === p.id} />
{p.title}
</button>
</span>
))}
</div>
</div>
</div>
);
}






