Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 56 additions & 47 deletions .claude/skills/ui-shaders/SKILL.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 <preset>` 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`. `<Shader>` renders one `<canvas>`; children are layers, first at
the bottom. Size it with CSS on `<Shader>`, 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 `<Shader>` 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.
3 changes: 2 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
56 changes: 56 additions & 0 deletions apps/web/src/app/effects/dot-canvas.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLCanvasElement>(null);
const field = useRef<DotField | null>(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 <canvas ref={canvas} className="effect-canvas" />;
}
43 changes: 43 additions & 0 deletions apps/web/src/app/effects/dot-field.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
Loading
Loading