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) => ( + + + + 15 + +); + +export const ForwardIcon = (p: IconProps) => ( + + + + 30 + +); + +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 }) => ( + + + {p.queued ? : } + +); + +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 }) => ( + + + {p.muted ? ( + + ) : ( + + )} + +); + +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 ( +
+
+ + {episode.title} + + + {anchorPositioning.value && ( + + )} + {watching && ( + + )} + +