feat(workspace): add text editing and image previews

This commit is contained in:
2026-10-15 23:10:13 +08:00
parent d380e18db0
commit a8ba3d74dc
19 changed files with 1188 additions and 7 deletions
+169
View File
@@ -0,0 +1,169 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
const state = vi.hoisted(() => ({slots: [] as any[], cursor: 0, effects: [] as (() => void)[]}));
vi.mock('react', async importOriginal => ({
...await importOriginal<typeof import('react')>(),
useState(value: unknown) {
const i = state.cursor++;
if (!(i in state.slots)) state.slots[i] = value;
return [state.slots[i], (next: unknown) => { state.slots[i] = next; }];
},
useRef(value: unknown) { const i = state.cursor++; return state.slots[i] ??= {current: value}; },
useEffect(effect: () => void | (() => void), deps: unknown[]) {
const i = state.cursor++;
const previous = state.slots[i];
if (!previous || deps.some((value, index) => !Object.is(value, previous.deps[index]))) {
state.effects.push(() => {
previous?.cleanup?.();
state.slots[i] = {deps, cleanup: effect()};
});
}
},
}));
vi.mock('./api', async importOriginal => ({
...await importOriginal<typeof import('./api')>(),
api: {readText: vi.fn(), saveText: vi.fn()},
}));
import { FileEditor } from './FileEditor';
import { api, ApiError } from './api';
import { Button } from './components/ui/button';
import { DialogRoot } from './components/ui/dialog';
import { maxTextBytes } from './fileEditor';
const props = {path: 'nested/config.yaml', instanceId: 'instance-two', onClose: vi.fn(), onSaved: vi.fn()};
function render() {
state.cursor = 0;
const tree = FileEditor(props);
state.effects.splice(0).forEach(effect => effect());
return tree;
}
function nodes(root: any, predicate: (node: any) => boolean): any[] {
if (Array.isArray(root)) return root.flatMap(child => nodes(child, predicate));
if (!root || typeof root !== 'object') return [];
return [...(predicate(root) ? [root] : []), ...nodes(root.props?.children, predicate)];
}
const button = (text: string) => nodes(render(), n => n.type === Button && n.props.children === text)[0];
const editor = () => nodes(render(), n => n.props?.label === '文件内容 · ' + props.path)[0];
const flush = () => new Promise(resolve => setTimeout(resolve, 0));
async function load() { render(); await flush(); return render(); }
function unmount() { state.slots.forEach(slot => slot?.cleanup?.()); state.slots = []; }
beforeEach(() => {
state.slots = []; state.cursor = 0; state.effects = [];
vi.resetAllMocks();
vi.stubGlobal('window', {confirm: vi.fn(() => true), addEventListener: vi.fn(), removeEventListener: vi.fn()});
vi.mocked(api.readText).mockResolvedValue({content: 'name: original', version: 'version-one'});
vi.mocked(api.saveText).mockResolvedValue({version: 'version-two'});
});
afterEach(() => { unmount(); vi.unstubAllGlobals(); });
it('loads the selected path and instance, then exposes its content and language', async () => {
expect(JSON.stringify(render())).toContain('正在读取文件');
expect(button('保存').props.disabled).toBe(true);
await flush();
expect(api.readText).toHaveBeenCalledExactlyOnceWith(props.path, props.instanceId);
expect(editor().props).toMatchObject({value: 'name: original', language: 'yaml', readOnly: false});
expect(button('保存').props.disabled).toBe(true);
});
it('saves against the loaded version, path and instance and uses the returned version next time', async () => {
await load();
editor().props.onChange('name: edited');
button('保存').props.onClick();
await flush();
expect(api.saveText).toHaveBeenCalledExactlyOnceWith(props.path, props.instanceId, 'name: edited', 'version-one');
expect(props.onSaved).toHaveBeenCalledOnce();
expect(JSON.stringify(render())).toContain('已保存');
expect(button('保存').props.disabled).toBe(true);
editor().props.onChange('name: edited again');
button('保存').props.onClick();
await flush();
expect(api.saveText).toHaveBeenLastCalledWith(props.path, props.instanceId, 'name: edited again', 'version-two');
});
it('preserves the draft and version after a conflict', async () => {
await load();
vi.mocked(api.saveText).mockRejectedValueOnce(new ApiError(409, 'conflict'));
editor().props.onChange('precious draft');
button('保存').props.onClick();
await flush();
expect(editor().props.value).toBe('precious draft');
expect(JSON.stringify(render())).toContain('当前修改已保留');
expect(props.onSaved).not.toHaveBeenCalled();
expect(button('保存').props.disabled).toBe(false);
button('保存').props.onClick();
await flush();
expect(api.saveText).toHaveBeenLastCalledWith(props.path, props.instanceId, 'precious draft', 'version-one');
});
it('canceling close, dialog dismissal, reload and save retains edits without requests', async () => {
await load();
editor().props.onChange('keep me');
vi.mocked(window.confirm).mockReturnValue(false);
button('关闭').props.onClick();
nodes(render(), n => n.type === DialogRoot)[0].props.onOpenChange(false);
button('重新加载').props.onClick();
button('保存').props.onClick();
await flush();
expect(editor().props.value).toBe('keep me');
expect(props.onClose).not.toHaveBeenCalled();
expect(api.readText).toHaveBeenCalledTimes(1);
expect(api.saveText).not.toHaveBeenCalled();
});
it('registers an unload warning only while dirty and cleans it up on reset and unmount', async () => {
await load();
expect(window.addEventListener).not.toHaveBeenCalled();
editor().props.onChange('dirty');
render();
const listener = vi.mocked(window.addEventListener).mock.calls[0][1] as (event: any) => void;
const event = {preventDefault: vi.fn(), returnValue: undefined};
listener(event);
expect(event.preventDefault).toHaveBeenCalledOnce();
expect(event.returnValue).toBe('');
editor().props.onChange('name: original');
render();
expect(window.removeEventListener).toHaveBeenCalledWith('beforeunload', listener);
editor().props.onChange('dirty again');
render();
const last = vi.mocked(window.addEventListener).mock.calls.at(-1)![1];
unmount();
expect(window.removeEventListener).toHaveBeenLastCalledWith('beforeunload', last);
});
it.each([[413, '文件超过 1 MiB'], [415, '不是支持的 UTF-8 文本文件']])('shows a useful read error for status %s', async (status, text) => {
vi.mocked(api.readText).mockRejectedValueOnce(new ApiError(status as number, 'read failed'));
await load();
expect(JSON.stringify(render())).toContain(text);
expect(editor()).toBeUndefined();
expect(button('保存').props.disabled).toBe(true);
});
it('counts UTF-8 bytes and prevents oversize drafts from saving', async () => {
await load();
editor().props.onChange('界'.repeat(Math.floor(maxTextBytes / 3) + 1));
expect(button('保存').props.disabled).toBe(true);
expect(JSON.stringify(render())).toContain('内容超过 1 MiB');
button('保存').props.onClick();
expect(api.saveText).not.toHaveBeenCalled();
});
it('locks duplicate saves and close/reload actions while the write is pending', async () => {
await load();
let resolve!: (result: {version: string}) => void;
vi.mocked(api.saveText).mockReturnValueOnce(new Promise(done => { resolve = done; }));
editor().props.onChange('pending draft');
const save = button('保存').props.onClick;
save(); save();
expect(api.saveText).toHaveBeenCalledTimes(1);
expect(window.confirm).toHaveBeenCalledTimes(1);
expect(editor().props.readOnly).toBe(true);
for (const text of ['保存', '关闭', '重新加载']) expect(button(text).props.disabled).toBe(true);
button('关闭').props.onClick();
button('重新加载').props.onClick();
expect(props.onClose).not.toHaveBeenCalled();
expect(api.readText).toHaveBeenCalledTimes(1);
resolve({version: 'saved-version'});
await flush();
expect(editor().props.readOnly).toBe(false);
expect(props.onSaved).toHaveBeenCalledOnce();
});
+75
View File
@@ -0,0 +1,75 @@
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { api, ApiError, type TextFile } from './api';
import { Alert, message } from './ui';
import { isSensitiveFile } from './fileWarnings';
import { fileLanguage, maxTextBytes } from './fileEditor';
import { DialogContent, DialogFooter, DialogRoot } from './components/ui/dialog';
import { Button } from './components/ui/button';
const Editor = lazy(() => import('./MonacoProfileEditor'));
export function FileEditor({path, instanceId, onClose, onSaved}: {path: string; instanceId: string; onClose: () => void; onSaved: () => void}) {
const [original, setOriginal] = useState<TextFile>();
const [draft, setDraft] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [notice, setNotice] = useState('');
const [reload, setReload] = useState(0);
const lock = useRef(false);
const dirty = !!original && draft !== original.content;
const size = new TextEncoder().encode(draft).length;
useEffect(() => {
let active = true;
setLoading(true); setError(''); setNotice('');
api.readText(path, instanceId).then(file => {
if (active) { setOriginal(file); setDraft(file.content); }
}).catch(e => {
if (active) setError(e instanceof ApiError && e.status === 413 ? '文件超过 1 MiB,请下载后编辑。'
: e instanceof ApiError && e.status === 415 ? '不是支持的 UTF-8 文本文件,请下载查看。' : message(e));
}).finally(() => { if (active) setLoading(false); });
return () => { active = false; };
}, [path, instanceId, reload]);
useEffect(() => {
if (!dirty && !saving) return;
const warn = (e: BeforeUnloadEvent) => { e.preventDefault(); e.returnValue = ''; };
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [dirty, saving]);
function close() {
if (!lock.current && (!dirty || window.confirm('有未保存的修改,确认放弃并关闭?'))) onClose();
}
function reloadFile() {
if (lock.current || (dirty && !window.confirm('重新加载会丢弃当前修改,是否继续?'))) return;
setReload(reload + 1);
}
async function save() {
if (!original || !dirty || loading || lock.current || size > maxTextBytes) return;
if (!window.confirm('确认保存「' + path + '」?将替换文件内容。文件可能包含配置或密钥,建议先停止实例并备份;这里不执行 YAML 校验,也不强制停机。')) return;
lock.current = true; setSaving(true); setError(''); setNotice('');
try {
const result = await api.saveText(path, instanceId, draft, original.version);
setOriginal({content: draft, version: result.version}); setNotice('已保存'); onSaved();
} catch (e) {
setError(e instanceof ApiError && e.status === 409
? '保存被拒绝:文件已变化、被删除,或实例需要恢复。当前修改已保留;请先复制需要的内容,再重新加载核对。'
: e instanceof ApiError && e.status === 413 ? '文件超过大小限制或存储配额不足,修改已保留。' : message(e));
} finally { lock.current = false; setSaving(false); }
}
return <DialogRoot open onOpenChange={open => { if (!open) close(); }}>
<DialogContent title={'编辑文件 · ' + path} className="w-[min(70rem,calc(100vw-1.5rem))]" aria-busy={saving} onInteractOutside={e => e.preventDefault()}>
<p className="text-sm text-muted-foreground">UTF-8 文本,最大 1 MiB。{isSensitiveFile(path) ? '此文件可能包含凭据或敏感配置,请谨慎修改。' : '文件可能包含敏感信息,请勿公开分享。'}建议修改前停机并备份。</p>
{error && <Alert>{error}</Alert>}
{loading ? <p role="status">正在读取文件…</p> : original && <Suspense fallback={<p role="status">正在加载编辑器…</p>}>
<Editor value={draft} onChange={setDraft} language={fileLanguage(path)} label={'文件内容 · ' + path} readOnly={saving} />
</Suspense>}
{size > maxTextBytes && <Alert>内容超过 1 MiB,无法保存。</Alert>}
<p role="status" className="mt-2 text-sm text-muted-foreground">{saving ? '正在保存…' : dirty ? '有未保存的修改' : notice}</p>
<DialogFooter>
<Button variant="outline" disabled={saving || loading} onClick={reloadFile}>重新加载</Button>
<Button variant="outline" disabled={saving} onClick={close}>关闭</Button>
<Button disabled={saving || loading || !dirty || size > maxTextBytes} onClick={() => void save()}>保存</Button>
</DialogFooter>
</DialogContent>
</DialogRoot>;
}
+118
View File
@@ -0,0 +1,118 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
const state = vi.hoisted(() => ({slots: [] as any[], cursor: 0}));
vi.mock('react', async importOriginal => ({
...await importOriginal<typeof import('react')>(),
useState(value: unknown) {
const i = state.cursor++;
if (!(i in state.slots)) state.slots[i] = value;
return [state.slots[i], (next: unknown) => { state.slots[i] = next; }];
},
}));
vi.mock('./api', () => ({api: {me: vi.fn()}}));
import { ImagePreview } from './ImagePreview';
import { api } from './api';
import { Button } from './components/ui/button';
import { DialogRoot } from './components/ui/dialog';
import { imagePreviewURL } from './imagePreview';
import { downloadWarning } from './fileWarnings';
const props = {path: 'nested/a &b.SVG', instanceId: 'instance two', onClose: vi.fn()};
function render() { state.cursor = 0; return ImagePreview(props); }
function nodes(root: any, predicate: (node: any) => boolean): any[] {
if (Array.isArray(root)) return root.flatMap(child => nodes(child, predicate));
if (!root || typeof root !== 'object') return [];
return [...(predicate(root) ? [root] : []), ...nodes(root.props?.children, predicate)];
}
const button = (text: string) => nodes(render(), n => n.type === Button && (n.props.children === text || n.props['aria-label'] === text))[0];
const image = () => nodes(render(), n => n.type === 'img')[0];
const load = () => image().props.onLoad({currentTarget: {naturalWidth: 800, naturalHeight: 600}});
const flush = () => new Promise(resolve => setTimeout(resolve, 0));
beforeEach(() => {
state.slots = []; state.cursor = 0;
vi.resetAllMocks();
vi.stubGlobal('window', {confirm: vi.fn(() => true), location: {assign: vi.fn()}});
});
afterEach(() => vi.unstubAllGlobals());
it('loads the encoded image as an img and shows natural dimensions after loading', () => {
expect(image().props).toMatchObject({src: imagePreviewURL(props.path, props.instanceId) + '&revision=0', alt: props.path, referrerPolicy: 'no-referrer'});
expect(nodes(render(), n => n.props?.role === 'status')).toHaveLength(1);
for (const label of ['原始尺寸', '缩小图片', '放大图片']) expect(button(label).props.disabled).toBe(true);
expect(nodes(render(), n => ['iframe', 'object', 'embed'].includes(n.type))).toHaveLength(0);
load();
expect(nodes(render(), n => n.props?.role === 'status')).toHaveLength(0);
expect(JSON.stringify(render())).toContain('800 × 600');
expect(button('原始尺寸').props.disabled).toBe(false);
});
it('zooms within bounds, resets to original size, and returns to fit mode', () => {
load();
expect(image().props.style).toMatchObject({maxWidth: '100%', maxHeight: '100%', width: 'auto'});
button('放大图片').props.onClick();
expect(image().props.style.width).toBe(1200);
for (let i = 0; i < 10; i++) button('放大图片').props.onClick();
expect(image().props.style.width).toBe(3200);
expect(button('放大图片').props.disabled).toBe(true);
for (let i = 0; i < 20; i++) button('缩小图片').props.onClick();
expect(image().props.style.width).toBe(80);
expect(button('缩小图片').props.disabled).toBe(true);
button('原始尺寸').props.onClick();
expect(image().props.style.width).toBe(800);
expect(JSON.stringify(render())).toContain('100%');
button('适应窗口').props.onClick();
expect(image().props.style).toMatchObject({maxWidth: '100%', maxHeight: '100%', width: 'auto'});
});
it('shows load errors and retries only after checking the session, clearing stale dimensions', async () => {
load();
image().props.onError();
expect(image()).toBeUndefined();
expect(nodes(render(), n => n.props?.role === 'alert')).toHaveLength(1);
expect(JSON.stringify(render())).toContain('16 MiB');
expect(button('原始尺寸').props.disabled).toBe(true);
let resolve!: () => void;
vi.mocked(api.me).mockReturnValueOnce(new Promise(done => { resolve = () => done({} as any); }));
button('重试').props.onClick();
expect(api.me).toHaveBeenCalledOnce();
expect(button('重试').props.disabled).toBe(true);
expect(image()).toBeUndefined();
resolve();
await flush();
expect(image().props.src).toBe(imagePreviewURL(props.path, props.instanceId) + '&revision=1');
expect(nodes(render(), n => n.props?.role === 'status')).toHaveLength(1);
expect(JSON.stringify(render())).not.toContain('800 × 600');
load();
expect(button('原始尺寸').props.disabled).toBe(false);
});
it('keeps the error visible when session recovery fails and permits another retry', async () => {
image().props.onError();
vi.mocked(api.me).mockRejectedValueOnce(new Error('expired'));
button('重试').props.onClick();
await flush();
expect(image()).toBeUndefined();
expect(nodes(render(), n => n.props?.role === 'alert')).toHaveLength(1);
expect(button('重试').props.disabled).toBe(false);
button('重试').props.onClick();
await flush();
expect(api.me).toHaveBeenCalledTimes(2);
expect(image()).toBeDefined();
});
it('requires download confirmation and preserves the selected path and instance', () => {
vi.mocked(window.confirm).mockReturnValueOnce(false);
button('下载图片').props.onClick();
expect(window.confirm).toHaveBeenCalledExactlyOnceWith(downloadWarning(props.path, false));
expect(window.location.assign).not.toHaveBeenCalled();
button('下载图片').props.onClick();
expect(window.location.assign).toHaveBeenCalledExactlyOnceWith(imagePreviewURL(props.path, props.instanceId));
});
it('closes from the footer and dialog dismissal but not an open notification', () => {
nodes(render(), n => n.type === DialogRoot)[0].props.onOpenChange(true);
expect(props.onClose).not.toHaveBeenCalled();
button('关闭').props.onClick();
nodes(render(), n => n.type === DialogRoot)[0].props.onOpenChange(false);
expect(props.onClose).toHaveBeenCalledTimes(2);
});
+43
View File
@@ -0,0 +1,43 @@
import { useState } from 'react';
import { DialogContent, DialogFooter, DialogRoot } from './components/ui/dialog';
import { Button } from './components/ui/button';
import { imagePreviewURL } from './imagePreview';
import { api } from './api';
import { downloadWarning } from './fileWarnings';
export function ImagePreview({path, instanceId, onClose}: {path: string; instanceId: string; onClose: () => void}) {
const [scale, setScale] = useState<number | null>(null);
const [size, setSize] = useState<{width: number; height: number}>();
const [error, setError] = useState(false);
const [revision, setRevision] = useState(0);
const [retrying, setRetrying] = useState(false);
async function retry() {
setRetrying(true);
try { await api.me(); setError(false); setSize(undefined); setRevision(revision + 1); }
catch { setError(true); }
finally { setRetrying(false); }
}
function download() {
if (window.confirm(downloadWarning(path, false))) window.location.assign(imagePreviewURL(path, instanceId));
}
return <DialogRoot open onOpenChange={open => { if (!open) onClose(); }}>
<DialogContent title={'图片预览 · ' + path} className="w-[min(70rem,calc(100vw-1.5rem))]">
<div className="mb-3 flex flex-wrap items-center gap-2">
<Button variant="outline" onClick={() => setScale(null)}>适应窗口</Button>
<Button variant="outline" disabled={!size || error} onClick={() => setScale(1)}>原始尺寸</Button>
<Button variant="outline" aria-label="缩小图片" disabled={!size || error || (scale !== null && scale <= 0.1)} onClick={() => setScale(Math.max(0.1, (scale ?? 1) / 1.5))}>−</Button>
<Button variant="outline" aria-label="放大图片" disabled={!size || error || (scale !== null && scale >= 4)} onClick={() => setScale(Math.min(4, (scale ?? 1) * 1.5))}>+</Button>
<span className="text-sm text-muted-foreground">{scale === null ? '适应窗口' : Math.round(scale * 100) + '%'}{size && ' · ' + size.width + ' × ' + size.height}</span>
</div>
{error ? <div role="alert" className="rounded-lg bg-destructive-muted p-4 text-destructive">图片无法预览:可能已删除、格式损坏、超过 16 MiB 或登录已失效。<Button variant="outline" className="ml-2" disabled={retrying} onClick={() => void retry()}>重试</Button></div>
: <div className="h-[55dvh] overflow-auto rounded-lg border border-border bg-muted p-2">
{!size && <p role="status">正在加载图片…</p>}
<img key={revision} src={imagePreviewURL(path, instanceId) + '&revision=' + revision} alt={path} referrerPolicy="no-referrer"
className="block" style={scale === null ? {maxWidth: '100%', maxHeight: '100%', width: 'auto', height: 'auto', margin: 'auto'} : {maxWidth: 'none', width: size ? size.width * scale : undefined, height: 'auto'}}
onLoad={e => setSize({width: e.currentTarget.naturalWidth, height: e.currentTarget.naturalHeight})} onError={() => setError(true)} />
</div>}
<p className="mt-3 text-xs text-muted-foreground">支持 PNG、JPEG、GIF、WebP、SVG,最大 16 MiB。SVG 仅以图片展示,不执行脚本。图片也可能包含敏感信息,请勿公开分享。</p>
<DialogFooter><Button variant="outline" onClick={download}>下载图片</Button><Button onClick={onClose}>关闭</Button></DialogFooter>
</DialogContent>
</DialogRoot>;
}
+25 -5
View File
@@ -2,20 +2,39 @@
import { useEffect, useRef } from 'react';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import 'monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution';
import 'monaco-editor/esm/vs/basic-languages/cpp/cpp.contribution';
import 'monaco-editor/esm/vs/basic-languages/css/css.contribution';
import 'monaco-editor/esm/vs/basic-languages/dockerfile/dockerfile.contribution';
import 'monaco-editor/esm/vs/basic-languages/go/go.contribution';
import 'monaco-editor/esm/vs/basic-languages/html/html.contribution';
import 'monaco-editor/esm/vs/basic-languages/ini/ini.contribution';
import 'monaco-editor/esm/vs/basic-languages/java/java.contribution';
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
import 'monaco-editor/esm/vs/basic-languages/markdown/markdown.contribution';
import 'monaco-editor/esm/vs/basic-languages/python/python.contribution';
import 'monaco-editor/esm/vs/basic-languages/rust/rust.contribution';
import 'monaco-editor/esm/vs/basic-languages/scss/scss.contribution';
import 'monaco-editor/esm/vs/basic-languages/shell/shell.contribution';
import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution';
import 'monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution';
import 'monaco-editor/esm/vs/basic-languages/xml/xml.contribution';
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import 'monaco-editor/esm/vs/language/json/monaco.contribution';
import JSONWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import { useNightMode } from './nightMode';
// Vite emits this worker locally; no AMD loader or CDN is involved.
self.MonacoEnvironment = { getWorker: () => new EditorWorker() };
self.MonacoEnvironment = { getWorker: (_id, label) => label === 'json' ? new JSONWorker() : new EditorWorker() };
export interface ProfileEditorProps {
value: string;
onChange?: (value: string) => void;
readOnly?: boolean;
label?: string;
language?: string;
}
export default function MonacoProfileEditor({ value, onChange, readOnly = false, label = 'YAML 配置' }: ProfileEditorProps) {
export default function MonacoProfileEditor({ value, onChange, readOnly = false, label = 'YAML 配置', language = 'yaml' }: ProfileEditorProps) {
const host = useRef<HTMLDivElement>(null);
const editor = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
const change = useRef(onChange);
@@ -25,7 +44,7 @@ export default function MonacoProfileEditor({ value, onChange, readOnly = false,
const dark = useNightMode();
useEffect(() => {
if (!host.current) return;
const model = monaco.editor.createModel(initialValue.current, 'yaml');
const model = monaco.editor.createModel(initialValue.current, language);
const instance = monaco.editor.create(host.current, {
model, automaticLayout: true, minimap: { enabled: false },
scrollBeyondLastLine: false, tabSize: 2, insertSpaces: true,
@@ -34,13 +53,13 @@ export default function MonacoProfileEditor({ value, onChange, readOnly = false,
});
editor.current = instance;
const listener = instance.onDidChangeModelContent(() => {
if (!updating.current) change.current?.(instance.getValue());
if (!updating.current) change.current?.(model.getValue(undefined, true));
});
return () => { listener.dispose(); instance.dispose(); model.dispose(); editor.current = null; };
}, []);
useEffect(() => {
const instance = editor.current;
if (instance && instance.getValue() !== value) {
if (instance && instance.getModel()?.getValue(undefined, true) !== value) {
updating.current = true;
instance.setValue(value);
updating.current = false;
@@ -48,5 +67,6 @@ export default function MonacoProfileEditor({ value, onChange, readOnly = false,
}, [value]);
useEffect(() => { editor.current?.updateOptions({ readOnly, ariaLabel: label }); }, [readOnly, label]);
useEffect(() => { monaco.editor.setTheme(dark ? 'vs-dark' : 'vs'); }, [dark]);
useEffect(() => { const model = editor.current?.getModel(); if (model) monaco.editor.setModelLanguage(model, language); }, [language]);
return <div role="group" aria-label={label} ref={host} style={{ height: 420, minWidth: 0, border: '1px solid var(--color-border, #d5dbe5)', borderRadius: 8, overflow: 'hidden' }} />;
}
+64
View File
@@ -12,6 +12,10 @@ vi.mock('./ui', async importOriginal => ({
}));
vi.mock('./api', () => ({api: {download: vi.fn(() => '/download-test'), upload: vi.fn(async () => {}), rename: vi.fn(async () => {}), delete: vi.fn(async () => {})}}));
import { Workspace } from './Workspace';
import { FileEditor } from './FileEditor';
import { ImagePreview } from './ImagePreview';
import { maxImageBytes } from './imagePreview';
import { maxTextBytes } from './fileEditor';
import { api } from './api';
import { ConfirmDialog } from './components/ConfirmDialog';
import { DialogContent } from './components/ui/dialog';
@@ -34,12 +38,72 @@ const dialog = () => nodes(render(), n => n.type === ConfirmDialog)[0];
const flush = () => new Promise(resolve => setTimeout(resolve, 0));
const locationAssign = () => vi.mocked((window as any).location.assign);
it('opens image previews from desktop and mobile actions with path and instance identity', () => {
state.entries = [{name: 'photo.PNG', is_dir: false, size: maxImageBytes}];
const buttons = nodes(render(), byText('预览'));
expect(buttons).toHaveLength(2);
for (const button of buttons) {
expect(button.props.disabled).toBe(false);
button.props.onClick();
const preview = nodes(render(), n => n.type === ImagePreview)[0];
expect(preview.props).toMatchObject({path: 'photo.PNG', instanceId: 'one'});
expect(preview.key).toBe('one:photo.PNG');
preview.props.onClose();
expect(nodes(render(), n => n.type === ImagePreview)).toHaveLength(0);
}
});
it('offers preview only for image files, never directories or unsupported extensions', () => {
state.entries = [
{name: 'directory.png', is_dir: true, size: 0},
{name: 'notes.txt', is_dir: false, size: 10},
{name: 'photo.bmp', is_dir: false, size: 10},
{name: 'photo.svg.html', is_dir: false, size: 10},
];
expect(nodes(render(), byText('预览'))).toHaveLength(0);
});
it('disables both preview entry points above the 16 MiB boundary', () => {
state.entries = [{name: 'large.webp', is_dir: false, size: maxImageBytes + 1}];
const buttons = nodes(render(), byText('预览'));
expect(buttons).toHaveLength(2);
for (const button of buttons) {
expect(button.props.disabled).toBe(true);
expect(button.props.title).toContain('超过 16 MiB');
}
expect(nodes(render(), n => n.type === ImagePreview)).toHaveLength(0);
});
beforeEach(() => {
state.slots = []; state.cursor = 0; state.entries = [{name: '.credentials.yaml', is_dir: false}];
vi.clearAllMocks(); vi.stubGlobal('window', {location: {assign: vi.fn()}});
});
afterEach(() => vi.unstubAllGlobals());
it('opens a path- and instance-keyed editor from both desktop and mobile file actions', () => {
const buttons = nodes(render(), byText('编辑'));
expect(buttons).toHaveLength(2);
for (const button of buttons) {
expect(button.props.disabled).toBe(false);
button.props.onClick();
const editor = nodes(render(), n => n.type === FileEditor)[0];
expect(editor.props).toMatchObject({path: '.credentials.yaml', instanceId: 'one'});
expect(editor.key).toBe('one:.credentials.yaml');
editor.props.onClose();
expect(nodes(render(), n => n.type === FileEditor)).toHaveLength(0);
}
});
it('does not offer directory editing and disables oversized file editing', () => {
state.entries = [{name: 'directory', is_dir: true}, {name: 'large.txt', is_dir: false, size: maxTextBytes + 1}];
const buttons = nodes(render(), byText('编辑'));
expect(buttons).toHaveLength(2);
for (const button of buttons) {
expect(button.props.disabled).toBe(true);
expect(button.props.title).toContain('超过 1 MiB');
}
});
it.each([false, true])('cancel blocks download navigation and acceptance preserves owner access (directory=%s)', async is_dir => {
state.entries = [{name: is_dir ? 'photos' : 'renamed.txt', is_dir}];
// Both the desktop table and the mobile cards render a download button.
+10
View File
@@ -12,6 +12,10 @@ import { buttonVariants } from './components/ui/button';
import { inputClass } from './components/ui/input';
import { AlertBox } from './components/ui/alert';
import { cn } from './lib/utils';
import { FileEditor } from './FileEditor';
import { maxTextBytes } from './fileEditor';
import { ImagePreview } from './ImagePreview';
import { isPreviewImage, maxImageBytes } from './imagePreview';
export function Workspace({runtime}: {runtime: ReturnType<typeof useRuntimeInstances>}) {
const selected = runtime.instances?.find(instance => instance.id === runtime.selectedId);
@@ -45,6 +49,8 @@ function WorkspaceFiles({instanceId, instanceName, controls, path, setPath}: Fil
const confirm = useConfirm();
const go = (target: string) => setPath(navigateDirectory(path, target, action.busy));
const [newName, setNewName] = useState(''), [rename, setRename] = useState<{path: string; name: string}>();
const [editing, setEditing] = useState<string>();
const [preview, setPreview] = useState<string>();
const join = (name: string) => joinFilePath(path, name);
const refresh = async () => { await Promise.all([tree.refresh(), usage.refresh()]); };
function mkdir(e: FormEvent) { e.preventDefault(); void action.run(async () => { await api.mkdir(join(newName), instanceId); setNewName(''); await refresh(); }, '目录已创建'); }
@@ -67,6 +73,8 @@ function WorkspaceFiles({instanceId, instanceName, controls, path, setPath}: Fil
const actionButtons = (entry: Entry) => {
const target = entry.path || join(entry.name);
return <>
{!entry.is_dir && isPreviewImage(entry.name) && <button className={cn(buttonVariants({variant: 'outline', size: 'sm'}))} disabled={action.busy || entry.size > maxImageBytes} title={entry.size > maxImageBytes ? '超过 16 MiB,请下载查看' : '预览图片'} onClick={() => setPreview(target)}>预览</button>}
{!entry.is_dir && <button className={cn(buttonVariants({variant: 'outline', size: 'sm'}))} disabled={action.busy || entry.size > maxTextBytes} title={entry.size > maxTextBytes ? '超过 1 MiB,请下载后编辑' : '查看和编辑文本文件'} onClick={() => setEditing(target)}><Pencil aria-hidden />编辑</button>}
<button className={cn(buttonVariants({variant: 'outline', size: 'sm'}))} disabled={action.busy} title={downloadWarning(target, entry.is_dir)} onClick={() => void downloadEntry(target, entry.is_dir)}><Download aria-hidden />下载</button>
<button className={cn(buttonVariants({variant: 'ghost', size: 'sm'}))} disabled={action.busy} onClick={() => setRename({path: target, name: entry.name})}><Pencil aria-hidden />重命名</button>
<button className={cn(buttonVariants({variant: 'ghost', size: 'sm'}), 'text-destructive hover:bg-destructive-muted')} disabled={action.busy} onClick={() => void deleteEntry(target)}><Trash2 aria-hidden />删除</button>
@@ -75,6 +83,8 @@ function WorkspaceFiles({instanceId, instanceName, controls, path, setPath}: Fil
return <>
{controls(action.busy)}
{preview && <ImagePreview key={instanceId + ':' + preview} path={preview} instanceId={instanceId} onClose={() => setPreview(undefined)} />}
{editing && <FileEditor key={instanceId + ':' + editing} path={editing} instanceId={instanceId} onClose={() => setEditing(undefined)} onSaved={() => { void refresh(); }} />}
{confirm.element}
<div className="mb-5 flex flex-wrap items-center justify-between gap-4 rounded-xl border border-border bg-secondary/50 p-4 sm:p-5">
<div className="min-w-0">
+3
View File
@@ -11,6 +11,7 @@ export interface Release { release_id: string; version: string; commit: string;
export const selectableImage = (image: Image) => image.status === 'available' && image.selectable === true;
export interface Entry { name: string; path?: string; is_dir: boolean; size: number; mod_time: string }
export interface Usage { used_bytes: number; quota_bytes: number }
export interface TextFile { content: string; version: string }
export interface Backup { id: string; created_at: string; size: number }
export interface Audit { id: string; action: string; target: string; detail: string; user_id: string; created_at: string }
export function createApi(fetcher: typeof fetch = fetch) {
@@ -88,6 +89,8 @@ export function createApi(fetcher: typeof fetch = fetch) {
build: (id: string) => request<Build>('/builds/' + encodeURIComponent(id)),
usage: (instance?: string) => request<Usage>('/ws/usage' + (instance ? '?instance=' + encodeURIComponent(instance) : '')),
tree: (path: string, instance?: string) => request<Entry[]>('/ws/tree?path=' + encodeURIComponent(path) + (instance ? '&instance=' + encodeURIComponent(instance) : '')),
readText: (path: string, instance: string) => request<TextFile>('/ws/text?path=' + encodeURIComponent(path) + '&instance=' + encodeURIComponent(instance)),
saveText: (path: string, instance: string, content: string, version: string) => request<{version: string}>('/ws/text?path=' + encodeURIComponent(path) + '&instance=' + encodeURIComponent(instance), 'PUT', {content, version}),
download: (path: string, instance?: string) => '/api/ws/download?path=' + encodeURIComponent(path) + (instance ? '&instance=' + encodeURIComponent(instance) : ''),
mkdir: (path: string, instance?: string) => request('/ws/mkdir' + (instance ? '?instance=' + encodeURIComponent(instance) : ''), 'POST', {path}),
rename: (path: string, newPath: string, instance?: string) => request('/ws/rename' + (instance ? '?instance=' + encodeURIComponent(instance) : ''), 'POST', {path, new_path: newPath}),
+20
View File
@@ -0,0 +1,20 @@
import { expect, it } from 'vitest';
import { fileLanguage, maxTextBytes } from './fileEditor';
it('sets the text limit to exactly one MiB', () => {
expect(maxTextBytes).toBe(1024 * 1024);
});
it.each([
['nested/CONFIG.YAML', 'yaml'], ['config.yml', 'yaml'],
['settings.jsonc', 'json'], ['app.tsx', 'typescript'], ['app.mjs', 'javascript'],
['README.md', 'markdown'], ['script.sh', 'shell'], ['main.py', 'python'],
['main.go', 'go'], ['main.rs', 'rust'], ['index.html', 'html'],
['theme.css', 'css'], ['theme.scss', 'scss'], ['data.xml', 'xml'],
['schema.sql', 'sql'], ['settings.toml', 'ini'], ['service.conf', 'ini'],
['Main.java', 'java'], ['main.c', 'c'], ['include.h', 'c'], ['main.cpp', 'cpp'],
['build/Dockerfile', 'dockerfile'], ['secrets/.env', 'ini'], ['secrets/.env.local', 'ini'],
['README', 'plaintext'], ['data.unknown', 'plaintext'], ['folder.yaml/plain', 'plaintext'],
])('selects a language for %s', (path, language) => {
expect(fileLanguage(path)).toBe(language);
});
+16
View File
@@ -0,0 +1,16 @@
export const maxTextBytes = 1 << 20;
export function fileLanguage(path: string): string {
const name = path.split('/').at(-1)!.toLowerCase();
if (name === 'dockerfile') return 'dockerfile';
if (name === '.env' || name.startsWith('.env.')) return 'ini';
const languages: Record<string, string> = {
yaml: 'yaml', yml: 'yaml', json: 'json', jsonc: 'json',
js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript',
ts: 'typescript', tsx: 'typescript', md: 'markdown', markdown: 'markdown',
sh: 'shell', bash: 'shell', py: 'python', go: 'go', rs: 'rust',
html: 'html', css: 'css', scss: 'scss', xml: 'xml', sql: 'sql',
ini: 'ini', toml: 'ini', conf: 'ini', java: 'java', c: 'c', h: 'c', cpp: 'cpp',
};
return languages[name.split('.').at(-1)!] || 'plaintext';
}
+1 -1
View File
@@ -1,4 +1,4 @@
export const homeAccessNotice = '所有者可完整管理实例 home,包括读取、下载凭据;不承诺凭据仅写入(write-only)。专用 profile 页面提供受控编辑流程,不是强制安全边界;通用文件上传、重命名或删除可绕过该流程的 YAML 校验和停机要求。';
export const homeAccessNotice = '所有者可完整管理实例 home,包括读取、下载凭据;不承诺凭据仅写入(write-only)。专用 profile 页面提供受控编辑流程,不是强制安全边界;通用文件编辑、上传、重命名或删除可绕过该流程的 YAML 校验和停机要求。';
const configMutationWarning = '修改配置可能影响实例运行。建议先停止实例并备份,再继续;这里不强制停机。';
// Filename hints are UX only: renamed secrets cannot be reliably identified.
+19
View File
@@ -0,0 +1,19 @@
import { expect, it } from 'vitest';
import { imagePreviewURL, isPreviewImage, maxImageBytes } from './imagePreview';
it.each(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'])('allows .%s images regardless of case', extension => {
expect(isPreviewImage('nested/photo.' + extension)).toBe(true);
expect(isPreviewImage('nested/photo.' + extension.toUpperCase())).toBe(true);
});
it.each(['photo.bmp', 'photo.ico', 'photo.avif', 'photo.png.txt', 'photo.svg.html', 'notpng', 'photo-jpeg', 'png', ''])('rejects unsupported or missing extensions: %s', path => {
expect(isPreviewImage(path)).toBe(false);
});
it('encodes the entire path and instance independently without query injection', () => {
expect(imagePreviewURL('相册/a &b#?%.PNG', 'two /&?#%')).toBe('/api/ws/image?path=%E7%9B%B8%E5%86%8C%2Fa%20%26b%23%3F%25.PNG&instance=two%20%2F%26%3F%23%25');
});
it('limits preview size to 16 MiB', () => {
expect(maxImageBytes).toBe(16 * 1024 * 1024);
});
+3
View File
@@ -0,0 +1,3 @@
export const maxImageBytes = 16 << 20;
export const isPreviewImage = (path: string) => /\.(png|jpe?g|gif|webp|svg)$/i.test(path);
export const imagePreviewURL = (path: string, instance: string) => '/api/ws/image?path=' + encodeURIComponent(path) + '&instance=' + encodeURIComponent(instance);