/*
* Nested Squares — a moving Background (All You Need Is Taste).
* Four squares nested one inside the next each turn a quarter in turn, the inner ones first, so the set winds up and settles like a slow combination lock.
*
* Usage: put the markup inside the block it should sit behind (a hero, a
* section), with the block `position: relative`, and mount it:
*
* const destroy = mount(document.querySelector('[data-element="nested-squares-background"]'), {
* bg: '#121212', fg: '#4C74FF', accent: '#F3EFE6', speed: 1, density: 1,
* });
*
* It fills its parent, draws one loop of 6 seconds on a canvas forever,
* caps the pixel ratio at 2, sleeps while off screen or in a hidden tab, and
* shows one still frame to a visitor who asked for reduced motion.
* `destroy.update(options)` re-tunes a live mount; `destroy.seek(t)` stops the
* clock and draws the loop at t seconds (a recorder's hook).
*/
const PERIOD = 6;
const DEFAULTS = {"bg":"#121212","fg":"#F2C230","accent":"#F3EFE6","speed":1,"density":1,"paused":false};
const TAU = Math.PI * 2;
const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
const easeInOut = (t) => { t = clamp(t); return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
const wrap = (x, m = 1) => ((x % m) + m) % m;
/** `#rrggbb` at an alpha, as an `rgba()` the canvas takes. */
const rgba = (hex, a = 1) => {
const n = Number.parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${clamp(a)})`;
};
/** A seeded random, so anything scattered lands in the same place every frame. */
const rng = (seed) => { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
/**
* One frame. `p` is the phase, 0 → 1 over the period, and frame 1 is frame 0;
* `c` the colours ({ bg, fg, accent }); `o.density` scales how many things
* there are. The ground is already painted.
*/
function draw(ctx, w, h, p, c, o) {
const cx = w / 2, cy = h / 2;
const base = Math.min(w, h) * 0.62;
const count = Math.max(3, Math.round(4 * o.density));
// Each square turns four quarter turns per loop (a whole turn), the inner
// one leading, each turn easing in and out and then holding.
for (let i = 0; i < count; i++) {
const size = base * (1 - i / (count + 0.6));
const q = wrap(p - i * 0.05) * 4;
const angle = (Math.floor(q) + easeInOut(smooth(0, 0.6, q % 1))) * (Math.PI / 2);
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(angle * (i % 2 ? -1 : 1));
if (i === count - 1) {
ctx.fillStyle = c.accent;
ctx.fillRect(-size / 2, -size / 2, size, size);
} else {
ctx.strokeStyle = c.fg;
ctx.lineWidth = Math.max(2, base * 0.035);
ctx.strokeRect(-size / 2, -size / 2, size, size);
}
ctx.restore();
}
}
export function mount(root, options = {}) {
const o = { ...DEFAULTS, ...options };
const canvas = root.querySelector('[data-part="field"]');
const ctx = canvas.getContext('2d');
const still = matchMedia('(prefers-reduced-motion: reduce)');
let w = 0, h = 0, dpr = 1, raf = 0, last = 0, clock = 0, onScreen = true, seeking = false;
const paint = () => {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.globalAlpha = 1;
ctx.fillStyle = o.bg;
ctx.fillRect(0, 0, w, h);
// A still visitor gets the loop at a third of its period, where every
// piece has something on show.
const t = still.matches && !seeking ? PERIOD / 3 : clock;
draw(ctx, w, h, wrap(t, PERIOD) / PERIOD, { bg: o.bg, fg: o.fg, accent: o.accent }, { density: clamp(o.density, 0.25, 3) });
};
const fit = () => {
const box = root.getBoundingClientRect();
dpr = Math.min(2, window.devicePixelRatio || 1);
w = Math.max(1, box.width);
h = Math.max(1, box.height);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
paint();
};
const running = () => onScreen && !document.hidden && !o.paused && !still.matches && !seeking;
const frame = (now) => {
raf = 0;
if (!running()) return;
clock += Math.min(0.1, (now - last) / 1000) * o.speed;
last = now;
paint();
raf = requestAnimationFrame(frame);
};
const wake = () => {
if (raf || !running()) return;
last = performance.now();
raf = requestAnimationFrame(frame);
};
root.style.setProperty('--ayt-ground', o.bg);
const resized = new ResizeObserver(fit);
resized.observe(root);
const seen = new IntersectionObserver(([entry]) => { onScreen = entry.isIntersecting; wake(); });
seen.observe(root);
const onVisibility = () => wake();
document.addEventListener('visibilitychange', onVisibility);
still.addEventListener('change', fit);
fit();
wake();
function destroy() {
cancelAnimationFrame(raf);
raf = 0;
resized.disconnect();
seen.disconnect();
document.removeEventListener('visibilitychange', onVisibility);
still.removeEventListener('change', fit);
}
destroy.update = (next = {}) => {
Object.assign(o, next);
root.style.setProperty('--ayt-ground', o.bg);
paint();
wake();
};
destroy.seek = (t) => {
seeking = true;
cancelAnimationFrame(raf);
raf = 0;
clock = t;
paint();
};
destroy.loop = PERIOD;
return destroy;
}