@arraypress/effects-astro 0.5.0 → 0.7.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.
@@ -11,6 +11,10 @@ export interface PixelGlitchConfig {
11
11
  shift?: number;
12
12
  /** With a width (CSS px), the text at rest is an outline that the pixels fill: one outline round the word, so overlapping letters merge. Default 0 (solid). */
13
13
  stroke?: number;
14
+ /** What slips: `cell`, each hot cell on its own; `row`, a whole row at once, now and then, by its hottest cell (up to half of `shift` either way). Default `cell`. */
15
+ tear?: 'cell' | 'row';
16
+ /** A colour for a copy of the blocks, nudged 3px right behind them (an accent under the break). Default none. */
17
+ ghost?: string;
14
18
  }
15
19
 
16
20
  /**
@@ -20,5 +24,8 @@ export interface PixelGlitchConfig {
20
24
  */
21
25
  export function outlineAlpha(rgba: Uint8ClampedArray, width: number, height: number, radius: number): Uint8ClampedArray;
22
26
 
27
+ /** How far each row of a heat grid tears this frame (whole CSS px): a row whose hottest cell is over 0.45 tears on about a third of frames, by up to half of `shift` either way, scaled by that heat. */
28
+ export function rowTears(heat: Float32Array, cols: number, rows: number, shift: number, random?: () => number): Float32Array;
29
+
23
30
  /** Starts the pixel glitch on an element of text. Returns a function that stops it. */
24
31
  export function pixelGlitch(el: HTMLElement, config: PixelGlitchConfig): () => void;
@@ -8,6 +8,11 @@
8
8
  * pointer and the text knits back together behind it. Faster movement adds
9
9
  * more heat.
10
10
  *
