diff --git a/packages/starpod/src/components/SearchDialog.tsx b/packages/starpod/src/components/SearchDialog.tsx index bc18eed..e26b598 100644 --- a/packages/starpod/src/components/SearchDialog.tsx +++ b/packages/starpod/src/components/SearchDialog.tsx @@ -8,7 +8,7 @@ import { } from 'preact/hooks'; import { navigate } from 'astro:transitions/client'; import { flipFrom, layoutRect, nudge, reducedMotion } from '../motion/propflip'; -import { isSearchOpen, islandAt, islandBack } from './state'; +import { isSearchOpen } from './state'; import { personFact } from '../lib/cast'; import { loadPaletteEpisodes, type PaletteEpisode } from './palette-episodes'; import { matchesWords } from './explorer/query'; @@ -253,26 +253,6 @@ export default function SearchDialog({ // life, always reading the latest results and selection. const handleKeyDown = useRef((_e: KeyboardEvent) => {}); handleKeyDown.current = (e: KeyboardEvent) => { - // Open search with cmd+k or ctrl+k - if ((e.metaKey || e.ctrlKey) && e.key === 'k') { - e.preventDefault(); - // The now-playing card is a modal that leaves the rest of the page - // inert: the shortcut closes it first (the island's own way home, - // loaded lazily so the palette doesn't carry the player), then opens - // the palette on the next frame. The island lifts inert only once it - // has landed, but a modal escapes its ancestors' inert, so - // the palette takes typing at once. - if (!isSearchOpen.value && islandAt.value === 'card') { - void import('./media/Island').then(({ go }) => { - go(islandBack.value); - requestAnimationFrame(() => (isSearchOpen.value = true)); - }); - return; - } - isSearchOpen.value = !isSearchOpen.value; - return; - } - // Close on escape if (e.key === 'Escape' && isSearchOpen.value) { e.preventDefault(); diff --git a/packages/starpod/src/components/rail.ts b/packages/starpod/src/components/rail.ts new file mode 100644 index 0000000..7364863 --- /dev/null +++ b/packages/starpod/src/components/rail.ts @@ -0,0 +1,460 @@ +// The sidebar is held by one divider. While it is held the layout is one +// number: the divider's x, written to the line and to the page's column, and +// the rail (anchored to the line) follows in CSS, re-forming by its own +// width. Letting go projects the throw, picks a stop and PropFLIPs only the +// divider there; the rail rides it, the page re-lays once and glides, and +// other areas' registered boxes flip. The toggle, "[", double-click and the +// arrow keys take the same glide. Also runs the collapsed rail's travelling +// tooltip. +import { flipLayout, nudge, reducedMotion, slomo } from '../motion/propflip'; + +export const root = document.documentElement; +export const wide = window.matchMedia('(min-width: 1024px)'); +const anchors = CSS.supports( + 'anchor-name', + 'attr(data-a type())' +); +// The tooltip needs only plain anchor positioning (rail.css places it +// without attributes where typed attr() is missing). +const placeable = CSS.supports('anchor-name', '--a'); +export const collapsed = () => root.dataset.rail === 'collapsed'; +const $ = (selector: string) => document.querySelector(selector); +// The two stops, from rail.css; the rail re-forms halfway between them. +// Read once: a computed-style read here, on every move of a drag and in +// every settle, would force a style recalc each time. +let railStops: number[] | null = null; +export const stops = () => + (railStops ??= ['--rail-shut', '--rail-open'].map((name) => + parseFloat(getComputedStyle(root).getPropertyValue(name)) + )); +const tip = () => document.getElementById('rail-tip'); +const tipText = (el: HTMLElement) => + el.dataset.tip || el.textContent?.trim() || ''; +let tipTimer = 0; + +// Stacked (the icon rail), the platform and host links sit under the +// stack's button. +function stack(shut: boolean) { + document + .querySelectorAll('.rail-follow-body, .rail-hosts-body') + .forEach((list) => (list.inert = shut)); +} + +export function sync() { + const shut = collapsed(); + const toggle = document.querySelector('.rail-toggle'); + if (toggle) { + toggle.setAttribute('aria-expanded', String(!shut)); + toggle.dataset.tip = shut ? 'Expand sidebar' : 'Collapse sidebar'; + } + stack(shut); + $('.rail-edge')?.setAttribute('aria-valuenow', String(stops()[shut ? 0 : 1])); + // Without anchored tooltips, native titles name the icons. + if (!placeable) { + document + .querySelectorAll('.rail [data-tip], .rail-nav a') + .forEach((el) => { + el.title = shut || el === toggle ? tipText(el) : ''; + }); + } +} + +export function showTip(el: HTMLElement) { + const box = tip(); + if (!placeable || !box) { + return; + } + clearTimeout(tipTimer); + document.querySelector('[data-tip-at]')?.removeAttribute('data-tip-at'); + el.setAttribute('data-tip-at', ''); + box.querySelector('.rail-tip-box > span')!.textContent = tipText(el); + box.querySelector('kbd')!.textContent = el.dataset.tipKey ?? ''; + if (!box.matches(':popover-open')) { + box.showPopover(); + } +} + +export function hideTip() { + clearTimeout(tipTimer); + const box = tip(); + if (box?.matches(':popover-open')) { + box.hidePopover(); + } +} + +// The first name waits a beat; moving along the rail, it travels. +export function tipSoon(el: HTMLElement) { + clearTimeout(tipTimer); + if (tip()?.matches(':popover-open')) { + showTip(el); + } else { + tipTimer = window.setTimeout(() => showTip(el), 350); + } +} + +export function hideTipSoon(delay: number) { + clearTimeout(tipTimer); + tipTimer = window.setTimeout(hideTip, delay); +} + +// The divider's value stays within its stops; the hand's overshoot past the +// open stop is only drawn. +const valueAt = (x: number) => String(Math.round(Math.min(stops()[1]!, x))); + +// Held: one number, on the line and the page's column (never on :root, +// which would restyle the whole page every frame). +function apply(x: number) { + $('.rail-edge')!.style.left = `${x}px`; + $('.app')!.style.gridTemplateColumns = `${x}px minmax(0, 1fr)`; + $('.rail-edge')!.setAttribute('aria-valuenow', valueAt(x)); +} + +// The rail's form while held: the icon rail below the middle. At a change +// the filling pieces are anchored again first (data-reforming lets them out +// of the flow), so the re-form travels from where they are, then holds for +// long enough to land. +function form(narrow: boolean, travel: boolean) { + const next = narrow ? 'icons' : 'open'; + if (travel) { + reform(); + } + root.dataset.railForm = next; + // The stacks take the form the hold is in (sync() would read the settled + // one, which the hold hasn't changed yet). + stack(narrow); +} + +// The pieces sit in their slots in flow at rest (rail.css). A re-form +// anchors them again (data-reforming) so they travel from where they are, +// and lets them back into flow once they have landed (their longest leg, +// stagger included, at the page's --slomo). The switch itself takes no +// transition (data-anchoring, held for one style flush): only the change of +// form that follows travels. The hold is timed from the frame after the one +// that draws the change, as the legs are: a slow first frame would +// otherwise cut their ends short. +let reformed = 0; +let reforming = 0; +function reform() { + const rail = $('.rail')!; + rail.dataset.anchoring = ''; + rail.dataset.reforming = ''; + void getComputedStyle(rail).transitionDuration; + delete rail.dataset.anchoring; + clearTimeout(reforming); + const s = slomo(); + const at = ++reformed; + requestAnimationFrame(() => + requestAnimationFrame(() => { + if (at === reformed) { + reforming = window.setTimeout( + () => delete rail.dataset.reforming, + 760 * s + ); + } + }) + ); +} + +// A click on the toggle or a release settles in the next frame: the input +// event returns at once, and the flip's measurement at the new width lands +// in the frame that lays the page out there anyway. Keys and double-clicks +// settle at once, so the divider's value is right as they return; any +// settle replaces one still waiting. +let settleFrame = 0; +let settleTo: number | null = null; +export function settleSoon(width: number) { + cancelAnimationFrame(settleFrame); + settleTo = width; + settleFrame = requestAnimationFrame(() => settle(width)); +} +// Collapsed, counting a settle still waiting for its frame. +const shutSoon = () => { + const [shut, open] = stops(); + return settleTo === null ? collapsed() : settleTo < (shut + open) / 2; +}; + +// Glide the divider to a stop. The page's column snaps there, the page +// glides in from where it was (picking up mid-flight), and the divider and +// every registered box flip; the rail rides the divider. +export function settle(width: number) { + cancelAnimationFrame(settleFrame); + settleTo = null; + const [shut, open] = stops(); + const next = width < (shut + open) / 2 ? 'collapsed' : 'expanded'; + try { + localStorage.setItem('starpod:rail', next); + } catch { + // No storage: the choice lasts for this page only. + } + hideTip(); + document + .querySelectorAll('.rail-fly:popover-open') + .forEach((fly) => fly.hidePopover()); + const main = $('.main'); + const rest = () => { + root.dataset.rail = next; + delete root.dataset.railForm; + $('.rail-edge')?.style.removeProperty('left'); + $('.app')?.style.removeProperty('grid-template-columns'); + }; + if (!wide.matches || !anchors || reducedMotion() || !main) { + rest(); + main?.style.removeProperty('translate'); + delete main?.dataset.gliding; + sync(); + return; + } + // Where the page column starts now (its grid column, plus any glide or + // ride in progress) and where it will start: known numbers, so nothing + // here forces a layout of the page. + const shift = + 'gliding' in main.dataset || main.style.translate + ? parseFloat(getComputedStyle(main).translate) || 0 + : 0; + const column = parseFloat($('.app')!.style.gridTemplateColumns); + const from = + (Number.isNaN(column) ? stops()[collapsed() ? 0 : 1]! : column) + shift; + // The page column starts its glide where it was, set inside the update so + // the flip's own commit (the one reflow) commits it too. (Boxes in the + // column are measured against it, so its translate never reads as a + // move.) Anchored again before the flip's first read, so the pieces travel + // from their slots now to their slots in the new form. + reform(); + const moves = flipLayout( + () => { + rest(); + main.style.transition = 'none'; + main.style.translate = `${from - width}px 0`; + main.dataset.gliding = ''; + }, + { + frame: (el) => (main.contains(el) ? main : null), + extra: [$('.rail-edge')] + } + ); + // Nothing moved, so nothing was committed: a style flush is enough to + // start from here (a layout flush would re-lay every anchored box). + if (!moves.length) { + void getComputedStyle(main).translate; + } + main.style.transition = ''; + main.style.translate = ''; + // Over when it lands or is cut short, and never started when the column + // didn't move. + main.ontransitionend = main.ontransitioncancel = (event) => { + if (event.target === main) { + delete main.dataset.gliding; + } + }; + if (from === width) { + delete main.dataset.gliding; + } + sync(); +} + +/** The stop the rail isn't at, or isn't about to be. */ +export const other = () => stops()[shutSoon() ? 1 : 0]!; + +// Holding the divider: the hand moves it, letting go throws it to a stop. +const nearest = (x: number, snaps: number[]) => + snaps.reduce((a, b) => (Math.abs(b - x) < Math.abs(a - x) ? b : a)); + +// Grabbing mid-glide: make the layout equal what is on screen (the divider +// where its pixels are, the page column under it) with no transition, and +// carry on from there. +function freeze() { + const edge = $('.rail-edge')!; + const main = $('.main')!; + const x = edge.getBoundingClientRect().left; + // At rest there is nothing in flight to catch, and nothing to measure. + if (!('gliding' in main.dataset) && !edge.getAnimations().length) { + apply(x); + return { x, caught: false }; + } + flipLayout( + () => { + edge.style.transition = 'none'; + nudge(edge, { tx: 0, ty: 0, sx: 1, sy: 1 }); + main.style.transition = 'none'; + main.style.translate = ''; + delete main.dataset.gliding; + apply(x); + }, + { frame: (el) => (main.contains(el) ? main : null) } + ); + void edge.offsetWidth; + edge.style.transition = ''; + main.style.transition = ''; + return { x, caught: true }; +} + +type Drag = { + // The pointer that took hold; another finger can't move or end it. + pointerId: number; + x0: number; + w0: number; + // Where the hand wants the divider, and the frame that will put it there + // (0 when none is waiting). + x: number; + frame: number; + samples: Array<[number, number]>; + moved: boolean; + narrow: boolean; + costs: number[]; + ride: boolean; +}; +let drag: Drag | null = null; + +/** A press on the divider takes hold of it. */ +export function press(event: PointerEvent, edge: HTMLElement) { + if (event.button || drag) { + return; + } + // No text selection, no native drag: on a long page either costs more + // than the whole layout. A settle still waiting is the hand's now. + event.preventDefault(); + cancelAnimationFrame(settleFrame); + settleTo = null; + edge.setPointerCapture(event.pointerId); + const { x: w0, caught } = freeze(); + const [shut, open] = stops(); + const rail = $('.rail')!; + const narrow = w0 < (shut + open) / 2; + // Caught mid-glide, pieces in flight finish travelling, and a rail held on + // the far side of the middle from its form re-forms. + const inFlight = caught || narrow !== collapsed(); + edge.dataset.held = ''; + rail.dataset.held = ''; + form(narrow, inFlight); + // For anything riding --rail-edge that would otherwise ease after it (an + // attribute on the root restyles only what selects on it). + root.dataset.railHeld = ''; + drag = { + pointerId: event.pointerId, + x0: event.clientX, + w0, + x: w0, + frame: 0, + samples: [[event.timeStamp, event.clientX]], + moved: false, + narrow, + costs: [], + ride: false + }; +} + +// A move only records the hand; the next frame puts the divider and the +// page's column there, once however many moves arrive. Writing the width in +// the event would leave layout dirty for whatever reads boxes in the same +// event (prop-for-that's pointer-local does, for whatever is hovered), +// forcing a layout of the page on every move. +function move(event: PointerEvent) { + if (drag?.pointerId !== event.pointerId) { + return; + } + const dx = event.clientX - drag.x0; + drag.moved ||= Math.abs(dx) > 3; + drag.samples.push([event.timeStamp, event.clientX]); + while ( + drag.samples.length > 2 && + event.timeStamp - drag.samples[0]![0] > 100 + ) { + drag.samples.shift(); + } + const [shut, open] = stops(); + drag.x = Math.min(open + 48, Math.max(shut, drag.w0 + dx)); + drag.frame ||= requestAnimationFrame(follow); +} +document.addEventListener('pointermove', move); + +function follow() { + if (!drag) { + return; + } + drag.frame = 0; + const { x } = drag; + const [shut, open] = stops(); + const main = $('.main')!; + if (drag.ride) { + // Too long a page to re-lay every frame: the line and the rail follow + // the hand, the page rides on a translate and re-lays once when it is + // let go. + $('.rail-edge')!.style.left = `${x}px`; + $('.rail-edge')!.setAttribute('aria-valuenow', valueAt(x)); + main.style.translate = `${x - drag.w0}px 0`; + } else { + // The page re-lays under the hand while that fits in a frame: the first + // few frames time the page's own re-lay, and a page that takes longer + // rides. The rail re-lays at the line's every move either way, riding + // or not, so it is laid out first and left out of the time: in WebKit + // it alone took ~10ms, and riding saved none of it. (Without anchors + // the rail is the grid's column, so the page never rides.) + const timed = anchors && drag.costs.length < 3; + if (timed) { + $('.rail-edge')!.style.left = `${x}px`; + void $('.rail')!.offsetWidth; + } + const start = performance.now(); + apply(x); + if (timed) { + void main.offsetWidth; + drag.costs.push(performance.now() - start); + if ( + drag.costs.length === 3 && + [...drag.costs].sort((a, b) => a - b)[1]! > 8 + ) { + drag.ride = true; + $('.app')!.style.gridTemplateColumns = `${drag.w0}px minmax(0, 1fr)`; + main.style.translate = `${x - drag.w0}px 0`; + } + } + } + // Crossing halfway re-forms the rail; its pieces travel for that, then + // sit in their slots again. + const narrow = x < (shut + open) / 2; + if (narrow !== drag.narrow) { + drag.narrow = narrow; + form(narrow, true); + } +} + +// Letting go: the last 100ms of movement is a velocity; a throw coasts about +// 220ms, and the stop nearest where it would come to rest wins. A hand that +// stopped before lifting threw nothing. +function release(event: PointerEvent) { + if (!drag || drag.pointerId !== event.pointerId) { + return; + } + const [[t0, x0], [t1, x1]] = [drag.samples[0]!, drag.samples.at(-1)!]; + const v = t1 > t0 && event.timeStamp - t1 < 80 ? (x1 - x0) / (t1 - t0) : 0; + // Where the hand let go, though the frame showing it may not have come: + // that frame is dropped, and the glide starts from what is on screen. + cancelAnimationFrame(drag.frame); + const { x } = drag; + const target = drag.moved + ? nearest(x + v * 220, stops()) + : stops()[collapsed() ? 0 : 1]!; + letGo(); + settleSoon(target); +} +function letGo() { + drag = null; + delete $('.rail-edge')!.dataset.held; + delete $('.rail')!.dataset.held; + delete root.dataset.railHeld; +} +// Narrowed to the phone layout mid-hold, the rail is gone: the hold ends at +// the stop nearest where it was, the page back in its grid. +wide.addEventListener('change', () => { + if (!wide.matches && drag) { + cancelAnimationFrame(drag.frame); + const target = nearest(drag.x, stops()); + letGo(); + settle(target); + } +}); +document.addEventListener('pointerup', release); +document.addEventListener('pointercancel', release); +// Capture can go without an up or a cancel (the pointer's page lost focus, +// say): the hold still ends. +document.addEventListener('lostpointercapture', release); diff --git a/packages/starpod/src/components/search-shortcut.ts b/packages/starpod/src/components/search-shortcut.ts new file mode 100644 index 0000000..e6fb818 --- /dev/null +++ b/packages/starpod/src/components/search-shortcut.ts @@ -0,0 +1,25 @@ +import { isSearchOpen, islandAt, islandBack } from './state'; + +// ⌘K (Ctrl+K) opens and closes the palette. It listens from the first +// script, not from the palette's island, which hydrates once the page is +// idle: pressed before then, the palette opens as it hydrates. +document.addEventListener('keydown', (e) => { + if (!(e.metaKey || e.ctrlKey) || e.key !== 'k') { + return; + } + e.preventDefault(); + // The now-playing card is a modal that leaves the rest of the page inert: + // the shortcut closes it first (the island's own way home, loaded lazily + // so this doesn't carry the player), then opens the palette on the next + // frame. The island lifts inert only once it has landed, but a modal + // escapes its ancestors' inert, so the palette takes typing at + // once. + if (!isSearchOpen.value && islandAt.value === 'card') { + void import('./media/Island').then(({ go }) => { + go(islandBack.value); + requestAnimationFrame(() => (isSearchOpen.value = true)); + }); + return; + } + isSearchOpen.value = !isSearchOpen.value; +}); diff --git a/packages/starpod/src/layouts/Layout.astro b/packages/starpod/src/layouts/Layout.astro index 501b3b2..53be933 100644 --- a/packages/starpod/src/layouts/Layout.astro +++ b/packages/starpod/src/layouts/Layout.astro @@ -555,471 +555,34 @@ const publicationLinkTag = +