feat: preview components

This commit is contained in:
tao.chen
2026-08-11 15:02:16 +08:00
parent 5969f2f749
commit b44d057241
4 changed files with 203 additions and 27 deletions
@@ -7,7 +7,10 @@ import type {
} from "../../services/api";
import { scriptIcon } from "./WorkspaceTree";
import type { MouseEvent as ReactMouseEvent, RefObject } from "react";
import { useRef, useEffect } from "react";
import Editor from "@monaco-editor/react";
import { useRef, useLayoutEffect } from "react";
import { useScriptWorkspaceStore } from "./state/scriptWorkspaceStore";
type ToastState = {
tone: "success" | "error" | "info";
@@ -129,9 +132,9 @@ export function ScriptWorkspace({
left: direction === "left" ? -scrollAmount : scrollAmount,
behavior: "smooth",
});
};
};
useEffect(() => {
useLayoutEffect(() => {
const tabbar = tabbarRef.current;
if (!tabbar) return;
const activeTab = tabbar.querySelector(".editor-tab--active") as HTMLElement | null;
@@ -232,13 +235,11 @@ export function ScriptWorkspace({
</button>
<span className={`stage-badge${isEditing ? " is-editing" : ""}`}>
<span />
{isEditing
? isNotebook
? "Demo 无锁模式 · Kernel 已连接"
: "Demo 无锁模式 · 编辑中"
: latestVersion
{
latestVersion
? `最新 ${latestVersion.version_label}`
: "工作副本已就绪"}
: "工作副本已就绪"
}
</span>
</div>
</div>
@@ -378,13 +379,13 @@ export function ScriptWorkspace({
<span>Python </span>
<em>{isEditing ? "Jupyter 中可编辑" : "平台只读预览"}</em>
</div>
<PythonPreview />
<PythonPreview workspaceId={script.workspace_id} filePath={`${script.script_id}.py`}/>
</div>
<div className="integrity-row">
<span>
<Icon name="check" size={15} />
{isEditing ? "Demo 无锁编辑会话已连接" : "工作副本已同步"}
{/*{isEditing ? "Demo 无锁编辑会话已连接" : "工作副本已同步"}*/}
</span>
<span>SHA-256&nbsp; {shortHash(script.content_hash)}</span>
<span>
@@ -403,19 +404,59 @@ export function ScriptWorkspace({
);
}
function PythonPreview() {
interface PythonPreviewProps {
workspaceId: string;
filePath: string;
}
export function PythonPreview({
workspaceId,
filePath,
}: PythonPreviewProps) {
const previewKey = `${workspaceId}::${filePath}`;
const storeKey = useScriptWorkspaceStore((s) => s.previewKey);
const previewCode = useScriptWorkspaceStore((s) => s.previewCode);
const previewCodeSize = useScriptWorkspaceStore((s) => s.previewCodeSize);
const previewLoading = useScriptWorkspaceStore((s) => s.previewLoading);
const previewError = useScriptWorkspaceStore((s) => s.previewError);
const loadPreview = useScriptWorkspaceStore((s) => s.loadPreview);
useLayoutEffect(() => {
void loadPreview(workspaceId, filePath);
}, [previewKey]);
if (storeKey !== previewKey) {
return <div>Loading...</div>;
}
if (previewLoading) {
return <div>Loading...</div>;
}
if (previewError) {
return <div>Failed to load: {previewError}</div>;
}
return (
<div className="python-preview">
<div className="line-numbers">
1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9
</div>
<pre>
<span className="code-comment">&quot;&quot;&quot;&quot;&quot;&quot;</span>
{"\n\n"}<b>def</b> <span className="code-function">main</span>() -&gt; <b>None</b>:
{"\n"} print(<i>&quot;Hello, Model Platform!&quot;</i>)
{"\n\n\n"}<b>if</b> __name__ == <i>&quot;__main__&quot;</i>:
{"\n"} main()
</pre>
</div>
<Editor
height="550px"
language="python"
value={previewCode ?? ""}
theme="vs"
options={{
readOnly: true,
domReadOnly: true,
minimap: {
enabled: previewCodeSize !== null && previewCodeSize > 1000,
},
lineNumbers: "off",
folding: true,
wordWrap: "on",
contextmenu: false,
dragAndDrop: false,
automaticLayout: true,
renderLineHighlight: "none",
}}
/>
);
}
@@ -8,7 +8,7 @@ import type {
Visibility,
WorkspaceBoundApi,
WorkspaceDirectory,
} from "../../../services/api";
} from "~/services/api";
import type { NewScriptForm } from "./uiStore";
import { useUiStore } from "./uiStore";
@@ -27,6 +27,8 @@ let _editSession: ActiveEditSession | null = null;
let _editorOpening = false;
let _editorOpenRequest = 0;
let _api: WorkspaceBoundApi | null = null;
let _previewController: AbortController | null = null;
let _previewRequest = 0;
export const bindScriptWorkspaceApi = (api: WorkspaceBoundApi | null) => {
_api = api;
@@ -60,6 +62,12 @@ type State = {
latestVersion: LatestVersion | null;
latestVersionLoading: boolean;
previewKey: string | null;
previewCode: string | null;
previewCodeSize: number | null;
previewLoading: boolean;
previewError: string | null;
// actions
setApiOnline: (online: boolean) => void;
setKeyword: (keyword: string) => void;
@@ -72,6 +80,7 @@ type State = {
openScriptEditor: (script: ScriptItem, showToast?: boolean) => Promise<void>;
endEditing: (closeTabFlag?: boolean, showToast?: boolean) => Promise<void>;
loadLatestVersion: (scriptId: string) => Promise<void>;
loadPreview: (workspaceId: string, filePath: string) => Promise<void>;
createScript: (form: NewScriptForm) => Promise<ScriptItem | null>;
uploadScripts: (files: File[], parentPath: string) => Promise<void>;
createFolder: (name: string, parentPath: string) => Promise<void>;
@@ -132,10 +141,21 @@ export const useScriptWorkspaceStore = create<State>((set, get) => {
latestVersion: null,
latestVersionLoading: false,
previewKey: null,
previewCode: null,
previewCodeSize: null,
previewLoading: false,
previewError: null,
setApiOnline: (online) => set({ apiOnline: online }),
setKeyword: (keyword) => set({ keyword }),
reset: () => {
if (_previewController) {
_previewController.abort();
_previewController = null;
}
_previewRequest += 1;
_selectedId = null;
_editSession = null;
editSessionHandle.current = null;
@@ -150,6 +170,11 @@ export const useScriptWorkspaceStore = create<State>((set, get) => {
editorOpenError: null,
latestVersion: null,
latestVersionLoading: false,
previewKey: null,
previewCode: null,
previewCodeSize: null,
previewLoading: false,
previewError: null,
});
},
@@ -390,6 +415,58 @@ export const useScriptWorkspaceStore = create<State>((set, get) => {
}
},
loadPreview: async (workspaceId, filePath) => {
if (_previewController) {
_previewController.abort();
}
_previewRequest += 1;
const requestId = _previewRequest;
const previewKey = `${workspaceId}::${filePath}`;
set({ previewKey, previewLoading: true, previewError: null });
const controller = new AbortController();
_previewController = controller;
try {
const url =
`/jupyter/${workspaceId}/api/contents/${filePath}` +
`?type=file&content=1&hash=1&format=text`;
const response = await fetch(url, {
signal: controller.signal,
credentials: "include",
cache: "no-store",
});
if (!response.ok) {
throw new Error(`Failed to load file: ${response.status}`);
}
const data = await response.json();
if (_previewRequest !== requestId) return;
set({
previewKey,
previewCode: data.content ?? "",
previewCodeSize: data.size ?? 0,
previewLoading: false,
previewError: null,
});
} catch (error) {
if (_previewRequest !== requestId) return;
if (error instanceof Error && error.name === "AbortError") return;
set({
previewKey,
previewCode: null,
previewCodeSize: null,
previewLoading: false,
previewError:
error instanceof Error ? error.message : "加载预览失败",
});
} finally {
if (_previewRequest === requestId) {
_previewController = null;
}
}
},
createScript: async (form) => {
const api = requireApi();
const suffix = form.scriptType === "notebook" ? ".ipynb" : ".py";
@@ -666,4 +743,4 @@ export const useScriptWorkspaceStore = create<State>((set, get) => {
}
},
};
});
});