From d240365e88678ec8a38305f7cc24d1b63d2e561c Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Fri, 20 Nov 2026 06:41:08 -0500 Subject: [PATCH 01/10] The home page becomes an episode explorer The fourth slice of the media-first redesign (#76). The home page is the whole archive as cards: search, filter by guest or topic and sort from a sticky toolbar, open a card in a close-up with its play, Up next and episode link, and come back to the card you left. Filters live in the URL (explorer/query), so a filtered view can be linked and stepped back through. Its styles are imported by the shell slice, which swaps in the new layout. Co-Authored-By: Claude Opus 5.5 --- .../starpod/src/components/EpisodeList.astro | 243 +- .../src/components/explorer/Card.astro | 147 + .../src/components/explorer/Hero.astro | 132 + .../src/components/explorer/Toolbar.astro | 246 ++ .../src/components/explorer/archive.ts | 211 + .../src/components/explorer/explorer.ts | 2311 +++++++++++ .../starpod/src/components/explorer/icons.tsx | 36 + .../starpod/src/components/explorer/query.ts | 139 + packages/starpod/src/pages/index.astro | 23 +- packages/starpod/src/styles/explorer.css | 3396 +++++++++++++++++ tests/unit/explorer-query.test.ts | 101 + 11 files changed, 6914 insertions(+), 71 deletions(-) create mode 100644 packages/starpod/src/components/explorer/Card.astro create mode 100644 packages/starpod/src/components/explorer/Hero.astro create mode 100644 packages/starpod/src/components/explorer/Toolbar.astro create mode 100644 packages/starpod/src/components/explorer/archive.ts create mode 100644 packages/starpod/src/components/explorer/explorer.ts create mode 100644 packages/starpod/src/components/explorer/icons.tsx create mode 100644 packages/starpod/src/components/explorer/query.ts create mode 100644 packages/starpod/src/styles/explorer.css create mode 100644 tests/unit/explorer-query.test.ts diff --git a/packages/starpod/src/components/EpisodeList.astro b/packages/starpod/src/components/EpisodeList.astro index c49a3dcb..eba01c26 100644 --- a/packages/starpod/src/components/EpisodeList.astro +++ b/packages/starpod/src/components/EpisodeList.astro @@ -1,85 +1,204 @@ --- -import FormattedDate from '../components/FormattedDate'; -import FullPlayButton from '../components/FullPlayButton'; import UFOIllustration from '../components/illustrations/UFOIllustration.astro'; +import { ArrowOutIcon, CloseIcon, QueueIcon } from './icons'; import type { Episode, Show } from '../lib/rss'; -import { dasherize } from '../utils/dasherize'; +import type { ArchiveCard, ArchiveChoice } from './explorer/archive'; +import Card from './explorer/Card.astro'; +import Toolbar from './explorer/Toolbar.astro'; export interface Props { + /** The archive, newest first, as `loadArchive()` prepares it. */ + cards: Array; episodes: Array; + people: Array; show: Show; + years: Array; } -const { episodes, show } = Astro.props; +const { cards, episodes, people, show, years } = Astro.props; --- + + { episodes.length === 0 ? ( -
-
+
+
- -

- No episodes yet. Check back soon! +

+ No episodes yet. The first one lands here the moment it’s in the feed.

) : ( -
    - {episodes.map((episode) => { - return ( -
  • -
    - +
    +

    + All episodes {episodes.length} +

    + +
    + {/* The Close-Up: two skeletons, one change. Opening a card re-targets + its artwork, facts line and title to these slots, and the archive + folds into a filmstrip beside it. The slots are empty boxes; the + two text slots hold an invisible copy, so they take the size the + travelling part will have when it lands. */} + {/* Only boxes: what shows in it belongs to the open card, so it is + no landmark of its own. */} + +
      + {cards.map((card) => ( + + ))} +
    +
    + {/* The open card's detail, after its description: where to resume and + what to do. One copy for the archive, moved into the card that + opens (explorer.ts). */} + + +
    + ) +} -
    - + diff --git a/packages/starpod/src/components/explorer/Card.astro b/packages/starpod/src/components/explorer/Card.astro new file mode 100644 index 00000000..ed4cac98 --- /dev/null +++ b/packages/starpod/src/components/explorer/Card.astro @@ -0,0 +1,147 @@ +--- +import type { Show } from '../../lib/rss'; +import { dasherize } from '../../utils/dasherize'; +import { formatDuration, toPlayable } from '../../utils/playable'; +import type { ArchiveCard } from './archive'; + +export interface Props { + card: ArchiveCard; + show: Show; +} + +const { card, show } = Astro.props; +const { episode } = card; +const date = new Date(episode.published); +const number = + episode.episodeNumber === 'Bonus' ? 'Bonus' : episode.episodeNumber; +// Sentence case under the title: "Ep 254 · Sep 24, 2026 · 1 hr 21 min". +const short = episode.episodeNumber === 'Bonus' ? 'Bonus' : `Ep ${number}`; +const detailId = `xp-detail-${episode.id.replace(/[^a-z0-9]/gi, '')}`; +const length = formatDuration(episode.duration); +const playable = toPlayable(episode, show); +// The episode's playable slice, once, on the card itself: the play disc, Up +// next and the close-up all read it from here (explorer.ts, playableOf). +// Media types are only written when they aren't the usual ones. +const media = { + 'data-audio': playable.audio.src, + 'data-audio-type': + playable.audio.type === 'audio/mpeg' ? undefined : playable.audio.type, + 'data-video': playable.video ? playable.video.src : undefined, + 'data-video-type': + playable.video && playable.video.type !== 'application/x-mpegURL' + ? playable.video.type + : undefined, + 'data-thumb': playable.image +}; +const ids = (people: typeof card.people) => + people.map((person) => encodeURIComponent(person.id)).join(' '); +--- + +{ + /* + A card is loose parts, as in the Close-Up: the artwork, the facts line + and the title each travel on their own, and the detail (description, + cast, Up next, the episode link) is laid out wherever the card is shown: + a list row's text, or the close-up's column. +*/ +} +
  • person.isHost)) || undefined} + data-people={ids(card.people)} + {...media} + data-vt={dasherize(episode.title)} + data-year={card.year} +> +
    + +
    +
    +

    + {short} + + {length} + {episode.video && Video} +

    +

    + {episode.title} +

    +
    +
    +

    + {episode.description} +

    + + { + /* The cast, where to resume and the actions are made when the card + opens (explorer.ts): only the open card shows them. */ + } +
    +
    + { + /* At rest the disc is plain markup; the card that is playing gets the + live control (explorer.ts). */ + } + +
    +
  • diff --git a/packages/starpod/src/components/explorer/Hero.astro b/packages/starpod/src/components/explorer/Hero.astro new file mode 100644 index 00000000..57c2daaa --- /dev/null +++ b/packages/starpod/src/components/explorer/Hero.astro @@ -0,0 +1,132 @@ +--- +import FullPlayButton from '../FullPlayButton'; +import { ArrowOutIcon, HeadphonesIcon, VideoIcon } from '../icons'; +import { optimizeImage } from '../../lib/optimize-episode-image'; +import type { Show } from '../../lib/rss'; +import { dasherize } from '../../utils/dasherize'; +import { formatDuration, toPlayable } from '../../utils/playable'; +import type { ArchiveCard } from './archive'; +import PersonFace from '../PersonFace.astro'; +import { voiceFor } from '../../lib/cast'; +import { getEpisodeCues } from '../../lib/episode-cues'; + +export interface Props { + card: ArchiveCard; + show: Show; +} + +const { card, show } = Astro.props; +const { episode } = card; +const playable = toPlayable(episode, show); +// The same rendition the episode stage shows, so the two morph into each +// other on navigation without a change of resolution. +const art = + (await optimizeImage(episode.episodeImage ?? show.image, { + width: 960, + height: 960 + })) ?? show.image; +const date = new Date(episode.published); +// The artwork's address as a CSS string (the feed's own, when it couldn't be +// optimised, may hold anything). +const artUrl = `url("${art.replace(/["\\\n\r]/g, (c) => (c === '\n' ? '\\a ' : c === '\r' ? '\\d ' : `\\${c}`))}")`; +// Who speaks in the transcript wears that voice's ring. +const cues = card.people.length ? await getEpisodeCues(episode) : null; +const number = + episode.episodeNumber === 'Bonus' + ? 'Bonus' + : `Episode ${episode.episodeNumber}`; +--- + +
    + +
    + + + + {episode.video ? : } + {episode.video ? 'Video' : 'Audio'} + + + + + +
    + +
    +

    + + Latest episode +

    +

    + {episode.title} +

    +

    + {number} + + {formatDuration(episode.duration)} +

    + { + card.people.length > 0 && ( + + ) + } +

    {episode.description}

    + +
    +
    diff --git a/packages/starpod/src/components/explorer/Toolbar.astro b/packages/starpod/src/components/explorer/Toolbar.astro new file mode 100644 index 00000000..0e015fd5 --- /dev/null +++ b/packages/starpod/src/components/explorer/Toolbar.astro @@ -0,0 +1,246 @@ +--- +import { CloseIcon, ListIcon, SearchIcon } from '../icons'; +import PersonFace from '../PersonFace.astro'; +import type { ArchiveChoice } from './archive'; +import { ChevronIcon, GridIcon, ResumeIcon, SortIcon, UpIcon } from './icons'; + +export interface Props { + people: Array; + total: number; + years: Array; +} + +const { people, total, years } = Astro.props; + +const sorts = [ + { value: 'newest', label: 'Newest first' }, + { value: 'oldest', label: 'Oldest first' }, + { value: 'longest', label: 'Longest first' }, + { value: 'shortest', label: 'Shortest first' } +]; + +// Anchored auto layout attributes have an emoji in their name, which JSX +// can't spell; spread them in. +const segRoot = { 'data-⚓️-root': '', 'data-⚓️-scope-name': '--xp-on' }; +const segThumb = { + 'data-⚓️-to': '--xp-on', + 'data-⚓️-fill': '', + 'data-⚓️-transition': 'glide' +}; +--- + +
    + +
    +

    diff --git a/packages/starpod/src/components/explorer/archive.ts b/packages/starpod/src/components/explorer/archive.ts new file mode 100644 index 00000000..adb16e45 --- /dev/null +++ b/packages/starpod/src/components/explorer/archive.ts @@ -0,0 +1,211 @@ +/** + * Everything the home page's explorer renders, gathered once at build time: + * each episode's artwork at card sizes, its hosts and guests (from the + * opt-in database), and the menus' choices (years, people). + * + * Server-only. + */ +import type { ImageMetadata } from 'astro'; +import { getImage } from 'astro:assets'; +import { eq } from 'drizzle-orm'; +import starpodConfig, { database } from 'virtual:starpod/config'; + +import avatarLight from '../../assets/avatar-light.png'; +import { createDb } from '../../db'; +import { HostOrGuest, Person } from '../../db/schema'; +import { sortCast, type CastPerson } from '../../lib/cast'; +import type { Episode, Show } from '../../lib/rss'; + +export interface ArchivePerson { + id: string; + name: string; + avatar: string; + isHost: boolean; +} + +export interface ArchiveCard { + episode: Episode; + /** Feed order: 0 is the newest. */ + index: number; + art: { src: string; srcset?: string }; + people: Array; + year: string; +} + +export interface ArchiveChoice { + value: string; + label: string; + count: number; + avatar?: string; + /** Hosted most of their episodes (people only; set by loadPeople). */ + host?: boolean; +} + +const photos = import.meta.glob<{ default: ImageMetadata }>( + '/src/img/people/*.{jpeg,jpg,png}' +); + +const avatars = new Map>(); + +function avatarFor(img: string | null): Promise { + const key = img ?? ''; + if (!avatars.has(key)) { + avatars.set( + key, + (async () => { + const source = + (img && (await photos[`/src/img/people/${img}`]?.())?.default) || + avatarLight; + const image = await getImage({ + src: source, + width: 64, + height: 64, + format: 'webp' + }); + return image.src; + })() + ); + } + return avatars.get(key)!; +} + +/** Square artwork at the sizes a card can be shown at, grid tile to list row. */ +async function cardArt(src: string | undefined, fallback: string) { + if (!src) { + return { src: fallback }; + } + try { + const image = await getImage({ + src, + format: 'avif', + height: 320, + quality: 75, + width: 320, + widths: [160, 320, 640] + }); + return { src: image.src, srcset: image.srcSet.attribute }; + } catch { + return { src: fallback }; + } +} + +/** Each episode's people, keyed by episode slug, when the database is on. */ +async function peopleBySlug(): Promise>> { + const bySlug = new Map>(); + if (!database) { + return bySlug; + } + const db = createDb( + import.meta.env.ASTRO_DB_REMOTE_URL, + import.meta.env.ASTRO_DB_APP_TOKEN + ); + const rows = await db + .select({ + id: Person.id, + img: Person.img, + isHost: HostOrGuest.isHost, + name: Person.name, + slug: HostOrGuest.episodeSlug + }) + .from(HostOrGuest) + .innerJoin(Person, eq(HostOrGuest.personId, Person.id)); + for (const { slug, ...person } of rows) { + bySlug.set(slug, [...(bySlug.get(slug) ?? []), person]); + } + return bySlug; +} + +let everyone: Promise> | undefined; + +/** + * Everyone in the archive and how many episodes they are on, most first: the + * With filter's choices without the card art, for the search palette (every + * page). Gathered once; empty when the database is off or out of reach. + */ +export function loadPeople(): Promise> { + everyone ??= (async () => { + const counted = new Map< + string, + CastPerson & { count: number; hosted: number } + >(); + for (const cast of (await peopleBySlug()).values()) { + for (const person of cast) { + const seen = counted.get(person.id); + counted.set(person.id, { + ...person, + count: (seen?.count ?? 0) + 1, + hosted: (seen?.hosted ?? 0) + (person.isHost ? 1 : 0) + }); + } + } + const choices = await Promise.all( + [...counted.values()].map( + async (person): Promise => ({ + value: person.id, + label: person.name, + count: person.count, + avatar: await avatarFor(person.img), + host: person.hosted * 2 > person.count + }) + ) + ); + return choices.sort( + (a, b) => b.count - a.count || a.label.localeCompare(b.label) + ); + })().catch(() => []); + return everyone; +} + +export async function loadArchive(episodes: Array, show: Show) { + const people = await peopleBySlug(); + const hosts = starpodConfig.hosts.map((host) => host.name); + + const cards: Array = await Promise.all( + episodes.map(async (episode, index) => ({ + episode, + index, + art: await cardArt( + episode.episodeImage, + episode.episodeThumbnail ?? show.image + ), + people: await Promise.all( + sortCast(people.get(episode.episodeSlug) ?? [], hosts).map( + async (person) => ({ + id: person.id, + name: person.name, + avatar: await avatarFor(person.img), + isHost: person.isHost + }) + ) + ), + year: String(new Date(episode.published).getFullYear()) + })) + ); + + const years = new Map(); + const everyone = new Map(); + for (const card of cards) { + years.set(card.year, (years.get(card.year) ?? 0) + 1); + for (const person of card.people) { + const choice = everyone.get(person.id); + everyone.set(person.id, { + value: person.id, + label: person.name, + count: (choice?.count ?? 0) + 1, + avatar: person.avatar + }); + } + } + + return { + cards, + years: [...years] + .sort(([a], [b]) => Number(b) - Number(a)) + .map( + ([year, count]): ArchiveChoice => ({ value: year, label: year, count }) + ), + people: [...everyone.values()].sort( + (a, b) => b.count - a.count || a.label.localeCompare(b.label) + ) + }; +} diff --git a/packages/starpod/src/components/explorer/explorer.ts b/packages/starpod/src/components/explorer/explorer.ts new file mode 100644 index 00000000..04e3ae09 --- /dev/null +++ b/packages/starpod/src/components/explorer/explorer.ts @@ -0,0 +1,2311 @@ +/** + * The home page's explorer: search, filter, sort, re-view and open the + * whole archive in the browser. Every episode is already in the page; this + * only decides which cards show, in what order and in which layout, and + * carries the cards on screen to their new places with PropFLIP. + * + * - Only cards near the viewport are measured and flipped (an + * IntersectionObserver keeps that set), so the cost of a change doesn't + * grow with the archive, and `content-visibility` keeps skipping the rest. + * - A card flips as parts: its artwork scales (it is square in every + * layout, so it never squishes), its text block only travels, and when + * the text block changes width its re-wrapped lines fade in at the + * destination instead of being stretched. + * - Opening a card is the Close-Up (propflip-anchored-auto-layout's + * demos/closeup.html): its artwork, facts line and title re-target to + * their own slots in a close-up layout on three delays, the title growing + * as type and the artwork turning over, while the archive folds into a + * filmstrip beside it in the same change. The arrow keys step through the + * results and swap mid-flight; Escape closes. + * - Cards that leave fade out where they stood, out of the flow; cards that + * arrive come in with `@starting-style`; cards that slide into view from + * far away rise in. + * - Everything is interruptible: a flip starts from the pixels on screen. + * + * State lives in the URL query (see ./query.ts), so other pages can link + * into a filtered archive and back/forward steps through the changes. + */ +import { + flip, + onFlip, + registerFlipTargets, + reducedMotion, + type FlipRect +} from '../../motion/propflip'; +import { readPosition } from '../media/position'; +import { + currentEpisode, + dequeue, + enqueue, + playEpisode, + queue, + type PlayableEpisode +} from '../state'; +import FullPlayButton from '../FullPlayButton'; +import { personFact } from '../../lib/cast'; +import { effect, untracked } from '@preact/signals'; +import { h, render as mount } from 'preact'; +import { + compare, + DEFAULT_STATE, + inProgress, + isFiltered, + matches, + parseState, + toSearch, + type ExplorerEntry, + type ExplorerState +} from './query'; + +interface Card { + entry: ExplorerEntry; + li: HTMLElement; + art: HTMLButtonElement; + turn: HTMLElement; + body: HTMLElement; + facts: HTMLElement; + title: HTMLElement; + play: HTMLElement; + detail: HTMLElement; +} + +/** The episode's playable slice, from its card (Card.astro writes it once). */ +function playableOf(li: HTMLElement): PlayableEpisode { + const data = li.dataset; + const title = li.querySelector('.xp-title a')!; + return { + audio: { src: data.audio!, type: data.audioType ?? 'audio/mpeg' }, + duration: Number(data.duration), + episodeNumber: li.querySelector('.xp-number')!.dataset.number!, + id: data.id!, + image: data.thumb, + slug: title.getAttribute('href')!.slice(1), + title: title.textContent!.trim(), + video: data.video + ? { src: data.video, type: data.videoType ?? 'application/x-mpegURL' } + : undefined + } as PlayableEpisode; +} + +/** Milliseconds between one card and the next in a cascade, and its cap. */ +const STEP = 16; +const MAX_DELAY = 240; +/** The Close-Up's three delays: artwork, facts line, title (then play). */ +const PART_STEP = 60; +/** How long a change to the close-up takes to land, at --slomo 1. */ +const SWAP_MS = 1300; +/** When a card in the archive has all but arrived (explorer.css: its + * flight eases out over 550ms, 97% of the way by half of it), and when one + * coming home from the close-up has (its title, last of its parts, sets + * out 120ms in, over 600ms). */ +const ARRIVED_MS = 280; +/** When a card the sidebar carries has nearly arrived (the column glides on + * the same clock, so its text may come back sooner). */ +const CARRIED_MS = 140; +/** How long a card leaving the cut takes to clear its text (explorer.css). */ +const LEAVE_MS = 120; +const SWAP_ARRIVED_MS = 480; +// Where the reading order can follow `order`, a sort only restyles the +// cards; elsewhere the cards move in the DOM so keyboard and screen readers +// meet them in the order they are shown. +const READING_FLOW = + typeof CSS !== 'undefined' && CSS.supports('reading-flow', 'grid-order'); +// Only the cards around the viewport are boxes in the archive's grid (see +// "The window" below). Where find in page can't open a parked block +// (hidden until found), the close-up can't anchor its parts, or a parked +// block can't lay its cards on the grid's own tracks, every card stays in +// the grid. +const WINDOWING = + typeof CSS !== 'undefined' && + 'onbeforematch' in HTMLElement.prototype && + CSS.supports('position-anchor', '--x') && + CSS.supports('grid-template-rows', 'subgrid'); +// A card the shell glides keeps its containment and widens its clip (see +// `fly`), where the browser has a clip to widen. +const GLIDE_CLIP = + typeof CSS !== 'undefined' && CSS.supports('overflow-clip-margin', '1px'); + +function slomo() { + return ( + Number( + getComputedStyle(document.documentElement).getPropertyValue('--slomo') + ) || 1 + ); +} + +/** The archive's sizes when it was last live, and what they depend on. */ +let lastSize: { key: string; width: string; bar: string } | undefined; +const sizeKey = () => + `${innerWidth} ${document.documentElement.dataset.rail ?? ''}`; + +// Coming home as wide as the archive last was, it arrives sized: the router +// lays the incoming page out once (to restore its scroll), and that is the +// archive's only layout before the morph home is captured. +if (typeof document !== 'undefined') { + document.addEventListener('astro:before-swap', (event) => { + const explorer = ( + event as Event & { newDocument?: Document } + ).newDocument?.querySelector('[data-explorer]'); + if (!explorer || lastSize?.key !== sizeKey()) { + return; + } + explorer.style.setProperty('--xp-bar-h', lastSize.bar); + explorer + .querySelectorAll( + '.xp-stage, .xp-list, [data-xp-ghost="title"]' + ) + .forEach((el) => el.style.setProperty('--xp-w', lastSize!.width)); + explorer.querySelector('.xp-stage')?.setAttribute('data-sized', ''); + }); +} + +function clock(seconds: number) { + const s = Math.floor(seconds); + const parts = [Math.floor(s / 3600), Math.floor((s % 3600) / 60), s % 60]; + return (parts[0] ? parts : parts.slice(1)) + .map((n, i) => (i ? String(n).padStart(2, '0') : String(n))) + .join(':'); +} + +export function startExplorer() { + const found = document.querySelector('[data-explorer]'); + if (!found || found.dataset.live !== undefined) { + return; + } + const root: HTMLElement = found; + root.dataset.live = ''; + + const list = root.querySelector('.xp-list')!; + const stage = root.querySelector('.xp-stage')!; + const closeup = root.querySelector('[data-xp-closeup]')!; + const ghostFacts = closeup.querySelector( + '[data-xp-ghost="facts"]' + )!; + const ghostTitle = closeup.querySelector( + '[data-xp-ghost="title"]' + )!; + const form = root.querySelector('.xp-bar-in')!; + const bar = root.querySelector('[data-xp-bar]')!; + const status = root.querySelector('[data-xp-status]')!; + const empty = root.querySelector('[data-xp-empty]')!; + const shownCount = root.querySelector('[data-xp-shown]')!; + const ofTotal = root.querySelector('[data-xp-of]')!; + const progressButton = + form.querySelector('[data-xp-progress]')!; + const search = form.elements.namedItem('q') as HTMLInputElement; + const lifetime = new AbortController(); + const { signal } = lifetime; + + // A pointer resting on the page as it arrives (a reload, or back from an + // episode) is not a hover yet: the browser applies :hover a beat later on + // its own (with pointerover, never pointermove), and the card under it + // would start to grow by itself. Cards answer the pointer once it moves. + root.dataset.still = ''; + const moved = () => { + delete root.dataset.still; + removeEventListener('pointermove', moved); + }; + addEventListener('pointermove', moved, { signal, passive: true }); + + // Everyone on the show, from the With menu: name and portrait by id. A + // card's cast is made from these when it opens. + const everyone = new Map(); + for (const option of form.querySelectorAll('#xp-people .xp-option')) { + const id = option.querySelector('input')!.value; + if (id) { + everyone.set(id, { + name: option.querySelector('span:not([class])')!.textContent!.trim(), + photo: option.querySelector('img')?.getAttribute('src') ?? '' + }); + } + } + const idsOf = (li: HTMLElement, key: 'people' | 'hosts') => + li.dataset[key] ? li.dataset[key]!.split(' ').map(decodeURIComponent) : []; + + const cards: Array = [...list.children].map((node) => { + const li = node as HTMLElement; + const part = (selector: string) => + li.querySelector(selector)!; + let text: string | undefined; + return { + entry: { + index: Number(li.dataset.index), + duration: Number(li.dataset.duration), + people: idsOf(li, 'people'), + position: 0, + // Read from the card when a search first needs it, not on arrival + // (coming home, the explorer starts inside the morph). + get text() { + return (text ??= [ + part('.xp-facts').textContent, + part('.xp-title').textContent, + part('.xp-desc').textContent, + ...idsOf(li, 'people').map((id) => everyone.get(id)?.name) + ] + .join(' ') + .replace(/\s+/g, ' ') + .toLowerCase()); + }, + video: li.dataset.video !== undefined, + year: li.dataset.year ?? '' + }, + li, + art: part('.xp-art'), + turn: part('.xp-turn'), + body: part('.xp-text'), + facts: part('.xp-facts'), + title: part('.xp-title'), + play: part('.xp-play'), + detail: part('.xp-detail') + }; + }); + const cardOf = new Map(cards.map((card) => [card.li, card])); + + /** A year or person the menus don't offer is no filter at all (a stale + * link, or people when the site has no guests database). */ + function known(next: ExplorerState): ExplorerState { + const offered = (name: 'year' | 'guest') => { + const field = form.elements.namedItem(name) as RadioNodeList | null; + return new Set( + field + ? [...field].map((input) => (input as HTMLInputElement).value) + : [] + ); + }; + return { + ...next, + year: offered('year').has(next.year) ? next.year : '', + guest: offered('guest').has(next.guest) ? next.guest : '' + }; + } + + let state = known(parseState(location.search)); + // The page arrives newest first. + let order = cards; + let sorted: ExplorerState['sort'] = 'newest'; + // The card in the close-up, and the cards on their way in or out of it. + let open: Card | null = null; + // The stage's width, as last measured. + let width = ''; + const swapping = new Map(); + // While the explorer runs a flip of its own, its listener adds the cascade. + let mine = false; + // The view the archive was in when the change began (its text's look), + // and where the stage was once it had changed. + let fromView = 'grid'; + let stageAt: DOMRect | null = null; + let scale = 1; + + /* ---------- What is on screen ---------- */ + + const near = new Set(); + const watcher = new IntersectionObserver( + (entries) => { + for (const { isIntersecting, target } of entries) { + const card = cardOf.get(target)!; + if (isIntersecting) { + near.add(card); + } else { + near.delete(card); + } + } + }, + { rootMargin: '25% 0px' } + ); + cards.forEach((card) => watcher.observe(card.li)); + + // How much of the stuck toolbar is cut away (on a phone on its side, all + // but its first row: explorer.css), read with its size. + let cut = 0; + + /** The line under the sticky toolbar: cards above it are out of sight. */ + function fold() { + return bar.getBoundingClientRect().bottom - cut; + } + + /** Shown cards whose box is in the viewport now, found by bisection. */ + function onScreen() { + const shown = order.filter( + (card) => !card.li.hidden && card.li.parentElement === list + ); + const top = fold(); + let lo = 0; + let hi = shown.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (shown[mid]!.li.getBoundingClientRect().bottom <= top) { + lo = mid + 1; + } else { + hi = mid; + } + } + const seen: Array = []; + for (const card of shown.slice(lo)) { + const box = card.li.getBoundingClientRect(); + if (box.top >= innerHeight) { + break; + } + // (A phone's strip runs past the screen's sides.) + if (box.right > 0 && box.left < innerWidth) { + seen.push(card); + } + } + return seen; + } + + // In the close-up (and on the way in or out) the text block comes apart: + // its facts line and title travel on their own. + const parts = (card: Card) => + card === open || swapping.has(card) + ? [card.art, card.facts, card.title, card.play] + : [card.art, card.body, card.play]; + + /** Each close-up part's place in the Close-Up's three delays. */ + function partIndex(card: Card, el: HTMLElement) { + return [card.art, card.facts, card.title, card.play].indexOf(el); + } + + /* ---------- The window ---------- + Every card box in the grid costs each frame that changes anything on + the page (the compositor's layerizing walks them all, rendered or + skipped) and every relayout of the grid. So only the cards around the + viewport are grid items. The rest wait in two parked blocks, one before + them and one after: each is one box spanning exactly the rows its cards + would take (every row is the same height), with its cards laid on the + same tracks inside (subgrid) and hidden until found, so find in page + opens a block where the match would be and the window moves there. The + window follows the scroll, and every change re-windows around the card + it keeps in place. The HTML still holds every card in the grid. */ + + const parked = (where: 'above' | 'below') => { + const block = document.createElement('li'); + block.className = 'xp-park'; + block.dataset[where] = ''; + block.dataset.empty = ''; + block.setAttribute('role', 'none'); + block.setAttribute('hidden', 'until-found'); + return block; + }; + const above = parked('above'); + const below = parked('below'); + // Shown cards [from, to) in display order are in the grid. + let win = { from: 0, to: Infinity }; + let windowed = false; + // The grid's columns and its row pitch, read from style (no layout). On a + // phone the close-up's strip is one row that scrolls sideways (`across`): + // there every cell is a "row" of the window, a column wide. + let span = 1; + let pitch = 0; + let gap = 0; + let inset = 0; + let across = false; + + const inGrid = (card: Card) => card.li.parentElement === list; + const activeTransition = () => { + try { + return document.documentElement.matches(':active-view-transition'); + } catch { + return false; + } + }; + + function metrics() { + const style = getComputedStyle(list); + across = style.gridAutoFlow.startsWith('column'); + const row = parseFloat(across ? style.gridAutoColumns : style.gridAutoRows); + span = parseInt(style.getPropertyValue('--xp-span'), 10) || 1; + gap = parseFloat(across ? style.columnGap : style.rowGap) || 0; + pitch = row + gap; + inset = parseFloat(across ? style.paddingLeft : style.paddingTop) || 0; + return row > 0 && pitch > 0; + } + + /** How far the window looks: the viewport's height, or a strip's width. */ + const extent = () => (across ? innerWidth : innerHeight); + + /** Rows above and below the viewport the window keeps. */ + const margin = () => Math.max(2, Math.ceil(extent() / pitch)); + + /** The rows in the viewport now (one layout read). */ + // The first row whose top is in the viewport, and where: noted with every + // read of the rows in view (no read of its own), so a resize can hold it. + let seenRow: { row: number; y: number; span: number } | null = null; + function viewRows() { + if (across) { + // The first cell's left edge, wherever the strip is scrolled. + const left = list.getBoundingClientRect().left + inset - list.scrollLeft; + return [ + Math.max(0, Math.floor(-left / pitch)), + Math.max(0, Math.floor((innerWidth - left) / pitch)) + ] as const; + } + const top = list.getBoundingClientRect().top + inset; + const row = Math.max(0, Math.ceil(-top / pitch)); + seenRow = { row, y: top + row * pitch, span }; + return [ + Math.max(0, Math.floor(-top / pitch)), + Math.max(0, Math.floor((innerHeight - top) / pitch)) + ] as const; + } + + /** + * The window around a card: the viewport it will be in (its top at `y`, + * or centred) and a screen either side, as following the scroll keeps, + * so the window that settles after a change is the one it made. + */ + function rowsAround(card: Card, y?: number) { + const shown = order.filter((other) => !other.li.hidden); + const row = Math.floor(Math.max(0, shown.indexOf(card)) / span); + // (A phone's strip is always placed with the card in the middle.) + const at = + y === undefined || across + ? (extent() - pitch) / 2 + : Math.min(Math.max(y, 0), innerHeight); + const reach = margin(); + return [ + row - Math.ceil(at / pitch) - reach, + row + Math.ceil((extent() - at) / pitch) + reach + ] as const; + } + + /** + * Put the shown cards in rows `first` to `last` in the grid and the rest + * in the parked blocks. `keep` stays in the grid wherever it falls (the + * open card, the focused card, cards fading out where they stood). + */ + function partition( + first: number, + last: number, + keep = new Set(), + linger = new Set() + ) { + const shown = order.filter((card) => !card.li.hidden); + const rows = Math.ceil(shown.length / span); + first = Math.max(0, Math.min(first, rows - 1)); + last = Math.max(first, Math.min(last, rows - 1)); + for (const card of keep) { + if (card.li.hidden || card.li.dataset.away !== undefined) { + continue; + } + const row = Math.floor(shown.indexOf(card) / span); + first = Math.min(first, row); + last = Math.max(last, row); + } + const from = rows ? first * span : 0; + const to = rows ? Math.min(shown.length, (last + 1) * span) : 0; + win = { from, to }; + above.style.setProperty('--xp-rows', String(rows ? first : 0)); + below.style.setProperty('--xp-rows', String(rows ? rows - last - 1 : 0)); + above.toggleAttribute('data-empty', !rows || first === 0); + below.toggleAttribute('data-empty', !rows || last >= rows - 1); + // Find in page may have opened one; the window has moved there now. + for (const block of [above, below]) { + if (block.getAttribute('hidden') !== 'until-found') { + block.setAttribute('hidden', 'until-found'); + } + } + const grid = shown.slice(from, to); + shown.forEach((card, i) => { + if (i >= from && i < to) { + fade(card, false); + return; + } + // A card on screen whose new place is out of the window fades out + // where it stood, and waits in the grid until it has. + if (linger.has(card) && inGrid(card)) { + fade(card, true); + } + }); + // Assistive technology meets only the window: it says where each card + // is in the whole cut. + grid.forEach((card, i) => { + card.li.setAttribute('aria-posinset', String(from + i + 1)); + card.li.setAttribute('aria-setsize', String(shown.length)); + }); + // Cards go where they show: in the grid's DOM order (it is the reading + // order where `order` isn't, and the order until a sort sets it) and + // the blocks' (the order a block lays its cards out in, should find in + // page open it). Only cards out of place move (a moved card is laid out + // afresh and rebound by everything that observes it): each run is laid + // past whatever else is in its parent, which moves elsewhere or stays. + // (Cards hidden or fading out where they stood keep their DOM place.) + const lay = (parent: Element, start: Element | null, run: Array) => { + const members = new Set(run.map((card) => card.li)); + const next = (el: Element | null) => { + let sibling = el ? el.nextElementSibling : parent.firstElementChild; + while (sibling && !members.has(sibling)) { + sibling = sibling.nextElementSibling; + } + return sibling; + }; + let previous = start; + for (const card of run) { + if (next(previous) !== card.li) { + if (previous) { + previous.after(card.li); + } else { + parent.prepend(card.li); + } + } + previous = card.li; + } + }; + // (A card fading out where it stood parks once it has.) + const parks = (card: Card) => card.li.dataset.away === undefined; + lay(list, above, grid); + lay(above, null, shown.slice(0, from).filter(parks)); + lay(below, null, shown.slice(to).filter(parks)); + } + + /** Move the window to the viewport, if it is getting near an edge. */ + function follow(force = false) { + if (!windowed || !metrics()) { + return; + } + const [top, bottom] = viewRows(); + const reach = margin(); + const first = Math.floor(win.from / span); + const last = Math.ceil(win.to / span) - 1; + if (!force && top - first >= reach / 2 && last - bottom >= reach / 2) { + return; + } + partition(top - reach, bottom + reach, kept()); + } + + /** Cards the window keeps wherever they fall. */ + function kept() { + const keep = new Set([...flying.keys()].map((li) => cardOf.get(li)!)); + if (open) { + keep.add(open); + } + // The focused card, and the card named for a view transition (coming + // back from its episode, it flies home), stay in the grid. + for (const li of [ + document.activeElement?.closest('.xp-card'), + list.querySelector('.xp-card[data-vt-named]') + ]) { + if (li && cardOf.has(li)) { + keep.add(cardOf.get(li)!); + } + } + return keep; + } + + let following = 0; + let scrolled = false; + const followSoon = () => { + if (!following) { + following = requestAnimationFrame(() => { + following = 0; + follow(); + if (scrolled) { + scrolled = false; + deepen(false); + } + }); + } + }; + + /* ---------- Depth ---------- + In the close-up only the strip's cells in view (and a quarter screen + either way) are in depth (data-depth, explorer.css): their wrappers + become boxes that lean back and catch the vantage. So opening, stepping + and closing restyle the insides of those cells and of the cards flying, + not of every cell the strip renders. While the page scrolls, cells take + depth a screen ahead, before they render, and the far ones give it back + once the scroll settles (`settled`). */ + const deep = new Set(); + function deepen(settled: boolean, extra: Iterable = []) { + // Folding back into the wall, the cells keep their depth until they + // land (`folding`), so they straighten up in perspective. + if ((!open && (!deep.size || folded)) || !metrics()) { + return; + } + const want = new Set(); + if (open) { + const [top, bottom] = viewRows(); + const reach = settled + ? Math.max(1, Math.ceil(extent() / pitch / 4)) + : margin(); + order + .filter((card) => !card.li.hidden) + .slice(Math.max(0, top - reach) * span, (bottom + reach + 1) * span) + .forEach((card) => want.add(card)); + for (const card of extra) { + if (!card.li.hidden) { + want.add(card); + } + } + } + for (const card of deep) { + if (settled && !want.has(card)) { + delete card.li.dataset.depth; + card.turn.parentElement!.style.removeProperty('perspective-origin'); + deep.delete(card); + } + } + for (const card of want) { + if (!deep.has(card)) { + card.li.dataset.depth = ''; + deep.add(card); + } + } + } + + /** + * Start windowing, once the grid's rows have a size. The first partition + * parks most of the archive, so it waits for idle time, and for any view + * transition (the morph home) to end: moving the cards under one shifts + * the page in WebKit, and would cost the morph its frames anywhere. + */ + let starting: (() => void) | null = null; + function startWindow() { + if (windowed || !WINDOWING || starting) { + return; + } + const begin = () => { + starting = null; + if (windowed || !metrics()) { + return; + } + list.prepend(above); + list.append(below); + // Every row keeps its place as cards come and go, so the browser's + // scroll anchoring has nothing to correct; left on, it would chase a + // card on its way into or out of a parked block. + list.style.overflowAnchor = 'none'; + windowed = true; + follow(true); + }; + const wait = () => { + if (activeTransition()) { + const timer = window.setTimeout(wait, 100); + starting = () => clearTimeout(timer); + } else if (typeof requestIdleCallback === 'function') { + const idle = requestIdleCallback(begin, { timeout: 1000 }); + starting = () => cancelIdleCallback(idle); + } else { + const timer = window.setTimeout(begin, 50); + starting = () => clearTimeout(timer); + } + }; + wait(); + } + + /** + * Re-window after a change: around `card` (the one holding the reader's + * place, or the close-up's), around the top of the results (`null`), or + * around the viewport (left out). `y` is where that card's top will be in + * the viewport, if not centred. `linger` were on screen: those whose + * place is now out of the window fade out where they stood. + */ + function reWindow(card?: Card | null, linger?: Set, y?: number) { + if (!windowed || !metrics()) { + return; + } + const keep = new Set(); + if (open) { + keep.add(open); + } + // The focused card takes its new place rather than fade out where it + // stood (inert, which would drop the focus). + const focused = document.activeElement?.closest('.xp-card'); + if (focused && cardOf.has(focused)) { + keep.add(cardOf.get(focused)!); + } + const anchor = + card === null ? order.find((other) => !other.li.hidden) : card; + if (anchor && !anchor.li.hidden) { + const [first, last] = rowsAround(anchor, y); + keep.add(anchor); + partition(first, last, keep, linger); + } else { + const [top, bottom] = viewRows(); + partition(top - margin(), bottom + margin(), keep, linger); + } + } + + /** + * A card fading out where it stood keeps its old place in the DOM until + * it parks, which is the reading order where reading-flow isn't: until + * then it is inert, out of the tab order and the accessibility tree. + */ + function fade(card: Card, on: boolean) { + card.li.toggleAttribute('data-away', on); + card.li.inert = on; + } + + /** Cards that faded out where they stood go to their parked block. */ + let settling = 0; + function settleAway(after: number) { + clearTimeout(settling); + settling = window.setTimeout(() => { + for (const card of cards) { + fade(card, false); + } + follow(true); + }, after); + } + + /* ---------- Motion ---------- */ + + const flying = new Map(); + const refitting = new WeakMap(); + /** + * Copies of text blocks as they were (in `view`, at their old boxes), + * fading out where they stood: inert, unseen by assistive technology, + * gone once faded. Styled by a list in the old view, so they look as the + * text did before it re-wrapped. + */ + function fadeOutText( + texts: Array<[HTMLElement, number, FlipRect]>, + view: string, + s: number, + at?: DOMRect | null + ) { + if (!texts.length || reducedMotion()) { + return; + } + const frame = at ?? stage.getBoundingClientRect(); + const layer = document.createElement('div'); + layer.className = 'xp-fading-text'; + layer.dataset.view = view; + layer.inert = true; + layer.setAttribute('aria-hidden', 'true'); + for (const [el, , first] of texts) { + const li = document.createElement('div'); + li.className = 'xp-fading-card'; + li.toggleAttribute( + 'data-current', + el.closest('.xp-card')?.dataset.current !== undefined + ); + const copy = el.cloneNode(true) as HTMLElement; + for (const node of [copy, ...copy.querySelectorAll('*')]) { + node.removeAttribute('id'); + node.removeAttribute('style'); + node.removeAttribute('data-props-for'); + node.classList.remove('PropFLIP'); + } + copy.style.cssText = `position: absolute; left: ${first.left - frame.left}px; top: ${first.top - frame.top}px; width: ${first.width}px; height: ${first.height}px; margin: 0; transform: none;`; + li.append(copy); + layer.append(li); + } + stage.append(layer); + layer.animate([{ opacity: 1 }, { opacity: 0 }], { + duration: 200 * s, + easing: 'ease-out', + fill: 'forwards' + }).onfinish = () => layer.remove(); + } + + /** Text that lands somewhere new fades in there (opacity only). */ + function fadeIn(el: HTMLElement, delay: number, s: number) { + refitting.get(el)?.cancel(); + refitting.set( + el, + el.animate([{ opacity: 0 }, { opacity: 1 }], { + delay, + duration: 380 * s, + easing: 'ease-out', + fill: 'backwards' + }) + ); + } + + // A card skips styling and painting its contents while it is off screen + // (content-visibility), and clips them to its box. A card about to fly + // must render in full from before the flip until it lands, or its parts + // would never start their transitions, or be cut off on the way. + // The shell's glide carries only cards in view, which render already: + // those keep their containment and widen their clip (`reach`, px) to + // where their parts set out from, which restyles the card's own box and + // nothing inside it, before the glide and after. + function fly(card: Card, s: number, reach?: number) { + if (reach === undefined) { + card.li.dataset.flying = ''; + } else { + card.li.style.setProperty('overflow-clip-margin', `${reach}px`); + } + clearTimeout(flying.get(card.li)); + flying.set( + card.li, + window.setTimeout( + () => { + delete card.li.dataset.flying; + card.li.style.removeProperty('overflow-clip-margin'); + flying.delete(card.li); + followSoon(); + }, + (900 + MAX_DELAY) * s + ) + ); + } + + // Hears every flip, including the shell's sidebar. Nothing in here may + // read style or layout before every delay is written: a flush would start + // the transitions without their place in the cascade. + const stopHearing = onFlip((moves) => { + const s = mine ? scale : slomo(); + const ranks = new Map(); + const refits: Array<[HTMLElement, number, FlipRect]> = []; + // How far outside its box each card the shell glides must paint: as far + // as any of its parts sets out from where it lands. + const reaches = new Map(); + for (const move of moves) { + const li = move.el.closest('.xp-card'); + if (!li) { + continue; + } + if (!ranks.has(li)) { + ranks.set(li, ranks.size); + } + if (!mine && GLIDE_CLIP && cardOf.has(li)) { + const { first, last } = move; + reaches.set( + cardOf.get(li)!, + Math.max( + reaches.get(cardOf.get(li)!) ?? 0, + Math.abs(first.left - last.left), + Math.abs(first.top - last.top), + Math.abs(first.left + first.width - last.left - last.width), + Math.abs(first.top + first.height - last.top - last.height) + ) + ); + } + // A cascade for the explorer's own changes, card by card in reading + // order; anything already in flight keeps going without a pause. The + // card going into or out of the close-up leaves on three delays. + const card = cardOf.get(li); + const part = card && swapping.has(card) ? partIndex(card, move.el) : -1; + const delay = + !mine || move.moving + ? 0 + : part >= 0 + ? part * PART_STEP + : Math.min(ranks.get(li)! * STEP, MAX_DELAY); + if (mine) { + move.el.style.setProperty('--flip-delay', `${delay}ms`); + } + if ( + move.el.classList.contains('xp-text') && + Math.abs(move.first.width - move.last.width) > 2 + ) { + refits.push([move.el, delay, move.first]); + } + } + // (The strip's leaning cells reach 48px past their boxes already.) + reaches.forEach((reach, card) => fly(card, s, Math.ceil(reach) + 48)); + // Re-wrapped text can't be stretched into place: a copy of it as it was + // fades out where it stood, and the text fades in where it lands once + // the artwork has carried the card there (a list row's description + // with it). Into the strip it only fades out: it leaves there. + fadeOutText( + refits, + mine ? fromView : (list.dataset.view ?? 'grid'), + s, + mine ? stageAt : null + ); + for (const [el, delay] of open ? [] : refits) { + const detail = cardOf.get(el.closest('.xp-card')!)?.detail; + for (const part of detail ? [el, detail] : [el]) { + fadeIn(part, (delay + (mine ? ARRIVED_MS : CARRIED_MS)) * s, s); + } + } + }); + + // A shell layout change (the sidebar folding) carries only the cards that + // are actually in view (read in one pass, then marked), and the close-up's + // parts. Measured on home: the glide costs the same with no card motion at + // all; one box per card (a translate and a uniform scale) held 60fps but + // never 120 and scaled the type, so the parts travel on their own. They + // are marked once the glide has measured them (above), unless the + // browser can't widen a clip. + // Before the glide measures where they land (settle), the archive sizes + // itself from the column's new width (what the ResizeObserver would do a + // frame late), re-deals its blocks if the column count changed, and holds + // the reader's place: the first card in view (or the close-up's) stays + // where it was on screen, as the browser's scroll anchoring would if the + // window hadn't turned it off. Its boxes are measured in the viewport, so + // that scroll is part of the flight. + let carried: Array = []; + let held: { card: Card; y: number } | null = null; + const unregister = registerFlipTargets( + () => { + const top = fold(); + held = null; + carried = [...near].filter((card) => { + const box = card.li.getBoundingClientRect(); + const seen = card !== open && box.bottom > 0 && box.top < innerHeight; + if ( + seen && + box.top >= top - 1 && + (!held || + box.top < held.y - 1 || + (box.top < held.y + 1 && + order.indexOf(card) < order.indexOf(held.card))) + ) { + held = { card, y: box.top }; + } + return seen; + }); + if (open) { + held = { card: open, y: open.li.getBoundingClientRect().top }; + carried.push(open); + } + if (!GLIDE_CLIP) { + const s = slomo(); + carried.forEach((card) => fly(card, s)); + } + return carried.flatMap(parts); + }, + { + viewport: true, + settle: () => { + const columns = span; + size(); + const place = held; + held = null; + if (!place || place.card.li.hidden) { + return; + } + if (windowed && metrics() && span !== columns) { + const [first, last] = rowsAround(place.card, place.y); + partition(first, last, new Set([...carried, place.card])); + } + const shift = place.card.li.getBoundingClientRect().top - place.y; + if (Math.abs(shift) > 0.5) { + window.scrollBy({ top: shift, behavior: 'instant' }); + } + } + } + ); + + const wide = matchMedia('(min-width: 1024px)'); + + /** Where the close-up's top edge sits: under the stuck toolbar. */ + function ceiling() { + return parseFloat(getComputedStyle(bar).top) + bar.offsetHeight - cut; + } + + /** Where the dock and the phone's tab bar start covering the page. */ + function floor() { + const style = getComputedStyle(root); + // (On a phone the tab bar itself is measured: its height has the safe + // area in it, which its custom property can't give as a number.) + const tabs = across + ? (document.querySelector('.tabbar')?.offsetHeight ?? 0) + : parseFloat(style.getPropertyValue('--tabbar-h')) || 0; + return ( + innerHeight - + (parseFloat(style.getPropertyValue('--dock-h')) || 0) - + (wide.matches ? 0 : tabs) + ); + } + + /** + * On a phone (the strip one row under the close-up, which scrolls with + * the page: explorer.css): the page brings the close-up under the + * toolbar, and the strip brings `card`'s cell into view, in the middle + * when the close-up opens, the least distance when stepping. While the + * archive folds into the strip it isn't a scroller yet (nothing flying + * into it is clipped): it is laid out shifted along by as much + * (--xp-strip-x), and scrolls by that much once it lands. + */ + function placeAcross(card: Card, centre: boolean, smooth: boolean) { + const top = ceiling(); + const view = closeup.getBoundingClientRect(); + const shift = stage.getBoundingClientRect().top - top; + if ((centre || view.top < top - 1) && Math.abs(shift) > 0.5) { + // The folded archive is short: the page is given the room it needs + // below the strip for the close-up to come up under the toolbar. + const room = parseFloat(stage.style.getPropertyValue('--xp-room')) || 0; + const spare = + document.documentElement.scrollHeight - room - innerHeight - scrollY; + const need = Math.max(0, Math.ceil(shift - spare)); + if (need !== room) { + stage.style.setProperty('--xp-room', `${need}px`); + } + window.scrollBy({ top: shift, behavior: smooth ? 'smooth' : 'instant' }); + } + const shown = order.filter((other) => !other.li.hidden); + const at = shown.indexOf(card); + const landing = root.dataset.folding !== undefined; + const now = landing + ? parseFloat(list.style.getPropertyValue('--xp-strip-x')) || 0 + : list.scrollLeft; + // The strip's width in view (landing, its box reaches further back by + // the shift), the cells in full view at once, and how far it scrolls. + const width = list.clientWidth - (landing ? now : 0); + const fit = Math.max(1, Math.floor((width - 2 * inset + gap) / pitch)); + const most = Math.max(0, 2 * inset + shown.length * pitch - gap - width); + // Every place it stops at has a cell at its start (scroll snapping). + let x = now; + if (centre) { + x = (at - Math.floor((fit - 1) / 2)) * pitch; + } else if (at * pitch < now) { + x = at * pitch; + } else if ((at + 1) * pitch - gap > now + width - 2 * inset) { + x = (at - fit + 1) * pitch; + } + x = Math.min(Math.max(x, 0), most); + if (landing) { + list.style.setProperty('--xp-strip-x', `${x}px`); + } else if (Math.abs(x - now) > 0.5) { + list.scrollTo({ left: x, behavior: smooth ? 'smooth' : 'instant' }); + } + } + + /** + * In the close-up the page itself scrolls the filmstrip, so nothing in + * flight is ever clipped by a scroller, and the close-up sticks under the + * toolbar. Bring `card`'s cell into view: centred when the close-up opens, + * the least distance when stepping, and not at all when it is in view + * already (a cell clicked in the strip: nothing moves under the pointer). + */ + function placeStrip(card: Card, centre: boolean, smooth = false) { + if (metrics() && across) { + placeAcross(card, centre, smooth); + return; + } + const top = ceiling(); + const bottom = floor(); + const cell = card.li.getBoundingClientRect(); + let shift = 0; + if (centre) { + shift = cell.top + cell.height / 2 - (top + bottom) / 2; + } else if (cell.top < top + 8) { + shift = cell.top - top - 8; + } else if (cell.bottom > bottom - 8) { + shift = cell.bottom - bottom + 8; + } else { + return; + } + const box = stage.getBoundingClientRect(); + const view = closeup.getBoundingClientRect(); + // The stage reaches the toolbar, so the close-up sticks at once, and + // never scrolls past its end, so the close-up stays whole. + const least = box.top - top; + const most = Math.max(least, box.bottom - top - view.height); + shift = Math.min(Math.max(shift, least), most); + if (Math.abs(shift) > 0.5) { + window.scrollBy({ top: shift, behavior: smooth ? 'smooth' : 'instant' }); + } + } + + /** The toolbar is stuck under the top of the page. */ + const stuck = () => + bar.getBoundingClientRect().top <= + parseFloat(getComputedStyle(bar).top) + 0.5; + + /** + * Back in the archive, the closed card is in view, under the toolbar. + * The page never scrolls back above the archive's top: the toolbar stays + * stuck and nothing above the archive comes into view in one frame (only + * the cards are carried through the scroll). + */ + function placeHome(card: Card) { + stage.style.removeProperty('--xp-room'); + const top = ceiling(); + const bottom = floor(); + const box = card.li.getBoundingClientRect(); + if (box.top < top + 8 || box.bottom > bottom - 8) { + const least = stage.getBoundingClientRect().top - top; + const shift = Math.max( + box.top + box.height / 2 - (top + bottom) / 2, + Math.min(least, 0) + ); + if (Math.abs(shift) > 0.5) { + window.scrollBy({ top: shift, behavior: 'instant' }); + } + } + } + + /** + * Run a layout change and carry the cards on screen through it. + * `keep` is the card that should hold its place in the viewport. Left + * out, the first card on screen that stays does; `null` (a re-sort) keeps + * none. When there is nothing to hold and the visitor is down in the + * results, they start under the toolbar again. `place` replaces all of + * that (the close-up places the reader itself). + */ + function change( + mutate: () => void, + { + keep, + place, + anchor + }: { + keep?: Card | null; + place?: () => void; + /** The card the window must hold when `place` places the reader. */ + anchor?: Card | null; + } = {} + ) { + // On screen now: in the viewport (read in one pass over the cards the + // observer has near it), still in flight from the last change (its box + // may be far away while its parts are not), or in the close-up. Cards + // that come into view from further away rise in instead of flying. + const before = new Set(); + for (const card of near) { + const box = card.li.getBoundingClientRect(); + if (box.bottom > 0 && box.top < innerHeight) { + before.add(card); + } + } + for (const li of flying.keys()) { + before.add(cardOf.get(li)!); + } + if (open) { + before.add(open); + } + swapping.forEach((_, card) => before.add(card)); + scale = slomo(); + // Every read before the change comes first, in one pass; the first write + // (marking the cards as flying) waits until the flip has measured them. + const top = fold(); + // Where the reader is, unless the change places them itself. + const seen = (place ? [] : keep !== undefined ? [keep] : [...before]) + .filter((card): card is Card => Boolean(card && !card.li.hidden)) + .map((card) => ({ card, y: card.li.getBoundingClientRect().top })) + .filter(({ y }) => keep || (y >= top - 1 && y < innerHeight)) + .sort((a, b) => a.y - b.y); + const listTop = list.getBoundingClientRect().top; + const shownBefore = new Set(cards.filter((card) => !card.li.hidden)); + + // Cards on screen that are about to leave fade out where they stand. + const frame = stage.getBoundingClientRect(); + const leaving = [...before].filter((card) => !card.li.hidden); + const boxes = leaving.map((card) => card.li.getBoundingClientRect()); + + const targets = [...before].flatMap(parts); + + fromView = list.dataset.view ?? 'grid'; + mine = true; + let position: Map | undefined; + const rank = (el: HTMLElement) => + (position ??= new Map(order.map((card, n) => [card.li, n]))).get( + el.closest('.xp-card')! + )!; + flip( + targets, + () => { + // The browser's own scroll anchoring would pick its own card and + // adjust again a frame later; this change places the reader itself. + list.dataset.moving = ''; + before.forEach((card) => fly(card, scale)); + mutate(); + // Cards on screen that left the cut fade out where they stood: + // marked and pinned there the moment they leave, before anything + // reads style, which would take them out at once (display: none, + // no fade). A card whose new place is out of the window is pinned + // once the window has moved (below). + const pin = (card: Card, i: number) => { + const box = boxes[i]!; + card.li.style.setProperty('--xp-x', `${box.left - frame.left}px`); + card.li.style.setProperty('--xp-y', `${box.top - frame.top}px`); + card.li.style.setProperty('--xp-w', `${box.width}px`); + card.li.style.setProperty('--xp-h', `${box.height}px`); + }; + leaving.forEach((card, i) => { + card.li.toggleAttribute('data-exit', card.li.hidden); + if (card.li.hidden) { + pin(card, i); + } + }); + // The window moves with the reader: around the card that holds + // their place (where it is held), the close-up's, or the top of the + // results (just under the toolbar). + const held = + place || open ? undefined : seen.find(({ card }) => !card.li.hidden); + const atTop = !place && !open && !held && listTop < top; + if (windowed) { + reWindow( + place ? anchor : (open ?? held?.card ?? (atTop ? null : undefined)), + new Set(leaving), + held ? held.y : atTop ? top + 8 : undefined + ); + } + leaving.forEach((card, i) => { + if (!card.li.hidden && card.li.dataset.away !== undefined) { + pin(card, i); + } + }); + if (place) { + place(); + } else if (open) { + placeStrip(open, false); + } else if (held) { + // Hold the reader's place. + window.scrollBy({ + top: held.card.li.getBoundingClientRect().top - held.y, + behavior: 'instant' + }); + } else if (atTop) { + window.scrollBy({ + top: list.getBoundingClientRect().top - top - 8, + behavior: 'instant' + }); + } + // In the close-up, the strip's cells in view and the cards flying + // into it are in depth; closing, none are. + deepen(true, before); + // Where the stage is now, for the copies of re-wrapped text (read + // here, where the flip is about to lay the page out anyway). + stageAt = stage.getBoundingClientRect(); + }, + // The cascade runs in the order the cards are shown. + { order: (a, b) => rank(a) - rank(b) } + ); + mine = false; + if (windowed) { + settleAway(320 * scale); + } + // Let the browser's anchoring forget the old layout before it resumes. + requestAnimationFrame(() => + requestAnimationFrame(() => delete list.dataset.moving) + ); + + if (reducedMotion()) { + return; + } + // Cards that were shown but far away and now slide into view rise in. + // Found at the start of the next frame (still before it paints), where + // the layout this read needs is computed once, with the frame's own, + // rather than forced a second time inside the handler. Where cards on + // screen are leaving, they rise once those have cleared their text + // (explorer.css), so the two never read over each other. + const s = scale; + const clearing = leaving.some( + (card) => + card.li.dataset.exit !== undefined || card.li.dataset.away !== undefined + ) + ? LEAVE_MS + : 0; + requestAnimationFrame(() => + onScreen() + .filter((card) => !before.has(card) && shownBefore.has(card)) + .forEach((card, i) => { + // (Arriving, its picture fades in once loaded: explorer.css.) + card.li.dataset.join = ''; + window.setTimeout(() => delete card.li.dataset.join, 700 * s); + card.li.animate( + [ + { opacity: 0, translate: '0 32px' }, + { opacity: 1, translate: '0 0' } + ], + { + delay: (clearing + Math.min(i * STEP, MAX_DELAY)) * s, + duration: 520 * s, + easing: 'cubic-bezier(0.16, 1, 0.3, 1)', + fill: 'backwards' + } + ); + }) + ); + } + + /* ---------- State ---------- */ + + function render(next: ExplorerState) { + const shown = cards.filter((card) => matches(card.entry, next)); + const visible = new Set(shown); + // The close-up's card left the cut: the close-up closes with it. + if (open && !visible.has(open)) { + home(open, false); + open = null; + delete root.dataset.open; + } + // Cards that join the cut fade up into their cell (@starting-style keys + // on the mark); a card only moving between the grid and a parked block + // is not arriving. + const joined: Array = []; + for (const card of cards) { + const was = card.li.hidden; + card.li.hidden = !visible.has(card); + if (!card.li.hidden) { + card.li.removeAttribute('data-exit'); + if (was) { + card.li.dataset.join = ''; + joined.push(card.li); + } + } + } + if (joined.length) { + window.setTimeout( + () => joined.forEach((li) => delete li.dataset.join), + 700 * slomo() + ); + } + if (next.sort !== sorted) { + sorted = next.sort; + order = [...cards].sort((a, b) => compare(next.sort)(a.entry, b.entry)); + if (READING_FLOW) { + order.forEach((card, i) => (card.li.style.order = String(i))); + } else if (!windowed) { + // Elsewhere the DOM order is the reading order (windowed, the + // window keeps its own in step). + list.append(...order.map((card) => card.li)); + } + } + list.dataset.view = next.view; + + empty.hidden = shown.length > 0; + empty.querySelector('[data-xp-empty-what]')!.textContent = next.q + ? `“${next.q}”` + : 'those filters'; + shownCount.textContent = String(shown.length); + ofTotal.hidden = !isFiltered(next); + } + + /** Make the controls say what the state is (after a URL load or a back). */ + function syncControls(next: ExplorerState) { + if (search.value.trim() !== next.q) { + search.value = next.q; + } + for (const name of ['view', 'kind', 'sort', 'year', 'guest'] as const) { + const field = form.elements.namedItem(name) as RadioNodeList | null; + if (field) { + field.value = next[name]; + } + } + progressButton.setAttribute('aria-pressed', String(next.progress)); + for (const name of ['sort', 'year', 'guest'] as const) { + const label = form.querySelector(`[data-xp-label="${name}"]`); + const field = form.elements.namedItem(name) as RadioNodeList | null; + const option = [...(field ?? [])].find( + (input) => (input as HTMLInputElement).checked + ); + if (label) { + label.textContent = next[name] + ? (option?.parentElement?.querySelector('span:not([class])') + ?.textContent ?? next[name]) + : name === 'year' + ? 'Any' + : 'Anyone'; + if (name !== 'sort') { + label + .closest('.xp-pick')! + .toggleAttribute('data-on', Boolean(next[name])); + const unset = form.querySelector( + `[data-xp-unset="${name}"]` + ); + if (unset) { + unset.hidden = !next[name]; + } + } + // The With chip shows the chosen person's face. + if (name === 'guest') { + const face = form.querySelector('[data-xp-face]'); + const photo = + option?.parentElement?.querySelector( + '.person-face img' + ); + if (face) { + face.hidden = !next.guest || !photo; + if (photo) { + face.querySelector('img')!.src = photo.currentSrc || photo.src; + } + } + } + } + } + form.querySelector('[data-xp-reset]')!.hidden = + !isFiltered(next); + } + + let announce = 0; + function tell(next: ExplorerState) { + clearTimeout(announce); + announce = window.setTimeout(() => { + const count = cards.filter((card) => !card.li.hidden).length; + status.textContent = + count === 0 + ? 'No episodes match.' + : isFiltered(next) + ? `${count} of ${cards.length} episodes shown.` + : `All ${cards.length} episodes shown.`; + }, 500); + } + + let lastParam = ''; + function remember(next: ExplorerState, param: string) { + const url = location.pathname + toSearch(next); + if (url === location.pathname + location.search) { + return; + } + // Consecutive changes to one control (typing, arrowing through a menu) + // are one step in history; switching controls starts a new one. + if (param === lastParam) { + history.replaceState(history.state, '', url); + } else { + history.pushState(history.state, '', url); + } + lastParam = param; + } + + /** + * Where the visitor has got to in each episode (the media engine keeps + * saving it as they listen): progress bars, and the In progress chip. + */ + function readProgress(next = state) { + let started = 0; + for (const card of cards) { + card.entry.position = readPosition(card.li.dataset.id!); + if (inProgress(card.entry)) { + started++; + card.li.style.setProperty( + '--xp-progress', + String(Math.min(card.entry.position / card.entry.duration, 1)) + ); + } + } + progressButton.hidden = started === 0 && !next.progress; + progressButton.querySelector('[data-xp-progress-count]')!.textContent = + String(started); + } + + function commit(next: ExplorerState, param: string | null) { + if (toSearch(next) === toSearch(state)) { + return; + } + readProgress(next); + if (open) { + swap(open); + } + change(() => render(next), { + keep: next.sort === state.sort ? undefined : null + }); + state = next; + syncControls(next); + tell(next); + if (param) { + remember(next, param); + } + } + + /* ---------- The Close-Up ---------- */ + + // The open card's detail after its description: its cast, where to + // resume, and what to do. Only the open card shows them, so the page + // carries one copy of the rest, moved into the card that opens, and the + // cast is made from the With menu's people when a card first opens. + const extras = root + .querySelector('template[data-xp-actions]')! + .content.cloneNode(true) as DocumentFragment; + const resume = extras.querySelector('.xp-resume')!; + const actions = extras.querySelector('.xp-actions')!; + const queueButton = actions.querySelector('.xp-queue')!; + const openLink = actions.querySelector('.xp-open')!; + const closeLabel = actions.querySelector('.xp-close .sr-only')!; + const casts = new WeakMap(); + + /** + * What each person is on each episode, in a line (`personFact`): their + * tally, and which of their episodes this one is, counted oldest first. + */ + let facts: Map> | undefined; + function factsOf(card: Card) { + if (!facts) { + facts = new Map(); + const tally = new Map(); + cards.forEach((other) => + other.entry.people.forEach((id) => + tally.set(id, (tally.get(id) ?? 0) + 1) + ) + ); + const seen = new Map(); + for (const other of [...cards].sort( + (a, b) => b.entry.index - a.entry.index + )) { + const number = + other.facts.querySelector('.xp-number')!.dataset.number!; + const label = number === 'Bonus' ? 'a bonus episode' : `Ep ${number}`; + const hosts = new Set(idsOf(other.li, 'hosts')); + const lines = new Map(); + for (const id of other.entry.people) { + const so = seen.get(id) ?? { count: 0, first: label }; + so.count += 1; + seen.set(id, so); + const host = hosts.has(id); + lines.set( + id, + personFact({ + host, + count: tally.get(id) ?? so.count, + appearance: host ? undefined : so.count, + first: so.first + }) + ); + } + facts.set(other, lines); + } + } + return facts.get(card)!; + } + + /** The card's cast as the shared people chips, made once. */ + function castOf(card: Card) { + if (!casts.has(card)) { + const people = card.entry.people.filter((id) => everyone.has(id)); + let list: HTMLElement | null = null; + if (people.length) { + const lines = factsOf(card); + list = document.createElement('ul'); + list.className = 'xp-people'; + list.setAttribute('aria-label', 'Hosts and guests'); + for (const id of people) { + const { name, photo } = everyone.get(id)!; + const item = document.createElement('li'); + item.dataset.speaksAs = name; + item.innerHTML = + ''; + item.querySelector('a')!.href = `/?guest=${encodeURIComponent(id)}`; + item.querySelector('img')!.src = photo; + item.querySelector('.xp-person-name')!.textContent = name; + item.querySelector('.person-fact')!.textContent = lines.get(id) ?? ''; + list.append(item); + } + } + casts.set(card, list); + } + return casts.get(card)!; + } + + function fillResume(card: Card) { + const seconds = readPosition(card.li.dataset.id!); + resume.hidden = seconds < 30; + // (A phone's close-up leaves out the long part: explorer.css.) + const rest = document.createElement('span'); + rest.className = 'xp-long'; + rest.textContent = ', and play picks up there'; + resume.replaceChildren(`You stopped at ${clock(seconds)}`, rest, '.'); + closeup.toggleAttribute('data-resume', !resume.hidden); + } + + /** The Up next button says whether its episode is queued. */ + function syncQueue(card: Card, ids = new Set(queue.value.map((e) => e.id))) { + const queued = ids.has(card.li.dataset.id!); + queueButton.setAttribute('aria-pressed', String(queued)); + // (A phone's close-up shows "Up next" alone: explorer.css.) + queueButton.querySelector('.xp-long')!.textContent = queued + ? 'In ' + : 'Add to '; + } + + /** + * The back of the card, made the first time it opens: the picture again, + * its number and kind standing off it at different depths. + */ + function backOf(card: Card) { + if (card.turn.querySelector('.xp-back')) { + return; + } + const front = card.turn.querySelector('img')!; + const img = front.cloneNode() as HTMLImageElement; + img.loading = 'eager'; + img.sizes = '(min-width: 1024px) 560px, 40vw'; + const layer = (name: string, text = '') => { + const span = document.createElement('span'); + span.className = name; + span.textContent = text; + return span; + }; + const face = layer('xp-face xp-back'); + face.setAttribute('aria-hidden', 'true'); + const length = card.facts.querySelector('.xp-facts-length')?.textContent; + const light = card.turn + .querySelector('.xp-progress')! + .cloneNode() as HTMLElement; + delete light.dataset.propsFor; + face.append( + img, + light, + layer('xp-plate-shade'), + layer( + 'xp-plate-no', + card.facts.querySelector('.xp-number')!.dataset.number! + ), + layer( + 'xp-plate-tag', + `${card.entry.video ? 'Video' : 'Audio'} · ${length ?? ''}` + ) + ); + card.turn.append(face); + if (currentEpisode.value?.id === card.li.dataset.id) { + light.dataset.propsFor = 'media-clock'; + clocked.push(light); + } + } + + /** + * Re-home one card's parts: into the close-up's slots, or back to its + * cell. The slots are CSS anchors; this only flips the attribute. + */ + function home(card: Card, on: boolean) { + card.li.toggleAttribute('data-on', on); + card.art.setAttribute('aria-expanded', String(on)); + if (on) { + // The close-up takes its light from the artwork (prop-for-that). + card.li.dataset.propsTo = '.xp-stage'; + card.li.dataset.propsFor = 'img-color'; + card.title.style.setProperty('--xp-w', width); + const cast = castOf(card); + card.detail.append(...(cast ? [cast] : []), resume, actions); + openLink.href = card.title.querySelector('a')!.href; + closeLabel.textContent = `Close episode ${ + card.facts.querySelector('.xp-number')!.dataset.number + }`; + fillResume(card); + syncQueue(card); + // The text slots hold invisible copies, so they are exactly as big + // as what lands in them. + ghostFacts.replaceChildren( + ...[...card.facts.childNodes].map((node) => node.cloneNode(true)) + ); + ghostTitle.textContent = card.title.textContent?.trim() ?? ''; + } else { + card.title.style.removeProperty('--xp-w'); + delete card.li.dataset.propsFor; + delete card.li.dataset.propsTo; + } + } + + /** + * The close-up's detail column belongs to the open card and goes with it + * the moment it closes; a copy of it, as it stands, fades out where it + * was (inert, unseen by assistive technology, gone once faded). + */ + function fadeOutDetail(card: Card) { + const box = card.detail.getBoundingClientRect(); + if (reducedMotion() || !box.width || !box.height) { + return; + } + const s = slomo(); + const copy = card.detail.cloneNode(true) as HTMLElement; + for (const el of [copy, ...copy.querySelectorAll('*')]) { + el.removeAttribute('id'); + delete el.dataset.propsFor; + } + // Styled as the open card's detail (explorer.css), so it looks as it + // did; fixed where it stood in the viewport (outside the explorer, whose + // containment would carry it with the page as the close scrolls). + const shell = document.createElement('div'); + shell.className = 'xp-fading-detail'; + shell.style.setProperty( + '--xp-phone', + getComputedStyle(stage).getPropertyValue('--xp-phone') + ); + shell.inert = true; + shell.setAttribute('aria-hidden', 'true'); + copy.style.cssText = `position: fixed; inset: auto; top: ${box.top}px; left: ${box.left}px; width: ${box.width}px; height: ${box.height}px; margin: 0;`; + shell.append(copy); + document.body.append(shell); + copy.scrollTop = card.detail.scrollTop; + copy.animate([{ opacity: 1 }, { opacity: 0 }], { + duration: 220 * s, + easing: 'ease-out', + fill: 'forwards' + }).onfinish = () => shell.remove(); + } + + /** Mark a card as on its way into or out of the close-up until it lands. */ + function swap(card: Card) { + clearTimeout(swapping.get(card)); + card.li.dataset.swap = ''; + swapping.set( + card, + window.setTimeout(() => { + swapping.delete(card); + delete card.li.dataset.swap; + }, SWAP_MS * slomo()) + ); + } + + // While the archive folds into the strip (or back), the cards' text and + // play discs fade on their way; once it lands they leave the page. + let folded = 0; + function folding(on: boolean) { + if (!on) { + return; + } + clearTimeout(folded); + root.dataset.folding = ''; + folded = window.setTimeout(() => { + folded = 0; + // A phone's strip, landed, scrolls from where it was laid out. + const x = parseFloat(list.style.getPropertyValue('--xp-strip-x')) || 0; + list.style.removeProperty('--xp-strip-x'); + delete root.dataset.folding; + if (open && x) { + list.scrollLeft = x; + } + deepen(true); + }, SWAP_MS * slomo()); + } + + /** + * Show a card in the close-up, swap it for another (mid-flight too: the + * old parts turn for home as the new ones leave), or close it (`null`). + * `still`: a cell pressed in the strip, which stays where it is. + */ + function show(next: Card | null, still = false) { + if (next === open) { + return; + } + const prev = open; + // Opening from above the archive (the toolbar not yet stuck), the page + // scrolls up to it smoothly as the card flies, rather than at once: the + // card and the archive set out at once, and nothing above the archive + // is thrown out of view in one frame. (Stuck, only the toolbar's empty + // margin lies between it and the archive, and the cards are carried + // through the scroll: it happens at once.) + const glide = Boolean(next && !prev && !reducedMotion() && !stuck()); + // The detail column it leaves fades where it stood. + if (prev) { + fadeOutDetail(prev); + } + // Folding back, the strip's cells straighten up seen from where they + // were: the point each is seen from follows its place in the strip as + // it scrolls (a view() timeline), and leaves with the open state, so it + // is held where it stood, as a share of the cell (it moves with the + // cell's new size), until the cell has landed and gives up its depth. + if (prev && !next) { + const held = [...deep].map((card) => { + const tilt = card.turn.parentElement!; + const [x, y] = getComputedStyle(tilt) + .perspectiveOrigin.split(' ') + .map(parseFloat); + return [tilt, x! / tilt.offsetWidth, y! / tilt.offsetHeight] as const; + }); + for (const [tilt, x, y] of held) { + if (Number.isFinite(x) && Number.isFinite(y)) { + tilt.style.perspectiveOrigin = `${x * 100}% ${y * 100}%`; + } + } + } else if (next && !prev) { + deep.forEach((card) => + card.turn.parentElement!.style.removeProperty('perspective-origin') + ); + } + if (prev) { + swap(prev); + } + if (next) { + swap(next); + backOf(next); + } + for (const card of [prev, next]) { + card?.art.style.setProperty('--flip-delay', '0ms'); + card?.facts.style.setProperty('--flip-delay', `${PART_STEP}ms`); + card?.title.style.setProperty('--flip-delay', `${2 * PART_STEP}ms`); + } + change( + () => { + // Opening and closing fold the archive; stepping does not. (Marked + // in the change: before it, the strip's text and play discs would + // be laid out to be measured, 96px wide, and fly home stretched.) + folding(!prev || !next); + if (prev) { + home(prev, false); + } + if (next) { + home(next, true); + } + open = next; + root.toggleAttribute('data-open', Boolean(next)); + }, + { + place: () => { + if (next && !(prev && still)) { + placeStrip(next, !prev, glide); + } else if (!next && prev) { + placeHome(prev); + } + }, + anchor: next ?? prev + } + ); + // Back in a list row, its description fades in as the title lands. + if (prev && list.dataset.view === 'list' && !reducedMotion()) { + fadeIn(prev.detail, SWAP_ARRIVED_MS * slomo(), slomo()); + } + if (next) { + status.textContent = `Episode ${ + next.facts.querySelector('.xp-number')?.dataset.number ?? + '' + }: ${next.title.textContent?.trim()}. Arrow keys for the next and previous.`; + } + } + + // The media clock (`--live-progress`, `--live-paused`) is written only + // where an element opts in. Only the playing episode's progress lights and + // the hero's on-air levels opt in, and only while it is the current one, so + // a tick restyles a handful of elements and never the archive. + const byId = new Map(cards.map((card) => [card.li.dataset.id, card])); + const hero = document.querySelector('.xp-hero'); + let clocked: Array = []; + const stopClock = effect(() => { + const id = currentEpisode.value?.id; + clocked.forEach((el) => delete el.dataset.propsFor); + clocked = []; + if (!id) { + return; + } + const card = byId.get(id); + if (card) { + clocked.push(...card.li.querySelectorAll('.xp-progress')); + } + if (hero?.dataset.id === id) { + clocked.push( + ...hero.querySelectorAll('.xp-hero-progress, .xp-onair') + ); + } + clocked.forEach((el) => (el.dataset.propsFor = 'media-clock')); + }); + + // The card whose episode is loaded gets the live play control (pause, the + // on-air levels, buffering; it marks its card current and playing). Every + // other card's disc is plain markup until it is pressed. + let live: Card | null = null; + const resting = new Map(); + const stopLive = effect(() => { + const id = currentEpisode.value?.id; + const card = (id && byId.get(id)) || null; + if (card === live) { + return; + } + untracked(() => { + if (live) { + mount(null, live.play); + live.play.append(resting.get(live)!); + live.li.removeAttribute('data-current'); + live.li.removeAttribute('data-playing'); + } + live = card; + if (card) { + const disc = card.play.querySelector('[data-static]'); + const focused = Boolean(disc) && disc === document.activeElement; + if (disc) { + resting.set(card, disc); + disc.remove(); + } + mount( + h(FullPlayButton, { episode: playableOf(card.li), look: 'row' }), + card.play + ); + if (focused) { + card.play.querySelector('button')?.focus({ preventScroll: true }); + } + } + }); + }); + + const stopQueue = effect(() => { + const ids = new Set(queue.value.map((episode) => episode.id)); + if (open) { + syncQueue(open, ids); + } + }); + + // The close-up sticks just under the toolbar, whatever its height; and + // every card's exact size follows from the stage's width (explorer.css). + // (The heading is as wide as the stage, and its size never depends on + // the cards'.) + const heading = root.querySelector('.xp-heading')!; + function size() { + // Every read before any write, and only what changed is written (coming + // home, the archive arrived sized already). Stuck on a phone on its side, + // the toolbar shows only its first row (explorer.css): what sits under + // it sits under that. + cut = + parseFloat(getComputedStyle(bar).getPropertyValue('--xp-bar-cut')) || 0; + const barHeight = `${bar.offsetHeight - cut}px`; + const was = width; + width = `${heading.clientWidth}px`; + const set = (el: HTMLElement | undefined, name: string, value: string) => { + if (el && el.style.getPropertyValue(name) !== value) { + el.style.setProperty(name, value); + } + }; + set(root, '--xp-bar-h', barHeight); + // The stage's width doesn't inherit (explorer.css): it goes where + // something sizes from it, so a width change restyles those alone. + for (const el of [stage, list, ghostTitle, open?.title]) { + set(el, '--xp-w', width); + } + if (stage.dataset.sized === undefined) { + stage.dataset.sized = ''; + } + lastSize = { key: sizeKey(), width, bar: barHeight }; + return width !== was; + } + const sizes = new ResizeObserver(() => { + const place = seenRow; + const columns = span; + const resized = size(); + // In the close-up the strip's cells change size; depth follows them on + // the next frame (and is trimmed once the page next settles). + if (open) { + scrolled = true; + followSoon(); + } + if (!windowed) { + startWindow(); + return; + } + // A new column count re-deals the parked blocks' rows at once. Rows + // that only grow or shrink keep every card in its place, so while the + // sidebar's edge is dragged the window just follows, as on a scroll. + const recount = metrics() && span !== columns; + // A width the archive wasn't sized for already (a window resize, the + // rail snapping where it doesn't glide; the glide sizes it in its + // settle) holds the reader's place: the first card in view goes back + // to where it was on screen, as the browser's scroll anchoring would. + const card = + resized && !open && place?.span === columns + ? order.filter((other) => !other.li.hidden)[place.row * columns] + : undefined; + if (!card || !place) { + if (recount) { + follow(true); + } else { + followSoon(); + } + return; + } + if (recount) { + const [first, last] = rowsAround(card, place.y); + partition(first, last, kept().add(card)); + } else { + followSoon(); + } + // Row tops on both sides (a card's box stands out of its row). + const row = Math.floor((place.row * columns) / span); + const shift = + list.getBoundingClientRect().top + inset + row * pitch - place.y; + if (Math.abs(shift) > 0.5) { + window.scrollBy({ top: shift, behavior: 'instant' }); + } + }); + sizes.observe(bar); + sizes.observe(heading); + + /* ---------- Controls ---------- */ + + form.addEventListener( + 'input', + (event) => { + if (event.target === search) { + commit({ ...state, q: search.value.trim() }, 'q'); + } + }, + { signal } + ); + + form.addEventListener( + 'change', + (event) => { + const input = event.target as HTMLInputElement; + if (input.type !== 'radio') { + return; + } + commit({ ...state, [input.name]: input.value }, input.name); + }, + { signal } + ); + + // Picking an option with a click or Space settles the menu; a set + // filter's × clears it. + form.addEventListener( + 'click', + (event) => { + const target = event.target as Element; + const input = target.closest('.xp-menu input'); + input?.closest('[popover]')?.hidePopover(); + const unset = target.closest('[data-xp-unset]'); + if (unset) { + const name = unset.dataset.xpUnset as 'year' | 'guest'; + commit({ ...state, [name]: '' }, name); + unset + .closest('.xp-filter') + ?.querySelector('.xp-pick') + ?.focus(); + } + }, + { signal } + ); + + form.addEventListener( + 'submit', + (event) => { + event.preventDefault(); + form.querySelector('.xp-menu:popover-open')?.hidePopover(); + search.blur(); + }, + { signal } + ); + + const clear = () => + commit({ ...DEFAULT_STATE, sort: state.sort, view: state.view }, 'reset'); + + form.addEventListener( + 'reset', + (event) => { + event.preventDefault(); + clear(); + }, + { signal } + ); + root + .querySelector('[data-xp-clear]')! + .addEventListener('click', clear, { signal }); + + // Opening a menu puts you on its current choice, and points its caret at + // its chip, however far the menu was moved to fit (explorer.css). + for (const menu of form.querySelectorAll('.xp-menu')) { + const chip = form.querySelector( + `[popovertarget="${menu.id}"]` + ); + menu.addEventListener( + 'toggle', + (event) => { + if ((event as ToggleEvent).newState !== 'open') { + return; + } + menu.querySelector('input:checked')?.focus(); + if (chip) { + const at = chip.getBoundingClientRect(); + const box = menu.getBoundingClientRect(); + const x = at.left + at.width / 2 - box.left; + menu.style.setProperty( + '--xp-caret', + `${Math.min(Math.max(x, 24), box.width - 24)}px` + ); + } + }, + { signal } + ); + } + + progressButton.addEventListener( + 'click', + () => commit({ ...state, progress: !state.progress }, 'progress'), + { signal } + ); + + root.querySelector('[data-xp-top]')!.addEventListener( + 'click', + (event) => { + window.scrollTo({ + top: 0, + behavior: reducedMotion() ? 'auto' : 'smooth' + }); + // From the keyboard, carry on from the search field. + if ((event as MouseEvent).detail === 0) { + search.focus({ preventScroll: true }); + } + }, + { signal } + ); + + // While the page scrolls the window follows; once it settles, the + // strip's depth is trimmed to the cells in view. + // (So does a phone's strip, which scrolls sideways on its own.) + let settle = 0; + const onScroll = () => { + scrolled = true; + followSoon(); + clearTimeout(settle); + settle = window.setTimeout(() => { + settle = 0; + deepen(true); + }, 150); + }; + addEventListener('scroll', onScroll, { passive: true, signal }); + list.addEventListener('scroll', onScroll, { passive: true, signal }); + signal.addEventListener('abort', () => clearTimeout(settle)); + + // A card's controls carry a scroll margin that clears the sticky toolbar + // and the dock (explorer.css). Chromium honours it when focus scrolls a + // control into view; Firefox doesn't scroll a control that is only partly + // hidden, so it can sit under the toolbar. Bringing it in here honours the + // margin everywhere, and where the browser already did nothing moves. + // Only keyboard focus: a press focuses its button too, and scrolling then + // would move the button out from under the pointer before the click. + list.addEventListener( + 'focusin', + (event) => { + const target = event.target as HTMLElement; + if (target.matches('.xp-card :is(a, button):focus-visible')) { + target.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + } + }, + { signal } + ); + + list.addEventListener( + 'click', + (event) => { + const target = event.target as Element; + const card = cardOf.get(target.closest('.xp-card')!); + if (!card) { + return; + } + if (target.closest('.xp-close')) { + show(null); + card.art.focus({ preventScroll: true }); + } else if (target.closest('.xp-play [data-static]')) { + // A resting disc: play its episode (the card then gets the live one). + playEpisode(playableOf(card.li)); + } else if (target.closest('.xp-queue')) { + const episode = playableOf(card.li); + if (queue.value.some((queued) => queued.id === episode.id)) { + dequeue(episode.id); + status.textContent = 'Removed from Up next.'; + } else { + enqueue(episode); + status.textContent = 'Added to Up next.'; + } + } else if (target.closest('.xp-art')) { + show(open === card ? null : card, (event as MouseEvent).detail > 0); + } else if (!target.closest('a, button, .xp-detail') && open !== card) { + // The rest of a card (a filmstrip cell) opens it too. + show(card, (event as MouseEvent).detail > 0); + } + }, + { signal } + ); + + // In the close-up: Escape closes and the arrow keys step through the + // results as they are shown, filtered and sorted, from anywhere in the + // archive or the page itself (a click leaves focus on the page). A key + // another widget took is not ours: one it handled (listened for on the + // window, so the page's own document listeners go first), one pressed in + // another part of the page (the sidebar's divider, the player), one typed + // in a field, or one a menu, sheet or dialog is open to take. + addEventListener( + 'keydown', + (event) => { + const target = event.target as Element; + if ( + !open || + event.defaultPrevented || + event.altKey || + event.ctrlKey || + event.metaKey || + (target !== document.body && + target !== document.documentElement && + !root.contains(target)) || + target.closest?.('input, textarea, select, [contenteditable]') || + document.querySelector( + "[popover]:not([popover='manual']):popover-open, dialog[open]" + ) + ) { + return; + } + const card = open; + if (event.key === 'Escape') { + show(null); + card.art.focus({ preventScroll: true }); + return; + } + const step = ( + { + ArrowRight: 1, + ArrowDown: 1, + ArrowLeft: -1, + ArrowUp: -1 + } as Record + )[event.key]; + if (!step || target.closest?.('[data-xp-bar]')) { + return; + } + event.preventDefault(); + const shown = order.filter((other) => !other.li.hidden); + const next = + shown[(shown.indexOf(card) + step + shown.length) % shown.length]!; + const followFocus = card.li.contains(document.activeElement); + show(next); + if (followFocus) { + next.art.focus({ preventScroll: true }); + } + }, + { signal } + ); + + // Find in page opens a parked block where the match is and scrolls to it; + // the window then moves there (and closes the block again). + for (const block of [above, below]) { + block.addEventListener( + 'beforematch', + () => requestAnimationFrame(() => follow(true)), + { signal } + ); + } + + // Back and forward between explorer states stay on the page; the router + // only takes over when the page itself changes. + const path = location.pathname; + addEventListener( + 'popstate', + (event) => { + if (location.pathname !== path) { + return; + } + event.stopImmediatePropagation(); + lastParam = ''; + const next = known(parseState(location.search)); + commit(next, null); + syncControls(next); + }, + { capture: true, signal } + ); + + // Arriving with a query: show that cut at once, without motion. A filter + // the menus don't offer leaves the address as well. + if (toSearch(parseState(location.search)) !== toSearch(state)) { + history.replaceState( + history.state, + '', + location.pathname + toSearch(state) + location.hash + ); + } + readProgress(); + syncControls(state); + if (toSearch(state)) { + render(state); + } + delete document.documentElement.dataset.xpPending; + + // Back from an episode (EpisodeList starts the explorer as the page is + // swapped in, before the morph home is captured): the router restored the + // scroll the page had when it left, which in the close-up was the strip's. + // The card for the episode just left (named for the morph) goes back in + // view, under the toolbar, at its exact place. + const back = list.querySelector('.xp-card[data-vt-named]'); + if (back && !back.hidden && cardOf.has(back)) { + size(); + placeHome(cardOf.get(back)!); + } + + document.addEventListener( + 'astro:before-swap', + () => { + lifetime.abort(); + watcher.disconnect(); + sizes.disconnect(); + stopHearing(); + stopQueue(); + stopClock(); + stopLive(); + clocked.forEach((el) => delete el.dataset.propsFor); + unregister(); + swapping.forEach((timer) => clearTimeout(timer)); + clearTimeout(folded); + clearTimeout(settling); + cancelAnimationFrame(following); + starting?.(); + }, + { once: true, signal } + ); +} diff --git a/packages/starpod/src/components/explorer/icons.tsx b/packages/starpod/src/components/explorer/icons.tsx new file mode 100644 index 00000000..ddc682ce --- /dev/null +++ b/packages/starpod/src/components/explorer/icons.tsx @@ -0,0 +1,36 @@ +/** The explorer's own icons, drawn on the shared 24px grid (see ../icons). */ +import { Svg, type IconProps } from '../icons'; + +export const GridIcon = (p: IconProps) => ( + + + + + + +); + +export const ChevronIcon = (p: IconProps) => ( + + + +); + +export const SortIcon = (p: IconProps) => ( + + + +); + +export const ResumeIcon = (p: IconProps) => ( + + + + +); + +export const UpIcon = (p: IconProps) => ( + + + +); diff --git a/packages/starpod/src/components/explorer/query.ts b/packages/starpod/src/components/explorer/query.ts new file mode 100644 index 00000000..5151eae9 --- /dev/null +++ b/packages/starpod/src/components/explorer/query.ts @@ -0,0 +1,139 @@ +/** + * The explorer's state, and the URL query it lives in. Pure functions, shared + * by the browser controller and the tests. + * + * The query is a contract other pages link into: + * `?q=&kind=video|audio&guest=&year=&sort=newest|oldest|longest|shortest&view=grid|list`, + * plus `progress=1` for episodes the visitor has started. Defaults are left + * out of the URL. + */ + +export const SORTS = ['newest', 'oldest', 'longest', 'shortest'] as const; +export type Sort = (typeof SORTS)[number]; + +export interface ExplorerState { + q: string; + kind: '' | 'video' | 'audio'; + guest: string; + year: string; + progress: boolean; + sort: Sort; + view: 'grid' | 'list'; +} + +export const DEFAULT_STATE: ExplorerState = { + q: '', + kind: '', + guest: '', + year: '', + progress: false, + sort: 'newest', + view: 'grid' +}; + +export function parseState(search: string): ExplorerState { + const params = new URLSearchParams(search); + const kind = params.get('kind'); + const sort = params.get('sort') as Sort | null; + const year = params.get('year') ?? ''; + return { + q: params.get('q')?.trim() ?? '', + kind: kind === 'video' || kind === 'audio' ? kind : '', + guest: params.get('guest') ?? '', + year: /^\d{4}$/.test(year) ? year : '', + progress: params.get('progress') === '1', + sort: sort && SORTS.includes(sort) ? sort : 'newest', + view: params.get('view') === 'list' ? 'list' : 'grid' + }; +} + +/** The query string for a state, `''` when everything is at its default. */ +export function toSearch(state: ExplorerState): string { + const params = new URLSearchParams(); + if (state.q) { + params.set('q', state.q); + } + if (state.kind) { + params.set('kind', state.kind); + } + if (state.guest) { + params.set('guest', state.guest); + } + if (state.year) { + params.set('year', state.year); + } + if (state.progress) { + params.set('progress', '1'); + } + if (state.sort !== 'newest') { + params.set('sort', state.sort); + } + if (state.view !== 'grid') { + params.set('view', state.view); + } + const query = params.toString(); + return query ? `?${query}` : ''; +} + +/** Is anything narrowing the archive? (Sort and view only rearrange it.) */ +export function isFiltered(state: ExplorerState): boolean { + return Boolean( + state.q || state.kind || state.guest || state.year || state.progress + ); +} + +/** What the explorer knows about one episode card. */ +export interface ExplorerEntry { + /** Feed order: 0 is the newest. */ + index: number; + duration: number; + people: Array; + /** Seconds the visitor has listened, from the media engine's resume store. */ + position: number; + /** Lowercased title, description and people, for search. */ + text: string; + video: boolean; + year: string; +} + +export function matches(entry: ExplorerEntry, state: ExplorerState): boolean { + if (state.kind && entry.video !== (state.kind === 'video')) { + return false; + } + if (state.year && entry.year !== state.year) { + return false; + } + if (state.guest && !entry.people.includes(state.guest)) { + return false; + } + if (state.progress && !inProgress(entry)) { + return false; + } + if (state.q) { + const words = state.q.toLowerCase().split(/\s+/); + return words.every((word) => entry.text.includes(word)); + } + return true; +} + +/** The engine resumes from 30 seconds in; anything less is a sample. */ +export const RESUME_MIN_SECONDS = 30; + +export function inProgress(entry: ExplorerEntry): boolean { + return entry.position >= RESUME_MIN_SECONDS; +} + +export function compare(sort: Sort) { + return (a: ExplorerEntry, b: ExplorerEntry): number => { + switch (sort) { + case 'oldest': + return b.index - a.index; + case 'longest': + return b.duration - a.duration || a.index - b.index; + case 'shortest': + return a.duration - b.duration || a.index - b.index; + default: + return a.index - b.index; + } + }; +} diff --git a/packages/starpod/src/pages/index.astro b/packages/starpod/src/pages/index.astro index 57577192..a51c557c 100644 --- a/packages/starpod/src/pages/index.astro +++ b/packages/starpod/src/pages/index.astro @@ -1,18 +1,23 @@ --- import Layout from '../layouts/Layout.astro'; import EpisodeList from 'virtual:starpod/components/EpisodeList'; +import { loadArchive } from '../components/explorer/archive'; +import Hero from '../components/explorer/Hero.astro'; import { getAllEpisodes, getShowInfo } from '../lib/rss'; + const episodes = await getAllEpisodes(); const show = await getShowInfo(); -const title = `${show.title}`; +const { cards, people, years } = await loadArchive(episodes, show); --- - -
    -

    - Episodes -

    - - -
    + +

    {show.title}

    + {cards[0] && } +
    diff --git a/packages/starpod/src/styles/explorer.css b/packages/starpod/src/styles/explorer.css new file mode 100644 index 00000000..e6e33922 --- /dev/null +++ b/packages/starpod/src/styles/explorer.css @@ -0,0 +1,3396 @@ +/* The home explorer: toolbar, filters, sorting, grid and list views, expanding cards. */ + +/* The stage's width, in pixels (the script measures it). Not inherited: it + is written only where something sizes from it. */ +@property --xp-w { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +/* One column's width, from it: the grid alone sizes its rows from it, and + inherited it would restyle every rendered card at each width change. */ +@property --xp-cell { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +:root { + /* The sticky toolbar sits under the top bar below desktop. */ + --xp-stick: calc(var(--topbar-h) + env(safe-area-inset-top)); + --xp-glass: oklch(15% 0.02 280 / 0.78); + --xp-on-glass: oklch(97% 0.005 280); +} + +@media (min-width: 1024px) { + :root { + --xp-stick: 0px; + } +} + +@media (prefers-color-scheme: dark) { + :root { + --xp-glow: 60%; + } +} + +/* ---------- The latest episode ---------- */ + +.xp-hero { + /* The pointer over the picture (prop-for-that pointer-local, hoisted + here), centred, and nothing at all while it is elsewhere. */ + --px: calc( + (var(--live-local-pointer-x-ratio, 0.5) - 0.5) * + var(--live-local-pointer-inside, 0) + ); + --py: calc( + (var(--live-local-pointer-y-ratio, 0.5) - 0.5) * + var(--live-local-pointer-inside, 0) + ); + display: grid; + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + 'media' + 'meta'; + gap: 20px clamp(24px, 4vw, 56px); + align-items: center; + margin-bottom: clamp(40px, 6vw, 72px); + isolation: isolate; +} + +@media (min-width: 900px) { + .xp-hero { + grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); + grid-template-areas: 'media meta'; + } +} + +.xp-hero-meta { + grid-area: meta; +} + +/* A phone on its side: the picture beside its words, as on a wide screen, + and no taller than the screen leaves it under the top bar and the tab + bar, so its play disc and Play are on the first screen. */ +@media (orientation: landscape) and (max-height: 500px) { + .xp-hero { + --xp-hero-max: calc( + (100dvh - var(--topbar-h) - var(--tabbar-h) - 2 * var(--gutter)) * 16 / 9 + ); + grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); + grid-template-areas: 'media meta'; + align-items: start; + margin-bottom: 32px; + } + + .xp-hero-media, + .xp-hero-glow { + max-width: var(--xp-hero-max); + } + + .xp-hero .xp-hero-title { + font-size: clamp(1.4rem, 9dvh, 2.2rem); + } + + .xp-hero .xp-hero-desc { + -webkit-line-clamp: 2; + } + + .xp-hero .xp-hero-people { + display: none; + } +} + +/* Light from the artwork itself (prop-for-that img-color), cast away from + the pointer as if the cursor were the sun. Only a translate moves. */ +.xp-hero-glow { + grid-area: media; + z-index: -1; + aspect-ratio: 16 / 9; + scale: 1.15; + background: radial-gradient( + closest-side, + color-mix( + in oklch, + var(--live-img-accent, transparent) var(--xp-glow, 45%), + transparent + ), + transparent + ); + translate: calc(var(--px) * -56px) calc(var(--py) * -40px + 16px); + transition: translate 700ms var(--ease-out); + pointer-events: none; +} + +.xp-hero-media { + grid-area: media; + position: relative; + aspect-ratio: 16 / 9; + border-radius: var(--r-card); + overflow: hidden; + background: var(--media-ground); + box-shadow: var(--shadow-soft); + isolation: isolate; + transform-origin: 50% 0; +} + +.xp-hero-ambient { + position: absolute; + inset: -12%; + background: var(--art) center / cover; + filter: blur(48px) saturate(1.35) brightness(0.55); + transform: scale(1.1); +} + +.xp-hero-art { + position: absolute; + top: 50%; + left: 50%; + height: 78%; + width: auto; + aspect-ratio: 1; + object-fit: cover; + border-radius: var(--r-tile); + /* The hairline: light and dark art meet the page with the same edge. */ + outline: 1px solid var(--hairline); + outline-offset: -1px; + box-shadow: var(--shadow-float); + /* The artwork leans toward the pointer, a little: depth, not a tilt. */ + translate: calc(-50% + var(--px) * 18px) calc(-50% + var(--py) * 12px); + transition: + scale 700ms var(--ease-out), + translate 500ms var(--ease-out); +} + +/* The house ring, lit on the rim nearest the pointer. */ +.xp-hero-media::after { + content: ''; + position: absolute; + inset: 0; + z-index: 4; + padding: 1.5px; + border-radius: inherit; + background: conic-gradient( + from + calc( + atan2( + var(--live-local-pointer-y-ratio, 0.5) - 0.5, + var(--live-local-pointer-x-ratio, 0.5) - 0.5 + ) + + 90deg + ), + var(--glow-b), + oklch(from var(--glow-a) l c h / 0.1) 80deg, + oklch(from var(--glow-a) l c h / 0.1) 280deg, + var(--glow-b) + ); + mask: + linear-gradient(oklch(0% 0 0) 0 0) content-box, + linear-gradient(oklch(0% 0 0) 0 0); + mask-composite: exclude; + opacity: var(--live-local-pointer-inside, 0); + transition: opacity 300ms var(--ease-out); + pointer-events: none; +} + +/* The playing episode follows the media from CSS (prop-for-that media on + ): progress along the picture, levels that stop when it pauses. */ +.xp-hero-progress { + position: absolute; + inset: auto 0 0; + z-index: 3; + height: 3px; + background: linear-gradient(90deg, var(--glow-b), var(--glow-a)); + transform-origin: 0 50%; + scale: 0 1; + /* The media clock ticks four times a second; glide between ticks. */ + transition: scale 250ms linear; +} + +.xp-hero[data-current] .xp-hero-progress { + scale: var(--live-progress, 0) 1; +} + +.xp-onair { + display: none; + align-items: flex-end; + gap: 2px; + height: 0.7rem; + margin-right: 0.4rem; + vertical-align: -1px; +} + +.xp-hero[data-current] .xp-onair { + display: inline-flex; + /* Off screen the levels are skipped, so they stop costing frames. */ + content-visibility: auto; + contain-intrinsic-size: 12.5px 0.7rem; +} + +/* Each bar takes its own tempo and phase from its place in the row. */ +.xp-onair > span { + width: 2.5px; + height: 100%; + border-radius: 1px; + background: currentColor; + transform-origin: 50% 100%; + animation: xp-onair 760ms ease-in-out infinite alternate; + animation-duration: calc(760ms - (sibling-index() - 1) * 110ms); + animation-delay: calc((sibling-index() - 1) * -215ms); +} + +@container style(--live-paused: 1) { + .xp-onair > span { + animation-play-state: paused; + } +} + +/* Scrolled out of sight they rest too: a view timeline marks the levels as + seen only while they are in the viewport (as the rail's do, shell.css). */ +@supports (animation-timeline: view()) { + .xp-hero[data-current] .xp-onair { + animation: onair-seen linear none; + animation-timeline: view(); + animation-range: cover; + } + + @container style(--onair-seen: 0) { + .xp-onair > span { + animation-play-state: paused; + } + } +} + +@keyframes xp-onair { + from { + scale: 1 0.25; + } +} + +.xp-hero[data-playing] .xp-hero-art { + scale: 1.04; +} + +.xp-hero-kind { + position: absolute; + top: clamp(12px, 2vw, 20px); + left: clamp(12px, 2vw, 20px); +} + +.xp-hero-play { + position: absolute; + bottom: clamp(14px, 2.5vw, 28px); + left: clamp(14px, 2.5vw, 28px); + z-index: 2; +} + +.xp-hero-eyebrow { + margin: 0 0 0.6rem; + color: var(--accent-ink); + font-size: 0.8125rem; + font-weight: 650; +} + +.xp-hero-title { + margin: 0 0 0.85rem; + max-width: 18ch; + font-family: var(--font-display); + font-size: clamp(2rem, 1.2rem + 2.6vw, 3.6rem); + font-stretch: 72%; + font-weight: 800; + line-height: 0.95; + letter-spacing: -0.01em; + text-transform: uppercase; +} + +.xp-hero-title a { + text-decoration: none; + transition: color 300ms var(--ease-out); +} + +@media (hover: hover) { + .xp-hero-title a:hover { + color: var(--voice-0); + } +} + +.xp-hero[data-current] .xp-hero-title { + color: var(--voice-0); +} + +.xp-hero-facts { + display: flex; + flex-wrap: wrap; + gap: 0.2rem 1rem; + margin: 0 0 1rem; + overflow: hidden; + color: var(--muted); + font-size: 0.875rem; + font-variant-numeric: tabular-nums; + font-weight: 500; +} + +/* One unit, in sentence case: "Ep 260 · Nov 12, 2026 · 1 hr 13 min". + Every fact carries its separator in the gap before it (a negative start + margin), and the line clips, so whichever fact starts a line, wrapped or + not, loses its separator. */ +:is(.xp-hero-facts, .xp-facts, .xp-cu-facts) > * { + margin-inline-start: -1rem; +} + +:is(.xp-hero-facts, .xp-facts, .xp-cu-facts) > ::before { + content: '·'; + display: inline-block; + width: 1rem; + text-align: center; +} + +.xp-hero-desc { + max-width: 58ch; + margin: 0 0 1.25rem; + color: var(--text); + font-size: 1rem; + display: -webkit-box; + -webkit-line-clamp: 4; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.xp-hero-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px 20px; +} + +.xp-hero-link { + display: inline-flex; + align-items: center; + gap: 0.35rem; + color: var(--accent-ink); + font-weight: 650; + text-decoration: none; +} + +.xp-hero-link svg { + transition: translate 300ms var(--ease-spring); +} + +.xp-hero-link:hover svg { + translate: 3px -3px; +} + +/* As the archive takes over, the hero recedes with the scroll. */ +@supports (animation-timeline: view()) { + @media (prefers-reduced-motion: no-preference) { + .xp-hero-media { + animation: xp-recede linear both; + animation-timeline: view(); + animation-range: exit 0% exit 100%; + } + } +} + +@keyframes xp-recede { + to { + opacity: 0.3; + scale: 0.9; + translate: 0 14%; + } +} + +/* ---------- People (hero and open cards) ---------- + The shared identity (styles/people.css): 32px ringed circles with names, + each a link to the archive filtered to them. The hero's row is names + only; the close-up's cast adds what this episode is for them. */ + +:is(.xp-hero-people, .xp-people) { + display: flex; + flex-wrap: wrap; + gap: 10px 20px; + margin: 0 0 1.1rem; + padding: 0; + list-style: none; +} + +:is(.xp-hero-people, .xp-people) .person-chip { + border-radius: 999px; + transition: color var(--quick); +} + +@media (hover: hover) { + :is(.xp-hero-people, .xp-people) .person-chip:hover { + color: var(--accent-ink); + } +} + +.xp-person { + display: grid; +} + +.xp-person .person-fact { + font-size: 0.75rem; + line-height: 1rem; +} + +/* ---------- Glass chips over media ---------- + Tinted, not blurred: a backdrop filter made every chip on every card a + composited layer of its own (two a card, about sixty on the archive), + and a stuck toolbar's blur over them more. */ + +.xp-chip { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 3px 8px; + border-radius: 999px; + background: var(--xp-glass); + color: var(--xp-on-glass); + font-size: 0.6875rem; + font-weight: 650; + line-height: 1.3; + font-variant-numeric: tabular-nums; +} + +/* ---------- The archive ---------- */ + +.xp { + container: xp / inline-size; +} + +.xp-heading { + display: flex; + align-items: baseline; + gap: 0.6rem; + margin: 0; + font-family: var(--font-display); + font-size: clamp(1.35rem, 1.1rem + 0.8vw, 1.75rem); + font-stretch: 72%; + font-weight: 800; + letter-spacing: -0.01em; + line-height: 1.15; + text-transform: uppercase; +} + +.xp-heading span { + color: var(--muted); + font-family: var(--font-ui); + font-size: 0.9rem; + font-stretch: 100%; + font-weight: 500; +} + +/* ---------- The toolbar: sticks, and knows when it's stuck ---------- */ + +.xp-bar { + position: sticky; + top: var(--xp-stick); + z-index: 20; + margin: 0 calc(var(--gutter) * -1) 22px; + container: xp-bar / scroll-state; +} + +.xp-bar-in { + display: grid; + gap: 8px; + margin: 0; + padding: 12px var(--gutter); + background: color-mix(in oklch, var(--ground) 88%, transparent); + backdrop-filter: blur(14px) saturate(1.4); + transition: + background-color 300ms var(--ease-out), + box-shadow 300ms var(--ease-out); +} + +@supports (container-type: scroll-state) { + .xp-bar-in { + background-color: transparent; + backdrop-filter: none; + } + + /* Stuck: the bar becomes chrome over the cards scrolling under it. */ + @container xp-bar scroll-state(stuck: top) { + .xp-bar-in { + background-color: color-mix(in oklch, var(--ground) 86%, transparent); + backdrop-filter: blur(14px) saturate(1.4); + box-shadow: + 0 1px 0 var(--line), + 0 16px 32px -28px oklch(10% 0.03 280 / 0.6); + } + } + + /* A phone upright has a little height to spare: while you scroll on down + the archive, the stuck toolbar keeps to its first row (the field, the + views) and its chips fade; they come back as soon as the page scrolls + up. Nothing moves in the page: the second row is only cut away (the + cards show through), never taken out of the flow. */ + @media (max-width: 767px) { + :root:has(.xp-heading) { + container: xp-page / scroll-state; + } + + .xp-bar-in { + clip-path: inset(0 0 0 0); + transition: + background-color 300ms var(--ease-out), + box-shadow 300ms var(--ease-out), + clip-path 300ms var(--ease-out); + } + + .xp-chips { + transition: + opacity 300ms var(--ease-out), + visibility 300ms allow-discrete; + } + + /* (Not in the close-up, which sits under the whole toolbar.) */ + @container xp-page scroll-state(scrolled: bottom) { + @container xp-bar scroll-state(stuck: top) { + .xp:not([data-open]) .xp-bar-in { + clip-path: inset(0 0 calc(100% - 64px) 0); + } + + .xp:not([data-open]) .xp-chips { + visibility: hidden; + opacity: 0; + } + } + } + } +} + +.xp-bar-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 10px; + /* As wide as the toolbar, never its field's natural width: on a 320px + phone the field gives way to the views beside it. */ + min-width: 0; +} + +/* On a phone the toolbar takes the top bar's place: as it arrives at the + top it pushes the top bar up and away, and it sticks at the safe-area + top. The top bar moves with the scroll, pixel for pixel (a scroll-driven + animation on the heading's view timeline, which ends where the toolbar + sticks); where that is missing, the top bar stays put and the toolbar + sticks under it, as on a tablet. */ +@media (max-width: 767px), (orientation: landscape) and (max-height: 500px) { + @supports (animation-timeline: --a) and (timeline-scope: --a) { + :root:has(.xp-heading) { + --xp-stick: env(safe-area-inset-top); + timeline-scope: --xp-head; + } + + .xp-heading { + view-timeline: --xp-head block; + } + + /* From the toolbar meeting the top bar's lower edge (the heading's + bottom there) to the toolbar sticking; the bar's safe-area strip + stays. */ + :root:has(.xp-heading) .topbar { + animation: xp-topbar-away linear both; + animation-timeline: --xp-head; + animation-range: exit-crossing + calc(100% - var(--topbar-h) - env(safe-area-inset-top) - 1px) + exit-crossing calc(100% - env(safe-area-inset-top)); + } + } + + /* The narrowest phones keep the toolbar to two rows, without its back + to the top button (a flick does the same). */ + @media (max-width: 22rem) { + .xp-top { + display: none; + } + } +} + +@keyframes xp-topbar-away { + to { + translate: 0 calc(env(safe-area-inset-top) - 100%); + } +} + +/* A phone on its side has no height to spare: once the toolbar is stuck it + keeps to its first row (the field, the views), on the same timeline: over + the next 48px of scroll its chips fade and the row they leave is cut away + (the cards show through; nothing in the page moves). The script reads + the cut (--xp-bar-cut), so whatever sits under the toolbar sits under + its first row. */ +@media (orientation: landscape) and (max-height: 500px) { + @supports (animation-timeline: --a) and (timeline-scope: --a) { + .xp-bar { + --xp-bar-cut: 48px; + } + + .xp-bar-in, + .xp-chips { + animation: xp-bar-cut linear both; + animation-timeline: --xp-head; + animation-range: exit-crossing calc(100% - env(safe-area-inset-top)) + exit-crossing calc(100% - env(safe-area-inset-top) + 48px); + } + + .xp-chips { + animation-name: xp-chips-away; + } + } +} + +@keyframes xp-bar-cut { + from { + clip-path: inset(0 0 0 0); + } + + to { + /* Its padding, the first row, and its padding again. */ + clip-path: inset(0 0 calc(100% - 64px) 0); + } +} + +@keyframes xp-chips-away { + to { + visibility: hidden; + opacity: 0; + } +} + +.xp-search { + display: flex; + flex: 1 1 10rem; + align-items: center; + gap: 8px; + min-width: 0; + height: 40px; + padding: 0 16px; + border: 1px solid var(--line-strong); + border-radius: 999px; + background: var(--surface); + color: var(--muted); + transition: + border-color var(--quick), + box-shadow var(--quick); +} + +.xp-search:focus-within { + border-color: var(--accent); + box-shadow: 0 0 0 4px var(--accent-soft); +} + +.xp-search input { + flex: 1; + min-width: 0; + height: 100%; + padding: 0; + border: 0; + background: none; + box-shadow: none; + color: var(--ink); + font: inherit; + font-size: 0.9375rem; + outline: none; +} + +.xp-search input::placeholder { + color: var(--muted); +} + +/* On a touch screen the field is 16px type at least: iOS zooms the page + into any smaller field it focuses. */ +@media (pointer: coarse) { + .xp-search input { + font-size: max(1rem, 16px); + } +} + +.xp-count { + flex: none; + color: var(--muted); + font-size: 0.8125rem; + white-space: nowrap; +} + +/* Narrow: the count is a number (filtered, only the number shown), the + view switch is icons. */ +@container xp (width < 30rem) { + .xp-count-unit, + .xp-count [data-xp-of], + .xp-views label span { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } + + .xp-views label { + padding: 0 0.6rem; + } +} + +.xp-count b { + color: var(--ink); + font-weight: 700; +} + +/* Pills that pick a value: sort, year, people, in progress. */ +.xp-pick, +.xp-reset { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + height: 40px; + padding: 0 0.9rem; + border: 1px solid var(--line-strong); + border-radius: 999px; + background: var(--surface); + color: var(--text); + font: inherit; + font-size: 0.8125rem; + font-weight: 600; + white-space: nowrap; + cursor: pointer; + transition: + background-color var(--quick), + border-color var(--quick), + color var(--quick); +} + +@media (hover: hover) { + .xp-pick:not([data-on], [aria-pressed='true']):hover { + border-color: var(--ink); + } +} + +.xp-pick b { + color: var(--ink); + font-weight: 700; +} + +.xp-pick svg { + flex: none; + color: var(--muted); +} + +/* A filter with a value set turns solid; its chevron gives way to a × + (a button of its own, over the pill's end) that clears it. */ +.xp-pick[data-on], +.xp-pick[aria-pressed='true'] { + border-color: var(--ink); + background: var(--ink); + color: var(--on-ink); +} + +.xp-pick[data-on] :is(b, svg), +.xp-pick[aria-pressed='true'] :is(b, svg) { + color: var(--on-ink); +} + +.xp-filter { + position: relative; + display: inline-flex; + flex: none; +} + +.xp-pick[data-on] { + padding-inline-end: 38px; +} + +.xp-pick[data-on] .xp-chevron { + display: none; +} + +.xp-unset { + position: absolute; + inset-block: 8px; + inset-inline-end: 8px; + display: grid; + place-items: center; + width: 24px; + padding: 0; + border: 0; + border-radius: 50%; + background: color-mix(in oklch, var(--on-ink) 16%, transparent); + color: var(--on-ink); + cursor: pointer; + transition: background-color var(--quick); +} + +.xp-unset[hidden] { + display: none; +} + +/* On a touch screen it keeps its 24px look but takes a 44px tap, and the + pill makes a little more room for it, so a near miss doesn't open the + menu instead. */ +@media (pointer: coarse) { + .xp-pick[data-on] { + padding-inline-end: 42px; + } + + .xp-unset::before { + content: ''; + position: absolute; + inset: -10px; + } +} + +@media (hover: hover) { + .xp-unset:hover { + background: color-mix(in oklch, var(--on-ink) 30%, transparent); + } +} + +.xp-unset:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +/* The With chip wears the chosen person's face (the shared identity, at + 20px: a 1px ring, 1px clear). */ +.xp-pick-face { + --person-size: 20px; + --person-ring: color-mix(in oklch, var(--on-ink) 45%, transparent); + margin-inline-start: -0.45rem; + padding: 1px; + border-width: 1px; +} + +.xp-pick-face::before { + inset: 1px; +} + +.xp-pick-face[hidden] { + display: none; +} + +.xp-pick .xp-chevron { + transition: rotate 300ms var(--ease-spring); +} + +.xp-bar-in:has(#xp-sort:popover-open) [popovertarget='xp-sort'] .xp-chevron, +.xp-bar-in:has(#xp-year:popover-open) [popovertarget='xp-year'] .xp-chevron, +.xp-bar-in:has(#xp-people:popover-open) + [popovertarget='xp-people'] + .xp-chevron { + rotate: 180deg; +} + +.xp-sort { + margin-left: auto; +} + +.xp-reset { + border-color: transparent; + background: none; + color: var(--accent-ink); + font-weight: 650; +} + +.xp-reset:hover { + text-decoration: underline; + text-underline-offset: 0.2em; +} + +/* Chips that come and go (In progress, Reset) arrive in the row's order. */ +.xp-chips > * { + transition: + opacity calc(260ms * var(--slomo)) var(--ease-out), + scale calc(420ms * var(--slomo)) var(--ease-spring), + display calc(260ms * var(--slomo)) allow-discrete; + transition-delay: 0s; + transition-delay: calc(min(sibling-index() - 1, 8) * 18ms * var(--slomo)); +} + +.xp-chips > [hidden] { + display: none; + opacity: 0; + scale: 0.8; +} + +@starting-style { + .xp-chips > * { + opacity: 0; + scale: 0.8; + } +} + +/* Back to the top: it shows up only once you're well into the archive. A + scroll position triggers a timed animation, and scrolling back reverses + it. */ +.xp-top { + flex: none; + border: 1px solid var(--line); + background: var(--surface); + animation-name: xp-top-in; + animation-duration: calc(420ms * var(--slomo)); + animation-timing-function: var(--ease-spring); + animation-fill-mode: both; + animation-trigger: --xp-deep play-forwards play-backwards; +} + +@keyframes xp-top-in { + from { + visibility: hidden; + opacity: 0; + scale: 0.5; + rotate: -90deg; + } + + to { + visibility: visible; + opacity: 1; + scale: 1; + rotate: 0deg; + } +} + +.xp { + trigger-scope: --xp-deep; +} + +.xp-list { + timeline-trigger: --xp-deep view() contain 50vh cover 100%; +} + +/* ---------- Segmented controls: the thumb rides an anchor ---------- + The checked label is the anchor; the thumb fills it (anchored auto + layout's data-⚓️-fill) and glides to whichever label is checked next. */ +.xp-seg { + position: relative; + display: inline-flex; + flex: none; + margin: 0; + padding: 3px; + min-inline-size: 0; + border: 1px solid var(--line-strong); + border-radius: 999px; + background: var(--ground); +} + +.xp-seg label { + position: relative; + z-index: 1; + display: inline-flex; + align-items: center; + gap: 6px; + height: 32px; + padding: 0 0.9rem; + border-radius: 999px; + color: var(--muted); + font-size: 0.8125rem; + font-weight: 650; + white-space: nowrap; + cursor: pointer; + transition: color var(--quick); +} + +@media (hover: hover) { + .xp-seg label:not(:has(:checked)):hover { + color: var(--ink); + } +} + +.xp-seg input { + position: absolute; + opacity: 0; + pointer-events: none; +} + +/* In the close-up the archive is a strip, with no grid or list to pick: the + view switch steps out of the toolbar, the field taking its room (its row + keeps its height), and steps back in on closing. */ +.xp-views { + interpolate-size: allow-keywords; + transition: + opacity calc(200ms * var(--slomo)) var(--ease-out), + scale calc(300ms * var(--slomo)) var(--ease-out), + width calc(300ms * var(--slomo)) var(--ease-out), + margin calc(300ms * var(--slomo)) var(--ease-out), + padding calc(300ms * var(--slomo)) var(--ease-out), + border-width calc(300ms * var(--slomo)) var(--ease-out), + visibility calc(300ms * var(--slomo)) allow-discrete; +} + +.xp[data-open] .xp-views { + width: 0; + margin-inline-start: -10px; + padding-inline: 0; + border-inline-width: 0; + overflow: hidden; + opacity: 0; + scale: 0.6; + visibility: hidden; +} + +.xp-seg label:has(:checked) { + anchor-name: --xp-on; + color: var(--on-ink); +} + +.xp-seg label:has(:focus-visible) { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.xp-seg-thumb { + border-radius: 999px; + background: var(--ink); + transition: + inset calc(520ms * var(--slomo)) var(--ease-spring), + width calc(520ms * var(--slomo)) var(--ease-spring), + height calc(520ms * var(--slomo)) var(--ease-spring); +} + +/* Without typed attr() (anchored auto layout's engine), the checked label + fills itself. */ +@supports not (anchor-name: attr(data-x type())) { + .xp-seg-thumb { + display: none; + } + + .xp-seg label:has(:checked) { + background: var(--ink); + } +} + +/* ---------- The chip row scrolls sideways, and says so ---------- */ + +.xp-chips { + display: flex; + align-items: center; + gap: 8px; + margin: -6px calc(var(--gutter) * -1); + padding: 6px var(--gutter); + /* A chip scrolled into view (a filter just set) keeps the gutter. */ + scroll-padding-inline: var(--gutter); + overflow-x: auto; + overscroll-behavior-x: contain; + scrollbar-width: none; + container: xp-chips / scroll-state; +} + +.xp-chips::before, +.xp-chips::after { + content: ''; + position: sticky; + z-index: 2; + flex: none; + align-self: stretch; + width: 32px; + margin: -6px 0; + opacity: 0; + pointer-events: none; + transition: opacity 250ms var(--ease-out); +} + +.xp-chips::before { + left: calc(var(--gutter) * -1); + margin-right: -40px; + background: linear-gradient(to right, var(--ground) 30%, transparent); +} + +.xp-chips::after { + right: calc(var(--gutter) * -1); + margin-left: -32px; + background: linear-gradient(to left, var(--ground) 30%, transparent); +} + +@container xp-chips scroll-state(scrollable: inline-start) { + .xp-chips::before { + opacity: 1; + } +} + +@container xp-chips scroll-state(scrollable: inline-end) { + .xp-chips::after { + opacity: 1; + } +} + +/* ---------- Menus: anchored popovers that know which way they flipped ---------- */ + +.xp-menu { + margin: 0; + padding: 0; + border: 0; + background: none; + color: var(--text); + overflow: visible; +} + +.xp-menu-in { + position: relative; + min-width: 240px; + border: 1px solid var(--line); + border-radius: var(--r-card); + background: var(--surface); + box-shadow: var(--shadow-float); + transform-origin: 34px 0; + transition: + opacity calc(200ms * var(--slomo)) var(--ease-out), + scale calc(360ms * var(--slomo)) var(--ease-spring), + translate calc(360ms * var(--slomo)) var(--ease-out); +} + +.xp-menu-list { + max-height: min(420px, 62dvh); + min-inline-size: 0; + margin: 0; + /* 28px corners, 12px in: the rows round at 16px. */ + padding: 12px; + border: 0; + border-radius: inherit; + overflow: auto; + overscroll-behavior: contain; +} + +@starting-style { + .xp-menu:popover-open .xp-menu-in { + opacity: 0; + scale: 0.94; + translate: 0 -8px; + } +} + +.xp-menu-title { + float: left; + width: 100%; + padding: 4px 12px 6px; + color: var(--muted); + font-size: 0.8125rem; + font-weight: 600; +} + +.xp-option { + position: relative; + display: flex; + align-items: center; + gap: 10px; + min-height: 44px; + padding: 0 12px; + border-radius: var(--r-row); + color: var(--ink); + font-size: 0.875rem; + font-weight: 600; + cursor: pointer; + transition: background-color var(--quick); +} + +.xp-option > span:not([class]) { + flex: 1; + min-width: 0; +} + +.xp-option .person-face { + margin-inline-start: -6px; +} + +/* The choice's radio, on the right: a ring that fills when chosen. */ +.xp-radio { + flex: none; + width: 20px; + height: 20px; + border: 1.5px solid var(--line-strong); + border-radius: 50%; + transition: + border-color var(--quick), + box-shadow var(--quick); +} + +.xp-option:has(:checked) .xp-radio { + border-color: var(--ink); + box-shadow: + inset 0 0 0 4px var(--surface), + inset 0 0 0 10px var(--ink); +} + +.xp-option input { + position: absolute; + opacity: 0; + pointer-events: none; +} + +.xp-option small { + color: var(--muted); + font-size: 0.75rem; + font-variant-numeric: tabular-nums; + font-weight: 500; +} + +.xp-option:hover { + background: var(--raised); +} + +/* Opening a menu, its choices arrive one after another, from the tree. */ +.xp-menu:popover-open .xp-option { + transition: + background-color var(--quick), + opacity calc(220ms * var(--slomo)) var(--ease-out), + translate calc(320ms * var(--slomo)) var(--ease-out); + transition-delay: 0s; + transition-delay: + 0s, calc(min(sibling-index() - 1, 10) * 18ms * var(--slomo)), + calc(min(sibling-index() - 1, 10) * 18ms * var(--slomo)); +} + +@starting-style { + .xp-menu:popover-open .xp-option { + opacity: 0; + translate: 0 -6px; + } +} + +.xp-option:has(:focus-visible) { + outline: 2px solid var(--accent); + outline-offset: -2px; +} + +@supports (anchor-name: --xp) { + .xp-menu { + inset: auto; + margin-block: 8px; + position-area: block-end span-inline-end; + position-try-fallbacks: + flip-inline, + flip-block, + flip-block flip-inline; + container-type: anchored; + } + + /* A caret points back at the button; it and the menu's growth follow the + fallback the browser picked. */ + .xp-menu-in::before { + content: ''; + position: absolute; + top: -6px; + left: 30px; + width: 10px; + height: 10px; + border: 1px solid var(--line); + border-width: 1px 0 0 1px; + background: var(--surface); + rotate: 45deg; + } + + @container anchored(fallback: flip-inline) { + .xp-menu-in { + transform-origin: calc(100% - 34px) 0; + } + + .xp-menu-in::before { + left: auto; + right: 30px; + } + } + + @container anchored(fallback: flip-block) { + .xp-menu-in { + transform-origin: 34px 100%; + } + + .xp-menu-in::before { + top: auto; + bottom: -6px; + border-width: 0 1px 1px 0; + } + + @starting-style { + .xp-menu:popover-open .xp-menu-in { + translate: 0 8px; + } + } + } + + @container anchored(fallback: flip-block flip-inline) { + .xp-menu-in { + transform-origin: calc(100% - 34px) 100%; + } + + .xp-menu-in::before { + top: auto; + bottom: -6px; + left: auto; + right: 30px; + border-width: 0 1px 1px 0; + } + + @starting-style { + .xp-menu:popover-open .xp-menu-in { + translate: 0 8px; + } + } + } + + /* On a phone a menu is often moved along to fit, away from its chip + (the chip row scrolled, the menu wider than what is left beside it): + its caret points at the chip wherever the menu landed (explorer.ts + measures it as the menu opens), above or below as it flipped. */ + @media (max-width: 767px), (orientation: landscape) and (max-height: 500px) { + .xp-menu-in::before { + right: auto; + left: calc(var(--xp-caret, 35px) - 5px); + } + } +} + +/* ---------- Cards ---------- + A card is loose parts that flip on their own: the artwork (square in + every layout, so it scales without squishing), the text block (it only + travels; re-wrapped lines fade in where they land) and the play disc. In + the close-up the text block comes apart: the facts line and the title + travel to slots of their own. The card itself never transforms. + + Every card has an exact size, worked out from the column it sits in, so + a card rendering in for the first time never changes a row's height and + never makes the archive lay out again (size containment). */ + +.xp-stage { + --xp-title-size: clamp(1rem, 0.92rem + 0.35vw, 1.2rem); + position: relative; + display: grid; + grid-template-columns: minmax(0, 1fr); + /* Cards fading out where they stood go behind the rest (z-index: -1): + behind them here, not behind the page's own ground, where they would + vanish at once. */ + isolation: isolate; +} + +.xp-list { + --xp-cols: 2; + /* The columns the window counts in (the script reads it): the grid's, + one in the list and the strip, four in a phone's strip. */ + --xp-span: var(--xp-cols); + --xp-gap-x: 18px; + --xp-gap-y: 30px; + /* One column's width, from the stage's width (--xp-w, which the script + keeps in pixels: container units here crash Chrome 157 alongside the + list's scroll trigger). */ + --xp-cell: calc( + (var(--xp-w) - (var(--xp-cols) - 1) * var(--xp-gap-x)) / var(--xp-cols) + ); + --xp-facts-lh: calc(0.8125rem * 1.3); + --xp-title-lh: calc(var(--xp-title-size) * 1.02); + --xp-desc-lh: calc(0.9375rem * 1.5); + --xp-text-h: calc(var(--xp-facts-lh) + 0.3rem + 3 * var(--xp-title-lh)); + display: grid; + grid-template-columns: repeat(var(--xp-cols), minmax(0, 1fr)); + gap: var(--xp-gap-y) var(--xp-gap-x); + margin: 0; + padding: 0; + list-style: none; + /* Every part travels in a straight line and lands without overshoot: + across, down and in size on one clock and one curve. It is the page + column's own (rail.css: its glide as the sidebar folds), so a card the + sidebar carries rides the column's motion and its own as one. */ + --flip-dx: 0.55s; + --flip-dy: 0.55s; + --flip-ds: 0.55s; + --flip-ex: var(--ease-out); + --flip-ey: var(--ease-out); + --flip-es: var(--ease-out); + /* A card turning (the strip's lean, the close-up's turn and the title's + tumble) turns on a clock of its own. */ + --xp-turn-d: 0.7s; +} + +/* As many columns as the old auto-fill gave (150px, then 196px, then + 216px at least), so a scroll renders as many cards per row as before. */ +@container xp (width >= 30rem) { + .xp-list { + --xp-cols: 3; + } +} + +@container xp (width >= 40rem) { + .xp-list { + --xp-gap-x: 22px; + --xp-gap-y: 36px; + } +} + +@container xp (width >= 53rem) { + .xp-list { + --xp-cols: 4; + } +} + +@container xp (width >= 73rem) { + .xp-list { + --xp-cols: 5; + } +} + +@container xp (width >= 88rem) { + .xp-list { + --xp-cols: 6; + } +} + +/* A sort sets `order` on the cards; keyboard and screen readers follow it. */ +.xp-list { + reading-flow: grid-order; +} + +/* ---------- The window ---------- + Only the cards around the viewport are grid items (explorer.ts). The rest + wait in two parked blocks, before and after them: each is one box that + spans exactly the rows its cards would take (every row is one height), + lays its cards on the grid's own tracks (subgrid), and renders nothing + unless find in page opens it (hidden until found; set here as well, so a + browser without that keeps the box and its size). */ +.xp-park { + display: grid; + grid-column: 1 / -1; + grid-row: span var(--xp-rows, 1); + grid-template-columns: subgrid; + grid-template-rows: subgrid; + margin: 0; + padding: 0; + list-style: none; + content-visibility: hidden; +} + +.xp-park[data-above] { + order: -1; +} + +.xp-park[data-below] { + order: 999999; +} + +.xp-park:not([hidden]) { + content-visibility: visible; +} + +.xp-park[data-empty] { + display: none; +} + +.xp-list[data-moving] { + overflow-anchor: none; +} + +/* The close-up places the reader itself (the current cell in view, the + close-up stuck); the browser's scroll anchoring would undo it a frame + later. */ +.xp:is([data-open], [data-folding]) .xp-stage { + overflow-anchor: none; +} + +.xp-card { + position: relative; + display: grid; + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + 'art' + 'text'; + align-content: start; + /* Text sits 8px under the art and 4px in from its edge. */ + gap: 8px 18px; + /* Room for focus rings inside the card's paint containment. */ + margin: -6px; + padding: 6px; + content-visibility: auto; + contain-intrinsic-block-size: auto 340px; + cursor: pointer; +} + +/* Once the stage's width is known, every card's size is exact: rows are + fixed, and a card is its own layout boundary, so one rendering in for the + first time never lays out the archive again. */ +.xp-stage[data-sized] .xp-list[data-view='grid'] { + grid-auto-rows: calc(var(--xp-cell) + 8px + var(--xp-text-h)); +} + +.xp-stage[data-sized] .xp-card { + contain: size; +} + +/* On the explorer's own flights a card renders in full until it lands; one + the shell's glide carries keeps its containment and widens its clip + (explorer.ts). */ +.xp-card[data-flying] { + content-visibility: visible; +} + +.xp-card :is(a, button) { + cursor: pointer; + /* Focus never lands under the sticky toolbar or the dock: when the + browser scrolls a card's control into view, it clears both. */ + scroll-margin-block: calc(var(--xp-stick) + var(--xp-bar-h, 112px) + 12px) + calc(var(--dock-h) + 12px); +} + +@media (max-width: 1023px) { + .xp-card :is(a, button) { + scroll-margin-block-end: calc(var(--dock-h) + var(--tabbar-h) + 12px); + } +} + +/* The artwork's cell: never transformed, so it keeps its square when the + artwork leaves for the close-up and is never the box that artwork is + placed against. */ +.xp-art-box { + grid-area: art; + min-width: 0; + aspect-ratio: 1; +} + +/* Under the pointer the artwork grows: a flat scale, from its centre, + eased both ways (a tile by 6%, a list row's thumb by 12%, so both read). + At rest no card in the wall is in 3D. The scale is tweened through a + number on the artwork, which carries its flip transform (and so its own + transform node) already: as a transition of scale itself, each hover + promoted a new layer and dropped it after, and its first frames went out + before its tiles were drawn (a flicker under load). The flip scales from + the top left corner; the translate keeps this growth centred. (Not on + the art's cell: any transform there makes it the box the open card's + artwork is placed against, instead of the close-up's slot.) Never on the + card in the close-up or on its way out: it is under the pointer there + only because its detail sits under the close button. */ +@property --xp-grow { + syntax: ''; + inherits: false; + initial-value: 1; +} + +.xp-list { + --xp-hover-grow: 1.06; +} + +.xp-list[data-view='list'], +.xp[data-open] .xp-list { + --xp-hover-grow: 1.12; +} + +/* It grows under the pointer and with keyboard focus anywhere in the card, + in the wall and in the strip alike. */ +@media (hover: hover) and (prefers-reduced-motion: no-preference) { + .xp:not([data-still]) .xp-card:not([data-on], [data-swap]):hover .xp-art { + --xp-grow: var(--xp-hover-grow); + } +} + +@media (prefers-reduced-motion: no-preference) { + .xp-card:not([data-on], [data-swap]):has(:focus-visible) .xp-art { + --xp-grow: var(--xp-hover-grow); + } +} + +.xp-art { + --r: var(--r-tile); + --xp-r: var(--r-tile); + /* What the open card holds (its depth, its back's lettering) is sized + from its own width, so a card in flight is the open card scaled. */ + container-type: inline-size; + translate: calc((1 - var(--xp-grow)) * 50%) calc((1 - var(--xp-grow)) * 50%); + scale: var(--xp-grow); + /* Join the flip's own transition list (motion/propflip.css): the hover's + growth, and the corner radius alongside the flip's size. */ + --also: + --xp-grow calc(240ms * var(--slomo)) ease, + --r calc(var(--flip-ds) * var(--slomo)) var(--flip-es) + calc(var(--flip-delay, 0s) * var(--slomo)); + position: relative; + display: grid; + width: 100%; + height: 100%; + padding: 0; + border: 0; + /* Flat, the box itself is the picture's ground and clips it, once. */ + background: var(--media-ground); + overflow: hidden; + color: inherit; + font: inherit; + text-align: start; +} + +/* ---------- Depth: tilt → turn → two faces → layers ---------- + Nothing here may clip, fade or filter, or the browser flattens the 3D. + Only cards in the close-up use depth (the open card turning over, the + filmstrip's cells in view leaning back); the wall is always flat. */ +/* The layers stack in one grid cell rather than by absolute positioning: + a positioned box is a paint layer of its own, and a wall of cards with + eight each would cost the compositor dearly on every frame of a scroll. + They round their corners from a plain token (--xp-r), not from the + box's radius, which eases with every flight and would restyle every + layer with it; only the card in or leaving the close-up, whose box + doesn't clip them, follows its box (below). */ +.xp-tilt, +.xp-turn, +.xp-face { + grid-area: 1 / 1; + grid-template: minmax(0, 1fr) / minmax(0, 1fr); + min-width: 0; + min-height: 0; + border-radius: var(--xp-r, var(--r-tile)); +} + +/* The depth wrappers are boxes in the flat wall too, so a card going into + depth (turning over, or a filmstrip cell coming into view: data-depth, + explorer.ts) only stops clipping and takes its 3D, rather than having + its picture taken out of the layout and put back. */ +.xp-tilt, +.xp-turn, +.xp-face { + display: grid; +} + +:is(.xp .xp-card[data-depth], .xp-card:is([data-on], [data-swap])) .xp-art { + background: none; + overflow: visible; +} + +/* Unclipped, the layers inside round their own corners. A strip cell's + keep the strip's (a value that never changes, so its layers are never + restyled as it flies); the card in or leaving the close-up's match its + box as it is seen, its radius undone by its flip scale. Flat, the box + clips them. */ +.xp .xp-card[data-depth] .xp-art { + --xp-r: var(--r-thumb); +} + +.xp-card:is([data-on], [data-swap]) .xp-art { + --xp-r: calc(var(--r) / var(--sx)); +} + +/* In depth the face is what its layers sit on. */ +:is(.xp .xp-card[data-depth], .xp-card:is([data-on], [data-swap])) .xp-face { + position: relative; +} + +/* The turn inside leans back in the filmstrip with this perspective, seen + from the close-up (--xp-vantage), as the demo's one stage sees its strip + from the middle of the page. */ +.xp-card[data-depth] .xp-tilt { + perspective: var(--xp-depth, 1500px); + perspective-origin: var(--xp-vantage-x, 50%) var(--xp-vantage-y, 50%); +} + +/* The turn travels while the archive folds (the strip's cells lean in or + out, set back by a scale rather than a depth: a scale has no unit, so it + holds as the cell is laid out at its new size, and the compositor runs + it) and while a card turns over; a cell that takes depth as the strip + scrolls leans at once. */ +.xp[data-folding] .xp-turn, +.xp-card:is([data-on], [data-swap]) .xp-turn { + transition: + rotate calc(var(--xp-turn-d) * var(--slomo)) var(--xp-spring-1) + calc(var(--flip-delay, 0s) * var(--slomo)), + scale calc(var(--xp-turn-d) * var(--slomo)) var(--ease-out) + calc(var(--flip-delay, 0s) * var(--slomo)); +} + +/* The faces are flat: what is printed on them turns with them and never + stands off them, so nothing is ever drawn outside the card as it turns, + and a face turned away hides all of it. */ +.xp-card:is([data-on], [data-swap]) :is(.xp-tilt, .xp-turn) { + transform-style: preserve-3d; +} + +/* Perspective, like every transform, costs a node in the compositor's + tree for each card that has it; only cards in depth get one. The open + card's is in proportion to it (three of its widths), so on the way home + it is seen as it was in the close-up, only smaller. */ +.xp-card:is([data-on], [data-swap]) .xp-tilt { + perspective: 300cqi; + perspective-origin: 50% 50%; +} + +/* A card stepped away from goes home to the strip: on the way it takes the + strip's perspective, so it lands as a strip cell, with nothing left to + change when it stops travelling. */ +.xp[data-open] .xp-card[data-swap]:not([data-on]) .xp-tilt { + perspective: var(--xp-depth, 1500px); + transition: perspective calc(var(--xp-turn-d) * var(--slomo)) var(--ease-out) + calc(var(--flip-delay, 0s) * var(--slomo)); +} + +.xp-face { + background: var(--media-ground); +} + +/* Cards in depth cast a shadow, the flat wall none: the strip's cells + while the close-up is open, and the card in or leaving it. */ +.xp[data-open] .xp-card[data-depth] .xp-face, +.xp-card:is([data-on], [data-swap]) .xp-face { + box-shadow: 0 14px 22px -16px oklch(0% 0 0 / 0.5); +} + +.xp-card:is([data-on], [data-swap]) .xp-face { + backface-visibility: hidden; +} + +/* Closing, the card goes home to the flat wall: its shadow fades on the + way, so it lands with none. */ +.xp:not([data-open]) .xp-card[data-swap] .xp-face { + box-shadow: 0 14px 22px -16px oklch(0% 0 0 / 0); + transition: box-shadow calc(var(--flip-ds) * var(--slomo)) var(--ease-out); +} + +.xp-turn > * { + grid-area: 1 / 1; +} + +/* The layers on the picture are positioned, as on any card, against the + box in the flat wall and against the face in depth. */ +.xp-skeleton, +.xp-plate-shade { + position: absolute; + inset: 0; +} + +/* On a card arriving through a change (joining the cut, or rising into + view: data-join), the picture fades in once it has loaded (prop-for-that + img on the box), through a number, so no composited layer comes and goes + for it. One already loaded shows at once; one that loads as the page + scrolls appears as it always has, so a scroll repaints nothing more. */ +@property --xp-shown { + syntax: ''; + inherits: false; + initial-value: 1; +} + +@container style(--live-loaded: 0) { + .xp-card[data-join] .xp-face img { + --xp-shown: 0; + } +} + +.xp-face img { + opacity: var(--xp-shown); + transition: --xp-shown calc(300ms * var(--slomo)) var(--ease-out); + display: block; + width: 100%; + height: 100%; + border-radius: var(--xp-r, var(--r-tile)); + object-fit: cover; + /* The hairline: light and dark art meet the page with the same edge. An + outline drawn inward rides the picture's own box, where an overlay + would be one more positioned layer on every card in the wall. */ + outline: 1px solid var(--hairline); + outline-offset: -1px; +} + +/* Until the artwork has loaded (prop-for-that img), a light passes over + its frame. Only a translate animates. In the flat wall the box clips it; + cards in depth, whose box no longer clips, give it a clip of its own. */ +.xp-card:is([data-depth], [data-on], [data-swap]) .xp-skeleton { + border-radius: var(--xp-r, var(--r-tile)); + overflow: hidden; +} + +.xp-skeleton::before { + content: ''; + position: absolute; + inset: 0 -100%; + background: linear-gradient( + 90deg, + oklch(100% 0 0 / 0) 40%, + oklch(100% 0 0 / 0.09) 50%, + oklch(100% 0 0 / 0) 60% + ); + opacity: 0; + transition: opacity 300ms var(--ease-out); +} + +/* The light runs on the card's own scroll (a view() timeline), not on a + clock: it sweeps as a card still loading scrolls into view, and nothing + off screen (or at rest) runs at all. A clock-driven shimmer on every + unloaded card cost a fast scroll a third of its frames. */ +@container style(--live-loaded: 0) and style(--live-broken: 0) { + .xp-skeleton::before { + opacity: 1; + } + + @supports (animation-timeline: view()) { + @media (prefers-reduced-motion: no-preference) { + .xp-skeleton::before { + animation: xp-shimmer linear both; + animation-timeline: view(); + animation-range: cover 0% cover 100%; + } + } + } +} + +@keyframes xp-shimmer { + from { + translate: -33.3% 0; + } + + to { + translate: 33.3% 0; + } +} + +.xp-chip-kind { + position: absolute; + top: 8px; + left: 8px; +} + +/* The kind's glyph and the "More" chevron are painted from a mask in this + sheet, once, rather than an inline icon in each of the 261 cards. */ +.xp-chip-kind::before, +.xp-more::after { + content: ''; + flex: none; + width: 14px; + height: 14px; + background: currentColor; + mask: var(--xp-glyph) center / contain no-repeat; +} + +.xp-chip-kind::before { + --xp-glyph: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.75' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4 14.5V12a8 8 0 0 1 16 0v2.5'/%3E%3Crect height='6.5' rx='1.6' width='4' x='3.5' y='13.5'/%3E%3Crect height='6.5' rx='1.6' width='4' x='16.5' y='13.5'/%3E%3C/svg%3E"); +} + +[data-video] .xp-chip-kind::before { + --xp-glyph: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.75' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect height='11' rx='2' width='13' x='2.5' y='6.5'/%3E%3Cpath d='m15.5 10.6 5-2.8v8.4l-5-2.8'/%3E%3C/svg%3E"); +} + +.xp-more::after { + --xp-glyph: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.75' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m7 10 5 5 5-5'/%3E%3C/svg%3E"); +} + +.xp-chip-length { + position: absolute; + bottom: 8px; + left: 8px; +} + +/* How far the visitor got: their saved place, or live for the episode + that's loaded. */ +.xp-progress { + position: absolute; + inset: auto 0 0; + height: 3px; + border-radius: 0 0 var(--r-tile) var(--r-tile); + background: linear-gradient(90deg, var(--glow-b), var(--glow-a)); + transform-origin: 0 50%; + scale: var(--xp-progress, 0) 1; +} + +.xp-card[data-current] .xp-progress { + scale: var(--live-progress, 0) 1; + /* The media clock ticks four times a second; glide between ticks. */ + transition: scale 250ms linear; +} + +/* The back of the card, made the first time it opens: the picture again, + with its number and kind printed on it. */ +.xp-back { + rotate: y 180deg; + box-shadow: 0 60px 70px -40px oklch(0% 0 0 / 0.6); + /* Out of 3D it would paint over the front, mirrored. */ + visibility: hidden; +} + +.xp-card:is([data-on], [data-swap]) .xp-back { + visibility: visible; +} + +.xp-plate-shade { + border-radius: var(--xp-r, var(--r-tile)); + background: + radial-gradient( + circle at 0 0, + oklch(10% 0.02 280 / 0.55), + oklch(10% 0.02 280 / 0) 55% + ), + linear-gradient( + to top, + oklch(10% 0.02 280 / 0.5), + oklch(10% 0.02 280 / 0) 40% + ); +} + +.xp-plate-no { + position: absolute; + top: 5%; + left: 7%; + color: oklch(100% 0 0 / 0.86); + font-family: var(--font-display); + /* In proportion to the box (as is everything on the back), so the card + flying home is the open card made smaller, number and all. */ + font-size: 20cqi; + font-stretch: 72%; + font-weight: 800; + line-height: 0.8; + letter-spacing: -0.02em; +} + +.xp-plate-tag { + position: absolute; + right: 6%; + bottom: 6%; + color: oklch(100% 0 0 / 0.9); + font-size: var(--xp-tag-size, 2.8cqi); + white-space: nowrap; + font-variant-numeric: tabular-nums; + font-weight: 600; +} + +.xp-play { + grid-area: art; + align-self: end; + justify-self: end; + z-index: 2; + margin: 8px; + /* Opacity only: a visibility transition would restyle the whole + subtree on every frame of the flight. */ + --also: opacity calc(0.3s * var(--slomo)) ease; +} + +.xp-text { + grid-area: text; + min-width: 0; + padding-inline: 4px; + block-size: var(--xp-text-h); + /* It travels; it never scales. */ + transform: translate(calc(var(--tx) * 1px), calc(var(--ty) * 1px)); + /* Opacity only: a visibility transition would restyle the whole + subtree on every frame of the flight. */ + --also: opacity calc(0.3s * var(--slomo)) ease; + /* The title is as wide as the block, in pixels (below). */ + container-type: inline-size; +} + +/* The facts line and the title travel too, in the close-up. They only + translate; the title grows as type on the way. In the wall they carry no + transform at all (their text block travels for them). */ +.xp-facts, +.xp-title { + transform: none; +} + +/* Its own transitions, not the text block's (--also inherits): into the + close-up and back its type eases with the flight. */ +.xp-facts { + --also: visibility 0s; +} + +.xp-card[data-swap] .xp-facts { + --xp-lay: calc(var(--flip-ds) * var(--slomo)) var(--flip-es) + calc(var(--flip-delay, 0s) * var(--slomo)); + --also: font-size var(--xp-lay), letter-spacing var(--xp-lay); +} + +.xp-card:is([data-on], [data-swap]) :is(.xp-facts, .xp-title) { + transform: translate(calc(var(--tx) * 1px), calc(var(--ty) * 1px)); +} + +.xp-facts, +.xp-cu-facts { + display: flex; + gap: 0.15rem 1rem; + margin: 0 0 0.3rem; + overflow: hidden; + color: var(--muted); + font-size: 0.8125rem; + font-variant-numeric: tabular-nums; + font-weight: 500; + line-height: 1.3; + white-space: nowrap; +} + +.xp-number { + color: var(--ink); + font-weight: 650; +} + +.xp-facts-kind { + color: var(--accent-ink); + font-weight: 650; +} + +.xp-facts-length, +.xp-facts-kind { + display: none; + opacity: 0; + transition: + opacity calc(300ms * var(--slomo)) var(--ease-out), + display calc(300ms * var(--slomo)) allow-discrete; +} + +.xp-title, +.xp-cu-title { + margin: 0; + font-family: var(--font-display); + font-size: var(--xp-title-size); + font-stretch: 78%; + font-weight: 800; + line-height: 1.02; + text-transform: uppercase; +} + +/* In a card the title is as wide as its block, as a length (not auto), so + it keeps that width when it leaves for the close-up until it changes. + Into the close-up and back it tumbles a full turn (its link, below) and + takes its new size, width and line count while it faces away, unseen: + the link turns through its back about a fifth of the way through the + spring. Elsewhere a re-wrapped title fades in where it lands. */ +.xp-title { + width: 100cqi; + --also: visibility 0s; +} + +.xp-card[data-swap] .xp-title { + --xp-lay: calc(var(--xp-turn-d) * var(--slomo)) linear(0, 0 20%, 1 20%, 1) + calc(var(--flip-delay, 0s) * var(--slomo)); + --also: + font-size var(--xp-lay), line-height var(--xp-lay), + letter-spacing var(--xp-lay), width var(--xp-lay); +} + +.xp-card[data-swap] .xp-title a { + transition: + color 300ms var(--ease-out), + rotate calc(var(--xp-turn-d) * var(--slomo)) var(--xp-spring-1) + calc(var(--flip-delay, 0s) * var(--slomo)), + -webkit-line-clamp var(--xp-lay); + transition-behavior: allow-discrete; +} + +.xp-title a { + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; + text-decoration: none; + transition: + color 300ms var(--ease-out), + rotate calc(var(--xp-turn-d) * var(--slomo)) var(--xp-spring-1) + calc(var(--flip-delay, 0s) * var(--slomo)); +} + +@media (hover: hover) { + .xp:not([data-still]) .xp-card:not([data-on]):hover .xp-title a { + color: var(--voice-0); + } +} + +:is(.xp-card, .xp-fading-card)[data-current] .xp-title { + color: var(--voice-0); +} + +/* To and from an episode, its headline and the card's title morph under + one name, but they are two different blocks of type: cross-faded, both + show at once (a double exposure). The one leaving fades out first and + the one arriving fades in after it (EpisodeList.astro names them). */ +:root::view-transition-old(*.xp-morph-title) { + animation: xp-morph-out calc(160ms * var(--slomo)) ease-out both; +} + +:root::view-transition-new(*.xp-morph-title) { + animation: xp-morph-in calc(240ms * var(--slomo)) ease-out + calc(160ms * var(--slomo)) both; +} + +@keyframes xp-morph-out { + to { + opacity: 0; + } +} + +@keyframes xp-morph-in { + from { + opacity: 0; + } +} + +/* The rest of a card: a list row's description, the close-up's column. */ +.xp-detail { + display: none; + grid-area: detail; + min-width: 0; +} + +.xp-desc { + margin: 0; + color: var(--text); + font-size: 0.9375rem; + line-height: 1.5; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +/* "More" only where the description is actually cut off (prop-for-that + truncated, written on the detail). It sits over the end of the last + line, so a row's height never depends on it. */ +.xp-more { + position: absolute; + right: 0; + bottom: 0; + display: none; + align-items: center; + gap: 2px; + padding-left: 2.5rem; + /* It fades into the row, lit or not (--xp-lit, below). */ + background: linear-gradient( + to right, + transparent, + color-mix(in oklch, var(--raised) calc(var(--xp-lit) * 100%), var(--ground)) + 2rem + ); + transition: --xp-lit calc(240ms * var(--slomo)) ease; + color: var(--accent-ink); + font-size: 0.8125rem; + font-weight: 650; + line-height: var(--xp-desc-lh); +} + +@container style(--live-truncated-y: 1) { + .xp-more { + display: inline-flex; + } +} + +.xp-people, +.xp-resume, +.xp-actions { + display: none; +} + +/* The play disc: a surface circle that turns solid ink while its episode + is loaded (interactions.css adds the gradient fill). */ +.row-play { + display: grid; + place-items: center; + width: 44px; + height: 44px; + border: 1px solid var(--line-strong); + border-radius: 999px; + background: var(--surface); + color: var(--ink); + cursor: pointer; + transition: transform 300ms var(--ease-spring); +} + +.row-play:active { + transform: scale(0.92); +} + +[data-episode-row][data-current] .row-play { + color: var(--on-ink); +} + +/* ---------- List view: the same parts, in a row ---------- */ + +.xp-list[data-view='list'] { + --xp-span: 1; + --xp-row-text: calc(var(--xp-facts-lh) + 0.3rem + 2 * var(--xp-title-lh)); + grid-template-columns: minmax(0, 1fr); + grid-auto-rows: calc(28px + max(56px, var(--xp-row-text))); + gap: 0; +} + +/* Hairlines between rows fade in once the cards have landed. */ +.xp-list::before, +.xp-card::after { + content: ''; + position: absolute; + inset: auto 0 0; + height: 1px; + background: var(--line); + opacity: 0; + pointer-events: none; +} + +.xp-list::before { + inset: 0 0 auto; +} + +.xp-list[data-view='list']::before, +.xp-list[data-view='list'] .xp-card::after { + opacity: 1; + transition: opacity calc(400ms * var(--slomo)) var(--ease-out) + calc(450ms * var(--slomo)); +} + +/* Folding back from the close-up (where they are not drawn) they fade in + too. */ +@starting-style { + .xp[data-folding] .xp-list[data-view='list']::before, + .xp[data-folding] .xp-list[data-view='list'] .xp-card::after { + opacity: 0; + } +} + +.xp-list[data-view='list'] .xp-card { + grid-template-columns: 56px minmax(0, 1fr) auto; + grid-template-rows: auto minmax(0, 1fr); + grid-template-areas: + 'art text play' + 'art detail play'; + align-items: start; + column-gap: 14px; + margin: 0; + padding: 14px 6px; +} + +/* Under the pointer a row lights up (a Raised fill, eased in and out) as + its thumb grows: a response the whole row gives, not only the thumb. The + fill is its own box under the row (the row's paint containment keeps it + there), faded through a number that nothing inherits, so a hover + restyles that box and the "More" over the description, nothing else. */ +@property --xp-lit { + syntax: ''; + inherits: false; + initial-value: 0; +} + +.xp-list[data-view='list'] .xp-card:not([data-on])::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + border-radius: var(--r-thumb); + background: var(--raised); + opacity: var(--xp-lit); + transition: --xp-lit calc(240ms * var(--slomo)) ease; + pointer-events: none; +} + +@media (hover: hover) { + .xp:not([data-open], [data-still]) + .xp-list[data-view='list'] + .xp-card:not([data-on], [data-swap]):hover::before, + .xp:not([data-open], [data-still]) + .xp-list[data-view='list'] + .xp-card:not([data-on], [data-swap]):hover + .xp-more { + --xp-lit: 1; + } +} + +.xp-list[data-view='list'] .xp-art-box { + align-self: center; +} + +/* A thumb's corners, not a tile's. */ +.xp-list[data-view='list'] .xp-card:not([data-on]) .xp-art { + --r: var(--r-thumb); + --xp-r: var(--r-thumb); +} + +:is(.xp-list, .xp-fading-text)[data-view='list'] .xp-text { + block-size: auto; + padding-inline: 0; +} + +.xp-list[data-view='list'] .xp-play { + grid-area: play; + align-self: center; + margin: 0; +} + +/* A thumb has no room for chips, and in the close-up the face they are on + has turned away: a list card never shows them. */ +.xp-list[data-view='list'] .xp-chip { + display: none; +} + +:is(.xp-list, .xp-fading-text)[data-view='list'] + :is(.xp-facts-length, .xp-facts-kind) { + display: inline; + opacity: 1; + transition: none; +} + +:is(.xp-list, .xp-fading-text)[data-view='list'] .xp-title a { + -webkit-line-clamp: 2; +} + +/* A phone's list row has no room for the whole facts line on one line: + it takes two (a fact starting the second drops its separator, as on any + wrap), and every row is that much taller. */ +@container xp (width < 40rem) { + .xp-list[data-view='list'] { + --xp-row-text: calc( + 2 * var(--xp-facts-lh) + 0.15rem + 0.3rem + 2 * var(--xp-title-lh) + ); + } + + :is(.xp-list, .xp-fading-text)[data-view='list'] .xp-facts { + flex-wrap: wrap; + } +} + +/* A card too narrow for the whole date (two columns on a 320px phone) + leaves out its year. */ +@container (width < 9rem) { + .xp-facts .xp-year { + display: none; + } +} + +@container xp (width >= 40rem) { + .xp-list[data-view='list'] { + grid-auto-rows: calc( + 36px + max(72px, var(--xp-row-text) + 0.35rem + 2 * var(--xp-desc-lh)) + ); + } + + .xp-list[data-view='list'] .xp-card { + grid-template-columns: 72px minmax(0, 1fr) auto; + column-gap: 20px; + padding: 18px 8px; + } + + .xp-list[data-view='list'] .xp-card:not([data-on]) .xp-detail { + position: relative; + display: block; + margin-top: 0.35rem; + } + + .xp-list[data-view='list'] + .xp-card:not([data-on]) + .xp-detail + > :not(.xp-desc, .xp-more) { + display: none; + } +} + +/* ---------- The Close-Up ---------- + Two skeletons, one change, as in the reference demo. The explorer gets + `data-open`: the archive folds into a filmstrip beside the close-up (the + page scrolls it, so nothing in flight is ever clipped by a scroller), the + close-up sticks under the toolbar, and the open card's artwork, facts + line and title re-target to the close-up's slots on three delays. The + artwork turns over one level below the box that travels; the strip leans + back in space. */ + +.xp-stage { + --xp-strip: 112px; + --xp-cu-top: calc(var(--xp-stick) + var(--xp-bar-h, 112px)); + --xp-cu-h: calc( + 100dvh - var(--xp-cu-top) - var(--dock-h) - var(--tabbar-h) - 12px + ); + /* The filmstrip leans back in space, set back to 91% (as 90px deep under + its 900px perspective). Its perspective and vantage are in a cell's + own width (cqi), so a cell folding back into the wall, laid out at its + new size and scaled from its old one, is seen as it was: 900px, and + 3.4 cells to the left of a 112px cell. */ + --xp-lean-r: y -26deg; + --xp-lean-s: 0.91; + --xp-depth: 804cqi; + --xp-vantage-x: -340cqi; + --xp-vantage-y: 50%; + --xp-spring-1: linear( + 0, + 0.012, + 0.044, + 0.09, + 0.147, + 0.211, + 0.278, + 0.346, + 0.414, + 0.48, + 0.542, + 0.601, + 0.656, + 0.706, + 0.752, + 0.792, + 0.829, + 0.861, + 0.888, + 0.912, + 0.933, + 0.951, + 0.965, + 0.977, + 0.987, + 0.995, + 1.001, + 1.006, + 1.01, + 1.012, + 1.014, + 1.015, + 1.015, + 1.015, + 1.015, + 1.014, + 1.013, + 1.012, + 1.011, + 1.01, + 1.009, + 1.008, + 1.007, + 1.006, + 1.006, + 1.005, + 1.004, + 1.003, + 1 + ); +} + +@media (min-width: 1024px) { + .xp-stage { + --xp-cu-h: calc(100dvh - var(--xp-cu-top) - var(--dock-h) - 16px); + } +} + +/* The card on its way home flies over the rows it passes. */ +.xp-card[data-swap]:not([data-on]) { + z-index: 3; +} + +/* The parts that open and close travel a little longer, still straight + (across and down on one clock and curve). Opening, the artwork grows + slowly at first (in and out), so the facts line and title are mostly + clear of it before it covers where they were; closing, it shrinks + at once, before they arrive home under it. The turn and the title's + tumble keep their spring. */ +.xp-card[data-swap] { + --flip-dx: 0.6s; + --flip-dy: 0.6s; + --flip-ds: 0.6s; + --xp-turn-d: 0.85s; +} + +.xp-card[data-swap][data-on] { + --flip-es: cubic-bezier(0.65, 0, 0.35, 1); +} + +.xp-closeup { + display: none; +} + +.xp[data-open] .xp-stage { + grid-template-columns: minmax(0, 1fr) var(--xp-strip); + column-gap: clamp(52px, 5.4vw, 84px); + align-items: start; +} + +.xp[data-open] .xp-closeup { + position: sticky; + top: var(--xp-cu-top); + z-index: 2; + grid-row: 1; + grid-column: 1; + display: grid; + /* The picture leads: it takes whatever the column of text leaves it, as + tall as the close-up allows. */ + grid-template-columns: minmax(0, 1fr) clamp(17rem, 36%, 26rem); + grid-template-areas: 'art col'; + gap: 0 clamp(28px, 3.4vw, 56px); + align-items: center; + height: var(--xp-cu-h); + min-height: 420px; +} + +/* Light from the open artwork (prop-for-that img-color), behind it. */ +.xp-cu-glow { + grid-area: art; + z-index: -1; + align-self: center; + aspect-ratio: 1; + scale: 1.25; + background: radial-gradient( + closest-side, + color-mix( + in oklch, + var(--live-img-accent, transparent) var(--xp-glow, 40%), + transparent + ), + transparent + ); + pointer-events: none; +} + +/* The close-up floats toward you, so its slot leaves room for the + perspective. */ +.xp-cu-art { + grid-area: art; + justify-self: center; + width: min(100% - 24px, var(--xp-cu-h) - 48px); + aspect-ratio: 1; + margin: 24px 4px 24px 20px; + anchor-name: --xp-d-art; +} + +.xp-cu-col { + grid-area: col; + display: flex; + flex-direction: column; + align-self: stretch; + min-height: 0; + padding-block: clamp(20px, 9vh, 96px) 12px; +} + +/* Invisible copies of the facts line and the title, at the close-up's + size, so their slots are exactly as big as what lands in them. (What + lands in them sets `position-visibility: always`: an invisible anchor + would otherwise hide it.) */ +.xp-cu-facts { + visibility: hidden; + margin: 0 0 0.6rem; + anchor-name: --xp-d-inf; +} + +.xp-cu-title { + visibility: hidden; + margin: 0 0 1.1rem; + anchor-name: --xp-d-ttl; +} + +.xp-cu-facts, +.xp-card[data-on] .xp-facts { + flex-wrap: wrap; + font-size: 0.875rem; + letter-spacing: 0.02em; + white-space: normal; +} + +.xp-card[data-on] .xp-facts { + width: anchor-size(width); +} + +/* The close-up's title grows with its column, which follows the stage's + width. --xp-w doesn't inherit (a width change would restyle everything + under it): the script writes it on the stage, the grid and these two + titles, the only places that size from it. */ +.xp-cu-title, +.xp-card[data-on] .xp-title { + --xp-cu-title-size: clamp( + 1.4rem, + (var(--xp-w) - var(--xp-strip) - 84px) * 0.036, + 3rem + ); + font-size: var(--xp-cu-title-size); + line-height: 0.96; + letter-spacing: -0.01em; +} + +.xp-cu-detail { + flex: 1 1 0; + min-height: 140px; + anchor-name: --xp-d-col; +} + +/* Narrower stages (a tablet, or a desktop with the sidebar open): the + picture keeps most of the width, the facts and title beside it and the + detail beneath, as on a phone, with the strip still at the side. */ +@container xp (40rem <= width < 56rem) { + .xp-stage { + --xp-tag-size: 3.8cqi; + } + + .xp-cu-title, + .xp-card[data-on] .xp-title { + --xp-cu-title-size: clamp( + 1.2rem, + (var(--xp-w) - var(--xp-strip)) * 0.04, + 1.75rem + ); + } + + .xp[data-open] .xp-closeup { + grid-template-columns: minmax(0, 58%) minmax(0, 1fr); + grid-template-rows: auto auto auto minmax(0, 1fr); + grid-template-areas: + 'art facts' + 'art title' + 'art .' + 'detail detail'; + align-items: start; + gap: 16px 20px; + } + + .xp-cu-art { + justify-self: start; + width: min(100%, var(--xp-cu-h) - 200px); + margin: 8px 0 0; + } + + .xp-cu-col { + display: contents; + } + + .xp-cu-facts { + grid-area: facts; + margin: 8px 0 0.4rem; + } + + .xp-cu-title { + grid-area: title; + margin: 0; + } + + .xp-cu-detail { + grid-area: detail; + align-self: stretch; + min-height: 0; + } +} + +/* ---------- The open card's parts, in their close-up slots ---------- */ + +.xp-stage .xp-card[data-on] { + /* Its parts are positioned against the stage, so the card may not be a + containing block or clip them. */ + position: static; + content-visibility: visible; + contain: none; +} + +.xp-card[data-on]::after { + display: none; +} + +/* The text block comes apart: its facts line and title leave on their own. */ +.xp-card[data-on] .xp-text { + display: contents; +} + +.xp-card[data-on] .xp-art { + position: absolute; + z-index: 4; + position-anchor: --xp-d-art; + top: anchor(top); + left: anchor(left); + width: anchor-size(width); + height: anchor-size(height); +} + +.xp-card[data-on] .xp-turn { + rotate: y 180deg; +} + +.xp-card[data-on] .xp-facts { + position: absolute; + z-index: 4; + position-visibility: always; + position-anchor: --xp-d-inf; + top: anchor(top); + left: anchor(left); + margin: 0; +} + +.xp-cu-facts :is(.xp-facts-length, .xp-facts-kind), +.xp-card[data-on] :is(.xp-facts-length, .xp-facts-kind) { + display: inline; + opacity: 1; +} + +@starting-style { + .xp-card[data-on] :is(.xp-facts-length, .xp-facts-kind) { + opacity: 0; + } +} + +.xp-card[data-on] .xp-title { + position: absolute; + z-index: 5; + position-visibility: always; + position-anchor: --xp-d-ttl; + top: anchor(top); + left: anchor(left); + width: anchor-size(width); + transform-origin: 50% 50%; +} + +/* The title tumbles one turn on its way up, as in the demo. */ +.xp-card:is([data-on], [data-swap]) .xp-title { + perspective: 900px; +} + +.xp-card:is([data-on], [data-swap]) .xp-title a { + backface-visibility: hidden; +} + +.xp-card[data-on] .xp-title a { + -webkit-line-clamp: unset; + rotate: x 360deg; +} + +:is(.xp-card[data-on], .xp-fading-detail) .xp-detail { + position: absolute; + z-index: 4; + position-anchor: --xp-d-col; + top: anchor(top); + left: anchor(left); + display: block; + width: anchor-size(width); + height: anchor-size(height); + overflow: auto; + overscroll-behavior: contain; +} + +:is(.xp-card[data-on], .xp-fading-detail) .xp-desc { + max-width: 62ch; + margin-bottom: 1.1rem; + -webkit-line-clamp: unset; +} + +:is(.xp-card[data-on], .xp-fading-detail) .xp-more { + display: none; +} + +:is(.xp-card[data-on], .xp-fading-detail) .xp-people { + display: flex; +} + +:is(.xp-card[data-on], .xp-fading-detail) .xp-resume:not([hidden]) { + display: block; +} + +:is(.xp-card[data-on], .xp-fading-detail) .xp-actions { + display: flex; +} + +/* The play disc lands in the detail's row of actions. */ +:is(.xp-card[data-on], .xp-fading-detail) .xp-play-slot { + display: block; + flex: none; + width: 44px; + height: 44px; +} + +.xp-card[data-on] .xp-play-slot { + anchor-name: --xp-d-play; +} + +.xp-card[data-on] .xp-play { + position: absolute; + z-index: 5; + position-anchor: --xp-d-play; + top: anchor(top); + left: anchor(left); + margin: 0; + position-visibility: anchors-visible; +} + +/* Copies of re-wrapped text fading where they stood (explorer.ts), out of + every flow, styled as the list they left (data-view). */ +.xp-fading-text { + position: absolute; + inset: 0; + pointer-events: none; +} + +.xp-fading-card { + display: contents; +} + +/* A copy of the detail fading where it stood as the close-up closes + (explorer.ts), out of every flow, styled as the open card's detail. */ +.xp-fading-detail { + position: fixed; + inset: 0; + z-index: 4; + contain: strict; + pointer-events: none; +} + +/* The detail column rises in, line after line, from the tree. */ +.xp-card[data-on] .xp-detail > * { + animation: xp-rise calc(600ms * var(--slomo)) cubic-bezier(0.2, 0.8, 0.2, 1) + backwards; + animation-delay: calc(400ms * var(--slomo)); + animation-delay: calc( + (220ms + min(sibling-index() - 1, 5) * 90ms) * var(--slomo) + ); +} + +.xp-card[data-on] .xp-people > li { + animation: xp-rise calc(500ms * var(--slomo)) cubic-bezier(0.2, 0.8, 0.2, 1) + backwards; + animation-delay: calc(460ms * var(--slomo)); + animation-delay: calc( + (400ms + min(sibling-index() - 1, 8) * 40ms) * var(--slomo) + ); +} + +@keyframes xp-rise { + from { + opacity: 0; + translate: 0 14px; + } +} + +.xp-resume { + margin: 0 0 1rem; + color: var(--accent-ink); + font-size: 0.875rem; + font-weight: 650; +} + +.xp-actions { + flex-wrap: wrap; + align-items: center; + gap: 10px; + padding-bottom: 6px; +} + +.xp-actions .button-secondary { + padding: 0.6rem 1.1rem; + font-size: 0.875rem; +} + +.xp-queue svg { + flex: none; +} + +.xp-queue[aria-pressed='true'] { + border-color: transparent; + background: var(--accent-soft); + color: var(--accent-ink); +} + +.xp-close { + margin-left: auto; +} + +/* ---------- The filmstrip: every other card, small, leaning back ---------- */ + +.xp[data-open] .xp-stage .xp-list { + --xp-span: 1; + grid-row: 1; + grid-column: 2; + grid-template-columns: minmax(0, 1fr); + grid-auto-rows: var(--xp-strip); + gap: 16px; + padding-block: 4px; +} + +.xp[data-open] .xp-list::before, +.xp[data-open] .xp-card::after { + display: none; +} + +.xp[data-open] .xp-card { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: 'art'; + margin: 0; + padding: 0; + /* A leaning cell reaches past its box; its paint containment may not + cut it off. */ + overflow-clip-margin: 48px; +} + +.xp[data-open] .xp-card:not([data-on]) :is(.xp-text, .xp-play) { + position: absolute; + bottom: 6px; + left: 8px; + width: calc(var(--xp-strip) - 16px); + opacity: 0; + pointer-events: none; +} + +/* The text, re-wrapped to the strip's width, goes at once: a copy of it as + it was fades out where it stood (explorer.ts). */ +.xp[data-open] .xp-card:not([data-on]) .xp-text { + --also: visibility 0s; +} + +/* Once the fold has landed they leave the page, out of the tab order. */ +.xp[data-open]:not([data-folding]) + .xp-card:not([data-on]) + :is(.xp-text, .xp-play) { + display: none; +} + +/* Folding back into the wall, they fade in where they land. */ +@starting-style { + .xp[data-folding]:not([data-open]) .xp-card :is(.xp-text, .xp-play) { + opacity: 0; + } +} + +.xp[data-open] .xp-card:not([data-on]) .xp-detail, +.xp[data-open] .xp-card:not([data-on]) .xp-chip { + display: none; +} + +/* The lean, the strip's corners and its vantage belong to the open state: + folding back, the cells straighten up in depth, and give their depth + back once they have landed (explorer.ts). */ +.xp[data-open] .xp-card[data-depth]:not([data-on]) .xp-turn { + rotate: var(--xp-lean-r); + scale: var(--xp-lean-s); +} + +.xp[data-open] .xp-card:not([data-on]) .xp-art { + --r: var(--r-thumb); +} + +/* The strip is seen from the middle of the page: as a cell scrolls past, + the point it is seen from moves across it (a view() timeline), so cells + above the middle tilt up and cells below tilt down, as on the demo's one + stage. Nothing runs off screen. */ +@supports (animation-timeline: view()) { + @media (prefers-reduced-motion: no-preference) { + .xp[data-open] .xp-card[data-depth]:not([data-on]) .xp-tilt { + animation: xp-vantage linear both; + animation-timeline: view(); + animation-range: cover 0% cover 100%; + } + } +} + +@keyframes xp-vantage { + from { + perspective-origin: var(--xp-vantage-x) -50vh; + } + + to { + perspective-origin: var(--xp-vantage-x) calc(50vh + var(--xp-strip)); + } +} + +/* ---------- Phones: the close-up on top, the strip along the bottom ---------- + An upright phone (the explorer under 40rem, its own breakpoint) and a + phone on its side (the shared landscape form) both mark the stage + (--xp-phone), and share one close-up: the artwork with the facts line + and the title beside it, the close button in the corner, three lines of + description and one row of actions, as tall as that and no taller, and + the strip one row of thumbnails under it that scrolls sideways (and + snaps). With the strip a row, the folded archive is short: the + close-up scrolls with the page (stuck, the strip would only slide under + it), and the page brings it up under the toolbar (explorer.ts). */ + +@container xp (width < 40rem) { + .xp-cu-title, + .xp-card[data-on] .xp-title { + --xp-cu-title-size: clamp(1.15rem, 0.8rem + 1.6vw, 1.5rem); + } + + .xp-stage { + --xp-phone: 1; + --xp-tag-size: 6.5cqi; + --xp-strip: 72px; + /* As 30px deep, 900px and 2.6 cells above, for a cell about 80px wide. */ + --xp-lean-r: x 24deg; + --xp-lean-s: 0.97; + --xp-depth: 1125cqi; + --xp-vantage-x: 50%; + --xp-vantage-y: -260cqi; + } + + /* (With the room the page needs under the strip: explorer.ts.) */ + .xp[data-open] .xp-stage { + grid-template-columns: minmax(0, 1fr); + align-content: start; + padding-bottom: var(--xp-room, 0px); + } +} + +@media (orientation: landscape) and (max-height: 500px) { + .xp-cu-title, + .xp-card[data-on] .xp-title { + --xp-cu-title-size: 1.25rem; + } + + .xp-stage { + --xp-phone: 1; + --xp-tag-size: 6.5cqi; + --xp-strip: 72px; + --xp-lean-r: x 24deg; + --xp-lean-s: 0.97; + --xp-depth: 1125cqi; + --xp-vantage-x: 50%; + --xp-vantage-y: -260cqi; + } + + .xp[data-open] .xp-stage { + grid-template-columns: minmax(0, 1fr); + align-content: start; + padding-bottom: var(--xp-room, 0px); + } +} + +@container style(--xp-phone: 1) { + .xp[data-open] .xp-card[data-depth]:not([data-on]) .xp-tilt { + animation: none; + } + + /* Three lines of description, a line to resume from (when there is + one), and the row of actions. */ + .xp-closeup { + --xp-cu-body-h: calc(3 * 0.9375rem * 1.5 + 12px + 44px); + } + + .xp-closeup[data-resume] { + --xp-cu-body-h: calc( + 3 * 0.9375rem * 1.5 + 12px + 0.875rem * 1.4 + 8px + 44px + ); + } + + .xp[data-open] .xp-closeup { + grid-template-columns: 44% minmax(0, 1fr); + grid-template-rows: auto auto 1fr var(--xp-cu-body-h); + grid-template-areas: + 'art facts' + 'art title' + 'art .' + 'body body'; + align-items: start; + gap: 0 16px; + position: relative; + top: auto; + height: auto; + min-height: 0; + padding-bottom: 14px; + } + + .xp-cu-glow { + display: none; + } + + .xp-cu-art { + width: 100%; + margin: 4px 0 14px; + } + + .xp-cu-col { + display: contents; + } + + /* The facts line leaves the corner to the close button, and the title + starts under it. */ + .xp-cu-facts { + grid-area: facts; + min-height: 34px; + margin: 4px 52px 0.4rem 0; + } + + .xp-cu-title { + grid-area: title; + margin: 0 0 14px; + } + + /* The detail spans the whole close-up: the close button in its top + corner, the description and the actions along its foot (the last + row's height is theirs). It lets taps through to the art and title + under its empty part. */ + .xp-cu-detail { + grid-area: 1 / 1 / -1 / -1; + align-self: stretch; + height: auto; + min-height: 0; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-detail { + display: flex; + flex-direction: column; + justify-content: flex-end; + overflow: visible; + pointer-events: none; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-detail > * { + pointer-events: auto; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-desc { + flex: none; + max-width: none; + min-height: 3lh; + margin: 0 0 12px; + -webkit-line-clamp: 3; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-people { + display: none; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-resume:not([hidden]) { + flex: none; + margin: 0 0 8px; + overflow: hidden; + line-height: 1.4; + text-overflow: ellipsis; + white-space: nowrap; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-actions { + flex: none; + flex-wrap: nowrap; + gap: 8px; + padding: 0; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-actions .button-secondary { + min-height: 44px; + padding-inline: 1rem; + white-space: nowrap; + } + + /* "Up next", "Open": the rest is still their name. */ + :is(.xp-card[data-on], .xp-fading-detail) .xp-long { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } + + .xp-resume .xp-long { + display: none; + } + + :is(.xp-card[data-on], .xp-fading-detail) .xp-close { + position: absolute; + top: 0; + right: 0; + width: 44px; + height: 44px; + margin: 0; + } + + /* The actions rise one by one (the row itself holds still: it is what the + close button is placed against while it rises). */ + .xp-card[data-on] .xp-detail > .xp-actions { + animation: none; + } + + .xp-card[data-on] .xp-actions > * { + animation: xp-rise calc(600ms * var(--slomo)) cubic-bezier(0.2, 0.8, 0.2, 1) + backwards; + animation-delay: calc(400ms * var(--slomo)); + animation-delay: calc( + (400ms + min(sibling-index() - 1, 4) * 60ms) * var(--slomo) + ); + } + + /* The strip: one row of thumbnails under the close-up, reaching the + screen's sides, that scrolls sideways and comes to rest with a cell at + its start. (Near one: only the cells around the view are laid out, and + a fling past them may not be pulled back to the last.) While the + archive folds into it, it isn't a scroller yet (the cards flying into + it would be clipped): it is laid out shifted along by what it will + scroll to (explorer.ts). */ + .xp[data-open] .xp-stage .xp-list { + --xp-span: 1; + grid-row: 2; + grid-column: 1; + grid-auto-flow: column; + grid-template-columns: none; + grid-template-rows: var(--xp-strip); + grid-auto-columns: var(--xp-strip); + gap: 12px; + margin-inline: calc(var(--gutter) * -1); + padding: 14px var(--gutter) 18px; + overflow-x: auto; + overflow-y: hidden; + overscroll-behavior-x: contain; + scroll-snap-type: x proximity; + scroll-padding-inline: var(--gutter); + scrollbar-width: none; + } + + .xp[data-open][data-folding] .xp-stage .xp-list { + margin-inline-start: calc(var(--gutter) * -1 - var(--xp-strip-x, 0px)); + overflow: visible; + } + + .xp[data-open] .xp-stage .xp-card { + scroll-snap-align: start; + } + + .xp[data-open] .xp-stage .xp-park { + grid-row: 1; + grid-column: span var(--xp-rows, 1); + } +} + +/* On its side the picture takes the close-up's height, and the words, the + description and the actions stand beside it, the close button in their + corner. */ +@media (orientation: landscape) and (max-height: 500px) { + .xp[data-open] .xp-closeup { + grid-template-columns: clamp(120px, 26%, 220px) minmax(0, 1fr); + grid-template-areas: + 'art facts' + 'art title' + 'art .' + 'art body'; + } + + .xp[data-open] .xp-closeup { + padding-bottom: 8px; + } + + .xp-cu-art { + margin: 4px 0 0; + } + + /* The words are a line or two wide here: both leave the corner to the + close button. */ + .xp-cu-facts { + min-height: 0; + margin: 4px 52px 0.3rem 0; + } + + .xp-cu-title { + margin: 0 52px 8px 0; + } + + .xp-cu-detail { + grid-area: 1 / 2 / -1 / -1; + } +} + +/* ---------- Without anchor positioning: a plain detail view ---------- + No travel: the open card spans the archive in place, artwork beside its + text and detail, and the archive stays as it was. */ +@supports not (position-anchor: --xp) { + .xp[data-open] .xp-stage { + grid-template-columns: minmax(0, 1fr); + } + + .xp[data-open] .xp-closeup { + display: none; + } + + .xp[data-open] .xp-stage .xp-list { + grid-column: 1; + } + + .xp-card[data-on] { + grid-column: 1 / -1; + grid-row: span 2; + grid-template-columns: minmax(0, 0.8fr) minmax(0, 1fr); + grid-template-rows: auto minmax(0, 1fr); + grid-template-areas: + 'art text' + 'art detail'; + position: relative; + } + + .xp-card[data-on] :is(.xp-art, .xp-facts, .xp-title, .xp-detail, .xp-play) { + position: static; + width: auto; + height: auto; + } + + .xp-card[data-on] .xp-art { + height: 100%; + } + + .xp-card[data-on] .xp-text { + display: block; + block-size: auto; + } + + .xp-card[data-on] .xp-detail { + overflow: visible; + } + + .xp-card[data-on] .xp-play { + grid-area: art; + margin: 12px; + } +} + +/* ---------- Coming and going ---------- + Cards that join a cut fade up into their cell; cards that leave it fade + out where they stood, out of the flow, so the rest close ranks at once. */ + +.xp[data-live] .xp-card { + transition: + opacity calc(320ms * var(--slomo)) var(--ease-out) + calc(140ms * var(--slomo)), + scale calc(480ms * var(--slomo)) var(--ease-out) calc(140ms * var(--slomo)), + display calc(460ms * var(--slomo)) allow-discrete; +} + +@starting-style { + .xp[data-live] .xp-card[data-join] { + opacity: 0; + scale: 0.9; + } +} + +.xp-card[hidden] { + display: none; + opacity: 0; + scale: 0.9; +} + +.xp[data-live] .xp-card[hidden] { + transition-delay: 0s; + transition-duration: calc(240ms * var(--slomo)); +} + +.xp[data-live] .xp-card[hidden]:not([data-exit]) { + transition: none; +} + +/* A card still shown whose new place is out of the window fades out the + same way, then goes to its parked block. */ +.xp[data-live] .xp-card[data-away] { + opacity: 0; + scale: 0.9; + transition-delay: 0s; + transition-duration: calc(240ms * var(--slomo)); +} + +.xp-card:is([hidden][data-exit], [data-away]) { + position: absolute; + z-index: -1; + top: var(--xp-y); + left: var(--xp-x); + width: var(--xp-w); + height: var(--xp-h); + margin: 0; + pointer-events: none; +} + +/* Its text clears first, in 120ms (LEAVE_MS, explorer.ts), before any card + arriving in its place comes up, so two cards' words never read over each + other in one cell; its picture fades on. */ +.xp-card:is([hidden][data-exit], [data-away]) .xp-text { + opacity: 0; + --also: opacity calc(120ms * var(--slomo)) ease-out; +} + +/* A page that arrives with a query waits for it to be applied; should the + script never run, the archive shows anyway. */ +:root[data-xp-pending] .xp :is(.xp-list, .xp-empty) { + animation: xp-pending 3s steps(1) both; +} + +@keyframes xp-pending { + from { + opacity: 0; + } +} + +/* ---------- Nothing matches ---------- */ + +.xp-empty { + display: flex; + flex-direction: column; + align-items: center; + gap: 1rem; + padding: 1rem 0 3rem; + color: var(--text); + text-align: center; +} + +.xp-empty[hidden] { + display: none; +} + +.xp-empty p { + margin: 0; + max-width: 40ch; +} diff --git a/tests/unit/explorer-query.test.ts b/tests/unit/explorer-query.test.ts new file mode 100644 index 00000000..87f8e334 --- /dev/null +++ b/tests/unit/explorer-query.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest'; +import { + compare, + DEFAULT_STATE, + isFiltered, + matches, + parseState, + toSearch, + type ExplorerEntry +} from 'starpod/src/components/explorer/query'; + +const entry = (overrides: Partial = {}): ExplorerEntry => ({ + index: 0, + duration: 3600, + people: ['robbiethewagner', 'argyleink'], + position: 0, + text: 'css container queries with chris coyier', + video: true, + year: '2024', + ...overrides +}); + +describe('explorer query', () => { + it('reads every documented parameter', () => { + expect( + parseState( + '?q=%20css%20&kind=audio&guest=chriscoyier&year=2023&progress=1&sort=longest&view=list' + ) + ).toEqual({ + q: 'css', + kind: 'audio', + guest: 'chriscoyier', + year: '2023', + progress: true, + sort: 'longest', + view: 'list' + }); + }); + + it('falls back to defaults for missing or unknown values', () => { + expect(parseState('?kind=vinyl&sort=random&view=table&year=next')).toEqual( + DEFAULT_STATE + ); + }); + + it('leaves defaults out of the URL', () => { + expect(toSearch(DEFAULT_STATE)).toBe(''); + expect(toSearch({ ...DEFAULT_STATE, kind: 'video', view: 'list' })).toBe( + '?kind=video&view=list' + ); + }); + + it('round-trips through the URL', () => { + const state = parseState('?q=ai&guest=argyleink&sort=oldest'); + expect(parseState(toSearch(state))).toEqual(state); + }); + + it('knows sort and view only rearrange', () => { + expect(isFiltered({ ...DEFAULT_STATE, sort: 'oldest', view: 'list' })).toBe( + false + ); + expect(isFiltered({ ...DEFAULT_STATE, year: '2024' })).toBe(true); + }); + + it('matches every word of a search, in any order', () => { + expect(matches(entry(), { ...DEFAULT_STATE, q: 'Coyier CSS' })).toBe(true); + expect(matches(entry(), { ...DEFAULT_STATE, q: 'css grid' })).toBe(false); + }); + + it('filters by kind, year, person and progress', () => { + expect(matches(entry(), { ...DEFAULT_STATE, kind: 'audio' })).toBe(false); + expect( + matches(entry({ video: false }), { ...DEFAULT_STATE, kind: 'audio' }) + ).toBe(true); + expect(matches(entry(), { ...DEFAULT_STATE, year: '2025' })).toBe(false); + expect(matches(entry(), { ...DEFAULT_STATE, guest: 'argyleink' })).toBe( + true + ); + expect(matches(entry(), { ...DEFAULT_STATE, guest: 'chriscoyier' })).toBe( + false + ); + expect( + matches(entry({ position: 12 }), { ...DEFAULT_STATE, progress: true }) + ).toBe(false); + expect( + matches(entry({ position: 600 }), { ...DEFAULT_STATE, progress: true }) + ).toBe(true); + }); + + it('sorts newest, oldest, longest and shortest', () => { + const a = entry({ index: 0, duration: 1800 }); + const b = entry({ index: 1, duration: 5400 }); + const c = entry({ index: 2, duration: 3600 }); + const order = (sort: Parameters[0]) => + [c, a, b].sort(compare(sort)).map((e) => e.index); + expect(order('newest')).toEqual([0, 1, 2]); + expect(order('oldest')).toEqual([2, 1, 0]); + expect(order('longest')).toEqual([1, 2, 0]); + expect(order('shortest')).toEqual([0, 2, 1]); + }); +}); From c799f2fe450e3cea76c6b750b550e857817a2d9d Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Fri, 20 Nov 2026 10:42:48 -0500 Subject: [PATCH 02/10] Keep the open card's parts on their slots in Firefox The close-up sticks under the toolbar, and the open card's artwork, facts, title, detail and play are anchored to slots inside it. Firefox resolves those anchors as if the close-up weren't stuck, so once the page has scrolled (opening a card scrolls it) the parts sat off their slots by the close-up's sticky offset: 54px in CI. A still, invisible marker anchored like the artwork shows where the browser puts it; on opening, scrolling and resizing the explorer measures it against the slot and the parts make up the gap through --xp-cu-fix. Where anchors follow a stuck box the gap is 0 and nothing changes. Co-Authored-By: Claude Opus 5.5 --- .../src/components/explorer/explorer.ts | 35 +++++++++++++++++++ packages/starpod/src/styles/explorer.css | 23 +++++++++--- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/packages/starpod/src/components/explorer/explorer.ts b/packages/starpod/src/components/explorer/explorer.ts index 04e3ae09..cf2fd75a 100644 --- a/packages/starpod/src/components/explorer/explorer.ts +++ b/packages/starpod/src/components/explorer/explorer.ts @@ -1813,6 +1813,7 @@ export function startExplorer() { } open = next; root.toggleAttribute('data-open', Boolean(next)); + requestAnimationFrame(mendAnchors); }, { place: () => { @@ -2125,6 +2126,40 @@ export function startExplorer() { list.addEventListener('scroll', onScroll, { passive: true, signal }); signal.addEventListener('abort', () => clearTimeout(settle)); + // Firefox resolves the open card's anchors as if the close-up weren't + // stuck: once the page has scrolled, its artwork, facts and title sit off + // their slots by the close-up's sticky offset. A still, invisible marker + // anchored like the artwork shows where the browser puts it; the parts + // make up any gap from the slot (--xp-cu-fix, explorer.css). Where anchors + // follow a stuck box the gap is 0. + const cuArt = closeup.querySelector('.xp-cu-art'); + const marker = document.createElement('i'); + marker.className = 'xp-anchor-marker'; + marker.setAttribute('aria-hidden', 'true'); + stage.append(marker); + let anchorFix = 0; + function mendAnchors() { + const gap = + open && cuArt + ? Math.round( + cuArt.getBoundingClientRect().top - + marker.getBoundingClientRect().top + ) + : 0; + // A pixel either way is a sticky offset's rounding, not a gap. + const fix = Math.abs(gap) > 1 ? gap : 0; + if (fix !== anchorFix) { + anchorFix = fix; + if (fix) { + stage.style.setProperty('--xp-cu-fix', `${fix}px`); + } else { + stage.style.removeProperty('--xp-cu-fix'); + } + } + } + addEventListener('scroll', mendAnchors, { passive: true, signal }); + addEventListener('resize', mendAnchors, { passive: true, signal }); + // A card's controls carry a scroll margin that clears the sticky toolbar // and the dock (explorer.css). Chromium honours it when focus scrolls a // control into view; Firefox doesn't scroll a control that is only partly diff --git a/packages/starpod/src/styles/explorer.css b/packages/starpod/src/styles/explorer.css index e6e33922..962797c2 100644 --- a/packages/starpod/src/styles/explorer.css +++ b/packages/starpod/src/styles/explorer.css @@ -2641,6 +2641,19 @@ /* ---------- The open card's parts, in their close-up slots ---------- */ +/* Where the browser puts something anchored to the artwork's slot, kept + still so the explorer can measure it against the slot (mendAnchors). */ +.xp-anchor-marker { + position: absolute; + position-anchor: --xp-d-art; + top: anchor(top, 0px); + left: 0; + width: 0; + height: 0; + visibility: hidden; + pointer-events: none; +} + .xp-stage .xp-card[data-on] { /* Its parts are positioned against the stage, so the card may not be a containing block or clip them. */ @@ -2662,7 +2675,7 @@ position: absolute; z-index: 4; position-anchor: --xp-d-art; - top: anchor(top); + top: calc(anchor(top) + var(--xp-cu-fix, 0px)); left: anchor(left); width: anchor-size(width); height: anchor-size(height); @@ -2677,7 +2690,7 @@ z-index: 4; position-visibility: always; position-anchor: --xp-d-inf; - top: anchor(top); + top: calc(anchor(top) + var(--xp-cu-fix, 0px)); left: anchor(left); margin: 0; } @@ -2699,7 +2712,7 @@ z-index: 5; position-visibility: always; position-anchor: --xp-d-ttl; - top: anchor(top); + top: calc(anchor(top) + var(--xp-cu-fix, 0px)); left: anchor(left); width: anchor-size(width); transform-origin: 50% 50%; @@ -2723,7 +2736,7 @@ position: absolute; z-index: 4; position-anchor: --xp-d-col; - top: anchor(top); + top: calc(anchor(top) + var(--xp-cu-fix, 0px)); left: anchor(left); display: block; width: anchor-size(width); @@ -2770,7 +2783,7 @@ position: absolute; z-index: 5; position-anchor: --xp-d-play; - top: anchor(top); + top: calc(anchor(top) + var(--xp-cu-fix, 0px)); left: anchor(left); margin: 0; position-visibility: anchors-visible; From 53d275b948b12ee214fde1531541bf9e2a6680a3 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Sat, 21 Nov 2026 07:32:43 -0500 Subject: [PATCH 03/10] Show the close-up's resume line by the engine's resume rule It showed from 30s on, where the engine resumes only past 30s (resumePoint, from #79's review). Co-Authored-By: Claude Opus 5.5 --- packages/starpod/src/components/explorer/explorer.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/starpod/src/components/explorer/explorer.ts b/packages/starpod/src/components/explorer/explorer.ts index cf2fd75a..7d88e6cb 100644 --- a/packages/starpod/src/components/explorer/explorer.ts +++ b/packages/starpod/src/components/explorer/explorer.ts @@ -32,7 +32,7 @@ import { reducedMotion, type FlipRect } from '../../motion/propflip'; -import { readPosition } from '../media/position'; +import { readPosition, resumePoint } from '../media/position'; import { currentEpisode, dequeue, @@ -1572,8 +1572,9 @@ export function startExplorer() { } function fillResume(card: Card) { - const seconds = readPosition(card.li.dataset.id!); - resume.hidden = seconds < 30; + // Shown only where Play would pick up (the engine's rule). + const seconds = resumePoint(card.li.dataset.id!); + resume.hidden = !seconds; // (A phone's close-up leaves out the long part: explorer.css.) const rest = document.createElement('span'); rest.className = 'xp-long'; From 8ea56610954f6009b306d3b60a126fa75e14ff52 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Sat, 21 Nov 2026 07:47:34 -0500 Subject: [PATCH 04/10] Measure the close-up's anchor gap in a frame, confirmed over two In CI's Chromium the correction for Firefox's anchors sometimes fired: a measurement in the scroll event can read the marker before Chromium has moved anchored boxes for the scroll, which showed a 54px gap that wasn't there, and nothing measured again once the scroll stopped. Measurements now run in an animation frame (after scrolls, their end, resizes and opening), and a new correction is taken only when two frames in a row agree on it. Co-Authored-By: Claude Opus 5.5 --- .../src/components/explorer/explorer.ts | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/packages/starpod/src/components/explorer/explorer.ts b/packages/starpod/src/components/explorer/explorer.ts index 7d88e6cb..acb26005 100644 --- a/packages/starpod/src/components/explorer/explorer.ts +++ b/packages/starpod/src/components/explorer/explorer.ts @@ -1814,7 +1814,7 @@ export function startExplorer() { } open = next; root.toggleAttribute('data-open', Boolean(next)); - requestAnimationFrame(mendAnchors); + mendAnchors(); }, { place: () => { @@ -2139,7 +2139,18 @@ export function startExplorer() { marker.setAttribute('aria-hidden', 'true'); stage.append(marker); let anchorFix = 0; + // Measured in a frame, never in the scroll event itself: Chromium moves + // anchored boxes for a scroll a frame later, and read early the marker + // shows a gap that isn't there. A new fix is taken only once two frames + // in a row agree on it. + let mendFrame = 0; + let pendingFix: number | null = null; function mendAnchors() { + cancelAnimationFrame(mendFrame); + mendFrame = requestAnimationFrame(measureAnchors); + } + function measureAnchors() { + mendFrame = 0; const gap = open && cuArt ? Math.round( @@ -2149,17 +2160,27 @@ export function startExplorer() { : 0; // A pixel either way is a sticky offset's rounding, not a gap. const fix = Math.abs(gap) > 1 ? gap : 0; - if (fix !== anchorFix) { - anchorFix = fix; - if (fix) { - stage.style.setProperty('--xp-cu-fix', `${fix}px`); - } else { - stage.style.removeProperty('--xp-cu-fix'); - } + if (fix === anchorFix) { + pendingFix = null; + return; } + if (pendingFix !== fix) { + pendingFix = fix; + mendAnchors(); + return; + } + pendingFix = null; + anchorFix = fix; + if (fix) { + stage.style.setProperty('--xp-cu-fix', `${fix}px`); + } else { + stage.style.removeProperty('--xp-cu-fix'); + } + } + for (const type of ['scroll', 'scrollend', 'resize']) { + addEventListener(type, mendAnchors, { passive: true, signal }); } - addEventListener('scroll', mendAnchors, { passive: true, signal }); - addEventListener('resize', mendAnchors, { passive: true, signal }); + signal.addEventListener('abort', () => cancelAnimationFrame(mendFrame)); // A card's controls carry a scroll margin that clears the sticky toolbar // and the dock (explorer.css). Chromium honours it when focus scrolls a From 9f3403616b55e709c799ae78f3de72bdada61931 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Mon, 23 Nov 2026 07:05:53 -0500 Subject: [PATCH 05/10] Give explorer faces without a photo the light-or-dark avatar Co-Authored-By: Claude Opus 5.5 --- packages/starpod/src/components/explorer/archive.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/starpod/src/components/explorer/archive.ts b/packages/starpod/src/components/explorer/archive.ts index adb16e45..ffcf4a2e 100644 --- a/packages/starpod/src/components/explorer/archive.ts +++ b/packages/starpod/src/components/explorer/archive.ts @@ -10,7 +10,8 @@ import { getImage } from 'astro:assets'; import { eq } from 'drizzle-orm'; import starpodConfig, { database } from 'virtual:starpod/config'; -import avatarLight from '../../assets/avatar-light.png'; +// The face for someone without a photo, light or dark with the page. +import avatar from '../../assets/avatar.svg?url'; import { createDb } from '../../db'; import { HostOrGuest, Person } from '../../db/schema'; import { sortCast, type CastPerson } from '../../lib/cast'; @@ -53,11 +54,12 @@ function avatarFor(img: string | null): Promise { avatars.set( key, (async () => { - const source = - (img && (await photos[`/src/img/people/${img}`]?.())?.default) || - avatarLight; + const photo = img && (await photos[`/src/img/people/${img}`]?.())?.default; + if (!photo) { + return avatar; + } const image = await getImage({ - src: source, + src: photo, width: 64, height: 64, format: 'webp' From d729623bfd451cb4204c9ca620ae76ba46e32ee9 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Tue, 24 Nov 2026 11:51:57 -0500 Subject: [PATCH 06/10] Address CodeRabbit and review on the explorer - Back from an episode comes home to the row it was opened from (card or hero), remembered per episode. - An unreachable guests database leaves the archive without a cast rather than failing the home page; the cast is asked for once. - Details ids come from the card's index, so no two can collide. - A sort that moves cards in the DOM keeps keyboard focus where it was. - A pause updates the loaded card's progress, the In progress count and that cut, from the place the engine saved. - A progress bar clears once an episode is no longer in progress. - The close-up offers no saved resume for the loaded episode, and follows it when the loaded episode changes. - The live play control is unmounted when the page swaps. - In progress follows the engine's resume rule: past 30 seconds. - Without anchor positioning the archive no longer folds into the strip; the card opens in place. - Filter changes keep the address's fragment. Co-Authored-By: Claude Opus 5.5 --- .../starpod/src/components/EpisodeList.astro | 11 ++- .../src/components/explorer/Card.astro | 2 +- .../src/components/explorer/archive.ts | 21 ++++- .../src/components/explorer/explorer.ts | 89 +++++++++++++++---- .../starpod/src/components/explorer/query.ts | 8 +- packages/starpod/src/styles/explorer.css | 18 ++-- tests/unit/explorer-query.test.ts | 6 ++ 7 files changed, 117 insertions(+), 38 deletions(-) diff --git a/packages/starpod/src/components/EpisodeList.astro b/packages/starpod/src/components/EpisodeList.astro index eba01c26..9248a513 100644 --- a/packages/starpod/src/components/EpisodeList.astro +++ b/packages/starpod/src/components/EpisodeList.astro @@ -166,8 +166,10 @@ const { cards, episodes, people, show, years } = Astro.props; let leaving = ''; // The latest episode is both the hero and a card; come home to the one - // you left from. + // you left from. Remembered per episode, as the way back (browser Back, + // or a link on the episode page) has no row to say. let fromCard = false; + const leftFromCard = new Map(); document.addEventListener('astro:before-preparation', (event) => { leaving = event.from.pathname; @@ -177,7 +179,12 @@ const { cards, episodes, people, show, years } = Astro.props; const row = link ? (link.closest('[data-episode-row]') as HTMLElement) : null; - fromCard = Boolean(row?.matches('li')); + if (row) { + fromCard = row.matches('li'); + leftFromCard.set(event.to.pathname, fromCard); + } else { + fromCard = leftFromCard.get(leaving) ?? false; + } name(row); }); diff --git a/packages/starpod/src/components/explorer/Card.astro b/packages/starpod/src/components/explorer/Card.astro index ed4cac98..9aa8e50a 100644 --- a/packages/starpod/src/components/explorer/Card.astro +++ b/packages/starpod/src/components/explorer/Card.astro @@ -16,7 +16,7 @@ const number = episode.episodeNumber === 'Bonus' ? 'Bonus' : episode.episodeNumber; // Sentence case under the title: "Ep 254 · Sep 24, 2026 · 1 hr 21 min". const short = episode.episodeNumber === 'Bonus' ? 'Bonus' : `Ep ${number}`; -const detailId = `xp-detail-${episode.id.replace(/[^a-z0-9]/gi, '')}`; +const detailId = `xp-detail-${card.index}`; const length = formatDuration(episode.duration); const playable = toPlayable(episode, show); // The episode's playable slice, once, on the card itself: the play disc, Up diff --git a/packages/starpod/src/components/explorer/archive.ts b/packages/starpod/src/components/explorer/archive.ts index ffcf4a2e..1237ef97 100644 --- a/packages/starpod/src/components/explorer/archive.ts +++ b/packages/starpod/src/components/explorer/archive.ts @@ -54,7 +54,8 @@ function avatarFor(img: string | null): Promise { avatars.set( key, (async () => { - const photo = img && (await photos[`/src/img/people/${img}`]?.())?.default; + const photo = + img && (await photos[`/src/img/people/${img}`]?.())?.default; if (!photo) { return avatar; } @@ -91,8 +92,22 @@ async function cardArt(src: string | undefined, fallback: string) { } } -/** Each episode's people, keyed by episode slug, when the database is on. */ -async function peopleBySlug(): Promise>> { +let cast: Promise>> | undefined; + +/** + * Each episode's people, keyed by episode slug: asked once, and empty when + * the database is off or out of reach (the cast is extra; the archive is + * not). + */ +function peopleBySlug(): Promise>> { + cast ??= queryPeople().catch((error) => { + console.warn('[starpod] No cast for the archive:', error); + return new Map(); + }); + return cast; +} + +async function queryPeople(): Promise>> { const bySlug = new Map>(); if (!database) { return bySlug; diff --git a/packages/starpod/src/components/explorer/explorer.ts b/packages/starpod/src/components/explorer/explorer.ts index acb26005..d2b61f56 100644 --- a/packages/starpod/src/components/explorer/explorer.ts +++ b/packages/starpod/src/components/explorer/explorer.ts @@ -37,6 +37,7 @@ import { currentEpisode, dequeue, enqueue, + isPlaying, playEpisode, queue, type PlayableEpisode @@ -120,6 +121,11 @@ const WINDOWING = 'onbeforematch' in HTMLElement.prototype && CSS.supports('position-anchor', '--x') && CSS.supports('grid-template-rows', 'subgrid'); +// Without anchor positioning the close-up can't take a card's parts: the +// card opens in place in the archive instead (explorer.css), and the +// archive doesn't fold into the strip. +const ANCHORED = + typeof CSS !== 'undefined' && CSS.supports('position-anchor', '--x'); // A card the shell glides keeps its containment and widens its clip (see // `fly`), where the browser has a clip to widen. const GLIDE_CLIP = @@ -1343,8 +1349,17 @@ export function startExplorer() { order.forEach((card, i) => (card.li.style.order = String(i))); } else if (!windowed) { // Elsewhere the DOM order is the reading order (windowed, the - // window keeps its own in step). + // window keeps its own in step). Moving a card drops the focus in + // it, so that goes back where it was. + const focused = document.activeElement; list.append(...order.map((card) => card.li)); + if ( + focused instanceof HTMLElement && + focused !== document.activeElement && + list.contains(focused) + ) { + focused.focus({ preventScroll: true }); + } } } list.dataset.view = next.view; @@ -1429,8 +1444,8 @@ export function startExplorer() { let lastParam = ''; function remember(next: ExplorerState, param: string) { - const url = location.pathname + toSearch(next); - if (url === location.pathname + location.search) { + const url = location.pathname + toSearch(next) + location.hash; + if (url === location.pathname + location.search + location.hash) { return; } // Consecutive changes to one control (typing, arrowing through a menu) @@ -1448,17 +1463,26 @@ export function startExplorer() { * saving it as they listen): progress bars, and the In progress chip. */ function readProgress(next = state) { - let started = 0; for (const card of cards) { - card.entry.position = readPosition(card.li.dataset.id!); - if (inProgress(card.entry)) { - started++; - card.li.style.setProperty( - '--xp-progress', - String(Math.min(card.entry.position / card.entry.duration, 1)) - ); - } + showProgress(card, readPosition(card.li.dataset.id!)); } + countProgress(next); + } + + function showProgress(card: Card, position: number) { + card.entry.position = position; + if (inProgress(card.entry)) { + card.li.style.setProperty( + '--xp-progress', + String(Math.min(position / card.entry.duration, 1)) + ); + } else { + card.li.style.removeProperty('--xp-progress'); + } + } + + function countProgress(next = state) { + const started = cards.filter((card) => inProgress(card.entry)).length; progressButton.hidden = started === 0 && !next.progress; progressButton.querySelector('[data-xp-progress-count]')!.textContent = String(started); @@ -1572,8 +1596,10 @@ export function startExplorer() { } function fillResume(card: Card) { - // Shown only where Play would pick up (the engine's rule). - const seconds = resumePoint(card.li.dataset.id!); + // Shown only where Play would pick up (the engine's rule), and never for + // the loaded episode: its control pauses, or plays on from the playhead. + const id = card.li.dataset.id!; + const seconds = currentEpisode.peek()?.id === id ? 0 : resumePoint(id); resume.hidden = !seconds; // (A phone's close-up leaves out the long part: explorer.css.) const rest = document.createElement('span'); @@ -1813,7 +1839,7 @@ export function startExplorer() { home(next, true); } open = next; - root.toggleAttribute('data-open', Boolean(next)); + root.toggleAttribute('data-open', ANCHORED && Boolean(next)); mendAnchors(); }, { @@ -1884,6 +1910,9 @@ export function startExplorer() { live.li.removeAttribute('data-playing'); } live = card; + if (open) { + fillResume(open); + } if (card) { const disc = card.play.querySelector('[data-static]'); const focused = Boolean(disc) && disc === document.activeElement; @@ -1902,6 +1931,31 @@ export function startExplorer() { }); }); + // A pause saves the place (the engine: where it stopped, or 0 at the + // end), and the loaded card's progress follows: its bar, the In progress + // count, and the cut when that filter is on. Only on a pause, never on a + // tick; read just after, once the engine's own save has landed. + let wasPlaying = isPlaying.peek(); + let saved = 0; + const stopProgress = effect(() => { + const playing = isPlaying.value; + if (wasPlaying && !playing && live) { + const card = live; + clearTimeout(saved); + saved = window.setTimeout(() => { + const was = inProgress(card.entry); + showProgress(card, readPosition(card.li.dataset.id!)); + if (inProgress(card.entry) !== was) { + countProgress(); + if (state.progress) { + render(state); + } + } + }, 250); + } + wasPlaying = playing; + }); + const stopQueue = effect(() => { const ids = new Set(queue.value.map((episode) => episode.id)); if (open) { @@ -2355,6 +2409,11 @@ export function startExplorer() { stopQueue(); stopClock(); stopLive(); + stopProgress(); + clearTimeout(saved); + if (live) { + mount(null, live.play); + } clocked.forEach((el) => delete el.dataset.propsFor); unregister(); swapping.forEach((timer) => clearTimeout(timer)); diff --git a/packages/starpod/src/components/explorer/query.ts b/packages/starpod/src/components/explorer/query.ts index 5151eae9..5ba34f8d 100644 --- a/packages/starpod/src/components/explorer/query.ts +++ b/packages/starpod/src/components/explorer/query.ts @@ -8,6 +8,8 @@ * out of the URL. */ +import { RESUME_MIN_SECONDS } from '../media/position'; + export const SORTS = ['newest', 'oldest', 'longest', 'shortest'] as const; export type Sort = (typeof SORTS)[number]; @@ -116,11 +118,9 @@ export function matches(entry: ExplorerEntry, state: ExplorerState): boolean { return true; } -/** The engine resumes from 30 seconds in; anything less is a sample. */ -export const RESUME_MIN_SECONDS = 30; - +/** Started, by the engine's own rule: Play would pick up where it was left. */ export function inProgress(entry: ExplorerEntry): boolean { - return entry.position >= RESUME_MIN_SECONDS; + return entry.position > RESUME_MIN_SECONDS; } export function compare(sort: Sort) { diff --git a/packages/starpod/src/styles/explorer.css b/packages/starpod/src/styles/explorer.css index 962797c2..159b46a0 100644 --- a/packages/starpod/src/styles/explorer.css +++ b/packages/starpod/src/styles/explorer.css @@ -3263,20 +3263,9 @@ /* ---------- Without anchor positioning: a plain detail view ---------- No travel: the open card spans the archive in place, artwork beside its - text and detail, and the archive stays as it was. */ + text and detail, and the archive stays as it was (explorer.ts leaves + data-open off, so it never folds into the strip). */ @supports not (position-anchor: --xp) { - .xp[data-open] .xp-stage { - grid-template-columns: minmax(0, 1fr); - } - - .xp[data-open] .xp-closeup { - display: none; - } - - .xp[data-open] .xp-stage .xp-list { - grid-column: 1; - } - .xp-card[data-on] { grid-column: 1 / -1; grid-row: span 2; @@ -3294,7 +3283,9 @@ height: auto; } + /* A size container: it takes its width from the box, never its content. */ .xp-card[data-on] .xp-art { + width: 100%; height: 100%; } @@ -3309,6 +3300,7 @@ .xp-card[data-on] .xp-play { grid-area: art; + place-self: end start; margin: 12px; } } diff --git a/tests/unit/explorer-query.test.ts b/tests/unit/explorer-query.test.ts index 87f8e334..45467d57 100644 --- a/tests/unit/explorer-query.test.ts +++ b/tests/unit/explorer-query.test.ts @@ -87,6 +87,12 @@ describe('explorer query', () => { ).toBe(true); }); + it("counts an episode in progress by the engine's resume rule: past 30s", () => { + const progress = { ...DEFAULT_STATE, progress: true }; + expect(matches(entry({ position: 30 }), progress)).toBe(false); + expect(matches(entry({ position: 30.5 }), progress)).toBe(true); + }); + it('sorts newest, oldest, longest and shortest', () => { const a = entry({ index: 0, duration: 1800 }); const b = entry({ index: 1, duration: 5400 }); From e448e27f458316fd2a64a7956c88e81607d13021 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Tue, 24 Nov 2026 12:24:56 -0500 Subject: [PATCH 07/10] Name each episode's people from the database or the feed Like transcripts, people now come from either of two optional sources: the guests database where it lists the episode, else the feed's tags (name, role, photo, link). A feed name the database knows is that record, so one person has one id and photo across both. src/lib/people.ts gathers them once for the explorer, the episode page, the stage and the search palette; with neither source, the pieces that show people leave themselves out. Feed photos are resized like local ones. The JSON API's episodes carry the feed's people too. Co-Authored-By: Claude Opus 5.5 --- .../starpod/src/components/EpisodeStage.astro | 15 +- .../src/components/explorer/archive.ts | 86 +--------- .../src/components/explorer/explorer.ts | 2 +- packages/starpod/src/lib/feed-media.ts | 106 ++++++++++--- packages/starpod/src/lib/openapi.ts | 14 ++ packages/starpod/src/lib/people.ts | 148 ++++++++++++++++++ packages/starpod/src/lib/rss.ts | 24 ++- packages/starpod/src/pages/[episode].astro | 60 ++----- tests/unit/feed-media.test.ts | 44 +++++- 9 files changed, 318 insertions(+), 181 deletions(-) create mode 100644 packages/starpod/src/lib/people.ts diff --git a/packages/starpod/src/components/EpisodeStage.astro b/packages/starpod/src/components/EpisodeStage.astro index 9bd1e0fd..21c20ce7 100644 --- a/packages/starpod/src/components/EpisodeStage.astro +++ b/packages/starpod/src/components/EpisodeStage.astro @@ -1,6 +1,7 @@ --- import { matchNames, sortCast, voiceFor, type CastPerson } from '../lib/cast'; import { getEpisodeCues } from '../lib/episode-cues'; +import { faceOf } from '../lib/people'; import { optimizeImage } from '../lib/optimize-episode-image'; import type { Episode, Show } from '../lib/rss'; import { dasherize } from '../utils/dasherize'; @@ -11,11 +12,7 @@ import LiveScript from './media/LiveScript'; import PersonFace from './PersonFace.astro'; import StageControls from './media/StageControls'; -import type { ImageMetadata } from 'astro'; -import { getImage } from 'astro:assets'; import starpodConfig from 'virtual:starpod/config'; -// The face for someone without a photo, light or dark with the page. -import avatar from '../assets/avatar.svg?url'; export interface Props { episode: Episode; @@ -54,9 +51,6 @@ const presets = [ // The cast: this episode's own hosts and guests, in credit order. Anyone who // speaks as one of the transcript's two main voices wears that voice's face. -const photos = import.meta.glob<{ default: ImageMetadata }>( - '/src/img/people/*.{jpeg,jpg,png}' -); const cues = people.length ? await getEpisodeCues(episode) : null; const names = people.map((person) => person.name); const speakerOf = matchNames(names, [...new Set(cues?.flatMap((cue) => (cue.n ? [cue.n] : [])))], { @@ -64,16 +58,11 @@ const speakerOf = matchNames(names, [...new Set(cues?.flatMap((cue) => (cue.n ? }); const cast = await Promise.all( sortCast(people, starpodConfig.hosts.map((host) => host.name)).map(async (person) => { - const photo = - person.img && (await photos[`/src/img/people/${person.img}`]?.())?.default; - const image = photo - ? await getImage({ src: photo, width: 112, height: 112, format: 'webp' }) - : { src: avatar }; return { guest: !person.isHost, name: person.name, speaksAs: speakerOf.get(person.name), - src: image.src, + src: await faceOf(person.img, 112), voice: voiceFor(person.name, cues, names) }; }) diff --git a/packages/starpod/src/components/explorer/archive.ts b/packages/starpod/src/components/explorer/archive.ts index 1237ef97..c9270471 100644 --- a/packages/starpod/src/components/explorer/archive.ts +++ b/packages/starpod/src/components/explorer/archive.ts @@ -1,20 +1,16 @@ /** * Everything the home page's explorer renders, gathered once at build time: - * each episode's artwork at card sizes, its hosts and guests (from the - * opt-in database), and the menus' choices (years, people). + * each episode's artwork at card sizes, its hosts and guests (the guests + * database's or the feed's: src/lib/people.ts), and the menus' choices + * (years, people). * * Server-only. */ -import type { ImageMetadata } from 'astro'; import { getImage } from 'astro:assets'; -import { eq } from 'drizzle-orm'; -import starpodConfig, { database } from 'virtual:starpod/config'; +import starpodConfig from 'virtual:starpod/config'; -// The face for someone without a photo, light or dark with the page. -import avatar from '../../assets/avatar.svg?url'; -import { createDb } from '../../db'; -import { HostOrGuest, Person } from '../../db/schema'; import { sortCast, type CastPerson } from '../../lib/cast'; +import { faceOf, peopleBySlug } from '../../lib/people'; import type { Episode, Show } from '../../lib/rss'; export interface ArchivePerson { @@ -42,35 +38,7 @@ export interface ArchiveChoice { host?: boolean; } -const photos = import.meta.glob<{ default: ImageMetadata }>( - '/src/img/people/*.{jpeg,jpg,png}' -); - -const avatars = new Map>(); - -function avatarFor(img: string | null): Promise { - const key = img ?? ''; - if (!avatars.has(key)) { - avatars.set( - key, - (async () => { - const photo = - img && (await photos[`/src/img/people/${img}`]?.())?.default; - if (!photo) { - return avatar; - } - const image = await getImage({ - src: photo, - width: 64, - height: 64, - format: 'webp' - }); - return image.src; - })() - ); - } - return avatars.get(key)!; -} +const avatarFor = (img: string | null) => faceOf(img, 64); /** Square artwork at the sizes a card can be shown at, grid tile to list row. */ async function cardArt(src: string | undefined, fallback: string) { @@ -92,52 +60,12 @@ async function cardArt(src: string | undefined, fallback: string) { } } -let cast: Promise>> | undefined; - -/** - * Each episode's people, keyed by episode slug: asked once, and empty when - * the database is off or out of reach (the cast is extra; the archive is - * not). - */ -function peopleBySlug(): Promise>> { - cast ??= queryPeople().catch((error) => { - console.warn('[starpod] No cast for the archive:', error); - return new Map(); - }); - return cast; -} - -async function queryPeople(): Promise>> { - const bySlug = new Map>(); - if (!database) { - return bySlug; - } - const db = createDb( - import.meta.env.ASTRO_DB_REMOTE_URL, - import.meta.env.ASTRO_DB_APP_TOKEN - ); - const rows = await db - .select({ - id: Person.id, - img: Person.img, - isHost: HostOrGuest.isHost, - name: Person.name, - slug: HostOrGuest.episodeSlug - }) - .from(HostOrGuest) - .innerJoin(Person, eq(HostOrGuest.personId, Person.id)); - for (const { slug, ...person } of rows) { - bySlug.set(slug, [...(bySlug.get(slug) ?? []), person]); - } - return bySlug; -} - let everyone: Promise> | undefined; /** * Everyone in the archive and how many episodes they are on, most first: the * With filter's choices without the card art, for the search palette (every - * page). Gathered once; empty when the database is off or out of reach. + * page). Gathered once; empty when no episode names anyone. */ export function loadPeople(): Promise> { everyone ??= (async () => { diff --git a/packages/starpod/src/components/explorer/explorer.ts b/packages/starpod/src/components/explorer/explorer.ts index d2b61f56..28a384ad 100644 --- a/packages/starpod/src/components/explorer/explorer.ts +++ b/packages/starpod/src/components/explorer/explorer.ts @@ -268,7 +268,7 @@ export function startExplorer() { const cardOf = new Map(cards.map((card) => [card.li, card])); /** A year or person the menus don't offer is no filter at all (a stale - * link, or people when the site has no guests database). */ + * link, or people when no episode names anyone). */ function known(next: ExplorerState): ExplorerState { const offered = (name: 'year' | 'guest') => { const field = form.elements.namedItem(name) as RadioNodeList | null; diff --git a/packages/starpod/src/lib/feed-media.ts b/packages/starpod/src/lib/feed-media.ts index 2a03e828..8a17209b 100644 --- a/packages/starpod/src/lib/feed-media.ts +++ b/packages/starpod/src/lib/feed-media.ts @@ -1,10 +1,12 @@ /** - * Video discovery for feed items. + * Video and people discovery for feed items. * * `rss-to-json` drops nested Podcasting 2.0 elements such as * ``, so the raw feed XML is scanned here instead. * An item's video is its first alternate enclosure whose type is video or an - * HLS playlist; the `` inside it is the stream URL. + * HLS playlist; the `` inside it is the stream URL. Its + * people are its `` tags: a name, and a role, photo and link + * when given. */ import { decodeEntities } from './entities'; @@ -14,16 +16,30 @@ export interface FeedVideo { type: string; } +export interface FeedPerson { + name: string; + /** The tag's role, lower case; the namespace's default is host. */ + role: string; + img?: string; + href?: string; +} + const HLS_TYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl']; const FETCH_TIMEOUT_MS = 10_000; // Attribute names are fixed by this module, never taken from the feed. -const ATTRIBUTE_PATTERNS: Record<'type' | 'uri', RegExp> = { +const ATTRIBUTE_PATTERNS = { + href: /\bhref\s*=\s*(["'])(.*?)\1/i, + img: /\bimg\s*=\s*(["'])(.*?)\1/i, + role: /\brole\s*=\s*(["'])(.*?)\1/i, type: /\btype\s*=\s*(["'])(.*?)\1/i, uri: /\buri\s*=\s*(["'])(.*?)\1/i -}; +} as const; -function attribute(tag: string, name: 'type' | 'uri'): string | undefined { +function attribute( + tag: string, + name: keyof typeof ATTRIBUTE_PATTERNS +): string | undefined { const match = tag.match(ATTRIBUTE_PATTERNS[name]); return match ? decodeEntities(match[2]) : undefined; } @@ -44,24 +60,31 @@ export function isVideoType(type: string): boolean { return lower.startsWith('video/') || HLS_TYPES.includes(lower); } +/** Each item's body, with its guid. */ +function* itemsOf(xml: string): Generator<[guid: string, body: string]> { + for (const item of xml.split(/]/i).slice(1)) { + const body = item.split(/<\/item>/i)[0]; + const guid = body.match(/]*>([\s\S]*?)<\/guid>/i)?.[1]; + if (guid) { + yield [characterData(guid), body]; + } + } +} + /** * Map each item's guid to its video, for items that carry one. */ export function extractVideosByGuid(xml: string): Map { const videos = new Map(); - for (const item of xml.split(/]/i).slice(1)) { - const body = item.split(/<\/item>/i)[0]; - const guid = body.match(/]*>([\s\S]*?)<\/guid>/i)?.[1]; - if (!guid) { - continue; - } - + for (const [guid, body] of itemsOf(xml)) { const enclosures = body.match( //gi ); for (const enclosure of enclosures ?? []) { - const openTag = enclosure.match(/]*>/i)![0]; + const openTag = enclosure.match( + /]*>/i + )![0]; const type = attribute(openTag, 'type') ?? ''; if (!isVideoType(type)) { continue; @@ -69,7 +92,7 @@ export function extractVideosByGuid(xml: string): Map { const sourceTag = enclosure.match(/]*>/i)?.[0]; const src = sourceTag && attribute(sourceTag, 'uri'); if (src) { - videos.set(characterData(guid), { src, type }); + videos.set(guid, { src, type }); break; } } @@ -79,12 +102,47 @@ export function extractVideosByGuid(xml: string): Map { } /** - * Fetch the feed and extract its videos. A failure here must never break the - * build: the site simply falls back to audio-first everywhere. + * Map each item's guid to its people, for items that name any. (The + * channel's own people are the show's current ones, not every episode's.) + */ +export function extractPeopleByGuid( + xml: string +): Map> { + const people = new Map>(); + + for (const [guid, body] of itemsOf(xml)) { + const found: Array = []; + for (const [, tag, text] of body.matchAll( + /(]*>)([\s\S]*?)<\/podcast:person>/gi + )) { + const name = characterData(text); + if (!name) { + continue; + } + found.push({ + name, + role: (attribute(tag, 'role') ?? 'host').toLowerCase(), + img: attribute(tag, 'img') || undefined, + href: attribute(tag, 'href') || undefined + }); + } + if (found.length) { + people.set(guid, found); + } + } + + return people; +} + +/** + * Fetch the feed and extract its videos and people. A failure here must never + * break the build: the site simply falls back to audio-first everywhere, and + * to whoever the guests database names. */ -export async function fetchFeedVideos( - feedUrl: string -): Promise> { +export async function fetchFeedExtras(feedUrl: string): Promise<{ + videos: Map; + people: Map>; +}> { try { // A deadline on the whole request, body included: a stalled response // must not hold up the build, which then falls back to audio. @@ -92,10 +150,14 @@ export async function fetchFeedVideos( signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); if (!response.ok) { - return new Map(); + return { videos: new Map(), people: new Map() }; } - return extractVideosByGuid(await response.text()); + const xml = await response.text(); + return { + videos: extractVideosByGuid(xml), + people: extractPeopleByGuid(xml) + }; } catch { - return new Map(); + return { videos: new Map(), people: new Map() }; } } diff --git a/packages/starpod/src/lib/openapi.ts b/packages/starpod/src/lib/openapi.ts index 51e8935c..2599fa93 100644 --- a/packages/starpod/src/lib/openapi.ts +++ b/packages/starpod/src/lib/openapi.ts @@ -252,6 +252,20 @@ export function generateOpenApiSpec( src: { type: 'string', format: 'uri' }, type: { type: 'string' } } + }, + people: { + type: 'array', + description: + "The episode's hosts and guests, from its tags", + items: { + type: 'object', + properties: { + name: { type: 'string' }, + role: { type: 'string', description: 'host, guest, …' }, + img: { type: 'string', format: 'uri' }, + href: { type: 'string', format: 'uri' } + } + } } } }, diff --git a/packages/starpod/src/lib/people.ts b/packages/starpod/src/lib/people.ts new file mode 100644 index 00000000..9a1b7d76 --- /dev/null +++ b/packages/starpod/src/lib/people.ts @@ -0,0 +1,148 @@ +/** + * Who is on each episode, for every page that shows people. Like + * transcripts (a markdown file, else the feed's), people come from two + * optional sources: the guests database where it lists the episode, else the + * feed's `` tags (src/lib/feed-media.ts). With neither, + * nobody is named, and the pieces that show people leave themselves out. + * + * Server-only. + */ +import type { ImageMetadata } from 'astro'; +import { getImage } from 'astro:assets'; +import { eq } from 'drizzle-orm'; +import { database } from 'virtual:starpod/config'; + +// The face for someone without a photo, light or dark with the page. +import avatar from '../assets/avatar.svg?url'; +import { createDb } from '../db'; +import { HostOrGuest, Person } from '../db/schema'; +import { dasherize } from '../utils/dasherize'; +import { matchNames, type CastPerson } from './cast'; +import { getAllEpisodes } from './rss'; + +interface Records { + bySlug: Map>; + everyone: Array>; +} + +/** The database's casts, and everyone in it; nothing when it is off or out of reach. */ +async function fromDatabase(): Promise { + const none: Records = { bySlug: new Map(), everyone: [] }; + if (!database) { + return none; + } + try { + const db = createDb( + import.meta.env.ASTRO_DB_REMOTE_URL, + import.meta.env.ASTRO_DB_APP_TOKEN + ); + const [rows, everyone] = await Promise.all([ + db + .select({ + id: Person.id, + img: Person.img, + isHost: HostOrGuest.isHost, + name: Person.name, + slug: HostOrGuest.episodeSlug + }) + .from(HostOrGuest) + .innerJoin(Person, eq(HostOrGuest.personId, Person.id)), + db + .select({ id: Person.id, img: Person.img, name: Person.name }) + .from(Person) + ]); + const bySlug = new Map>(); + for (const { slug, ...person } of rows) { + bySlug.set(slug, [...(bySlug.get(slug) ?? []), person]); + } + return { bySlug, everyone }; + } catch (error) { + console.warn( + '[starpod] The guests database is out of reach; people come from the feed alone.', + error + ); + return none; + } +} + +let cast: Promise>> | undefined; + +/** + * Each episode's hosts and guests, keyed by episode slug: the database's + * where it lists the episode, else the feed's. A name the feed gives that the + * database knows (the same name, or surely the same person) is that record, + * so one person has one id, and one photo, across both. Gathered once. + */ +export function peopleBySlug(): Promise>> { + cast ??= (async () => { + const [{ bySlug, everyone }, episodes] = await Promise.all([ + fromDatabase(), + getAllEpisodes() + ]); + const recordOf = matchNames( + episodes.flatMap( + (episode) => episode.people?.map((person) => person.name) ?? [] + ), + everyone.map((person) => person.name) + ); + const byName = new Map(everyone.map((person) => [person.name, person])); + for (const episode of episodes) { + if (!episode.people || bySlug.has(episode.episodeSlug)) { + continue; + } + bySlug.set( + episode.episodeSlug, + episode.people.map((person) => { + const record = byName.get(recordOf.get(person.name) ?? ''); + return { + id: record?.id ?? dasherize(person.name), + img: record?.img ?? person.img ?? null, + isHost: person.role === 'host', + name: record?.name ?? person.name + }; + }) + ); + } + return bySlug; + })(); + return cast; +} + +const photos = import.meta.glob<{ default: ImageMetadata }>( + '/src/img/people/*.{jpeg,jpg,png}' +); +const faces = new Map>(); + +/** + * A person's face, square at `size`: their photo (a file in src/img/people, + * or the feed's image URL), else the avatar. + */ +export function faceOf( + img: string | null | undefined, + size: number +): Promise { + const key = `${img ?? ''}@${size}`; + if (!faces.has(key)) { + faces.set( + key, + (async () => { + const src = !img + ? undefined + : /^https?:\/\//i.test(img) + ? img + : (await photos[`/src/img/people/${img}`]?.())?.default; + if (!src) { + return avatar; + } + try { + return ( + await getImage({ src, width: size, height: size, format: 'webp' }) + ).src; + } catch { + return avatar; + } + })() + ); + } + return faces.get(key)!; +} diff --git a/packages/starpod/src/lib/rss.ts b/packages/starpod/src/lib/rss.ts index ddeb1b19..d9e02ea8 100644 --- a/packages/starpod/src/lib/rss.ts +++ b/packages/starpod/src/lib/rss.ts @@ -1,16 +1,8 @@ import { htmlToText } from 'html-to-text'; import parseFeed from 'rss-to-json'; -import { - array, - number, - object, - optional, - parse, - string, - union -} from 'valibot'; - -import { fetchFeedVideos, type FeedVideo } from './feed-media'; +import { array, number, object, optional, parse, string, union } from 'valibot'; + +import { fetchFeedExtras, type FeedPerson, type FeedVideo } from './feed-media'; import { optimizeImage } from './optimize-episode-image'; import type { StarpodConfig } from '../utils/config'; import { dasherize } from '../utils/dasherize'; @@ -65,6 +57,9 @@ export interface Episode { // video or HLS type. When present the site leads with video and offers a // switch to audio. video?: FeedVideo; + // The episode's hosts and guests from its `` tags, when the + // feed names them (src/lib/people.ts prefers the guests database). + people?: Array; // A transcript referenced by the feed's `` tag, if any. // Used as a fallback when no explicit markdown transcript is provided for the // episode. @@ -152,9 +147,9 @@ export async function getAllEpisodes(config?: StarpodConfig) { }); const feedUrl = await resolveRssFeed(config); - const [feed, videos] = await Promise.all([ + const [feed, { videos, people }] = await Promise.all([ parseRssFeed(feedUrl) as Promise, - fetchFeedVideos(feedUrl) + fetchFeedExtras(feedUrl) ]); let items = parse(FeedSchema, feed).items; @@ -202,7 +197,8 @@ export async function getAllEpisodes(config?: StarpodConfig) { src: audioEnclosure.url, type: audioEnclosure.type ?? 'audio/mpeg' }, - video: videos.get(id) + video: videos.get(id), + people: people.get(id) }; } ) diff --git a/packages/starpod/src/pages/[episode].astro b/packages/starpod/src/pages/[episode].astro index 5ecc1db5..df1ffc6b 100644 --- a/packages/starpod/src/pages/[episode].astro +++ b/packages/starpod/src/pages/[episode].astro @@ -1,16 +1,9 @@ --- -import { getImage } from 'astro:assets'; import { getEntry, render } from 'astro:content'; import { count, eq, inArray } from 'drizzle-orm'; import { createDb } from '../db'; -import { - Episode as DbEpisode, - HostOrGuest, - Person, - Sponsor, - SponsorForEpisode -} from '../db/schema'; +import { Episode as DbEpisode, Sponsor, SponsorForEpisode } from '../db/schema'; import { Schema } from 'astro-seo-schema'; @@ -27,14 +20,12 @@ import UFOIllustration from '../components/illustrations/UFOIllustration.astro'; import { generateDocumentLinkTag } from '@bryanguffey/astro-standard-site'; import starpodConfig, { database } from 'virtual:starpod/config'; -import type { ImageMetadata } from 'astro'; -// The face for someone without a photo, light or dark with the page. -import avatar from '../assets/avatar.svg?url'; import Layout from '../layouts/Layout.astro'; import { factGivesCount, matchNames, personFact, sortCast } from '../lib/cast'; import { getEpisodeCues } from '../lib/episode-cues'; import { optimizeImage } from '../lib/optimize-episode-image'; +import { faceOf, peopleBySlug } from '../lib/people'; import { getAllEpisodes, getShowInfo, type Episode } from '../lib/rss'; import { getRssTranscriptParagraphs, @@ -130,19 +121,9 @@ const db = database ) : null; -const hostsAndGuests = !db - ? [] - : await db - .select({ - id: Person.id, - img: Person.img, - isHost: HostOrGuest.isHost, - name: Person.name - }) - .from(HostOrGuest) - .innerJoin(DbEpisode, eq(HostOrGuest.episodeSlug, DbEpisode.episodeSlug)) - .innerJoin(Person, eq(HostOrGuest.personId, Person.id)) - .where(eq(DbEpisode.episodeSlug, episode.episodeSlug)); +// Its hosts and guests: the database's, else the feed's (src/lib/people.ts). +const castBySlug = await peopleBySlug(); +const hostsAndGuests = castBySlug.get(episode.episodeSlug) ?? []; const sponsors = !db ? [] @@ -171,25 +152,10 @@ const newer = allEpisodes[position - 1]; const older = allEpisodes[position + 1]; const bySlug = new Map(allEpisodes.map((item) => [item.episodeSlug, item])); -const appearances = - !db || !hostsAndGuests.length - ? [] - : await db - .select({ - personId: HostOrGuest.personId, - episodeSlug: HostOrGuest.episodeSlug - }) - .from(HostOrGuest) - .where( - inArray( - HostOrGuest.personId, - hostsAndGuests.map((person) => person.id) - ) - ); const episodesOf = (personId: string) => - appearances - .filter((row) => row.personId === personId) - .map((row) => bySlug.get(row.episodeSlug)) + [...castBySlug] + .filter(([, people]) => people.some((person) => person.id === personId)) + .map(([slug]) => bySlug.get(slug)) .filter((item): item is Episode => Boolean(item)) .sort((a, b) => b.published - a.published); @@ -226,9 +192,6 @@ const card = async (item: Episode, reason?: string, face?: string) => ({ face }); -const photos = import.meta.glob<{ default: ImageMetadata }>( - '/src/img/people/*.{jpeg,jpg,png}' -); const cast = sortCast( hostsAndGuests, starpodConfig.hosts.map((host) => host.name) @@ -249,16 +212,11 @@ const people = await Promise.all( const earliest = theirs.at(-1); const speaker = speakerOf.get(person.name); const said = speaker ? talk.get(speaker) : undefined; - const photo = - person.img && - (await photos[`/src/img/people/${person.img}`]?.())?.default; return { id: person.id, name: person.name, guest: !person.isHost, - src: photo - ? (await getImage({ src: photo, width: 128, height: 128, format: 'webp' })).src - : avatar, + src: await faceOf(person.img, 128), count: theirs.length, fact: personFact({ appearance, diff --git a/tests/unit/feed-media.test.ts b/tests/unit/feed-media.test.ts index 4b427680..64a6c92e 100644 --- a/tests/unit/feed-media.test.ts +++ b/tests/unit/feed-media.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { extractVideosByGuid, isVideoType } from 'starpod/src/lib/feed-media'; +import { + extractPeopleByGuid, + extractVideosByGuid, + isVideoType +} from 'starpod/src/lib/feed-media'; const feed = ` @@ -55,3 +59,41 @@ describe('isVideoType', () => { expect(isVideoType('audio/mpeg')).toBe(false); }); }); + +describe('extractPeopleByGuid', () => { + const people = extractPeopleByGuid(` +Show Host +Two peopleflightcast:AAA +Robbie Wagner + +No Role + + +Nobodyflightcast:BBB +`); + + it("reads each item's people: name, role, photo and link", () => { + expect(people.get('flightcast:AAA')).toEqual([ + { + name: 'Robbie Wagner', + role: 'host', + img: 'https://example.com/r.jpg?a=1&b=2', + href: 'https://r.example/' + }, + { + name: 'Guest & Co', + role: 'guest', + img: undefined, + href: 'https://g.example/' + }, + { name: 'No Role', role: 'host', img: undefined, href: undefined } + ]); + }); + + it("leaves out items that name nobody, and the channel's own people", () => { + expect(people.has('flightcast:BBB')).toBe(false); + expect([...people.values()].flat().map((p) => p.name)).not.toContain( + 'Show Host' + ); + }); +}); From c8fa4a4f9f3d16fe0ac35e1842b36d22cc2e39c9 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Tue, 24 Nov 2026 16:21:03 -0500 Subject: [PATCH 08/10] Keep the explorer's state in the hash, through Astro's router Astro's router treats a change of query as another page, so each filter step and each Back fetched and swapped the home page. A change of hash alone is the router's move within the page: no fetch, no swap, and Back and Forward step through it. The explorer now writes its state to the hash with navigate(), and follows the address on hashchange and the Navigation API's currententrychange, in place of intercepting popstate. Co-Authored-By: Claude Opus 5.5 --- .../starpod/src/components/EpisodeList.astro | 6 +- .../src/components/episode/People.astro | 4 +- .../src/components/explorer/Hero.astro | 2 +- .../src/components/explorer/explorer.ts | 75 ++++++++++--------- .../starpod/src/components/explorer/query.ts | 51 ++++++++++--- tests/unit/explorer-query.test.ts | 25 +++++-- 6 files changed, 103 insertions(+), 60 deletions(-) diff --git a/packages/starpod/src/components/EpisodeList.astro b/packages/starpod/src/components/EpisodeList.astro index 9248a513..c9b3d6aa 100644 --- a/packages/starpod/src/components/EpisodeList.astro +++ b/packages/starpod/src/components/EpisodeList.astro @@ -19,10 +19,10 @@ const { cards, episodes, people, show, years } = Astro.props; ---