@arraypress/effects-astro 0.6.1 → 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.
package/AGENTS.md CHANGED
@@ -34,6 +34,7 @@ Pick by what is asked for:
34
34
  | A light or texture over a background (a spotlight, film grain) | `<GlowField>`, `<Grain>` (`still` for either to hold) |
35
35
  | The brand's logo as the hero's centrepiece | `<GlassGlyph>`, `<LiquidMetal>` (liquid chrome you can poke and splash; `tint="gold"`…), `<ParticleLogo>`, `<NeonSwarm>` (a flowing neon swarm), `<NebulaLogo>` (filled with nebula gas), `<VoxelLogo>`, `<PointCloud>`, all with `src="/logo.svg"` or `text` |
36
36
  | A footer wordmark | `<SpotlightText fit>`, `<PixelGlitchText fit>`, `<OutlineWordmark>` |
37
+ | Something retro or 8-bit on a footer: pixels firing out of it, sparks, "insert coin" | `<PixelFountain>` inside the footer (its top edge must not clip: `overflow-x: clip`, not `overflow: hidden`); `source="text"` sheds pixels from a wordmark; `color` or `colors` for the ramp |
37
38
  | Sections that arrive on scroll, site-wide | `<ScrollReveal />` once in the layout, then reveal.css classes (`fade-in-up`…) on elements |
38
39
  | A type foundry or bold brand headline: big variable-font letters that swell under the pointer | `<VariableType as="h1" fit>` set in a variable font (`axes` for which axes swell) |
39
40
  | Text that arrives or moves | `<Reveal>`, `<ScrambleText>`, `<Typewriter>`, `<HighlightSweep>`, `<Marquee>` |
@@ -58,6 +59,7 @@ Things that trip people up:
58
59
  - **Audio from another origin** needs CORS to be followed: `crossorigin="anonymous"` on the element (WaveformPlayer: `data-cross-origin="anonymous"`) and `Access-Control-Allow-Origin` on the server. Without it the effect keeps its own motion.
59
60
  - **`<Glass refract>` bends only in Chromium.** Safari and Firefox show the frosted glass instead; do not sniff browsers around it. It needs something detailed behind it (type, a photo) for the bending to show, and its bezel should be well under half the panel's shorter side.
60
61
  - **Clicks:** effects that react to clicks ignore links, buttons and form fields. Add `data-effect-ignore` to anything else whose clicks are its own.
62
+ - **`<PixelFountain>` draws above its host's top edge**, so a host with `overflow: hidden` clips it away. Use `overflow-x: clip` on the host, or put the fountain in a zero-height positioned strip on the edge and name the host with `host="…"`.
61
63
  - **`<SpotlightText fill="dodge">`** blends with what is behind it: no stacking context may sit between them (no `z-index` on a positioned ancestor, no `opacity`, `transform`, `filter` or `isolation`). Use `fill="solid"` where that cannot be arranged.
62
64
  - **Styling a component's element** from the page needs `:global(.its-class)`, since the element belongs to the component.
63
65
  - **`<Scene>` takes a palette by name** (`palette="Barbie"`); `@logomarks/shaders` itself takes the palette object (`PALETTES.Barbie`), never the name. Its `lazy` is the scene's own (a context held near the screen, given back four seconds after leaving on a fresh canvas), not `mount()`'s.
package/COMPONENTS.md CHANGED
@@ -847,6 +847,39 @@ ParticleLogo: a logo or a word in thousands of twinkling particles that scatter
847
847
  | `fixed` | `boolean` | Fill the viewport, behind the page (position: fixed, z-index -1). Default false. |
848
848
  | `class` | `string` | Classes for the element. |
849
849
 
850
+ ## `<PixelFountain>`
851
+
852
+ PixelFountain: retro 8-bit sparks. Chunky square pixels fire up out of the host's top edge (a footer) or, with `source="text"`, out of the letters of its wordmark, arc under gravity and break down as they go: through a short ramp of colours, shrinking in whole-pixel steps or splitting into pieces that scatter, some flickering out like a dying CRT pixel. A few trickle up on their own; the pointer moving over the host fires a stream, a click or tap a power-up. See src/runtime/pixel-fountain.js.
853
+
854
+ ```astro
855
+ <footer class="site-footer" style="position: relative">
856
+ <PixelFountain cell={8} />
857
+ …
858
+ </footer>
859
+ ```
860
+
861
+ | Prop | Type | |
862
+ |---|---|---|
863
+ | `color` | `string` | The pixels' colour when they fire; the darker steps they fade through are made from it. Default `#c8ff00`. |
864
+ | `colors` | `string[]` | The steps a pixel fades through, first to last (overrides `color`). Default made from `color`. |
865
+ | `palette` | `string` | A shared palette by name, its colours as the steps, when there are no `colors`. Default none. |
866
+ | `cell` | `number` | A pixel's size, CSS px (a power-up's biggest blocks are two). Default 8. |
867
+ | `rise` | `number` | How far above the edge the pixels can fly, CSS px. Default 240. |
868
+ | `rate` | `number` | Pixels a second trickling up on their own, per 1,000 CSS px of edge; 0 for none. Default 14. |
869
+ | `burst` | `number` | Pixels a click or tap fires. Default 40. |
870
+ | `gravity` | `number` | How hard they are pulled back, 0–2. Default 1. |
871
+ | `spread` | `number` | How widely they fan out, 0–1. Default 0.5. |
872
+ | `drift` | `number` | How much a wind pushes them sideways, 0–1. Default 0.3. |
873
+ | `life` | `number` | The longest a pixel lives, seconds. Default 1.4. |
874
+ | `split` | `number` | The chance a pixel splits into smaller ones rather than shrinking, 0–1. Default 0.4. |
875
+ | `flicker` | `number` | The chance a pixel flickers out on and off before it goes, 0–1. Default 0.35. |
876
+ | `source` | `'edge' \| 'text'` | Fire from the host's top edge, or from the filled pixels of its text. Default `edge`. |
877
+ | `host` | `string` | A selector for the element the pixels fire from and the pointer is followed over: the nearest ancestor that matches, else the first on the page. Default the element's positioned parent. |
878
+ | `seed` | `number` | Seeds the randomness. Default 1. |
879
+ | `zIndex` | `number` | The canvas's `z-index`, over what is above the host. Default none (auto). |
880
+ | `lazy` | `boolean \| string` | Run only while near the screen (true, or how near as a CSS length; default `200px`). Default false. |
881
+ | `class` | `string` | Classes for the element. |
882
+
850
883
  ## `<PixelGlitchText>`
851
884
 
852
885
  PixelGlitchText: one line of text that breaks into pixels under the pointer and knits back together behind it. With `stroke`, a hollow outline at rest that the pixels fill in; `tear="row"` tears whole rows, and `ghost` lays a coloured copy behind the blocks. See src/runtime/pixel-glitch.js.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @arraypress/effects-astro
2
2
 
3
- Effects for Astro sites, as components: shader backgrounds, a real fluid, logos made of glass, particles or cubes, text that glitches, scrambles or types itself, glass panels and marquees. Plain WebGL, Canvas and CSS with no third-party dependencies, and the fallbacks a theme needs built in.
3
+ Effects for Astro sites, as components: shader backgrounds, a real fluid, logos made of glass, particles or cubes, text that glitches, scrambles or types itself, retro pixels firing out of a footer, glass panels and marquees. Plain WebGL, Canvas and CSS with no third-party dependencies, and the fallbacks a theme needs built in.
4
4
 
