~ 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
1015 lines · 41.5 KB Raw History
<script lang="ts" module>
	import type { Place } from './Stack.svelte';

	/** A history entry's state (`Navigation.here`): the tab, where its stack was, and whether the entry before is the same a step up. */
	export type Here = Place & { tab: number; up: boolean };

	/**
	 * The host's history, as its router keeps it (SvelteKit's shallow
	 * routing): the state of the entry on screen, read as it changes (`here`);
	 * an entry made for a URL with a state, pushed or in place of the one on
	 * screen (`go`); and `entered`, which runs a function once the page the
	 * server drew is hydrated and the router can make entries, called as the
	 * shell starts (where a router's own lifecycle hooks may be).
	 */
	export type Navigation = {
		readonly here: unknown;
		go(url: string, here: Here, replace: boolean): Promise<void>;
		entered(run: () => void): void;
	};

	/** What the host gives the shell besides the app: where its server takes the pages' calls and uploads, where signing in starts (a URL given `?back=` the path to come back to; signed in, it adds another account) and out ends (POSTed), where switching to another of the browser's accounts is POSTed (`use`, `{did}`), and, where it draws the navigation at widths of its own, its bands. */
	export type Host = { endpoints: Endpoints; signIn: string; signOut: string; use?: string; bands?: Frame['bands'] };
</script>

