feat(playground): migrate client to React

This commit is contained in:
Yujong Lee 2026-09-10 15:56:07 -07:00
parent d7492bf9ec
commit de7df11fcf
17 changed files with 667 additions and 357 deletions

View file

@ -48,6 +48,7 @@ runuser -u playground -- env -i \
NODE_ENV=production \
HOST=0.0.0.0 \
PORT=8080 \
PLAYGROUND_USERNAME="${OPENCODE_SERVER_USERNAME:-opencode}" \
PLAYGROUND_PASSWORD="${OPENCODE_SERVER_PASSWORD}" \
PLAYGROUND_REPOSITORY_DIR="${repository_directory}" \
PLAYGROUND_WORKSPACE_DIR="${workspace_directory}" \

View file

@ -7,54 +7,7 @@
<title>LiteLLM Rust Playground</title>
</head>
<body>
<main class="shell">
<header class="topbar">
<div>
<span class="eyebrow">LOCAL PROOF</span>
<h1>LiteLLM Rust Playground</h1>
</div>
<div class="status-row">
<span id="lsp-status" class="status" data-state="loading">Connecting to rust-analyzer</span>
<span id="diagnostic-status" class="status">Diagnostics pending</span>
<button id="reset-button" class="button secondary" type="button">Reset</button>
<button id="run-button" class="button primary" type="button">Run</button>
</div>
</header>
<section class="workspace">
<aside class="docs" aria-label="Markdown document">
<div class="docbar">
<span id="guide-path">GUIDE.md</span>
<span class="document-language">Markdown</span>
</div>
<div id="markdown-editor"></div>
</aside>
<section class="editor-panel" aria-label="Rust editor">
<div class="filebar">
<span id="active-path">src/main.rs</span>
<span id="revision" class="revision"></span>
</div>
<div class="editor-body">
<div id="editors"></div>
<aside class="file-tree" aria-label="Project files">
<p class="tree-title">EXAMPLES</p>
<nav id="example-nav" class="example-nav" aria-label="Examples"></nav>
<p id="file-tree-title" class="tree-title files-title">FILES</p>
<nav id="file-nav" class="file-nav"></nav>
</aside>
</div>
</section>
<section class="output-panel" aria-live="polite">
<div class="output-header">
<span>OUTPUT</span>
<span id="run-status"></span>
</div>
<pre id="output">Press Run to compile against the cloned LiteLLM repository.</pre>
</section>
</section>
</main>
<script type="module" src="/src/main.ts"></script>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View file

@ -12,11 +12,16 @@
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.11",
"@pierre/trees": "^1.0.0-beta.6",
"@tanstack/react-query": "^5.102.8",
"codemirror": "^6.0.2",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"vite": "^7.1.5",
"ws": "^8.18.3"
},
"devDependencies": {
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"typescript": "^5.9.2"
}
},
@ -1127,12 +1132,58 @@
"win32"
]
},
"node_modules/@tanstack/query-core": {
"version": "5.102.8",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.102.8.tgz",
"integrity": "sha512-ZNjkJ33CqvPNec/6lZBnHqLc3EVGPZ9ySLhYahU9TcuRFdmwXewuj0c4hwSWcGHqEUwcSrKeZ+oGcvPBqXcQcg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.102.8",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.102.8.tgz",
"integrity": "sha512-TYBea4OuXWD7MhaSHq069TWbFe7rcwWN6kzT7JF0OKi1K6c1gTv2IzD6A6ExJsCMozdkqBWeuIUZmu4KQg0O5A==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.102.8"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"license": "MIT"
},
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
"integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
"dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
"integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.3.0"
}
},
"node_modules/codemirror": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz",
@ -1154,6 +1205,13 @@
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
@ -1326,7 +1384,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",
"integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@ -1336,7 +1393,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
"integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.28.0"
},
@ -1393,8 +1449,7 @@
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
"integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/source-map-js": {
"version": "1.2.1",

View file

@ -13,11 +13,16 @@
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.11",
"@pierre/trees": "^1.0.0-beta.6",
"@tanstack/react-query": "^5.102.8",
"codemirror": "^6.0.2",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"vite": "^7.1.5",
"ws": "^8.18.3"
},
"devDependencies": {
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"typescript": "^5.9.2"
}
}

View file

