feat(web): draggable floating panels and a non-hanging tutorial demo open
- add a shared useDraggablePanel hook (pointer capture, clamping, offset persistence in localStorage, double-click / button / menu reset) and use it for the tutorial step panel, the quick toolbar, the adjust-last-operation panel and the robot tool drawer - quick toolbar drags out of the dock into a compact floating bar and can be folded; robot tool scrim is transparent and click-through so the 3D scene stays visible and usable while the tool is open - 窗口 > 恢复默认面板位置 clears every stored panel offset - fix a pre-existing hang: tutorial demo scene opens went through the "save current project?" prompt and waited forever; course demos now persist the current OPFS project like the dialog's 保存后继续 and continue - PBR tutorial spec: demos must not auto-download .blend (OPFS-only rule) Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,7 @@ import {NATIVE_EDITORS} from './native-editors';
|
||||
import {recoverDesktop,saveDesktop} from './desktop-workspace-storage';
|
||||
import {NativeResourceClient} from '../engine-client/NativeResourceClient';
|
||||
import { COURSES, type AvailableCourseId } from "../tutorial/course";
|
||||
import { resetAllPanelOffsets, useDraggablePanel } from "./use-draggable-panel";
|
||||
import { TutorialOverlay } from "../tutorial/TutorialOverlay";
|
||||
import type { PbrCameraMode, PbrResolution, TutorialApi, TutorialContext, TutorialRenderResult } from "../tutorial/parts/types";
|
||||
import type {NativeExportFormat} from '../../../protocol/native-workflow';
|
||||
@@ -4857,6 +4858,12 @@ export function App({localOnly=false,course}:{localOnly?:boolean;course?:Availab
|
||||
const preferencesRef = useRef<WebPreferencesIR>(webPreferences);
|
||||
preferencesRef.current = webPreferences;
|
||||
const [quickTools,setQuickTools]=useState(()=> (initialWebSettings?.preferences ?? DEFAULT_WEB_PREFERENCES).interface.quickTools);
|
||||
/* The quick toolbar sits on top of every area; let the user drag it out of
|
||||
* the way (it becomes a compact floating bar) or fold it entirely. */
|
||||
const [quickToolsCollapsed,setQuickToolsCollapsed]=useState(false);
|
||||
const quickToolbarDrag=useDraggablePanel("quick-toolbar");
|
||||
/* Adjust-last-operation also floats over the viewport's bottom-left corner. */
|
||||
const lastOperatorDrag=useDraggablePanel("last-operator");
|
||||
const [showStatus,setShowStatus]=useState(()=> (initialWebSettings?.preferences ?? DEFAULT_WEB_PREFERENCES).interface.showStatus);
|
||||
const [showAreaSwitcher,setShowAreaSwitcher]=useState(()=> (initialWebSettings?.preferences ?? DEFAULT_WEB_PREFERENCES).interface.showAreaSwitcher);
|
||||
const [preferencesError,setPreferencesError]=useState('');
|
||||
@@ -6728,7 +6735,7 @@ export function App({localOnly=false,course}:{localOnly?:boolean;course?:Availab
|
||||
const response = await fetch(url, { cache: "no-cache" });
|
||||
if (!response.ok) return false;
|
||||
const file = new File([await response.arrayBuffer()], fileName, { type: "application/x-blender" });
|
||||
return openBlendFile(file);
|
||||
return openBlendFile(file, [], [], { saveDirtyProject: true });
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
@@ -7638,7 +7645,7 @@ export function App({localOnly=false,course}:{localOnly?:boolean;course?:Availab
|
||||
}
|
||||
};
|
||||
|
||||
const openBlendFile = async (file: File, librarySources: Array<{ path: string; file: File }> = [], replacementChoices: MissingDatablockReplacement[] = []): Promise<boolean> => {
|
||||
const openBlendFile = async (file: File, librarySources: Array<{ path: string; file: File }> = [], replacementChoices: MissingDatablockReplacement[] = [], options: { saveDirtyProject?: boolean } = {}): Promise<boolean> => {
|
||||
const identity = nextUserActionIdentity("OPEN");
|
||||
try { if (!await waitForAutosave(identity)) return false; } catch (error) { setEngineStatus(recordDiagnostic('ENGINE', 'BLEND_OPEN_FAILED', error)); return false; }
|
||||
const replacements = replacementChoices.filter(choice => choice.replacementName).map(({ sourcePath, idCode, missingName, replacementName, replacementSourcePath }) => ({ sourcePath, idCode, missingName, replacementName, replacementSourcePath }));
|
||||
@@ -7652,7 +7659,7 @@ export function App({localOnly=false,course}:{localOnly?:boolean;course?:Availab
|
||||
let failureCode = "OPEN_FILE_READ_FAILED";
|
||||
try {
|
||||
await editCommandTailRef.current;
|
||||
if (!await prepareProjectReplacement()) {
|
||||
if (!await prepareProjectReplacement(options.saveDirtyProject ? "save" : "ask")) {
|
||||
cancelUserAction(identity, "OPEN_CANCELLED");
|
||||
setLibraryRecovery(current => current?.file === file ? { ...current, message: "恢复已取消;原工程保留。" } : current);
|
||||
return false;
|
||||
@@ -8275,14 +8282,19 @@ export function App({localOnly=false,course}:{localOnly?:boolean;course?:Availab
|
||||
};
|
||||
// Called under the existing project action lock. Saving here uses the same
|
||||
// native Main and storage transaction; do not acquire a nested SAVE lock.
|
||||
const prepareProjectReplacement = async (): Promise<boolean> => {
|
||||
const prepareProjectReplacement = async (mode: 'ask' | 'save' = 'ask'): Promise<boolean> => {
|
||||
if (!dirtyState.dirty && !textDraftDirty.current) return true;
|
||||
const choice = await new Promise<'save' | 'discard' | 'cancel'>(resolve => {
|
||||
replacementChoiceRef.current = resolve;
|
||||
setReplacementPrompt({ hasTextDraft: textDraftDirty.current });
|
||||
});
|
||||
if (choice === 'cancel') return false;
|
||||
if (choice === 'discard') return true;
|
||||
/* A scripted course demo (教程“演示本步”) cannot answer this prompt, so it
|
||||
* would hang the step forever; the course keeps its own OPFS checkpoint, so
|
||||
* persist the current project exactly like the dialog's “保存后继续”. */
|
||||
if (mode === 'ask') {
|
||||
const choice = await new Promise<'save' | 'discard' | 'cancel'>(resolve => {
|
||||
replacementChoiceRef.current = resolve;
|
||||
setReplacementPrompt({ hasTextDraft: textDraftDirty.current });
|
||||
});
|
||||
if (choice === 'cancel') return false;
|
||||
if (choice === 'discard') return true;
|
||||
}
|
||||
// Unapplied editor text is not yet part of Main's .blend serialization.
|
||||
if (textDraftDirty.current) return false;
|
||||
if (!storageClientRef.current) {
|
||||
@@ -9127,7 +9139,7 @@ else:
|
||||
'窗口':[menuAction('新建窗口',()=>{window.open(window.location.href,'_blank','noopener');}),{...menuAction('切换全屏',()=>{void toggleBrowserFullscreen();},fullscreenPending||(!browserFullscreen&&!document.fullscreenEnabled)),checked:browserFullscreen,reason:fullscreenPending?'全屏切换进行中':!browserFullscreen&&!document.fullscreenEnabled?'浏览器当前不允许全屏':undefined},separator,
|
||||
menuAction('完整桌面工作区',()=>{void openFullDesktop();},!hasProject),separator,menuAction('下一个工作区',()=>cycleWorkspace(1)),menuAction('上一个工作区',()=>cycleWorkspace(-1)),{label:'编辑器',children:NATIVE_EDITORS.map(item=>menuAction(item.label,()=>openNativeEditor(item.id),!hasProject))},{label:'显示状态栏',checked:showStatus,action:()=>setShowStatus(!showStatus)},separator,
|
||||
menuAction('保存视口截图',()=>{const canvas=document.querySelector<HTMLCanvasElement>('canvas.viewport-canvas');if(!canvas)return;canvas.toBlob(blob=>{if(!blob)return;const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download='viewport.png';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});},workspace==='Rendering'||new URLSearchParams(location.search).get('offscreen')==='1'),
|
||||
{label:'Web 扩展',children:[menuAction('六轴机器人工具',()=>setRobotToolOpen(true)),menuAction('原生桌面会话',()=>setInteractiveDesktop({context:nativeContext()}),!hasProject),{label:'显示快捷操作栏',checked:quickTools,action:()=>setQuickTools(!quickTools)}]}],
|
||||
{label:'Web 扩展',children:[menuAction('六轴机器人工具',()=>setRobotToolOpen(true)),menuAction('原生桌面会话',()=>setInteractiveDesktop({context:nativeContext()}),!hasProject),{label:'显示快捷操作栏',checked:quickTools,action:()=>setQuickTools(!quickTools)}]},menuAction('恢复默认面板位置',()=>{resetAllPanelOffsets();setQuickToolsCollapsed(false);})],
|
||||
'帮助':[menuAction('使用手册(网页版)',()=>{window.open('/manuals/index.html','_blank','noopener');}),menuAction('PDF 手册(旧版下载)',()=>{window.open('/manuals/WEB_Blender_Function_User_Guide.pdf','_blank','noopener');}),menuAction('菜单操作对照',()=>{window.open('/manuals/WEB_Blender_Desktop_Menus.pdf','_blank','noopener');}),menuAction('导航操作说明',()=>{window.open('/manuals/WEB_Blender_Viewport_Navigation.pdf','_blank','noopener');}),menuAction('机器人工具说明',()=>{window.open('/manuals/WEB_Blender_Robot_Tool_User_Manual.pdf','_blank','noopener');}),menuAction('零件建模教学',()=>{window.open('/?tutorial=parts','_blank','noopener');}),menuAction('二级减速器教学',()=>{window.open('/?tutorial=reducer','_blank','noopener');}),menuAction('PBR 渲染教学',()=>{window.open('/?ui=web&tutorial=pbr','_blank','noopener');}),menuAction('PBR 渲染图文/视频教案',()=>{window.open('/tutorial/pbr/render-lesson.html','_blank','noopener');}),menuAction('渲染四条通路教案',()=>{window.open('/tutorial/rendering/index.html','_blank','noopener');}),menuAction('渲染入门(四条通路实走)',()=>{window.open('/tutorial/render-basics/index.html','_blank','noopener');}),menuAction('渲染全流程实训',()=>{window.open('/?tutorial=rendering','_blank','noopener');}),menuAction('完整初学者课程(31 项能力)',()=>{window.open('/tutorial/complete/index.html','_blank','noopener');}),separator,
|
||||
menuAction('导出诊断报告',exportDiagnosticReport,diagnostics.length===0),menuAction('关于 Web Blender',()=>setHeaderDialog('about'))]
|
||||
};
|
||||
@@ -9656,7 +9668,11 @@ else:
|
||||
{isMeshEdit?<div className="desktop-selection-controls" aria-label="网格选择模式">{(['VERT','EDGE','FACE'] as MeshElementMode[]).map((mode,index)=><button key={mode} type="button" aria-label={['顶点选择','边选择','面选择'][index]} aria-pressed={meshSelection.mode===mode} onClick={()=>setMeshSelectionMode(mode)}>{['•','╱','▣'][index]}</button>)}</div>:null}
|
||||
{localOnly && snapshot ? <span aria-label="工作区显示"><button type="button" aria-pressed={gpuSurfaceOpen} onClick={()=>{if(discardTextDraft())setGPUSurfaceOpen(true);}}>Blender 桌面</button><button type="button" aria-pressed={!gpuSurfaceOpen} onClick={()=>{cancelNativeGesture();localInvokeAbortRef.current?.abort();setLocalInvokePending(null);setLocalRetryPending(null);setGPUSurfaceOpen(false);}}>Web 业务工具</button></span> : null}
|
||||
<span className="viewport-header-status"><span>{selectedObjectIds.size} selected</span><output data-testid="dirty-status">{saved?'已保存':'未保存'}</output></span>
|
||||
<div className="legacy-quick-toolbar">{uiState.context.mode === "Edit" ? <><div className="segmented" aria-label="网格选择模式">{(["VERT", "EDGE", "FACE"] as MeshElementMode[]).map((mode) => <button key={mode} type="button" className={meshSelection.mode === mode ? "active" : ""} onClick={() => setMeshSelectionMode(mode)}>{mode === "VERT" ? "1 Vertex" : mode === "EDGE" ? "2 Edge" : "3 Face"}</button>)}</div><button type="button" onClick={selectAllMeshElements}>Select All</button>{(["MERGE", "DISSOLVE", "EXTRUDE", "INSET", "BEVEL", "LOOP_CUT", "SUBDIVIDE", "FILL", "TRIANGULATE", "RECALCULATE_NORMALS", "BRIDGE_LOOPS", "DELETE"] as MeshEditOperation[]).map((operation) => <button key={operation} type="button" disabled={meshSelection.indices.size === 0 || (["TRIANGULATE", "RECALCULATE_NORMALS"].includes(operation) && meshSelection.mode !== "FACE") || (operation === "BRIDGE_LOOPS" && meshSelection.mode !== "EDGE") || (operation === "SUBDIVIDE" && meshSelection.mode === "VERT")} onClick={() => runMeshEdit(operation)}>{operation.replaceAll("_", " ")}</button>)}<button type="button" disabled={meshSelection.mode !== "FACE" || meshSelection.indices.size === 0 || !snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "separateMeshFaces", objectId: snapshot.activeObjectId, faceIndices: [...meshSelection.indices], name: "Separated" })}>Separate</button></> : <>{(["CUBE", "PLANE", "UV_SPHERE", "ICO_SPHERE", "CYLINDER", "CONE", "TORUS"] as MeshPrimitive[]).map((primitive) => <button key={primitive} type="button" aria-label={primitive === "CUBE" ? "添加立方体" : `添加 ${primitive.toLowerCase().replaceAll("_", " ")}`} onClick={() => void applyEditCommand(coreSceneCommands.createPrimitive(primitive))}>Add {primitive.replaceAll("_", " ")}</button>)}<button type="button" onClick={()=>void invokeNativeOperator('mesh.primitive_circle_add')}>Add Circle</button><button type="button" onClick={()=>void invokeNativeOperator('mesh.primitive_grid_add')}>Add Grid</button><button type="button" onClick={()=>void invokeNativeOperator('mesh.primitive_monkey_add')}>Add Monkey</button><button type="button" aria-label="复制对象" disabled={!snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "duplicateObject", objectId: snapshot.activeObjectId, offset: [0.25, 0.25, 0] })}>Duplicate</button><button type="button" aria-label="链接复制对象" disabled={!snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "duplicateObject", objectId: snapshot.activeObjectId, offset: [0.5, 0.5, 0], linked: true })}>Linked Duplicate</button><button type="button" aria-label="删除对象" disabled={!snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "deleteObject", objectId: snapshot.activeObjectId })}>Delete</button><button type="button" disabled={selectedObjectIds.size < 2 || !snapshot?.activeObjectId || !selectedObjectIds.has(snapshot.activeObjectId)} onClick={() => parentSelectedObjects(false)} title="以活动对象为父级,保持所选对象的变换">Parent</button><button type="button" disabled={selectedObjectIds.size === 0} onClick={() => parentSelectedObjects(true)}>Unparent</button><button type="button" disabled={selectedObjectIds.size < 2 || !snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "joinObjects", activeObjectId: snapshot.activeObjectId, objectIds: [...selectedObjectIds] })}>Join</button><button type="button" onClick={() => void applyEditCommand({ type: "createCollection", name: `Collection ${(snapshot?.collections.length ?? 0) + 1}` })}>New Collection</button></>}</div>
|
||||
{quickToolsCollapsed?<button type="button" className="quick-toolbar-reopen" aria-label="展开快捷操作栏" title="展开快捷操作栏" onClick={()=>setQuickToolsCollapsed(false)}>⠿ 快捷操作</button>:null}
|
||||
<div className={quickToolbarDrag.offset.x!==0||quickToolbarDrag.offset.y!==0?"legacy-quick-toolbar is-floating":"legacy-quick-toolbar"} data-draggable-panel="quick-toolbar" data-quick-toolbar-floating={quickToolbarDrag.offset.x!==0||quickToolbarDrag.offset.y!==0?"true":"false"} data-panel-offset={`${quickToolbarDrag.offset.x},${quickToolbarDrag.offset.y}`} data-quick-tools-collapsed={quickToolsCollapsed?"true":"false"} style={{transform:`translate(${quickToolbarDrag.offset.x}px, ${quickToolbarDrag.offset.y}px)`}} {...quickToolbarDrag.handle}>
|
||||
<span className="quick-toolbar-grip" aria-hidden="true">⠿</span>{uiState.context.mode === "Edit" ? <><div className="segmented" aria-label="网格选择模式">{(["VERT", "EDGE", "FACE"] as MeshElementMode[]).map((mode) => <button key={mode} type="button" className={meshSelection.mode === mode ? "active" : ""} onClick={() => setMeshSelectionMode(mode)}>{mode === "VERT" ? "1 Vertex" : mode === "EDGE" ? "2 Edge" : "3 Face"}</button>)}</div><button type="button" onClick={selectAllMeshElements}>Select All</button>{(["MERGE", "DISSOLVE", "EXTRUDE", "INSET", "BEVEL", "LOOP_CUT", "SUBDIVIDE", "FILL", "TRIANGULATE", "RECALCULATE_NORMALS", "BRIDGE_LOOPS", "DELETE"] as MeshEditOperation[]).map((operation) => <button key={operation} type="button" disabled={meshSelection.indices.size === 0 || (["TRIANGULATE", "RECALCULATE_NORMALS"].includes(operation) && meshSelection.mode !== "FACE") || (operation === "BRIDGE_LOOPS" && meshSelection.mode !== "EDGE") || (operation === "SUBDIVIDE" && meshSelection.mode === "VERT")} onClick={() => runMeshEdit(operation)}>{operation.replaceAll("_", " ")}</button>)}<button type="button" disabled={meshSelection.mode !== "FACE" || meshSelection.indices.size === 0 || !snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "separateMeshFaces", objectId: snapshot.activeObjectId, faceIndices: [...meshSelection.indices], name: "Separated" })}>Separate</button></> : <>{(["CUBE", "PLANE", "UV_SPHERE", "ICO_SPHERE", "CYLINDER", "CONE", "TORUS"] as MeshPrimitive[]).map((primitive) => <button key={primitive} type="button" aria-label={primitive === "CUBE" ? "添加立方体" : `添加 ${primitive.toLowerCase().replaceAll("_", " ")}`} onClick={() => void applyEditCommand(coreSceneCommands.createPrimitive(primitive))}>Add {primitive.replaceAll("_", " ")}</button>)}<button type="button" onClick={()=>void invokeNativeOperator('mesh.primitive_circle_add')}>Add Circle</button><button type="button" onClick={()=>void invokeNativeOperator('mesh.primitive_grid_add')}>Add Grid</button><button type="button" onClick={()=>void invokeNativeOperator('mesh.primitive_monkey_add')}>Add Monkey</button><button type="button" aria-label="复制对象" disabled={!snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "duplicateObject", objectId: snapshot.activeObjectId, offset: [0.25, 0.25, 0] })}>Duplicate</button><button type="button" aria-label="链接复制对象" disabled={!snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "duplicateObject", objectId: snapshot.activeObjectId, offset: [0.5, 0.5, 0], linked: true })}>Linked Duplicate</button><button type="button" aria-label="删除对象" disabled={!snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "deleteObject", objectId: snapshot.activeObjectId })}>Delete</button><button type="button" disabled={selectedObjectIds.size < 2 || !snapshot?.activeObjectId || !selectedObjectIds.has(snapshot.activeObjectId)} onClick={() => parentSelectedObjects(false)} title="以活动对象为父级,保持所选对象的变换">Parent</button><button type="button" disabled={selectedObjectIds.size === 0} onClick={() => parentSelectedObjects(true)}>Unparent</button><button type="button" disabled={selectedObjectIds.size < 2 || !snapshot?.activeObjectId} onClick={() => snapshot?.activeObjectId && void applyEditCommand({ type: "joinObjects", activeObjectId: snapshot.activeObjectId, objectIds: [...selectedObjectIds] })}>Join</button><button type="button" onClick={() => void applyEditCommand({ type: "createCollection", name: `Collection ${(snapshot?.collections.length ?? 0) + 1}` })}>New Collection</button></>}
|
||||
<span className="quick-toolbar-actions"><button type="button" aria-label="复位快捷操作栏位置" title="复位快捷操作栏位置" disabled={quickToolbarDrag.offset.x===0&&quickToolbarDrag.offset.y===0} onClick={quickToolbarDrag.reset}>⌖</button><button type="button" aria-label="折叠快捷操作栏" title="折叠快捷操作栏" onClick={()=>setQuickToolsCollapsed(true)}>‹</button></span>
|
||||
</div>
|
||||
</div>
|
||||
{failedNativeFiles.length > 0 && <aside aria-label="待完成文件" style={{ position:'fixed', right:12, bottom:36, zIndex:40, maxWidth:420, maxHeight:'40vh', overflowY:'auto', padding:12, background:'#303030', color:'#eee', border:'1px solid #666' }}>
|
||||
<strong>文件交付未完成</strong>
|
||||
@@ -9864,10 +9880,10 @@ else:
|
||||
}}/>:null}
|
||||
{interactiveDesktop?<section className="native-desktop-dialog" role="dialog" aria-modal="true" aria-label="Native Blender Desktop"><header><strong>Native Blender</strong><button aria-label="Close native desktop" onClick={()=>{setInteractiveDesktop(null);activeViewportCanvas()?.focus({preventScroll:true});}}>×</button></header><NativeSessionPanel desktop client={webClientRef.current} context={interactiveDesktop.context} initialOperator={interactiveDesktop.command} onApplied={(scene)=>{applyNativeScene(scene);setInteractiveDesktop(null);activeViewportCanvas()?.focus({preventScroll:true});}} onCommandStatus={(status)=>{if(status==='CANCELLED'||status==='FAILED'){activeViewportCanvas()?.focus({preventScroll:true});setEngineStatus(status==='CANCELLED'?'Native Blender command cancelled':'Native Blender command failed');const client=webClientRef.current,project=projectIdRef.current;if(client)void client.snapshot().then(result=>{if(client!==webClientRef.current||project!==projectIdRef.current)return;const changed=result.snapshot.revision!==snapshot?.revision;applyNativeScene(result,changed);const recoveryRevision=projectRevisionRef.current;if(changed)void persistRecoveryCheckpoint(client,project,recoveryRevision).catch(error=>{if(client===webClientRef.current&&project===projectIdRef.current&&recoveryRevision===projectRevisionRef.current)setStorageStatus(recordDiagnostic("STORAGE","OPERATION_LOG_FAILED",error,{command:"native-session-recovery",recovery:"checkpoint"}));});}).catch(error=>{if(client===webClientRef.current&&project===projectIdRef.current)setEngineStatus(recordDiagnostic("ENGINE","COMMAND_FAILED",error,{workflow:"native-session-recovery",recovery:"snapshot"}));});}}}/></section>:null}
|
||||
<footer className="status-bar"><span className="status-hint">LMB Select · MMB Rotate View · Wheel Zoom</span><span data-testid="scene-stats">Active {snapshot?.nodes.find(node => node.id === snapshot?.activeObjectId)?.name ?? '—'} · Objects {objectCount} · Vertices {vertexCount} · Faces {faceCount}</span>{openProgress ? <span className="open-progress" data-testid="open-progress" data-phase={openProgress.phase} data-stage={openProgress.stage} data-cancellable={openProgress.cancellable} data-bytes-read={openProgress.bytesRead} data-total-bytes={openProgress.totalBytes}><progress aria-label="打开文件进度" max={(openProgress.totalBytes ?? 0) > 0 ? openProgress.totalBytes : 1} value={openProgress.bytesRead ?? openProgress.fraction ?? 0} /><span>{openProgress.message ?? "Opening"}</span>{canCancelOpenRead ? <button type="button" aria-label="取消打开" title="取消打开" onClick={cancelOpenFileRead}>×</button> : null}</span> : null}<span className="status-spacer" /><span className="runtime-status">{manifestStatus}</span><span className="runtime-status" data-testid="wasm-status">{wasmStatus}</span><span className="runtime-status" data-testid="engine-status" title={displayedEngineStatus}>{displayedEngineStatus}</span>{localInvokePending || localInvokeActive ? <button type="button" disabled={typeof SharedArrayBuffer === 'undefined' || !globalThis.crossOriginIsolated} data-testid="native-invoke-cancel" aria-label="取消原生操作" title={`取消 ${localInvokePending?.command.operator ?? '当前操作'}`} onClick={() => { localInvokeAbortRef.current?.abort(); activeViewportCanvas()?.dispatchEvent(new Event('native-cancel')); setLocalInvokePending(null); setLocalRetryPending(null); activeViewportCanvas()?.focus({ preventScroll: true }); setEngineStatus('已请求取消原生操作'); }}>取消原生操作</button> : null}{localRetryPending ? <button type="button" data-testid="native-retry" aria-label="重试原生操作" title={`重试 ${localRetryPending.command.operator}`} onClick={() => { const retry = localRetryPending; setLocalRetryPending(null); setLocalInvokePending(retry); setGPUSurfaceOpen(true); }}>{`重试 ${localRetryPending.command.operator}`}</button> : null}<span className="runtime-status">{storageStatus}</span><StorageBudgetPanel budget={storageBudget} onCleanup={() => void cleanupProjectAssets()} />{webPreferences.interface.statusbarVersion ? <span className="blender-version">5.2.0 LTS</span> : null}</footer>
|
||||
{createPortal(lastNativeOperator ? <section className="last-operator-panel" aria-label="调整上一步操作">
|
||||
{createPortal(lastNativeOperator ? <section className="last-operator-panel" aria-label="调整上一步操作" data-draggable-panel="last-operator" data-panel-offset={`${lastOperatorDrag.offset.x},${lastOperatorDrag.offset.y}`} style={{transform:`translate(${lastOperatorDrag.offset.x}px, ${lastOperatorDrag.offset.y}px)`}} {...lastOperatorDrag.handle}>
|
||||
{!lastOperatorOpen ? <button type="button" aria-label="调整上一步操作" onClick={() => openAdjustLastOperation()}>调整上一步操作<small>{lastNativeOperator.operator}</small></button>
|
||||
: <form onSubmit={(event) => { event.preventDefault(); void applyAdjustedLastOperation(); }}>
|
||||
<header><strong>调整上一步操作</strong><button type="button" aria-label="关闭调整面板" onClick={() => setLastOperatorOpen(false)}>×</button></header>
|
||||
<header><strong><span aria-hidden="true">⠿</span> 调整上一步操作</strong><button type="button" aria-label="复位调整面板位置" title="复位位置" disabled={lastOperatorDrag.offset.x===0&&lastOperatorDrag.offset.y===0} onClick={lastOperatorDrag.reset}>⌖</button><button type="button" aria-label="关闭调整面板" onClick={() => setLastOperatorOpen(false)}>×</button></header>
|
||||
<small>{lastNativeOperator.operator}</small>
|
||||
{lastOperatorSchema === null ? <p>正在读取原生属性…</p> : lastOperatorSchema.length === 0 ? <p>此操作没有可调属性。</p> : lastOperatorSchema.map((property) => renderAdjustProperty(property))}
|
||||
{lastOperatorError ? <p role="alert">{lastOperatorError}</p> : null}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.desktop-menu-trigger{display:inline-flex;flex:none;position:relative}.desktop-menu-trigger>button{min-height:24px;padding:3px 7px;background:transparent;color:#d3d3d3;white-space:nowrap;border-radius:2px}.desktop-menu-trigger>button[aria-expanded=true]{background:#454545}.desktop-menu-panel{position:fixed;z-index:1500;width:280px;max-width:calc(100vw - 8px);padding:5px;background:#282b2a;color:#e0e3e1;border:1px solid #656b67;box-shadow:0 7px 20px #0007;border-radius:4px;overflow:auto}.desktop-menu-panel>button{display:flex;position:relative;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:7px;width:100%;min-height:28px;text-align:left;padding:5px 9px;color:inherit;background:transparent;border:0;border-radius:2px;font-size:12px}.desktop-menu-panel>button:hover:enabled,.desktop-menu-panel>button:focus-visible{background:#44644f;color:white;outline:1px solid #bdd7c4}.desktop-menu-panel>button:disabled{color:#949c96;cursor:default}.desktop-menu-panel small{display:block;flex-basis:100%;font-size:10px;color:#a7b1a9;white-space:normal;line-height:1.4}.desktop-menu-shortcut{color:#b2beb5;font-size:10px}.desktop-menu-panel [role=separator]{height:1px;background:#49514b;margin:5px 3px}.desktop-menu-back{border-bottom:1px solid #657268!important;margin-bottom:4px}.desktop-header-menus{display:flex;align-items:center;min-width:0;gap:1px}.desktop-selection-controls{display:flex;align-items:center;gap:3px;margin-left:8px}.desktop-header-label{color:#cbd4ce;min-width:0;overflow:hidden;text-overflow:ellipsis;font-size:11px}.desktop-dialog-backdrop{position:fixed;inset:0;z-index:1600;background:#0006;display:flex;align-items:center;justify-content:center;padding:14px}.desktop-dialog{background:#292d2a;border:1px solid #87948b;border-radius:5px;width:440px;max-width:100%;max-height:90vh;overflow:auto;padding:14px;color:#e3e8e4}.desktop-dialog header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.desktop-dialog h2{font-size:16px;margin:0}.desktop-dialog button{padding:6px 11px;color:inherit;background:#49534c;border:1px solid #7c8b81;border-radius:3px}.desktop-dialog header button{padding:2px;width:27px;height:27px}.desktop-dialog input:not([type=checkbox]){width:100%;padding:7px;background:#1e211f;border:1px solid #6d7c72;color:inherit}.desktop-dialog p{font-size:12px;line-height:1.7}.desktop-dialog-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:15px}.desktop-dialog label{display:flex;gap:8px;align-items:center;margin:12px 0}.workspace-toolbar{overflow:visible}.desktop-header-actions{display:flex;min-width:0;align-items:center;overflow-x:auto;scrollbar-width:none}.legacy-quick-toolbar{display:none}.blender-app[data-quick-tools=true] .legacy-quick-toolbar{display:flex;position:absolute;top:100%;left:0;right:0;z-index:10;background:#303532;overflow-x:auto;gap:4px;padding:4px}.legacy-quick-toolbar>button{white-space:nowrap;min-height:27px;padding:3px 7px;background:#414942}.blender-app[data-hide-status=true] .status-bar{display:none}.blender-app[data-hide-status=true]{grid-template-rows:28px 30px minmax(0,1fr) 0}.workspace-menu-control{flex:none}.workspace-tabs{min-width:90px}.workspace-tabs .workspace-menu-control{position:sticky;right:0;background:#222}.viewport-header-status{margin-left:auto;display:flex;align-items:center;gap:12px;font-size:11px;white-space:nowrap;padding-right:8px}.topbar-actions .extension-robot{color:#bbd4c3}
|
||||
.desktop-menu-trigger{display:inline-flex;flex:none;position:relative}.desktop-menu-trigger>button{min-height:24px;padding:3px 7px;background:transparent;color:#d3d3d3;white-space:nowrap;border-radius:2px}.desktop-menu-trigger>button[aria-expanded=true]{background:#454545}.desktop-menu-panel{position:fixed;z-index:1500;width:280px;max-width:calc(100vw - 8px);padding:5px;background:#282b2a;color:#e0e3e1;border:1px solid #656b67;box-shadow:0 7px 20px #0007;border-radius:4px;overflow:auto}.desktop-menu-panel>button{display:flex;position:relative;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:7px;width:100%;min-height:28px;text-align:left;padding:5px 9px;color:inherit;background:transparent;border:0;border-radius:2px;font-size:12px}.desktop-menu-panel>button:hover:enabled,.desktop-menu-panel>button:focus-visible{background:#44644f;color:white;outline:1px solid #bdd7c4}.desktop-menu-panel>button:disabled{color:#949c96;cursor:default}.desktop-menu-panel small{display:block;flex-basis:100%;font-size:10px;color:#a7b1a9;white-space:normal;line-height:1.4}.desktop-menu-shortcut{color:#b2beb5;font-size:10px}.desktop-menu-panel [role=separator]{height:1px;background:#49514b;margin:5px 3px}.desktop-menu-back{border-bottom:1px solid #657268!important;margin-bottom:4px}.desktop-header-menus{display:flex;align-items:center;min-width:0;gap:1px}.desktop-selection-controls{display:flex;align-items:center;gap:3px;margin-left:8px}.desktop-header-label{color:#cbd4ce;min-width:0;overflow:hidden;text-overflow:ellipsis;font-size:11px}.desktop-dialog-backdrop{position:fixed;inset:0;z-index:1600;background:#0006;display:flex;align-items:center;justify-content:center;padding:14px}.desktop-dialog{background:#292d2a;border:1px solid #87948b;border-radius:5px;width:440px;max-width:100%;max-height:90vh;overflow:auto;padding:14px;color:#e3e8e4}.desktop-dialog header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.desktop-dialog h2{font-size:16px;margin:0}.desktop-dialog button{padding:6px 11px;color:inherit;background:#49534c;border:1px solid #7c8b81;border-radius:3px}.desktop-dialog header button{padding:2px;width:27px;height:27px}.desktop-dialog input:not([type=checkbox]){width:100%;padding:7px;background:#1e211f;border:1px solid #6d7c72;color:inherit}.desktop-dialog p{font-size:12px;line-height:1.7}.desktop-dialog-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:15px}.desktop-dialog label{display:flex;gap:8px;align-items:center;margin:12px 0}.workspace-toolbar{overflow:visible}.desktop-header-actions{display:flex;min-width:0;align-items:center;overflow-x:auto;scrollbar-width:none}.legacy-quick-toolbar{display:none}.blender-app[data-quick-tools=true] .legacy-quick-toolbar{display:flex;align-items:center;position:absolute;top:100%;left:0;right:0;z-index:10;background:#303532;overflow-x:auto;gap:4px;padding:4px;touch-action:none;user-select:none}.legacy-quick-toolbar[data-quick-tools-collapsed=true]{display:none!important}.legacy-quick-toolbar .quick-toolbar-grip{flex:none;color:#8d968f;padding:0 2px;cursor:grab;letter-spacing:-1px}.legacy-quick-toolbar.is-floating{position:fixed;top:58px;left:0;right:auto;width:max-content;max-width:calc(100vw - 16px);z-index:55;border:1px solid #4b554d;border-radius:6px;box-shadow:0 10px 28px #0007;cursor:grab}.legacy-quick-toolbar.is-floating:active{cursor:grabbing}.legacy-quick-toolbar .quick-toolbar-actions{display:flex;flex:none;align-items:center;gap:2px;margin-left:auto;padding-left:4px}.legacy-quick-toolbar .quick-toolbar-actions>button{cursor:pointer;min-height:27px;padding:3px 7px;background:#414942}.legacy-quick-toolbar .quick-toolbar-actions>button:disabled{opacity:.4;cursor:default}.quick-toolbar-reopen{position:absolute;top:100%;left:0;z-index:11;background:#303532;color:#d3d3d3;border:1px solid #4b554d;border-radius:0 0 4px 4px;padding:3px 8px;font-size:11px;cursor:pointer}.legacy-quick-toolbar>button{white-space:nowrap;min-height:27px;padding:3px 7px;background:#414942}.blender-app[data-hide-status=true] .status-bar{display:none}.blender-app[data-hide-status=true]{grid-template-rows:28px 30px minmax(0,1fr) 0}.workspace-menu-control{flex:none}.workspace-tabs{min-width:90px}.workspace-tabs .workspace-menu-control{position:sticky;right:0;background:#222}.viewport-header-status{margin-left:auto;display:flex;align-items:center;gap:12px;font-size:11px;white-space:nowrap;padding-right:8px}.topbar-actions .extension-robot{color:#bbd4c3}
|
||||
@media(max-width:700px){.desktop-header-label{display:none}.viewport-header-status{gap:3px;font-size:10px}.desktop-selection-controls{margin-left:0}.desktop-header-menus{max-width:100%;overflow-x:auto;scrollbar-width:none}}
|
||||
@media(max-width:900px){.topbar .menu-bar{display:flex}.topbar .menu-bar button{padding-inline:5px}.topbar-actions>select,.topbar-actions>.topbar-context,.topbar-actions>.extension-robot{display:none}.workspace-tabs .workspace-tab:nth-child(n+4){display:initial}.workspace-tabs .workspace-tab{flex:none}.workspace-tabs{min-width:40px}.workspace-menu-control>button{font-size:0;width:26px;padding:3px}.workspace-menu-control>button::after{content:'▾';font-size:14px}}
|
||||
@media(max-width:550px){.topbar-actions{display:none}.workspace-tabs{min-width:48px}.brand{padding:0}.topbar .menu-bar button{padding-inline:4px;font-size:11px}}
|
||||
|
||||
162
web/app/src/app/use-draggable-panel.ts
Normal file
162
web/app/src/app/use-draggable-panel.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
|
||||
|
||||
/**
|
||||
* Draggable floating panels.
|
||||
*
|
||||
* Every overlay that covers the 3D viewport (tutorial steps, quick toolbar,
|
||||
* adjust-last-operation, robot tool) can be moved out of the way. Positions are
|
||||
* a browser comfort setting, not project data: they live in one localStorage
|
||||
* map, the same place the tutorial panel already kept its offset. Project files
|
||||
* stay OPFS-only.
|
||||
*/
|
||||
const OFFSET_KEY = "web-blender.panel-offsets.v1";
|
||||
/** Pre-existing key for the tutorial panel; migrated on first read. */
|
||||
const LEGACY_TUTORIAL_KEY = "web-blender.tutorial-panel-offset.v1";
|
||||
export const PANEL_OFFSETS_RESET_EVENT = "web-blender:panel-offsets-reset";
|
||||
|
||||
export interface PanelOffset { x: number; y: number }
|
||||
|
||||
type OffsetMap = Record<string, PanelOffset>;
|
||||
|
||||
function isOffset(value: unknown): value is PanelOffset {
|
||||
const candidate = value as PanelOffset | null;
|
||||
return Boolean(candidate) && typeof candidate?.x === "number" && typeof candidate?.y === "number" &&
|
||||
Number.isFinite(candidate.x) && Number.isFinite(candidate.y);
|
||||
}
|
||||
|
||||
function readMap(): OffsetMap {
|
||||
try {
|
||||
const raw = JSON.parse(window.localStorage.getItem(OFFSET_KEY) ?? "null") as unknown;
|
||||
if (!raw || typeof raw !== "object") return {};
|
||||
const map: OffsetMap = {};
|
||||
for (const [id, value] of Object.entries(raw as Record<string, unknown>)) if (isOffset(value)) map[id] = value;
|
||||
return map;
|
||||
}
|
||||
catch { return {}; }
|
||||
}
|
||||
|
||||
function writeMap(map: OffsetMap): void {
|
||||
try { window.localStorage.setItem(OFFSET_KEY, JSON.stringify(map)); }
|
||||
catch { /* A read-only profile keeps the drag for this page only. */ }
|
||||
}
|
||||
|
||||
export function readPanelOffset(id: string, fallback: PanelOffset = { x: 0, y: 0 }): PanelOffset {
|
||||
const map = readMap();
|
||||
if (map[id]) return map[id];
|
||||
if (id === "tutorial") {
|
||||
try {
|
||||
const legacy = JSON.parse(window.localStorage.getItem(LEGACY_TUTORIAL_KEY) ?? "null") as unknown;
|
||||
if (isOffset(legacy)) {
|
||||
map[id] = legacy;
|
||||
writeMap(map);
|
||||
window.localStorage.removeItem(LEGACY_TUTORIAL_KEY);
|
||||
return legacy;
|
||||
}
|
||||
}
|
||||
catch { /* ignore a corrupt legacy entry */ }
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function writePanelOffset(id: string, offset: PanelOffset): void {
|
||||
const map = readMap();
|
||||
map[id] = offset;
|
||||
writeMap(map);
|
||||
}
|
||||
|
||||
/** Clear every remembered panel position (窗口 → 恢复默认面板位置). */
|
||||
export function resetAllPanelOffsets(): void {
|
||||
try {
|
||||
window.localStorage.removeItem(OFFSET_KEY);
|
||||
window.localStorage.removeItem(LEGACY_TUTORIAL_KEY);
|
||||
}
|
||||
catch { /* nothing to clear */ }
|
||||
window.dispatchEvent(new CustomEvent(PANEL_OFFSETS_RESET_EVENT));
|
||||
}
|
||||
|
||||
export function useDraggablePanel(id: string, options: { defaultOffset?: PanelOffset } = {}) {
|
||||
const [offset, setOffset] = useState<PanelOffset>(() => readPanelOffset(id, options.defaultOffset ?? { x: 0, y: 0 }));
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const offsetRef = useRef(offset);
|
||||
const dragRef = useRef<{ pointerId: number; startX: number; startY: number; originX: number; originY: number } | null>(null);
|
||||
const panelRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
const commit = useCallback((next: PanelOffset) => {
|
||||
offsetRef.current = next;
|
||||
setOffset(next);
|
||||
writePanelOffset(id, next);
|
||||
}, [id]);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
dragRef.current = null;
|
||||
setDragging(false);
|
||||
commit({ x: 0, y: 0 });
|
||||
}, [commit]);
|
||||
|
||||
/* Another panel's reset (or the menu action) resets this panel too. */
|
||||
useEffect(() => {
|
||||
const onReset = () => reset();
|
||||
window.addEventListener(PANEL_OFFSETS_RESET_EVENT, onReset);
|
||||
return () => window.removeEventListener(PANEL_OFFSETS_RESET_EVENT, onReset);
|
||||
}, [reset]);
|
||||
|
||||
/* A saved offset is honoured as-is; only a panel whose handle ended up
|
||||
* completely outside the window is pulled back, e.g. after a resize. */
|
||||
useEffect(() => {
|
||||
const handle = panelRef.current?.querySelector("[data-draggable-handle]");
|
||||
if (!(handle instanceof HTMLElement)) return;
|
||||
const rect = handle.getBoundingClientRect();
|
||||
const visible = rect.bottom > 0 && rect.top < window.innerHeight && rect.right > 0 && rect.left < window.innerWidth;
|
||||
if (!visible && (offsetRef.current.x !== 0 || offsetRef.current.y !== 0)) reset();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const panelOf = (event: ReactPointerEvent<HTMLElement>): HTMLElement | null => {
|
||||
const handle = event.currentTarget;
|
||||
const closest = handle.closest("[data-draggable-panel]");
|
||||
return closest instanceof HTMLElement ? closest : panelRef.current;
|
||||
};
|
||||
|
||||
const handle = {
|
||||
"data-draggable-handle": "",
|
||||
onPointerDown: (event: ReactPointerEvent<HTMLElement>) => {
|
||||
/* Never start a drag from a button inside the handle. */
|
||||
if ((event.target as HTMLElement).closest("button")) return;
|
||||
if (event.button !== 0) return;
|
||||
const panel = panelOf(event);
|
||||
if (panel?.dataset.draggableDisabled === "true") return;
|
||||
dragRef.current = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, originX: offsetRef.current.x, originY: offsetRef.current.y };
|
||||
setDragging(true);
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
},
|
||||
onPointerMove: (event: ReactPointerEvent<HTMLElement>) => {
|
||||
const drag = dragRef.current;
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
const panel = panelOf(event);
|
||||
if (!panel) return;
|
||||
const rect = panel.getBoundingClientRect();
|
||||
const current = offsetRef.current;
|
||||
const wantedLeft = rect.left + (drag.originX + event.clientX - drag.startX - current.x);
|
||||
const wantedTop = rect.top + (drag.originY + event.clientY - drag.startY - current.y);
|
||||
/* Keep the handle grabbable: at least half the panel width (capped) and
|
||||
* 160px of handle stay on screen, and the handle never leaves the window. */
|
||||
const left = Math.min(Math.max(wantedLeft, 8 - rect.width * 0.5), window.innerWidth - 160);
|
||||
const top = Math.min(Math.max(wantedTop, -48), window.innerHeight - 60);
|
||||
commit({ x: Math.round(current.x + left - rect.left), y: Math.round(current.y + top - rect.top) });
|
||||
},
|
||||
onPointerUp: (event: ReactPointerEvent<HTMLElement>) => {
|
||||
if (dragRef.current?.pointerId !== event.pointerId) return;
|
||||
dragRef.current = null;
|
||||
setDragging(false);
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
},
|
||||
onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => {
|
||||
if (dragRef.current?.pointerId !== event.pointerId) return;
|
||||
dragRef.current = null;
|
||||
setDragging(false);
|
||||
},
|
||||
onDoubleClick: () => reset(),
|
||||
};
|
||||
|
||||
return { offset, dragging, panelRef, handle, commit, reset };
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {sha256Hex} from '../../../protocol/render-assets';
|
||||
import {exportGLB} from '../../../protocol/glb-export';
|
||||
import {parseRobotURDF,resolveRobotFiles,type RobotModel} from './urdf';
|
||||
import workflow from './robot-workflow.py?raw';
|
||||
import {useDraggablePanel} from '../app/use-draggable-panel';
|
||||
|
||||
interface Result {schemaVersion:1;model:RobotModel;assembled:boolean;angles:Record<string,number>;checks:{name:string;status:string;stepRadians:number;maxWorldDelta:number;descendants:number}[];objects:string[];matrices:Record<string,{parent:string|null;local:number[];world:number[]}>}
|
||||
type Applied=Awaited<ReturnType<WebEngineClient['applyServerBlendResult']>>;
|
||||
@@ -18,6 +19,8 @@ export function RobotTool({client,snapshot,onApplied,onStart,onSave,onClose}:Pro
|
||||
const [result,setResult]=useState<Result|null>(null),[angles,setAngles]=useState<Record<string,number>>({}),[error,setError]=useState(''),[status,setStatus]=useState('等待输入');
|
||||
const [busy,setBusy]=useState(false),[ready,setReady]=useState(false),[verified,setVerified]=useState(false),[exports,setExports]=useState<string[]>([]);
|
||||
const currentHash=useRef(''),revision=useRef<number|null>(null),abort=useRef<AbortController|null>(null),mounted=useRef(true),operation=useRef(false),panelRef=useRef<HTMLElement>(null);
|
||||
/* The drawer can be moved away from the model it is driving. */
|
||||
const drag=useDraggablePanel('robot-tool');
|
||||
useEffect(()=>{mounted.current=true;const previous=document.activeElement as HTMLElement|null;panelRef.current?.querySelector<HTMLButtonElement>('button')?.focus();return()=>{mounted.current=false;abort.current?.abort();previous?.focus();};},[]);
|
||||
useEffect(()=>{if(result&&snapshot?.revision!==revision.current){setVerified(false);setStatus('场景已变化,请读取项目机器人');}},[snapshot?.revision,result]);
|
||||
const run=async(fn:()=>Promise<void>)=>{
|
||||
@@ -87,8 +90,8 @@ export function RobotTool({client,snapshot,onApplied,onStart,onSave,onClose}:Pro
|
||||
const controls=Array.from(panelRef.current?.querySelectorAll<HTMLElement>('button:not(:disabled),input:not(:disabled),[tabindex="0"]')??[]).filter(el=>el.getClientRects().length);
|
||||
const first=controls[0],last=controls.at(-1);if(event.shiftKey&&document.activeElement===first){event.preventDefault();last?.focus();}else if(!event.shiftKey&&document.activeElement===last){event.preventDefault();first?.focus();}
|
||||
}}}>
|
||||
<section ref={panelRef} className="robot-tool" role="dialog" aria-modal="true" aria-label="六轴机器人工具">
|
||||
<header><h2>六轴机器人</h2><button aria-label="关闭机器人工具" title="关闭" disabled={busy} onClick={onClose}>×</button></header>
|
||||
<section ref={panelRef} className="robot-tool" role="dialog" aria-modal="true" aria-label="六轴机器人工具" data-draggable-panel="robot-tool" data-panel-offset={`${drag.offset.x},${drag.offset.y}`} style={{transform:`translate(${drag.offset.x}px, ${drag.offset.y}px)`}}>
|
||||
<header {...drag.handle} title="拖动标题栏可移动工具面板,双击复位"><h2><span className="robot-tool-grip" aria-hidden="true">⠿</span> 六轴机器人</h2><button aria-label="复位机器人工具位置" title="复位位置" disabled={drag.offset.x===0&&drag.offset.y===0} onClick={drag.reset}>⌖</button><button aria-label="关闭机器人工具" title="关闭" disabled={busy} onClick={onClose}>×</button></header>
|
||||
<div className="robot-tool-body">
|
||||
<section><h3>1 · 模型与资源</h3><div className="robot-tool-actions"><button disabled={busy} onClick={preset}>加载 ABB IRB120 样例</button><button disabled={busy||!snapshot} onClick={()=>void run(()=>execute('inspect'))}>读取项目机器人</button></div>
|
||||
<label>URDF 文件<input aria-label="机器人 URDF 文件" type="file" accept=".urdf,.xml" disabled={busy} onChange={e=>{const file=e.target.files?.[0];if(file)void run(async()=>{invalidate();setModel(null);const next=parseRobotURDF(await file.text());setModel(next);setStatus('URDF 已读取');});}}/></label>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
.robot-tool-backdrop{position:fixed;inset:0;z-index:1200;background:#0003;display:flex;justify-content:flex-end;padding:36px 12px 16px;box-sizing:border-box}
|
||||
.robot-tool{width:580px;max-width:100%;display:flex;flex-direction:column;min-height:0;background:#252827;color:#e4e8e5;border:1px solid #737b76;box-shadow:0 8px 25px #0005}
|
||||
.robot-tool header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #555e58;padding:10px 14px}.robot-tool h2{font-size:17px;margin:0}.robot-tool header button{width:28px;height:28px;padding:0;font-size:20px}
|
||||
/* Transparent, click-through scrim: the 3D scene stays visible and usable while
|
||||
* the drawer is open, so the user can watch the robot react to the tool. */
|
||||
.robot-tool-backdrop{position:fixed;inset:0;z-index:1200;background:transparent;display:flex;justify-content:flex-end;padding:36px 12px 16px;box-sizing:border-box;pointer-events:none}
|
||||
.robot-tool{pointer-events:auto;width:580px;max-width:100%;display:flex;flex-direction:column;min-height:0;background:#252827;color:#e4e8e5;border:1px solid #737b76;box-shadow:0 8px 25px #0005}
|
||||
.robot-tool header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #555e58;padding:10px 14px;cursor:grab;touch-action:none;user-select:none}.robot-tool header:active{cursor:grabbing}.robot-tool-grip{color:#8d968f;letter-spacing:-1px}.robot-tool h2{font-size:17px;margin:0}.robot-tool header button{width:28px;height:28px;padding:0;font-size:20px}.robot-tool header button[disabled]{opacity:.4;cursor:default}
|
||||
.robot-tool-body{overflow:auto;min-height:0;padding:0 14px}.robot-tool-body>section{padding:12px 0;border-bottom:1px solid #4e5550}.robot-tool h3{font-size:13px;margin:0 0 10px;color:#c6dace}.robot-tool label{display:flex;align-items:center;gap:8px;margin:7px 0;font-size:12px;flex-wrap:wrap}.robot-tool input{min-width:0;max-width:100%;color:inherit}.robot-tool input[type=file]{flex:1;min-width:150px;font-size:11px}
|
||||
.robot-tool button{background:#444d47;color:#edf2ee;border:1px solid #78867b;border-radius:3px;padding:6px 9px;cursor:pointer;font-size:12px}.robot-tool button:disabled{opacity:.45;cursor:default}.robot-tool button:hover:enabled{background:#54645a}.robot-tool button:focus-visible,.robot-tool input:focus-visible{outline:2px solid #bfcf79;outline-offset:2px}.robot-tool-actions{display:flex;gap:7px;flex-wrap:wrap;margin:7px 0}
|
||||
.robot-tool-summary{color:#bad5c4;font-size:11px;padding-top:6px}.robot-tool table{width:100%;border-collapse:collapse;font-size:11px;table-layout:fixed}.robot-tool th,.robot-tool td{text-align:left;padding:6px 3px;border-bottom:1px solid #414942;overflow-wrap:anywhere}.robot-tool th:nth-child(2){width:40%}.robot-tool small{display:block;color:#a4b1a8;font-size:10px}
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { TutorialCourse } from "./course";
|
||||
import { sceneHierarchyTree } from "./scene-tree";
|
||||
import { TutorialTreeView } from "./TutorialTreeView";
|
||||
import { useTutorialProgress } from "./parts/usePartsTutorialProgress";
|
||||
import { useDraggablePanel } from "../app/use-draggable-panel";
|
||||
import type { StepCheck, TutorialAction, TutorialApi, TutorialContext, TutorialStep } from "./parts/types";
|
||||
|
||||
function CheckRow({ item }: { item: StepCheck }) {
|
||||
@@ -20,8 +21,6 @@ async function delay(ms: number): Promise<void> {
|
||||
/* A React remount must not re-open the last checkpoint over newer unsaved
|
||||
* edits in the same page session; a real reload resets this module state. */
|
||||
const preparedCourseIds = new Set<string>();
|
||||
/** Where the learner last dragged the panel, as a pixel offset from its CSS home. */
|
||||
const PANEL_OFFSET_KEY = "web-blender.tutorial-panel-offset.v1";
|
||||
|
||||
export function TutorialOverlay({ course, api, context }: { course: TutorialCourse; api: TutorialApi; context: TutorialContext }) {
|
||||
const { progress, hydrated, setCurrentStep, completeStep, recordProject, recordSavedProject, reset, completedRequired } = useTutorialProgress(course);
|
||||
@@ -35,18 +34,8 @@ export function TutorialOverlay({ course, api, context }: { course: TutorialCour
|
||||
const checkpointInFlightRef = useRef(false);
|
||||
/* The panel floats over the real viewport, so the learner must be able to move
|
||||
* it off whatever the current step is demonstrating. Position is page-level
|
||||
* (not per-course): it is a comfort setting, keyed by nothing but the app. */
|
||||
const [offset, setOffset] = useState<{ x: number; y: number }>(() => {
|
||||
try {
|
||||
const raw = JSON.parse(window.localStorage.getItem(PANEL_OFFSET_KEY) ?? "null") as { x?: unknown; y?: unknown } | null;
|
||||
return typeof raw?.x === "number" && typeof raw?.y === "number" && Number.isFinite(raw.x) && Number.isFinite(raw.y)
|
||||
? { x: raw.x, y: raw.y }
|
||||
: { x: 0, y: 0 };
|
||||
}
|
||||
catch { return { x: 0, y: 0 }; }
|
||||
});
|
||||
const dragRef = useRef<{ pointerId: number; startX: number; startY: number; originX: number; originY: number } | null>(null);
|
||||
const panelRef = useRef<HTMLElement | null>(null);
|
||||
* (not per-course) and shared with the other floating panels. */
|
||||
const { offset, dragging, panelRef, handle, reset: resetPosition } = useDraggablePanel("tutorial");
|
||||
/* Everything drawn in this page is clipped to the browser viewport, so a DOM
|
||||
* panel can never sit outside the window. A separate Document PiP window can:
|
||||
* it is a real OS window the learner can park on a second screen while the
|
||||
@@ -149,11 +138,6 @@ export function TutorialOverlay({ course, api, context }: { course: TutorialCour
|
||||
setDemoRunning(false);
|
||||
}
|
||||
};
|
||||
const commitOffset = (next: { x: number; y: number }) => {
|
||||
setOffset(next);
|
||||
try { window.localStorage.setItem(PANEL_OFFSET_KEY, JSON.stringify(next)); }
|
||||
catch { /* A read-only profile keeps the drag for this page only. */ }
|
||||
};
|
||||
/* Pop the panel into its own OS window so it can live outside the browser.
|
||||
* Falls back to a plain popup window on browsers without Document PiP. */
|
||||
const openFloatingWindow = async () => {
|
||||
@@ -190,40 +174,6 @@ export function TutorialOverlay({ course, api, context }: { course: TutorialCour
|
||||
setDemoError(`无法打开独立窗口:${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
};
|
||||
const onHeaderPointerDown = (event: ReactPointerEvent<HTMLElement>) => {
|
||||
/* Never start a drag from the collapse button or a text selection inside the title. */
|
||||
if ((event.target as HTMLElement).closest("button")) return;
|
||||
if (event.button !== 0) return;
|
||||
dragRef.current = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, originX: offset.x, originY: offset.y };
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
};
|
||||
const onHeaderPointerMove = (event: ReactPointerEvent<HTMLElement>) => {
|
||||
const drag = dragRef.current;
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
const panel = event.currentTarget.closest(".parts-tutorial-overlay");
|
||||
if (!(panel instanceof HTMLElement)) return;
|
||||
/* In a floating window the panel fills its own document, so a page-space
|
||||
* offset means nothing; the OS moves the window instead. */
|
||||
if (panel.dataset.tutorialFloating === "true") return;
|
||||
const rect = panel.getBoundingClientRect();
|
||||
/* Free drag, but the header must stay grabbable: it is the only handle, so
|
||||
* every clamp below is expressed in terms of "how much header is on
|
||||
* screen". A DOM panel is clipped at the window edge anyway — to actually
|
||||
* sit outside the browser, use the floating-window button. */
|
||||
const wantedLeft = rect.left + (drag.originX + event.clientX - drag.startX - offset.x);
|
||||
const wantedTop = rect.top + (drag.originY + event.clientY - drag.startY - offset.y);
|
||||
/* Never lose more than half the title, and always keep 160px of header width. */
|
||||
const left = Math.min(Math.max(wantedLeft, 8 - rect.width * 0.5), window.innerWidth - 160);
|
||||
/* Header is ~60px tall: keep at least 12px of it below the top edge and it
|
||||
* fully visible above the bottom edge. */
|
||||
const top = Math.min(Math.max(wantedTop, -48), window.innerHeight - 60);
|
||||
commitOffset({ x: Math.round(offset.x + left - rect.left), y: Math.round(offset.y + top - rect.top) });
|
||||
};
|
||||
const onHeaderPointerUp = (event: ReactPointerEvent<HTMLElement>) => {
|
||||
if (dragRef.current?.pointerId !== event.pointerId) return;
|
||||
dragRef.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
};
|
||||
/* Closing the floating window must bring the panel back into the page; the
|
||||
* `pagehide` listener covers most closes, the poll covers the rest. */
|
||||
useEffect(() => {
|
||||
@@ -237,16 +187,6 @@ export function TutorialOverlay({ course, api, context }: { course: TutorialCour
|
||||
pipWindow.close();
|
||||
setPipWindow(null);
|
||||
}, [collapsed, pipWindow]);
|
||||
/* The drag is deliberately unbounded, so a saved offset is honoured as-is.
|
||||
* Only the very first mount sanity-checks that the header is reachable, in
|
||||
* case the panel was parked outside a window that has since been resized. */
|
||||
useEffect(() => {
|
||||
const header = panelRef.current?.querySelector(".tutorial-head");
|
||||
if (!(header instanceof HTMLElement)) return;
|
||||
const rect = header.getBoundingClientRect();
|
||||
if (rect.bottom > 0 && rect.top < window.innerHeight && rect.right > 0 && rect.left < window.innerWidth) return;
|
||||
commitOffset({ x: 0, y: 0 });
|
||||
}, []);
|
||||
if (collapsed) {
|
||||
return <button type="button" className="tutorial-reopen" aria-label={course.reopenAria} onClick={() => setCollapsed(false)}>
|
||||
<span aria-hidden="true">?</span><span>教程</span>
|
||||
@@ -254,18 +194,14 @@ export function TutorialOverlay({ course, api, context }: { course: TutorialCour
|
||||
</button>;
|
||||
}
|
||||
const isSummary = step.id === course.summaryStepId;
|
||||
const panel = <aside ref={panelRef} className={demoRunning ? "parts-tutorial-overlay is-demoing" : "parts-tutorial-overlay"} aria-label={course.overlayTitle} data-course={course.id} data-tutorial-step={step.id} data-tutorial-ready={ready ? "true" : "false"} data-tutorial-project={projectState} data-tutorial-floating={pipWindow ? "true" : "false"} style={{ transform: `translate(${offset.x}px, ${offset.y}px)` }}>
|
||||
<header className="tutorial-head"
|
||||
onPointerDown={onHeaderPointerDown}
|
||||
onPointerMove={onHeaderPointerMove}
|
||||
onPointerUp={onHeaderPointerUp}
|
||||
onPointerCancel={onHeaderPointerUp}
|
||||
onDoubleClick={() => commitOffset({ x: 0, y: 0 })}
|
||||
title="拖动标题栏可移动面板,双击复位">
|
||||
const panel = <aside ref={panelRef} className={dragging ? "parts-tutorial-overlay is-dragging" : demoRunning ? "parts-tutorial-overlay is-demoing" : "parts-tutorial-overlay"} aria-label={course.overlayTitle} data-draggable-panel="tutorial" data-draggable-disabled={pipWindow ? "true" : "false"} data-course={course.id} data-tutorial-step={step.id} data-tutorial-ready={ready ? "true" : "false"} data-tutorial-project={projectState} data-tutorial-floating={pipWindow ? "true" : "false"} data-panel-offset={`${offset.x},${offset.y}`} style={{ transform: `translate(${offset.x}px, ${offset.y}px)` }}>
|
||||
<header className="tutorial-head" {...handle} title="拖动标题栏可移动面板,双击复位">
|
||||
<span className="tutorial-drag-grip" aria-hidden="true">⠿</span>
|
||||
<div>
|
||||
<p className="tutorial-kicker">{isSummary ? "课程完成" : step.chapter}</p>
|
||||
<h2>{step.title}</h2>
|
||||
</div>
|
||||
<button type="button" className="tutorial-icon-button" aria-label="复位教程面板位置" title="复位面板位置" onClick={resetPosition} disabled={offset.x === 0 && offset.y === 0}>⌖</button>
|
||||
<button type="button" className="tutorial-icon-button" aria-label={pipWindow ? "将教程面板收回本页" : "在独立窗口打开教程面板"} title={pipWindow ? "收回本页" : "在独立窗口打开(可拖到浏览器之外、置于另一块屏幕)"} onClick={() => void openFloatingWindow()} data-testid="tutorial-float">{pipWindow ? "⤡" : "⧉"}</button>
|
||||
<button type="button" className="tutorial-icon-button" aria-label="收起教程侧栏" title="收起教程" onClick={() => setCollapsed(true)}>×</button>
|
||||
</header>
|
||||
|
||||
@@ -115,6 +115,11 @@
|
||||
.tutorial-head { display: flex; align-items: start; justify-content: space-between; gap: 12px; padding: 16px 18px 10px; cursor: grab; touch-action: none; user-select: none; }
|
||||
.tutorial-head:active { cursor: grabbing; }
|
||||
.tutorial-head .tutorial-icon-button { cursor: pointer; }
|
||||
/* Visible affordance that the title bar is the drag handle. */
|
||||
.tutorial-drag-grip { flex: none; margin-top: 2px; color: #7c848b; font-size: 15px; line-height: 1; letter-spacing: -1px; }
|
||||
.parts-tutorial-overlay.is-dragging { box-shadow: 0 24px 60px rgba(0, 0, 0, .62); }
|
||||
.parts-tutorial-overlay.is-dragging .tutorial-drag-grip { color: #f28c28; }
|
||||
.tutorial-head .tutorial-icon-button[disabled] { opacity: .35; cursor: default; }
|
||||
/* Inside a floating PiP window the panel is the whole document: drop the
|
||||
* viewport anchoring, let it fill the window, and keep the drag handle. */
|
||||
.parts-tutorial-overlay[data-tutorial-floating="true"] {
|
||||
|
||||
176
web/tests/e2e/wbv2-panel-drag-production.spec.ts
Normal file
176
web/tests/e2e/wbv2-panel-drag-production.spec.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
import { expect, test, type Locator, type Page } from "@playwright/test";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const outputDir = path.join(root, "tests/golden/WEB-PANEL-DRAG-20261123");
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
|
||||
const OFFSET_KEY = "web-blender.panel-offsets.v1";
|
||||
|
||||
async function storedOffsets(page: Page): Promise<Record<string, { x: number; y: number }>> {
|
||||
return page.evaluate((key) => {
|
||||
try { return JSON.parse(window.localStorage.getItem(key) ?? "{}") as Record<string, { x: number; y: number }>; }
|
||||
catch { return {}; }
|
||||
}, OFFSET_KEY);
|
||||
}
|
||||
|
||||
function offsetOf(panel: Locator): Promise<{ x: number; y: number }> {
|
||||
return panel.getAttribute("data-panel-offset").then((value) => {
|
||||
const [x, y] = (value ?? "0,0").split(",").map(Number);
|
||||
return { x, y };
|
||||
});
|
||||
}
|
||||
|
||||
/** Drag `handle` by (dx, dy) with real pointer input. */
|
||||
async function dragBy(page: Page, handle: Locator, dx: number, dy: number): Promise<void> {
|
||||
const box = await handle.boundingBox();
|
||||
expect(box, "drag handle must be laid out").toBeTruthy();
|
||||
const startX = box!.x + Math.min(24, box!.width / 2);
|
||||
const startY = box!.y + box!.height / 2;
|
||||
await page.mouse.move(startX, startY);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(startX + dx / 2, startY + dy / 2, { steps: 4 });
|
||||
await page.mouse.move(startX + dx, startY + dy, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
}
|
||||
|
||||
test("tutorial step panel (PBR Studio Ground) drags, remembers its offset and resets", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/?ui=web&tutorial=pbr&start=1");
|
||||
const panel = page.locator(".parts-tutorial-overlay").first();
|
||||
await expect(panel).toBeVisible({ timeout: 120_000 });
|
||||
await expect(page.locator(".tutorial-drag-grip")).toBeVisible();
|
||||
|
||||
const before = await offsetOf(panel);
|
||||
expect(before).toEqual({ x: 0, y: 0 });
|
||||
|
||||
await dragBy(page, panel.locator("header.tutorial-head"), 160, 120);
|
||||
await expect.poll(async () => (await offsetOf(panel)).x, { timeout: 10_000 }).not.toBe(0);
|
||||
const dragged = await offsetOf(panel);
|
||||
expect(dragged.y).toBeGreaterThan(50);
|
||||
expect((await storedOffsets(page)).tutorial).toEqual(dragged);
|
||||
|
||||
/* A reload must land the panel where the learner parked it. */
|
||||
await page.reload();
|
||||
await expect(panel).toBeVisible({ timeout: 120_000 });
|
||||
expect(await offsetOf(panel)).toEqual(dragged);
|
||||
|
||||
/* The header carries an explicit reset for learners who cannot double-click. */
|
||||
await page.getByLabel("复位教程面板位置").click();
|
||||
await expect.poll(async () => (await offsetOf(panel)).x, { timeout: 10_000 }).toBe(0);
|
||||
expect(await offsetOf(panel)).toEqual({ x: 0, y: 0 });
|
||||
|
||||
/* Double-clicking the header does the same after a fresh drag. */
|
||||
await dragBy(page, panel.locator("header.tutorial-head"), 90, 60);
|
||||
await expect.poll(async () => (await offsetOf(panel)).x, { timeout: 10_000 }).not.toBe(0);
|
||||
await panel.locator("header.tutorial-head").dblclick();
|
||||
await expect.poll(async () => (await offsetOf(panel)).x, { timeout: 10_000 }).toBe(0);
|
||||
|
||||
fs.writeFileSync(path.join(outputDir, "tutorial-panel.json"), JSON.stringify({
|
||||
schemaVersion: 1, browser: "chromium", storage: "OPFS",
|
||||
workflow: "/?ui=web&tutorial=pbr&start=1 -> drag step panel -> reload -> 复位 -> drag -> double-click reset",
|
||||
before, dragged, stored: (await storedOffsets(page)).tutorial ?? null,
|
||||
status: "PASS", acceptance: "NOT_CLAIMED",
|
||||
}, null, 2));
|
||||
});
|
||||
|
||||
test("quick toolbar floats out of the viewport top and can be folded", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/?ui=web");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "tests/files/web/basic_scene.blend"));
|
||||
await expect(page.getByTestId("engine-status")).toContainText(/SceneIR r\d+/, { timeout: 120_000 });
|
||||
|
||||
const bar = page.locator(".legacy-quick-toolbar").first();
|
||||
await expect(bar).toBeVisible({ timeout: 60_000 });
|
||||
await expect(bar).toHaveAttribute("data-quick-toolbar-floating", "false");
|
||||
|
||||
/* Before the drag the bar spans the workspace and covers the viewport top. */
|
||||
const coveredBefore = await page.evaluate(() => {
|
||||
const bar = document.querySelector(".legacy-quick-toolbar");
|
||||
const rect = bar!.getBoundingClientRect();
|
||||
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
|
||||
return Boolean(hit && bar!.contains(hit));
|
||||
});
|
||||
expect(coveredBefore).toBe(true);
|
||||
|
||||
await dragBy(page, bar.locator(".quick-toolbar-grip"), 120, 150);
|
||||
await expect(bar).toHaveAttribute("data-quick-toolbar-floating", "true", { timeout: 10_000 });
|
||||
const offset = await offsetOf(bar);
|
||||
expect(offset.y).toBeGreaterThan(80);
|
||||
expect((await storedOffsets(page))["quick-toolbar"]).toEqual(offset);
|
||||
|
||||
/* Floating, it is a compact bar: the canvas top-centre is no longer the bar. */
|
||||
const coveredAfter = await page.evaluate(() => {
|
||||
const bar = document.querySelector(".legacy-quick-toolbar") as HTMLElement;
|
||||
const rect = bar.getBoundingClientRect();
|
||||
const hit = document.elementFromPoint(window.innerWidth / 2, rect.bottom + 4);
|
||||
return Boolean(hit && bar.contains(hit));
|
||||
});
|
||||
expect(coveredAfter).toBe(false);
|
||||
|
||||
await page.getByLabel("折叠快捷操作栏").click();
|
||||
await expect(bar).toHaveAttribute("data-quick-tools-collapsed", "true");
|
||||
await expect(page.getByLabel("展开快捷操作栏")).toBeVisible();
|
||||
await page.getByLabel("展开快捷操作栏").click();
|
||||
await expect(bar).toHaveAttribute("data-quick-tools-collapsed", "false");
|
||||
|
||||
await page.getByLabel("复位快捷操作栏位置").click();
|
||||
await expect.poll(async () => (await offsetOf(bar)).y, { timeout: 10_000 }).toBe(0);
|
||||
|
||||
fs.writeFileSync(path.join(outputDir, "quick-toolbar.json"), JSON.stringify({
|
||||
schemaVersion: 1, browser: "chromium", storage: "OPFS",
|
||||
workflow: "drag quick toolbar out of the dock -> floating -> fold/unfold -> reset",
|
||||
coveredBefore, coveredAfter, offset,
|
||||
status: "PASS", acceptance: "NOT_CLAIMED",
|
||||
}, null, 2));
|
||||
});
|
||||
|
||||
test("adjust-last-operation and robot tool panels can be moved off the model", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/?ui=web");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "tests/files/web/basic_scene.blend"));
|
||||
await expect(page.getByTestId("engine-status")).toContainText(/SceneIR r\d+/, { timeout: 120_000 });
|
||||
|
||||
/* The quick toolbar's Add Monkey goes through invokeNativeOperator, which is
|
||||
* the path that keeps the operator recorded for 调整上一步操作. */
|
||||
await page.locator(".legacy-quick-toolbar").getByRole("button", { name: "Add Monkey", exact: true }).click();
|
||||
await expect(page.getByTestId("engine-status")).toContainText(/mesh\.primitive_monkey_add/, { timeout: 120_000 });
|
||||
|
||||
const adjust = page.locator(".last-operator-panel").first();
|
||||
await expect(adjust).toBeVisible({ timeout: 60_000 });
|
||||
await page.getByLabel("调整上一步操作").first().click();
|
||||
await expect(adjust.locator("form header")).toBeVisible({ timeout: 30_000 });
|
||||
await dragBy(page, adjust.locator("form header"), 180, -120);
|
||||
await expect.poll(async () => (await offsetOf(adjust)).x, { timeout: 10_000 }).not.toBe(0);
|
||||
const adjustOffset = await offsetOf(adjust);
|
||||
expect((await storedOffsets(page))["last-operator"]).toEqual(adjustOffset);
|
||||
|
||||
/* Robot tool: the scrim is transparent and the drawer is draggable. */
|
||||
await page.getByLabel("六轴机器人工具").click();
|
||||
const robot = page.locator(".robot-tool").first();
|
||||
await expect(robot).toBeVisible({ timeout: 60_000 });
|
||||
const scrim = await page.evaluate(() => {
|
||||
const style = getComputedStyle(document.querySelector(".robot-tool-backdrop")!);
|
||||
return { background: style.backgroundColor, pointerEvents: style.pointerEvents };
|
||||
});
|
||||
expect(["transparent", "rgba(0, 0, 0, 0)"]).toContain(scrim.background);
|
||||
expect(scrim.pointerEvents).toBe("none");
|
||||
|
||||
await dragBy(page, robot.locator("header"), -260, 90);
|
||||
await expect.poll(async () => (await offsetOf(robot)).x, { timeout: 10_000 }).not.toBe(0);
|
||||
const robotOffset = await offsetOf(robot);
|
||||
expect(robotOffset.x).toBeLessThan(0);
|
||||
expect((await storedOffsets(page))["robot-tool"]).toEqual(robotOffset);
|
||||
|
||||
fs.writeFileSync(path.join(outputDir, "tool-panels.json"), JSON.stringify({
|
||||
schemaVersion: 1, browser: "chromium", storage: "OPFS",
|
||||
workflow: "add monkey -> adjust-last-operation drag -> open robot tool -> transparent scrim -> drag drawer",
|
||||
adjustOffset, robotOffset, scrim,
|
||||
status: "PASS", acceptance: "NOT_CLAIMED",
|
||||
}, null, 2));
|
||||
});
|
||||
@@ -43,6 +43,8 @@ test("PBR tutorial runs every demo through the real asset library and renderer",
|
||||
"render-setup", "download-save", "summary",
|
||||
]));
|
||||
expect(downloads.some((name) => /\.png$/i.test(name))).toBe(true);
|
||||
expect(downloads.some((name) => /\.blend$/i.test(name))).toBe(true);
|
||||
/* 铁律:工程只写入 OPFS;本地 .blend 必须由用户显式点「下载 .blend」触发,
|
||||
* 保存流程(含教程演示的 save 动作)不得自动下载。 */
|
||||
expect(downloads.some((name) => /\.blend$/i.test(name))).toBe(false);
|
||||
await expect(overlay).toContainText("12 张材质对比");
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user