@arraypress/effects-astro 0.2.0 → 0.3.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
@@ -13,6 +13,8 @@ Pick by what is asked for:
13
13
  | An animated, colourful background for a page or hero | `<LightField>` (liquid light), `<FlutedGlass>` (light, gallery-white or dark), `<AsciiRain>` (techy, dark), `<DotGrid>` (quiet, minimal), `<SignalLines>` / `<WaveBars>` (audio) |
14
14
  | Ink in water, a lit fluid background, or a hero whose colours a palette switcher changes | `<InkField palette="…">` (Lumetri, Forest, Cadmium, Peacock, Vermillion, Barbie, Uranium, Azure, Ruby, Ultramarine, Saffron, Crimson); `setColors(el, INK_PALETTES[name].colors, INK_PALETTES[name].glint)` recolours it live |
15
15
  | Something to play with: ink, smoke, liquid, "interactive" | `<Ink>` over a section, or `<LightField>` (it has the fluid under it), or `<DotGrid>` (click ripples) |
16
+ | A soft gradient that drifts (a card, a hero, a section) — "grainy gradient", "mesh", "aurora" | `<LiveGradient colors={[…]}>` (lazy by default; `liveGradient(colors)` for HTML made in a script) |
17
+ | Smoke or ink on a light page | `<Ink dark colors={[…]}>` (dark dye alone barely shows) |
16
18
  | Panels of colour fanning out of the dark, a bold launch or fintech hero with depth | `<ColorPanels>` (Opening by default; `preset="Glass"`, `"Default"` or `"Gradient"`; `palette` or `colors`, `quiet` behind copy) |
17
19
  | A gradient, noise, halftone or liquid-metal look by name | `<PaperShader shader="…" preset="…">`; the demo has a hero for every shader, its presets in the tag |
18
20
  | A themed hero background by name (mesh gradient, grainy gradient, silk, light bands, synthwave grid, neon waves), tinted from the site's accent | `<ShaderBackground effect="…">`; `static` when it sits behind body copy or is `fixed` |
@@ -44,6 +46,8 @@ Pick by what is asked for:
44
46
 
45
47
  Things that trip people up:
46
48
 
49
+ - **Many effects on one page** (a wall of cards, a long list): mark them `lazy` (or use `whenNear`). A browser keeps about sixteen WebGL contexts and silently drops the oldest past that.
50
+
47
51
  - **`fixed` backgrounds need a transparent `body`.** They sit at `z-index: -1` behind the page: `body { background: transparent }` and paint the page colour on `html`.
48
52
  - **Non-fixed effects fill their nearest positioned ancestor.** Give the section `position: relative`, and put the effect before the content.
49
53
  - **Headlines over a busy background:** pass `quiet` (`<LightField>`, `<AsciiRain>`) so it dims behind them.
package/COMPONENTS.md CHANGED
@@ -415,6 +415,8 @@ Ink: ink in water over whatever is behind it. The pointer stirs it and trails in
415
415
  | `momentum` | `number` | How fast the motion dies away, per second (lower flows on longer). Default 0.25. |
416
416
  | `opacity` | `number` | The ink's strongest cover, 0–1. Default 1. |
417
417
  | `idle` | `number` | Seconds between drops of ink on their own, so it moves before anyone touches it; 0 for none. They wait while it's off screen or the tab is hidden. Default 0. |
418
+ | `dark` | `boolean` | Ink for a light ground: the colours given are laid dark on light (dark dye alone would barely show). Default false. |
419
+ | `lazy` | `boolean \| string` | Run only while near the screen (true, or a CSS length; default `200px`), handled by `mount`. Default false. |
418
420
  | `ignore` | `string` | Clicks on these are theirs, not the ink's. Default: links, buttons, form fields and `[data-effect-ignore]`. |
419
421
  | `fixed` | `boolean` | Fill the viewport (position: fixed). Default false. |
420
422
  | `class` | `string` | Classes for the element. |
@@ -528,6 +530,27 @@ LiquidMetal: a logo or a word made of liquid chrome. At rest it is a polished sl
528
530
  | `fixed` | `boolean` | Fill the viewport, behind the page (position: fixed, z-index -1). Default false. |
529
531
  | `class` | `string` | Classes for the element. |
530
532
 
