From 29fa866902a44789f7933d2f2a1565f15bfb874f Mon Sep 17 00:00:00 2001 From: Marius Maaland Date: Wed, 7 Oct 2026 20:06:18 +0200 Subject: [PATCH] Draw the probe field and scan band with WebGPU (#54) A small renderer of our own (one WGSL fragment shader, ~2 KB gzipped) draws the home page's dot field, with a lens of signal dots following the cursor, and the running scan's dot strip, with a signal band sweeping across. Each effect renders its CSS version first and loads the renderer lazily, only with WebGPU, no reduced motion, no data saving, and for the lens a mouse. If the GPU can't start or goes away, the CSS version stays. Colours come from the theme tokens and follow light/dark. Finished reports don't load it. We tried the shaders package first; it bundles all ~200 of its effects (~720 KB gzipped) and reports visitors' user agents by default, so the ui-shaders skill now describes our renderer instead. Closes #54 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/ui-shaders/SKILL.md | 103 ++++---- apps/web/package.json | 3 +- apps/web/src/app/effects/dot-canvas.tsx | 56 +++++ apps/web/src/app/effects/dot-field.test.ts | 43 ++++ apps/web/src/app/effects/dot-field.ts | 235 ++++++++++++++++++ apps/web/src/app/effects/effects.test.tsx | 17 ++ apps/web/src/app/effects/gate.ts | 90 +++++++ apps/web/src/app/effects/probe-field.tsx | 45 ++++ apps/web/src/app/effects/scan-band.tsx | 44 ++++ apps/web/src/app/globals.css | 59 ++++- apps/web/src/app/page.tsx | 6 +- .../app/s/[domain]/report-sections.test.tsx | 1 + .../src/app/s/[domain]/report-sections.tsx | 2 + pnpm-lock.yaml | 8 + 14 files changed, 657 insertions(+), 55 deletions(-) create mode 100644 apps/web/src/app/effects/dot-canvas.tsx create mode 100644 apps/web/src/app/effects/dot-field.test.ts create mode 100644 apps/web/src/app/effects/dot-field.ts create mode 100644 apps/web/src/app/effects/effects.test.tsx create mode 100644 apps/web/src/app/effects/gate.ts create mode 100644 apps/web/src/app/effects/probe-field.tsx create mode 100644 apps/web/src/app/effects/scan-band.tsx diff --git a/.claude/skills/ui-shaders/SKILL.md b/.claude/skills/ui-shaders/SKILL.md index aede1fd..5bdefbf 100644 --- a/.claude/skills/ui-shaders/SKILL.md +++ b/.claude/skills/ui-shaders/SKILL.md @@ -1,6 +1,6 @@ --- name: ui-shaders -description: When and how stackprobe's web app may use GPU shader effects (the MIT `shaders` package, WebGPU) — the two allowed places, fallbacks, performance and colour rules. Load before adding or changing any shader, canvas animation or animated background in apps/web. +description: When and how stackprobe's web app may use GPU effects (our own small WebGPU dot-field renderer) — the two allowed places, fallbacks, performance, colour rules and how to check them. Load before adding or changing any shader, canvas animation or animated background in apps/web. --- # Shaders in stackprobe @@ -14,63 +14,72 @@ everything here uses its tokens. Only these two. Anything else needs the user's approval first, and an update to this file. 1. **Probe field**, behind the home headline. A still dot grid in `--dot`. Dots near the cursor - light up in `--signal`, like a lens passing over the page. On touch devices the lens drifts - slowly by itself. It fades out to the left so the headline stays readable. + light up in `--signal`, like a lens passing over the page. Only with a mouse: on touch + devices the static version shows. It fades out to the left so the headline stays readable. 2. **Scan band**, on the running-scan page. A strip of `--dot` dots with a `--signal` band sweeping across while the scan runs. It disappears when the report replaces the running state. Never on: the report, tables, evidence, buttons, text, OG images or email. No shader carries information; it's atmosphere around the information. -## The package - -[`shaders`](https://github.com/shader-effects-inc/shaders) (npm `shaders`, MIT). The engine and -components are free; presets, the online editor and `npx shaders install ` are Pro. We -don't use Pro, and we don't run `npx shaders connect` (it signs in and writes a config): compose -by hand from the free components. - -- Component API and props: the upstream skill (`npx skills add shader-effects-inc/shaders`, or - read https://github.com/shader-effects-inc/shaders/blob/main/skills/shaders/SKILL.md) and the - full prop reference at https://shaders.com/llms-full.txt. Check props there; don't guess. -- React import: `shaders/react`. `` renders one ``; children are layers, first at - the bottom. Size it with CSS on ``, never on the inner canvas. -- Useful parts for us: `DotGrid` (`color`, `density`, `dotSize`, `speed`), `Circle` with - `center={{ type: 'mouse-position', smoothing, momentum }}` as a mask (`id` + `visible={false}` - on the mask, `maskSource` on the masked layer), and `auto-animate` props for the band. -- Colour props take hex strings, but our tokens are oklch CSS variables. Resolve the token at - runtime (read `getComputedStyle` of an element that uses it and convert to hex through a 1×1 - canvas), and re-resolve when `prefers-color-scheme` changes. Never hard-code a colour. +## The renderer + +Both effects use our own renderer in `apps/web/src/app/effects/`, not a library: + +- `dot-field.ts`: one WGSL fragment shader (dot grid + lens or band) and the loop around it. + ~2 KB gzipped. Motion maths (`bandCenter`, `follow`) are pure and unit-tested. +- `dot-canvas.tsx`: the canvas component; starts the renderer, reports ready or unavailable. +- `gate.ts`: `useShaderAllowed` (may it run here?) and `useTokenColors` (theme colours as hex). +- `probe-field.tsx`, `scan-band.tsx`: the effects. Each renders its CSS version, and lazily + loads `dot-canvas.tsx` over it once allowed. Their `SHAPE` constants match the CSS version. + +We tried the `shaders` package (shader-effects-inc, MIT) first. Its engine imports all ~200 of +its effects, so any use adds ~720 KB gzipped, and it sends visitors' user agents to its +servers unless told not to. Don't bring it, or any other effect library, back without asking. + +To add an effect, extend `dot-field.ts` (a new `kind`), not a new renderer. Keep the shader +one pass, no textures, no extra buffers. ## Rules -1. **Client only, lazy, and only where used.** The component file starts with `'use client'` and - is loaded with `next/dynamic` (`ssr: false`) from the home and running-scan views only. The - report page must not ship the `shaders` package; check the build output. +1. **Client only, lazy, and only where used.** Effects are client components; the renderer is + loaded with `next/dynamic` (`ssr: false`) only after the gate passes. A finished report must + not load it (check in a production build: the dev server preloads lazy chunks). 2. **Static first.** The server renders the CSS version (a `radial-gradient` dot grid in `--dot`, - plus a static `--signal` lens or band). The shader mounts on top of the same box at the same - size once ready, so nothing shifts. If it never loads, the page looks finished anyway. -3. **Fallbacks.** The package has no built-in fallback. Keep the static version, and don't - mount the shader, when: - - `!('gpu' in navigator)`, or `navigator.gpu.requestAdapter()` returns `null`; - - `prefers-reduced-motion: reduce` matches (listen for changes); - - the device saves data (`navigator.connection?.saveData`). -4. **Pause when unseen.** Stop rendering when the box is off screen (`IntersectionObserver`) or - the tab is hidden (`visibilitychange`), and unmount the probe field when a scan starts. -5. **Cheap.** One `` per page; three layers at most; no blur, glass, 3D, particles or - post-processing. Keep the dot density close to the CSS version (one dot every 16 px on home, - 8 px in the band). Cap the drawing buffer at 2× device pixels. -6. **Quiet.** Signal appears only in the lens or band, never as a fill or glow. Movement is slow: - the lens follows with smoothing ≥ 0.1; the band takes ~2.4 s per sweep with `--ease-in-out`. - No twinkle, no colour cycling. -7. **Decorative.** The box is `aria-hidden="true"` and never takes focus or pointer events away - from the content above it (`pointer-events: none` on the overlay; track the cursor on the - section instead). + plus a static `--signal` lens or band). The canvas sits on top of the same box, transparent + until its first frame, then fades in over `--dur-considered`. If it never loads, the page + looks finished anyway. +3. **Fallbacks.** `useShaderAllowed` keeps the static version, and the canvas unmounted, when: + - there's no `navigator.gpu`, or `requestAdapter()` returns `null`; + - `prefers-reduced-motion: reduce` matches (it listens for changes); + - the device saves data (`navigator.connection?.saveData`); + - for the probe field, there's no mouse (`(hover: hover) and (pointer: fine)`). + If the renderer can't start or the GPU device is lost, `onUnavailable` removes the canvas. +4. **Pause when unseen.** The renderer stops its frame loop off screen (IntersectionObserver); + browsers stop animation frames in hidden tabs. The lens only draws while catching up with + the cursor. +5. **Cheap.** One canvas per page, one draw call per frame. Drawing buffer capped at 2× device + pixels. Dot spacing matches the CSS version: 16 px on home, 8 px in the band. +6. **Colours from tokens.** `useTokenColors` resolves the oklch tokens to hex and follows + light/dark changes; the shader writes them as-is, so they match the CSS. The canvas is opaque, + drawn in the colour behind it (`ground`: `--page` on home, `--surface` in the band). +7. **Quiet.** Signal appears only in the lens or band, never as a fill or glow. The lens follows + with lag; the band takes `SWEEP_MS` (2.4 s) each way, easing in and out. No twinkle, no + colour cycling. +8. **Decorative.** The box is `aria-hidden="true"`; the canvas has `pointer-events: none` and the + renderer reads the cursor from `window`. ## Checking your work -- Run the page in a WebGPU browser and in one without (Firefox on macOS, or Chrome with - `--disable-features=WebGPU`): both look finished. -- Turn on reduced motion: nothing moves. -- Switch the system between light and dark with the page open: the dots change colour. -- `pnpm build` and confirm the report route's JavaScript didn't grow. +Headless Chromium can draw WebGPU on macOS: launch with `--enable-unsafe-webgpu +--use-angle=metal --enable-gpu --ignore-gpu-blocklist`, against a page on `localhost` (WebGPU +needs a secure context). Plain headless has no adapter, which tests the fallback; SwiftShader +(`--use-webgpu-adapter=swiftshader`) loses the device, which tests `onUnavailable`. + +- Screenshot each effect with WebGPU, in light and dark: both look like the CSS version, with + the lens or band in clear signal green. Move the mouse in steps for the lens; take two + frames a second apart for the band. +- Without WebGPU and with reduced motion: the static version, nothing moves. +- In a production build (`next build && next start`): a finished report doesn't fetch the + renderer chunk; the home and running pages do, and nothing goes to another host. - Then run the `ui-review` skill. diff --git a/apps/web/package.json b/apps/web/package.json index aeadc6e..e7da46c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -13,7 +13,8 @@ }, "devDependencies": { "@types/react": "^19.3.0", - "@types/react-dom": "^19.3.0" + "@types/react-dom": "^19.3.0", + "@webgpu/types": "^0.1.74" }, "dependencies": { "@drippa/stackprobe-browser-playwright": "workspace:*", diff --git a/apps/web/src/app/effects/dot-canvas.tsx b/apps/web/src/app/effects/dot-canvas.tsx new file mode 100644 index 0000000..0c816e3 --- /dev/null +++ b/apps/web/src/app/effects/dot-canvas.tsx @@ -0,0 +1,56 @@ +'use client'; + +import { useEffect, useRef } from 'react'; +import { + type DotField, + type DotFieldColors, + type DotFieldShape, + startDotField, +} from './dot-field.ts'; + +// The canvas over an effect's CSS version. Calls onReady once the first frame is drawn, and +// onUnavailable if WebGPU can't start or the GPU goes away, so the CSS version stays. +export default function DotCanvas({ + shape, + colors, + onReady, + onUnavailable, +}: { + shape: DotFieldShape; + colors: DotFieldColors; + onReady: () => void; + onUnavailable: () => void; +}) { + const canvas = useRef(null); + const field = useRef(null); + // The latest values, read by the one-time start below without restarting it. + const latest = useRef({ shape, colors, onReady, onUnavailable }); + latest.current = { shape, colors, onReady, onUnavailable }; + + useEffect(() => { + const element = canvas.current; + if (!element) return; + let cancelled = false; + const { shape, colors } = latest.current; + startDotField(element, shape, colors, () => latest.current.onUnavailable()).then( + (started) => { + if (cancelled) return started?.destroy(); + if (!started) return latest.current.onUnavailable(); + field.current = started; + requestAnimationFrame(() => latest.current.onReady()); + }, + () => latest.current.onUnavailable(), + ); + return () => { + cancelled = true; + field.current?.destroy(); + field.current = null; + }; + }, []); + + useEffect(() => { + field.current?.setColors(colors); + }, [colors]); + + return ; +} diff --git a/apps/web/src/app/effects/dot-field.test.ts b/apps/web/src/app/effects/dot-field.test.ts new file mode 100644 index 0000000..2ddb186 --- /dev/null +++ b/apps/web/src/app/effects/dot-field.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from 'vitest'; +import { bandCenter, follow, hexToRgb, SWEEP_MS } from './dot-field.ts'; + +test('hexToRgb reads token colours for the shader', () => { + expect(hexToRgb('#1fa836')).toEqual([31 / 255, 168 / 255, 54 / 255]); + expect(hexToRgb('#000000')).toEqual([0, 0, 0]); +}); + +describe('bandCenter', () => { + const width = 1000; + const half = 100; + + test('starts fully off the left edge and reaches fully off the right after one sweep', () => { + expect(bandCenter(0, width, half)).toBe(-half); + expect(bandCenter(SWEEP_MS, width, half)).toBeCloseTo(width + half); + }); + + test('comes back the same way, and repeats', () => { + expect(bandCenter(2 * SWEEP_MS, width, half)).toBeCloseTo(-half); + expect(bandCenter(SWEEP_MS / 2, width, half)).toBeCloseTo(width / 2); + expect(bandCenter(1.5 * SWEEP_MS, width, half)).toBeCloseTo(width / 2); + expect(bandCenter(2.25 * SWEEP_MS, width, half)).toBeCloseTo( + bandCenter(0.25 * SWEEP_MS, width, half), + ); + }); + + test('eases: slow at the ends, fastest in the middle', () => { + const step = SWEEP_MS / 20; + const atEnd = bandCenter(step, width, half) - bandCenter(0, width, half); + const inMiddle = + bandCenter(SWEEP_MS / 2 + step / 2, width, half) - + bandCenter(SWEEP_MS / 2 - step / 2, width, half); + expect(inMiddle).toBeGreaterThan(5 * atEnd); + }); +}); + +test('follow moves the lens the same distance at any frame rate', () => { + const at60 = follow(follow(0, 100, 1000 / 60), 100, 1000 / 60); + const at30 = follow(0, 100, 1000 / 30); + expect(at30).toBeCloseTo(at60); + expect(follow(0, 100, 1000 / 60)).toBeCloseTo(12); + expect(follow(100, 100, 16)).toBe(100); +}); diff --git a/apps/web/src/app/effects/dot-field.ts b/apps/web/src/app/effects/dot-field.ts new file mode 100644 index 0000000..8e248b7 --- /dev/null +++ b/apps/web/src/app/effects/dot-field.ts @@ -0,0 +1,235 @@ +/// +// A dot grid drawn with WebGPU, with dots turning signal-coloured inside a soft lens (following +// the cursor) or a band (sweeping across). One full-screen fragment shader, no dependencies. +// Rules for where and how it's used: .claude/skills/ui-shaders/SKILL.md. + +export interface DotFieldColors { + ground: string; // what's behind the dots, so the canvas can be opaque + dot: string; + signal: string; +} + +export interface DotFieldShape { + kind: 'lens' | 'band'; + spacing: number; // CSS px between dots, matching the CSS version + dotRadius: number; // CSS px + signalRadius: number; // CSS px, for dots inside the lens or band + radius: number; // lens radius, or band half-width, in CSS px + softness: number; // 0–1: how much of the radius is a fade + rest: { x: number; y: number }; // where the lens sits before the cursor moves, 0–1 of the box +} + +export interface DotField { + setColors(colors: DotFieldColors): void; + destroy(): void; +} + +// The band eases from one end to the other and back, this long each way. +export const SWEEP_MS = 2400; +// The lens closes this fraction of the gap to the cursor every 1/60 s. +const FOLLOW = 0.12; +// Drawing buffer cap, in device pixels per CSS pixel. +const MAX_DPR = 2; + +const SHADER = /* wgsl */ ` +struct U { + dpr: f32, spacing: f32, dotR: f32, sigR: f32, + mode: f32, radius: f32, softness: f32, _pad: f32, + center: vec2f, _pad2: vec2f, + ground: vec4f, dot: vec4f, signal: vec4f, +} +@group(0) @binding(0) var u: U; + +@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f { + var p = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(p[i], 0.0, 1.0); +} + +@fragment fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f { + let css = pos.xy / u.dpr; + let cell = css - u.spacing * floor(css / u.spacing) - vec2f(u.spacing * 0.5); + var dist: f32; + if (u.mode < 0.5) { dist = length(css - u.center); } else { dist = abs(css.x - u.center.x); } + let w = 1.0 - smoothstep(u.radius * (1.0 - u.softness), u.radius, dist); + let r = mix(u.dotR, u.sigR, w); + let edge = 0.6 / u.dpr + 0.3; + let a = 1.0 - smoothstep(r - edge, r + edge, length(cell)); + let c = mix(u.dot.rgb, u.signal.rgb, w); + return vec4f(mix(u.ground.rgb, c, a), 1.0); +} +`; + +// '#1fa836' → [r, g, b] in 0–1. Shader output is written as-is, so colours match the CSS ones. +export function hexToRgb(hex: string): [number, number, number] { + const n = Number.parseInt(hex.replace('#', ''), 16); + return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; +} + +// The band's centre at time t: from fully off the left edge to fully off the right and back, +// easing in and out like cubic-bezier(0.65, 0, 0.35, 1) does. +export function bandCenter(t: number, width: number, halfWidth: number): number { + const phase = (t / SWEEP_MS) % 2; + const leg = phase < 1 ? phase : 2 - phase; + const eased = 0.5 - 0.5 * Math.cos(Math.PI * leg); + return -halfWidth + eased * (width + 2 * halfWidth); +} + +// One step of the lens towards its target, the same at any frame rate. +export function follow(current: number, target: number, ms: number): number { + return target + (current - target) * (1 - FOLLOW) ** (ms / (1000 / 60)); +} + +// Starts drawing into the canvas. Resolves null when WebGPU can't be used; onLost is called if +// the GPU goes away later, and the caller should fall back to the CSS version. +export async function startDotField( + canvas: HTMLCanvasElement, + shape: DotFieldShape, + initial: DotFieldColors, + onLost: () => void, +): Promise { + const gpu = 'gpu' in navigator ? navigator.gpu : undefined; + const adapter = await gpu?.requestAdapter().catch(() => null); + const device = await adapter?.requestDevice().catch(() => null); + const context = canvas.getContext('webgpu'); + if (!gpu || !device || !context) return null; + + const format = gpu.getPreferredCanvasFormat(); + context.configure({ device, format, alphaMode: 'opaque' }); + const pipeline = device.createRenderPipeline({ + layout: 'auto', + vertex: { module: device.createShaderModule({ code: SHADER }), entryPoint: 'vs' }, + fragment: { + module: device.createShaderModule({ code: SHADER }), + entryPoint: 'fs', + targets: [{ format }], + }, + primitive: { topology: 'triangle-list' }, + }); + const uniforms = new Float32Array(24); + const buffer = device.createBuffer({ + size: uniforms.byteLength, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + const bindGroup = device.createBindGroup({ + layout: pipeline.getBindGroupLayout(0), + entries: [{ binding: 0, resource: { buffer } }], + }); + + let colors = initial; + let width = 0; + let height = 0; + let dpr = 1; + let visible = true; + let destroyed = false; + let frame = 0; + let last = performance.now(); + const start = last; + const lens = { x: 0, y: 0, tx: 0, ty: 0, placed: false }; + + const draw = () => { + if (width === 0 || height === 0) return; + uniforms.set([dpr, shape.spacing, shape.dotRadius, shape.signalRadius]); + uniforms.set([shape.kind === 'lens' ? 0 : 1, shape.radius, shape.softness, 0], 4); + uniforms.set([lens.x, lens.y, 0, 0], 8); + uniforms.set([...hexToRgb(colors.ground), 1], 12); + uniforms.set([...hexToRgb(colors.dot), 1], 16); + uniforms.set([...hexToRgb(colors.signal), 1], 20); + device.queue.writeBuffer(buffer, 0, uniforms); + const encoder = device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { view: context.getCurrentTexture().createView(), loadOp: 'clear', storeOp: 'store' }, + ], + }); + pass.setPipeline(pipeline); + pass.setBindGroup(0, bindGroup); + pass.draw(3); + pass.end(); + device.queue.submit([encoder.finish()]); + }; + + // The band always moves; the lens only draws while it's catching up with the cursor. + const tick = (now: number) => { + frame = 0; + if (destroyed || !visible) return; + const ms = Math.min(now - last, 100); + last = now; + let moving = shape.kind === 'band'; + if (shape.kind === 'band') { + lens.x = bandCenter(now - start, width, shape.radius); + } else { + lens.x = follow(lens.x, lens.tx, ms); + lens.y = follow(lens.y, lens.ty, ms); + moving = Math.abs(lens.x - lens.tx) + Math.abs(lens.y - lens.ty) > 0.25; + } + draw(); + if (moving) schedule(); + }; + const schedule = () => { + if (!frame && !destroyed && visible) frame = requestAnimationFrame(tick); + }; + + const rest = () => { + lens.tx = shape.rest.x * width; + lens.ty = shape.rest.y * height; + if (!lens.placed) { + lens.x = lens.tx; + lens.y = lens.ty; + lens.placed = true; + } + }; + const resize = new ResizeObserver(([entry]) => { + width = entry?.contentRect.width ?? 0; + height = entry?.contentRect.height ?? 0; + dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR); + canvas.width = Math.max(1, Math.round(width * dpr)); + canvas.height = Math.max(1, Math.round(height * dpr)); + rest(); + draw(); + schedule(); + }); + resize.observe(canvas); + const seen = new IntersectionObserver(([entry]) => { + visible = entry?.isIntersecting ?? true; + last = performance.now(); + schedule(); + }); + seen.observe(canvas); + + const onMove = (e: PointerEvent) => { + if (e.pointerType !== 'mouse') return; + const box = canvas.getBoundingClientRect(); + lens.tx = e.clientX - box.left; + lens.ty = e.clientY - box.top; + schedule(); + }; + const onLeave = () => { + rest(); + schedule(); + }; + if (shape.kind === 'lens') { + window.addEventListener('pointermove', onMove, { passive: true }); + document.documentElement.addEventListener('pointerleave', onLeave); + } + + device.lost.then(() => { + if (!destroyed) onLost(); + }); + + return { + setColors(next) { + colors = next; + draw(); + }, + destroy() { + destroyed = true; + if (frame) cancelAnimationFrame(frame); + resize.disconnect(); + seen.disconnect(); + window.removeEventListener('pointermove', onMove); + document.documentElement.removeEventListener('pointerleave', onLeave); + buffer.destroy(); + device.destroy(); + }, + }; +} diff --git a/apps/web/src/app/effects/effects.test.tsx b/apps/web/src/app/effects/effects.test.tsx new file mode 100644 index 0000000..5b7362f --- /dev/null +++ b/apps/web/src/app/effects/effects.test.tsx @@ -0,0 +1,17 @@ +import { renderToStaticMarkup } from 'react-dom/server'; +import { expect, test } from 'vitest'; +import { ProbeField } from './probe-field.tsx'; +import { ScanBand } from './scan-band.tsx'; + +// On the server (and before the browser has said it can draw them), both effects are their +// static CSS version: no canvas, nothing that waits on the GPU. +test('the probe field and scan band render their static version first', () => { + const field = renderToStaticMarkup(); + expect(field).toBe( + '', + ); + const band = renderToStaticMarkup(); + expect(band).toBe( + '', + ); +}); diff --git a/apps/web/src/app/effects/gate.ts b/apps/web/src/app/effects/gate.ts new file mode 100644 index 0000000..b5b4613 --- /dev/null +++ b/apps/web/src/app/effects/gate.ts @@ -0,0 +1,90 @@ +'use client'; + +import { useEffect, useState } from 'react'; + +// Shader helpers shared by the probe field and the scan band. Rules: the ui-shaders skill. + +type GpuNavigator = Navigator & { + gpu?: { requestAdapter(): Promise }; + connection?: { saveData?: boolean }; +}; + +// Whether a shader may run here: WebGPU with an adapter, no reduced motion, no data saving, and +// for effects that follow the cursor, a mouse. Starts false, so the server render and first paint +// are always the static version. +export function useShaderAllowed({ needsHover = false } = {}): boolean { + const [allowed, setAllowed] = useState(false); + useEffect(() => { + const nav = navigator as GpuNavigator; + const reduced = matchMedia('(prefers-reduced-motion: reduce)'); + const hover = matchMedia('(hover: hover) and (pointer: fine)'); + let gpu = false; + let cancelled = false; + const update = () => + setAllowed( + gpu && + !reduced.matches && + nav.connection?.saveData !== true && + (!needsHover || hover.matches), + ); + nav.gpu?.requestAdapter().then( + (adapter) => { + if (cancelled) return; + gpu = adapter != null; + update(); + }, + () => {}, + ); + reduced.addEventListener('change', update); + hover.addEventListener('change', update); + return () => { + cancelled = true; + reduced.removeEventListener('change', update); + hover.removeEventListener('change', update); + }; + }, [needsHover]); + return allowed; +} + +// The theme's colours as hex, which shader props need; tokens.css defines them in oklch. +// Resolved again when the system switches between light and dark. +export function useTokenColors( + tokens: Record, +): Record | null { + const [colors, setColors] = useState | null>(null); + const key = JSON.stringify(tokens); + useEffect(() => { + const names = JSON.parse(key) as Record; + const scheme = matchMedia('(prefers-color-scheme: dark)'); + const resolve = () => setColors(resolveTokens(names)); + resolve(); + scheme.addEventListener('change', resolve); + return () => scheme.removeEventListener('change', resolve); + }, [key]); + return colors; +} + +function resolveTokens(tokens: Record): Record | null { + const probe = document.createElement('span'); + probe.style.display = 'none'; + document.body.append(probe); + const canvas = document.createElement('canvas'); + canvas.width = 1; + canvas.height = 1; + const context = canvas.getContext('2d', { willReadFrequently: true }); + try { + if (!context) return null; + const out = {} as Record; + for (const [name, token] of Object.entries(tokens) as [K, string][]) { + probe.style.color = `var(${token})`; + context.clearRect(0, 0, 1, 1); + context.fillStyle = getComputedStyle(probe).color; + context.fillRect(0, 0, 1, 1); + const [r = 0, g = 0, b = 0] = context.getImageData(0, 0, 1, 1).data; + out[name] = `#${[r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('')}`; + } + return out; + } finally { + probe.remove(); + } +} diff --git a/apps/web/src/app/effects/probe-field.tsx b/apps/web/src/app/effects/probe-field.tsx new file mode 100644 index 0000000..0811437 --- /dev/null +++ b/apps/web/src/app/effects/probe-field.tsx @@ -0,0 +1,45 @@ +'use client'; + +import dynamic from 'next/dynamic'; +import { useState } from 'react'; +import type { DotFieldShape } from './dot-field.ts'; +import { useShaderAllowed, useTokenColors } from './gate.ts'; + +// Loaded only when it may run, so other pages and browsers never fetch the renderer. +const DotCanvas = dynamic(() => import('./dot-canvas.tsx'), { ssr: false }); + +// Matches the CSS version in globals.css: a dot every 16 px, the lens at 72% / 46% until the +// cursor moves, solid for ~40 px and fading out by ~120 px. +const SHAPE: DotFieldShape = { + kind: 'lens', + spacing: 16, + dotRadius: 1.15, + signalRadius: 2, + radius: 120, + softness: 0.7, + rest: { x: 0.72, y: 0.46 }, +}; + +// The dot field behind the home headline. The CSS version is always drawn first; on a desktop +// browser with WebGPU the shader fades in over it, and the lens follows the cursor. +export function ProbeField() { + const allowed = useShaderAllowed({ needsHover: true }); + const colors = useTokenColors({ ground: '--page', dot: '--dot', signal: '--signal' }); + const [ready, setReady] = useState(false); + const [unavailable, setUnavailable] = useState(false); + const live = allowed && colors !== null && !unavailable; + return ( +