11
+ * The slip is each hot cell's own by default; with `tear: 'row'` a whole
12
+ * row tears at once, now and then, by its hottest cell (the Logomarks
13
+ * site's footer). With `ghost`, a copy of the blocks in that colour sits
14
+ * nudged 3px right behind them, an accent under the break.
15
+ *
11
16
  * With `stroke` set, the text at rest is a hollow outline of that width and
12
17
  * the pixels it breaks into fill the letters solid, so the pointer lights
13
18
  * the word up as it passes. The outline is one shape for the whole word
@@ -32,7 +37,7 @@
32
37
  */
33
38
 
34
39
  import { canHover, prefersReducedMotion } from './device.js';
35
- import { textNodes } from './text.js';
40
+ import { textNodes, paintGlyphs } from './text.js';
36
41
 
37
42
  /**
38
43
  * @typedef {object} PixelGlitchConfig
@@ -42,8 +47,47 @@ import { textNodes } from './text.js';
42
47
  * @property {number} [block=22] The pixel block size at full heat, CSS px.
43
48
  * @property {number} [shift=16] How far the hottest rows slip sideways, CSS px.
44
49
  * @property {number} [stroke=0] With a width (CSS px), the text at rest is an outline that the pixels fill.
50
+ * @property {'cell' | 'row'} [tear='cell'] What slips: each hot cell on its own, or a whole row at once.
51
+ * @property {string} [ghost] A colour for a copy of the blocks, nudged right behind them (none by default).
45
52
  */
46
53
 
54
+ /** How far the ghost sits right of its block, CSS px. */
55
+ const GHOST_OFFSET = 3;
56
+
57
+ /** The heat a block needs to cast its ghost. */
58
+ const GHOST_HEAT = 0.3;
59
+
60
+ /** A row's hottest cell must pass this for the row to tear… */
61
+ const TEAR_HEAT = 0.45;
62
+
63
+ /** …and then it tears on this share of frames. */
64
+ const TEAR_CHANCE = 0.35;
65
+
66
+ /** The heat a cell needs to slip on its own (`tear: 'cell'`). */
67
+ const SLIP_HEAT = 0.55;
68
+
69
+ /**
70
+ * How far each row of a heat grid tears this frame: rows whose hottest
71
+ * cell passes TEAR_HEAT tear on some frames, by up to half of `shift`
72
+ * either way (scaled by that heat), and the rest stay put.
73
+ *
74
+ * @param {Float32Array} heat The grid, row by row.
75
+ * @param {number} cols Cells a row.
76
+ * @param {number} rows Rows.
77
+ * @param {number} shift The most a row slips, at full heat, CSS px (end to end).
78
+ * @param {() => number} [random=Math.random] Random values, 0–1.
79
+ * @returns {Float32Array} Each row's slip, whole CSS px.
80
+ */
81
+ export function rowTears(heat, cols, rows, shift, random = Math.random) {
82
+ const tear = new Float32Array(rows);
83
+ for (let row = 0; row < rows; row++) {
84
+ let h = 0;
85
+ for (let col = 0; col < cols; col++) h = Math.max(h, heat[row * cols + col]);
86
+ tear[row] = h > TEAR_HEAT && random() < TEAR_CHANCE ? Math.round((random() - 0.5) * h * shift) : 0;
87
+ }
88
+ return tear;
89
+ }
90
+
47
91
  /** The 16 directions the outline's erosion looks in, as unit vectors. */
48
92
  const AROUND = Array.from({ length: 16 }, (_, k) => [Math.cos((k / 16) * Math.PI * 2), Math.sin((k / 16) * Math.PI * 2)]);
49
93
 
@@ -97,6 +141,8 @@ export function pixelGlitch(el, config) {
97
141
  const MAX_BLOCK = config.block ?? 22;
98
142
  const SHIFT = config.shift ?? 16;
99
143
  const STROKE = config.stroke ?? 0;
144
+ const ROWS = config.tear === 'row';
145
+ const GHOST = config.ghost || '';
100
146
 
101
147
  const canvas = document.createElement('canvas');
102
148
  canvas.className = 'effect-pixel-glitch-canvas';
@@ -148,6 +194,7 @@ export function pixelGlitch(el, config) {
148
194
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
149
195
  ctx.fillStyle = g.ink;
150
196
  let hot = false;
197
+ const tears = ROWS ? rowTears(g.heat, g.cols, g.rows, SHIFT) : null;
151
198
  for (let row = 0; row < g.rows; row++) {
152
199
  for (let col = 0; col < g.cols; col++) {
153
200
  const i = row * g.cols + col;
@@ -162,17 +209,24 @@ export function pixelGlitch(el, config) {
162
209
  // Wipe the cell, then fill it with blocks sampled from the filled text.
163
210
  ctx.clearRect(x0, y0, CELL, CELL);
164
211
  const block = Math.max(3, Math.round(3 + heat * (MAX_BLOCK - 3)));
165
- // The hottest cells also slip sideways: the glitch.
166
- const shift = heat > 0.55 ? Math.round((Math.random() - 0.5) * heat * SHIFT) : 0;
212
+ // The hottest cells (or rows) also slip sideways: the glitch.
213
+ const shift = tears ? tears[row] : heat > SLIP_HEAT ? Math.round((Math.random() - 0.5) * heat * SHIFT) : 0;
167
214
  const bx0 = Math.floor(x0 / block) * block;
168
215
  const by0 = Math.floor(y0 / block) * block;
169
216
  for (let by = by0; by < y0 + CELL; by += block) {
170
217
  for (let bx = bx0; bx < x0 + CELL; bx += block) {
171
218
  if (!inked(bx + block / 2, by + block / 2)) continue;
172
219
  // Clipped to the cell, so neighbours tile cleanly.
220
+ const x = Math.max(bx, x0) + shift;
221
+ const y = Math.max(by, y0);
173
222
  const w = Math.min(bx + block, x0 + CELL) - Math.max(bx, x0);
174
223
  const h = Math.min(by + block, y0 + CELL) - Math.max(by, y0);
175
- ctx.fillRect(Math.max(bx, x0) + shift, Math.max(by, y0), w, h);
224
+ if (GHOST && heat > GHOST_HEAT) {
225
+ ctx.fillStyle = GHOST;
226
+ ctx.fillRect(x + GHOST_OFFSET, y, w, h);
227
+ ctx.fillStyle = g.ink;
228
+ }
229
+ ctx.fillRect(x, y, w, h);
176
230
  }
177
231
  }
178
232
  g.heat[i] = heat * DECAY;
@@ -226,29 +280,7 @@ export function pixelGlitch(el, config) {
226
280
  c2.setTransform(dpr, 0, 0, dpr, 0, 0);
227
281
  c2.clearRect(0, 0, g.w, g.h);
228
282
  c2.fillStyle = g.ink;
229
- c2.font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
230
- c2.textBaseline = 'alphabetic';
231
- const range = document.createRange();
232
- /**
233
- * Draws every glyph where the browser laid it out.
234
- *
235
- * @param {(ch: string, x: number, y: number) => void} glyph Draws one glyph at a baseline position.
236
- */
237
- const eachGlyph = (glyph) => {
238
- for (const text of texts) {
239
- const str = text.textContent ?? '';
240
- for (let i = 0; i < str.length; i++) {
241
- const ch = str[i];
242
- if (!ch.trim()) continue;
243
- range.setStart(text, i);
244
- range.setEnd(text, i + 1);
245
- const r = range.getBoundingClientRect();
246
- // The glyph's box starts at r.top; its baseline sits one font ascent below.
247
- glyph(ch, r.left - origin.x, r.top - origin.y + c2.measureText(ch).fontBoundingBoxAscent);
248
- }
249
- }
250
- };
251
- eachGlyph((ch, x, y) => c2.fillText(ch, x, y));
283
+ paintGlyphs(c2, texts, origin);
252
284
  g.alpha = c2.getImageData(0, 0, crisp.width, crisp.height).data;
253
285
  if (STROKE > 0) {
254
286
  // The pixels still sample the solid letters (g.alpha); what shows at rest is their outline, in the ink.
@@ -1,2 +1,14 @@
1
+ /** A seeded generator's name: `mulberry32` (well mixed from any seed) or `park-miller` (the minimal standard, × 16807 mod 2³¹ − 1). */
2
+ export type RandomName = 'mulberry32' | 'park-miller';
3
+
1
4
  /** A seeded generator (mulberry32): the same seed gives the same sequence of values, 0 (inclusive) to 1 (exclusive). */
2
5
  export function seededRandom(seed: number): () => number;
6
+
7
+ /** A Park–Miller minimal standard generator (× 16807 mod 2³¹ − 1): the same seed gives the same sequence, over 0 and under 1. A seed that comes to 0 is moved into range. */
8
+ export function parkMiller(seed: number): () => number;
9
+
10
+ /** The generators by name. */
11
+ export const RANDOMS: Readonly<Record<RandomName, (seed: number) => () => number>>;
12
+
13
+ /** Makes a generator by name (default `mulberry32`). Throws a TypeError for an unknown name. */
14
+ export function randomFrom(name: RandomName | undefined, seed: number): () => number;
@@ -1,10 +1,19 @@
1
1
  /**
2
2
  * @module @arraypress/effects-astro/random
3
3
  *
4
- * A small seeded random generator (mulberry32), for effects that build
5
- * something from a `seed` and must build the same thing on every load.
4
+ * Small seeded random generators, for effects that build something from a
5
+ * `seed` and must build the same thing on every load: mulberry32 (the
6
+ * default, well mixed from any seed) and the Park–Miller minimal standard
7
+ * (a multiplicative generator, × 16807 mod 2³¹ − 1), kept so a sky first
8
+ * drawn with it can be drawn again exactly.
6
9
  */
7
10
 
11
+ /** Park–Miller's modulus, 2³¹ − 1. */
12
+ const PM_MODULUS = 2147483647;
13
+
14
+ /** Park–Miller's multiplier (the minimal standard's). */
15
+ const PM_MULTIPLIER = 16807;
16
+
8
17
  /**
9
18
  * Makes a seeded generator: the same seed gives the same sequence.
10
19
  *
@@ -20,3 +29,35 @@ export function seededRandom(seed) {
20
29
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
21
30
  };
22
31
  }
32
+
33
+ /**
34
+ * Makes a Park–Miller generator: the state times 16807, mod 2³¹ − 1, read
35
+ * as a fraction of the modulus. Exact in double precision. A seed that
36
+ * comes to 0 (or a multiple of the modulus) would stick at 0, so it is
37
+ * moved into range first.
38
+ *
39
+ * @param {number} seed Any number; its integer part is used.
40
+ * @returns {() => number} The next value, over 0 and under 1.
41
+ */
42
+ export function parkMiller(seed) {
43
+ let s = Math.floor(seed) % PM_MODULUS;
44
+ if (s <= 0) s += PM_MODULUS - 1;
45
+ return () => (s = (s * PM_MULTIPLIER) % PM_MODULUS) / PM_MODULUS;
46
+ }
47
+
48
+ /** The generators by name, for an effect's `rng` setting. */
49
+ export const RANDOMS = Object.freeze({ mulberry32: seededRandom, 'park-miller': parkMiller });
50
+
51
+ /**
52
+ * Makes a generator by name.
53
+ *
54
+ * @param {string | undefined} name `mulberry32` (the default) or `park-miller`.
55
+ * @param {number} seed The seed.
56
+ * @returns {() => number} The generator.
57
+ * @throws {TypeError} When the name is not one of RANDOMS.
58
+ */
59
+ export function randomFrom(name, seed) {
60
+ const key = /** @type {keyof typeof RANDOMS} */ (name ?? 'mulberry32');
61
+ if (!Object.hasOwn(RANDOMS, key)) throw new TypeError(`Unknown random generator: ${name} (use ${Object.keys(RANDOMS).join(' or ')})`);
62
+ return RANDOMS[key](seed);
63
+ }
@@ -1,7 +1,7 @@
1
- import type { SceneOptions } from '@arraypress/shaders';
1
+ import type { SceneOptions } from '@logomarks/shaders';
2
2
  import type { PaletteName } from './palettes.js';
3
3
 
4
- /** A scene's name: one of `@arraypress/shaders`' scenes. */
4
+ /** A scene's name: one of `@logomarks/shaders`' scenes. */
5
5
  export type SceneName =
6
6
  | 'marble'
7
7
  | 'frosted'
@@ -51,7 +51,7 @@ export interface SceneConfig {
51
51
  near?: boolean | string;
52
52
  }
53
53
 
54
- /** A `<Scene>`'s settings as `@arraypress/shaders`' options: the palette found by name, `near` as `lazy`. */
54
+ /** A `<Scene>`'s settings as `@logomarks/shaders`' options: the palette found by name, `near` as `lazy`. */
55
55
  export function sceneSettings(config: SceneConfig): { name: SceneName; options: SceneOptions };
56
56
 
57
57
  /** Starts a scene on an element's canvas; returns a function that stops it. */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @module @arraypress/effects-astro/scene
3
3
  *
4
- * A scene from `@arraypress/shaders` on an effect's canvas: liquid marble,
4
+ * A scene from `@logomarks/shaders` on an effect's canvas: liquid marble,
5
5
  * frosted glass, glossy tiles, chrome, glitter, holographic foil, ink in
6
6
  * water and the rest, recoloured by a palette and shaped by the scene's own
7
7
  * settings. `<Scene>` is the component.
@@ -14,14 +14,14 @@
14
14
  * with reduced motion. `setColors` recolours it live.
15
15
  */
16
16
 
17
- import { scene as run, LOOK } from '@arraypress/shaders/core';
18
- import { load } from '@arraypress/shaders/load';
17
+ import { scene as run, LOOK } from '@logomarks/shaders/core';
18
+ import { load } from '@logomarks/shaders/load';
19
19
  import { findPalette } from './palettes.js';
20
20
  import { watchColors } from './mount.js';
21
21
 
22
22
  /**
23
23
  * @typedef {import('./scene.js').SceneConfig} SceneConfig
24
- * @typedef {import('@arraypress/shaders').SceneOptions} SceneOptions
24
+ * @typedef {import('@logomarks/shaders').SceneOptions} SceneOptions
25
25
  */
26
26
 
27
27
  /** The settings a `<Scene>` hands to its scene as they are: the look, the colours, the params, the frame rate and resolution. */
@@ -61,7 +61,7 @@ export function scene(el, config) {
61
61
  if (!canvas) return () => {};
62
62
  const { name, options } = sceneSettings(config);
63
63
  let stopped = false;
64
- /** @type {import('@arraypress/shaders').SceneHandle | null} */
64
+ /** @type {import('@logomarks/shaders').SceneHandle | null} */
65
65
  let handle = null;
66
66
  let unwatch = () => {};
67
67
  load(name)
@@ -9,3 +9,9 @@ export function splitLetters(el: HTMLElement): HTMLElement[];
9
9
 
10
10
  /** Puts letters split by `splitLetters` back as plain text. */
11
11
  export function joinLetters(el: HTMLElement): void;
12
+
13
+ /** Every non-empty text node inside `root`, at any depth, except those inside `skip`. */
14
+ export function textNodesWithin(root: Element, skip?: Element | null): Text[];
15
+
16
+ /** Draws text nodes into a 2D context (CSS px) glyph by glyph, each where the browser laid it out and in its own element's font, `origin` being the viewport point the context's 0, 0 stands for. */
17
+ export function paintGlyphs(ctx: CanvasRenderingContext2D, texts: Text[], origin: { x: number; y: number }): void;
@@ -6,7 +6,8 @@
6
6
  * all, whose box is the text's own extent rather than the element's, and
7
7
  * its letters, each in a span of its own, for effects that move or restyle
8
8
  * them one by one. Split letters stay real text: selectable, found by
9
- * search and read as words.
9
+ * search and read as words. For effects that redraw text into a canvas,
10
+ * `paintGlyphs` draws each glyph where the browser laid it out.
10
11
  */
11
12
 
12
13
  /** Marks a letter's span. */
@@ -88,3 +89,58 @@ export function joinLetters(el) {
88
89
  el.querySelectorAll(`[${LETTER}]`).forEach((span) => span.replaceWith(span.textContent ?? ''));
89
90
  el.normalize();
90
91
  }
92
+
93
+ /**
94
+ * Every non-empty text node inside an element, at any depth, except those
95
+ * inside `skip` (an effect's own element placed in the text).
96
+ *
97
+ * @param {Element} root The element.
98
+ * @param {Element | null} [skip] An element whose text is left out.
99
+ * @returns {Text[]} The text nodes, in document order.
100
+ */
101
+ export function textNodesWithin(root, skip = null) {
102
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
103
+ /** @type {Text[]} */
104
+ const texts = [];
105
+ while (walker.nextNode()) {
106
+ const node = /** @type {Text} */ (walker.currentNode);
107
+ if (!node.textContent?.trim()) continue;
108
+ if (skip && skip.contains(node)) continue;
109
+ texts.push(node);
110
+ }
111
+ return texts;
112
+ }
113
+
114
+ /**
115
+ * Draws text into a 2D context glyph by glyph, each where the browser laid
116
+ * it out (one Range a character), so letter-spacing, kerning and wrapping
117
+ * match the CSS. Each glyph takes its own element's font; the context's
118
+ * fill style is the ink.
119
+ *
120
+ * @param {CanvasRenderingContext2D} ctx The context, in CSS px.
121
+ * @param {Text[]} texts The text nodes to draw.
122
+ * @param {{ x: number, y: number }} origin The viewport point the context's 0, 0 stands for.
123
+ */
124
+ export function paintGlyphs(ctx, texts, origin) {
125
+ const range = document.createRange();
126
+ /** @type {Element | null} */
127
+ let parent = null;
128
+ ctx.textBaseline = 'alphabetic';
129
+ for (const text of texts) {
130
+ if (text.parentElement && text.parentElement !== parent) {
131
+ parent = text.parentElement;
132
+ const cs = getComputedStyle(parent);
133
+ ctx.font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
134
+ }
135
+ const str = text.textContent ?? '';
136
+ for (let i = 0; i < str.length; i++) {
137
+ const ch = str[i];
138
+ if (!ch.trim()) continue;
139
+ range.setStart(text, i);
140
+ range.setEnd(text, i + 1);
141
+ const r = range.getBoundingClientRect();
142
+ // The glyph's box starts at r.top; its baseline sits one font ascent below.
143
+ ctx.fillText(ch, r.left - origin.x, r.top - origin.y + ctx.measureText(ch).fontBoundingBoxAscent);
144
+ }
145
+ }
146
+ }