5
5
  ## Install
6
6
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arraypress/effects-astro",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "GPU effects for Astro sites, as components: liquid light with a real fluid under it, ink in water, and outline text a spotlight fills. Plain WebGL, no third-party dependencies, with the fallbacks a theme needs (reduced motion, no WebGL, touch screens, off-screen pausing).",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -36,14 +36,17 @@ interface Props {
36
36
  lazy?: boolean | string;
37
37
  /** Fade the canvas in once it starts, over the `background`. Default false. */
38
38
  fadeIn?: boolean;
39
+ /** More inline style for the element (a component's own custom properties, a z-index). */
40
+ style?: string;
39
41
  class?: string;
40
42
  }
41
43
 
42
- const { name, config, fixed = false, behind = false, background, pixelated = false, fade = false, opacity, blend, lazy = false, fadeIn = false, class: className } = Astro.props;
44
+ const { name, config, fixed = false, behind = false, background, pixelated = false, fade = false, opacity, blend, lazy = false, fadeIn = false, style: extra, class: className } = Astro.props;
43
45
  const style = [
44
46
  background && `background: ${background}`,
45
47
  opacity !== undefined && opacity < 1 && `opacity: ${opacity}`,
46
48
  blend && blend !== 'normal' && `mix-blend-mode: ${blend}`,
49
+ extra?.trim().replace(/;$/, ''),
47
50
  ]
48
51
  .filter(Boolean)
49
52
  .join('; ');
@@ -0,0 +1,70 @@
1
+ ---
2
+ /**
3
+ * PixelFountain: retro 8-bit sparks. Chunky square pixels fire up out of
4
+ * the host's top edge (a footer) or, with `source="text"`, out of the
5
+ * letters of its wordmark, arc under gravity and break down as they go:
6
+ * through a short ramp of colours, shrinking in whole-pixel steps or
7
+ * splitting into pieces that scatter, some flickering out like a dying CRT
8
+ * pixel. A few trickle up on their own; the pointer moving over the host
9
+ * fires a stream, a click or tap a power-up. See
10
+ * src/runtime/pixel-fountain.js.
11
+ *
12
+ * Put it inside the host (its nearest positioned ancestor): the canvas sits
13
+ * above the host's top edge, `rise` px tall (over the host and above it
14
+ * with `source="text"`), so the host must not clip its top (no
15
+ * `overflow: hidden`; `overflow-x: clip` is fine). Or put it in a
16
+ * zero-height positioned strip on the host's top edge and name the host
17
+ * with `host`. The canvas takes no pointer events; the host's are read.
18
+ * With reduced motion, a still scatter of pixels.
19
+ *
20
+ * @example
21
+ * <footer class="site-footer" style="position: relative">
22
+ * <PixelFountain cell={8} />
23
+ * …
24
+ * </footer>
25
+ */
26
+ import EffectCanvas from './EffectCanvas.astro';
27
+ import type { PixelFountainConfig } from '../runtime/pixel-fountain.js';
28
+
29
+ interface Props extends PixelFountainConfig {
30
+ /** The canvas's `z-index`, over what is above the host. Default none (auto). */
31
+ zIndex?: number;
32
+ /** Run only while near the screen (true, or how near as a CSS length; default `200px`). Default false. */
33
+ lazy?: boolean | string;
34
+ class?: string;
35
+ }
36
+
37
+ const { zIndex, lazy = false, class: className, ...config } = Astro.props;
38
+ const rise = config.rise ?? 240;
39
+ const text = config.source === 'text';
40
+ const classes = ['effect-pixel-fountain', text && 'is-text', className].filter(Boolean).join(' ');
41
+ ---
42
+
43
+ <EffectCanvas
44
+ name="pixel-fountain"
45
+ config={config}
46
+ lazy={lazy}
47
+ pixelated
48
+ class={classes}
49
+ style={[`--fountain-rise: ${rise}px`, zIndex !== undefined && `z-index: ${zIndex}`].filter(Boolean).join('; ')}
50
+ />
51
+
52
+ <script>
53
+ import { mount } from '../runtime/mount.js';
54
+ import { pixelFountain } from '../runtime/pixel-fountain.js';
55
+
56
+ mount('[data-effect-pixel-fountain]', pixelFountain);
57
+ </script>
58
+
59
+ <style>
60
+ /* Above the host's top edge: the canvas's bottom on it, `rise` tall. Global, as the element is EffectCanvas's. */
61
+ :global(.effect-canvas.effect-pixel-fountain[data-effect-pixel-fountain]) {
62
+ inset: auto 0 100% 0;
63
+ height: var(--fountain-rise);
64
+ }
65
+ /* From the text: over the host and the space above it. */
66
+ :global(.effect-canvas.effect-pixel-fountain.is-text[data-effect-pixel-fountain]) {
67
+ inset: auto 0 0 0;
68
+ height: calc(100% + var(--fountain-rise));
69
+ }
70
+ </style>
package/src/index.d.ts CHANGED
@@ -18,8 +18,10 @@ export { voxelLogo } from './runtime/voxel-logo.js';
18
18
  export type { VoxelLogoConfig } from './runtime/voxel-logo.js';
19
19
  export { pixelGlitch, outlineAlpha, rowTears } from './runtime/pixel-glitch.js';
20
20
  export type { PixelGlitchConfig } from './runtime/pixel-glitch.js';
21
+ export { pixelFountain, createFountain, fadeSteps, shadeAt, tierSizes, pixelRect, inkedCells, MAX_PIXELS } from './runtime/pixel-fountain.js';
22
+ export type { PixelFountainConfig, Pixel, EmitKind, FountainOptions, Fountain } from './runtime/pixel-fountain.js';
21
23
  export { fit, fitText } from './runtime/fit-text.js';
22
- export { textNodes, textRange, splitLetters, joinLetters } from './runtime/text.js';
24
+ export { textNodes, textRange, splitLetters, joinLetters, textNodesWithin, paintGlyphs } from './runtime/text.js';
23
25
  export { variableType, DEFAULT_AXES } from './runtime/variable-type.js';
24
26
  export type { VariableTypeConfig, Axes } from './runtime/variable-type.js';
25
27
  export { dotGrid } from './runtime/dot-grid.js';
package/src/index.js CHANGED
@@ -21,8 +21,9 @@ export { particleLogo } from './runtime/particle-logo.js';
21
21
  export { pointCloud } from './runtime/point-cloud.js';
22
22
  export { voxelLogo } from './runtime/voxel-logo.js';
23
23
  export { pixelGlitch, outlineAlpha, rowTears } from './runtime/pixel-glitch.js';
24
+ export { pixelFountain, createFountain, fadeSteps, shadeAt, tierSizes, pixelRect, inkedCells, MAX_PIXELS } from './runtime/pixel-fountain.js';
24
25
  export { fit, fitText } from './runtime/fit-text.js';
25
- export { textNodes, textRange, splitLetters, joinLetters } from './runtime/text.js';
26
+ export { textNodes, textRange, splitLetters, joinLetters, textNodesWithin, paintGlyphs } from './runtime/text.js';
26
27
  export { variableType, DEFAULT_AXES } from './runtime/variable-type.js';
