~ 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
382 lines · 13.6 KB Raw History
<script lang="ts">
	import { tick, untrack } from 'svelte';
	import Icon from '../atoms/Icon.svelte';
	import type { Row } from '../launcher.svelte';
	import { chains, widthOf, type Actor, type Column as ColumnModel, type Slot } from '../model';
	import { accountOf, callKey } from '../tiles';
	import type { Workspace } from '../workspace.svelte';
	import Column from './Column.svelte';
	import Launcher from './Launcher.svelte';
	import Tile from './Tile.svelte';

	/**
	 * A canvas's strip: its columns left to right, scrolled natively
	 * sideways and snapping to their starts, then a ghost column to open a
	 * launcher at the end. What it is asked (a column shown, or flashed) it
	 * does by scrolling; a change made elsewhere, even left of what is in
	 * view, never moves what is in view. A swipe that leaves the focus out
	 * of sight gives it to the column most in view. A strip stays mounted
	 * while its tab is out of sight, keeping its scroll and its tiles and
	 * what they read; but only the columns within a screen of what is in
	 * view, on the tab on screen, draw it (Tile's `live`), so memory follows
	 * what is on screen, not what is open.
	 */
	let {
		ws,
		canvas,
		me,
		shown,
		onconnect
	}: {
		ws: Workspace;
		canvas: string;
		me: Actor;
		/** Whether its tab is the one on screen. */
		shown: boolean;
		onconnect: () => void;
	} = $props();

	const ui = $derived(ws.ui(canvas));
	const strip: ColumnModel[] = $derived(ws.strip(canvas));
	const readonly = $derived(ws.readonly(canvas));
	const linked = $derived(chains(strip, ui.colours));
	/** Where each slot stands: its column's index and its place in it. */
	const where = $derived(new Map(strip.flatMap((column, c) => column.slots.map((slot, r): [string, { c: number; r: number }] => [slot.key, { c, r }]))));
	const titles = $derived(new Map(strip.flatMap((column) => column.slots.flatMap((slot) => (slot.kind === 'tile' ? [[slot.key, ws.title(slot.tile)] as const] : [])))));
	const openCalls = $derived(new Set(strip.flatMap((column) => column.slots.flatMap((slot) => (slot.kind === 'tile' ? [callKey(slot.tile.tool, slot.tile.arguments)] : [])))));
	let flashes = $state<Record<string, number>>({});
	/** The columns more than a screen's width out of view either side: their tiles keep what they read, but draw none of it, until they come near again. */
	const far = $derived.by(() => {
		const view = ui.view;
		if (!view) return new Set<string>();
		return new Set(view.columns.filter((c) => c.left + c.width < view.scroll - view.room || c.left > view.scroll + 2 * view.room).map((c) => c.key));
	});

	let element: HTMLElement | undefined = $state();

	const motion = () => !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
	const columnOf = (key: string) => strip[where.get(key)?.c ?? -1];
	const columnElement = (key: string) => element?.querySelector<HTMLElement>(`[data-column="${CSS.escape(key)}"]`) ?? null;
	const gap = () => parseFloat(getComputedStyle(element!).columnGap) || 0;

	/** Scroll so a column shows: onto a column's start (a snap point), as centred as one allows; `nearest` only when it is out of sight. */
	function reveal(key: string, mode: 'center' | 'nearest') {
		const target = columnElement(key);
		if (!element || !target) return;
		const room = element.clientWidth;
		const max = element.scrollWidth - room;
		const now = element.scrollLeft;
		const g = gap();
		const left = target.offsetLeft;
		const width = target.offsetWidth;
		const fits = (s: number) => left >= s + g - 1 && left + width <= s + room - g + 1;
		if (mode === 'nearest' && fits(now)) return;
		const clamp = (s: number) => Math.min(Math.max(s, 0), max);
		const starts = [...new Set([0, max, ...[...element.querySelectorAll<HTMLElement>('[data-column]')].map((c) => clamp(c.offsetLeft - g))])].filter(fits);
		const score = (s: number) => (mode === 'center' ? Math.abs(left + width / 2 - (s + room / 2)) * 4 + Math.abs(s - now) / 100 : Math.abs(s - now));
		const best = starts.length ? starts.reduce((a, b) => (score(b) < score(a) ? b : a)) : clamp(left - g);
		if (Math.abs(best - now) > 0.5) element.scrollTo({ left: best, behavior: motion() ? 'smooth' : 'instant' });
	}

	/** The count of the ask done last: each is done once, as it is made or as its tab comes on screen. */
	let done = 0;

	// What is asked of the strip: a column shown, flashed, or both. An ask
	// moves the strip once; the columns changing after (a tile's arrival,
	// the canvas read again as the stream reopens) never do it again, so
	// nothing takes a person who scrolled away back to what they asked for
	// before. One whose column is not there yet waits for it.
	$effect(() => {
		const ask = ui.ask;
		if (!ask || ask.n === done || !shown) return;
		const column = columnOf(ask.key);
		if (!column) return;
		done = ask.n;
		if (ask.reveal) {
			const to = ask.reveal;
			requestAnimationFrame(() => reveal(column.key, to));
		}
		if (ask.flash) untrack(() => (flashes[column.key] = (flashes[column.key] ?? 0) + 1));
	});

	// A change to the columns keeps the first column in view where it was.
	$effect.pre(() => {
		void strip;
		if (!element) return;
		const box = element;
		const anchor = [...box.querySelectorAll<HTMLElement>('[data-column]')].find((c) => c.offsetLeft + c.offsetWidth > box.scrollLeft);
		if (!anchor) return;
		const key = anchor.dataset.column;
		const before = anchor.offsetLeft - box.scrollLeft;
		void tick().then(() => {
			const now = key ? columnElement(key) : null;
			if (!now) return;
			const moved = now.offsetLeft - box.scrollLeft - before;
			if (Math.abs(moved) > 0.5) box.scrollTo({ left: box.scrollLeft + moved, behavior: 'instant' });
		});
	});

	/** How much of a column is in view, from 0 to 1. */
	function seen(c: HTMLElement) {
		if (!element) return 0;
		const s = element.scrollLeft;
		return Math.max(0, Math.min(c.offsetLeft + c.offsetWidth, s + element.clientWidth) - Math.max(c.offsetLeft, s)) / c.offsetWidth;
	}

	let measuring = 0;
	/** Say where the strip lies, for its map, once a frame at most. */
	function measure() {
		if (measuring) return;
		measuring = requestAnimationFrame(() => {
			measuring = 0;
			if (!element) return;
			ui.view = {
				scroll: element.scrollLeft,
				room: element.clientWidth,
				total: element.scrollWidth,
				columns: [...element.querySelectorAll<HTMLElement>('[data-column]')].map((c) => ({ key: c.dataset.column ?? '', left: c.offsetLeft, width: c.offsetWidth }))
			};
		});
	}

	// Measured as the columns change, and as the strip is sized.
	$effect(() => {
		void strip;
		void ui.zoomed;
		if (!element) return;
		void tick().then(measure);
		const observer = new ResizeObserver(measure);
		observer.observe(element);
		return () => observer.disconnect();
	});

	// A wheel's listener that may keep the page from scrolling.
	$effect(() => {
		if (!element) return;
		const box = element;
		box.addEventListener('wheel', wheel, { passive: false });
		return () => box.removeEventListener('wheel', wheel);
	});

	let settle: number | undefined;
	/** A swipe that leaves the focus mostly out of sight gives it to the column most in view. */
	function scrolled() {
		measure();
		window.clearTimeout(settle);
		settle = window.setTimeout(() => {
			if (!shown || !element || !ui.focus) return;
			const focused = columnOf(ui.focus);
			const at = focused && columnElement(focused.key);
			if (at && seen(at) >= 0.5) return;
			const best = [...element.querySelectorAll<HTMLElement>('[data-column]')].reduce<HTMLElement | null>((a, b) => (!a || seen(b) > seen(a) + 0.01 ? b : a), null);
			const column = best?.dataset.column ? strip.find((c) => c.key === best.dataset.column) : undefined;
			if (column) ws.focus(canvas, column.slots[0].key);
		}, 160);
	}

	let wheeled = 0;
	let wheelLock = 0;
	/** When the last wheel up or down came, and the last one sideways. */
	let wheelAt = -Infinity;
	let sidewaysAt = -Infinity;
	/** A mouse's wheel, turned over a header or a gap (not a tile's body, which scrolls), steps the focus a column. A swipe sideways (a trackpad's) goes a little up or down too: while one goes on, and a moment after, its wheels are the browser's to scroll, never a step, which would take the strip back to the focus it left. A turn begins afresh after a pause, so what a swipe left does not add up into one. */
	function wheel(event: WheelEvent) {
		if (event.ctrlKey) return;
		const now = performance.now();
		if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) {
			sidewaysAt = now;
			wheeled = 0;
			return;
		}
		if ((event.target as Element).closest('.body') || now - sidewaysAt < 300) return;
		event.preventDefault();
		if (now - wheelAt > 250) wheeled = 0;
		wheelAt = now;
		if (now < wheelLock) return;
		wheeled += event.deltaY;
		if (Math.abs(wheeled) < 40) return;
		step(Math.sign(wheeled) as 1 | -1);
		wheeled = 0;
		wheelLock = now + 220;
	}

	function step(by: 1 | -1) {
		const at = ui.focus ? where.get(ui.focus) : undefined;
		const next = strip[Math.min(Math.max((at?.c ?? -1) + by, 0), strip.length - 1)];
		if (next) ws.focus(canvas, next.slots[Math.min(at?.r ?? 0, next.slots.length - 1)].key, 'center');
	}

	/** Where a tile's source is, from it: its arrow. */
	function source(key: string, from: string | null) {
		if (!from || !where.has(from)) return null;
		const a = where.get(key)!;
		const b = where.get(from)!;
		const arrow = b.c < a.c ? '←' : b.c > a.c ? '→' : b.r < a.r ? '↑' : '↓';
		return { title: titles.get(from) ?? 'its source', arrow } as const;
	}

	const opened = (row: Row) => openCalls.has(callKey(row.call.tool, row.call.arguments));
