@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
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,197 @@
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 round 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 draws the wave as a
12
+ ripple through water: the dots refract through its slope, shine as small
13
+ lit beads and bloom, and an echo trails the front. Or bring your own
14
+ fragment shader (see [Shaders](#shaders)).
15
+ - **Everywhere else on a 2D canvas:** without a GPU (or when the browser
16
+ would render WebGL on the CPU), when the shader fails, when more than 8
17
+ waves run on one page or when the GPU context is lost.
18
+ - **After loading** the dots fade away (`'hide'`) or stay as a quiet dotted
19
+ background (`'keep'`).
20
+ - **Polite:** no wave with `prefers-reduced-motion`, paused off screen,
21
+ nothing on the server, `aria-busy` on the host while loading, the canvas
22
+ hidden from assistive technology.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ npm install @wolsok/loading-wave
28
+ ```
29
+
30
+ Peer dependency: `@angular/core` 22 (the version it is built with). No other dependency.
31
+
32
+ ## Use
33
+
34
+ ```ts
35
+ import { Component, signal } from '@angular/core';
36
+ import { LoadingWaveDirective } from '@wolsok/loading-wave';
37
+
38
+ @Component({
39
+ selector: 'app-results',
40
+ imports: [LoadingWaveDirective],
41
+ template: `
42
+ <section class="results" [wsLoadingWave]="loading()">
43
+ @if (loading()) {
44
+ <p>Loading results…</p>
45
+ } @else {
46
+ <app-result-list />
47
+ }
48
+ </section>
49
+ `,
50
+ })
51
+ export class ResultsComponent {
52
+ protected readonly loading = signal(true);
53
+ }
54
+ ```
55
+
56
+ The directive puts one canvas behind the host's content (`z-index: -1` in a
57
+ stacking context of the host: it gives the host `isolation: isolate`, and
58
+ `position: relative` where it was `static`). Give the host a size and,
59
+ for the look of the video, a dark background.
60
+
61
+ ### Options
62
+
63
+ Per element with `[wsLoadingWaveOptions]`, or app-wide with
64
+ `provideLoadingWave(…)` in your providers:
65
+
66
+ ```html
67
+ <header
68
+ [wsLoadingWave]="intro()"
69
+ [wsLoadingWaveOptions]="{ afterLoading: 'keep', dotSpacing: 24 }"
70
+ >
71
+ ```
72
+
73
+ ```ts
74
+ bootstrapApplication(AppComponent, {
75
+ providers: [provideLoadingWave({ color: 'var(--mat-sys-primary)' })],
76
+ });
77
+ ```
78
+
79
+ | Option | Default | What it does |
80
+ | ---------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------- |
81
+ | `afterLoading` | `'hide'` | `'hide'`: dots and wave fade out, the canvas goes. `'keep'`: the wave fades out, the dots stay. |
82
+ | `dotSpacing` | `28` | distance between two dots, CSS pixels |
83
+ | `dotSize` | `1.5` | diameter of a dot at rest, CSS pixels |
84
+ | `color` | host's colour | any CSS colour, variables included; unset, the dots take the host's `currentColor` |
85
+ | `accentColor` | dots' colour | any CSS colour for the lit dots and the wave itself |
86
+ | `sweepMs` | `1600` | one sweep of the wave across the element, milliseconds |
87
+ | `frontRoundness` | `0.5` | 0 (a straight front) to 1 (a half circle): how far the front's ends lag its middle, as a share of `min(height / 2, width)` |
88
+ | `renderer` | `'auto'` | `'auto'`: the shader on a GPU; `'webgl'`: also in software; both fall back to the 2D canvas. `'canvas'`: never WebGL |
89
+ | `shader` | `rippleShader` | the fragment shader the WebGL renderer draws with, see [Shaders](#shaders) |
90
+
91
+ Before 0.0.2 the front was nearly straight on a wide host; `frontRoundness:
92
+ 0.05` gives about that look again.
93
+
94
+ The dots follow the host's colour through theme changes (a class or
95
+ attribute on `<html>` or `<body>`, or the system's colour scheme).
96
+
97
+ `exportAs: 'wsLoadingWave'` gives the template the directive; its
98
+ `activeRenderer()` signal says what draws right now (`'webgl'`, `'canvas'` or
99
+ `null`).
100
+
101
+ ## Shaders
102
+
103
+ On the GPU the wave is drawn by a fragment shader, `rippleShader` unless
104
+ you pass another one as `shader`. The 2D canvas fallback always draws the
105
+ dot wave.
106
+
107
+ ```ts
108
+ import { LoadingWaveShader } from '@wolsok/loading-wave';
109
+
110
+ const scanShader: LoadingWaveShader = {
111
+ fragment: `
112
+ uniform float u_speed;
113
+ vec4 wsShade(vec2 point) {
114
+ vec2 center = ws_cellCenter(ws_cell(point));
115
+ float lit = ws_waveIntensity(center);
116
+ float core = ws_dotDisk(point, center, 0.5 * ws_dotSize * (1.0 + 2.0 * lit));
117
+ float scan = lit * (0.5 + 0.5 * sin(point.y * 0.5 - ws_time * u_speed));
118
+ vec4 ink = ws_ink(lit);
119
+ float dots = core * ink.a * mix(WS_REST_ALPHA, WS_LIT_ALPHA, lit);
120
+ float glow = 0.15 * scan * ws_accent.a;
121
+ float alpha = dots + glow;
122
+ return vec4((ink.rgb * dots + ws_accent.rgb * glow) / max(alpha, 1.0e-4), alpha);
123
+ }
124
+ `,
125
+ uniforms: { u_speed: 8 },
126
+ };
127
+ ```
128
+
129
+ ```html
130
+ <section
131
+ [wsLoadingWave]="loading()"
132
+ [wsLoadingWaveOptions]="{ shader: scanShader }"
133
+ >
134
+ ```
135
+
136
+ or app-wide with `provideLoadingWave({ shader: scanShader })`.
137
+
138
+ **The contract.** `fragment` is GLSL ES 3.00 that defines
139
+ `vec4 wsShade(vec2 point)`: the colour and opacity at `point`, in CSS
140
+ pixels from the host's top left corner (y down), as straight (not
141
+ premultiplied) RGBA. The lib puts `#version 300 es`, `precision highp
142
+ float`, the uniforms and helpers below before it and a `main` after it, so
143
+ the fragment holds neither. It is drawn over the host's background: draw
144
+ with alpha, not by adding light, and it reads in light and dark themes.
145
+
146
+ - **At rest** (`ws_wave == 0`) draw the resting state, without `ws_time`:
147
+ that is what `afterLoading: 'keep'` leaves and what
148
+ `prefers-reduced-motion` shows.
149
+ - **Own uniforms** are declared in the fragment and given in `uniforms`
150
+ (a number, or 2 to 4 numbers for a `vec2` to `vec4`). Changing only
151
+ `uniforms` updates a running wave, and a uniform left out goes back to 0
152
+ (as before it was first set); another `fragment` starts the wave over. The `ws_` prefix is the
153
+ lib's: `uniforms` never set a `ws_` uniform.
154
+ - **When it fails** to compile or link, the lib warns once per fragment in
155
+ the console with the GPU's log (its line numbers count from the
156
+ fragment's first line) and draws on the 2D canvas; `activeRenderer()` says
157
+ `'canvas'`.
158
+
159
+ | Uniform | Type | Holds |
160
+ | ------------------------------------------------ | ------- | ------------------------------------------------------------------------------------------------------ |
161
+ | `ws_size` | `vec2` | the host's size, CSS pixels |
162
+ | `ws_pixel` | `float` | CSS pixels per device pixel, for anti-aliasing |
163
+ | `ws_spacing` | `float` | the dot spacing in use |
164
+ | `ws_dotSize` | `float` | a resting dot's diameter |
165
+ | `ws_color` | `vec4` | the dots' colour, straight RGBA 0 to 1 |
166
+ | `ws_accent` | `vec4` | the accent colour (the dots' colour when unset) |
167
+ | `ws_center` | `vec2` | the centre of the front's circle (left of the host) |
168
+ | `ws_frontRadius` | `float` | the front's radius now |
169
+ | `ws_echoRadius` | `float` | the echo's radius, negative while there is none |
170
+ | `ws_travel` | `float` | how far the radius grows in one sweep |
171
+ | `ws_falloff`, `ws_rise`, `ws_tail`, `ws_maxPush` | `float` | the wave's lengths: dimming behind the front, lighting up ahead of it, the lit tail, the farthest push |
172
+ | `ws_phase` | `float` | the share of the sweep passed, 0 to 1 |
173
+ | `ws_time` | `float` | seconds since loading started |
174
+ | `ws_previousSweep` | `float` | 1 once a sweep went before, else 0 |
175
+ | `ws_wave` | `float` | the wave's strength, 0 to 1 (fades in and out, 0 at rest) |
176
+
177
+ | Helper | Gives |
178
+ | ---------------------------------------------------------------------- | ------------------------------------------------------------------ |
179
+ | `float ws_behindFront(vec2 p)` | how far `p` lies behind the front, negative ahead of it |
180
+ | `float ws_waveIntensity(vec2 p)` | the wave's light at `p`, 0 to 1, scaled by `ws_wave` |
181
+ | `float ws_echoGlow(vec2 p)` | the echo's light at `p` |
182
+ | `float ws_behindEcho(vec2 p)` | how far `p` lies behind the echo, far negative while there is none |
183
+ | `float ws_frontGlow(float behind)`, `float ws_afterglow(float behind)` | the two parts of `ws_waveIntensity` |
184
+ | `vec2 ws_cell(vec2 p)`, `vec2 ws_cellCenter(vec2 cell)` | the grid cell of `p` and where its dot sits |
185
+ | `float ws_dotDisk(vec2 p, vec2 center, float radius)` | anti-aliased coverage of a disk |
186
+ | `float ws_segment(vec2 p, vec2 a, vec2 b, float width)` | anti-aliased coverage of a line |
187
+ | `float ws_hash(vec2 p)`, `vec2 ws_hash2(vec2 p)` | stable pseudo-random numbers in [0, 1), say per cell |
188
+ | `vec4 ws_ink(float lit)` | the dots' colour mixed towards the accent |
189
+
190
+ The constants `WS_REST_ALPHA`, `WS_LIT_ALPHA`, `WS_LIT_GROWTH`,
191
+ `WS_FRONT_LINE_ALPHA`, `WS_AFTERGLOW`, `WS_AFTERGLOW_FADE_START` and
192
+ `WS_ECHO_STRENGTH` give the
193
+ dot wave's own look. `rippleShader`'s source is a fuller example.
194
+
195
+ ## License
196
+
197
+ MIT
@@ -0,0 +1,7 @@
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
+ export { rippleShader } from './lib/webgl/shaders/ripple.shader';
7
+ //# 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;AAapC,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,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 ResolvedLoadingWaveOptions,\n WaveRendererPreference,\n} from './lib/loading-wave-options';\nexport type { WaveRendererKind } from './lib/renderer';\nexport type {\n LoadingWaveShader,\n ShaderUniforms,\n ShaderUniformValue,\n} from './lib/webgl/loading-wave-shader';\nexport { rippleShader } from './lib/webgl/shaders/ripple.shader';\n"]}
@@ -0,0 +1,125 @@
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
+ // the colours' own opacities are applied per dot, as the shader does
37
+ const { color, accent = color } = this.look;
38
+ const visible = Math.max(dotsOpacity(frame, color), dotsOpacity(frame, accent));
39
+ if (geometry == null || visible <= 0) {
40
+ return;
41
+ }
42
+ context.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
43
+ context.fillStyle = `rgb(${color.r}, ${color.g}, ${color.b})`;
44
+ const litDots = this.drawRestingDots(geometry, frame);
45
+ this.drawLitDots(geometry, frame, litDots);
46
+ this.drawFrontLine(geometry, frame);
47
+ context.globalAlpha = 1;
48
+ }
49
+ setLook(look) {
50
+ this.look = look;
51
+ }
52
+ /** a 2D canvas runs no shader */
53
+ setShaderUniforms() {
54
+ // nothing to set
55
+ }
56
+ dispose() {
57
+ this.geometry = undefined;
58
+ this.centers = [];
59
+ }
60
+ /** draws every dot at rest in one path, returns the lit ones */
61
+ drawRestingDots(geometry, frame) {
62
+ const { context } = this;
63
+ const radius = this.look.dotSize / 2;
64
+ const lit = [];
65
+ context.globalAlpha = dotsOpacity(frame, this.look.color) * REST_ALPHA;
66
+ context.beginPath();
67
+ for (const center of this.centers) {
68
+ const intensity = frame.wave > 0
69
+ ? frame.wave *
70
+ waveIntensity(center.x, center.y, frame.elapsedMs, geometry)
71
+ : 0;
72
+ if (intensity >= LIT_THRESHOLD) {
73
+ lit.push({ center, intensity });
74
+ continue;
75
+ }
76
+ context.moveTo(center.x + radius, center.y);
77
+ context.arc(center.x, center.y, radius, 0, 2 * Math.PI);
78
+ }
79
+ context.fill();
80
+ return lit;
81
+ }
82
+ drawLitDots(geometry, frame, litDots) {
83
+ const { context } = this;
84
+ const restRadius = this.look.dotSize / 2;
85
+ const { color, accent = color } = this.look;
86
+ for (const { center, intensity } of litDots) {
87
+ if (accent !== color) {
88
+ context.fillStyle = mixedRgb(color, accent, intensity);
89
+ }
90
+ const { dx, dy } = dotDisplacement(center.x, center.y, frame.elapsedMs, geometry);
91
+ context.globalAlpha =
92
+ frame.dots *
93
+ mixedAlpha(color, accent, intensity) *
94
+ (REST_ALPHA + (LIT_ALPHA - REST_ALPHA) * intensity);
95
+ context.beginPath();
96
+ context.arc(center.x + dx * frame.wave, center.y + dy * frame.wave, restRadius * (1 + LIT_GROWTH * intensity), 0, 2 * Math.PI);
97
+ context.fill();
98
+ }
99
+ }
100
+ drawFrontLine(geometry, frame) {
101
+ if (frame.wave <= 0) {
102
+ return;
103
+ }
104
+ const { context } = this;
105
+ const { color, accent = color } = this.look;
106
+ context.strokeStyle = mixedRgb(color, accent, 1);
107
+ context.globalAlpha =
108
+ frame.dots * (accent.alpha ?? 1) * frame.wave * FRONT_LINE_ALPHA;
109
+ context.lineWidth = 1 / this.pixelRatio;
110
+ context.beginPath();
111
+ context.arc(geometry.centerX, geometry.centerY, frontRadius(geometry, frame.elapsedMs), -Math.PI / 2, Math.PI / 2);
112
+ context.stroke();
113
+ }
114
+ }
115
+ /** the colours' own opacity `share` of the way from `from` to `to` */
116
+ function mixedAlpha(from, to, share) {
117
+ const fromAlpha = from.alpha ?? 1;
118
+ return fromAlpha + ((to.alpha ?? 1) - fromAlpha) * share;
119
+ }
120
+ /** the CSS colour `share` of the way from `from` to `to` */
121
+ function mixedRgb(from, to, share) {
122
+ const mix = (a, b) => Math.round(a + (b - a) * share);
123
+ return `rgb(${mix(from.r, to.r)}, ${mix(from.g, to.g)}, ${mix(from.b, to.b)})`;
124
+ }
125
+ //# 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/l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,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;AACjF,CAAC","sourcesContent":["import {\n dotsOpacity,\n type Rgb,\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 // the colours' own opacities are applied per dot, as the shader does\n const { color, accent = color } = this.look;\n const visible = Math.max(\n dotsOpacity(frame, color),\n dotsOpacity(frame, accent)\n );\n if (geometry == null || visible <= 0) {\n return;\n }\n context.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);\n context.fillStyle = `rgb(${color.r}, ${color.g}, ${color.b})`;\n const litDots = this.drawRestingDots(geometry, frame);\n this.drawLitDots(geometry, frame, litDots);\n this.drawFrontLine(geometry, frame);\n context.globalAlpha = 1;\n }\n\n public setLook(look: WaveLook): void {\n this.look = look;\n }\n\n /** a 2D canvas runs no shader */\n public setShaderUniforms(): void {\n // nothing to set\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 = dotsOpacity(frame, this.look.color) * 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 const { color, accent = color } = this.look;\n for (const { center, intensity } of litDots) {\n if (accent !== color) {\n context.fillStyle = mixedRgb(color, accent, intensity);\n }\n const { dx, dy } = dotDisplacement(\n center.x,\n center.y,\n frame.elapsedMs,\n geometry\n );\n context.globalAlpha =\n frame.dots *\n mixedAlpha(color, accent, intensity) *\n (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 const { color, accent = color } = this.look;\n context.strokeStyle = mixedRgb(color, accent, 1);\n context.globalAlpha =\n frame.dots * (accent.alpha ?? 1) * 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\n/** the colours' own opacity `share` of the way from `from` to `to` */\nfunction mixedAlpha(from: Rgb, to: Rgb, share: number): number {\n const fromAlpha = from.alpha ?? 1;\n return fromAlpha + ((to.alpha ?? 1) - fromAlpha) * share;\n}\n\n/** the CSS colour `share` of the way from `from` to `to` */\nfunction mixedRgb(from: Rgb, to: Rgb, share: number): string {\n const mix = (a: number, b: number) => Math.round(a + (b - a) * share);\n return `rgb(${mix(from.r, to.r)}, ${mix(from.g, to.g)}, ${mix(from.b, to.b)})`;\n}\n"]}
@@ -0,0 +1,66 @@
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
+ /** fragments whose failure was reported, so a broken one warns only once */
26
+ const reportedFragments = new Set();
27
+ /** the budget all waves of the page share */
28
+ export const PAGE_GPU_BUDGET = new GpuContextBudget();
29
+ /**
30
+ * The WebGL renderer where WebGL2 runs (for `'auto'` only on a GPU, for
31
+ * `'webgl'` also in software), the budget allows one more and the shaders
32
+ * compile; the 2D canvas renderer otherwise and always for `'canvas'`.
33
+ * `null` only where not even a 2D context exists.
34
+ */
35
+ export function chooseWaveRenderer(params) {
36
+ const gpuRenderer = params.preference === 'canvas' ? null : tryWebGlRenderer(params);
37
+ return (gpuRenderer ?? CanvasWaveRenderer.create(params.createCanvas(), params.look));
38
+ }
39
+ function tryWebGlRenderer({ preference, look, shader, createCanvas, onContextLost, gpuBudget = PAGE_GPU_BUDGET, }) {
40
+ if (!gpuBudget.tryAcquire()) {
41
+ return null;
42
+ }
43
+ const canvas = createCanvas();
44
+ // 'webgl' takes a software-rendered context too, 'auto' only a GPU's
45
+ const gl = WebGlWaveRenderer.createContext(canvas, preference === 'auto');
46
+ if (gl == null) {
47
+ gpuBudget.release();
48
+ return null;
49
+ }
50
+ try {
51
+ return new WebGlWaveRenderer(canvas, gl, look, shader, {
52
+ onContextLost,
53
+ onDispose: () => gpuBudget.release(),
54
+ });
55
+ }
56
+ catch (error) {
57
+ if (!reportedFragments.has(shader.fragment)) {
58
+ reportedFragments.add(shader.fragment);
59
+ console.warn('ws-loading-wave: drawing on a 2D canvas instead', error);
60
+ }
61
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
62
+ gpuBudget.release();
63
+ return null;
64
+ }
65
+ }
66
+ //# 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;AAI5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAE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;IACrE,MAAM,EAAE,GAAG,iBAAiB,CAAC,aAAa,CAAC,MAAM,EAAE,UAAU,KAAK,MAAM,CAAC,CAAC;IAC1E,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC;QACf,SAAS,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACH,OAAO,IAAI,iBAAiB,CAAC,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;YACrD,aAAa;YACb,SAAS,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE;SACrC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC5C,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;QACD,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 type { LoadingWaveShader } from './webgl/loading-wave-shader';\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/** fragments whose failure was reported, so a broken one warns only once */\nconst reportedFragments = new Set<string>();\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 /** what the WebGL renderer draws with */\n readonly shader: LoadingWaveShader;\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 shader,\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, shader, {\n onContextLost,\n onDispose: () => gpuBudget.release(),\n });\n } catch (error) {\n if (!reportedFragments.has(shader.fragment)) {\n reportedFragments.add(shader.fragment);\n console.warn('ws-loading-wave: drawing on a 2D canvas instead', error);\n }\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,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7E,MAAM,CAAC,EAAE,AAAD,EAAG,AAAD,EAAG,AAAD,EAAG,SAAS,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC;IAC3C,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,SAAS,EAAE,OAAO,KAAK,GAAG,CAAC,E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AC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC/D,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,KAAK,GAAG,GAAG,EAAE,CAAC;AACzC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAC7B,IAAiB,EACjB,KAAyB,EACzB,YAAqC;IAErC,MAAM,IAAI,GAAG,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC;IAC5C,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;QACjB,OAAO,kBAAkB,CAAC;IAC5B,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;IACvD,KAAK,CAAC,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC;IAC7B,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,KAAK,IAAI,cAAc,CAAC;IAC5C,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;IACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC;IACpD,KAAK,CAAC,MAAM,EAAE,CAAC;IACf,OAAO,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,48 @@
1
+ import { InjectionToken } from '@angular/core';
2
+ import { DEFAULT_FRONT_ROUNDNESS } from './wave-model';
3
+ import { rippleShader } from './webgl/shaders/ripple.shader';
4
+ export const DEFAULT_LOADING_WAVE_OPTIONS = {
5
+ afterLoading: 'hide',
6
+ dotSpacing: 28,
7
+ dotSize: 1.5,
8
+ sweepMs: 1600,
9
+ renderer: 'auto',
10
+ frontRoundness: DEFAULT_FRONT_ROUNDNESS,
11
+ shader: rippleShader,
12
+ };
13
+ export const LOADING_WAVE_OPTIONS = new InjectionToken('LOADING_WAVE_OPTIONS', { providedIn: 'root', factory: () => DEFAULT_LOADING_WAVE_OPTIONS });
14
+ /** sets app-wide defaults; the directive's own options still win */
15
+ export function provideLoadingWave(options) {
16
+ return {
17
+ provide: LOADING_WAVE_OPTIONS,
18
+ useValue: resolveLoadingWaveOptions(DEFAULT_LOADING_WAVE_OPTIONS, options),
19
+ };
20
+ }
21
+ /**
22
+ * Merges `overrides` into `defaults`, ignoring `undefined` values,
23
+ * replacing sizes and durations that are no positive finite number and
24
+ * clamping the front's roundness into 0 to 1.
25
+ */
26
+ export function resolveLoadingWaveOptions(defaults, overrides = {}) {
27
+ const defined = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined));
28
+ const merged = { ...defaults, ...defined };
29
+ return {
30
+ ...merged,
31
+ dotSpacing: positiveOr(merged.dotSpacing, defaults.dotSpacing),
32
+ dotSize: positiveOr(merged.dotSize, defaults.dotSize),
33
+ sweepMs: positiveOr(merged.sweepMs, defaults.sweepMs),
34
+ // an app's own LOADING_WAVE_OPTIONS may lack the newer options
35
+ frontRoundness: unitOr(merged.frontRoundness, defaults.frontRoundness ?? DEFAULT_FRONT_ROUNDNESS),
36
+ shader: merged.shader ?? rippleShader,
37
+ };
38
+ }
39
+ /** `value` clamped into 0 to 1, `fallback` where it is no finite number */
40
+ function unitOr(value, fallback) {
41
+ return value !== undefined && Number.isFinite(value)
42
+ ? Math.min(1, Math.max(0, value))
43
+ : fallback;
44
+ }
45
+ function positiveOr(value, fallback) {
46
+ return Number.isFinite(value) && value > 0 ? value : fallback;
47
+ }
48
+ //# sourceMappingURL=loading-wave-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loading-wave-options.js","sourceRoot":"","sources":["../../../../../../libs/public/ws-loading-wave/src/lib/loading-wave-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAY,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAkD7D,MAAM,CAAC,MAAM,4BAA4B,GAA+B;IACtE,YAAY,EAAE,MAAM;IACpB,UAAU,EAAE,EAAE;IACd,OAAO,EAAE,GAAG;IACZ,OAAO,EAAE,IAAI;IACb,QAAQ,EAAE,MAAM;IAChB,cAAc,EAAE,uBAAuB;IACvC,MAAM,EAAE,YAAY;CACrB,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,cAAc,CACpD,sBAAsB,EACtB,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,4BAA4B,EAAE,CACpE,CAAC;AAEF,oEAAoE;AACpE,MAAM,UAAU,kBAAkB,CAChC,OAAoC;IAEpC,OAAO;QACL,OAAO,EAAE,oBAAoB;QAC7B,QAAQ,EAAE,yBAAyB,CAAC,4BAA4B,EAAE,OAAO,CAAC;KAC3E,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CACvC,QAA4B,EAC5B,YAAyC,EAAE;IAE3C,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAChC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CACtC,CAAC;IACjC,MAAM,MAAM,GAAG,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,EAAE,CAAC;IAC3C,OAAO;QACL,GAAG,MAAM;QACT,UAAU,EAAE,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,QAAQ,CAAC,UAAU,CAAC;QAC9D,OAAO,EAAE,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC;QACrD,OAAO,EAAE,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC;QACrD,+DAA+D;QAC/D,cAAc,EAAE,MAAM,CACpB,MAAM,CAAC,cAAc,EACrB,QAAQ,CAAC,cAAc,IAAI,uBAAuB,CACnD;QACD,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,YAAY;KACtC,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,SAAS,MAAM,CAAC,KAAyB,EAAE,QAAgB;IACzD,OAAO,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAClD,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;QACjC,CAAC,CAAC,QAAQ,CAAC;AACf,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';\nimport { DEFAULT_FRONT_ROUNDNESS } from './wave-model';\nimport type { LoadingWaveShader } from './webgl/loading-wave-shader';\nimport { rippleShader } from './webgl/shaders/ripple.shader';\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 /**\n * any CSS colour for the lit dots and the wave itself; unset, they take\n * the dots' colour\n */\n readonly accentColor?: 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 * 0 (a straight front) to 1 (a half circle): how far the wave front's ends\n * lag its middle, as a share of `min(height / 2, width)`; 0.5 when unset\n */\n readonly frontRoundness?: number;\n /**\n * the fragment shader the WebGL renderer draws with: a built-in one\n * (`rippleShader`) or one's own; unset, `rippleShader`. The 2D canvas\n * always draws the dot wave.\n */\n readonly shader?: LoadingWaveShader;\n}\n\n/** options with every default filled in, as the wave runs with them */\nexport type ResolvedLoadingWaveOptions = LoadingWaveOptions &\n Required<Pick<LoadingWaveOptions, 'frontRoundness' | 'shader'>>;\n\nexport const DEFAULT_LOADING_WAVE_OPTIONS: ResolvedLoadingWaveOptions = {\n afterLoading: 'hide',\n dotSpacing: 28,\n dotSize: 1.5,\n sweepMs: 1600,\n renderer: 'auto',\n frontRoundness: DEFAULT_FRONT_ROUNDNESS,\n shader: rippleShader,\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,\n * replacing sizes and durations that are no positive finite number and\n * clamping the front's roundness into 0 to 1.\n */\nexport function resolveLoadingWaveOptions(\n defaults: LoadingWaveOptions,\n overrides: Partial<LoadingWaveOptions> = {}\n): ResolvedLoadingWaveOptions {\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 // an app's own LOADING_WAVE_OPTIONS may lack the newer options\n frontRoundness: unitOr(\n merged.frontRoundness,\n defaults.frontRoundness ?? DEFAULT_FRONT_ROUNDNESS\n ),\n shader: merged.shader ?? rippleShader,\n };\n}\n\n/** `value` clamped into 0 to 1, `fallback` where it is no finite number */\nfunction unitOr(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isFinite(value)\n ? Math.min(1, Math.max(0, value))\n : fallback;\n}\n\nfunction positiveOr(value: number, fallback: number): number {\n return Number.isFinite(value) && value > 0 ? value : fallback;\n}\n"]}