@wolsok/loading-wave 0.0.0-stage → 0.0.1

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -2
  3. package/esm2022/index.js +6 -0
  4. package/esm2022/index.js.map +1 -0
  5. package/esm2022/lib/canvas-wave-renderer.js +103 -0
  6. package/esm2022/lib/canvas-wave-renderer.js.map +1 -0
  7. package/esm2022/lib/choose-wave-renderer.js +61 -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 +34 -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 +230 -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 +147 -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/wave-shaders.js +114 -0
  26. package/esm2022/lib/webgl/wave-shaders.js.map +1 -0
  27. package/esm2022/lib/webgl/webgl-wave-renderer.js +172 -0
  28. package/esm2022/lib/webgl/webgl-wave-renderer.js.map +1 -0
  29. package/esm2022/wolsok-loading-wave.js +5 -0
  30. package/esm2022/wolsok-loading-wave.js.map +1 -0
  31. package/index.d.ts +4 -0
  32. package/lib/canvas-wave-renderer.d.ts +27 -0
  33. package/lib/choose-wave-renderer.d.ts +28 -0
  34. package/lib/dot-color.d.ts +15 -0
  35. package/lib/loading-wave-options.d.ts +35 -0
  36. package/lib/loading-wave.d.ts +55 -0
  37. package/lib/loading-wave.directive.d.ts +29 -0
  38. package/lib/renderer.d.ts +49 -0
  39. package/lib/wave-environment.d.ts +23 -0
  40. package/lib/wave-model.d.ts +74 -0
  41. package/lib/wave-timeline.d.ts +33 -0
  42. package/lib/webgl/wave-shaders.d.ts +14 -0
  43. package/lib/webgl/webgl-wave-renderer.d.ts +47 -0
  44. package/package.json +44 -3
  45. package/wolsok-loading-wave.d.ts +5 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Wolfram Sokollek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # @wolsok/loading-wave
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A calm loading effect for Angular: a grid of small dots behind any element,
4
+ crossed again and again by a curved wave front that lights the dots it
5
+ passes. It lies in the background, so it shows that something loads without
6
+ pulling the eye away from the content.
7
+
8
+ Try it in the [playground](https://angularexamples.wolsok.de/loadingWavePlayground).
9
+
10
+ - **One directive**, a boolean input: `[wsLoadingWave]="loading()"`.
11
+ - **On the GPU where there is one:** a WebGL2 shader adds a soft glow around
12
+ the lit dots, an echo ripple trailing the front and a push through the
13
+ grid.
14
+ - **Everywhere else on a 2D canvas:** without a GPU (or when the browser
15
+ would render WebGL on the CPU), when the shader fails, when more than 8
16
+ waves run on one page or when the GPU context is lost.
17
+ - **After loading** the dots fade away (`'hide'`) or stay as a quiet dotted
18
+ background (`'keep'`).
19
+ - **Polite:** no wave with `prefers-reduced-motion`, paused off screen,
20
+ nothing on the server, `aria-busy` on the host while loading, the canvas
21
+ hidden from assistive technology.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ npm install @wolsok/loading-wave
27
+ ```
28
+
29
+ Peer dependency: `@angular/core` 22 (the version it is built with). No other dependency.
30
+
31
+ ## Use
32
+
33
+ ```ts
34
+ import { Component, signal } from '@angular/core';
35
+ import { LoadingWaveDirective } from '@wolsok/loading-wave';
36
+
37
+ @Component({
38
+ selector: 'app-results',
39
+ imports: [LoadingWaveDirective],
40
+ template: `
41
+ <section class="results" [wsLoadingWave]="loading()">
42
+ @if (loading()) {
43
+ <p>Loading results…</p>
44
+ } @else {
45
+ <app-result-list />
46
+ }
47
+ </section>
48
+ `,
49
+ })
50
+ export class ResultsComponent {
51
+ protected readonly loading = signal(true);
52
+ }
53
+ ```
54
+
55
+ The directive puts one canvas behind the host's content (`z-index: -1` in a
56
+ stacking context of the host: it gives the host `isolation: isolate`, and
57
+ `position: relative` where it was `static`). Give the host a size and,
58
+ for the look of the video, a dark background.
59
+
60
+ ### Options
61
+
62
+ Per element with `[wsLoadingWaveOptions]`, or app-wide with
63
+ `provideLoadingWave(…)` in your providers:
64
+
65
+ ```html
66
+ <header
67
+ [wsLoadingWave]="intro()"
68
+ [wsLoadingWaveOptions]="{ afterLoading: 'keep', dotSpacing: 24 }"
69
+ >
70
+ ```
71
+
72
+ ```ts
73
+ bootstrapApplication(AppComponent, {
74
+ providers: [provideLoadingWave({ color: 'var(--mat-sys-primary)' })],
75
+ });
76
+ ```
77
+
78
+ | Option | Default | What it does |
79
+ | -------------- | ------------- | -------------------------------------------------------------------------------------------------------------------- |
80
+ | `afterLoading` | `'hide'` | `'hide'`: dots and wave fade out, the canvas goes. `'keep'`: the wave fades out, the dots stay. |
81
+ | `dotSpacing` | `28` | distance between two dots, CSS pixels |
82
+ | `dotSize` | `1.5` | diameter of a dot at rest, CSS pixels |
83
+ | `color` | host's colour | any CSS colour, variables included; unset, the dots take the host's `currentColor` |
84
+ | `sweepMs` | `1600` | one sweep of the wave across the element, milliseconds |
85
+ | `renderer` | `'auto'` | `'auto'`: the shader on a GPU; `'webgl'`: also in software; both fall back to the 2D canvas. `'canvas'`: never WebGL |
86
+
87
+ The dots follow the host's colour through theme changes (a class or
88
+ attribute on `<html>` or `<body>`, or the system's colour scheme).
89
+
90
+ `exportAs: 'wsLoadingWave'` gives the template the directive; its
91
+ `activeRenderer()` signal says what draws right now (`'webgl'`, `'canvas'` or
92
+ `null`).
93
+
94
+ ## License
95
+
96
+ MIT
@@ -0,0 +1,6 @@
1
+ /*
2
+ * Public API Surface of @wolsok/loading-wave
3
+ */
4
+ export { LoadingWaveDirective } from './lib/loading-wave.directive';
5
+ export { DEFAULT_LOADING_WAVE_OPTIONS, LOADING_WAVE_OPTIONS, provideLoadingWave, } from './lib/loading-wave-options';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../libs/public/ws-loading-wave/src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EACL,4BAA4B,EAC5B,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,4BAA4B,CAAC","sourcesContent":["/*\n * Public API Surface of @wolsok/loading-wave\n */\nexport { LoadingWaveDirective } from './lib/loading-wave.directive';\nexport {\n DEFAULT_LOADING_WAVE_OPTIONS,\n LOADING_WAVE_OPTIONS,\n provideLoadingWave,\n} from './lib/loading-wave-options';\nexport type {\n AfterLoading,\n LoadingWaveOptions,\n WaveRendererPreference,\n} from './lib/loading-wave-options';\nexport type { WaveRendererKind } from './lib/renderer';\n"]}
@@ -0,0 +1,103 @@
1
+ import { dotsOpacity, FRONT_LINE_ALPHA, LIT_ALPHA, LIT_GROWTH, REST_ALPHA, sizeCanvas, } from './renderer';
2
+ import { dotCenters, dotDisplacement, frontRadius, waveIntensity, } from './wave-model';
3
+ /** below this a dot counts as at rest and is drawn in one batch */
4
+ const LIT_THRESHOLD = 0.01;
5
+ /**
6
+ * Draws the wave of the video with the 2D canvas API: dots that brighten,
7
+ * grow and are pushed a little behind the front, and the front's hairline.
8
+ * Runs everywhere, with or without a GPU.
9
+ */
10
+ export class CanvasWaveRenderer {
11
+ constructor(canvas, context, look) {
12
+ this.canvas = canvas;
13
+ this.context = context;
14
+ this.look = look;
15
+ this.kind = 'canvas';
16
+ this.centers = [];
17
+ this.pixelRatio = 1;
18
+ }
19
+ /** `null` where the canvas has no 2D context */
20
+ static create(canvas, look) {
21
+ const context = canvas.getContext('2d');
22
+ return context == null
23
+ ? null
24
+ : new CanvasWaveRenderer(canvas, context, look);
25
+ }
26
+ resize(geometry, pixelRatio) {
27
+ this.geometry = geometry;
28
+ this.pixelRatio = pixelRatio;
29
+ this.centers = dotCenters(geometry);
30
+ sizeCanvas(this.canvas, geometry, pixelRatio);
31
+ }
32
+ draw(frame) {
33
+ const { context, canvas, geometry } = this;
34
+ context.setTransform(1, 0, 0, 1, 0, 0);
35
+ context.clearRect(0, 0, canvas.width, canvas.height);
36
+ const dots = dotsOpacity(frame, this.look.color);
37
+ if (geometry == null || dots <= 0) {
38
+ return;
39
+ }
40
+ context.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
41
+ const { r, g, b } = this.look.color;
42
+ context.fillStyle = `rgb(${r}, ${g}, ${b})`;
43
+ context.strokeStyle = context.fillStyle;
44
+ const shown = { ...frame, dots };
45
+ const litDots = this.drawRestingDots(geometry, shown);
46
+ this.drawLitDots(geometry, shown, litDots);
47
+ this.drawFrontLine(geometry, shown);
48
+ context.globalAlpha = 1;
49
+ }
50
+ setLook(look) {
51
+ this.look = look;
52
+ }
53
+ dispose() {
54
+ this.geometry = undefined;
55
+ this.centers = [];
56
+ }
57
+ /** draws every dot at rest in one path, returns the lit ones */
58
+ drawRestingDots(geometry, frame) {
59
+ const { context } = this;
60
+ const radius = this.look.dotSize / 2;
61
+ const lit = [];
62
+ context.globalAlpha = frame.dots * REST_ALPHA;
63
+ context.beginPath();
64
+ for (const center of this.centers) {
65
+ const intensity = frame.wave > 0
66
+ ? frame.wave *
67
+ waveIntensity(center.x, center.y, frame.elapsedMs, geometry)
68
+ : 0;
69
+ if (intensity >= LIT_THRESHOLD) {
70
+ lit.push({ center, intensity });
71
+ continue;
72
+ }
73
+ context.moveTo(center.x + radius, center.y);
74
+ context.arc(center.x, center.y, radius, 0, 2 * Math.PI);
75
+ }
76
+ context.fill();
77
+ return lit;
78
+ }
79
+ drawLitDots(geometry, frame, litDots) {
80
+ const { context } = this;
81
+ const restRadius = this.look.dotSize / 2;
82
+ for (const { center, intensity } of litDots) {
83
+ const { dx, dy } = dotDisplacement(center.x, center.y, frame.elapsedMs, geometry);
84
+ context.globalAlpha =
85
+ frame.dots * (REST_ALPHA + (LIT_ALPHA - REST_ALPHA) * intensity);
86
+ context.beginPath();
87
+ context.arc(center.x + dx * frame.wave, center.y + dy * frame.wave, restRadius * (1 + LIT_GROWTH * intensity), 0, 2 * Math.PI);
88
+ context.fill();
89
+ }
90
+ }
91
+ drawFrontLine(geometry, frame) {
92
+ if (frame.wave <= 0) {
93
+ return;
94
+ }
95
+ const { context } = this;
96
+ context.globalAlpha = frame.dots * frame.wave * FRONT_LINE_ALPHA;
97
+ context.lineWidth = 1 / this.pixelRatio;
98
+ context.beginPath();
99
+ context.arc(geometry.centerX, geometry.centerY, frontRadius(geometry, frame.elapsedMs), -Math.PI / 2, Math.PI / 2);
100
+ context.stroke();
101
+ }
102
+ }
103
+ //# sourceMappingURL=canvas-wave-renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canvas-wave-renderer.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/canvas-wave-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,SAAS,EACT,UAAU,EACV,UAAU,EACV,UAAU,GAIX,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,UAAU,EACV,eAAe,EACf,WAAW,EAGX,aAAa,GACd,MAAM,cAAc,CAAC;AAQtB,mEAAmE;AACnE,MAAM,aAAa,GAAG,IAAI,CAAC;AAE3B;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAM7B,YACkB,MAAyB,EACxB,OAAiC,EAC1C,IAAc;QAFN,WAAM,GAAN,MAAM,CAAmB;QACxB,YAAO,GAAP,OAAO,CAA0B;QAC1C,SAAI,GAAJ,IAAI,CAAU;QARR,SAAI,GAAG,QAAQ,CAAC;QAExB,YAAO,GAAY,EAAE,CAAC;QACtB,eAAU,GAAG,CAAC,CAAC;IAMpB,CAAC;IAEJ,gDAAgD;IACzC,MAAM,CAAC,MAAM,CAClB,MAAyB,EACzB,IAAc;QAEd,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACxC,OAAO,OAAO,IAAI,IAAI;YACpB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,IAAI,kBAAkB,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IACpD,CAAC;IAEM,MAAM,CAAC,QAAsB,EAAE,UAAkB;QACtD,IAAI,CAAC,Q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I,CAAC;QACzB,OAAO,CAAC,WAAW,GAAG,KAAK,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,GAAG,gBAAgB,CAAC;QACjE,OAAO,CAAC,SAAS,GAAG,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC;QACxC,OAAO,CAAC,SAAS,EAAE,CAAC;QACpB,OAAO,CAAC,GAAG,CACT,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,WAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,EACtC,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EACZ,IAAI,CAAC,EAAE,GAAG,CAAC,CACZ,CAAC;QACF,OAAO,CAAC,MAAM,EAAE,CAAC;IACnB,CAAC;CACF","sourcesContent":["import {\n dotsOpacity,\n FRONT_LINE_ALPHA,\n LIT_ALPHA,\n LIT_GROWTH,\n REST_ALPHA,\n sizeCanvas,\n WaveFrame,\n WaveLook,\n WaveRenderer,\n} from './renderer';\nimport {\n dotCenters,\n dotDisplacement,\n frontRadius,\n Point,\n WaveGeometry,\n waveIntensity,\n} from './wave-model';\n\n/** a dot the wave lights, drawn on its own */\ninterface LitDot {\n readonly center: Point;\n readonly intensity: number;\n}\n\n/** below this a dot counts as at rest and is drawn in one batch */\nconst LIT_THRESHOLD = 0.01;\n\n/**\n * Draws the wave of the video with the 2D canvas API: dots that brighten,\n * grow and are pushed a little behind the front, and the front's hairline.\n * Runs everywhere, with or without a GPU.\n */\nexport class CanvasWaveRenderer implements WaveRenderer {\n public readonly kind = 'canvas';\n private geometry?: WaveGeometry;\n private centers: Point[] = [];\n private pixelRatio = 1;\n\n private constructor(\n public readonly canvas: HTMLCanvasElement,\n private readonly context: CanvasRenderingContext2D,\n private look: WaveLook\n ) {}\n\n /** `null` where the canvas has no 2D context */\n public static create(\n canvas: HTMLCanvasElement,\n look: WaveLook\n ): CanvasWaveRenderer | null {\n const context = canvas.getContext('2d');\n return context == null\n ? null\n : new CanvasWaveRenderer(canvas, context, look);\n }\n\n public resize(geometry: WaveGeometry, pixelRatio: number): void {\n this.geometry = geometry;\n this.pixelRatio = pixelRatio;\n this.centers = dotCenters(geometry);\n sizeCanvas(this.canvas, geometry, pixelRatio);\n }\n\n public draw(frame: WaveFrame): void {\n const { context, canvas, geometry } = this;\n context.setTransform(1, 0, 0, 1, 0, 0);\n context.clearRect(0, 0, canvas.width, canvas.height);\n const dots = dotsOpacity(frame, this.look.color);\n if (geometry == null || dots <= 0) {\n return;\n }\n context.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);\n const { r, g, b } = this.look.color;\n context.fillStyle = `rgb(${r}, ${g}, ${b})`;\n context.strokeStyle = context.fillStyle;\n const shown = { ...frame, dots };\n const litDots = this.drawRestingDots(geometry, shown);\n this.drawLitDots(geometry, shown, litDots);\n this.drawFrontLine(geometry, shown);\n context.globalAlpha = 1;\n }\n\n public setLook(look: WaveLook): void {\n this.look = look;\n }\n\n public dispose(): void {\n this.geometry = undefined;\n this.centers = [];\n }\n\n /** draws every dot at rest in one path, returns the lit ones */\n private drawRestingDots(geometry: WaveGeometry, frame: WaveFrame): LitDot[] {\n const { context } = this;\n const radius = this.look.dotSize / 2;\n const lit: LitDot[] = [];\n context.globalAlpha = frame.dots * REST_ALPHA;\n context.beginPath();\n for (const center of this.centers) {\n const intensity =\n frame.wave > 0\n ? frame.wave *\n waveIntensity(center.x, center.y, frame.elapsedMs, geometry)\n : 0;\n if (intensity >= LIT_THRESHOLD) {\n lit.push({ center, intensity });\n continue;\n }\n context.moveTo(center.x + radius, center.y);\n context.arc(center.x, center.y, radius, 0, 2 * Math.PI);\n }\n context.fill();\n return lit;\n }\n\n private drawLitDots(\n geometry: WaveGeometry,\n frame: WaveFrame,\n litDots: LitDot[]\n ): void {\n const { context } = this;\n const restRadius = this.look.dotSize / 2;\n for (const { center, intensity } of litDots) {\n const { dx, dy } = dotDisplacement(\n center.x,\n center.y,\n frame.elapsedMs,\n geometry\n );\n context.globalAlpha =\n frame.dots * (REST_ALPHA + (LIT_ALPHA - REST_ALPHA) * intensity);\n context.beginPath();\n context.arc(\n center.x + dx * frame.wave,\n center.y + dy * frame.wave,\n restRadius * (1 + LIT_GROWTH * intensity),\n 0,\n 2 * Math.PI\n );\n context.fill();\n }\n }\n\n private drawFrontLine(geometry: WaveGeometry, frame: WaveFrame): void {\n if (frame.wave <= 0) {\n return;\n }\n const { context } = this;\n context.globalAlpha = frame.dots * frame.wave * FRONT_LINE_ALPHA;\n context.lineWidth = 1 / this.pixelRatio;\n context.beginPath();\n context.arc(\n geometry.centerX,\n geometry.centerY,\n frontRadius(geometry, frame.elapsedMs),\n -Math.PI / 2,\n Math.PI / 2\n );\n context.stroke();\n }\n}\n"]}
@@ -0,0 +1,61 @@
1
+ import { CanvasWaveRenderer } from './canvas-wave-renderer';
2
+ import { WebGlWaveRenderer } from './webgl/webgl-wave-renderer';
3
+ /**
4
+ * Browsers drop the oldest WebGL context once about 16 are alive, so only
5
+ * this many waves draw on the GPU at the same time; the rest use the 2D canvas.
6
+ */
7
+ const MAX_GPU_WAVES = 8;
8
+ /** counts the waves that hold a WebGL context */
9
+ export class GpuContextBudget {
10
+ constructor(max = MAX_GPU_WAVES) {
11
+ this.max = max;
12
+ this.live = 0;
13
+ }
14
+ tryAcquire() {
15
+ if (this.live >= this.max) {
16
+ return false;
17
+ }
18
+ this.live++;
19
+ return true;
20
+ }
21
+ release() {
22
+ this.live = Math.max(0, this.live - 1);
23
+ }
24
+ }
25
+ /** the budget all waves of the page share */
26
+ export const PAGE_GPU_BUDGET = new GpuContextBudget();
27
+ /**
28
+ * The WebGL renderer where WebGL2 runs (for `'auto'` only on a GPU, for
29
+ * `'webgl'` also in software), the budget allows one more and the shaders
30
+ * compile; the 2D canvas renderer otherwise and always for `'canvas'`.
31
+ * `null` only where not even a 2D context exists.
32
+ */
33
+ export function chooseWaveRenderer(params) {
34
+ const gpuRenderer = params.preference === 'canvas' ? null : tryWebGlRenderer(params);
35
+ return (gpuRenderer ?? CanvasWaveRenderer.create(params.createCanvas(), params.look));
36
+ }
37
+ function tryWebGlRenderer({ preference, look, createCanvas, onContextLost, gpuBudget = PAGE_GPU_BUDGET, }) {
38
+ if (!gpuBudget.tryAcquire()) {
39
+ return null;
40
+ }
41
+ const canvas = createCanvas();
42
+ // 'webgl' takes a software-rendered context too, 'auto' only a GPU's
43
+ const gl = WebGlWaveRenderer.createContext(canvas, preference === 'auto');
44
+ if (gl == null) {
45
+ gpuBudget.release();
46
+ return null;
47
+ }
48
+ try {
49
+ return new WebGlWaveRenderer(canvas, gl, look, {
50
+ onContextLost,
51
+ onDispose: () => gpuBudget.release(),
52
+ });
53
+ }
54
+ catch (error) {
55
+ console.warn('ws-loading-wave: drawing on a 2D canvas instead', error);
56
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
57
+ gpuBudget.release();
58
+ return null;
59
+ }
60
+ }
61
+ //# sourceMappingURL=choose-wave-renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"choose-wave-renderer.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/choose-wave-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAG5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE;;;GAGG;AACH,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,iDAAiD;AACjD,MAAM,OAAO,gBAAgB;IAG3B,YAAoC,MAAM,aAAa;QAAnB,QAAG,GAAH,GAAG,CAAgB;QAF/C,SAAI,GAAG,CAAC,CAAC;IAEyC,CAAC;IAEpD,UAAU;QACf,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,IA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QACvE,EAAE,CAAC,YAAY,CAAC,oBAAoB,CAAC,EAAE,WAAW,EAAE,CAAC;QACrD,SAAS,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { CanvasWaveRenderer } from './canvas-wave-renderer';\nimport type { WaveRendererPreference } from './loading-wave-options';\nimport type { WaveLook, WaveRenderer } from './renderer';\nimport { WebGlWaveRenderer } from './webgl/webgl-wave-renderer';\n\n/**\n * Browsers drop the oldest WebGL context once about 16 are alive, so only\n * this many waves draw on the GPU at the same time; the rest use the 2D canvas.\n */\nconst MAX_GPU_WAVES = 8;\n\n/** counts the waves that hold a WebGL context */\nexport class GpuContextBudget {\n private live = 0;\n\n public constructor(private readonly max = MAX_GPU_WAVES) {}\n\n public tryAcquire(): boolean {\n if (this.live >= this.max) {\n return false;\n }\n this.live++;\n return true;\n }\n\n public release(): void {\n this.live = Math.max(0, this.live - 1);\n }\n}\n\n/** the budget all waves of the page share */\nexport const PAGE_GPU_BUDGET = new GpuContextBudget();\n\nexport interface ChooseWaveRendererParams {\n readonly preference: WaveRendererPreference;\n readonly look: WaveLook;\n /** a new, detached canvas for each renderer tried */\n readonly createCanvas: () => HTMLCanvasElement;\n /** the WebGL renderer lost its context; swap it for a 2D one */\n readonly onContextLost: () => void;\n readonly gpuBudget?: GpuContextBudget;\n}\n\n/**\n * The WebGL renderer where WebGL2 runs (for `'auto'` only on a GPU, for\n * `'webgl'` also in software), the budget allows one more and the shaders\n * compile; the 2D canvas renderer otherwise and always for `'canvas'`.\n * `null` only where not even a 2D context exists.\n */\nexport function chooseWaveRenderer(\n params: ChooseWaveRendererParams\n): WaveRenderer | null {\n const gpuRenderer =\n params.preference === 'canvas' ? null : tryWebGlRenderer(params);\n return (\n gpuRenderer ?? CanvasWaveRenderer.create(params.createCanvas(), params.look)\n );\n}\n\nfunction tryWebGlRenderer({\n preference,\n look,\n createCanvas,\n onContextLost,\n gpuBudget = PAGE_GPU_BUDGET,\n}: ChooseWaveRendererParams): WaveRenderer | null {\n if (!gpuBudget.tryAcquire()) {\n return null;\n }\n const canvas = createCanvas();\n // 'webgl' takes a software-rendered context too, 'auto' only a GPU's\n const gl = WebGlWaveRenderer.createContext(canvas, preference === 'auto');\n if (gl == null) {\n gpuBudget.release();\n return null;\n }\n try {\n return new WebGlWaveRenderer(canvas, gl, look, {\n onContextLost,\n onDispose: () => gpuBudget.release(),\n });\n } catch (error) {\n console.warn('ws-loading-wave: drawing on a 2D canvas instead', error);\n gl.getExtension('WEBGL_lose_context')?.loseContext();\n gpuBudget.release();\n return null;\n }\n}\n"]}
@@ -0,0 +1,63 @@
1
+ /** the colour the dots take when the host's colour cannot be read */
2
+ export const FALLBACK_DOT_COLOR = { r: 128, g: 128, b: 128 };
3
+ const RGB_FUNCTION = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+)(%?))?/i;
4
+ /** reads `rgb(…)`/`rgba(…)`, as `getComputedStyle` gives most colours */
5
+ export function parseRgbFunction(cssColor) {
6
+ const match = RGB_FUNCTION.exec(cssColor.trim());
7
+ if (match == null) {
8
+ return null;
9
+ }
10
+ const [r, g, b] = match.slice(1, 4).map((channel) => clampChannel(+channel));
11
+ const [, , , , alphaText, percent] = match;
12
+ return { r, g, b, alpha: parseAlpha(alphaText, percent === '%') };
13
+ }
14
+ /** `undefined` (no alpha given) is opaque */
15
+ function parseAlpha(text, percent) {
16
+ if (text === undefined) {
17
+ return 1;
18
+ }
19
+ const value = percent ? +text / 100 : +text;
20
+ return Math.min(1, Math.max(0, value));
21
+ }
22
+ function clampChannel(value) {
23
+ return Math.round(Math.min(255, Math.max(0, value)));
24
+ }
25
+ /**
26
+ * Turns any computed CSS colour into channels: `rgb()` directly, others
27
+ * (`oklch()`, `color()`, …) by painting one pixel with a 2D canvas.
28
+ */
29
+ export function cssColorToRgb(cssColor, createCanvas) {
30
+ const parsed = parseRgbFunction(cssColor);
31
+ if (parsed != null) {
32
+ return parsed;
33
+ }
34
+ const canvas = createCanvas();
35
+ canvas.width = 1;
36
+ canvas.height = 1;
37
+ const context = canvas.getContext('2d', { willReadFrequently: true });
38
+ if (context == null) {
39
+ return FALLBACK_DOT_COLOR;
40
+ }
41
+ context.fillStyle = cssColor;
42
+ context.fillRect(0, 0, 1, 1);
43
+ const [r, g, b, alpha] = context.getImageData(0, 0, 1, 1).data;
44
+ return { r, g, b, alpha: alpha / 255 };
45
+ }
46
+ /**
47
+ * The colour `color` (any CSS colour, variables included) has inside `host`;
48
+ * the host's own `currentColor` without one.
49
+ */
50
+ export function resolveDotColor(host, color, createCanvas) {
51
+ const view = host.ownerDocument.defaultView;
52
+ if (view == null) {
53
+ return FALLBACK_DOT_COLOR;
54
+ }
55
+ const probe = host.ownerDocument.createElement('span');
56
+ probe.style.display = 'none';
57
+ probe.style.color = color ?? 'currentColor';
58
+ host.appendChild(probe);
59
+ const computed = view.getComputedStyle(probe).color;
60
+ probe.remove();
61
+ return cssColorToRgb(computed, createCanvas);
62
+ }
63
+ //# sourceMappingURL=dot-color.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dot-color.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/dot-color.ts"],"names":[],"mappings":"AAEA,qEAAqE;AACrE,MAAM,CAAC,MAAM,kBAAkB,GAAQ,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC;AAElE,MAAM,YAAY,GAChB,6EAA6E,CAAC;AAEhF,yEAAyE;AACzE,MAAM,UAAU,gBAAgB,CAAC,QAAgB;IAC/C,MAAM,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IACjD,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,CAAC,CAAC,EAAE,CAAC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aAAa,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type { Rgb } from './renderer';\n\n/** the colour the dots take when the host's colour cannot be read */\nexport const FALLBACK_DOT_COLOR: Rgb = { r: 128, g: 128, b: 128 };\n\nconst RGB_FUNCTION =\n /^rgba?\\(\\s*([\\d.]+)[\\s,]+([\\d.]+)[\\s,]+([\\d.]+)(?:\\s*[,/]\\s*([\\d.]+)(%?))?/i;\n\n/** reads `rgb(…)`/`rgba(…)`, as `getComputedStyle` gives most colours */\nexport function parseRgbFunction(cssColor: string): Rgb | null {\n const match = RGB_FUNCTION.exec(cssColor.trim());\n if (match == null) {\n return null;\n }\n const [r, g, b] = match.slice(1, 4).map((channel) => clampChannel(+channel));\n const [, , , , alphaText, percent] = match;\n return { r, g, b, alpha: parseAlpha(alphaText, percent === '%') };\n}\n\n/** `undefined` (no alpha given) is opaque */\nfunction parseAlpha(text: string | undefined, percent: boolean): number {\n if (text === undefined) {\n return 1;\n }\n const value = percent ? +text / 100 : +text;\n return Math.min(1, Math.max(0, value));\n}\n\nfunction clampChannel(value: number): number {\n return Math.round(Math.min(255, Math.max(0, value)));\n}\n\n/**\n * Turns any computed CSS colour into channels: `rgb()` directly, others\n * (`oklch()`, `color()`, …) by painting one pixel with a 2D canvas.\n */\nexport function cssColorToRgb(\n cssColor: string,\n createCanvas: () => HTMLCanvasElement\n): Rgb {\n const parsed = parseRgbFunction(cssColor);\n if (parsed != null) {\n return parsed;\n }\n const canvas = createCanvas();\n canvas.width = 1;\n canvas.height = 1;\n const context = canvas.getContext('2d', { willReadFrequently: true });\n if (context == null) {\n return FALLBACK_DOT_COLOR;\n }\n context.fillStyle = cssColor;\n context.fillRect(0, 0, 1, 1);\n const [r, g, b, alpha] = context.getImageData(0, 0, 1, 1).data;\n return { r, g, b, alpha: alpha / 255 };\n}\n\n/**\n * The colour `color` (any CSS colour, variables included) has inside `host`;\n * the host's own `currentColor` without one.\n */\nexport function resolveDotColor(\n host: HTMLElement,\n color: string | undefined,\n createCanvas: () => HTMLCanvasElement\n): Rgb {\n const view = host.ownerDocument.defaultView;\n if (view == null) {\n return FALLBACK_DOT_COLOR;\n }\n const probe = host.ownerDocument.createElement('span');\n probe.style.display = 'none';\n probe.style.color = color ?? 'currentColor';\n host.appendChild(probe);\n const computed = view.getComputedStyle(probe).color;\n probe.remove();\n return cssColorToRgb(computed, createCanvas);\n}\n"]}
@@ -0,0 +1,34 @@
1
+ import { InjectionToken } from '@angular/core';
2
+ export const DEFAULT_LOADING_WAVE_OPTIONS = {
3
+ afterLoading: 'hide',
4
+ dotSpacing: 28,
5
+ dotSize: 1.5,
6
+ sweepMs: 1600,
7
+ renderer: 'auto',
8
+ };
9
+ export const LOADING_WAVE_OPTIONS = new InjectionToken('LOADING_WAVE_OPTIONS', { providedIn: 'root', factory: () => DEFAULT_LOADING_WAVE_OPTIONS });
10
+ /** sets app-wide defaults; the directive's own options still win */
11
+ export function provideLoadingWave(options) {
12
+ return {
13
+ provide: LOADING_WAVE_OPTIONS,
14
+ useValue: resolveLoadingWaveOptions(DEFAULT_LOADING_WAVE_OPTIONS, options),
15
+ };
16
+ }
17
+ /**
18
+ * Merges `overrides` into `defaults`, ignoring `undefined` values and
19
+ * replacing sizes and durations that are no positive finite number.
20
+ */
21
+ export function resolveLoadingWaveOptions(defaults, overrides = {}) {
22
+ const defined = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined));
23
+ const merged = { ...defaults, ...defined };
24
+ return {
25
+ ...merged,
26
+ dotSpacing: positiveOr(merged.dotSpacing, defaults.dotSpacing),
27
+ dotSize: positiveOr(merged.dotSize, defaults.dotSize),
28
+ sweepMs: positiveOr(merged.sweepMs, defaults.sweepMs),
29
+ };
30
+ }
31
+ function positiveOr(value, fallback) {
32
+ return Number.isFinite(value) && value > 0 ? value : fallback;
33
+ }
34
+ //# sourceMappingURL=loading-wave-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loading-wave-options.js","s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;KACtD,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,KAAa,EAAE,QAAgB;IACjD,OAAO,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC;AAChE,CAAC","sourcesContent":["import { InjectionToken, Provider } from '@angular/core';\n\n/** what the dots do once loading ended */\nexport type AfterLoading = 'hide' | 'keep';\n\n/** which renderer draws the wave */\nexport type WaveRendererPreference = 'auto' | 'webgl' | 'canvas';\n\nexport interface LoadingWaveOptions {\n /**\n * `'hide'`: dots and wave fade out and the effect is removed.\n * `'keep'`: the wave fades out, the dots stay as a quiet background.\n */\n readonly afterLoading: AfterLoading;\n /** distance between two dots, in CSS pixels */\n readonly dotSpacing: number;\n /** diameter of a dot at rest, in CSS pixels */\n readonly dotSize: number;\n /** any CSS colour; unset, the dots take the host's `currentColor` */\n readonly color?: string;\n /** how long one sweep of the wave across the element takes, in ms */\n readonly sweepMs: number;\n /**\n * `'auto'` draws with a WebGL2 shader on a GPU, `'webgl'` also where the\n * browser renders WebGL in software; both fall back to a 2D canvas where\n * that fails. `'canvas'` never uses WebGL.\n */\n readonly renderer: WaveRendererPreference;\n}\n\nexport const DEFAULT_LOADING_WAVE_OPTIONS: LoadingWaveOptions = {\n afterLoading: 'hide',\n dotSpacing: 28,\n dotSize: 1.5,\n sweepMs: 1600,\n renderer: 'auto',\n};\n\nexport const LOADING_WAVE_OPTIONS = new InjectionToken<LoadingWaveOptions>(\n 'LOADING_WAVE_OPTIONS',\n { providedIn: 'root', factory: () => DEFAULT_LOADING_WAVE_OPTIONS }\n);\n\n/** sets app-wide defaults; the directive's own options still win */\nexport function provideLoadingWave(\n options: Partial<LoadingWaveOptions>\n): Provider {\n return {\n provide: LOADING_WAVE_OPTIONS,\n useValue: resolveLoadingWaveOptions(DEFAULT_LOADING_WAVE_OPTIONS, options),\n };\n}\n\n/**\n * Merges `overrides` into `defaults`, ignoring `undefined` values and\n * replacing sizes and durations that are no positive finite number.\n */\nexport function resolveLoadingWaveOptions(\n defaults: LoadingWaveOptions,\n overrides: Partial<LoadingWaveOptions> = {}\n): LoadingWaveOptions {\n const defined = Object.fromEntries(\n Object.entries(overrides).filter(([, value]) => value !== undefined)\n ) as Partial<LoadingWaveOptions>;\n const merged = { ...defaults, ...defined };\n return {\n ...merged,\n dotSpacing: positiveOr(merged.dotSpacing, defaults.dotSpacing),\n dotSize: positiveOr(merged.dotSize, defaults.dotSize),\n sweepMs: positiveOr(merged.sweepMs, defaults.sweepMs),\n };\n}\n\nfunction positiveOr(value: number, fallback: number): number {\n return Number.isFinite(value) && value > 0 ? value : fallback;\n}\n"]}
@@ -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,CAAC;AAC7C,OAAO,EACL,oBAAoB,EAEpB,yBAAyB,GAC1B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,sBAAsB,EAAmB,MAAM,oBAAoB,CAAC;;AAE7E,4DAA4D;AAC5D,MAAM,CAAC,MAAM,wBAAwB,GAAG,IAAI,cAAc,CACxD,0BAA0B,EAC1B;IACE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ACF,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"]}