diff --git a/scripts/starry-night-theme.test.mts b/scripts/starry-night-theme.test.mts new file mode 100644 index 00000000..cfaffc7c --- /dev/null +++ b/scripts/starry-night-theme.test.mts @@ -0,0 +1,1112 @@ +/* + * Copyright (C) 2026 spicetify + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import "../modules/stdlib/lib/test-setup.mts"; + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { Window } from "happy-dom"; + +import { + backingSize, + FALLBACK_COLOR, + canvasScale, + dotAlpha, + firstDelayMs, + flightDistance, + flightKeyframes, + generateField, + MAX_STARS, + motionState, + pickLaunch, + placeStar, + planFlight, + type Rand, + type Star, + starCount, + TWINKLE_DOT_MIN, + TWINKLE_FPS, + twinkleEnvelope, + twinkleGlow, +} from "../themes/starry-night/logic.ts"; +import { + type AnimationHandle, + createSky, + RESIZE_SETTLE_MS, + type SkyColors, + type SkyDeps, + type Viewport, +} from "../themes/starry-night/sky.ts"; +import { type MountEnv, mountSky } from "../themes/starry-night/mount.ts"; + +// Cycles a fixed list of draws. +function seq(...values: number[]): Rand { + let i = 0; + return () => values[i++ % values.length]; +} + +// Deterministic LCG in [0, 1). +function lcg(seed: number): Rand { + let s = seed >>> 0; + return () => { + s = (Math.imul(s, 1664525) + 1013904223) >>> 0; + return s / 2 ** 32; + }; +} + +describe("starry-night star field", () => { + it("counts one star per 4000 px² up to the cap", () => { + assert.equal(starCount(717, 1152), 206); + assert.equal(starCount(3840, 1200), 1152); + assert.equal(starCount(3840, 2160), MAX_STARS); + assert.equal(MAX_STARS, 1500); + assert.equal(starCount(0, 800), 0); + assert.equal(starCount(800, 0), 0); + }); + + it("generates no stars for a zero-area viewport", () => { + assert.equal(generateField(0, 800, Math.random).length, 0); + }); + + it("draws x, y, size, opacity, twinkle-pick, period, phase in that order", () => { + const [low] = generateField(800, 600, seq(0, 0, 0, 0, 0, 0, 0)); + assert.deepEqual(low, { x: 0, y: 0, size: 1, opacity: 0.5, twinkle: { period: 4000, phase: 0 } }); + const [high] = generateField(800, 600, seq(0.9999)); + assert.ok(high.x < 0.99 && high.y < 0.99); + assert.equal(high.size, 2); + assert.ok(high.opacity < 1); + assert.equal(high.twinkle, null); + }); + + it("keeps generated stars in range with a fifth of them twinkling", () => { + const stars: Star[] = []; + const rand = lcg(42); + while (stars.length < 10_000) stars.push(...generateField(3840, 2160, rand)); + let twinkling = 0; + for (const s of stars) { + assert.ok(s.x >= 0 && s.x < 0.99, `x ${s.x}`); + assert.ok(s.y >= 0 && s.y < 0.99, `y ${s.y}`); + assert.ok(s.opacity >= 0.5 && s.opacity < 1, `opacity ${s.opacity}`); + assert.ok(s.size === 1 || s.size === 2); + if (s.twinkle) twinkling++; + } + const share = twinkling / stars.length; + assert.ok(Math.abs(share - 0.2) <= 0.02, `twinkle share ${share}`); + }); + + it("caps the canvas scale and treats invalid ratios as 1", () => { + assert.equal(canvasScale(1), 1); + assert.equal(canvasScale(1.5), 1.5); + assert.equal(canvasScale(3), 2); + assert.equal(canvasScale(Number.NaN), 1); + assert.equal(canvasScale(0), 1); + assert.equal(canvasScale(-2), 1); + }); + + it("rounds backing-store sizes", () => { + assert.deepEqual(backingSize(717, 1152, 1.25), { width: 896, height: 1440 }); + }); + + it("snaps odd diameters to half pixels and even ones to whole pixels", () => { + const rand = lcg(7); + for (const star of generateField(717, 1152, rand)) { + const { cx, cy, diameter } = placeStar(star, 717, 1152, 1.5); + assert.equal(diameter, star.size === 1 ? 2 : 3); + const frac = diameter % 2 === 1 ? 0.5 : 0; + assert.equal(cx - Math.floor(cx), frac, `cx ${cx}`); + assert.equal(cy - Math.floor(cy), frac, `cy ${cy}`); + assert.ok(Math.abs(cx - star.x * 717 * 1.5) <= 1); + assert.ok(Math.abs(cy - star.y * 1152 * 1.5) <= 1); + } + const tiny = placeStar({ x: 0.5, y: 0.5, size: 1, opacity: 1, twinkle: null }, 100, 100, 0.4); + assert.equal(tiny.diameter, 1); + }); +}); + +describe("starry-night twinkle", () => { + it("holds full glow for the first fifth and none from 40% to 80%", () => { + for (const u of [0, 0.1, 0.199]) assert.equal(twinkleEnvelope(u), 1, `u ${u}`); + for (const u of [0.4, 0.6, 0.799]) assert.equal(twinkleEnvelope(u), 0, `u ${u}`); + }); + + it("fades out and back in monotonically", () => { + const samples = (from: number, to: number) => + Array.from({ length: 21 }, (_, i) => twinkleEnvelope(from + ((to - from) * (i + 1)) / 22)); + const out = samples(0.2, 0.4); + const back = samples(0.8, 1); + for (let i = 1; i < 21; i++) { + assert.ok(out[i] < out[i - 1], `fade out at ${i}`); + assert.ok(back[i] > back[i - 1], `fade in at ${i}`); + } + }); + + it("eases the fades instead of ramping linearly", () => { + assert.ok(Math.abs(twinkleEnvelope(0.25) - 0.75) > 0.05); + }); + + it("is continuous at the wraparound and reduces any input mod 1", () => { + assert.ok(Math.abs(twinkleEnvelope(0.99999) - twinkleEnvelope(0)) < 1e-3); + assert.equal(twinkleEnvelope(1.1), twinkleEnvelope(0.1)); + assert.ok(Math.abs(twinkleEnvelope(-0.7) - twinkleEnvelope(0.3)) < 1e-9); + }); + + it("dims the dot to TWINKLE_DOT_MIN of its base opacity at zero glow", () => { + assert.equal(dotAlpha(0.8, 1), 0.8); + assert.ok(Math.abs(dotAlpha(0.8, 0) - 0.8 * TWINKLE_DOT_MIN) < 1e-9); + }); + + it("evaluates glow from the star's own period and phase at any time", () => { + const glow = twinkleGlow({ period: 5000, phase: 1000 }, 3_600_000); + assert.ok(glow >= 0 && glow <= 1); + assert.equal(glow, twinkleEnvelope(((3_600_000 + 1000) % 5000) / 5000)); + }); + + it("takes separate draws for each twinkling star's period and phase", () => { + const counting = (value: number) => { + let draws = 0; + const rand: Rand = () => { + draws++; + return value; + }; + return { rand, draws: () => draws }; + }; + // 80 × 50 px is exactly one star. + const plain = counting(0.9); + assert.equal(generateField(80, 50, plain.rand)[0].twinkle, null); + const twinkling = counting(0.1); + const [star] = generateField(80, 50, twinkling.rand); + assert.ok(star.twinkle); + assert.equal(twinkling.draws() - plain.draws(), 2); + assert.ok(star.twinkle.period >= 4000 && star.twinkle.period <= 6000); + assert.ok(star.twinkle.phase >= 0 && star.twinkle.phase < star.twinkle.period); + }); +}); + +describe("starry-night shooting stars", () => { + it("launches from above the top edge or past the right edge", () => { + // The top-edge offset draw is scaled to 0–90% of the width. + const top = pickLaunch(800, 600, seq(0.5, 0.5 / 0.9)); + assert.ok(Math.abs(top.x - 400) < 1e-9); + assert.equal(top.y, -4); + assert.deepEqual(pickLaunch(800, 600, seq(0.75, 0.5)), { x: 804, y: 150 }); + }); + + it("splits launches 75/25 within the original ranges", () => { + const rand = lcg(11); + let topCount = 0; + for (let i = 0; i < 1000; i++) { + const l = pickLaunch(800, 600, rand); + if (l.y === -4) { + topCount++; + assert.ok(l.x >= 80 && l.x <= 800, `top x ${l.x}`); + } else { + assert.equal(l.x, 804); + assert.ok(l.y >= 0 && l.y <= 300, `right y ${l.y}`); + } + } + assert.ok(Math.abs(topCount / 1000 - 0.75) <= 0.04, `top share ${topCount / 1000}`); + }); + + it("flies until the head leaves the viewport, plus the tail", () => { + const expected = Math.min(400 * Math.SQRT2, (1152 + 4) * Math.SQRT2) + 300; + assert.ok(Math.abs(flightDistance({ x: 400, y: -4 }, 717, 1152) - expected) < 1e-9); + }); + + it("puts the head on the left or bottom edge exactly when the tail starts clearing", () => { + const rand = lcg(5); + for (const [w, h] of [ + [717, 1152], + [3840, 1200], + [800, 600], + ]) { + for (let i = 0; i < 200; i++) { + const launch = pickLaunch(w, h, rand); + const d = flightDistance(launch, w, h) - 300; + const at = (k: number) => ({ x: launch.x - k / Math.SQRT2, y: launch.y + k / Math.SQRT2 }); + const end = at(d); + assert.ok(Math.abs(end.x) < 1e-6 || Math.abs(end.y - h) < 1e-6, `end ${end.x},${end.y}`); + const before = at(d * 0.99); + assert.ok(before.x > 0 && before.y < h); + } + } + }); + + it("derives the duration from a speed in [250, 500] px/s", () => { + const slow = planFlight(800, 600, seq(0.1, 0.5, 0)); + assert.equal(slow.durationMs, (slow.distance / 250) * 1000); + const fast = planFlight(800, 600, seq(0.1, 0.5, 1 - 1e-12)); + assert.ok(Math.abs(fast.durationMs - (fast.distance / 500) * 1000) < 1e-6); + assert.equal(slow.distance, flightDistance(slow.launch, 800, 600)); + }); + + it("delays only by whole seconds from 0 to 6", () => { + assert.equal(firstDelayMs(seq(0)), 0); + assert.equal(firstDelayMs(seq(0.999)), 6000); + const rand = lcg(3); + for (let i = 0; i < 100; i++) assert.equal(firstDelayMs(rand) % 1000, 0); + }); + + it("keeps the original rotation and opacity shape", () => { + assert.deepEqual(flightKeyframes(1000), [ + { transform: "rotate(315deg) translateX(0)", opacity: 1, offset: 0 }, + { opacity: 1, offset: 0.7 }, + { transform: "rotate(315deg) translateX(-1000px)", opacity: 0, offset: 1 }, + ]); + }); +}); + +describe("starry-night motion state", () => { + it("suspends when hidden or empty, else goes static under reduced motion", () => { + const cases: [boolean, boolean, boolean, string][] = [ + // visible, reducedMotion, zeroArea, expected + [true, false, false, "animating"], + [true, true, false, "static"], + [true, false, true, "suspended"], + [true, true, true, "suspended"], + [false, false, false, "suspended"], + [false, true, false, "suspended"], + [false, false, true, "suspended"], + [false, true, true, "suspended"], + ]; + for (const [visible, reducedMotion, zero, expected] of cases) { + const size = zero ? { width: 0, height: 600 } : { width: 800, height: 600 }; + assert.equal( + motionState({ visible, reducedMotion, ...size }), + expected, + `${visible}/${reducedMotion}/${zero}`, + ); + } + assert.equal(motionState({ visible: true, reducedMotion: false, width: 800, height: 0 }), "suspended"); + }); +}); + +// ---- Fakes for the renderer ------------------------------------------- + +class FakeFrames { + now = 0; + private nextId = 1; + private callbacks = new Map void>(); + requests = 0; + request = (cb: (t: number) => void) => { + this.requests++; + const id = this.nextId++; + this.callbacks.set(id, cb); + return id; + }; + cancel = (id: number) => { + this.callbacks.delete(id); + }; + get pending() { + return this.callbacks.size; + } + tick(dt = 1000 / 120) { + this.now += dt; + const due = [...this.callbacks.values()]; + this.callbacks.clear(); + for (const cb of due) cb(this.now); + } + ticks(n: number, dt = 1000 / 120) { + for (let i = 0; i < n; i++) this.tick(dt); + } +} + +class FakeTimers { + now = 0; + private nextId = 1; + private timers = new Map void; at: number }>(); + set = (fn: () => void, ms: number) => { + const id = this.nextId++; + this.timers.set(id, { fn, at: this.now + ms }); + return id; + }; + clear = (id: number) => { + this.timers.delete(id); + }; + get pending() { + return this.timers.size; + } + delays() { + return [...this.timers.values()].map((t) => t.at - this.now); + } + advance(ms: number) { + const end = this.now + ms; + for (;;) { + const next = [...this.timers.entries()].sort((a, b) => a[1].at - b[1].at)[0]; + if (!next || next[1].at > end) break; + this.timers.delete(next[0]); + this.now = next[1].at; + next[1].fn(); + } + this.now = end; + } +} + +interface Op { + op: string; + args: unknown[]; + alpha: number; + fill: unknown; + t: number; +} + +function fakeContext(canvas: HTMLCanvasElement, clock: { now: number }) { + const ops: Op[] = []; + const record = + (op: string) => + (...args: unknown[]) => { + ops.push({ op, args, alpha: ctx.globalAlpha, fill: ctx.fillStyle, t: clock.now }); + }; + const ctx = { + canvas, + ops, + globalAlpha: 1, + fillStyle: "#000" as unknown, + clearRect: record("clearRect"), + fillRect: record("fillRect"), + beginPath: record("beginPath"), + arc: record("arc"), + fill: record("fill"), + drawImage: record("drawImage"), + setTransform: record("setTransform"), + createRadialGradient: (...args: unknown[]) => { + const stops: [number, string][] = []; + ops.push({ op: "createRadialGradient", args, alpha: ctx.globalAlpha, fill: stops, t: clock.now }); + return { stops, addColorStop: (o: number, c: string) => stops.push([o, c]) }; + }, + }; + return ctx; +} +type FakeCtx = ReturnType; + +function setupSky(opts: { + viewport?: Viewport; + visible?: boolean; + reducedMotion?: boolean; + colors?: SkyColors; + animate?: SkyDeps["animate"]; + rand?: Rand; +}) { + const frames = new FakeFrames(); + const timers = new FakeTimers(); + const vp: Viewport = opts.viewport ?? { width: 800, height: 600, dpr: 1 }; + const colors: SkyColors = opts.colors ?? { star: "#aabbcc", glow: "#112233" }; + const contexts = new Map(); + const sprites: HTMLCanvasElement[] = []; + let reads = 0; + const container = document.createElement("div"); + container.className = "starrynight-bg-container"; + document.body.appendChild(container); + const deps: SkyDeps = { + container, + rand: opts.rand ?? lcg(1), + viewport: () => ({ ...vp }), + getContext: (canvas) => { + let c = contexts.get(canvas); + if (!c) contexts.set(canvas, (c = fakeContext(canvas, frames))); + return c as unknown as CanvasRenderingContext2D; + }, + createCanvas: () => { + const c = document.createElement("canvas"); + sprites.push(c); + return c; + }, + requestFrame: frames.request, + cancelFrame: frames.cancel, + setTimer: timers.set, + clearTimer: timers.clear, + animate: + opts.animate ?? (() => ({ play() {}, pause() {}, cancel() {}, onfinish: null }) satisfies AnimationHandle), + readColors: () => { + reads++; + return { ...colors }; + }, + }; + const sky = createSky(deps, { visible: opts.visible ?? true, reducedMotion: opts.reducedMotion ?? false }); + const canvas = (cls: string) => container.querySelector(`canvas.${cls}`)!; + const ctxOf = (cls: string) => deps.getContext(canvas(cls)) as unknown as FakeCtx; + const staticCtx = () => ctxOf("starrynight-static"); + const twinkleCtx = () => ctxOf("starrynight-twinkle"); + const dots = (c: FakeCtx) => c.ops.filter((o) => o.op === "fillRect" || o.op === "arc"); + // A static pass starts with a whole-canvas clear. + const staticPasses = () => staticCtx().ops.filter((o) => o.op === "clearRect").length; + // Every twinkle batch redraws every twinkling dot; glows at zero are skipped. + const batchTimes = () => new Set(dots(twinkleCtx()).map((o) => o.t)); + // Advance timers and frames together, as a browser would. + const run = (n: number, dt = 1000 / 120) => { + for (let i = 0; i < n; i++) { + timers.advance(dt); + frames.tick(dt); + } + }; + return { + sky, + deps, + run, + frames, + timers, + vp, + colors, + sprites, + container, + reads: () => reads, + canvas, + staticCtx, + twinkleCtx, + dots, + staticPasses, + batchTimes, + }; +} + +describe("starry-night canvas sky", () => { + it("appends two canvases and a color sentinel", () => { + const t = setupSky({}); + assert.ok(t.canvas("starrynight-static")); + assert.ok(t.canvas("starrynight-twinkle")); + assert.equal(t.container.querySelectorAll("span.starrynight-sentinel").length, 1); + }); + + it("draws the static layer once and caps twinkle batches (AC21)", () => { + const t = setupSky({ viewport: { width: 3840, height: 1200, dpr: 1 } }); + t.run(120); + assert.equal(t.staticPasses(), 1); + const batches = t.batchTimes(); + assert.ok(batches.size <= TWINKLE_FPS, `batches ${batches.size}`); + assert.ok(batches.size >= TWINKLE_FPS - 4, `batches ${batches.size}`); + const first = Math.min(...batches); + const twinkling = t.dots(t.twinkleCtx()).filter((o) => o.t === first).length; + assert.ok(twinkling > 0); + assert.equal(t.dots(t.staticCtx()).length + twinkling, starCount(3840, 1200)); + }); + + it("requests a frame only when a twinkle batch is due", () => { + const t = setupSky({ viewport: { width: 3840, height: 1200, dpr: 1 } }); + t.run(120); + assert.ok(t.frames.requests <= TWINKLE_FPS + 1, `requests ${t.frames.requests}`); + assert.ok(t.batchTimes().size >= TWINKLE_FPS - 6, `batches ${t.batchTimes().size}`); + }); + + it("gives square dots the light of the original round 1–2 px stars", () => { + const t = setupSky({}); + t.frames.tick(); + const alphas = t + .staticCtx() + .ops.filter((o) => o.op === "fillRect") + .map((o) => o.alpha); + assert.ok(alphas.length > 0); + // Base opacity is in [0.5, 1); a round dot covers π/4 of its square. + for (const a of alphas) assert.ok(a >= (0.5 * Math.PI) / 4 - 1e-9 && a < Math.PI / 4, `alpha ${a}`); + }); + + it("regenerates at most once per frame while resizing, then once when settled (AC10)", () => { + const t = setupSky({}); + t.frames.tick(); + assert.equal(t.staticPasses(), 1); + t.vp.width = 900; + t.vp.height = 700; + for (let i = 0; i < 10; i++) t.sky.resize(); + t.frames.tick(); + assert.equal(t.staticPasses(), 2); + assert.equal(t.canvas("starrynight-static").width, 900); + t.frames.ticks(5); + assert.equal(t.staticPasses(), 2); + t.timers.advance(RESIZE_SETTLE_MS); + t.frames.tick(); + assert.equal(t.staticPasses(), 3); + t.frames.ticks(5); + assert.equal(t.staticPasses(), 3); + }); + + it("keeps the field when the settle pass finds the size unchanged", () => { + const t = setupSky({}); + t.frames.tick(); + t.vp.width = 900; + t.sky.resize(); + t.frames.tick(); + const rects = (time: number) => + t + .staticCtx() + .ops.filter((o) => o.op === "fillRect" && o.t === time) + .map((o) => o.args.join(",")); + const resized = rects(t.frames.now); + t.timers.advance(RESIZE_SETTLE_MS); + t.frames.tick(); + assert.equal(t.staticPasses(), 3); + assert.deepEqual(rects(t.frames.now), resized); + }); + + it("resizes backing stores and rebuilds the glow sprite on a DPR change (AC23)", () => { + const t = setupSky({}); + t.frames.tick(); + const spriteBefore = t.sprites.at(-1)!; + const widthBefore = spriteBefore.width; + t.vp.dpr = 1.5; + t.sky.resize(); + t.frames.tick(); + const expected = backingSize(800, 600, 1.5); + for (const cls of ["starrynight-static", "starrynight-twinkle"]) { + assert.equal(t.canvas(cls).width, expected.width); + assert.equal(t.canvas(cls).height, expected.height); + } + const spriteAfter = t.sprites.at(-1)!; + assert.ok(spriteAfter !== spriteBefore || spriteAfter.width !== widthBefore); + assert.ok(spriteAfter.width > widthBefore); + }); + + it("re-reads colors only on notification, coalesced, and waits while hidden (AC11)", () => { + const t = setupSky({}); + assert.equal(t.reads(), 1); + t.frames.tick(); + t.colors.star = "#ff0000"; + t.sky.colorsChanged(); + t.sky.colorsChanged(); + t.sky.colorsChanged(); + assert.equal(t.reads(), 1); + t.frames.tick(); + assert.equal(t.reads(), 2); + assert.equal(t.staticPasses(), 2); + const now = t.frames.now; + const fills = t.staticCtx().ops.filter((o) => o.op === "fillRect" && o.t === now); + assert.ok(fills.length > 0 && fills.every((o) => o.fill === "#ff0000")); + + t.sky.setVisible(false); + t.colors.star = "#00ff00"; + t.sky.colorsChanged(); + t.frames.ticks(3); + t.timers.advance(1000); + assert.equal(t.reads(), 2); + assert.equal(t.staticPasses(), 2); + t.sky.setVisible(true); + t.frames.tick(); + assert.equal(t.reads(), 3); + assert.equal(t.staticPasses(), 3); + }); + + it("stops twinkling and stops re-arming frames while hidden (AC12)", () => { + const t = setupSky({}); + t.run(10); + t.sky.setVisible(false); + const before = t.twinkleCtx().ops.length; + t.run(30); + assert.equal(t.twinkleCtx().ops.length, before); + assert.equal(t.frames.pending, 0); + }); + + it("draws twinkling stars once without glow under reduced motion (AC13)", () => { + const t = setupSky({}); + t.run(10); + t.sky.setReducedMotion(true); + const before = t.twinkleCtx().ops.length; + t.run(30); + const after = t.twinkleCtx().ops.slice(before); + assert.ok(after.length > 0); + assert.equal(after.filter((o) => o.op === "drawImage").length, 0); + assert.ok(t.dots({ ops: after } as FakeCtx).length > 0); + assert.equal(t.frames.pending, 0); + t.sky.setVisible(false); + t.sky.setVisible(true); + t.run(30); + assert.equal( + t + .twinkleCtx() + .ops.slice(before) + .filter((o) => o.op === "drawImage").length, + 0, + ); + assert.equal(t.frames.pending, 0); + }); + + it("starts static when created under reduced motion (AC13)", () => { + const t = setupSky({ reducedMotion: true }); + t.frames.ticks(5); + assert.ok(t.dots(t.twinkleCtx()).length > 0); + assert.equal(t.twinkleCtx().ops.filter((o) => o.op === "drawImage").length, 0); + assert.equal(t.frames.pending, 0); + }); + + it("draws nothing for a zero-area viewport and recovers on resize (AC22)", () => { + const t = setupSky({ viewport: { width: 0, height: 800, dpr: 1 } }); + t.frames.ticks(5); + assert.equal(t.dots(t.staticCtx()).length + t.dots(t.twinkleCtx()).length, 0); + t.vp.width = 800; + t.vp.height = 600; + t.sky.resize(); + t.frames.tick(); + const now = t.frames.now; + const twinkling = t.dots(t.twinkleCtx()).filter((o) => o.t === now).length; + assert.equal(t.dots(t.staticCtx()).length + twinkling, starCount(800, 600)); + }); + + it("draws the field the first time a hidden start becomes visible (Review Focus 1)", () => { + const t = setupSky({ visible: false, viewport: { width: 717, height: 1152, dpr: 1 } }); + t.frames.ticks(5); + t.timers.advance(1000); + assert.equal(t.staticCtx().ops.length + t.twinkleCtx().ops.length, 0); + assert.notEqual(t.canvas("starrynight-static").width, 717); + t.sky.setVisible(true); + t.frames.tick(); + assert.equal(t.canvas("starrynight-static").width, 717); + assert.equal(t.canvas("starrynight-static").height, 1152); + assert.ok(t.dots(t.staticCtx()).length > 0); + }); + + it("falls back to white when the palette has no star colors (Review Focus 2)", () => { + const t = setupSky({ colors: { star: "", glow: "" } }); + t.frames.tick(); + const fills = t.dots(t.staticCtx()).map((o) => o.fill); + assert.ok(fills.length > 0 && fills.every((f) => f === FALLBACK_COLOR)); + const sprite = t.deps.getContext(t.sprites.at(-1)!) as unknown as { shadowColor: string }; + assert.equal(sprite.shadowColor, FALLBACK_COLOR); + }); + + it("recolors the static sky under reduced motion without starting animation (Review Focus 3)", () => { + const t = setupSky({ reducedMotion: true }); + t.frames.tick(); + t.colors.star = "#123456"; + t.sky.colorsChanged(); + t.frames.tick(); + const now = t.frames.now; + const fills = t.dots(t.staticCtx()).filter((o) => o.t === now); + assert.ok(fills.length > 0 && fills.every((o) => o.fill === "#123456")); + assert.equal(t.frames.pending, 0); + assert.equal(t.twinkleCtx().ops.filter((o) => o.op === "drawImage").length, 0); + }); + + it("draws one batch after a long hidden gap, with alphas in range (Review Focus 4)", () => { + const t = setupSky({}); + t.run(10); + t.sky.setVisible(false); + t.sky.setVisible(true); + const before = t.batchTimes().size; + t.frames.tick(3_600_000); + assert.equal(t.batchTimes().size, before + 1); + t.frames.tick(); + assert.equal(t.batchTimes().size, before + 1); + for (const c of [t.staticCtx(), t.twinkleCtx()]) { + for (const o of c.ops) assert.ok(o.alpha >= 0 && o.alpha <= 1, `alpha ${o.alpha}`); + } + }); +}); + +// ---- Shooting stars ---------------------------------------------------- + +class FakeAnimation implements AnimationHandle { + onfinish: (() => void) | null = null; + state: "running" | "paused" | "cancelled" | "finished" = "running"; + readonly el: HTMLElement; + readonly keyframes: Keyframe[]; + readonly options: KeyframeAnimationOptions; + constructor(el: HTMLElement, keyframes: Keyframe[], options: KeyframeAnimationOptions) { + this.el = el; + this.keyframes = keyframes; + this.options = options; + } + play() { + this.state = "running"; + } + pause() { + this.state = "paused"; + } + cancel() { + this.state = "cancelled"; + } + finish() { + this.state = "finished"; + this.onfinish?.(); + } +} + +function setupShooting(opts: Parameters[0] = {}) { + const flights: FakeAnimation[] = []; + const t = setupSky({ + ...opts, + animate: (el, keyframes, options) => { + const a = new FakeAnimation(el, keyframes, options); + flights.push(a); + return a; + }, + }); + const live = () => flights.filter((f) => f.state === "running" || f.state === "paused"); + const stars = () => [...t.container.querySelectorAll("span.shootingstar")]; + return { ...t, flights, live, stars }; +} + +// The distance a flight was given, read back from its last keyframe. +const flownDistance = (f: FakeAnimation) => + Number(/translateX\(-([\d.e+-]+)px\)/.exec(String(f.keyframes[2].transform))![1]); +const launchOf = (f: FakeAnimation) => ({ + x: Number.parseFloat(f.el.style.left), + y: Number.parseFloat(f.el.style.top), +}); + +describe("starry-night shooting stars on screen", () => { + it("flies four independent stars along exit-aware paths (AC8)", () => { + const t = setupShooting({ viewport: { width: 717, height: 1152, dpr: 1 } }); + assert.equal(t.stars().length, 4); + t.timers.advance(6000); + assert.equal(t.flights.length, 4); + assert.equal(new Set(t.flights.map((f) => f.el)).size, 4); + for (const f of t.flights) { + assert.ok(f.el.classList.contains("shootingstar")); + const d = flownDistance(f); + assert.deepEqual(f.keyframes, flightKeyframes(d)); + assert.ok(Math.abs(d - flightDistance(launchOf(f), 717, 1152)) < 1e-6); + const duration = Number(f.options.duration); + assert.ok(duration >= (d / 500) * 1000 - 1e-6 && duration <= (d / 250) * 1000 + 1e-6); + assert.equal(f.options.easing, "linear"); + assert.match(f.el.style.left, /px$/); + assert.match(f.el.style.top, /px$/); + } + }); + + it("delays only the first flight and relaunches straight from finish (AC9)", () => { + const draws = [0.1, 0.5, 0.99, 0]; + const rest = lcg(9); + const t = setupShooting({ rand: () => (draws.length ? draws.shift()! : rest()) }); + assert.deepEqual( + t.timers.delays().sort((a, b) => a - b), + [0, 0, 3000, 6000], + ); + t.timers.advance(6000); + const timersBefore = t.timers.pending; + t.flights[0].finish(); + assert.equal(t.flights.length, 5); + assert.equal(t.flights[4].el, t.flights[0].el); + assert.equal(t.timers.pending, timersBefore); + + t.sky.setVisible(false); + t.flights[1].finish(); + assert.equal(t.flights.length, 5); + t.sky.setVisible(true); + t.sky.setReducedMotion(true); + const count = t.flights.length; + t.flights[2].onfinish?.(); + assert.equal(t.flights.length, count); + t.sky.setReducedMotion(false); + const after = t.flights.length; + t.sky.dispose(); + for (const f of t.flights) f.onfinish?.(); + assert.equal(t.flights.length, after); + }); + + it("lets a flight finish across a resize and uses the new size next (AC10)", () => { + const t = setupShooting(); + t.timers.advance(6000); + const first = t.flights[0]; + t.vp.width = 1600; + t.vp.height = 900; + t.sky.resize(); + assert.equal(first.state, "running"); + first.finish(); + const next = t.flights.at(-1)!; + assert.ok(Math.abs(flownDistance(next) - flightDistance(launchOf(next), 1600, 900)) < 1e-6); + }); + + it("pauses while hidden and launches a missed first flight on return (AC12)", () => { + const t = setupShooting(); + t.timers.advance(6000); + t.sky.setVisible(false); + assert.ok(t.live().every((f) => f.state === "paused")); + t.sky.setVisible(true); + assert.ok(t.live().length === 4 && t.live().every((f) => f.state === "running")); + + const h = setupShooting({ visible: false }); + h.timers.advance(6000); + assert.equal(h.flights.length, 0); + h.sky.setVisible(true); + assert.equal(h.flights.length, 4); + }); + + it("hides shooting stars under reduced motion and relaunches without delay (AC13)", () => { + const t = setupShooting(); + t.timers.advance(6000); + const flying = t.live(); + t.sky.setReducedMotion(true); + assert.ok(flying.every((f) => f.state === "cancelled")); + assert.ok(t.stars().every((el) => el.hidden)); + const timers = t.timers.pending; + t.sky.setReducedMotion(false); + assert.equal(t.live().length, 4); + assert.equal(t.timers.pending, timers); + assert.ok(t.stars().every((el) => !el.hidden)); + + const r = setupShooting({ reducedMotion: true }); + r.timers.advance(6000); + assert.equal(r.flights.length, 0); + }); + + it("launches nothing at zero area and resumes when the area returns (AC22)", () => { + const t = setupShooting({ viewport: { width: 0, height: 800, dpr: 1 } }); + t.timers.advance(6000); + assert.equal(t.flights.length, 0); + t.vp.width = 800; + t.sky.resize(); + assert.equal(t.flights.length, 4); + + t.vp.height = 0; + t.sky.resize(); + t.flights[0].finish(); + assert.equal(t.flights.length, 4); + t.vp.height = 600; + t.sky.resize(); + assert.equal(t.flights.length, 5); + }); +}); + +// ---- Mount and lifecycle ---------------------------------------------- + +type Listener = [target: object, type: string, fn: unknown]; + +class FakeMediaQueryList { + readonly media: string; + matches: boolean; + private readonly registry: Listener[]; + constructor(media: string, matches: boolean, registry: Listener[]) { + this.media = media; + this.matches = matches; + this.registry = registry; + } + addEventListener(type: string, fn: unknown) { + this.registry.push([this, type, fn]); + } + removeEventListener(type: string, fn: unknown) { + const i = this.registry.findIndex(([t, ty, f]) => t === this && ty === type && f === fn); + if (i >= 0) this.registry.splice(i, 1); + } + fire(matches: boolean) { + this.matches = matches; + for (const [t, type, fn] of this.registry.slice()) { + if (t === this && type === "change") (fn as (e: { matches: boolean }) => void)({ matches }); + } + } +} + +function setupMount(opts: { container?: boolean; waitTries?: number } = {}) { + const win = new Window({ url: "https://xpui.app.spotify.com" }); + const doc = win.document as unknown as Document; + const registry: Listener[] = []; + // Track every listener added to or removed from a happy-dom target. + let owner: object = doc; + while (!Object.hasOwn(owner, "addEventListener")) owner = Object.getPrototypeOf(owner); + const target = owner as EventTarget; + const origAdd = target.addEventListener; + const origRemove = target.removeEventListener; + target.addEventListener = function (this: object, type: string, fn: unknown, o?: unknown) { + registry.push([this, type, fn]); + return origAdd.call(this, type, fn as EventListener, o as AddEventListenerOptions); + }; + target.removeEventListener = function (this: object, type: string, fn: unknown, o?: unknown) { + const i = registry.findIndex(([t, ty, f]) => t === this && ty === type && f === fn); + if (i >= 0) registry.splice(i, 1); + return origRemove.call(this, type, fn as EventListener, o as EventListenerOptions); + }; + const restore = () => { + target.addEventListener = origAdd; + target.removeEventListener = origRemove; + }; + + if (opts.container !== false) { + const top = doc.createElement("div"); + top.className = "Root__top-container"; + doc.body.appendChild(top); + } + const frames = new FakeFrames(); + const timers = new FakeTimers(); + const queries: FakeMediaQueryList[] = []; + let colorReads = 0; + const fakeWindow = { + innerWidth: 800, + innerHeight: 600, + devicePixelRatio: 1, + addEventListener(type: string, fn: unknown) { + registry.push([fakeWindow, type, fn]); + }, + removeEventListener(type: string, fn: unknown) { + const i = registry.findIndex(([t, ty, f]) => t === fakeWindow && ty === type && f === fn); + if (i >= 0) registry.splice(i, 1); + }, + matchMedia(media: string) { + const q = new FakeMediaQueryList(media, false, registry); + queries.push(q); + return q as unknown as MediaQueryList; + }, + getComputedStyle() { + colorReads++; + return { + color: "rgb(255, 255, 255)", + backgroundColor: "rgb(255, 255, 255)", + getPropertyValue: () => "#ffffff", + } as unknown as CSSStyleDeclaration; + }, + }; + const contexts = new Map(); + const flights: FakeAnimation[] = []; + const env: MountEnv = { + document: doc, + window: fakeWindow as unknown as MountEnv["window"], + rand: lcg(1), + getContext: (canvas) => { + let c = contexts.get(canvas); + if (!c) contexts.set(canvas, (c = fakeContext(canvas, frames))); + return c as unknown as CanvasRenderingContext2D; + }, + createCanvas: () => doc.createElement("canvas") as HTMLCanvasElement, + requestFrame: frames.request, + cancelFrame: frames.cancel, + setTimer: timers.set, + clearTimer: timers.clear, + animate: (el, keyframes, options) => { + const a = new FakeAnimation(el, keyframes, options); + flights.push(a); + return a; + }, + waitTries: opts.waitTries, + }; + return { + win, + doc, + env, + frames, + timers, + queries, + registry, + flights, + restore, + colorReads: () => colorReads, + count: (selector: string) => doc.querySelectorAll(selector).length, + }; +} + +describe("starry-night mount", () => { + it("gives up within the bounded wait and creates nothing (AC24)", async () => { + const t = setupMount({ container: false, waitTries: 3 }); + try { + const handle = mountSky(t.env); + t.timers.advance(250 * 3); + assert.equal(await handle.ready, false); + assert.equal(t.count(".starrynight-bg-container"), 0); + assert.equal(t.timers.pending, 0); + } finally { + t.restore(); + } + }); + + it("settles and stays empty when disposed during the wait (AC24)", async () => { + const t = setupMount({ container: false }); + try { + const handle = mountSky(t.env); + t.timers.advance(500); + handle.dispose(); + assert.equal(await handle.ready, false); + const top = t.doc.createElement("div"); + top.className = "Root__top-container"; + t.doc.body.appendChild(top); + t.timers.advance(10_000); + t.frames.ticks(5); + assert.equal(t.count(".starrynight-bg-container"), 0); + assert.equal(t.timers.pending, 0); + } finally { + t.restore(); + } + }); + + it("leaves nothing behind after dispose (AC14)", async () => { + const t = setupMount(); + try { + const handle = mountSky(t.env); + assert.equal(await handle.ready, true); + t.frames.ticks(10); + t.timers.advance(6000); + assert.ok(t.registry.length > 0); + assert.equal(t.count(".shootingstar"), 4); + handle.dispose(); + handle.dispose(); + for (const sel of [".starrynight-bg-container", "canvas", ".starrynight-sentinel", ".shootingstar"]) { + assert.equal(t.count(sel), 0, sel); + } + assert.deepEqual( + t.registry.map(([, type]) => type), + [], + ); + assert.equal(t.frames.pending, 0); + assert.equal(t.timers.pending, 0); + assert.ok(t.flights.every((f) => f.state !== "running" && f.state !== "paused")); + } finally { + t.restore(); + } + }); + + it("ends with one backdrop after a fast disable and enable (Review Focus 5)", async () => { + const t = setupMount({ container: false }); + try { + const a = mountSky(t.env); + a.dispose(); + const b = mountSky(t.env); + const top = t.doc.createElement("div"); + top.className = "Root__top-container"; + t.doc.body.appendChild(top); + t.timers.advance(1000); + assert.equal(await a.ready, false); + assert.equal(await b.ready, true); + t.frames.ticks(3); + assert.equal(t.count(".starrynight-bg-container"), 1); + b.dispose(); + } finally { + t.restore(); + } + }); + + it("renders without per-star elements (AC5)", async () => { + const t = setupMount(); + try { + const handle = mountSky(t.env); + await handle.ready; + t.frames.ticks(5); + assert.equal(t.count(".starrynight-star"), 0); + assert.equal(t.count("canvas"), 2); + handle.dispose(); + } finally { + t.restore(); + } + }); + + it("recolors when the sentinel's transition fires", async () => { + const t = setupMount(); + try { + const handle = mountSky(t.env); + await handle.ready; + t.frames.tick(); + const reads = t.colorReads(); + const sentinel = t.doc.querySelector(".starrynight-sentinel")!; + sentinel.dispatchEvent(new t.win.Event("transitionend") as unknown as Event); + t.frames.tick(); + assert.equal(t.colorReads(), reads + 1); + handle.dispose(); + } finally { + t.restore(); + } + }); + + it("follows reduced motion and DPR media queries", async () => { + const t = setupMount(); + try { + const handle = mountSky(t.env); + await handle.ready; + t.timers.advance(6000); + const reduce = t.queries.find((q) => q.media.includes("prefers-reduced-motion"))!; + reduce.fire(true); + assert.equal(t.count(".shootingstar:not([hidden])"), 0); + const dpr = t.queries.find((q) => q.media.includes("resolution"))!; + const queriesBefore = t.queries.length; + dpr.fire(false); + assert.equal(t.queries.length, queriesBefore + 1); + handle.dispose(); + assert.equal(t.registry.length, 0); + } finally { + t.restore(); + } + }); +}); diff --git a/themes/starry-night/index.css b/themes/starry-night/index.css index 2eed9f01..e7d5a5d4 100644 --- a/themes/starry-night/index.css +++ b/themes/starry-night/index.css @@ -270,11 +270,30 @@ background-color: transparent; } -.starrynight-star { +/* Static stars and twinkling stars, drawn by mod.tsx. */ +.starrynight-static, +.starrynight-twinkle { position: absolute; + inset: 0; + width: 100%; + height: 100%; z-index: -1; - border-radius: 50%; - background-color: var(--spice-star); +} + +/* Carries the sky's star colors so a palette change fires a transition the + script can listen for. The duration is pinned so no global rule turns it + into a 0s transition, which fires no events. */ +.starrynight-sentinel { + position: absolute; + width: 0; + height: 0; + overflow: hidden; + color: var(--spice-star); + background-color: var(--spice-star-glow); + transition: + color 1ms, + background-color 1ms !important; + transition-duration: 1ms !important; } button[data-testid="cover-art-button"] { @@ -286,110 +305,6 @@ button[data-testid="cover-art-button"] { display: contents; } -@keyframes twinkle1 { - 0% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 20% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 40% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 60% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 80% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 100% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } -} - -@keyframes twinkle2 { - 0% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 20% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 40% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 60% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 80% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 100% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } -} - -@keyframes twinkle3 { - 0% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 20% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 40% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 60% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 80% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 100% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } -} - -@keyframes twinkle4 { - 0% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 20% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } - - 40% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 60% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 80% { - box-shadow: 0px 0px 8px 2px var(--spice-star-glow); - } - - 100% { - box-shadow: 0px 0px -8px 2px var(--spice-star-glow); - } -} - @keyframes spin { from { transform: rotate(0deg); @@ -415,8 +330,8 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI height: 4px; background: var(--spice-shooting-star); border-radius: 50%; - animation: animate 3s linear; - left: initial; + top: 0; + left: 0; z-index: -1; box-shadow: 0 0 0 4px rgba(var(--spice-rgb-shooting-star-glow), 0.1), @@ -433,19 +348,3 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI height: 1px; background: linear-gradient(90deg, var(--spice-shooting-star), transparent); } - -@keyframes animate { - 0% { - transform: rotate(315deg) translateX(0); - opacity: 1; - } - - 70% { - opacity: 1; - } - - 100% { - transform: rotate(315deg) translateX(-1500px); - opacity: 0; - } -} diff --git a/themes/starry-night/logic.ts b/themes/starry-night/logic.ts new file mode 100644 index 00000000..b18311b2 --- /dev/null +++ b/themes/starry-night/logic.ts @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2026 spicetify + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +// Pure sky math: no DOM, no globals. Everything random takes an injected +// source so tests can seed it. + +// One star per this much viewport area (CSS px²), capped for huge windows. +export const STAR_AREA_PER_STAR = 4000; +export const MAX_STARS = 1500; +export const TWINKLE_CHANCE = 1 / 5; +export const TWINKLE_PERIOD_MIN = 4000; +export const TWINKLE_PERIOD_MAX = 6000; +// Twinkle redraws per second, and how far a twinkling dot dims (as a share +// of its base opacity) while its glow is off. +export const TWINKLE_FPS = 20; +export const TWINKLE_DOT_MIN = 0.7; +export const MAX_CANVAS_DPR = 2; +export const SHOOTING_STAR_COUNT = 4; +export const SHOOTING_SPEED_MIN = 250; +export const SHOOTING_SPEED_MAX = 500; +export const SHOOTING_TAIL = 300; +export const GLOW_BLUR = 8; +export const GLOW_SPREAD = 2; +export const FALLBACK_COLOR = "#FFFFFF"; + +/** Uniform in [0, 1). */ +export type Rand = () => number; +/** Period in ms; phase in [0, period). */ +export interface Twinkle { + period: number; + phase: number; +} +/** x and y are fractions of the viewport in [0, 0.99). */ +export interface Star { + x: number; + y: number; + size: 1 | 2; + opacity: number; + twinkle: Twinkle | null; +} + +export function starCount(width: number, height: number): number { + if (!(width > 0) || !(height > 0)) return 0; + return Math.min(Math.floor((width * height) / STAR_AREA_PER_STAR), MAX_STARS); +} + +// Draw order per star: x, y, size, opacity, twinkle-pick, then period and +// phase only for twinkling stars. +export function generateField(width: number, height: number, rand: Rand): Star[] { + const count = starCount(width, height); + const stars: Star[] = []; + for (let i = 0; i < count; i++) { + const x = rand() * 0.99; + const y = rand() * 0.99; + const size = rand() < 0.5 ? 1 : 2; + const opacity = 0.5 + rand() * 0.5; + let twinkle: Twinkle | null = null; + if (rand() < TWINKLE_CHANCE) { + const period = TWINKLE_PERIOD_MIN + rand() * (TWINKLE_PERIOD_MAX - TWINKLE_PERIOD_MIN); + twinkle = { period, phase: rand() * period }; + } + stars.push({ x, y, size, opacity, twinkle }); + } + return stars; +} + +export function canvasScale(dpr: number): number { + if (!Number.isFinite(dpr) || dpr <= 0) return 1; + return Math.min(dpr, MAX_CANVAS_DPR); +} + +export function backingSize(cssWidth: number, cssHeight: number, scale: number): { width: number; height: number } { + return { width: Math.round(cssWidth * scale), height: Math.round(cssHeight * scale) }; +} + +// Smoothstep: eased, monotonic on [0, 1]. +const ease = (t: number) => t * t * (3 - 2 * t); + +// Glow over one cycle, u reduced mod 1: full for 20%, eased fade out for +// 20%, off for 40%, eased fade in for 20%. Matches the original keyframes. +export function twinkleEnvelope(u: number): number { + const p = u - Math.floor(u); + if (p < 0.2) return 1; + if (p < 0.4) return 1 - ease((p - 0.2) / 0.2); + if (p < 0.8) return 0; + return ease((p - 0.8) / 0.2); +} + +export function twinkleGlow(twinkle: Twinkle, timeMs: number): number { + return twinkleEnvelope( + ((((timeMs + twinkle.phase) % twinkle.period) + twinkle.period) % twinkle.period) / twinkle.period, + ); +} + +export function dotAlpha(baseOpacity: number, glow: number): number { + return baseOpacity * (TWINKLE_DOT_MIN + (1 - TWINKLE_DOT_MIN) * glow); +} + +// An odd diameter centers on a half pixel and an even one on a whole pixel, +// so the dot covers whole backing pixels and stays crisp at fractional DPR. +const snap = (value: number, diameter: number) => (diameter % 2 === 1 ? Math.floor(value) + 0.5 : Math.round(value)); + +/** Center and diameter in backing pixels. */ +export function placeStar( + star: Star, + cssWidth: number, + cssHeight: number, + scale: number, +): { cx: number; cy: number; diameter: number } { + const diameter = Math.max(1, Math.round(star.size * scale)); + return { + cx: snap(star.x * cssWidth * scale, diameter), + cy: snap(star.y * cssHeight * scale, diameter), + diameter, + }; +} + +/** Head position in CSS px, viewport coordinates. */ +export interface Launch { + x: number; + y: number; +} +export interface Flight { + launch: Launch; + distance: number; + durationMs: number; +} + +// As in the original pen: 75% enter just above the top edge, offset 0–90% +// of the width from the right; 25% enter just past the right edge in the +// top half. +export function pickLaunch(width: number, height: number, rand: Rand): Launch { + if (rand() < 0.75) return { x: width * (1 - rand() * 0.9), y: -4 }; + return { x: width + 4, y: rand() * 0.5 * height }; +} + +// The head travels 45° down-left, so it leaves through the left edge after +// x·√2 or through the bottom after (height − y)·√2. Adding the tail length +// lets the streak clear the screen before the flight ends. +export function flightDistance(launch: Launch, width: number, height: number): number { + return Math.min(launch.x * Math.SQRT2, (height - launch.y) * Math.SQRT2) + SHOOTING_TAIL; +} + +export function planFlight(width: number, height: number, rand: Rand): Flight { + const launch = pickLaunch(width, height, rand); + const distance = flightDistance(launch, width, height); + const speed = SHOOTING_SPEED_MIN + rand() * (SHOOTING_SPEED_MAX - SHOOTING_SPEED_MIN); + return { launch, distance, durationMs: (distance / speed) * 1000 }; +} + +export function firstDelayMs(rand: Rand): number { + return Math.floor(rand() * 7) * 1000; +} + +export function flightKeyframes(distance: number): Keyframe[] { + return [ + { transform: "rotate(315deg) translateX(0)", opacity: 1, offset: 0 }, + { opacity: 1, offset: 0.7 }, + { transform: `rotate(315deg) translateX(-${distance}px)`, opacity: 0, offset: 1 }, + ]; +} + +export type MotionState = "animating" | "static" | "suspended"; + +// The single switch for what runs. Hidden or empty suspends everything; +// reduced motion wins over resuming. +export function motionState(s: { + visible: boolean; + reducedMotion: boolean; + width: number; + height: number; +}): MotionState { + if (!s.visible || !(s.width > 0) || !(s.height > 0)) return "suspended"; + return s.reducedMotion ? "static" : "animating"; +} diff --git a/themes/starry-night/metadata.json b/themes/starry-night/metadata.json index 03c66e1c..96fab513 100644 --- a/themes/starry-night/metadata.json +++ b/themes/starry-night/metadata.json @@ -2,7 +2,7 @@ "name": "Starry Night", "id": "starry-night", "kind": "theme", - "version": "0.1.6", + "version": "0.2.0", "authors": ["Brandon Chen", "Julissa Laignelet"], "description": "Night sky backdrop with twinkling stars and shooting stars, in seven skies", "entries": { diff --git a/themes/starry-night/mod.tsx b/themes/starry-night/mod.tsx index 0d3ddded..ab7162d8 100644 --- a/themes/starry-night/mod.tsx +++ b/themes/starry-night/mod.tsx @@ -10,61 +10,14 @@ import { type ModuleRuntimeContext, client } from "/modules/stdlib/mod.ts"; -// One star per this much backdrop area, at either 1px or 2px across. -const STAR_AREA_PER_STAR = 4000; -const TWINKLE_CHANCE = 1 / 5; -const TWINKLE_VARIANTS = 4; -const SHOOTING_STAR_COUNT = 4; +import { mountSky } from "./mount.ts"; +import type { AnimationHandle } from "./sky.ts"; + // The width the client persists for the right sidebar. The playbar tracks // the sidebar so the two stacked panels share an edge. const PANEL_WIDTH_KEY = `${client.platform.username}:panel-width`; const FALLBACK_PANEL_WIDTH = 420; -const random = (min: number, max: number) => Math.random() * (max - min) + min; - -// Shooting stars enter either from the top edge or the right edge, and are -// parked just off-screen so a delayed animation does not show a stray dot. -function placeShootingStar(star: HTMLElement): void { - if (Math.random() < 0.75) { - star.style.top = "-4px"; - star.style.right = `${random(0, 90)}%`; - } else { - star.style.top = `${random(0, 50)}%`; - star.style.right = "-4px"; - } -} - -function createStars(backdrop: HTMLElement, area: number): void { - const count = Math.floor(area / STAR_AREA_PER_STAR); - for (let i = 0; i < count; i++) { - const size = Math.random() < 0.5 ? 1 : 2; - const star = document.createElement("div"); - star.className = "starrynight-star"; - star.style.left = `${random(0, 99)}%`; - star.style.top = `${random(0, 99)}%`; - star.style.opacity = String(random(0.5, 1)); - star.style.width = `${size}px`; - star.style.height = `${size}px`; - if (Math.random() < TWINKLE_CHANCE) { - const variant = Math.floor(Math.random() * TWINKLE_VARIANTS) + 1; - star.style.setProperty("animation", `twinkle${variant} 5s infinite`, "important"); - } - backdrop.appendChild(star); - } -} - -function createShootingStars(backdrop: HTMLElement, onEnd: (star: HTMLElement) => void): void { - for (let i = 0; i < SHOOTING_STAR_COUNT; i++) { - const star = document.createElement("span"); - star.className = "shootingstar"; - placeShootingStar(star); - star.style.animationDuration = `${Math.floor(Math.random() * 3) + 3}s`; - star.style.animationDelay = `${Math.floor(Math.random() * 7)}s`; - star.addEventListener("animationend", () => onEnd(star)); - backdrop.appendChild(star); - } -} - export default async function (ctx: ModuleRuntimeContext) { let disposed = false; const timers = new Set(); @@ -91,33 +44,28 @@ export default async function (ctx: ModuleRuntimeContext) { attempt(); }); - const backdrop = document.createElement("div"); - backdrop.className = "starrynight-bg-container"; - ctx.defer(() => { disposed = true; for (const id of timers) clearTimeout(id); timers.clear(); - backdrop.remove(); }); - const topContainer = await waitFor(".Root__top-container"); - if (!topContainer || disposed) return; - topContainer.appendChild(backdrop); - - // The backdrop is a viewport-sized fixed layer. Sizing off the viewport - // rather than its own box keeps the star count right even if the theme - // stylesheet has not been adopted yet when this runs. - createStars(backdrop, window.innerWidth * window.innerHeight); - createShootingStars(backdrop, (star) => { - placeShootingStar(star); - // Restart the animation with a fresh duration: drop it, force a - // reflow so the removal takes, then let the class rule reapply. - star.style.animation = "none"; - void star.offsetWidth; - star.style.animation = ""; - star.style.setProperty("animation-duration", `${Math.floor(Math.random() * 4) + 3}s`, "important"); + // The sky owns its own frames, timers and listeners and releases them + // all on dispose. + const sky = mountSky({ + document, + window, + rand: Math.random, + getContext: (canvas) => canvas.getContext("2d"), + createCanvas: () => document.createElement("canvas"), + requestFrame: (cb) => requestAnimationFrame(cb), + cancelFrame: (id) => cancelAnimationFrame(id), + setTimer: (fn, ms) => window.setTimeout(fn, ms), + clearTimer: (id) => clearTimeout(id), + animate: (el, keyframes, options) => el.animate(keyframes, options) as AnimationHandle, }); + ctx.defer(sky.dispose); + if (!(await sky.ready) || disposed) return; // Keep the playbar the same width as the right sidebar stacked above it. const playbar = document.querySelector(".Root__now-playing-bar"); diff --git a/themes/starry-night/mount.ts b/themes/starry-night/mount.ts new file mode 100644 index 00000000..281e28f9 --- /dev/null +++ b/themes/starry-night/mount.ts @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2026 spicetify + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +// DOM discovery, event wiring and lifecycle for the sky. The browser comes +// in through MountEnv so tests can drive it with fakes. + +import { createSky, type Sky, type SkyColors, type SkyDeps } from "./sky.ts"; + +export interface MountEnv extends Omit { + document: Document; + window: Pick< + Window, + | "addEventListener" + | "removeEventListener" + | "innerWidth" + | "innerHeight" + | "devicePixelRatio" + | "matchMedia" + | "getComputedStyle" + >; + /** Default 20. */ + waitTries?: number; + /** Default 250. */ + waitIntervalMs?: number; +} + +const REDUCED_MOTION = "(prefers-reduced-motion: reduce)"; + +export function mountSky(env: MountEnv): { ready: Promise; dispose(): void } { + const { document: doc, window: win } = env; + let disposed = false; + let waitTimer: number | null = null; + let settle: (mounted: boolean) => void = () => {}; + let sky: Sky | null = null; + let backdrop: HTMLElement | null = null; + const cleanups: (() => void)[] = []; + + const listen = ( + target: Pick, + type: string, + fn: EventListener, + ) => { + target.addEventListener(type, fn); + cleanups.push(() => target.removeEventListener(type, fn)); + }; + + // A palette variable the sky cannot read comes back as "", which the + // renderer replaces with its fallback. Present ones are read resolved, + // so any color syntax the palette writes reaches the canvas as rgb(). + const readColors = (sentinel: HTMLElement): SkyColors => { + const style = win.getComputedStyle(sentinel); + const has = (name: string) => style.getPropertyValue(name).trim() !== ""; + return { + star: has("--spice-star") ? style.color : "", + glow: has("--spice-star-glow") ? style.backgroundColor : "", + }; + }; + + const mount = (top: Element) => { + backdrop = doc.createElement("div"); + backdrop.className = "starrynight-bg-container"; + top.appendChild(backdrop); + + const reduced = win.matchMedia(REDUCED_MOTION); + const visible = () => doc.visibilityState !== "hidden"; + const current = (sky = createSky( + { + ...env, + container: backdrop, + viewport: () => ({ width: win.innerWidth, height: win.innerHeight, dpr: win.devicePixelRatio }), + readColors, + }, + { visible: visible(), reducedMotion: reduced.matches }, + )); + + listen(win, "resize", () => current.resize()); + listen(doc, "visibilitychange", () => current.setVisible(visible())); + listen(reduced, "change", () => current.setReducedMotion(reduced.matches)); + + // A resolution query matches only the current ratio; re-arm it for + // the new one after every change. + let dprQuery: MediaQueryList | null = null; + const onDpr = () => { + current.resize(); + watchDpr(); + }; + const watchDpr = () => { + dprQuery?.removeEventListener("change", onDpr); + dprQuery = win.matchMedia(`(resolution: ${win.devicePixelRatio}dppx)`); + dprQuery.addEventListener("change", onDpr); + }; + watchDpr(); + cleanups.push(() => dprQuery?.removeEventListener("change", onDpr)); + + const sentinel = backdrop.querySelector(".starrynight-sentinel"); + if (sentinel) { + const recolor = () => current.colorsChanged(); + listen(sentinel, "transitionend", recolor); + listen(sentinel, "transitionrun", recolor); + } + }; + + // Bounded: the loader awaits the module, so a container that never + // appears must give up rather than hang every other module. + const ready = new Promise((resolve) => { + settle = resolve; + let left = env.waitTries ?? 20; + const attempt = () => { + waitTimer = null; + if (disposed) return resolve(false); + const top = doc.querySelector(".Root__top-container"); + if (top) { + mount(top); + return resolve(true); + } + if (left-- <= 0) return resolve(false); + waitTimer = env.setTimer(attempt, env.waitIntervalMs ?? 250); + }; + attempt(); + }); + + return { + ready, + dispose() { + if (disposed) return; + disposed = true; + if (waitTimer !== null) env.clearTimer(waitTimer); + waitTimer = null; + settle(false); + for (const cleanup of cleanups.splice(0)) cleanup(); + sky?.dispose(); + sky = null; + backdrop?.remove(); + backdrop = null; + }, + }; +} diff --git a/themes/starry-night/sky.ts b/themes/starry-night/sky.ts new file mode 100644 index 00000000..5faca13a --- /dev/null +++ b/themes/starry-night/sky.ts @@ -0,0 +1,447 @@ +/* + * Copyright (C) 2026 spicetify + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +// The sky renderer. Every browser API comes in through SkyDeps so the +// whole controller runs under tests with fakes. + +import { + backingSize, + canvasScale, + dotAlpha, + FALLBACK_COLOR, + firstDelayMs, + flightKeyframes, + GLOW_BLUR, + GLOW_SPREAD, + generateField, + motionState, + placeStar, + planFlight, + type Rand, + SHOOTING_STAR_COUNT, + type Star, + TWINKLE_FPS, + twinkleGlow, +} from "./logic.ts"; + +export interface SkyColors { + star: string; + glow: string; +} +export interface AnimationHandle { + play(): void; + pause(): void; + cancel(): void; + onfinish: (() => void) | null; +} +export interface Viewport { + width: number; + height: number; + dpr: number; +} +export interface SkyDeps { + /** `.starrynight-bg-container`, already in the DOM. */ + container: HTMLElement; + rand: Rand; + viewport(): Viewport; + getContext(canvas: HTMLCanvasElement): CanvasRenderingContext2D | null; + /** For the off-DOM glow sprites. */ + createCanvas(): HTMLCanvasElement; + requestFrame(cb: (timeMs: number) => void): number; + cancelFrame(id: number): void; + setTimer(fn: () => void, ms: number): number; + clearTimer(id: number): void; + animate(el: HTMLElement, keyframes: Keyframe[], options: KeyframeAnimationOptions): AnimationHandle; + /** May return "" for a variable the palette does not define. */ + readColors(sentinel: HTMLElement): SkyColors; +} +export interface Sky { + /** Viewport size or device pixel ratio changed. */ + resize(): void; + setVisible(visible: boolean): void; + setReducedMotion(reduce: boolean): void; + /** The sentinel's color transition fired. */ + colorsChanged(): void; + dispose(): void; +} + +// After the last resize event, regenerate once more at the final size. +export const RESIZE_SETTLE_MS = 150; +const TWINKLE_INTERVAL = 1000 / TWINKLE_FPS; + +interface Placed { + star: Star; + cx: number; + cy: number; + diameter: number; + // Alpha factor so a filled square gives off the light of the round dot + // the original theme drew (a circle covers π/4 of its square). + light: number; +} + +interface Sprite { + canvas: HTMLCanvasElement; + half: number; +} + +function drawDot(ctx: CanvasRenderingContext2D, p: Placed, alpha: number): void { + if (p.diameter <= 2) { + ctx.globalAlpha = alpha * p.light; + ctx.fillRect(p.cx - p.diameter / 2, p.cy - p.diameter / 2, p.diameter, p.diameter); + return; + } + ctx.globalAlpha = alpha; + ctx.beginPath(); + ctx.arc(p.cx, p.cy, p.diameter / 2, 0, Math.PI * 2); + ctx.fill(); +} + +/* +Pure CSS Shooting Star Animation Effect Copyright (c) 2021 by Delroy Prithvi (https://codepen.io/delroyprithvi/pen/LYyJROR) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +interface ShootingStar { + el: HTMLElement; + flight: AnimationHandle | null; + firstDelay: number | null; + // Wants to fly as soon as motion is allowed again. + pending: boolean; +} + +interface ShootingStars { + /** Apply the current visibility, reduced motion and viewport. */ + update(): void; + dispose(): void; +} + +// Four independent stars animated with the Web Animations API, which the +// client's `animation-duration: … !important` rule cannot touch. Each +// flight ends when its tail has cleared the viewport and the next one +// starts straight from the finish handler. +function createShootingStars(deps: SkyDeps, mode: () => { visible: boolean; reducedMotion: boolean }): ShootingStars { + let disposed = false; + const animating = () => motionState({ ...mode(), ...deps.viewport() }) === "animating"; + + const launch = (s: ShootingStar) => { + if (disposed) return; + if (!animating()) { + s.pending = true; + s.el.hidden = true; + return; + } + s.pending = false; + const { width, height } = deps.viewport(); + const { launch: at, distance, durationMs } = planFlight(width, height, deps.rand); + s.el.style.left = `${at.x}px`; + s.el.style.top = `${at.y}px`; + s.el.hidden = false; + const flight = deps.animate(s.el, flightKeyframes(distance), { duration: durationMs, easing: "linear" }); + s.flight = flight; + flight.onfinish = () => { + if (s.flight !== flight) return; + s.flight = null; + launch(s); + }; + }; + + const stars: ShootingStar[] = []; + for (let i = 0; i < SHOOTING_STAR_COUNT; i++) { + const el = deps.container.ownerDocument.createElement("span"); + el.className = "shootingstar"; + el.hidden = true; + deps.container.append(el); + const s: ShootingStar = { el, flight: null, firstDelay: null, pending: false }; + s.firstDelay = deps.setTimer(() => { + s.firstDelay = null; + launch(s); + }, firstDelayMs(deps.rand)); + stars.push(s); + } + + return { + update() { + if (disposed) return; + const { visible, reducedMotion } = mode(); + for (const s of stars) { + if (reducedMotion) { + if (s.flight) { + s.flight.cancel(); + s.flight = null; + s.pending = true; + } + s.el.hidden = true; + } else if (!visible) { + s.flight?.pause(); + } else if (s.flight) { + s.flight.play(); + } else if (s.pending) { + launch(s); + } + } + }, + dispose() { + if (disposed) return; + disposed = true; + for (const s of stars) { + if (s.firstDelay !== null) deps.clearTimer(s.firstDelay); + s.flight?.cancel(); + s.flight = null; + s.el.remove(); + } + }, + }; +} + +export function createSky(deps: SkyDeps, initial: { visible: boolean; reducedMotion: boolean }): Sky { + const doc = deps.container.ownerDocument; + const staticCanvas = doc.createElement("canvas"); + staticCanvas.className = "starrynight-static"; + const twinkleCanvas = doc.createElement("canvas"); + twinkleCanvas.className = "starrynight-twinkle"; + const sentinel = doc.createElement("span"); + sentinel.className = "starrynight-sentinel"; + deps.container.append(staticCanvas, twinkleCanvas, sentinel); + const staticCtx = deps.getContext(staticCanvas); + const twinkleCtx = deps.getContext(twinkleCanvas); + + let visible = initial.visible; + let reducedMotion = initial.reducedMotion; + let disposed = false; + let frame: number | null = null; + let settleTimer: number | null = null; + + let colors = deps.readColors(sentinel); + let size: Viewport = { width: 0, height: 0, dpr: 1 }; + let scale = 1; + let field: Placed[] = []; + let twinkling: Placed[] = []; + // Glow sprites by star size (1 or 2 CSS px). + let sprites: Record = {}; + // Armed between twinkle batches. Batches are timer-driven so frames are + // requested only when one is due: every main frame also re-services the + // shooting stars' animations, which costs a style recalc. + let twinkleTimer: number | null = null; + let twinkleDue = false; + + // Work waiting for the next visible frame. + let needsLayout = true; + let laidOut = false; + let needsColors = false; + let staticDirty = false; + let twinkleFull = false; + + const starColor = () => colors.star || FALLBACK_COLOR; + const glowColor = () => colors.glow || FALLBACK_COLOR; + + // One sprite per star size reproduces `box-shadow: 0 0 GLOW_BLUR + // GLOW_SPREAD` exactly: canvas shadowBlur uses the same blur model as + // CSS. The disc is drawn off the sprite and only its shadow lands on it. + function buildSprite(starSize: number): Sprite | null { + const half = Math.ceil((starSize / 2 + GLOW_SPREAD + GLOW_BLUR * 1.5) * scale); + const canvas = deps.createCanvas(); + canvas.width = canvas.height = half * 2; + const ctx = deps.getContext(canvas); + if (!ctx) return null; + const offset = half * 4; + ctx.shadowColor = glowColor(); + ctx.shadowBlur = GLOW_BLUR * scale; + ctx.shadowOffsetX = offset; + ctx.fillStyle = glowColor(); + ctx.beginPath(); + ctx.arc(half - offset, half, (starSize / 2 + GLOW_SPREAD) * scale, 0, Math.PI * 2); + ctx.fill(); + return { canvas, half }; + } + + function layout(): void { + scale = canvasScale(size.dpr); + const backing = backingSize(size.width, size.height, scale); + for (const canvas of [staticCanvas, twinkleCanvas]) { + canvas.width = backing.width; + canvas.height = backing.height; + } + field = generateField(size.width, size.height, deps.rand).map((star) => { + const placed = placeStar(star, size.width, size.height, scale); + const round = (Math.PI * (star.size * scale) ** 2) / 4; + return { star, ...placed, light: Math.min(1, round / placed.diameter ** 2) }; + }); + twinkling = field.filter((p) => p.star.twinkle); + } + + function drawStatic(): void { + if (!staticCtx) return; + staticCtx.clearRect(0, 0, staticCanvas.width, staticCanvas.height); + staticCtx.fillStyle = starColor(); + for (const p of field) { + if (p.star.twinkle) continue; + drawDot(staticCtx, p, p.star.opacity); + } + staticCtx.globalAlpha = 1; + } + + // Reduced motion: twinkling stars sit still at base opacity, no glow. + function drawTwinkleStill(): void { + if (!twinkleCtx) return; + twinkleCtx.clearRect(0, 0, twinkleCanvas.width, twinkleCanvas.height); + twinkleCtx.fillStyle = starColor(); + for (const p of twinkling) { + drawDot(twinkleCtx, p, p.star.opacity); + } + twinkleCtx.globalAlpha = 1; + } + + function drawTwinkleBatch(timeMs: number, full: boolean): void { + if (!twinkleCtx) return; + if (full) { + twinkleCtx.clearRect(0, 0, twinkleCanvas.width, twinkleCanvas.height); + } else { + // Clear every glow first so a neighbor's clear never erases a + // glow drawn earlier in this batch. + for (const p of twinkling) { + const half = sprites[p.star.size]?.half ?? p.diameter; + twinkleCtx.clearRect(Math.round(p.cx - half), Math.round(p.cy - half), half * 2, half * 2); + } + } + twinkleCtx.fillStyle = starColor(); + for (const p of twinkling) { + const glow = twinkleGlow(p.star.twinkle!, timeMs); + const sprite = sprites[p.star.size]; + if (sprite && glow > 0) { + // The original star's opacity applied to its box-shadow too. + twinkleCtx.globalAlpha = p.star.opacity * glow; + twinkleCtx.drawImage(sprite.canvas, Math.round(p.cx - sprite.half), Math.round(p.cy - sprite.half)); + } + drawDot(twinkleCtx, p, dotAlpha(p.star.opacity, glow)); + } + twinkleCtx.globalAlpha = 1; + } + + function onFrame(timeMs: number): void { + frame = null; + if (disposed || !visible) return; + + let spritesDirty = false; + if (needsColors) { + needsColors = false; + colors = deps.readColors(sentinel); + spritesDirty = staticDirty = twinkleFull = true; + } + if (needsLayout) { + needsLayout = false; + const next = deps.viewport(); + // The settle pass after a resize usually finds the size it already + // laid out; redraw then, without reshuffling the stars a second time. + const same = laidOut && next.width === size.width && next.height === size.height && next.dpr === size.dpr; + size = next; + if (!same) layout(); + laidOut = true; + spritesDirty = staticDirty = twinkleFull = true; + } + if (spritesDirty) sprites = { 1: buildSprite(1), 2: buildSprite(2) }; + if (staticDirty) { + staticDirty = false; + drawStatic(); + } + + const state = motionState({ visible, reducedMotion, width: size.width, height: size.height }); + if (state === "static") { + if (twinkleFull) drawTwinkleStill(); + twinkleFull = false; + stopTwinkle(); + } else if (state === "animating") { + // A batch runs when the timer says so, when something forced a + // full redraw, or on resume (no timer armed). Each batch restarts + // the timer, so batches stay at least TWINKLE_INTERVAL apart and a + // long gap never causes a catch-up burst. + if (twinkleDue || twinkleFull || twinkleTimer === null) { + drawTwinkleBatch(timeMs, twinkleFull); + twinkleDue = twinkleFull = false; + stopTwinkle(); + twinkleTimer = deps.setTimer(() => { + twinkleTimer = null; + twinkleDue = true; + schedule(); + }, TWINKLE_INTERVAL); + } + } else { + stopTwinkle(); + } + } + + function stopTwinkle(): void { + if (twinkleTimer === null) return; + deps.clearTimer(twinkleTimer); + twinkleTimer = null; + } + + function schedule(): void { + if (disposed || !visible || frame !== null) return; + frame = deps.requestFrame(onFrame); + } + + function cancelFrame(): void { + if (frame === null) return; + deps.cancelFrame(frame); + frame = null; + } + + const shooting = createShootingStars(deps, () => ({ visible, reducedMotion })); + schedule(); + + return { + resize() { + if (disposed) return; + needsLayout = true; + if (settleTimer !== null) deps.clearTimer(settleTimer); + settleTimer = deps.setTimer(() => { + settleTimer = null; + needsLayout = true; + schedule(); + }, RESIZE_SETTLE_MS); + schedule(); + shooting.update(); + }, + setVisible(next) { + if (disposed) return; + visible = next; + if (visible) schedule(); + else { + cancelFrame(); + stopTwinkle(); + } + shooting.update(); + }, + setReducedMotion(reduce) { + if (disposed || reduce === reducedMotion) return; + reducedMotion = reduce; + twinkleFull = true; + schedule(); + shooting.update(); + }, + colorsChanged() { + if (disposed) return; + needsColors = true; + schedule(); + }, + dispose() { + if (disposed) return; + disposed = true; + cancelFrame(); + stopTwinkle(); + if (settleTimer !== null) deps.clearTimer(settleTimer); + settleTimer = null; + shooting.dispose(); + staticCanvas.remove(); + twinkleCanvas.remove(); + sentinel.remove(); + }, + }; +}