533
+ ## `<LiveGradient>`
534
+
535
+ LiveGradient: a gradient that's alive — Paper's mesh gradient in your colours, morphing slowly, with film grain over it. Subtle by default (a sixth of Paper's speed, a gentle swirl), so it sits behind a card, a hero or a section without pulling the eye. The same colours show as a still CSS gradient first (and without WebGL); the live one fades in over it. Lazy by default: it runs only while near the screen, so a page can have many. Fills its nearest positioned ancestor. See src/runtime/live-gradient.js.
536
+
537
+ ```astro
538
+ <article class="card" style="position: relative">
539
+ <LiveGradient colors={['#ff5c8a', '#ffb347', '#7b3ff2', '#1a0b2e']} />
540
+ <h3>…</h3>
541
+ </article>
542
+ ```
543
+
544
+ | Prop | Type | |
545
+ |---|---|---|
546
+ | `colors` (required) | `string[]` | Two to four colours (hex); the last is the ground the others bloom on. Required. |
547
+ | `speed` | `number` | How fast it morphs (1 is Paper's own speed). Default 0.16. |
548
+ | `distortion` | `number` | How far the colours bend into each other, 0–1. Default 0.7. |
549
+ | `swirl` | `number` | How much they turn, 0–1. Default 0.3. |
550
+ | `grain` | `number` | Film grain over it, 0–1 (0 for none). Default 0.35. |
551
+ | `lazy` | `boolean \| string` | Run only while near the screen (true, or a CSS length). Default true. |
552
+ | `class` | `string` | Classes for the element. |
553
+
531
554
  ## `<Magnetic>`
532
555
 
533
556
  Magnetic: an element the pointer pulls on. As the pointer comes near it leans towards it, its contents a little further, and springs back when the pointer goes: a call to action that feels like a soft object. See src/runtime/magnetic.js. Still on touch screens and with reduced motion.
@@ -724,6 +747,7 @@ PaperShader: any of the thirty Paper Shaders (mesh and grain gradients, god rays
724
747
  | `gradientAngle` | `number` | The made picture's angle, degrees. Default 135. |
725
748
  | `speed` | `number` | How fast it moves, over the preset's (0 is still). |
726
749
  | `scale` | `number` | Share of the pixel ratio drawn at. Default 1. |
750
+ | `lazy` | `boolean \| string` | Run only while near the screen (true, or a CSS length; default `200px`), handled by `mount`. Default false. |
727
751
  | `fixed` | `boolean` | Fill the viewport, behind the page (position: fixed, z-index -1). Default false. |
728
752
  | `background` | `string` | The colour shown before it draws, and without WebGL 2. Default transparent. |
729
753
  | `opacity` | `number` | Its opacity, 0–1, for backdrops under copy. Default 1. |
@@ -1001,6 +1025,7 @@ ShaderBackground: six animated shader backgrounds for a hero or section, tinted
1001
1025
  | `static` | `boolean` | One frame, never the loop: for a shader background that is wallpaper. Default false. |
1002
1026
  | `frame` | `number` | With `static`, the moment drawn, in seconds. Default 12. |
1003
1027
  | `interactive` | `boolean` | Lean towards the pointer, on devices that hover. Default false. |
1028
+ | `lazy` | `boolean \| string` | Run only while near the screen (true, or a CSS length; default `200px`), handled by `mount`. Default false. |
1004
1029
  | `opacity` | `number` | Its opacity, 0–1, to fade it against the section without changing the shader. Default 1. |
1005
1030
  | `blend` | `string` | CSS `mix-blend-mode` with what is behind it (`screen`, `lighten`, `plus-lighter`…), for layering over imagery. Default normal. |
1006
1031
  | `fade` | `'none' \| 'bottom' \| 'top' \| 'both'` | Fade it out towards an edge, so it melts into the page: 'bottom', 'top', 'both' (top and bottom) or 'none'. Default 'bottom'. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arraypress/effects-astro",
3
- "version": "0.2.0",
3
+ "version": "0.3.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 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",
@@ -32,10 +32,14 @@ interface Props {
32
32
  opacity?: number;
33
33
  /** CSS `mix-blend-mode` with what is behind it (`screen`, `plus-lighter`…). Default normal. */
34
34
  blend?: string;
35
+ /** Run only while near the screen (true, or how near as a CSS length; default `200px`), giving its WebGL context back when away: for pages with many effects. Default false. */
36
+ lazy?: boolean | string;
37
+ /** Fade the canvas in once it starts, over the `background`. Default false. */
38
+ fadeIn?: boolean;
35
39
  class?: string;
36
40
  }
37
41
 
38
- const { name, config, fixed = false, behind = false, background, pixelated = false, fade = false, opacity, blend, class: className } = Astro.props;
42
+ const { name, config, fixed = false, behind = false, background, pixelated = false, fade = false, opacity, blend, lazy = false, fadeIn = false, class: className } = Astro.props;
39
43
  const style = [
40
44
  background && `background: ${background}`,
41
45
  opacity !== undefined && opacity < 1 && `opacity: ${opacity}`,
@@ -46,7 +50,8 @@ const style = [
46
50
  ---
47
51
 
48
52
  <div
49
- class:list={['effect-canvas', { 'is-fixed': fixed, 'is-behind': fixed && behind, 'is-pixelated': pixelated, 'is-faded': fade === true }, typeof fade === 'string' && `is-faded-${fade}`, className]}
53
+ class:list={['effect-canvas', { 'is-fixed': fixed, 'is-behind': fixed && behind, 'is-pixelated': pixelated, 'is-faded': fade === true, 'is-fade-in': fadeIn }, typeof fade === 'string' && `is-faded-${fade}`, className]}
54
+ data-effect-lazy={lazy === false ? undefined : lazy === true ? '' : lazy}
50
55
  data-effect-config={JSON.stringify(config)}
51
56
  style={style || undefined}
52
57
  aria-hidden="true"
@@ -73,6 +78,19 @@ const style = [
73
78
  width: 100%;
74
79
  height: 100%;
75
80
  }
81
+ /* fadeIn: the canvas comes in over the background once the effect starts (mount sets data-effect-live) */
82
+ .effect-canvas.is-fade-in canvas {
83
+ opacity: 0;
84
+ transition: opacity 1.2s ease;
85
+ }
86
+ .effect-canvas.is-fade-in[data-effect-live] canvas {
87
+ opacity: 1;
88
+ }
89
+ @media (prefers-reduced-motion: reduce) {
90
+ .effect-canvas.is-fade-in canvas {
91
+ transition: none;
92
+ }
93
+ }
76
94
  .effect-canvas.is-faded {
77
95
  -webkit-mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
78
96
  mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
@@ -0,0 +1,62 @@
1
+ ---
2
+ /**
3
+ * LiveGradient: a gradient that's alive — Paper's mesh gradient in your
4
+ * colours, morphing slowly, with film grain over it. Subtle by default (a
5
+ * sixth of Paper's speed, a gentle swirl), so it sits behind a card, a hero
6
+ * or a section without pulling the eye. The same colours show as a still
7
+ * CSS gradient first (and without WebGL); the live one fades in over it.
8
+ * Lazy by default: it runs only while near the screen, so a page can have
9
+ * many. Fills its nearest positioned ancestor. See src/runtime/live-gradient.js.
10
+ *
11
+ * @example
12
+ * <article class="card" style="position: relative">
13
+ * <LiveGradient colors={['#ff5c8a', '#ffb347', '#7b3ff2', '#1a0b2e']} />
14
+ * <h3>…</h3>
15
+ * </article>
16
+ */
17
+ import EffectCanvas from './EffectCanvas.astro';
18
+ import Grain from './Grain.astro';
19
+ import { liveGradient } from '../runtime/live-gradient.js';
20
+
21
+ interface Props {
22
+ /** Two to four colours (hex); the last is the ground the others bloom on. Required. */
23
+ colors: string[];
24
+ /** How fast it morphs (1 is Paper's own speed). Default 0.16. */
25
+ speed?: number;
26
+ /** How far the colours bend into each other, 0–1. Default 0.7. */
27
+ distortion?: number;
28
+ /** How much they turn, 0–1. Default 0.3. */
29
+ swirl?: number;
30
+ /** Film grain over it, 0–1 (0 for none). Default 0.35. */
31
+ grain?: number;
32
+ /** Run only while near the screen (true, or a CSS length). Default true. */
33
+ lazy?: boolean | string;
34
+ class?: string;
35
+ }
36
+
37
+ const { colors, speed, distortion, swirl, grain = 0.35, lazy = true, class: className } = Astro.props;
38
+ const { config, fallback } = liveGradient(colors, { speed, distortion, swirl });
39
+ ---
40
+
41
+ <div class:list={['effect-live-gradient', className]} aria-hidden="true">
42
+ <EffectCanvas name="paper" config={config} background={fallback} lazy={lazy} fadeIn />
43
+ {grain > 0 && <Grain opacity={grain} still />}
44
+ </div>
45
+
46
+ <script>
47
+ import { mount } from '../runtime/mount.js';
48
+ import { paperShader } from '../runtime/paper.js';
49
+
50
+ mount('[data-effect-paper]', paperShader);
51
+ </script>
52
+
53
+ <style>
54
+ .effect-live-gradient {
55
+ position: absolute;
56
+ inset: 0;
57
+ z-index: 0;
58
+ overflow: hidden;
59
+ border-radius: inherit;
60
+ pointer-events: none;
61
+ }
62
+ </style>
package/src/index.d.ts CHANGED
@@ -93,6 +93,9 @@ export type { Canvas2D } from './runtime/canvas2d.js';
93
93
  export { loadImage, imageTexture, coverScale, GLSL_COVER } from './runtime/image.js';
94
94
  export { boxBlur } from './runtime/blur.js';
95
95
  export { paperShader, paperSettings, paperUniforms } from './runtime/paper.js';
96
+ export { whenNear, lazyMargin } from './runtime/near.js';
97
+ export { liveGradient } from './runtime/live-gradient.js';
98
+ export type { LiveGradientOptions } from './runtime/live-gradient.js';
96
99
  export type { PaperConfig, PaperShaderName } from './runtime/paper.js';
97
100
  export { paperLook, paperLookSettings } from './runtime/paper-look.js';
98
101
  export type { PaperLookConfig, PaperLookOptions } from './runtime/paper-look.js';
package/src/index.js CHANGED
@@ -65,6 +65,8 @@ export { createCanvas2D, grainPattern, grainOnto } from './runtime/canvas2d.js';
65
65
  export { loadImage, imageTexture, coverScale, GLSL_COVER } from './runtime/image.js';
66
66
  export { boxBlur } from './runtime/blur.js';
67
67
  export { paperShader, paperSettings, paperUniforms } from './runtime/paper.js';
68
+ export { whenNear, lazyMargin } from './runtime/near.js';
69
+ export { liveGradient } from './runtime/live-gradient.js';
68
70
  export { paperLook, paperLookSettings } from './runtime/paper-look.js';
69
71
  export { PAPER_LOOKS } from './runtime/paper-looks.js';
70
72
  export { createStage } from './runtime/stage.js';
@@ -25,6 +25,10 @@ export interface InkConfig {
25
25
  opacity?: number;
26
26
  /** Seconds between drops of ink on their own, so it moves before anyone touches it; 0 for none. They wait while it's off screen or the tab is hidden. Default 0. */
27
27
  idle?: number;
28
+ /** Ink for a light ground: the colours given are laid dark on light (dark dye alone would barely show). Default false. */
29
+ dark?: boolean;
30
+ /** Run only while near the screen (true, or a CSS length; default `200px`), handled by `mount`. Default false. */
31
+ lazy?: boolean | string;
28
32
  /** Clicks on these are theirs, not the ink's. Default: links, buttons, form fields and `[data-effect-ignore]`. */
29
33
  ignore?: string;
30
34
  }
@@ -34,6 +34,7 @@ import { PALETTES, pickColors } from './palettes.js';
34
34
  * @property {number} [momentum=0.25] How fast the motion dies away, per second (lower flows on longer).
35
35
  * @property {number} [opacity=1] The ink's strongest cover, 0–1.
36
36
  * @property {number} [idle=0] Seconds between drops of ink on their own, so it moves before anyone touches it; 0 for none. They wait while the ink is off screen or the tab is hidden.
37
+ * @property {boolean} [dark=false] Ink for a light ground: the colours given are laid dark on light (a pale dye, turned over as it's shown), since the ink's cover follows the dye's brightness and dark dye would barely show.
37
38
  * @property {string} [ignore] Clicks on these are theirs, not the ink's (default: links, buttons, form fields, `[data-effect-ignore]`).
38
39
  */
39
40
 
@@ -43,12 +44,16 @@ precision highp float;
43
44
  uniform vec2 uRes;
44
45
  uniform sampler2D uDye;
45
46
  uniform float uOpacity;
47
+ uniform float uDark;
46
48
  void main() {
47
49
  vec3 dye = texture2D(uDye, gl_FragCoord.xy / uRes).rgb;
48
50
  float ink = max(dye.r, max(dye.g, dye.b));
49
51
  float cover = (1.0 - exp(-ink * 2.5)) * uOpacity;
52
+ vec3 colour = dye / max(ink, 1e-4);
53
+ // dark ink: the dye was laid as the colour's opposite; turn it back
54
+ colour = mix(colour, 1.0 - colour, uDark);
50
55
  // Premultiplied, as the canvas composites.
51
- gl_FragColor = vec4(dye / max(ink, 1e-4) * cover, cover);
56
+ gl_FragColor = vec4(colour * cover, cover);
52
57
  }
53
58
  `;
54
59
 
@@ -69,6 +74,14 @@ export function ink(el, config) {
69
74
  let fluid = null;
70
75
  /** @type {ReturnType<typeof stir> | null} */
71
76
  let stirrer = null;
77
+ const dark = config.dark === true;
78
+ /**
79
+ * A colour as dye: itself, or its opposite for dark ink (turned back when shown).
80
+ *
81
+ * @param {import('./color.js').Rgb} c The colour.
82
+ * @returns {import('./color.js').Rgb} The dye.
83
+ */
84
+ const dye = (c) => (dark ? /** @type {import('./color.js').Rgb} */ (c.map((v) => 1 - v)) : c);
72
85
  const idle = Math.max(0, config.idle ?? 0);
73
86
  // the first drop comes soon after it starts, then one every `idle` seconds of running
74
87
  let untilDrop = Math.min(idle, 0.4);
@@ -83,8 +96,9 @@ export function ink(el, config) {
83
96
  gl.useProgram(program);
84
97
  gl.uniform1i(uniform('uDye'), 3);
85
98
  gl.uniform1f(uniform('uOpacity'), config.opacity ?? 1);
99
+ gl.uniform1f(uniform('uDark'), dark ? 1 : 0);
86
100
  const s = stir(fluid, el, {
87
- colors: pickColors(config, [...PALETTES.Peacock.colors]).map(parseColor),
101
+ colors: pickColors(config, [...PALETTES.Peacock.colors]).map(parseColor).map(dye),
88
102
  trail: config.trail ?? 0.35,
89
103
  drops: config.drops,
90
104
  force: config.force,
@@ -110,7 +124,7 @@ export function ink(el, config) {
110
124
  });
111
125
  if (!stage) return stop;
112
126
 
113
- const unwatch = watchColors(el, (next) => stirrer?.setColors(next.colors.map(parseColor)));
127
+ const unwatch = watchColors(el, (next) => stirrer?.setColors(next.colors.map(parseColor).map(dye)));
114
128
  return () => {
115
129
  stop();
116
130
  unwatch();
@@ -0,0 +1,15 @@
1
+ import type { PaperConfig } from './paper.js';
2
+
3
+ export interface LiveGradientOptions {
4
+ /** How fast it morphs (Paper's speed; 1 is Paper's own). Default 0.16. */
5
+ speed?: number;
6
+ /** How far the colours bend into each other, 0–1. Default 0.7. */
7
+ distortion?: number;
8
+ /** How much they turn, 0–1. Default 0.3. */
9
+ swirl?: number;
10
+ /** Share of the pixel ratio drawn at. Default 0.5. */
11
+ scale?: number;
12
+ }
13
+
14
+ /** The Paper settings (`config`, for `paperShader`) and a still CSS `background` (`fallback`) for a live gradient. Throws with fewer than two colours. */
15
+ export function liveGradient(colors: string[], options?: LiveGradientOptions): { config: PaperConfig; fallback: string };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/live-gradient
3
+ *
4
+ * A live gradient: Paper's mesh gradient in your colours, morphing slowly
5
+ * (subtle by default: a sixth of Paper's speed, a gentle swirl), drawn at
6
+ * half resolution (a soft gradient loses nothing, and grain covers the
7
+ * rest). It comes with the same colours as a still CSS gradient, to show
8
+ * before it starts and without WebGL, so the live one can fade in over it.
9
+ * `<LiveGradient>` is the component; this builds its settings, for pages
10
+ * that write their own HTML (a card list made in a script).
11
+ */
12
+
13
+ /**
14
+ * @typedef {object} LiveGradientOptions
15
+ * @property {number} [speed=0.16] How fast it morphs (Paper's speed; 1 is Paper's own).
16
+ * @property {number} [distortion=0.7] How far the colours bend into each other, 0–1.
17
+ * @property {number} [swirl=0.3] How much they turn, 0–1.
18
+ * @property {number} [scale=0.5] Share of the pixel ratio drawn at.
19
+ */
20
+
21
+ /**
22
+ * The Paper settings and the still CSS gradient for a live gradient.
23
+ *
24
+ * @param {string[]} colors Two to four colours (hex); the last is the ground the others bloom on.
25
+ * @param {LiveGradientOptions} [options] How it moves.
26
+ * @returns {{ config: import('./paper.js').PaperConfig, fallback: string }} `config` for `paperShader`, `fallback` a CSS `background`.
27
+ * @throws {TypeError} With fewer than two colours.
28
+ */
29
+ export function liveGradient(colors, { speed = 0.16, distortion = 0.7, swirl = 0.3, scale = 0.5 } = {}) {
30
+ if (!Array.isArray(colors) || colors.length < 2) throw new TypeError('A live gradient needs at least two colours');
31
+ const cs = colors.slice(0, 4);
32
+ const ground = cs[cs.length - 1];
33
+ const blooms = cs.slice(0, -1);
34
+ const at = ['20% 18%', '82% 72%', '28% 88%'];
35
+ const fallback = [...blooms.map((c, i) => `radial-gradient(at ${at[i]}, ${c} 0, transparent 60%)`), ground].join(', ');
36
+ return {
37
+ config: { shader: 'mesh-gradient', colors: cs, speed, scale, params: { distortion, swirl, grainMixer: 0, grainOverlay: 0 } },
38
+ fallback,
39
+ };
40
+ }
@@ -9,8 +9,14 @@
9
9
  * an element with its settings as JSON in `data-effect-config`; the setup
10
10
  * function is called once per element with those settings, and the
11
11
  * function it returns is called when the element leaves the page.
12
+ *
13
+ * An element marked lazy (`data-effect-lazy`, or `lazy` in its settings)
14
+ * runs only while it is near the screen (./near.js): a page can carry many
15
+ * effects and still hold only the WebGL contexts it shows.
12
16
  */
13
17
 
18
+ import { whenNear, lazyMargin } from './near.js';
19
+
14
20
  /** @type {Map<string, (el: HTMLElement, config: any) => (() => void) | void>} */
15
21
  const effects = new Map();
16
22
  /** For each registered selector, its running elements and how to stop each: one element can carry several effects. */
@@ -48,7 +54,13 @@ function scan() {
48
54
  document.querySelectorAll(selector).forEach((node) => {
49
55
  const el = /** @type {HTMLElement} */ (node);
50
56
  if (live.has(el)) return;
51
- live.set(el, setup(el, readConfig(el)) ?? (() => {}));
57
+ const config = readConfig(el);
58
+ const margin = lazyMargin(el, config);
59
+ if (margin) live.set(el, whenNear(el, () => setup(el, config), { margin }));
60
+ else {
61
+ live.set(el, setup(el, config) ?? (() => {}));
62
+ el.setAttribute('data-effect-live', '');
63
+ }
52
64
  });
53
65
  }
54
66
  }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Starts `start` while `el` is within `margin` (default `200px`) of the viewport and stops it when it moves away,
3
+ * again each time it comes back; `data-effect-live` is on the element while it runs. Returns a function that stops
4
+ * watching (and the effect).
5
+ */
6
+ export function whenNear(el: HTMLElement, start: () => (() => void) | void, options?: { margin?: string }): () => void;
7
+
8
+ /** An element's lazy margin: `data-effect-lazy`, or `lazy` in its config (true for `200px`); null to start at once. */
9
+ export function lazyMargin(el: HTMLElement, config: Record<string, unknown>): string | null;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/near
3
+ *
4
+ * Runs an effect only while its element is near the screen: started as it
5
+ * comes within `margin` of the viewport, stopped (its WebGL context given
6
+ * back) as it leaves. A browser keeps about sixteen WebGL contexts at once
7
+ * and drops the oldest past that, so a page with many effects (a wall of
8
+ * cards, a long list) needs this; `mount` uses it for any element marked
9
+ * `lazy`. While running, the element carries `data-effect-live`, which the
10
+ * stylesheet can fade the canvas in on.
11
+ */
12
+
13
+ /** One observer per margin, shared by every element that uses it. */
14
+ /** @type {Map<string, { observer: IntersectionObserver, handlers: Map<Element, (near: boolean) => void> }>} */
15
+ const observers = new Map();
16
+
17
+ /**
18
+ * The shared observer for a margin, made on first use.
19
+ *
20
+ * @param {string} margin A CSS length for `rootMargin`'s top and bottom (and left and right).
21
+ * @returns {{ observer: IntersectionObserver, handlers: Map<Element, (near: boolean) => void> }} It and its handlers.
22
+ */
23
+ function observerFor(margin) {
24
+ let entry = observers.get(margin);
25
+ if (!entry) {
26
+ /** @type {Map<Element, (near: boolean) => void>} */
27
+ const handlers = new Map();
28
+ const observer = new IntersectionObserver(
29
+ (changes) => {
30
+ for (const change of changes) handlers.get(change.target)?.(change.isIntersecting);
31
+ },
32
+ { rootMargin: `${margin} ${margin}` },
33
+ );
34
+ entry = { observer, handlers };
35
+ observers.set(margin, entry);
36
+ }
37
+ return entry;
38
+ }
39
+
40
+ /**
41
+ * Starts `start` while `el` is within `margin` of the viewport, and stops it
42
+ * when it moves further away; again each time it comes back.
43
+ *
44
+ * @param {HTMLElement} el The element to watch.
45
+ * @param {() => (() => void) | void} start Starts the effect; returns how to stop it.
46
+ * @param {{ margin?: string }} [options] How near counts as near (CSS length). Default `200px`.
47
+ * @returns {() => void} Stops watching, and stops the effect if it is running.
48
+ */
49
+ export function whenNear(el, start, { margin = '200px' } = {}) {
50
+ /** @type {(() => void) | null} */
51
+ let stop = null;
52
+ /** Starts the effect, if it isn't running. */
53
+ const on = () => {
54
+ if (stop) return;
55
+ stop = start() ?? (() => {});
56
+ el.setAttribute('data-effect-live', '');
57
+ };
58
+ /** Stops the effect, if it's running. */
59
+ const off = () => {
60
+ if (!stop) return;
61
+ const s = stop;
62
+ stop = null;
63
+ el.removeAttribute('data-effect-live');
64
+ s();
65
+ };
66
+ if (typeof IntersectionObserver === 'undefined') {
67
+ on();
68
+ return off;
69
+ }
70
+ const { observer, handlers } = observerFor(margin);
71
+ handlers.set(el, (near) => (near ? on() : off()));
72
+ observer.observe(el);
73
+ return () => {
74
+ observer.unobserve(el);
75
+ handlers.delete(el);
76
+ off();
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Reads how lazy an element is: its `data-effect-lazy` attribute, or a
82
+ * `lazy` setting in its config (true for the default margin, or a length).
83
+ *
84
+ * @param {HTMLElement} el The element.
85
+ * @param {Record<string, unknown>} config Its settings.
86
+ * @returns {string | null} The margin to start within, or null to start at once.
87
+ */
88
+ export function lazyMargin(el, config) {
89
+ const attr = el.dataset.effectLazy;
90
+ if (attr !== undefined) return attr || '200px';
91
+ if (config.lazy === true) return '200px';
92
+ if (typeof config.lazy === 'string' && config.lazy) return config.lazy;
93
+ return null;
94
+ }
@@ -25,6 +25,8 @@ export interface PaperConfig {
25
25
  speed?: number;
26
26
  /** Share of the pixel ratio drawn at. Default 1. */
27
27
  scale?: number;
28
+ /** Run only while near the screen (true, or a CSS length; default `200px`), handled by `mount`. Default false. */
29
+ lazy?: boolean | string;
28
30
  }
29
31
 
30
32
  /** A shader's settings: its preset with the config's settings over it. Throws for an unknown shader. */
@@ -21,6 +21,8 @@ export interface ShaderBackgroundConfig {
21
21
  frame?: number;
22
22
  /** Lean towards the pointer, on devices that hover. Default false. */
23
23
  interactive?: boolean;
24
+ /** Run only while near the screen (true, or a CSS length; default `200px`), handled by `mount`. Default false. */
25
+ lazy?: boolean | string;
24
26
  }
25
27
 
26
28
  /** Every shader background's fragment shader, by name. */