mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-16 09:22:22 +00:00
refactor(playground): split client modules
This commit is contained in:
parent
b34d31c8e1
commit
d7492bf9ec
9 changed files with 577 additions and 506 deletions
25
playground/src/api.ts
Normal file
25
playground/src/api.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import type { PlaygroundInfo, RunResult, StoredFiles } from './types';
|
||||
|
||||
const jsonRequest = async <T>(input: string, init?: RequestInit): Promise<T> => {
|
||||
const response = await fetch(input, init);
|
||||
if (!response.ok) {
|
||||
throw new Error(`${init?.method ?? 'GET'} ${input} failed: ${response.status}`);
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
};
|
||||
|
||||
export const loadInfo = () => jsonRequest<PlaygroundInfo>('/api/info');
|
||||
|
||||
export const runCode = (exampleId: string, files: StoredFiles) =>
|
||||
jsonRequest<RunResult>('/api/run', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ exampleId, files }),
|
||||
});
|
||||
|
||||
export const persistFile = (target: string, source: string) =>
|
||||
jsonRequest<unknown>('/api/file', {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ target, source }),
|
||||
});
|
||||
24
playground/src/dom.ts
Normal file
24
playground/src/dom.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
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'),
|
||||
};
|
||||
60
playground/src/file-tree.ts
Normal file
60
playground/src/file-tree.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { FileTree } from '@pierre/trees';
|
||||
|
||||
import type { PlaygroundExample } from './types';
|
||||
|
||||
export class ExampleFileTree {
|
||||
private tree: FileTree | null = null;
|
||||
private syncingSelection = false;
|
||||
|
||||
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>();
|
||||
example.files.forEach(file => {
|
||||
const segments = file.path.split('/');
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.add(`${segments.slice(0, index).join('/')}/`);
|
||||
}
|
||||
});
|
||||
|
||||
this.tree = new FileTree({
|
||||
paths: [...directories, ...example.files.map(file => file.path)],
|
||||
initialExpansion: 'open',
|
||||
initialSelectedPaths: selectedPath ? [selectedPath] : [],
|
||||
icons: { set: 'complete', colored: true },
|
||||
density: 'compact',
|
||||
stickyFolders: true,
|
||||
onSelectionChange: selectedPaths => {
|
||||
if (this.syncingSelection) {
|
||||
return;
|
||||
}
|
||||
const selectedFile = example.files.find(file => file.path === selectedPaths.at(-1));
|
||||
if (selectedFile) {
|
||||
this.openFile(selectedFile.uri);
|
||||
}
|
||||
},
|
||||
});
|
||||
this.tree.render({ containerWrapper: this.container });
|
||||
}
|
||||
|
||||
public select(path: string) {
|
||||
this.syncingSelection = true;
|
||||
this.tree?.getSelectedPaths().forEach(selectedPath => {
|
||||
if (selectedPath !== path) {
|
||||
this.tree?.getItem(selectedPath)?.deselect();
|
||||
}
|
||||
});
|
||||
this.tree?.getItem(path)?.select();
|
||||
this.tree?.scrollToPath(path, { focus: false, offset: 'nearest' });
|
||||
this.syncingSelection = false;
|
||||
}
|
||||
}
|
||||
106
playground/src/lsp.ts
Normal file
106
playground/src/lsp.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import {
|
||||
jumpToDefinition,
|
||||
LSPClient,
|
||||
LSPPlugin,
|
||||
Workspace,
|
||||
type Transport,
|
||||
type WorkspaceFile,
|
||||
} from '@codemirror/lsp-client';
|
||||
import { EditorView } from '@codemirror/view';
|
||||
|
||||
class OpenFile implements WorkspaceFile {
|
||||
public version = 0;
|
||||
public doc;
|
||||
|
||||
public constructor(
|
||||
public readonly uri: string,
|
||||
public readonly languageId: string,
|
||||
public readonly view: EditorView,
|
||||
) {
|
||||
this.doc = view.state.doc;
|
||||
}
|
||||
|
||||
public getView() {
|
||||
return this.view;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaygroundWorkspace extends Workspace {
|
||||
public files: OpenFile[] = [];
|
||||
|
||||
public constructor(
|
||||
client: LSPClient,
|
||||
private readonly showFile: (uri: string) => EditorView | null,
|
||||
) {
|
||||
super(client);
|
||||
}
|
||||
|
||||
public syncFiles() {
|
||||
return this.files.flatMap(file => {
|
||||
const plugin = LSPPlugin.get(file.view);
|
||||
if (!plugin || plugin.unsyncedChanges.empty) {
|
||||
return [];
|
||||
}
|
||||
const changes = plugin.unsyncedChanges;
|
||||
const prevDoc = file.doc;
|
||||
file.doc = file.view.state.doc;
|
||||
file.version += 1;
|
||||
plugin.clear();
|
||||
return [{ file, prevDoc, changes }];
|
||||
});
|
||||
}
|
||||
|
||||
public openFile(uri: string, languageId: string, view: EditorView) {
|
||||
const file = new OpenFile(uri, languageId, view);
|
||||
this.files = [...this.files, file];
|
||||
this.client.didOpen(file);
|
||||
}
|
||||
|
||||
public closeFile(uri: string) {
|
||||
this.files = this.files.filter(file => file.uri !== uri);
|
||||
this.client.didClose(uri);
|
||||
}
|
||||
|
||||
public displayFile(uri: string) {
|
||||
return Promise.resolve(this.showFile(uri));
|
||||
}
|
||||
}
|
||||
|
||||
export const commandClickDefinition = EditorView.domEventHandlers({
|
||||
mousedown(event, view) {
|
||||
if ((!event.metaKey && !event.ctrlKey) || event.button !== 0) {
|
||||
return false;
|
||||
}
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
if (position === null) {
|
||||
return false;
|
||||
}
|
||||
view.dispatch({ selection: { anchor: position } });
|
||||
const handled = jumpToDefinition(view);
|
||||
if (handled) {
|
||||
event.preventDefault();
|
||||
}
|
||||
return handled;
|
||||
},
|
||||
});
|
||||
|
||||
export const connectTransport = (
|
||||
url: string,
|
||||
onClose: () => void,
|
||||
): Promise<Transport> => new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(url);
|
||||
const handlers = new Set<(message: string) => void>();
|
||||
|
||||
socket.addEventListener('open', () => {
|
||||
resolve({
|
||||
send: message => socket.send(message),
|
||||
subscribe: handler => handlers.add(handler),
|
||||
unsubscribe: handler => handlers.delete(handler),
|
||||
});
|
||||
});
|
||||
socket.addEventListener('message', event => {
|
||||
handlers.forEach(handler => handler(String(event.data)));
|
||||
});
|
||||
socket.addEventListener('close', onClose);
|
||||
socket.addEventListener('error', () => reject(new Error('WebSocket connection failed')));
|
||||
});
|
||||
|
|
@ -1,508 +1,4 @@
|
|||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { rust } from '@codemirror/lang-rust';
|
||||
import {
|
||||
languageServerExtensions,
|
||||
jumpToDefinition,
|
||||
LSPClient,
|
||||
LSPPlugin,
|
||||
Workspace,
|
||||
type Transport,
|
||||
type WorkspaceFile,
|
||||
} from '@codemirror/lsp-client';
|
||||
import { oneDark } from '@codemirror/theme-one-dark';
|
||||
import { Decoration, MatchDecorator, ViewPlugin } from '@codemirror/view';
|
||||
import { FileTree } from '@pierre/trees';
|
||||
import { EditorView, basicSetup } from 'codemirror';
|
||||
|
||||
import { startPlayground } from './playground-app';
|
||||
import './style.css';
|
||||
|
||||
type PlaygroundFile = {
|
||||
languageId: 'rust' | 'toml';
|
||||
path: string;
|
||||
source: string;
|
||||
target: string;
|
||||
uri: string;
|
||||
};
|
||||
|
||||
type PlaygroundGuide = {
|
||||
path: string;
|
||||
source: string;
|
||||
target: string;
|
||||
};
|
||||
|
||||
type PlaygroundExample = {
|
||||
files: PlaygroundFile[];
|
||||
id: string;
|
||||
title: string;
|
||||
};
|
||||
|
||||
type PlaygroundInfo = {
|
||||
examples: PlaygroundExample[];
|
||||
guide: PlaygroundGuide;
|
||||
rootUri: string;
|
||||
revision: string;
|
||||
};
|
||||
|
||||
type RunResult = {
|
||||
success: boolean;
|
||||
output: string;
|
||||
};
|
||||
|
||||
type StoredFiles = Record<string, string>;
|
||||
|
||||
class OpenFile implements WorkspaceFile {
|
||||
public version = 0;
|
||||
public doc;
|
||||
|
||||
public constructor(
|
||||
public readonly uri: string,
|
||||
public readonly languageId: string,
|
||||
public readonly view: EditorView,
|
||||
) {
|
||||
this.doc = view.state.doc;
|
||||
}
|
||||
|
||||
public getView() {
|
||||
return this.view;
|
||||
}
|
||||
}
|
||||
|
||||
class PlaygroundWorkspace extends Workspace {
|
||||
public files: OpenFile[] = [];
|
||||
|
||||
public constructor(
|
||||
client: LSPClient,
|
||||
private readonly showFile: (uri: string) => EditorView | null,
|
||||
) {
|
||||
super(client);
|
||||
}
|
||||
|
||||
public syncFiles() {
|
||||
return this.files.flatMap(file => {
|
||||
const plugin = LSPPlugin.get(file.view);
|
||||
if (!plugin || plugin.unsyncedChanges.empty) {
|
||||
return [];
|
||||
}
|
||||
const changes = plugin.unsyncedChanges;
|
||||
const prevDoc = file.doc;
|
||||
file.doc = file.view.state.doc;
|
||||
file.version += 1;
|
||||
plugin.clear();
|
||||
return [{ file, prevDoc, changes }];
|
||||
});
|
||||
}
|
||||
|
||||
public openFile(uri: string, languageId: string, view: EditorView) {
|
||||
const file = new OpenFile(uri, languageId, view);
|
||||
this.files = [...this.files, file];
|
||||
this.client.didOpen(file);
|
||||
}
|
||||
|
||||
public closeFile(uri: string) {
|
||||
this.files = this.files.filter(file => file.uri !== uri);
|
||||
this.client.didClose(uri);
|
||||
}
|
||||
|
||||
public displayFile(uri: string) {
|
||||
return Promise.resolve(this.showFile(uri));
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
const lspStatus = requireElement<HTMLSpanElement>('lsp-status');
|
||||
const diagnosticStatus = requireElement<HTMLSpanElement>('diagnostic-status');
|
||||
const revision = requireElement<HTMLSpanElement>('revision');
|
||||
const runButton = requireElement<HTMLButtonElement>('run-button');
|
||||
const resetButton = requireElement<HTMLButtonElement>('reset-button');
|
||||
const runStatus = requireElement<HTMLSpanElement>('run-status');
|
||||
const output = requireElement<HTMLPreElement>('output');
|
||||
const editorsParent = requireElement<HTMLDivElement>('editors');
|
||||
const markdownEditorParent = requireElement<HTMLDivElement>('markdown-editor');
|
||||
const exampleNav = requireElement<HTMLElement>('example-nav');
|
||||
const fileNav = requireElement<HTMLElement>('file-nav');
|
||||
const fileTreeTitle = requireElement<HTMLParagraphElement>('file-tree-title');
|
||||
const activePath = requireElement<HTMLSpanElement>('active-path');
|
||||
const guidePath = requireElement<HTMLSpanElement>('guide-path');
|
||||
|
||||
const commandClickDefinition = EditorView.domEventHandlers({
|
||||
mousedown(event, view) {
|
||||
if ((!event.metaKey && !event.ctrlKey) || event.button !== 0) {
|
||||
return false;
|
||||
}
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
if (position === null) {
|
||||
return false;
|
||||
}
|
||||
view.dispatch({ selection: { anchor: position } });
|
||||
const handled = jumpToDefinition(view);
|
||||
if (handled) {
|
||||
event.preventDefault();
|
||||
}
|
||||
return handled;
|
||||
},
|
||||
});
|
||||
|
||||
const playgroundLinkMatcher = new MatchDecorator({
|
||||
regexp: /\[[^\]\n]+\]\([a-z][a-z0-9+.-]*:\/\/[^)\s]+\)/gi,
|
||||
decoration: Decoration.mark({ class: 'cm-playground-link' }),
|
||||
});
|
||||
|
||||
const playgroundLinkDecorations = ViewPlugin.fromClass(
|
||||
class {
|
||||
public decorations;
|
||||
|
||||
public constructor(view: EditorView) {
|
||||
this.decorations = playgroundLinkMatcher.createDeco(view);
|
||||
}
|
||||
|
||||
public update(update: Parameters<typeof playgroundLinkMatcher.updateDeco>[0]) {
|
||||
this.decorations = playgroundLinkMatcher.updateDeco(update, this.decorations);
|
||||
}
|
||||
},
|
||||
{ decorations: instance => instance.decorations },
|
||||
);
|
||||
|
||||
const markdownFileNavigation = (openTarget: (target: string) => boolean) =>
|
||||
EditorView.domEventHandlers({
|
||||
mousedown(event, view) {
|
||||
if (event.button !== 0) {
|
||||
return false;
|
||||
}
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
if (position === null) {
|
||||
return false;
|
||||
}
|
||||
const line = view.state.doc.lineAt(position);
|
||||
const offset = position - line.from;
|
||||
const matches = line.text.matchAll(/\[([^\]\n]+)\]\(([a-z][a-z0-9+.-]*:\/\/[^)\s]+)\)/gi);
|
||||
for (const match of matches) {
|
||||
const start = match.index;
|
||||
if (offset >= start && offset <= start + match[0].length && openTarget(match[2])) {
|
||||
event.preventDefault();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
const connectTransport = (url: string): Promise<Transport> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(url);
|
||||
const handlers = new Set<(message: string) => void>();
|
||||
|
||||
socket.addEventListener('open', () => {
|
||||
resolve({
|
||||
send(message) {
|
||||
socket.send(message);
|
||||
},
|
||||
subscribe(handler) {
|
||||
handlers.add(handler);
|
||||
},
|
||||
unsubscribe(handler) {
|
||||
handlers.delete(handler);
|
||||
},
|
||||
});
|
||||
});
|
||||
socket.addEventListener('message', event => {
|
||||
handlers.forEach(handler => handler(String(event.data)));
|
||||
});
|
||||
socket.addEventListener('close', () => {
|
||||
lspStatus.textContent = 'rust-analyzer disconnected';
|
||||
lspStatus.dataset.state = 'error';
|
||||
});
|
||||
socket.addEventListener('error', () => reject(new Error('WebSocket connection failed')));
|
||||
});
|
||||
|
||||
const loadInfo = async (): Promise<PlaygroundInfo> => {
|
||||
const response = await fetch('/api/info');
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unable to load playground: ${response.status}`);
|
||||
}
|
||||
return response.json() as Promise<PlaygroundInfo>;
|
||||
};
|
||||
|
||||
const runCode = async (exampleId: string, files: StoredFiles): Promise<RunResult> => {
|
||||
const response = await fetch('/api/run', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ exampleId, files }),
|
||||
});
|
||||
return response.json() as Promise<RunResult>;
|
||||
};
|
||||
|
||||
const saveTimers = new Map<string, number>();
|
||||
|
||||
const saveFile = (target: string, source: string) => {
|
||||
const pendingTimer = saveTimers.get(target);
|
||||
if (pendingTimer !== undefined) {
|
||||
window.clearTimeout(pendingTimer);
|
||||
}
|
||||
saveTimers.set(target, window.setTimeout(async () => {
|
||||
saveTimers.delete(target);
|
||||
try {
|
||||
const response = await fetch('/api/file', {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ target, source }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unable to save ${target}`);
|
||||
}
|
||||
} catch {
|
||||
runStatus.textContent = `Save failed: ${target}`;
|
||||
runStatus.dataset.state = 'error';
|
||||
}
|
||||
}, 350));
|
||||
};
|
||||
|
||||
const main = async () => {
|
||||
const info = await loadInfo();
|
||||
const initialExample = info.examples[0];
|
||||
if (!initialExample) {
|
||||
throw new Error('No runnable examples found');
|
||||
}
|
||||
|
||||
const allFiles = info.examples.flatMap(example => example.files.map(file => ({ example, file })));
|
||||
const fileByUri = new Map(allFiles.map(entry => [entry.file.uri, entry]));
|
||||
const views = new Map<string, EditorView>();
|
||||
const containers = new Map<string, HTMLDivElement>();
|
||||
const exampleButtons = new Map<string, HTMLButtonElement>();
|
||||
let fileTree: FileTree | null = null;
|
||||
let syncingTreeSelection = false;
|
||||
let activeExampleId = initialExample.id;
|
||||
let activeUri = '';
|
||||
|
||||
const renderFileTree = (example: PlaygroundExample) => {
|
||||
fileTree?.cleanUp();
|
||||
fileNav.replaceChildren();
|
||||
fileTreeTitle.textContent = `FILES · ${example.id}://`;
|
||||
fileNav.setAttribute('aria-label', `${example.title} files`);
|
||||
|
||||
const directories = new Set<string>();
|
||||
example.files.forEach(file => {
|
||||
const segments = file.path.split('/');
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.add(`${segments.slice(0, index).join('/')}/`);
|
||||
}
|
||||
});
|
||||
|
||||
const activeFile = fileByUri.get(activeUri);
|
||||
const activePathInExample = activeFile?.example.id === example.id ? activeFile.file.path : undefined;
|
||||
fileTree = new FileTree({
|
||||
paths: [...directories, ...example.files.map(file => file.path)],
|
||||
initialExpansion: 'open',
|
||||
initialSelectedPaths: activePathInExample ? [activePathInExample] : [],
|
||||
icons: { set: 'complete', colored: true },
|
||||
density: 'compact',
|
||||
stickyFolders: true,
|
||||
onSelectionChange(selectedPaths) {
|
||||
if (syncingTreeSelection) {
|
||||
return;
|
||||
}
|
||||
const selectedPath = selectedPaths.at(-1);
|
||||
const selectedFile = example.files.find(file => file.path === selectedPath);
|
||||
if (selectedFile) {
|
||||
showFile(selectedFile.uri);
|
||||
}
|
||||
},
|
||||
});
|
||||
fileTree.render({ containerWrapper: fileNav });
|
||||
};
|
||||
|
||||
const selectExample = (exampleId: string, selectDefaultFile = true) => {
|
||||
const example = info.examples.find(candidate => candidate.id === exampleId);
|
||||
if (!example) {
|
||||
return false;
|
||||
}
|
||||
activeExampleId = example.id;
|
||||
exampleButtons.forEach((button, candidate) => {
|
||||
button.dataset.active = String(candidate === example.id);
|
||||
});
|
||||
renderFileTree(example);
|
||||
if (selectDefaultFile) {
|
||||
const current = fileByUri.get(activeUri);
|
||||
const file = current?.example.id === example.id ? current.file : example.files.find(candidate => candidate.path === 'src/main.rs');
|
||||
if (file) {
|
||||
showFile(file.uri);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
function showFile(uri: string) {
|
||||
const entry = fileByUri.get(uri);
|
||||
const view = views.get(uri);
|
||||
if (!entry || !view) {
|
||||
return null;
|
||||
}
|
||||
if (entry.example.id !== activeExampleId) {
|
||||
selectExample(entry.example.id, false);
|
||||
}
|
||||
activeUri = uri;
|
||||
containers.forEach((container, candidate) => {
|
||||
container.hidden = candidate !== uri;
|
||||
});
|
||||
syncingTreeSelection = true;
|
||||
fileTree?.getSelectedPaths().forEach(path => {
|
||||
if (path !== entry.file.path) {
|
||||
fileTree?.getItem(path)?.deselect();
|
||||
}
|
||||
});
|
||||
fileTree?.getItem(entry.file.path)?.select();
|
||||
fileTree?.scrollToPath(entry.file.path, { focus: false, offset: 'nearest' });
|
||||
syncingTreeSelection = false;
|
||||
activePath.textContent = `${entry.example.id}://${entry.file.path}`;
|
||||
view.focus();
|
||||
return view;
|
||||
}
|
||||
|
||||
const openFileTarget = (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]);
|
||||
const view = file ? 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;
|
||||
};
|
||||
|
||||
info.examples.forEach(example => {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'example-item';
|
||||
button.dataset.active = String(example.id === activeExampleId);
|
||||
button.type = 'button';
|
||||
button.textContent = example.title;
|
||||
button.addEventListener('click', () => selectExample(example.id));
|
||||
exampleNav.append(button);
|
||||
exampleButtons.set(example.id, button);
|
||||
});
|
||||
|
||||
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const transport = await connectTransport(`${protocol}//${location.host}/lsp`);
|
||||
const client = new LSPClient({
|
||||
rootUri: info.rootUri,
|
||||
timeout: 15_000,
|
||||
workspace: lspClient => new PlaygroundWorkspace(lspClient, showFile),
|
||||
extensions: languageServerExtensions(),
|
||||
notificationHandlers: {
|
||||
'textDocument/publishDiagnostics': (_client, params) => {
|
||||
const diagnostics = Array.isArray(params?.diagnostics) ? params.diagnostics : [];
|
||||
const filename = String(params?.uri ?? '').split('/').at(-1) ?? 'file';
|
||||
diagnosticStatus.textContent = `${diagnostics.length} diagnostic${diagnostics.length === 1 ? '' : 's'} in ${filename}`;
|
||||
diagnosticStatus.dataset.state = diagnostics.length === 0 ? 'ready' : 'warning';
|
||||
return false;
|
||||
},
|
||||
},
|
||||
}).connect(transport);
|
||||
|
||||
await client.initializing;
|
||||
|
||||
allFiles.forEach(({ file }) => {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'editor-container';
|
||||
container.hidden = true;
|
||||
editorsParent.append(container);
|
||||
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) {
|
||||
saveFile(file.target, update.state.doc.toString());
|
||||
}
|
||||
}),
|
||||
],
|
||||
parent: container,
|
||||
});
|
||||
views.set(file.uri, view);
|
||||
});
|
||||
|
||||
const markdownView = new EditorView({
|
||||
doc: info.guide.source,
|
||||
extensions: [
|
||||
basicSetup,
|
||||
markdown(),
|
||||
oneDark,
|
||||
playgroundLinkDecorations,
|
||||
markdownFileNavigation(openFileTarget),
|
||||
EditorView.lineWrapping,
|
||||
EditorView.updateListener.of(update => {
|
||||
if (update.docChanged) {
|
||||
saveFile(info.guide.target, update.state.doc.toString());
|
||||
}
|
||||
}),
|
||||
],
|
||||
parent: markdownEditorParent,
|
||||
});
|
||||
|
||||
guidePath.textContent = info.guide.path;
|
||||
selectExample(activeExampleId);
|
||||
lspStatus.textContent = 'rust-analyzer connected';
|
||||
lspStatus.dataset.state = 'ready';
|
||||
if (diagnosticStatus.textContent === 'Diagnostics pending') {
|
||||
const rustFileCount = allFiles.filter(entry => entry.file.languageId === 'rust').length;
|
||||
diagnosticStatus.textContent = `${rustFileCount} Rust files open in LSP`;
|
||||
diagnosticStatus.dataset.state = 'ready';
|
||||
}
|
||||
revision.textContent = info.revision.slice(0, 8);
|
||||
|
||||
runButton.addEventListener('click', async () => {
|
||||
const example = info.examples.find(candidate => candidate.id === activeExampleId);
|
||||
if (!example) {
|
||||
return;
|
||||
}
|
||||
runButton.disabled = true;
|
||||
runStatus.textContent = `Running ${example.title}`;
|
||||
output.textContent = '';
|
||||
const files = Object.fromEntries(
|
||||
example.files.map(file => [file.path, views.get(file.uri)?.state.doc.toString() ?? file.source]),
|
||||
);
|
||||
const result = await runCode(example.id, files);
|
||||
output.textContent = result.output;
|
||||
runStatus.textContent = result.success ? 'Finished' : 'Failed';
|
||||
runStatus.dataset.state = result.success ? 'ready' : 'error';
|
||||
runButton.disabled = false;
|
||||
});
|
||||
|
||||
resetButton.addEventListener('click', () => {
|
||||
const example = info.examples.find(candidate => candidate.id === activeExampleId);
|
||||
if (!example) {
|
||||
return;
|
||||
}
|
||||
example.files.forEach(file => {
|
||||
const view = views.get(file.uri);
|
||||
view?.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: file.source } });
|
||||
});
|
||||
markdownView.dispatch({
|
||||
changes: { from: 0, to: markdownView.state.doc.length, insert: info.guide.source },
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
main().catch(error => {
|
||||
lspStatus.textContent = error instanceof Error ? error.message : 'Unable to start';
|
||||
lspStatus.dataset.state = 'error';
|
||||
});
|
||||
startPlayground();
|
||||
|
|
|
|||
45
playground/src/markdown-navigation.ts
Normal file
45
playground/src/markdown-navigation.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { Decoration, EditorView, MatchDecorator, ViewPlugin } from '@codemirror/view';
|
||||
|
||||
const linkMatcher = new MatchDecorator({
|
||||
regexp: /\[[^\]\n]+\]\([a-z][a-z0-9+.-]*:\/\/[^)\s]+\)/gi,
|
||||
decoration: Decoration.mark({ class: 'cm-playground-link' }),
|
||||
});
|
||||
|
||||
export const playgroundLinkDecorations = ViewPlugin.fromClass(
|
||||
class {
|
||||
public decorations;
|
||||
|
||||
public constructor(view: EditorView) {
|
||||
this.decorations = linkMatcher.createDeco(view);
|
||||
}
|
||||
|
||||
public update(update: Parameters<typeof linkMatcher.updateDeco>[0]) {
|
||||
this.decorations = linkMatcher.updateDeco(update, this.decorations);
|
||||
}
|
||||
},
|
||||
{ decorations: instance => instance.decorations },
|
||||
);
|
||||
|
||||
export const markdownFileNavigation = (openTarget: (target: string) => boolean) =>
|
||||
EditorView.domEventHandlers({
|
||||
mousedown(event, view) {
|
||||
if (event.button !== 0) {
|
||||
return false;
|
||||
}
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
if (position === null) {
|
||||
return false;
|
||||
}
|
||||
const line = view.state.doc.lineAt(position);
|
||||
const offset = position - line.from;
|
||||
const matches = line.text.matchAll(/\[([^\]\n]+)\]\(([a-z][a-z0-9+.-]*:\/\/[^)\s]+)\)/gi);
|
||||
for (const match of matches) {
|
||||
const start = match.index;
|
||||
if (offset >= start && offset <= start + match[0].length && openTarget(match[2])) {
|
||||
event.preventDefault();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
20
playground/src/persistence.ts
Normal file
20
playground/src/persistence.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { persistFile } from './api';
|
||||
|
||||
export const createFileSaver = (onError: (target: string) => void) => {
|
||||
const timers = new Map<string, number>();
|
||||
|
||||
return (target: string, source: string) => {
|
||||
const pendingTimer = timers.get(target);
|
||||
if (pendingTimer !== undefined) {
|
||||
window.clearTimeout(pendingTimer);
|
||||
}
|
||||
timers.set(target, window.setTimeout(async () => {
|
||||
timers.delete(target);
|
||||
try {
|
||||
await persistFile(target, source);
|
||||
} catch {
|
||||
onError(target);
|
||||
}
|
||||
}, 350));
|
||||
};
|
||||
};
|
||||
262
playground/src/playground-app.ts
Normal file
262
playground/src/playground-app.ts
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
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';
|
||||
});
|
||||
};
|
||||
33
playground/src/types.ts
Normal file
33
playground/src/types.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
export type PlaygroundFile = {
|
||||
languageId: 'rust' | 'toml';
|
||||
path: string;
|
||||
source: string;
|
||||
target: string;
|
||||
uri: string;
|
||||
};
|
||||
|
||||
export type PlaygroundGuide = {
|
||||
path: string;
|
||||
source: string;
|
||||
target: string;
|
||||
};
|
||||
|
||||
export type PlaygroundExample = {
|
||||
files: PlaygroundFile[];
|
||||
id: string;
|
||||
title: string;
|
||||
};
|
||||
|
||||
export type PlaygroundInfo = {
|
||||
examples: PlaygroundExample[];
|
||||
guide: PlaygroundGuide;
|
||||
rootUri: string;
|
||||
revision: string;
|
||||
};
|
||||
|
||||
export type RunResult = {
|
||||
success: boolean;
|
||||
output: string;
|
||||
};
|
||||
|
||||
export type StoredFiles = Record<string, string>;
|
||||
Loading…
Add table
Reference in a new issue