The best way to control Claude Code, Codex and more from any computer or phone

main
astro 486 lines 17 KB
Raw
1 ---
2 /**
3 * Animated mandala background for the hero — endless lotus zoom
4 * emanating from the Yantra's bindu (center dot).
5 *
6 * The vanishing point is measured at runtime from the element matched
7 * by `center` (default `.alc-hero__mark`), so the animation truly
8 * radiates from the brand mark's dot rather than the canvas geometric
9 * center. The same coordinates are pushed back to CSS as `--alc-bg-cx`
10 * / `--alc-bg-cy` so the mask feather follows.
11 *
12 * Multiple stylistic variants live in this file. The active one is
13 * picked by the `?variant=N` query string (default 1) so we can A/B
14 * compare on the live page without editing the MDX.
15 *
16 * Only variant 1 is exposed: concentric rings + radial vesica arcs
17 * blooming back toward the bindu. The trippy/subtle baseline.
18 *
19 * Variant 2 is kept in this file as a backup (Sri-Yantra-style lotus
20 * petals from the canonical TikZ construction) but is intentionally
21 * not toggleable via `?variant=` — flip the dispatch in `draw()`
22 * manually to revisit it.
23 */
24
25 interface Props {
26 /** CSS selector for the element whose center the animation emanates from. */
27 center?: string;
28 /** Stroke color. */
29 color?: string;
30 /** Multiplier on stroke alpha (0..1). */
31 intensity?: number;
32 /** Number of concurrent layers. */
33 count?: number;
34 /** Zoom rate. ~0.06 = one octave of growth per ~16s. */
35 zoom?: number;
36 /** Default variant number when no `?variant=` query is present.
37 * Only `1` is exposed in the public API; variant 2 is kept in the
38 * file as a backup but isn't toggleable from a query string. */
39 variant?: 1;
40 }
41
42 const {
43 center = ".alc-hero__mark",
44 color = "var(--alc-fg-1)",
45 intensity = 1,
46 count = 10,
47 zoom = 0.025,
48 variant = 1,
49 } = Astro.props;
50 ---
51
52 <canvas
53 class="alc-hero__bg-graph"
54 data-variant={variant}
55 data-center={center}
56 data-intensity={intensity}
57 data-count={count}
58 data-zoom={zoom}
59 style={`color: ${color};`}
60 aria-hidden="true"
61 ></canvas>
62
63 <script>
64 const init = (canvas: HTMLCanvasElement) => {
65 const ctx = canvas.getContext("2d", { alpha: true });
66 if (!ctx) return;
67
68 const variant: number = Number(canvas.dataset.variant ?? 1);
69
70 const centerSel = canvas.dataset.center ?? ".alc-hero__mark";
71 const intensity = Number(canvas.dataset.intensity ?? 1);
72 const nLayers = Math.max(1, Number(canvas.dataset.count ?? 10));
73 const zoom = Number(canvas.dataset.zoom ?? 0.06);
74 const motionMq = window.matchMedia("(prefers-reduced-motion: reduce)");
75 let reduced = motionMq.matches;
76
77 let dpr = Math.min(window.devicePixelRatio || 1, 2);
78 let width = 0;
79 let height = 0;
80 /** Vanishing point in canvas-local CSS pixels. Updated by `resize`. */
81 let cx0 = 0;
82 let cy0 = 0;
83
84 const centerEl =
85 (centerSel && (document.querySelector(centerSel) as HTMLElement | null)) ||
86 null;
87
88 const measureCenter = () => {
89 if (centerEl) {
90 const heroRect = canvas.getBoundingClientRect();
91 const markRect = centerEl.getBoundingClientRect();
92 cx0 = markRect.left + markRect.width / 2 - heroRect.left;
93 cy0 = markRect.top + markRect.height / 2 - heroRect.top;
94 canvas.style.setProperty("--alc-bg-cx", `${cx0.toFixed(2)}px`);
95 canvas.style.setProperty("--alc-bg-cy", `${cy0.toFixed(2)}px`);
96 } else {
97 cx0 = width / 2;
98 cy0 = height / 2;
99 }
100 };
101
102 const resize = (): boolean => {
103 const rect = canvas.getBoundingClientRect();
104 const newW = rect.width;
105 const newH = rect.height;
106 const newDpr = Math.min(window.devicePixelRatio || 1, 2);
107 // iOS Safari fires `resize` continuously as the URL bar collapses
108 // / expands during scroll. Reassigning `canvas.width`/`height`
109 // wipes the bitmap *even when set to the same value*, which
110 // shows up as the mandala flashing every time you swipe. Skip
111 // when nothing actually changed; only the centerline (handled
112 // separately via ResizeObserver) needs to update on scroll.
113 if (newW === width && newH === height && newDpr === dpr) {
114 return false;
115 }
116 width = newW;
117 height = newH;
118 dpr = newDpr;
119 canvas.width = Math.round(width * dpr);
120 canvas.height = Math.round(height * dpr);
121 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
122 measureCenter();
123 return true;
124 };
125
126 const resolveRGB = (): [number, number, number] => {
127 const rgb = getComputedStyle(canvas).color;
128 const m = rgb.match(/\d+(\.\d+)?/g);
129 if (!m) return [0, 0, 0];
130 return [Number(m[0]), Number(m[1]), Number(m[2])];
131 };
132
133 let rgb = resolveRGB();
134 const rgba = (a: number) =>
135 `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a.toFixed(3)})`;
136
137 /** Tiny bindu marker — drawn for every variant so the dot visually
138 * sources the emanation. */
139 const drawBindu = () => {
140 ctx.fillStyle = rgba(0.55 * intensity);
141 ctx.beginPath();
142 ctx.arc(cx0, cy0, 1.8, 0, Math.PI * 2);
143 ctx.fill();
144 };
145
146 // ============================================================
147 // Variant 1 — concentric rings + radial vesica arcs (original)
148 // ============================================================
149
150 /** Petal count per ring index. Grows outward so outer rings bloom
151 * into more detail while inner rings stay restful. */
152 const petalsAtRing = (i: number) => {
153 const seq = [6, 8, 12, 16, 18, 20, 24, 28, 32, 36, 40];
154 return seq[Math.min(i, seq.length - 1)];
155 };
156
157 const drawV1 = (t: number) => {
158 const minR = Math.max(width, height) * 0.02;
159 const maxR = Math.max(width, height) * 0.95;
160 const logRange = Math.log(maxR / minR);
161 const clock = ((t * 0.001 * zoom) % 1 + 1) % 1;
162 const tSec = t * 0.001;
163
164 drawBindu();
165
166 ctx.lineWidth = 1;
167 const cap = 0.32 * intensity;
168
169 for (let i = 0; i < nLayers; i++) {
170 const phase = (i / nLayers + clock) % 1;
171 const r = minR * Math.exp(phase * logRange);
172 const fade = Math.pow(Math.sin(phase * Math.PI), 1.2);
173 const a = cap * fade;
174 if (a < 0.01) continue;
175
176 // Very slow uniform drift — adjacent rings counter-rotate,
177 // but at the same gentle rate (no per-ring parallax speed-up).
178 // ~1 revolution per ~3 minutes.
179 const spin = tSec * 0.035 * (i % 2 === 0 ? 1 : -1);
180
181 // Concentric ring.
182 ctx.strokeStyle = rgba(a * 0.85);
183 ctx.beginPath();
184 ctx.arc(cx0, cy0, r, 0, Math.PI * 2);
185 ctx.stroke();
186
187 // Radial petal arcs — small arcs centered on points around the
188 // ring, drawing a vesica-like bloom. Arc radius scales with
189 // the ring radius so they read as part of the same petal.
190 const k = petalsAtRing(i);
191 const petalR = r * 0.35;
192 const petalSweep = Math.PI * 0.55;
193 ctx.strokeStyle = rgba(a * 0.65);
194 for (let p = 0; p < k; p++) {
195 const ang = spin + (p * 2 * Math.PI) / k;
196 const px = cx0 + Math.cos(ang) * r;
197 const py = cy0 + Math.sin(ang) * r;
198 // Arc faces back toward the bindu so each petal forms a leaf
199 // pointing outward.
200 ctx.beginPath();
201 ctx.arc(
202 px,
203 py,
204 petalR,
205 ang + Math.PI - petalSweep / 2,
206 ang + Math.PI + petalSweep / 2,
207 );
208 ctx.stroke();
209 }
210 }
211 };
212
213 // ============================================================
214 // Variant 2 (backup, not query-string toggleable) — Sri Yantra
215 // lotus rim built from the canonical TikZ construction
216 // (bhaskatripathi/SriYantra). Two cubic Beziers per side + an
217 // arc base on the inner circle, so the petal silhouette has a
218 // smooth scalloped base and a single sharp tip on the outer
219 // circle. Petal-band aspect (r1/r0 = 1.2) is decoupled from the
220 // inter-layer log spacing.
221 // ============================================================
222
223 /** Stroke a single canonical lotus petal — the TikZ Sri Yantra
224 * construction.
225 *
226 * The petal occupies angular span `[theta - halfAngle, theta +
227 * halfAngle]` on the inner circle (radius `r0`). Its tip sits on
228 * the outer circle (radius `r1`) at the petal's center angle
229 * `theta`. Two cubic Beziers form the upward + downward sides;
230 * the base is a circular arc along `r0` between the two anchor
231 * points, so neighbors share an arc segment (not a single point)
232 * — that's what gives the silhouette a smooth, rounded base
233 * rather than the spiky triangle we had before.
234 *
235 * Control radii / angular offsets follow the proportions used in
236 * the bhaskatripathi/SriYantra LaTeX source (8-petal: anchors
237 * 45° apart, controls at ±5° / ±17.5° at radii 0.7·len /
238 * 0.5·len above the inner circle). Generalized here to any
239 * petal count. */
240 const strokeLotusPetal = (
241 theta: number,
242 r0: number,
243 r1: number,
244 halfAngle: number,
245 ) => {
246 const len = r1 - r0;
247
248 // Anchor points where the petal meets the inner circle.
249 const startAng = theta + halfAngle;
250 const endAng = theta - halfAngle;
251 const sx = cx0 + Math.cos(startAng) * r0;
252 const sy = cy0 + Math.sin(startAng) * r0;
253 const ex = cx0 + Math.cos(endAng) * r0;
254 const ey = cy0 + Math.sin(endAng) * r0;
255
256 // Tip on the outer circle.
257 const tx = cx0 + Math.cos(theta) * r1;
258 const ty = cy0 + Math.sin(theta) * r1;
259
260 // First cubic: from start anchor up to the tip. Two controls
261 // bow the curve up + sideways before pinching back to the tip.
262 const c1Ang = theta + halfAngle * (7 / 9);
263 const c1R = r0 + 0.7 * len;
264 const c1x = cx0 + Math.cos(c1Ang) * c1R;
265 const c1y = cy0 + Math.sin(c1Ang) * c1R;
266
267 const c2Ang = theta + halfAngle * (2 / 9);
268 const c2R = r0 + 0.5 * len;
269 const c2x = cx0 + Math.cos(c2Ang) * c2R;
270 const c2y = cy0 + Math.sin(c2Ang) * c2R;
271
272 // Second cubic (mirror): tip down to end anchor.
273 const c3Ang = theta - halfAngle * (2 / 9);
274 const c3R = r0 + 0.5 * len;
275 const c3x = cx0 + Math.cos(c3Ang) * c3R;
276 const c3y = cy0 + Math.sin(c3Ang) * c3R;
277
278 const c4Ang = theta - halfAngle * (7 / 9);
279 const c4R = r0 + 0.7 * len;
280 const c4x = cx0 + Math.cos(c4Ang) * c4R;
281 const c4y = cy0 + Math.sin(c4Ang) * c4R;
282
283 ctx.beginPath();
284 ctx.moveTo(sx, sy);
285 ctx.bezierCurveTo(c1x, c1y, c2x, c2y, tx, ty);
286 ctx.bezierCurveTo(c3x, c3y, c4x, c4y, ex, ey);
287 // Close the base with an arc along the inner circle from the
288 // end anchor back to the start anchor (anticlockwise=true in
289 // canvas coords traces the short arc from endAng up to
290 // startAng).
291 ctx.arc(cx0, cy0, r0, endAng, startAng, true);
292 ctx.closePath();
293 ctx.stroke();
294 };
295
296 const drawV2 = (t: number) => {
297 const minR = Math.max(width, height) * 0.015;
298 const maxR = Math.max(width, height) * 1.0;
299 const logRange = Math.log(maxR / minR);
300 // Petal-band aspect (`r1/r0`) is decoupled from inter-layer
301 // spacing — the LaTeX reference uses 1.2 for nice wide petals.
302 const petalRatio = 1.2;
303 const clock = ((t * 0.001 * zoom) % 1 + 1) % 1;
304 const tSec = t * 0.001;
305
306 drawBindu();
307
308 const cap = 0.5 * intensity;
309
310 for (let i = 0; i < nLayers; i++) {
311 const phase = (i / nLayers + clock) % 1;
312 const r0 = minR * Math.exp(phase * logRange);
313 const r1 = r0 * petalRatio;
314 // Asymmetric envelope: quick fade-in near the bindu, then a
315 // steep (1−phase)^2 falloff so outer layers dissolve faster
316 // than they grow.
317 const fadeIn = Math.min(1, phase / 0.12);
318 const fadeOut = Math.pow(1 - phase, 1.8);
319 const fade = fadeIn * fadeOut;
320 const a = cap * fade;
321 if (a < 0.01) continue;
322
323 const spinScale = 0.06 / Math.max(0.06, phase + 0.05);
324 const spin = tSec * spinScale * (i % 2 === 0 ? 1 : -1);
325
326 // Bounding circles for this lotus rim — faint so the petal
327 // silhouettes dominate (matches the block-print reference).
328 ctx.lineWidth = 1;
329 ctx.strokeStyle = rgba(a * 0.4);
330 ctx.beginPath();
331 ctx.arc(cx0, cy0, r0, 0, Math.PI * 2);
332 ctx.stroke();
333 ctx.beginPath();
334 ctx.arc(cx0, cy0, r1, 0, Math.PI * 2);
335 ctx.stroke();
336
337 const k = 8;
338 const halfAngle = Math.PI / k;
339
340 ctx.lineWidth = 1.05;
341 ctx.strokeStyle = rgba(a * 0.9);
342 for (let p = 0; p < k; p++) {
343 const ang = spin + (p * 2 * Math.PI) / k;
344 strokeLotusPetal(ang, r0, r1, halfAngle);
345 }
346 }
347 };
348
349 // ============================================================
350 // Frame loop
351 // ============================================================
352
353 const draw = (t: number) => {
354 ctx.clearRect(0, 0, width, height);
355 // Variant 2 (`drawV2`) is intentionally unreachable from the
356 // public API — uncomment the case below to revisit it.
357 void drawV2;
358 switch (variant) {
359 case 1:
360 default:
361 drawV1(t);
362 break;
363 }
364 };
365
366 let raf = 0;
367 let visible = true;
368 // The page's "Pause motion" control (WCAG 2.2.2) sets this class.
369 const isPaused = () =>
370 document.documentElement.classList.contains("alc-motion-paused");
371 // Playback rate for every motion in the graph (zoom and ring spin).
372 const SPEED = 0.5;
373 // Own clock, advanced only while running, so pausing freezes the frame
374 // and resuming continues from it without a jump.
375 let clock = 0;
376 let last: number | null = null;
377 const loop = (t: number) => {
378 if (last !== null) clock += t - last;
379 last = t;
380 draw(clock * SPEED);
381 if (visible && !reduced && !isPaused()) {
382 raf = requestAnimationFrame(loop);
383 } else {
384 last = null;
385 }
386 };
387 window.addEventListener("alc-motion-change", () => {
388 cancelAnimationFrame(raf);
389 last = null;
390 if (!isPaused() && visible && !reduced) raf = requestAnimationFrame(loop);
391 });
392
393 resize();
394 if (reduced || isPaused()) {
395 draw(0);
396 } else {
397 raf = requestAnimationFrame(loop);
398 }
399
400 let resizeQueued = false;
401 const onResize = () => {
402 if (resizeQueued) return;
403 resizeQueued = true;
404 requestAnimationFrame(() => {
405 resizeQueued = false;
406 const changed = resize();
407 rgb = resolveRGB();
408 // In reduced-motion mode the RAF loop is stopped, so when the
409 // canvas was actually resized we need to explicitly redraw the
410 // static frame. If `resize()` no-op'd (mobile URL-bar wiggle
411 // with unchanged dimensions) we don't need to redraw at all.
412 if (reduced && changed) draw(0);
413 });
414 };
415 window.addEventListener("resize", onResize, { passive: true });
416
417 // The stroke color is derived from `getComputedStyle(canvas).color`,
418 // which resolves `var(--alc-fg-1)` against the current theme. When
419 // the user toggles light/dark mid-session the cached `rgb` would
420 // otherwise stay frozen on the previous theme until the next resize
421 // — observable as a flash of stale-color strokes after the theme
422 // switch. Re-resolve whenever `<html data-theme>` changes.
423 const themeObs = new MutationObserver(() => {
424 rgb = resolveRGB();
425 if (reduced) draw(0);
426 });
427 themeObs.observe(document.documentElement, {
428 attributes: true,
429 attributeFilter: ["data-theme"],
430 });
431
432 // Honor live changes to the user's `prefers-reduced-motion` setting.
433 // When the user enables reduced motion mid-session, stop the loop and
434 // hold a static frame; when they disable it, resume the animation.
435 const onMotionChange = (e: MediaQueryListEvent) => {
436 reduced = e.matches;
437 cancelAnimationFrame(raf);
438 if (reduced) {
439 draw(0);
440 } else if (visible && !isPaused()) {
441 raf = requestAnimationFrame(loop);
442 }
443 };
444 motionMq.addEventListener("change", onMotionChange);
445
446 if (centerEl && typeof ResizeObserver !== "undefined") {
447 const ro = new ResizeObserver(() => {
448 measureCenter();
449 if (reduced) draw(0);
450 });
451 ro.observe(centerEl);
452 const hero = canvas.parentElement;
453 if (hero) ro.observe(hero);
454 }
455
456 const io = new IntersectionObserver(
457 (entries) => {
458 const wasVisible = visible;
459 visible = entries[0]?.isIntersecting ?? true;
460 if (visible && !wasVisible) {
461 // Restart the loop when the canvas scrolls back into view, or
462 // — in reduced-motion mode — redraw the single static frame
463 // (it may have been cleared / sized while off-screen).
464 if (reduced) draw(0);
465 else if (!isPaused()) raf = requestAnimationFrame(loop);
466 } else if (!visible) {
467 cancelAnimationFrame(raf);
468 }
469 },
470 { threshold: 0 },
471 );
472 io.observe(canvas);
473 };
474
475 const start = () => {
476 document
477 .querySelectorAll<HTMLCanvasElement>("canvas.alc-hero__bg-graph")
478 .forEach(init);
479 };
480
481 if (document.readyState === "loading") {
482 document.addEventListener("DOMContentLoaded", start, { once: true });
483 } else {
484 start();
485 }
486 </script>