@wolsok/loading-wave 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +196 -2
  3. package/esm2022/index.js +7 -0
  4. package/esm2022/index.js.map +1 -0
  5. package/esm2022/lib/canvas-wave-renderer.js +125 -0
  6. package/esm2022/lib/canvas-wave-renderer.js.map +1 -0
  7. package/esm2022/lib/choose-wave-renderer.js +66 -0
  8. package/esm2022/lib/choose-wave-renderer.js.map +1 -0
  9. package/esm2022/lib/dot-color.js +63 -0
  10. package/esm2022/lib/dot-color.js.map +1 -0
  11. package/esm2022/lib/loading-wave-options.js +48 -0
  12. package/esm2022/lib/loading-wave-options.js.map +1 -0
  13. package/esm2022/lib/loading-wave.directive.js +74 -0
  14. package/esm2022/lib/loading-wave.directive.js.map +1 -0
  15. package/esm2022/lib/loading-wave.js +238 -0
  16. package/esm2022/lib/loading-wave.js.map +1 -0
  17. package/esm2022/lib/renderer.js +18 -0
  18. package/esm2022/lib/renderer.js.map +1 -0
  19. package/esm2022/lib/wave-environment.js +59 -0
  20. package/esm2022/lib/wave-environment.js.map +1 -0
  21. package/esm2022/lib/wave-model.js +171 -0
  22. package/esm2022/lib/wave-model.js.map +1 -0
  23. package/esm2022/lib/wave-timeline.js +61 -0
  24. package/esm2022/lib/wave-timeline.js.map +1 -0
  25. package/esm2022/lib/webgl/echo.js +5 -0
  26. package/esm2022/lib/webgl/echo.js.map +1 -0
  27. package/esm2022/lib/webgl/loading-wave-shader.js +1 -0
  28. package/esm2022/lib/webgl/loading-wave-shader.js.map +1 -0
  29. package/esm2022/lib/webgl/shader-program.js +227 -0
  30. package/esm2022/lib/webgl/shader-program.js.map +1 -0
  31. package/esm2022/lib/webgl/shaders/ripple.shader.js +110 -0
  32. package/esm2022/lib/webgl/shaders/ripple.shader.js.map +1 -0
  33. package/esm2022/lib/webgl/webgl-wave-renderer.js +182 -0
  34. package/esm2022/lib/webgl/webgl-wave-renderer.js.map +1 -0
  35. package/esm2022/wolsok-loading-wave.js +5 -0
  36. package/esm2022/wolsok-loading-wave.js.map +1 -0
  37. package/index.d.ts +6 -0
  38. package/lib/canvas-wave-renderer.d.ts +29 -0
  39. package/lib/choose-wave-renderer.d.ts +31 -0
  40. package/lib/dot-color.d.ts +15 -0
  41. package/lib/loading-wave-options.d.ts +55 -0
  42. package/lib/loading-wave.d.ts +55 -0
  43. package/lib/loading-wave.directive.d.ts +29 -0
  44. package/lib/renderer.d.ts +54 -0
  45. package/lib/wave-environment.d.ts +23 -0
  46. package/lib/wave-model.d.ts +85 -0
  47. package/lib/wave-timeline.d.ts +33 -0
  48. package/lib/webgl/echo.d.ts +4 -0
  49. package/lib/webgl/loading-wave-shader.d.ts +20 -0
  50. package/lib/webgl/shader-program.d.ts +33 -0
  51. package/lib/webgl/shaders/ripple.shader.d.ts +10 -0
  52. package/lib/webgl/webgl-wave-renderer.d.ts +58 -0
  53. package/package.json +44 -3
  54. package/wolsok-loading-wave.d.ts +5 -0