</script>

{#snippet slot(one: Slot)}
	{#if one.kind === 'tile'}
		{@const tile = one.tile}
		{@const column = columnOf(one.key)}
		{@const account = accountOf(tile.tool, tile.arguments)}
		<Tile
			{tile}
			{canvas}
			title={titles.get(one.key) ?? ws.title(tile)}
			account={account === 'me' ? me.did : account}
			{me}
			focused={shown && ui.focus === one.key}
			arrived={ui.arrived.has(one.key)}
			chain={linked.colour.get(one.key)}
			source={source(one.key, tile.from)}
			author={tile.author !== me.did ? tile.author : null}
			{readonly}
			width={column?.slots[0].key === one.key ? widthOf(ui.zoomed === column.key ? 'full' : column.width).label : null}
			zoomed={ui.zoomed === column?.key}
			live={shown && !(column && far.has(column.key))}
			onfocus={() => ws.focus(canvas, one.key)}
			onsource={() => {
				if (!tile.from) return;
				ws.show(canvas, tile.from);
			}}
			onwidth={() => ws.cycleWidth(canvas, one.key)}
			onzoom={() => {
				ws.focus(canvas, one.key);
				ws.zoom(canvas);
			}}
			onclose={() => void ws.close(canvas, one.key)}
			onpreview={(found) => ws.previews.set(one.key, found)}
			onlabel={(learned) => ws.labels.set(one.key, learned)}
		/>
	{:else}
		<Launcher
			{me}
			focused={shown && ui.focus === one.key}
			{readonly}
			empty={!strip.some((found) => found.slots[0].kind === 'tile')}
			canvases={ws.canvases.filter((found) => found.id !== canvas && found.invitedBy === null)}
			{opened}
			onfocus={() => ws.focus(canvas, one.key)}
			onpick={(call) => void ws.pick(canvas, one.key, call)}
			oncanvas={(id) => {
				ws.closeLauncher(canvas, one.key);
				void ws.activate(id);
			}}
			onclose={() => ws.closeLauncher(canvas, one.key)}
			onstep={step}
			{onconnect}
		/>
	{/if}
{/snippet}

<main bind:this={element} class="strip" class:shown aria-hidden={!shown} inert={!shown} onscroll={scrolled} aria-label="Columns">
	{#each strip as column (column.key)}
		{@const head = column.slots[0]}
		<Column
			{column}
			share={ui.zoomed === column.key ? 1 : widthOf(column.width).share}
			bridge={head.kind === 'tile' && linked.link.get(head.key) === 'left' ? linked.colour.get(head.key) : undefined}
			flash={flashes[column.key] ?? 0}
			{slot}
		/>
	{:else}
		<div class="empty-canvas">
			<h2>This canvas is empty</h2>
			{#if readonly}
				<p>No tiles yet. Its owner and editors put them here.</p>
			{:else}
				<p>No tiles yet. Open one from your atproto, or ask your AI to put one here.</p>
				<button type="button" class="btn primary" title="New tile (T)" onclick={() => ws.launch(canvas, null)}><Icon name="add" />New tile</button>
			{/if}
		</div>
	{/each}
	{#if !readonly && strip.length > 0 && strip.at(-1)?.slots[0].kind !== 'launcher'}
		<button type="button" class="ghost" title="New tile (T)" onclick={() => ws.launch(canvas, strip.at(-1)?.key ?? null)}>
			<Icon name="add" />
			<span>New tile</span>
		</button>
	{/if}
</main>

<style>
	.strip {
		position: absolute;
		inset: 0;
		display: flex;
		gap: var(--gap);
		padding: var(--space-2) var(--gap) var(--gap);
		overflow-x: auto;
		overflow-y: hidden;
		overscroll-behavior-x: contain;
		scroll-snap-type: x proximity;
		scroll-padding-inline: var(--gap);
		scrollbar-width: none;
		visibility: hidden;
	}

	.strip::-webkit-scrollbar {
		display: none;
	}

	.strip.shown {
		visibility: visible;
	}

	.empty-canvas {
		display: flex;
		flex: 1;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: var(--space-2);
		padding: var(--space-10) var(--pad-x);
		color: var(--mute);
		text-align: center;
	}

	.empty-canvas h2 {
		color: var(--fg);
		font-size: var(--text-lg);
	}

	.empty-canvas .btn {
		margin-top: var(--space-2);
	}

	.ghost {
		display: grid;
		flex: none;
		place-content: center;
		justify-items: center;
		gap: var(--space-1);
		width: var(--ghost);
		border: 1.5px dashed var(--line-strong);
		border-radius: var(--radius-lg);
		background: none;
		color: var(--mute);
		font: inherit;
		font-size: var(--text-sm);
		cursor: pointer;
	}

	.ghost:hover {
		border-color: var(--faint);
		background: var(--hover);
		color: var(--fg);
	}

	@media (max-width: 640px) {
		.strip {
			scroll-snap-type: x mandatory;
		}

		/* No snap point of its own: one kept snapped as columns come before it would carry the strip to its end. */
		.ghost {
			width: 50%;
		}
	}
</style>