diff --git a/packages/starpod/package.json b/packages/starpod/package.json
index 25f3180e..19feb7d2 100644
--- a/packages/starpod/package.json
+++ b/packages/starpod/package.json
@@ -43,10 +43,13 @@
"@tailwindcss/typography": "^0.5.19",
"@tailwindcss/vite": "^4.3.0",
"@vercel/speed-insights": "^1.3.1",
+ "anchored-auto-layout": "^1.0.0",
"astro-seo-schema": "^5.2.0",
"atropos": "^2.0.2",
"drizzle-orm": "^0.45.2",
+ "hls.js": "1.6.15",
"html-to-text": "^9.0.5",
+ "prop-for-that": "^0.7.12",
"rss-to-json": "^2.1.1",
"schema-dts": "^1.1.5",
"tailwindcss": "^4.3.0",
diff --git a/packages/starpod/src/components/FullPlayButton.tsx b/packages/starpod/src/components/FullPlayButton.tsx
index 1a5076ae..07251011 100644
--- a/packages/starpod/src/components/FullPlayButton.tsx
+++ b/packages/starpod/src/components/FullPlayButton.tsx
@@ -1,82 +1,90 @@
-import type { JSX } from 'preact/jsx-runtime';
+import { useLayoutEffect, useRef, useState } from 'preact/hooks';
-import { currentEpisode, isPlaying } from './state';
+import { startEngine } from './media/engine';
+import PlayGlyph from './media/PlayGlyph';
+import PlayToggle from './media/PlayToggle';
+import { resumePoint } from './media/position';
+import { formatClock } from '../utils/playable';
+import {
+ currentEpisode,
+ isPlaying,
+ playEpisode,
+ type PlayableEpisode
+} from './state';
type Props = {
- episode: (typeof currentEpisode)['value'];
+ episode: PlayableEpisode | null;
+ /**
+ * `row`: the round play disc on an episode card. `disc`: the large disc
+ * over featured media. `pill`: a labelled primary button that offers to
+ * resume where the visitor left off.
+ */
+ look?: 'row' | 'disc' | 'pill';
};
-const PlayIcon = (
-
-);
+/**
+ * A play control for one episode. Marks its card (`[data-episode-row]`) as
+ * current (the lit room / the speaking line) while that episode is loaded,
+ * and as playing while it plays.
+ */
+export default function FullPlayButton({ episode, look = 'row' }: Props) {
+ const button = useRef(null);
+ const [resumeAt, setResumeAt] = useState(0);
-const PauseIcon = (
-
-);
+ const isCurrent =
+ Boolean(episode) && episode!.id === currentEpisode.value?.id;
-function renderIcon(icon: JSX.Element, key?: string) {
- return {icon};
-}
+ // Read again when it stops being current: it has just been played.
+ useLayoutEffect(() => {
+ startEngine();
+ if (episode && look === 'pill') {
+ setResumeAt(resumePoint(episode.id));
+ }
+ }, [episode, look, isCurrent]);
+
+ const playing = isCurrent && isPlaying.value;
+
+ useLayoutEffect(() => {
+ const row = button.current?.closest('[data-episode-row]');
+ row?.toggleAttribute('data-current', isCurrent);
+ row?.toggleAttribute('data-playing', playing);
+ });
-export default function FullPlayButton({ episode }: Props) {
if (!episode) {
return null;
}
- const isCurrentEpisode = episode.id === currentEpisode.value?.id;
- const showPauseIcon = isCurrentEpisode && isPlaying.value;
+ if (look === 'pill') {
+ const resume = !isCurrent && resumeAt > 0;
+ return (
+
+ );
+ }
return (
-
+
+ `${on ? 'Pause' : 'Play'} episode ${episode.episodeNumber}: ${episode.title}`
+ }
+ onAir={look === 'row'}
+ size={look === 'disc' ? 30 : 18}
+ />
);
}
diff --git a/packages/starpod/src/components/icons.tsx b/packages/starpod/src/components/icons.tsx
new file mode 100644
index 00000000..21ff35b8
--- /dev/null
+++ b/packages/starpod/src/components/icons.tsx
@@ -0,0 +1,262 @@
+/**
+ * Starpod's icon set: one 24px grid, 1.75 stroke, round caps. Rendered
+ * statically from Astro and live inside islands. Decorative by default; give
+ * the surrounding control its accessible name.
+ */
+import type { JSX } from 'preact';
+
+export type IconProps = { class?: string; size?: number };
+
+/**
+ * Each icon carries its own vertical gradient whose stops read `--icon-a` and
+ * `--icon-b` from the control around it. Controls that opt in (tokens.css)
+ * paint the icon with it, so hovering fades the icon from its resting colour
+ * into the Iris/Aqua gradient. The id is per instance because a `url(#id)`
+ * paint resolves to the first match in the document.
+ */
+export function Svg({
+ children,
+ class: className,
+ size = 20
+}: IconProps & { children: JSX.Element | Array }) {
+ const id = `sp-icon-${Math.random().toString(36).slice(2, 9)}`;
+ return (
+
+ );
+}
+
+export const PlayIcon = (p: IconProps) => (
+
+);
+
+export const PauseIcon = (p: IconProps) => (
+
+);
+
+export const BackIcon = (p: IconProps) => (
+
+);
+
+export const ForwardIcon = (p: IconProps) => (
+
+);
+
+export const ListIcon = (p: IconProps) => (
+
+);
+
+/** The sidebar toggle: a panel whose chevron turns with the rail's state. */
+export const RailIcon = (p: IconProps) => (
+
+);
+
+export const SearchIcon = (p: IconProps) => (
+
+);
+
+export const InfoIcon = (p: IconProps) => (
+
+);
+
+export const MailIcon = (p: IconProps) => (
+
+);
+
+export const ArrowOutIcon = (p: IconProps) => (
+
+);
+
+export const BagIcon = (p: IconProps) => (
+
+);
+
+export const MegaphoneIcon = (p: IconProps) => (
+
+);
+
+export const HeartIcon = (p: IconProps) => (
+
+);
+
+export const LinkIcon = (p: IconProps) => (
+
+);
+
+export const VideoIcon = (p: IconProps) => (
+
+);
+
+export const HeadphonesIcon = (p: IconProps) => (
+
+);
+
+export const ExpandIcon = (p: IconProps) => (
+
+);
+
+export const ChevronUpIcon = (p: IconProps) => (
+
+);
+
+/** A screen with the small picture in `corner` (where it is, or is going). */
+export const PipIcon = (p: IconProps & { corner?: 'se' | 'sw' | 'nw' | 'ne' }) => (
+
+);
+
+export const QueueIcon = (p: IconProps & { queued?: boolean }) => (
+
+);
+
+export const NextIcon = (p: IconProps) => (
+
+);
+
+export const GripIcon = (p: IconProps) => (
+
+);
+
+export const MoreIcon = (p: IconProps) => (
+
+);
+
+export const FollowIcon = (p: IconProps) => (
+
+);
+
+export const CloseIcon = (p: IconProps) => (
+
+);
+
+export const VolumeIcon = (p: IconProps & { muted?: boolean }) => (
+
+);
+
+export const GithubIcon = (p: IconProps) => (
+
+);
+
+export const XIcon = (p: IconProps) => (
+
+);
diff --git a/packages/starpod/src/components/media/Island.tsx b/packages/starpod/src/components/media/Island.tsx
new file mode 100644
index 00000000..c081c01e
--- /dev/null
+++ b/packages/starpod/src/components/media/Island.tsx
@@ -0,0 +1,1009 @@
+import { navigate } from 'astro:transitions/client';
+import { computed } from '@preact/signals';
+import { createPortal } from 'preact/compat';
+import { useLayoutEffect, useRef } from 'preact/hooks';
+
+import { flip } from '../../motion/propflip';
+import {
+ ArrowOutIcon,
+ BackIcon,
+ ChevronUpIcon,
+ CloseIcon,
+ ExpandIcon,
+ ForwardIcon,
+ MoreIcon,
+ NextIcon,
+ PipIcon,
+ Svg,
+ VolumeIcon,
+ type IconProps
+} from '../icons';
+import {
+ activeMedium,
+ closeMini,
+ currentEpisode,
+ currentTime,
+ dockPicture,
+ anchorPositioning,
+ homeOnScreen,
+ isMuted,
+ islandAt,
+ islandBack,
+ islandHome,
+ ISLAND_HOMES,
+ mediaDuration,
+ miniClosed,
+ phoneScreen,
+ pictureDocked,
+ pipCorner,
+ playbackRate,
+ playEpisode,
+ queue,
+ type Corner,
+ type IslandHome,
+ type PlayableEpisode
+} from '../state';
+import { formatClock } from '../../utils/playable';
+import { mountBoard, nextEpisode, type Board } from './board';
+import { enterFullscreen, mediaStation, placeMedia, setRate, skip, startEngine } from './engine';
+import MediumSwitch from './MediumSwitch';
+import PlayToggle from './PlayToggle';
+import Scrubber from './Scrubber';
+
+const RATES = [1, 1.25, 1.5, 1.75, 2, 0.75];
+const HOME_NAME: Record = { pill: 'Pill', card: 'Card', dock: 'Dock', rail: 'Rail' };
+
+// Clockwise round the screen, for the keyboard's way of moving the picture.
+const NEXT_CORNER: Record = { se: 'sw', sw: 'nw', nw: 'ne', ne: 'se' };
+const CORNER_NAME: Record = {
+ se: 'bottom right',
+ sw: 'bottom left',
+ nw: 'top left',
+ ne: 'top right'
+};
+
+let board: Board | null = null;
+let settling = 0;
+
+/**
+ * How the dock lays itself out at a width, widest first: everything; the
+ * home control folded into one "Move player" button and its popover; the
+ * watch/listen switch down to its icons; speed and mute into the popover;
+ * the bars, the switch and the picture button into it too; and the times
+ * and Play next as well, the title giving way. The scrubber keeps a real
+ * track (240px at least) in every form, and the picture, title, transport
+ * and play never leave.
+ */
+export type DockFit = 'full' | 'move' | 'icon' | 'fold' | 'lean' | 'tight';
+
+/**
+ * The room each form needs besides the art, at 1024px and wider: its parts,
+ * gaps and padding, and the scrubber at its minimum (measured, with a few
+ * pixels to spare). Narrower than all of them, the dock is 'tight'.
+ */
+const DOCK_ROOM: Array<[DockFit, number]> = [
+ ['full', 1370],
+ ['move', 1217],
+ ['icon', 1136],
+ ['fold', 1036],
+ ['lean', 822]
+];
+
+export function dockFit(width: number, art: number): DockFit {
+ return DOCK_ROOM.find(([, room]) => width - art >= room)?.[0] ?? 'tight';
+}
+
+/**
+ * Re-form the dock for its station's width. The station is where the dock
+ * will be, so a journey to it flies straight to its final form, and a width
+ * change at rest (the sidebar folding) flips the parts to their new places.
+ */
+function refit(island: HTMLElement, width: number) {
+ const art = island.dataset.medium === 'watch' ? (56 * 16) / 9 : 56;
+ const fit = dockFit(width, art);
+ if (island.dataset.fit === fit) {
+ return;
+ }
+ const set = () => {
+ island.dataset.fit = fit;
+ const label = fit === 'move' || fit === 'icon' ? 'Move player' : 'Player options';
+ const more = island.querySelector('.island-more-button');
+ more?.setAttribute('aria-label', label);
+ more?.setAttribute('title', label);
+ };
+ if (island.dataset.fit && island.dataset.state === 'dock' && !island.hasAttribute('data-moving')) {
+ flip([...island.children] as Array, set);
+ } else {
+ set();
+ }
+}
+
+// The clock's text, bound as signals: a time update rewrites these text nodes
+// and the scrubber, not the island.
+const elapsed = computed(() => formatClock(currentTime.value));
+const remaining = computed(
+ () => `-${formatClock(Math.max(0, (mediaDuration.value || currentEpisode.value?.duration || 0) - currentTime.value))}`
+);
+
+function LiveScrubber({ episode }: { episode: PlayableEpisode }) {
+ return (
+
+ );
+}
+
+/** Publish the island's home on , for the rail slot and the room to read. */
+export function markHome() {
+ const root = document.documentElement;
+ const island = document.getElementById('player');
+ if (currentEpisode.value && island) {
+ root.dataset.island = islandAt.value;
+ } else {
+ delete root.dataset.island;
+ }
+ syncPage();
+}
+
+/** What the open card made inert, to give back exactly that when it closes. */
+const held = new Set();
+
+/**
+ * Hold the page (or let it go) to match the card, but only with the island
+ * at rest: making the page inert, or lifting it, restyles the whole page
+ * (some 900 elements), which mid-journey cost a frame. The landing calls
+ * this again. Until then trapTab() keeps the keyboard in the card.
+ */
+function syncPage() {
+ const island = document.getElementById('player');
+ if (island?.hasAttribute('data-moving')) {
+ return;
+ }
+ holdPage(island && islandAt.value === 'card' ? island : null);
+}
+
+/**
+ * The island's tab stops, in the order Tab visits them: shown, focusable
+ * from the keyboard, one per radio group, and not inside the More popover
+ * (closed in the card).
+ */
+function tabStops(island: HTMLElement) {
+ return [
+ ...island.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), [tabindex]')
+ ].filter(
+ (el) =>
+ el.tabIndex >= 0 &&
+ !(el instanceof HTMLInputElement && el.type === 'radio' && !el.checked) &&
+ !el.closest('[popover]') &&
+ el.checkVisibility?.({ visibilityProperty: true }) !== false
+ );
+}
+
+/**
+ * While the card is open, Tab and Shift+Tab wrap round the card's own stops,
+ * so the keyboard never reaches the page under the scrim: before the card
+ * lands the page is not inert yet, and even once it is, Chrome still tabs
+ * into an inert page's scrollable lists. (aria-modal says the same to
+ * assistive technology from the start.)
+ */
+function trapTab(event: KeyboardEvent) {
+ const island = document.getElementById('player');
+ if (event.key !== 'Tab' || islandAt.value !== 'card' || !island) {
+ return;
+ }
+ const stops = tabStops(island);
+ const at = stops.indexOf(document.activeElement as HTMLElement);
+ const wrap = event.shiftKey
+ ? at <= 0 && stops.at(-1)
+ : (at === -1 || at === stops.length - 1) && stops[0];
+ if (wrap) {
+ event.preventDefault();
+ wrap.focus();
+ }
+}
+
+/**
+ * The card is modal: it all but fills the screen over a scrim, so while it
+ * is open everything else on the page is inert (out of the tab order and out
+ * of reach of assistive technology; the floating picture's layer too, which
+ * still draws the picture in the card). A navigation swaps the page in under
+ * an open card, so this runs again after every swap.
+ */
+/**
+ * Focus that reaches the page some other way while the card is open (a
+ * browser that tabs only to form fields, say) is brought back into it.
+ */
+function keepFocusIn(event: FocusEvent) {
+ const island = document.getElementById('player');
+ const target = event.target;
+ if (islandAt.value !== 'card' || !island || !(target instanceof Element) || island.contains(target)) {
+ return;
+ }
+ cardStart(island)?.focus({ preventScroll: true });
+}
+
+/** Where focus starts in the card: its close on phones, or else its home control. */
+function cardStart(island: HTMLElement) {
+ return island.querySelector(
+ phoneScreen.value ? '.island-close button' : '.island-station input[value="card"]'
+ );
+}
+
+function holdPage(card: HTMLElement | null) {
+ if (card) {
+ for (const el of document.body.children) {
+ if (el instanceof HTMLElement && !el.contains(card) && !el.hasAttribute('inert')) {
+ el.setAttribute('inert', '');
+ held.add(el);
+ }
+ }
+ return;
+ }
+ held.forEach((el) => el.removeAttribute('inert'));
+ held.clear();
+}
+
+/**
+ * Focus a control of the island's, or its title (every home has one) if
+ * that control is not showing in the current home.
+ */
+function focusIsland(selector: string) {
+ const island = document.getElementById('player');
+ const wanted = island?.querySelector(selector);
+ const target = wanted?.checkVisibility?.({ visibilityProperty: true })
+ ? wanted
+ : island?.querySelector('.island-name');
+ target?.focus({ preventScroll: true });
+}
+
+/**
+ * Send the island to a home. One attribute re-homes it: the island is
+ * `data-⚓️-fill` on a station, so changing `data-⚓️-to` makes its own size and
+ * place tween (x and y each on their own spring). Its grid re-templates per
+ * `data-state`, and every part is a PropFLIP leaf: it inverts against the
+ * island at frame zero and rides home on a stagger the parts take from their
+ * place in the tree. Interruptible: flip() starts from the pixels on screen.
+ */
+export function go(home: IslandHome) {
+ const island = document.getElementById('player');
+ const to = homeOnScreen(home);
+ if (!island || island.dataset.state === to) {
+ islandHome.value = home;
+ return;
+ }
+ // The More popover belongs to the dock; it closes as the island leaves.
+ const pop = island.querySelector('.island-more-pop');
+ if (pop?.matches(':popover-open')) {
+ pop.hidePopover();
+ }
+ // WebKit tweens the island's anchor() insets when its station changes, but
+ // not a size given as anchor-size(): the box took its new size at once and
+ // parts flying in from outside it were clipped out of sight. There the
+ // journey's size is given in pixels, from where it is to where it is going,
+ // and handed back to the anchor on landing. (The rail's slot grows as the
+ // island arrives, so that journey keeps the old way.)
+ const station =
+ to !== 'rail' &&
+ typeof CSS?.supports === 'function' &&
+ CSS.supports('anchor-name: --a') &&
+ !CSS.supports('width: attr(x type())')
+ ? document.querySelector(`.island-home[data-home='${to}']`)
+ : null;
+ if (station) {
+ const now = island.getBoundingClientRect();
+ island.style.width = `${now.width}px`;
+ island.style.height = `${now.height}px`;
+ } else {
+ island.style.removeProperty('width');
+ island.style.removeProperty('height');
+ }
+ // Reads happen where flip() has just measured (style and layout clean) and
+ // writes inside its update, so go() forces no layout of its own (bar
+ // WebKit's one read of where the island is going).
+ let slomo = 0;
+ const moves = flip([...island.children] as Array, () => {
+ slomo = parseFloat(getComputedStyle(island).getPropertyValue('--slomo')) || 0;
+ // The cascade runs from the far end on the way back to a smaller home.
+ island.dataset.going = ISLAND_HOMES.indexOf(to) === 1 ? 'out' : 'in';
+ // Its own tween runs only for the journey (and the rail slot's growth);
+ // at rest it follows its station exactly. The longest leg is 0.8s.
+ island.dataset.moving = '';
+ island.dataset.state = to;
+ island.setAttribute('data-⚓️-to', `--home-${to}`);
+ document.documentElement.dataset.island = to;
+ if (station) {
+ const end = station.getBoundingClientRect();
+ island.style.width = `${end.width}px`;
+ island.style.height = `${end.height}px`;
+ }
+ });
+ window.clearTimeout(settling);
+ settling = window.setTimeout(() => {
+ delete island.dataset.moving;
+ island.style.removeProperty('width');
+ island.style.removeProperty('height');
+ syncPage();
+ }, 900 * slomo + 50);
+ // Parts at rest take their delay from CSS (sibling-index()); parts already
+ // in flight keep the zero flip() gave them, so an interrupt never freezes.
+ for (const move of moves) {
+ if (!move.moving) {
+ move.el.style.removeProperty('--flip-delay');
+ }
+ }
+ islandHome.value = home;
+ keepFocus(island, to);
+}
+
+/**
+ * Focus moves with the choice, never into a part the new home has parked
+ * (hidden): into the card it goes to the home control, so the next arrow
+ * chooses again; anywhere else it stays on its control if that control still
+ * shows, or else lands on the island's title, which every home has.
+ */
+function keepFocus(island: HTMLElement, to: IslandHome) {
+ const focused = document.activeElement;
+ if (!(focused instanceof HTMLElement) || !island.contains(focused)) {
+ // The card is a dialog: opened from anywhere, focus goes into it, and
+ // goes back to what opened it when it closes.
+ if (to === 'card') {
+ opener = focused instanceof HTMLElement && focused !== document.body ? focused : null;
+ cardStart(island)?.focus({ preventScroll: true });
+ }
+ return;
+ }
+ if (to !== 'card' && opener?.isConnected) {
+ const back = opener;
+ opener = null;
+ back.focus({ preventScroll: true });
+ return;
+ }
+ opener = to === 'card' ? opener : null;
+ const part = focused.closest('#player > *');
+ const target =
+ to === 'card' && !focused.closest('.island-queue')
+ ? cardStart(island)
+ : part && getComputedStyle(part).position === 'absolute'
+ ? island.querySelector('.island-name')
+ : null;
+ target?.focus({ preventScroll: true });
+}
+
+/** What had focus outside the player when the card opened, for its close. */
+let opener: HTMLElement | null = null;
+
+/** The island's body toggles the card and the home it came from. */
+export function toggleCard() {
+ go(islandAt.value === 'card' ? islandBack.value : 'card');
+}
+
+/** The floating picture's own bar: what it is, where it goes, and how to leave it. */
+function PipBar({ episode, href }: { episode: PlayableEpisode; href: string }) {
+ const watching = activeMedium.value === 'watch';
+ const next = NEXT_CORNER[pipCorner.value];
+ // On phones closing it only puts the picture back in the player (closeMini).
+ const close = phoneScreen.value
+ ? watching
+ ? 'Put the video back in the player'
+ : 'Put the artwork back in the player'
+ : watching
+ ? 'Close video'
+ : 'Close artwork';
+ return (
+
+ );
+}
+
+/**
+ * A segmented radio with one indicator, anchored to the checked option, that
+ * glides. The More popover holds a second one, its checked option filled.
+ */
+function Stations({ popover = false }: { popover?: boolean }) {
+ const at = islandAt.value;
+ // Without anchor positioning there is only the dock: nothing to choose.
+ if (!anchorPositioning.value) {
+ return null;
+ }
+ return (
+
+ );
+}
+
+function SpeedButton() {
+ return (
+
+ );
+}
+
+function MuteButton() {
+ return (
+
+ );
+}
+
+function PipButton({ docked }: { docked: boolean }) {
+ return (
+
+ );
+}
+
+/** The player's homes: a window with the dock along its foot. */
+const MoveIcon = (p: IconProps) => (
+
+);
+
+/**
+ * What a narrow dock does not show, one button away: the home control
+ * ("Move player"), and as the dock narrows, speed and mute, the switch and
+ * the picture button, the times and Play next. Anchored to its button, it
+ * opens above the dock, or below where there is no room, its caret turning
+ * with it. Which rows show follows the dock's form (data-fit).
+ */
+function More({ docked, episode, following }: { docked: boolean; episode: PlayableEpisode; following?: PlayableEpisode }) {
+ const next = skipLabel(following);
+ return (
+
+
+
+
+
+ {elapsed}
+ {remaining}
+
+
+
+
+
+
+
+ {episode.video && }
+
+
+
+
+
+
+ );
+}
+
+/**
+ * What the skip button says: Up next's first is what plays next (and plays on
+ * its own when this one ends); without one, the shelf's first is only where
+ * a skip goes.
+ */
+function skipLabel(following?: PlayableEpisode) {
+ if (!following) {
+ return 'Nothing to play next';
+ }
+ return queue.value[0]?.id === following.id ? `Play next: ${following.title}` : `Skip to ${following.title}`;
+}
+
+/** The card's close, pointing down to where it goes. */
+const ChevronDownIcon = (p: IconProps) => (
+
+);
+
+/**
+ * Phones: the card follows a finger down from its top strip (the grabber's),
+ * and goes home when let go a third of the way down or flicked, springing
+ * back otherwise; a tap on the strip closes it too. The island rides its own
+ * translate, so letting go anywhere continues from the pixels it is on.
+ */
+function swipeToClose(strip: HTMLElement) {
+ let from: { y: number; t: number; id: number } | null = null;
+ let dy = 0;
+ const island = () => document.getElementById('player');
+ const down = (event: PointerEvent) => {
+ if (event.button || islandAt.value !== 'card') {
+ return;
+ }
+ from = { y: event.clientY, t: event.timeStamp, id: event.pointerId };
+ dy = 0;
+ strip.setPointerCapture(event.pointerId);
+ };
+ const move = (event: PointerEvent) => {
+ const el = island();
+ if (!from || event.pointerId !== from.id || !el) {
+ return;
+ }
+ dy = Math.max(0, event.clientY - from.y);
+ el.style.transition = 'none';
+ el.style.translate = `0 ${dy}px`;
+ };
+ const up = (event: PointerEvent) => {
+ const el = island();
+ if (!from || event.pointerId !== from.id || !el) {
+ return;
+ }
+ const speed = dy / Math.max(1, event.timeStamp - from.t);
+ from = null;
+ el.style.removeProperty('transition');
+ if (event.type === 'pointerup' && (dy < 6 || dy > innerHeight / 3 || speed > 0.6)) {
+ go(islandBack.value);
+ }
+ el.style.removeProperty('translate');
+ };
+ strip.addEventListener('pointerdown', down);
+ strip.addEventListener('pointermove', move);
+ strip.addEventListener('pointerup', up);
+ strip.addEventListener('pointercancel', up);
+ return () => {
+ strip.removeEventListener('pointerdown', down);
+ strip.removeEventListener('pointermove', move);
+ strip.removeEventListener('pointerup', up);
+ strip.removeEventListener('pointercancel', up);
+ // Closed mid-swipe (Escape under the finger): the card lets go of it.
+ if (from) {
+ if (strip.hasPointerCapture(from.id)) {
+ strip.releasePointerCapture(from.id);
+ }
+ from = null;
+ const el = island();
+ el?.style.removeProperty('transition');
+ el?.style.removeProperty('translate');
+ }
+ };
+}
+
+type Watcher = { onclose: (() => void) | null; destroy: () => void };
+const CloseWatcherType = (globalThis as { CloseWatcher?: new () => Watcher }).CloseWatcher;
+
+/**
+ * Phones: the system's back gesture closes the card (a close watcher, where
+ * there is one: Android). It adds no history entry, so back and forward
+ * still move between pages exactly as before.
+ */
+function closeOnBack() {
+ if (!CloseWatcherType) {
+ return () => {};
+ }
+ const watcher = new CloseWatcherType();
+ watcher.onclose = () => {
+ if (islandAt.value === 'card') {
+ go(islandBack.value);
+ }
+ };
+ return () => watcher.destroy();
+}
+
+const typing = (target: EventTarget | null) =>
+ target instanceof HTMLElement &&
+ (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) &&
+ !(target instanceof HTMLInputElement && (target.type === 'radio' || target.type === 'range'));
+
+/**
+ * The player: one island with four homes (pill, dock, card, rail), the
+ * floating picture's bar, and the scrim behind the card. Lives in the
+ * layout's dock block and survives client-side navigation.
+ */
+export default function Island() {
+ // Layout effects throughout the player: WebKit runs passive ones only after
+ // a painted frame, which a page sitting still may not produce, and these
+ // start the engine, register keys and move UI in answer to the visitor.
+ useLayoutEffect(() => {
+ startEngine();
+ }, []);
+
+ const episode = currentEpisode.value;
+ const hasEpisode = Boolean(episode);
+ const queueHost = useRef(null);
+
+ // The art part is a home for the picture: once it exists, re-home it; and
+ // tell the page where the island is.
+ useLayoutEffect(() => {
+ markHome();
+ if (hasEpisode) {
+ placeMedia();
+ }
+ }, [hasEpisode]);
+ useLayoutEffect(markHome, [islandAt.value]);
+ // A navigation swaps in the new page's attributes.
+ useLayoutEffect(() => {
+ document.addEventListener('astro:after-swap', markHome);
+ return () => document.removeEventListener('astro:after-swap', markHome);
+ }, []);
+
+ // The queue board is drawn imperatively (its covers never move in the DOM).
+ useLayoutEffect(() => {
+ if (!queueHost.current) {
+ return;
+ }
+ board = mountBoard(queueHost.current);
+ return () => {
+ board?.stop();
+ board = null;
+ };
+ }, [hasEpisode]);
+
+ // Tapping the floating picture opens its episode, where it returns to the stage.
+ const target = episode ? `/${episode.slug ?? episode.episodeNumber}` : null;
+ useLayoutEffect(() => {
+ const picture = document.querySelector('[data-player-media] > *');
+ if (!picture || !target) {
+ return;
+ }
+ const open = () => mediaStation.value === 'corner' && void navigate(target);
+ picture.addEventListener('click', open);
+ return () => picture.removeEventListener('click', open);
+ }, [target]);
+
+ // The dock re-forms by its station's width (and the art's, which grows
+ // while watching).
+ const medium = activeMedium.value;
+ useLayoutEffect(() => {
+ const island = document.getElementById('player');
+ const station = document.querySelector(".island-home[data-home='dock']");
+ if (!island || !station) {
+ return;
+ }
+ refit(island, station.getBoundingClientRect().width);
+ const watch = new ResizeObserver(([entry]) => {
+ refit(island, entry!.borderBoxSize?.[0]?.inlineSize ?? entry!.contentRect.width);
+ });
+ watch.observe(station);
+ return () => watch.disconnect();
+ }, [hasEpisode, medium]);
+
+ // 1 to 4 choose a home, as in the demo; Escape closes the card.
+ useLayoutEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (!currentEpisode.value || event.metaKey || event.ctrlKey || event.altKey || typing(event.target)) {
+ return;
+ }
+ const home = ISLAND_HOMES[Number(event.key) - 1];
+ if (home && homeOnScreen(home) === home) {
+ go(home);
+ } else if (event.key === 'Escape' && islandAt.value === 'card') {
+ go(islandBack.value);
+ } else {
+ return;
+ }
+ // Handled here, so nothing else acts on it (the explorer's close-up
+ // behind the card, say): listened for first, on the window's capture.
+ event.preventDefault();
+ event.stopPropagation();
+ };
+ addEventListener('keydown', onKey, true);
+ addEventListener('keydown', trapTab, true);
+ document.addEventListener('focusin', keepFocusIn, true);
+ return () => {
+ removeEventListener('keydown', onKey, true);
+ removeEventListener('keydown', trapTab, true);
+ document.removeEventListener('focusin', keepFocusIn, true);
+ };
+ }, []);
+
+ // Phones: the card's grabber strip and the back gesture close it.
+ const grab = useRef(null);
+ const phone = phoneScreen.value;
+ const cardOpen = islandAt.value === 'card';
+ useLayoutEffect(() => {
+ if (!cardOpen || !phone || !grab.current) {
+ return;
+ }
+ const stops = [swipeToClose(grab.current), closeOnBack()];
+ return () => stops.forEach((stop) => stop());
+ }, [cardOpen, phone, hasEpisode]);
+
+ if (!episode) {
+ return null;
+ }
+
+ const href = `/${episode.slug ?? episode.episodeNumber}`;
+ const at = islandAt.value;
+ const docked = miniClosed.value || pictureDocked.value;
+ const floating = mediaStation.value === 'corner' && !docked;
+ const following = nextEpisode();
+ const watching = activeMedium.value === 'watch';
+ const name = (
+ <>
+ {episode.title}
+
+ {episode.episodeNumber !== 'Bonus' ? `Ep ${episode.episodeNumber}` : 'Bonus'}
+ {' · '}
+ {watching ? 'Watching' : 'Listening'}
+
+ >
+ );
+
+ // The bar is anchored to the picture, so it has to come after it.
+ const barHost = document.querySelector('[data-pip-bar-host]');
+ const bar = floating && at !== 'card' && ;
+
+ // Clicking the island's body (not one of its controls) opens or closes the card.
+ const onBody = (event: MouseEvent) => {
+ const hit = event.target as Element;
+ if (!hit.closest('button, a, input, label, select, .island-scrub, .island-queue, .island-station, .island-more, .island-grab')) {
+ toggleCard();
+ }
+ };
+
+ return (
+ <>
+ {barHost ? createPortal(bar, barHost) : bar}
+
go(islandBack.value)} />
+
+ {/* Phones: the card's way out, a grabber strip to swipe it down by and
+ a close, standing in for the home control (phones offer only the
+ dock and the card). Other screens never render them. */}
+ {phone && (
+
+
+
+ )}
+ {phone && (
+
+
+
+ )}
+
+
+
+ {/* The artwork's palette, for the whole page to take its accent
+ from (--live-img, --live-img-accent, … on ; once per episode). */}
+ {episode.image && (
+
+ )}
+
+
+
+
+
+ {anchorPositioning.value ? (
+
+ ) : (
+ // No card to open without anchor positioning: the name goes to its episode.
+
+ {name}
+
+ )}
+
+ Open the episode
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {elapsed}
+
+
+
+
+
+ {remaining}
+
+
+
+ {/* Each control sits in its own part: the part flies, the control
+ inside keeps its own press and hover transitions. */}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {episode.video && }
+
+
+
+
+
+
+
+
+
+
+
+ >
+ );
+}
diff --git a/packages/starpod/src/components/media/LiveScript.tsx b/packages/starpod/src/components/media/LiveScript.tsx
new file mode 100644
index 00000000..614a451f
--- /dev/null
+++ b/packages/starpod/src/components/media/LiveScript.tsx
@@ -0,0 +1,187 @@
+import { useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks';
+
+import type { TranscriptCue } from '../../lib/cues';
+import { formatClock } from '../../utils/playable';
+import { currentEpisode, currentTime, seekToEpisode, type PlayableEpisode } from '../state';
+import { cueIndexAt, loadCues } from './cue-cache';
+
+type Props = { episode: PlayableEpisode };
+
+const BEFORE = 5;
+const AFTER = 2;
+// Further than this and the lines on screen aren't the same conversation:
+// crossfade instead of flying lines across unrelated text.
+const JUMP = 3;
+const EASE = 'cubic-bezier(0.25, 1, 0.5, 1)';
+const MOVE_MS = 720;
+
+type Box = { top: number; left: number; right: number; size: number };
+
+/**
+ * FLIP the script from its last layout to its new one. Sizes and line
+ * positions change instantly in the layout (no reflowing transitions, so the
+ * text never re-wraps mid-motion); each line then animates from where it was
+ * to where it is using transforms only: the new live line swells, spoken
+ * lines glide up as they shrink, and arrivals fade up from below.
+ */
+function useFlip(
+ list: { current: HTMLOListElement | null },
+ anchor: number,
+ cues: Array | null
+) {
+ const boxes = useRef(new Map());
+ const lastAnchor = useRef(null);
+
+ useLayoutEffect(() => {
+ const ol = list.current;
+ if (!ol) {
+ return;
+ }
+ // Off screen the lines skip rendering (content-visibility), so nothing
+ // is measured or animated there; back on screen, the next change starts
+ // from where the lines are.
+ if (ol.firstElementChild?.checkVisibility?.({ contentVisibilityAuto: true }) === false) {
+ boxes.current = new Map();
+ lastAnchor.current = null;
+ return;
+ }
+ const calm =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+ const previous = boxes.current;
+ const next = new Map();
+ const moved = lastAnchor.current !== null && lastAnchor.current !== anchor;
+ const jumped = moved && Math.abs(anchor - lastAnchor.current!) > JUMP;
+ const origin = ol.getBoundingClientRect();
+
+ for (const li of Array.from(ol.children) as Array) {
+ li.getAnimations?.().forEach((animation) => animation.cancel());
+ const index = Number(li.dataset.index);
+ const rect = li.getBoundingClientRect();
+ const box = {
+ top: rect.top - origin.top,
+ left: rect.left - origin.left,
+ right: rect.right - origin.left,
+ size: parseFloat(getComputedStyle(li).fontSize) || 16
+ };
+ next.set(index, box);
+ if (!moved || jumped || calm) {
+ continue;
+ }
+ const before = previous.get(index);
+ if (!before) {
+ li.animate?.([{ opacity: 0, transform: 'translateY(18px)' }, {}], {
+ duration: MOVE_MS,
+ easing: EASE
+ });
+ continue;
+ }
+ const fromRight = li.dataset.v === '1';
+ const dx = fromRight ? before.right - box.right : before.left - box.left;
+ const dy = before.top - box.top;
+ const scale = before.size / box.size;
+ if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5 && Math.abs(scale - 1) < 0.01) {
+ continue;
+ }
+ li.style.transformOrigin = fromRight ? 'top right' : 'top left';
+ li.animate?.(
+ [{ transform: `translate(${dx}px, ${dy}px) scale(${scale})` }, { transform: 'none' }],
+ { duration: MOVE_MS, easing: EASE }
+ );
+ }
+
+ if (jumped && !calm) {
+ ol.animate?.([{ opacity: 0.1 }, { opacity: 1 }], { duration: 420, easing: EASE });
+ }
+ boxes.current = next;
+ lastAnchor.current = anchor;
+ }, [anchor, cues, list]);
+}
+
+/**
+ * The stage's signature: the conversation typeset live beside the
+ * player. Each voice speaks in its own face, the line being heard swells, and
+ * lines already spoken shrink back into the page. Any line seeks.
+ */
+export default function LiveScript({ episode }: Props) {
+ const [cues, setCues] = useState | null>(null);
+
+ // Fetched as hydration completes, not after the next frame; again for a
+ // new episode, whose lines replace the last one's (a reply for the old one
+ // arriving late is dropped).
+ useLayoutEffect(() => {
+ if (!episode.slug) {
+ setCues([]);
+ return;
+ }
+ let current = true;
+ setCues(null);
+ void loadCues(episode.slug).then((next) => current && setCues(next));
+ return () => {
+ current = false;
+ };
+ }, [episode.slug]);
+
+ const list = useRef(null);
+ const isCurrent = currentEpisode.value?.id === episode.id;
+ const live = useMemo(
+ () => (cues?.length && isCurrent ? cueIndexAt(cues, currentTime.value + 0.25) : -1),
+ [cues, isCurrent, Math.floor(currentTime.value * 4)]
+ );
+
+ // Idle (not this episode, or not started): the opening line already holds
+ // the stage at full voice, with what follows waiting below it.
+ const idle = live === -1;
+ const anchor = idle ? 0 : live;
+ useFlip(list, idle ? -1 : anchor, cues);
+
+ if (!cues) {
+ return ;
+ }
+
+ if (cues.length === 0) {
+ return ;
+ }
+
+ const start = idle ? 0 : Math.max(0, anchor - BEFORE);
+ const end = Math.min(cues.length, anchor + (idle ? 4 : AFTER + 1));
+ const visible = cues.slice(start, end);
+ const speakers = new Set(cues.map((cue) => cue.n).filter(Boolean)).size;
+
+ return (
+
+ {visible.map((cue, offset) => {
+ const index = start + offset;
+ const distance = index - anchor;
+ return (
+
,
+ document.querySelector('.dock') ?? document.body
+ )}
+ >
+ );
+}
diff --git a/packages/starpod/src/components/media/StageControls.tsx b/packages/starpod/src/components/media/StageControls.tsx
new file mode 100644
index 00000000..8abc4a87
--- /dev/null
+++ b/packages/starpod/src/components/media/StageControls.tsx
@@ -0,0 +1,119 @@
+import { useLayoutEffect, useRef, useState } from 'preact/hooks';
+
+import { QueueIcon } from '../icons';
+import PlayGlyph from './PlayGlyph';
+import PlayToggle from './PlayToggle';
+import {
+ activeMedium,
+ currentEpisode,
+ dequeue,
+ enqueue,
+ isBuffering,
+ isPlaying,
+ playEpisode,
+ queue,
+ type PlayableEpisode
+} from '../state';
+import { formatClock } from '../../utils/playable';
+import { startEngine, watchStage } from './engine';
+import { resumePoint } from './position';
+import MediumSwitch from './MediumSwitch';
+
+type Props = {
+ episode: PlayableEpisode;
+ /**
+ * `overlay`: the large play control over the stage frame (also keeps the
+ * stage's state attributes in sync). `actions`: the play button and
+ * Watch/Listen switch beside the title.
+ */
+ part: 'overlay' | 'actions';
+};
+
+export default function StageControls({ episode, part }: Props) {
+ const anchor = useRef(null);
+ const [resumeAt, setResumeAt] = useState(0);
+
+ const isCurrent = currentEpisode.value?.id === episode.id;
+ const playing = isCurrent && isPlaying.value;
+ const watching = isCurrent && activeMedium.value === 'watch';
+ const buffering = playing && isBuffering.value;
+
+ // Read again when it stops being current: it has just been played.
+ useLayoutEffect(() => {
+ startEngine();
+ setResumeAt(resumePoint(episode.id));
+ }, [episode.id, isCurrent]);
+
+ // Reflect state on the stage so CSS can stage the light, swap artwork for
+ // video, and pin the frame while watching.
+ useLayoutEffect(() => {
+ if (part !== 'overlay') {
+ return;
+ }
+ const stage = anchor.current?.closest('[data-stage]');
+ if (!stage) {
+ return;
+ }
+ stage.toggleAttribute('data-current', isCurrent);
+ stage.toggleAttribute('data-playing', playing);
+ stage.toggleAttribute('data-watching', watching);
+ stage.toggleAttribute('data-buffering', buffering);
+ });
+
+ // The picture leaves for its picture-in-picture place while the stage is
+ // scrolled away, and comes back with it.
+ useLayoutEffect(() => {
+ const room = anchor.current?.closest('[data-stage]')?.querySelector('.stage-room');
+ return part === 'overlay' && isCurrent && room ? watchStage(room) : undefined;
+ }, [isCurrent, part]);
+
+ const label = playing ? 'Pause' : resumeAt > 0 && !isCurrent ? 'Resume' : 'Play';
+
+ if (part === 'overlay') {
+ return (
+
+
+ `${playing ? 'Pause' : resumeAt > 0 && !isCurrent ? 'Resume' : 'Play'} episode ${episode.episodeNumber}: ${episode.title}`
+ }
+ size={30}
+ />
+ {!isCurrent && resumeAt > 0 && (
+ Resume at {formatClock(resumeAt)}
+ )}
+
+ );
+ }
+
+ const queued = queue.value.some((item) => item.id === episode.id);
+
+ return (
+
+
+ {episode.video && }
+ {/* Not offered for the episode that is playing, but it keeps its place
+ (unseen, and out of reach), so the row never changes height: on a
+ phone it can be a line of its own. */}
+
+
+ );
+}
diff --git a/packages/starpod/src/components/media/board.ts b/packages/starpod/src/components/media/board.ts
new file mode 100644
index 00000000..1e5f65b2
--- /dev/null
+++ b/packages/starpod/src/components/media/board.ts
@@ -0,0 +1,777 @@
+/**
+ * Up next, as a board where "the DOM never moves" (the queue demo).
+ *
+ * Now playing, Up next and a shelf of more episodes are slots: plain layout
+ * in the island's card. Episode covers are sibling tiles at the end of the
+ * board, never re-parented; each one fills a slot by name
+ * (`data-⚓️-fill="--slot-q2"`). The ring is that mapping. Every change (play,
+ * queue, reorder, next, an episode ending, the explorer adding one) rewrites
+ * the attribute and one staggered flip() flies every cover that changed slot,
+ * resizing between the big now-playing slot and the small ones. A cover can
+ * be dragged onto any slot: held mid-flight, nudged, and released with a
+ * forced flip. What flies and is dragged is the cover's face, inside it: the
+ * tile on its anchor keeps its style, since Chrome lays an anchor-positioned
+ * box out again on every change to its style.
+ *
+ * The state is state.ts's (`queue`, `currentEpisode`); the board only draws
+ * it and asks for changes. Client-only.
+ */
+import { effect, signal, untracked } from '@preact/signals';
+
+import { flip, hold, nudge, type FlipProps } from '../../motion/propflip';
+import { formatDuration } from '../../utils/playable';
+import {
+ currentEpisode,
+ currentTime,
+ dequeue,
+ enqueue,
+ islandAt,
+ moveInQueue,
+ playEpisode,
+ queue,
+ type PlayableEpisode
+} from '../state';
+
+const A = 'data-⚓️-';
+/* Anchored Auto Layout names a slot and fills it through typed attr().
+ Where that is missing (WebKit 26, Firefox), the board writes the same
+ names in style instead, so every cover still fills its slot. */
+const typedAttr = globalThis.CSS?.supports?.('width: attr(x type())') ?? true;
+const MAX_NEXT = 6;
+const SHELF = 12;
+const STAGGER = 22;
+
+/** Episodes the board has met, by id. */
+const known = new Map();
+/** The shelf's own order: more episodes, the ones played most recently last. */
+let shelf: Array = [];
+let loading: Promise | null = null;
+/** Bumped whenever the shelf changes, so what reads it (nextEpisode()) re-renders. */
+const shelfChanged = signal(0);
+
+type Place = { name: string; order: number; label: string };
+
+/* Writes only what changed: rewriting an attribute or a text to the same value
+ still restyles or relays it out, and a cover's tabindex is dearer still. */
+function set(el: Element, attr: string, value: string) {
+ if (el.getAttribute(attr) !== value) {
+ el.setAttribute(attr, value);
+ }
+}
+
+function text(el: Element, value: string) {
+ if (el.textContent !== value) {
+ el.textContent = value;
+ }
+}
+
+function showImage() {
+ return document.querySelector('.rail-art img, .topbar-show img')?.src;
+}
+
+/**
+ * The shelf comes from the JSON API (see mountBoard() for when). Resolves
+ * whether it loaded: only a shelf that did is kept for later boards, so a
+ * failed request can be made again.
+ */
+function loadShelf(): Promise {
+ loading ??= fetch('/api/episodes/1.json')
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(`Shelf: ${response.status}`);
+ }
+ return response.json();
+ })
+ .then((body) => {
+ const fallback = showImage();
+ for (const episode of body?.episodes?.data ?? []) {
+ const playable: PlayableEpisode = {
+ audio: episode.audio,
+ duration: episode.duration,
+ episodeNumber: episode.episodeNumber,
+ id: episode.id,
+ image: episode.episodeThumbnail ?? fallback,
+ slug: episode.episodeSlug,
+ title: episode.title,
+ video: episode.video
+ };
+ known.set(playable.id, { ...playable, ...known.get(playable.id) });
+ if (!shelf.includes(playable.id)) {
+ shelf.push(playable.id);
+ }
+ }
+ shelfChanged.value++;
+ return true;
+ })
+ .catch(() => {
+ loading = null;
+ return false;
+ });
+ return loading;
+}
+
+const number = (episode: PlayableEpisode) =>
+ episode.episodeNumber && episode.episodeNumber !== 'Bonus' ? `Ep ${episode.episodeNumber}` : 'Bonus';
+
+/** One unit of proof under a title: "Ep 240 · 1 hr 5 min". */
+function caption(episode: PlayableEpisode) {
+ return episode.duration ? `${number(episode)} · ${formatDuration(episode.duration)}` : number(episode);
+}
+
+export interface Board {
+ stop: () => void;
+}
+
+/**
+ * Build the board inside `host` (the island's queue part). Returns the board;
+ * call stop() when the island goes away.
+ */
+export function mountBoard(host: HTMLElement): Board {
+ host.innerHTML = `
+
+
+
Up next
+
+
+
+
More episodes
+
Tap a cover to queue it · drag any cover onto any slot
+
Enter queues a cover, or plays a queued one. Arrows move between covers, Alt with an arrow reorders Up next, Delete takes one out.
+
+
+
+ `;
+ const nextList = host.querySelector('.board-next-list')!;
+ const shelfGrid = host.querySelector('.board-shelf-grid')!;
+ const tileLayer = host.querySelector('.board-tiles')!;
+ const live = host.querySelector('.board-live')!;
+ const tiles = new Map();
+ const hit = (tile: HTMLElement) => tile.querySelector('.tile-hit')!;
+ /** What flies and is dragged: the cover's face (the tile itself stays on its anchor). */
+ const face = (tile: HTMLElement) => tile.firstElementChild as HTMLElement;
+ const tileOf = (el: HTMLElement) => el.parentElement as HTMLElement;
+ let lastNow: string | undefined;
+ let lastQueue = new Set();
+ let committing = false;
+ let focusId: string | undefined;
+
+ const say = (message: string) => (live.textContent = message);
+ const open = () => islandAt.value === 'card';
+
+ /** The ring: which episode fills which slot, in slot order. */
+ function ring() {
+ const now = currentEpisode.value;
+ const next = queue.value.slice(0, MAX_NEXT);
+ // All of Up next, though only its first few show: a queued episode on the
+ // shelf would offer to queue what is already queued.
+ const taken = new Set([now?.id, ...queue.value.map((episode) => episode.id)]);
+ const rest = shelf.filter((id) => !taken.has(id) && known.has(id)).slice(0, SHELF);
+ const places = new Map();
+ let order = 0;
+ if (now) {
+ places.set(now.id, { name: '--slot-now', order: order++, label: 'now playing' });
+ }
+ next.forEach((episode, i) =>
+ places.set(episode.id, {
+ name: `--slot-q${i}`,
+ order: order++,
+ label: `Up next ${i + 1} of ${next.length}, tap to play now`
+ })
+ );
+ rest.forEach((id, i) =>
+ places.set(id, { name: `--slot-s${i}`, order: order++, label: 'more episodes, tap to play next' })
+ );
+ return { next, rest, places };
+ }
+
+ function slots(parent: HTMLElement, count: number, make: (i: number) => HTMLElement) {
+ while (parent.children.length > count) {
+ parent.lastElementChild!.remove();
+ }
+ for (let i = parent.children.length; i < count; i++) {
+ parent.append(make(i));
+ }
+ }
+
+ function tileFor(episode: PlayableEpisode) {
+ let tile = tiles.get(episode.id);
+ if (tile) {
+ // Its artwork may have come with the shelf after the cover was made.
+ const img = tile.querySelector('img')!;
+ if (episode.image && img.getAttribute('src') !== episode.image) {
+ img.src = episode.image;
+ }
+ return tile;
+ }
+ // A cover: the art (the button you tap or drag), a glass chip with its
+ // number on it, and a remove control that shows on hover or focus. The
+ // image is not draggable: the browser's own drag of it would take the
+ // pointer from the cover's at the first move.
+ tile = document.createElement('div');
+ tile.className = 'tile';
+ tile.dataset.id = episode.id;
+ tile.innerHTML = ``;
+ const img = tile.querySelector('img')!;
+ if (episode.image) {
+ img.src = episode.image;
+ }
+ tile.querySelector('.tile-chip')!.textContent = number(episode);
+ tile.querySelector('.tile-remove')!.setAttribute('aria-label', `Remove ${episode.title} from Up next`);
+ wire(tile);
+ // One that appears with the card open (the shelf arriving late) fades in,
+ // in slot order.
+ if (open()) {
+ tile.dataset.arriving = '';
+ window.setTimeout(() => delete tile.dataset.arriving, 1500);
+ }
+ tileLayer.append(tile);
+ tiles.set(episode.id, tile);
+ return tile;
+ }
+
+ const name = (el: HTMLElement, anchor: string) => {
+ set(el, `${A}name`, anchor);
+ set(el, 'data-slot', anchor);
+ if (!typedAttr && el.style.getPropertyValue('anchor-name') !== anchor) {
+ el.style.setProperty('anchor-name', anchor);
+ }
+ };
+
+ /** Write the ring onto the slots and covers. Synchronous, so flip() can measure it. */
+ function render() {
+ name(host.querySelector('.slot-now')!, '--slot-now');
+ const now = currentEpisode.value;
+ // The episode that just stopped being current goes to the end of the
+ // shelf as far as it shows (the conveyor), never off the end of it.
+ if (lastNow && lastNow !== now?.id && !queue.value.some((episode) => episode.id === lastNow)) {
+ const taken = new Set([now?.id, ...queue.value.map((episode) => episode.id)]);
+ const rest = shelf.filter((id) => id !== lastNow);
+ const shown = rest.filter((id) => !taken.has(id) && known.has(id)).slice(0, SHELF - 1);
+ rest.splice(shown.length ? rest.indexOf(shown.at(-1)!) + 1 : 0, 0, lastNow);
+ shelf = rest;
+ }
+ lastNow = now?.id;
+ // One taken out of Up next (not to play it) goes back to the front of the shelf.
+ const queued = new Set(queue.value.map((episode) => episode.id));
+ for (const id of lastQueue) {
+ if (!queued.has(id) && id !== now?.id) {
+ shelf = [id, ...shelf.filter((other) => other !== id)];
+ }
+ }
+ lastQueue = queued;
+ for (const episode of [now, ...queue.value]) {
+ if (episode) {
+ known.set(episode.id, { ...known.get(episode.id), ...episode });
+ }
+ }
+ const { next, rest, places } = ring();
+
+ slots(nextList, next.length + 1, () => {
+ const row = document.createElement('li');
+ row.className = 'board-row';
+ // On phones a queued row's remove sits at its end (player.css), off
+ // the cover, so a tap on the cover still plays it.
+ row.innerHTML = ``;
+ return row;
+ });
+ // The row after Up next says how to add one: the shelf is under it in
+ // every form of the card, once it has covers.
+ const more = rest.length ? 'Tap a cover below to queue it' : 'Queue more from any episode';
+ [...nextList.children].forEach((row, i) => {
+ name(row.querySelector('.slot')!, i < next.length ? `--slot-q${i}` : '--slot-drop');
+ text(
+ row.querySelector('.board-row-name')!,
+ i < next.length ? next[i]!.title : next.length ? more : 'Nothing queued yet'
+ );
+ text(row.querySelector('.board-row-meta')!, i < next.length ? caption(next[i]!) : '');
+ row.toggleAttribute('data-drop', i === next.length);
+ const remove = row.querySelector('.board-row-remove')!;
+ remove.hidden = i >= next.length;
+ if (i < next.length) {
+ set(remove, 'data-id', next[i]!.id);
+ set(remove, 'aria-label', `Remove ${next[i]!.title} from Up next`);
+ }
+ });
+ // Each shelf slot carries its occupant's title and caption beneath it.
+ slots(shelfGrid, rest.length, () => {
+ const cell = document.createElement('div');
+ cell.className = 'shelf-cell';
+ cell.innerHTML = ``;
+ return cell;
+ });
+ [...shelfGrid.children].forEach((cell, i) => {
+ const episode = known.get(rest[i]!)!;
+ name(cell.querySelector('.slot')!, `--slot-s${i}`);
+ text(cell.querySelector('.shelf-cell-title')!, episode.title);
+ text(cell.querySelector('.shelf-cell-meta')!, caption(episode));
+ });
+
+ for (const [id, place] of places) {
+ const tile = tileFor(known.get(id)!);
+ const episode = known.get(id)!;
+ set(tile, `${A}fill`, place.name);
+ set(tile, 'data-slot', place.name);
+ if (!typedAttr && tile.style.getPropertyValue('position-anchor') !== place.name) {
+ tile.style.setProperty('position-anchor', place.name);
+ }
+ set(tile, 'data-order', String(place.order));
+ if (tile.style.getPropertyValue('--slot-i') !== String(place.order)) {
+ tile.style.setProperty('--slot-i', String(place.order));
+ }
+ tile.classList.toggle('is-now', place.name === '--slot-now');
+ tile.toggleAttribute('data-queued', place.name.startsWith('--slot-q'));
+ tile.hidden = false;
+ set(hit(tile), 'aria-label', `${episode.title}: ${place.label}`);
+ }
+ for (const [id, tile] of tiles) {
+ if (!places.has(id)) {
+ tile.hidden = true;
+ tile.classList.remove('is-now');
+ tile.removeAttribute(`${A}fill`);
+ }
+ }
+ }
+
+ /**
+ * One cover is in the tab order: the focused one, or else the first. Done
+ * at the next frame, never in the middle of a change: a tabindex change
+ * makes the browser bring style and layout up to date there and then,
+ * which at the frame it does anyway.
+ */
+ let roving = 0;
+ function roveAll() {
+ cancelAnimationFrame(roving);
+ roving = requestAnimationFrame(() => {
+ const list = ordered();
+ const keep = list.find((tile) => tile.dataset.id === focusId) ?? list[0];
+ tiles.forEach((tile) => rove(tile, tile === keep));
+ });
+ }
+
+ /** The one cover in the tab order, with its remove control when it has one. */
+ function rove(tile: HTMLElement, active: boolean) {
+ // The attribute, not the tabIndex property: reading that asks whether the
+ // button can take focus, which brings style up to date mid-update.
+ const tab = (button: HTMLButtonElement, on: boolean) => set(button, 'tabindex', on ? '0' : '-1');
+ tab(hit(tile), active);
+ tab(tile.querySelector('.tile-remove')!, active && Boolean(tile.dataset.slot?.startsWith('--slot-q')));
+ }
+
+ /**
+ * The covers the keyboard moves between, in slot order. Not the one now
+ * playing: the picture stands in front of it (and where it has no box of
+ * its own, WebKit will not focus it), and a tap on it does nothing.
+ */
+ const ordered = () =>
+ [...tiles.values()]
+ .filter((tile) => !tile.hidden && !tile.classList.contains('is-now'))
+ .sort((a, b) => Number(a.dataset.order) - Number(b.dataset.order));
+
+ /** Change the state and fly every cover that moved, in slot order. */
+ function commit(change: () => void, opts: { stagger?: number; force?: (el: HTMLElement) => boolean } = {}) {
+ committing = true;
+ const shelfBefore = shelf;
+ try {
+ if (!open()) {
+ change();
+ render();
+ // Nothing flies while the card is closed, so a cover still held from
+ // a drag the card closed under goes straight back to its slot.
+ for (const tile of tiles.values()) {
+ if (face(tile).style.transition === 'none') {
+ settle(tile);
+ }
+ }
+ } else {
+ const force = opts.force;
+ flip([...tiles.values()].map(face), () => {
+ change();
+ render();
+ }, {
+ force: force && ((el) => force(tileOf(el))),
+ order: (a, b) => Number(tileOf(a).dataset.order) - Number(tileOf(b).dataset.order),
+ stagger: opts.stagger ?? STAGGER
+ });
+ }
+ roveAll();
+ } finally {
+ committing = false;
+ if (shelf !== shelfBefore) {
+ shelfChanged.value++;
+ }
+ }
+ }
+
+ // ---------- what each gesture means ----------
+
+ const kindOf = (name: string) =>
+ name === '--slot-now' ? 'now' : name.startsWith('--slot-s') ? 'shelf' : 'next';
+ const indexOf = (name: string) => Number(name.replace(/\D+/g, '')) || 0;
+
+ /** The one that plays when the current one leaves now: Up next first, then the shelf. */
+ const successor = () => queue.value[0] ?? known.get(ring().rest[0] ?? '');
+
+ /** Tap: a shelf cover plays next; a queued one plays now. */
+ function tap(tile: HTMLElement) {
+ const episode = known.get(tile.dataset.id!);
+ const kind = kindOf(tile.dataset.slot ?? '');
+ if (!episode || kind === 'now') {
+ return;
+ }
+ if (kind === 'shelf') {
+ commit(() => enqueue(episode, 0));
+ say(`${episode.title} plays next.`);
+ } else {
+ commit(() => playEpisode(episode));
+ say(`Playing ${episode.title}.`);
+ }
+ }
+
+ /** A cover dropped on a slot (or nowhere: it flies home). */
+ function drop(tile: HTMLElement, onto: string | null) {
+ const force = (el: HTMLElement) => el === tile;
+ const episode = known.get(tile.dataset.id!);
+ const from = kindOf(tile.dataset.slot ?? '');
+ if (!episode || !onto || onto === tile.dataset.slot) {
+ commit(() => {}, { force });
+ return;
+ }
+ const to = onto === '--slot-drop' ? 'next' : kindOf(onto);
+ const at = onto === '--slot-drop' ? Infinity : indexOf(onto);
+ commit(() => {
+ if (to === 'now') {
+ // In it goes; what was playing waits at the front of Up next.
+ const was = currentEpisode.value;
+ playEpisode(episode);
+ if (was) {
+ enqueue(was, 0);
+ }
+ } else if (to === 'next') {
+ if (from === 'now') {
+ const following = successor();
+ if (following) {
+ playEpisode(following);
+ }
+ enqueue(episode, at);
+ } else if (from === 'next') {
+ moveInQueue(episode.id, at);
+ } else {
+ enqueue(episode, at);
+ }
+ } else {
+ if (from === 'now') {
+ const following = successor();
+ if (following) {
+ playEpisode(following);
+ }
+ }
+ dequeue(episode.id);
+ lastQueue.delete(episode.id);
+ const others = shelf.filter((id) => id !== episode.id);
+ const shown = ring().rest.filter((id) => id !== episode.id);
+ const before = shown[at];
+ // Past the last cover shown (its slot was the last one): right after
+ // that cover, not behind episodes the shelf has no room to show.
+ const last = shown.at(-1);
+ const index = before
+ ? others.indexOf(before)
+ : last
+ ? others.indexOf(last) + 1
+ : others.length;
+ others.splice(index, 0, episode.id);
+ shelf = others;
+ lastNow = currentEpisode.value?.id;
+ }
+ }, { force });
+ say(`${episode.title} moved.`);
+ }
+
+ /** Take one out of Up next (its cover's remove, or its row's on phones). */
+ function remove(id: string | undefined) {
+ const episode = known.get(id ?? '');
+ if (episode) {
+ commit(() => dequeue(episode.id));
+ say(`${episode.title} is out of Up next.`);
+ }
+ }
+
+ nextList.addEventListener('click', (event) => {
+ const button = (event.target as Element).closest('.board-row-remove');
+ if (button) {
+ remove(button.dataset.id);
+ }
+ });
+
+ // ---------- pointer: tap, or drag onto any slot ----------
+
+ let drag: {
+ tile: HTMLElement;
+ pointerId: number;
+ x: number;
+ y: number;
+ p: FlipProps | null;
+ moved: boolean;
+ over: HTMLElement | null;
+ } | null = null;
+
+ // The slots' rects, read once per drag before anything moves (reading them
+ // after each nudge would lay the card out on every move), and again only
+ // if the card scrolls or the window resizes under the drag.
+ let rects: Array<{ slot: HTMLElement; r: DOMRect }> | null = null;
+ const forget = () => (rects = null);
+ const slotAt = (x: number, y: number) =>
+ rects?.find(({ r }) => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom)?.slot ?? null;
+
+ /** A cover back in its slot, nothing held. */
+ function settle(tile: HTMLElement) {
+ face(tile).style.transition = '';
+ nudge(face(tile), { tx: 0, ty: 0, sx: 1, sy: 1 });
+ }
+
+ /** Nothing held any more: the drag's marks and listeners go. */
+ function release() {
+ if (!drag) {
+ return null;
+ }
+ const { tile, over } = drag;
+ drag = null;
+ over?.removeAttribute('data-hot');
+ delete tile.dataset.held;
+ forget();
+ removeEventListener('scroll', forget, { capture: true });
+ removeEventListener('resize', forget);
+ return tile;
+ }
+
+ /** End a drag without dropping (the card closed under it): the cover goes home. */
+ function letGo() {
+ const tile = release();
+ if (tile) {
+ settle(tile);
+ }
+ }
+
+ function wire(tile: HTMLElement) {
+ tile.addEventListener('pointerdown', (event) => {
+ // One cover at a time, held by one pointer.
+ if (drag || event.button || (event.target as Element).closest('.tile-remove')) {
+ return;
+ }
+ tile.setPointerCapture(event.pointerId);
+ drag = {
+ tile,
+ pointerId: event.pointerId,
+ x: event.clientX,
+ y: event.clientY,
+ p: null,
+ moved: false,
+ over: null
+ };
+ });
+ tile.addEventListener('pointermove', (event) => {
+ if (drag?.tile !== tile || event.pointerId !== drag.pointerId) {
+ return;
+ }
+ const dx = event.clientX - drag.x;
+ const dy = event.clientY - drag.y;
+ if (!drag.moved) {
+ if (Math.hypot(dx, dy) < 5) {
+ return;
+ }
+ drag.moved = true;
+ addEventListener('scroll', forget, { capture: true, passive: true });
+ addEventListener('resize', forget, { passive: true });
+ }
+ rects ??= [...host.querySelectorAll('.slot')].map((slot) => ({ slot, r: slot.getBoundingClientRect() }));
+ if (!drag.p) {
+ tile.dataset.held = '';
+ // Grabbing mid-flight keeps it exactly where it is.
+ drag.p = hold(face(tile));
+ }
+ nudge(face(tile), { ...drag.p!, tx: drag.p!.tx + dx, ty: drag.p!.ty + dy });
+ const over = slotAt(event.clientX, event.clientY);
+ if (over !== drag.over) {
+ drag.over?.removeAttribute('data-hot');
+ over?.setAttribute('data-hot', '');
+ drag.over = over;
+ }
+ });
+ const end = (event: PointerEvent) => {
+ if (drag?.tile !== tile || event.pointerId !== drag.pointerId) {
+ return;
+ }
+ const { moved } = drag;
+ // The slot under the pointer as it lets go: the card may have scrolled
+ // since the last move.
+ const at = [...host.querySelectorAll('.slot')].find((slot) => {
+ const r = slot.getBoundingClientRect();
+ return (
+ event.clientX >= r.left &&
+ event.clientX <= r.right &&
+ event.clientY >= r.top &&
+ event.clientY <= r.bottom
+ );
+ });
+ release();
+ if (moved) {
+ // Its click is a drag's, not a tap; it flies on from where it is.
+ tile.dataset.dragged = '';
+ drop(tile, at?.dataset.slot ?? null);
+ }
+ };
+ tile.addEventListener('pointerup', end);
+ // Cancelled, or capture lost without a pointerup (the tile hidden, the
+ // window blurred): the cover goes home and nothing is dropped.
+ const cancel = (event: PointerEvent) => {
+ if (drag?.tile === tile && event.pointerId === drag.pointerId) {
+ letGo();
+ }
+ };
+ tile.addEventListener('pointercancel', cancel);
+ tile.addEventListener('lostpointercapture', cancel);
+ // The click lands on the cover itself (it holds the pointer while pressed).
+ tile.addEventListener('click', (event) => {
+ if ((event.target as Element).closest('.tile-remove')) {
+ return;
+ }
+ // A drag ends in a click too; only a tap (or a key) means tap.
+ if (tile.dataset.dragged !== undefined) {
+ delete tile.dataset.dragged;
+ return;
+ }
+ tap(tile);
+ });
+ tile.querySelector('.tile-remove')!.addEventListener('click', () => remove(tile.dataset.id));
+ tile.addEventListener('focusin', () => (focusId = tile.dataset.id));
+ hit(tile).addEventListener('keydown', (event) => key(tile, event));
+ }
+
+ // ---------- keys: the drag's equivalents ----------
+
+ function key(tile: HTMLElement, event: KeyboardEvent) {
+ const list = ordered();
+ const at = list.indexOf(tile);
+ const episode = known.get(tile.dataset.id!);
+ const queued = tile.dataset.slot?.startsWith('--slot-q');
+ const step = event.key === 'ArrowUp' || event.key === 'ArrowLeft' ? -1 : 1;
+ if (event.key.startsWith('Arrow') && event.altKey && queued && episode) {
+ const index = queue.value.findIndex((item) => item.id === episode.id);
+ commit(() => moveInQueue(episode.id, index + step));
+ say(`${episode.title} is ${Math.max(1, Math.min(queue.value.length, index + step + 1))} in Up next.`);
+ hit(tile).focus();
+ } else if (event.key.startsWith('Arrow')) {
+ const target = list[Math.max(0, Math.min(list.length - 1, at + step))];
+ if (target) {
+ list.forEach((item) => rove(item, item === target));
+ hit(target).focus();
+ }
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && queued && episode) {
+ commit(() => dequeue(episode.id));
+ say(`${episode.title} is out of Up next.`);
+ const after = list[at + 1];
+ if (after) {
+ hit(after).focus();
+ }
+ } else if ((event.key === 'Enter' || event.key === ' ') && !event.repeat) {
+ tap(tile);
+ } else {
+ return;
+ }
+ // A key the board handles is not also acted on by anything behind it.
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ // ---------- staying in step with everyone else ----------
+
+ // The card closing under a drag (Escape, a number key) ends it.
+ const stopClosing = effect(() => {
+ if (!open()) {
+ untracked(letGo);
+ }
+ });
+
+ const stopState = effect(() => {
+ void currentEpisode.value;
+ void queue.value;
+ if (!committing) {
+ // Auto-advance, the explorer's enqueue, a play elsewhere: the same flight.
+ untracked(() => commit(() => {}));
+ }
+ });
+ // The board is always current (every change renders it, open or not), so
+ // opening the card only flips. The shelf is fetched and drawn ahead of
+ // time, on idle once something has actually played (its clock has moved),
+ // while the card is parked; when the visitor asks to save data, only once
+ // the card first opens. Should it arrive with the card open, it waits for
+ // the island to land, then its covers fade in one after another.
+ let stopped = false;
+ function arrive() {
+ if (stopped) {
+ return;
+ }
+ const island = document.getElementById('player');
+ if (open() && island?.hasAttribute('data-moving')) {
+ window.setTimeout(arrive, 100);
+ return;
+ }
+ commit(() => {});
+ }
+ const idle = window.requestIdleCallback ?? ((fn: () => void) => window.setTimeout(fn, 200));
+ const lean = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection?.saveData === true;
+ // A shelf that failed to load is asked for again when the card is open
+ // (at once if it is), then each time it opens: never in a loop.
+ let asked = false;
+ const failed = signal(false);
+ const stopAsking = effect(() => {
+ const due = failed.value || lean ? open() : currentTime.value > 0;
+ if (asked || !due) {
+ return;
+ }
+ asked = true;
+ idle(() => {
+ if (stopped) {
+ return;
+ }
+ void loadShelf().then((ok) => {
+ if (stopped) {
+ return;
+ }
+ if (ok) {
+ arrive();
+ stopAsking();
+ } else {
+ asked = false;
+ // Asked again once the card next opens (not while it is open now).
+ failed.value = true;
+ }
+ });
+ });
+ });
+
+ return {
+ stop: () => {
+ stopped = true;
+ letGo();
+ cancelAnimationFrame(roving);
+ stopClosing();
+ stopState();
+ stopAsking();
+ }
+ };
+}
+
+/**
+ * What the skip button goes to: Up next's first, or else the shelf's. Only
+ * Up next plays on its own when an episode ends (state.ts, playNext()); the
+ * shelf's first is a skip the visitor chooses.
+ */
+export function nextEpisode(): PlayableEpisode | undefined {
+ void shelfChanged.value;
+ if (queue.value[0]) {
+ return queue.value[0];
+ }
+ const taken = new Set([currentEpisode.value?.id]);
+ const id = shelf.find((item) => !taken.has(item) && known.has(item));
+ return id ? known.get(id) : undefined;
+}
diff --git a/packages/starpod/src/components/media/cue-cache.ts b/packages/starpod/src/components/media/cue-cache.ts
new file mode 100644
index 00000000..e54dd17f
--- /dev/null
+++ b/packages/starpod/src/components/media/cue-cache.ts
@@ -0,0 +1,55 @@
+import type { TranscriptCue } from '../../lib/cues';
+
+const cache = new Map>>();
+
+/**
+ * Timed transcript lines for an episode, fetched once per visit and shared by
+ * everything that reads them (the live script, the scrubber preview).
+ * Resolves to an empty list when the episode has no transcript.
+ */
+export function loadCues(slug: string): Promise> {
+ let request = cache.get(slug);
+ if (!request) {
+ // The endpoint answers every episode, with [] when it has no transcript,
+ // so a failure is the network's or the server's: forget it, and the next
+ // reader asks again.
+ const attempt: Promise> = fetch(`/api/cues/${slug}.json`)
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(`cues: ${response.status}`);
+ }
+ return response.json();
+ })
+ // cueIndexAt() searches by start time: not every transcript source
+ // lists its lines in order.
+ .then((cues: Array) =>
+ Array.isArray(cues) ? [...cues].sort((a, b) => a.s - b.s) : []
+ )
+ .catch(() => {
+ if (cache.get(slug) === attempt) {
+ cache.delete(slug);
+ }
+ return [];
+ });
+ request = attempt;
+ cache.set(slug, request);
+ }
+ return request;
+}
+
+/** The index of the line being spoken at `time` (binary search). */
+export function cueIndexAt(cues: Array, time: number) {
+ let low = 0;
+ let high = cues.length - 1;
+ let found = 0;
+ while (low <= high) {
+ const mid = (low + high) >> 1;
+ if (cues[mid].s <= time) {
+ found = mid;
+ low = mid + 1;
+ } else {
+ high = mid - 1;
+ }
+ }
+ return found;
+}
diff --git a/packages/starpod/src/components/media/engine.ts b/packages/starpod/src/components/media/engine.ts
new file mode 100644
index 00000000..423cae39
--- /dev/null
+++ b/packages/starpod/src/components/media/engine.ts
@@ -0,0 +1,839 @@
+/**
+ * The media engine: one