chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.3.1 Latest 5 packages
0
0
<script lang="ts" module>
import { ACTION_TOOLS, type Call } from '@hud/shared/result';
import type { UiSequence } from '@hud/renderer';
import type { Measure } from './app';
import type { Answer } from './screen';
/** The story viewer over a stack: its pages' calls, the one it shows, and the screen of the story its Slides shows there (`shown`), which the app's URL follows. */
export type Paged = UiSequence & { shown?: Call | null };
/** Where a stack is: each level's call, its root's first, the story viewer over them, and the sheet's call over all. */
export type Place = { calls: Call[]; pager: Paged | null; sheet?: Call | null };
/** How a stack moved: on a step from where it was (`open`), in place of where it was (`replace`), or to somewhere else (`jump`). */
export type Move = 'open' | 'replace' | 'jump';
/** A level the stack starts with, as the server drew it: its call, and what it answered, or will (streamed), or nothing yet; and the measure it keeps, where the server drew it in a tab's root's place (Screen's `measure`). */
export type Seed = { call: Call; answer: Answer | Promise<Answer> | null; measure?: Measure };
/** The tools that write as the account: after one, no screen shows what it wrote over. */
export const WRITES = new Set<string>([...Object.values(ACTION_TOOLS), 'apply_writes']);
</script>
<script lang="ts">
import { barOf, ErrorMessage, GENERIC_SKELETON, LoadMore, recallSkeleton, rememberSkeleton, Skeleton, SKELETON_DELAY, translateOf, Tree, unopened, type ActionArgs, type ActionHandler, type UiAccounts, type UiBarPlace, type UiInteractionHandler, type UiReport, type UiToolHandler, type UiTree } from '@hud/renderer';
import { CLICKTHROUGH, SEEN, type Interactions } from '@hud/shared/interactions';
import { acted, answered, append, feedOf, nextPage, ownsPaging, read, viewer, type Entry, type ToolResult, type View } from '@hud/shared/result';
import { untrack } from 'svelte';
import { SvelteSet } from 'svelte/reactivity';
import { BROWSER as browser } from 'esm-env';
import { headOfView, type ScreenHead } from './head';
import { SignInNeeded, type Client } from './client';
import Pager from './Pager.svelte';
import type { Ahead } from './prefetch';
import { pageItems, pagedPast, type Recent } from './recent';
import Sheet from './Sheet.svelte';
import { plain, same } from './routes';
import { inStrip, measureOf } from './app';
import { entryOf } from './screen';
// One tab's nav stack: its root call, and each call opened from it on top,
// as a native app's navigation stack holds its screens. Every level stays
// mounted, each its own scroll container, so going back finds the one
// below as it was left: its scroll, its pages more, a like made. Only the
// top one shows; one under it that never showed (the root under a page
// loaded at a screen over it) draws its screen only once it shows. A
// call that needs an account draws a way to sign in in
// its place. It starts as the server drew it (`seed`), each level with
// what the server answered, or will once it streams; a level of its own
// takes its call's answer as it was read ahead (prefetch.ts), or makes
// it. Its top screen's head (its view's `head` and `hero`) it tells the
// app (`head`). A level's actions, forms and uploads go to HUD as the
// account; what its feed is told goes through `feedback`. The app keeps
// the browser's history: each move is told it (`onmove`), a step back is
// asked of it (`onback`), and a history entry gone back or forward to
// sets the stack (`sync`). A call opened as a sheet (`open.sheet`) draws
// over everything, a pager under it held and the sheet centred over it;
// what is opened from the sheet closes it and the pager, and opens in
// their place. A level opening a
// screen drawn a while ago (`recent`, recent.ts) draws its last tree at
// once, marked as refreshing, until its call answers in its place;
// else, while it loads, its screen's skeleton as last drawn (the
// renderer's `recallSkeleton`). A level shown again (gone back to, its
// tab chosen again) makes its call again the same way, unless it
// answered a moment ago; the items it drew past its first page stay
// after the fresh one, so where it was scrolled to stays. After a write
// (`stale`), every level makes its call again as it shows, those under
// the screen on top at once. A tab chosen in a level (or the sheet)
// swaps its call in place: the level stays, its tree drawn as it was
// until the new one comes (or the new call's last tree), its page list
// a skeleton once that is slow. A call that opens its screen at a form
// (a query's `compose`) opens it so as its level is first made; the
// level's call, as the stack's place and the memory of screens hold
// it, is the call less it (routes.ts's `plain`), and the tree kept of
// it unmarked (the renderer's `unopened`), so that screen drawn again
// (gone back or forward to, loaded again, opened again) opens no form.
type More = { loading: boolean; error: string | null };
/** A level: the call it draws (less any `compose`), the call its first answer is asked with where that opens a form (`opening`, with its `compose`), what it answered (null while out; while a tab's call is on its way, the call before's; while its call is made again, its last), whether that call is past `SKELETON_DELAY`, whether it is drawn as it last was while its call is made again (`refreshing`), when the call it draws was made, how many items its first page has, its page more, and the measure it is drawn at whatever its view says (`measure`: the root's, kept as a tab's call is drawn in the root's place). */
type Level = { id: number; call: Call; opening: Call | null; entry: Entry | null; signIn: boolean; slow: boolean; refreshing: boolean; at: number; first: number; more: More; measure?: Measure };
/** What a call answered, to draw, and when it was made. */
type Answered = { entry: Entry; signIn: boolean; asked: number };
/** How soon a level shown again makes its call again: not where it answered a moment ago. */
const AGAIN = 5_000;
let {
root,
seed,
title,
wordmark,
active,
signedIn,
feedback,
now,
hrefOf,
onopenlink,
signIn,
client,
reading,
areas,
head = $bindable(null),
recent,
onresult,
onacted,
onwrote,
onsignedout,
onmove,
onback,
onsignout,
accounts,
ontab,
seedPager = null,
paged,
brand
}: {
/** The call at the stack's root; null asks to sign in. */
root: Call | null;
/** The levels it starts with, as the server drew them. */
seed?: Seed[];
/** The story viewer it starts with over them, as the server drew it (a story's URL), and what its page answered. */
seedPager?: { pager: Paged; answer: Answer | null } | null;
/** Whether a call opens as a story, in the story viewer (a route's with `pager`). */
paged: (call: Call) => boolean;
/** The app's wordmark, which the story viewer draws in a wide window. */
brand: string;
title: string;
/** The root's title drawn as the app's logo, in place of `title`. */
wordmark?: string;
active: boolean;
signedIn: boolean;
feedback: Interactions;
/** The server's now, which its trees' times are first drawn from. */
now: number;
/** The URL of a call's screen, which its link is drawn with. */
hrefOf: (call: Call) => string | null;
/** A link a screen draws opened (a page, mail): the app's own paths in the app, the rest elsewhere. */
onopenlink: (url: string) => void;
/** Where signing in starts. */
signIn: string;
/** HUD's tools and uploads, through the app's server. */
client: Client;
/** The answers read ahead, which a level takes where it can. */
reading: Ahead;
/** How wide a screen of each measure draws its main area, as an `<img>`'s sizes says. */
areas: Record<Measure, string>;
/** Its top screen's head, as its view says it; kept as it was while the screen loads. */
head?: ScreenHead | null;
/** The last tree of each screen drawn, which a level drawing it again draws first. */
recent: Recent<View>;
/** Every result a call here answered. */
onresult: (result: ToolResult) => void;
/** An action here done: a procedure called, a record made or deleted. */
onacted?: (kind: keyof ActionArgs, args: ActionArgs[keyof ActionArgs]) => void;
/** The account wrote, here: by an action, or a form's tool. */
onwrote: () => void;
/** HUD refused the account's token: the app is signed out. */
onsignedout: () => void;
/** The stack moved, by a person here: `place()` says where to. */
onmove: (how: Move) => void;
/** A step back asked for: a level's back, a pager closed. */
onback: () => void;
/** A view's Sign out asked for (`{ host: 'signOut' }`): the app signs out. */
onsignout: () => void;
/** The browser's accounts, for a view's `Accounts` to list. */
accounts?: UiAccounts;
/** A call a screen opens that is a tab's own screen (the account's own profile): the app chooses that tab in its place, and says whether it did. */
ontab: (call: Call) => boolean;
} = $props();
let nextId = 0;
/** How many items a drawn tree's page list has. */
const itemsIn = (entry: Entry | null) => (entry?.view.renderer === 'tree' ? (pageItems(entry.view.ui.root)?.length ?? 0) : 0);
/** A level for a call: drawn as its screen last was, where `recent` has it, while its call is made again; a call opening a form opens it as the level's first answer comes. */
function newLevel(made: Call): Level {
const call = plain(made);
const view = recent.recall(call);
const entry = view && { view, call };
return { id: nextId++, call, opening: call === made ? null : made, entry, signIn: false, slow: false, refreshing: entry !== null, at: 0, first: itemsIn(entry), more: { loading: false, error: null } };
}
/** A tree a call made at `asked` answered, kept as its screen's last, in the browser (each page the server draws is drawn afresh): unmarked, so drawn again it opens no form. */
function keep(made: Call, result: ToolResult, view: View, asked: number) {
if (browser && view.renderer === 'tree') recent.keep(viewer(result)?.did ?? null, made, { ...view, ui: unopened(view.ui) }, asked);
}
/** When the page was drawn: what the server answered for it was asked no later. */
const loaded = Date.now();
/** A level the server drew, with what it answered drawn in it, or once it streams. */
function seeded({ call, answer, measure }: Seed): Level {
const level = { ...newLevel(call), measure };
if (answer instanceof Promise) {
if (browser)
void answer.then((streamed) => {
const shown = entryOf(call, streamed);
if ('result' in streamed) keep(call, streamed.result, shown.entry.view, loaded);
drawn(level, call, { ...shown, asked: loaded });
});
return level;
}
if (!answer) return level;
const shown = entryOf(call, answer);
if ('result' in answer) keep(call, answer.result, shown.entry.view, loaded);
return { ...level, ...shown, at: loaded, first: itemsIn(shown.entry) };
}
// svelte-ignore state_referenced_locally
let levels: Level[] = $state.raw((seed ?? []).map(seeded));
const top = $derived(levels.at(-1));
const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));
/** The level by its id: one on the stack, or the sheet's. */
const find = (id: number) => (sheet?.id === id ? sheet : levels.find((l) => l.id === id));
function update(level: Level, change: Partial<Level>) {
if (sheet?.id === level.id) sheet = { ...sheet, ...change };
else levels = levels.map((l) => (l.id === level.id ? { ...l, ...change } : l));
}
/** A tool called, its result told: taken as it was read ahead, where it was. */
async function call(made: Call, ahead = false): Promise<ToolResult> {
const result = await ((ahead && reading.take(made)) || client.callTool(made.name, made.args));
onresult(result);
return result;
}
/** A call made (`sent`, which opens a form where `made`, its screen's call, does not), and what it answers to draw: an account's sign-in asked for where it needs one. A tree it answers is its screen's skeleton next time, and its last tree (`recent`). */
async function answer(made: Call, sent = made): Promise<Answered> {
const asked = Date.now();
try {
const result = await call(sent, true);
const view = read(result);
if (view.renderer === 'tree') rememberSkeleton(made, view.ui);
keep(made, result, view, asked);
return { entry: { view, call: made }, signIn: false, asked };
} catch (error) {
const signIn = error instanceof SignInNeeded;
if (signIn && signedIn) onsignedout();
return { entry: { view: { renderer: 'error', message: errorText(error) }, call: made }, signIn, asked };
}
}
/** Whether a level draws what its own call answered (not, while a tab's call is on its way, the call before's). */
const current = (level: Level) => level.entry?.call != null && (level.entry.call === level.call || same(level.entry.call, level.call));
/** Whether a level is in front and settled, so its list pages as it is scrolled to its foot: the sheet's while one is open, else the stack's top with no pager over it, in the tab on show, and not drawn as it was while its call is made again (refreshing, or swapped for another). */
const inFront = (level: Level) => active && !level.refreshing && (sheet ? sheet.id === level.id : !pager && top?.id === level.id);
/** Make a level's call (opening its form the first time, where it does), and draw what it answers in it, while it is still on the stack (or the sheet) drawing that call; past `SKELETON_DELAY`, it is `slow`, unless it draws its last tree meanwhile. */
async function load(level: Level) {
const made = level.call;
const sent = level.opening ?? made;
if (level.opening) update(level, { opening: null });
const drawing = () => {
const now = find(level.id);
return now?.call === made ? now : null;
};
const slow = current(level)
? undefined
: setTimeout(() => {
const now = drawing();
if (now) update(now, { slow: true });
}, SKELETON_DELAY);
const answered = await answer(made, sent);
clearTimeout(slow);
drawn(level, made, answered);
}
/** What a level's call answered, drawn in it, while it is still on the stack (or the sheet) drawing that call. Where it drew that call's tree already (refreshing), a failure leaves it, and the items it drew past its first page stay after the fresh one's. */
function drawn(level: Level, made: Call, { entry, signIn, asked }: Answered) {
const now = find(level.id);
if (now?.call !== made) return;
const was = current(now) && now.entry?.view.renderer === 'tree' ? now.entry.view : null;
if (was && !signIn && entry.view.renderer === 'error') return update(now, { refreshing: false });
const fresh = was ? refreshed(was, now.first, entry) : entry;
update(now, { entry: fresh, signIn, slow: false, refreshing: false, at: asked, first: itemsIn(entry) });
unswapped(now.id, was);
}
/** A screen in the root's place by its strip (a strip's tab chosen there, or its URL loaded) that its tree, read again (`was` its tree before), no longer offers there (a feed unpinned): the root under it, so it is a screen pushed over the root, its back and title drawn, at the same address and width. A screen pushed over the root stays there, whatever its strip says. */
function unswapped(id: number, was: View | null) {
const level = levels[0];
const now = level?.id === id ? level.entry?.view : null;
if (!root || was?.renderer !== 'tree' || now?.renderer !== 'tree' || !inStrip(was.ui) || inStrip(now.ui) || same(level.call, root)) return;
const under = newLevel(root);
levels = [under, ...levels];
onmove('replace');
void load(under);
}
/** A fresh answer to a screen drawn already (`was`, its first page `first` items), with the items it drew past that page after the fresh page's, and the call for the page after them. */
function refreshed(was: View, first: number, fresh: Entry): Entry {
if (was.renderer !== 'tree' || fresh.view.renderer !== 'tree') return fresh;
const drawnItems = pageItems(was.ui.root) ?? [];
if (drawnItems.length <= first) return fresh;
const items = pagedPast(drawnItems, first, pageItems(fresh.view.ui.root) ?? []);
const grown = append(fresh.view, { renderer: 'tree', ui: { ...was.ui, root: { c: 'List', p: { page: true }, items } }, data: null });
return grown ? { ...fresh, view: grown } : fresh;
}
/** When the account last wrote: an answer to a call made no later is old. */
let wrote = -Infinity;
/** A level shown again, its call made again, unless it answered a moment ago (since the account last wrote) or is loading: what it drew stays, marked as refreshing, until the answer is drawn in its place. */
function revalidate(level: Level | undefined) {
if (!browser || !level || !current(level) || level.refreshing || level.signIn || (level.at > wrote && Date.now() - level.at < AGAIN)) return;
update(level, { refreshing: true });
const marked = find(level.id);
if (marked) void load(marked);
}
/** Whether the stack is drawn in the browser past hydrating: only then is a skeleton the one last drawn here (`recallSkeleton`, kept in the browser's storage), so a level the server drew loading (under a story's URL, the screens under the viewer) hydrates as the server drew it. */
let hydrated = $state(false);
$effect(() => {
hydrated = true;
});
/** A level's skeleton while it loads: as last drawn here, once hydrated. */
const skeletonFor = (call: Call) => (hydrated ? recallSkeleton(call) : GENERIC_SKELETON);
/** The levels that have shown, by id: each stays drawn once it has, under others as it was left. One under the top that never showed (the root under a page loaded at a screen over it, which streams after the page) draws its bar alone until it shows, on the server as in the browser, so a page loading never draws a screen no one sees. */
const shownOnce = new SvelteSet<number>();
$effect(() => {
if (top) shownOnce.add(top.id);
});
/** The story viewer, over everything: items opened from a List of `pages`, or a story's own screen; at first, the server's. */
// svelte-ignore state_referenced_locally
let pager: Paged | null = $state.raw(seedPager?.pager ?? null);
/** The page the server answered for its viewer, drawn by it from the first paint. */
// svelte-ignore state_referenced_locally
const pagerSeeded = seedPager?.answer ? { calls: seedPager.pager.calls, page: pageOf(seedPager.pager.calls[seedPager.pager.at], seedPager.answer) } : null;
/** The view of the story viewer's page in front, by its viewer's calls: the page's head while it is open. */
let pagerView: { calls: Call[]; view: View } | null = $state.raw(null);
/** A call opened as a sheet: its level, over everything, the pager too. */
let sheet: Level | null = $state.raw(null);
/** What a story viewer's page draws for an answer to its call. */
function pageOf(call: Call, answer: Answer) {
const { entry, signIn } = entryOf(call, answer);
return { view: entry.view, signIn };
}
// A level the server drew no answer for (the screen under a story whose
// URL was loaded), read in the browser.
// svelte-ignore state_referenced_locally
if (browser) for (const [i, s] of (seed ?? []).entries()) if (s.answer === null) void load(levels[i]);
/** A level's screen title, as its tree's `Bar` names it; null while it loads, or where its view names none. */
function titleOf(level: Level): string | null {
const view = level.entry?.view;
const named = view?.renderer === 'tree' ? barOf(view.ui.root)?.p?.title : null;
return typeof named === 'string' ? named : null;
}
/** A level on top, told as `how`. */
function push(made: Call, how: Move = 'open') {
void feedback.flush();
const pushed = newLevel(made);
levels = [...levels, pushed];
onmove(how);
void load(pushed);
}
/** A tab's call drawn in a level's place (or the sheet's): the level kept, what it drew drawn until the call answers, or the new call's last tree, where `recent` has it, while it is made again. In the root's place, it is drawn as wide as the root was, so a strip's choice never changes the screen's width. */
function swap(level: Level, made: Call) {
void feedback.flush();
const call = plain(made);
const view = recent.recall(call);
const last = view ? { entry: { view, call }, refreshing: true, at: 0, first: itemsIn({ view, call }) } : { refreshing: false };
const was = level.entry?.view.renderer === 'tree' ? measureOf(level.entry.view.ui) : undefined;
const measure = levels[0]?.id === level.id ? (level.measure ?? was) : undefined;
update(level, { call, opening: call === made ? null : made, slow: false, more: { loading: false, error: null }, measure, ...last });
onmove('replace');
const swapped = find(level.id);
if (swapped) void load(swapped);
}
/** Where the stack is. */
export function place(): Place {
return { calls: levels.length > 0 ? levels.map((l) => l.call) : root ? [root] : [], pager, sheet: sheet?.call ?? null };
}
/** A call's screen as a sheet over what is open: a view's `open.sheet`, or the app's action. */
export function openSheet(made: Call) {
const opened = newLevel(made);
sheet = opened;
onmove('open');
void load(opened);
}
/** The stack set to a place, as a history entry gone back or forward to: the levels it shares with it kept as they were, the rest read (drawn as they last were meanwhile, where `recent` has them), but for one it drew already, somewhere above (its tree unmarked, opening no form again). The screen it shows, kept, is made again (`revalidate`). A call there that opens a form (the app's, opening a screen) opens it once, as its level is made. */
export function sync(to: Place) {
void feedback.flush();
let kept = 0;
while (kept < Math.min(levels.length, to.calls.length) && same(levels[kept].call, plain(to.calls[kept]))) kept++;
if (kept < levels.length || kept < to.calls.length) {
const gone = levels.slice(kept);
const made = to.calls.slice(kept).map((c) => {
const was = gone.find((l) => l.entry && same(l.call, plain(c)));
return was?.entry ? { ...newLevel(c), entry: unopenedEntry(was.entry), opening: null, signIn: was.signIn, refreshing: false, at: was.at, first: was.first } : newLevel(c);
});
levels = [...levels.slice(0, kept), ...made];
for (const m of made) if (!m.entry || m.refreshing) void load(m);
}
// The same pager, less any form its tapped page opens at, is kept as it is.
const pagerCalls = (p: UiSequence | null | undefined) => JSON.stringify(p?.calls.map(plain));
if (pagerCalls(to.pager) !== pagerCalls(pager)) pager = to.pager;
const want = to.sheet ?? null;
if (!(want && sheet && same(plain(want), sheet.call))) {
sheet = want && newLevel(want);
if (sheet) void load(sheet);
}
revalidate(sheet ?? levels.at(-1));
}
/** An entry as it is, its tree unmarked: drawn in a new level, it opens no form again. */
function unopenedEntry(entry: Entry): Entry {
return entry.view.renderer === 'tree' ? { ...entry, view: { ...entry.view, ui: unopened(entry.view.ui) } } : entry;
}
/** A step up, where the browser's back is not one (the screen under was not the entry before: a screen opened on another tab, a page loaded): the sheet closed, or the pager, or the top level left, in place of the history entry on show, so the browser's back still goes where it went; the screen shown again made again. */
export function up() {
void feedback.flush();
if (sheet) sheet = null;
else if (pager) pager = null;
else if (levels.length > 1) levels = levels.slice(0, -1);
else return;
onmove('replace');
revalidate(levels.at(-1));
}
/** The top screen made again (unless it answered a moment ago): a write done over it. */
export function shown() {
revalidate(sheet ?? levels.at(-1));
}
/** The stack's tab chosen: back to its root, the sheet and pager closed and the screens over it let go, the root made again unless it answered a moment ago. The app makes the history entry. */
export function rooted() {
void feedback.flush();
sheet = null;
pager = null;
if (levels.length > 1) levels = levels.slice(0, 1);
revalidate(levels[0]);
}
/** The account wrote: every level's answer is old, made again as it shows, and at once for those under the screen on top, which drew the write itself. */
export function stale() {
wrote = Date.now();
if (active) for (const level of sheet ? levels : levels.slice(0, -1)) revalidate(level);
}
/** Back to the root; at the root, its call made afresh. */
export function home() {
pager = null;
sheet = null;
if (levels.length > 1) {
levels = levels.slice(0, 1);
onmove('jump');
revalidate(levels[0]);
} else {
start();
onmove('replace');
}
}
function start() {
levels = [];
if (!root) return;
const made = newLevel(root);
levels = [made];
void load(made);
}
// Its top screen's head, told as it changes, the story viewer's page's
// while it is open (drawn at the measure of the screen under it, which
// stays as it is); kept while a screen loads.
$effect(() => {
const view = top?.entry?.view;
const story = pager && pagerView?.calls === pager.calls ? pagerView.view : null;
const under = top?.measure ?? (view?.renderer === 'tree' ? measureOf(view.ui) : undefined);
if (story) head = headOfView(story, areas, under);
else if (view) head = headOfView(view, areas, top?.measure);
});
// Focus follows the screen on top, as a native stack's does: a screen
// opened takes it at its title (its level, while it has none), and one
// gone back to has it again where it was left, so it never stays in a
// level covered (`inert`) or let go. Only where it was in this stack:
// elsewhere (the frame's tabs, the search) it stays where it is.
let stackElement: HTMLElement | undefined = $state();
/** Where focus was in each level now covered, by its id. */
const focusedIn = new Map<number, Element>();
let topId: number | undefined;
/** The top level's id as it changes, and whether focus is to follow it there. */
let follow: number | null = null;
$effect.pre(() => {
const id = top?.id;
untrack(() => {
const was = topId;
topId = id;
if (was === undefined || id === undefined || was === id) return;
for (const kept of focusedIn.keys()) if (!levels.some((l) => l.id === kept)) focusedIn.delete(kept);
const focused = document.activeElement;
if (!focused || !stackElement?.contains(focused)) return;
if (levels.some((l) => l.id === was)) focusedIn.set(was, focused);
follow = id;
});
});
$effect(() => {
void top?.id;
untrack(() => {
const id = follow;
follow = null;
if (id === null || id !== top?.id) return;
const level = stackElement?.querySelector<HTMLElement>(':scope > section.level:not(.under)');
const back = focusedIn.get(id);
focusedIn.delete(id);
const to = back instanceof HTMLElement && back.isConnected ? back : (level?.querySelector<HTMLElement>(':scope > .screen-bar > h1') ?? level);
to?.focus({ preventScroll: true });
});
});
// The root afresh whenever its call changes (signing in or out changes
// it), but at first not where the server's page (`seed`) or `sync` has
// set the stack already.
let started = false;
$effect(() => {
void JSON.stringify(root);
void signedIn;
untrack(() => {
const first = !started;
started = true;
if (first && levels.length > 0) return;
start();
if (!first) onmove('replace');
});
});
async function loadMore(level: Level) {
const next = level.entry && nextPage(level.entry);
if (!level.entry || !next) return;
update(level, { more: { loading: true, error: null } });
try {
const view = read(await call(next));
const current = find(level.id);
// Gone, or swapped to another call while the page came: not its page.
if (!current?.entry || current.entry.call !== level.entry.call) return;
if (view.renderer === 'error') return update(current, { more: { loading: false, error: view.message } });
const grown = append(current.entry.view, view);
update(current, {
entry: grown ? { ...current.entry, view: grown } : current.entry,
more: { loading: false, error: grown ? null : 'The next page is not of this list.' }
});
} catch (error) {
update(level, { more: { loading: false, error: errorText(error) } });
}
}
/** A level's call made again, what it answers drawn in its place; a failure throws with the server's words. */
async function reload(level: Level) {
const made = level.call;
const asked = Date.now();
const result = await call(made);
const view = read(result);
if (view.renderer === 'error') throw new Error(view.message);
keep(made, result, view, asked);
const entry = { view, call: made };
const now = find(level.id);
const was = now && current(now) ? (now.entry?.view ?? null) : null;
update(level, { entry, refreshing: false, at: asked, first: itemsIn(entry), more: { loading: false, error: null } });
unswapped(level.id, was);
}
/** A level done with (what it showed deleted): back from it, the level below read again so it shows it gone; the root, read again; the sheet, closed. */
function leave(level: Level) {
if (level.id === sheet?.id) return onback();
const at = levels.findIndex((l) => l.id === level.id);
const below = at > 0 ? levels[at - 1] : level;
if (at > 0) onback();
void reload(below).catch(() => undefined);
}
/** An action done as the account. Signed out, one that writes a record (a ♡, a Follow) goes to sign in, as Grain's web asks, its button busy until it has; a procedure's call (a story marked watched) fails as it would. */
const act: ActionHandler = async (kind, args) => {
if (!signedIn && kind !== 'call') {
location.assign(signIn);
return new Promise<never>(() => undefined);
}
const result = await client.callTool(ACTION_TOOLS[kind], $state.snapshot(args) as Record<string, unknown>);
onwrote();
const done = acted(kind, result);
onacted?.(kind, args);
return done;
};
const tool: UiToolHandler = async (name, args) => {
const result = await client.callTool(name, $state.snapshot(args) as Record<string, unknown>);
if (WRITES.has(name)) onwrote();
return answered(result);
};
/** Open a call from a level, telling its feed the item was opened: one of a List of `pages` in a pager of them all, a story's own screen (`paged`) in the story viewer alone, a `sheet` one as a sheet over what is open; a tab's own screen as that tab (`ontab`); the screen on top again, nothing. From the sheet, the sheet and the pager close and it opens in their place. */
function open(level: Level, made: Call, item: UiReport | null, listed?: UiSequence, asSheet = false) {
const to = level.entry && feedOf(level.entry.view);
const opened = to?.signedIn && item !== null ? to.of(CLICKTHROUGH, item) : null;
if (to && opened) feedback.add(to.feed, opened);
const sequence = listed ?? (!asSheet && paged(made) ? { calls: [made], at: 0 } : undefined);
if (!asSheet && !sequence) {
const top = levels.at(-1);
if (made.args.compose === undefined && !sheet && top?.id === level.id && same(made, top.call)) return;
if (ontab(made)) {
sheet = null;
pager = null;
return;
}
}
const fromSheet = level.id === sheet?.id;
if (asSheet && !fromSheet) return openSheet(made);
if (fromSheet) {
sheet = null;
pager = null;
}
const how: Move = fromSheet ? 'replace' : 'open';
if (sequence) {
pager = sequence;
onmove(how);
} else push(made, how);
}
/** The posts each level told its feed were seen, so it tells each once. */
const seen = new Map<number, Set<string>>();
function onseen(level: Level) {
const to = level.entry && feedOf(level.entry.view);
if (!to?.signedIn) return undefined;
return (item: unknown) => {
const found = to.of(SEEN, item);
if (!found) return;
const told = seen.get(level.id) ?? new Set<string>();
seen.set(level.id, told);
if (told.has(found.item)) return;
told.add(found.item);
feedback.add(to.feed, found);
};
}
function interact(level: Level): UiInteractionHandler | undefined {
const to = level.entry && feedOf(level.entry.view);
if (!to) return undefined;
return async (event, item) => {
const found = to.of(event, item);
if (!found) throw new Error('This item names no post to tell the feed of.');
await feedback.now(to.feed, found);
};
}
</script>
{#snippet treeOf(level: Level, entry: Entry, ui: UiTree, bar: UiBarPlace)}
{@const paged = nextPage(entry)}
<Tree
{ui}
{bar}
{now}
{hrefOf}
root={levels[0]?.id === level.id}
area={areas[level.measure ?? measureOf(ui)]}
held={sheet !== null && level.id !== sheet.id}
oncall={(call, item, sequence, asSheet) => open(level, call, item, sequence, asSheet)}
onreplace={(call) => swap(level, call)}
{onopenlink}
onaction={act}
oninteraction={interact(level)}
onseen={bar === 'only' ? undefined : onseen(level)}
paging={paged && ownsPaging(entry) ? { load: () => void loadMore(level), loading: level.more.loading, error: level.more.error } : null}
onreload={() => reload(level)}
onleave={() => leave(level)}
ontool={signedIn ? tool : undefined}
onupload={signedIn ? client.uploadBlob : undefined}
onhost={signedIn ? onsignout : undefined}
onsignin={signedIn ? undefined : () => location.assign(signIn)}
accounts={signedIn ? accounts : undefined}
pending={level.slow && !current(level)}
/>
{/snippet}
<!-- A screen's Bar in its top bar, the same tree drawn with its Bar alone: on the server as in the browser, so a page drawn there has its buttons where they stay. -->
{#snippet tools(level: Level)}
{#if level.entry && !level.signIn && level.entry.view.renderer === 'tree'}
{@render treeOf(level, level.entry, level.entry.view.ui, 'only')}
{/if}
{/snippet}
{#snippet screen(level: Level)}
{#if !level.entry}
<Skeleton node={skeletonFor(level.call)} delayed root={levels[0]?.id === level.id} />
{:else if level.signIn}
<div class="ask">
<p>Sign in to see this.</p>
<a class="primary" href={signIn} data-sveltekit-reload>Sign in</a>
</div>
{:else if level.entry.view.renderer === 'tree'}
{@const entry = level.entry}
{@const paged = nextPage(entry)}
{@render treeOf(level, entry, level.entry.view.ui, 'apart')}
{#if paged && !ownsPaging(entry) && current(level)}
<LoadMore onload={() => loadMore(level)} loading={level.more.loading} error={level.more.error} auto={inFront(level)} />
{/if}
{:else}
<ErrorMessage message={level.entry.view.message} onretry={() => void load(level)} />
{/if}
{/snippet}
<div class="stack" hidden={!active} bind:this={stackElement}>
{#if !root}
<section class="level">
<header class="screen-bar"><h1 class:wordmark translate={wordmark ? 'no' : undefined}>{wordmark ?? title}</h1></header>
<div class="ask">
<p>Sign in to see your {title.toLowerCase()}.</p>
<a class="primary" href={signIn} data-sveltekit-reload>Sign in</a>
</div>
</section>
{/if}
{#each levels as level, i (level.id)}
{@const shown = level === top}
{@const drawn = shown || shownOnce.has(level.id)}
<section class="level" class:under={!shown} inert={!shown} aria-busy={level.refreshing} tabindex="-1">
<!-- Its screen drawn as it last was while its call is made again: a line along its top, taking no room. -->
{#if level.refreshing}<span class="refreshing" aria-hidden="true"></span>{/if}
<!-- While its screen loads, `reserved` where the screen's last tree had a Bar with buttons: the desktop frame keeps it, so its buttons fill in with no jump. -->
<header class="screen-bar" class:reserved={!level.entry && barOf(skeletonFor(level.call)) !== null}>
{#if i > 0}
{@const named = titleOf(level)}
<button type="button" class="back" onclick={onback} aria-label="Back">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6" /></svg>
</button>
{#if named}<h1 class="screen" tabindex="-1" translate={translateOf(named)}>{named}</h1>{/if}
{:else}
<h1 class:wordmark tabindex="-1" translate={wordmark ? 'no' : undefined}>{wordmark ?? title}</h1>
{/if}
<span class="tools">{#if drawn}{@render tools(level)}{/if}</span>
</header>
<div class="body">
{#if drawn}{@render screen(level)}{/if}
</div>
</section>
{/each}
{#if pager}
{#key pager.calls}
{@const calls = pager.calls}
<Pager
{calls}
start={pager.at}
seed={pagerSeeded?.calls === calls ? pagerSeeded.page : null}
slide={pager.shown ?? null}
wordmark={brand}
recall={(call) => recent.recall(call)}
load={async (call) => {
const { entry, signIn } = await answer(call);
return { view: entry.view, signIn };
}}
onaction={act}
ontool={signedIn ? tool : undefined}
onupload={signedIn ? client.uploadBlob : undefined}
held={sheet !== null}
onopen={(call, asSheet) => {
if (asSheet) return openSheet(call);
pager = null;
push(call, 'replace');
}}
onsignin={() => location.assign(signIn)}
onat={(at, shown) => {
if (pager) pager = { ...pager, at, shown };
onmove('replace');
}}
onview={(view) => (pagerView = { calls, view })}
onclose={onback}
/>
{/key}
{/if}
{#if sheet}
{@const shown = sheet}
{#key shown.id}
<Sheet title={titleOf(shown)} centred={pager !== null} onclose={onback}>
{#snippet bar()}{@render tools(shown)}{/snippet}
{@render screen(shown)}
</Sheet>
{/key}
{/if}
</div>
<style>
.stack {
position: absolute;
inset: 0;
}
/* Sticky at the top of its level's scroll, over the bar, with no height of
its own: a short band sweeping along a hairline, once its call has taken
a moment (as a skeleton waits SKELETON_DELAY), so a quick answer shows none. */
.refreshing {
position: sticky;
top: 0;
z-index: 3;
display: block;
height: 0;
}
.refreshing::after {
content: '';
position: absolute;
inset: 0 0 auto;
height: 2px;
background: linear-gradient(90deg, transparent, var(--app-accent, var(--color-text-secondary)), transparent) no-repeat;
background-size: 40% 100%;
animation:
sweep 1.2s ease-in-out infinite,
appear 0.2s ease 150ms both;
}
@keyframes sweep {
from {
background-position: -70% 0;
}
to {
background-position: 170% 0;
}
}
@keyframes appear {
from {
opacity: 0;
}
to {
opacity: 0.8;
}
}
@media (prefers-reduced-motion: reduce) {
.refreshing::after {
background-size: 100% 100%;
animation: appear 0.2s ease 150ms both;
}
}
.stack[hidden] {
display: block;
visibility: hidden;
pointer-events: none;
}
/* A screen scrolls in its level, its bottom padding the room the tabs
floating over the window's foot take: its end scrolls clear of them,
and what sticks to the bottom of what scrolls (a Covers' bar while
picking) is held above them, as sticky keeps inside that padding. */
.level {
position: absolute;
inset: 0;
overflow-y: auto;
overscroll-behavior: contain;
background: var(--color-background-primary);
padding-bottom: calc(var(--hud-frame-tabbar-height) + 2 * var(--hud-space-3) + env(safe-area-inset-bottom));
}
.level.under {
visibility: hidden;
}
.screen-bar {
position: sticky;
top: 0;
z-index: 2;
display: flex;
align-items: center;
gap: var(--hud-space-3);
min-height: 3rem;
padding: env(safe-area-inset-top) var(--hud-space-4) 0;
background: color-mix(in srgb, var(--color-background-primary) 88%, transparent);
backdrop-filter: blur(12px);
border-bottom: var(--border-width-regular) solid var(--color-border-secondary);
}
/* A screen's title in the app's display font, as Grain's own pages set theirs. */
h1 {
margin: 0;
font-family: var(--app-font-display, inherit);
font-size: var(--font-heading-lg-size);
line-height: var(--font-heading-lg-line-height);
font-weight: var(--font-weight-bold);
}
/* The app's logo in its place, as Grain's top bar sets "grain": its display font at its heaviest. */
.wordmark {
font-size: 1.625rem;
font-weight: 800;
letter-spacing: -0.01em;
}
/* A pushed screen's title beside its back button, as Grain's detail pages head theirs: on one line, cut short where long. */
.screen {
flex: 1;
min-width: 0;
font-size: var(--font-heading-md-size);
line-height: var(--font-heading-md-line-height);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Where a view's Bar draws its buttons: the bar's end. */
.tools {
display: flex;
align-items: center;
margin-left: auto;
margin-right: calc(-1 * var(--hud-space-2));
}
.tools:empty {
display: none;
}
.back {
display: grid;
place-items: center;
width: 2.25rem;
height: 2.25rem;
margin-left: calc(-1 * var(--hud-space-2));
border: 0;
border-radius: var(--border-radius-full);
background: none;
color: var(--color-text-primary);
cursor: pointer;
}
.back svg {
width: 1.5rem;
height: 1.5rem;
fill: none;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
/* Its padding is `--hud-bleed`, how far rows, tiles and pictures that bleed
reach past it, as a tile's body; `--hud-screen` the room between the bar
and the tabs, which a story fills. */
.body {
--hud-bleed: var(--hud-space-3);
--hud-screen: calc(
100dvh - 3rem - env(safe-area-inset-top) - var(--hud-frame-tabbar-height) - 4 * var(--hud-space-3) - env(safe-area-inset-bottom)
);
display: flex;
flex-direction: column;
gap: var(--hud-space-3);
padding: var(--hud-bleed);
}
/* Its top padding is `--hud-lead` to what is first in it alone: a
picture or map that bleeds there meets the bar, as Grain's place's map. */
.body > :global(*) {
--hud-lead: 0px;
}
.body > :global(:first-child) {
--hud-lead: var(--hud-bleed);
}
.ask {
display: grid;
justify-items: center;
gap: var(--hud-space-3);
padding: var(--hud-space-6) var(--hud-space-4);
color: var(--color-text-secondary);
text-align: center;
}
.ask p {
margin: 0;
}
.primary {
display: inline-block;
padding: var(--hud-space-2) var(--hud-space-5);
border: 0;
border-radius: var(--border-radius-full);
background: var(--app-primary, var(--color-background-inverse));
color: var(--app-on-primary, var(--color-text-inverse));
font: inherit;
font-weight: var(--font-weight-semibold);
text-decoration: none;
cursor: pointer;
}
</style>