~ 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
72 lines · 2.2 KB Raw History
<script lang="ts">
	import { EditorState, type Extension } from '@codemirror/state';
	import { forceLinting } from '@codemirror/lint';
	import { relinted } from '../playground/editor';
	import { EditorView } from '@codemirror/view';
	import { onMount } from 'svelte';

	/**
	 * A CodeMirror editor of `value`, as its `extensions` make it (given
	 * once, as it mounts): what is typed in it goes back to `value`, and a
	 * `value` given from outside (another template) replaces what it holds.
	 * `label` names it, for its text box has no visible label of its own.
	 */
	let { value = $bindable(), extensions, label }: { value: string; extensions: Extension[]; label: string } = $props();

	let host: HTMLDivElement | undefined = $state();
	let view: EditorView | undefined;
	/** What it holds, as it last said or was told: a `value` that differs came from outside. */
	let held = '';

	onMount(() => {
		held = value;
		view = new EditorView({
			parent: host,
			state: EditorState.create({
				doc: value,
				extensions: [
					...extensions,
					EditorView.contentAttributes.of({ 'aria-label': label }),
					EditorView.updateListener.of((update) => {
						if (!update.docChanged) return;
						held = update.state.doc.toString();
						value = held;
					})
				]
			})
		});
		return () => view?.destroy();
	});

	$effect(() => {
		const next = value;
		if (!view || next === held) return;
		held = next;
		view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: next } });
	});

	/** Select `span`, as `find` finds it in what it holds now, scrolled into view, and focus it. */
	export function reveal(find: (state: EditorState) => { from: number; to: number }) {
		if (!view) return;
		const { from, to } = find(view.state);
		view.dispatch({ selection: { anchor: from, head: to }, effects: EditorView.scrollIntoView(from, { y: 'center' }) });
		view.focus();
	}

	/** Mark it again now, as what its marks are made of changed (the server's problems). */
	export function relint() {
		if (!view) return;
		view.dispatch({ effects: relinted.of(null) });
		forceLinting(view);
	}
</script>

<div class="code" bind:this={host}></div>

<style>
	.code {
		height: 100%;
		min-height: 0;
		overflow: hidden;
	}
</style>