<script lang="ts">
	import { ErrorMessage, formOf, Glyph, Tree, type ActionHandler, type UiAccounts, type UiToolHandler, type UiTree } from '@hud/renderer';
	import { Interactions } from '@hud/shared/interactions';
	import { ACTION_TOOLS, acted, answered as dataOf, read, sent, text, viewer, type Call, type ToolResult, type View } from '@hud/shared/result';
	import { onMount, tick, untrack } from 'svelte';
	import { at, isTabPath, rootsOf, routesOf, tabCall, tabPath, type App } from './app';
	import { Client, type Endpoints } from './client';
	import { actionForm, areasOf, frameCss, layoutOf, type CallItem, type Frame } from './frame';
	import Head from './Head.svelte';
	import { headOf, headOfAnswer, NOT_A_VIEW, type ScreenHead } from './head';
	import Nav from './Nav.svelte';
	import { Ahead } from './prefetch';
	import { Recent } from './recent';
	import { callOf, Names, pathOf, plain, recordAt, routeOf, same } from './routes';
	import type { Answer, Screen } from './screen';
	import SearchFlyout from './SearchFlyout.svelte';
	import SignIn from './SignIn.svelte';
	import { pictureIn } from './server';
	import type { AccountsData } from './session';
	import Stack, { WRITES, type Move, type Seed } from './Stack.svelte';
	import { applyScheme, schemeIn } from './theme';

	// An app as a phone app is laid out, framed by its app file's `frame`
	// (frame.ts): its tabs, each a nav stack of its own, drawn once first
	// chosen. Choosing a tab shows its root, as its link says, the screens
	// left over it let go and its root made again, drawn as it was
	// meanwhile (Stack.svelte); choosing it again at its root asks its call
	// afresh. A screen that is a tab's own (a link to the account's own
	// profile, its URL) is that tab, chosen, never a copy pushed over
	// another tab; and a screen opened over itself is not pushed again.
	// Signed in, a tab with a `badge` shows its count on its icon,
	// as the server read it for the page, then when the window is focused
	// again and each minute it is shown, cleared as the tab is opened (its
	// list marks what it shows seen); the account's picture (the frame's
	// `account.picture`) is drawn on its tab in place of its icon. Signed
	// in, a tab with `first` has the root the account's data chooses (Grain's
	// Home, the first feed pinned), as the server chose it for the page; after
	// its `after` procedure it is chosen again, taken at once by a tab not on
	// show and by the tab on show as it is chosen again or its own URL come
	// back to, its URL its own still.
	//
	// The tabs are a bar along the foot of a narrow window, a rail of icons
	// beside a wider one and a sidebar with words beside a wide one (Nav,
	// with Search, which slides out beside it, SearchFlyout.svelte, the
	// app's `search`; the account's screens, the app's action and its links),
	// the screens in a column the width the screen on top asks for (its
	// view's `measure`), and the frame's aside beside it where it fits. The
	// band is the stylesheet's (`frameCss`), so the server draws what the
	// browser hydrates: where the navigation draws the action, a screen's
	// Bar button for the action's form too is the stylesheet's to hide.
	//
	// The server draws the page the URL names (server.ts's `screenAt`), its
	// stack seeded with what it answered, and the browser takes it from
	// there: each screen it opens is a call it makes itself (through the
	// host's server, `host.endpoints`), read ahead as a link is hovered,
	// pressed or shown (prefetch.ts). The URL follows the screen on top, by
	// the app's routes (routes.ts): a screen with none has the URL of the one
	// under it, and a tab's root its tab's. Each screen opened and each tab
	// chosen is a history entry made through the host's router
	// (`navigation`), its state (`Here`) the tab and every call of its stack,
	// so the browser's back and forward set the stack to it with no page
	// loaded. A screen's back is the browser's where the entry before is the
	// screen under it (`up`), else a step up of its own. A URL the browser
	// loads is drawn by the server again.
	//
	// Each screen's last tree is kept a while (recent.ts), so a screen
	// opened again draws it at once while its call is made again: in this
	// page's memory, the account's alone, let go as it signs out and after
	// any write it makes (`wrote`), as are the answers read ahead, every
	// stack's levels then made again as they show. The page's head
	// (Head.svelte) is the screen on top's, as its view says it.
	//
	// A call that opens its screen at a form (a query's `compose`) opens it
	// once, as that screen opens: the stacks keep, and history entries and
	// URLs hold, each call less it (routes.ts's `plain`), so a screen gone
	// back or forward to, or loaded again, opens no form. The frame's
	// action opens no screen: its call is made (read ahead as its button is
	// hovered or pressed), and where it answers a screen opened at a form,
	// that form alone is drawn over the screen on show (`Tree`'s `form`),
	// its writes the account's as any screen's. Sent, the screen of the
	// first record it made that a route opens is opened over the tab on
	// show (Grain's new gallery), else the screen on show is read again. A
	// call that answers no form opens as a screen on the tab on show.

	let {
		app,
		host,
		navigation,
		screen,
		under,
		signedIn: signedInAtFirst,
		origin,
		path: pathAtFirst,
		now,
		counts: countsAtFirst,
		picture: pictureAtFirst,
		accounts: accountsAtFirst = null
	}: {
		app: App;
		host: Host;
		navigation: Navigation;
		screen: Screen;
		/** What the root under the screen answers, streamed after the page. */
		under: Promise<Answer> | null;
		signedIn: boolean;
		/** The app's public origin, for its canonical URLs. */
		origin: string;
		/** The URL the page was drawn for: its path and query. */
		path: string;
		/** The server's now, which the pages' times are drawn from as it drew them. */
		now: number;
		/** Each tab's badge count, by its place, as the server read it: none signed out. */
		counts: Promise<Record<number, number>> | null;
		/** The account's picture, as the server read it for the page: none signed out. */
		picture: string | null;
		/** The browser's accounts, as the server read them for the page: none signed out, or where the host keeps none. */
		accounts?: AccountsData | null;
	} = $props();

	// svelte-ignore state_referenced_locally
	const frame = app.frame;
	// svelte-ignore state_referenced_locally
	const layout = layoutOf(frame, host.bands);
	const css = frameCss(layout, actionForm(frame));
	const areas = areasOf(layout);
	// svelte-ignore state_referenced_locally
	const client = new Client(host.endpoints);
	const reading = new Ahead(client);
	// svelte-ignore state_referenced_locally
	let signedIn = $state(signedInAtFirst);
	// svelte-ignore state_referenced_locally
	let current = $state(screen.tab);
	/** The tabs drawn so far, each kept mounted from its first showing. */
	// svelte-ignore state_referenced_locally
	let opened = $state(new Set<number>([screen.tab]));
	const stacks: Stack[] = $state([]);
	// svelte-ignore state_referenced_locally
	const names = new Names(screen.names);
	/** Each tab's badge count, by its place: none signed out. */
	let counts: Record<number, number> = $state({});
	/** The account's picture: the server's at first, so the page is drawn with it; read again after an action. */
	// svelte-ignore state_referenced_locally
	let picture: string | null = $state(pictureAtFirst);
	/** Whether the search flyout is out. */
	let searching = $state(false);
	/** Where the app is: the URL on screen, a path with its query. */
	// svelte-ignore state_referenced_locally
	let path = $state(pathAtFirst);
	/** Each tab's top screen's head, as its stack tells it: the server's page's at first. */
	// svelte-ignore state_referenced_locally
	const heads: (ScreenHead | null)[] = $state(app.tabs.map((_, i) => (i !== screen.tab ? null : screen.missing ? NOT_A_VIEW : headOfAnswer(screen.top, areas, screen.measure))));
	/** How wide the column is: as the tab's top screen asks (its view's `measure`), the server's page's at first, so it is drawn so before any code runs. */
	const measure = $derived(heads[current]?.measure ?? 'content');
	/** Each URL a link is drawn with, and the call it opens: what is read ahead as it is hovered. */
	const linked = new Map<string, Call>();
	/** Each screen's last tree, the account's, which a stack draws a screen it opens again with first. */
	const recent = new Recent<View>();
	/** The tab whose icon is the account's picture; -1 where none is. */
	// svelte-ignore state_referenced_locally
	const pictureTab = app.tabs.findIndex((t) => t.label === frame?.account?.picture?.tab);
	/** The aside's tree, as the server answered it, then as the browser does. */
	// svelte-ignore state_referenced_locally
	let aside: View | null = $state.raw(screen.aside && 'result' in screen.aside ? read(screen.aside.result) : null);
	/** Each tab's root signed in, as the server chose it for the page (`rootsOf`), then as the account's data chooses it afresh (`rechoose`). */
	// svelte-ignore state_referenced_locally
	let roots: (Call | null)[] = $state.raw(screen.roots ?? app.tabs.map((t) => tabCall(t, signedInAtFirst)));
	/** A root chosen afresh for the tab on show, by its place: taken as the tab is next chosen, never from under the screens over its root. */
	const pending: (Call | undefined)[] = [];
	/** A tab's root: signed in, as chosen; signed out, its guest call. */
	const rootOf = (tab: number) => (signedIn ? roots[tab] : tabCall(app.tabs[tab], false));

	/** The server's page, as the first tab's stack starts: under a story's URL, the story viewer over its stack, the screen it answered its page's, the levels under it (but the root, which streams) read in the browser. */
	// svelte-ignore state_referenced_locally
	const seed: Seed[] = screen.calls.map((call, i) => ({
		call,
		answer: screen.pager ? (i === 0 ? under : null) : i === screen.calls.length - 1 ? screen.top : i === 0 ? under : null,
		measure: i === 0 ? screen.measure : undefined
	}));
	// svelte-ignore state_referenced_locally
	const seedPager = screen.pager ? { pager: screen.pager, answer: screen.top } : null;

	const feedback = new Interactions(
		async (feed, interactions) => {
			const result: ToolResult = await client.callTool('send_interactions', { feed, interactions });
			if (result.isError) throw new Error(text(result) || 'send_interactions failed.');
			return sent(result);
		},
		(message) => console.debug(message)
	);

	const isHere = (state: unknown): state is Here =>
		typeof state === 'object' && state !== null && typeof (state as Here).tab === 'number' && Array.isArray((state as Here).calls);

	/** A call's path by the app's routes, or null. */
	const routed = (call: Call) => pathOf(call, routesOf(app), names);

	/** Whether a call opens as a story, in the story viewer: its route's `pager`. */
	const paged = (call: Call) => routeOf(call, routesOf(app))?.pager === true;

	/** A call's URL for a link the renderer draws: read ahead as it is hovered. */
	function hrefOf(call: Call): string | null {
		const href = routed(call);
		if (href) linked.set(href, call);
		return href;
	}

	/** The URL of a tab's place: the story its viewer shows, else its viewer's page, else its top screen with a route, else its tab's. */
	function urlOf(tab: number, place: Place): string {
		const pager = place.pager;
		const page = pager && ((pager.shown && routed(pager.shown)) || routed(pager.calls[pager.at]));
		if (page) return page;
		for (let i = place.calls.length - 1; i > 0; i--) {
			const found = routed(place.calls[i]);
			if (found) return found;
		}
		const own = rootOf(tab);
		const root = place.calls[0];
		return (root && !(own && same(root, own)) && routed(root)) || tabPath(app, app.tabs[tab], names);
	}

	/** An entry come to (gone back or forward to, the page loaded again) as it draws now: at its tab's own URL, its root is the tab's as chosen now, which the account's data may have changed since (`first`), a root chosen afresh for it meanwhile (`pending`) taken. */
	function comeTo(here: Here): Here {
		const own = tabPath(app, app.tabs[here.tab], names);
		if (here.calls.length === 0 || !isTabPath(own, location.pathname, location.search)) return here;
		const fresh = pending[here.tab];
		pending[here.tab] = undefined;
		if (fresh) roots = roots.with(here.tab, fresh);
		const root = rootOf(here.tab);
		return root ? { ...here, calls: [root, ...here.calls.slice(1)] } : here;
	}

	/** The history entry the app last made or came to (`made`, as JSON): the stack is already where it says. Read in place of `navigation.here`, which a router may set only once its move settles: an answer that lands before then (one read ahead, already there as its screen opens) teaching handles (`renamed`) would otherwise put the entry before back over the one just made, the screen tapped open gone again. */
	let entered: Here | undefined = undefined;
	let made = '';

	/** A place as history keeps it: each call less its `compose` (routes.ts's `plain`), the pager's too, so going back or forward to it, or loading it again, opens no form. */
	const plainPlace = <P extends Place>(place: P): P => ({
		...place,
		calls: place.calls.map(plain),
		pager: place.pager ? { ...place.pager, calls: place.pager.calls.map(plain) } : place.pager,
		sheet: place.sheet ? plain(place.sheet) : place.sheet
	});

	/** A history entry for a tab's place: pushed, or in place of the one on screen; a lone root has no screen under it to go up to. */
	async function enter(tab: number, place: Place, how: Move) {
		const was = entered ?? navigation.here;
		const under = place.calls.length > 1 || place.pager !== null || Boolean(place.sheet);
		const up = under && (how === 'open' || (how === 'replace' && isHere(was) && was.up));
		const here: Here = { tab, ...plainPlace($state.snapshot(place)), up };
		const url = urlOf(tab, here);
		path = url;
		entered = here;
		made = JSON.stringify(here);
		await navigation.go(url, here, how === 'replace');
	}

	/** Whether the server's page is being made the first history entries: the stack's moves meanwhile are the last one's. */
	let entering = false;

	/** The tab on screen moved. */
	function moved(tab: number, how: Move) {
		const place = stacks[tab]?.place();
		if (tab === current && place && !entering) void enter(tab, place, how);
	}

	/** Accounts' handles learnt: the URL on screen names them. */
	function renamed() {
		const here = entered ?? navigation.here;
		if (!isHere(here)) return;
		const url = urlOf(here.tab, here);
		if (url !== path) void enter(here.tab, here, 'replace');
	}

	function answered(result: ToolResult) {
		let learnt = names.learn(result.structuredContent);
		if (!result.isError) {
			const who = viewer(result);
			if (who) learnt = names.viewer(who) || learnt;
		}
		if (learnt) renamed();
	}

	/** A handle's DID, as `describe_repo` resolves it; the handle as it is where it cannot. */
	async function resolve(actor: string): Promise<string> {
		const result = await client.callTool('describe_repo', { actor }).catch(() => null);
		if (!result || result.isError) return actor;
		names.learn(result.structuredContent);
		const did = (result.structuredContent as { did?: unknown } | null)?.did;
		return typeof did === 'string' ? did : actor;
	}

	/** A tab shown, its stack drawn first if it never was, its badge cleared. */
	async function show(tab: number) {
		current = tab;
		opened = new Set(opened).add(tab);
		if (counts[tab]) counts = { ...counts, [tab]: 0 };
		await tick();
	}

	/** A badge's count, as its call answers it. */
	async function count(i: number) {
		const badge = app.tabs[i].badge;
		if (!badge) return;
		const result = await client.callTool(badge.call.name, badge.call.args).catch(() => null);
		if (!result || result.isError || !signedIn) return;
		const found = at(result.structuredContent, badge.count);
		if (typeof found === 'number') counts = { ...counts, [i]: i === current ? 0 : found };
	}

	// Signed in, every badge as the server read it, then on focus and each minute while shown.
	$effect(() => {
		if (!signedIn || !app.tabs.some((t) => t.badge)) {
			counts = {};
			return;
		}
		void countsAtFirst?.then((read) => {
			if (signedIn) counts = Object.fromEntries(Object.entries(read).map(([i, n]) => [i, Number(i) === current ? 0 : n]));
		});
		const all = () => app.tabs.forEach((_, i) => void count(i));
		const timer = setInterval(() => {
			if (document.visibilityState === 'visible') all();
		}, 60_000);
		addEventListener('focus', all);
		return () => {
			clearInterval(timer);
			removeEventListener('focus', all);
		};
	});

	// Signed out, no picture.
	$effect(() => {
		if (!signedIn) picture = null;
	});

	/** An action done: after the app's `scheme.after` (a setting set), its scheme is read again (and the server keeps it as it answers); after a tab's `first.after`, its root is chosen again (`rechoose`). After any, the account's picture is read again, where it may have changed it (its profile edited). */
	async function actedOn(kind: string, args: unknown) {
		const shown = frame?.account?.picture;
		if (shown) {
			void client
				.callTool(shown.call.name, shown.call.args)
				.then((result) => {
					if (signedIn && !result.isError) picture = pictureIn(result.structuredContent, shown.at) ?? picture;
				})
				.catch(() => undefined);
		}
		const method = kind === 'call' ? (args as { method?: unknown }).method : undefined;
		if (method !== undefined) void rechoose(method);
		const scheme = app.scheme;
		if (!scheme?.after || method !== scheme.after) return;
		const result = await client.callTool(scheme.call.name, scheme.call.args).catch(() => null);
		if (!result || result.isError || !signedIn) return;
		applyScheme(schemeIn(result.structuredContent, scheme.at));
	}

	/** After the procedure `method`, the root of each tab whose `first.after` it is chosen again from the account's data (Grain's Home, after My feeds reordered): a tab not on show takes it at once (its stack starts at it), the tab on show as it is next chosen. */
	async function rechoose(method: unknown) {
		const asked = app.tabs.map((t) => t.first?.after !== undefined && t.first.after === method);
		if (!asked.includes(true)) return;
		const ask = async (call: Call) => {
			const result = await client.callTool(call.name, call.args).catch(() => null);
			return result && !result.isError ? result.structuredContent : null;
		};
		const fresh = await rootsOf(app, true, ask, resolve);
		if (!signedIn) return;
		fresh.forEach((call, i) => {
			if (!asked[i] || !call) return;
			pending[i] = undefined;
			const was = roots[i];
			if (was && same(call, was)) return;
			if (i === current) pending[i] = call;
			else roots = roots.with(i, call);
		});
	}

	/** The account wrote: no screen is drawn from before it, nor from what was read ahead. */
	function wrote() {
		recent.forget();
		reading.forget();
		for (const stack of stacks) stack?.stale();
	}

	/** The account gone (signed out, or its token refused): nothing of its is drawn again. */
	function gone() {
		recent.forget();
		reading.forget();
	}

	/** A tab chosen: its root, as its link says, made again where it answered a while ago; the tab on show, chosen again at its root, asks its call afresh. A root chosen afresh for it meanwhile (`pending`) is taken: its stack starts at that root, in place of the entry on show where it is the tab on show. */
	async function choose(i: number) {
		searching = false;
		const fresh = pending[i];
		pending[i] = undefined;
		if (fresh) roots = roots.with(i, fresh);
		if (i === current) {
			if (!fresh) stacks[i]?.home();
			return;
		}
		// Started at its new root before it shows, so its start moves no history.
		if (fresh) await tick();
		const again = opened.has(i) && !fresh;
		await show(i);
		if (again) stacks[i]?.rooted();
		moved(i, 'jump');
	}

	/** The tab whose own URL a path is (Profile's, the account's own profile), or -1. */
	const tabAt = (path: string) => app.tabs.findIndex((t) => tabPath(app, t, names) === path);

	/** A call a screen opens that is a tab's own screen: that tab chosen in its place; whether it was. */
	function ontab(call: Call): boolean {
		const href = call.args.compose === undefined ? routed(call) : null;
		const tab = href ? tabAt(href) : -1;
		if (tab < 0) return false;
		void choose(tab);
		return true;
	}

	/** The history entry a step back was last taken from: a second asked for before the first lands (a pager's ✕ as its last story runs out, Escape and ✕) is the same step, never one more. */
	let left: unknown = undefined;

	/** Back a step, once from each entry: the browser's, where the entry before is the screen under this one; else up a level of its own. */
	function back() {
		const here = navigation.here;
		if (here !== undefined && here === left) return;
		left = here;
		if (isHere(here) && here.up) history.back();
		else stacks[current]?.up();
	}

	// A history entry gone back or forward to: its tab and stack as they
	// were. The app's own entries come here too, where the stack is already.
	// Any entry come to may be stepped back from again, even one stepped
	// back from before (back, forward, back).
	$effect(() => {
		const here = navigation.here;
		left = undefined;
		if (!isHere(here) || here.tab >= app.tabs.length) return;
		const said = JSON.stringify(here);
		if (said === made) return;
		entered = here;
		made = said;
		untrack(() => {
			path = location.pathname + location.search;
			const to = comeTo(here);
			void show(here.tab).then(() => stacks[here.tab]?.sync(plainPlace(to)));
		});
	});

	/** A call opened as a screen over the tab `tab`'s, a step on from where it is (from its root, on a tab not on show), unless that is the screen on top already: a story (`paged`) in the story viewer over it; where it opens a form (`compose`), that form opens once, as the screen does. */
	async function openOn(tab: number, call: Call) {
		searching = false;
		const was = current;
		await show(tab);
		const all = stacks[tab]?.place().calls ?? [];
		const under = tab === was ? all : all.slice(0, 1);
		const top = under.at(-1);
		if (top && same(top, call)) {
			if (tab === was) return;
			stacks[tab]?.rooted();
			moved(tab, 'jump');
			return;
		}
		const place: Place = paged(call) ? { calls: under, pager: { calls: [call], at: 0 } } : { calls: [...under, call], pager: null };
		stacks[tab]?.sync(place);
		void enter(tab, place, tab === was ? 'open' : 'jump');
	}

	/** A screen a route found: on its route's tab, else over the tab on screen. */
	function openAt(found: { call: Call; tab?: string }) {
		const named = app.tabs.findIndex((t) => t.label === found.tab);
		return openOn(named < 0 ? current : named, found.call);
	}

	/** A path of the app's (with its query) opened as a screen: a tab's own URL as that tab, else by its routes, on its route's tab, else over the tab on screen; whether one was. */
	async function visit(url: string): Promise<boolean> {
		const at = new URL(url, location.origin);
		const tab = tabAt(at.pathname + at.search);
		if (tab >= 0) {
			await choose(tab);
			return true;
		}
		const found = await callOf(at.pathname, at.search, routesOf(app), resolve);
		if (found) await openAt(found);
		return found !== null;
	}

	/** A link a screen draws, opened: one to the app's own site (this origin, or its domain's, as an app's own page links its paths) as its screen where a route has it, else there in this tab; mail in the mail app; any other page in a new tab. */
	async function openLink(url: string) {
		const to = new URL(url, location.origin);
		if (to.protocol === 'mailto:') {
			location.href = url;
			return;
		}
		if (to.origin !== location.origin && to.host !== app.domain) {
			window.open(url, '_blank', 'noopener,noreferrer');
			return;
		}
		if (!(await visit(to.pathname + to.search))) location.href = url;
	}

	/** A footer link of the app's own (a path, as `/support/terms`): its screen, as `openLink` opens it, unless the browser opens it elsewhere. */
	function linkClick(event: MouseEvent, href: string) {
		if (ownClick(event)) return;
		event.preventDefault();
		void openLink(href);
	}

	/** The frame's action's form, drawn alone over the screen on show: the tree its call answered. */
	let composing: UiTree | null = $state.raw(null);
	/** The records the action's form made, as its writes answered. */
	let composed: string[] = [];
	/** Whether the action's call is on its way. */
	let acting = false;

	/** The frame's action: its call made (as read ahead), and the form its screen opens at drawn alone over the screen on show; where it answers none, its screen opened on the tab on show. */
	async function act() {
		const call = frame?.action?.call;
		if (!call || acting) return;
		searching = false;
		acting = true;
		const result = await (reading.take(call) ?? client.callTool(call.name, call.args)).catch(() => null);
		acting = false;
		if (result) answered(result);
		const view = result && read(result);
		if (view?.renderer === 'tree' && formOf(view.ui.root)) {
			composed = [];
			composing = view.ui;
		} else await openOn(current, call);
	}

	/** The action's form's tools, as a screen's: a write the account's (`wrote`), the records it made kept to open. */
	const formTool: UiToolHandler = async (name, args) => {
		const result = await client.callTool(name, $state.snapshot(args) as Record<string, unknown>);
		if (WRITES.has(name)) wrote();
		const data = dataOf(result) as { results?: { uri?: unknown }[]; uri?: unknown } | null;
		if (name === 'apply_writes') composed = (data?.results ?? []).flatMap((r) => (typeof r.uri === 'string' ? [r.uri] : []));
		return data;
	};

	/** The action's form's procedure (a form with a `call`), as a screen's. */
	const formAction: ActionHandler = async (kind, args) => {
		const result = await client.callTool(ACTION_TOOLS[kind], $state.snapshot(args) as Record<string, unknown>);
		wrote();
		const done = acted(kind, result);
		void actedOn(kind, args);
		return done;
	};

	/** The action's form sent: the screen of the first record it made that a route opens, over the tab on show; else the screen on show read again. */
	async function formSent() {
		const opened = composed.map((uri) => recordAt(uri, routesOf(app))).find((found) => found !== null);
		composed = [];
		if (opened) await openAt(opened);
		else stacks[current]?.shown();
	}

	// The page as the server drew it, made the first history entry: a
	// screen over its tab's root becomes two, the root's and the screen's
	// over it, so its back goes to the root; a story's URL three, the story
	// viewer over those, so closing it goes to the screen under it (its
	// account's profile). Meanwhile what the stack tells of its moves (the
	// story the viewer shows) is the last entry's, made from where it is
	// then. An entry come back to (the
	// page loaded again) is drawn as it was, at its tab's own URL from the
	// tab's root as chosen now (`comeTo`).
	// svelte-ignore state_referenced_locally
	navigation.entered(() => {
		const was = navigation.here;
		if (isHere(was) && was.tab < app.tabs.length) {
			const to = comeTo(was);
			void show(was.tab).then(() => stacks[was.tab]?.sync(plainPlace(to)));
			return;
		}
		if (screen.missing || screen.signIn) return;
		const root: Place = { calls: screen.calls.slice(0, 1), pager: null };
		entering = Boolean(screen.pager);
		void (async () => {
			await enter(screen.tab, root, 'replace');
			if (screen.calls.length > 1) await enter(screen.tab, { calls: screen.calls, pager: null }, 'open');
			if (screen.pager) await enter(screen.tab, stacks[screen.tab]?.place() ?? { calls: screen.calls, pager: screen.pager }, 'open');
			entering = false;
		})();
	});

	/** Sign in, coming back here (on the sign-in screen, where it comes back to): the host's sign-in screen. */
	const signIn = $derived(`${host.signIn}?back=${encodeURIComponent(screen.signIn?.back ?? path)}`);

	/** Sign out (the navigation's, or a view's `{ host: 'signOut' }`): the host's server ends the account's session, and the page is drawn anew, as the account it has in use next, else signed out. */
	async function leave() {
		gone();
		await fetch(host.signOut, { method: 'POST' }).catch(() => undefined);
		location.assign(path);
	}

	/**
	 * The browser's accounts, for a view's `Accounts`: a tap on another asks
	 * the host's server to switch to it, and Add account signs in to another
	 * (as signing in does, coming back here); either way the page is loaded
	 * anew, so nothing of the account before is drawn again.
	 */
	// svelte-ignore state_referenced_locally
	const accounts: UiAccounts | undefined = (() => {
		const use = host.use;
		if (!accountsAtFirst || !use) return undefined;
		return {
			list: accountsAtFirst.list,
			current: accountsAtFirst.current,
			use: (did) => {
				gone();
				void fetch(use, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ did }) })
					.catch(() => undefined)
					.then(() => location.assign(path));
			},
			add: () => {
				gone();
				location.assign(signIn);
			}
		};
	})();

	onMount(() => {
		const hidden = () => {
			if (document.visibilityState === 'hidden') void feedback.flush();
		};
		document.addEventListener('visibilitychange', hidden);
		// An aside the server could not answer for the page, asked again.
		const call = frame?.aside?.call;
		if (call && !aside)
			void client
				.callTool(call.name, call.args)
				.then((result) => (aside = read(result)))
				.catch(() => undefined);
		return () => document.removeEventListener('visibilitychange', hidden);
	});

	const head = $derived.by(() => {
		const found = headOf(app.head, heads[current] ?? null, origin, path);
		if (screen.signIn) return { ...found, title: `Sign in · ${app.head.siteName}`, noindex: true };
		return screen.missing ? { ...found, title: `Not found · ${app.head.siteName}` } : found;
	});

	/** Whether a click is the browser's own (a new tab or window), or one the app takes; with no stack drawn (an address with nothing at it, the sign-in screen), the browser goes there. */
	const ownClick = (event: MouseEvent) => screen.missing || screen.signIn !== undefined || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;

	/** A link to a tab: the browser's own for a new tab or window, else the tab chosen in place. */
	function tabClick(event: MouseEvent, i: number) {
		if (ownClick(event)) return;
		event.preventDefault();
		void choose(i);
	}

	/** A link to an account's screen (Settings): its route's, as any link to it opens, else over the tab on show. */
	function itemClick(event: MouseEvent, item: CallItem) {
		if (ownClick(event)) return;
		event.preventDefault();
		const href = routed(item.call);
		void (href ? visit(href) : openOn(current, item.call));
	}

	/** The account's screen on show, by its place in the frame's items: the one whose URL is the one on screen. */
	const on = $derived(signedIn ? (frame?.account?.items ?? []).findIndex((item) => 'call' in item && routed(item.call) === path) : -1);
	const wordmark = $derived(app.tabs.find((t) => t.wordmark)?.wordmark ?? app.name);
