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
// The playground's JSON editors, CodeMirror's: drawn in the workspace's
// tokens (light and dark by their `light-dark()`, a palette's where the page
// has one), JSON's syntax errors marked as they are typed, the server's
// problems with a view marked where each says (`at`, a path of keys and
// [indexes]), and the catalog's components and props offered as they are
// typed (`"component": "`, a key in `props`).
import { autocompletion, closeBrackets, closeBracketsKeymap, completionKeymap, type Completion, type CompletionContext, type CompletionResult, type CompletionSource } from '@codemirror/autocomplete';
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
import { json, jsonParseLinter } from '@codemirror/lang-json';
import { bracketMatching, ensureSyntaxTree, foldGutter, foldKeymap, HighlightStyle, indentOnInput, syntaxHighlighting, syntaxTree } from '@codemirror/language';
import { linter, lintKeymap, type Diagnostic } from '@codemirror/lint';
import { EditorState, StateEffect, type Extension } from '@codemirror/state';
import { drawSelection, EditorView, highlightActiveLineGutter, highlightSpecialChars, keymap, lineNumbers } from '@codemirror/view';
import type { SyntaxNode } from '@lezer/common';
import { tags } from '@lezer/highlight';
/** One problem the server found with a view. */
export type Problem = { at: string; message: string };
/** A prop as the catalog describes it (`hud_core::catalog::to_json`). */
type CatalogProp = { type?: string; required?: boolean; values?: string[]; keys?: string[]; min?: number; max?: number };
/** The catalog, as getPlayground hands it: what completes is its components. */
export type Catalog = { components?: Record<string, { props?: Record<string, CatalogProp>; children?: boolean; notes?: string }> };
/** Where something is in the document: its first and last offsets. */
export type Span = { from: number; to: number };
const theme = EditorView.theme({
'&': { height: '100%', backgroundColor: 'var(--bg)', color: 'var(--fg)', fontSize: 'var(--text-sm)' },
'&.cm-focused': { outline: 'none' },
'.cm-scroller': { fontFamily: 'var(--font-mono)', lineHeight: 'var(--leading)' },
'.cm-content': { padding: 'var(--space-2) 0', caretColor: 'var(--fg)' },
'.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--fg)' },
'.cm-selectionBackground, &.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection': { backgroundColor: 'var(--soft)', outline: '1px solid var(--line-strong)' },
'.cm-gutters': { borderRight: 'var(--border)', backgroundColor: 'var(--panel)', color: 'var(--faint)' },
'.cm-activeLineGutter': { backgroundColor: 'var(--soft)', color: 'var(--mute)' },
'.cm-foldGutter .cm-gutterElement': { color: 'var(--faint)', cursor: 'pointer' },
'.cm-foldPlaceholder': { margin: '0 var(--space-0-5)', padding: '0 var(--space-1)', border: 'var(--border)', borderRadius: 'var(--radius-sm)', backgroundColor: 'var(--soft)', color: 'var(--mute)' },
'&.cm-focused .cm-matchingBracket': { backgroundColor: 'var(--soft)', outline: '1px solid var(--line-strong)' },
'&.cm-focused .cm-nonmatchingBracket': { backgroundColor: 'transparent', textDecoration: 'underline wavy var(--danger)' },
'.cm-lintRange-error': { backgroundImage: 'none', textDecoration: 'underline wavy var(--danger)', textDecorationSkipInk: 'none' },
'.cm-tooltip': { border: 'var(--border)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--panel)', color: 'var(--fg)', boxShadow: 'var(--shadow-pop)', fontFamily: 'var(--font-sans)', fontSize: 'var(--text-xs)' },
'.cm-tooltip-lint': { padding: 0 },
'.cm-diagnostic': { padding: 'var(--space-1-5) var(--space-2-5)', borderLeft: 'var(--space-0-5) solid var(--danger)' },
'.cm-diagnosticSource': { color: 'var(--mute)', fontFamily: 'var(--font-mono)' },
'.cm-tooltip.cm-tooltip-autocomplete > ul': { maxHeight: 'var(--menu-width)', fontFamily: 'var(--font-mono)' },
'.cm-tooltip.cm-tooltip-autocomplete > ul > li': { padding: 'var(--space-0-5) var(--space-2)' },
'.cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]': { backgroundColor: 'var(--accent-soft)', color: 'var(--fg)' },
'.cm-completionDetail': { marginLeft: 'var(--space-2)', color: 'var(--mute)', fontStyle: 'normal' },
'.cm-completionMatchedText': { textDecoration: 'none', fontWeight: 'var(--weight-semibold)' },
'.cm-tooltip.cm-completionInfo': { maxWidth: 'var(--menu-width)', padding: 'var(--space-2) var(--space-2-5)', lineHeight: 'var(--leading)' },
'.cm-completionIcon': { display: 'none' }
});
/** JSON's parts, each in a colour that reads on the editor (harness/contrast.json). */
const highlight = HighlightStyle.define([
{ tag: tags.propertyName, color: 'var(--accent)' },
{ tag: tags.string, color: 'var(--open)' },
{ tag: tags.number, color: 'var(--merged)' },
{ tag: [tags.bool, tags.null], color: 'var(--danger)' },
{ tag: [tags.brace, tags.squareBracket, tags.separator, tags.punctuation], color: 'var(--mute)' }
]);
/** What every editor here is: JSON, drawn in the tokens, with its own history and keys. */
function base(): Extension[] {
return [
lineNumbers(),
foldGutter({ openText: '▾', closedText: '▸' }),
highlightSpecialChars(),
drawSelection(),
bracketMatching(),
highlightActiveLineGutter(),
syntaxHighlighting(highlight),
json(),
EditorState.tabSize.of(2),
EditorView.lineWrapping,
theme
];
}
/** Said to an editor whose marks' makings changed (the server's problems came): its linter runs again. */
export const relinted = StateEffect.define<null>();
/** An editor for JSON that is written: its history, closing brackets, completions and its syntax errors marked. */
export function writable(options: { lint: (view: EditorView) => Diagnostic[]; complete?: CompletionSource }): Extension[] {
return [
...base(),
history(),
indentOnInput(),
closeBrackets(),
autocompletion({ override: options.complete ? [options.complete] : [], icons: false }),
linter(options.lint, { delay: 300, needsRefresh: (update) => update.transactions.some((tr) => tr.effects.some((e) => e.is(relinted))) }),
keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap, ...foldKeymap, ...completionKeymap, ...lintKeymap, indentWithTab])
];
}
/** An editor for JSON that is only read: selectable and foldable, never changed. */
export function readable(): Extension[] {
return [...base(), EditorState.readOnly.of(true), keymap.of([...defaultKeymap, ...foldKeymap])];
}
const parseErrors = jsonParseLinter();
/** The arguments' editor's marks: JSON's syntax errors, or that what it holds is not an object. */
export function argumentsLint(view: EditorView): Diagnostic[] {
const found = parseErrors(view);
if (found.length) return found;
const top = syntaxTree(view.state).topNode.firstChild;
if (top && top.name !== 'Object') return [{ from: top.from, to: top.to, severity: 'error', message: 'The arguments are an object.' }];
return [];
}
/** The view's editor's marks: JSON's syntax errors, and `problems()`, the server's, each where its path says. */
export function viewLint(problems: () => Problem[]): (view: EditorView) => Diagnostic[] {
return (view) => [
...parseErrors(view),
...problems().map((problem): Diagnostic => ({ ...locate(view.state, pathOf(problem.at)), severity: 'error', message: problem.message, source: problem.at }))
];
}
/** A problem's `at` as its keys and indexes: `list.layout.children[0]` as `list`, `layout`, `children`, 0; `view`, the whole, as none. */
export function pathOf(at: string): (string | number)[] {
return [...at.replace(/^view(?:\.|$)/, '').matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map((m) => (m[2] === undefined ? m[1] : Number(m[2])));
}
const VALUES: Record<string, true> = { Object: true, Array: true, String: true, Number: true, True: true, False: true, Null: true };
/** A property name's key, as JSON reads it. */
function keyOf(state: EditorState, name: SyntaxNode): string {
const text = state.sliceDoc(name.from, name.to);
try {
return String(JSON.parse(text));
} catch {
return text.replace(/^"|"$/g, '');
}
}
/** The property of `object` named `key`, or null. */
function propertyOf(state: EditorState, object: SyntaxNode, key: string): SyntaxNode | null {
for (let p = object.firstChild; p; p = p.nextSibling) {
const name = p.name === 'Property' ? p.getChild('PropertyName') : null;
if (name && keyOf(state, name) === key) return p;
}
return null;
}
/** A property's value, once written. */
function valueOf(property: SyntaxNode): SyntaxNode | null {
const last = property.lastChild;
return last && VALUES[last.name] ? last : null;
}
/**
* Where `path` is in the document: a key and its value when the value is
* short, the key alone when it opens an object or array, an array's element
* on its first line. A path the document does not have is marked at the
* nearest part of it that it does, a missing prop at the object it is
* missing from.
*/
export function locate(state: EditorState, path: (string | number)[]): Span {
const tree = ensureSyntaxTree(state, state.doc.length, 200) ?? syntaxTree(state);
let value = tree.topNode.firstChild;
if (!value) return { from: 0, to: Math.min(1, state.doc.length) };
let key: SyntaxNode | null = null;
for (const part of path) {
let found: { key: SyntaxNode | null; value: SyntaxNode | null } | null = null;
if (typeof part === 'string' && value.name === 'Object') {
const property = propertyOf(state, value, part);
if (property) found = { key: property.getChild('PropertyName'), value: valueOf(property) };
} else if (typeof part === 'number' && value.name === 'Array') {
let i = 0;
for (let c: SyntaxNode | null = value.firstChild; c && !found; c = c.nextSibling) if (VALUES[c.name] && i++ === part) found = { key: null, value: c };
}
if (!found) break;
key = found.key;
if (!found.value) {
value = null;
break;
}
value = found.value;
}
if (!value) return key ? { from: key.from, to: key.to } : { from: 0, to: 1 };
const scalar = value.name !== 'Object' && value.name !== 'Array';
if (key) return { from: key.from, to: scalar ? value.to : key.to };
if (scalar) return { from: value.from, to: value.to };
return { from: value.from, to: Math.min(value.to, state.doc.lineAt(value.from).to) };
}
/** The component an object holding `"component": "<name>"` names, or null. */
function componentOf(state: EditorState, node: SyntaxNode | null): string | null {
const property = node?.name === 'Object' ? propertyOf(state, node, 'component') : null;
const value = property && valueOf(property);
return value?.name === 'String' ? keyOf(state, value) : null;
}
/** The innermost object at `pos`, or null in an array or outside any. */
function objectAt(state: EditorState, pos: number): SyntaxNode | null {
for (let node: SyntaxNode | null = syntaxTree(state).resolveInner(pos, 1); node; node = node.parent) {
if (node.name === 'Object') return node;
if (node.name === 'Array') return null;
}
return null;
}
/** The key of the property whose value `node` is, or null. */
function heldAs(state: EditorState, node: SyntaxNode | null): string | null {
const name = node?.parent?.name === 'Property' ? node.parent.getChild('PropertyName') : null;
return name ? keyOf(state, name) : null;
}
/** What a typed string is completed to, as far as its closing quote: a key's `": ` after it, unless the closing quote is there already. Nothing until a quote or a letter is typed, or completions are asked for. */
function quoted(context: CompletionContext, word: string, quote: string, options: Completion[], suffix: string): CompletionResult | null {
if (!word && !quote && !context.explicit) return null;
const closing = quote !== '' && context.state.sliceDoc(context.pos, context.pos + 1) === '"';
return {
from: context.pos - word.length,
to: closing ? context.pos + 1 : context.pos,
options: options.map((option) => ({ ...option, apply: `${quote ? '' : '"'}${option.label}"${suffix}` })),
validFor: /^[\w$-]*$/
};
}
/** Completions from `catalog()`: a component's name after `"component": `, a component's props as keys in its `props`, a prop's words as its value, and a layout node's own keys. */
export function catalogCompletions(catalog: () => Catalog | null): CompletionSource {
return (context) => {
const components = catalog()?.components;
if (!components) return null;
const { state, pos } = context;
const before = state.sliceDoc(Math.max(0, pos - 200), pos);
const named = /"component"\s*:\s*("?)([A-Za-z]*)$/.exec(before);
if (named) {
const [, quote, word] = named;
const options = Object.entries(components).map(([name, c]): Completion => ({ label: name, type: 'class', info: c.notes || undefined }));
return quoted(context, word, quote, options, '');
}
const valued = /"([\w$]+)"\s*:\s*("?)([\w-]*)$/.exec(before);
if (valued) {
const [, key, quote, word] = valued;
const object = objectAt(state, pos - valued[0].length);
const prop = heldAs(state, object) === 'props' ? components[componentOf(state, object?.parent?.parent ?? null) ?? '']?.props?.[key] : undefined;
if (!prop?.values?.length || prop.type === 'words') return null;
return quoted(context, word, quote, prop.values.map((label) => ({ label, type: 'enum' })), '');
}
const keyed = /[{,]\s*("?)([\w$]*)$/.exec(before);
if (!keyed) return null;
const [, quote, word] = keyed;
const object = objectAt(state, pos - keyed[0].length);
if (!object) return null;
const present = new Set<string>();
for (let p = object.firstChild; p; p = p.nextSibling) {
const name = p.name === 'Property' ? p.getChild('PropertyName') : null;
if (name && name.to < pos - word.length - quote.length) present.add(keyOf(state, name));
}
const held = heldAs(state, object);
let options: Completion[] = [];
if (held === 'props') {
const props = components[componentOf(state, object.parent?.parent ?? null) ?? '']?.props ?? {};
options = Object.entries(props).map(([label, p]) => ({
label,
type: 'property',
detail: [p.type, p.required ? 'required' : null].filter(Boolean).join(', '),
info: p.values?.length ? `One of ${p.values.join(', ')}` : p.min !== undefined ? `From ${p.min} to ${p.max}` : undefined,
boost: p.required ? 1 : 0
}));
} else if (held === 'layout' || heldAs(state, object.parent) === 'children') {
const children = components[componentOf(state, object) ?? '']?.children !== false;
options = ['component', 'props', ...(children ? ['children'] : [])].map((label) => ({ label, type: 'property' }));
}
options = options.filter((option) => !present.has(option.label));
if (!options.length) return null;
return quoted(context, word, quote, options, ': ');
};
}