@ -17,14 +17,16 @@ const host = process.env.HOST ?? '127.0.0.1';
const isProduction = process.env.NODE_ENV === 'production';
const staticDirectory = path.join(playgroundDirectory, 'dist');
const playgroundPassword = process.env.PLAYGROUND_PASSWORD;
const playgroundUsername = process.env.PLAYGROUND_USERNAME ?? 'opencode';
const commandEnvironment = { ...process.env };
delete commandEnvironment.PLAYGROUND_PASSWORD;
delete commandEnvironment.PLAYGROUND_USERNAME;
const isAuthorized = request => {
if (!playgroundPassword) {
return true;
}
const expected = Buffer.from(`opencode:${playgroundPassword}`);
const expected = Buffer.from(`${playgroundUsername}:${playgroundPassword}`);
const authorization = request.headers.authorization ?? '';
const actual = authorization.startsWith('Basic ')
? Buffer.from(authorization.slice('Basic '.length), 'base64')

View file

@ -0,0 +1,147 @@
import { rust } from '@codemirror/lang-rust';
import { languageServerExtensions, LSPClient } from '@codemirror/lsp-client';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView, basicSetup } from 'codemirror';
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
import { commandClickDefinition, connectTransport, PlaygroundWorkspace } from './lsp';
import type { PlaygroundExample, PlaygroundInfo, StoredFiles } from './types';
export type CodeEditorsHandle = {
getFiles: (example: PlaygroundExample) => StoredFiles;
goToLine: (uri: string, requestedLine: number) => void;
reset: (example: PlaygroundExample) => void;
};
type CodeEditorsProps = {
activeUri: string;
info: PlaygroundInfo;
onConnectionChange: (state: 'connecting' | 'ready' | 'error', message?: string) => void;
onDiagnostics: (message: string, hasDiagnostics: boolean) => void;
onOpenFile: (uri: string) => boolean;
onSave: (target: string, source: string) => void;
};
export const CodeEditors = forwardRef<CodeEditorsHandle, CodeEditorsProps>(function CodeEditors(
{ activeUri, info, onConnectionChange, onDiagnostics, onOpenFile, onSave },
handle,
) {
const containers = useRef(new Map<string, HTMLDivElement>());
const views = useRef(new Map<string, EditorView>());
const callbacks = useRef({ onConnectionChange, onDiagnostics, onOpenFile, onSave });
callbacks.current = { onConnectionChange, onDiagnostics, onOpenFile, onSave };
useImperativeHandle(handle, () => ({
getFiles: example => Object.fromEntries(
example.files.map(file => [file.path, views.current.get(file.uri)?.state.doc.toString() ?? file.source]),
),
goToLine: (uri, requestedLine) => {
const view = views.current.get(uri);
if (!view) {
return;
}
const line = view.state.doc.line(Math.min(Math.max(requestedLine, 1), view.state.doc.lines));
view.dispatch({
selection: { anchor: line.from },
effects: EditorView.scrollIntoView(line.from, { y: 'center' }),
});
view.focus();
},
reset: example => example.files.forEach(file => {
const view = views.current.get(file.uri);
view?.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: file.source } });
}),
}), []);
useEffect(() => {
let disposed = false;
const setup = async () => {
callbacks.current.onConnectionChange('connecting');
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const transport = await connectTransport(`${protocol}//${location.host}/lsp`, () => {
if (!disposed) {
callbacks.current.onConnectionChange('error', 'rust-analyzer disconnected');
}
});
const client = new LSPClient({
rootUri: info.rootUri,
timeout: 15_000,
workspace: lspClient => new PlaygroundWorkspace(lspClient, uri => {
callbacks.current.onOpenFile(uri);
return views.current.get(uri) ?? null;
}),
extensions: languageServerExtensions(),
notificationHandlers: {
'textDocument/publishDiagnostics': (_client, params) => {
const diagnostics = Array.isArray(params?.diagnostics) ? params.diagnostics : [];
const filename = String(params?.uri ?? '').split('/').at(-1) ?? 'file';
callbacks.current.onDiagnostics(
`${diagnostics.length} diagnostic${diagnostics.length === 1 ? '' : 's'} in ${filename}`,
diagnostics.length > 0,
);
return false;
},
},
}).connect(transport);
await client.initializing;
if (disposed) {
return;
}
info.examples.flatMap(example => example.files).forEach(file => {
const parent = containers.current.get(file.uri);
if (!parent) {
return;
}
const languageExtensions = file.languageId === 'rust'
? [rust(), client.plugin(file.uri, 'rust'), commandClickDefinition]
: [];
const view = new EditorView({
doc: file.source,
extensions: [
basicSetup,
oneDark,
languageExtensions,
EditorView.lineWrapping,
EditorView.updateListener.of(update => {
if (update.docChanged) {
callbacks.current.onSave(file.target, update.state.doc.toString());
}
}),
],
parent,
});
views.current.set(file.uri, view);
});
callbacks.current.onConnectionChange('ready');
};
setup().catch(error => {
const message = error instanceof Error ? error.message : 'Unable to start rust-analyzer';
callbacks.current.onConnectionChange('error', message);
});
return () => {
disposed = true;
views.current.forEach(view => view.destroy());
views.current.clear();
};
}, [info]);
return (
<div className="editors">
{info.examples.flatMap(example => example.files).map(file => (
<div
key={file.uri}
className="editor-container"
hidden={file.uri !== activeUri}
ref={element => {
if (element) {
containers.current.set(file.uri, element);
} else {
containers.current.delete(file.uri);
}
}}
/>
))}
</div>
);
});