</script>

<svelte:head>
	{@html `<style>${css}</style>`}
	<!-- iOS Safari otherwise marks words it recognises in an app's own text (a place, a number, a date) with dotted underlines and taps of its own. -->
	<meta name="format-detection" content="telephone=no,date=no,address=no,email=no,url=no" />
</svelte:head>

<Head {head} />

<div class="hud-frame" data-measure={measure} data-signed-in={signedIn || undefined}>
	<!-- The navigation first: a page arrives in pieces, and the browser draws what has come; the screen after it, so the navigation is never drawn late beside it. -->
	<div class="side">
		<Nav
			{wordmark}
			tabs={app.tabs}
			hrefs={app.tabs.map((t) => tabPath(app, t, names))}
			{current}
			{counts}
			{picture}
			{pictureTab}
			{frame}
			{on}
			{hrefOf}
			{signedIn}
			{signIn}
			searchable={app.search !== undefined}
			searchOpen={searching}
			onchoose={tabClick}
			onsearch={() => (searching = !searching)}
			onitem={itemClick}
			onlink={linkClick}
			onaction={() => void act()}
			onactionahead={() => frame?.action && reading.prefetch(frame.action.call)}
			onsignout={leave}
		/>
	</div>
	{#if screen.missing}
		<main class="center"><ErrorMessage message="Nothing is at this address." /></main>
	{:else if screen.signIn}
		<main class="center sign-in"><SignIn plan={app.signIn} name={app.name} action={host.signIn} asked={screen.signIn} /></main>
	{:else}
		<main class:wide={measure === 'wide'} class:full={measure === 'full'} {@attach reading.readAhead(linked)}>
			{#each app.tabs as tab, i (tab.label)}
				{#if opened.has(i)}
					<Stack
						bind:this={stacks[i]}
						bind:head={heads[i]}
						root={rootOf(i)}
						seed={i === screen.tab ? seed : undefined}
						seedPager={i === screen.tab ? seedPager : null}
						{paged}
						brand={wordmark}
						title={tab.label}
						wordmark={tab.wordmark}
						active={i === current}
						{signedIn}
						{feedback}
						{now}
						{hrefOf}
						onopenlink={(url) => void openLink(url)}
						{signIn}
						{client}
						{reading}
						{areas}
						{recent}
						onresult={answered}
						onacted={actedOn}
						onwrote={wrote}
						onmove={(how) => moved(i, how)}
						onback={back}
						{ontab}
						onsignedout={() => {
							gone();
							signedIn = false;
						}}
						onsignout={leave}
						{accounts}
					/>
				{/if}
			{/each}
		</main>
	{/if}
	{#if frame?.aside}
		<aside class="hud-aside" aria-label="Aside">
			{#if aside?.renderer === 'tree'}
				<Tree
					ui={aside.ui}
					{now}
					{hrefOf}
					root={false}
					area="{layout.aside}px"
					oncall={(call) => void openOn(current, call)}
					onopenlink={(url) => void openLink(url)}
				/>
			{:else if aside}
				<ErrorMessage message={aside.message} />
			{/if}
		</aside>
	{/if}
	<!-- The action's form, a tree of its own each time it opens: held as an item, so going it is not drawn from nothing. -->
	{#each composing ? [composing] : [] as ui (ui)}
		<Tree
			{ui}
			{now}
			{hrefOf}
			area={areas.content}
			form={() => (composing = null)}
			oncall={(call) => void openOn(current, call)}
			onopenlink={(url) => void openLink(url)}
			onaction={formAction}
			ontool={formTool}
			onupload={signedIn ? client.uploadBlob : undefined}
			onreload={formSent}
		/>
	{/each}
	<nav class="tabs" aria-label={app.name}>
		{#each app.tabs as tab, i (tab.label)}
			{@const n = i === current ? 0 : (counts[i] ?? 0)}
			<a
				href={tabPath(app, tab, names)}
				class:on={i === current}
				aria-current={i === current ? 'page' : undefined}
				aria-label={n ? `${tab.label}, ${n} new` : undefined}
				onclick={(event) => tabClick(event, i)}
			>
				<span class="icon">
					{#if picture && i === pictureTab}
						<img class="picture" src={picture} alt="" width="22" height="22" />
					{:else}
						<svg viewBox="0 0 24 24" aria-hidden="true"><Glyph name={tab.icon} /></svg>
					{/if}
					{#if n}<span class="badge" aria-hidden="true">{n > 9 ? '9+' : n}</span>{/if}
				</span>
				<span>{tab.label}</span>
			</a>
		{/each}
	</nav>
	{#if app.search}
		{@const search = app.search}
		<SearchFlyout
			bind:open={searching}
			{client}
			typeahead={search.typeahead}
			onsearch={(q) => visit(search.results.replace('{q}', encodeURIComponent(q)))}
			onactor={(did) => visit(search.person.replace('{actor}', encodeURIComponent(did)))}
		/>
	{/if}
</div>

<style>
	/* The column: the frame's (shell.css's `--hud-frame-column`, a phone's
	   width centred on a wider window in the bar's band); beside the
	   navigation, a wide screen's all the room right of it, a full one's
	   that to the window's edge, `--stretch` its share of the way there (the
	   band, 0 in the bar's). Moving between them the column eases from one
	   width to the other; the navigation stays put. */
	main {
		--stretch: 0;
		--target: var(--hud-frame-column);
		position: fixed;
		inset: 0 auto;
		left: calc(var(--hud-frame-column-start) - var(--stretch) * (var(--hud-frame-column-start) - var(--hud-frame-nav-end)));
		width: calc(var(--hud-frame-column) + var(--stretch) * (var(--target) - var(--hud-frame-column)));
		overflow: hidden;
		transition:
			left 240ms ease,
			width 240ms ease;
	}

	main.wide {
		--stretch: var(--hud-frame-band);
		--target: var(--hud-frame-main);
	}

	main.full {
		--stretch: var(--hud-frame-band);
		--target: calc(100vw - var(--hud-frame-nav-end));
	}

	/* The story viewer the server drew in its stack (a story's URL), over the
	   navigation and the tabs as it is once the browser moves it to the
	   frame's end. */
	main:has(:global(.pager)) {
		z-index: 4;
	}

	@media (prefers-reduced-motion: reduce) {
		main {
			transition: none;
		}
	}

	/* A phone's column on a wider window, edged; beside navigation, not. */
	@media (min-width: 30rem) {
		main {
			border-inline: calc((1 - var(--hud-frame-band)) * var(--border-width-regular)) solid var(--color-border-secondary);
		}
	}

	.center {
		display: grid;
		place-items: center;
		padding: var(--hud-space-4);
	}

	/* The sign-in screen scrolls where the window is short, clear of the
	   bar's pill at its foot. */
	.center.sign-in {
		overflow-y: auto;
		padding-bottom: calc(5rem + env(safe-area-inset-bottom));
	}

	/* The navigation at the frame's start, as wide as its band makes it: a
	   container, so it draws as a rail or a sidebar by its own width (Nav). */
	.side {
		display: var(--hud-frame-side-display, none);
		position: fixed;
		inset: 0 auto;
		left: var(--hud-frame-start);
		z-index: 3;
		width: var(--hud-frame-nav);
		container: hud-nav / inline-size;
	}

	/* The aside at the frame's end, shown where frameCss says it fits. */
	.hud-aside {
		display: none;
		position: fixed;
		inset: 0 auto;
		left: calc(var(--hud-frame-start) + var(--hud-frame-width) - var(--hud-frame-aside));
		width: var(--hud-frame-aside);
		padding: var(--hud-space-3);
		overflow-y: auto;
		border-left: var(--border-width-regular) solid var(--color-border-secondary);
	}

	/* The tabs float over the foot of the window in a pill, as the iOS app's do, in the bar's band alone. */
	.tabs {
		position: fixed;
		inset: auto 0 calc(var(--hud-space-3) + env(safe-area-inset-bottom));
		z-index: 3;
		display: var(--hud-frame-bar-display, grid);
		grid-auto-flow: column;
		grid-auto-columns: 1fr;
		width: min(calc(100% - 2 * var(--hud-space-4)), calc(var(--hud-frame-column) - 2 * var(--hud-space-4)));
		height: 3.5rem;
		margin-inline: auto;
		padding: var(--hud-space-1);
		border: var(--border-width-regular) solid var(--color-border-primary);
		border-radius: var(--border-radius-full);
		background: color-mix(in srgb, var(--app-panel, var(--color-background-secondary)) 80%, transparent);
		backdrop-filter: blur(16px) saturate(1.4);
		box-shadow: 0 8px 24px rgb(0 0 0 / 0.25);
	}

	.tabs a {
		display: grid;
		place-items: center;
		align-content: center;
		gap: 1px;
		border-radius: var(--border-radius-full);
		color: var(--color-text-secondary);
		font-size: var(--font-text-xs-size);
		font-weight: var(--font-weight-medium);
		text-decoration: none;
	}

	.tabs a.on {
		background: var(--app-accent-soft, var(--color-background-tertiary));
		color: var(--app-accent, var(--color-text-primary));
		font-weight: var(--font-weight-semibold);
	}

	/* Its count over the icon's corner, as Grain's tab bar has it: a pill in the app's colour. */
	.icon {
		position: relative;
		display: grid;
	}

	.badge {
		position: absolute;
		top: -0.3125rem;
		left: calc(100% - 0.5rem);
		display: grid;
		place-items: center;
		min-width: 1.25rem;
		height: 1.25rem;
		padding: 0 0.3125rem;
		border: 2px solid var(--app-panel, var(--color-background-secondary));
		border-radius: var(--border-radius-full);
		background: var(--app-primary, var(--color-text-danger));
		color: var(--app-on-primary, var(--color-text-inverse));
		font-size: 0.625rem;
		font-weight: var(--font-weight-bold);
		line-height: 1;
	}

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

	.picture {
		width: 1.375rem;
		height: 1.375rem;
		border-radius: var(--border-radius-full);
		object-fit: cover;
		background: var(--color-background-tertiary);
	}

	/* The side navigation carries the wordmark: a tab root's screen bar
	   (Stack's own header, never a view's `.bar`) does not repeat it, and
	   with nothing else in it (no title, back or tools) is gone; but not
	   while its screen loads with buttons to come (`reserved`), so they
	   fill in with no jump. frameCss says which band does. */
	main :global(.screen-bar > h1.wordmark) {
		display: var(--hud-frame-wordmark-display, block);
	}

	main :global(.screen-bar:not(.reserved):not(:has(h1:not(.wordmark), .back, .tools > *))) {
		display: var(--hud-frame-lone-bar-display, flex);
	}
</style>