@@ -0,0 +1,74 @@
1
+ import { DOCUMENT, isPlatformBrowser } from '@angular/common';
2
+ import { afterNextRender, booleanAttribute, DestroyRef, Directive, effect, ElementRef, inject, InjectionToken, input, PLATFORM_ID, signal, untracked, } from '@angular/core';
3
+ import { LoadingWave } from './loading-wave';
4
+ import { LOADING_WAVE_OPTIONS, resolveLoadingWaveOptions, } from './loading-wave-options';
5
+ import { browserWaveEnvironment } from './wave-environment';
6
+ import * as i0 from "@angular/core";
7
+ /** the browser APIs the wave runs on; specs replace them */
8
+ export const LOADING_WAVE_ENVIRONMENT = new InjectionToken('LOADING_WAVE_ENVIRONMENT', {
9
+ providedIn: 'root',
10
+ factory: () => browserWaveEnvironment(inject(DOCUMENT)),
11
+ });
12
+ /**
13
+ * Lays a calm loading wave behind the host's content: a grid of dots that a
14
+ * curved wave front lights again and again while `wsLoadingWave` is true.
15
+ *
16
+ * ```html
17
+ * <section [wsLoadingWave]="loading()" [wsLoadingWaveOptions]="{ afterLoading: 'keep' }">
18
+ * ```
19
+ *
20
+ * Runs only in the browser, never on the server.
21
+ */
22
+ export class LoadingWaveDirective {
23
+ constructor() {
24
+ /** whether the host is loading */
25
+ this.wsLoadingWave = input(false, { ...(ngDevMode ? { debugName: "wsLoadingWave" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
26
+ /** overrides the app-wide options (`provideLoadingWave`) for this host */
27
+ this.wsLoadingWaveOptions = input(/* @ts-ignore */
28
+ ...(ngDevMode ? [undefined, { debugName: "wsLoadingWaveOptions" }] : /* istanbul ignore next */ []));
29
+ this.activeRendererState = signal(null, /* @ts-ignore */
30
+ ...(ngDevMode ? [{ debugName: "activeRendererState" }] : /* istanbul ignore next */ []));
31
+ /** what draws the effect right now, `null` while nothing shows */
32
+ this.activeRenderer = this.activeRendererState.asReadonly();
33
+ if (!isPlatformBrowser(inject(PLATFORM_ID))) {
34
+ return;
35
+ }
36
+ const host = inject(ElementRef).nativeElement;
37
+ const defaults = inject(LOADING_WAVE_OPTIONS);
38
+ const env = inject(LOADING_WAVE_ENVIRONMENT);
39
+ const rendered = signal(false, /* @ts-ignore */
40
+ ...(ngDevMode ? [{ debugName: "rendered" }] : /* istanbul ignore next */ []));
41
+ let wave;
42
+ let appliedOptions = '';
43
+ afterNextRender(() => rendered.set(true));
44
+ inject(DestroyRef).onDestroy(() => wave?.dispose());
45
+ effect(() => {
46
+ if (!rendered()) {
47
+ return;
48
+ }
49
+ const options = resolveLoadingWaveOptions(defaults, this.wsLoadingWaveOptions());
50
+ const loading = this.wsLoadingWave();
51
+ untracked(() => {
52
+ const optionsKey = JSON.stringify(options);
53
+ if (wave == null) {
54
+ wave = new LoadingWave(host, options, env, (kind) => this.activeRendererState.set(kind));
55
+ }
56
+ else if (optionsKey !== appliedOptions) {
57
+ wave.setOptions(options);
58
+ }
59
+ appliedOptions = optionsKey;
60
+ wave.setLoading(loading);
61
+ });
62
+ });
63
+ }
64
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.3.0", ngImport: i0, type: LoadingWaveDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
65
+ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.3.0", type: LoadingWaveDirective, isStandalone: true, selector: "[wsLoadingWave]", inputs: { wsLoadingWave: { classPropertyName: "wsLoadingWave", publicName: "wsLoadingWave", isSignal: true, isRequired: false, transformFunction: null }, wsLoadingWaveOptions: { classPropertyName: "wsLoadingWaveOptions", publicName: "wsLoadingWaveOptions", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["wsLoadingWave"], ngImport: i0 }); }
66
+ }
67
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.3.0", ngImport: i0, type: LoadingWaveDirective, decorators: [{
68
+ type: Directive,
69
+ args: [{
70
+ selector: '[wsLoadingWave]',
71
+ exportAs: 'wsLoadingWave',
72
+ }]
73
+ }], ctorParameters: () => [], propDecorators: { wsLoadingWave: [{ type: i0.Input, args: [{ isSignal: true, alias: "wsLoadingWave", required: false }] }], wsLoadingWaveOptions: [{ type: i0.Input, args: [{ isSignal: true, alias: "wsLoadingWaveOptions", required: false }] }] } });
74
+ //# sourceMappingURL=loading-wave.directive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loading-wave.directive.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/loading-wave.directive.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,SAAS,EACT,MAAM,EACN,UAAU,EACV,MAAM,EACN,cAAc,EACd,KAAK,EACL,WAAW,EACX,MAAM,EACN,SAAS,GACV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAA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AI,EAAE,OAAO,EAAE,CAAC,CAAC;QAEpD,MAAM,CAAC,GAAG,EAAE;YACV,IAAI,CAAC,QAAQ,EAAE,EAAE,CAAC;gBAChB,OAAO;YACT,CAAC;YACD,MAAM,OAAO,GAAG,yBAAyB,CACvC,QAAQ,EACR,IAAI,CAAC,oBAAoB,EAAE,CAC5B,CAAC;YACF,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;YACrC,SAAS,CAAC,GAAG,EAAE;gBACb,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;gBAC3C,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;oBACjB,IAAI,GAAG,IAAI,WAAW,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,CAClD,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,CACnC,CAAC;gBACJ,CAAC;qBAAM,IAAI,UAAU,KAAK,cAAc,EAAE,CAAC;oBACzC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;gBAC3B,CAAC;gBACD,cAAc,GAAG,UAAU,CAAC;gBAC5B,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;YAC3B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;8GAhDU,oBAAoB;kGAApB,oBAAoB;;2FAApB,oBAAoB;kBAJhC,SAAS;mBAAC;oBACT,QAAQ,EAAE,iBAAiB;oBAC3B,QAAQ,EAAE,eAAe;iBAC1B","sourcesContent":["import { DOCUMENT, isPlatformBrowser } from '@angular/common';\nimport {\n afterNextRender,\n booleanAttribute,\n DestroyRef,\n Directive,\n effect,\n ElementRef,\n inject,\n InjectionToken,\n input,\n PLATFORM_ID,\n signal,\n untracked,\n} from '@angular/core';\nimport { LoadingWave } from './loading-wave';\nimport {\n LOADING_WAVE_OPTIONS,\n LoadingWaveOptions,\n resolveLoadingWaveOptions,\n} from './loading-wave-options';\nimport type { WaveRendererKind } from './renderer';\nimport { browserWaveEnvironment, WaveEnvironment } from './wave-environment';\n\n/** the browser APIs the wave runs on; specs replace them */\nexport const LOADING_WAVE_ENVIRONMENT = new InjectionToken<WaveEnvironment>(\n 'LOADING_WAVE_ENVIRONMENT',\n {\n providedIn: 'root',\n factory: () => browserWaveEnvironment(inject(DOCUMENT)),\n }\n);\n\n/**\n * Lays a calm loading wave behind the host's content: a grid of dots that a\n * curved wave front lights again and again while `wsLoadingWave` is true.\n *\n * ```html\n * <section [wsLoadingWave]=\"loading()\" [wsLoadingWaveOptions]=\"{ afterLoading: 'keep' }\">\n * ```\n *\n * Runs only in the browser, never on the server.\n */\n@Directive({\n selector: '[wsLoadingWave]',\n exportAs: 'wsLoadingWave',\n})\nexport class LoadingWaveDirective {\n /** whether the host is loading */\n public readonly wsLoadingWave = input(false, {\n transform: booleanAttribute,\n });\n /** overrides the app-wide options (`provideLoadingWave`) for this host */\n public readonly wsLoadingWaveOptions = input<Partial<LoadingWaveOptions>>();\n\n private readonly activeRendererState = signal<WaveRendererKind | null>(null);\n /** what draws the effect right now, `null` while nothing shows */\n public readonly activeRenderer = this.activeRendererState.asReadonly();\n\n public constructor() {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const defaults = inject(LOADING_WAVE_OPTIONS);\n const env = inject(LOADING_WAVE_ENVIRONMENT);\n const rendered = signal(false);\n let wave: LoadingWave | undefined;\n let appliedOptions = '';\n\n afterNextRender(() => rendered.set(true));\n inject(DestroyRef).onDestroy(() => wave?.dispose());\n\n effect(() => {\n if (!rendered()) {\n return;\n }\n const options = resolveLoadingWaveOptions(\n defaults,\n this.wsLoadingWaveOptions()\n );\n const loading = this.wsLoadingWave();\n untracked(() => {\n const optionsKey = JSON.stringify(options);\n if (wave == null) {\n wave = new LoadingWave(host, options, env, (kind) =>\n this.activeRendererState.set(kind)\n );\n } else if (optionsKey !== appliedOptions) {\n wave.setOptions(options);\n }\n appliedOptions = optionsKey;\n wave.setLoading(loading);\n });\n });\n }\n}\n"]}
@@ -0,0 +1,238 @@
1
+ import { waveGeometry } from './wave-model';
2
+ import { WaveTimeline } from './wave-timeline';
3
+ /** styles that lay the canvas behind the host's content, filling it */
4
+ const CANVAS_STYLE = {
5
+ position: 'absolute',
6
+ inset: '0',
7
+ width: '100%',
8
+ height: '100%',
9
+ display: 'block',
10
+ pointerEvents: 'none',
11
+ zIndex: '-1',
12
+ };
13
+ /**
14
+ * The most device pixels a wave's canvas holds: a tall host (a whole page)
15
+ * gets a lower pixel ratio rather than a canvas of hundreds of megabytes.
16
+ */
17
+ export const MAX_CANVAS_PIXELS = 4_000_000;
18
+ /** the device pixel ratio, lowered where the canvas would grow too large */
19
+ export function fitPixelRatio(width, height, pixelRatio) {
20
+ const area = width * height;
21
+ return area <= 0
22
+ ? pixelRatio
23
+ : Math.min(pixelRatio, Math.sqrt(MAX_CANVAS_PIXELS / area));
24
+ }
25
+ /**
26
+ * The loading wave of one host element, without Angular: puts a canvas
27
+ * behind the host's content while loading, runs the animation and removes
28
+ * it again (`'hide'`) or leaves the resting dots (`'keep'`).
29
+ */
30
+ export class LoadingWave {
31
+ constructor(host, options, env, onRendererChange = () => undefined) {
32
+ this.host = host;
33
+ this.options = options;
34
+ this.env = env;
35
+ this.onRendererChange = onRendererChange;
36
+ this.visible = true;
37
+ this.loading = false;
38
+ this.disconnects = [];
39
+ }
40
+ setLoading(loading) {
41
+ if (loading === this.loading) {
42
+ return;
43
+ }
44
+ this.loading = loading;
45
+ if (loading) {
46
+ this.host.setAttribute('aria-busy', 'true');
47
+ if (this.timeline == null) {
48
+ this.mount(0);
49
+ }
50
+ this.timeline?.start(this.env.now());
51
+ }
52
+ else {
53
+ this.host.removeAttribute('aria-busy');
54
+ this.timeline?.stop(this.env.now());
55
+ // off screen no frame would finish the fade: free the canvas right away
56
+ if (!this.visible && this.options.afterLoading === 'hide') {
57
+ this.unmount();
58
+ }
59
+ }
60
+ this.scheduleFrame();
61
+ }
62
+ /**
63
+ * applies new options: look, spacing and speed in place; a new renderer or
64
+ * `afterLoading` starts a running effect over, and resting dots stay where
65
+ * the new options keep them
66
+ */
67
+ setOptions(options) {
68
+ const previous = this.options;
69
+ this.options = options;
70
+ if (this.timeline == null) {
71
+ return;
72
+ }
73
+ if (options.renderer === previous.renderer &&
74
+ options.afterLoading === previous.afterLoading &&
75
+ options.shader.fragment === previous.shader.fragment) {
76
+ this.renderer?.setLook(this.look());
77
+ this.renderer?.setShaderUniforms(options.shader.uniforms);
78
+ this.resize();
79
+ return;
80
+ }
81
+ this.unmount();
82
+ if (this.loading) {
83
+ this.mount(0);
84
+ this.timeline?.start(this.env.now());
85
+ }
86
+ else if (options.afterLoading === 'keep') {
87
+ this.mount(1);
88
+ }
89
+ this.scheduleFrame();
90
+ }
91
+ dispose() {
92
+ this.unmount();
93
+ this.host.removeAttribute('aria-busy');
94
+ }
95
+ mount(restingDots) {
96
+ const renderer = this.createRenderer(this.options.renderer);
97
+ if (renderer == null) {
98
+ return;
99
+ }
100
+ this.styleHost();
101
+ // last, not first: hydration finds the host's own nodes from its first child
102
+ this.host.append(renderer.canvas);
103
+ this.renderer = renderer;
104
+ this.timeline = new WaveTimeline(this.options.afterLoading, !this.env.prefersReducedMotion(), restingDots);
105
+ this.visible = true;
106
+ this.disconnects = [
107
+ this.env.observeSize(this.host, () => this.resize()),
108
+ this.env.observeVisibility(this.host, (visible) => this.setVisible(visible)),
109
+ this.env.observeTheme(() => this.recolor()),
110
+ ];
111
+ this.resize();
112
+ this.onRendererChange(renderer.kind);
113
+ }
114
+ unmount() {
115
+ this.cancelFrame();
116
+ this.disconnects.forEach((disconnect) => disconnect());
117
+ this.disconnects = [];
118
+ if (this.renderer != null) {
119
+ this.renderer.dispose();
120
+ this.renderer.canvas.remove();
121
+ this.onRendererChange(null);
122
+ }
123
+ this.renderer = undefined;
124
+ this.timeline = undefined;
125
+ this.restoreHost();
126
+ }
127
+ createRenderer(preference) {
128
+ const renderer = this.env.chooseRenderer({
129
+ preference,
130
+ look: this.look(),
131
+ shader: this.options.shader,
132
+ createCanvas: () => this.env.createCanvas(),
133
+ onContextLost: () => this.fallBackToCanvas(),
134
+ });
135
+ if (renderer != null) {
136
+ renderer.canvas.setAttribute('aria-hidden', 'true');
137
+ Object.assign(renderer.canvas.style, CANVAS_STYLE);
138
+ }
139
+ return renderer;
140
+ }
141
+ /** the GPU took the WebGL context away: go on with a 2D canvas */
142
+ fallBackToCanvas() {
143
+ const lost = this.renderer;
144
+ const replacement = this.createRenderer('canvas');
145
+ if (lost == null || replacement == null) {
146
+ this.unmount();
147
+ return;
148
+ }
149
+ lost.canvas.replaceWith(replacement.canvas);
150
+ lost.dispose();
151
+ this.renderer = replacement;
152
+ this.resize();
153
+ this.onRendererChange(replacement.kind);
154
+ }
155
+ look() {
156
+ const { dotSize, color, accentColor } = this.options;
157
+ return {
158
+ dotSize,
159
+ color: this.env.resolveColor(this.host, color),
160
+ accent: accentColor === undefined
161
+ ? undefined
162
+ : this.env.resolveColor(this.host, accentColor),
163
+ };
164
+ }
165
+ resize() {
166
+ const { clientWidth: width, clientHeight: height } = this.host;
167
+ this.renderer?.resize(waveGeometry(width, height, {
168
+ dotSpacing: this.options.dotSpacing,
169
+ sweepMs: this.options.sweepMs,
170
+ frontRoundness: this.options.frontRoundness,
171
+ }), fitPixelRatio(width, height, this.env.pixelRatio()));
172
+ // a resized canvas is blank until drawn again
173
+ this.scheduleFrame();
174
+ }
175
+ recolor() {
176
+ this.renderer?.setLook(this.look());
177
+ this.scheduleFrame();
178
+ }
179
+ setVisible(visible) {
180
+ this.visible = visible;
181
+ if (visible) {
182
+ this.scheduleFrame();
183
+ }
184
+ else {
185
+ this.cancelFrame();
186
+ }
187
+ }
188
+ scheduleFrame() {
189
+ if (this.frameId != null || !this.visible || this.renderer == null) {
190
+ return;
191
+ }
192
+ this.frameId = this.env.requestFrame(() => this.drawFrame());
193
+ }
194
+ cancelFrame() {
195
+ if (this.frameId != null) {
196
+ this.env.cancelFrame(this.frameId);
197
+ this.frameId = undefined;
198
+ }
199
+ }
200
+ drawFrame() {
201
+ this.frameId = undefined;
202
+ if (this.renderer == null || this.timeline == null) {
203
+ return;
204
+ }
205
+ const { frame, settled, finished } = this.timeline.frameAt(this.env.now());
206
+ if (finished) {
207
+ this.unmount();
208
+ return;
209
+ }
210
+ this.renderer.draw(frame);
211
+ if (!settled) {
212
+ this.scheduleFrame();
213
+ }
214
+ }
215
+ /**
216
+ * `isolation` keeps the canvas's `z-index: -1` above the host's own
217
+ * background; a static host becomes `relative` to hold the canvas.
218
+ */
219
+ styleHost() {
220
+ const { style } = this.host;
221
+ this.hostStyle = { position: style.position, isolation: style.isolation };
222
+ const view = this.host.ownerDocument.defaultView;
223
+ const position = view?.getComputedStyle(this.host).position;
224
+ // jsdom leaves an unset position empty
225
+ if (position === 'static' || position === '') {
226
+ style.position = 'relative';
227
+ }
228
+ style.isolation = 'isolate';
229
+ }
230
+ restoreHost() {
231
+ if (this.hostStyle != null) {
232
+ this.host.style.position = this.hostStyle.position;
233
+ this.host.style.isolation = this.hostStyle.isolation;
234
+ this.hostStyle = undefined;
235
+ }
236
+ }
237
+ }
238
+ //# sourceMappingURL=loading-wave.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loading-wave.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/loading-wave.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,uEAAuE;AACvE,MAAM,YAAY,GAAiC;IACjD,QAAQ,EAAE,UAAU;IACpB,KAAK,EAAE,GAAG;IACV,KAAK,EAAE,MAAM;IACb,MAAM,EAAE,MAAM;IACd,OAAO,EAAE,OAAO;IAChB,aAAa,EAAE,MAAM;IACrB,MAAM,EAAE,IAAI;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C;IACH,CAAC;CACF","sourcesContent":["import type {\n LoadingWaveOptions,\n ResolvedLoadingWaveOptions,\n} from './loading-wave-options';\nimport type { WaveLook, WaveRenderer, WaveRendererKind } from './renderer';\nimport type { Disconnect, WaveEnvironment } from './wave-environment';\nimport { waveGeometry } from './wave-model';\nimport { WaveTimeline } from './wave-timeline';\n\n/** styles that lay the canvas behind the host's content, filling it */\nconst CANVAS_STYLE: Partial<CSSStyleDeclaration> = {\n position: 'absolute',\n inset: '0',\n width: '100%',\n height: '100%',\n display: 'block',\n pointerEvents: 'none',\n zIndex: '-1',\n};\n\n/**\n * The most device pixels a wave's canvas holds: a tall host (a whole page)\n * gets a lower pixel ratio rather than a canvas of hundreds of megabytes.\n */\nexport const MAX_CANVAS_PIXELS = 4_000_000;\n\n/** the device pixel ratio, lowered where the canvas would grow too large */\nexport function fitPixelRatio(\n width: number,\n height: number,\n pixelRatio: number\n): number {\n const area = width * height;\n return area <= 0\n ? pixelRatio\n : Math.min(pixelRatio, Math.sqrt(MAX_CANVAS_PIXELS / area));\n}\n\n/**\n * The loading wave of one host element, without Angular: puts a canvas\n * behind the host's content while loading, runs the animation and removes\n * it again (`'hide'`) or leaves the resting dots (`'keep'`).\n */\nexport class LoadingWave {\n private renderer?: WaveRenderer;\n private timeline?: WaveTimeline;\n private frameId?: number;\n private visible = true;\n private loading = false;\n private disconnects: Disconnect[] = [];\n private hostStyle?: { position: string; isolation: string };\n\n public constructor(\n private readonly host: HTMLElement,\n private options: ResolvedLoadingWaveOptions,\n private readonly env: WaveEnvironment,\n private readonly onRendererChange: (\n kind: WaveRendererKind | null\n ) => void = () => undefined\n ) {}\n\n public setLoading(loading: boolean): void {\n if (loading === this.loading) {\n return;\n }\n this.loading = loading;\n if (loading) {\n this.host.setAttribute('aria-busy', 'true');\n if (this.timeline == null) {\n this.mount(0);\n }\n this.timeline?.start(this.env.now());\n } else {\n this.host.removeAttribute('aria-busy');\n this.timeline?.stop(this.env.now());\n // off screen no frame would finish the fade: free the canvas right away\n if (!this.visible && this.options.afterLoading === 'hide') {\n this.unmount();\n }\n }\n this.scheduleFrame();\n }\n\n /**\n * applies new options: look, spacing and speed in place; a new renderer or\n * `afterLoading` starts a running effect over, and resting dots stay where\n * the new options keep them\n */\n public setOptions(options: ResolvedLoadingWaveOptions): void {\n const previous = this.options;\n this.options = options;\n if (this.timeline == null) {\n return;\n }\n if (\n options.renderer === previous.renderer &&\n options.afterLoading === previous.afterLoading &&\n options.shader.fragment === previous.shader.fragment\n ) {\n this.renderer?.setLook(this.look());\n this.renderer?.setShaderUniforms(options.shader.uniforms);\n this.resize();\n return;\n }\n this.unmount();\n if (this.loading) {\n this.mount(0);\n this.timeline?.start(this.env.now());\n } else if (options.afterLoading === 'keep') {\n this.mount(1);\n }\n this.scheduleFrame();\n }\n\n public dispose(): void {\n this.unmount();\n this.host.removeAttribute('aria-busy');\n }\n\n private mount(restingDots: number): void {\n const renderer = this.createRenderer(this.options.renderer);\n if (renderer == null) {\n return;\n }\n this.styleHost();\n // last, not first: hydration finds the host's own nodes from its first child\n this.host.append(renderer.canvas);\n this.renderer = renderer;\n this.timeline = new WaveTimeline(\n this.options.afterLoading,\n !this.env.prefersReducedMotion(),\n restingDots\n );\n this.visible = true;\n this.disconnects = [\n this.env.observeSize(this.host, () => this.resize()),\n this.env.observeVisibility(this.host, (visible) =>\n this.setVisible(visible)\n ),\n this.env.observeTheme(() => this.recolor()),\n ];\n this.resize();\n this.onRendererChange(renderer.kind);\n }\n\n private unmount(): void {\n this.cancelFrame();\n this.disconnects.forEach((disconnect) => disconnect());\n this.disconnects = [];\n if (this.renderer != null) {\n this.renderer.dispose();\n this.renderer.canvas.remove();\n this.onRendererChange(null);\n }\n this.renderer = undefined;\n this.timeline = undefined;\n this.restoreHost();\n }\n\n private createRenderer(\n preference: LoadingWaveOptions['renderer']\n ): WaveRenderer | null {\n const renderer = this.env.chooseRenderer({\n preference,\n look: this.look(),\n shader: this.options.shader,\n createCanvas: () => this.env.createCanvas(),\n onContextLost: () => this.fallBackToCanvas(),\n });\n if (renderer != null) {\n renderer.canvas.setAttribute('aria-hidden', 'true');\n Object.assign(renderer.canvas.style, CANVAS_STYLE);\n }\n return renderer;\n }\n\n /** the GPU took the WebGL context away: go on with a 2D canvas */\n private fallBackToCanvas(): void {\n const lost = this.renderer;\n const replacement = this.createRenderer('canvas');\n if (lost == null || replacement == null) {\n this.unmount();\n return;\n }\n lost.canvas.replaceWith(replacement.canvas);\n lost.dispose();\n this.renderer = replacement;\n this.resize();\n this.onRendererChange(replacement.kind);\n }\n\n private look(): WaveLook {\n const { dotSize, color, accentColor } = this.options;\n return {\n dotSize,\n color: this.env.resolveColor(this.host, color),\n accent:\n accentColor === undefined\n ? undefined\n : this.env.resolveColor(this.host, accentColor),\n };\n }\n\n private resize(): void {\n const { clientWidth: width, clientHeight: height } = this.host;\n this.renderer?.resize(\n waveGeometry(width, height, {\n dotSpacing: this.options.dotSpacing,\n sweepMs: this.options.sweepMs,\n frontRoundness: this.options.frontRoundness,\n }),\n fitPixelRatio(width, height, this.env.pixelRatio())\n );\n // a resized canvas is blank until drawn again\n this.scheduleFrame();\n }\n\n private recolor(): void {\n this.renderer?.setLook(this.look());\n this.scheduleFrame();\n }\n\n private setVisible(visible: boolean): void {\n this.visible = visible;\n if (visible) {\n this.scheduleFrame();\n } else {\n this.cancelFrame();\n }\n }\n\n private scheduleFrame(): void {\n if (this.frameId != null || !this.visible || this.renderer == null) {\n return;\n }\n this.frameId = this.env.requestFrame(() => this.drawFrame());\n }\n\n private cancelFrame(): void {\n if (this.frameId != null) {\n this.env.cancelFrame(this.frameId);\n this.frameId = undefined;\n }\n }\n\n private drawFrame(): void {\n this.frameId = undefined;\n if (this.renderer == null || this.timeline == null) {\n return;\n }\n const { frame, settled, finished } = this.timeline.frameAt(this.env.now());\n if (finished) {\n this.unmount();\n return;\n }\n this.renderer.draw(frame);\n if (!settled) {\n this.scheduleFrame();\n }\n }\n\n /**\n * `isolation` keeps the canvas's `z-index: -1` above the host's own\n * background; a static host becomes `relative` to hold the canvas.\n */\n private styleHost(): void {\n const { style } = this.host;\n this.hostStyle = { position: style.position, isolation: style.isolation };\n const view = this.host.ownerDocument.defaultView;\n const position = view?.getComputedStyle(this.host).position;\n // jsdom leaves an unset position empty\n if (position === 'static' || position === '') {\n style.position = 'relative';\n }\n style.isolation = 'isolate';\n }\n\n private restoreHost(): void {\n if (this.hostStyle != null) {\n this.host.style.position = this.hostStyle.position;\n this.host.style.isolation = this.hostStyle.isolation;\n this.hostStyle = undefined;\n }\n }\n}\n"]}
@@ -0,0 +1,18 @@
1
+ /** the frame's grid opacity times the colour's own */
2
+ export function dotsOpacity(frame, color) {
3
+ return frame.dots * (color.alpha ?? 1);
4
+ }
5
+ /** opacity of a dot at rest, times the colour's */
6
+ export const REST_ALPHA = 0.22;
7
+ /** opacity of a dot right behind the front */
8
+ export const LIT_ALPHA = 0.9;
9
+ /** how much a dot right behind the front grows, 0.8 = 80% larger */
10
+ export const LIT_GROWTH = 0.8;
11
+ /** opacity of the hairline along the front */
12
+ export const FRONT_LINE_ALPHA = 0.14;
13
+ /** sets the canvas's backing store to the CSS size times the pixel ratio */
14
+ export function sizeCanvas(canvas, geometry, pixelRatio) {
15
+ canvas.width = Math.max(1, Math.round(geometry.width * pixelRatio));
16
+ canvas.height = Math.max(1, Math.round(geometry.height * pixelRatio));
17
+ }
18
+ //# sourceMappingURL=renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"renderer.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/renderer.ts"],"names":[],"mappings":"AAcA,sDAAsD;AACtD,MAAM,UAAU,WAAW,CAAC,KAAgB,EAAE,KAAU;IACtD,OAAO,KAAK,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;AACzC,CAAC;AAqBD,mDAAmD;AACnD,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC;AAC/B,8CAA8C;AAC9C,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,CAAC;AAC7B,oEAAoE;AACpE,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAC9B,8CAA8C;AAC9C,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAiBrC,4EAA4E;AAC5E,MAAM,UAAU,UAAU,CACxB,MAAyB,EACzB,QAAsB,EACtB,UAAkB;IAElB,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,GAAG,UAAU,CAAC,CAAC,CAAC;IACpE,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import type { ShaderUniforms } from './webgl/loading-wave-shader';\nimport type { WaveGeometry } from './wave-model';\n\nexport type WaveRendererKind = 'webgl' | 'canvas';\n\n/** a colour channel by channel, each 0 to 255 */\nexport interface Rgb {\n readonly r: number;\n readonly g: number;\n readonly b: number;\n /** the colour's own opacity, 0 to 1; 1 when unset */\n readonly alpha?: number;\n}\n\n/** the frame's grid opacity times the colour's own */\nexport function dotsOpacity(frame: WaveFrame, color: Rgb): number {\n return frame.dots * (color.alpha ?? 1);\n}\n\n/** how the dots look, the same in both renderers */\nexport interface WaveLook {\n /** diameter of a dot at rest, in CSS pixels */\n readonly dotSize: number;\n readonly color: Rgb;\n /** the colour lit dots and the wave take; the dots' colour when unset */\n readonly accent?: Rgb;\n}\n\n/** what one frame shows */\nexport interface WaveFrame {\n /** time since the wave started, drives where the front is */\n readonly elapsedMs: number;\n /** strength of the wave, 0 (no wave) to 1, for fading it in and out */\n readonly wave: number;\n /** opacity of the whole dot grid, 0 to 1, for fading it in and out */\n readonly dots: number;\n}\n\n/** opacity of a dot at rest, times the colour's */\nexport const REST_ALPHA = 0.22;\n/** opacity of a dot right behind the front */\nexport const LIT_ALPHA = 0.9;\n/** how much a dot right behind the front grows, 0.8 = 80% larger */\nexport const LIT_GROWTH = 0.8;\n/** opacity of the hairline along the front */\nexport const FRONT_LINE_ALPHA = 0.14;\n\n/** draws the dot grid and the wave into its own canvas */\nexport interface WaveRenderer {\n readonly kind: WaveRendererKind;\n readonly canvas: HTMLCanvasElement;\n /** sizes the canvas to the geometry at the given device pixel ratio */\n resize(geometry: WaveGeometry, pixelRatio: number): void;\n draw(frame: WaveFrame): void;\n /** changes the dots' look, say after the theme changed the host's colour */\n setLook(look: WaveLook): void;\n /** changes the values of a shader's own uniforms; only WebGL has any */\n setShaderUniforms(uniforms: ShaderUniforms | undefined): void;\n /** frees what the renderer holds; the canvas stays where it is */\n dispose(): void;\n}\n\n/** sets the canvas's backing store to the CSS size times the pixel ratio */\nexport function sizeCanvas(\n canvas: HTMLCanvasElement,\n geometry: WaveGeometry,\n pixelRatio: number\n): void {\n canvas.width = Math.max(1, Math.round(geometry.width * pixelRatio));\n canvas.height = Math.max(1, Math.round(geometry.height * pixelRatio));\n}\n"]}
@@ -0,0 +1,59 @@
1
+ import { chooseWaveRenderer } from './choose-wave-renderer';
2
+ import { resolveDotColor } from './dot-color';
3
+ /** sharper than this the dots gain nothing, the GPU only works more */
4
+ const MAX_PIXEL_RATIO = 2;
5
+ const noop = () => undefined;
6
+ /** the real browser, tolerant of the APIs a browser (or jsdom) lacks */
7
+ export function browserWaveEnvironment(document) {
8
+ const view = document.defaultView;
9
+ const createCanvas = () => document.createElement('canvas');
10
+ return {
11
+ now: () => view?.performance.now() ?? Date.now(),
12
+ requestFrame: (callback) => view?.requestAnimationFrame(() => callback()) ?? 0,
13
+ cancelFrame: (id) => view?.cancelAnimationFrame(id),
14
+ pixelRatio: () => Math.min(MAX_PIXEL_RATIO, view?.devicePixelRatio || 1),
15
+ prefersReducedMotion: () => view?.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false,
16
+ createCanvas,
17
+ chooseRenderer: chooseWaveRenderer,
18
+ resolveColor: (host, color) => resolveDotColor(host, color, createCanvas),
19
+ observeSize: (element, onResize) => {
20
+ if (view?.ResizeObserver == null) {
21
+ return noop;
22
+ }
23
+ const observer = new view.ResizeObserver(() => onResize());
24
+ observer.observe(element);
25
+ return () => observer.disconnect();
26
+ },
27
+ observeVisibility: (element, onChange) => {
28
+ if (view?.IntersectionObserver == null) {
29
+ return noop;
30
+ }
31
+ const observer = new view.IntersectionObserver((entries) => onChange(entries.some((entry) => entry.isIntersecting)));
32
+ observer.observe(element);
33
+ return () => observer.disconnect();
34
+ },
35
+ observeTheme: (onChange) => observeTheme(document, onChange),
36
+ };
37
+ }
38
+ /** the colour scheme of the system, or a class or attribute on the root */
39
+ function observeTheme(document, onChange) {
40
+ const view = document.defaultView;
41
+ const scheme = view?.matchMedia?.('(prefers-color-scheme: dark)');
42
+ // optional calls: Safari before 14 knows only addListener
43
+ scheme?.addEventListener?.('change', onChange);
44
+ const observer = view?.MutationObserver == null
45
+ ? undefined
46
+ : new view.MutationObserver(() => onChange());
47
+ observer?.observe(document.documentElement, { attributes: true });
48
+ if (document.body != null) {
49
+ observer?.observe(document.body, {
50
+ attributes: true,
51
+ attributeFilter: ['class', 'style'],
52
+ });
53
+ }
54
+ return () => {
55
+ scheme?.removeEventListener?.('change', onChange);
56
+ observer?.disconnect();
57
+ };
58
+ }
59
+ //# sourceMappingURL=wave-environment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wave-environment.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/wave-environment.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AA2B9C,uEAAuE;AACvE,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,MAAM,IAAI,GAAe,GAAG,EAAE,CAAC,SAAS,CAAC;AAEzC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,CAAC,IAAI,EAAE;YAC/B,UAAU,EAAE,IAAI;YAChB,eAAe,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC;SACpC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,GAAG,EAAE;QACV,MAAM,EAAE,mBAAmB,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAClD,QAAQ,EAAE,UAAU,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ChooseWaveRendererParams } from './choose-wave-renderer';\nimport { chooseWaveRenderer } from './choose-wave-renderer';\nimport { resolveDotColor } from './dot-color';\nimport type { Rgb, WaveRenderer } from './renderer';\n\n/** stops an observation */\nexport type Disconnect = () => void;\n\n/** what the loading wave takes from the browser, replaceable in specs */\nexport interface WaveEnvironment {\n now(): number;\n requestFrame(callback: () => void): number;\n cancelFrame(id: number): void;\n pixelRatio(): number;\n prefersReducedMotion(): boolean;\n createCanvas(): HTMLCanvasElement;\n chooseRenderer(params: ChooseWaveRendererParams): WaveRenderer | null;\n resolveColor(host: HTMLElement, color: string | undefined): Rgb;\n /** calls back when the element's size changed */\n observeSize(element: HTMLElement, onResize: () => void): Disconnect;\n /** calls back when the element enters or leaves the viewport */\n observeVisibility(\n element: HTMLElement,\n onChange: (visible: boolean) => void\n ): Disconnect;\n /** calls back when the page's theme may have changed the colours */\n observeTheme(onChange: () => void): Disconnect;\n}\n\n/** sharper than this the dots gain nothing, the GPU only works more */\nconst MAX_PIXEL_RATIO = 2;\n\nconst noop: Disconnect = () => undefined;\n\n/** the real browser, tolerant of the APIs a browser (or jsdom) lacks */\nexport function browserWaveEnvironment(document: Document): WaveEnvironment {\n const view = document.defaultView;\n const createCanvas = () => document.createElement('canvas');\n return {\n now: () => view?.performance.now() ?? Date.now(),\n requestFrame: (callback) =>\n view?.requestAnimationFrame(() => callback()) ?? 0,\n cancelFrame: (id) => view?.cancelAnimationFrame(id),\n pixelRatio: () => Math.min(MAX_PIXEL_RATIO, view?.devicePixelRatio || 1),\n prefersReducedMotion: () =>\n view?.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false,\n createCanvas,\n chooseRenderer: chooseWaveRenderer,\n resolveColor: (host, color) => resolveDotColor(host, color, createCanvas),\n observeSize: (element, onResize) => {\n if (view?.ResizeObserver == null) {\n return noop;\n }\n const observer = new view.ResizeObserver(() => onResize());\n observer.observe(element);\n return () => observer.disconnect();\n },\n observeVisibility: (element, onChange) => {\n if (view?.IntersectionObserver == null) {\n return noop;\n }\n const observer = new view.IntersectionObserver((entries) =>\n onChange(entries.some((entry) => entry.isIntersecting))\n );\n observer.observe(element);\n return () => observer.disconnect();\n },\n observeTheme: (onChange) => observeTheme(document, onChange),\n };\n}\n\n/** the colour scheme of the system, or a class or attribute on the root */\nfunction observeTheme(document: Document, onChange: () => void): Disconnect {\n const view = document.defaultView;\n const scheme = view?.matchMedia?.('(prefers-color-scheme: dark)');\n // optional calls: Safari before 14 knows only addListener\n scheme?.addEventListener?.('change', onChange);\n const observer =\n view?.MutationObserver == null\n ? undefined\n : new view.MutationObserver(() => onChange());\n observer?.observe(document.documentElement, { attributes: true });\n if (document.body != null) {\n observer?.observe(document.body, {\n attributes: true,\n attributeFilter: ['class', 'style'],\n });\n }\n return () => {\n scheme?.removeEventListener?.('change', onChange);\n observer?.disconnect();\n };\n}\n"]}
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The loading wave as pure math, shared by the 2D canvas renderer and
3
+ * mirrored by the WebGL shaders' header (`webgl/shader-program.ts`).
4
+ *
5
+ * The wave front is an arc of a circle whose centre lies left of the
6
+ * element, at mid-height: a ripple from off-screen. How round it is
7
+ * (`frontRoundness`) sets the circle's radius. Its radius grows at an even
8
+ * speed, so the front sweeps from the left edge until the lit tail behind
9
+ * it has left the element at every row, then starts again.
10
+ * Every length is in CSS pixels, every time in milliseconds.
11
+ */
12
+ /**
13
+ * How round the front is by default: its ends lag its middle by half of
14
+ * `min(height / 2, width)`.
15
+ */
16
+ export const DEFAULT_FRONT_ROUNDNESS = 0.5;
17
+ /**
18
+ * The largest radius of the front's circle, times the element's larger
19
+ * side: a straight front (`frontRoundness` 0) gets this one, which keeps the
20
+ * shader's floats exact.
21
+ */
22
+ const MAX_RADIUS_SIDES = 50;
23
+ /** distance behind the front over which a dot dims to 1/e, in dot spacings */
24
+ const FALLOFF_SPACINGS = 1.5;
25
+ /** how lit a dot stays once the front passed it, as in the video */
26
+ export const AFTERGLOW = 0.45;
27
+ /** share of a sweep after which a passed dot's afterglow starts to fade */
28
+ export const AFTERGLOW_FADE_START = 0.45;
29
+ /** distance ahead of the front over which a dot lights up, in dot spacings */
30
+ const RISE_SPACINGS = 0.25;
31
+ /** length of the bright tail behind the front, in dot spacings */
32
+ const TAIL_SPACINGS = 4;
33
+ /**
34
+ * The most dots a grid holds: a tiny spacing on a large host is widened
35
+ * rather than creating millions of dots each frame.
36
+ */
37
+ export const MAX_DOTS = 20_000;
38
+ /** the farthest a lit dot is pushed along the wave, in dot spacings */
39
+ const MAX_PUSH_SPACINGS = 0.15;
40
+ export function waveGeometry(width, height, { dotSpacing: askedSpacing, sweepMs, frontRoundness = DEFAULT_FRONT_ROUNDNESS, }) {
41
+ const dotSpacing = spacingWithinDotLimit(width, height, askedSpacing);
42
+ const distance = frontCircleRadius(width, height, dotSpacing, frontRoundness);
43
+ const tail = TAIL_SPACINGS * dotSpacing;
44
+ const endRadius = Math.hypot(distance + width + tail, height / 2);
45
+ return {
46
+ width,
47
+ height,
48
+ dotSpacing,
49
+ sweepMs,
50
+ centerX: -distance,
51
+ centerY: height / 2,
52
+ startRadius: distance,
53
+ endRadius,
54
+ travel: endRadius - distance,
55
+ falloff: FALLOFF_SPACINGS * dotSpacing,
56
+ rise: RISE_SPACINGS * dotSpacing,
57
+ tail,
58
+ maxPush: MAX_PUSH_SPACINGS * dotSpacing,
59
+ };
60
+ }
61
+ /**
62
+ * The radius of the circle whose arc across the element's height lags at
63
+ * its ends by the sagitta `frontRoundness × min(height / 2, width)`:
64
+ * `R = (a² + s²) / (2s)` with `a = height / 2`, capped for a straight front.
65
+ */
66
+ function frontCircleRadius(width, height, dotSpacing, frontRoundness) {
67
+ const maxRadius = MAX_RADIUS_SIDES * Math.max(width, height, dotSpacing);
68
+ const halfHeight = height / 2;
69
+ const sagitta = frontRoundness * Math.min(halfHeight, width);
70
+ if (sagitta <= 0) {
71
+ return maxRadius;
72
+ }
73
+ return Math.min(maxRadius, (halfHeight * halfHeight + sagitta * sagitta) / (2 * sagitta));
74
+ }
75
+ /** how many dots a grid of this spacing holds, rows times columns */
76
+ function dotCount(width, height, spacing) {
77
+ const along = (length) => length <= 0 ? 0 : Math.max(0, Math.ceil(length / spacing - 0.5));
78
+ return along(width) * along(height);
79
+ }
80
+ /** the asked spacing, widened until the grid holds at most `MAX_DOTS` */
81
+ function spacingWithinDotLimit(width, height, askedSpacing) {
82
+ let spacing = Math.max(askedSpacing, Math.sqrt((width * height) / MAX_DOTS));
83
+ // the rows and columns round up: widen a little more where they still do
84
+ while (dotCount(width, height, spacing) > MAX_DOTS) {
85
+ spacing *= 1.01;
86
+ }
87
+ return spacing;
88
+ }
89
+ /** the share of the current sweep that has passed, 0 up to (not including) 1 */
90
+ export function sweepPhase(geometry, elapsedMs) {
91
+ const { sweepMs } = geometry;
92
+ return (((elapsedMs % sweepMs) + sweepMs) % sweepMs) / sweepMs;
93
+ }
94
+ /** the front's radius at the time `elapsedMs` */
95
+ export function frontRadius(geometry, elapsedMs) {
96
+ return (geometry.startRadius + geometry.travel * sweepPhase(geometry, elapsedMs));
97
+ }
98
+ /** how far the dot lies behind the front: negative ahead of it */
99
+ function distanceBehindFront(x, y, elapsedMs, geometry) {
100
+ const fromCenter = Math.hypot(x - geometry.centerX, y - geometry.centerY);
101
+ return frontRadius(geometry, elapsedMs) - fromCenter;
102
+ }
103
+ function smoothstep(edge0, edge1, value) {
104
+ const t = Math.min(1, Math.max(0, (value - edge0) / (edge1 - edge0)));
105
+ return t * t * (3 - 2 * t);
106
+ }
107
+ /**
108
+ * The bright part of the wave: 1 right behind the front, dimming
109
+ * exponentially further behind, 0 ahead of it.
110
+ */
111
+ function frontGlow(behind, geometry) {
112
+ return (smoothstep(-geometry.rise, 0, behind) *
113
+ Math.exp(-Math.max(behind, 0) / geometry.falloff));
114
+ }
115
+ /** whether a sweep went before this one, whose afterglow and echo show */
116
+ export function hasPreviousSweep(geometry, elapsedMs) {
117
+ return elapsedMs >= geometry.sweepMs;
118
+ }
119
+ /**
120
+ * What stays lit once the front passed: `AFTERGLOW` for the first part of a
121
+ * sweep, then fading out until the next front arrives. Ahead of the front a
122
+ * dot still glows from the sweep before, if there was one.
123
+ */
124
+ function afterglow(behind, geometry, elapsedMs) {
125
+ if (behind < 0 && !hasPreviousSweep(geometry, elapsedMs)) {
126
+ return 0;
127
+ }
128
+ const sincePassed = (behind >= 0 ? behind : behind + geometry.travel) / geometry.travel;
129
+ return AFTERGLOW * (1 - smoothstep(AFTERGLOW_FADE_START, 1, sincePassed));
130
+ }
131
+ /**
132
+ * How much the wave lights the dot at `(x, y)`: 1 right behind the front,
133
+ * dimming over a few spacings to the afterglow of the dots it passed, which
134
+ * fades out again until the next front comes. On the first sweep nothing
135
+ * ahead of the front is lit.
136
+ */
137
+ export function waveIntensity(x, y, elapsedMs, geometry) {
138
+ const behind = distanceBehindFront(x, y, elapsedMs, geometry);
139
+ return Math.max(frontGlow(behind, geometry), afterglow(behind, geometry, elapsedMs));
140
+ }
141
+ /**
142
+ * How far the wave pushes the dot at `(x, y)` away from the circle's centre:
143
+ * nothing at rest, most at one falloff behind the front.
144
+ */
145
+ export function dotDisplacement(x, y, elapsedMs, geometry) {
146
+ const behind = distanceBehindFront(x, y, elapsedMs, geometry);
147
+ if (behind <= 0) {
148
+ return { dx: 0, dy: 0 };
149
+ }
150
+ const scaled = behind / geometry.falloff;
151
+ const push = geometry.maxPush * scaled * Math.exp(1 - scaled);
152
+ const toX = x - geometry.centerX;
153
+ const toY = y - geometry.centerY;
154
+ const length = Math.hypot(toX, toY);
155
+ return { dx: (push * toX) / length, dy: (push * toY) / length };
156
+ }
157
+ /** the centres of the grid's dots, row by row, each centred in its cell */
158
+ export function dotCenters({ width, height, dotSpacing, }) {
159
+ const centers = [];
160
+ // an empty host has no dots, however small the spacing
161
+ if (width <= 0 || height <= 0) {
162
+ return centers;
163
+ }
164
+ for (let y = dotSpacing / 2; y < height; y += dotSpacing) {
165
+ for (let x = dotSpacing / 2; x < width; x += dotSpacing) {
166
+ centers.push({ x, y });
167
+ }
168
+ }
169
+ return centers;
170
+ }
171
+ //# sourceMappingURL=wave-model.js.map