@link-foundation/ui-animation 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +454 -2
  3. package/package.json +77 -4
  4. package/src/backgrounds/README.md +131 -0
  5. package/src/backgrounds/beams.d.ts +21 -0
  6. package/src/backgrounds/beams.js +140 -0
  7. package/src/backgrounds/common.d.ts +23 -0
  8. package/src/backgrounds/common.js +322 -0
  9. package/src/backgrounds/grid.d.ts +16 -0
  10. package/src/backgrounds/grid.js +122 -0
  11. package/src/backgrounds/nebula.d.ts +9 -0
  12. package/src/backgrounds/nebula.js +57 -0
  13. package/src/backgrounds/rain-cleanup.js +77 -0
  14. package/src/backgrounds/rain.d.ts +33 -0
  15. package/src/backgrounds/rain.js +238 -0
  16. package/src/backgrounds/shader.d.ts +14 -0
  17. package/src/backgrounds/shader.js +151 -0
  18. package/src/backgrounds/sprites.js +72 -0
  19. package/src/backgrounds/starfield.d.ts +38 -0
  20. package/src/backgrounds/starfield.js +168 -0
  21. package/src/clock.js +98 -0
  22. package/src/compile-waapi.js +147 -0
  23. package/src/diagnostics.js +51 -0
  24. package/src/easing.js +327 -0
  25. package/src/effects/decipher.js +83 -0
  26. package/src/effects.js +44 -0
  27. package/src/index.d.ts +581 -0
  28. package/src/index.js +74 -0
  29. package/src/layers.js +88 -0
  30. package/src/model.js +636 -0
  31. package/src/player.js +267 -0
  32. package/src/random.js +62 -0
  33. package/src/recorder/buffer.js +40 -0
  34. package/src/recorder/clock.js +2 -0
  35. package/src/recorder/format.js +125 -0
  36. package/src/recorder/input.js +53 -0
  37. package/src/recorder/recorder.js +183 -0
  38. package/src/recorder/redact.js +43 -0
  39. package/src/recorder/replay.js +115 -0
  40. package/src/recorder/state-at.js +62 -0
  41. package/src/recorder/store.js +92 -0
  42. package/src/recorder/to-playwright.js +113 -0
  43. package/src/recorder/verify.js +49 -0
  44. package/src/run.js +283 -0
  45. package/src/sample.js +160 -0
  46. package/src/timeline.js +115 -0
  47. package/src/timing.js +172 -0
  48. package/src/tokens.js +32 -0
  49. package/src/types.js +130 -0
  50. package/src/validate.js +218 -0
  51. package/src/values.js +331 -0
