~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
599 lines · 19.3 KB Raw History
<script lang="ts">
	import { ErrorMessage, formOf, recallSkeleton, Skeleton, Tree, unopened, type ActionHandler, type UiCall, type UiTree, type UiToolHandler, type UiUploadHandler } from '@hud/renderer';
	import type { Call, View } from '@hud/shared/result';

	// The story viewer: a pager of stories over the tabs, as a photo app goes
	// through who has stories. Each page is a call (a List's item's, or a
	// story's own screen, a route's with `pager`), drawn as its own tree, the
	// pages either side read ahead and drawn waiting (`active` false). On a
	// phone it fills the window; in a box wide enough (a container query, so
	// the server draws what the browser hydrates) it is Instagram's: a dark
	// window, the app's wordmark at its top-left and ✕ at its top-right, the
	// page a 9:16 column in the middle as tall as the box allows, and the
	// pages either side beside it, small and dimmed, a click on one going to
	// it. A sideways drag follows the finger: the pages move a slot with it,
	// the one showing shrinking and fading as the one beside it comes in,
	// and let go past a quarter of the width (or flicked) it goes there,
	// else back. A page's Slides running off its end goes on (`onend`), and
	// past the last closes. A drag down closes it, as do Escape and ✕; ← and
	// → go between pages, and with a mouse so do the arrows beside it. The
	// page it is at, and the screen of the story its Slides shows there
	// (`onslide`), it tells (`onat`) once both have settled, so the app's
	// URL follows the story shown; drawn again at a story (`slide`), the
	// page it starts at begins there. A sheet opened from a page (`onopen`'s
	// `sheet`) leaves it open under the sheet, `held`: its page waits, and
	// its keys are the sheet's. A page drawn a while ago (`recall`) is drawn
	// as it last was until its call answers; the page the server answered
	// (`seed`) is drawn from that, and not asked again. The view of the
	// page in front it tells (`onview`), so the page's head is its. A page
	// whose call opens it at a form (Your story's `compose`, with none of
	// one's own) opens it only where it is the page tapped (`start`) and
	// while it has not been left: read ahead beside another, swiped to, or
	// come back to, it is drawn with its form unmarked (`unopened`). The
	// renderer opens it only in the tree in front (`active`). Where the page
	// tapped does open at its form (none of one's own), the stories are not
	// drawn: that form alone is (`alone`), over what is under them, as the
	// frame's action's is, and it closing, sent or not, closes them, as a
	// photo app's Your story with none goes to the camera and back to the
	// feed; until that page answers, nothing is drawn (`waiting`), not its
	// last tree, since it may be only that form.

	type Page = { view: View | null; signIn: boolean };

	let {
		calls,
		start,
		seed = null,
		slide = null,
		wordmark,
		recall,
		load,
		onaction,
		ontool,
		onupload,
		onopen,
		held = false,
		onsignin,
		onat,
		onview,
		onclose
	}: {
		calls: UiCall[];
		start: number;
		/** The page at `start` as the server answered it: drawn from the first paint, and not asked again. */
		seed?: Page | null;
		/** The screen of the story the page at `start` begins at (its Slides' picture's `open`): drawn again where it was. */
		slide?: Call | null;
		/** The app's wordmark, drawn at the top-left of a wide box. */
		wordmark?: string;
		/** A page's call's last tree, where the app has it, drawn until it answers again. */
		recall: (call: Call) => View | null;
		/** A page's call made, and what it answered. */
		load: (call: Call) => Promise<Page>;
		onaction: ActionHandler;
		/** A page's form's tools (a story added, a report); none signed out, so it offers none. */
		ontool?: UiToolHandler;
		/** A page's form's photos uploaded; none signed out. */
		onupload?: UiUploadHandler;
		/** A call opened from a page: a sheet over it, or else the pager closes and the app opens it. */
		onopen: (call: Call, sheet: boolean) => void;
		/** Something is over it (a sheet): its page waits, and it takes no keys. */
		held?: boolean;
		onsignin: () => void;
		/** The page showing is the one at this place, showing the story whose screen is `shown` (none where its Slides has none, or has not said). */
		onat: (at: number, shown: Call | null) => void;
		/** The view of the page in front, once it has one. */
		onview?: (view: View) => void;
		onclose: () => void;
	} = $props();

	// svelte-ignore state_referenced_locally
	let at = $state(start);
	/** Whether the page tapped opens at a form (its call's `compose`): drawn from nothing until it answers, since it may be only that form. */
	// svelte-ignore state_referenced_locally
	const composes = calls[start]?.args.compose !== undefined;
	// svelte-ignore state_referenced_locally
	let pages: Page[] = $state.raw(calls.map((call, i) => (i === start && seed ? seed : { view: i === start && composes ? null : recall(call), signIn: false })));
	// svelte-ignore state_referenced_locally
	const asked = new Set<number>(seed ? [start] : []);
	/** The page tapped, as the pager opened (`start` follows the page shown after). */
	// svelte-ignore state_referenced_locally
	const tapped = start;
	/** Whether the page tapped was left: from then on, its form opens nothing by itself, and its Slides begins where it would. */
	let leftTapped = $state(false);
	/** A page's tree as it is drawn: its form marked open only on the page tapped, until it is left. */
	const drawnUi = (i: number, ui: UiTree): UiTree => (i === tapped && !leftTapped ? ui : unopened(ui));
	/** The tree of the page tapped where its form opened by itself, drawn as that form alone; null where it did not, or once the page is left. */
	const alone = $derived.by(() => {
		const view = pages[tapped]?.view;
		return !leftTapped && view?.renderer === 'tree' && formOf(view.ui.root) !== null ? view.ui : null;
	});
	/** The page tapped, opening at a form, has not answered: nothing is drawn yet. */
	const waiting = $derived(composes && !leftTapped && !pages[tapped]?.view);
	/** The screen of the story the page in front shows, as its Slides said. */
	// svelte-ignore state_referenced_locally
	let shown: Call | null = $state.raw(slide);

	/** A page's call made, what it answers drawn in its place; but where it draws its last tree, a failure leaves it. */
	async function read(i: number) {
		if (i < 0 || i >= calls.length || asked.has(i)) return;
		asked.add(i);
		const page = await load(calls[i]);
		const kept = (was: Page) => was.view?.renderer === 'tree' && page.view?.renderer === 'error' && !page.signIn;
		pages = pages.map((p, j) => (j === i && !kept(p) ? page : p));
	}

	/** A page read again (a story of it deleted). */
	async function reread(i: number) {
		const page = await load(calls[i]);
		pages = pages.map((p, j) => (j === i ? page : p));
	}

	// The page showing, and those either side read ahead.
	$effect(() => {
		for (const i of [at, at + 1, at - 1]) void read(i);
	});

	// The page in front's view, told as it comes.
	$effect(() => {
		const view = pages[at]?.view;
		if (view) onview?.(view);
	});

	// Where it is, told once a move and the story it shows have both settled
	// (the page in front's Slides says its story as it becomes active), and
	// only where that changed.
	// svelte-ignore state_referenced_locally
	let told = JSON.stringify([start, slide]);
	$effect(() => {
		void [at, shown];
		queueMicrotask(() => {
			const now = JSON.stringify([at, shown]);
			if (now === told || closing) return;
			told = now;
			onat(at, shown);
		});
	});

	let width = $state(1);
	let height = $state(1);
	/** How far the finger has gone: sideways between pages, down to close. */
	let dx = $state(0);
	let dy = $state(0);
	/** Letting go: the pages move to where they settle, not with the finger. */
	let settling = $state(false);
	let gesture: { id: number; x: number; y: number; t: number; axis: 'x' | 'y' | null } | null = null;
	/** A drag ended: the click it ends in is not a tap on the page. */
	let dragged = false;

	const SETTLE = 300;
	const swipe = $derived(Math.min(Math.abs(dx) / width, 1));
	const fall = $derived(Math.max(0, Math.min(dy / height, 1)));

	function settle(then: () => void) {
		settling = true;
		setTimeout(() => {
			then();
			settling = false;
		}, SETTLE);
	}

	/** To the page `way` of this one, as a swipe would: it is there at once, the pages moving from where they were to their places; past either end, back, or past the last, closed. */
	function go(way: 1 | -1) {
		const to = at + way;
		if (to >= calls.length) return close();
		if (to < 0) {
			dx = 0;
			return settle(() => undefined);
		}
		if (at === tapped) leftTapped = true;
		// Where the finger left them, a slot further on: then they settle.
		const from = dx + way * width;
		settling = false;
		at = to;
		shown = null;
		dx = from;
		requestAnimationFrame(() => {
			dx = 0;
			settle(() => undefined);
		});
	}

	/** Whether it is closing: what asks again meanwhile (its last page running out, Escape, ✕, a drag down) closes it no more than once. */
	let closing = false;

	function close() {
		if (closing) return;
		closing = true;
		dy = height;
		settle(onclose);
	}

	/** The form drawn alone closed, sent or not: the stories close at once, with nothing of theirs drawn to move away. */
	function done() {
		if (closing) return;
		closing = true;
		onclose();
	}

	function down(event: PointerEvent) {
		if (settling || !event.isPrimary) return;
		gesture = { id: event.pointerId, x: event.clientX, y: event.clientY, t: performance.now(), axis: null };
		dragged = false;
	}

	function move(event: PointerEvent) {
		if (!gesture || event.pointerId !== gesture.id) return;
		const x = event.clientX - gesture.x;
		const y = event.clientY - gesture.y;
		if (!gesture.axis) {
			if (Math.max(Math.abs(x), Math.abs(y)) < 10) return;
			gesture.axis = Math.abs(x) > Math.abs(y) ? 'x' : y > 0 ? 'y' : null;
			if (!gesture.axis) return void (gesture = null);
			dragged = true;
			(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
		}
		if (gesture.axis === 'x') {
			// No page that way: it gives a little, and no more.
			const edge = (x > 0 && at === 0) || (x < 0 && at === calls.length - 1);
			dx = edge ? x / 4 : x;
		} else dy = Math.max(0, y);
	}

	function up(event: PointerEvent) {
		if (!gesture || event.pointerId !== gesture.id) return;
		const { axis, t } = gesture;
		const speed = (axis === 'x' ? Math.abs(dx) : dy) / Math.max(performance.now() - t, 1);
		gesture = null;
		if (axis === 'x') {
			const way = dx < 0 ? 1 : -1;
			const far = swipe > 0.25 || speed > 0.6;
			const there = way === 1 ? at < calls.length - 1 : at > 0;
			if (far && there) go(way);
			else {
				dx = 0;
				settle(() => undefined);
			}
		} else if (axis === 'y') {
			if (fall > 0.35 || speed > 0.8) close();
			else {
				dy = 0;
				settle(() => undefined);
			}
		}
	}

	/** A drag is no tap: the click it ends in stops before the page. */
	function swallow(event: MouseEvent) {
		if (!dragged) return;
		event.stopPropagation();
		event.preventDefault();
		dragged = false;
	}

	function key(event: KeyboardEvent) {
		if (held || alone) return;
		if (event.key === 'Escape') close();
		else if (event.key === 'ArrowRight') go(1);
		else if (event.key === 'ArrowLeft') go(-1);
	}

	/** Drawn at the frame's end (the body's, outside one), over the tabs and whatever holds the stack, and focused for the keys. */
	function overAll(element: HTMLElement) {
		(document.querySelector('.hud-frame') ?? document.body).append(element);
		element.focus();
		return () => element.remove();
	}

	/** Where page `i` is, in slots from the middle (the finger's way past it a fraction of one), and how far from the middle, 0 to 1: the stylesheet places, sizes and dims it by them, a phone's way or a wide box's. */
	function place(i: number) {
		const slot = i - at + dx / width;
		return { slot, off: Math.min(Math.abs(slot), 1) };
	}
</script>

<svelte:window onkeydown={key} />

{#if alone}
	<!-- The page tapped opened at its form: that form alone, over what is under the stories. -->
	<Tree
		ui={alone}
		form={done}
		{onaction}
		{ontool}
		{onupload}
		oncall={(call, _report, _sequence, sheet) => onopen(call, sheet === true)}
		onreload={async () => done()}
		onopenlink={(url) => void window.open(url, '_blank', 'noopener,noreferrer')}
		root={false}
	/>
{:else if !waiting}
	<div
		class="pager"
		class:settling
		role="dialog"
		aria-modal="true"
		aria-label="Stories"
		tabindex="-1"
		{@attach overAll}
		ondragstart={(event) => event.preventDefault()}
		bind:clientWidth={width}
		bind:clientHeight={height}
		style:transform="translateY({dy}px) scale({1 - fall * 0.1})"
		style:--fall={fall}
		onpointerdown={down}
		onpointermove={move}
		onpointerup={up}
		onpointercancel={up}
		onclickcapture={swallow}
	>
		<div class="shade" aria-hidden="true"></div>
		{#if wordmark}<span class="wordmark" aria-hidden="true" translate="no">{wordmark}</span>{/if}
		{#each calls as _, i (i)}
			{#if Math.abs(i - at) <= 1}
				{@const where = place(i)}
				{@const page = pages[i]}
				<section class="page" class:side={i !== at} inert={i !== at} style:--slot={where.slot} style:--off={where.off}>
					{#if !page?.view}
						<Skeleton node={recallSkeleton(calls[i])} delayed />
					{:else if page.signIn}
						<div class="ask">
							<p>Sign in to see this.</p>
							<button type="button" onclick={onsignin}>Sign in</button>
						</div>
					{:else if page.view.renderer === 'tree'}
						<Tree
							ui={drawnUi(i, page.view.ui)}
							active={i === at}
							{held}
							slide={i === tapped && !leftTapped ? slide : null}
							onslide={(open) => {
								if (i === at && 'call' in open) shown = open.call;
							}}
							onend={(way) => go(way === 'next' ? 1 : -1)}
							{onaction}
							{ontool}
							{onupload}
							oncall={(call, _report, _sequence, sheet) => onopen(call, sheet === true)}
							onleave={close}
							onreload={() => reread(i)}
							onopenlink={(url) => void window.open(url, '_blank', 'noopener,noreferrer')}
							bar="apart"
							root={false}
						/>
					{:else}
						<ErrorMessage message={page.view.message} />
					{/if}
				</section>
				{#if i !== at}
					<!-- In a wide box, the page beside it, small: a click goes to it. -->
					<button type="button" class="peek" style:--slot={where.slot} style:--off={where.off} aria-label={i > at ? 'Next' : 'Previous'} tabindex="-1" onclick={() => go(i > at ? 1 : -1)}></button>
				{/if}
			{/if}
		{/each}
		<button type="button" class="close" aria-label="Close" onclick={close}>
			<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" /></svg>
		</button>
		{#if at > 0}
			<button type="button" class="arrow previous" aria-label="Previous" onclick={() => go(-1)}>
				<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6" /></svg>
			</button>
		{/if}
		{#if at < calls.length - 1}
			<button type="button" class="arrow next" aria-label="Next" onclick={() => go(1)}>
				<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6" /></svg>
			</button>
		{/if}
	</div>
{/if}

<style>
	/* Over everything, the tabs too, on black that clears as it is dragged
	   down; a container, so what is in it is laid out by its own box. */
	.pager {
		--hud-screen: 100dvh;
		--hud-bleed: 0px;
		/* The ✕'s room at the end of a story's top row, its ⋯ beside it. */
		--hud-slides-end: 3.25rem;
		container: pager / size;
		position: fixed;
		inset: 0;
		z-index: 10;
		overflow: hidden;
		color: #fff;
		touch-action: none;
		user-select: none;
		outline: none;
	}

	.shade {
		position: absolute;
		inset: 0;
		background: rgb(0 0 0 / calc(1 - var(--fall)));
	}

	.wordmark,
	.peek {
		display: none;
	}

	/* On a phone, each page the window, a slot of its width from the next;
	   away from the middle, smaller and faded. */
	.page {
		position: absolute;
		inset: 0;
		overflow: hidden;
		background: #000;
		transform-origin: center;
		transform: translateX(calc(var(--slot) * 100%)) scale(calc(1 - var(--off) * 0.08));
		opacity: calc(1 - var(--off));
		will-change: transform, opacity;
	}

	/* Letting go: a spring's ease to where they settle. */
	.settling,
	.settling .page,
	.settling .peek {
		transition:
			transform 300ms cubic-bezier(0.2, 0.9, 0.25, 1),
			opacity 300ms cubic-bezier(0.2, 0.9, 0.25, 1);
	}

	.ask {
		display: grid;
		place-content: center;
		justify-items: center;
		gap: var(--hud-space-3);
		height: 100%;
	}

	.ask button {
		padding: var(--hud-space-2) var(--hud-space-5);
		border: 0;
		border-radius: var(--border-radius-full);
		background: var(--color-background-inverse);
		color: var(--color-text-inverse);
		font: inherit;
		cursor: pointer;
	}

	.close,
	.arrow {
		position: absolute;
		display: grid;
		place-items: center;
		width: 2.5rem;
		height: 2.5rem;
		padding: 0;
		border: 0;
		border-radius: var(--border-radius-full);
		background: rgb(0 0 0 / 0.35);
		color: #fff;
		cursor: pointer;
	}

	/* On the line of a story's name row (its top's padding, bars and gap: 18px down), level with its ⋯. */
	.close {
		top: calc(env(safe-area-inset-top) + 1.125rem);
		right: var(--hud-space-3);
	}

	.arrow {
		top: 50%;
		translate: 0 -50%;
		display: none;
	}

	.previous {
		left: var(--hud-space-3);
	}

	.next {
		right: var(--hud-space-3);
	}

	/* A pointer that hovers (a mouse): arrows to go between pages. */
	@media (hover: hover) and (pointer: fine) {
		.arrow {
			display: grid;
		}
	}

	svg {
		width: 1.25rem;
		height: 1.25rem;
		fill: none;
		stroke: currentColor;
		stroke-width: 2;
		stroke-linecap: round;
		stroke-linejoin: round;
	}

	/* A box wider than a phone: Instagram's. The window dark, the page a
	   9:16 column in its middle as tall as the box allows (leaving room for
	   the pages beside it), those beside it small and dimmed a slot away;
	   the wordmark at the top-left, ✕ at the top-right, the arrows at the
	   column's sides. */
	@container pager (min-width: 40rem) {
		.page,
		.peek,
		.arrow {
			--tall: min(100cqh - 2 * var(--hud-space-4), (100cqw - 16rem) * 16 / 9);
			--wide: calc(var(--tall) * 9 / 16);
		}

		.shade {
			background: rgb(18 18 18 / calc(1 - var(--fall)));
		}

		.wordmark {
			position: absolute;
			top: var(--hud-space-4);
			left: var(--hud-space-5);
			display: block;
			font-family: var(--app-font-display, inherit);
			font-size: 1.75rem;
			font-weight: 800;
			line-height: 1;
			letter-spacing: -0.02em;
		}

		/* The page a size container, so its Slides is as tall as it is. */
		.page,
		.peek {
			inset: auto;
			top: 50%;
			left: 50%;
			width: var(--wide);
			height: var(--tall);
			margin: calc(var(--tall) / -2) 0 0 calc(var(--wide) / -2);
			border-radius: var(--border-radius-md);
			/* A slot: half the column, a gap, and half a page beside it. */
			transform: translateX(calc(var(--slot) * (71% + var(--hud-space-6)))) scale(calc(1 - var(--off) * 0.58));
		}

		.page {
			--hud-screen: 100cqh;
			--hud-slides-end: 0px;
			container-type: size;
			opacity: calc(1 - var(--off) * 0.55);
		}

		/* Over the page beside it, as the pages are placed: the shade under it. */
		.peek {
			position: absolute;
			display: block;
			padding: 0;
			border: 0;
			background: none;
			cursor: pointer;
		}

		.close {
			top: var(--hud-space-4);
			right: var(--hud-space-4);
			background: none;
		}

		.close svg {
			width: 1.75rem;
			height: 1.75rem;
		}

		.arrow {
			display: grid;
			width: 2rem;
			height: 2rem;
			background: rgb(255 255 255 / 0.85);
			color: #000;
		}

		.previous {
			left: calc(50% - var(--wide) / 2 - 2.75rem);
		}

		.next {
			right: calc(50% - var(--wide) / 2 - 2.75rem);
		}
	}
</style>