27
28
  export { dotGrid } from './runtime/dot-grid.js';
28
29
  export { signalLines, waveBars } from './runtime/waves.js';
@@ -0,0 +1,134 @@
1
+ export interface PixelFountainConfig {
2
+ /** The pixels' colour when they fire; the darker steps they fade through are made from it. Default `#c8ff00`. */
3
+ color?: string;
4
+ /** The steps a pixel fades through, first to last (overrides `color`). Default made from `color`. */
5
+ colors?: string[];
6
+ /** A shared palette by name, its colours as the steps, when there are no `colors`. Default none. */
7
+ palette?: string;
8
+ /** A pixel's size, CSS px (a power-up's biggest blocks are two). Default 8. */
9
+ cell?: number;
10
+ /** How far above the edge the pixels can fly, CSS px. Default 240. */
11
+ rise?: number;
12
+ /** Pixels a second trickling up on their own, per 1,000 CSS px of edge; 0 for none. Default 14. */
13
+ rate?: number;
14
+ /** Pixels a click or tap fires. Default 40. */
15
+ burst?: number;
16
+ /** How hard they are pulled back, 0–2. Default 1. */
17
+ gravity?: number;
18
+ /** How widely they fan out, 0–1. Default 0.5. */
19
+ spread?: number;
20
+ /** How much a wind pushes them sideways, 0–1. Default 0.3. */
21
+ drift?: number;
22
+ /** The longest a pixel lives, seconds. Default 1.4. */
23
+ life?: number;
24
+ /** The chance a pixel splits into smaller ones rather than shrinking, 0–1. Default 0.4. */
25
+ split?: number;
26
+ /** The chance a pixel flickers out on and off before it goes, 0–1. Default 0.35. */
27
+ flicker?: number;
28
+ /** Fire from the host's top edge, or from the filled pixels of its text. Default `edge`. */
29
+ source?: 'edge' | 'text';
30
+ /** A selector for the element the pixels fire from and the pointer is followed over: the nearest ancestor that matches, else the first on the page. Default the element's positioned parent. */
31
+ host?: string;
32
+ /** Seeds the randomness. Default 1. */
33
+ seed?: number;
34
+ }
35
+
36
+ /** One pixel of a fountain. */
37
+ export interface Pixel {
38
+ /** Centre, CSS px from the canvas's left and top. */
39
+ x: number;
40
+ y: number;
41
+ /** Velocity, CSS px/s (negative `vy` rises). */
42
+ vx: number;
43
+ vy: number;
44
+ /** Seconds lived, and seconds it lives. */
45
+ age: number;
46
+ life: number;
47
+ /** Its size: 0 a double block, 1 a block, 2 a half, 3 a quarter. */
48
+ tier: number;
49
+ /** The share of its life at which it next breaks down, and the share between breaks. */
50
+ next: number;
51
+ gap: number;
52
+ /** A power-up's pixel: its first frames burn white. */
53
+ hot: boolean;
54
+ /** The share of life from which it flickers (over 1 for never). */
55
+ flicker: number;
56
+ /** Whether it shows this frame. */
57
+ on: boolean;
58
+ /** Steps until it next flickers. */
59
+ blink: number;
60
+ /** Its own sideways push, CSS px/s². */
61
+ wobble: number;
62
+ }
63
+
64
+ /** What fired a pixel: the ambient trickle, the pointer moving, or a press (a power-up). */
65
+ export type EmitKind = 'ambient' | 'move' | 'burst';
66
+
67
+ /** A fountain's settings: the canvas's size and the effect's physics. */
68
+ export interface FountainOptions {
69
+ /** The canvas's size, CSS px. */
70
+ width: number;
71
+ height: number;
72
+ /** Where the edge is, CSS px down the canvas. Default its bottom. */
73
+ floor?: number;
74
+ cell?: number;
75
+ rise?: number;
76
+ rate?: number;
77
+ gravity?: number;
78
+ spread?: number;
79
+ drift?: number;
80
+ life?: number;
81
+ split?: number;
82
+ flicker?: number;
83
+ seed?: number;
84
+ }
85
+
86
+ /** A seeded pool of pixels, stepped at a fixed rate: `pixels[0…count)` are alive. */
87
+ export interface Fountain {
88
+ pixels: Pixel[];
89
+ readonly count: number;
90
+ /** Seconds stepped. */
91
+ readonly time: number;
92
+ resize(width: number, height: number, floor?: number): void;
93
+ /** Points (x, y pairs, tops first) the ambient pixels fire from instead of the edge, as `inkedCells` gives them. */
94
+ setOrigins(points: Float32Array | null, tops?: number): void;
95
+ /** Fires `n` pixels from a point; returns how many the pool had room for. */
96
+ emit(x: number, y: number, n: number, kind?: EmitKind): number;
97
+ /** Fires `n` pixels from the origins within `radius` of a point (a press with none near fires from the point). */
98
+ emitNear(x: number, y: number, n: number, kind?: EmitKind, radius?: number): number;
99
+ /** Fires `n` pixels from the edge, from the cell under `x`. */
100
+ emitEdge(x: number, n: number, kind?: EmitKind): number;
101
+ /** Fires `n` pixels from where the ambient ones fire. */
102
+ emitAmbient(n: number, kind?: EmitKind): number;
103
+ /** One step (default 1/60 s): the trickle, then every pixel ages, breaks down, moves and flickers. */
104
+ step(dt?: number): void;
105
+ /** Empties the pool. */
106
+ clear(): void;
107
+ }
108
+
109
+ /** The most pixels alive at once (400). */
110
+ export const MAX_PIXELS: number;
111
+
112
+ /** The simulation's fixed step, seconds (1/60). */
113
+ export const STEP: number;
114
+
115
+ /** The steps a pixel fades through, made from one colour in Oklab: darker and less saturated each step, turning a little towards olive. */
116
+ export function fadeSteps(color: string, count?: number): string[];
117
+
118
+ /** The colour step for a share of a pixel's life (one step per equal share), or -1 for a power-up's hot first frames. */
119
+ export function shadeAt(t: number, count: number, hot?: boolean): number;
120
+
121
+ /** Each tier's size in whole device pixels: the double block's, the block's, the half's and the quarter's. */
122
+ export function tierSizes(cell: number, dpr: number): number[];
123
+
124
+ /** Where a pixel is drawn (device px): its centre snapped to the grid of its own size, columns from the left and rows up from the floor. Returns its left and top. */
125
+ export function pixelRect(x: number, y: number, size: number, floor: number): [number, number];
126
+
127
+ /** The grid cells a picture of text fills (centre and most of four points round it inked), rows up from `floor`: centres as x, y pairs, tops first, and how many are tops. */
128
+ export function inkedCells(rgba: Uint8ClampedArray, width: number, height: number, cell: number, floor?: number): { points: Float32Array; tops: number };
129
+
130
+ /** Makes a seeded fountain of pixels. */
131
+ export function createFountain(options: FountainOptions): Fountain;
132
+
133
+ /** Starts the pixel fountain on an element placed over its host's top edge. Returns a function that stops it. */
134
+ export function pixelFountain(el: HTMLElement, config: PixelFountainConfig): () => void;
@@ -0,0 +1,730 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/pixel-fountain
3
+ *
4
+ * Retro 8-bit sparks: chunky square pixels fire up out of an element's top
5
+ * edge (a footer, a band) or out of the letters of a wordmark, arc under
6
+ * gravity with a little spread and a drifting wind, and break down as they
7
+ * go. Each steps through a short ramp of colours (an acid lime, a darker
8
+ * lime, olive, then gone), shrinks in whole-pixel steps (a double block, a
9
+ * block, half, a quarter) or splits into two to four smaller pixels that
10
+ * scatter, and some flicker on and off like a dying CRT pixel before they
11
+ * vanish. Every pixel is drawn on its size's grid, anchored to the edge,
12
+ * each frame, so motion reads as stepped rather than smooth.
13
+ *
14
+ * A few pixels trickle up on their own along the edge; moving the pointer
15
+ * over the host fires a stream from under it, and a click or tap fires a
16
+ * power-up: a bigger burst whose first frames burn white.
17
+ *
18
+ * The simulation (`createFountain`) is pure and seeded: it runs in fixed
19
+ * 60 Hz steps, so the same seed and the same emits give the same pixels
20
+ * whatever the frame rate. At most MAX_PIXELS live at once, in a pool that
21
+ * allocates nothing while it runs. Canvas 2D in device pixels, every
22
+ * rectangle on whole pixels, so the blocks stay crisp at any pixel ratio.
23
+ * Drawn only while near the screen and while the tab shows (the shared
24
+ * loop); with prefers-reduced-motion, a still scatter of pixels.
25
+ */
26
+
27
+ import { createCanvas2D } from './canvas2d.js';
28
+ import { parseColor, toHex, toOklab, fromOklab, mixOklab } from './color.js';
29
+ import { watchColors } from './mount.js';
30
+ import { pickColors } from './palettes.js';
31
+ import { pressAt } from './pointer.js';
32
+ import { seededRandom } from './random.js';
33
+ import { textNodesWithin, paintGlyphs } from './text.js';
34
+
35
+ /**
36
+ * @typedef {object} PixelFountainConfig
37
+ * @property {string} [color='#c8ff00'] The pixels' colour when they fire; the darker steps they fade through are made from it.
38
+ * @property {string[]} [colors] The steps a pixel fades through, first to last (overrides `color`).
39
+ * @property {string} [palette] A shared palette by name, its colours as the steps, when there are no `colors`.
40
+ * @property {number} [cell=8] A pixel's size, CSS px (a power-up's biggest blocks are two).
41
+ * @property {number} [rise=240] How far above the edge the pixels can fly, CSS px.
42
+ * @property {number} [rate=14] Pixels a second trickling up on their own, per 1,000 CSS px of edge; 0 for none.
43
+ * @property {number} [burst=40] Pixels a click or tap fires.
44
+ * @property {number} [gravity=1] How hard they are pulled back, 0–2.
45
+ * @property {number} [spread=0.5] How widely they fan out, 0–1.
46
+ * @property {number} [drift=0.3] How much a wind pushes them sideways, 0–1.
47
+ * @property {number} [life=1.4] The longest a pixel lives, seconds.
48
+ * @property {number} [split=0.4] The chance a pixel splits into smaller ones rather than shrinking, 0–1.
49
+ * @property {number} [flicker=0.35] The chance a pixel flickers out on and off before it goes, 0–1.
50
+ * @property {'edge' | 'text'} [source='edge'] Fire from the host's top edge, or from the filled pixels of its text.
51
+ * @property {string} [host] A selector for the element the pixels fire from and the pointer is followed over: the nearest ancestor that matches, else the first on the page. Default the element's positioned parent.
52
+ * @property {number} [seed=1] Seeds the randomness.
53
+ */
54
+
55
+ /** The most pixels alive at once. */
56
+ export const MAX_PIXELS = 400;
57
+
58
+ /** The simulation's fixed step, seconds (60 Hz). */
59
+ export const STEP = 1 / 60;
60
+
61
+ /** A pixel's sizes, in cells: a power-up's double block, a block, a half and a quarter. */
62
+ const TIER_CELLS = [2, 1, 0.5, 0.25];
63
+
64
+ /** The smallest tier. */
65
+ const LAST_TIER = TIER_CELLS.length - 1;
66
+
67
+ /** The pull, CSS px/s², at `gravity` 1. */
68
+ const GRAVITY = 1000;
69
+
70
+ /** How hard each kind of emit throws, a share of the throw that reaches 0.62 of `rise`. */
71
+ const POWER = { ambient: [0.5, 0.35], move: [0.62, 0.3], burst: [0.7, 0.6] };
72
+
73
+ /** How far into its flight a fired pixel may already be, seconds: a burst comes out as a spurt, not one slab. */
74
+ const LEAD = { ambient: 0, move: 0.06, burst: 0.3 };
75
+
76
+ /** The wind at `drift` 1, CSS px/s² (a slow swing either way). */
77
+ const WIND = 70;
78
+
79
+ /** Each pixel's own sideways push at `drift` 1, CSS px/s². */
80
+ const WOBBLE = 140;
81
+
82
+ /** How fast pieces of a split scatter, CSS px/s, at `spread` 0.5. */
83
+ const SCATTER = 110;
84
+
85
+ /** A power-up's first share of life, drawn in its hot colour. */
86
+ const HOT = 0.1;
87
+
88
+ /** How light the hot colour is: the first step mixed this far to white. */
89
+ const HOT_MIX = 0.6;
90
+
91
+ /**
92
+ * @typedef {object} Pixel
93
+ * @property {number} x Centre, CSS px from the canvas's left.
94
+ * @property {number} y Centre, CSS px from the canvas's top.
95
+ * @property {number} vx Velocity across, CSS px/s.
96
+ * @property {number} vy Velocity down, CSS px/s (negative rises).
97
+ * @property {number} age Seconds lived.
98
+ * @property {number} life Seconds it lives.
99
+ * @property {number} tier Its size: an index into the tiers (0 a double block, 3 a quarter).
100
+ * @property {number} next The share of its life at which it next breaks down.
101
+ * @property {number} gap The share of life between breaks.
102
+ * @property {boolean} hot A power-up's pixel: its first frames burn white.
103
+ * @property {number} flicker The share of life from which it flickers (over 1 for never).
104
+ * @property {boolean} on Whether it shows this frame (false while flickered off).
105
+ * @property {number} blink Steps until it next flickers.
106
+ * @property {number} wobble Its own sideways push, CSS px/s².
107
+ */
108
+
109
+ /**
110
+ * @typedef {object} FountainOptions
111
+ * @property {number} width The canvas's width, CSS px.
112
+ * @property {number} height The canvas's height, CSS px.
113
+ * @property {number} [floor] Where the edge is, CSS px down the canvas. Default its bottom.
114
+ * @property {number} [cell=8] A block's size, CSS px.
115
+ * @property {number} [rise=240] How far above the floor a full throw reaches, CSS px.
116
+ * @property {number} [rate=14] Ambient pixels a second per 1,000 CSS px of width.
117
+ * @property {number} [gravity=1] The pull, 0–2.
118
+ * @property {number} [spread=0.5] The fan, 0–1.
119
+ * @property {number} [drift=0.3] The wind, 0–1.
120
+ * @property {number} [life=1.4] The longest life, seconds.
121
+ * @property {number} [split=0.4] The chance of a split at each break, 0–1.
122
+ * @property {number} [flicker=0.35] The chance of flickering out, 0–1.
123
+ * @property {number} [seed=1] The seed.
124
+ */
125
+
126
+ /**
127
+ * @typedef {'ambient' | 'move' | 'burst'} EmitKind
128
+ */
129
+
130
+ /**
131
+ * The steps a pixel fades through, made from one colour in Oklab: darker
132
+ * and less saturated each step, the hue turning a little towards olive.
133
+ *
134
+ * @param {string} color The first step, CSS hex.
135
+ * @param {number} [count=4] How many steps.
136
+ * @returns {string[]} The steps, CSS hex, first to last.
137
+ * @throws {TypeError} When the colour is not hex.
138
+ */
139
+ export function fadeSteps(color, count = 4) {
140
+ const [L, a, b] = toOklab(parseColor(color));
141
+ const chroma = Math.hypot(a, b);
142
+ const hue = Math.atan2(b, a);
143
+ return Array.from({ length: Math.max(1, count) }, (_, k) => {
144
+ const t = count > 1 ? k / (count - 1) : 0;
145
+ const l = L * (1 - 0.55 * t);
146
+ const c = chroma * (1 - 0.5 * t);
147
+ const h = hue - ((16 * Math.PI) / 180) * t;
148
+ return toHex(fromOklab([l, c * Math.cos(h), c * Math.sin(h)]));
149
+ });
150
+ }
151
+
152
+ /**
153
+ * The colour a pixel is drawn in at a point in its life: one step of the
154
+ * ramp for each equal share of it (the first while new, the last as it
155
+ * goes), or the hot colour (-1) for a power-up's first frames.
156
+ *
157
+ * @param {number} t The share of its life lived, 0–1.
158
+ * @param {number} count How many steps.
159
+ * @param {boolean} [hot=false] A power-up's pixel.
160
+ * @returns {number} The step's index, or -1 for the hot colour.
161
+ */
162
+ export function shadeAt(t, count, hot = false) {
163
+ if (hot && t < HOT) return -1;
164
+ return Math.min(count - 1, Math.max(0, Math.floor(t * count)));
165
+ }
166
+
167
+ /**
168
+ * Each tier's size in device pixels: whole pixels, at least one, so every
169
+ * block lands on the device's own grid.
170
+ *
171
+ * @param {number} cell A block's size, CSS px.
172
+ * @param {number} dpr Device pixels a CSS px.
173
+ * @returns {number[]} The double block's, the block's, the half's and the quarter's sizes.
174
+ */
175
+ export function tierSizes(cell, dpr) {
176
+ const block = Math.max(1, Math.round(cell * dpr));
177
+ return TIER_CELLS.map((k) => Math.max(1, Math.round(block * k)));
178
+ }
179
+
180
+ /**
181
+ * Where a pixel is drawn: its centre snapped to the grid of its own size,
182
+ * the grid's columns counted from the left and its rows up from the floor,
183
+ * so a block resting on the edge sits flush on it and every move is a
184
+ * whole step of the grid.
185
+ *
186
+ * @param {number} x Centre, across (device px).
187
+ * @param {number} y Centre, down (device px).
188
+ * @param {number} size Its size (device px, whole).
189
+ * @param {number} floor The edge, down (device px, whole).
190
+ * @returns {[number, number]} The block's left and top.
191
+ */
192
+ export function pixelRect(x, y, size, floor) {
193
+ const col = Math.round(x / size - 0.5);
194
+ const row = Math.round((floor - y) / size - 0.5);
195
+ // + 0 turns a -0 (a centre just left of the first column) into 0.
196
+ return [col * size + 0, floor - (row + 1) * size + 0];
197
+ }
198
+
199
+ /**
200
+ * The cells of a grid that a picture of text fills, for firing from the
201
+ * letters: each cell whose centre and most of four points round it are
202
+ * inked. The grid's columns run from the left and its rows up from the
203
+ * floor, as the pixels' do. Tops (filled cells with an empty one above)
204
+ * are listed first.
205
+ *
206
+ * @param {Uint8ClampedArray} rgba The picture, RGBA (only alpha is read), one pixel a CSS px.
207
+ * @param {number} width Its width.
208
+ * @param {number} height Its height.
209
+ * @param {number} cell The grid's cell, CSS px.
210
+ * @param {number} [floor=height] The grid's bottom, px down the picture.
211
+ * @returns {{ points: Float32Array, tops: number }} Cell centres as x, y pairs (tops first), and how many are tops.
212
+ */
213
+ export function inkedCells(rgba, width, height, cell, floor = height) {
214
+ const cols = Math.floor(width / cell);
215
+ const rows = Math.floor(floor / cell);
216
+ /**
217
+ * Is the picture inked at a point?
218
+ *
219
+ * @param {number} x Across, px.
220
+ * @param {number} y Down, px.
221
+ * @returns {number} 1 if so, else 0.
222
+ */
223
+ const at = (x, y) => {
224
+ const px = Math.min(width - 1, Math.max(0, Math.floor(x)));
225
+ const py = Math.min(height - 1, Math.max(0, Math.floor(y)));
226
+ return rgba[(py * width + px) * 4 + 3] > 127 ? 1 : 0;
227
+ };
228
+ const q = cell / 4;
229
+ const filled = new Uint8Array(cols * rows);
230
+ for (let row = 0; row < rows; row++) {
231
+ for (let col = 0; col < cols; col++) {
232
+ const cx = col * cell + cell / 2;
233
+ const cy = floor - row * cell - cell / 2;
234
+ const around = at(cx - q, cy - q) + at(cx + q, cy - q) + at(cx - q, cy + q) + at(cx + q, cy + q);
235
+ filled[row * cols + col] = at(cx, cy) && around >= 2 ? 1 : 0;
236
+ }
237
+ }
238
+ /** @type {number[]} */
239
+ const tops = [];
240
+ /** @type {number[]} */
241
+ const rest = [];
242
+ for (let row = 0; row < rows; row++) {
243
+ for (let col = 0; col < cols; col++) {
244
+ if (!filled[row * cols + col]) continue;
245
+ const above = row + 1 < rows && filled[(row + 1) * cols + col];
246
+ (above ? rest : tops).push(col * cell + cell / 2, floor - row * cell - cell / 2);
247
+ }
248
+ }
249
+ return { points: Float32Array.from([...tops, ...rest]), tops: tops.length / 2 };
250
+ }
251
+
252
+ /**
253
+ * Makes a fountain: a seeded pool of pixels, stepped at a fixed rate.
254
+ *
255
+ * @param {FountainOptions} options The settings.
256
+ * @returns {{
257
+ * pixels: Pixel[],
258
+ * readonly count: number,
259
+ * readonly time: number,
260
+ * resize: (width: number, height: number, floor?: number) => void,
261
+ * setOrigins: (points: Float32Array | null, tops?: number) => void,
262
+ * emit: (x: number, y: number, n: number, kind?: EmitKind) => number,
263
+ * emitNear: (x: number, y: number, n: number, kind?: EmitKind, radius?: number) => number,
264
+ * emitEdge: (x: number, n: number, kind?: EmitKind) => number,
265
+ * emitAmbient: (n: number, kind?: EmitKind) => number,
266
+ * step: (dt?: number) => void,
267
+ * clear: () => void,
268
+ * }} The fountain: `pixels[0…count)` are alive.
269
+ */
270
+ export function createFountain(options) {
271
+ const CELL = options.cell ?? 8;
272
+ const RISE = options.rise ?? 240;
273
+ const RATE = options.rate ?? 14;
274
+ const G = GRAVITY * (options.gravity ?? 1);
275
+ const SPREAD = options.spread ?? 0.5;
276
+ const DRIFT = options.drift ?? 0.3;
277
+ const LIFE = options.life ?? 1.4;
278
+ const SPLIT = options.split ?? 0.4;
279
+ const FLICKER = options.flicker ?? 0.35;
280
+ const random = seededRandom(options.seed ?? 1);
281
+ // The throw that reaches 0.62 of `rise` at the nominal pull, whatever `gravity` is: gravity changes the arc, not the throw.
282
+ const THROW = Math.sqrt(2 * GRAVITY * RISE * 0.62);
283
+ const sizes = TIER_CELLS.map((k) => CELL * k);
284
+
285
+ let width = options.width;
286
+ let height = options.height;
287
+ let floor = options.floor ?? options.height;
288
+ let count = 0;
289
+ let time = 0;
290
+ let owed = 0;
291
+ /** @type {Float32Array | null} */
292
+ let origins = null;
293
+ let topCount = 0;
294
+
295
+ /** @type {Pixel[]} */
296
+ const pixels = Array.from({ length: MAX_PIXELS }, () => ({
297
+ x: 0,
298
+ y: 0,
299
+ vx: 0,
300
+ vy: 0,
301
+ age: 0,
302
+ life: 1,
303
+ tier: 1,
304
+ next: 2,
305
+ gap: 1,
306
+ hot: false,
307
+ flicker: 2,
308
+ on: true,
309
+ blink: 0,
310
+ wobble: 0,
311
+ }));
312
+
313
+ /**
314
+ * Sets a pixel's break-downs from its tier: evenly from about a third
315
+ * of its life (a fifth for a double block).
316
+ *
317
+ * @param {Pixel} p The pixel.
318
+ */
319
+ const schedule = (p) => {
320
+ const left = LAST_TIER - p.tier;
321
+ if (left <= 0) {
322
+ p.next = 2;
323
+ return;
324
+ }
325
+ const first = (p.tier === 0 ? 0.18 : 0.3) + random() * 0.12;
326
+ p.next = first;
327
+ // The last break late (about four fifths of the way), so the smallest pieces only flash before they go.
328
+ p.gap = (1.2 - first) / left;
329
+ };
330
+
331
+ /**
332
+ * Brings a pixel to life from the pool.
333
+ *
334
+ * @param {number} x Centre, across, CSS px.
335
+ * @param {number} y Centre, down, CSS px.
336
+ * @param {EmitKind} kind What fired it.
337
+ * @returns {boolean} False when the pool is full.
338
+ */
339
+ const spawn = (x, y, kind) => {
340
+ if (count >= MAX_PIXELS) return false;
341
+ const p = pixels[count++];
342
+ const [base, range] = POWER[kind];
343
+ const speed = THROW * (base + random() * range);
344
+ const fan = kind === 'burst' ? 2 : 1;
345
+ p.x = x;
346
+ p.y = y;
347
+ p.vx = (random() * 2 - 1) * SPREAD * fan * speed * 0.5;
348
+ p.vy = -speed;
349
+ p.age = 0;
350
+ // Gone before it lands: a flight's length at most, so each runs through its colours in the air.
351
+ const flight = G > 0 ? (2 * speed) / G : Infinity;
352
+ p.life = Math.min(LIFE * (0.6 + random() * 0.4), flight * (0.85 + random() * 0.2));
353
+ const roll = random();
354
+ p.tier = kind === 'burst' ? (roll < 0.4 ? 0 : 1) : kind === 'move' ? (roll < 0.15 ? 0 : 1) : roll < 0.7 ? 1 : 2;
355
+ schedule(p);
356
+ p.hot = kind === 'burst';
357
+ p.flicker = random() < FLICKER ? 0.45 + random() * 0.3 : 2;
358
+ p.on = true;
359
+ p.blink = 0;
360
+ p.wobble = (random() * 2 - 1) * DRIFT * WOBBLE;
361
+ // Some way into its flight already, as if fired a moment ago.
362
+ const lead = random() * LEAD[kind];
363
+ p.x += p.vx * lead;
364
+ p.y += p.vy * lead + 0.5 * G * lead * lead;
365
+ p.vy += G * lead;
366
+ p.age = Math.min(lead, p.life * 0.5);
367
+ return true;
368
+ };
369
+
370
+ /**
371
+ * Breaks a pixel down a tier: it shrinks where it is, or (by `split`'s
372
+ * chance, room allowing) splits into two to four of the quarters of
373
+ * itself, each thrown outward from where it sat.
374
+ *
375
+ * @param {Pixel} p The pixel.
376
+ */
377
+ const breakDown = (p) => {
378
+ const was = sizes[p.tier];
379
+ p.tier++;
380
+ p.next += p.gap;
381
+ if (random() >= SPLIT || count >= MAX_PIXELS) return;
382
+ const pieces = Math.min(2 + Math.floor(random() * 3), 1 + MAX_PIXELS - count);
383
+ // The four quarters, in a shuffled order; the pixel keeps the first.
384
+ const quarters = [
385
+ [-1, -1],
386
+ [1, -1],
387
+ [-1, 1],
388
+ [1, 1],
389
+ ];
390
+ for (let i = 3; i > 0; i--) {
391
+ const j = Math.floor(random() * (i + 1));
392
+ [quarters[i], quarters[j]] = [quarters[j], quarters[i]];
393
+ }
394
+ const scatter = SCATTER * (0.5 + SPREAD);
395
+ const cx = p.x;
396
+ const cy = p.y;
397
+ for (let k = 0; k < pieces; k++) {
398
+ const q = k === 0 ? p : pixels[count++];
399
+ if (q !== p) {
400
+ Object.assign(q, p);
401
+ q.flicker = random() < FLICKER ? Math.max(p.age / p.life, 0.45 + random() * 0.3) : 2;
402
+ q.wobble = (random() * 2 - 1) * DRIFT * WOBBLE;
403
+ }
404
+ const [qx, qy] = quarters[k];
405
+ q.x = cx + (qx * was) / 4;
406
+ q.y = cy + (qy * was) / 4;
407
+ q.vx = p.vx + qx * scatter * (0.4 + random() * 0.6);
408
+ q.vy = p.vy + qy * scatter * (0.2 + random() * 0.5) - scatter * 0.3;
409
+ }
410
+ };
411
+
412
+ /**
413
+ * Returns a pixel to the pool: the last live one takes its place.
414
+ *
415
+ * @param {number} i Its index.
416
+ */
417
+ const kill = (i) => {
418
+ count--;
419
+ if (i !== count) [pixels[i], pixels[count]] = [pixels[count], pixels[i]];
420
+ };
421
+
422
+ /**
423
+ * A random place for an ambient pixel: on a letter's top (mostly) or
424
+ * anywhere in it when there are origins, else along the edge.
425
+ *
426
+ * @returns {[number, number]} Its centre, CSS px.
427
+ */
428
+ const ambientAt = () => {
429
+ if (origins && origins.length) {
430
+ const n = origins.length / 2;
431
+ const i = topCount && random() < 0.8 ? Math.floor(random() * topCount) : Math.floor(random() * n);
432
+ return [origins[i * 2], origins[i * 2 + 1]];
433
+ }
434
+ const col = Math.floor((random() * width) / CELL);
435
+ return [col * CELL + CELL / 2, floor - CELL / 2];
436
+ };
437
+
438
+ return {
439
+ pixels,
440
+ get count() {
441
+ return count;
442
+ },
443
+ get time() {
444
+ return time;
445
+ },
446
+ resize(w, h, f = h) {
447
+ width = w;
448
+ height = h;
449
+ floor = f;
450
+ },
451
+ setOrigins(points, tops = 0) {
452
+ origins = points;
453
+ topCount = tops;
454
+ },
455
+ emit(x, y, n, kind = 'burst') {
456
+ const jitter = (kind === 'burst' ? 2.5 : kind === 'move' ? 1 : 0) * CELL;
457
+ let made = 0;
458
+ for (let i = 0; i < n; i++) {
459
+ if (!spawn(x + (random() * 2 - 1) * jitter, y, kind)) break;
460
+ made++;
461
+ }
462
+ return made;
463
+ },
464
+ emitNear(x, y, n, kind = 'burst', radius = 80) {
465
+ if (!origins || !origins.length) return this.emit(x, y, n, kind);
466
+ /** @type {number[]} */
467
+ const near = [];
468
+ for (let i = 0; i < origins.length; i += 2) {
469
+ if (Math.hypot(origins[i] - x, origins[i + 1] - y) <= radius) near.push(i);
470
+ }
471
+ // Nothing to fire from near a move; a press fires where it landed.
472
+ if (!near.length) return kind === 'burst' ? this.emit(x, y, n, kind) : 0;
473
+ let made = 0;
474
+ for (let k = 0; k < n; k++) {
475
+ const i = near[Math.floor(random() * near.length)];
476
+ if (!spawn(origins[i], origins[i + 1], kind)) break;
477
+ made++;
478
+ }
479
+ return made;
480
+ },
481
+ emitEdge(x, n, kind = 'burst') {
482
+ return this.emit(Math.floor(x / CELL) * CELL + CELL / 2, floor - CELL / 2, n, kind);
483
+ },
484
+ emitAmbient(n, kind = 'ambient') {
485
+ let made = 0;
486
+ for (let i = 0; i < n; i++) {
487
+ const [x, y] = ambientAt();
488
+ if (!spawn(x, y, kind)) break;
489
+ made++;
490
+ }
491
+ return made;
492
+ },
493
+ step(dt = STEP) {
494
+ time += dt;
495
+ owed += ((RATE * width) / 1000) * dt;
496
+ // A hair under one counts: sixty steps of a sixtieth must make a whole pixel.
497
+ while (owed >= 1 - 1e-9) {
498
+ owed--;
499
+ const [x, y] = ambientAt();
500
+ spawn(x, y, 'ambient');
501
+ }
502
+ const wind = DRIFT * WIND * Math.sin(time * 0.7) * Math.cos(time * 0.23);
503
+ const drag = 1 - 0.6 * dt;
504
+ for (let i = 0; i < count; i++) {
505
+ const p = pixels[i];
506
+ p.age += dt;
507
+ const t = p.age / p.life;
508
+ if (t >= 1) {
509
+ kill(i--);
510
+ continue;
511
+ }
512
+ while (t >= p.next && p.tier < LAST_TIER) breakDown(p);
513
+ p.vy += G * dt;
514
+ p.vx = (p.vx + (wind + p.wobble) * dt) * drag;
515
+ p.x += p.vx * dt;
516
+ p.y += p.vy * dt;
517
+ const half = sizes[p.tier] / 2;
518
+ // Fallen back into the edge, or off the sides.
519
+ if ((p.vy > 0 && p.y - half > floor) || p.x < -half || p.x > width + half) {
520
+ kill(i--);
521
+ continue;
522
+ }
523
+ if (t >= p.flicker && --p.blink <= 0) {
524
+ // A dying pixel: on for a shorter while, off for a longer, the nearer its end.
525
+ p.on = !p.on;
526
+ p.blink = p.on ? 1 + Math.floor(random() * 4 * (1 - t) + 1) : 1 + Math.floor(random() * 3 + t * 4);
527
+ }
528
+ }
529
+ },
530
+ clear() {
531
+ count = 0;
532
+ owed = 0;
533
+ },
534
+ };
535
+ }
536
+
537
+ /**
538
+ * The element the pixels fire from: the nearest ancestor matching
539
+ * `selector`, else the first match on the page, else the element's
540
+ * positioned parent (or its parent).
541
+ *
542
+ * @param {HTMLElement} el The effect's element.
543
+ * @param {string} [selector] The host's selector.
544
+ * @returns {HTMLElement} The host.
545
+ */
546
+ function findHost(el, selector) {
547
+ if (selector) {
548
+ const found = el.parentElement?.closest(selector) ?? document.querySelector(selector);
549
+ if (found instanceof HTMLElement) return found;
550
+ console.warn('[effects-astro]', `PixelFountain: no host "${selector}"; using its parent`);
551
+ }
552
+ return /** @type {HTMLElement} */ (el.offsetParent ?? el.parentElement ?? el);
553
+ }
554
+
555
+ /**
556
+ * Starts the pixel fountain on an element (its first canvas is drawn
557
+ * into). The element should be positioned over its host's top edge (or,
558
+ * with `source: 'text'`, over the host and the space above it), with its
559
+ * bottom on the host's bottom edge: the component does this.
560
+ *
561
+ * @param {HTMLElement} el The element.
562
+ * @param {PixelFountainConfig} config The settings.
563
+ * @returns {() => void} Stops it.
564
+ */
565
+ export function pixelFountain(el, config) {
566
+ const CELL = Math.max(2, config.cell ?? 8);
567
+ const BURST = config.burst ?? 40;
568
+ const TEXT = config.source === 'text';
569
+ const host = findHost(el, config.host);
570
+ const fountain = createFountain({ ...config, cell: CELL, width: 1, height: 1 });
571
+
572
+ let steps = pickColors(config, fadeSteps(config.color ?? '#c8ff00'));
573
+ let hot = '';
574
+ /**
575
+ * Takes a new set of steps, and the hot colour from the first.
576
+ *
577
+ * @param {string[]} next The steps.
578
+ */
579
+ const recolor = (next) => {
580
+ steps = next;
581
+ try {
582
+ hot = toHex(mixOklab(parseColor(steps[0]), [1, 1, 1], HOT_MIX));
583
+ } catch {
584
+ hot = steps[0];
585
+ }
586
+ };
587
+ recolor(steps);
588
+ const unwatch = watchColors(el, ({ colors }) => recolor(colors));
589
+
590
+ let acc = 0;
591
+ let stopped = false;
592
+ /** @type {import('./canvas2d.js').Canvas2D | null} */
593
+ let canvas2d = null;
594
+
595
+ /** Reads the letters' filled cells (with `source: 'text'`), in the canvas's CSS px. */
596
+ const readText = () => {
597
+ const c = canvas2d;
598
+ if (!TEXT || !c || stopped) return;
599
+ const texts = textNodesWithin(host, el);
600
+ const w = Math.max(1, Math.round(c.width));
601
+ const h = Math.max(1, Math.round(c.height));
602
+ const scratch = document.createElement('canvas');
603
+ scratch.width = w;
604
+ scratch.height = h;
605
+ const ctx = scratch.getContext('2d', { willReadFrequently: true });
606
+ if (!ctx) return;
607
+ const box = c.canvas.getBoundingClientRect();
608
+ ctx.fillStyle = '#000';
609
+ paintGlyphs(ctx, texts, { x: box.left, y: box.top });
610
+ const { points, tops } = inkedCells(ctx.getImageData(0, 0, w, h).data, w, h, CELL);
611
+ fountain.setOrigins(points, tops);
612
+ if (c.still) scatter(c);
613
+ };
614
+
615
+ /**
616
+ * With reduced motion: a still scatter, the fountain run on its own
617
+ * for a moment from its seed and held.
618
+ *
619
+ * @param {import('./canvas2d.js').Canvas2D} c The canvas.
620
+ */
621
+ const scatter = (c) => {
622
+ fountain.clear();
623
+ for (let i = 0; i < 90; i++) {
624
+ fountain.step();
625
+ if (i % 5 === 0) fountain.emitAmbient(1, 'move');
626
+ }
627
+ render(c);
628
+ };
629
+
630
+ /**
631
+ * Draws the live pixels, each on its own grid in device pixels.
632
+ *
633
+ * @param {import('./canvas2d.js').Canvas2D} c The canvas.
634
+ */
635
+ const render = (c) => {
636
+ const { ctx, dpr } = c;
637
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
638
+ ctx.clearRect(0, 0, c.canvas.width, c.canvas.height);
639
+ const sizes = tierSizes(CELL, dpr);
640
+ const floor = c.canvas.height;
641
+ const n = steps.length;
642
+ let fill = '';
643
+ for (let i = 0; i < fountain.count; i++) {
644
+ const p = fountain.pixels[i];
645
+ if (!p.on) continue;
646
+ const shade = shadeAt(p.age / p.life, n, p.hot);
647
+ const color = shade < 0 ? hot : steps[shade];
648
+ if (color !== fill) ctx.fillStyle = fill = color;
649
+ const size = sizes[p.tier];
650
+ const [x, y] = pixelRect(p.x * dpr, p.y * dpr, size, floor);
651
+ ctx.fillRect(x, y, size, size);
652
+ }
653
+ };
654
+
655
+ const { c, stop } = createCanvas2D(el, {
656
+ resize(c) {
657
+ canvas2d = c;
658
+ fountain.resize(c.width, c.height);
659
+ if (TEXT) readText();
660
+ else if (c.still) scatter(c);
661
+ },
662
+ draw(c, _now, dt) {
663
+ if (c.still) return render(c);
664
+ acc = Math.min(acc + dt, STEP * 4);
665
+ while (acc >= STEP) {
666
+ fountain.step();
667
+ acc -= STEP;
668
+ }
669
+ render(c);
670
+ },
671
+ });
672
+ if (!c) {
673
+ unwatch();
674
+ return () => {};
675
+ }
676
+ if (TEXT) document.fonts?.ready.then(readText).catch(() => {});
677
+
678
+ /** The pointer's last place over the host, viewport px, to fire along its path. */
679
+ let last = /** @type {{ x: number, y: number } | null} */ (null);
680
+ let travel = 0;
681
+
682
+ /**
683
+ * Fires pixels from under a point.
684
+ *
685
+ * @param {number} clientX Viewport x.
686
+ * @param {number} clientY Viewport y.
687
+ * @param {number} n How many.
688
+ * @param {EmitKind} kind What fired them.
689
+ */
690
+ const fireAt = (clientX, clientY, n, kind) => {
691
+ const box = c.canvas.getBoundingClientRect();
692
+ const x = clientX - box.left;
693
+ if (TEXT) fountain.emitNear(x, clientY - box.top, n, kind, kind === 'burst' ? 110 : 60);
694
+ else fountain.emitEdge(x, n, kind);
695
+ };
696
+
697
+ /** @param {PointerEvent} e The move. */
698
+ const move = (e) => {
699
+ if (last) travel += Math.hypot(e.clientX - last.x, e.clientY - last.y);
700
+ last = { x: e.clientX, y: e.clientY };
701
+ const n = Math.min(8, Math.floor(travel / 10));
702
+ if (!n) return;
703
+ travel -= n * 10;
704
+ fireAt(e.clientX, e.clientY, n, 'move');
705
+ };
706
+ /** Forgets the pointer's path when it leaves the host. */
707
+ const leave = () => {
708
+ last = null;
709
+ travel = 0;
710
+ };
711
+ /** @param {PointerEvent} e The press. */
712
+ const press = (e) => {
713
+ if (!pressAt(host, e)) return;
714
+ fireAt(e.clientX, e.clientY, BURST, 'burst');
715
+ };
716
+ if (!c.still) {
717
+ host.addEventListener('pointermove', move, { passive: true });
718
+ host.addEventListener('pointerleave', leave);
719
+ host.addEventListener('pointerdown', press);
720
+ }
721
+
722
+ return () => {
723
+ stopped = true;
724
+ host.removeEventListener('pointermove', move);
725
+ host.removeEventListener('pointerleave', leave);
726
+ host.removeEventListener('pointerdown', press);
727
+ unwatch();
728
+ stop();
729
+ };
730
+ }
@@ -37,7 +37,7 @@
37
37
  */
