@jsb188/gfx 1.1.2 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +54 -248
  2. package/libs/dotGrid.ts +77 -480
  3. package/libs/effects/effectQuad.ts +2 -8
  4. package/libs/pointer.ts +0 -6
  5. package/libs/runtime.ts +4 -6
  6. package/libs/types.ts +1 -8
  7. package/main.ts +0 -2
  8. package/modules/Carousel.helpers.ts +0 -234
  9. package/modules/Carousel.tsx +29 -135
  10. package/modules/DotsArea.tsx +120 -0
  11. package/modules/GfxCanvas.tsx +2 -10
  12. package/modules/ScrollSteps.tsx +52 -7
  13. package/modules/VisionBoard.helpers.ts +561 -0
  14. package/modules/VisionBoard.tsx +358 -0
  15. package/modules/VisionBoard.types.ts +88 -0
  16. package/package.json +5 -15
  17. package/scenes/Carousel.ts +18 -99
  18. package/scenes/DotsArea.ts +208 -0
  19. package/tsconfig.json +1 -1
  20. package/utils/color.ts +2 -64
  21. package/utils/dotGridSpecs.ts +46 -304
  22. package/elements/Shapes.helpers.ts +0 -204
  23. package/elements/Shapes.hooks.ts +0 -171
  24. package/elements/Shapes.tsx +0 -505
  25. package/elements/Shapes.types.ts +0 -81
  26. package/elements/Stack.helpers.ts +0 -42
  27. package/elements/Stack.tsx +0 -143
  28. package/elements/Text.helpers.ts +0 -45
  29. package/elements/Text.hooks.ts +0 -197
  30. package/elements/Text.tsx +0 -98
  31. package/libs/dotGrid.helpers.ts +0 -53
  32. package/libs/effects/dotEffects.ts +0 -136
  33. package/modules/Carousel.hooks.ts +0 -520
  34. package/modules/Dots.tsx +0 -269
  35. package/modules/DotsBoard.helpers.ts +0 -388
  36. package/modules/DotsBoard.hooks.ts +0 -144
  37. package/modules/DotsBoard.strings.ts +0 -649
  38. package/modules/DotsBoard.types.ts +0 -240
  39. package/modules/DotsBoardCanvas.hooks.ts +0 -49
  40. package/modules/DotsBoardCanvas.tsx +0 -190
  41. package/modules/DotsBoardElements.tsx +0 -330
  42. package/modules/Gallery.helpers.ts +0 -32
  43. package/modules/Gallery.hooks.ts +0 -149
  44. package/modules/Gallery.tsx +0 -194
  45. package/modules/KineticHeader.helpers.ts +0 -44
  46. package/modules/KineticHeader.hooks.ts +0 -206
  47. package/modules/KineticHeader.tsx +0 -305
  48. package/modules/KineticHeader.types.ts +0 -56
  49. package/modules/ScrollSteps.hooks.ts +0 -138
  50. package/scenes/DotsBoard.helpers.ts +0 -12
  51. package/scenes/DotsBoard.ts +0 -245
  52. package/utils/align.ts +0 -18
  53. package/utils/dotEffectSpecs.ts +0 -79
  54. package/utils/motion.ts +0 -88
  55. package/utils/random.ts +0 -22
  56. package/utils/strings.ts +0 -116
@@ -17,18 +17,12 @@ export interface CarouselSceneSlide {
17
17
  key: string;
18
18
  /** The focused slide is drawn with the effect fully off; every other slide has it fully on. */
19
19
  focused: boolean;
20
- /** Overall thumbnail opacity, animated independently of focus; defaults to 1. */
21
- opacity?: number;
22
20
  }
23
21
 
