#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add a hidden brand-mark brick game, behind an admin kill switch (#7826)
ConnorYoh0991cc2f411a
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex ed8408d7ec..a6160de0a3 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -1029,6 +1029,7 @@ public class ApplicationProperties {private Boolean enablePosthog;private Boolean enableScarf;private Boolean enableDesktopInstallSlide = true;+ private boolean enableEasterEggs = true;private Datasource datasource;private boolean disableSanitize;private int maxDPI = 500;diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.javaindex 618d5d642d..c57856877b 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java@@ -334,6 +334,8 @@ public class ConfigController {configData.put("enableDesktopInstallSlide",applicationProperties.getSystem().getEnableDesktopInstallSlide());+ configData.put(+ "enableEasterEggs", applicationProperties.getSystem().isEnableEasterEggs());// Premium/Enterprise settingsconfigData.put("premiumEnabled", applicationProperties.getPremium().isEnabled());diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex ecf7ea8538..0c01c91991 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -179,6 +179,7 @@ system:tessdataDir: "" # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored.enableAnalytics: null # Master toggle for analytics: set to 'true' to enable all analytics, 'false' to disable all analytics, or leave as 'null' to prompt admin on first launchenableDesktopInstallSlide: true # Set to 'false' to hide the desktop app installation slide in the onboarding flow+ enableEasterEggs: true # Set to 'false' to remove the app's hidden novelty featuresenablePosthog: null # Enable PostHog analytics (open-source product analytics): set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabledenableScarf: null # Enable Scarf tracking pixel: set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabledenableUrlToPDF: false # Set to 'true' to enable URL to PDF, INTERNAL ONLY, known security issues, should not be used externallydiff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex a077c52161..f8c1d99f7a 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -2371,6 +2371,35 @@ bullet4 = "For short-edge printers: Enable 'Flip on short edge' option"text = "Follow these steps for perfect booklets:"title = "How to Print & Assemble"+[brickGame]+balls = "Balls"+best = "Best"+close = "Close game"+effectTimer = "{{label}} {{seconds}}s"+hint = "Move with the pointer or the arrow keys. Click to capture the pointer, Esc to get back to work."+hintPointerLocked = "Pointer captured. Esc releases it, then Esc again to get back to work."+score = "Score"+title = "Hidden game"++[brickGame.effect]+fast = "Fast"+narrow = "Narrow"+reversed = "Reversed"+slow = "Slow"+wide = "Wide"++[brickGame.lost]+detail = "Click or press Space to try again"+headline = "Out of balls"++[brickGame.ready]+detail = "Click or press Space to serve"+headline = "Ready"++[brickGame.won]+detail = "Click or press Space to play again"+headline = "All clear"+[bulkSelection]syntaxError = "There is a syntax issue. See Page Selection tips for help."diff --git a/frontend/editor/src/core/components/easterEgg/brickGame/BrickGame.css b/frontend/editor/src/core/components/easterEgg/brickGame/BrickGame.cssnew file mode 100644index 0000000000..a1ef4df34b--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/brickGame/BrickGame.css@@ -0,0 +1,211 @@+/* The game's own little arcade cabinet.+ The playfield is deliberately dark in both themes so the paper bricks read as+ paper either way; only the mark itself takes its colour from the brand tokens.+ Everything the canvas paints is declared here and read back through+ getComputedStyle, so the palette stays in the stylesheet where it belongs. */++.brick-game-scrim {+ position: fixed;+ inset: 0;+ z-index: 1000;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 1rem;+ background: rgba(0, 0, 0, 0.72);+ backdrop-filter: blur(0.25rem);+ /* Getting in needs seven fast clicks, and serving is a click too. Without+ this the browser reads those bursts as double/triple clicks and selects+ the HUD text under the cursor. */+ user-select: none;+}++.brick-game-cabinet {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ width: min(100%, 60rem);+ /* Read by the canvas renderer, not used by any rule below. */+ --brick-game-field: rgba(0, 0, 0, 0.92);+ --brick-game-field-edge: rgba(255, 255, 255, 0.14);+ --brick-game-page: #fff;+ --brick-game-page-edge: rgba(0, 0, 0, 0.3);+ --brick-game-ball: #fff;+ --brick-game-mark: var(--c-brand-mark);+ --brick-game-mark-soft: var(--c-brand-mark-soft);+ --brick-game-power-wide: var(--c-accent-solid);+ --brick-game-power-slow: var(--c-warning);+ --brick-game-power-multi: var(--c-success);+ --brick-game-power-life: var(--c-brand-mark);+ --brick-game-power-bane: var(--c-danger);+}++.brick-game-cabinet:focus {+ outline: none;+}++.brick-game-hud {+ display: flex;+ align-items: center;+ gap: 1rem;+ color: #fff;+ font-size: 0.8125rem;+ font-variant-numeric: tabular-nums;+}++.brick-game-hud__stat {+ color: rgba(255, 255, 255, 0.72);+}++/* Pushes the whole readout to the right, where the title used to sit. */+.brick-game-hud__stat--first {+ margin-left: auto;+}++.brick-game-hud__stat b {+ color: #fff;+ font-weight: 600;+}++.brick-game-effects {+ display: flex;+ gap: 0.375rem;+}++.brick-game-effect {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ padding: 0.0625rem 0.375rem;+ border-radius: 999px;+ color: #fff;+ font-size: 0.6875rem;+ font-weight: 600;+}++.brick-game-effect--good {+ background: var(--c-accent-solid);+}++.brick-game-effect--bad {+ background: var(--c-danger);+}++.brick-game-close {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ padding: 0;+ border: 1px solid rgba(255, 255, 255, 0.22);+ border-radius: var(--radius-sm);+ background: transparent;+ color: #fff;+ font-size: 1rem;+ line-height: 1;+ cursor: pointer;+}++.brick-game-close:hover {+ background: rgba(255, 255, 255, 0.12);+}++.brick-game-close:focus-visible {+ outline: 0.125rem solid var(--c-primary);+ outline-offset: 0.125rem;+}++.brick-game-stage {+ position: relative;+ width: 100%;+ aspect-ratio: 800 / 560;+ max-height: 74vh;+ margin-inline: auto;+ border-radius: var(--radius-md);+ overflow: hidden;+}++.brick-game-canvas {+ display: block;+ width: 100%;+ height: 100%;+ touch-action: none;+}++/* Unlocked, the pointer is still what aims, so the arrow is only in the way. */+.brick-game-canvas--aiming {+ cursor: none;+}++.brick-game-banner {+ position: absolute;+ inset: 0;+ color: #fff;+ text-align: center;+ /* Clicks belong to the canvas underneath, which serves the next ball. */+ pointer-events: none;+}++/* Sits in the clear band between the wall of pages and the paddle. Centred in+ the stage it landed on the bottom row of pages, and white text on a white+ page thumbnail was unreadable. `top` is used rather than percentage padding+ because a percentage padding resolves against the containing block's WIDTH+ even on the block axis, which on this 800x560 stage is the wrong reference. */+.brick-game-banner__plate {+ position: absolute;+ top: 64%;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.25rem;+ max-width: calc(100% - 2rem);+ padding: 0.5rem 1.125rem 0.625rem;+ border-radius: var(--radius-md);+ /* A plate behind the text, so it stays legible whatever the page shows. */+ background: rgba(0, 0, 0, 0.74);+}++.brick-game-banner__headline {+ font-size: 1.375rem;+ font-weight: 600;+ letter-spacing: 0.02em;+}++.brick-game-banner__detail {+ color: rgba(255, 255, 255, 0.82);+ font-size: 0.8125rem;+}++.brick-game-hint {+ margin: 0;+ color: rgba(255, 255, 255, 0.62);+ font-size: 0.75rem;+ text-align: center;+}++@media (max-width: 40rem) {+ .brick-game-hud__stat--best {+ display: none;+ }++ /* The plate is sized in rem but placed as a share of the playfield, so on a+ small stage it covers far more of the field. Shrinking it keeps the longest+ message from wrapping down onto the paddle. */+ .brick-game-banner__plate {+ /* Lifted as well as shrunk: a wrapped message grows downwards, towards the+ paddle. There is far more spare field above the plate than below it. */+ top: 58%;+ padding: 0.375rem 0.75rem 0.5rem;+ }++ .brick-game-banner__headline {+ font-size: 1.0625rem;+ }++ .brick-game-banner__detail {+ font-size: 0.75rem;+ }+}diff --git a/frontend/editor/src/core/components/easterEgg/brickGame/BrickGame.tsx b/frontend/editor/src/core/components/easterEgg/brickGame/BrickGame.tsxnew file mode 100644index 0000000000..31e45d309c--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/brickGame/BrickGame.tsx@@ -0,0 +1,412 @@+import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+} from "react";+import { createPortal } from "react-dom";+import { useTranslation } from "react-i18next";+import {+ BrickGame as BrickGameEngine,+ type DropKind,+ FIELD_H,+ FIELD_W,+ type GameStatus,+ type Palette,+} from "@app/components/easterEgg/brickGame/brickGameEngine";+import type { Box } from "@app/components/easterEgg/brickGame/brickGameGeometry";+import "@app/components/easterEgg/brickGame/BrickGame.css";++export interface BrickGameProps {+ /** Where the mark flies in from, in client coordinates. */+ originRect: DOMRect | null;+ /** Page thumbnails to face the bricks with; already decoded. */+ images?: readonly HTMLImageElement[];+ onClose: () => void;+}++/**+ * Pulls the palette out of BrickGame.css. A probe element is used rather than+ * reading the custom properties straight off the host because canvas needs a+ * resolved colour and these tokens are themselves `var()` chains.+ */+function resolvePalette(host: HTMLElement): Palette {+ const probe = document.createElement("span");+ probe.style.display = "none";+ host.appendChild(probe);+ const read = (name: string, fallback: string): string => {+ probe.style.color = `var(${name})`;+ return window.getComputedStyle(probe).color || fallback;+ };+ const palette: Palette = {+ field: read("--brick-game-field", "#000"),+ fieldEdge: read("--brick-game-field-edge", "#fff"),+ page: read("--brick-game-page", "#fff"),+ pageEdge: read("--brick-game-page-edge", "#000"),+ ball: read("--brick-game-ball", "#fff"),+ markSoft: read("--brick-game-mark-soft", "#fff"),+ markStrong: read("--brick-game-mark", "#fff"),+ powerWide: read("--brick-game-power-wide", "#fff"),+ powerSlow: read("--brick-game-power-slow", "#fff"),+ powerMulti: read("--brick-game-power-multi", "#fff"),+ powerLife: read("--brick-game-power-life", "#fff"),+ powerBane: read("--brick-game-power-bane", "#fff"),+ };+ probe.remove();+ return palette;+}++/** The scale factor from CSS pixels to playfield units for this canvas. */+function fieldScale(canvas: HTMLCanvasElement): number {+ const rect = canvas.getBoundingClientRect();+ if (rect.width === 0 || rect.height === 0) return 1;+ return Math.min(rect.width / FIELD_W, rect.height / FIELD_H);+}++/** Converts a client point into playfield units, matching the canvas letterbox. */+function toFieldX(canvas: HTMLCanvasElement, clientX: number): number {+ const rect = canvas.getBoundingClientRect();+ if (rect.width === 0 || rect.height === 0) return FIELD_W / 2;+ const scale = fieldScale(canvas);+ const inset = (rect.width - FIELD_W * scale) / 2;+ return (clientX - rect.left - inset) / scale;+}++/** The origin rect expressed in playfield units, or null when unmeasurable. */+function toFieldBox(+ canvas: HTMLCanvasElement,+ rect: DOMRect | null,+): Box | null {+ if (!rect) return null;+ const canvasRect = canvas.getBoundingClientRect();+ if (canvasRect.width === 0 || canvasRect.height === 0) return null;+ const scale = fieldScale(canvas);+ const insetX = (canvasRect.width - FIELD_W * scale) / 2;+ const insetY = (canvasRect.height - FIELD_H * scale) / 2;+ return {+ x: (rect.left - canvasRect.left - insetX) / scale,+ y: (rect.top - canvasRect.top - insetY) / scale,+ w: rect.width / scale,+ h: rect.height / scale,+ };+}++/** Phases that get a banner, and the key prefix carrying its copy. */+const BANNER_PHASES = {+ ready: "brickGame.ready",+ won: "brickGame.won",+ lost: "brickGame.lost",+} as const;++type BannerPhase = keyof typeof BANNER_PHASES;++function isBannerPhase(phase: GameStatus["phase"]): phase is BannerPhase {+ return phase in BANNER_PHASES;+}++export default function BrickGame({+ originRect,+ images,+ onClose,+}: BrickGameProps) {+ const { t } = useTranslation();+ const cabinetRef = useRef<HTMLDivElement>(null);+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const gameRef = useRef<BrickGameEngine | null>(null);+ const [locked, setLocked] = useState(false);+ const [status, setStatus] = useState<GameStatus>({+ phase: "intro",+ score: 0,+ lives: 3,+ bricksLeft: 0,+ best: 0,+ balls: 1,+ effects: [],+ });++ // Read once, at construction, so a re-render cannot restart the game by+ // feeding new object identities into the setup effect.+ const originRef = useRef(originRect);+ const imagesRef = useRef(images);++ const resize = useCallback((canvas: HTMLCanvasElement) => {+ const rect = canvas.getBoundingClientRect();+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ canvas.width = Math.max(1, Math.round(rect.width * dpr));+ canvas.height = Math.max(1, Math.round(rect.height * dpr));+ }, []);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;++ resize(canvas);+ // The cabinet carries the palette custom properties, not the stage.+ const palette = resolvePalette(+ canvas.closest<HTMLElement>(".brick-game-cabinet") ?? canvas,+ );+ const skipIntro = window.matchMedia(+ "(prefers-reduced-motion: reduce)",+ ).matches;++ const game = new BrickGameEngine({+ ctx,+ palette,+ origin: toFieldBox(canvas, originRef.current),+ skipIntro,+ images: imagesRef.current,+ onStatus: setStatus,+ });+ gameRef.current = game;+ game.start();++ const observer = new ResizeObserver(() => resize(canvas));+ observer.observe(canvas);++ // A hidden tab stops delivering frames; re-baseline the clock on return so+ // the first frame back is not one enormous delta.+ const onVisibility = () => {+ if (document.hidden) game.stop();+ else game.start();+ };+ document.addEventListener("visibilitychange", onVisibility);++ return () => {+ document.removeEventListener("visibilitychange", onVisibility);+ observer.disconnect();+ game.stop();+ gameRef.current = null;+ };+ }, [resize]);++ // Pages are rendered asynchronously, so they arrive after the game is built.+ useEffect(() => {+ gameRef.current?.setImages(images ?? []);+ }, [images]);++ // Pointer lock keeps the aim from running out of the playfield mid-rally.+ useEffect(() => {+ const onChange = () => {+ const canvas = canvasRef.current;+ const isLocked =+ Boolean(canvas) && document.pointerLockElement === canvas;+ setLocked(isLocked);+ // Absolute tracking would jump the paddle on the next stray move.+ if (!isLocked) gameRef.current?.setPointer(null);+ };+ document.addEventListener("pointerlockchange", onChange);+ document.addEventListener("pointerlockerror", onChange);+ return () => {+ document.removeEventListener("pointerlockchange", onChange);+ document.removeEventListener("pointerlockerror", onChange);+ };+ }, []);++ // Releasing the pointer on the way out, so the cursor is never left captured.+ useEffect(+ () => () => {+ if (document.pointerLockElement) document.exitPointerLock();+ },+ [],+ );++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ const game = gameRef.current;+ if (!game) return;+ if (event.key === "Escape") {+ // While the pointer is captured, Escape belongs to the browser: it+ // releases the cursor, and only a second press closes the game.+ if (!document.pointerLockElement) onClose();+ return;+ }+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {+ event.preventDefault();+ game.setKeyDir(event.key === "ArrowLeft" ? -1 : 1);+ return;+ }+ if (event.key === " " || event.key === "Enter") {+ event.preventDefault();+ game.act();+ }+ };+ const onKeyUp = (event: KeyboardEvent) => {+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {+ gameRef.current?.setKeyDir(0);+ }+ };+ window.addEventListener("keydown", onKeyDown);+ window.addEventListener("keyup", onKeyUp);+ return () => {+ window.removeEventListener("keydown", onKeyDown);+ window.removeEventListener("keyup", onKeyUp);+ };+ }, [onClose]);++ const handlePointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {+ const canvas = canvasRef.current;+ const game = gameRef.current;+ if (!canvas || !game) return;+ if (document.pointerLockElement === canvas) {+ game.nudgePaddle(event.movementX / fieldScale(canvas));+ return;+ }+ game.setPointer(toFieldX(canvas, event.clientX));+ };++ const handlePointerDown = (event: ReactPointerEvent<HTMLCanvasElement>) => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ if (document.pointerLockElement !== canvas) {+ // Rejected when the browser declines (a recent release rate-limits the+ // next request, and an iframe needs allow="pointer-lock"). Play carries+ // on with absolute tracking, so there is nothing to report.+ void Promise.resolve(canvas.requestPointerLock()).catch(() => {});+ handlePointerMove(event);+ }+ gameRef.current?.act();+ };++ useEffect(() => {+ // Focus the shell rather than the close button, so the keys the game wants+ // are not being handed to a button that would act on them.+ cabinetRef.current?.focus();+ // The click burst that got in here happened before this overlay existed, so+ // it may have left a selection behind in the chrome underneath.+ window.getSelection()?.removeAllRanges();+ }, []);++ // Literal keys throughout, so the translation audit can see every one.+ const effectLabel = (kind: DropKind): string => {+ switch (kind) {+ case "wide":+ return t("brickGame.effect.wide", "Wide");+ case "shrink":+ return t("brickGame.effect.narrow", "Narrow");+ case "slow":+ return t("brickGame.effect.slow", "Slow");+ case "fast":+ return t("brickGame.effect.fast", "Fast");+ case "reverse":+ return t("brickGame.effect.reversed", "Reversed");+ default:+ return "";+ }+ };++ const bannerCopy = (phase: BannerPhase) => {+ switch (phase) {+ case "won":+ return {+ headline: t("brickGame.won.headline", "All clear"),+ detail: t(+ "brickGame.won.detail",+ "Click or press Space to play again",+ ),+ };+ case "lost":+ return {+ headline: t("brickGame.lost.headline", "Out of balls"),+ detail: t(+ "brickGame.lost.detail",+ "Click or press Space to try again",+ ),+ };+ case "ready":+ return {+ headline: t("brickGame.ready.headline", "Ready"),+ detail: t("brickGame.ready.detail", "Click or press Space to serve"),+ };+ }+ };++ const banner = isBannerPhase(status.phase) ? bannerCopy(status.phase) : null;++ return createPortal(+ <div className="brick-game-scrim">+ <div+ ref={cabinetRef}+ className="brick-game-cabinet"+ role="dialog"+ aria-modal="true"+ aria-label={t("brickGame.title", "Hidden game")}+ tabIndex={-1}+ >+ <div className="brick-game-hud">+ <div className="brick-game-effects">+ {status.effects.map((effect) => (+ <span+ key={effect.kind}+ className={`brick-game-effect brick-game-effect--${+ effect.bad ? "bad" : "good"+ }`}+ >+ {t("brickGame.effectTimer", "{{label}} {{seconds}}s", {+ label: effectLabel(effect.kind),+ seconds: effect.seconds,+ })}+ </span>+ ))}+ </div>+ <span className="brick-game-hud__stat brick-game-hud__stat--first">+ {t("brickGame.score", "Score")} <b>{status.score}</b>+ </span>+ <span className="brick-game-hud__stat brick-game-hud__stat--best">+ {t("brickGame.best", "Best")}{" "}+ <b>{Math.max(status.best, status.score)}</b>+ </span>+ <span className="brick-game-hud__stat">+ {t("brickGame.balls", "Balls")} <b>{status.lives}</b>+ </span>+ <button+ type="button"+ className="brick-game-close"+ onClick={onClose}+ aria-label={t("brickGame.close", "Close game")}+ >+ ×+ </button>+ </div>++ <div className="brick-game-stage">+ <canvas+ ref={canvasRef}+ className={`brick-game-canvas${+ locked ? "" : " brick-game-canvas--aiming"+ }`}+ onPointerMove={handlePointerMove}+ onPointerDown={handlePointerDown}+ />+ {banner && (+ <div className="brick-game-banner" aria-live="polite">+ <div className="brick-game-banner__plate">+ <span className="brick-game-banner__headline">+ {banner.headline}+ </span>+ <span className="brick-game-banner__detail">+ {banner.detail}+ </span>+ </div>+ </div>+ )}+ </div>++ <p className="brick-game-hint">+ {locked+ ? t(+ "brickGame.hintPointerLocked",+ "Pointer captured. Esc releases it, then Esc again to get back to work.",+ )+ : t(+ "brickGame.hint",+ "Move with the pointer or the arrow keys. Click to capture the pointer, Esc to get back to work.",+ )}+ </p>+ </div>+ </div>,+ document.body,+ );+}diff --git a/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.test.ts b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.test.tsnew file mode 100644index 0000000000..f3da54d6c5--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.test.ts@@ -0,0 +1,443 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ BrickGame,+ FIELD_W,+ type GameStatus,+ type Palette,+} from "@app/components/easterEgg/brickGame/brickGameEngine";++const PALETTE: Palette = {+ markSoft: "#1",+ markStrong: "#2",+ page: "#3",+ pageEdge: "#4",+ field: "#5",+ fieldEdge: "#6",+ ball: "#7",+ powerWide: "#8",+ powerSlow: "#9",+ powerMulti: "#a",+ powerLife: "#b",+ powerBane: "#c",+};++interface DrawnImage {+ image: CanvasImageSource;+}++/** Records only the image draws, which is the one output a test asserts on. */+function stubContext(): {+ ctx: CanvasRenderingContext2D;+ drawn: DrawnImage[];+} {+ const noop = () => {};+ const drawn: DrawnImage[] = [];+ const ctx = {+ canvas: { width: 1600, height: 1120 },+ setTransform: noop,+ clearRect: noop,+ fillRect: noop,+ strokeRect: noop,+ beginPath: noop,+ closePath: noop,+ moveTo: noop,+ lineTo: noop,+ arc: noop,+ roundRect: noop,+ clip: noop,+ fill: noop,+ stroke: noop,+ save: noop,+ restore: noop,+ drawImage: (image: CanvasImageSource) => {+ drawn.push({ image });+ },+ fillStyle: "",+ strokeStyle: "",+ lineWidth: 1,+ lineCap: "butt",+ globalAlpha: 1,+ };+ return { ctx: ctx as unknown as CanvasRenderingContext2D, drawn };+}++/** A stand-in for a decoded thumbnail; the engine only reads its dimensions. */+function fakeImage(): HTMLImageElement {+ return { naturalWidth: 60, naturalHeight: 80 } as HTMLImageElement;+}++interface Harness {+ game: BrickGame;+ status: () => GameStatus;+ drawn: DrawnImage[];+ /** Runs `frames` animation frames at a steady 60fps. */+ run: (frames: number) => void;+}++function setup(+ options: {+ skipIntro?: boolean;+ images?: readonly HTMLImageElement[];+ } = {},+): Harness {+ let now = 0;+ let pending: FrameRequestCallback | null = null;+ vi.spyOn(performance, "now").mockImplementation(() => now);+ vi.stubGlobal("requestAnimationFrame", (fn: FrameRequestCallback) => {+ pending = fn;+ return 1;+ });+ vi.stubGlobal("cancelAnimationFrame", () => {+ pending = null;+ });++ const { ctx, drawn } = stubContext();+ let latest: GameStatus | null = null;+ const game = new BrickGame({+ ctx,+ palette: PALETTE,+ origin: null,+ skipIntro: options.skipIntro ?? true,+ images: options.images,+ onStatus: (next) => {+ latest = next;+ },+ });+ game.start();++ return {+ game,+ drawn,+ status: () => {+ if (!latest) throw new Error("game reported no status");+ return latest;+ },+ run: (frames) => {+ for (let i = 0; i < frames; i++) {+ const frame = pending;+ pending = null;+ if (!frame) return;+ now += 1000 / 60;+ frame(now);+ }+ },+ };+}++/**+ * Serves from the middle and then runs the paddle away, so the ball is missed.+ * The paddle has to leave *after* the serve: a held ball sits on the paddle+ * wherever it is, so parking the paddle first just gets the ball served+ * straight back into it.+ */+function concedeABall({ game, run }: Harness): void {+ game.setPointer(FIELD_W / 2);+ run(2);+ game.act();+ game.setPointer(0);+ run(600);+}++/** Seconds left on a named effect, or 0 when it is not running. */+function effectSeconds(status: GameStatus, kind: string): number {+ return status.effects.find((e) => e.kind === kind)?.seconds ?? 0;+}++beforeEach(() => {+ window.localStorage.clear();+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("BrickGame", () => {+ it("waits on the player before it moves anything", () => {+ const { status, run } = setup();+ expect(status().phase).toBe("ready");+ run(60);+ // A held ball scores nothing however long the player leaves it.+ expect(status().score).toBe(0);+ expect(status().bricksLeft).toBeGreaterThan(0);+ });++ it("holds the player off until the fly-in lands, then plays", () => {+ let now = 0;+ let pending: FrameRequestCallback | null = null;+ vi.spyOn(performance, "now").mockImplementation(() => now);+ vi.stubGlobal("requestAnimationFrame", (fn: FrameRequestCallback) => {+ pending = fn;+ return 1;+ });+ vi.stubGlobal("cancelAnimationFrame", () => {+ pending = null;+ });+ // Collected rather than kept in a `let`: read directly after a callback-only+ // assignment, TypeScript still narrows the variable to its initial null.+ const reported: GameStatus[] = [];+ const phase = () => reported.at(-1)?.phase;+ const game = new BrickGame({+ ctx: stubContext().ctx,+ palette: PALETTE,+ origin: { x: -80, y: -120, w: 30, h: 33 },+ skipIntro: false,+ onStatus: (next) => {+ reported.push(next);+ },+ });+ game.start();+ expect(phase()).toBe("intro");++ // A serve during the fly-in is ignored rather than queued.+ game.act();+ expect(phase()).toBe("intro");++ const step = () => {+ const frame = pending;+ pending = null;+ if (!frame) return false;+ now += 1000 / 60;+ frame(now);+ return true;+ };++ // The intro is 2s, so one second in it must still be running.+ for (let i = 0; i < 60; i++) step();+ expect(phase()).toBe("intro");++ for (let i = 0; i < 90; i++) step();+ expect(phase()).toBe("ready");+ });++ it("skips the fly-in with no origin to fly in from", () => {+ // prefers-reduced-motion takes the same path.+ const { status } = setup({ skipIntro: false });+ expect(status().phase).toBe("ready");+ });++ it("clears pages and scores once the ball is served", () => {+ const { game, status, run } = setup();+ const before = status().bricksLeft;+ game.act();+ expect(status().phase).toBe("playing");+ run(240);+ expect(status().bricksLeft).toBeLessThan(before);+ expect(status().score).toBeGreaterThan(0);+ });++ it("costs a life when the paddle is nowhere near the ball", () => {+ // A dead-centre serve, so the return is predictable.+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ const harness = setup();+ concedeABall(harness);+ expect(harness.status().lives).toBe(2);+ });++ it("ends the round after the third miss", () => {+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ const harness = setup();+ concedeABall(harness);+ concedeABall(harness);+ concedeABall(harness);+ expect(harness.status().lives).toBe(0);+ expect(harness.status().phase).toBe("lost");+ });++ it("remembers a best score across games", () => {+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ const first = setup();+ // Ending the round is what commits the score.+ concedeABall(first);+ concedeABall(first);+ concedeABall(first);+ expect(first.status().phase).toBe("lost");+ const best = first.status().best;+ expect(best).toBeGreaterThan(0);++ first.game.stop();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();++ const second = setup();+ expect(second.status().best).toBe(best);+ });++ it("resets the board on restart", () => {+ const { game, status, run } = setup();+ game.act();+ run(240);+ const cleared = status().bricksLeft;+ game.restart();+ expect(status().phase).toBe("ready");+ expect(status().score).toBe(0);+ expect(status().lives).toBe(3);+ expect(status().bricksLeft).toBeGreaterThan(cleared);+ });++ it("simulates nothing while stopped, and does not lurch on resume", () => {+ const { game, status, run } = setup();+ game.act();+ run(60);+ const scoreBeforeStop = status().score;+ game.stop();+ run(600); // frames are no longer scheduled+ expect(status().score).toBe(scoreBeforeStop);++ // A long wall-clock gap while stopped must not be spent in one step.+ game.start();+ run(1);+ expect(status().bricksLeft).toBeGreaterThan(0);+ });++ it.each([-5000, FIELD_W + 5000])(+ "keeps the paddle on the field with the pointer at %i",+ (pointerX) => {+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ const { game, status, run } = setup();+ game.setPointer(pointerX);+ run(5);+ game.act();+ // One second: long enough to reach the wall, short enough that the ball+ // has not yet come back down to where the paddle would have to catch it.+ run(60);+ // An unclamped paddle would carry the held ball off the field and+ // concede the moment it was served.+ expect(status().lives).toBe(3);+ expect(status().score).toBeGreaterThan(0);+ },+ );++ it("moves the paddle by relative deltas from a captured pointer", () => {+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ const { game, status, run } = setup();+ // Drive it hard left with relative motion alone, then serve: the ball is+ // held on the paddle, so a paddle that did not move would score anyway.+ game.setPointer(FIELD_W / 2);+ run(2);+ for (let i = 0; i < 20; i++) game.nudgePaddle(-40);+ run(2);+ game.act();+ game.setPointer(null);+ run(60);+ // Serving straight up from the far left hits the first column.+ expect(status().score).toBeGreaterThan(0);+ expect(status().lives).toBe(3);+ });++ describe("power-ups", () => {+ /** Forces every brick to drop the chosen kind. */+ function alwaysDrop(kindRoll: number): void {+ let call = 0;+ vi.spyOn(Math, "random").mockImplementation(() => {+ call += 1;+ // launch angle, then alternating drop-chance / kind rolls+ if (call === 1) return 0.5;+ return call % 2 === 0 ? 0 : kindRoll;+ });+ }++ it("drops nothing when the roll never comes up", () => {+ vi.spyOn(Math, "random").mockReturnValue(0.99);+ const { game, status, run } = setup();+ game.act();+ run(240);+ expect(status().score).toBeGreaterThan(0);+ expect(status().effects).toEqual([]);+ });++ /**+ * Peak rather than final value: losing a ball deliberately clears the+ * board's effects, so an effect can have come and gone by the last frame.+ */+ function peak(+ harness: Harness,+ pick: (status: GameStatus) => number,+ ): number {+ let best = 0;+ for (let chunk = 0; chunk < 30; chunk++) {+ harness.run(20);+ best = Math.max(best, pick(harness.status()));+ }+ return best;+ }++ it.each([+ ["wide", 0.1],+ ["slow", 0.3],+ ["shrink", 0.7],+ ["fast", 0.85],+ ["reverse", 0.97],+ ])("runs the %s effect when that drop is caught", (kind, roll) => {+ alwaysDrop(roll as number);+ const harness = setup();+ harness.game.act();+ expect(+ peak(harness, (s) => effectSeconds(s, kind as string)),+ ).toBeGreaterThan(0);+ });++ it("clears the board's effects when a ball is conceded", () => {+ alwaysDrop(0.1);+ const harness = setup();+ harness.game.act();+ expect(peak(harness, (s) => effectSeconds(s, "wide"))).toBeGreaterThan(0);+ // Run the paddle off and let the ball go.+ harness.game.setPointer(0);+ harness.run(900);+ expect(harness.status().lives).toBeLessThan(3);+ expect(harness.status().effects).toEqual([]);+ });++ it("splits into more balls when a multi drop is caught", () => {+ alwaysDrop(0.45);+ const { game, status, run } = setup();+ game.act();+ expect(status().balls).toBe(1);+ run(600);+ expect(status().balls).toBeGreaterThan(1);+ });++ it("grants a ball in reserve when a life drop is caught", () => {+ alwaysDrop(0.6);+ const { game, status, run } = setup();+ game.act();+ run(600);+ expect(status().lives).toBeGreaterThan(3);+ });++ it("only concedes when the last ball is lost", () => {+ alwaysDrop(0.45);+ const harness = setup();+ harness.game.act();+ harness.run(600);+ expect(harness.status().balls).toBeGreaterThan(1);++ // Run the paddle away: balls drain one at a time, and the life goes with+ // the last of them.+ harness.game.setPointer(0);+ harness.run(60);+ expect(harness.status().lives).toBe(3);+ harness.run(1200);+ expect(harness.status().lives).toBeLessThan(4);+ });+ });++ describe("thumbnails", () => {+ it("faces the pages with the supplied thumbnails", () => {+ const images = [fakeImage(), fakeImage(), fakeImage()];+ const { drawn, run } = setup({ images });+ run(2);+ expect(drawn.length).toBeGreaterThan(0);+ // Every draw is one of the supplied images, cycled across the wall.+ for (const entry of drawn) expect(images).toContain(entry.image);+ expect(new Set(drawn.map((d) => d.image)).size).toBe(images.length);+ });++ it("draws no image at all when none are supplied", () => {+ const { drawn, run } = setup();+ run(2);+ expect(drawn).toHaveLength(0);+ });+ });+});diff --git a/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.ts b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.tsnew file mode 100644index 0000000000..58b9c82169--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.ts@@ -0,0 +1,1010 @@+import {+ type Box,+ type MarkPose,+ type Quad,+ clamp,+ easeOutBack,+ lerpPose,+ logoPose,+ paddlePose,+} from "@app/components/easterEgg/brickGame/brickGameGeometry";++/**+ * Knock a stack of pages apart with the Stirling mark.+ *+ * The simulation runs in a fixed 800x560 playfield and the renderer scales that+ * to whatever canvas it is given, so physics behaves identically on every+ * screen and nothing has to be retuned per device pixel ratio.+ *+ * React owns none of the frame loop. The component constructs this, feeds it+ * input, and receives HUD state through `onStatus` only when it actually+ * changes, which keeps re-renders off the animation path.+ */++export const FIELD_W = 800;+export const FIELD_H = 560;++/** Small enough that the fastest ball advances ~2.5 units between checks. */+const PHYSICS_STEP = 1 / 240;+/** Caps catch-up work after a tab switch or a long paint stall. */+const MAX_FRAME_S = 1 / 15;++const COLS = 13;+const ROWS = 3;+const BRICK_W = 49;+const BRICK_H = 68;+const BRICK_GAP_X = 6;+const BRICK_GAP_Y = 8;+const WALL_TOP = 64;+const BRICK_FOLD = 12;++const PADDLE_W = 132;+const PADDLE_H = 16;+const PADDLE_Y = FIELD_H - 48;+const PADDLE_KEY_SPEED = 620;+/** Paddle-width and ball-speed multipliers, good and bad, and their duration. */+const WIDE_SCALE = 1.55;+const SHRINK_SCALE = 0.62;+const SLOW_FACTOR = 0.62;+const FAST_FACTOR = 1.4;+const EFFECT_S = 12;++const BALL_R = 7;+const BALL_SPEED_START = 340;+const BALL_SPEED_PER_BRICK = 4;+const BALL_SPEED_MAX = 560;+/** Keeps a bounce off the paddle from flattening into an unwinnable rally. */+const MIN_VERTICAL_RATIO = 0.32;+const MAX_BALLS = 6;+/** Angle spread applied when a split adds balls either side of the original. */+const SPLIT_SPREAD = 0.45;++const DROP_CHANCE = 0.24;+const POWERUP_W = 30;+const POWERUP_H = 20;+const POWERUP_FALL_SPEED = 145;+const POWERUP_SCORE = 25;++const START_LIVES = 3;++/**+ * Intro beats, in ms from the start. The mark's flight and the pages' sweep+ * overlap on purpose: the wall assembles itself while the logo is still on its+ * way down, so neither half is dead time.+ */+const INTRO_MS = 2000;+const MARK_FLIGHT_MS = 1500;+const BRICK_SWEEP_START_MS = 400;+const BRICK_STAGGER_COL_MS = 70;+const BRICK_STAGGER_ROW_MS = 90;+const BRICK_FADE_MS = 300;+/** How far a page slides down into place as it fades in. */+const BRICK_DROP = 14;++const BEST_SCORE_KEY = "stirling.easterEgg.best";++export type GamePhase = "intro" | "ready" | "playing" | "lost" | "won";++/** Worth catching. */+export type BoonKind = "wide" | "slow" | "multi" | "life";+/** Worth dodging. */+export type BaneKind = "shrink" | "fast" | "reverse";+export type DropKind = BoonKind | BaneKind;++export interface ActiveEffect {+ kind: DropKind;+ seconds: number;+ bad: boolean;+}++export interface GameStatus {+ phase: GamePhase;+ score: number;+ lives: number;+ bricksLeft: number;+ best: number;+ balls: number;+ /** Whatever is currently running, good or bad, for the HUD to show. */+ effects: ActiveEffect[];+}++export interface Palette {+ markSoft: string;+ markStrong: string;+ page: string;+ pageEdge: string;+ field: string;+ fieldEdge: string;+ ball: string;+ powerWide: string;+ powerSlow: string;+ powerMulti: string;+ powerLife: string;+ /** Every bane shares one colour, so "do not catch this" is learnt once. */+ powerBane: string;+}++interface Ball {+ x: number;+ y: number;+ vx: number;+ vy: number;+ /** Base speed before any slow effect is applied. */+ speed: number;+}++interface Brick {+ x: number;+ y: number;+ row: number;+ col: number;+ alive: boolean;+ /** Index into the thumbnail list, or -1 to draw a blank page. */+ image: number;+ /** When this page starts fading in, in ms from the intro's start. */+ appearAt: number;+}++interface Drop {+ x: number;+ y: number;+ kind: DropKind;+}++/** A multiplier that expires, used for both the paddle and the ball. */+interface TimedEffect {+ kind: DropKind;+ factor: number;+ remaining: number;+}++/**+ * The drop table. Boons come first so a low roll is always good news, and they+ * hold about two thirds of the range: banes are there to be dodged, not to make+ * a good run feel unlucky. An extra ball is the rarest thing in the game.+ */+const DROP_TABLE: { kind: DropKind; upTo: number }[] = [+ { kind: "wide", upTo: 0.2 },+ { kind: "slow", upTo: 0.4 },+ { kind: "multi", upTo: 0.56 },+ { kind: "life", upTo: 0.65 },+ { kind: "shrink", upTo: 0.79 },+ { kind: "fast", upTo: 0.92 },+ { kind: "reverse", upTo: 1 },+];++const BANES: ReadonlySet<DropKind> = new Set<DropKind>([+ "shrink",+ "fast",+ "reverse",+]);++export function isBane(kind: DropKind): boolean {+ return BANES.has(kind);+}++function pickDropKind(roll: number): DropKind {+ for (const entry of DROP_TABLE) {+ if (roll < entry.upTo) return entry.kind;+ }+ return "wide";+}++function readBest(): number {+ try {+ const raw = window.localStorage.getItem(BEST_SCORE_KEY);+ const parsed = raw === null ? 0 : Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;+ } catch {+ return 0;+ }+}++function writeBest(score: number): void {+ try {+ window.localStorage.setItem(BEST_SCORE_KEY, String(score));+ } catch {+ // A blocked storage partition costs the player a leaderboard, nothing more.+ }+}++function buildBricks(imageCount: number): Brick[] {+ const marginX = (FIELD_W - (COLS * BRICK_W + (COLS - 1) * BRICK_GAP_X)) / 2;+ const bricks: Brick[] = [];+ for (let row = 0; row < ROWS; row++) {+ for (let col = 0; col < COLS; col++) {+ bricks.push({+ x: marginX + col * (BRICK_W + BRICK_GAP_X),+ y: WALL_TOP + row * (BRICK_H + BRICK_GAP_Y),+ row,+ col,+ alive: true,+ // Pages run in reading order across the wall, so a loaded document is+ // recognisable rather than shuffled.+ image: imageCount > 0 ? (row * COLS + col) % imageCount : -1,+ appearAt:+ BRICK_SWEEP_START_MS ++ col * BRICK_STAGGER_COL_MS ++ row * BRICK_STAGGER_ROW_MS,+ });+ }+ }+ return bricks;+}++export class BrickGame {+ private readonly ctx: CanvasRenderingContext2D;+ private readonly palette: Palette;+ private readonly onStatus: (status: GameStatus) => void;+ private readonly introFrom: MarkPose | null;++ private bricks: Brick[];+ private phase: GamePhase = "intro";+ private score = 0;+ private lives = START_LIVES;+ private best = readBest();++ private paddleX = (FIELD_W - PADDLE_W) / 2;+ private paddleKeyDir = 0;+ private pointerX: number | null = null;++ private balls: Ball[] = [];+ private drops: Drop[] = [];+ /** One at a time each, so opposites replace rather than cancel confusingly. */+ private paddleEffect: TimedEffect | null = null;+ private ballEffect: TimedEffect | null = null;+ private reverseRemaining = 0;+ private ballFactorApplied = 1;+ private nextBallSpeed = BALL_SPEED_START;+ private images: readonly HTMLImageElement[];++ private introElapsed = 0;+ private accumulator = 0;+ private lastFrame = 0;+ private rafId: number | null = null;+ private running = false;++ constructor(options: {+ ctx: CanvasRenderingContext2D;+ palette: Palette;+ /** The nav-rail logo's rect in playfield units; the mark flies in from it. */+ origin: Box | null;+ /** Honours prefers-reduced-motion by landing everything already in place. */+ skipIntro: boolean;+ /** Page thumbnails to face the bricks with; empty draws blank pages. */+ images?: readonly HTMLImageElement[];+ onStatus: (status: GameStatus) => void;+ }) {+ this.ctx = options.ctx;+ this.palette = options.palette;+ this.onStatus = options.onStatus;+ this.images = options.images ?? [];+ this.introFrom = options.origin ? logoPose(options.origin) : null;+ this.bricks = buildBricks(this.images.length);+ if (options.skipIntro || !this.introFrom) {+ this.phase = "ready";+ this.introElapsed = INTRO_MS;+ }+ this.resetBalls();+ }++ /** Also re-baselines the clock, so a stop/start pause costs no simulation time. */+ start(): void {+ if (this.running) return;+ this.running = true;+ this.lastFrame = performance.now();+ this.emit();+ this.rafId = requestAnimationFrame(this.frame);+ }++ stop(): void {+ this.running = false;+ if (this.rafId !== null) cancelAnimationFrame(this.rafId);+ this.rafId = null;+ }++ /**+ * Faces the bricks with these thumbnails. Called after construction because+ * the pages are rendered asynchronously; the wall starts blank and fills in,+ * usually while the fly-in is still running.+ */+ setImages(images: readonly HTMLImageElement[]): void {+ this.images = images;+ for (const [index, brick] of this.bricks.entries()) {+ brick.image = images.length > 0 ? index % images.length : -1;+ }+ }++ /** Absolute pointer position; null hands the paddle back to the keyboard. */+ setPointer(fieldX: number | null): void {+ this.pointerX = fieldX;+ }++ /** Relative motion, as delivered by a locked pointer. */+ nudgePaddle(deltaFieldX: number): void {+ this.paddleKeyDir = 0;+ const centre =+ (this.pointerX ?? this.paddleX + this.paddleW / 2) + deltaFieldX;+ this.pointerX = clamp(centre, 0, FIELD_W);+ }++ setKeyDir(dir: number): void {+ this.paddleKeyDir = dir;+ if (dir !== 0) this.pointerX = null;+ }++ /** Launches a held ball, or restarts once the round is over. */+ act(): void {+ if (this.phase === "ready") {+ this.launch();+ return;+ }+ if (this.phase === "lost" || this.phase === "won") this.restart();+ }++ restart(): void {+ this.bricks = buildBricks(this.images.length);+ this.score = 0;+ this.lives = START_LIVES;+ this.nextBallSpeed = BALL_SPEED_START;+ this.clearBoard();+ this.phase = "ready";+ this.resetBalls();+ this.emit();+ }++ private get paddleW(): number {+ return PADDLE_W * (this.paddleEffect?.factor ?? 1);+ }++ private get ballFactor(): number {+ return this.ballEffect?.factor ?? 1;+ }++ /** Kinds only, never labels: the copy is the component's business. */+ private get activeEffects(): ActiveEffect[] {+ const effects: ActiveEffect[] = [];+ const push = (kind: DropKind, remaining: number) => {+ effects.push({+ kind,+ seconds: Math.max(1, Math.ceil(remaining)),+ bad: isBane(kind),+ });+ };+ if (this.paddleEffect) {+ push(this.paddleEffect.kind, this.paddleEffect.remaining);+ }+ if (this.ballEffect) {+ push(this.ballEffect.kind, this.ballEffect.remaining);+ }+ if (this.reverseRemaining > 0) {+ push("reverse", this.reverseRemaining);+ }+ return effects;+ }++ private get bricksLeft(): number {+ return this.bricks.reduce((n, b) => n + (b.alive ? 1 : 0), 0);+ }++ private emit(): void {+ this.onStatus({+ phase: this.phase,+ score: this.score,+ lives: this.lives,+ bricksLeft: this.bricksLeft,+ best: this.best,+ balls: this.balls.length,+ effects: this.activeEffects,+ });+ }++ /** Parks a single held ball on the paddle, ready to be served. */+ private resetBalls(): void {+ this.balls = [+ {+ x: this.paddleX + this.paddleW / 2,+ y: PADDLE_Y - BALL_R - 1,+ vx: 0,+ vy: 0,+ speed: this.nextBallSpeed,+ },+ ];+ }++ private holdBall(): void {+ const held = this.balls[0];+ if (!held) return;+ held.x = this.paddleX + this.paddleW / 2;+ held.y = PADDLE_Y - BALL_R - 1;+ held.vx = 0;+ held.vy = 0;+ }++ private launch(): void {+ const held = this.balls[0];+ if (!held) return;+ // A shallow spread either side of straight up, so no two rounds open alike.+ const angle = Math.random() * 0.7 - 0.35 - Math.PI / 2;+ const speed = this.liveSpeed(held);+ held.vx = Math.cos(angle) * speed;+ held.vy = Math.sin(angle) * speed;+ this.phase = "playing";+ this.emit();+ }++ /** A ball's speed with any slow or fast effect folded in. */+ private liveSpeed(ball: Ball): number {+ return ball.speed * this.ballFactor;+ }++ private frame = (now: number): void => {+ if (!this.running) return;+ const dt = Math.min((now - this.lastFrame) / 1000, MAX_FRAME_S);+ this.lastFrame = now;+ this.update(dt);+ this.draw();+ this.rafId = requestAnimationFrame(this.frame);+ };++ private update(dt: number): void {+ if (this.phase === "intro") {+ this.introElapsed += dt * 1000;+ if (this.introElapsed >= INTRO_MS) {+ this.introElapsed = INTRO_MS;+ this.phase = "ready";+ this.emit();+ }+ }++ this.movePaddle(dt);++ if (this.phase !== "playing") {+ this.holdBall();+ return;+ }++ this.tickEffects(dt);+ this.moveDrops(dt);++ this.accumulator += dt;+ while (this.accumulator >= PHYSICS_STEP) {+ this.accumulator -= PHYSICS_STEP;+ this.stepBalls(PHYSICS_STEP);+ if (this.phase !== "playing") {+ this.accumulator = 0;+ break;+ }+ }+ }++ private tickEffects(dt: number): void {+ const before = this.activeEffects.length;++ if (this.paddleEffect) {+ this.paddleEffect.remaining -= dt;+ if (this.paddleEffect.remaining <= 0) this.paddleEffect = null;+ }+ if (this.ballEffect) {+ this.ballEffect.remaining -= dt;+ if (this.ballEffect.remaining <= 0) this.ballEffect = null;+ }+ if (this.reverseRemaining > 0) this.reverseRemaining -= dt;++ // Velocity carries the speed factor, so it is rescaled whenever it changes.+ if (this.ballFactor !== this.ballFactorApplied) {+ this.ballFactorApplied = this.ballFactor;+ for (const ball of this.balls) this.rescale(ball);+ }+ if (this.activeEffects.length !== before) this.emit();+ }++ private movePaddle(dt: number): void {+ const reversed = this.reverseRemaining > 0;+ if (this.pointerX !== null) {+ // Mirrored rather than negated, so the pointer still maps onto the field.+ // Relative nudges land in pointerX too, so they invert with it.+ const aim = reversed ? FIELD_W - this.pointerX : this.pointerX;+ this.paddleX = aim - this.paddleW / 2;+ } else if (this.paddleKeyDir !== 0) {+ const dir = reversed ? -this.paddleKeyDir : this.paddleKeyDir;+ this.paddleX += dir * PADDLE_KEY_SPEED * dt;+ }+ this.paddleX = clamp(this.paddleX, 0, FIELD_W - this.paddleW);+ }++ private moveDrops(dt: number): void {+ if (this.drops.length === 0) return;+ const top = PADDLE_Y;+ const left = this.paddleX;+ const right = this.paddleX + this.paddleW;+ const survivors: Drop[] = [];+ let caught = false;++ for (const drop of this.drops) {+ drop.y += POWERUP_FALL_SPEED * dt;+ const overlapsPaddle =+ drop.y + POWERUP_H >= top &&+ drop.y <= top + PADDLE_H &&+ drop.x + POWERUP_W >= left &&+ drop.x <= right;+ if (overlapsPaddle) {+ this.collect(drop.kind);+ caught = true;+ continue;+ }+ if (drop.y <= FIELD_H) survivors.push(drop);+ }++ this.drops = survivors;+ if (caught) this.emit();+ }++ private collect(kind: DropKind): void {+ // Banes are their own punishment; no points are taken for catching one.+ if (!isBane(kind)) this.score += POWERUP_SCORE;+ switch (kind) {+ case "wide":+ this.paddleEffect = { kind, factor: WIDE_SCALE, remaining: EFFECT_S };+ break;+ case "shrink":+ this.paddleEffect = { kind, factor: SHRINK_SCALE, remaining: EFFECT_S };+ break;+ case "slow":+ this.ballEffect = { kind, factor: SLOW_FACTOR, remaining: EFFECT_S };+ break;+ case "fast":+ this.ballEffect = { kind, factor: FAST_FACTOR, remaining: EFFECT_S };+ break;+ case "reverse":+ this.reverseRemaining = EFFECT_S;+ break;+ case "life":+ this.lives += 1;+ break;+ case "multi":+ this.splitBalls();+ break;+ }+ // A paddle that just changed width must not straddle the wall.+ this.paddleX = clamp(this.paddleX, 0, FIELD_W - this.paddleW);+ }++ /** Adds a ball either side of each existing one, up to the cap. */+ private splitBalls(): void {+ const spawned: Ball[] = [];+ for (const ball of this.balls) {+ for (const spread of [-SPLIT_SPREAD, SPLIT_SPREAD]) {+ if (this.balls.length + spawned.length >= MAX_BALLS) break;+ const angle = Math.atan2(ball.vy, ball.vx) + spread;+ const speed = Math.hypot(ball.vx, ball.vy) || this.liveSpeed(ball);+ spawned.push({+ x: ball.x,+ y: ball.y,+ vx: Math.cos(angle) * speed,+ vy: Math.sin(angle) * speed,+ speed: ball.speed,+ });+ }+ }+ this.balls.push(...spawned);+ }++ private stepBalls(step: number): void {+ for (const ball of this.balls) {+ ball.x += ball.vx * step;+ ball.y += ball.vy * step;++ if (ball.x - BALL_R < 0) {+ ball.x = BALL_R;+ ball.vx = Math.abs(ball.vx);+ } else if (ball.x + BALL_R > FIELD_W) {+ ball.x = FIELD_W - BALL_R;+ ball.vx = -Math.abs(ball.vx);+ }+ if (ball.y - BALL_R < 0) {+ ball.y = BALL_R;+ ball.vy = Math.abs(ball.vy);+ }++ this.hitPaddle(ball);+ this.hitBricks(ball);+ }++ const alive = this.balls.filter((ball) => ball.y - BALL_R <= FIELD_H);+ if (alive.length !== this.balls.length) {+ this.balls = alive;+ // Only the last ball off the field costs anything.+ if (this.balls.length === 0) this.loseLife();+ else this.emit();+ }+ if (this.phase === "playing" && this.bricksLeft === 0) this.finish("won");+ }++ private hitPaddle(ball: Ball): void {+ if (ball.vy <= 0) return;+ const top = PADDLE_Y;+ const width = this.paddleW;+ const withinX =+ ball.x + BALL_R >= this.paddleX &&+ ball.x - BALL_R <= this.paddleX + width;+ const crossingTop =+ ball.y + BALL_R >= top && ball.y - BALL_R <= top + PADDLE_H;+ if (!withinX || !crossingTop) return;++ // Offset from centre steers the bounce, so the paddle aims rather than just blocks.+ const offset = (ball.x - (this.paddleX + width / 2)) / (width / 2);+ const angle = -Math.PI / 2 + clamp(offset, -1, 1) * 1.05;+ const speed = this.liveSpeed(ball);+ ball.y = top - BALL_R;+ ball.vx = Math.cos(angle) * speed;+ ball.vy = Math.sin(angle) * speed;+ this.enforceMinVertical(ball);+ }++ private enforceMinVertical(ball: Ball): void {+ const speed = this.liveSpeed(ball);+ const minVy = speed * MIN_VERTICAL_RATIO;+ if (Math.abs(ball.vy) >= minVy) return;+ ball.vy = Math.sign(ball.vy || -1) * minVy;+ const room = speed ** 2 - ball.vy ** 2;+ ball.vx = Math.sign(ball.vx || 1) * Math.sqrt(Math.max(room, 0));+ }++ private hitBricks(ball: Ball): void {+ for (const brick of this.bricks) {+ if (!brick.alive) continue;+ const nearestX = clamp(ball.x, brick.x, brick.x + BRICK_W);+ const nearestY = clamp(ball.y, brick.y, brick.y + BRICK_H);+ const dx = ball.x - nearestX;+ const dy = ball.y - nearestY;+ if (dx * dx + dy * dy > BALL_R * BALL_R) continue;++ // Reflect on whichever axis is least penetrated - that is the face it met.+ const cx = brick.x + BRICK_W / 2;+ const cy = brick.y + BRICK_H / 2;+ const overlapX = BRICK_W / 2 + BALL_R - Math.abs(ball.x - cx);+ const overlapY = BRICK_H / 2 + BALL_R - Math.abs(ball.y - cy);+ if (overlapX < overlapY) {+ ball.x += Math.sign(ball.x - cx || 1) * overlapX;+ ball.vx = -ball.vx;+ } else {+ ball.y += Math.sign(ball.y - cy || 1) * overlapY;+ ball.vy = -ball.vy;+ }++ brick.alive = false;+ this.score += 10 * (ROWS - brick.row);+ ball.speed = Math.min(ball.speed + BALL_SPEED_PER_BRICK, BALL_SPEED_MAX);+ this.nextBallSpeed = ball.speed;+ this.rescale(ball);+ this.maybeDrop(brick);+ this.emit();+ // One brick per step: the ball cannot legitimately reach two at this scale.+ return;+ }+ }++ private maybeDrop(brick: Brick): void {+ if (Math.random() >= DROP_CHANCE) return;+ this.drops.push({+ x: brick.x + (BRICK_W - POWERUP_W) / 2,+ y: brick.y + (BRICK_H - POWERUP_H) / 2,+ kind: pickDropKind(Math.random()),+ });+ }++ /** Keeps a velocity vector's length equal to the ball's current live speed. */+ private rescale(ball: Ball): void {+ const len = Math.hypot(ball.vx, ball.vy);+ if (len === 0) return;+ const speed = this.liveSpeed(ball);+ ball.vx = (ball.vx / len) * speed;+ ball.vy = (ball.vy / len) * speed;+ }++ private loseLife(): void {+ this.lives -= 1;+ if (this.lives <= 0) {+ this.finish("lost");+ return;+ }+ // A fresh ball arrives with the board's effects cleared, good and bad.+ this.clearBoard();+ this.phase = "ready";+ this.resetBalls();+ this.emit();+ }++ private finish(phase: "won" | "lost"): void {+ this.phase = phase;+ if (this.score > this.best) {+ this.best = this.score;+ writeBest(this.best);+ }+ this.clearBoard();+ this.resetBalls();+ this.emit();+ }++ /** Drops in flight and every timed effect, gone. */+ private clearBoard(): void {+ this.drops = [];+ this.paddleEffect = null;+ this.ballEffect = null;+ this.reverseRemaining = 0;+ this.ballFactorApplied = 1;+ }++ private draw(): void {+ const { ctx } = this;+ const canvas = ctx.canvas;+ const scale = Math.min(canvas.width / FIELD_W, canvas.height / FIELD_H);+ const ox = (canvas.width - FIELD_W * scale) / 2;+ const oy = (canvas.height - FIELD_H * scale) / 2;++ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ ctx.setTransform(scale, 0, 0, scale, ox, oy);++ ctx.fillStyle = this.palette.field;+ ctx.fillRect(0, 0, FIELD_W, FIELD_H);+ ctx.strokeStyle = this.palette.fieldEdge;+ ctx.lineWidth = 1;+ ctx.strokeRect(0.5, 0.5, FIELD_W - 1, FIELD_H - 1);++ this.drawBricks();+ this.drawDrops();+ this.drawMark();+ if (this.phase === "playing" || this.phase === "ready") this.drawBalls();+ }++ /** Traces a page outline with its corner turned down. */+ private pagePath(x: number, y: number): void {+ const { ctx } = this;+ ctx.beginPath();+ ctx.moveTo(x, y);+ ctx.lineTo(x + BRICK_W - BRICK_FOLD, y);+ ctx.lineTo(x + BRICK_W, y + BRICK_FOLD);+ ctx.lineTo(x + BRICK_W, y + BRICK_H);+ ctx.lineTo(x, y + BRICK_H);+ ctx.closePath();+ }++ private drawBricks(): void {+ const { ctx } = this;+ for (const brick of this.bricks) {+ if (!brick.alive) continue;+ const appear = clamp(+ (this.introElapsed - brick.appearAt) / BRICK_FADE_MS,+ 0,+ 1,+ );+ if (appear <= 0) continue;+ const y = brick.y - (1 - appear) * BRICK_DROP;++ ctx.save();+ ctx.globalAlpha = appear;+ this.pagePath(brick.x, y);+ ctx.fillStyle = this.palette.page;+ ctx.fill();++ const image = this.images[brick.image];+ if (image) {+ // Clipped to the page outline so a thumbnail cannot bleed over the fold.+ ctx.save();+ this.pagePath(brick.x, y);+ ctx.clip();+ this.drawCover(image, brick.x, y);+ ctx.restore();+ }++ this.pagePath(brick.x, y);+ ctx.strokeStyle = this.palette.pageEdge;+ ctx.lineWidth = 1;+ ctx.stroke();++ // The turned-down corner, tinted per row so the stack reads as depth.+ ctx.beginPath();+ ctx.moveTo(brick.x + BRICK_W - BRICK_FOLD, y);+ ctx.lineTo(brick.x + BRICK_W, y + BRICK_FOLD);+ ctx.lineTo(brick.x + BRICK_W - BRICK_FOLD, y + BRICK_FOLD);+ ctx.closePath();+ ctx.fillStyle =+ brick.row === 0+ ? this.palette.markStrong+ : brick.row === 1+ ? this.palette.markSoft+ : this.palette.pageEdge;+ ctx.fill();+ ctx.restore();+ }+ }++ /** Fills the brick with the image, cropping the overflowing axis. */+ private drawCover(image: HTMLImageElement, x: number, y: number): void {+ const iw = image.naturalWidth || image.width;+ const ih = image.naturalHeight || image.height;+ if (iw === 0 || ih === 0) return;+ const scale = Math.max(BRICK_W / iw, BRICK_H / ih);+ const w = iw * scale;+ const h = ih * scale;+ this.ctx.drawImage(+ image,+ x + (BRICK_W - w) / 2,+ y + (BRICK_H - h) / 2,+ w,+ h,+ );+ }++ private dropColour(kind: DropKind): string {+ switch (kind) {+ case "wide":+ return this.palette.powerWide;+ case "slow":+ return this.palette.powerSlow;+ case "multi":+ return this.palette.powerMulti;+ case "life":+ return this.palette.powerLife;+ default:+ return this.palette.powerBane;+ }+ }++ private drawDrops(): void {+ const { ctx } = this;+ for (const drop of this.drops) {+ const cx = drop.x + POWERUP_W / 2;+ const cy = drop.y + POWERUP_H / 2;+ const bane = isBane(drop.kind);++ ctx.save();+ ctx.beginPath();+ if (bane) {+ // Banes are spiked as well as red: shape carries at a glance, and it+ // still reads for anyone who cannot tell the colours apart.+ const spike = 5;+ ctx.moveTo(drop.x, cy);+ ctx.lineTo(drop.x + spike, drop.y);+ ctx.lineTo(drop.x + POWERUP_W - spike, drop.y);+ ctx.lineTo(drop.x + POWERUP_W, cy);+ ctx.lineTo(drop.x + POWERUP_W - spike, drop.y + POWERUP_H);+ ctx.lineTo(drop.x + spike, drop.y + POWERUP_H);+ ctx.closePath();+ } else {+ ctx.roundRect(drop.x, drop.y, POWERUP_W, POWERUP_H, 5);+ }+ ctx.fillStyle = this.dropColour(drop.kind);+ ctx.fill();++ // Glyphs are drawn rather than set as text, so no font has to load.+ ctx.strokeStyle = this.palette.page;+ ctx.fillStyle = this.palette.page;+ ctx.lineWidth = 1.6;+ ctx.lineCap = "round";+ ctx.beginPath();+ switch (drop.kind) {+ case "wide":+ // Outward arrows.+ ctx.moveTo(cx - 8, cy);+ ctx.lineTo(cx + 8, cy);+ for (const [tip, inner] of [+ [cx - 8, cx - 5],+ [cx + 8, cx + 5],+ ]) {+ ctx.moveTo(tip, cy);+ ctx.lineTo(inner, cy - 3);+ ctx.moveTo(tip, cy);+ ctx.lineTo(inner, cy + 3);+ }+ ctx.stroke();+ break;+ case "shrink":+ // The same arrows, turned inward.+ ctx.moveTo(cx - 8, cy);+ ctx.lineTo(cx + 8, cy);+ for (const [tip, outer] of [+ [cx - 4, cx - 7],+ [cx + 4, cx + 7],+ ]) {+ ctx.moveTo(tip, cy);+ ctx.lineTo(outer, cy - 3);+ ctx.moveTo(tip, cy);+ ctx.lineTo(outer, cy + 3);+ }+ ctx.stroke();+ break;+ case "slow":+ ctx.arc(cx, cy, 5.5, 0, Math.PI * 2);+ ctx.stroke();+ ctx.beginPath();+ ctx.moveTo(cx, cy - 3);+ ctx.lineTo(cx, cy);+ ctx.lineTo(cx + 3, cy);+ ctx.stroke();+ break;+ case "fast":+ // Stacked chevrons, the usual shorthand for speed.+ for (const dy of [-3.5, 1]) {+ ctx.moveTo(cx - 5, cy + dy);+ ctx.lineTo(cx, cy + dy + 3.5);+ ctx.lineTo(cx + 5, cy + dy);+ }+ ctx.stroke();+ break;+ case "reverse":+ // A U-turn: right along the bottom, back along the top.+ ctx.moveTo(cx - 6, cy + 3.5);+ ctx.lineTo(cx + 3, cy + 3.5);+ ctx.arc(cx + 3, cy, 3.5, Math.PI / 2, -Math.PI / 2, false);+ ctx.lineTo(cx - 6, cy - 3.5);+ ctx.stroke();+ ctx.beginPath();+ ctx.moveTo(cx - 6, cy - 3.5);+ ctx.lineTo(cx - 3, cy - 6);+ ctx.moveTo(cx - 6, cy - 3.5);+ ctx.lineTo(cx - 3, cy - 1);+ ctx.stroke();+ break;+ case "multi":+ for (const [dx, dy] of [+ [-6, 2],+ [0, -3],+ [6, 2],+ ]) {+ ctx.beginPath();+ ctx.arc(cx + dx, cy + dy, 2.4, 0, Math.PI * 2);+ ctx.fill();+ }+ break;+ case "life":+ ctx.moveTo(cx - 5, cy);+ ctx.lineTo(cx + 5, cy);+ ctx.moveTo(cx, cy - 5);+ ctx.lineTo(cx, cy + 5);+ ctx.stroke();+ break;+ }+ ctx.restore();+ }+ }++ private drawMark(): void {+ const target = paddlePose({+ x: this.paddleX,+ y: PADDLE_Y,+ w: this.paddleW,+ h: PADDLE_H,+ });+ const flight = clamp(this.introElapsed / MARK_FLIGHT_MS, 0, 1);+ const pose =+ this.introFrom && flight < 1+ ? lerpPose(this.introFrom, target, easeOutBack(flight))+ : target;++ this.fillQuad(pose.a, this.palette.markSoft);+ this.fillQuad(pose.b, this.palette.markStrong);+ }++ private fillQuad(quad: Quad, fill: string): void {+ const { ctx } = this;+ ctx.beginPath();+ ctx.moveTo(quad[0].x, quad[0].y);+ for (let i = 1; i < quad.length; i++) ctx.lineTo(quad[i].x, quad[i].y);+ ctx.closePath();+ ctx.fillStyle = fill;+ ctx.fill();+ }++ private drawBalls(): void {+ const { ctx } = this;+ ctx.fillStyle = this.palette.ball;+ for (const ball of this.balls) {+ ctx.beginPath();+ ctx.arc(ball.x, ball.y, BALL_R, 0, Math.PI * 2);+ ctx.fill();+ }+ }+}diff --git a/frontend/editor/src/core/components/easterEgg/brickGame/brickGameGeometry.test.ts b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameGeometry.test.tsnew file mode 100644index 0000000000..2cdfac8507--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameGeometry.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from "vitest";+import {+ type Box,+ type Quad,+ easeOutBack,+ lerpPose,+ logoPose,+ paddlePose,+} from "@app/components/easterEgg/brickGame/brickGameGeometry";++const spanX = (quad: Quad) => ({+ min: Math.min(...quad.map((p) => p.x)),+ max: Math.max(...quad.map((p) => p.x)),+});+const spanY = (quad: Quad) => ({+ min: Math.min(...quad.map((p) => p.y)),+ max: Math.max(...quad.map((p) => p.y)),+});++/** Opposite sides equal and parallel - the property the corner tween relies on. */+function isParallelogram(quad: Quad): boolean {+ const [tl, tr, br, bl] = quad;+ return (+ Math.abs(tr.x - tl.x - (br.x - bl.x)) < 1e-9 &&+ Math.abs(tr.y - tl.y - (br.y - bl.y)) < 1e-9+ );+}++const PADDLE: Box = { x: 100, y: 500, w: 132, h: 16 };++describe("paddlePose", () => {+ it("fills the collision box exactly, so the ball hits what is drawn", () => {+ const { a, b } = paddlePose(PADDLE);+ expect(spanX(a).min).toBeCloseTo(PADDLE.x);+ expect(spanX(b).max).toBeCloseTo(PADDLE.x + PADDLE.w);+ for (const piece of [a, b]) {+ expect(spanY(piece).min).toBeCloseTo(PADDLE.y);+ expect(spanY(piece).max).toBeCloseTo(PADDLE.y + PADDLE.h);+ }+ });++ it("leaves a gap between the two pieces rather than overlapping them", () => {+ const { a, b } = paddlePose(PADDLE);+ // Compared along the bottom edge, where both pieces start unskewed.+ const gap = b[3].x - a[2].x;+ expect(gap).toBeGreaterThan(0);+ expect(gap).toBeLessThan(PADDLE.w / 4);+ });++ it("draws both pieces as parallelograms", () => {+ const { a, b } = paddlePose(PADDLE);+ expect(isParallelogram(a)).toBe(true);+ expect(isParallelogram(b)).toBe(true);+ });++ it("tracks the box as the paddle moves", () => {+ const moved = paddlePose({ ...PADDLE, x: PADDLE.x + 40 });+ expect(spanX(moved.a).min).toBeCloseTo(PADDLE.x + 40);+ });+});++describe("logoPose", () => {+ it("keeps the mark inside the box and preserves its aspect ratio", () => {+ const box: Box = { x: 10, y: 20, w: 64, h: 64 };+ const { a, b } = logoPose(box);+ for (const piece of [a, b]) {+ expect(spanX(piece).min).toBeGreaterThanOrEqual(box.x - 1e-9);+ expect(spanX(piece).max).toBeLessThanOrEqual(box.x + box.w + 1e-9);+ expect(spanY(piece).min).toBeGreaterThanOrEqual(box.y - 1e-9);+ expect(spanY(piece).max).toBeLessThanOrEqual(box.y + box.h + 1e-9);+ expect(isParallelogram(piece)).toBe(true);+ }+ // The mark is taller than it is wide, so a square box letterboxes sideways.+ expect(spanX(b).max - spanX(a).min).toBeLessThan(box.w);+ expect(spanY(a).max - spanY(a).min).toBeGreaterThan(0);+ });+});++describe("easeOutBack", () => {+ it("pins both ends so the mark starts at the logo and lands on the paddle", () => {+ expect(easeOutBack(0)).toBeCloseTo(0);+ expect(easeOutBack(1)).toBeCloseTo(1);+ });++ it("overshoots, then settles back", () => {+ const peak = Math.max(+ ...Array.from({ length: 99 }, (_, i) => easeOutBack((i + 1) / 100)),+ );+ expect(peak).toBeGreaterThan(1);+ // Small enough that the paddle never leaves the playfield on the way past.+ expect(peak).toBeLessThan(1.12);+ });+});++describe("lerpPose", () => {+ const from = logoPose({ x: 0, y: 0, w: 40, h: 44 });+ const to = paddlePose(PADDLE);++ it("returns the endpoints unchanged at t=0 and t=1", () => {+ expect(lerpPose(from, to, 0)).toEqual(from);+ expect(lerpPose(from, to, 1)).toEqual(to);+ });++ it("stays a parallelogram all the way through the morph", () => {+ for (const t of [0.1, 0.25, 0.5, 0.75, 0.9]) {+ const mid = lerpPose(from, to, t);+ expect(isParallelogram(mid.a)).toBe(true);+ expect(isParallelogram(mid.b)).toBe(true);+ }+ });++ it("moves monotonically towards the paddle", () => {+ const early = lerpPose(from, to, 0.25).a[0];+ const late = lerpPose(from, to, 0.75).a[0];+ const target = to.a[0];+ expect(Math.abs(late.y - target.y)).toBeLessThan(+ Math.abs(early.y - target.y),+ );+ });+});diff --git a/frontend/editor/src/core/components/easterEgg/brickGame/brickGameGeometry.ts b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameGeometry.tsnew file mode 100644index 0000000000..3eb66fa37f--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameGeometry.ts@@ -0,0 +1,128 @@+/**+ * The brand mark as two movable parallelograms, and the maths that carries them+ * from the logo's pose in the nav rail to the paddle's pose at the foot of the+ * playfield.+ *+ * Both poses are parallelograms, so interpolating the four corners is an exact+ * affine tween with no intermediate distortion — the same property BrandMark.css+ * exploits to morph the logo into its chevron with a plain CSS matrix.+ */++export interface Point {+ x: number;+ y: number;+}++/** Corners in a fixed cycle — leftTop, rightTop, rightBottom, leftBottom. */+export type Quad = [Point, Point, Point, Point];++/** The mark's two pieces: `a` is the soft/back parallelogram, `b` the front one. */+export interface MarkPose {+ a: Quad;+ b: Quad;+}++export interface Box {+ x: number;+ y: number;+ w: number;+ h: number;+}++/** The mark's own viewBox, matching the `d` attributes in BrandMark.tsx. */+const LOGO_VIEW_W = 71;+const LOGO_VIEW_H = 79;++const LOGO_A: Quad = [+ { x: 0, y: 39 },+ { x: 46.5, y: 0 },+ { x: 46.5, y: 35.5 },+ { x: 0, y: 74.5 },+];++const LOGO_B: Quad = [+ { x: 24, y: 43 },+ { x: 70.5, y: 4 },+ { x: 70.5, y: 39.5 },+ { x: 24, y: 78.5 },+];++/** How far the paddle's top edge leans right of its bottom edge. */+const PADDLE_SKEW = 10;+/** The sliver of playfield visible between the two pieces, measured across. */+const PADDLE_GAP = 10;++function fitQuad(+ quad: Quad,+ box: Box,+ scale: number,+ ox: number,+ oy: number,+): Quad {+ return quad.map((p) => ({+ x: box.x + ox + p.x * scale,+ y: box.y + oy + p.y * scale,+ })) as Quad;+}++/** The mark upright and centred inside `box`, preserving its aspect ratio. */+export function logoPose(box: Box): MarkPose {+ const scale = Math.min(box.w / LOGO_VIEW_W, box.h / LOGO_VIEW_H);+ const ox = (box.w - LOGO_VIEW_W * scale) / 2;+ const oy = (box.h - LOGO_VIEW_H * scale) / 2;+ return {+ a: fitQuad(LOGO_A, box, scale, ox, oy),+ b: fitQuad(LOGO_B, box, scale, ox, oy),+ };+}++/** One right-leaning parallelogram whose bottom edge runs `w` from `x`. */+function slantedBar(x: number, y: number, w: number, h: number): Quad {+ return [+ { x: x + PADDLE_SKEW, y },+ { x: x + w + PADDLE_SKEW, y },+ { x: x + w, y: y + h },+ { x, y: y + h },+ ];+}++/**+ * The mark laid flat as a paddle, sized to exactly fill the collision box so+ * what the ball hits is what the player sees.+ */+export function paddlePose(box: Box): MarkPose {+ // Each bar overhangs its bottom edge by the skew, so only the trailing piece's+ // overhang adds to the total: 2 * pieceW + gap + skew must equal the box width.+ const pieceW = (box.w - PADDLE_GAP - PADDLE_SKEW) / 2;+ const secondX = box.x + pieceW + PADDLE_GAP;+ return {+ a: slantedBar(box.x, box.y, pieceW, box.h),+ b: slantedBar(secondX, box.y, pieceW, box.h),+ };+}++function lerpQuad(from: Quad, to: Quad, t: number): Quad {+ return from.map((p, i) => ({+ x: p.x + (to[i].x - p.x) * t,+ y: p.y + (to[i].y - p.y) * t,+ })) as Quad;+}++export function lerpPose(from: MarkPose, to: MarkPose, t: number): MarkPose {+ return { a: lerpQuad(from.a, to.a, t), b: lerpQuad(from.b, to.b, t) };+}++/**+ * Overshoots the target slightly and settles back, so the mark arrives with a+ * weight to it rather than easing politely to a stop. The overshoot is small+ * enough that the paddle never leaves the playfield on the way past.+ */+export function easeOutBack(t: number): number {+ const overshoot = 1.22;+ const p = t - 1;+ return 1 + (overshoot + 1) * p ** 3 + overshoot * p ** 2;+}++export function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}diff --git a/frontend/editor/src/core/components/easterEgg/collectThumbnails.test.ts b/frontend/editor/src/core/components/easterEgg/collectThumbnails.test.tsnew file mode 100644index 0000000000..d3a4789c6f--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/collectThumbnails.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it } from "vitest";+import type { StirlingFileStub } from "@app/types/fileContext";+import {+ MAX_THUMBNAILS,+ planThumbnails,+} from "@app/components/easterEgg/collectThumbnails";++/** Only the thumbnail-bearing fields matter to the planner. */+function stub(options: {+ pages?: (string | undefined)[];+ totalPages?: number;+ thumbnailUrl?: string;+}): StirlingFileStub {+ const hasProcessed =+ options.pages !== undefined || options.totalPages !== undefined;+ return {+ thumbnailUrl: options.thumbnailUrl,+ processedFile: hasProcessed+ ? {+ pages: (options.pages ?? []).map((thumbnail) => ({ thumbnail })),+ totalPages: options.totalPages,+ }+ : undefined,+ } as StirlingFileStub;+}++/** Compact "file:page" view of a plan, for readable expectations. */+const shape = (plan: ReturnType<typeof planThumbnails>) =>+ plan.map((r) => `${r.fileIndex}:${r.pageNumber}`);++describe("planThumbnails", () => {+ it("plans nothing when there are no files", () => {+ expect(planThumbnails([])).toEqual([]);+ });++ it("plans the first page of a file nothing has looked at yet", () => {+ // A freshly opened file has no page data at all, so page 1 is all we know.+ const plan = planThumbnails([stub({})]);+ expect(shape(plan)).toEqual(["0:1"]);+ expect(plan[0].existing).toBeUndefined();+ });++ it("interleaves files so a long document cannot crowd the others out", () => {+ const plan = planThumbnails([+ stub({ totalPages: 4 }),+ stub({ totalPages: 1 }),+ stub({ totalPages: 2 }),+ ]);+ expect(shape(plan)).toEqual([+ "0:1",+ "1:1",+ "2:1",+ "0:2",+ "2:2",+ "0:3",+ "0:4",+ ]);+ });++ it("represents every file even when the wall fills up", () => {+ const plan = planThumbnails([+ stub({ totalPages: 500 }),+ stub({ totalPages: 500 }),+ stub({ totalPages: 500 }),+ ]);+ expect(plan).toHaveLength(MAX_THUMBNAILS);+ const files = new Set(plan.map((r) => r.fileIndex));+ expect([...files].sort()).toEqual([0, 1, 2]);+ });++ it("fills the whole wall from one document when it is the only one open", () => {+ const plan = planThumbnails([stub({ totalPages: 500 })]);+ expect(plan).toHaveLength(MAX_THUMBNAILS);+ // Distinct pages, so the wall is not the same page over and over.+ expect(new Set(plan.map((r) => r.pageNumber)).size).toBe(MAX_THUMBNAILS);+ });++ it("shares the wall out evenly between several documents", () => {+ const plan = planThumbnails([+ stub({ totalPages: 500 }),+ stub({ totalPages: 500 }),+ stub({ totalPages: 500 }),+ ]);+ const perFile = [0, 1, 2].map(+ (i) => plan.filter((r) => r.fileIndex === i).length,+ );+ expect(perFile).toEqual([13, 13, 13]);+ });++ it("reuses a page thumbnail the app has already rendered", () => {+ const plan = planThumbnails([stub({ pages: ["a1", "a2"] })]);+ expect(plan.map((r) => r.existing)).toEqual(["a1", "a2"]);+ });++ it("marks pages with no thumbnail for rendering", () => {+ const plan = planThumbnails([stub({ pages: ["a1", undefined, "a3"] })]);+ expect(shape(plan)).toEqual(["0:1", "0:2", "0:3"]);+ expect(plan.map((r) => r.existing)).toEqual(["a1", undefined, "a3"]);+ });++ it("uses a file's own thumbnail for its first page only", () => {+ const plan = planThumbnails([+ stub({ totalPages: 2, thumbnailUrl: "file-a" }),+ ]);+ expect(plan[0].existing).toBe("file-a");+ expect(plan[1].existing).toBeUndefined();+ });++ it("prefers a page thumbnail over the file's own", () => {+ const plan = planThumbnails([+ stub({ pages: ["a1"], thumbnailUrl: "file-a" }),+ ]);+ expect(plan[0].existing).toBe("a1");+ });++ it("does not spend two bricks on the same image", () => {+ const plan = planThumbnails([+ stub({ pages: ["shared", "a2"] }),+ stub({ pages: ["shared"] }),+ ]);+ expect(plan.map((r) => r.existing)).toEqual(["shared", "a2"]);+ });++ it("honours a caller-supplied cap", () => {+ const plan = planThumbnails([stub({ totalPages: 5 })], 2);+ expect(plan).toHaveLength(2);+ });+});diff --git a/frontend/editor/src/core/components/easterEgg/collectThumbnails.ts b/frontend/editor/src/core/components/easterEgg/collectThumbnails.tsnew file mode 100644index 0000000000..81f6e290b9--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/collectThumbnails.ts@@ -0,0 +1,61 @@+import type { StirlingFileStub } from "@app/types/fileContext";++/** The wall is 13x3, so more thumbnails than that would never be seen. */+export const MAX_THUMBNAILS = 39;+export interface ThumbnailRequest {+ /** Index into the file list this plan was built from. */+ fileIndex: number;+ /** 1-based, as the thumbnail service expects. */+ pageNumber: number;+ /** Already generated and reusable; absent means it has to be rendered. */+ existing?: string;+}++/** How many pages a stub is known to have, as far as the app has worked out. */+function knownPageCount(stub: StirlingFileStub): number {+ const pages = stub.processedFile?.pages;+ if (pages && pages.length > 0) return pages.length;+ const total = stub.processedFile?.totalPages;+ if (typeof total === "number" && total > 0) return total;+ // Nothing has looked at the file yet; its own thumbnail is all there is.+ return 1;+}++/**+ * Plans which page of which file faces each brick.+ *+ * Requests are interleaved, one page from each file in turn: taken depth-first+ * a single long document fills the whole wall and every other open file goes+ * unseen. A page the app has already rendered is reused; the rest are left for+ * the caller to generate, because in practice almost nothing is pre-rendered -+ * page thumbnails only exist once something like the page editor has asked for+ * them, so a freshly opened file offers at most one image for the whole wall.+ */+export function planThumbnails(+ stubs: readonly StirlingFileStub[],+ max: number = MAX_THUMBNAILS,+): ThumbnailRequest[] {+ // No per-file cap: the interleaving already keeps one document from crowding+ // the others out, and capping per file only cost variety when few are open.+ // Total work stays bounded by `max`.+ const depths = stubs.map((stub) => Math.min(knownPageCount(stub), max));+ const deepest = depths.reduce((n, d) => Math.max(n, d), 0);++ const plan: ThumbnailRequest[] = [];+ const seen = new Set<string>();+ for (let page = 1; page <= deepest; page++) {+ for (const [fileIndex, stub] of stubs.entries()) {+ if (page > depths[fileIndex]) continue;+ const pageThumb = stub.processedFile?.pages?.[page - 1]?.thumbnail;+ // The file's own thumbnail stands in for its first page only.+ const existing =+ pageThumb ?? (page === 1 ? stub.thumbnailUrl : undefined);+ // The same image twice would waste a brick on a repeat.+ if (existing && seen.has(existing)) continue;+ if (existing) seen.add(existing);+ plan.push({ fileIndex, pageNumber: page, existing });+ if (plan.length >= max) return plan;+ }+ }+ return plan;+}diff --git a/frontend/editor/src/core/components/easterEgg/useBrandFlourish.test.tsx b/frontend/editor/src/core/components/easterEgg/useBrandFlourish.test.tsxnew file mode 100644index 0000000000..7a8ea4a3b0--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/useBrandFlourish.test.tsx@@ -0,0 +1,105 @@+import { renderHook } from "@testing-library/react";+import { act } from "react";+import { describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { AppConfigProvider } from "@app/contexts/AppConfigContext";+import { FileStoreContext } from "@app/contexts/file/contexts";+import type { FileStateStore } from "@app/contexts/file/contexts";+import type { FileContextState } from "@app/types/fileContext";+import { useBrandFlourish } from "@app/components/easterEgg/useBrandFlourish";+import type { ReactNode } from "react";++vi.mock("@app/services/thumbnailGenerationService", () => ({+ thumbnailGenerationService: { generateThumbnails: vi.fn(async () => []) },+}));++/** AppConfigProvider reads through react-query, so it needs a client. */+function configWrapper(+ enableEasterEggs: boolean,+ store?: FileStateStore,+): ({ children }: { children: ReactNode }) => ReactNode {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return ({ children }) => (+ <QueryClientProvider client={client}>+ <AppConfigProvider autoFetch={false} initialConfig={{ enableEasterEggs }}>+ {store ? (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ ) : (+ children+ )}+ </AppConfigProvider>+ </QueryClientProvider>+ );+}++/** Config only, no file provider: the processor's shape. */+const withConfigOnly = configWrapper(true);+const withFileStore = (store: FileStateStore) => configWrapper(true, store);++function emptyStore(): FileStateStore {+ const getStirlingFileStubs = vi.fn(() => []);+ const getFiles = vi.fn(() => []);+ return {+ // Only the `files` slice is read; the rest of the state is not touched.+ getState: () =>+ ({ files: { ids: [], byId: {} } }) as unknown as FileContextState,+ subscribe: () => () => {},+ selectors: {+ getStirlingFileStubs,+ getFiles,+ } as unknown as FileStateStore["selectors"],+ };+}++describe("useBrandFlourish", () => {+ it("offers no trigger when the feature is switched off", () => {+ const { result } = renderHook(() => useBrandFlourish(), {+ wrapper: configWrapper(false),+ });+ expect(result.current.trigger).toBeUndefined();+ expect(result.current.overlay).toBeNull();+ });++ it("offers a trigger when the feature is on", () => {+ const { result } = renderHook(() => useBrandFlourish(), {+ wrapper: withFileStore(emptyStore()),+ });+ expect(result.current.trigger).toBeTypeOf("function");+ });++ // The processor renders QuickNavHostBridge but mounts no FileContextProvider.+ // Reaching for the file hooks here threw and took the whole page down.+ describe("without a file provider", () => {+ it("mounts without throwing", () => {+ expect(() =>+ renderHook(() => useBrandFlourish(), { wrapper: withConfigOnly }),+ ).not.toThrow();+ });++ it("still opens the game, just with no pages to show", () => {+ const { result } = renderHook(() => useBrandFlourish(), {+ wrapper: withConfigOnly,+ });+ expect(result.current.overlay).toBeNull();++ act(() => result.current.trigger?.(null));+ expect(result.current.overlay).not.toBeNull();+ });+ });++ it("asks the store for the open files when one is mounted", () => {+ const store = emptyStore();+ const { result } = renderHook(() => useBrandFlourish(), {+ wrapper: withFileStore(store),+ });++ act(() => result.current.trigger?.(null));+ expect(result.current.overlay).not.toBeNull();+ expect(store.selectors.getStirlingFileStubs).toHaveBeenCalled();+ expect(store.selectors.getFiles).toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/components/easterEgg/useBrandFlourish.tsx b/frontend/editor/src/core/components/easterEgg/useBrandFlourish.tsxnew file mode 100644index 0000000000..ac84423294--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/useBrandFlourish.tsx@@ -0,0 +1,168 @@+import {+ Suspense,+ lazy,+ useCallback,+ useContext,+ useRef,+ useState,+ type ReactNode,+} from "react";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import { FileStoreContext } from "@app/contexts/file/contexts";+import { thumbnailGenerationService } from "@app/services/thumbnailGenerationService";+import {+ type ThumbnailRequest,+ planThumbnails,+} from "@app/components/easterEgg/collectThumbnails";+import type { StirlingFile } from "@app/types/fileContext";++// Its own chunk: nothing here is fetched unless somebody actually finds it.+const BrickGame = lazy(+ () => import("@app/components/easterEgg/brickGame/BrickGame"),+);++/** Small: the bricks are 49x68, so anything larger is detail nobody sees. */+const THUMBNAIL_SCALE = 0.3;++export interface BrandFlourish {+ /**+ * Undefined where an admin has turned the hidden features off, so the+ * caller's trigger has nothing to call and no gate of its own to remember.+ */+ trigger?: (originRect: DOMRect | null) => void;+ overlay: ReactNode;+}++function decode(src: string): Promise<HTMLImageElement | null> {+ return new Promise((resolve) => {+ const image = new Image();+ image.onload = () => resolve(image);+ image.onerror = () => resolve(null);+ image.src = src;+ });+}++/**+ * Renders the planned pages, reusing anything already generated.+ *+ * Work is grouped into one service call per file, and `onBatch` fires as each+ * file lands so the wall fills in progressively rather than waiting on the+ * slowest document. Order is kept against the plan, so pages stay interleaved+ * across files however they arrive.+ */+async function renderPlan(+ plan: readonly ThumbnailRequest[],+ files: readonly StirlingFile[],+ onBatch: (images: HTMLImageElement[]) => void,+): Promise<void> {+ const sources = new Map<number, string>();+ const missingByFile = new Map<number, number[]>();+ plan.forEach((request, index) => {+ if (request.existing) {+ sources.set(index, request.existing);+ return;+ }+ const pending = missingByFile.get(request.fileIndex) ?? [];+ pending.push(index);+ missingByFile.set(request.fileIndex, pending);+ });++ const publish = async () => {+ const ordered = plan+ .map((_, index) => sources.get(index))+ .filter((src): src is string => Boolean(src));+ const decoded = await Promise.all(ordered.map(decode));+ onBatch(decoded.filter((img): img is HTMLImageElement => Boolean(img)));+ };++ // Anything the app had already rendered goes up straight away.+ if (sources.size > 0) await publish();++ for (const [fileIndex, planIndexes] of missingByFile) {+ const file = files[fileIndex];+ if (!file) continue;+ try {+ const buffer = await file.arrayBuffer();+ const results = await thumbnailGenerationService.generateThumbnails(+ file.fileId,+ buffer,+ planIndexes.map((index) => plan[index].pageNumber),+ { scale: THUMBNAIL_SCALE },+ );+ for (const result of results) {+ if (!result.success || !result.thumbnail) continue;+ const planIndex = planIndexes.find(+ (index) => plan[index].pageNumber === result.pageNumber,+ );+ if (planIndex !== undefined) sources.set(planIndex, result.thumbnail);+ }+ await publish();+ } catch {+ // A document that will not render just leaves its bricks blank.+ }+ }+}++/**+ * Owns the hidden game's lifetime on the app side of the quick-nav seam. The+ * trigger lives out in the nav rail, which renders above the app's providers and+ * so cannot read app config itself; handing the rail an action that simply does+ * not exist when `enableEasterEggs` is false keeps the whole switch here.+ *+ * Being app-side is also what lets the bricks be faced with the user's own+ * pages: the file context is only reachable from in here.+ */+export function useBrandFlourish(): BrandFlourish {+ const { config } = useAppConfig();+ const enabled = config?.enableEasterEggs === true;+ /**+ * The store is read straight off its context, not through `useAllFiles`.+ * This hook runs from QuickNavHostBridge, which BOTH apps render, and only+ * the editor mounts a FileContextProvider - the file hooks throw without+ * one, which took the processor page down with it. Reading the context+ * yields undefined there instead.+ *+ * Not subscribing is also the right call on its own: the files are wanted+ * once, when somebody triggers the game, so there is no reason to re-render+ * the bridge every time the workbench changes.+ */+ const fileStore = useContext(FileStoreContext);+ const [origin, setOrigin] = useState<DOMRect | null>(null);+ const [open, setOpen] = useState(false);+ const [images, setImages] = useState<readonly HTMLImageElement[]>([]);+ const runRef = useRef(0);++ const trigger = useCallback(+ (originRect: DOMRect | null) => {+ setOrigin(originRect);+ setImages([]);+ setOpen(true);+ if (!fileStore) return;++ // Opening does not wait on the pages: the game starts with blank ones+ // and they arrive while the fly-in is still running.+ const run = ++runRef.current;+ const ids = fileStore.getState().files.ids;+ const plan = planThumbnails(+ fileStore.selectors.getStirlingFileStubs(ids),+ );+ void renderPlan(plan, fileStore.selectors.getFiles(ids), (loaded) => {+ // A game closed and reopened mid-render must not be fed the old pages.+ if (runRef.current === run) setImages(loaded);+ });+ },+ [fileStore],+ );++ const close = useCallback(() => setOpen(false), []);++ return {+ trigger: enabled ? trigger : undefined,+ overlay:+ enabled && open ? (+ <Suspense fallback={null}>+ <BrickGame originRect={origin} images={images} onClose={close} />+ </Suspense>+ ) : null,+ };+}diff --git a/frontend/editor/src/core/components/easterEgg/useSecretClicks.test.tsx b/frontend/editor/src/core/components/easterEgg/useSecretClicks.test.tsxnew file mode 100644index 0000000000..79bbf404b0--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/useSecretClicks.test.tsx@@ -0,0 +1,79 @@+import { renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ CLICKS_REQUIRED,+ WINDOW_MS,+ useSecretClicks,+} from "@app/components/easterEgg/useSecretClicks";++// Driven off the real constants, so retuning the trigger does not need these+// rewritten - only the behaviour is asserted, never the specific number.++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++function setup() {+ const onUnlock = vi.fn();+ const { result } = renderHook(() => useSecretClicks<string>(onUnlock));+ return { onUnlock, click: (payload = "rect") => result.current(payload) };+}++describe("useSecretClicks", () => {+ it("does not unlock on a single click", () => {+ const { onUnlock, click } = setup();+ click();+ expect(onUnlock).not.toHaveBeenCalled();+ });++ it("unlocks once a fast enough burst arrives", () => {+ const { onUnlock, click } = setup();+ for (let i = 0; i < CLICKS_REQUIRED; i++) click();+ expect(onUnlock).toHaveBeenCalledTimes(1);+ });++ it("does not unlock one click short of the threshold", () => {+ const { onUnlock, click } = setup();+ for (let i = 0; i < CLICKS_REQUIRED - 1; i++) click();+ expect(onUnlock).not.toHaveBeenCalled();+ });++ it("never unlocks on a slow trickle, however many clicks", () => {+ const { onUnlock, click } = setup();+ for (let i = 0; i < CLICKS_REQUIRED * 3; i++) {+ click();+ vi.advanceTimersByTime(WINDOW_MS + 1);+ }+ expect(onUnlock).not.toHaveBeenCalled();+ });++ it("hands the unlocking click's payload to the caller", () => {+ const { onUnlock, click } = setup();+ for (let i = 0; i < CLICKS_REQUIRED - 1; i++) click("early");+ click("the one that counted");+ expect(onUnlock).toHaveBeenCalledWith("the one that counted");+ });++ it("starts counting again after it fires, rather than firing every click", () => {+ const { onUnlock, click } = setup();+ for (let i = 0; i < CLICKS_REQUIRED; i++) click();+ expect(onUnlock).toHaveBeenCalledTimes(1);+ // The counter resets, so the next click starts a fresh attempt.+ click();+ expect(onUnlock).toHaveBeenCalledTimes(1);+ });++ it("does not carry stale clicks over from an abandoned attempt", () => {+ const { onUnlock, click } = setup();+ // An attempt that got one click from the threshold, then was given up on.+ for (let i = 0; i < CLICKS_REQUIRED - 1; i++) click();+ vi.advanceTimersByTime(WINDOW_MS + 1);+ // The stale clicks must not complete it.+ click();+ expect(onUnlock).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/components/easterEgg/useSecretClicks.ts b/frontend/editor/src/core/components/easterEgg/useSecretClicks.tsnew file mode 100644index 0000000000..fa23e0fbc7--- /dev/null+++ b/frontend/editor/src/core/components/easterEgg/useSecretClicks.ts@@ -0,0 +1,40 @@+import { useCallback, useRef } from "react";++/** Clicks needed, and the window they must all land inside. */+export const CLICKS_REQUIRED = 12;+/**+ * Widened along with the count: twelve clicks in three seconds is a test of how+ * fast someone can click, which is not the point. Four seconds keeps it a+ * deliberate burst that anyone can manage.+ */+export const WINDOW_MS = 4000;++/**+ * Counts rapid repeat clicks on a control without changing what that control+ * does — every click still runs the host's own handler, and only the last one+ * of a fast burst also unlocks. Deliberate impatience is the signal: a dozen+ * clicks in four seconds is not something a normal user produces by accident.+ *+ * The payload from the unlocking click is handed on, so a caller can pass+ * through something only the event knows (such as the trigger's own rect).+ */+export function useSecretClicks<T>(+ onUnlock: (payload: T) => void,+): (payload: T) => void {+ const times = useRef<number[]>([]);++ return useCallback(+ (payload: T) => {+ const now = Date.now();+ const recent = times.current.filter((t) => now - t <= WINDOW_MS);+ recent.push(now);+ if (recent.length >= CLICKS_REQUIRED) {+ times.current = [];+ onUnlock(payload);+ return;+ }+ times.current = recent;+ },+ [onUnlock],+ );+}diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavBrand.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavBrand.tsxindex 51b13b6a18..c43db79621 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavBrand.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavBrand.tsx@@ -1,6 +1,9 @@+import { useCallback } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@app/components/shared/Tooltip";import { BrandMark } from "@app/components/shared/BrandMark";+import { useQuickNavHost } from "@app/contexts/QuickNavHostContext";+import { useSecretClicks } from "@app/components/easterEgg/useSecretClicks";export interface QuickNavBrandProps {/** Returns the app you are in to its default state. */@@ -10,6 +13,16 @@ export interface QuickNavBrandProps {export function QuickNavBrand({ onReturnHome }: QuickNavBrandProps) {const { t } = useTranslation();const label = t("quickNav.home", "Stirling");+ const host = useQuickNavHost();++ // Nothing happens where the app has not offered the action.+ const flourish = useCallback(+ (originRect: DOMRect) => {+ host?.actions.current?.onBrandFlourish?.(originRect);+ },+ [host],+ );+ const countClick = useSecretClicks(flourish);return (<div className="quick-nav-brand">@@ -18,7 +31,16 @@ export function QuickNavBrand({ onReturnHome }: QuickNavBrandProps) {type="button"className="quick-nav-brand-button"aria-label={label}- onClick={onReturnHome}+ onClick={(event) => {+ // The rect comes off the event, not a ref: Tooltip clones its child+ // to attach its own ref and reads the child's back off the element,+ // which is what React 19 dropped.+ const rect = event.currentTarget.getBoundingClientRect();+ // Going home stays the button's only advertised job; the counter+ // rides along and can only fire on the last click of a fast burst.+ onReturnHome();+ countClick(rect);+ }}><BrandMark height="1.6rem" /></button>diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsxnew file mode 100644index 0000000000..a0b990cd6c--- /dev/null+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx@@ -0,0 +1,46 @@+import { render } from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import { describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { AppConfigProvider } from "@app/contexts/AppConfigContext";+import { QuickNavHostProvider } from "@app/contexts/QuickNavHostContext";+import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";++vi.mock("@app/services/thumbnailGenerationService", () => ({+ thumbnailGenerationService: { generateThumbnails: vi.fn(async () => []) },+}));++/**+ * The processor's provider stack, which is the point of this file: it has app+ * config and the quick-nav host, and deliberately NO FileContextProvider.+ *+ * Both apps render this bridge, and the file hooks throw outside a provider, so+ * anything here that reaches for files takes the whole processor page down with+ * a "File hooks must be used within a FileContextProvider" crash. That shipped+ * once; this test is here so it cannot ship again.+ */+function renderInProcessorShape() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <MemoryRouter>+ <QueryClientProvider client={client}>+ <AppConfigProvider+ autoFetch={false}+ initialConfig={{ enableEasterEggs: true }}+ >+ <QuickNavHostProvider>+ <QuickNavHostBridge portalAccess onOpenSettings={() => {}} />+ </QuickNavHostProvider>+ </AppConfigProvider>+ </QueryClientProvider>+ </MemoryRouter>,+ );+}++describe("QuickNavHostBridge without a FileContextProvider", () => {+ it("mounts, as the processor needs it to", () => {+ expect(() => renderInProcessorShape()).not.toThrow();+ });+});diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsxindex c6db541627..6eeb140623 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx@@ -7,6 +7,7 @@ import {import { useNotificationActions } from "@app/components/notifications/notificationActions";import { useNotificationPasswordPrompt } from "@app/components/notifications/useNotificationPasswordPrompt";import { useQuickNavToolReasons } from "@app/components/shared/quickNav/useQuickNavToolReasons";+import { useBrandFlourish } from "@app/components/easterEgg/useBrandFlourish";import { useNotificationsAvailable } from "@app/components/notifications/useNotificationsAvailable";import { useSigningBadgeCount } from "@app/hooks/signing/useSigningBadgeCount";import {@@ -53,6 +54,7 @@ export function QuickNavHostBridge({if (!endpointReasons && !extra) return undefined;return { ...endpointReasons, ...extra };}, [endpointReasons, toolReasons]);+ const brandFlourish = useBrandFlourish();const [notificationsOpen, setNotificationsOpen] = useState(false);const closeNotifications = useCallback(() => setNotificationsOpen(false), []);const { requestPassword, promptModal } =@@ -75,24 +77,29 @@ export function QuickNavHostBridge({setReaderMode: onSetReaderMode,goToDefaultState: onGoToDefaultState,toggleNotifications: () => setNotificationsOpen((open) => !open),+ onBrandFlourish: brandFlourish.trigger,},);- if (!notificationsAvailable) return null;return (<>- {/* Mounted only while open, so a closed panel never subscribes to the poll. */}- {notificationsOpen && (- <NotificationPanel- id={NOTIFICATIONS_PANEL_ID}- onClose={closeNotifications}- registry={notificationActions}- onRequestPassword={requestPassword}- className="notification-bell__panel--rail"- />+ {notificationsAvailable && (+ <>+ {/* Mounted only while open, so a closed panel never subscribes to the poll. */}+ {notificationsOpen && (+ <NotificationPanel+ id={NOTIFICATIONS_PANEL_ID}+ onClose={closeNotifications}+ registry={notificationActions}+ onRequestPassword={requestPassword}+ className="notification-bell__panel--rail"+ />+ )}+ {/* Outside the panel: an unlock closes it, and the prompt reports back afterwards. */}+ {promptModal}+ </>)}- {/* Outside the panel: an unlock closes it, and the prompt reports back afterwards. */}- {promptModal}+ {brandFlourish.overlay}</>);}diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.css b/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.cssindex 4d6845f592..8ef18e7ec8 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.css+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.css@@ -136,6 +136,9 @@background: transparent;padding: 0;cursor: pointer;+ /* Repeated fast clicks otherwise read as a double/triple click and start a+ text selection in the surrounding chrome. */+ user-select: none;}.quick-nav-brand-button:focus-visible {diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.tsxindex 1a19cffc6f..9fe409c78b 100644--- a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx@@ -41,6 +41,12 @@ export interface QuickNavHostActions {toggleNotifications?: () => void;goToDefaultState?: () => void;requestNavigation?: (go: () => void) => void;+ /**+ * Absent unless the app says the hidden novelty features are enabled, which+ * is the only gate the rail gets - see useBrandFlourish. `originRect` is the+ * clicked control, for whatever flies out of it.+ */+ onBrandFlourish?: (originRect: DOMRect | null) => void;}interface QuickNavHostValue extends QuickNavHostData {diff --git a/frontend/editor/src/core/types/appConfig.ts b/frontend/editor/src/core/types/appConfig.tsindex ef31ed4f4e..c493b646d5 100644--- a/frontend/editor/src/core/types/appConfig.ts+++ b/frontend/editor/src/core/types/appConfig.ts@@ -19,6 +19,8 @@ export interface AppConfig {enablePosthog?: boolean | null;enableScarf?: boolean | null;enableDesktopInstallSlide?: boolean;+ /** False strips the hidden novelty features - see useSecretClicks. */+ enableEasterEggs?: boolean;premiumEnabled?: boolean;premiumKey?: string;paygEnabled?: boolean;