// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), the poster wall: // src/components/app/lattice/PosterWall.tsx, LatticePoster.tsx, tileMotion.ts and // src/components/wall/wallReflowMotion.ts. See ../README.md. // // A wall of covers, one card to a song. The card of the song that plays is open: it takes a 6x6 gear in its // block, the eleven around it re-gear to keep the block covered, and it carries the transport and the lyrics. // Cards land in a wave from the top left when the wall first shows, lift by one gap under the pointer, and // spring to their new places when the open card changes. // // Changed from Folia: the wall is finite and stands in the page's flow, so the page scrolls it (Folia pans an // endless wall under a camera); the cards are the page's own elements, found in the wall's root and laid out // here; a narrow screen gets a plain two-column grid instead of the blocks. The wall's sheet, ./lattice.css, is // imported by the page that mounts the wall, not here (a sheet brought in by a lazily loaded script does not // survive the site's page swaps). // // A wall the page placed: a page that draws the cards on the server can put them in the closed wall's slots itself, // so its first frame shows the wall and not a grid this script then rearranges. It writes each card's slot on the // card (--lx, --ly, --lw, --lh, world units, from layoutFiniteWall), the plan's size on the root // (--lattice-plan-width, --lattice-plan-height), and where the wall begins runs a few lines that set the root's // `is-narrow`, or else --lattice-fit (fitWallScale), --lattice-left, its height and `is-placed` (lattice.css // places the cards from these). This script then starts from those slots: no opening wave, and nothing moves // unless a card is open. import type { Theme } from '../types'; import { buildLinesFromStamps } from '../lyrics/timeline'; import { Motion } from '../motion'; import { GAP, NARROW_WIDTH, OPEN_SIZE, PITCH, fitWallScale, layoutFiniteWall, type WallRect } from './blockTemplates'; import { TileLyrics } from './lyrics'; export type { Theme } from '../types'; export interface LatticeWallOptions { /** Seconds into the playing song. */ clock: () => number; playing: () => boolean; theme: Theme; } /** The spring a card's place and size run on when its block re-gears: nearly critically damped, no bounce. */ const REFLOW_SPRING = { type: 'spring', stiffness: 300, damping: 34 } as const; const ENTRANCE_LIFT = 90; const ENTRANCE_STAGGER = 0.03; const ENTRANCE_MAX_DELAY = 0.34; /** How long after a card starts to open its lyrics are fitted to it (the spring has landed by then). */ const EXPANSION_SETTLE_MS = 520; const SETTLE_MS = 1200; type Channels = 'x' | 'y' | 'w' | 'h' | 'opacity' | 'scale' | 'popX' | 'popY'; interface Tile { el: HTMLElement; motion: Motion; rect: WallRect | null; /** Its entrance has started (the opening wave, or the fade when it first scrolls into view). */ entered: boolean; inView: boolean; /** The size last written to the element, so a frame that does not change it writes nothing. */ written: { w: number; h: number }; } /** What the wall writes on a card; the card's own inline style (its cover) is the page's and stays. */ const PLACED = ['transform', 'opacity', 'width', 'height'] as const; /** The slot a page wrote on a card it placed itself (--lx, --ly, --lw, --lh), or null when it wrote none. */ const slotOf = (poster: HTMLElement): WallRect | null => { const [x, y, width, height] = ['--lx', '--ly', '--lw', '--lh'].map((name) => Number.parseFloat(poster.style.getPropertyValue(name))); return [x, y, width, height].every(Number.isFinite) && width > 0 && height > 0 ? { x, y, width, height } : null; }; export class LatticeWall { #root: HTMLElement; #world: HTMLElement; #controls: HTMLElement | null; #options: LatticeWallOptions; #lyrics: TileLyrics; #tiles = new Map(); #current: HTMLElement | null = null; #narrow = false; #first = true; #reduced = matchMedia('(prefers-reduced-motion: reduce)'); #mutations: MutationObserver; #resize: ResizeObserver; #seen: IntersectionObserver; #pending = 0; #settleTimer = 0; #fitTimer = 0; #frame = 0; #last = 0; #settleUntil = 0; #active = true; #destroyed = false; #abort = new AbortController(); constructor(root: HTMLElement, options: LatticeWallOptions) { this.#root = root; this.#options = options; this.#world = root.querySelector('.lattice-world')!; this.#controls = root.querySelector('[data-lattice-controls]'); this.#lyrics = new TileLyrics(options.theme); const { signal } = this.#abort; // The page keeps the cards: which are shown, their order, which one plays. The wall follows. this.#mutations = new MutationObserver(() => this.#schedule()); this.#mutations.observe(this.#world, { childList: true, subtree: true, attributes: true, attributeFilter: ['hidden', 'aria-current'] }); this.#resize = new ResizeObserver(() => this.#schedule()); this.#resize.observe(root); window.addEventListener('resize', () => this.#schedule(), { signal }); this.#seen = new IntersectionObserver((entries) => { for (const entry of entries) { const tile = this.#tiles.get(entry.target as HTMLElement); if (!tile) continue; tile.inView = entry.isIntersecting; if (entry.isIntersecting && !tile.entered) this.#reveal(tile); } }, { rootMargin: '80px' }); this.#world.addEventListener('pointerover', (event) => this.#pop(event, true), { signal }); this.#world.addEventListener('pointerout', (event) => this.#pop(event, false), { signal }); this.#world.addEventListener('click', (event) => { // A card that was pressed is about to open: once it has, bring all of it onto the screen. const tile = event.target instanceof Element ? event.target.closest('.lattice-poster') : null; if (!tile || tile === this.#current) return; window.setTimeout(() => { if (tile === this.#current) tile.scrollIntoView({ block: 'nearest', behavior: this.#reduced.matches ? 'auto' : 'smooth' }); }, EXPANSION_SETTLE_MS); }, { signal }); this.#layout(); } setTheme(theme: Theme) { this.#options.theme = theme; this.#lyrics.setTheme(theme); this.nudge(); } /** The playing song's lyrics as time stamps and words (a stamp without words ends the line before it); null or empty for none. */ setLyrics(stamps: ReadonlyArray<{ time: number; text: string }> | null) { this.#lyrics.setLines(stamps?.length ? buildLinesFromStamps(stamps) : []); this.#current?.classList.toggle('has-lyrics', this.#lyrics.hasLines); this.#lyrics.resize(); this.nudge(); } /** Whether the wall is on screen; its lyrics draw only then. */ setActive(active: boolean) { if (active === this.#active) return; this.#active = active; this.nudge(); } /** The music started, stopped or jumped. */ nudge() { if (this.#destroyed) return; this.#root.classList.toggle('is-playing', this.#options.playing()); this.#settleUntil = performance.now() + SETTLE_MS; if (!this.#frame && this.#active) { this.#last = performance.now(); this.#frame = requestAnimationFrame(this.#tick); } } destroy() { this.#destroyed = true; this.#abort.abort(); this.#mutations.disconnect(); this.#resize.disconnect(); this.#seen.disconnect(); cancelAnimationFrame(this.#frame); cancelAnimationFrame(this.#pending); window.clearTimeout(this.#settleTimer); window.clearTimeout(this.#fitTimer); for (const tile of this.#tiles.values()) tile.motion.destroy(); this.#lyrics.destroy(); } #schedule() { if (this.#pending || this.#destroyed) return; this.#pending = requestAnimationFrame(() => { this.#pending = 0; this.#layout(); }); } #tileOf(el: HTMLElement): Tile { let tile = this.#tiles.get(el); if (!tile) { const written = { w: -1, h: -1 }; const motion = new Motion({ x: 0, y: 0, w: 0, h: 0, opacity: 0, scale: 1, popX: 1, popY: 1 }, (values) => { if (this.#narrow) return; const scale = values.scale as number; el.style.transform = `translate(${(values.x as number).toFixed(1)}px, ${(values.y as number).toFixed(1)}px) scale(${(scale * (values.popX as number)).toFixed(4)}, ${(scale * (values.popY as number)).toFixed(4)})`; el.style.opacity = String(values.opacity); const w = Math.round(values.w as number); const h = Math.round(values.h as number); if (w !== written.w) el.style.width = `${written.w = w}px`; if (h !== written.h) el.style.height = `${written.h = h}px`; }); tile = { el, motion, rect: null, entered: false, inView: false, written }; this.#tiles.set(el, tile); this.#seen.observe(el); } return tile; } #layout() { if (this.#destroyed) return; const root = this.#root; const posters = [...this.#world.querySelectorAll('.lattice-poster')]; const shown = posters.filter((poster) => !poster.hidden); const current = shown.find((poster) => poster.querySelector('[aria-current="true"]')) ?? null; this.#setCurrent(current); const available = root.clientWidth; const narrow = available < NARROW_WIDTH; if (narrow !== this.#narrow) { this.#narrow = narrow; root.classList.toggle('is-narrow', narrow); // Only what the wall wrote goes: a card's cover is in its inline style too. for (const poster of posters) for (const property of PLACED) poster.style.removeProperty(property); this.#world.removeAttribute('style'); root.style.removeProperty('height'); root.style.removeProperty('--lattice-scale'); for (const tile of this.#tiles.values()) { tile.rect = null; tile.written.w = tile.written.h = -1; } } if (narrow) { // The grid does the placing; a card only fades in the first time it is seen. for (const poster of shown) this.#tileOf(poster); this.#first = false; return; } const plan = layoutFiniteWall(shown.length, 1, current ? shown.indexOf(current) : -1); const scale = fitWallScale(available, plan.width, window.innerHeight, OPEN_SIZE); // The page put the cards in the closed wall's slots before this script arrived: they start from there. const placed = this.#first && root.classList.contains('is-placed'); this.#world.style.width = `${plan.width}px`; this.#world.style.height = `${plan.height}px`; this.#world.style.transform = `scale(${scale.toFixed(4)})`; this.#world.style.marginLeft = `${Math.max(0, (available - plan.width * scale) / 2).toFixed(1)}px`; root.style.height = `${Math.ceil(plan.height * scale)}px`; root.style.setProperty('--lattice-scale', scale.toFixed(4)); const reduced = this.#reduced.matches; const viewBottom = (window.innerHeight - root.getBoundingClientRect().top) / scale; shown.forEach((poster, index) => { const tile = this.#tileOf(poster); const slot = placed && !tile.entered ? slotOf(poster) : null; if (slot) { tile.rect = slot; tile.entered = true; tile.motion.set({ x: slot.x, y: slot.y, w: slot.width, h: slot.height, opacity: 1, scale: 1 }); } const rect = plan.rects[index]; const before = tile.rect; tile.rect = rect; const place = { x: rect.x, y: rect.y, w: rect.width, h: rect.height }; if (reduced) { tile.entered = true; tile.motion.set({ ...place, opacity: 1, scale: 1 }); } else if (!tile.entered) { if (this.#first && rect.y < viewBottom) { // The opening wave: from the top left, each card dropping into its slot a little after its neighbour. tile.entered = true; const delay = Math.min(ENTRANCE_MAX_DELAY, ((rect.x + rect.y) / PITCH) * ENTRANCE_STAGGER); tile.motion.set({ ...place, y: rect.y - ENTRANCE_LIFT, opacity: 0, scale: 0.88 }); void tile.motion.to({ y: rect.y, opacity: 1, scale: 1 }, { type: 'spring', stiffness: 360, damping: 24, delay, opacity: { duration: 0.24, delay } }); } else { // Below the fold: it waits where it belongs and fades up when it is scrolled to. tile.motion.set({ ...place, opacity: 0, scale: 0.94 }); if (tile.inView) this.#reveal(tile); } } else if (!before) { // Back from the narrow grid, where it had no place of its own: it is simply put there. tile.motion.set({ ...place, opacity: 1, scale: 1 }); } else if (before.x !== rect.x || before.y !== rect.y || before.width !== rect.width || before.height !== rect.height) { void tile.motion.to(place, REFLOW_SPRING); } }); this.#first = false; // The open card may have a new size: its lyrics are fitted again once it has settled. window.clearTimeout(this.#fitTimer); this.#fitTimer = window.setTimeout(() => { this.#lyrics.resize(); this.nudge(); }, EXPANSION_SETTLE_MS + 40); } #reveal(tile: Tile) { tile.entered = true; if (this.#narrow || this.#reduced.matches) { tile.motion.set({ opacity: 1, scale: 1 }); return; } void tile.motion.to({ opacity: 1, scale: 1 }, { ...REFLOW_SPRING, opacity: { duration: 0.26, ease: 'easeOut' } }); } /** The card under the pointer lifts by one gap on every side; the open card never does. */ #pop(event: PointerEvent, over: boolean) { if (this.#narrow || event.pointerType === 'touch' || this.#reduced.matches) return; const el = event.target instanceof Element ? event.target.closest('.lattice-poster') : null; if (!el || (event.relatedTarget instanceof Node && el.contains(event.relatedTarget))) return; const tile = this.#tiles.get(el); if (!tile?.rect) return; const lifted = over && el !== this.#current; void tile.motion.to({ popX: lifted ? (tile.rect.width + GAP * 2) / tile.rect.width : 1, popY: lifted ? (tile.rect.height + GAP * 2) / tile.rect.height : 1, }, { duration: 0.3, ease: 'easeOut' }); } /** Opens the playing song's card: it wears the mark, takes the transport and, once grown, the lyrics. */ #setCurrent(current: HTMLElement | null) { if (current === this.#current) return; const previous = this.#current; this.#current = current; previous?.classList.remove('is-current', 'is-expanded', 'has-lyrics', 'is-settled'); window.clearTimeout(this.#settleTimer); // Lyrics belong to the song: the page hands the new song's over when they arrive. this.#lyrics.setLines([]); this.#lyrics.el.remove(); if (this.#controls) this.#controls.hidden = !current; if (!current) return; current.classList.add('is-current', 'is-expanded'); void this.#tiles.get(current)?.motion.to({ popX: 1, popY: 1 }, { duration: 0.2 }); if (this.#controls) current.append(this.#controls); current.append(this.#lyrics.el); // The lyrics are fitted to the card's box, so they wait for it to finish growing. this.#settleTimer = window.setTimeout(() => { current.classList.add('is-settled'); current.classList.toggle('has-lyrics', this.#lyrics.hasLines); this.#lyrics.resize(); this.nudge(); }, this.#first || this.#reduced.matches ? 0 : EXPANSION_SETTLE_MS); } #tick = (now: number) => { this.#frame = 0; if (this.#destroyed) return; const delta = Math.min(0.1, Math.max(0.001, (now - this.#last) / 1000)); this.#last = now; const playing = this.#options.playing(); const current = this.#current; let moving = false; if (current?.classList.contains('is-settled') && this.#lyrics.hasLines) { moving = this.#lyrics.frame(this.#options.clock(), delta, this.#reduced.matches); } if (this.#active && (playing || moving || now < this.#settleUntil)) this.#frame = requestAnimationFrame(this.#tick); }; }