38
38
 
39
39
  import { canHover, prefersReducedMotion } from './device.js';
40
- import { textNodes } from './text.js';
40
+ import { textNodes, paintGlyphs } from './text.js';
41
41
 
42
42
  /**
43
43
  * @typedef {object} PixelGlitchConfig
@@ -280,29 +280,7 @@ export function pixelGlitch(el, config) {
280
280
  c2.setTransform(dpr, 0, 0, dpr, 0, 0);
281
281
  c2.clearRect(0, 0, g.w, g.h);
282
282
  c2.fillStyle = g.ink;
283
- c2.font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
284
- c2.textBaseline = 'alphabetic';
285
- const range = document.createRange();
286
- /**
287
- * Draws every glyph where the browser laid it out.
288
- *
289
- * @param {(ch: string, x: number, y: number) => void} glyph Draws one glyph at a baseline position.
290
- */
291
- const eachGlyph = (glyph) => {
292
- for (const text of texts) {
293
- const str = text.textContent ?? '';
294
- for (let i = 0; i < str.length; i++) {
295
- const ch = str[i];
296
- if (!ch.trim()) continue;
297
- range.setStart(text, i);
298
- range.setEnd(text, i + 1);
299
- const r = range.getBoundingClientRect();
300
- // The glyph's box starts at r.top; its baseline sits one font ascent below.
301
- glyph(ch, r.left - origin.x, r.top - origin.y + c2.measureText(ch).fontBoundingBoxAscent);
302
- }
303
- }
304
- };
305
- eachGlyph((ch, x, y) => c2.fillText(ch, x, y));
283
+ paintGlyphs(c2, texts, origin);
306
284
  g.alpha = c2.getImageData(0, 0, crisp.width, crisp.height).data;
307
285
  if (STROKE > 0) {
308
286
  // The pixels still sample the solid letters (g.alpha); what shows at rest is their outline, in the ink.
@@ -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
+ }