@5even7/dlc-ui 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1658 @@
1
+ /**
2
+ * Tiny event emitter. Accepts any event name so the API stays open for
3
+ * future events (hover, click, custom) without breaking changes.
4
+ */
5
+ function createEmitter() {
6
+ // Plain object storage (no Map/Set) so the legacy build has no API
7
+ // dependencies beyond what IE11 provides.
8
+ const listeners = Object.create(null);
9
+
10
+ return {
11
+ on(event, fn) {
12
+ if (!listeners[event]) listeners[event] = [];
13
+ listeners[event].push(fn);
14
+ return () => {
15
+ const current = listeners[event];
16
+ if (current) {
17
+ const index = current.indexOf(fn);
18
+ if (index !== -1) current.splice(index, 1);
19
+ }
20
+ };
21
+ },
22
+ off(event, fn) {
23
+ const current = listeners[event];
24
+ if (!current) return false;
25
+ const index = current.indexOf(fn);
26
+ if (index === -1) return false;
27
+ current.splice(index, 1);
28
+ return true;
29
+ },
30
+ emit(event, ...args) {
31
+ const current = listeners[event];
32
+ if (!current) return;
33
+ for (const fn of current.slice()) fn(...args);
34
+ }
35
+ };
36
+ }
37
+
38
+ const UNIT_PATTERN = /^[\d.]+(?:px|%|vw|vh|vmin|vmax|em|rem)$/;
39
+
40
+ /**
41
+ * Normalize a size option to a CSS length string.
42
+ * Accepts numbers (treated as px) or strings with px/%, vw/vh/vmin/vmax, em/rem.
43
+ */
44
+ function parseSize(value) {
45
+ if (typeof value === 'number') {
46
+ if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid size: ${value}`);
47
+ return `${value}px`;
48
+ }
49
+ if (typeof value !== 'string') throw new Error(`Invalid size: ${String(value)}`);
50
+ const trimmed = value.trim();
51
+ if (!trimmed) throw new Error('Invalid size: empty string');
52
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) return `${trimmed}px`;
53
+ if (!UNIT_PATTERN.test(trimmed)) {
54
+ throw new Error(`Invalid size or unsupported unit: "${value}" (use px, %, vw, vh, vmin, vmax, em, rem)`);
55
+ }
56
+ return trimmed;
57
+ }
58
+
59
+ const QUALITY_TIERS = {
60
+ low: { dpr: 1 },
61
+ medium: { dpr: 1.5 },
62
+ high: { dpr: 2 }
63
+ };
64
+
65
+ function autoDprCap() {
66
+ const nav = typeof navigator !== 'undefined' ? navigator : null;
67
+ const memory = nav && typeof nav.deviceMemory === 'number' ? nav.deviceMemory : 8;
68
+ const cores = nav && typeof nav.hardwareConcurrency === 'number' ? nav.hardwareConcurrency : 8;
69
+ return memory <= 4 || cores <= 4 ? 1.5 : 2;
70
+ }
71
+
72
+ function dprCapFor(quality) {
73
+ if (quality === 'auto') return autoDprCap();
74
+ const tier = QUALITY_TIERS[quality] || QUALITY_TIERS.medium;
75
+ return tier.dpr;
76
+ }
77
+
78
+ /**
79
+ * Merge defaults < preset < user. Unknown user keys are preserved so the
80
+ * component API can grow (new props, cssVars, callbacks) without a breaking
81
+ * change.
82
+ */
83
+ function normalizeOptions(defaults, preset, user) {
84
+ // undefined means "not provided" (e.g. Vue $props with unset props):
85
+ // drop those keys before merging so defaults/preset values survive.
86
+ const omitUndefined = (source) => {
87
+ const result = {};
88
+ for (const key of Object.keys(source)) {
89
+ if (source[key] !== undefined) result[key] = source[key];
90
+ }
91
+ return result;
92
+ };
93
+ const presetOptions = omitUndefined(preset && typeof preset === 'object' ? preset : {});
94
+ const userOptions = omitUndefined(user && typeof user === 'object' ? user : {});
95
+ return { ...defaults, ...presetOptions, ...userOptions };
96
+ }
97
+
98
+ const PROGRESS_PRESETS = [
99
+ {
100
+ id: 'model-training',
101
+ code: 'NC-10',
102
+ name: 'MODEL TRAINING',
103
+ subtitle: 'SHA 4.5 + 100 2026 TKN',
104
+ group: 'progress',
105
+ initialProgress: 43,
106
+ edgeStyle: 'flow',
107
+ colors: ['#2B1025', '#FF3F94', '#FF8A3D', '#FFF06A']
108
+ },
109
+ {
110
+ id: 'agent-migration',
111
+ code: 'NC-11',
112
+ name: 'AGENT MIGRATION',
113
+ subtitle: 'TRANSFERRING PROTOCOL',
114
+ group: 'progress',
115
+ initialProgress: 33,
116
+ edgeStyle: 'flow',
117
+ colors: ['#101C37', '#245BFF', '#00CFFF', '#5DFFE6']
118
+ },
119
+ {
120
+ id: 'visual-training',
121
+ code: 'NC-12',
122
+ name: 'VISUAL TRAINING',
123
+ subtitle: 'GENERATING POWER ++',
124
+ group: 'progress',
125
+ initialProgress: 58,
126
+ edgeStyle: 'flow',
127
+ colors: ['#21142D', '#7042FF', '#42F58D', '#C4FF8A']
128
+ },
129
+ {
130
+ id: 'tide',
131
+ code: 'NC-13',
132
+ name: 'TIDE',
133
+ subtitle: 'MOON PULL / COAST',
134
+ group: 'progress',
135
+ initialProgress: 30,
136
+ edgeStyle: 'tide',
137
+ colors: ['#0A2239', '#2E9BFF', '#7FE3FF', '#EAF9FF']
138
+ }
139
+ ];
140
+
141
+ function validateProgressPreset(preset) {
142
+ return Boolean(
143
+ preset &&
144
+ typeof preset.id === 'string' &&
145
+ typeof preset.code === 'string' &&
146
+ typeof preset.name === 'string' &&
147
+ preset.group === 'progress' &&
148
+ Number.isFinite(preset.initialProgress) &&
149
+ ['flow', 'tide'].indexOf(preset.edgeStyle || 'flow') !== -1 &&
150
+ Array.isArray(preset.colors) &&
151
+ preset.colors.length === 4
152
+ );
153
+ }
154
+
155
+ function getPreset(kind, ref) {
156
+ const list = PROGRESS_PRESETS ;
157
+ if (!list) throw new Error(`Unknown preset kind: ${kind} (use "capsule" or "progress")`);
158
+ if (ref && typeof ref === 'object') {
159
+ const valid = validateProgressPreset(ref);
160
+ if (!valid) throw new Error(`Invalid ${kind} preset object`);
161
+ return ref;
162
+ }
163
+ const key = String(ref).trim().toLowerCase();
164
+ const found = list.find(
165
+ (preset) =>
166
+ preset.id.toLowerCase() === key ||
167
+ preset.code.toLowerCase() === key ||
168
+ preset.name.toLowerCase() === key
169
+ );
170
+ if (!found) throw new Error(`Unknown ${kind} preset: ${ref}`);
171
+ return found;
172
+ }
173
+
174
+ const DEFAULTS = {
175
+ progress: {
176
+ width: 454,
177
+ height: 104,
178
+ min: 0,
179
+ max: 100,
180
+ draggable: true,
181
+ keyboard: true,
182
+ edgeStyle: 'flow',
183
+ quality: 'auto',
184
+ renderer: 'auto',
185
+ showCopy: true,
186
+ respectReducedMotion: true
187
+ }
188
+ };
189
+
190
+ /**
191
+ * All user-facing copy lives here so wording/brand changes never require a
192
+ * global search. Templates use {brand} {code} {name} placeholders.
193
+ */
194
+ const COPY = {
195
+ brandName: '画境观屿',
196
+ dragLabel: 'DRAG',
197
+ valueSuffix: '%',
198
+ progressAria: '{brand} {code} 加载进度',
199
+ capsuleAria: '打开 {name} 沉浸预览'
200
+ };
201
+
202
+ function hexToRgba(hex, alpha = 1) {
203
+ const normalized = hex.replace('#', '');
204
+ const value = Number.parseInt(normalized, 16);
205
+ const red = (value >> 16) & 255;
206
+ const green = (value >> 8) & 255;
207
+ const blue = value & 255;
208
+ return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
209
+ }
210
+
211
+ /**
212
+ * Document-level shared rAF scheduler. Every component instance subscribes
213
+ * its own frame callback; the whole page runs ONE animation loop (like the
214
+ * original demo), which avoids jank from many competing rAF loops.
215
+ */
216
+ const subscribers = [];
217
+ let running = false;
218
+ let rafId = 0;
219
+ let last = 0;
220
+
221
+ function tick(now) {
222
+ if (!running) return;
223
+ const delta = last ? Math.min((now - last) / 1000, 0.05) : 0;
224
+ last = now;
225
+ // Schedule the next frame BEFORE running callbacks so one throwing
226
+ // subscriber can never kill the whole animation loop.
227
+ rafId = requestAnimationFrame(tick);
228
+ {
229
+ for (const item of subscribers.slice()) {
230
+ try {
231
+ if (!item.isPaused()) item.onFrame(delta, now);
232
+ } catch (error) {
233
+ console.warn('[dlc-ui] frame error:', error);
234
+ }
235
+ }
236
+ }
237
+ if (subscribers.length === 0) {
238
+ cancelAnimationFrame(rafId);
239
+ running = false;
240
+ rafId = 0;
241
+ }
242
+ }
243
+
244
+ function start() {
245
+ if (running) return;
246
+ running = true;
247
+ last = 0;
248
+ rafId = requestAnimationFrame(tick);
249
+ }
250
+
251
+ function subscribeScheduler(onFrame, isPaused) {
252
+ const item = { onFrame, isPaused };
253
+ subscribers.push(item);
254
+ start();
255
+ return () => {
256
+ const index = subscribers.indexOf(item);
257
+ if (index !== -1) subscribers.splice(index, 1);
258
+ if (subscribers.length === 0 && rafId) {
259
+ cancelAnimationFrame(rafId);
260
+ running = false;
261
+ rafId = 0;
262
+ }
263
+ };
264
+ }
265
+
266
+ /**
267
+ * Gates drawing on "element intersects viewport AND the page tab is visible".
268
+ * Falls back to always-visible when IntersectionObserver is unavailable.
269
+ */
270
+ function createVisibilityGuard(element) {
271
+ let intersecting = true;
272
+ let pageVisible = typeof document === 'undefined' || !document.hidden;
273
+ let disposed = false;
274
+ let observer = null;
275
+
276
+ if (typeof IntersectionObserver !== 'undefined') {
277
+ observer = new IntersectionObserver(
278
+ (entries) => {
279
+ intersecting = entries.some((entry) => entry.isIntersecting);
280
+ },
281
+ { rootMargin: '180px' }
282
+ );
283
+ observer.observe(element);
284
+ }
285
+
286
+ const onVisibilityChange = () => {
287
+ pageVisible = typeof document !== 'undefined' && !document.hidden;
288
+ };
289
+ if (typeof document !== 'undefined') {
290
+ document.addEventListener('visibilitychange', onVisibilityChange);
291
+ }
292
+
293
+ return {
294
+ isVisible() {
295
+ return intersecting && pageVisible;
296
+ },
297
+ dispose() {
298
+ if (disposed) return;
299
+ disposed = true;
300
+ if (observer) observer.disconnect();
301
+ if (typeof document !== 'undefined') {
302
+ document.removeEventListener('visibilitychange', onVisibilityChange);
303
+ }
304
+ }
305
+ };
306
+ }
307
+
308
+ const PROGRESS_MOTION_WIDTH = 240;
309
+ const PROGRESS_MOTION_HEIGHT = 80;
310
+ const PROGRESS_MOTION_DURATION = 12.0;
311
+ const PROGRESS_MOTION_MAX_PX = 40.0;
312
+
313
+ const PROFILE_CONFIG = {
314
+ 'model-training': { seed: 0.37, broad: 0.58, middle: 0.25, detail: 0.13, lobe: 0.24 },
315
+ 'agent-migration': { seed: 1.71, broad: 0.72, middle: 0.10, detail: 0.03, lobe: 0.18 },
316
+ 'visual-training': { seed: 2.83, broad: 0.66, middle: 0.16, detail: 0.06, lobe: 0.23 },
317
+ // ponytail: first-pass tide = asymmetric time warp on the same motion pipeline.
318
+ // Refine (foam line / wash streaks) in the shader after visual QA.
319
+ 'tide': { seed: 4.12, broad: 0.82, middle: 0.07, detail: 0.02, lobe: 0.30, warp: 0.5 }
320
+ };
321
+
322
+ const CACHE$1 = Object.create(null);
323
+
324
+ function gaussian(value, center, width) {
325
+ const delta = (value - center) / Math.max(width, 0.001);
326
+ return Math.exp(-delta * delta);
327
+ }
328
+
329
+ function createMotionData(id, edgeStyle = 'flow') {
330
+ const profile = edgeStyle === 'tide'
331
+ ? PROFILE_CONFIG.tide
332
+ : (PROFILE_CONFIG[id] || PROFILE_CONFIG['visual-training']);
333
+ const data = new Uint8Array(PROGRESS_MOTION_WIDTH * PROGRESS_MOTION_HEIGHT);
334
+
335
+ for (let x = 0; x < PROGRESS_MOTION_WIDTH; x += 1) {
336
+ let time = (x / PROGRESS_MOTION_WIDTH) * Math.PI * 2;
337
+ if (profile.warp) time += profile.warp * Math.sin(time * 2);
338
+ const centerA = 0.28 + Math.sin(time * 0.53 + profile.seed) * 0.13;
339
+ const centerB = 0.70 + Math.cos(time * 0.47 + profile.seed * 1.7) * 0.12;
340
+
341
+ for (let y = 0; y < PROGRESS_MOTION_HEIGHT; y += 1) {
342
+ const ratio = y / Math.max(PROGRESS_MOTION_HEIGHT - 1, 1);
343
+ const envelope = Math.pow(Math.max(Math.sin(Math.PI * ratio), 0), 0.48);
344
+ const broad = Math.sin(ratio * Math.PI * 2 * 1.35 + time * 0.58 + profile.seed) * profile.broad;
345
+ const middle = Math.sin(ratio * Math.PI * 2 * 3.2 - time * 0.91 + profile.seed * 2.1) * profile.middle;
346
+ const detail = Math.sin(ratio * Math.PI * 2 * 6.1 + time * 1.31 + profile.seed * 3.2) * profile.detail;
347
+ const lobes = (
348
+ gaussian(ratio, centerA, 0.09) * Math.sin(time * 1.11 + profile.seed * 4.0) -
349
+ gaussian(ratio, centerB, 0.10) * Math.cos(time * 0.97 + profile.seed * 3.3)
350
+ ) * profile.lobe;
351
+ const normalized = Math.max(-1, Math.min(1, (broad + middle + detail + lobes) * envelope));
352
+ data[y * PROGRESS_MOTION_WIDTH + x] = Math.round((normalized * 0.5 + 0.5) * 255);
353
+ }
354
+ }
355
+
356
+ return data;
357
+ }
358
+
359
+ function getProgressMotionData(id, edgeStyle = 'flow') {
360
+ const key = `${id}:${edgeStyle}`;
361
+ if (!CACHE$1[key]) CACHE$1[key] = createMotionData(id, edgeStyle);
362
+ return CACHE$1[key];
363
+ }
364
+
365
+ function hexToRgb01(hex) {
366
+ const value = Number.parseInt(hex.replace('#', ''), 16);
367
+ return [
368
+ ((value >> 16) & 255) / 255,
369
+ ((value >> 8) & 255) / 255,
370
+ (value & 255) / 255
371
+ ];
372
+ }
373
+
374
+ function stringSeed$1(value) {
375
+ let hash = 2166136261;
376
+ for (const character of value) {
377
+ hash ^= character.charCodeAt(0);
378
+ hash = Math.imul(hash, 16777619);
379
+ }
380
+ return (hash >>> 0) / 4294967295;
381
+ }
382
+
383
+ const PROFILE_INDEX = {
384
+ 'model-training': 0,
385
+ 'agent-migration': 1,
386
+ 'visual-training': 2,
387
+ 'tide': 3
388
+ };
389
+
390
+ const MOTION_SCALE_FACTORS = {
391
+ 'model-training': 1.05,
392
+ 'agent-migration': 1.04,
393
+ 'visual-training': 1.04,
394
+ 'tide': 1.18
395
+ };
396
+
397
+ const VERTEX_SHADER = `#version 300 es
398
+ in vec2 a_position;
399
+ out vec2 v_uv;
400
+ void main() {
401
+ v_uv = a_position * 0.5 + 0.5;
402
+ gl_Position = vec4(a_position, 0.0, 1.0);
403
+ }`;
404
+
405
+ const FRAGMENT_SHADER = `#version 300 es
406
+ precision highp float;
407
+
408
+ in vec2 v_uv;
409
+ out vec4 outColor;
410
+
411
+ uniform vec2 u_resolution;
412
+ uniform float u_time;
413
+ uniform float u_progress;
414
+ uniform float u_seed;
415
+ uniform float u_profile;
416
+ uniform sampler2D u_motion;
417
+ uniform sampler2D u_effect;
418
+ uniform float u_hasEffect;
419
+ uniform float u_effectFrames;
420
+ uniform float u_motionDuration;
421
+ uniform float u_motionScale;
422
+ uniform vec3 u_dark;
423
+ uniform vec3 u_accentA;
424
+ uniform vec3 u_accentB;
425
+ uniform vec3 u_glow;
426
+
427
+ float hash21(vec2 p) {
428
+ p = fract(p * vec2(123.34, 456.21));
429
+ p += dot(p, p + 45.32 + u_seed * 11.7);
430
+ return fract(p.x * p.y);
431
+ }
432
+
433
+ float noise(vec2 p) {
434
+ vec2 i = floor(p);
435
+ vec2 f = fract(p);
436
+ f = f * f * (3.0 - 2.0 * f);
437
+ float a = hash21(i);
438
+ float b = hash21(i + vec2(1.0, 0.0));
439
+ float c = hash21(i + vec2(0.0, 1.0));
440
+ float d = hash21(i + vec2(1.0, 1.0));
441
+ return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
442
+ }
443
+
444
+ float fbm(vec2 p) {
445
+ float value = 0.0;
446
+ float amplitude = 0.55;
447
+ mat2 rotation = mat2(0.82, 0.57, -0.57, 0.82);
448
+ for (int i = 0; i < 6; i++) {
449
+ value += noise(p) * amplitude;
450
+ p = rotation * p * 2.02 + 13.7;
451
+ amplitude *= 0.48;
452
+ }
453
+ return value;
454
+ }
455
+
456
+ float gaussian(float value, float center, float width) {
457
+ float delta = (value - center) / max(width, 0.0001);
458
+ return exp(-delta * delta);
459
+ }
460
+
461
+ float profileMix(float model, float agent, float visual) {
462
+ if (u_profile < 0.5) return model;
463
+ if (u_profile < 1.5) return agent;
464
+ return visual;
465
+ }
466
+
467
+ float motionSample(float y, float t) {
468
+ float phase = fract(t / max(u_motionDuration, 0.001));
469
+ float captured = texture(u_motion, vec2(phase, 1.0 - clamp(y, 0.0, 1.0))).r;
470
+ return (captured * 2.0 - 1.0) * u_motionScale;
471
+ }
472
+
473
+ float edgeDisplacement(float y, float t) {
474
+ return motionSample(y, t);
475
+ }
476
+
477
+ float flowDisplacement(float y, float t) {
478
+ return (
479
+ motionSample(y - 0.024, t) * 0.08 +
480
+ motionSample(y - 0.012, t) * 0.18 +
481
+ motionSample(y, t) * 0.48 +
482
+ motionSample(y + 0.012, t) * 0.18 +
483
+ motionSample(y + 0.024, t) * 0.08
484
+ );
485
+ }
486
+
487
+ float ellipseRing(vec2 p, float radius, float width) {
488
+ return gaussian(length(p), radius, width);
489
+ }
490
+
491
+ void main() {
492
+ vec2 uv = v_uv;
493
+ float t = u_time;
494
+ float edge = u_progress + edgeDisplacement(uv.y, t);
495
+ float flowEdge = u_progress + flowDisplacement(uv.y, t);
496
+ float d = uv.x - edge;
497
+ float fd = uv.x - flowEdge;
498
+
499
+ vec3 rightBase = vec3(0.125, 0.129, 0.145);
500
+ vec3 color = rightBase;
501
+
502
+ float leftMask = 1.0 - smoothstep(-0.001, 0.002, d);
503
+ color = mix(color, u_dark, leftMask * profileMix(0.96, 0.92, 0.96));
504
+
505
+ vec2 flowP = vec2((fd + 0.10) * 6.2, uv.y * 1.95);
506
+ float flowA = fbm(flowP + vec2(-t * 0.22, t * 0.27) + u_seed * 1.7);
507
+ float flowB = fbm(flowP * 1.52 + vec2(t * 0.28, -t * 0.36) + 8.2 + u_seed);
508
+ float flowC = fbm(flowP * 2.25 + vec2(-t * 0.41, t * 0.46) + 19.0);
509
+
510
+ float farCenter = profileMix(-0.060, -0.079, -0.045) + (flowA - 0.5) * profileMix(0.018, 0.022, 0.014);
511
+ float midCenter = profileMix(-0.039, -0.052, -0.030) + (flowB - 0.5) * profileMix(0.013, 0.016, 0.010);
512
+ float hotCenter = profileMix(-0.026, -0.029, -0.023) + (flowC - 0.5) * 0.010;
513
+
514
+ float farBand = gaussian(fd, farCenter, profileMix(0.035, 0.049, 0.030));
515
+ float midBand = gaussian(fd, midCenter, profileMix(0.026, 0.034, 0.026));
516
+ float hotBand = gaussian(fd, hotCenter, profileMix(0.023, 0.027, 0.026));
517
+ float darkTrough = gaussian(fd, profileMix(-0.050, -0.058, -0.044) + (flowB - 0.5) * 0.010, profileMix(0.020, 0.025, 0.021));
518
+
519
+ float ringY = 0.47 + sin(t * 0.58 + u_seed * 2.4) * 0.12;
520
+ vec2 ringP = vec2((fd + 0.086) / 0.078, (uv.y - ringY) / 0.25);
521
+ ringP += vec2((flowB - 0.5) * 0.08, (flowA - 0.5) * 0.06);
522
+ float ringTexture = fbm(ringP * 2.15 + vec2(t * 0.18, -t * 0.14) + u_seed * 1.9);
523
+ float ring = ellipseRing(ringP, 0.66, 0.32) * (0.30 + 0.64 * ringTexture);
524
+ float ringCore = gaussian(length(ringP), 0.25, 0.25);
525
+ float ringPulse = smoothstep(0.58, 0.90, 0.5 + 0.5 * sin(t * 0.82 + u_seed * 4.1));
526
+ float modelRing = ring * ringPulse * (1.0 - step(0.5, u_profile));
527
+ float visualRing = ring * 0.16 * step(1.5, u_profile) * ringPulse;
528
+
529
+ float cloudGate = leftMask * smoothstep(-0.30, -0.008, fd);
530
+ float textureA = smoothstep(0.24, 0.92, flowA * 0.72 + flowB * 0.42);
531
+ float textureB = smoothstep(0.28, 0.94, flowB * 0.68 + flowC * 0.38);
532
+
533
+ vec3 hotColor = u_accentB;
534
+ color += u_accentA * farBand * cloudGate * (0.07 + textureA * profileMix(0.42, 0.24, 0.40));
535
+ color += u_accentB * midBand * cloudGate * (0.15 + textureB * profileMix(0.70, 0.46, 0.68));
536
+ color += hotColor * hotBand * cloudGate * profileMix(0.88, 0.62, 0.84);
537
+ float modelMask = 1.0 - step(0.5, u_profile);
538
+ color += u_accentA * (modelRing + visualRing) * cloudGate * profileMix(0.54, 0.0, 0.34);
539
+ color *= 1.0 - darkTrough * profileMix(0.44, 0.24, 0.24) * cloudGate;
540
+ color *= 1.0 - ringCore * modelMask * ringPulse * 0.44 * cloudGate;
541
+
542
+ float broadHalo = exp(-abs(d) * 96.0);
543
+ float innerHalo = exp(-abs(d) * 176.0);
544
+ float colorCore = exp(-abs(d) * 360.0);
545
+ float sharpCore = exp(-abs(d) * 760.0);
546
+ float leftGate = 1.0 - smoothstep(-0.003, 0.005, d);
547
+
548
+ color += u_accentA * broadHalo * leftGate * profileMix(0.09, 0.04, 0.06);
549
+ color += hotColor * innerHalo * leftGate * profileMix(0.76, 0.72, 0.78);
550
+ color += u_glow * colorCore * profileMix(0.72, 0.34, 0.24);
551
+
552
+ float whiteStrength = profileMix(0.10, 0.0, 0.0);
553
+ color += vec3(1.0, 0.99, 0.91) * sharpCore * whiteStrength;
554
+
555
+ float rightCut = smoothstep(0.001, 0.006, d);
556
+ color = mix(color, rightBase, rightCut);
557
+
558
+ float effectX = (d * 1257.0 + 260.0) / 320.0;
559
+ float atlasPhase = fract(t / 12.0) * u_effectFrames;
560
+ float atlasFrameA = floor(atlasPhase);
561
+ float atlasFrameB = mod(atlasFrameA + 1.0, u_effectFrames);
562
+ float atlasMix = smoothstep(0.0, 1.0, fract(atlasPhase));
563
+ float atlasXA = (atlasFrameA + clamp(effectX, 0.0, 1.0)) / u_effectFrames;
564
+ float atlasXB = (atlasFrameB + clamp(effectX, 0.0, 1.0)) / u_effectFrames;
565
+ vec3 referenceA = texture(u_effect, vec2(atlasXA, uv.y)).rgb;
566
+ vec3 referenceB = texture(u_effect, vec2(atlasXB, uv.y)).rgb;
567
+ vec3 referenceColor = mix(referenceA, referenceB, atlasMix);
568
+ float stripMask = smoothstep(0.0, 0.018, effectX) * (1.0 - smoothstep(0.982, 1.0, effectX));
569
+ float referenceLeft = 1.0 - smoothstep(-0.026, -0.012, d);
570
+ color = mix(color, referenceColor, stripMask * referenceLeft * u_hasEffect);
571
+
572
+ outColor = vec4(clamp(color, 0.0, 1.0), 1.0);
573
+ }`;
574
+
575
+ function compileShader(gl, type, source) {
576
+ const shader = gl.createShader(type);
577
+ gl.shaderSource(shader, source);
578
+ gl.compileShader(shader);
579
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
580
+ const message = gl.getShaderInfoLog(shader) || 'Unknown shader compile error';
581
+ gl.deleteShader(shader);
582
+ throw new Error(message);
583
+ }
584
+ return shader;
585
+ }
586
+
587
+ function createProgram(gl) {
588
+ const vertex = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
589
+ const fragment = compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER);
590
+ const program = gl.createProgram();
591
+ gl.attachShader(program, vertex);
592
+ gl.attachShader(program, fragment);
593
+ gl.linkProgram(program);
594
+ gl.deleteShader(vertex);
595
+ gl.deleteShader(fragment);
596
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
597
+ const message = gl.getProgramInfoLog(program) || 'Unknown shader link error';
598
+ gl.deleteProgram(program);
599
+ throw new Error(message);
600
+ }
601
+ return program;
602
+ }
603
+
604
+ class ProgressFlowRenderer {
605
+ constructor(canvas, preset) {
606
+ const gl = canvas.getContext('webgl2', {
607
+ alpha: false,
608
+ antialias: true,
609
+ premultipliedAlpha: false,
610
+ powerPreference: 'high-performance'
611
+ });
612
+ if (!gl) throw new Error('WebGL2 unavailable');
613
+
614
+ this.canvas = canvas;
615
+ this.gl = gl;
616
+ this.program = createProgram(gl);
617
+ this.profile = preset.edgeStyle === 'tide' ? 3 : (PROFILE_INDEX[preset.id] ?? 2);
618
+ this.seed = stringSeed$1(`${preset.id}-shader`) * 13.7 + 1.0;
619
+ this.colors = preset.colors.map(hexToRgb01);
620
+ this.motionData = getProgressMotionData(preset.id, preset.edgeStyle);
621
+ const motionFactor = preset.edgeStyle === 'tide'
622
+ ? MOTION_SCALE_FACTORS.tide
623
+ : (MOTION_SCALE_FACTORS[preset.id] || 1.04);
624
+ this.motionScale = (PROGRESS_MOTION_MAX_PX * motionFactor) / 1257;
625
+
626
+ this.position = gl.getAttribLocation(this.program, 'a_position');
627
+ this.uniforms = {
628
+ resolution: gl.getUniformLocation(this.program, 'u_resolution'),
629
+ time: gl.getUniformLocation(this.program, 'u_time'),
630
+ progress: gl.getUniformLocation(this.program, 'u_progress'),
631
+ seed: gl.getUniformLocation(this.program, 'u_seed'),
632
+ profile: gl.getUniformLocation(this.program, 'u_profile'),
633
+ motion: gl.getUniformLocation(this.program, 'u_motion'),
634
+ effect: gl.getUniformLocation(this.program, 'u_effect'),
635
+ hasEffect: gl.getUniformLocation(this.program, 'u_hasEffect'),
636
+ effectFrames: gl.getUniformLocation(this.program, 'u_effectFrames'),
637
+ motionDuration: gl.getUniformLocation(this.program, 'u_motionDuration'),
638
+ motionScale: gl.getUniformLocation(this.program, 'u_motionScale'),
639
+ dark: gl.getUniformLocation(this.program, 'u_dark'),
640
+ accentA: gl.getUniformLocation(this.program, 'u_accentA'),
641
+ accentB: gl.getUniformLocation(this.program, 'u_accentB'),
642
+ glow: gl.getUniformLocation(this.program, 'u_glow')
643
+ };
644
+
645
+ this.buffer = gl.createBuffer();
646
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
647
+ gl.bufferData(
648
+ gl.ARRAY_BUFFER,
649
+ new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
650
+ gl.STATIC_DRAW
651
+ );
652
+
653
+ this.motionTexture = gl.createTexture();
654
+ gl.activeTexture(gl.TEXTURE0);
655
+ gl.bindTexture(gl.TEXTURE_2D, this.motionTexture);
656
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
657
+ gl.texImage2D(
658
+ gl.TEXTURE_2D,
659
+ 0,
660
+ gl.R8,
661
+ PROGRESS_MOTION_WIDTH,
662
+ PROGRESS_MOTION_HEIGHT,
663
+ 0,
664
+ gl.RED,
665
+ gl.UNSIGNED_BYTE,
666
+ this.motionData
667
+ );
668
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
669
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
670
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
671
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
672
+
673
+ this.effectTexture = gl.createTexture();
674
+ gl.activeTexture(gl.TEXTURE1);
675
+ gl.bindTexture(gl.TEXTURE_2D, this.effectTexture);
676
+ gl.texImage2D(
677
+ gl.TEXTURE_2D,
678
+ 0,
679
+ gl.RGB,
680
+ 1,
681
+ 1,
682
+ 0,
683
+ gl.RGB,
684
+ gl.UNSIGNED_BYTE,
685
+ new Uint8Array([32, 33, 38])
686
+ );
687
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
688
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
689
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
690
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
691
+ this.effectUploaded = false;
692
+ }
693
+
694
+ resize(width, height, dpr) {
695
+ const pixelWidth = Math.max(1, Math.round(width * dpr));
696
+ const pixelHeight = Math.max(1, Math.round(height * dpr));
697
+ if (this.canvas.width !== pixelWidth || this.canvas.height !== pixelHeight) {
698
+ this.canvas.width = pixelWidth;
699
+ this.canvas.height = pixelHeight;
700
+ }
701
+ this.gl.viewport(0, 0, pixelWidth, pixelHeight);
702
+ }
703
+
704
+ draw(time, progress, effectImage = null) {
705
+ const gl = this.gl;
706
+ gl.useProgram(this.program);
707
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
708
+ gl.enableVertexAttribArray(this.position);
709
+ gl.vertexAttribPointer(this.position, 2, gl.FLOAT, false, 0, 0);
710
+
711
+ gl.uniform2f(this.uniforms.resolution, this.canvas.width, this.canvas.height);
712
+ gl.uniform1f(this.uniforms.time, time);
713
+ gl.uniform1f(this.uniforms.progress, progress / 100);
714
+ gl.uniform1f(this.uniforms.seed, this.seed);
715
+ gl.uniform1f(this.uniforms.profile, this.profile);
716
+ gl.activeTexture(gl.TEXTURE0);
717
+ gl.bindTexture(gl.TEXTURE_2D, this.motionTexture);
718
+ gl.uniform1i(this.uniforms.motion, 0);
719
+ gl.uniform1f(this.uniforms.motionDuration, PROGRESS_MOTION_DURATION);
720
+ gl.uniform1f(this.uniforms.motionScale, this.motionScale);
721
+
722
+ let hasEffect = this.effectUploaded ? 1 : 0;
723
+ if (!this.effectUploaded && effectImage && effectImage.complete && effectImage.naturalWidth > 0) {
724
+ gl.activeTexture(gl.TEXTURE1);
725
+ gl.bindTexture(gl.TEXTURE_2D, this.effectTexture);
726
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
727
+ try {
728
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, effectImage);
729
+ this.effectUploaded = true;
730
+ hasEffect = 1;
731
+ } catch (error) {
732
+ console.warn('[画境观屿] 参考纹理图集上传失败,继续使用程序化降级。', error);
733
+ }
734
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
735
+ }
736
+ gl.activeTexture(gl.TEXTURE1);
737
+ gl.bindTexture(gl.TEXTURE_2D, this.effectTexture);
738
+ gl.uniform1i(this.uniforms.effect, 1);
739
+ gl.uniform1f(this.uniforms.hasEffect, hasEffect);
740
+ gl.uniform1f(this.uniforms.effectFrames, 24);
741
+
742
+ gl.uniform3fv(this.uniforms.dark, this.colors[0]);
743
+ gl.uniform3fv(this.uniforms.accentA, this.colors[1]);
744
+ gl.uniform3fv(this.uniforms.accentB, this.colors[2]);
745
+ gl.uniform3fv(this.uniforms.glow, this.colors[3]);
746
+
747
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
748
+ }
749
+
750
+ setColors(colors) {
751
+ this.colors = colors.map(hexToRgb01);
752
+ }
753
+
754
+ dispose() {
755
+ const gl = this.gl;
756
+ gl.deleteBuffer(this.buffer);
757
+ gl.deleteTexture(this.motionTexture);
758
+ gl.deleteTexture(this.effectTexture);
759
+ gl.deleteProgram(this.program);
760
+ const lose = gl.getExtension('WEBGL_lose_context');
761
+ if (lose) lose.loseContext();
762
+ }
763
+ }
764
+
765
+ function createProgressFlowRenderer(canvas, preset) {
766
+ try {
767
+ return new ProgressFlowRenderer(canvas, preset);
768
+ } catch (error) {
769
+ console.warn('[画境观屿] 进度流体 WebGL2 不可用,使用 Canvas 2D 降级。', error);
770
+ return null;
771
+ }
772
+ }
773
+
774
+ const PROGRESS_REFERENCE_DURATION = 12;
775
+ const PROGRESS_REFERENCE_FRAME_COUNT = 24;
776
+
777
+ const FRAME_WIDTH = 64;
778
+ const FRAME_HEIGHT = 32;
779
+ const CACHE = Object.create(null);
780
+
781
+ const PALETTES = {
782
+ 'model-training': ['#20131f', '#ff3f94', '#ff8a3d', '#fff06a'],
783
+ 'agent-migration': ['#111a31', '#245bff', '#00cfff', '#5dffe6'],
784
+ 'visual-training': ['#1f172b', '#7042ff', '#42f58d', '#c4ff8a'],
785
+ 'tide': ['#0a2239', '#2e9bff', '#7fe3ff', '#eaf9ff']
786
+ };
787
+
788
+ function drawCloud(context, x, y, radiusX, radiusY, color, alpha) {
789
+ context.save();
790
+ context.translate(x, y);
791
+ context.scale(1, radiusY / radiusX);
792
+ const gradient = context.createRadialGradient(0, 0, 0, 0, 0, radiusX);
793
+ gradient.addColorStop(0, `${color}${Math.round(alpha * 255).toString(16).padStart(2, '0')}`);
794
+ gradient.addColorStop(0.46, `${color}${Math.round(alpha * 0.42 * 255).toString(16).padStart(2, '0')}`);
795
+ gradient.addColorStop(1, `${color}00`);
796
+ context.fillStyle = gradient;
797
+ context.fillRect(-radiusX, -radiusX, radiusX * 2, radiusX * 2);
798
+ context.restore();
799
+ }
800
+
801
+ function createAtlas(id) {
802
+ const palette = PALETTES[id] || PALETTES['visual-training'];
803
+ const canvas = document.createElement('canvas');
804
+ canvas.width = FRAME_WIDTH * PROGRESS_REFERENCE_FRAME_COUNT;
805
+ canvas.height = FRAME_HEIGHT;
806
+ const context = canvas.getContext('2d');
807
+
808
+ for (let frame = 0; frame < PROGRESS_REFERENCE_FRAME_COUNT; frame += 1) {
809
+ const phase = (frame / PROGRESS_REFERENCE_FRAME_COUNT) * Math.PI * 2;
810
+ const left = frame * FRAME_WIDTH;
811
+ context.save();
812
+ context.translate(left, 0);
813
+ context.fillStyle = palette[0];
814
+ context.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
815
+ context.globalCompositeOperation = 'screen';
816
+
817
+ drawCloud(context, 35 + Math.sin(phase * 0.83) * 5, 10 + Math.cos(phase * 0.61) * 5, 27, 18, palette[1], id === 'agent-migration' ? 0.32 : 0.42);
818
+ drawCloud(context, 45 + Math.cos(phase * 0.72) * 4, 23 + Math.sin(phase * 0.54) * 4, 22, 15, palette[2], 0.44);
819
+ drawCloud(context, 53 + Math.sin(phase * 1.07) * 2, 16 + Math.cos(phase * 0.89) * 6, 12, 13, palette[3], id === 'model-training' ? 0.30 : 0.20);
820
+
821
+ context.globalCompositeOperation = 'source-over';
822
+ const trough = context.createRadialGradient(41, 16, 1, 41, 16, 17);
823
+ trough.addColorStop(0, 'rgba(5,6,11,0.64)');
824
+ trough.addColorStop(0.58, 'rgba(6,7,12,0.26)');
825
+ trough.addColorStop(1, 'rgba(6,7,12,0)');
826
+ context.fillStyle = trough;
827
+ context.fillRect(20, 0, 44, FRAME_HEIGHT);
828
+ context.restore();
829
+ }
830
+
831
+ const image = new Image();
832
+ image.decoding = 'async';
833
+ const state = { image, ready: false };
834
+ image.addEventListener('load', () => { state.ready = true; }, { once: true });
835
+ image.addEventListener('error', () => { state.ready = false; }, { once: true });
836
+ image.src = canvas.toDataURL('image/png');
837
+ return state;
838
+ }
839
+
840
+ function getProgressReferenceAtlas(id) {
841
+ if (!CACHE[id]) CACHE[id] = createAtlas(id);
842
+ return CACHE[id];
843
+ }
844
+
845
+ /**
846
+ * Attach a WebGL2 fluid overlay to a progress capsule root.
847
+ *
848
+ * @param {object} params
849
+ * @param {HTMLElement} params.root progress capsule root element
850
+ * @param {HTMLCanvasElement} params.canvas 2D fallback canvas (kept beneath)
851
+ * @param {object} params.preset progress preset
852
+ * @param {() => number} params.getProgress reads the current progress value
853
+ * @returns {{ update(flowTime: number): void, dispose(): void } | null}
854
+ */
855
+ function attachProgressFlowOverlay({ root, canvas, preset, getProgress }) {
856
+ const overlay = document.createElement('canvas');
857
+ overlay.className = 'hj-progress-canvas hj-progress-overlay';
858
+ overlay.setAttribute('aria-hidden', 'true');
859
+ canvas.insertAdjacentElement('afterend', overlay);
860
+
861
+ const renderer = createProgressFlowRenderer(overlay, preset);
862
+ if (!renderer) {
863
+ overlay.remove();
864
+ return null;
865
+ }
866
+
867
+ const atlas = getProgressReferenceAtlas(preset.id);
868
+ root.classList.add('has-webgl-progress');
869
+
870
+ const resize = () => {
871
+ const bounds = root.getBoundingClientRect();
872
+ const width = Math.max(1, bounds.width);
873
+ const height = Math.max(1, bounds.height);
874
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
875
+ overlay.style.width = `${width}px`;
876
+ overlay.style.height = `${height}px`;
877
+ renderer.resize(width, height, dpr);
878
+ };
879
+
880
+ let resizeObserver = null;
881
+ let onWindowResize = null;
882
+ if (typeof ResizeObserver !== 'undefined') {
883
+ resizeObserver = new ResizeObserver(resize);
884
+ resizeObserver.observe(root);
885
+ } else {
886
+ onWindowResize = resize;
887
+ window.addEventListener('resize', onWindowResize);
888
+ }
889
+ resize();
890
+
891
+ return {
892
+ update(flowTime) {
893
+ const effectTime = flowTime % PROGRESS_REFERENCE_DURATION;
894
+ const progress = getProgress();
895
+ renderer.draw(
896
+ effectTime,
897
+ Number.isFinite(progress) ? progress : preset.initialProgress,
898
+ atlas.ready ? atlas.image : null
899
+ );
900
+ },
901
+ setColors(colors) {
902
+ renderer.setColors(colors);
903
+ },
904
+ dispose() {
905
+ if (resizeObserver) resizeObserver.disconnect();
906
+ if (onWindowResize) window.removeEventListener('resize', onWindowResize);
907
+ renderer.dispose();
908
+ overlay.remove();
909
+ root.classList.remove('has-webgl-progress');
910
+ }
911
+ };
912
+ }
913
+
914
+ const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
915
+ const SUPPORTS_CTX_FILTER = typeof CanvasRenderingContext2D !== 'undefined' && 'filter' in CanvasRenderingContext2D.prototype;
916
+
917
+ function stringSeed(value) {
918
+ let hash = 2166136261;
919
+ for (const character of value) {
920
+ hash ^= character.charCodeAt(0);
921
+ hash = Math.imul(hash, 16777619);
922
+ }
923
+ return (hash >>> 0) / 4294967295;
924
+ }
925
+
926
+ function interpolate(template, values) {
927
+ return template.replace(/\{(\w+)\}/g, (_, key) => (values[key] !== undefined ? values[key] : ''));
928
+ }
929
+
930
+ function prefersReducedMotion() {
931
+ return typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
932
+ }
933
+
934
+ const FLOW_PROFILES = {
935
+ 'model-training': {
936
+ cycles: [0.98, 3.05, 5.45],
937
+ amplitudes: [11.2, 11.0, 5.2],
938
+ speeds: [0.31, -0.53, 0.78],
939
+ bulgeAmplitude: 8.2,
940
+ timeScale: 1.0,
941
+ glowWidth: 5.8,
942
+ haloWidth: 20,
943
+ whiteAlpha: 0.72,
944
+ whiteWidth: 1.15,
945
+ cloudWidth: 0.17,
946
+ autoRange: [25, 66]
947
+ },
948
+ 'agent-migration': {
949
+ cycles: [0.62, 1.55, 2.95],
950
+ amplitudes: [16.0, 7.8, 2.3],
951
+ speeds: [0.25, -0.4, 0.60],
952
+ bulgeAmplitude: 8.4,
953
+ timeScale: 0.82,
954
+ glowWidth: 6.3,
955
+ haloWidth: 21,
956
+ whiteAlpha: 0.18,
957
+ whiteWidth: 0.45,
958
+ cloudWidth: 0.18,
959
+ autoRange: [24, 62]
960
+ },
961
+ 'visual-training': {
962
+ cycles: [0.88, 2.45, 4.35],
963
+ amplitudes: [12.8, 10.2, 4.3],
964
+ speeds: [0.28, -0.47, 0.69],
965
+ bulgeAmplitude: 7.3,
966
+ timeScale: 0.91,
967
+ glowWidth: 6.0,
968
+ haloWidth: 21,
969
+ whiteAlpha: 0.30,
970
+ whiteWidth: 0.55,
971
+ cloudWidth: 0.175,
972
+ autoRange: [20, 75]
973
+ },
974
+ // ponytail: first-pass tide = asymmetric surge on the 2D fallback path.
975
+ // Tune surge/amplitudes after visual QA against the WebGL overlay.
976
+ 'tide': {
977
+ cycles: [0.72, 1.9, 4.2],
978
+ amplitudes: [19.0, 6.5, 1.5],
979
+ speeds: [0.42, -0.5, 0.66],
980
+ bulgeAmplitude: 9.5,
981
+ timeScale: 0.85,
982
+ glowWidth: 6.2,
983
+ haloWidth: 21,
984
+ whiteAlpha: 0.5,
985
+ whiteWidth: 1.0,
986
+ cloudWidth: 0.18,
987
+ autoRange: [18, 70],
988
+ surge: 0.55
989
+ }
990
+ };
991
+
992
+ class ProgressCapsuleController {
993
+ constructor({ root, canvas, valueElement, preset, emitter, options, copy }) {
994
+ this.root = root;
995
+ this.canvas = canvas;
996
+ this.valueElement = valueElement;
997
+ this.preset = preset;
998
+ this.emitter = emitter;
999
+ this.options = options;
1000
+ this.copy = copy;
1001
+ this.profile = preset.edgeStyle === 'tide'
1002
+ ? FLOW_PROFILES.tide
1003
+ : (FLOW_PROFILES[preset.id] || FLOW_PROFILES['visual-training']);
1004
+ this.min = options.min ?? 0;
1005
+ this.max = options.max ?? 100;
1006
+ this.dprCap = dprCapFor(options.quality);
1007
+ this.ctx = canvas.getContext('2d');
1008
+ this.value = clamp(options.value ?? preset.initialProgress, this.min, this.max);
1009
+ this.dragging = false;
1010
+ this.webglActive = false;
1011
+ this.flowTime = stringSeed(preset.id) * 31;
1012
+ this.seed = stringSeed(`${preset.id}-reference`) * Math.PI * 2;
1013
+ this.randomState = Math.floor(stringSeed(`${preset.id}-auto`) * 0x7fffffff) || 1;
1014
+ this.dpr = 1;
1015
+ this.width = 0;
1016
+ this.height = 0;
1017
+ this.handlers = {};
1018
+
1019
+ this.resizeObserver = typeof ResizeObserver !== 'undefined'
1020
+ ? new ResizeObserver(() => this.resizeCanvas())
1021
+ : null;
1022
+ if (this.resizeObserver) this.resizeObserver.observe(this.root);
1023
+ else window.addEventListener('resize', this.resizeCanvas);
1024
+
1025
+ this.suppressEvents = true;
1026
+ this.setProgress(this.value, 'init');
1027
+ this.suppressEvents = false;
1028
+ this.bindEvents();
1029
+ this.resizeCanvas();
1030
+ }
1031
+
1032
+ random() {
1033
+ this.randomState = (Math.imul(this.randomState, 1664525) + 1013904223) >>> 0;
1034
+ return this.randomState / 4294967296;
1035
+ }
1036
+
1037
+ setProgress(nextValue, source = 'auto') {
1038
+ this.value = clamp(nextValue, this.min, this.max);
1039
+ const rounded = Math.round(this.value);
1040
+ this.root.style.setProperty('--progress', this.value.toFixed(2));
1041
+ this.root.setAttribute('aria-valuenow', String(rounded));
1042
+ this.root.setAttribute('aria-valuetext', `${rounded}${this.copy.valueSuffix}`);
1043
+ this.valueElement.textContent = `${rounded}${this.copy.valueSuffix}`;
1044
+ if (!this.suppressEvents) this.emitter.emit('change', { value: this.value, source });
1045
+ }
1046
+
1047
+ resizeCanvas() {
1048
+ const bounds = this.root.getBoundingClientRect();
1049
+ this.dpr = Math.min(window.devicePixelRatio || 1, this.dprCap);
1050
+ this.width = Math.max(1, bounds.width);
1051
+ this.height = Math.max(1, bounds.height);
1052
+ this.canvas.width = Math.round(this.width * this.dpr);
1053
+ this.canvas.height = Math.round(this.height * this.dpr);
1054
+ this.canvas.style.width = `${this.width}px`;
1055
+ this.canvas.style.height = `${this.height}px`;
1056
+ this.ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
1057
+ }
1058
+
1059
+ edgeEnvelope(yRatio) {
1060
+ const edge = Math.sin(Math.PI * clamp(yRatio, 0, 1));
1061
+ return Math.pow(Math.max(edge, 0), 0.48);
1062
+ }
1063
+
1064
+ localBulge(yRatio, time, index) {
1065
+ const direction = index === 0 ? 1 : -1;
1066
+ const center = 0.28 + index * 0.40 + Math.sin(time * (0.19 + index * 0.035) + this.seed * (1.1 + index)) * 0.13;
1067
+ const width = 0.075 + index * 0.016 + Math.sin(time * 0.13 + this.seed * 2.1) * 0.012;
1068
+ const distance = (yRatio - center) / Math.max(width, 0.035);
1069
+ const gaussian = Math.exp(-0.5 * distance * distance);
1070
+ return gaussian * Math.sin(time * (0.71 + index * 0.09) + this.seed * (2.7 + index)) * this.profile.bulgeAmplitude * direction;
1071
+ }
1072
+
1073
+ edgeOffset(y, time, phase = 0, amplitudeScale = 1) {
1074
+ const yRatio = this.height > 0 ? y / this.height : 0;
1075
+ const envelope = this.edgeEnvelope(yRatio);
1076
+ const scaledTime = time * this.profile.timeScale;
1077
+ const phaseTime = this.profile.surge
1078
+ ? scaledTime + this.profile.surge * Math.sin(scaledTime * 2)
1079
+ : scaledTime;
1080
+ let offset = 0;
1081
+
1082
+ for (let index = 0; index < this.profile.cycles.length; index += 1) {
1083
+ const cycle = this.profile.cycles[index];
1084
+ const amplitude = this.profile.amplitudes[index];
1085
+ const speed = this.profile.speeds[index];
1086
+ const amplitudeMotion = 0.74 + 0.26 * Math.sin(
1087
+ phaseTime * (0.17 + index * 0.045) + this.seed * (index + 2.4)
1088
+ );
1089
+ offset += Math.sin(
1090
+ yRatio * Math.PI * 2 * cycle + phaseTime * speed * Math.PI * 2 + this.seed * (index + 1) + phase
1091
+ ) * amplitude * amplitudeMotion;
1092
+ }
1093
+
1094
+ offset += this.localBulge(yRatio, phaseTime + phase, 0);
1095
+ offset += this.localBulge(yRatio, phaseTime - phase * 0.7, 1);
1096
+ return offset * envelope * amplitudeScale;
1097
+ }
1098
+
1099
+ createEdgePath(ctx, baseX, time, phase = 0, amplitudeScale = 1) {
1100
+ const step = Math.max(1.8, this.height / 92);
1101
+ ctx.beginPath();
1102
+ for (let y = 0; y <= this.height + step; y += step) {
1103
+ const x = baseX + this.edgeOffset(y, time, phase, amplitudeScale);
1104
+ if (y === 0) ctx.moveTo(x, y);
1105
+ else ctx.lineTo(x, y);
1106
+ }
1107
+ }
1108
+
1109
+ createFillPath(ctx, baseX, time, phase = 0, amplitudeScale = 1) {
1110
+ const step = Math.max(1.8, this.height / 92);
1111
+ ctx.beginPath();
1112
+ ctx.moveTo(0, 0);
1113
+ ctx.lineTo(baseX + this.edgeOffset(0, time, phase, amplitudeScale), 0);
1114
+ for (let y = step; y <= this.height + step; y += step) {
1115
+ ctx.lineTo(baseX + this.edgeOffset(y, time, phase, amplitudeScale), y);
1116
+ }
1117
+ ctx.lineTo(0, this.height);
1118
+ ctx.closePath();
1119
+ }
1120
+
1121
+ drawEllipticalGlow(x, y, radiusX, radiusY, color, alpha) {
1122
+ const ctx = this.ctx;
1123
+ ctx.save();
1124
+ ctx.translate(x, y);
1125
+ ctx.scale(1, radiusY / radiusX);
1126
+ const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, radiusX);
1127
+ gradient.addColorStop(0, hexToRgba(color, alpha));
1128
+ gradient.addColorStop(0.42, hexToRgba(color, alpha * 0.48));
1129
+ gradient.addColorStop(1, hexToRgba(color, 0));
1130
+ ctx.globalCompositeOperation = 'screen';
1131
+ ctx.fillStyle = gradient;
1132
+ ctx.fillRect(-radiusX, -radiusX, radiusX * 2, radiusX * 2);
1133
+ ctx.restore();
1134
+ }
1135
+
1136
+ drawDarkEllipticalShadow(x, y, radiusX, radiusY, alpha) {
1137
+ const ctx = this.ctx;
1138
+ ctx.save();
1139
+ ctx.translate(x, y);
1140
+ ctx.scale(1, radiusY / radiusX);
1141
+ const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, radiusX);
1142
+ gradient.addColorStop(0, `rgba(6, 6, 11, ${alpha})`);
1143
+ gradient.addColorStop(0.54, `rgba(8, 8, 14, ${alpha * 0.62})`);
1144
+ gradient.addColorStop(1, 'rgba(8, 8, 14, 0)');
1145
+ ctx.globalCompositeOperation = 'source-over';
1146
+ ctx.fillStyle = gradient;
1147
+ ctx.fillRect(-radiusX, -radiusX, radiusX * 2, radiusX * 2);
1148
+ ctx.restore();
1149
+ }
1150
+
1151
+ drawColorClouds(shoreline, time, accentA, accentB, glow) {
1152
+ this.ctx;
1153
+ const width = this.width;
1154
+ const height = this.height;
1155
+ const scale = this.profile.cloudWidth;
1156
+ const t = time * this.profile.timeScale;
1157
+
1158
+ const upperY = height * (0.28 + Math.sin(t * 0.24 + this.seed) * 0.13);
1159
+ const lowerY = height * (0.70 + Math.cos(t * 0.21 + this.seed * 1.7) * 0.12);
1160
+ const middleY = height * (0.49 + Math.sin(t * 0.31 + this.seed * 2.3) * 0.15);
1161
+
1162
+ const farX = shoreline - width * 0.095;
1163
+ const farRx = Math.max(52, width * scale);
1164
+ const farRy = height * 0.42;
1165
+ this.drawEllipticalGlow(farX, upperY, farRx, farRy, accentA, 0.38);
1166
+ this.drawDarkEllipticalShadow(
1167
+ farX + farRx * 0.16,
1168
+ upperY,
1169
+ farRx * 0.58,
1170
+ farRy * 0.66,
1171
+ 0.74
1172
+ );
1173
+
1174
+ const lowerX = shoreline - width * 0.072;
1175
+ const lowerRx = Math.max(44, width * scale * 0.82);
1176
+ const lowerRy = height * 0.36;
1177
+ this.drawEllipticalGlow(lowerX, lowerY, lowerRx, lowerRy, accentB, 0.31);
1178
+ this.drawDarkEllipticalShadow(
1179
+ lowerX + lowerRx * 0.14,
1180
+ lowerY,
1181
+ lowerRx * 0.54,
1182
+ lowerRy * 0.62,
1183
+ 0.64
1184
+ );
1185
+
1186
+ this.drawEllipticalGlow(
1187
+ shoreline - width * 0.034,
1188
+ middleY,
1189
+ Math.max(30, width * scale * 0.48),
1190
+ height * 0.27,
1191
+ glow,
1192
+ 0.20
1193
+ );
1194
+ }
1195
+
1196
+ drawPathBand({ baseX, time, phase, amplitudeScale, color, alpha, blur, width, composite = 'screen' }) {
1197
+ const ctx = this.ctx;
1198
+ this.createEdgePath(ctx, baseX, time, phase, amplitudeScale);
1199
+ ctx.save();
1200
+ ctx.globalCompositeOperation = composite;
1201
+ ctx.globalAlpha = alpha;
1202
+ // Safari < 18 and some old WebViews ignore ctx.filter; setting it is a
1203
+ // no-op there, so only assign when supported to keep intent explicit.
1204
+ if (SUPPORTS_CTX_FILTER) ctx.filter = `blur(${blur}px)`;
1205
+ ctx.strokeStyle = color;
1206
+ ctx.lineWidth = width;
1207
+ ctx.stroke();
1208
+ ctx.restore();
1209
+ }
1210
+
1211
+ setRange(min, max) {
1212
+ this.min = min;
1213
+ this.max = max;
1214
+ const clamped = clamp(this.value, this.min, this.max);
1215
+ if (clamped !== this.value) this.setProgress(clamped, 'prop');
1216
+ }
1217
+
1218
+ drawReferenceFlow() {
1219
+ const ctx = this.ctx;
1220
+ const width = this.width;
1221
+ const height = this.height;
1222
+ if (!ctx || width <= 0 || height <= 0) return;
1223
+
1224
+ const shoreline = width * (this.value / 100);
1225
+ const time = this.flowTime;
1226
+ const [dark, accentA, accentB, glow] = this.preset.colors;
1227
+
1228
+ ctx.clearRect(0, 0, width, height);
1229
+ ctx.fillStyle = '#202126';
1230
+ ctx.fillRect(0, 0, width, height);
1231
+
1232
+ this.createFillPath(ctx, shoreline, time, 0, 1);
1233
+ const bodyGradient = ctx.createLinearGradient(0, 0, Math.max(shoreline, 1), 0);
1234
+ bodyGradient.addColorStop(0, dark);
1235
+ bodyGradient.addColorStop(0.74, dark);
1236
+ bodyGradient.addColorStop(0.89, hexToRgba(dark, 0.99));
1237
+ bodyGradient.addColorStop(0.955, hexToRgba(accentA, 0.09));
1238
+ bodyGradient.addColorStop(0.992, hexToRgba(accentB, 0.54));
1239
+ bodyGradient.addColorStop(1, hexToRgba(glow, 0.78));
1240
+ ctx.fillStyle = bodyGradient;
1241
+ ctx.fill();
1242
+
1243
+ this.drawColorClouds(shoreline, time, accentA, accentB, glow);
1244
+
1245
+ this.drawPathBand({
1246
+ baseX: shoreline - width * 0.105,
1247
+ time,
1248
+ phase: 1.42,
1249
+ amplitudeScale: 1.18,
1250
+ color: accentA,
1251
+ alpha: 0.22,
1252
+ blur: 21,
1253
+ width: 54
1254
+ });
1255
+ this.drawPathBand({
1256
+ baseX: shoreline - width * 0.073,
1257
+ time,
1258
+ phase: -0.92,
1259
+ amplitudeScale: 1.06,
1260
+ color: accentB,
1261
+ alpha: 0.30,
1262
+ blur: 15,
1263
+ width: 42
1264
+ });
1265
+ this.drawPathBand({
1266
+ baseX: shoreline - width * 0.047,
1267
+ time,
1268
+ phase: 0.42,
1269
+ amplitudeScale: 0.94,
1270
+ color: 'rgba(5, 5, 10, 0.92)',
1271
+ alpha: 0.72,
1272
+ blur: 12,
1273
+ width: 34,
1274
+ composite: 'source-over'
1275
+ });
1276
+ this.drawPathBand({
1277
+ baseX: shoreline - width * 0.025,
1278
+ time,
1279
+ phase: -0.28,
1280
+ amplitudeScale: 0.96,
1281
+ color: accentB,
1282
+ alpha: 0.66,
1283
+ blur: 8,
1284
+ width: 28
1285
+ });
1286
+
1287
+ ctx.save();
1288
+ this.createFillPath(ctx, shoreline, time, 0, 1);
1289
+ ctx.clip();
1290
+ this.createEdgePath(ctx, shoreline, time, 0, 1);
1291
+
1292
+ ctx.save();
1293
+ ctx.globalCompositeOperation = 'screen';
1294
+ ctx.strokeStyle = hexToRgba(accentA, 0.20);
1295
+ ctx.lineWidth = this.profile.haloWidth;
1296
+ ctx.shadowColor = accentA;
1297
+ ctx.shadowBlur = this.profile.haloWidth * 0.72;
1298
+ ctx.stroke();
1299
+ ctx.restore();
1300
+
1301
+ ctx.save();
1302
+ ctx.globalCompositeOperation = 'screen';
1303
+ ctx.strokeStyle = hexToRgba(accentB, 0.78);
1304
+ ctx.lineWidth = this.profile.glowWidth + 4.2;
1305
+ ctx.shadowColor = accentB;
1306
+ ctx.shadowBlur = 8;
1307
+ ctx.stroke();
1308
+ ctx.restore();
1309
+
1310
+ ctx.save();
1311
+ ctx.globalCompositeOperation = 'screen';
1312
+ ctx.strokeStyle = hexToRgba(glow, 0.88);
1313
+ ctx.lineWidth = this.profile.glowWidth;
1314
+ ctx.shadowColor = glow;
1315
+ ctx.shadowBlur = 5;
1316
+ ctx.stroke();
1317
+ ctx.restore();
1318
+
1319
+ ctx.restore();
1320
+
1321
+ ctx.save();
1322
+ ctx.globalCompositeOperation = 'screen';
1323
+ ctx.strokeStyle = hexToRgba(glow, 0.84);
1324
+ ctx.lineWidth = 2.15;
1325
+ ctx.shadowColor = glow;
1326
+ ctx.shadowBlur = 2.5;
1327
+ this.createEdgePath(ctx, shoreline, time, 0, 1);
1328
+ ctx.stroke();
1329
+ ctx.restore();
1330
+
1331
+ if (this.profile.whiteAlpha > 0.05) {
1332
+ ctx.save();
1333
+ ctx.globalCompositeOperation = 'screen';
1334
+ ctx.strokeStyle = `rgba(255,255,245,${this.profile.whiteAlpha})`;
1335
+ ctx.lineWidth = this.profile.whiteWidth;
1336
+ this.createEdgePath(ctx, shoreline, time, 0, 1);
1337
+ ctx.stroke();
1338
+ ctx.restore();
1339
+ }
1340
+ }
1341
+
1342
+ updateFromPointer(event) {
1343
+ const bounds = this.root.getBoundingClientRect();
1344
+ const ratio = bounds.width > 0 ? (event.clientX - bounds.left) / bounds.width : 0;
1345
+ this.setProgress(ratio * 100, 'drag');
1346
+ }
1347
+
1348
+ beginDrag(event) {
1349
+ if (event.button !== undefined && event.button !== 0) return;
1350
+ event.preventDefault();
1351
+ this.dragging = true;
1352
+ this.root.classList.add('is-dragging');
1353
+ try { this.root.setPointerCapture?.(event.pointerId); } catch {}
1354
+ this.emitter.emit('dragstart', { value: this.value });
1355
+ this.updateFromPointer(event);
1356
+ }
1357
+
1358
+ moveDrag(event) {
1359
+ if (!this.dragging) return;
1360
+ event.preventDefault();
1361
+ this.updateFromPointer(event);
1362
+ }
1363
+
1364
+ endDrag(event) {
1365
+ if (!this.dragging) return;
1366
+ this.dragging = false;
1367
+ this.root.classList.remove('is-dragging');
1368
+ try {
1369
+ if (event?.pointerId !== undefined && this.root.hasPointerCapture?.(event.pointerId)) {
1370
+ this.root.releasePointerCapture(event.pointerId);
1371
+ }
1372
+ } catch {}
1373
+ this.emitter.emit('dragend', { value: this.value });
1374
+ }
1375
+
1376
+ bindEvents() {
1377
+ if (this.options.draggable !== false) {
1378
+ this.handlers.pointerdown = (event) => this.beginDrag(event);
1379
+ this.handlers.pointermove = (event) => this.moveDrag(event);
1380
+ this.handlers.pointerup = (event) => this.endDrag(event);
1381
+ this.handlers.pointercancel = (event) => this.endDrag(event);
1382
+ this.root.addEventListener('pointerdown', this.handlers.pointerdown);
1383
+ this.root.addEventListener('pointermove', this.handlers.pointermove);
1384
+ this.root.addEventListener('pointerup', this.handlers.pointerup);
1385
+ this.root.addEventListener('pointercancel', this.handlers.pointercancel);
1386
+ }
1387
+
1388
+ if (this.options.keyboard !== false) {
1389
+ this.handlers.keydown = (event) => {
1390
+ const actions = {
1391
+ ArrowLeft: -2,
1392
+ ArrowDown: -2,
1393
+ ArrowRight: 2,
1394
+ ArrowUp: 2,
1395
+ PageDown: -10,
1396
+ PageUp: 10
1397
+ };
1398
+ if (event.key === 'Home') {
1399
+ event.preventDefault();
1400
+ this.setProgress(this.min, 'keyboard');
1401
+ } else if (event.key === 'End') {
1402
+ event.preventDefault();
1403
+ this.setProgress(this.max, 'keyboard');
1404
+ } else if (actions[event.key]) {
1405
+ event.preventDefault();
1406
+ this.setProgress(this.value + actions[event.key], 'keyboard');
1407
+ } else {
1408
+ return;
1409
+ }
1410
+ };
1411
+ this.root.addEventListener('keydown', this.handlers.keydown);
1412
+ }
1413
+ }
1414
+
1415
+ update(delta, paused) {
1416
+ if (!paused) this.flowTime += delta;
1417
+ }
1418
+
1419
+ draw() {
1420
+ // Performance fix: when the WebGL overlay is active the 2D layer is
1421
+ // hidden behind it, so drawing it every frame would be wasted CPU.
1422
+ if (this.webglActive) return;
1423
+ this.drawReferenceFlow();
1424
+ }
1425
+
1426
+ randomize() {
1427
+ this.flowTime = this.random() * 40;
1428
+ }
1429
+
1430
+ setColors(colors) {
1431
+ if (!Array.isArray(colors) || colors.length !== 4) return;
1432
+ this.preset = { ...this.preset, colors };
1433
+ }
1434
+
1435
+ dispose() {
1436
+ if (this.resizeObserver) this.resizeObserver.disconnect();
1437
+ else window.removeEventListener('resize', this.resizeCanvas);
1438
+ for (const name of Object.keys(this.handlers)) {
1439
+ const handler = this.handlers[name];
1440
+ this.root.removeEventListener(name, handler);
1441
+ }
1442
+ this.handlers = {};
1443
+ }
1444
+ }
1445
+
1446
+ /**
1447
+ * Mount a fluid progress capsule into `container`.
1448
+ *
1449
+ * Options: preset (id/code/name or object), width, height, value, min, max,
1450
+ * draggable, keyboard, colors, edgeStyle, quality,
1451
+ * respectReducedMotion, copy, cssVars.
1452
+ */
1453
+ function createProgressCapsule(container, options = {}) {
1454
+ if (!container || typeof container.appendChild !== 'function') {
1455
+ throw new Error('createProgressCapsule: container element is required');
1456
+ }
1457
+
1458
+ const preset = { ...getPreset('progress', options.preset ?? 'NC-10') };
1459
+ const merged = normalizeOptions(DEFAULTS.progress, preset, options);
1460
+ const copy = { ...COPY, ...(merged.copy || {}) };
1461
+
1462
+ const root = document.createElement('div');
1463
+ root.className = 'hj-capsule-root hj-progress-root';
1464
+ root.setAttribute('role', 'slider');
1465
+ root.setAttribute('tabindex', '0');
1466
+ root.setAttribute('data-draggable', String(merged.draggable !== false));
1467
+ root.setAttribute('aria-valuemin', String(merged.min ?? 0));
1468
+ root.setAttribute('aria-valuemax', String(merged.max ?? 100));
1469
+ root.setAttribute('aria-valuenow', String(preset.initialProgress));
1470
+ root.setAttribute(
1471
+ 'aria-label',
1472
+ interpolate(copy.progressAria, { brand: copy.brandName, code: preset.code, name: preset.name })
1473
+ );
1474
+ if (merged.keyboard === false) root.setAttribute('tabindex', '-1');
1475
+
1476
+ const canvas = document.createElement('canvas');
1477
+ canvas.className = 'hj-progress-canvas';
1478
+ canvas.setAttribute('aria-hidden', 'true');
1479
+
1480
+ const copyEnabled = copy.enabled !== false && merged.showCopy !== false;
1481
+
1482
+ const copyText = (key, fallback) => {
1483
+ const value = copy[key];
1484
+ return value === undefined ? fallback : value;
1485
+ };
1486
+
1487
+ function buildCopyHtml() {
1488
+ let html = '';
1489
+ const brandText = copy.brandName || '';
1490
+ const subtitleText = copyText('subtitle', preset.subtitle);
1491
+ if (brandText) html += `<span class="hj-progress-name">${brandText}</span>`;
1492
+ if (subtitleText) html += `<span class="hj-progress-subtitle">${subtitleText}</span>`;
1493
+ return html;
1494
+ }
1495
+
1496
+ const copyLayer = document.createElement('div');
1497
+ copyLayer.className = 'hj-progress-copy';
1498
+ const renderCopy = () => {
1499
+ if (copyEnabled) copyLayer.innerHTML = buildCopyHtml();
1500
+ };
1501
+ renderCopy();
1502
+
1503
+ if (copy.background) {
1504
+ root.style.setProperty('--hj-progress-copy-bg', copy.background);
1505
+ root.style.setProperty('--hj-progress-copy-pad', '6px 12px');
1506
+ }
1507
+ if (copy.color) root.style.setProperty('--hj-progress-copy-color', copy.color);
1508
+
1509
+ const valueElement = document.createElement('div');
1510
+ valueElement.className = 'hj-progress-value';
1511
+ valueElement.setAttribute('aria-hidden', 'true');
1512
+
1513
+ const dragLabel = document.createElement('span');
1514
+ dragLabel.className = 'hj-progress-drag-label';
1515
+ dragLabel.setAttribute('aria-hidden', 'true');
1516
+ dragLabel.textContent = copy.dragLabel;
1517
+
1518
+ root.appendChild(canvas);
1519
+ if (copyEnabled) root.appendChild(copyLayer);
1520
+ root.appendChild(valueElement);
1521
+ root.appendChild(dragLabel);
1522
+ container.appendChild(root);
1523
+
1524
+ const emitter = createEmitter();
1525
+ let paused = merged.respectReducedMotion && prefersReducedMotion();
1526
+
1527
+ const applySize = () => {
1528
+ root.style.width = parseSize(merged.width);
1529
+ root.style.height = parseSize(merged.height);
1530
+ const vars = merged.cssVars || {};
1531
+ for (const name of Object.keys(vars)) root.style.setProperty(name, vars[name]);
1532
+ };
1533
+ applySize();
1534
+
1535
+ const controller = new ProgressCapsuleController({
1536
+ root,
1537
+ canvas,
1538
+ valueElement,
1539
+ preset,
1540
+ emitter,
1541
+ options: merged,
1542
+ copy
1543
+ });
1544
+
1545
+ let overlay = null;
1546
+ if (merged.renderer !== 'canvas2d') {
1547
+ overlay = attachProgressFlowOverlay({
1548
+ root,
1549
+ canvas,
1550
+ preset,
1551
+ getProgress: () => controller.value
1552
+ });
1553
+ }
1554
+ if (overlay) controller.webglActive = true;
1555
+
1556
+ const visibility = createVisibilityGuard(root);
1557
+ let flowTime = 0;
1558
+ const unsubscribe = subscribeScheduler(
1559
+ (delta, now) => {
1560
+ flowTime += delta;
1561
+ controller.update(delta, false);
1562
+ if (visibility.isVisible()) {
1563
+ controller.draw();
1564
+ if (overlay) overlay.update(flowTime);
1565
+ }
1566
+ },
1567
+ () => paused
1568
+ );
1569
+
1570
+ emitter.emit('ready', { preset: { ...preset } });
1571
+
1572
+ const syncDom = () => {
1573
+ root.setAttribute(
1574
+ 'aria-label',
1575
+ interpolate(copy.progressAria, { brand: copy.brandName, code: preset.code, name: preset.name })
1576
+ );
1577
+ renderCopy();
1578
+ };
1579
+
1580
+ return {
1581
+ element: root,
1582
+ canvas,
1583
+ preset,
1584
+ on: emitter.on,
1585
+ off: emitter.off,
1586
+ setValue(value, source = 'prop') {
1587
+ controller.setProgress(value, source);
1588
+ return this;
1589
+ },
1590
+ getValue() {
1591
+ return controller.value;
1592
+ },
1593
+ setRange(min, max) {
1594
+ controller.setRange(min, max);
1595
+ return this;
1596
+ },
1597
+ setPreset(ref) {
1598
+ const next = getPreset('progress', ref);
1599
+ Object.assign(preset, next);
1600
+ controller.preset = next;
1601
+ controller.profile = next.edgeStyle === 'tide'
1602
+ ? FLOW_PROFILES.tide
1603
+ : (FLOW_PROFILES[next.id] || FLOW_PROFILES['visual-training']);
1604
+ controller.flowTime = stringSeed(next.id) * 31;
1605
+ controller.seed = stringSeed(`${next.id}-reference`) * Math.PI * 2;
1606
+ syncDom();
1607
+ if (overlay) {
1608
+ overlay.dispose();
1609
+ overlay = attachProgressFlowOverlay({ root, canvas, preset: next, getProgress: () => controller.value });
1610
+ }
1611
+ controller.webglActive = Boolean(overlay);
1612
+ controller.resizeCanvas();
1613
+ emitter.emit('presetchange', { preset: { ...next } });
1614
+ return this;
1615
+ },
1616
+ setColors(colors) {
1617
+ if (!Array.isArray(colors) || colors.length !== 4) return this;
1618
+ controller.setColors(colors);
1619
+ if (overlay) overlay.setColors(colors);
1620
+ controller.resizeCanvas();
1621
+ return this;
1622
+ },
1623
+ setSize(width, height) {
1624
+ if (width !== undefined) merged.width = width;
1625
+ if (height !== undefined) merged.height = height;
1626
+ applySize();
1627
+ controller.resizeCanvas();
1628
+ return this;
1629
+ },
1630
+ randomize() {
1631
+ controller.randomize();
1632
+ return this;
1633
+ },
1634
+ pause() {
1635
+ paused = true;
1636
+ return this;
1637
+ },
1638
+ resume() {
1639
+ paused = false;
1640
+ return this;
1641
+ },
1642
+ setQuality(quality) {
1643
+ merged.quality = quality;
1644
+ controller.dprCap = dprCapFor(quality);
1645
+ controller.resizeCanvas();
1646
+ return this;
1647
+ },
1648
+ dispose() {
1649
+ unsubscribe();
1650
+ visibility.dispose();
1651
+ if (overlay) overlay.dispose();
1652
+ controller.dispose();
1653
+ root.remove();
1654
+ }
1655
+ };
1656
+ }
1657
+
1658
+ export { ProgressCapsuleController, createProgressCapsule };