From 143200cae6f31758b3c7604e5d49214ffe9556b5 Mon Sep 17 00:00:00 2001
From: Maurice <61554723+mauriceboe@users.noreply.github.com>
Date: Wed, 5 Aug 2026 19:59:16 +0200
Subject: [PATCH] chore(dashboard): remove the 4.0.0 release moment (#1792)
The FourZero show was built as a one-off for the 4.0.0 release and was
always meant to come back out afterwards. It lived in its own folder
plus two marked lines on the dashboard, so removing it is exactly that:
the folder and the two lines.
The beacon carried its own cut-off date of 23 August, so nothing about
this changes what users see between now and then beyond taking it out
early.
---
.../components/FourZero/NoFearBeacon.test.tsx | 381 -------
.../src/components/FourZero/NoFearBeacon.tsx | 180 ----
.../components/FourZero/NoFearShow.test.tsx | 662 ------------
client/src/components/FourZero/NoFearShow.tsx | 370 -------
client/src/components/FourZero/fourzero.css | 435 --------
.../FourZero/noFearAssembly.test.ts | 346 -------
.../src/components/FourZero/noFearAssembly.ts | 95 --
.../components/FourZero/noFearAudio.test.ts | 969 ------------------
client/src/components/FourZero/noFearAudio.ts | 530 ----------
client/src/components/FourZero/noFearLines.ts | 833 ---------------
.../components/FourZero/noFearScene.test.ts | 609 -----------
client/src/components/FourZero/noFearScene.ts | 481 ---------
client/src/pages/DashboardPage.tsx | 2 -
13 files changed, 5893 deletions(-)
delete mode 100644 client/src/components/FourZero/NoFearBeacon.test.tsx
delete mode 100644 client/src/components/FourZero/NoFearBeacon.tsx
delete mode 100644 client/src/components/FourZero/NoFearShow.test.tsx
delete mode 100644 client/src/components/FourZero/NoFearShow.tsx
delete mode 100644 client/src/components/FourZero/fourzero.css
delete mode 100644 client/src/components/FourZero/noFearAssembly.test.ts
delete mode 100644 client/src/components/FourZero/noFearAssembly.ts
delete mode 100644 client/src/components/FourZero/noFearAudio.test.ts
delete mode 100644 client/src/components/FourZero/noFearAudio.ts
delete mode 100644 client/src/components/FourZero/noFearLines.ts
delete mode 100644 client/src/components/FourZero/noFearScene.test.ts
delete mode 100644 client/src/components/FourZero/noFearScene.ts
diff --git a/client/src/components/FourZero/NoFearBeacon.test.tsx b/client/src/components/FourZero/NoFearBeacon.test.tsx
deleted file mode 100644
index ecc9e25fc..000000000
--- a/client/src/components/FourZero/NoFearBeacon.test.tsx
+++ /dev/null
@@ -1,381 +0,0 @@
-// FE-NOFEAR-BCN-001 to FE-NOFEAR-BCN-019
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
-import { render, screen, act, fireEvent } from '../../../tests/helpers/render'
-import NoFearBeacon from './NoFearBeacon'
-
-vi.mock('./NoFearShow', () => ({
- default: ({ onClose }: { onClose: () => void }) => (
-
-
-
- ),
-}))
-
-const DISMISS_KEY = 'trek.fourzero.dismissed'
-const POINT_COUNT = 24
-
-interface StrokeRecord {
- style: string
- width: number
-}
-
-interface FakeCtx {
- strokeStyle: string
- lineWidth: number
- fillStyle: string
- globalCompositeOperation: string
- setTransform: ReturnType
- clearRect: ReturnType
- beginPath: ReturnType
- moveTo: ReturnType
- lineTo: ReturnType
- stroke: ReturnType
- arc: ReturnType
- fill: ReturnType
- strokes: StrokeRecord[]
-}
-
-interface FakeObserver {
- cb: ResizeObserverCallback
- observe: ReturnType
- unobserve: ReturnType
- disconnect: ReturnType
-}
-
-let frames: FrameRequestCallback[] = []
-let cancelSpy: ReturnType
-let ctx: FakeCtx | null = null
-let observers: FakeObserver[] = []
-let randomQueue: number[] = []
-const originalGetContext = HTMLCanvasElement.prototype.getContext
-const OriginalResizeObserver = globalThis.ResizeObserver
-
-function makeCtx(): FakeCtx {
- const c: FakeCtx = {
- strokeStyle: '',
- lineWidth: 0,
- fillStyle: '',
- globalCompositeOperation: 'source-over',
- setTransform: vi.fn(),
- clearRect: vi.fn(),
- beginPath: vi.fn(),
- moveTo: vi.fn(),
- lineTo: vi.fn(),
- stroke: vi.fn(() => { c.strokes.push({ style: c.strokeStyle, width: c.lineWidth }) }),
- arc: vi.fn(),
- fill: vi.fn(),
- strokes: [],
- }
- return c
-}
-
-class FakeResizeObserver {
- observe = vi.fn()
- unobserve = vi.fn()
- disconnect = vi.fn()
- constructor(public cb: ResizeObserverCallback) { observers.push(this) }
-}
-
-/** Runs the pending rAF callback with the given timestamp (ms). */
-function frame(ms: number): void {
- const pending = frames
- frames = []
- act(() => { pending.forEach(cb => cb(ms)) })
-}
-
-function resetDrawCounters(): void {
- ctx?.moveTo.mockClear()
- ctx?.lineTo.mockClear()
- ctx?.arc.mockClear()
- ctx?.fill.mockClear()
- if (ctx) ctx.strokes.length = 0
-}
-
-function setReducedMotion(reduce: boolean): void {
- window.matchMedia = vi.fn().mockImplementation((query: string) => ({
- matches: reduce,
- media: query,
- onchange: null,
- addListener: vi.fn(),
- removeListener: vi.fn(),
- addEventListener: vi.fn(),
- removeEventListener: vi.fn(),
- dispatchEvent: vi.fn(),
- }))
-}
-
-beforeEach(() => {
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
- // Well inside the release window so the beacon is not retired by the calendar.
- vi.setSystemTime(new Date('2026-08-01T09:00:00'))
- frames = []
- observers = []
- cancelSpy = vi.fn()
- ctx = makeCtx()
- randomQueue = [0]
- let randomIdx = 0
- vi.spyOn(Math, 'random').mockImplementation(() => {
- const v = randomQueue[randomIdx % randomQueue.length]
- randomIdx++
- return v
- })
- vi.stubGlobal('requestAnimationFrame', vi.fn((cb: FrameRequestCallback) => {
- frames.push(cb)
- return frames.length
- }))
- vi.stubGlobal('cancelAnimationFrame', cancelSpy)
- globalThis.ResizeObserver = FakeResizeObserver as unknown as typeof ResizeObserver
- HTMLCanvasElement.prototype.getContext = vi.fn(() => ctx) as unknown as typeof originalGetContext
- Object.defineProperty(HTMLCanvasElement.prototype, 'clientWidth', { configurable: true, get: () => 800 })
- Object.defineProperty(HTMLCanvasElement.prototype, 'clientHeight', { configurable: true, get: () => 400 })
- Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 1 })
- setReducedMotion(false)
-})
-
-afterEach(() => {
- HTMLCanvasElement.prototype.getContext = originalGetContext
- Reflect.deleteProperty(HTMLCanvasElement.prototype, 'clientWidth')
- Reflect.deleteProperty(HTMLCanvasElement.prototype, 'clientHeight')
- globalThis.ResizeObserver = OriginalResizeObserver
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
- vi.useRealTimers()
-})
-
-describe('NoFearBeacon', () => {
- it('FE-NOFEAR-BCN-001: renders the trigger card with title, subtitle and retirement badge', () => {
- render()
-
- const play = screen.getByRole('button', { name: 'Press play.' })
- expect(play).toHaveTextContent('NO FEAR')
- expect(play).toHaveTextContent('A sign for an open world.')
- expect(screen.getByText('Shown until Aug 23')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Dismiss' })).toBeInTheDocument()
- })
-
- it('FE-NOFEAR-BCN-002: renders nothing once the release window has passed', () => {
- vi.setSystemTime(new Date('2026-08-24T00:00:01'))
-
- const { container } = render()
-
- expect(container).toBeEmptyDOMElement()
- expect(screen.queryByText('NO FEAR')).toBeNull()
- })
-
- it('FE-NOFEAR-BCN-003: stays hidden when it was dismissed before', () => {
- localStorage.setItem(DISMISS_KEY, '1')
-
- const { container } = render()
-
- expect(container).toBeEmptyDOMElement()
- })
-
- it('FE-NOFEAR-BCN-004: still renders when localStorage cannot be read', () => {
- vi.spyOn(Storage.prototype, 'getItem').mockImplementation((key: string) => {
- if (key === DISMISS_KEY) throw new Error('storage blocked')
- return null
- })
-
- render()
-
- expect(screen.getByText('NO FEAR')).toBeInTheDocument()
- })
-
- it('FE-NOFEAR-BCN-005: needs two clicks to retire the moment and persists the choice', () => {
- render()
- const dismiss = screen.getByRole('button', { name: 'Dismiss' })
-
- fireEvent.click(dismiss)
-
- expect(dismiss).toHaveTextContent('Hide for good?')
- expect(dismiss).toHaveClass('fz-beacon-dismiss-confirm')
- expect(screen.getByText('NO FEAR')).toBeInTheDocument()
-
- fireEvent.click(dismiss)
-
- expect(screen.queryByText('NO FEAR')).toBeNull()
- expect(localStorage.getItem(DISMISS_KEY)).toBe('1')
- })
-
- it('FE-NOFEAR-BCN-006: disarms the confirm state when the pointer leaves', () => {
- render()
- const dismiss = screen.getByRole('button', { name: 'Dismiss' })
-
- fireEvent.click(dismiss)
- expect(dismiss).toHaveTextContent('Hide for good?')
-
- fireEvent.mouseLeave(dismiss)
-
- expect(dismiss).not.toHaveTextContent('Hide for good?')
- expect(dismiss).not.toHaveClass('fz-beacon-dismiss-confirm')
- })
-
- it('FE-NOFEAR-BCN-007: disarms the confirm state on blur', () => {
- render()
- const dismiss = screen.getByRole('button', { name: 'Dismiss' })
-
- fireEvent.click(dismiss)
- fireEvent.blur(dismiss)
-
- expect(dismiss).not.toHaveTextContent('Hide for good?')
- })
-
- it('FE-NOFEAR-BCN-008: hides for the session when the choice cannot be persisted', () => {
- vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') })
- render()
- const dismiss = screen.getByRole('button', { name: 'Dismiss' })
-
- fireEvent.click(dismiss)
- fireEvent.click(dismiss)
-
- expect(screen.queryByText('NO FEAR')).toBeNull()
- })
-
- it('FE-NOFEAR-BCN-009: opens the show on play and closes it again', async () => {
- render()
- expect(screen.queryByRole('dialog')).toBeNull()
-
- fireEvent.click(screen.getByRole('button', { name: 'Press play.' }))
- await act(async () => { await Promise.resolve() })
-
- expect(screen.getByRole('dialog', { name: 'show stub' })).toBeInTheDocument()
-
- fireEvent.click(screen.getByRole('button', { name: 'close show' }))
-
- expect(screen.queryByRole('dialog')).toBeNull()
- expect(screen.getByText('NO FEAR')).toBeInTheDocument()
- })
-
- it('FE-NOFEAR-BCN-010: sizes the teaser canvas by capped device pixel ratio', () => {
- Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 3 })
-
- render()
-
- const canvas = document.querySelector('canvas.fz-beacon-canvas')
- expect(canvas?.width).toBe(1200)
- expect(canvas?.height).toBe(600)
- expect(ctx?.setTransform).toHaveBeenCalledWith(1.5, 0, 0, 1.5, 0, 0)
- expect(observers[0].observe).toHaveBeenCalledWith(canvas)
- })
-
- it('FE-NOFEAR-BCN-011: re-fits the canvas when the observer reports a resize', () => {
- render()
- expect(ctx?.setTransform).toHaveBeenCalledTimes(1)
-
- act(() => { observers[0].cb([], observers[0] as unknown as ResizeObserver) })
-
- expect(ctx?.setTransform).toHaveBeenCalledTimes(2)
- })
-
- it('FE-NOFEAR-BCN-012: breathes every light twice per frame and keeps animating', () => {
- render()
-
- frame(0)
-
- expect(ctx?.clearRect).toHaveBeenCalledWith(0, 0, 800, 400)
- expect(ctx?.arc).toHaveBeenCalledTimes(POINT_COUNT * 2)
- expect(ctx?.fill).toHaveBeenCalledTimes(POINT_COUNT * 2)
- expect(ctx?.moveTo).not.toHaveBeenCalled()
- expect(ctx?.globalCompositeOperation).toBe('source-over')
- expect(frames).toHaveLength(1)
- })
-
- it('FE-NOFEAR-BCN-013: spawns a golden arc between two distant lights and grows it', () => {
- // a = point 0, first b throwaway, then a far point so the search breaks at once.
- randomQueue = [0, 0, 0.9]
- render()
-
- frame(0)
- resetDrawCounters()
-
- frame(2000)
- expect(ctx?.moveTo).toHaveBeenCalledTimes(1)
- // Two passes per arc: wide warm halo, then the bright core.
- expect(ctx?.strokes).toEqual([
- { style: 'rgba(255, 180, 95, 0.12)', width: 3.4 },
- { style: 'rgba(255, 208, 130, 0.55)', width: 1.1 },
- ])
- const partial = ctx?.lineTo.mock.calls.length ?? 0
- expect(partial).toBeGreaterThan(0)
- expect(partial).toBeLessThan(22)
-
- resetDrawCounters()
- frame(3600)
- expect(ctx?.lineTo).toHaveBeenCalledTimes(22)
- })
-
- it('FE-NOFEAR-BCN-014: fades an arc out and drops it once it is older than 4.5s', () => {
- randomQueue = [0, 0, 0.9]
- render()
-
- frame(0)
- frame(2000)
-
- // 3.75s old: half faded, drawn behind the arc that just spawned.
- resetDrawCounters()
- frame(5750)
- expect(ctx?.moveTo).toHaveBeenCalledTimes(2)
- expect(ctx?.strokes.slice(2)).toEqual([
- { style: 'rgba(255, 180, 95, 0.06)', width: 3.4 },
- { style: 'rgba(255, 208, 130, 0.275)', width: 1.1 },
- ])
-
- // Past 4.5s it is dropped and only the younger arc remains.
- resetDrawCounters()
- frame(7000)
- expect(ctx?.moveTo).toHaveBeenCalledTimes(1)
- })
-
- it('FE-NOFEAR-BCN-015: gives up looking for a distant partner after six tries', () => {
- // Every draw returns the same index, so no candidate is ever far enough away.
- randomQueue = [0]
- render()
-
- frame(0)
- resetDrawCounters()
- frame(2000)
-
- expect(ctx?.moveTo).toHaveBeenCalledTimes(1)
- expect(Math.random).toHaveBeenCalledTimes(8)
- })
-
- it('FE-NOFEAR-BCN-016: paints a single frame and stops when motion is reduced', () => {
- setReducedMotion(true)
-
- render()
- expect(frames).toHaveLength(1)
-
- frame(0)
-
- expect(ctx?.fill).toHaveBeenCalledTimes(POINT_COUNT * 2)
- expect(frames).toHaveLength(0)
- })
-
- it('FE-NOFEAR-BCN-017: skips the teaser entirely without a 2d context', () => {
- ctx = null
-
- render()
-
- expect(frames).toHaveLength(0)
- expect(observers).toHaveLength(0)
- expect(screen.getByText('NO FEAR')).toBeInTheDocument()
- })
-
- it('FE-NOFEAR-BCN-018: cancels the frame and disconnects the observer on unmount', () => {
- const { unmount } = render()
-
- unmount()
-
- expect(cancelSpy).toHaveBeenCalled()
- expect(observers[0].disconnect).toHaveBeenCalledTimes(1)
- })
-
- it('FE-NOFEAR-BCN-019: falls back to a pixel ratio of 1 when the browser reports none', () => {
- Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 0 })
-
- render()
-
- expect(document.querySelector('canvas.fz-beacon-canvas')?.width).toBe(800)
- expect(ctx?.setTransform).toHaveBeenCalledWith(1, 0, 0, 1, 0, 0)
- })
-})
diff --git a/client/src/components/FourZero/NoFearBeacon.tsx b/client/src/components/FourZero/NoFearBeacon.tsx
deleted file mode 100644
index 5f0db5743..000000000
--- a/client/src/components/FourZero/NoFearBeacon.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { lazy, Suspense, useEffect, useRef, useState } from 'react'
-import { X } from 'lucide-react'
-import { useTranslation } from '../../i18n'
-import { noFearChrome, noFearCopy } from './noFearLines'
-import './fourzero.css'
-
-// TREK 4.0.0 release moment — remove together with the FourZero folder.
-
-const NoFearShow = lazy(() => import('./NoFearShow'))
-
-// The moment retires itself. Last day it shows: 2026-08-23 (local midnight after
-// it ends the run). After that the beacon renders nothing even if the folder is
-// still in the build — so self-hosters who don't update past this version still
-// see it disappear on time. The end date holds regardless of updates.
-const VISIBLE_UNTIL = new Date('2026-08-24T00:00:00').getTime()
-const DISMISS_KEY = 'trek.fourzero.dismissed'
-
-// Abstract night-world for the teaser: light points loosely shaped like the
-// inhabited continents (relative coords), between which golden arcs travel.
-const TEASER_POINTS: [number, number][] = [
- [0.46, 0.28], [0.5, 0.22], [0.53, 0.3], [0.48, 0.38], [0.55, 0.42], [0.44, 0.5],
- [0.58, 0.55], [0.52, 0.62], [0.62, 0.3], [0.68, 0.4], [0.74, 0.32], [0.8, 0.45],
- [0.84, 0.58], [0.88, 0.36], [0.2, 0.3], [0.14, 0.4], [0.24, 0.52], [0.3, 0.66],
- [0.26, 0.78], [0.34, 0.35], [0.9, 0.72], [0.66, 0.68], [0.1, 0.26], [0.4, 0.72],
-]
-
-interface TeaserArc { a: number; b: number; born: number }
-
-/** The living background of the beacon: pulsing lights, traveling golden arcs. */
-function TeaserCanvas() {
- const ref = useRef(null)
- useEffect(() => {
- const cv = ref.current
- const c = cv?.getContext('2d')
- if (!cv || !c) return
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches
- const dpr = Math.min(window.devicePixelRatio || 1, 1.5)
- const fit = () => {
- cv.width = Math.round(cv.clientWidth * dpr)
- cv.height = Math.round(cv.clientHeight * dpr)
- c.setTransform(dpr, 0, 0, dpr, 0, 0)
- }
- fit()
- const ro = new ResizeObserver(fit)
- ro.observe(cv)
- const arcs: TeaserArc[] = []
- let last = 0
- let raf = 0
- const draw = (now: number) => {
- const t = now / 1000
- const w = cv.clientWidth
- const h = cv.clientHeight
- c.clearRect(0, 0, w, h)
- // A new arc every ~1.6s between two far-apart lights.
- if (t - last > 1.6 && arcs.length < 7) {
- last = t
- const a = Math.floor(Math.random() * TEASER_POINTS.length)
- let b = Math.floor(Math.random() * TEASER_POINTS.length)
- for (let tries = 0; tries < 6; tries++) {
- b = Math.floor(Math.random() * TEASER_POINTS.length)
- if (Math.abs(TEASER_POINTS[a][0] - TEASER_POINTS[b][0]) > 0.22) break
- }
- arcs.push({ a, b, born: t })
- }
- c.globalCompositeOperation = 'lighter'
- // Arcs: grow 1.4s, glow, fade until 4.5s.
- for (let i = arcs.length - 1; i >= 0; i--) {
- const arc = arcs[i]
- const age = t - arc.born
- if (age > 4.5) { arcs.splice(i, 1); continue }
- const grow = Math.min(age / 1.4, 1)
- const fade = age < 3 ? 1 : 1 - (age - 3) / 1.5
- const [ax, ay] = TEASER_POINTS[arc.a]
- const [bx, by] = TEASER_POINTS[arc.b]
- const x1 = ax * w; const y1 = ay * h
- const x2 = bx * w; const y2 = by * h
- const mx = (x1 + x2) / 2
- const my = (y1 + y2) / 2 - Math.min(Math.abs(x2 - x1) * 0.35, h * 0.34)
- c.beginPath()
- const steps = 22
- const eased = 1 - (1 - grow) ** 3
- const upto = Math.floor(steps * eased)
- const pt = (q: number): [number, number] => [
- (1 - q) * (1 - q) * x1 + 2 * (1 - q) * q * mx + q * q * x2,
- (1 - q) * (1 - q) * y1 + 2 * (1 - q) * q * my + q * q * y2,
- ]
- for (let s = 0; s <= upto; s++) {
- const [ix, iy] = pt(s / steps)
- if (s === 0) c.moveTo(ix, iy)
- else c.lineTo(ix, iy)
- }
- if (eased < 1) {
- const [tx, ty] = pt(eased)
- c.lineTo(tx, ty)
- }
- c.strokeStyle = `rgba(255, 180, 95, ${0.12 * fade})`
- c.lineWidth = 3.4
- c.stroke()
- c.strokeStyle = `rgba(255, 208, 130, ${0.55 * fade})`
- c.lineWidth = 1.1
- c.stroke()
- }
- // Lights: soft breathing points.
- for (let i = 0; i < TEASER_POINTS.length; i++) {
- const [px, py] = TEASER_POINTS[i]
- const breathe = 0.55 + 0.45 * Math.sin(t * 1.4 + i * 1.7)
- c.fillStyle = `rgba(255, 214, 150, ${0.5 * breathe})`
- c.beginPath()
- c.arc(px * w, py * h, 1.4 + breathe * 0.8, 0, Math.PI * 2)
- c.fill()
- c.fillStyle = `rgba(255, 190, 110, ${0.1 * breathe})`
- c.beginPath()
- c.arc(px * w, py * h, 6 + breathe * 3, 0, Math.PI * 2)
- c.fill()
- }
- c.globalCompositeOperation = 'source-over'
- if (!reduced) raf = requestAnimationFrame(draw)
- }
- raf = requestAnimationFrame(draw)
- return () => { cancelAnimationFrame(raf); ro.disconnect() }
- }, [])
- return
-}
-
-/**
- * The dashboard trigger for the 4.0.0 "KEINE ANGST" show: a dark cinematic card
- * with a living web of golden travel arcs (desktop only). One click starts the
- * show. Core colors ride inline so no dashboard widget CSS can wash them out.
- */
-export default function NoFearBeacon() {
- const { language } = useTranslation()
- const copy = noFearCopy(language)
- const chrome = noFearChrome(language)
- const [open, setOpen] = useState(false)
- const [confirming, setConfirming] = useState(false)
- const [dismissed, setDismissed] = useState(() => {
- try { return localStorage.getItem(DISMISS_KEY) === '1' } catch { return false }
- })
-
- // Past the end date, or dismissed for good — nothing renders.
- if (dismissed || Date.now() >= VISIBLE_UNTIL) return null
-
- const dismiss = () => {
- try { localStorage.setItem(DISMISS_KEY, '1') } catch { /* private mode — hide for this session at least */ }
- setDismissed(true)
- }
-
- return (
- <>
-
-
-
-
- {/* Top-right X: two-step so a stray click can't retire the moment for good.
- Dismissing is permanent (localStorage) — only an update brings it back. */}
-
- {/* White retirement badge: viewable until Aug 23. */}
- {chrome.until}
-
- {open && (
-
- setOpen(false)} />
-
- )}
- >
- )
-}
diff --git a/client/src/components/FourZero/NoFearShow.test.tsx b/client/src/components/FourZero/NoFearShow.test.tsx
deleted file mode 100644
index 2de2a7628..000000000
--- a/client/src/components/FourZero/NoFearShow.test.tsx
+++ /dev/null
@@ -1,662 +0,0 @@
-// FE-NOFEAR-SHOW-001 to FE-NOFEAR-SHOW-035
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
-import { render, screen, act } from '../../../tests/helpers/render'
-import apiClient, { placesApi, tripsApi } from '../../api/client'
-import NoFearShow from './NoFearShow'
-
-interface AudioStub {
- start: ReturnType
- setMuted: ReturnType
- resume: ReturnType
- setSuspended: ReturnType
- swell: ReturnType
- impact: ReturnType
- setAct: ReturnType
- dispose: ReturnType
-}
-
-interface SceneStub {
- layout: ReturnType
- load: ReturnType
- setPersonalPlaces: ReturnType
- draw: ReturnType
-}
-
-interface AssemblyStub {
- init: ReturnType
- draw: ReturnType
- isReady: ReturnType
-}
-
-// Audio, scene and the finale's particle assembly are replaced wholesale: this
-// suite is about the React shell (acts, clock, portal, teardown), not WebAudio
-// or canvas painting, both of which have their own unit tests.
-const stubs = vi.hoisted(() => {
- const audio: AudioStub[] = []
- const scene: SceneStub[] = []
- const assembly: AssemblyStub[] = []
- class FakeAudio {
- start = vi.fn()
- setMuted = vi.fn()
- resume = vi.fn()
- setSuspended = vi.fn()
- swell = vi.fn()
- impact = vi.fn()
- setAct = vi.fn()
- dispose = vi.fn()
- constructor() { audio.push(this) }
- }
- class FakeScene {
- layout = vi.fn()
- load = vi.fn()
- setPersonalPlaces = vi.fn()
- draw = vi.fn()
- constructor() { scene.push(this) }
- }
- class FakeAssembly {
- init = vi.fn()
- draw = vi.fn()
- isReady = vi.fn()
- constructor() { assembly.push(this) }
- }
- return { audio, scene, assembly, FakeAudio, FakeScene, FakeAssembly }
-})
-
-vi.mock('./noFearAudio', () => ({ NoFearAudio: stubs.FakeAudio }))
-vi.mock('./noFearScene', () => ({ NoFearScene: stubs.FakeScene }))
-vi.mock('./noFearAssembly', () => ({ TextAssembly: stubs.FakeAssembly }))
-
-const LINES = {
- afraid: 'They want you to be afraid.',
- ofTheStranger: 'Afraid of the stranger. Afraid of everything you don’t know.',
- fearTool: 'Because fear closes borders — first on maps, then in minds.',
- hateTrade: 'Fear is their tool. Hatred is their trade.',
- butYouTraveled: 'But you have traveled.',
- tables: 'You have eaten at foreign tables. Slept under foreign roofs. Laughed with strangers.',
- notAnOpinion: 'Racism is not an opinion. Fascism is not an alternative.',
- everyDot: 'Every one of these lights is a table where someone was welcome.',
- yourPlaces: 'This — this was you.',
-}
-
-let nowMs = 0
-let frames: FrameRequestCallback[] = []
-let cancelSpy: ReturnType
-let ctxStub: { setTransform: ReturnType } | null = null
-const originalGetContext = HTMLCanvasElement.prototype.getContext
-
-const audio = () => stubs.audio[0]
-const scene = () => stubs.scene[0]
-
-/** Runs the pending rAF callback at the given show time (seconds). */
-function frame(seconds: number): void {
- nowMs = seconds * 1000
- const pending = frames
- frames = []
- act(() => { pending.forEach(cb => cb(nowMs)) })
-}
-
-async function flush(): Promise {
- await act(async () => {
- for (let i = 0; i < 12; i++) await Promise.resolve()
- })
-}
-
-function canvas(): HTMLCanvasElement {
- const el = document.querySelector('canvas.fz-canvas')
- if (!el) throw new Error('show canvas missing')
- return el
-}
-
-/** The scene state handed to the canvas on the most recent frame. */
-function lastSceneState(): { opacity: number; particles: number } {
- const calls = scene().draw.mock.calls
- return calls[calls.length - 1][1] as { opacity: number; particles: number }
-}
-
-/** Visible line text, normalised across the sentence-by-sentence reveal. */
-function lineText(): string {
- const el = document.querySelector('.fz-line:not(.fz-line-ghost)')
- return (el?.textContent ?? '').replace(/\s+/g, ' ').trim()
-}
-
-function setReducedMotion(reduce: boolean): void {
- window.matchMedia = vi.fn().mockImplementation((query: string) => ({
- matches: reduce,
- media: query,
- onchange: null,
- addListener: vi.fn(),
- removeListener: vi.fn(),
- addEventListener: vi.fn(),
- removeEventListener: vi.fn(),
- dispatchEvent: vi.fn(),
- }))
-}
-
-beforeEach(() => {
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
- nowMs = 0
- frames = []
- stubs.audio.length = 0
- stubs.scene.length = 0
- stubs.assembly.length = 0
- cancelSpy = vi.fn()
- ctxStub = { setTransform: vi.fn() }
- vi.spyOn(performance, 'now').mockImplementation(() => nowMs)
- vi.stubGlobal('requestAnimationFrame', vi.fn((cb: FrameRequestCallback) => {
- frames.push(cb)
- return frames.length
- }))
- vi.stubGlobal('cancelAnimationFrame', cancelSpy)
- HTMLCanvasElement.prototype.getContext = vi.fn(() => ctxStub) as unknown as typeof originalGetContext
- Object.defineProperty(HTMLCanvasElement.prototype, 'clientWidth', { configurable: true, get: () => 800 })
- Object.defineProperty(HTMLCanvasElement.prototype, 'clientHeight', { configurable: true, get: () => 600 })
- Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 1 })
- setReducedMotion(false)
- // No traveler data by default — the generic show.
- vi.spyOn(tripsApi, 'list').mockResolvedValue([])
- vi.spyOn(placesApi, 'list').mockResolvedValue([])
- vi.spyOn(apiClient, 'get').mockRejectedValue(new Error('no atlas'))
-})
-
-afterEach(() => {
- HTMLCanvasElement.prototype.getContext = originalGetContext
- Reflect.deleteProperty(HTMLCanvasElement.prototype, 'clientWidth')
- Reflect.deleteProperty(HTMLCanvasElement.prototype, 'clientHeight')
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
- vi.useRealTimers()
- document.body.classList.remove('fz-show-open')
-})
-
-describe('NoFearShow', () => {
- it('FE-NOFEAR-SHOW-001: portals a labelled dialog into the body and locks the page chrome', () => {
- render()
-
- const dialog = screen.getByRole('dialog', { name: 'NO FEAR' })
- expect(dialog).toHaveAttribute('aria-modal', 'true')
- expect(dialog.parentElement).toBe(document.body)
- expect(document.body).toHaveClass('fz-show-open')
- })
-
- it('FE-NOFEAR-SHOW-002: boots audio and scene and starts the soundtrack', () => {
- render()
-
- expect(stubs.audio).toHaveLength(1)
- expect(stubs.scene).toHaveLength(1)
- expect(audio().start).toHaveBeenCalledTimes(1)
- expect(scene().layout).toHaveBeenCalledWith(800, 600)
- })
-
- it('FE-NOFEAR-SHOW-003: sizes the canvas by capped device pixel ratio', () => {
- Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 4 })
-
- render()
-
- expect(canvas().width).toBe(1400)
- expect(canvas().height).toBe(1050)
- expect(ctxStub?.setTransform).toHaveBeenCalledWith(1.75, 0, 0, 1.75, 0, 0)
- })
-
- it('FE-NOFEAR-SHOW-004: loads the scene with a live abort signal that aborts on unmount', () => {
- const { unmount } = render()
-
- const signal = scene().load.mock.calls[0][2] as AbortSignal
- expect(scene().load).toHaveBeenCalledWith(800, 600, signal)
- expect(signal.aborted).toBe(false)
-
- unmount()
- expect(signal.aborted).toBe(true)
- })
-
- it('FE-NOFEAR-SHOW-005: coalesces a resize storm into a single re-fit', () => {
- render()
- expect(scene().layout).toHaveBeenCalledTimes(1)
-
- act(() => {
- for (let i = 0; i < 20; i++) window.dispatchEvent(new Event('resize'))
- })
- // layout() rebakes every static layer, so nothing happens while the drag runs
- expect(scene().layout).toHaveBeenCalledTimes(1)
-
- act(() => { vi.advanceTimersByTime(150) })
-
- expect(scene().layout).toHaveBeenCalledTimes(2)
- expect(scene().layout).toHaveBeenLastCalledWith(800, 600)
- })
-
- it('FE-NOFEAR-SHOW-006: shows no line before the first cue', () => {
- render()
-
- frame(0.2)
-
- expect(document.querySelector('.fz-line')).toBeNull()
- expect(audio().setAct).not.toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-007: opens on the fear act with the first line', () => {
- render()
-
- frame(0.9)
-
- expect(lineText()).toBe(LINES.afraid)
- expect(audio().setAct).toHaveBeenCalledWith('fear')
- expect(scene().draw).toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-008: decays the replaced fear line into a per-character ghost', () => {
- render()
-
- frame(0.9)
- expect(document.querySelector('.fz-line-ghost')).toBeNull()
-
- frame(6.1)
- expect(lineText()).toBe(LINES.ofTheStranger)
- const ghost = document.querySelector('.fz-line-ghost')
- expect(ghost).not.toBeNull()
- expect(ghost?.querySelectorAll('.fz-char-decay')).toHaveLength(LINES.afraid.length)
-
- // Once its letters have decayed the ghost retires itself.
- act(() => { vi.advanceTimersByTime(1400) })
- expect(document.querySelector('.fz-line-ghost')).toBeNull()
-
- frame(12.1)
- const ghostText = document.querySelector('.fz-line-ghost')?.textContent ?? ''
- expect(ghostText.replace(/\u00a0/g, ' ')).toBe(LINES.ofTheStranger)
- })
-
- it('FE-NOFEAR-SHOW-009: raises the red vignette while the borders burn', () => {
- render()
-
- frame(12.1)
- expect(lineText()).toBe(LINES.fearTool)
- expect(audio().setAct).toHaveBeenLastCalledWith('dread')
- expect(document.querySelector('.fz-vignette')).not.toBeNull()
-
- frame(18.6)
- expect(lineText()).toBe(LINES.hateTrade)
- expect(document.querySelector('.fz-vignette')).not.toBeNull()
-
- frame(26.1)
- expect(document.querySelector('.fz-vignette')).toBeNull()
- })
-
- it('FE-NOFEAR-SHOW-010: strobes the staccato words and hides the line inside a flash window', () => {
- render()
-
- frame(18.6)
- expect(lineText()).toBe(LINES.hateTrade)
-
- frame(22.5)
- expect(screen.getByText('FEAR.')).toBeInTheDocument()
- expect(document.querySelector('.fz-line')).toBeNull()
-
- frame(23.8)
- expect(screen.getByText('HATRED.')).toBeInTheDocument()
-
- frame(25.2)
- expect(screen.getByText('WALLS.')).toBeInTheDocument()
-
- frame(25.8)
- expect(document.querySelector('.fz-flash')).toBeNull()
- expect(lineText()).toBe(LINES.hateTrade)
- })
-
- it('FE-NOFEAR-SHOW-011: cuts to silence with no line at all', () => {
- render()
-
- frame(18.6)
- frame(26.2)
-
- expect(audio().setAct).toHaveBeenLastCalledWith('silence')
- expect(document.querySelector('.fz-line:not(.fz-line-ghost)')).toBeNull()
- })
-
- it('FE-NOFEAR-SHOW-012: swells into the soft pivot line', () => {
- render()
-
- frame(26.2)
- frame(28.6)
-
- expect(lineText()).toBe(LINES.butYouTraveled)
- expect(document.querySelector('.fz-line-soft')).not.toBeNull()
- expect(audio().swell).toHaveBeenCalledTimes(1)
- })
-
- it('FE-NOFEAR-SHOW-013: reveals hope-act lines sentence by sentence', () => {
- render()
-
- frame(34.1)
-
- expect(audio().setAct).toHaveBeenLastCalledWith('hope')
- expect(lineText()).toBe(LINES.tables)
- const segments = document.querySelectorAll('.fz-seg')
- expect(segments).toHaveLength(3)
- expect(segments[0].textContent?.trim()).toBe('You have eaten at foreign tables.')
- expect((segments[2] as HTMLElement).style.animationDelay).toBe('1.9s')
- })
-
- it('FE-NOFEAR-SHOW-014: renders the hard line unsegmented and punches the audio', () => {
- render()
-
- frame(34.1)
- frame(64.1)
-
- expect(lineText()).toBe(LINES.notAnOpinion)
- expect(document.querySelector('.fz-line-hard')).not.toBeNull()
- expect(document.querySelectorAll('.fz-seg')).toHaveLength(0)
- expect(audio().impact).toHaveBeenCalledWith(1)
- })
-
- it('FE-NOFEAR-SHOW-015: falls back to the generic line when the traveler has no data', async () => {
- render()
- await flush()
-
- frame(55.6)
- expect(lineText()).toBe(LINES.everyDot)
- expect(audio().impact).toHaveBeenCalledWith(0.35)
-
- frame(58.9)
- expect(lineText()).toBe(LINES.everyDot)
- expect(scene().setPersonalPlaces).not.toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-016: feeds the traveler places into the scene and states the country count', async () => {
- vi.mocked(tripsApi.list).mockResolvedValue([{ id: 1 }, { id: 2 }])
- vi.mocked(placesApi.list).mockResolvedValue([
- { lat: 48.1, lng: 11.5 },
- { lat: 52.5, lng: 13.4 },
- { lat: null, lng: 9.9 },
- ])
- vi.mocked(apiClient.get).mockResolvedValue({ data: { stats: { totalCountries: 9 } } })
-
- render()
- await flush()
-
- expect(scene().setPersonalPlaces).toHaveBeenCalledWith([
- { lat: 48.1, lng: 11.5 },
- { lat: 52.5, lng: 13.4 },
- { lat: 48.1, lng: 11.5 },
- { lat: 52.5, lng: 13.4 },
- ])
-
- frame(55.6)
- expect(lineText()).toBe(LINES.yourPlaces)
-
- frame(58.9)
- expect(lineText()).toBe('4 places. 9 countries. And not once did the world hurt you.')
- })
-
- it('FE-NOFEAR-SHOW-017: falls back to trip counts when Atlas reports no countries', async () => {
- vi.mocked(tripsApi.list).mockResolvedValue([{ id: 1 }, { id: 2 }, { id: 3 }])
- vi.mocked(placesApi.list).mockResolvedValue([{ lat: 1, lng: 2 }])
- vi.mocked(apiClient.get).mockResolvedValue({ data: { stats: { totalCountries: 0 } } })
-
- render()
- await flush()
-
- frame(58.9)
-
- expect(lineText()).toBe('3 places. 3 journeys. And not once did the world hurt you.')
- })
-
- it('FE-NOFEAR-SHOW-018: falls back to trip counts when the Atlas request fails', async () => {
- vi.mocked(tripsApi.list).mockResolvedValue([{ id: 7 }])
- vi.mocked(placesApi.list).mockResolvedValue([
- { lat: 1, lng: 2 },
- { lat: 3, lng: 4 },
- { lat: 5, lng: 6 },
- ])
-
- render()
- await flush()
-
- frame(58.9)
-
- expect(lineText()).toBe('3 places. 1 journeys. And not once did the world hurt you.')
- })
-
- it('FE-NOFEAR-SHOW-019: ignores a trip whose places fail to load and skips thin data sets', async () => {
- vi.mocked(tripsApi.list).mockResolvedValue([{ id: 1 }, { id: 2 }])
- vi.mocked(placesApi.list)
- .mockResolvedValueOnce([{ lat: 1, lng: 2 }])
- .mockRejectedValueOnce(new Error('boom'))
-
- render()
- await flush()
-
- expect(scene().setPersonalPlaces).not.toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-020: survives a failing trip list', async () => {
- vi.mocked(tripsApi.list).mockRejectedValue(new Error('offline'))
-
- render()
- await flush()
-
- frame(58.9)
-
- expect(lineText()).toBe(LINES.everyDot)
- expect(scene().setPersonalPlaces).not.toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-021: ignores a non-array trip response', async () => {
- vi.mocked(tripsApi.list).mockResolvedValue({ trips: [] })
-
- render()
- await flush()
-
- expect(placesApi.list).not.toHaveBeenCalled()
- expect(scene().setPersonalPlaces).not.toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-022: drops late place results after unmount', async () => {
- let releasePlaces: (value: { lat: number; lng: number }[]) => void = () => {}
- vi.mocked(tripsApi.list).mockResolvedValue([{ id: 1 }])
- vi.mocked(placesApi.list).mockReturnValue(new Promise(resolve => { releasePlaces = resolve }))
-
- const { unmount } = render()
- await flush()
- unmount()
- releasePlaces([{ lat: 1, lng: 2 }, { lat: 3, lng: 4 }, { lat: 5, lng: 6 }])
- await flush()
-
- expect(scene().setPersonalPlaces).not.toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-023: pauses the clock while the tab is hidden', () => {
- render()
- frame(10)
- expect(lineText()).toBe(LINES.ofTheStranger)
-
- Object.defineProperty(document, 'hidden', { configurable: true, get: () => true })
- act(() => { document.dispatchEvent(new Event('visibilitychange')) })
- expect(audio().setSuspended).toHaveBeenCalledWith(true)
-
- nowMs = 30_000
- Object.defineProperty(document, 'hidden', { configurable: true, get: () => false })
- act(() => { document.dispatchEvent(new Event('visibilitychange')) })
- expect(audio().setSuspended).toHaveBeenLastCalledWith(false)
-
- // 21s of wall clock passed, but the show only advanced 1s.
- frame(31)
- expect(lineText()).toBe(LINES.ofTheStranger)
-
- Reflect.deleteProperty(document, 'hidden')
- })
-
- it('FE-NOFEAR-SHOW-024: resumes audio on any pointer gesture', () => {
- render()
-
- act(() => { window.dispatchEvent(new Event('pointerdown')) })
-
- expect(audio().resume).toHaveBeenCalledTimes(1)
- })
-
- it('FE-NOFEAR-SHOW-025: closes on Escape and ignores other keys', () => {
- const onClose = vi.fn()
- render()
-
- act(() => { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' })) })
- expect(onClose).not.toHaveBeenCalled()
-
- act(() => { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })) })
- expect(onClose).toHaveBeenCalledTimes(1)
- })
-
- it('FE-NOFEAR-SHOW-026: closes through the chrome button', () => {
- const onClose = vi.fn()
- render()
-
- act(() => { screen.getByRole('button', { name: 'Carry it on' }).click() })
-
- expect(onClose).toHaveBeenCalledTimes(1)
- })
-
- it('FE-NOFEAR-SHOW-027: toggles mute and relabels the button', () => {
- render()
-
- act(() => { screen.getByRole('button', { name: 'Sound off' }).click() })
- expect(audio().setMuted).toHaveBeenCalledWith(true)
-
- act(() => { screen.getByRole('button', { name: 'Sound on' }).click() })
- expect(audio().setMuted).toHaveBeenLastCalledWith(false)
- })
-
- it('FE-NOFEAR-SHOW-028: skip jumps straight to the anthem and retires the skip button', () => {
- render()
- frame(5)
- expect(lineText()).toBe(LINES.afraid)
-
- act(() => { screen.getByRole('button', { name: 'Skip' }).click() })
-
- expect(audio().setAct).toHaveBeenLastCalledWith('anthem')
- expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('NO FEAR')
- expect(screen.queryByRole('button', { name: 'Skip' })).toBeNull()
- expect(document.querySelector('.fz-line')).toBeNull()
- })
-
- it('FE-NOFEAR-SHOW-029: closes the show with the anthem cascade in every other language', () => {
- render()
-
- frame(71.2)
-
- expect(audio().setAct).toHaveBeenLastCalledWith('anthem')
- expect(audio().impact).toHaveBeenLastCalledWith(0.8)
- const cascade = document.querySelectorAll('.fz-cascade-item')
- expect(cascade).toHaveLength(22)
- expect(cascade[0].textContent).toBe('Keine Angst')
- expect(screen.queryByText('No fear')).toBeNull()
- })
-
- it('FE-NOFEAR-SHOW-030: condenses the anthem title out of one lazily built particle assembly', () => {
- vi.spyOn(HTMLHeadingElement.prototype, 'getBoundingClientRect').mockReturnValue({
- left: 100, top: 200, width: 300, height: 60,
- } as unknown as DOMRect)
-
- render()
-
- // The title only exists from the frame after the anthem state flipped.
- frame(71.2)
- expect(stubs.assembly).toHaveLength(0)
-
- frame(72)
- expect(stubs.assembly).toHaveLength(1)
- expect(stubs.assembly[0].init).toHaveBeenCalledWith(
- 'NO FEAR',
- expect.any(String),
- { left: 100, top: 200, width: 300, height: 60 },
- 800,
- 600,
- )
- const [drawCtx, progress, fade, drawT] = stubs.assembly[0].draw.mock.calls[0] as [unknown, number, number, number]
- expect(drawCtx).toBe(ctxStub)
- expect(progress).toBeCloseTo(0.1875, 6)
- expect(fade).toBe(0)
- expect(drawT).toBe(72)
- expect(screen.getByRole('heading', { level: 1 })).toHaveClass('fz-word-hidden')
-
- frame(76)
- expect(stubs.assembly).toHaveLength(1)
- expect(screen.getByRole('heading', { level: 1 })).not.toHaveClass('fz-word-hidden')
-
- // Targets are absolute screen coordinates, so a resize invalidates them and
- // the next frame re-samples the moved title.
- act(() => { window.dispatchEvent(new Event('resize')) })
- act(() => { vi.advanceTimersByTime(150) })
- frame(77)
- expect(stubs.assembly).toHaveLength(2)
- })
-
- it('FE-NOFEAR-SHOW-031: tears down chrome, listeners and audio on unmount', () => {
- const { unmount } = render()
- const onClose = vi.fn()
- const layoutCalls = scene().layout.mock.calls.length
-
- unmount()
-
- expect(document.body).not.toHaveClass('fz-show-open')
- expect(audio().dispose).toHaveBeenCalledTimes(1)
- expect(cancelSpy).toHaveBeenCalled()
-
- window.dispatchEvent(new Event('resize'))
- window.dispatchEvent(new Event('pointerdown'))
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
-
- expect(scene().layout.mock.calls.length).toBe(layoutCalls)
- expect(audio().resume).not.toHaveBeenCalled()
- expect(onClose).not.toHaveBeenCalled()
- })
-
- it('FE-NOFEAR-SHOW-032: reduced motion renders the finale as one static frame without audio', () => {
- setReducedMotion(true)
-
- render()
-
- expect(audio().start).not.toHaveBeenCalled()
- expect(audio().setAct).toHaveBeenCalledWith('anthem')
- expect(requestAnimationFrame).not.toHaveBeenCalled()
- expect(scene().draw).toHaveBeenCalledTimes(1)
- const [, state, t] = scene().draw.mock.calls[0] as [unknown, { particles: number; opacity: number }, number]
- expect(state.particles).toBe(0)
- expect(state.opacity).toBe(1)
- expect(t).toBe(79)
- expect(screen.getByRole('heading', { level: 1 })).not.toHaveClass('fz-word-assembled')
- })
-
- it('FE-NOFEAR-SHOW-033: still runs the show when the canvas has no 2d context', () => {
- ctxStub = null
-
- render()
- frame(12.1)
-
- expect(lineText()).toBe(LINES.fearTool)
- expect(scene().draw).not.toHaveBeenCalled()
- expect(stubs.assembly).toHaveLength(0)
- })
-
- it('FE-NOFEAR-SHOW-034: dims the world through the blackout and brings it back with the hope act', () => {
- render()
-
- frame(20)
- expect(lastSceneState().opacity).toBe(1)
-
- frame(27)
- expect(lastSceneState().opacity).toBe(0)
-
- frame(31)
- expect(lastSceneState().opacity).toBeGreaterThan(0.8)
- expect(lastSceneState().opacity).toBeLessThan(1)
-
- frame(32)
- expect(lastSceneState().opacity).toBe(1)
- })
-
- it('FE-NOFEAR-SHOW-035: falls back to a pixel ratio of 1 when the browser reports none', () => {
- Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 0 })
-
- render()
-
- expect(canvas().width).toBe(800)
- expect(ctxStub?.setTransform).toHaveBeenCalledWith(1, 0, 0, 1, 0, 0)
- })
-})
diff --git a/client/src/components/FourZero/NoFearShow.tsx b/client/src/components/FourZero/NoFearShow.tsx
deleted file mode 100644
index 4a72f05f1..000000000
--- a/client/src/components/FourZero/NoFearShow.tsx
+++ /dev/null
@@ -1,370 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import ReactDOM from 'react-dom'
-import { Volume2, VolumeX, X } from 'lucide-react'
-import { placesApi, tripsApi } from '../../api/client'
-import apiClient from '../../api/client'
-import { useTranslation } from '../../i18n'
-import type { Place, Trip } from '../../types'
-import { TextAssembly } from './noFearAssembly'
-import { NoFearAudio, type NoFearAct } from './noFearAudio'
-import { NoFearScene, type SceneState } from './noFearScene'
-import { ANTHEM_CASCADE, noFearCopy } from './noFearLines'
-import './fourzero.css'
-
-// TREK 4.0.0 release moment — remove together with the FourZero folder.
-
-type LineKey = keyof ReturnType['lines']
-
-interface Cue {
- at: number
- act?: NoFearAct
- line?: LineKey | null
- hard?: boolean
- soft?: boolean
- impact?: number
- swell?: boolean
-}
-
-// The script. Times in seconds; the scene ramps below share the same clock.
-const CUES: Cue[] = [
- { at: 0.8, act: 'fear', line: 'afraid' },
- { at: 6.0, line: 'ofTheStranger' },
- { at: 12.0, act: 'dread', line: 'fearTool' },
- { at: 18.5, line: 'hateTrade' },
- { at: 26.0, act: 'silence', line: null },
- { at: 28.5, line: 'butYouTraveled', soft: true, swell: true },
- { at: 34.0, act: 'hope', line: 'tables' },
- { at: 42.0, line: 'face' },
- { at: 49.0, line: 'fences' },
- { at: 55.5, line: 'yourPlaces', impact: 0.35 },
- { at: 58.8, line: 'yourStatsCountries' },
- { at: 64.0, line: 'notAnOpinion', hard: true, impact: 1 },
- { at: 71.0, act: 'anthem', line: null, impact: 0.8 },
-]
-const ANTHEM_AT = 71
-// The three staccato words strobe with the late fear act, just before the cut.
-const FLASH_WINDOWS: [number, number][] = [[22.2, 22.85], [23.6, 24.25], [25.0, 25.65]]
-
-const ramp = (t: number, from: number, to: number): number =>
- Math.min(Math.max((t - from) / (to - from), 0), 1)
-
-function sceneAt(t: number): SceneState {
- // Hard cut to black at 26s; the pivot line stands alone in the dark, then the
- // world returns WITH the hope act (28→31.5) — that overlap is intentional.
- const blackout = t >= 26 && t < 31.5 ? 1 - ramp(t, 28, 31.5) : 0
- return {
- land: ramp(t, 6, 10),
- cityLife: ramp(t, 6.5, 11),
- cityDeath: ramp(t, 13, 22),
- borderHeat: t < 34 ? ramp(t, 12, 15.5) : 1 - 0.55 * ramp(t, 34, 38),
- borderBurst: ramp(t, 64, 70),
- web: ramp(t, 34, 62),
- warmth: ramp(t, 34, 46),
- personalGlow: ramp(t, 55.5, 60.5),
- particles: ramp(t, ANTHEM_AT, ANTHEM_AT + 4),
- opacity: 1 - blackout,
- }
-}
-
-/** Formats "{p} places. {c} countries. …" with the traveler's real numbers. */
-function fillStats(template: string, p: number, cOrT: number): string {
- return template.replace('{p}', String(p)).replace('{c}', String(cOrT)).replace('{t}', String(cOrT))
-}
-
-export default function NoFearShow({ onClose }: { onClose: () => void }) {
- const { language } = useTranslation()
- const copy = useMemo(() => noFearCopy(language), [language])
- const overlayRef = useRef(null)
- const canvasRef = useRef(null)
- const audioRef = useRef(null)
- const sceneRef = useRef(null)
- const startRef = useRef(performance.now())
- const statsRef = useRef<{ line: string } | null>(null)
- const assemblyRef = useRef(null)
- const anthemWordRef = useRef(null)
- const [cueIdx, setCueIdx] = useState(-1)
- const [flashIdx, setFlashIdx] = useState(-1)
- const [muted, setMuted] = useState(false)
- const [anthem, setAnthem] = useState(false)
- // A fear-act line that was just replaced — rendered once more while its
- // letters decay away (the words of fear literally fall apart).
- const [ghost, setGhost] = useState<{ text: string; id: number } | null>(null)
- const reducedMotion = useMemo(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches, [])
-
- const skipToEnd = useCallback(() => {
- startRef.current = performance.now() - ANTHEM_AT * 1000
- setAnthem(true)
- audioRef.current?.setAct('anthem')
- }, [])
-
- // Boot: audio, scene, personal places, chrome side effects.
- useEffect(() => {
- document.body.classList.add('fz-show-open') // hides the dashboard FAB + locks scroll
- const audio = new NoFearAudio()
- audioRef.current = audio
- if (!reducedMotion) audio.start()
- const scene = new NoFearScene()
- sceneRef.current = scene
- const aborter = new AbortController()
- const cv = canvasRef.current
- const fit = () => {
- if (!cv) return
- const dpr = Math.min(window.devicePixelRatio || 1, 1.75)
- cv.width = Math.round(cv.clientWidth * dpr)
- cv.height = Math.round(cv.clientHeight * dpr)
- cv.getContext('2d')?.setTransform(dpr, 0, 0, dpr, 0, 0)
- scene.layout(cv.clientWidth, cv.clientHeight)
- // The finale samples the title rect in screen coordinates, so it has to be
- // re-sampled against the new geometry.
- assemblyRef.current = null
- }
- fit()
- if (cv) void scene.load(cv.clientWidth, cv.clientHeight, aborter.signal)
- // layout() rebakes every static layer, which is far too heavy for the event
- // storm a window drag produces — coalesce to the end of the gesture.
- let refitTimer = 0
- const onResize = () => {
- window.clearTimeout(refitTimer)
- refitTimer = window.setTimeout(fit, 150)
- }
- window.addEventListener('resize', onResize)
- // The traveler's own places, gathered quietly during the fear act. Fail-soft:
- // without them the show falls back to its generic lines.
- void (async () => {
- try {
- const trips = await tripsApi.list() as Trip[]
- if (aborter.signal.aborted || !Array.isArray(trips)) return
- const lists = await Promise.all(trips.slice(0, 12).map(t => placesApi.list(t.id).catch(() => [] as Place[])))
- if (aborter.signal.aborted) return
- const pts = lists.flat().filter((p: Place) => p.lat != null && p.lng != null).map((p: Place) => ({ lat: p.lat as number, lng: p.lng as number }))
- if (pts.length >= 3) {
- sceneRef.current?.setPersonalPlaces(pts)
- // Prefer real country counts from Atlas; fall back to trip counts.
- try {
- const { data } = await apiClient.get('/addons/atlas/stats', { signal: aborter.signal })
- const countries = data?.stats?.totalCountries
- statsRef.current = countries > 0
- ? { line: fillStats(copy.lines.yourStatsCountries, pts.length, countries) }
- : { line: fillStats(copy.lines.yourStatsTrips, pts.length, trips.length) }
- } catch {
- statsRef.current = { line: fillStats(copy.lines.yourStatsTrips, pts.length, trips.length) }
- }
- }
- } catch { /* not signed-in edge / API down — generic show */ }
- })()
- // Pause the whole show (clock + audio) while the tab is hidden.
- let hiddenAt: number | null = null
- const onVisibility = () => {
- if (document.hidden) {
- hiddenAt = performance.now()
- audio.setSuspended(true)
- } else {
- if (hiddenAt !== null) startRef.current += performance.now() - hiddenAt
- hiddenAt = null
- audio.setSuspended(false)
- }
- }
- document.addEventListener('visibilitychange', onVisibility)
- // Any real gesture inside the overlay doubles as an audio-resume recovery
- // for browsers that refused the post-lazy-load AudioContext start.
- const onPointer = () => audio.resume()
- window.addEventListener('pointerdown', onPointer)
- overlayRef.current?.focus()
- if (reducedMotion) skipToEnd()
- return () => {
- document.body.classList.remove('fz-show-open')
- window.clearTimeout(refitTimer)
- window.removeEventListener('resize', onResize)
- document.removeEventListener('visibilitychange', onVisibility)
- window.removeEventListener('pointerdown', onPointer)
- aborter.abort()
- audio.dispose()
- }
- }, [reducedMotion, skipToEnd, copy])
-
- // The clock: one rAF loop drives the canvas directly and only touches React
- // state on discrete cue/flash changes. Reduced motion renders one static frame.
- useEffect(() => {
- const cv = canvasRef.current
- const ctx = cv?.getContext('2d')
- if (reducedMotion) {
- setCueIdx(CUES.length - 1)
- if (ctx) sceneRef.current?.draw(ctx, { ...sceneAt(ANTHEM_AT + 8), particles: 0 }, ANTHEM_AT + 8)
- return
- }
- let raf = 0
- let lastCue = -1
- let lastFlash = -1
- const tick = () => {
- const t = (performance.now() - startRef.current) / 1000
- let idx = -1
- for (let i = 0; i < CUES.length; i++) if (t >= CUES[i].at) idx = i
- if (idx !== lastCue && idx >= 0) {
- // A replaced fear-act line decays letter by letter instead of vanishing.
- if (lastCue >= 0 && lastCue <= 3) {
- const ghostId = lastCue // pin it — lastCue advances on the next line
- const prevKey = CUES[ghostId].line
- if (prevKey) {
- setGhost({ text: copy.lines[prevKey], id: ghostId })
- window.setTimeout(() => setGhost(g => (g?.id === ghostId ? null : g)), 1400)
- }
- }
- lastCue = idx
- const cue = CUES[idx]
- if (cue.act) audioRef.current?.setAct(cue.act)
- if (cue.impact) audioRef.current?.impact(cue.impact)
- if (cue.swell) audioRef.current?.swell()
- setCueIdx(idx)
- if (t >= ANTHEM_AT) setAnthem(true)
- }
- let flash = -1
- for (let i = 0; i < FLASH_WINDOWS.length; i++) {
- if (t >= FLASH_WINDOWS[i][0] && t < FLASH_WINDOWS[i][1]) flash = i
- }
- if (flash !== lastFlash) {
- lastFlash = flash
- setFlashIdx(flash)
- }
- if (ctx) sceneRef.current?.draw(ctx, sceneAt(t), t)
- // The finale condenses out of light: once the anthem title is measurable,
- // sample its letterforms and gather rising particles into them; the real
- // DOM text takes over as they settle.
- if (ctx && cv && t >= ANTHEM_AT) {
- const word = anthemWordRef.current
- if (!assemblyRef.current && word) {
- const assembly = new TextAssembly()
- const style = window.getComputedStyle(word)
- const rect = word.getBoundingClientRect()
- assembly.init(
- word.textContent ?? '',
- `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`,
- { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
- cv.clientWidth,
- cv.clientHeight,
- )
- assemblyRef.current = assembly
- }
- const progress = ramp(t, ANTHEM_AT + 0.4, ANTHEM_AT + 3.6)
- const fade = ramp(t, ANTHEM_AT + 3.4, ANTHEM_AT + 4.8)
- assemblyRef.current?.draw(ctx, progress, fade, t)
- word?.classList.toggle('fz-word-hidden', fade < 0.15)
- }
- raf = requestAnimationFrame(tick)
- }
- raf = requestAnimationFrame(tick)
- return () => cancelAnimationFrame(raf)
- }, [reducedMotion])
-
- // ESC closes the show at any point.
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
- window.addEventListener('keydown', onKey)
- return () => window.removeEventListener('keydown', onKey)
- }, [onClose])
-
- const cue = cueIdx >= 0 ? CUES[cueIdx] : null
- const lineKey = cue?.line ?? null
- // The personal-stats line only exists when the traveler's data arrived; the
- // yourPlaces line falls back to the generic "every light" line without it,
- // and that line simply stays up through the stats slot (same text = no remount).
- let lineText: string | null = null
- if (lineKey === 'yourStatsCountries') lineText = statsRef.current?.line ?? copy.lines.everyDot
- else if (lineKey === 'yourPlaces') lineText = statsRef.current ? copy.lines.yourPlaces : copy.lines.everyDot
- else if (lineKey) lineText = copy.lines[lineKey]
- const hard = !!cue?.hard
-
- // Portal to body: the dashboard sidebar is position:sticky and forms its own
- // stacking context, so an in-place overlay would sit UNDER the fixed navbar
- // (z-200 at root level) no matter its z-index.
- return ReactDOM.createPortal(
-
-
-
- {/* Red vignette while the borders burn. */}
- {!anthem && cueIdx >= 2 && cueIdx <= 3 && }
-
- {/* Staccato words strobing to the heartbeat, right before the cut. */}
- {flashIdx >= 0 && !anthem && (
-
- {copy.flashes[flashIdx]}
-
- )}
-
- {/* A replaced fear line decays away letter by letter. */}
- {!anthem && ghost && (
-
- )}
-
- {/* The ending: the big words condense out of rising light, then the
- cascade through every TREK language joins — and it all stays. */}
- {anthem && (
-