@@ -0,0 +1,122 @@
1
+ import { mountLayer, changed, bounded } from './common.js';
2
+
3
+ const defaults = {
4
+ cellSize: 64,
5
+ lineWidth: 1,
6
+ markLength: 0.25,
7
+ level: 1,
8
+ pattern: 'lines',
9
+ tint: 'line',
10
+ color: '#7395b8',
11
+ radialFade: false,
12
+ period: 30,
13
+ onDrift: undefined,
14
+ };
15
+
16
+ function background(element, win, o) {
17
+ const token = {
18
+ line: '--color-line',
19
+ accent: '--color-accent',
20
+ 'second-accent': '--color-accent-2',
21
+ }[o.tint];
22
+ const color =
23
+ (token && win.getComputedStyle?.(element).getPropertyValue(token).trim()) ||
24
+ o.color;
25
+ const escaped = color
26
+ .replaceAll('&', '&')
27
+ .replaceAll('"', '"')
28
+ .replaceAll('<', '&lt;');
29
+ const cell = o.cellSize,
30
+ mark = cell * o.markLength;
31
+ let artwork;
32
+ if (o.pattern === 'dots') {
33
+ artwork = `<circle cx="${cell / 2}" cy="${cell / 2}" r="${o.lineWidth}" fill="${escaped}"/>`;
34
+ } else {
35
+ const center = cell / 2;
36
+ let path = `M0 ${center}H${cell}M${center} 0V${cell}`;
37
+ if (o.pattern === 'crosses') {
38
+ path = `M${center - mark / 2} ${center}h${mark}M${center} ${center - mark / 2}v${mark}`;
39
+ }
40
+ const dash =
41
+ o.pattern === 'dashed' ? `stroke-dasharray="${mark} ${cell - mark}"` : '';
42
+ artwork = `<path d="${path}" stroke="${escaped}" stroke-width="${o.lineWidth}" ${dash}/>`;
43
+ }
44
+ // Original CSS image, offset by half a cell so marks land on grid lines.
45
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${cell}" height="${cell}" viewBox="0 0 ${cell} ${cell}">${artwork}</svg>`;
46
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
47
+ }
48
+ function create(element, win) {
49
+ let o,
50
+ offset = 0,
51
+ dirty = true;
52
+ const pattern = element.ownerDocument.createElement('div');
53
+ element.append?.(pattern);
54
+ function paint() {
55
+ if (!dirty) {
56
+ pattern.style.transform = `translateY(${offset}px)`;
57
+ return;
58
+ }
59
+ dirty = false;
60
+ const cell = o.cellSize;
61
+ Object.assign(element.style, {
62
+ overflow: 'hidden',
63
+ maskImage: o.radialFade
64
+ ? 'radial-gradient(ellipse, #000, transparent 75%)'
65
+ : '',
66
+ });
67
+ Object.assign(pattern.style, {
68
+ position: 'absolute',
69
+ inset: `-${cell}px 0 0`,
70
+ backgroundImage: background(element, win, o),
71
+ backgroundSize: `${cell}px ${cell}px`,
72
+ backgroundPosition: `${-cell / 2}px ${-cell / 2}px`,
73
+ backgroundRepeat: 'repeat',
74
+ transform: `translateY(${offset}px)`,
75
+ opacity: String(o.level / 4),
76
+ });
77
+ }
78
+ return {
79
+ defaults,
80
+ css: true,
81
+ update(next, before) {
82
+ o = bounded(next, {
83
+ cellSize: [32, 128],
84
+ lineWidth: [0.5, 4],
85
+ markLength: [0.05, 1],
86
+ level: [0, 4],
87
+ period: [0, 120],
88
+ });
89
+ const visual = changed(next, before, [
90
+ 'cellSize',
91
+ 'lineWidth',
92
+ 'markLength',
93
+ 'level',
94
+ 'pattern',
95
+ 'tint',
96
+ 'color',
97
+ 'radialFade',
98
+ ]);
99
+ dirty ||= visual;
100
+ return visual;
101
+ },
102
+ invalidate() {
103
+ dirty = true;
104
+ },
105
+ resize() {},
106
+ draw(dt, { still }) {
107
+ const cell = o.cellSize;
108
+ if (!still && o.period > 0) {
109
+ offset += (dt * cell) / o.period;
110
+ }
111
+ offset %= cell;
112
+ paint();
113
+ o.onDrift?.(offset);
114
+ },
115
+ dispose() {
116
+ pattern.remove();
117
+ },
118
+ };
119
+ }
120
+ /** Mount on a positioned div; other layers mount on canvases. */
121
+ export const mount = (element, options = {}) =>
122
+ mountLayer(element, options, create);
@@ -0,0 +1,9 @@
1
+ import type { ShaderOptions, Uniform } from './shader.js';
2
+ export const source: string;
3
+ export const uniforms: Record<string, Uniform>;
4
+ export function nebula(
5
+ options?: Partial<ShaderOptions> & {
6
+ driftSpeed?: number;
7
+ twinkleSpeed?: number;
8
+ }
9
+ ): ShaderOptions;
@@ -0,0 +1,57 @@
1
+ /** Original analytic gas field; no consumer shader source or artwork. */
2
+ export const source = `
3
+ precision mediump float;
4
+ uniform vec2 resolution;
5
+ uniform float time, twinkleTime, gas, hue, starDensity, starBrightness;
6
+ uniform float twinkle, vignette, zoom, starSize;
7
+ uniform vec3 gasColor1, gasColor2, gasColor3, gasColor4, starColor;
8
+ float hash(vec2 p) { return fract(sin(dot(p, vec2(17.13, 91.71))) * 4317.173); }
9
+ vec3 hueTurn(vec3 c, float a) {
10
+ vec3 axis = normalize(vec3(1.0));
11
+ return c*cos(a) + cross(axis,c)*sin(a) + axis*dot(axis,c)*(1.0-cos(a));
12
+ }
13
+ void main() {
14
+ vec2 uv = (gl_FragCoord.xy - resolution*.5) / resolution.y;
15
+ vec2 p = uv / zoom;
16
+ float t = time * .025;
17
+ float a = .5 + .5*sin(p.x*3.7 + sin(p.y*4.3+t) + t);
18
+ float b = .5 + .5*cos(p.y*4.9 + sin(p.x*3.1-t) - t*.7);
19
+ vec3 cloud = mix(mix(gasColor1,gasColor2,a),mix(gasColor3,gasColor4,b),a*b);
20
+ float veil = pow(a*b, 1.4) * gas;
21
+ vec2 cells = p * 130.0;
22
+ vec2 id = floor(cells);
23
+ float exists = step(1.0 - starDensity*.045, hash(id));
24
+ float radius = length(fract(cells)-vec2(hash(id+1.0),hash(id+2.0)));
25
+ float point = 1.0-smoothstep(.005, .045*starSize, radius);
26
+ float flicker = 1.0 - .35*twinkle*(.5+.5*sin(twinkleTime+hash(id)*6.28));
27
+ vec3 color = hueTurn(cloud*veil,hue) + starColor*point*exists*starBrightness*max(.0,flicker);
28
+ color *= 1.0-vignette*smoothstep(.1,1.0,length(uv));
29
+ gl_FragColor = vec4(max(vec3(.008,.012,.025),color),1.0);
30
+ }`;
31
+
32
+ export const uniforms = {
33
+ gas: 1.2,
34
+ hue: { degrees: 0 },
35
+ starDensity: 1,
36
+ starBrightness: 1,
37
+ twinkle: 1,
38
+ vignette: 0.5,
39
+ zoom: 1,
40
+ starSize: 1,
41
+ gasColor1: '#17274a',
42
+ gasColor2: '#384477',
43
+ gasColor3: '#57366a',
44
+ gasColor4: '#194953',
45
+ starColor: '#dcecff',
46
+ };
47
+
48
+ /** Pass these options to the independent shader entry point's mount(). */
49
+ export function nebula(options = {}) {
50
+ const { driftSpeed = 1, twinkleSpeed = 1, ...rest } = options;
51
+ return {
52
+ ...rest,
53
+ source,
54
+ uniforms: { ...uniforms, ...rest.uniforms },
55
+ times: { time: driftSpeed, twinkleTime: twinkleSpeed, ...rest.times },
56
+ };
57
+ }
@@ -0,0 +1,77 @@
1
+ let nextFilterId = 0;
2
+
3
+ /** Remove quantization residue. The pixel path also covers engines without SVG filters. */
4
+ export function cleanupPixels(ctx, width, height) {
5
+ const image = ctx.getImageData(0, 0, width, height);
6
+ for (let i = 3; i < image.data.length; i += 4) {
7
+ if (image.data[i] <= 9) {
8
+ image.data[i] = 0;
9
+ }
10
+ }
11
+ ctx.putImageData(image, 0, 0);
12
+ }
13
+
14
+ export function alphaCleanup(canvas, ctx) {
15
+ const doc = canvas.ownerDocument;
16
+ let svg, filterId;
17
+ // An SVG table makes values 0..9/255 zero without blurring the glyphs.
18
+ if (doc.createElementNS && 'filter' in ctx) {
19
+ svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');
20
+ const filter = doc.createElementNS(svg.namespaceURI, 'filter');
21
+ const transfer = doc.createElementNS(
22
+ svg.namespaceURI,
23
+ 'feComponentTransfer'
24
+ );
25
+ const alpha = doc.createElementNS(svg.namespaceURI, 'feFuncA');
26
+ filterId = `ui-rain-${++nextFilterId}`;
27
+ svg.setAttribute('data-ui-rain-filter', '');
28
+ svg.setAttribute('aria-hidden', 'true');
29
+ svg.style.cssText =
30
+ 'position:absolute;width:0;height:0;pointer-events:none';
31
+ filter.id = filterId;
32
+ alpha.setAttribute('type', 'discrete');
33
+ alpha.setAttribute(
34
+ 'tableValues',
35
+ Array.from({ length: 256 }, (_, i) => (i <= 9 ? 0 : i / 255)).join(' ')
36
+ );
37
+ transfer.append(alpha);
38
+ filter.append(transfer);
39
+ svg.append(filter);
40
+ doc.body.append(svg);
41
+ }
42
+ let filtered = false;
43
+ if (svg) {
44
+ const probe = doc.createElement('canvas');
45
+ probe.width = probe.height = 1;
46
+ const test = probe.getContext('2d');
47
+ test.fillStyle = 'rgba(255,255,255,0.02)';
48
+ test.fillRect(0, 0, 1, 1);
49
+ test.filter = `url(#${filterId})`;
50
+ test.globalCompositeOperation = 'copy';
51
+ test.drawImage(probe, 0, 0);
52
+ filtered = test.getImageData(0, 0, 1, 1).data[3] === 0;
53
+ }
54
+ return {
55
+ run() {
56
+ ctx.save();
57
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
58
+ try {
59
+ if (filtered) {
60
+ ctx.filter = `url(#${filterId})`;
61
+ // copy replaces the source, so erased pixels cannot accumulate underneath.
62
+ ctx.globalCompositeOperation = 'copy';
63
+ ctx.globalAlpha = 1;
64
+ ctx.drawImage(canvas, 0, 0);
65
+ ctx.filter = 'none';
66
+ } else {
67
+ cleanupPixels(ctx, canvas.width, canvas.height);
68
+ }
69
+ } finally {
70
+ ctx.restore();
71
+ }
72
+ },
73
+ dispose() {
74
+ svg?.remove();
75
+ },
76
+ };
77
+ }
@@ -0,0 +1,33 @@
1
+ import type { CommonOptions, LayerHandle } from './common.js';
2
+ export interface RainOptions extends CommonOptions {
3
+ seed?: number | string;
4
+ cellSize?: number;
5
+ step?: number;
6
+ columnSteps?: number;
7
+ density?: number;
8
+ restart?: number;
9
+ fade?: number;
10
+ glow?: number;
11
+ padding?: number;
12
+ color?: string;
13
+ visible?: boolean;
14
+ drift?: number;
15
+ pick?: () => unknown;
16
+ paint?: (
17
+ ctx: CanvasRenderingContext2D,
18
+ glyph: unknown,
19
+ x: number,
20
+ y: number,
21
+ size: number,
22
+ glow: number
23
+ ) => void;
24
+ }
25
+ export function mount(
26
+ canvas: HTMLCanvasElement,
27
+ options?: RainOptions
28
+ ): LayerHandle<RainOptions>;
29
+ export function createCadence(): {
30
+ frame(gap: number): void;
31
+ ready(step: number, fps: number): boolean;
32
+ reset(): void;
33
+ };
@@ -0,0 +1,238 @@
1
+ import { seededRandom } from '../random.js';
2
+ import { mountLayer, changed, clamp, bounded } from './common.js';
3
+ import { alphaCleanup } from './rain-cleanup.js';
4
+
5
+ const defaultPaint = (ctx, glyph, x, y, size) => {
6
+ ctx.font = `${size}px monospace`;
7
+ ctx.fillText(String(glyph), x, y);
8
+ };
9
+ const defaults = {
10
+ seed: 224,
11
+ cellSize: 64,
12
+ step: 105,
13
+ columnSteps: 4,
14
+ density: 0.35,
15
+ restart: 0.03,
16
+ fade: 0.075,
17
+ glow: 10,
18
+ padding: 2,
19
+ color: '#77ffaa',
20
+ visible: true,
21
+ drift: 0,
22
+ paint: defaultPaint,
23
+ pick: undefined,
24
+ };
25
+
26
+ /** Quantize to whole measured display frames; never take two steps in one frame. */
27
+ export function createCadence() {
28
+ const gaps = [];
29
+ let frames = 0;
30
+ return {
31
+ frame(gap) {
32
+ if (gap > 0 && gap < 100) {
33
+ gaps.push(gap);
34
+ if (gaps.length > 30) {
35
+ gaps.shift();
36
+ }
37
+ }
38
+ },
39
+ ready(step, fps) {
40
+ const sorted = [...gaps].sort((a, b) => a - b);
41
+ const middle = Math.floor(sorted.length / 2);
42
+ const median = sorted.length
43
+ ? (sorted[middle] +
44
+ sorted[Math.max(0, Math.ceil(sorted.length / 2) - 1)]) /
45
+ 2
46
+ : 1000 / 60;
47
+ frames++;
48
+ const count = Math.max(
49
+ 1,
50
+ Math.round(Math.max(clamp(step, 20, 400), 1000 / fps) / median)
51
+ );
52
+ if (frames < count) {
53
+ return false;
54
+ }
55
+ frames = 0;
56
+ return true;
57
+ },
58
+ reset() {
59
+ frames = 0;
60
+ },
61
+ };
62
+ }
63
+
64
+ function shiftCanvas(canvas, ctx, dy) {
65
+ if (!dy) {
66
+ return;
67
+ }
68
+ ctx.save();
69
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
70
+ ctx.globalCompositeOperation = 'copy';
71
+ ctx.globalAlpha = 1;
72
+ ctx.drawImage(canvas, 0, dy);
73
+ ctx.restore();
74
+ }
75
+
76
+ function stillField(ctx, area, columns, o, glyph) {
77
+ ctx.clearRect(0, 0, area.width, area.height);
78
+ const fieldRandom = seededRandom(o.seed);
79
+ for (const column of columns) {
80
+ if (!column.active) {
81
+ continue;
82
+ }
83
+ for (let y = 0; y < area.height; y += o.cellSize / 2) {
84
+ glyph(
85
+ {
86
+ ...column,
87
+ y,
88
+ glyph:
89
+ o.pick?.() ??
90
+ String.fromCharCode(0x30 + Math.floor(fieldRandom() * 10)),
91
+ },
92
+ 0,
93
+ 0.2 + fieldRandom() * 0.6
94
+ );
95
+ }
96
+ }
97
+ ctx.globalAlpha = 1;
98
+ }
99
+
100
+ function create(canvas) {
101
+ const ctx = canvas.getContext('2d');
102
+ if (!ctx) {
103
+ return null;
104
+ }
105
+ const cleanup = alphaCleanup(canvas, ctx);
106
+ const cadence = createCadence();
107
+ let o,
108
+ area,
109
+ columns = [],
110
+ random,
111
+ steps = 0,
112
+ cleanupTime = 0,
113
+ priorDrift = 0;
114
+ const pick = () =>
115
+ o.pick?.() ?? String.fromCharCode(0x30 + Math.floor(random() * 10));
116
+ function seed() {
117
+ random = seededRandom(o.seed);
118
+ const spacing = clamp(o.cellSize, 32, 128) / 2;
119
+ columns = Array.from(
120
+ { length: Math.ceil(area.width / spacing) },
121
+ (_, i) => ({
122
+ x: i * spacing,
123
+ y: Math.floor((random() * area.height) / spacing) * spacing,
124
+ active: random() < o.density,
125
+ every: 1 + Math.floor(random() * clamp(o.columnSteps, 1, 8)),
126
+ glyph: pick(),
127
+ })
128
+ );
129
+ }
130
+ function glyph(column, glow, alpha = 1) {
131
+ const spacing = o.cellSize / 2;
132
+ const padding = clamp(o.padding, 0, Math.min(16, (o.cellSize * 3) / 8));
133
+ ctx.globalAlpha = alpha;
134
+ ctx.fillStyle = o.color;
135
+ ctx.shadowColor = o.color;
136
+ ctx.shadowBlur = glow;
137
+ o.paint(
138
+ ctx,
139
+ column.glyph,
140
+ column.x + padding,
141
+ column.y + o.drift,
142
+ Math.max(1, spacing - padding),
143
+ glow
144
+ );
145
+ ctx.shadowBlur = 0;
146
+ }
147
+ return {
148
+ defaults,
149
+ frame: cadence.frame,
150
+ cadence: (fps) => cadence.ready(o.step, fps),
151
+ resetClock: cadence.reset,
152
+ update(next, before) {
153
+ o = bounded(next, {
154
+ cellSize: [32, 128],
155
+ step: [20, 400],
156
+ columnSteps: [1, 8],
157
+ density: [0.05, 1],
158
+ restart: [0.005, 0.5],
159
+ fade: [0.01, 0.5],
160
+ glow: [0, 40],
161
+ padding: [0, 16],
162
+ });
163
+ if (area && changed(next, before, ['cellSize', 'seed'])) {
164
+ seed();
165
+ }
166
+ if (area && next.density !== before.density) {
167
+ const active = seededRandom(o.seed);
168
+ columns.forEach((c) => {
169
+ c.active = active() < o.density;
170
+ });
171
+ }
172
+ if (area && next.columnSteps !== before.columnSteps) {
173
+ const speed = seededRandom(o.seed);
174
+ columns.forEach((c) => {
175
+ c.every = 1 + Math.floor(speed() * clamp(o.columnSteps, 1, 8));
176
+ });
177
+ }
178
+ return changed(
179
+ next,
180
+ before,
181
+ Object.keys(defaults).filter(
182
+ (key) => !['step', 'columnSteps', 'restart', 'fade'].includes(key)
183
+ )
184
+ );
185
+ },
186
+ resize(next, old) {
187
+ area = next;
188
+ if (!old || next.width !== old.width) {
189
+ seed();
190
+ }
191
+ },
192
+ draw(dt, { still, frame }) {
193
+ ctx.setTransform(area.ratio, 0, 0, area.ratio, 0, 0);
194
+ // Round the absolute offset so subpixel deltas accumulate across frames.
195
+ const drift = Math.round(o.drift * area.ratio);
196
+ shiftCanvas(canvas, ctx, drift - priorDrift);
197
+ priorDrift = drift;
198
+ if (!o.visible) {
199
+ return;
200
+ }
201
+ if (still) {
202
+ stillField(ctx, area, columns, o, glyph);
203
+ return;
204
+ }
205
+ // An invalidation is a repaint, never a simulation step or extra fade.
206
+ if (!frame) {
207
+ columns.filter((c) => c.active).forEach((c) => glyph(c, o.glow));
208
+ return;
209
+ }
210
+ steps++;
211
+ cleanupTime += dt || o.step / 1000;
212
+ ctx.globalCompositeOperation = 'destination-out';
213
+ ctx.globalAlpha = clamp(o.fade, 0.01, 0.5);
214
+ ctx.fillRect(0, 0, area.width, area.height);
215
+ ctx.globalCompositeOperation = 'source-over';
216
+ ctx.globalAlpha = 1;
217
+ for (const column of columns) {
218
+ if (!column.active || steps % column.every) {
219
+ continue;
220
+ }
221
+ glyph(column, 0);
222
+ column.y += o.cellSize / 2;
223
+ if (column.y > area.height || random() < clamp(o.restart, 0.005, 0.5)) {
224
+ column.y = 0;
225
+ }
226
+ column.glyph = pick();
227
+ glyph(column, o.glow);
228
+ }
229
+ if (cleanupTime >= 1) {
230
+ cleanup.run();
231
+ cleanupTime %= 1;
232
+ }
233
+ },
234
+ dispose: cleanup.dispose,
235
+ };
236
+ }
237
+ export const mount = (canvas, options = {}) =>
238
+ mountLayer(canvas, options, create);
@@ -0,0 +1,14 @@
1
+ import type { CommonOptions, LayerHandle } from './common.js';
2
+ export type Uniform = number | string | { degrees: number };
3
+ export interface ShaderOptions extends CommonOptions {
4
+ source: string;
5
+ uniforms?: Record<string, Uniform>;
6
+ /** Named independent clocks and their speeds. */
7
+ times?: Record<string, number>;
8
+ startTime?: number | 'random';
9
+ seed?: number | string;
10
+ }
11
+ export function mount(
12
+ canvas: HTMLCanvasElement,
13
+ options: ShaderOptions
14
+ ): LayerHandle<ShaderOptions>;
@@ -0,0 +1,151 @@
1
+ import { seededRandom } from '../random.js';
2
+ import { mountLayer, changed, radians } from './common.js';
3
+
4
+ const vertex =
5
+ 'attribute vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); }';
6
+ const defaults = {
7
+ source: '',
8
+ uniforms: {},
9
+ times: { time: 1 },
10
+ startTime: 0,
11
+ seed: 224,
12
+ };
13
+ function compile(gl, type, source) {
14
+ const shader = gl.createShader(type);
15
+ gl.shaderSource(shader, source);
16
+ gl.compileShader(shader);
17
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
18
+ gl.deleteShader(shader);
19
+ throw new Error('Background shader compilation failed');
20
+ }
21
+ return shader;
22
+ }
23
+ function programFor(gl, source) {
24
+ const shaders = [];
25
+ let program;
26
+ try {
27
+ shaders.push(compile(gl, gl.VERTEX_SHADER, vertex));
28
+ shaders.push(compile(gl, gl.FRAGMENT_SHADER, source));
29
+ program = gl.createProgram();
30
+ shaders.forEach((shader) => gl.attachShader(program, shader));
31
+ gl.linkProgram(program);
32
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
33
+ throw new Error('Background shader link failed');
34
+ }
35
+ return program;
36
+ } catch (error) {
37
+ if (program) {
38
+ gl.deleteProgram(program);
39
+ }
40
+ throw error;
41
+ } finally {
42
+ shaders.forEach((shader) => gl.deleteShader(shader));
43
+ }
44
+ }
45
+ function upload(gl, location, value) {
46
+ if (typeof value === 'number') {
47
+ gl.uniform1f(location, value);
48
+ } else if (
49
+ typeof value === 'string' &&
50
+ value.startsWith('#') &&
51
+ value.length === 7
52
+ ) {
53
+ gl.uniform3f(
54
+ location,
55
+ ...[1, 3, 5].map((i) => parseInt(value.slice(i, i + 2), 16) / 255)
56
+ );
57
+ } else if (value && typeof value.degrees === 'number') {
58
+ gl.uniform1f(location, radians(value.degrees));
59
+ }
60
+ }
61
+ function create(canvas, win, initial) {
62
+ const gl = canvas.getContext('webgl', {
63
+ alpha: false,
64
+ antialias: false,
65
+ powerPreference: 'low-power',
66
+ preserveDrawingBuffer: true,
67
+ });
68
+ if (!gl) {
69
+ return null;
70
+ }
71
+ let program = programFor(gl, initial.source ?? '');
72
+ const buffer = gl.createBuffer();
73
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
74
+ gl.bufferData(
75
+ gl.ARRAY_BUFFER,
76
+ new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
77
+ gl.STATIC_DRAW
78
+ );
79
+ let o,
80
+ area,
81
+ failed = false;
82
+ const clocks = new Map();
83
+ function configure() {
84
+ gl.useProgram(program);
85
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
86
+ const position = gl.getAttribLocation(program, 'position');
87
+ gl.enableVertexAttribArray(position);
88
+ gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
89
+ }
90
+ configure();
91
+ return {
92
+ defaults,
93
+ webgl: true,
94
+ update(next, before) {
95
+ o = next;
96
+ if (before.source !== undefined && before.source !== next.source) {
97
+ try {
98
+ const replacement = programFor(gl, next.source);
99
+ gl.deleteProgram(program);
100
+ program = replacement;
101
+ configure();
102
+ failed = false;
103
+ canvas.style.visibility = '';
104
+ } catch (error) {
105
+ failed = true;
106
+ canvas.style.visibility = 'hidden';
107
+ o.onError?.(error);
108
+ }
109
+ }
110
+ for (const name of Object.keys(next.times)) {
111
+ if (!clocks.has(name) || next.startTime !== before.startTime) {
112
+ clocks.set(
113
+ name,
114
+ next.startTime === 'random'
115
+ ? seededRandom(`${next.seed}:${name}`)() * 1000
116
+ : Number(next.startTime)
117
+ );
118
+ }
119
+ }
120
+ return changed(next, before, ['source', 'uniforms', 'startTime']);
121
+ },
122
+ resize(next) {
123
+ area = next;
124
+ gl.viewport(0, 0, canvas.width, canvas.height);
125
+ },
126
+ draw(dt, { still }) {
127
+ if (failed) {
128
+ return;
129
+ }
130
+ gl.useProgram(program);
131
+ const location = (name) => gl.getUniformLocation(program, name);
132
+ gl.uniform2f(location('resolution'), canvas.width, canvas.height);
133
+ gl.uniform1f(location('pixelRatio'), area.ratio);
134
+ for (const [name, speed] of Object.entries(o.times)) {
135
+ const time = clocks.get(name) + (still ? 0 : dt * speed);
136
+ clocks.set(name, time);
137
+ gl.uniform1f(location(name), time);
138
+ }
139
+ for (const [name, value] of Object.entries(o.uniforms)) {
140
+ upload(gl, location(name), value);
141
+ }
142
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
143
+ },
144
+ dispose() {
145
+ gl.deleteBuffer(buffer);
146
+ gl.deleteProgram(program);
147
+ },
148
+ };
149
+ }
150
+ export const mount = (canvas, options = {}) =>
151
+ mountLayer(canvas, options, create);