View file

@ -1,24 +0,0 @@
const requireElement = <T extends HTMLElement>(id: string): T => {
const element = document.getElementById(id);
if (!element) {
throw new Error(`Missing element: ${id}`);
}
return element as T;
};
export const elements = {
activePath: requireElement<HTMLSpanElement>('active-path'),
diagnosticStatus: requireElement<HTMLSpanElement>('diagnostic-status'),
editorsParent: requireElement<HTMLDivElement>('editors'),
exampleNav: requireElement<HTMLElement>('example-nav'),
fileNav: requireElement<HTMLElement>('file-nav'),
fileTreeTitle: requireElement<HTMLParagraphElement>('file-tree-title'),
guidePath: requireElement<HTMLSpanElement>('guide-path'),
lspStatus: requireElement<HTMLSpanElement>('lsp-status'),
markdownEditorParent: requireElement<HTMLDivElement>('markdown-editor'),
output: requireElement<HTMLPreElement>('output'),
resetButton: requireElement<HTMLButtonElement>('reset-button'),
revision: requireElement<HTMLSpanElement>('revision'),
runButton: requireElement<HTMLButtonElement>('run-button'),
runStatus: requireElement<HTMLSpanElement>('run-status'),
};

View file

@ -0,0 +1,43 @@
import { useEffect, useRef } from 'react';
import { ExampleFileTree } from './file-tree';
import type { PlaygroundExample } from './types';
type FileTreePanelProps = {
activePath?: string;
example: PlaygroundExample;
onOpenFile: (uri: string) => boolean;
};
export const FileTreePanel = ({ activePath, example, onOpenFile }: FileTreePanelProps) => {
const container = useRef<HTMLElement>(null);
const tree = useRef<ExampleFileTree | null>(null);
const openFile = useRef(onOpenFile);
openFile.current = onOpenFile;
useEffect(() => {
if (!container.current) {
return;
}
const instance = new ExampleFileTree(container.current, uri => { openFile.current(uri); });
instance.render(example, activePath);
tree.current = instance;
return () => {
instance.cleanUp();
tree.current = null;
};
}, [example]);
useEffect(() => {
if (activePath) {
tree.current?.select(activePath);
}
}, [activePath]);
return (
<>
<p className="tree-title files-title">FILES · {example.id}://</p>
<nav ref={container} className="file-nav" aria-label={`${example.title} files`} />
</>
);
};

View file

@ -8,14 +8,12 @@ export class ExampleFileTree {
public constructor(
private readonly container: HTMLElement,
private readonly title: HTMLElement,
private readonly openFile: (uri: string) => void,
) {}
public render(example: PlaygroundExample, selectedPath?: string) {
this.tree?.cleanUp();
this.container.replaceChildren();
this.title.textContent = `FILES · ${example.id}://`;
this.container.setAttribute('aria-label', `${example.title} files`);
const directories = new Set<string>();
@ -57,4 +55,9 @@ export class ExampleFileTree {
this.tree?.scrollToPath(path, { focus: false, offset: 'nearest' });
this.syncingSelection = false;
}
public cleanUp() {
this.tree?.cleanUp();
this.tree = null;
}
}

View file

@ -1,4 +0,0 @@
import { startPlayground } from './playground-app';
import './style.css';
startPlayground();

22
playground/src/main.tsx Normal file
View file

@ -0,0 +1,22 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createRoot } from 'react-dom/client';
import { PlaygroundApp } from './playground-app';
import './style.css';
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: 1, staleTime: Number.POSITIVE_INFINITY },
},
});
const root = document.getElementById('root');
if (!root) {
throw new Error('Missing React root');
}
createRoot(root).render(
<QueryClientProvider client={queryClient}>
<PlaygroundApp />
</QueryClientProvider>,
);