24
22
  export interface CarouselSceneParams {
25
23
  slides: CarouselSceneSlide[];
26
24
  /** Live lookup of each slide's <video> by key. The component fills it from ref callbacks, so the scene reads it every frame. */
27
25
  videos: ReadonlyMap<string, HTMLVideoElement>;
28
- /** Default true; disable for galleries whose thumbnails load independently as they enter view. */
29
- waitForAllVideos?: boolean;
30
- /** Draw paused thumbnail frames at their wrappers only when they change; native overlays own active playback. */
31
- pausedThumbnails?: boolean;
32
26
  /** Effects applied to the unfocused slides, in order. */
33
27
  effects: ImageEffectSpec[];
34
28
  /** How long the effect takes to fade in or out when focus moves (ms); match the slide transition. */
@@ -44,16 +38,12 @@ export interface CarouselSceneParams {
44
38
  interface CarouselSlideState {
45
39
  video: HTMLVideoElement | null;
46
40
  texture: VideoTexture | null;
47
- unsubscribeVideo: (() => void) | null;
48
41
  /** Background of the video's wrapper, seen through the dimmed video in place of the page. */
49
42
  backdrop: RGB;
50
43
  /** Current effect strength, eased between `from` and `to` on the wall clock. */
51
44
  amount: number;
52
45
  from: number;
53
46
  to: number;
54
- opacity: number;
55
- opacityFrom: number;
56
- opacityTo: number;
57
47
  startedAt: number;
58
48
  }
59
49
 
@@ -62,16 +52,11 @@ interface CarouselSlideState {
62
52
  * slide's video is redrawn each frame at the exact place its <video> element occupies (read from
63
53
  * the DOM, so CSS slide transitions carry the drawing along), through the effect list at a
64
54
  * per-slide strength. The focused slide eases to 0 (an exact no-op, so it looks like the plain
65
- * video) and the others ease to 1, fading to `unfocusedOpacity` on the same curve. Each slide's
66
- * overall opacity can also animate independently without changing its effect. Videos that lie
67
- * entirely outside the canvas are skipped. By default the scene waits for every registered video
68
- * to have a frame; galleries can opt out so thumbnails appear independently as their videos load.
69
- * Paused thumbnails render on demand, waking only for frame readiness, opacity transitions, or layout changes.
55
+ * video) and the others ease to 1, fading to `unfocusedOpacity` on the same curve. Videos that lie
56
+ * entirely outside the canvas are skipped. The scene reports ready only once every registered
57
+ * video has a frame, so the wrapper keeps the plain videos visible until the canvas can replace them.
70
58
  */
71
- export default function createCarouselScene(
72
- { gl, invalidate, onDispose }: SceneContext,
73
- params: CarouselSceneParams,
74
- ): Scene<CarouselSceneParams> {
59
+ export default function createCarouselScene({ gl, onDispose }: SceneContext, params: CarouselSceneParams): Scene<CarouselSceneParams> {
75
60
  const canvas = gl.canvas as HTMLCanvasElement;
76
61
  const states = new Map<string, CarouselSlideState>();
77
62
  let quad: EffectQuad | null = null;
@@ -84,7 +69,7 @@ export default function createCarouselScene(
84
69
  const rect = { x: 0, y: 0, width: 0, height: 0 };
85
70
  const pointerUv: [number, number] = [0.5, 0.5];
86
71
  onDispose(() => {
87
- for (const state of states.values()) disposeVideo(state);
72
+ for (const state of states.values()) state.texture?.dispose();
88
73
  states.clear();
89
74
  quad?.dispose();
90
75
  disposeImageEffects(effects);
@@ -112,65 +97,32 @@ export default function createCarouselScene(
112
97
  for (const slide of next.slides) {
113
98
  keep.add(slide.key);
114
99
  const target = slide.focused ? 0 : 1;
115
- const opacity = Math.max(0, Math.min(1, slide.opacity ?? 1));
116
100
  let state = states.get(slide.key);
117
101
  if (!state) {
118
102
  // A slide that appears already in its resting state does not animate in.
119
- state = {
120
- video: null,
121
- texture: null,
122
- unsubscribeVideo: null,
123
- backdrop: fallbackBackdrop,
124
- amount: target,
125
- from: target,
126
- to: target,
127
- opacity,
128
- opacityFrom: opacity,
129
- opacityTo: opacity,
130
- startedAt: now,
131
- };
103
+ state = { video: null, texture: null, backdrop: fallbackBackdrop, amount: target, from: target, to: target, startedAt: now };
132
104
  states.set(slide.key, state);
133
- } else if (state.to !== target || state.opacityTo !== opacity) {
105
+ } else if (state.to !== target) {
134
106
  state.from = state.amount;
135
107
  state.to = target;
136
- state.opacityFrom = state.opacity;
137
- state.opacityTo = opacity;
138
108
  state.startedAt = now;
139
109
  }
140
110
  }
141
111
  for (const [key, state] of states) {
142
112
  if (keep.has(key)) continue;
143
- disposeVideo(state);
113
+ state.texture?.dispose();
144
114
  states.delete(key);
145
115
  }
146
116
  }
147
117
 
148
- /*
149
- * Release a slide's texture and readiness listeners when its video changes or the slide leaves.
150
- */
151
- function disposeVideo(state: CarouselSlideState) {
152
- state.unsubscribeVideo?.();
153
- state.unsubscribeVideo = null;
154
- state.texture?.dispose();
155
- state.texture = null;
156
- state.video = null;
157
- }
158
-
159
118
  /*
160
119
  * Bind the slide to whatever <video> is registered for it right now, swapping textures if the element changed.
161
120
  */
162
121
  function syncVideo(state: CarouselSlideState, video: HTMLVideoElement | null) {
163
122
  if (state.video === video) return;
164
- disposeVideo(state);
123
+ state.texture?.dispose();
165
124
  state.video = video;
166
125
  state.texture = video ? createVideoTexture(gl, video) : null;
167
- if (video) {
168
- const events = ['loadeddata', 'canplay', 'seeked', 'pause', 'error'] as const;
169
- for (const event of events) video.addEventListener(event, invalidate);
170
- state.unsubscribeVideo = () => {
171
- for (const event of events) video.removeEventListener(event, invalidate);
172
- };
173
- }
174
126
  // The wrapper's CSS background is the source of truth for what a dimmed video fades toward.
175
127
  const wrapper = video?.parentElement;
176
128
  state.backdrop = wrapper ? cssColorToRgb(getComputedStyle(wrapper).backgroundColor, fallbackBackdrop) : fallbackBackdrop;
@@ -180,39 +132,19 @@ export default function createCarouselScene(
180
132
  applySlides(params);
181
133
 
182
134
  return {
183
- /*
184
- * Keep full-rate playback for carousels and stop between changes for paused galleries.
185
- */
186
- get frameloop() {
187
- return current.pausedThumbnails ? 'demand' : 'always';
188
- },
189
- /*
190
- * Paused thumbnails have no pointer effect; their native previews handle interaction.
191
- */
192
- get followsPointer() {
193
- return !current.pausedThumbnails;
194
- },
195
- // The frames are the videos themselves (the plain ones hide under the canvas), so they keep
196
- // playing at full rate: never at the idle rate, nor paused for reduced motion.
135
+ frameloop: 'always',
136
+ // Video plays at full rate, so never drop to the idle rate.
197
137
  idleFrameRate: 0,
198
- pauseForReducedMotion: false,
199
- isReady: () =>
200
- current.waitForAllVideos === false ||
201
- current.slides.every(
202
- (slide) => !current.videos.has(slide.key) || current.videos.get(slide.key)?.error || states.get(slide.key)?.texture?.loaded,
203
- ),
138
+ isReady: () => current.slides.every((slide) => !current.videos.has(slide.key) || states.get(slide.key)?.texture?.loaded),
204
139
  resize(nextSize) {
205
140
  size = nextSize;
206
141
  },
207
142
  update() {
208
143
  const now = performance.now();
209
144
  for (const state of states.values()) {
210
- if (state.amount === state.to && state.opacity === state.opacityTo) continue;
145
+ if (state.amount === state.to) continue;
211
146
  const t = Math.min(1, (now - state.startedAt) / Math.max(1, current.transitionMs));
212
- const eased = easeInOutCubic(t);
213
- state.amount = state.from + (state.to - state.from) * eased;
214
- state.opacity = state.opacityFrom + (state.opacityTo - state.opacityFrom) * eased;
215
- if (t < 1) invalidate();
147
+ state.amount = state.from + (state.to - state.from) * easeInOutCubic(t);
216
148
  }
217
149
  },
218
150
  render({ elapsed, pointer }) {
@@ -229,27 +161,15 @@ export default function createCarouselScene(
229
161
  syncVideo(state, current.videos.get(slide.key) ?? null);
230
162
  const { video, texture } = state;
231
163
  if (!video || !texture) continue;
232
- // A carousel's initial reveal still waits for registered videos outside the visible canvas.
233
- if (current.waitForAllVideos !== false) texture.update();
234
- if (state.opacity <= 0) continue;
235
- // The enlarged native preview must not stretch the gallery's fixed thumbnail underneath it.
236
- const videoRect = (current.pausedThumbnails ? (video.parentElement ?? video) : video).getBoundingClientRect();
164
+ texture.update();
165
+ if (!texture.loaded) continue;
166
+ const videoRect = video.getBoundingClientRect();
237
167
  rect.x = videoRect.left - canvasRect.left;
238
168
  rect.y = videoRect.top - canvasRect.top;
239
169
  rect.width = videoRect.width;
240
170
  rect.height = videoRect.height;
241
171
  // Skip what the carousel has clipped away entirely.
242
- if (
243
- rect.width <= 0 ||
244
- rect.height <= 0 ||
245
- rect.x + rect.width <= 0 ||
246
- rect.x >= size.width ||
247
- rect.y + rect.height <= 0 ||
248
- rect.y >= size.height
249
- )
250
- continue;
251
- if (current.waitForAllVideos === false) texture.update();
252
- if (!texture.loaded) continue;
172
+ if (rect.width <= 0 || rect.height <= 0 || rect.x + rect.width <= 0 || rect.x >= size.width) continue;
253
173
  pointerUv[0] = (pointerX - rect.x) / rect.width;
254
174
  pointerUv[1] = 1 - (pointerY - rect.y) / rect.height;
255
175
  quad.draw({
@@ -262,7 +182,6 @@ export default function createCarouselScene(
262
182
  time: elapsed,
263
183
  radius: current.borderRadius,
264
184
  opacity: 1 - state.amount * (1 - current.unfocusedOpacity),
265
- alpha: state.opacity,
266
185
  backdrop: state.backdrop,
267
186
  });
268
187
  }
@@ -0,0 +1,208 @@
1
+ import { createDotGrid } from '../libs/dotGrid.ts';
2
+ import { createImageTexture } from '../libs/texture.ts';
3
+ import type { ImageTexture } from '../libs/texture.ts';
4
+ import type { SceneContext, Scene, SceneSize } from '../libs/types.ts';
5
+ import type { ResolvedDotGridOptions } from '../utils/dotGridSpecs.ts';
6
+ import { easeOutCubic } from '../utils/easing.ts';
7
+
8
+ /**
9
+ * Types
10
+ */
11
+
12
+ export interface DotsAreaSceneParams extends ResolvedDotGridOptions {
13
+ /** Image shown through the dots in place of their color, cover-fit to the area; null for the flat color. */
14
+ imageUrl: string | null;
15
+ /** `performance.now()` when the reveal timeline began (the area mounting), so a late-starting canvas joins it in step. */
16
+ revealBegin: number;
17
+ /** Height in CSS pixels of the fade to transparent along the bottom edge; 0 for none. Never fades the filled reveal state. */
18
+ fadeBottom: number;
19
+ }
20
+
21
+ /*
22
+ * Build the dots scene: one dot grid on a transparent canvas that a moving cursor throws
23
+ * around, optionally opening with a reveal (the dots fill the area, optionally zooming the image
24
+ * to 100% from mount, then shrink to size once the delay is up) or pulsing a few random dots.
25
+ * Frames run on demand unless dots pulse: the scene asks for the next frame only while a reveal
26
+ * or a throw is in progress, so an idle area costs nothing, and the pointer is only followed
27
+ * once kicks can land. The reveal runs on the wall clock (ease-out cubic, so it moves from the
28
+ * first frame and settles gently), since the runtime's clock only advances during frames.
29
+ */
30
+ export default function createDotsAreaScene(
31
+ { gl, signal, invalidate, onDispose }: SceneContext,
32
+ params: DotsAreaSceneParams,
33
+ ): Scene<DotsAreaSceneParams> {
34
+ const grid = createDotGrid(gl, params);
35
+ let size: SceneSize = { width: 1, height: 1, pixelRatio: 1 };
36
+ let overlay: ImageTexture | null = null;
37
+ let overlayUrl: string | null = null;
38
+ // The reveal timeline on the wall clock (ms): when it began (mount), when the zoom settles,
39
+ // when the shrink starts (`delay` after mount, zoom or not), and when it ends; null when there
40
+ // is no reveal.
41
+ let revealWindow: [number, number, number, number] | null = null;
42
+ let revealZoom = 1;
43
+ // When the shrink actually began: the first frame at or after the delay, since dots only exist
44
+ // once the canvas renders, so a delay shorter than the WebGL start-up waits for it.
45
+ let shrinkBeganAt: number | null = null;
46
+ let revealTimer: number | null = null;
47
+ // The runtime clock as of the last frame, so pulsing restarted from `setParams` begins now.
48
+ let pulseClock = 0;
49
+ // Raw (un-eased) pointer in CSS pixels from the last frame, for its velocity.
50
+ const previous: [number, number] = [0, 0];
51
+ const pointerPx: [number, number] = [0, 0];
52
+ const velocity: [number, number] = [0, 0];
53
+ onDispose(() => {
54
+ grid.dispose();
55
+ overlay?.dispose();
56
+ if (revealTimer !== null) clearTimeout(revealTimer);
57
+ });
58
+
59
+ /*
60
+ * Let the dots pulse from this moment on (a continuous loop is needed for that), or hold
61
+ * them still while a reveal is pending.
62
+ */
63
+ function startPulse(elapsed: number | null) {
64
+ grid.setPulseStart(elapsed);
65
+ scene.frameloop = elapsed !== null && grid.isPulsing() ? 'always' : 'demand';
66
+ }
67
+
68
+ /*
69
+ * Whether a reveal is still holding or shrinking, so kicks must wait.
70
+ */
71
+ function isRevealing() {
72
+ if (!revealWindow) return false;
73
+ return shrinkBeganAt === null || performance.now() < shrinkBeganAt + (revealWindow[3] - revealWindow[2]);
74
+ }
75
+
76
+ /*
77
+ * Start (or cancel) the reveal: fill the area now, zoom the image to 100% from mount if asked,
78
+ * and let `update` drive the shrink once the delay is up. The zoom needs frames; otherwise the
79
+ * hold is static and a timer wakes the loop for the shrink.
80
+ */
81
+ function scheduleReveal(reveal: ResolvedDotGridOptions['reveal'], begin: number) {
82
+ if (revealTimer !== null) clearTimeout(revealTimer);
83
+ revealTimer = null;
84
+ if (!reveal) {
85
+ revealWindow = null;
86
+ grid.setReveal(1);
87
+ grid.setOverlayZoom(1);
88
+ return;
89
+ }
90
+ const zoomEnd = begin + (reveal.zoomOnMount !== 1 ? reveal.zoomDuration : 0);
91
+ const start = begin + reveal.delay;
92
+ revealWindow = [begin, zoomEnd, start, start + reveal.duration];
93
+ revealZoom = reveal.zoomOnMount;
94
+ shrinkBeganAt = null;
95
+ grid.setReveal(0);
96
+ grid.setOverlayZoom(revealZoom);
97
+ if (revealZoom !== 1) invalidate();
98
+ revealTimer = window.setTimeout(
99
+ () => {
100
+ revealTimer = null;
101
+ invalidate();
102
+ },
103
+ Math.max(0, start - performance.now()),
104
+ );
105
+ }
106
+
107
+ /*
108
+ * Advance the reveal shrink for this frame; returns whether it is still running.
109
+ */
110
+ function updateReveal(elapsed: number) {
111
+ if (!revealWindow) return false;
112
+ const [begin, zoomEnd, start, end] = revealWindow;
113
+ const now = performance.now();
114
+ // The image zooms from `zoomOnMount` to 100% on its own clock, overlapping the hold and the
115
+ // shrink however the durations fall.
116
+ const zooming = now < zoomEnd;
117
+ grid.setOverlayZoom(zooming ? revealZoom + (1 - revealZoom) * easeOutCubic((now - begin) / (zoomEnd - begin)) : 1);
118
+ // The hold: nothing but the zoom to draw until the timer wakes the loop for the shrink.
119
+ if (now < start) return zooming;
120
+ // The shrink to dots, from the first frame the canvas draws at or after the delay.
121
+ if (shrinkBeganAt === null) shrinkBeganAt = now;
122
+ const progress = Math.min(1, (now - shrinkBeganAt) / (end - start));
123
+ grid.setReveal(easeOutCubic(progress));
124
+ if (progress >= 1) {
125
+ revealWindow = null;
126
+ grid.setOverlayZoom(1);
127
+ // The image → dots intro is over; ambient pulsing may begin now.
128
+ startPulse(elapsed);
129
+ return false;
130
+ }
131
+ return true;
132
+ }
133
+
134
+ /*
135
+ * Swap the overlay image; the dots keep their flat color until it decodes.
136
+ */
137
+ function loadOverlay(url: string | null) {
138
+ if (url === overlayUrl) return;
139
+ overlayUrl = url;
140
+ overlay?.dispose();
141
+ overlay = url
142
+ ? createImageTexture(gl, {
143
+ url,
144
+ signal,
145
+ onLoad: (loaded) => {
146
+ if (loaded !== overlay) return;
147
+ grid.setOverlay(overlay);
148
+ invalidate();
149
+ },
150
+ })
151
+ : null;
152
+ grid.setOverlay(overlay);
153
+ }
154
+
155
+ /*
156
+ * Pointer moves only matter once kicks can land.
157
+ */
158
+ function followsPointer() {
159
+ return grid.isInteractive() && !isRevealing();
160
+ }
161
+
162
+ loadOverlay(params.imageUrl);
163
+ grid.setFadeBottom(params.fadeBottom);
164
+ scheduleReveal(params.reveal, params.revealBegin);
165
+
166
+ const scene: Scene<DotsAreaSceneParams> = {
167
+ // Pulsing is an ambient animation, so it needs continuous frames (the runtime still idles
168
+ // to a lower rate and pauses off-screen); everything else runs on demand. It starts after
169
+ // any reveal, from `startPulse`.
170
+ frameloop: 'demand',
171
+ followsPointer: followsPointer(),
172
+ resize(nextSize) {
173
+ size = nextSize;
174
+ grid.resize(nextSize);
175
+ },
176
+ update({ pointer, delta, elapsed }) {
177
+ pulseClock = elapsed;
178
+ grid.setTime(elapsed);
179
+ const revealing = updateReveal(elapsed);
180
+ // The kick follows the actual cursor, not the eased one; y flips from UV space to CSS.
181
+ pointerPx[0] = pointer.targetX * size.width;
182
+ pointerPx[1] = (1 - pointer.targetY) * size.height;
183
+ // The first frame after a pause has no delta, so it only records where the pointer is.
184
+ velocity[0] = delta > 0 ? (pointerPx[0] - previous[0]) / delta : 0;
185
+ velocity[1] = delta > 0 ? (pointerPx[1] - previous[1]) / delta : 0;
186
+ previous[0] = pointerPx[0];
187
+ previous[1] = pointerPx[1];
188
+ const settling = grid.step(pointerPx, velocity, pointer.hover && !revealing, delta, elapsed);
189
+ scene.followsPointer = followsPointer();
190
+ if (revealing || settling) invalidate();
191
+ },
192
+ render() {
193
+ grid.draw(true);
194
+ },
195
+ setParams(next) {
196
+ grid.setOptions(next);
197
+ loadOverlay(next.imageUrl);
198
+ grid.setFadeBottom(next.fadeBottom);
199
+ scheduleReveal(next.reveal, next.revealBegin);
200
+ // A new reveal holds pulsing until it ends; otherwise pulsing may (re)start right away.
201
+ startPulse(next.reveal ? null : pulseClock);
202
+ scene.followsPointer = followsPointer();
203
+ invalidate();
204
+ },
205
+ };
206
+ if (!params.reveal) startPulse(0);
207
+ return scene;
208
+ }
package/tsconfig.json CHANGED
@@ -9,5 +9,5 @@
9
9
  "strict": true,
10
10
  "esModuleInterop": true
11
11
  },
12
- "include": ["main.ts", "libs/**/*", "utils/**/*", "scenes/**/*", "modules/**/*", "elements/**/*"]
12
+ "include": ["main.ts", "libs/**/*", "utils/**/*", "scenes/**/*", "modules/**/*"]
13
13
  }
package/utils/color.ts CHANGED
@@ -36,7 +36,8 @@ export function cssColorToRgb(value: string, fallback: RGB = [0, 0, 0]): RGB {
36
36
  if (!match) return fallback;
37
37
  const parts = match[2]
38
38
  .replace(/^srgb\s+/i, '')
39
- .split(/[\s,/]+/)
39
+ .replace(/\//g, ' ')
40
+ .split(/[\s,]+/)
40
41
  .filter(Boolean);
41
42
  if (parts.length < 3) return fallback;
42
43
  // rgb() channels are 0..255 (or percentages); color(srgb) channels are already 0..1.
@@ -47,66 +48,3 @@ export function cssColorToRgb(value: string, fallback: RGB = [0, 0, 0]): RGB {
47
48
  if (channels.some((channel) => Number.isNaN(channel))) return fallback;
48
49
  return channels as RGB;
49
50
  }
50
-
51
- /*
52
- * Convert a 0..1 RGB triple to #rrggbb.
53
- */
54
- export function rgbToHex(color: RGB): string {
55
- const channel = (value: number) =>
56
- Math.round(Math.min(1, Math.max(0, value)) * 255)
57
- .toString(16)
58
- .padStart(2, '0');
59
- return `#${channel(color[0])}${channel(color[1])}${channel(color[2])}`;
60
- }
61
-
62
- /*
63
- * Convert a 0..1 RGB triple to HSL (hue in degrees, saturation and lightness 0..1).
64
- */
65
- export function rgbToHsl(color: RGB): [number, number, number] {
66
- const [r, g, b] = color;
67
- const max = Math.max(r, g, b);
68
- const min = Math.min(r, g, b);
69
- const l = (max + min) / 2;
70
- if (max === min) return [0, 0, l];
71
- const d = max - min;
72
- const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
73
- let h: number;
74
- if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
75
- else if (max === g) h = (b - r) / d + 2;
76
- else h = (r - g) / d + 4;
77
- return [h * 60, s, l];
78
- }
79
-
80
- /*
81
- * Convert HSL (hue in degrees, saturation and lightness 0..1) to a 0..1 RGB triple.
82
- */
83
- export function hslToRgb(h: number, s: number, l: number): RGB {
84
- const k = (n: number) => (n + h / 30) % 12;
85
- const a = s * Math.min(l, 1 - l);
86
- const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
87
- return [f(0), f(8), f(4)];
88
- }
89
-
90
- /*
91
- * Shift a hex color's lightness by `delta` (-1..1) and optionally its hue by `hueDelta` degrees,
92
- * returning #rrggbb. Used to derive gradient stops and ink tones from one base color.
93
- */
94
- export function shiftHex(hex: string, delta: number, hueDelta = 0): string {
95
- const [h, s, l] = rgbToHsl(hexToRgb(hex));
96
- return rgbToHex(hslToRgb((h + hueDelta + 360) % 360, s, Math.min(1, Math.max(0, l + delta))));
97
- }
98
-
99
- /*
100
- * Preserve alpha when converting a browser-computed rgb/rgba or color(srgb) value for WebGL.
101
- * Resolve named colors, hex and theme variables through getComputedStyle before calling.
102
- */
103
- export function cssColorToRgba(value: string): [number, number, number, number] {
104
- const parts = value
105
- .slice(value.indexOf('(') + 1, value.lastIndexOf(')'))
106
- .replace(/^srgb\s+/i, '')
107
- .split(/[\s,/]+/)
108
- .filter(Boolean);
109
- const alpha = parts[3];
110
- const opacity = alpha === undefined ? 1 : Number.parseFloat(alpha) / (alpha.endsWith('%') ? 100 : 1);
111
- return [...cssColorToRgb(value), Number.isFinite(opacity) ? Math.min(1, Math.max(0, opacity)) : 1];
112
- }