@5even7/dlc-ui 0.2.15 → 0.2.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/color.mjs CHANGED
@@ -1,102 +1,102 @@
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
- };
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
36
  }
37
37
 
38
- const QUALITY_TIERS = {
39
- low: { dpr: 1 },
40
- medium: { dpr: 1.5 },
41
- high: { dpr: 2 }
42
- };
43
-
44
- function autoDprCap() {
45
- const nav = typeof navigator !== 'undefined' ? navigator : null;
46
- const memory = nav && typeof nav.deviceMemory === 'number' ? nav.deviceMemory : 8;
47
- const cores = nav && typeof nav.hardwareConcurrency === 'number' ? nav.hardwareConcurrency : 8;
48
- return memory <= 4 || cores <= 4 ? 1.5 : 2;
49
- }
50
-
51
- function dprCapFor(quality) {
52
- if (quality === 'auto') return autoDprCap();
53
- const tier = QUALITY_TIERS[quality] || QUALITY_TIERS.medium;
54
- return tier.dpr;
38
+ const QUALITY_TIERS = {
39
+ low: { dpr: 1 },
40
+ medium: { dpr: 1.5 },
41
+ high: { dpr: 2 }
42
+ };
43
+
44
+ function autoDprCap() {
45
+ const nav = typeof navigator !== 'undefined' ? navigator : null;
46
+ const memory = nav && typeof nav.deviceMemory === 'number' ? nav.deviceMemory : 8;
47
+ const cores = nav && typeof nav.hardwareConcurrency === 'number' ? nav.hardwareConcurrency : 8;
48
+ return memory <= 4 || cores <= 4 ? 1.5 : 2;
49
+ }
50
+
51
+ function dprCapFor(quality) {
52
+ if (quality === 'auto') return autoDprCap();
53
+ const tier = QUALITY_TIERS[quality] || QUALITY_TIERS.medium;
54
+ return tier.dpr;
55
+ }
56
+
57
+ function effectiveDprCap(quality, renderScale = 1) {
58
+ const scale = Number(renderScale);
59
+ const normalizedScale = Number.isFinite(scale) ? Math.min(1, Math.max(0.25, scale)) : 1;
60
+ return Math.max(0.5, dprCapFor(quality) * normalizedScale);
55
61
  }
56
62
 
57
- function effectiveDprCap(quality, renderScale = 1) {
58
- const scale = Number(renderScale);
59
- const normalizedScale = Number.isFinite(scale) ? Math.min(1, Math.max(0.25, scale)) : 1;
60
- return Math.max(0.5, dprCapFor(quality) * normalizedScale);
63
+ /**
64
+ * Merge defaults < preset < user. Unknown user keys are preserved so the
65
+ * component API can grow (new props, cssVars, callbacks) without a breaking
66
+ * change.
67
+ */
68
+ function normalizeOptions(defaults, preset, user) {
69
+ // undefined means "not provided" (e.g. Vue $props with unset props):
70
+ // drop those keys before merging so defaults/preset values survive.
71
+ const omitUndefined = (source) => {
72
+ const result = {};
73
+ for (const key of Object.keys(source)) {
74
+ if (source[key] !== undefined) result[key] = source[key];
75
+ }
76
+ return result;
77
+ };
78
+ const presetOptions = omitUndefined(preset && typeof preset === 'object' ? preset : {});
79
+ const userOptions = omitUndefined(user && typeof user === 'object' ? user : {});
80
+ return { ...defaults, ...presetOptions, ...userOptions };
61
81
  }
62
82
 
63
- /**
64
- * Merge defaults < preset < user. Unknown user keys are preserved so the
65
- * component API can grow (new props, cssVars, callbacks) without a breaking
66
- * change.
67
- */
68
- function normalizeOptions(defaults, preset, user) {
69
- // undefined means "not provided" (e.g. Vue $props with unset props):
70
- // drop those keys before merging so defaults/preset values survive.
71
- const omitUndefined = (source) => {
72
- const result = {};
73
- for (const key of Object.keys(source)) {
74
- if (source[key] !== undefined) result[key] = source[key];
75
- }
76
- return result;
77
- };
78
- const presetOptions = omitUndefined(preset && typeof preset === 'object' ? preset : {});
79
- const userOptions = omitUndefined(user && typeof user === 'object' ? user : {});
80
- return { ...defaults, ...presetOptions, ...userOptions };
81
- }
82
-
83
- /**
84
- * 公共色板:NC-01~NC-06 的四色组(底色 / 主色 / 辅色 / 高光色)。
85
- * Capsule 预置与 dlc-color 等组件共用,新增色板只改这里。
86
- */
87
- const PALETTES = {
88
- original: ['#FFF3EA', '#F5B27A', '#F67BC6', '#A978E8'],
89
- ocean: ['#EAF6FF', '#8FD0FF', '#3B87F6', '#6B58E9'],
90
- klein: ['#EDF2FF', '#2F58D5', '#1B2040', '#E07A43'],
91
- ultraviolet: ['#F2EEFF', '#B99AF1', '#8F74DB', '#D7D85C'],
92
- chrome: ['#F5F6F8', '#B9C0CC', '#7F8793', '#4A4F59'],
93
- plus: ['#FFF0E6', '#F6C26B', '#F98A64', '#E86D74']
83
+ /**
84
+ * 公共色板:NC-01~NC-06 的四色组(底色 / 主色 / 辅色 / 高光色)。
85
+ * Capsule 预置与 dlc-color 等组件共用,新增色板只改这里。
86
+ */
87
+ const PALETTES = {
88
+ original: ['#FFF3EA', '#F5B27A', '#F67BC6', '#A978E8'],
89
+ ocean: ['#EAF6FF', '#8FD0FF', '#3B87F6', '#6B58E9'],
90
+ klein: ['#EDF2FF', '#2F58D5', '#1B2040', '#E07A43'],
91
+ ultraviolet: ['#F2EEFF', '#B99AF1', '#8F74DB', '#D7D85C'],
92
+ chrome: ['#F5F6F8', '#B9C0CC', '#7F8793', '#4A4F59'],
93
+ plus: ['#FFF0E6', '#F6C26B', '#F98A64', '#E86D74']
94
94
  };
95
95
 
96
- /**
97
- * Capsule 预置:仅星云材质 NC-01~NC-06(NC-07~09 aurora 已移除)。
98
- * 颜色引用公共色板,seed/speed 决定形态与流速。
99
- */
96
+ /**
97
+ * Capsule 预置:仅星云材质 NC-01~NC-06(NC-07~09 aurora 已移除)。
98
+ * 颜色引用公共色板,seed/speed 决定形态与流速。
99
+ */
100
100
  const CAPSULE_PRESETS = [
101
101
  { id: 'original', code: 'NC-01', name: '初光', group: 'warm', seed: 1.7, speed: 0.5, colors: [...PALETTES.original] },
102
102
  { id: 'ocean', code: 'NC-02', name: '沧溟', group: 'cold', seed: 8.2, speed: 0.48, colors: [...PALETTES.ocean] },
@@ -126,11 +126,11 @@ function getPreset(kind, ref) {
126
126
  return found;
127
127
  }
128
128
 
129
- const DEFAULTS = {
130
- capsule: {
131
- quality: 'auto',
132
- renderer: 'auto',
133
- fps: 60,
129
+ const DEFAULTS = {
130
+ capsule: {
131
+ quality: 'auto',
132
+ renderer: 'auto',
133
+ fps: 60,
134
134
  respectReducedMotion: true}};
135
135
 
136
136
  /**
@@ -349,524 +349,524 @@ function hexToRgb01(color) {
349
349
  ];
350
350
  }
351
351
 
352
- const VERTEX_SHADER = `#version 300 es
353
- in vec2 a_position;
354
- out vec2 v_uv;
355
- void main() {
356
- v_uv = a_position * 0.5 + 0.5;
357
- gl_Position = vec4(a_position, 0.0, 1.0);
358
- }`;
359
-
360
- const FRAGMENT_SHADER = `#version 300 es
361
- precision highp float;
362
-
363
- in vec2 v_uv;
364
- out vec4 outColor;
365
-
366
- uniform vec2 u_resolution;
367
- uniform float u_time;
368
- uniform float u_seed;
369
- uniform float u_motion;
370
- uniform vec2 u_pointer;
371
- uniform vec3 u_colorA;
372
- uniform vec3 u_colorB;
373
- uniform vec3 u_colorC;
374
- uniform vec3 u_colorD;
375
-
376
- float hash21(vec2 p) {
377
- p = fract(p * vec2(123.34, 456.21));
378
- p += dot(p, p + 45.32 + u_seed);
379
- return fract(p.x * p.y);
380
- }
381
-
382
- float noise(vec2 p) {
383
- vec2 i = floor(p);
384
- vec2 f = fract(p);
385
- f = f * f * (3.0 - 2.0 * f);
386
- float a = hash21(i);
387
- float b = hash21(i + vec2(1.0, 0.0));
388
- float c = hash21(i + vec2(0.0, 1.0));
389
- float d = hash21(i + vec2(1.0, 1.0));
390
- return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
391
- }
392
-
393
- float fbm(vec2 p) {
394
- float value = 0.0;
395
- float amplitude = 0.52;
396
- mat2 rotation = mat2(0.80, 0.60, -0.60, 0.80);
397
- for (int i = 0; i < 6; i++) {
398
- value += amplitude * noise(p);
399
- p = rotation * p * 2.03 + 17.7;
400
- amplitude *= 0.5;
401
- }
402
- return value;
403
- }
404
-
405
- float gaussian(float value, float center, float width) {
406
- return exp(-pow(value - center, 2.0) / max(width, 0.0001));
407
- }
408
-
409
- vec3 palette(float t) {
410
- t = clamp(t, 0.0, 1.0);
411
- vec3 shadow = mix(u_colorA, u_colorB, smoothstep(0.06, 0.62, t));
412
- vec3 body = mix(u_colorB, u_colorC, smoothstep(0.30, 0.82, t));
413
- vec3 highlight = mix(u_colorC, u_colorD, smoothstep(0.74, 1.0, t));
414
- vec3 restrained = mix(shadow, body, smoothstep(0.26, 0.72, t));
415
- return mix(restrained, highlight, smoothstep(0.78, 0.97, t));
416
- }
417
-
418
- vec3 renderNebula(vec2 uv, vec2 p, vec2 pointer, float distanceToPointer, float t) {
419
- vec2 delta = p - pointer;
420
- float influence = exp(-distanceToPointer * 4.6) * u_motion;
421
- float angle = influence * 1.7;
422
- mat2 swirl = mat2(cos(angle), -sin(angle), sin(angle), cos(angle));
423
- p = pointer + swirl * delta;
424
- p += normalize(delta + 0.0001) * influence * 0.08;
425
-
426
- vec2 drift = vec2(t * 0.22, -t * 0.13);
427
- vec2 q = vec2(
428
- fbm(p * 1.35 + drift + u_seed),
429
- fbm(p * 1.35 + vec2(5.2, 1.3) - drift * 0.85)
430
- );
431
- vec2 r = vec2(
432
- fbm(p * 2.0 + 3.6 * q + vec2(1.7, 9.2) + t * 0.10),
433
- fbm(p * 2.0 + 3.0 * q + vec2(8.3, 2.8) - t * 0.085)
434
- );
435
-
436
- float cloud = fbm(p * 1.7 + 4.2 * r);
437
- float veins = fbm(p * 4.0 - 2.0 * q + t * 0.065);
438
- float nebula = smoothstep(0.18, 0.91, cloud * 0.9 + veins * 0.22);
439
-
440
- vec3 color = palette(nebula);
441
- color += u_colorD * pow(max(cloud - 0.63, 0.0), 2.0) * 1.05;
442
- color *= 0.78 + 0.34 * smoothstep(0.15, 0.9, veins);
443
-
444
- vec2 starGrid = floor((uv + vec2(u_seed * 0.013, 0.0)) * vec2(132.0, 58.0));
445
- vec2 starCell = fract(uv * vec2(132.0, 58.0)) - 0.5;
446
- float starRandom = hash21(starGrid);
447
- float starShape = smoothstep(0.075, 0.0, length(starCell));
448
- float starMask = step(0.989, starRandom) * starShape;
449
- float twinkle = 0.35 + 0.65 * sin(t * (1.0 + starRandom * 2.4) + starRandom * 40.0) * 0.5 + 0.5;
450
- color += starMask * twinkle * mix(u_colorC, u_colorD, starRandom) * 1.05;
451
-
452
- float pointerGlow = exp(-distanceToPointer * 7.0) * u_motion;
453
- color += u_colorD * pointerGlow * 0.28;
454
- return color;
455
- }
456
-
457
- void main() {
458
- vec2 uv = v_uv;
459
- vec2 p = uv - 0.5;
460
- p.x *= u_resolution.x / max(u_resolution.y, 1.0);
461
-
462
- vec2 pointer = u_pointer - 0.5;
463
- pointer.x *= u_resolution.x / max(u_resolution.y, 1.0);
464
- float distanceToPointer = length(p - pointer);
465
-
466
- vec3 color = renderNebula(uv, p, pointer, distanceToPointer, u_time);
467
- float vignette = smoothstep(0.94, 0.18, length((uv - 0.5) * vec2(1.0, 1.35)));
468
- color *= 0.70 + vignette * 0.42;
469
- color = pow(max(color, vec3(0.0)), vec3(0.88));
470
-
471
- outColor = vec4(color, 1.0);
472
- }`;
473
-
474
- function compileShader(gl, type, source) {
475
- const shader = gl.createShader(type);
476
- gl.shaderSource(shader, source);
477
- gl.compileShader(shader);
478
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
479
- const message = gl.getShaderInfoLog(shader) || 'Unknown shader compile error';
480
- gl.deleteShader(shader);
481
- throw new Error(message);
482
- }
483
- return shader;
484
- }
485
-
486
- function createProgram(gl) {
487
- const vertex = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
488
- const fragment = compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER);
489
- const program = gl.createProgram();
490
- gl.attachShader(program, vertex);
491
- gl.attachShader(program, fragment);
492
- gl.linkProgram(program);
493
- gl.deleteShader(vertex);
494
- gl.deleteShader(fragment);
495
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
496
- const message = gl.getProgramInfoLog(program) || 'Unknown program link error';
497
- gl.deleteProgram(program);
498
- throw new Error(message);
499
- }
500
- return program;
501
- }
502
-
503
- class CosmicRenderer {
504
- constructor(canvas, preset, options = {}) {
505
- this.canvas = canvas;
506
- this.preset = { ...preset };
507
- this.options = { dprCap: 1.75, mouseColor: true, ...options };
508
- this.gl = canvas.getContext('webgl2', {
509
- alpha: false,
510
- antialias: false,
511
- depth: false,
512
- powerPreference: this.options.powerPreference || 'high-performance',
513
- preserveDrawingBuffer: false
514
- });
515
- if (!this.gl) throw new Error('WebGL2 is not available');
516
-
517
- this.program = createProgram(this.gl);
518
- this.locations = this.#getLocations();
519
- this.pointer = [0.72, 0.45];
520
- this.pointerTarget = [...this.pointer];
521
- this.motion = 0;
522
- this.motionTarget = 0;
523
- this.timeOffset = preset.seed * 0.73;
524
- this.colors = preset.colors.map(hexToRgb01);
525
- this.visible = true;
526
- this.disposed = false;
527
-
528
- this.#setupGeometry();
529
- this.#bindEvents();
530
- this.#bindContextEvents();
531
- this.resize();
532
- }
533
-
534
- #getLocations() {
535
- const gl = this.gl;
536
- const uniform = (name) => gl.getUniformLocation(this.program, name);
537
- return {
538
- position: gl.getAttribLocation(this.program, 'a_position'),
539
- resolution: uniform('u_resolution'),
540
- time: uniform('u_time'),
541
- seed: uniform('u_seed'),
542
- motion: uniform('u_motion'),
543
- pointer: uniform('u_pointer'),
544
- colorA: uniform('u_colorA'),
545
- colorB: uniform('u_colorB'),
546
- colorC: uniform('u_colorC'),
547
- colorD: uniform('u_colorD')
548
- };
549
- }
550
-
551
- #setupGeometry() {
552
- const gl = this.gl;
553
- const vertices = new Float32Array([-1, -1, 3, -1, -1, 3]);
554
- this.buffer = gl.createBuffer();
555
- gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
556
- gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
557
- }
558
-
559
- #bindEvents() {
560
- if (this.options.mouseColor === false) return;
561
- this.eventTarget = this.options.eventTarget || this.canvas.parentElement || this.canvas;
562
- this.onPointerMove = (event) => {
563
- const rect = this.canvas.getBoundingClientRect();
564
- this.pointerTarget[0] = (event.clientX - rect.left) / Math.max(rect.width, 1);
565
- this.pointerTarget[1] = 1 - (event.clientY - rect.top) / Math.max(rect.height, 1);
566
- this.motionTarget = 1;
567
- };
568
- this.onPointerLeave = () => { this.motionTarget = 0; };
569
- this.eventTarget.addEventListener('pointermove', this.onPointerMove, { passive: true });
570
- this.eventTarget.addEventListener('pointerdown', this.onPointerMove, { passive: true });
571
- this.eventTarget.addEventListener('pointerleave', this.onPointerLeave, { passive: true });
572
- }
573
-
574
- #bindContextEvents() {
575
- this.onContextLost = (event) => {
576
- event.preventDefault();
577
- if (this.disposed) return;
578
- this.visible = false;
579
- if (typeof this.options.onContextLost === 'function') this.options.onContextLost(event);
580
- };
581
- this.onContextRestored = () => {
582
- if (this.disposed) return;
583
- this.program = createProgram(this.gl);
584
- this.locations = this.#getLocations();
585
- this.#setupGeometry();
586
- this.visible = true;
587
- this.resize();
588
- if (typeof this.options.onContextRestored === 'function') this.options.onContextRestored();
589
- };
590
- this.canvas.addEventListener('webglcontextlost', this.onContextLost, false);
591
- this.canvas.addEventListener('webglcontextrestored', this.onContextRestored, false);
592
- }
593
-
594
- setPreset(preset) {
595
- this.preset = { ...preset };
596
- this.colors = preset.colors.map(hexToRgb01);
597
- this.timeOffset = preset.seed * 0.73;
598
- }
599
-
600
- setDprCap(cap) {
601
- this.options.dprCap = cap;
602
- this.resize();
603
- }
604
-
605
- setMouseColor(enabled) {
606
- this.options.mouseColor = enabled !== false;
607
- if (this.options.mouseColor) {
608
- if (this.onPointerMove) return this;
609
- this.#bindEvents();
610
- return this;
611
- }
612
- if (this.onPointerMove) {
613
- const target = this.eventTarget;
614
- target.removeEventListener('pointermove', this.onPointerMove);
615
- target.removeEventListener('pointerdown', this.onPointerMove);
616
- target.removeEventListener('pointerleave', this.onPointerLeave);
617
- this.onPointerMove = null;
618
- this.onPointerLeave = null;
619
- }
620
- this.motionTarget = 0;
621
- return this;
622
- }
623
-
624
- randomize() {
625
- this.preset.seed = Math.random() * 100;
626
- this.timeOffset = Math.random() * 40;
627
- }
628
-
629
- resize() {
630
- const dpr = Math.min(window.devicePixelRatio || 1, this.options.dprCap);
631
- const rect = this.canvas.getBoundingClientRect();
632
- const width = Math.max(2, Math.round(rect.width * dpr));
633
- const height = Math.max(2, Math.round(rect.height * dpr));
634
- if (this.canvas.width !== width || this.canvas.height !== height) {
635
- this.canvas.width = width;
636
- this.canvas.height = height;
637
- }
638
- this.gl.viewport(0, 0, width, height);
639
- }
640
-
641
- draw(elapsedSeconds, paused = false) {
642
- if (this.disposed || !this.visible) return;
643
- const gl = this.gl;
644
- this.pointer[0] += (this.pointerTarget[0] - this.pointer[0]) * 0.08;
645
- this.pointer[1] += (this.pointerTarget[1] - this.pointer[1]) * 0.08;
646
- this.motion += (this.motionTarget - this.motion) * 0.07;
647
-
648
- gl.useProgram(this.program);
649
- gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
650
- gl.enableVertexAttribArray(this.locations.position);
651
- gl.vertexAttribPointer(this.locations.position, 2, gl.FLOAT, false, 0, 0);
652
-
653
- gl.uniform2f(this.locations.resolution, this.canvas.width, this.canvas.height);
654
- gl.uniform1f(this.locations.time, this.timeOffset + (paused ? 0 : elapsedSeconds * this.preset.speed));
655
- gl.uniform1f(this.locations.seed, this.preset.seed);
656
- gl.uniform1f(this.locations.motion, this.motion);
657
- gl.uniform2f(this.locations.pointer, this.pointer[0], this.pointer[1]);
658
- gl.uniform3fv(this.locations.colorA, this.colors[0]);
659
- gl.uniform3fv(this.locations.colorB, this.colors[1]);
660
- gl.uniform3fv(this.locations.colorC, this.colors[2]);
661
- gl.uniform3fv(this.locations.colorD, this.colors[3]);
662
- gl.drawArrays(gl.TRIANGLES, 0, 3);
663
- }
664
-
665
- dispose() {
666
- this.disposed = true;
667
- const target = this.eventTarget || this.canvas;
668
- target.removeEventListener('pointermove', this.onPointerMove);
669
- target.removeEventListener('pointerdown', this.onPointerMove);
670
- target.removeEventListener('pointerleave', this.onPointerLeave);
671
- this.canvas.removeEventListener('webglcontextlost', this.onContextLost, false);
672
- this.canvas.removeEventListener('webglcontextrestored', this.onContextRestored, false);
673
- this.gl.deleteBuffer(this.buffer);
674
- this.gl.deleteProgram(this.program);
675
- const lose = this.gl.getExtension('WEBGL_lose_context');
676
- if (lose) lose.loseContext();
677
- }
678
- }
679
-
680
- function rgb(color, alpha = 1) {
681
- const [r, g, b] = hexToRgb01(color).map((value) => Math.round(value * 255));
682
- return `rgba(${r}, ${g}, ${b}, ${alpha})`;
683
- }
684
-
685
- class FallbackRenderer {
686
- constructor(canvas, preset, options = {}) {
687
- this.canvas = canvas;
688
- this.preset = preset;
689
- this.context = canvas.getContext('2d');
690
- this.visible = true;
691
- this.timePhase = 0;
692
- this.dprCap = options.dprCap || 1.5;
693
- }
694
-
695
- resize() {
696
- const rect = this.canvas.getBoundingClientRect();
697
- const dpr = Math.min(window.devicePixelRatio || 1, this.dprCap);
698
- const width = Math.max(2, Math.round(rect.width * dpr));
699
- const height = Math.max(2, Math.round(rect.height * dpr));
700
- if (this.canvas.width !== width || this.canvas.height !== height) {
701
- this.canvas.width = width;
702
- this.canvas.height = height;
703
- }
704
- }
705
-
706
- drawNebula(time) {
707
- const ctx = this.context;
708
- const { width, height } = this.canvas;
709
- const t = (time + this.timePhase) * (this.preset.speed || 1);
710
- const phase = (this.preset.seed || 0) * 0.7;
711
- const gradient = ctx.createLinearGradient(0, 0, width, height);
712
- gradient.addColorStop(0, this.preset.colors[0]);
713
- gradient.addColorStop(0.38, this.preset.colors[1]);
714
- gradient.addColorStop(0.72, this.preset.colors[2]);
715
- gradient.addColorStop(1, this.preset.colors[3]);
716
- ctx.fillStyle = gradient;
717
- ctx.fillRect(0, 0, width, height);
718
-
719
- ctx.globalCompositeOperation = 'screen';
720
- for (let index = 0; index < 6; index += 1) {
721
- const x = (0.5 + 0.45 * Math.sin(t * 0.32 + index * 1.7 + phase)) * width;
722
- const y = (0.5 + 0.4 * Math.cos(t * 0.25 + index + phase)) * height;
723
- const radius = Math.max(width, height) * (0.08 + (index % 3) * 0.04);
724
- const glow = ctx.createRadialGradient(x, y, 0, x, y, radius);
725
- glow.addColorStop(0, rgb(this.preset.colors[(index + 1) % 4], 0.24));
726
- glow.addColorStop(1, rgb(this.preset.colors[index % 4], 0));
727
- ctx.fillStyle = glow;
728
- ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
729
- }
730
- ctx.globalCompositeOperation = 'source-over';
731
- }
732
-
733
- draw(time) {
734
- if (!this.visible) return;
735
- this.drawNebula(time);
736
- }
737
-
738
- setPreset(preset) {
739
- this.preset = preset;
740
- }
741
-
742
- setDprCap(cap) {
743
- this.dprCap = cap;
744
- this.resize();
745
- }
746
-
747
- randomize() {
748
- if (this.preset) {
749
- this.preset.seed = Math.random() * 100;
750
- this.timePhase = Math.random() * Math.PI * 2;
751
- }
752
- }
753
- setMouseColor() {}
754
- dispose() {}
755
- }
756
-
757
- /**
758
- * Document-level shared rAF scheduler. Every component instance subscribes
759
- * its own frame callback; the whole page runs ONE animation loop (like the
760
- * original demo), which avoids jank from many competing rAF loops.
761
- */
762
- const subscribers = [];
763
- let running = false;
764
- let rafId = 0;
765
- let last = 0;
766
-
767
- function tick(now) {
768
- if (!running) return;
769
- const activeItems = [];
770
- {
771
- for (const item of subscribers.slice()) {
772
- try {
773
- if (!item.isPaused()) activeItems.push(item);
774
- } catch {}
775
- }
776
- }
777
- if (activeItems.length === 0) {
778
- running = false;
779
- rafId = 0;
780
- last = 0;
781
- return;
782
- }
783
- const delta = last ? Math.min((now - last) / 1000, 0.05) : 0;
784
- last = now;
785
- // Schedule the next frame BEFORE running callbacks so one throwing
786
- // subscriber can never kill the whole animation loop.
787
- rafId = requestAnimationFrame(tick);
788
- for (const item of activeItems) {
789
- try {
790
- item.onFrame(delta, now);
791
- } catch (error) {
792
- console.warn('[dlc-ui] frame error:', error);
793
- }
794
- }
795
- if (subscribers.length === 0) {
796
- cancelAnimationFrame(rafId);
797
- running = false;
798
- rafId = 0;
799
- }
800
- }
801
-
802
- function start() {
803
- if (running) return;
804
- running = true;
805
- last = 0;
806
- rafId = requestAnimationFrame(tick);
352
+ const VERTEX_SHADER = `#version 300 es
353
+ in vec2 a_position;
354
+ out vec2 v_uv;
355
+ void main() {
356
+ v_uv = a_position * 0.5 + 0.5;
357
+ gl_Position = vec4(a_position, 0.0, 1.0);
358
+ }`;
359
+
360
+ const FRAGMENT_SHADER = `#version 300 es
361
+ precision highp float;
362
+
363
+ in vec2 v_uv;
364
+ out vec4 outColor;
365
+
366
+ uniform vec2 u_resolution;
367
+ uniform float u_time;
368
+ uniform float u_seed;
369
+ uniform float u_motion;
370
+ uniform vec2 u_pointer;
371
+ uniform vec3 u_colorA;
372
+ uniform vec3 u_colorB;
373
+ uniform vec3 u_colorC;
374
+ uniform vec3 u_colorD;
375
+
376
+ float hash21(vec2 p) {
377
+ p = fract(p * vec2(123.34, 456.21));
378
+ p += dot(p, p + 45.32 + u_seed);
379
+ return fract(p.x * p.y);
380
+ }
381
+
382
+ float noise(vec2 p) {
383
+ vec2 i = floor(p);
384
+ vec2 f = fract(p);
385
+ f = f * f * (3.0 - 2.0 * f);
386
+ float a = hash21(i);
387
+ float b = hash21(i + vec2(1.0, 0.0));
388
+ float c = hash21(i + vec2(0.0, 1.0));
389
+ float d = hash21(i + vec2(1.0, 1.0));
390
+ return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
391
+ }
392
+
393
+ float fbm(vec2 p) {
394
+ float value = 0.0;
395
+ float amplitude = 0.52;
396
+ mat2 rotation = mat2(0.80, 0.60, -0.60, 0.80);
397
+ for (int i = 0; i < 6; i++) {
398
+ value += amplitude * noise(p);
399
+ p = rotation * p * 2.03 + 17.7;
400
+ amplitude *= 0.5;
401
+ }
402
+ return value;
403
+ }
404
+
405
+ float gaussian(float value, float center, float width) {
406
+ return exp(-pow(value - center, 2.0) / max(width, 0.0001));
407
+ }
408
+
409
+ vec3 palette(float t) {
410
+ t = clamp(t, 0.0, 1.0);
411
+ vec3 shadow = mix(u_colorA, u_colorB, smoothstep(0.06, 0.62, t));
412
+ vec3 body = mix(u_colorB, u_colorC, smoothstep(0.30, 0.82, t));
413
+ vec3 highlight = mix(u_colorC, u_colorD, smoothstep(0.74, 1.0, t));
414
+ vec3 restrained = mix(shadow, body, smoothstep(0.26, 0.72, t));
415
+ return mix(restrained, highlight, smoothstep(0.78, 0.97, t));
416
+ }
417
+
418
+ vec3 renderNebula(vec2 uv, vec2 p, vec2 pointer, float distanceToPointer, float t) {
419
+ vec2 delta = p - pointer;
420
+ float influence = exp(-distanceToPointer * 4.6) * u_motion;
421
+ float angle = influence * 1.7;
422
+ mat2 swirl = mat2(cos(angle), -sin(angle), sin(angle), cos(angle));
423
+ p = pointer + swirl * delta;
424
+ p += normalize(delta + 0.0001) * influence * 0.08;
425
+
426
+ vec2 drift = vec2(t * 0.22, -t * 0.13);
427
+ vec2 q = vec2(
428
+ fbm(p * 1.35 + drift + u_seed),
429
+ fbm(p * 1.35 + vec2(5.2, 1.3) - drift * 0.85)
430
+ );
431
+ vec2 r = vec2(
432
+ fbm(p * 2.0 + 3.6 * q + vec2(1.7, 9.2) + t * 0.10),
433
+ fbm(p * 2.0 + 3.0 * q + vec2(8.3, 2.8) - t * 0.085)
434
+ );
435
+
436
+ float cloud = fbm(p * 1.7 + 4.2 * r);
437
+ float veins = fbm(p * 4.0 - 2.0 * q + t * 0.065);
438
+ float nebula = smoothstep(0.18, 0.91, cloud * 0.9 + veins * 0.22);
439
+
440
+ vec3 color = palette(nebula);
441
+ color += u_colorD * pow(max(cloud - 0.63, 0.0), 2.0) * 1.05;
442
+ color *= 0.78 + 0.34 * smoothstep(0.15, 0.9, veins);
443
+
444
+ vec2 starGrid = floor((uv + vec2(u_seed * 0.013, 0.0)) * vec2(132.0, 58.0));
445
+ vec2 starCell = fract(uv * vec2(132.0, 58.0)) - 0.5;
446
+ float starRandom = hash21(starGrid);
447
+ float starShape = smoothstep(0.075, 0.0, length(starCell));
448
+ float starMask = step(0.989, starRandom) * starShape;
449
+ float twinkle = 0.35 + 0.65 * sin(t * (1.0 + starRandom * 2.4) + starRandom * 40.0) * 0.5 + 0.5;
450
+ color += starMask * twinkle * mix(u_colorC, u_colorD, starRandom) * 1.05;
451
+
452
+ float pointerGlow = exp(-distanceToPointer * 7.0) * u_motion;
453
+ color += u_colorD * pointerGlow * 0.28;
454
+ return color;
455
+ }
456
+
457
+ void main() {
458
+ vec2 uv = v_uv;
459
+ vec2 p = uv - 0.5;
460
+ p.x *= u_resolution.x / max(u_resolution.y, 1.0);
461
+
462
+ vec2 pointer = u_pointer - 0.5;
463
+ pointer.x *= u_resolution.x / max(u_resolution.y, 1.0);
464
+ float distanceToPointer = length(p - pointer);
465
+
466
+ vec3 color = renderNebula(uv, p, pointer, distanceToPointer, u_time);
467
+ float vignette = smoothstep(0.94, 0.18, length((uv - 0.5) * vec2(1.0, 1.35)));
468
+ color *= 0.70 + vignette * 0.42;
469
+ color = pow(max(color, vec3(0.0)), vec3(0.88));
470
+
471
+ outColor = vec4(color, 1.0);
472
+ }`;
473
+
474
+ function compileShader(gl, type, source) {
475
+ const shader = gl.createShader(type);
476
+ gl.shaderSource(shader, source);
477
+ gl.compileShader(shader);
478
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
479
+ const message = gl.getShaderInfoLog(shader) || 'Unknown shader compile error';
480
+ gl.deleteShader(shader);
481
+ throw new Error(message);
482
+ }
483
+ return shader;
484
+ }
485
+
486
+ function createProgram(gl) {
487
+ const vertex = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
488
+ const fragment = compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER);
489
+ const program = gl.createProgram();
490
+ gl.attachShader(program, vertex);
491
+ gl.attachShader(program, fragment);
492
+ gl.linkProgram(program);
493
+ gl.deleteShader(vertex);
494
+ gl.deleteShader(fragment);
495
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
496
+ const message = gl.getProgramInfoLog(program) || 'Unknown program link error';
497
+ gl.deleteProgram(program);
498
+ throw new Error(message);
499
+ }
500
+ return program;
501
+ }
502
+
503
+ class CosmicRenderer {
504
+ constructor(canvas, preset, options = {}) {
505
+ this.canvas = canvas;
506
+ this.preset = { ...preset };
507
+ this.options = { dprCap: 1.75, mouseColor: true, ...options };
508
+ this.gl = canvas.getContext('webgl2', {
509
+ alpha: false,
510
+ antialias: false,
511
+ depth: false,
512
+ powerPreference: this.options.powerPreference || 'high-performance',
513
+ preserveDrawingBuffer: false
514
+ });
515
+ if (!this.gl) throw new Error('WebGL2 is not available');
516
+
517
+ this.program = createProgram(this.gl);
518
+ this.locations = this.#getLocations();
519
+ this.pointer = [0.72, 0.45];
520
+ this.pointerTarget = [...this.pointer];
521
+ this.motion = 0;
522
+ this.motionTarget = 0;
523
+ this.timeOffset = preset.seed * 0.73;
524
+ this.colors = preset.colors.map(hexToRgb01);
525
+ this.visible = true;
526
+ this.disposed = false;
527
+
528
+ this.#setupGeometry();
529
+ this.#bindEvents();
530
+ this.#bindContextEvents();
531
+ this.resize();
532
+ }
533
+
534
+ #getLocations() {
535
+ const gl = this.gl;
536
+ const uniform = (name) => gl.getUniformLocation(this.program, name);
537
+ return {
538
+ position: gl.getAttribLocation(this.program, 'a_position'),
539
+ resolution: uniform('u_resolution'),
540
+ time: uniform('u_time'),
541
+ seed: uniform('u_seed'),
542
+ motion: uniform('u_motion'),
543
+ pointer: uniform('u_pointer'),
544
+ colorA: uniform('u_colorA'),
545
+ colorB: uniform('u_colorB'),
546
+ colorC: uniform('u_colorC'),
547
+ colorD: uniform('u_colorD')
548
+ };
549
+ }
550
+
551
+ #setupGeometry() {
552
+ const gl = this.gl;
553
+ const vertices = new Float32Array([-1, -1, 3, -1, -1, 3]);
554
+ this.buffer = gl.createBuffer();
555
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
556
+ gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
557
+ }
558
+
559
+ #bindEvents() {
560
+ if (this.options.mouseColor === false) return;
561
+ this.eventTarget = this.options.eventTarget || this.canvas.parentElement || this.canvas;
562
+ this.onPointerMove = (event) => {
563
+ const rect = this.canvas.getBoundingClientRect();
564
+ this.pointerTarget[0] = (event.clientX - rect.left) / Math.max(rect.width, 1);
565
+ this.pointerTarget[1] = 1 - (event.clientY - rect.top) / Math.max(rect.height, 1);
566
+ this.motionTarget = 1;
567
+ };
568
+ this.onPointerLeave = () => { this.motionTarget = 0; };
569
+ this.eventTarget.addEventListener('pointermove', this.onPointerMove, { passive: true });
570
+ this.eventTarget.addEventListener('pointerdown', this.onPointerMove, { passive: true });
571
+ this.eventTarget.addEventListener('pointerleave', this.onPointerLeave, { passive: true });
572
+ }
573
+
574
+ #bindContextEvents() {
575
+ this.onContextLost = (event) => {
576
+ event.preventDefault();
577
+ if (this.disposed) return;
578
+ this.visible = false;
579
+ if (typeof this.options.onContextLost === 'function') this.options.onContextLost(event);
580
+ };
581
+ this.onContextRestored = () => {
582
+ if (this.disposed) return;
583
+ this.program = createProgram(this.gl);
584
+ this.locations = this.#getLocations();
585
+ this.#setupGeometry();
586
+ this.visible = true;
587
+ this.resize();
588
+ if (typeof this.options.onContextRestored === 'function') this.options.onContextRestored();
589
+ };
590
+ this.canvas.addEventListener('webglcontextlost', this.onContextLost, false);
591
+ this.canvas.addEventListener('webglcontextrestored', this.onContextRestored, false);
592
+ }
593
+
594
+ setPreset(preset) {
595
+ this.preset = { ...preset };
596
+ this.colors = preset.colors.map(hexToRgb01);
597
+ this.timeOffset = preset.seed * 0.73;
598
+ }
599
+
600
+ setDprCap(cap) {
601
+ this.options.dprCap = cap;
602
+ this.resize();
603
+ }
604
+
605
+ setMouseColor(enabled) {
606
+ this.options.mouseColor = enabled !== false;
607
+ if (this.options.mouseColor) {
608
+ if (this.onPointerMove) return this;
609
+ this.#bindEvents();
610
+ return this;
611
+ }
612
+ if (this.onPointerMove) {
613
+ const target = this.eventTarget;
614
+ target.removeEventListener('pointermove', this.onPointerMove);
615
+ target.removeEventListener('pointerdown', this.onPointerMove);
616
+ target.removeEventListener('pointerleave', this.onPointerLeave);
617
+ this.onPointerMove = null;
618
+ this.onPointerLeave = null;
619
+ }
620
+ this.motionTarget = 0;
621
+ return this;
622
+ }
623
+
624
+ randomize() {
625
+ this.preset.seed = Math.random() * 100;
626
+ this.timeOffset = Math.random() * 40;
627
+ }
628
+
629
+ resize() {
630
+ const dpr = Math.min(window.devicePixelRatio || 1, this.options.dprCap);
631
+ const rect = this.canvas.getBoundingClientRect();
632
+ const width = Math.max(2, Math.round(rect.width * dpr));
633
+ const height = Math.max(2, Math.round(rect.height * dpr));
634
+ if (this.canvas.width !== width || this.canvas.height !== height) {
635
+ this.canvas.width = width;
636
+ this.canvas.height = height;
637
+ }
638
+ this.gl.viewport(0, 0, width, height);
639
+ }
640
+
641
+ draw(elapsedSeconds, paused = false) {
642
+ if (this.disposed || !this.visible) return;
643
+ const gl = this.gl;
644
+ this.pointer[0] += (this.pointerTarget[0] - this.pointer[0]) * 0.08;
645
+ this.pointer[1] += (this.pointerTarget[1] - this.pointer[1]) * 0.08;
646
+ this.motion += (this.motionTarget - this.motion) * 0.07;
647
+
648
+ gl.useProgram(this.program);
649
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
650
+ gl.enableVertexAttribArray(this.locations.position);
651
+ gl.vertexAttribPointer(this.locations.position, 2, gl.FLOAT, false, 0, 0);
652
+
653
+ gl.uniform2f(this.locations.resolution, this.canvas.width, this.canvas.height);
654
+ gl.uniform1f(this.locations.time, this.timeOffset + (paused ? 0 : elapsedSeconds * this.preset.speed));
655
+ gl.uniform1f(this.locations.seed, this.preset.seed);
656
+ gl.uniform1f(this.locations.motion, this.motion);
657
+ gl.uniform2f(this.locations.pointer, this.pointer[0], this.pointer[1]);
658
+ gl.uniform3fv(this.locations.colorA, this.colors[0]);
659
+ gl.uniform3fv(this.locations.colorB, this.colors[1]);
660
+ gl.uniform3fv(this.locations.colorC, this.colors[2]);
661
+ gl.uniform3fv(this.locations.colorD, this.colors[3]);
662
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
663
+ }
664
+
665
+ dispose() {
666
+ this.disposed = true;
667
+ const target = this.eventTarget || this.canvas;
668
+ target.removeEventListener('pointermove', this.onPointerMove);
669
+ target.removeEventListener('pointerdown', this.onPointerMove);
670
+ target.removeEventListener('pointerleave', this.onPointerLeave);
671
+ this.canvas.removeEventListener('webglcontextlost', this.onContextLost, false);
672
+ this.canvas.removeEventListener('webglcontextrestored', this.onContextRestored, false);
673
+ this.gl.deleteBuffer(this.buffer);
674
+ this.gl.deleteProgram(this.program);
675
+ const lose = this.gl.getExtension('WEBGL_lose_context');
676
+ if (lose) lose.loseContext();
677
+ }
807
678
  }
