chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
@hud/shell 0.5.0 Latest 5 packages
0
0
// The workspace as this page holds it: who is signed in, their canvases,
// the ones open as tabs and the one on screen, each open canvas's tiles,
// who is on it, and what happened on it while it was out of sight (its
// tab's badges). Each method is one of the appview's, with what it changes
// shown at once and set right by the answer and by the live stream, whose
// events come here too, whoever made them: this page, another, another
// member, an agent through HUD's canvas tools.
//
// What only this page has, per canvas: the column with focus, the
// launchers (columns that are not tiles yet), the column zoomed, the tiles
// that arrived from someone else and are not yet seen, and the scrolls
// and flashes the strip is asked for.
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
import type { Call } from '@hud/shared/result';
import type * as addTile from './lexicons/place/hud/addTile.defs.ts';
import type * as checkTheme from './lexicons/place/hud/checkTheme.defs.ts';
import type * as closeCanvas from './lexicons/place/hud/closeCanvas.defs.ts';
import type * as createCanvas from './lexicons/place/hud/createCanvas.defs.ts';
import type * as createTheme from './lexicons/place/hud/createTheme.defs.ts';
import type * as declineInvite from './lexicons/place/hud/declineInvite.defs.ts';
import type * as deleteCanvas from './lexicons/place/hud/deleteCanvas.defs.ts';
import type * as deleteTheme from './lexicons/place/hud/deleteTheme.defs.ts';
import type * as getCanvas from './lexicons/place/hud/getCanvas.defs.ts';
import type * as getWorkspace from './lexicons/place/hud/getWorkspace.defs.ts';
import type * as listCanvases from './lexicons/place/hud/listCanvases.defs.ts';
import type * as listThemes from './lexicons/place/hud/listThemes.defs.ts';
import type * as HudDefs from './lexicons/place/hud/defs.defs.ts';
import type * as inviteMember from './lexicons/place/hud/inviteMember.defs.ts';
import type * as leaveCanvas from './lexicons/place/hud/leaveCanvas.defs.ts';
import type * as openCanvas from './lexicons/place/hud/openCanvas.defs.ts';
import type * as placeTile from './lexicons/place/hud/placeTile.defs.ts';
import type * as removeMember from './lexicons/place/hud/removeMember.defs.ts';
import type * as removeTile from './lexicons/place/hud/removeTile.defs.ts';
import type * as setMemberRole from './lexicons/place/hud/setMemberRole.defs.ts';
import type * as setTabOrder from './lexicons/place/hud/setTabOrder.defs.ts';
import type * as setTheme from './lexicons/place/hud/setTheme.defs.ts';
import type * as setTileWidth from './lexicons/place/hud/setTileWidth.defs.ts';
import type * as stackTile from './lexicons/place/hud/stackTile.defs.ts';
import type * as unstackTile from './lexicons/place/hud/unstackTile.defs.ts';
import type * as updateCanvas from './lexicons/place/hud/updateCanvas.defs.ts';
import type * as updateTile from './lexicons/place/hud/updateTile.defs.ts';
import { canvasOf, columns, handleText, STACK, tileOf, WIDTHS, type Actor, type Canvas, type Column, type Launcher, type PresenceEvent, type Role, type Tile, type TileEvent, type Width } from './model';
import type { Preview } from './preview';
import { launcher } from './launcher.svelte';
import { draw, type Palette, type Scheme, type Theme } from './theme';
import { callKey, tileTitle, type Learned } from './tiles';
import { procedure, SignedOut, xrpc, type Asked } from './xrpc';
/** An account as listThemes asks for one: a DID or a handle. */
type Identifier = NonNullable<Asked<typeof listThemes.main>['actor']>;
/** What a canvas's tab says of it while it is out of sight. */
export type Badge = { agent: number; changed: string | null };
/** A thing to go to, said for a moment at the top right. */
export type Toast = { id: number; message: string; action: { label: string; run: () => void } | null; tone: 'agent' | 'plain' };
/** A move of the strip asked for: a column shown (`center`, or `nearest` when it is out of sight), flashed, or both. */
export type Ask = { key: string; reveal: 'center' | 'nearest' | null; flash: boolean; n: number };
/** A call to put on a canvas, and the title a person or the launcher gave it; with none, the tile's title is made of what it shows. */
export type Opening = { tool: string; arguments: Record<string, unknown>; title?: string };
/** The strip as it lies: its scroll, the width in view, its whole width, and each column's place on it. */
export type StripView = { scroll: number; room: number; total: number; columns: { key: string; left: number; width: number }[] };
/** This page's own state of one canvas. */
export class CanvasUi {
focus = $state<string | null>(null);
launchers = $state<Launcher[]>([]);
zoomed = $state<string | null>(null);
arrived = new SvelteSet<string>();
ask = $state<Ask | null>(null);
/** Each chained tile's colour, kept as its chain grows. */
colours = new Map<string, number>();
/** What the strip shows, as its strip map draws it: how far it is scrolled, how wide it is in view, and where each column stands on it. */
view = $state<StripView | null>(null);
}
/** How long a toast stays. */
const TOAST_MS = 8000;
const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));
let launcherCount = 0;
let asks = 0;
let toasts = 0;
export class Workspace {
me = $state<Actor>({ did: '' });
/** The other accounts this browser is signed in to, to switch to, the one used last first. */
accounts = $state.raw<Actor[]>([]);
canvases = $state<Canvas[]>([]);
open = $state<string[]>([]);
current = $state<string | null>(null);
/** The theme chosen, as it is drawn; none, the system's light or dark. */
theme = $state.raw<Theme | null>(null);
/** HUD's themes, as getWorkspace lists them. */
themes = $state.raw<Theme[]>([]);
/** The themes this person made, once read (`loadMine`); null until then. */
mine = $state.raw<Theme[] | null>(null);
/** Whether the person signed in before HUD asked for all it asks for now: signing in again allows the rest. */
signInAgain = $state(false);
/** A choice of theme on its way to the server: a reading from before it leaves the page as it is. */
#choosing = 0;
/** Each open canvas's tiles, once read. */
tiles = new SvelteMap<string, Tile[]>();
/** Who is on each open canvas now, this person among them. */
present = new SvelteMap<string, Actor[]>();
badges = new SvelteMap<string, Badge>();
/** Each tile's mini form, by its id, from what it last drew: the overview's cards. */
previews = new SvelteMap<string, Preview>();
/** What each tile learned of itself when drawn, by its id: its record's label, its collection's name. */
labels = new SvelteMap<string, Learned>();
toast = $state<Toast | null>(null);
/** Why the workspace could not be read, until it is. */
failed = $state<string | null>(null);
#ui = new Map<string, CanvasUi>();
#toastTimer: number | null = null;
/** A canvas as listed, or undefined. */
info(id: string | null): Canvas | undefined {
return this.canvases.find((canvas) => canvas.id === id);
}
/** This page's state of a canvas. */
ui(id: string): CanvasUi {
let found = this.#ui.get(id);
if (!found) {
found = new CanvasUi();
this.#ui.set(id, found);
}
return found;
}
readonly(id: string | null): boolean {
return this.info(id)?.role === 'viewer';
}
/** A canvas's columns, its launchers among them. */
strip(id: string): Column[] {
return columns(this.tiles.get(id) ?? [], this.ui(id).launchers);
}
/** Who else is on a canvas now. */
others(id: string): Actor[] {
return (this.present.get(id) ?? []).filter((actor) => actor.did !== this.me.did);
}
/** Whether this person is in a canvas: theirs, or one they accepted. */
joined(canvas: Canvas): boolean {
return canvas.invitedBy === null;
}
/** Say something a moment, with a way to act on it. */
say(message: string, action: Toast['action'] = null, tone: Toast['tone'] = 'plain') {
this.toast = { id: ++toasts, message, action, tone };
if (this.#toastTimer !== null) window.clearTimeout(this.#toastTimer);
this.#toastTimer = window.setTimeout(() => (this.toast = null), TOAST_MS);
}
/** Say what went wrong, but for a sign-out, which shows the sign-in card. */
fail(error: unknown) {
if (!(error instanceof SignedOut)) this.say(errorText(error));
}
#viewOnly(id: string) {
if (!this.readonly(id)) return false;
this.say('You can view this canvas, not change it.');
return true;
}
/** Ask the strip to show a column of a canvas, and flash it if `flash`. */
ask(canvas: string, key: string, reveal: Ask['reveal'], flash = false) {
this.ui(canvas).ask = { key, reveal, flash, n: ++asks };
}
/** Focus a column of a canvas, its arrival seen. */
focus(canvas: string, key: string, reveal: Ask['reveal'] = null) {
const ui = this.ui(canvas);
ui.focus = key;
ui.arrived.delete(key);
if (reveal) this.ask(canvas, key, reveal);
}
/** Go to a column already there: focused, brought to the middle of the strip, and flashed. */
show(canvas: string, key: string) {
this.focus(canvas, key);
this.ask(canvas, key, 'center', true);
}
/** The workspace read again: the tabs, every canvas (each page of them), and the tiles of any open canvas not read yet. */
async load() {
let found: getWorkspace.$OutputBody;
const canvases: Canvas[] = [];
try {
found = await xrpc<typeof getWorkspace.main>('place.hud.getWorkspace', {});
let cursor: string | undefined;
do {
const page: listCanvases.$OutputBody = await xrpc<typeof listCanvases.main>('place.hud.listCanvases', { limit: 100, cursor });
canvases.push(...page.canvases.map(canvasOf));
cursor = page.cursor;
} while (cursor);
} catch (error) {
if (!(error instanceof SignedOut)) this.failed = errorText(error);
return;
}
this.failed = null;
this.me = found.me;
this.accounts = found.accounts ?? [];
this.signInAgain = found.signInAgain ?? false;
launcher.apps = found.launchers ?? [];
this.themes = found.themes ?? [];
if (this.#choosing === 0) this.#drawTheme(found.theme ?? null);
this.canvases = canvases;
this.#tabs(found.open, found.current);
}
#drawTheme(theme: Theme | null) {
this.theme = theme;
draw(theme);
}
/** Draw the workspace in a theme, or the system's for none, here at once and wherever the person is signed in. */
async chooseTheme(theme: Theme | null) {
const was = this.theme;
this.#drawTheme(theme);
this.#choosing++;
try {
const said = await procedure<typeof setTheme.main>('place.hud.setTheme', theme?.key ? { key: theme.key } : theme?.uri ? { uri: theme.uri } : {});
this.#drawTheme(said.theme ?? null);
} catch (error) {
this.#drawTheme(was);
this.fail(error);
} finally {
this.#choosing--;
}
}
/** The themes this person made, read again. */
async loadMine() {
try {
const found: Theme[] = [];
let cursor: string | undefined;
do {
const page = await xrpc<typeof listThemes.main>('place.hud.listThemes', { actor: this.me.did as Identifier, limit: 50, cursor });
found.push(...page.themes);
cursor = page.cursor;
} while (cursor);
this.mine = found;
} catch (error) {
this.fail(error);
}
}
/** Make a theme in this person's repository and draw the workspace in it. */
async makeTheme(name: string, colorScheme: Scheme, palette: Palette): Promise<void> {
const { theme } = await procedure<typeof createTheme.main>('place.hud.createTheme', { name, colorScheme, palette });
this.mine = [theme, ...(this.mine ?? [])];
await this.chooseTheme(theme);
}
/** Delete a theme this person made; drawn in it still, they keep its colours. */
async deleteTheme(theme: Theme) {
if (!theme.uri) return;
try {
await procedure<typeof deleteTheme.main>('place.hud.deleteTheme', { uri: theme.uri });
this.mine = (this.mine ?? []).filter((found) => found.uri !== theme.uri);
this.say(`Deleted “${theme.name}”.`);
} catch (error) {
this.fail(error);
}
}
/** A page of people's themes: an account's, by handle or DID, or everyone's. */
listThemes(actor: string | null, cursor: string | undefined) {
return xrpc<typeof listThemes.main>('place.hud.listThemes', { actor: (actor ?? undefined) as Identifier | undefined, cursor });
}
/** The texts of a palette that read at under 4.5:1 on what they are drawn on. */
async checkPalette(palette: Palette) {
const { problems } = await procedure<typeof checkTheme.main>('place.hud.checkTheme', { palette });
return problems;
}
/** A canvas as the server says it now, in the list. */
#know(view: HudDefs.CanvasView) {
const canvas = canvasOf(view);
this.canvases = this.canvases.some((found) => found.id === canvas.id) ? this.canvases.map((found) => (found.id === canvas.id ? canvas : found)) : [...this.canvases, canvas];
}
/** The tabs as the server has them; tiles read for those new, dropped for those closed. */
#tabs(tabs: HudDefs.Tab[], current: string) {
for (const tab of tabs) this.#know(tab.canvas);
const open = tabs.map((tab) => tab.canvas.key);
this.open = open;
if (!this.current || !open.includes(this.current)) this.current = current;
for (const id of [...this.tiles.keys()]) {
if (open.includes(id)) continue;
this.tiles.delete(id);
this.present.delete(id);
this.badges.delete(id);
}
for (const id of open) if (!this.tiles.has(id)) void this.loadCanvas(id);
}
/** One canvas's tiles, read whole: what changed while the stream was down is caught up. An empty canvas opens with a launcher. */
async loadCanvas(id: string) {
try {
const found = await xrpc<typeof getCanvas.main>('place.hud.getCanvas', { canvas: id });
const tiles = found.tiles.map(tileOf);
this.tiles.set(id, tiles);
const ui = this.ui(id);
if (tiles.length === 0 && ui.launchers.length === 0) this.launch(id, null);
else if (!ui.focus || !this.strip(id).some((column) => column.slots.some((slot) => slot.key === ui.focus))) ui.focus = this.strip(id)[0]?.slots[0]?.key ?? null;
} catch (error) {
this.fail(error);
}
}
/** Everything read again, as when the stream opens. */
async reload() {
await this.load();
await Promise.all(this.open.map((id) => this.loadCanvas(id)));
}
// The live stream.
/** A tile changed. One added by someone else, or an agent, glows on the
* canvas on screen, with a toast to go to it, and badges the tab of one
* out of sight; nothing moves the view. */
heardTile(event: TileEvent) {
const list = this.tiles.get(event.canvas);
if (!list) return;
const tile = event.tile ? tileOf(event.tile) : null;
if (event.op === 'remove') this.#drop(event.canvas, event.key);
else if (tile) this.#put(event.canvas, tile);
const by = event.by;
if (!by || (by.kind !== 'agent' && by.did === this.me.did)) return;
const agent = by.kind === 'agent';
const who = agent ? 'An agent' : by.handle ? handleText(by.did, by.handle) : 'A member';
const name = this.info(event.canvas)?.name ?? 'a canvas';
const canvas = event.canvas;
if (event.op === 'add' && tile) {
const id = tile.id;
if (canvas === this.current) {
this.ui(canvas).arrived.add(id);
this.say(`${who} added “${this.title(tile)}”`, { label: 'Show', run: () => this.focus(canvas, id, 'center') }, agent ? 'agent' : 'plain');
return;
}
const badge = this.badges.get(canvas) ?? { agent: 0, changed: null };
this.badges.set(canvas, agent ? { ...badge, agent: badge.agent + 1 } : { ...badge, changed: `${who} added “${this.title(tile)}”` });
this.ui(canvas).arrived.add(id);
this.say(
`${who} added “${this.title(tile)}” to “${name}”`,
{
label: 'Show',
run: () => {
void this.activate(canvas);
this.focus(canvas, id, 'center');
}
},
agent ? 'agent' : 'plain'
);
} else if (canvas !== this.current) {
const badge = this.badges.get(canvas) ?? { agent: 0, changed: null };
this.badges.set(canvas, { ...badge, changed: `${who} changed “${name}”` });
}
}
heardPresence(event: PresenceEvent) {
this.present.set(event.canvas, event.present);
}
#put(canvas: string, tile: Tile) {
const list = this.tiles.get(canvas) ?? [];
const at = list.findIndex((found) => found.id === tile.id);
this.tiles.set(canvas, at < 0 ? [...list, tile] : list.with(at, tile));
}
#drop(canvas: string, id: string) {
const list = this.tiles.get(canvas);
if (list) this.tiles.set(canvas, list.filter((tile) => tile.id !== id));
const ui = this.ui(canvas);
ui.arrived.delete(id);
this.labels.delete(id);
if (ui.zoomed === id) ui.zoomed = null;
}
/** A tile's title as people read it, in its header, its chip, the palette and wherever it is named. */
title(tile: Tile): string {
return tileTitle(tile, this.labels.get(tile.id), launcher.names);
}
// Tabs and canvases.
/** Show a canvas, opening it as a tab (and accepting it, for an invitation); its badges clear. */
async activate(id: string) {
this.badges.delete(id);
if (this.open.includes(id)) this.current = id;
try {
const found = await procedure<typeof openCanvas.main>('place.hud.openCanvas', { canvas: id });
this.#know(found.canvas);
this.#tabs(found.open, found.current);
this.current = id;
} catch (error) {
this.fail(error);
void this.load();
}
}
/** Put a canvas away: its tab closes, the canvas stays, in the + menu. */
async putAway(id: string) {
if (this.open.length <= 1) {
this.say('The last open tab can’t be closed.');
return;
}
const name = this.info(id)?.name ?? 'the canvas';
const at = this.open.indexOf(id);
const rest = this.open.filter((found) => found !== id);
if (this.current === id) this.current = rest[Math.min(at, rest.length - 1)];
this.open = rest;
try {
const found = await procedure<typeof closeCanvas.main>('place.hud.closeCanvas', { canvas: id });
const open = found.open.map((tab) => tab.canvas.key);
this.#tabs(found.open, this.current && open.includes(this.current) ? this.current : found.current);
this.say(`Put “${name}” away. It’s in the + menu.`, { label: 'Undo', run: () => void this.activate(id) });
} catch (error) {
this.fail(error);
void this.load();
}
}
async reorder(order: string[]) {
this.open = order;
try {
const found = await procedure<typeof setTabOrder.main>('place.hud.setTabOrder', { tabs: order.map((canvas) => ({ canvas })) });
this.#tabs(found.open, found.current);
} catch (error) {
this.fail(error);
void this.load();
}
}
/** A new canvas, open and on screen, with a launcher: its id, to name it. */
async create(name = 'Untitled canvas'): Promise<string | null> {
try {
const { canvas } = await procedure<typeof createCanvas.main>('place.hud.createCanvas', { name });
this.#know(canvas);
await this.activate(canvas.key);
return canvas.key;
} catch (error) {
this.fail(error);
return null;
}
}
async rename(id: string, name: string) {
const before = this.canvases;
this.canvases = this.canvases.map((canvas) => (canvas.id === id ? { ...canvas, name } : canvas));
try {
const { canvas } = await procedure<typeof updateCanvas.main>('place.hud.updateCanvas', { canvas: id, name });
this.#know(canvas);
} catch (error) {
this.canvases = before;
this.fail(error);
}
}
async remove(id: string) {
try {
await procedure<typeof deleteCanvas.main>('place.hud.deleteCanvas', { canvas: id });
} catch (error) {
this.fail(error);
}
await this.load();
}
async decline(id: string) {
try {
await procedure<typeof declineInvite.main>('place.hud.declineInvite', { canvas: id });
} catch (error) {
this.fail(error);
}
await this.load();
}
// Members: these throw, for the share dialog to say why.
async invite(id: string, actor: string, role: Exclude<Role, 'owner'>) {
this.#know((await procedure<typeof inviteMember.main>('place.hud.inviteMember', { canvas: id, actor: actor as inviteMember.$InputBody['actor'], role })).canvas);
}
async setRole(id: string, did: string, role: Exclude<Role, 'owner'>) {
this.#know((await procedure<typeof setMemberRole.main>('place.hud.setMemberRole', { canvas: id, did: did as setMemberRole.$InputBody['did'], role })).canvas);
}
async removeMember(id: string, did: string) {
this.#know((await procedure<typeof removeMember.main>('place.hud.removeMember', { canvas: id, did: did as removeMember.$InputBody['did'] })).canvas);
}
async leave(id: string) {
await procedure<typeof leaveCanvas.main>('place.hud.leaveCanvas', { canvas: id });
await this.load();
}
// Columns.
/** A launcher right of the column `after` (null: at the start), focused. */
launch(canvas: string, after: string | null) {
const ui = this.ui(canvas);
const key = `launcher-${++launcherCount}`;
ui.launchers = [...ui.launchers, { key, after }];
this.focus(canvas, key, 'center');
}
/** Close a launcher; what was right of it stays where it was. */
closeLauncher(canvas: string, key: string) {
const ui = this.ui(canvas);
const strip = this.strip(canvas);
const at = strip.findIndex((column) => column.key === key);
const left = strip[at - 1]?.key ?? null;
ui.launchers = ui.launchers.filter((launcher) => launcher.key !== key).map((launcher) => (launcher.after === key ? { ...launcher, after: left } : launcher));
if (ui.focus === key) {
const next = strip[at - 1] ?? strip[at + 1];
ui.focus = next?.slots[0]?.key ?? null;
}
}
/** The tile on a canvas that is the same call, if any. */
#same(canvas: string, call: Opening): Tile | undefined {
const key = callKey(call.tool, call.arguments);
return this.tiles.get(canvas)?.find((tile) => callKey(tile.tool, tile.arguments) === key);
}
/** Go to the tile on this canvas that is the same call, if there is one; never to another canvas. */
#goTo(canvas: string, call: Opening): boolean {
const tile = this.#same(canvas, call);
if (tile) this.show(canvas, tile.id);
return Boolean(tile);
}
/** The server found the same call on the canvas already, written otherwise: that tile, brought into view, nothing placed. */
#existing(canvas: string, found: addTile.$OutputBody): boolean {
if (!found.existing) return false;
const tile = tileOf(found.tile);
if (!this.tiles.get(canvas)?.some((known) => known.id === tile.id)) this.#put(canvas, tile);
this.show(canvas, tile.id);
return true;
}
/** The nearest tile column at or left of a column (the left side) or right of it. */
#tileColumn(strip: Column[], at: number, step: -1 | 1): Column | undefined {
for (let i = at; i >= 0 && i < strip.length; i += step) if (strip[i].slots[0]?.kind === 'tile') return strip[i];
return undefined;
}
/** Put a tile on a canvas where a column `at` the strip's index stands, a launcher's or a new one's. */
async #addAt(canvas: string, call: Opening, at: number, launcher: string | null) {
const strip = this.strip(canvas);
const left = this.#tileColumn(strip, at - 1, -1);
const right = left ? undefined : this.#tileColumn(strip, at + (launcher ? 1 : 0), 1);
try {
const found = await procedure<typeof addTile.main>('place.hud.addTile', {
canvas,
tool: call.tool,
arguments: call.arguments as addTile.$InputBody['arguments'],
title: call.title,
...(left ? { after: left.key } : {})
});
if (this.#existing(canvas, found)) {
if (launcher) this.closeLauncher(canvas, launcher);
return;
}
let tile = tileOf(found.tile);
if (right) tile = tileOf((await procedure<typeof placeTile.main>('place.hud.placeTile', { canvas, tile: tile.id, before: right.key })).tile);
this.#put(canvas, tile);
if (launcher) {
const ui = this.ui(canvas);
ui.launchers = ui.launchers.filter((found) => found.key !== launcher).map((found) => (found.after === launcher ? { ...found, after: tile.id } : found));
}
this.focus(canvas, tile.id, 'nearest');
} catch (error) {
this.fail(error);
}
}
/** A launcher's pick: the launcher turns into the tile, in its place; or goes to the tile already open. */
async pick(canvas: string, launcher: string, call: Opening) {
if (this.#same(canvas, call)) {
this.closeLauncher(canvas, launcher);
this.#goTo(canvas, call);
return;
}
if (this.#viewOnly(canvas)) return;
await this.#addAt(
canvas,
call,
this.strip(canvas).findIndex((column) => column.key === launcher),
launcher
);
}
/** From the palette: a new column right of the focused one; or the tile already open on this canvas. */
async openNew(canvas: string, call: Opening) {
if (this.#goTo(canvas, call) || this.#viewOnly(canvas)) return;
const strip = this.strip(canvas);
const focus = this.ui(canvas).focus;
const at = strip.findIndex((column) => column.slots.some((slot) => slot.key === focus));
await this.#addAt(canvas, call, at < 0 ? strip.length : at + 1, null);
}
/** Open a call from a tile: right of it, after what was opened from it already; or the tile already open on this canvas. */
async openFrom(canvas: string, from: string, next: Call) {
const call: Opening = { tool: next.name, arguments: next.args };
if (this.#goTo(canvas, call) || this.#viewOnly(canvas)) return;
try {
const found = await procedure<typeof addTile.main>('place.hud.addTile', {
canvas,
tool: call.tool,
arguments: call.arguments as addTile.$InputBody['arguments'],
title: call.title,
from
});
if (this.#existing(canvas, found)) return;
this.#put(canvas, tileOf(found.tile));
this.focus(canvas, found.tile.key, 'center');
} catch (error) {
this.fail(error);
}
}
/** Draw another call in a tile, as a tab chosen in it: the same tile, its
* key, place and `from` kept, its call the tab's, every page told (and
* this one by the answer). False on a canvas this person can only view,
* where nothing is kept. */
async replace(canvas: string, id: string, next: Call): Promise<boolean> {
if (this.readonly(canvas)) return false;
try {
const found = await procedure<typeof updateTile.main>('place.hud.updateTile', {
canvas,
tile: id,
tool: next.name,
arguments: next.args as updateTile.$InputBody['arguments']
});
this.#put(canvas, tileOf(found.tile));
} catch (error) {
this.fail(error);
}
return true;
}
/** Close a column's tile, or its launcher; the focus goes to the tile it came from, else the column on its left. */
async close(canvas: string, key: string) {
const ui = this.ui(canvas);
if (ui.launchers.some((launcher) => launcher.key === key)) return this.closeLauncher(canvas, key);
if (this.#viewOnly(canvas)) return;
const strip = this.strip(canvas);
const tile = this.tiles.get(canvas)?.find((found) => found.id === key);
const at = strip.findIndex((column) => column.slots.some((slot) => slot.key === key));
if (ui.focus === key) {
const source = tile?.from && this.tiles.get(canvas)?.some((found) => found.id === tile.from) ? tile.from : null;
const column = strip[at];
const below = column?.slots.find((slot) => slot.key !== key);
ui.focus = source ?? below?.key ?? (strip[at - 1] ?? strip[at + 1])?.slots[0]?.key ?? null;
}
const column = strip[at];
const heir = column && column.key === key && column.slots.length > 1 ? column.slots[1].key : (strip[at - 1]?.key ?? null);
ui.launchers = ui.launchers.map((launcher) => (launcher.after === key ? { ...launcher, after: heir } : launcher));
const before = this.tiles.get(canvas) ?? [];
this.#drop(canvas, key);
try {
await procedure<typeof removeTile.main>('place.hud.removeTile', { canvas, tile: key });
} catch (error) {
this.tiles.set(canvas, before);
this.fail(error);
}
}
/** Move the focused column one place left or right. */
async move(canvas: string, step: -1 | 1): Promise<boolean> {
const ui = this.ui(canvas);
const strip = this.strip(canvas);
const at = strip.findIndex((column) => column.slots.some((slot) => slot.key === ui.focus));
const column = strip[at];
const other = strip[at + step];
if (!column || !other) return false;
// A launcher moves on this page alone: the two columns swap, and each launcher is anchored again to what is now on its left.
if (column.slots[0].kind === 'launcher' || other.slots[0].kind === 'launcher') {
const keys = strip.map((found) => found.key);
[keys[at], keys[at + step]] = [keys[at + step], keys[at]];
const launchers = new Map(ui.launchers.map((launcher) => [launcher.key, launcher]));
ui.launchers = keys.flatMap((key, i) => (launchers.has(key) ? [{ key, after: keys[i - 1] ?? null }] : []));
this.ask(canvas, column.key, 'nearest');
return true;
}
if (this.#viewOnly(canvas)) return true;
const tiles = this.tiles.get(canvas) ?? [];
const head = tiles.find((tile) => tile.id === column.key);
const beyond = strip[at + 2 * step];
const near = Number(tiles.find((tile) => tile.id === other.key)?.order ?? 0);
const far = beyond && beyond.slots[0].kind === 'tile' ? Number(tiles.find((tile) => tile.id === beyond.key)?.order) : near + step;
if (head) this.#put(canvas, { ...head, order: String((near + far) / 2) });
this.ask(canvas, column.key, 'nearest');
try {
const { tile } = await procedure<typeof placeTile.main>('place.hud.placeTile', {
canvas,
tile: column.key,
...(step === -1 ? { before: other.key } : { after: other.key })
});
this.#put(canvas, tileOf(tile));
} catch (error) {
this.fail(error);
void this.loadCanvas(canvas);
}
return true;
}
/** Set a column's width, by any tile in it. */
async setWidth(canvas: string, id: string, width: Width) {
if (this.#viewOnly(canvas)) return;
const ui = this.ui(canvas);
const column = this.strip(canvas).find((found) => found.slots.some((slot) => slot.key === id));
if (!column || column.slots[0].kind !== 'tile') return;
if (ui.zoomed === column.key) ui.zoomed = null;
const head = column.slots[0].tile;
this.#put(canvas, { ...head, width });
this.ask(canvas, column.key, 'nearest');
try {
const { tile } = await procedure<typeof setTileWidth.main>('place.hud.setTileWidth', { canvas, tile: head.id, width });
this.#put(canvas, tileOf(tile));
} catch (error) {
this.#put(canvas, head);
this.fail(error);
}
}
/** The next width, or with `step` -1 the one before. */
cycleWidth(canvas: string, id: string, step: 1 | -1 = 1) {
const column = this.strip(canvas).find((found) => found.slots.some((slot) => slot.key === id));
if (!column) return;
const at = WIDTHS.findIndex((w) => w.width === column.width);
void this.setWidth(canvas, id, WIDTHS[(at + step + WIDTHS.length) % WIDTHS.length].width);
}
/** Stack a tile, with any stacked under it, at the foot of the column on its left. */
async stack(canvas: string, id: string): Promise<boolean> {
const strip = this.strip(canvas);
const at = strip.findIndex((column) => column.slots.some((slot) => slot.key === id));
const column = strip[at];
const left = strip[at - 1];
if (!column || !left || left.slots[0].kind !== 'tile' || column.slots[0].kind !== 'tile') return false;
const moving = column.slots[0].key === id ? column.slots.length : 1;
if (left.slots.length + moving > STACK) {
this.say(`A column stacks ${STACK} tiles at most.`);
return false;
}
if (this.#viewOnly(canvas)) return true;
try {
const { tile } = await procedure<typeof stackTile.main>('place.hud.stackTile', { canvas, tile: id, into: left.key });
this.#put(canvas, tileOf(tile));
this.focus(canvas, id, 'nearest');
} catch (error) {
this.fail(error);
}
return true;
}
/** Take a stacked tile out of its stack, into a column of its own on its right. */
async unstack(canvas: string, id: string): Promise<boolean> {
const column = this.strip(canvas).find((found) => found.slots.some((slot) => slot.key === id));
if (!column || column.slots.length < 2) return false;
if (this.#viewOnly(canvas)) return true;
try {
const { tile } = await procedure<typeof unstackTile.main>('place.hud.unstackTile', { canvas, tile: id });
this.#put(canvas, tileOf(tile));
this.focus(canvas, id, 'center');
} catch (error) {
this.fail(error);
}
return true;
}
/** Zoom the column with focus to fill the strip, or put its width back. */
zoom(canvas: string) {
const ui = this.ui(canvas);
const column = this.strip(canvas).find((found) => found.slots.some((slot) => slot.key === ui.focus));
if (!column) return;
ui.zoomed = ui.zoomed === column.key ? null : column.key;
this.ask(canvas, column.key, 'center');
}
}