View file

@ -0,0 +1,61 @@
import { markdown } from '@codemirror/lang-markdown';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView, basicSetup } from 'codemirror';
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
import { markdownFileNavigation, playgroundLinkDecorations } from './markdown-navigation';
import type { PlaygroundGuide } from './types';
export type MarkdownEditorHandle = { reset: () => void };
type MarkdownEditorProps = {
guide: PlaygroundGuide;
onOpenTarget: (target: string) => boolean;
onSave: (target: string, source: string) => void;
};
export const MarkdownEditor = forwardRef<MarkdownEditorHandle, MarkdownEditorProps>(function MarkdownEditor(
{ guide, onOpenTarget, onSave },
handle,
) {
const container = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const callbacks = useRef({ onOpenTarget, onSave });
callbacks.current = { onOpenTarget, onSave };
useImperativeHandle(handle, () => ({
reset: () => view.current?.dispatch({
changes: { from: 0, to: view.current.state.doc.length, insert: guide.source },
}),
}), [guide.source]);
useEffect(() => {
if (!container.current) {
return;
}
const editor = new EditorView({
doc: guide.source,
extensions: [
basicSetup,
markdown(),
oneDark,
playgroundLinkDecorations,
markdownFileNavigation(target => callbacks.current.onOpenTarget(target)),
EditorView.lineWrapping,
EditorView.updateListener.of(update => {
if (update.docChanged) {
callbacks.current.onSave(guide.target, update.state.doc.toString());
}
}),
],
parent: container.current,
});
view.current = editor;
return () => {
editor.destroy();
view.current = null;
};
}, [guide]);
return <div className="markdown-editor" ref={container} />;
});

View file