808
679
 
809
- function wakeScheduler() {
810
- start();
680
+ function rgb(color, alpha = 1) {
681
+ const [r, g, b] = hexToRgb01(color).map((value) => Math.round(value * 255));
682
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
683
+ }
684
+
685
+ class FallbackRenderer {
686
+ constructor(canvas, preset, options = {}) {
687
+ this.canvas = canvas;
688
+ this.preset = preset;
689
+ this.context = canvas.getContext('2d');
690
+ this.visible = true;
691
+ this.timePhase = 0;
692
+ this.dprCap = options.dprCap || 1.5;
693
+ }
694
+
695
+ resize() {
696
+ const rect = this.canvas.getBoundingClientRect();
697
+ const dpr = Math.min(window.devicePixelRatio || 1, this.dprCap);
698
+ const width = Math.max(2, Math.round(rect.width * dpr));
699
+ const height = Math.max(2, Math.round(rect.height * dpr));
700
+ if (this.canvas.width !== width || this.canvas.height !== height) {
701
+ this.canvas.width = width;
702
+ this.canvas.height = height;
703
+ }
704
+ }
705
+
706
+ drawNebula(time) {
707
+ const ctx = this.context;
708
+ const { width, height } = this.canvas;
709
+ const t = (time + this.timePhase) * (this.preset.speed || 1);
710
+ const phase = (this.preset.seed || 0) * 0.7;
711
+ const gradient = ctx.createLinearGradient(0, 0, width, height);
712
+ gradient.addColorStop(0, this.preset.colors[0]);
713
+ gradient.addColorStop(0.38, this.preset.colors[1]);
714
+ gradient.addColorStop(0.72, this.preset.colors[2]);
715
+ gradient.addColorStop(1, this.preset.colors[3]);
716
+ ctx.fillStyle = gradient;
717
+ ctx.fillRect(0, 0, width, height);
718
+
719
+ ctx.globalCompositeOperation = 'screen';
720
+ for (let index = 0; index < 6; index += 1) {
721
+ const x = (0.5 + 0.45 * Math.sin(t * 0.32 + index * 1.7 + phase)) * width;
722
+ const y = (0.5 + 0.4 * Math.cos(t * 0.25 + index + phase)) * height;
723
+ const radius = Math.max(width, height) * (0.08 + (index % 3) * 0.04);
724
+ const glow = ctx.createRadialGradient(x, y, 0, x, y, radius);
725
+ glow.addColorStop(0, rgb(this.preset.colors[(index + 1) % 4], 0.24));
726
+ glow.addColorStop(1, rgb(this.preset.colors[index % 4], 0));
727
+ ctx.fillStyle = glow;
728
+ ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
729
+ }
730
+ ctx.globalCompositeOperation = 'source-over';
731
+ }
732
+
733
+ draw(time) {
734
+ if (!this.visible) return;
735
+ this.drawNebula(time);
736
+ }
737
+
738
+ setPreset(preset) {
739
+ this.preset = preset;
740
+ }
741
+
742
+ setDprCap(cap) {
743
+ this.dprCap = cap;
744
+ this.resize();
745
+ }
746
+
747
+ randomize() {
748
+ if (this.preset) {
749
+ this.preset.seed = Math.random() * 100;
750
+ this.timePhase = Math.random() * Math.PI * 2;
751
+ }
752
+ }
753
+ setMouseColor() {}
754
+ dispose() {}
811
755
  }
812
756
 
813
- function subscribeScheduler(onFrame, isPaused) {
814
- const item = { onFrame, isPaused };
815
- subscribers.push(item);
816
- start();
817
- return () => {
818
- const index = subscribers.indexOf(item);
819
- if (index !== -1) subscribers.splice(index, 1);
820
- if (subscribers.length === 0 && rafId) {
821
- cancelAnimationFrame(rafId);
822
- running = false;
823
- rafId = 0;
824
- }
825
- };
757
+ /**
758
+ * Document-level shared rAF scheduler. Every component instance subscribes
759
+ * its own frame callback; the whole page runs ONE animation loop (like the
760
+ * original demo), which avoids jank from many competing rAF loops.
761
+ */
762
+ const subscribers = [];
763
+ let running = false;
764
+ let rafId = 0;
765
+ let last = 0;
766
+
767
+ function tick(now) {
768
+ if (!running) return;
769
+ const activeItems = [];
770
+ {
771
+ for (const item of subscribers.slice()) {
772
+ try {
773
+ if (!item.isPaused()) activeItems.push(item);
774
+ } catch {}
775
+ }
776
+ }
777
+ if (activeItems.length === 0) {
778
+ running = false;
779
+ rafId = 0;
780
+ last = 0;
781
+ return;
782
+ }
783
+ const delta = last ? Math.min((now - last) / 1000, 0.05) : 0;
784
+ last = now;
785
+ // Schedule the next frame BEFORE running callbacks so one throwing
786
+ // subscriber can never kill the whole animation loop.
787
+ rafId = requestAnimationFrame(tick);
788
+ for (const item of activeItems) {
789
+ try {
790
+ item.onFrame(delta, now);
791
+ } catch (error) {
792
+ console.warn('[dlc-ui] frame error:', error);
793
+ }
794
+ }
795
+ if (subscribers.length === 0) {
796
+ cancelAnimationFrame(rafId);
797
+ running = false;
798
+ rafId = 0;
799
+ }
800
+ }
801
+
802
+ function start() {
803
+ if (running) return;
804
+ running = true;
805
+ last = 0;
806
+ rafId = requestAnimationFrame(tick);
807
+ }
808
+
809
+ function wakeScheduler() {
810
+ start();
811
+ }
812
+
813
+ function subscribeScheduler(onFrame, isPaused) {
814
+ const item = { onFrame, isPaused };
815
+ subscribers.push(item);
816
+ start();
817
+ return () => {
818
+ const index = subscribers.indexOf(item);
819
+ if (index !== -1) subscribers.splice(index, 1);
820
+ if (subscribers.length === 0 && rafId) {
821
+ cancelAnimationFrame(rafId);
822
+ running = false;
823
+ rafId = 0;
824
+ }
825
+ };
826
826
  }
827
827
 
828
- /**
829
- * Gates drawing on "element intersects viewport AND the page tab is visible".
830
- * Falls back to always-visible when IntersectionObserver is unavailable.
831
- */
832
- function createVisibilityGuard(element, onChange = null) {
833
- let intersecting = true;
834
- let pageVisible = typeof document === 'undefined' || !document.hidden;
835
- let disposed = false;
836
- let observer = null;
837
-
838
- if (typeof IntersectionObserver !== 'undefined') {
839
- observer = new IntersectionObserver(
840
- (entries) => {
841
- intersecting = entries.some((entry) => entry.isIntersecting);
842
- if (typeof onChange === 'function') onChange();
843
- },
844
- { rootMargin: '180px' }
845
- );
846
- observer.observe(element);
847
- }
848
-
849
- const onVisibilityChange = () => {
850
- pageVisible = typeof document !== 'undefined' && !document.hidden;
851
- if (typeof onChange === 'function') onChange();
852
- };
853
- if (typeof document !== 'undefined') {
854
- document.addEventListener('visibilitychange', onVisibilityChange);
855
- }
856
-
857
- return {
858
- isVisible() {
859
- return intersecting && pageVisible;
860
- },
861
- dispose() {
862
- if (disposed) return;
863
- disposed = true;
864
- if (observer) observer.disconnect();
865
- if (typeof document !== 'undefined') {
866
- document.removeEventListener('visibilitychange', onVisibilityChange);
867
- }
868
- }
869
- };
828
+ /**
829
+ * Gates drawing on "element intersects viewport AND the page tab is visible".
830
+ * Falls back to always-visible when IntersectionObserver is unavailable.
831
+ */
832
+ function createVisibilityGuard(element, onChange = null) {
833
+ let intersecting = true;
834
+ let pageVisible = typeof document === 'undefined' || !document.hidden;
835
+ let disposed = false;
836
+ let observer = null;
837
+
838
+ if (typeof IntersectionObserver !== 'undefined') {
839
+ observer = new IntersectionObserver(
840
+ (entries) => {
841
+ intersecting = entries.some((entry) => entry.isIntersecting);
842
+ if (typeof onChange === 'function') onChange();
843
+ },
844
+ { rootMargin: '180px' }
845
+ );
846
+ observer.observe(element);
847
+ }
848
+
849
+ const onVisibilityChange = () => {
850
+ pageVisible = typeof document !== 'undefined' && !document.hidden;
851
+ if (typeof onChange === 'function') onChange();
852
+ };
853
+ if (typeof document !== 'undefined') {
854
+ document.addEventListener('visibilitychange', onVisibilityChange);
855
+ }
856
+
857
+ return {
858
+ isVisible() {
859
+ return intersecting && pageVisible;
860
+ },
861
+ dispose() {
862
+ if (disposed) return;
863
+ disposed = true;
864
+ if (observer) observer.disconnect();
865
+ if (typeof document !== 'undefined') {
866
+ document.removeEventListener('visibilitychange', onVisibilityChange);
867
+ }
868
+ }
869
+ };
870
870
  }
871
871
 
872
872
  /**
@@ -885,421 +885,421 @@ function nextTick(fn) {
885
885
  }
886
886
  }
887
887
 
888
- function normalizeFps(value, fallback = 60) {
889
- const fps = Number(value);
890
- if (!Number.isFinite(fps)) return fallback;
891
- return Math.min(60, Math.max(1, fps));
892
- }
893
-
894
- function createFrameGate(initialFps = 60) {
895
- let fps = normalizeFps(initialFps);
896
- let elapsed = 0;
897
- return {
898
- shouldDraw(delta) {
899
- elapsed += delta;
900
- const interval = 1 / fps;
901
- if (elapsed + 0.0001 < interval) return false;
902
- elapsed %= interval;
903
- return true;
904
- },
905
- setFps(value) {
906
- fps = normalizeFps(value, fps);
907
- elapsed = 0;
908
- return fps;
909
- },
910
- getFps() {
911
- return fps;
912
- }
913
- };
914
- }
915
-
916
- function createReducedMotionPreference(enabled, onChange) {
917
- const query = enabled && typeof matchMedia !== 'undefined'
918
- ? matchMedia('(prefers-reduced-motion: reduce)')
919
- : null;
920
- const notify = () => {
921
- if (typeof onChange === 'function') onChange(Boolean(query && query.matches));
922
- };
923
- if (query) {
924
- if (typeof query.addEventListener === 'function') query.addEventListener('change', notify);
925
- else if (typeof query.addListener === 'function') query.addListener(notify);
926
- }
927
- return {
928
- matches() {
929
- return Boolean(query && query.matches);
930
- },
931
- dispose() {
932
- if (!query) return;
933
- if (typeof query.removeEventListener === 'function') query.removeEventListener('change', notify);
934
- else if (typeof query.removeListener === 'function') query.removeListener(notify);
935
- }
936
- };
888
+ function normalizeFps(value, fallback = 60) {
889
+ const fps = Number(value);
890
+ if (!Number.isFinite(fps)) return fallback;
891
+ return Math.min(60, Math.max(1, fps));
892
+ }
893
+
894
+ function createFrameGate(initialFps = 60) {
895
+ let fps = normalizeFps(initialFps);
896
+ let elapsed = 0;
897
+ return {
898
+ shouldDraw(delta) {
899
+ elapsed += delta;
900
+ const interval = 1 / fps;
901
+ if (elapsed + 0.0001 < interval) return false;
902
+ elapsed %= interval;
903
+ return true;
904
+ },
905
+ setFps(value) {
906
+ fps = normalizeFps(value, fps);
907
+ elapsed = 0;
908
+ return fps;
909
+ },
910
+ getFps() {
911
+ return fps;
912
+ }
913
+ };
914
+ }
915
+
916
+ function createReducedMotionPreference(enabled, onChange) {
917
+ const query = enabled && typeof matchMedia !== 'undefined'
918
+ ? matchMedia('(prefers-reduced-motion: reduce)')
919
+ : null;
920
+ const notify = () => {
921
+ if (typeof onChange === 'function') onChange(Boolean(query && query.matches));
922
+ };
923
+ if (query) {
924
+ if (typeof query.addEventListener === 'function') query.addEventListener('change', notify);
925
+ else if (typeof query.addListener === 'function') query.addListener(notify);
926
+ }
927
+ return {
928
+ matches() {
929
+ return Boolean(query && query.matches);
930
+ },
931
+ dispose() {
932
+ if (!query) return;
933
+ if (typeof query.removeEventListener === 'function') query.removeEventListener('change', notify);
934
+ else if (typeof query.removeListener === 'function') query.removeListener(notify);
935
+ }
936
+ };
937
937
  }
938
938
 
939
- function toFiniteNumber(value) {
940
- if (value == null || typeof value === 'boolean') return null;
941
- if (typeof value === 'string' && value.trim() === '') return null;
942
- const number = Number(value);
943
- return Number.isFinite(number) ? number : null;
939
+ function toFiniteNumber(value) {
940
+ if (value == null || typeof value === 'boolean') return null;
941
+ if (typeof value === 'string' && value.trim() === '') return null;
942
+ const number = Number(value);
943
+ return Number.isFinite(number) ? number : null;
944
944
  }
945
945
 
946
- const HOST_STYLES = new WeakMap();
947
-
948
- function acquireHostStyles(host) {
949
- const active = HOST_STYLES.get(host);
950
- if (active) {
951
- active.count += 1;
952
- return;
953
- }
954
- const state = {
955
- count: 1,
956
- position: host.style.position,
957
- isolation: host.style.isolation
958
- };
959
- const computed = getComputedStyle(host);
960
- if (computed.position === 'static' || computed.position === '') host.style.position = 'relative';
961
- host.style.isolation = 'isolate';
962
- HOST_STYLES.set(host, state);
963
- }
964
-
965
- function releaseHostStyles(host) {
966
- const state = HOST_STYLES.get(host);
967
- if (!state) return;
968
- state.count -= 1;
969
- if (state.count > 0) return;
970
- host.style.position = state.position;
971
- host.style.isolation = state.isolation;
972
- HOST_STYLES.delete(host);
973
- }
974
-
975
- /**
976
- * Mount the cosmic (nebula) material as a background layer inside `host`.
977
- *
978
- * The layer is absolutely positioned and defaults to `z-index: -1`, so it
979
- * paints behind the host's in-flow content: text/buttons/images inside the
980
- * host sit on top with zero extra CSS. Host gets `position: relative;
981
- * isolation: isolate` automatically so the layer can never escape its box
982
- * (or break stacking outside it).
983
- *
984
- * Options: preset (literary name), colors, seed, speed, quality,
985
- * renderer, renderScale, powerPreference, fps, paused/static, mouseColor,
986
- * respectReducedMotion, opacity (0-1), fallbackColor (true=preset base
987
- * color, a hex string, or false to disable).
988
- */
989
- function createColorBackground(host, options = {}) {
990
- if (!host || typeof host.appendChild !== 'function') {
991
- throw new Error('createColorBackground: host element is required');
992
- }
993
-
994
- const preset = { ...getPreset('capsule', options.preset ?? '初光') };
995
- const merged = normalizeOptions(
996
- {
997
- quality: DEFAULTS.capsule.quality,
998
- renderer: DEFAULTS.capsule.renderer,
999
- respectReducedMotion: DEFAULTS.capsule.respectReducedMotion,
1000
- mouseColor: true,
1001
- renderScale: 1,
1002
- powerPreference: 'high-performance',
1003
- fps: DEFAULTS.capsule.fps,
1004
- paused: false,
1005
- static: false,
1006
- opacity: 1,
1007
- fallbackColor: true
1008
- },
1009
- preset,
1010
- options
1011
- );
1012
- merged.opacity = Number.isFinite(Number(merged.opacity))
1013
- ? Math.min(1, Math.max(0, Number(merged.opacity)))
1014
- : 1;
1015
- const normalizedColors = Array.isArray(merged.colors) ? merged.colors.map(normalizeColor) : [];
1016
- if (normalizedColors.length === 4 && normalizedColors.every(Boolean)) preset.colors = normalizedColors;
1017
- const initialSeed = toFiniteNumber(merged.seed);
1018
- const initialSpeed = toFiniteNumber(merged.speed);
1019
- if (initialSeed !== null) preset.seed = initialSeed;
1020
- if (initialSpeed !== null) preset.speed = initialSpeed;
1021
- merged.colors = [...preset.colors];
1022
- merged.seed = preset.seed;
1023
- merged.speed = preset.speed;
1024
- const optionColors = Array.isArray(options.colors) ? options.colors.map(normalizeColor) : [];
1025
- let colorOverride = optionColors.length === 4 && optionColors.every(Boolean)
1026
- ? [...optionColors]
1027
- : null;
1028
- let seedOverride = options.seed !== undefined ? toFiniteNumber(options.seed) : null;
1029
- let speedOverride = options.speed !== undefined ? toFiniteNumber(options.speed) : null;
1030
-
1031
- acquireHostStyles(host);
1032
-
1033
- const layer = document.createElement('div');
1034
- layer.className = 'dlc-color-layer';
1035
-
1036
- const syncLayerVars = () => {
1037
- layer.style.setProperty('--dlc-color-opacity', String(merged.opacity));
1038
- const fallback =
1039
- merged.fallbackColor === false || merged.fallbackColor == null
1040
- ? 'transparent'
1041
- : typeof merged.fallbackColor === 'string'
1042
- ? merged.fallbackColor
1043
- : preset.colors[0];
1044
- layer.style.setProperty('--dlc-color-bg', fallback);
1045
- };
1046
- syncLayerVars();
1047
-
1048
- const canvas = document.createElement('canvas');
1049
- canvas.className = 'dlc-color-canvas';
1050
- canvas.setAttribute('aria-hidden', 'true');
1051
- layer.appendChild(canvas);
1052
- host.appendChild(layer);
1053
-
1054
- const emitter = createEmitter();
1055
- let manuallyPaused = merged.paused === true;
1056
- let reducedPaused = false;
1057
- let staticMode = merged.static === true;
1058
- let contextLost = false;
1059
- let disposed = false;
1060
- let renderOnce = () => {};
1061
- const dirty = {
1062
- preset: false,
1063
- seed: false,
1064
- speed: false,
1065
- colors: false,
1066
- opacity: false,
1067
- fallbackColor: false,
1068
- mouseColor: false,
1069
- quality: false,
1070
- renderScale: false,
1071
- paused: false,
1072
- static: false,
1073
- fps: false
1074
- };
1075
-
1076
- let renderer;
1077
- const useWebgl = merged.renderer !== 'canvas2d';
1078
- if (useWebgl) {
1079
- try {
1080
- renderer = new CosmicRenderer(canvas, merged, {
1081
- dprCap: effectiveDprCap(merged.quality, merged.renderScale),
1082
- mouseColor: merged.mouseColor !== false,
1083
- eventTarget: host,
1084
- powerPreference: merged.powerPreference,
1085
- onContextLost: () => {
1086
- contextLost = true;
1087
- emitter.emit('contextlost', {});
1088
- },
1089
- onContextRestored: () => {
1090
- contextLost = false;
1091
- emitter.emit('contextrestored', {});
1092
- renderOnce();
1093
- wakeScheduler();
1094
- }
1095
- });
1096
- } catch (error) {
1097
- renderer = new FallbackRenderer(canvas, merged, {
1098
- dprCap: effectiveDprCap(merged.quality, merged.renderScale)
1099
- });
1100
- nextTick(() => {
1101
- if (disposed) return;
1102
- emitter.emit('error', {
1103
- message: String(error && error.message ? error.message : error)
1104
- });
1105
- });
1106
- }
1107
- } else {
1108
- renderer = new FallbackRenderer(canvas, merged, {
1109
- dprCap: effectiveDprCap(merged.quality, merged.renderScale)
1110
- });
1111
- }
1112
- renderer.resize();
1113
-
1114
- let animationTime = 0;
1115
- const frameGate = createFrameGate(merged.fps);
1116
- renderOnce = () => renderer.draw(animationTime);
1117
-
1118
- const resize = () => {
1119
- renderer.resize();
1120
- if (manuallyPaused || reducedPaused || staticMode) renderOnce();
1121
- };
1122
- const resizeObserver =
1123
- typeof ResizeObserver !== 'undefined'
1124
- ? new ResizeObserver(resize)
1125
- : null;
1126
- if (resizeObserver) resizeObserver.observe(host);
1127
- else window.addEventListener('resize', resize);
1128
-
1129
- const visibility = createVisibilityGuard(layer, wakeScheduler);
1130
- const motionPreference = createReducedMotionPreference(
1131
- merged.respectReducedMotion,
1132
- (matches) => {
1133
- reducedPaused = matches;
1134
- if (matches) renderOnce();
1135
- else wakeScheduler();
1136
- }
1137
- );
1138
- reducedPaused = motionPreference.matches();
1139
- const isMotionPaused = () => manuallyPaused || reducedPaused || staticMode || contextLost;
1140
-
1141
- renderOnce();
1142
- const unsubscribe = subscribeScheduler(
1143
- (delta) => {
1144
- animationTime += delta;
1145
- if (frameGate.shouldDraw(delta)) renderer.draw(animationTime);
1146
- },
1147
- () => isMotionPaused() || !visibility.isVisible()
1148
- );
1149
-
1150
- nextTick(() => {
1151
- if (disposed) return;
1152
- emitter.emit('ready', { preset: { ...preset } });
1153
- });
1154
-
1155
- return {
1156
- element: host,
1157
- layer,
1158
- canvas,
1159
- preset,
1160
- on: emitter.on,
1161
- off: emitter.off,
1162
- setPreset(ref) {
1163
- const next = getPreset('capsule', ref);
1164
- dirty.preset = true;
1165
- Object.assign(preset, next);
1166
- if (colorOverride) preset.colors = [...colorOverride];
1167
- if (seedOverride !== null) preset.seed = seedOverride;
1168
- if (speedOverride !== null) preset.speed = speedOverride;
1169
- const nextColors = preset.colors.map(normalizeColor);
1170
- if (nextColors.every(Boolean)) preset.colors = nextColors;
1171
- renderer.setPreset({ ...preset });
1172
- renderer.resize();
1173
- syncLayerVars();
1174
- if (isMotionPaused()) renderOnce();
1175
- emitter.emit('presetchange', { preset: { ...preset } });
1176
- return this;
1177
- },
1178
- setColors(colors) {
1179
- const next = Array.isArray(colors) ? colors.map(normalizeColor) : [];
1180
- if (next.length !== 4 || next.some((color) => !color)) return this;
1181
- dirty.colors = true;
1182
- colorOverride = [...next];
1183
- preset.colors = next;
1184
- renderer.setPreset({ ...preset, colors: next });
1185
- syncLayerVars();
1186
- if (isMotionPaused()) renderOnce();
1187
- return this;
1188
- },
1189
- setSeed(seed) {
1190
- const value = toFiniteNumber(seed);
1191
- if (value === null) return this;
1192
- dirty.seed = true;
1193
- seedOverride = value;
1194
- preset.seed = value;
1195
- renderer.setPreset({ ...preset });
1196
- if (isMotionPaused()) renderOnce();
1197
- return this;
1198
- },
1199
- setSpeed(speed) {
1200
- const value = toFiniteNumber(speed);
1201
- if (value === null) return this;
1202
- dirty.speed = true;
1203
- speedOverride = value;
1204
- preset.speed = value;
1205
- renderer.setPreset({ ...preset });
1206
- if (isMotionPaused()) renderOnce();
1207
- return this;
1208
- },
1209
- setFallbackColor(value) {
1210
- dirty.fallbackColor = true;
1211
- merged.fallbackColor = value;
1212
- syncLayerVars();
1213
- return this;
1214
- },
1215
- setMouseColor(value) {
1216
- dirty.mouseColor = true;
1217
- merged.mouseColor = value !== false;
1218
- if (typeof renderer.setMouseColor === 'function') renderer.setMouseColor(merged.mouseColor);
1219
- return this;
1220
- },
1221
- setQuality(quality) {
1222
- dirty.quality = true;
1223
- merged.quality = quality;
1224
- if (typeof renderer.setDprCap === 'function') {
1225
- renderer.setDprCap(effectiveDprCap(quality, merged.renderScale));
1226
- }
1227
- if (isMotionPaused()) renderOnce();
1228
- return this;
1229
- },
1230
- setRenderScale(renderScale) {
1231
- const value = Number(renderScale);
1232
- if (!Number.isFinite(value)) return this;
1233
- dirty.renderScale = true;
1234
- merged.renderScale = Math.min(1, Math.max(0.25, value));
1235
- if (typeof renderer.setDprCap === 'function') {
1236
- renderer.setDprCap(effectiveDprCap(merged.quality, merged.renderScale));
1237
- }
1238
- if (isMotionPaused()) renderOnce();
1239
- return this;
1240
- },
1241
- setOpacity(value) {
1242
- const opacity = Number(value);
1243
- if (!Number.isFinite(opacity)) return this;
1244
- dirty.opacity = true;
1245
- merged.opacity = Math.min(1, Math.max(0, opacity));
1246
- layer.style.setProperty('--dlc-color-opacity', String(merged.opacity));
1247
- return this;
1248
- },
1249
- randomize() {
1250
- this.setSeed(Math.random() * 100);
1251
- return this;
1252
- },
1253
- pause() {
1254
- dirty.paused = true;
1255
- manuallyPaused = true;
1256
- renderOnce();
1257
- return this;
1258
- },
1259
- resume() {
1260
- dirty.paused = true;
1261
- manuallyPaused = false;
1262
- wakeScheduler();
1263
- return this;
1264
- },
1265
- setPaused(value) {
1266
- return value ? this.pause() : this.resume();
1267
- },
1268
- setStatic(value) {
1269
- dirty.static = true;
1270
- staticMode = value === true;
1271
- merged.static = staticMode;
1272
- if (staticMode) renderOnce();
1273
- else wakeScheduler();
1274
- return this;
1275
- },
1276
- setFps(fps) {
1277
- dirty.fps = true;
1278
- merged.fps = frameGate.setFps(fps);
1279
- wakeScheduler();
1280
- return this;
1281
- },
1282
- dispose() {
1283
- disposed = true;
1284
- unsubscribe();
1285
- visibility.dispose();
1286
- motionPreference.dispose();
1287
- if (resizeObserver) resizeObserver.disconnect();
1288
- else window.removeEventListener('resize', resize);
1289
- renderer.dispose();
1290
- layer.remove();
1291
- releaseHostStyles(host);
1292
- },
1293
- get opacity() { return merged.opacity; },
1294
- get fallbackColor() { return merged.fallbackColor; },
1295
- get mouseColor() { return merged.mouseColor; },
1296
- get quality() { return merged.quality; },
1297
- get renderScale() { return merged.renderScale; },
1298
- get paused() { return manuallyPaused; },
1299
- get static() { return staticMode; },
1300
- get fps() { return frameGate.getFps(); },
1301
- dirty
1302
- };
946
+ const HOST_STYLES = new WeakMap();
947
+
948
+ function acquireHostStyles(host) {
949
+ const active = HOST_STYLES.get(host);
950
+ if (active) {
951
+ active.count += 1;
952
+ return;
953
+ }
954
+ const state = {
955
+ count: 1,
956
+ position: host.style.position,
957
+ isolation: host.style.isolation
958
+ };
959
+ const computed = getComputedStyle(host);
960
+ if (computed.position === 'static' || computed.position === '') host.style.position = 'relative';
961
+ host.style.isolation = 'isolate';
962
+ HOST_STYLES.set(host, state);
963
+ }
964
+
965
+ function releaseHostStyles(host) {
966
+ const state = HOST_STYLES.get(host);
967
+ if (!state) return;
968
+ state.count -= 1;
969
+ if (state.count > 0) return;
970
+ host.style.position = state.position;
971
+ host.style.isolation = state.isolation;
972
+ HOST_STYLES.delete(host);
973
+ }
974
+
975
+ /**
976
+ * Mount the cosmic (nebula) material as a background layer inside `host`.
977
+ *
978
+ * The layer is absolutely positioned and defaults to `z-index: -1`, so it
979
+ * paints behind the host's in-flow content: text/buttons/images inside the
980
+ * host sit on top with zero extra CSS. Host gets `position: relative;
981
+ * isolation: isolate` automatically so the layer can never escape its box
982
+ * (or break stacking outside it).
983
+ *
984
+ * Options: preset (literary name), colors, seed, speed, quality,
985
+ * renderer, renderScale, powerPreference, fps, paused/static, mouseColor,
986
+ * respectReducedMotion, opacity (0-1), fallbackColor (true=preset base
987
+ * color, a hex string, or false to disable).
988
+ */
989
+ function createColorBackground(host, options = {}) {
990
+ if (!host || typeof host.appendChild !== 'function') {
991
+ throw new Error('createColorBackground: host element is required');
992
+ }
993
+
994
+ const preset = { ...getPreset('capsule', options.preset ?? '初光') };
995
+ const merged = normalizeOptions(
996
+ {
997
+ quality: DEFAULTS.capsule.quality,
998
+ renderer: DEFAULTS.capsule.renderer,
999
+ respectReducedMotion: DEFAULTS.capsule.respectReducedMotion,
1000
+ mouseColor: true,
1001
+ renderScale: 1,
1002
+ powerPreference: 'high-performance',
1003
+ fps: DEFAULTS.capsule.fps,
1004
+ paused: false,
1005
+ static: false,
1006
+ opacity: 1,
1007
+ fallbackColor: true
1008
+ },
1009
+ preset,
1010
+ options
1011
+ );
1012
+ merged.opacity = Number.isFinite(Number(merged.opacity))
1013
+ ? Math.min(1, Math.max(0, Number(merged.opacity)))
1014
+ : 1;
1015
+ const normalizedColors = Array.isArray(merged.colors) ? merged.colors.map(normalizeColor) : [];
1016
+ if (normalizedColors.length === 4 && normalizedColors.every(Boolean)) preset.colors = normalizedColors;
1017
+ const initialSeed = toFiniteNumber(merged.seed);
1018
+ const initialSpeed = toFiniteNumber(merged.speed);
1019
+ if (initialSeed !== null) preset.seed = initialSeed;
1020
+ if (initialSpeed !== null) preset.speed = initialSpeed;
1021
+ merged.colors = [...preset.colors];
1022
+ merged.seed = preset.seed;
1023
+ merged.speed = preset.speed;
1024
+ const optionColors = Array.isArray(options.colors) ? options.colors.map(normalizeColor) : [];
1025
+ let colorOverride = optionColors.length === 4 && optionColors.every(Boolean)
1026
+ ? [...optionColors]
1027
+ : null;
1028
+ let seedOverride = options.seed !== undefined ? toFiniteNumber(options.seed) : null;
1029
+ let speedOverride = options.speed !== undefined ? toFiniteNumber(options.speed) : null;
1030
+
1031
+ acquireHostStyles(host);
1032
+
1033
+ const layer = document.createElement('div');
1034
+ layer.className = 'dlc-color-layer';
1035
+
1036
+ const syncLayerVars = () => {
1037
+ layer.style.setProperty('--dlc-color-opacity', String(merged.opacity));
1038
+ const fallback =
1039
+ merged.fallbackColor === false || merged.fallbackColor == null
1040
+ ? 'transparent'
1041
+ : typeof merged.fallbackColor === 'string'
1042
+ ? merged.fallbackColor
1043
+ : preset.colors[0];
1044
+ layer.style.setProperty('--dlc-color-bg', fallback);
1045
+ };
1046
+ syncLayerVars();
1047
+
1048
+ const canvas = document.createElement('canvas');
1049
+ canvas.className = 'dlc-color-canvas';
1050
+ canvas.setAttribute('aria-hidden', 'true');
1051
+ layer.appendChild(canvas);
1052
+ host.appendChild(layer);
1053
+
1054
+ const emitter = createEmitter();
1055
+ let manuallyPaused = merged.paused === true;
1056
+ let reducedPaused = false;
1057
+ let staticMode = merged.static === true;
1058
+ let contextLost = false;
1059
+ let disposed = false;
1060
+ let renderOnce = () => {};
1061
+ const dirty = {
1062
+ preset: false,
1063
+ seed: false,
1064
+ speed: false,
1065
+ colors: false,
1066
+ opacity: false,
1067
+ fallbackColor: false,
1068
+ mouseColor: false,
1069
+ quality: false,
1070
+ renderScale: false,
1071
+ paused: false,
1072
+ static: false,
1073
+ fps: false
1074
+ };
1075
+
1076
+ let renderer;
1077
+ const useWebgl = merged.renderer !== 'canvas2d';
1078
+ if (useWebgl) {
1079
+ try {
1080
+ renderer = new CosmicRenderer(canvas, merged, {
1081
+ dprCap: effectiveDprCap(merged.quality, merged.renderScale),
1082
+ mouseColor: merged.mouseColor !== false,
1083
+ eventTarget: host,
1084
+ powerPreference: merged.powerPreference,
1085
+ onContextLost: () => {
1086
+ contextLost = true;
1087
+ emitter.emit('contextlost', {});
1088
+ },
1089
+ onContextRestored: () => {
1090
+ contextLost = false;
1091
+ emitter.emit('contextrestored', {});
1092
+ renderOnce();
1093
+ wakeScheduler();
1094
+ }
1095
+ });
1096
+ } catch (error) {
1097
+ renderer = new FallbackRenderer(canvas, merged, {
1098
+ dprCap: effectiveDprCap(merged.quality, merged.renderScale)
1099
+ });
1100
+ nextTick(() => {
1101
+ if (disposed) return;
1102
+ emitter.emit('error', {
1103
+ message: String(error && error.message ? error.message : error)
1104
+ });
1105
+ });
1106
+ }
1107
+ } else {
1108
+ renderer = new FallbackRenderer(canvas, merged, {
1109
+ dprCap: effectiveDprCap(merged.quality, merged.renderScale)
1110
+ });
1111
+ }
1112
+ renderer.resize();
1113
+
1114
+ let animationTime = 0;
1115
+ const frameGate = createFrameGate(merged.fps);
1116
+ renderOnce = () => renderer.draw(animationTime);
1117
+
1118
+ const resize = () => {
1119
+ renderer.resize();
1120
+ if (manuallyPaused || reducedPaused || staticMode) renderOnce();
1121
+ };
1122
+ const resizeObserver =
1123
+ typeof ResizeObserver !== 'undefined'
1124
+ ? new ResizeObserver(resize)
1125
+ : null;
1126
+ if (resizeObserver) resizeObserver.observe(host);
1127
+ else window.addEventListener('resize', resize);
1128
+
1129
+ const visibility = createVisibilityGuard(layer, wakeScheduler);
1130
+ const motionPreference = createReducedMotionPreference(
1131
+ merged.respectReducedMotion,
1132
+ (matches) => {
1133
+ reducedPaused = matches;
1134
+ if (matches) renderOnce();
1135
+ else wakeScheduler();
1136
+ }
1137
+ );
1138
+ reducedPaused = motionPreference.matches();
1139
+ const isMotionPaused = () => manuallyPaused || reducedPaused || staticMode || contextLost;
1140
+
1141
+ renderOnce();
1142
+ const unsubscribe = subscribeScheduler(
1143
+ (delta) => {
1144
+ animationTime += delta;
1145
+ if (frameGate.shouldDraw(delta)) renderer.draw(animationTime);
1146
+ },
1147
+ () => isMotionPaused() || !visibility.isVisible()
1148
+ );
1149
+
1150
+ nextTick(() => {
1151
+ if (disposed) return;
1152
+ emitter.emit('ready', { preset: { ...preset } });
1153
+ });
1154
+
1155
+ return {
1156
+ element: host,
1157
+ layer,
1158
+ canvas,
1159
+ preset,
1160
+ on: emitter.on,
1161
+ off: emitter.off,
1162
+ setPreset(ref) {
1163
+ const next = getPreset('capsule', ref);
1164
+ dirty.preset = true;
1165
+ Object.assign(preset, next);
1166
+ if (colorOverride) preset.colors = [...colorOverride];
1167
+ if (seedOverride !== null) preset.seed = seedOverride;
1168
+ if (speedOverride !== null) preset.speed = speedOverride;
1169
+ const nextColors = preset.colors.map(normalizeColor);
1170
+ if (nextColors.every(Boolean)) preset.colors = nextColors;
1171
+ renderer.setPreset({ ...preset });
1172
+ renderer.resize();
1173
+ syncLayerVars();
1174
+ if (isMotionPaused()) renderOnce();
1175
+ emitter.emit('presetchange', { preset: { ...preset } });
1176
+ return this;
1177
+ },
1178
+ setColors(colors) {
1179
+ const next = Array.isArray(colors) ? colors.map(normalizeColor) : [];
1180
+ if (next.length !== 4 || next.some((color) => !color)) return this;
1181
+ dirty.colors = true;
1182
+ colorOverride = [...next];
1183
+ preset.colors = next;
1184
+ renderer.setPreset({ ...preset, colors: next });
1185
+ syncLayerVars();
1186
+ if (isMotionPaused()) renderOnce();
1187
+ return this;
1188
+ },
1189
+ setSeed(seed) {
1190
+ const value = toFiniteNumber(seed);
1191
+ if (value === null) return this;
1192
+ dirty.seed = true;
1193
+ seedOverride = value;
1194
+ preset.seed = value;
1195
+ renderer.setPreset({ ...preset });
1196
+ if (isMotionPaused()) renderOnce();
1197
+ return this;
1198
+ },
1199
+ setSpeed(speed) {
1200
+ const value = toFiniteNumber(speed);
1201
+ if (value === null) return this;
1202
+ dirty.speed = true;
1203
+ speedOverride = value;
1204
+ preset.speed = value;
1205
+ renderer.setPreset({ ...preset });
1206
+ if (isMotionPaused()) renderOnce();
1207
+ return this;
1208
+ },
1209
+ setFallbackColor(value) {
1210
+ dirty.fallbackColor = true;
1211
+ merged.fallbackColor = value;
1212
+ syncLayerVars();
1213
+ return this;
1214
+ },
1215
+ setMouseColor(value) {
1216
+ dirty.mouseColor = true;
1217
+ merged.mouseColor = value !== false;
1218
+ if (typeof renderer.setMouseColor === 'function') renderer.setMouseColor(merged.mouseColor);
1219
+ return this;
1220
+ },
1221
+ setQuality(quality) {
1222
+ dirty.quality = true;
1223
+ merged.quality = quality;
1224
+ if (typeof renderer.setDprCap === 'function') {
1225
+ renderer.setDprCap(effectiveDprCap(quality, merged.renderScale));
1226
+ }
1227
+ if (isMotionPaused()) renderOnce();
1228
+ return this;
1229
+ },
1230
+ setRenderScale(renderScale) {
1231
+ const value = Number(renderScale);
1232
+ if (!Number.isFinite(value)) return this;
1233
+ dirty.renderScale = true;
1234
+ merged.renderScale = Math.min(1, Math.max(0.25, value));
1235
+ if (typeof renderer.setDprCap === 'function') {
1236
+ renderer.setDprCap(effectiveDprCap(merged.quality, merged.renderScale));
1237
+ }
1238
+ if (isMotionPaused()) renderOnce();
1239
+ return this;
1240
+ },
1241
+ setOpacity(value) {
1242
+ const opacity = Number(value);
1243
+ if (!Number.isFinite(opacity)) return this;
1244
+ dirty.opacity = true;
1245
+ merged.opacity = Math.min(1, Math.max(0, opacity));
1246
+ layer.style.setProperty('--dlc-color-opacity', String(merged.opacity));
1247
+ return this;
1248
+ },
1249
+ randomize() {
1250
+ this.setSeed(Math.random() * 100);
1251
+ return this;
1252
+ },
1253
+ pause() {
1254
+ dirty.paused = true;
1255
+ manuallyPaused = true;
1256
+ renderOnce();
1257
+ return this;
1258
+ },
1259
+ resume() {
1260
+ dirty.paused = true;
1261
+ manuallyPaused = false;
1262
+ wakeScheduler();
1263
+ return this;
1264
+ },
1265
+ setPaused(value) {
1266
+ return value ? this.pause() : this.resume();
1267
+ },
1268
+ setStatic(value) {
1269
+ dirty.static = true;
1270
+ staticMode = value === true;
1271
+ merged.static = staticMode;
1272
+ if (staticMode) renderOnce();
1273
+ else wakeScheduler();
1274
+ return this;
1275
+ },
1276
+ setFps(fps) {
1277
+ dirty.fps = true;
1278
+ merged.fps = frameGate.setFps(fps);
1279
+ wakeScheduler();
1280
+ return this;
1281
+ },
1282
+ dispose() {
1283
+ disposed = true;
1284
+ unsubscribe();
1285
+ visibility.dispose();
1286
+ motionPreference.dispose();
1287
+ if (resizeObserver) resizeObserver.disconnect();
1288
+ else window.removeEventListener('resize', resize);
1289
+ renderer.dispose();
1290
+ layer.remove();
1291
+ releaseHostStyles(host);
1292
+ },
1293
+ get opacity() { return merged.opacity; },
1294
+ get fallbackColor() { return merged.fallbackColor; },
1295
+ get mouseColor() { return merged.mouseColor; },
1296
+ get quality() { return merged.quality; },
1297
+ get renderScale() { return merged.renderScale; },
1298
+ get paused() { return manuallyPaused; },
1299
+ get static() { return staticMode; },
1300
+ get fps() { return frameGate.getFps(); },
1301
+ dirty
1302
+ };
1303
1303
  }
1304
1304
 
1305
1305
  export { createColorBackground };