@ -1,6 +1,6 @@
import { persistFile } from './api';
export const createFileSaver = (onError: (target: string) => void) => {
export const createFileSaver = (
persist: (target: string, source: string) => Promise<unknown>,
) => {
const timers = new Map<string, number>();
return (target: string, source: string) => {
@ -8,13 +8,9 @@ export const createFileSaver = (onError: (target: string) => void) => {
if (pendingTimer !== undefined) {
window.clearTimeout(pendingTimer);
}
timers.set(target, window.setTimeout(async () => {
timers.set(target, window.setTimeout(() => {
timers.delete(target);
try {
await persistFile(target, source);
} catch {
onError(target);
}
void persist(target, source).catch(() => undefined);
}, 350));
};
};

View file

@ -1,262 +0,0 @@
import { markdown } from '@codemirror/lang-markdown';
import { rust } from '@codemirror/lang-rust';
import { languageServerExtensions, LSPClient } from '@codemirror/lsp-client';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView, basicSetup } from 'codemirror';
import { loadInfo, runCode } from './api';
import { elements } from './dom';
import { ExampleFileTree } from './file-tree';
import { commandClickDefinition, connectTransport, PlaygroundWorkspace } from './lsp';
import { markdownFileNavigation, playgroundLinkDecorations } from './markdown-navigation';
import { createFileSaver } from './persistence';
import type { PlaygroundExample, PlaygroundInfo } from './types';
class PlaygroundApp {
private activeExampleId = '';
private activeUri = '';
private readonly containers = new Map<string, HTMLDivElement>();
private readonly exampleButtons = new Map<string, HTMLButtonElement>();
private readonly views = new Map<string, EditorView>();
private info!: PlaygroundInfo;
private markdownView!: EditorView;
private readonly saveFile = createFileSaver(target => {
elements.runStatus.textContent = `Save failed: ${target}`;
elements.runStatus.dataset.state = 'error';
});
private readonly fileTree = new ExampleFileTree(
elements.fileNav,
elements.fileTreeTitle,
uri => { this.showFile(uri); },
);
public async start() {
this.info = await loadInfo();
const initialExample = this.info.examples[0];
if (!initialExample) {
throw new Error('No runnable examples found');
}
this.activeExampleId = initialExample.id;
this.renderExampleNavigation();
const client = await this.connectLsp();
this.createCodeEditors(client);
this.createMarkdownEditor();
this.finishSetup();
}
private get allFiles() {
return this.info.examples.flatMap(example => example.files.map(file => ({ example, file })));
}
private get fileByUri() {
return new Map(this.allFiles.map(entry => [entry.file.uri, entry]));
}
private renderExampleNavigation() {
this.info.examples.forEach(example => {
const button = document.createElement('button');
button.className = 'example-item';
button.dataset.active = String(example.id === this.activeExampleId);
button.type = 'button';
button.textContent = example.title;
button.addEventListener('click', () => this.selectExample(example.id));
elements.exampleNav.append(button);
this.exampleButtons.set(example.id, button);
});
}
private async connectLsp() {
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const transport = await connectTransport(`${protocol}//${location.host}/lsp`, () => {
elements.lspStatus.textContent = 'rust-analyzer disconnected';
elements.lspStatus.dataset.state = 'error';
});
const client = new LSPClient({
rootUri: this.info.rootUri,
timeout: 15_000,
workspace: lspClient => new PlaygroundWorkspace(lspClient, uri => this.showFile(uri)),
extensions: languageServerExtensions(),
notificationHandlers: {
'textDocument/publishDiagnostics': (_client, params) => {
const diagnostics = Array.isArray(params?.diagnostics) ? params.diagnostics : [];
const filename = String(params?.uri ?? '').split('/').at(-1) ?? 'file';
elements.diagnosticStatus.textContent = `${diagnostics.length} diagnostic${diagnostics.length === 1 ? '' : 's'} in ${filename}`;
elements.diagnosticStatus.dataset.state = diagnostics.length === 0 ? 'ready' : 'warning';
return false;
},
},
}).connect(transport);
await client.initializing;
return client;
}
private createCodeEditors(client: LSPClient) {
this.allFiles.forEach(({ file }) => {
const container = document.createElement('div');
container.className = 'editor-container';
container.hidden = true;
elements.editorsParent.append(container);
this.containers.set(file.uri, container);
const languageExtensions = file.languageId === 'rust'
? [rust(), client.plugin(file.uri, 'rust'), commandClickDefinition]
: [];
const view = new EditorView({
doc: file.source,
extensions: [
basicSetup,
oneDark,
languageExtensions,
EditorView.lineWrapping,
EditorView.updateListener.of(update => {
if (update.docChanged) {
this.saveFile(file.target, update.state.doc.toString());
}
}),
],
parent: container,
});
this.views.set(file.uri, view);
});
}
private createMarkdownEditor() {
this.markdownView = new EditorView({
doc: this.info.guide.source,
extensions: [
basicSetup,
markdown(),
oneDark,
playgroundLinkDecorations,
markdownFileNavigation(target => this.openFileTarget(target)),
EditorView.lineWrapping,
EditorView.updateListener.of(update => {
if (update.docChanged) {
this.saveFile(this.info.guide.target, update.state.doc.toString());
}
}),
],
parent: elements.markdownEditorParent,
});
}
private selectExample(exampleId: string, selectDefaultFile = true) {
const example = this.info.examples.find(candidate => candidate.id === exampleId);
if (!example) {
return false;
}
this.activeExampleId = example.id;
this.exampleButtons.forEach((button, candidate) => {
button.dataset.active = String(candidate === example.id);
});
const current = this.fileByUri.get(this.activeUri);
const currentPath = current?.example.id === example.id ? current.file.path : undefined;
this.fileTree.render(example, currentPath);
if (selectDefaultFile) {
const file = currentPath
? current?.file
: example.files.find(candidate => candidate.path === 'src/main.rs');
if (file) {
this.showFile(file.uri);
}
}
return true;
}
private showFile(uri: string) {
const entry = this.fileByUri.get(uri);
const view = this.views.get(uri);
if (!entry || !view) {
return null;
}
if (entry.example.id !== this.activeExampleId) {
this.selectExample(entry.example.id, false);
}
this.activeUri = uri;
this.containers.forEach((container, candidate) => {
container.hidden = candidate !== uri;
});
this.fileTree.select(entry.file.path);
elements.activePath.textContent = `${entry.example.id}://${entry.file.path}`;
view.focus();
return view;
}
private openFileTarget(target: string) {
const match = /^([a-z][a-z0-9+.-]*):\/\/(.+?)(?:#L(\d+))?$/i.exec(target);
const example = match ? this.info.examples.find(candidate => candidate.id === match[1]) : undefined;
const file = example?.files.find(candidate => candidate.path === match?.[2]);
const view = file ? this.showFile(file.uri) : null;
if (!view) {
return false;
}
const requestedLine = Number(match?.[3] ?? 1);
const line = view.state.doc.line(Math.min(Math.max(requestedLine, 1), view.state.doc.lines));
view.dispatch({
selection: { anchor: line.from },
effects: EditorView.scrollIntoView(line.from, { y: 'center' }),
});
return true;
}
private finishSetup() {
elements.guidePath.textContent = this.info.guide.path;
this.selectExample(this.activeExampleId);
elements.lspStatus.textContent = 'rust-analyzer connected';
elements.lspStatus.dataset.state = 'ready';
if (elements.diagnosticStatus.textContent === 'Diagnostics pending') {
const rustFileCount = this.allFiles.filter(entry => entry.file.languageId === 'rust').length;
elements.diagnosticStatus.textContent = `${rustFileCount} Rust files open in LSP`;
elements.diagnosticStatus.dataset.state = 'ready';
}
elements.revision.textContent = this.info.revision.slice(0, 8);
elements.runButton.addEventListener('click', () => { void this.runActiveExample(); });
elements.resetButton.addEventListener('click', () => this.reset());
}
private async runActiveExample() {
const example = this.activeExample;
if (!example) {
return;
}
elements.runButton.disabled = true;
elements.runStatus.textContent = `Running ${example.title}`;
elements.output.textContent = '';
try {
const files = Object.fromEntries(
example.files.map(file => [file.path, this.views.get(file.uri)?.state.doc.toString() ?? file.source]),
);
const result = await runCode(example.id, files);
elements.output.textContent = result.output;
elements.runStatus.textContent = result.success ? 'Finished' : 'Failed';
elements.runStatus.dataset.state = result.success ? 'ready' : 'error';
} catch (error) {
elements.runStatus.textContent = error instanceof Error ? error.message : 'Run failed';
elements.runStatus.dataset.state = 'error';
} finally {
elements.runButton.disabled = false;
}
}
private get activeExample(): PlaygroundExample | undefined {
return this.info.examples.find(candidate => candidate.id === this.activeExampleId);
}
private reset() {
this.activeExample?.files.forEach(file => {
const view = this.views.get(file.uri);
view?.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: file.source } });
});
this.markdownView.dispatch({
changes: { from: 0, to: this.markdownView.state.doc.length, insert: this.info.guide.source },
});
}
}
export const startPlayground = () => {
new PlaygroundApp().start().catch(error => {
elements.lspStatus.textContent = error instanceof Error ? error.message : 'Unable to start';
elements.lspStatus.dataset.state = 'error';
});
};

View file

@ -0,0 +1,229 @@
import { useMutation, useQuery } from '@tanstack/react-query';
import { useCallback, useMemo, useRef, useState } from 'react';
import { loadInfo, persistFile, runCode } from './api';
import { CodeEditors, type CodeEditorsHandle } from './code-editors';
import { FileTreePanel } from './file-tree-panel';
import { MarkdownEditor, type MarkdownEditorHandle } from './markdown-editor';
import { createFileSaver } from './persistence';
import type { PlaygroundExample, PlaygroundInfo } from './types';
type ConnectionState = 'connecting' | 'ready' | 'error';
const LoadingScreen = () => (
<main className="load-screen" aria-busy="true" aria-live="polite">
<div className="spinner" />
<p className="eyebrow">LOADING WORKSPACE</p>
<h1>Reading examples and starting the editor</h1>
</main>
);
const ErrorScreen = ({ message, retry }: { message: string; retry: () => void }) => (
<main className="load-screen" role="alert">
<p className="eyebrow">WORKSPACE ERROR</p>
<h1>{message}</h1>
<button className="button primary" type="button" onClick={retry}>Try again</button>
</main>
);
const initialFile = (example: PlaygroundExample) =>
example.files.find(file => file.path === 'src/main.rs') ?? example.files[0];
const Playground = ({ info }: { info: PlaygroundInfo }) => {
const firstExample = info.examples[0];
const [activeExampleId, setActiveExampleId] = useState(firstExample?.id ?? '');
const [activeUri, setActiveUri] = useState(firstExample ? initialFile(firstExample)?.uri ?? '' : '');
const [connection, setConnection] = useState<ConnectionState>('connecting');
const [connectionError, setConnectionError] = useState('');
const [diagnostics, setDiagnostics] = useState('Diagnostics pending');
const [diagnosticState, setDiagnosticState] = useState<'ready' | 'warning'>('ready');
const [saveError, setSaveError] = useState('');
const codeEditors = useRef<CodeEditorsHandle>(null);
const markdownEditor = useRef<MarkdownEditorHandle>(null);
const saveMutation = useMutation({
mutationFn: ({ target, source }: { target: string; source: string }) => persistFile(target, source),
onError: (_error, variables) => setSaveError(`Save failed: ${variables.target}`),
onSuccess: () => setSaveError(''),
});
const saveFile = useMemo(
() => createFileSaver((target, source) => saveMutation.mutateAsync({ target, source })),
[saveMutation.mutateAsync],
);
const activeExample = info.examples.find(example => example.id === activeExampleId);
const activeFile = activeExample?.files.find(file => file.uri === activeUri);
const openFile = useCallback((uri: string) => {
const entry = info.examples
.flatMap(example => example.files.map(file => ({ example, file })))
.find(candidate => candidate.file.uri === uri);
if (!entry) {
return false;
}
setActiveExampleId(entry.example.id);
setActiveUri(uri);
return true;
}, [info.examples]);
const openFileTarget = useCallback((target: string) => {
const match = /^([a-z][a-z0-9+.-]*):\/\/(.+?)(?:#L(\d+))?$/i.exec(target);
const example = match ? info.examples.find(candidate => candidate.id === match[1]) : undefined;
const file = example?.files.find(candidate => candidate.path === match?.[2]);
if (!file || !openFile(file.uri)) {
return false;
}
codeEditors.current?.goToLine(file.uri, Number(match?.[3] ?? 1));
return true;
}, [info.examples, openFile]);
const selectExample = (example: PlaygroundExample) => {
const file = initialFile(example);
setActiveExampleId(example.id);
if (file) {
setActiveUri(file.uri);
}
};
const runMutation = useMutation({
mutationFn: async () => {
if (!activeExample) {
throw new Error('No runnable example selected');
}
return runCode(activeExample.id, codeEditors.current?.getFiles(activeExample) ?? {});
},
});
const reset = () => {
if (activeExample) {
codeEditors.current?.reset(activeExample);
}
markdownEditor.current?.reset();
};
if (!firstExample) {
return <ErrorScreen message="No runnable examples found" retry={() => window.location.reload()} />;
}
const output = runMutation.data?.output
|| (runMutation.error instanceof Error ? runMutation.error.message : '')
|| 'Press Run to compile against the cloned LiteLLM repository.';
const runStatus = runMutation.isPending
? `Running ${activeExample?.title ?? 'example'}`
: runMutation.data ? (runMutation.data.success ? 'Finished' : 'Failed') : '';
const rustFileCount = info.examples.flatMap(example => example.files).filter(file => file.languageId === 'rust').length;
return (
<main className="shell">
<header className="topbar">
<div>
<span className="eyebrow">PERSISTENT PLAYGROUND</span>
<h1>LiteLLM Rust Playground</h1>
</div>
<div className="status-row">
<span className="status" data-state={connection === 'connecting' ? 'loading' : connection}>
{connection === 'ready' ? 'rust-analyzer connected' : connectionError || 'Connecting to rust-analyzer'}
</span>
<span className="status" data-state={diagnosticState}>{diagnostics}</span>
{(saveMutation.isPending || saveError) && (
<span className="status" data-state={saveError ? 'error' : 'loading'}>
{saveError || 'Saving'}
</span>
)}
<button className="button secondary" type="button" onClick={reset}>Reset</button>
<button
className="button primary"
type="button"
disabled={runMutation.isPending || connection !== 'ready'}
onClick={() => runMutation.mutate()}
>
{runMutation.isPending ? <><span className="button-spinner" />Running</> : 'Run'}
</button>
</div>
</header>
<section className="workspace" aria-busy={connection === 'connecting'}>
<aside className="docs" aria-label="Markdown document">
<div className="docbar">
<span>{info.guide.path}</span>
<span className="document-language">Markdown</span>
</div>
<MarkdownEditor ref={markdownEditor} guide={info.guide} onOpenTarget={openFileTarget} onSave={saveFile} />
</aside>
<section className="editor-panel" aria-label="Rust editor">
<div className="filebar">
<span>{activeExample && activeFile ? `${activeExample.id}://${activeFile.path}` : 'Select a file'}</span>
<span className="revision">{info.revision.slice(0, 8)}</span>
</div>
<div className="editor-body">
<div className="editor-stack">
<CodeEditors
ref={codeEditors}
info={info}
activeUri={activeUri}
onOpenFile={openFile}
onSave={saveFile}
onConnectionChange={(state, message) => {
setConnection(state);
setConnectionError(message ?? '');
if (state === 'ready' && diagnostics === 'Diagnostics pending') {
setDiagnostics(`${rustFileCount} Rust files open in LSP`);
}
}}
onDiagnostics={(message, hasDiagnostics) => {
setDiagnostics(message);
setDiagnosticState(hasDiagnostics ? 'warning' : 'ready');
}}
/>
{connection === 'connecting' && (
<div className="editor-loading" role="status">
<div className="spinner" />
<span>Starting rust-analyzer</span>
</div>
)}
</div>
<aside className="file-tree" aria-label="Project files">
<p className="tree-title">EXAMPLES</p>
<nav className="example-nav" aria-label="Examples">
{info.examples.map(example => (
<button
key={example.id}
className="example-item"
data-active={example.id === activeExampleId}
type="button"
onClick={() => selectExample(example)}
>
{example.title}
</button>
))}
</nav>
{activeExample && <FileTreePanel example={activeExample} activePath={activeFile?.path} onOpenFile={openFile} />}
</aside>
</div>
</section>
<section className="output-panel" aria-live="polite">
<div className="output-header">
<span>OUTPUT</span>
<span data-state={runMutation.data?.success === false || runMutation.isError ? 'error' : 'ready'}>{runStatus}</span>
</div>
<pre>{output || 'Program finished without output'}</pre>
</section>
</section>
</main>
);
};
export const PlaygroundApp = () => {
const infoQuery = useQuery({ queryKey: ['playground-info'], queryFn: loadInfo });
if (infoQuery.isPending) {
return <LoadingScreen />;
}
if (infoQuery.isError) {
const message = infoQuery.error instanceof Error ? infoQuery.error.message : 'Unable to load workspace';
return <ErrorScreen message={message} retry={() => { void infoQuery.refetch(); }} />;
}
return <Playground info={infoQuery.data} />;
};

View file

@ -18,6 +18,10 @@ body {
#0b0d10;
}
#root {
min-height: 100vh;
}
button {
font: inherit;
}
@ -90,6 +94,11 @@ h1 {
content: '';
}
[data-state='loading']::before {
background: #d06a3a;
animation: pulse 1s ease-in-out infinite;
}
[data-state='ready']::before {
background: #6abf8f;
}
@ -118,6 +127,18 @@ h1 {
opacity: 0.6;
}
.button-spinner {
display: inline-block;
width: 0.8rem;
height: 0.8rem;
margin-right: 0.45rem;
border: 2px solid rgba(255, 255, 255, 0.35);
border-top-color: #fff;
border-radius: 50%;
vertical-align: -0.1rem;
animation: spin 0.75s linear infinite;
}
.primary {
background: #bd5b2f;
}
@ -202,8 +223,8 @@ h1 {
color: #686f7a;
}
#editors,
#markdown-editor,
.editors,
.markdown-editor,
.editor-container,
.cm-editor {
height: 100%;
@ -211,6 +232,67 @@ h1 {
min-height: 0;
}
.editor-stack {
position: relative;
min-width: 0;
min-height: 0;
}
.editor-loading {
position: absolute;
inset: 0;
z-index: 2;
display: flex;
align-items: center;
justify-content: center;
gap: 0.75rem;
color: #aab0ba;
background: rgba(11, 13, 16, 0.92);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.82rem;
}
.load-screen {
display: flex;
min-height: 100vh;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 0.9rem;
padding: 2rem;
text-align: center;
}
.load-screen h1,
.load-screen p {
margin: 0;
}
.spinner {
width: 1.4rem;
height: 1.4rem;
border: 2px solid #343a44;
border-top-color: #d06a3a;
border-radius: 50%;
animation: spin 0.75s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes pulse {
50% { opacity: 0.35; }
}
@media (prefers-reduced-motion: reduce) {
.spinner,
.button-spinner,
[data-state='loading']::before {
animation: none;
}
}
.file-tree {
display: flex;
flex-direction: column;

View file

@ -1,6 +1,7 @@
{
"compilerOptions": {
"lib": ["DOM", "ES2023"],
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "Bundler",
"noEmit": true,