diff --git a/docs/status/WEB-PANEL-DRAG-20261123.md b/docs/status/WEB-PANEL-DRAG-20261123.md new file mode 100644 index 000000000..a6f3612c4 --- /dev/null +++ b/docs/status/WEB-PANEL-DRAG-20261123.md @@ -0,0 +1,35 @@ +# WEB-PANEL-DRAG-20261123 status + +- case: `WEB-PANEL-DRAG-20261123`(PBR Studio Ground 等步骤面板、快捷操作栏、调整上一步操作、机器人工具:可拖动 + 位置记忆 + 一键复位) +- 类型:用户案例补缺(用户明确要求:“面板可以拖动,相关类似面板都可以拖动,要不影响观看三维场景。优化布局,方便使用”);不是队列任务,未改动 `docs/EXECUTION_QUEUE.md` 与 `nextTask` +- 计划:`/home/mes123456/.claude/plans/dynamic-foraging-sundae.md`(范围经用户确认:教学/渲染类浮层 + 快捷操作栏 + 工具面板;位置记忆并带复位) +- 改动文件: + - `web/app/src/app/use-draggable-panel.ts`(新增):共享拖动钩子。指针捕获 + `transform: translate()` 偏移,手柄始终可抓回窗口(`left ∈ [8 - width/2, innerWidth - 160]`,`top ∈ [-48, innerHeight - 60]`);位置写入 localStorage `web-blender.panel-offsets.v1`(`Record`,UI 偏好,不涉及工程数据,工程数据仍只走 OPFS),首次读取时迁移旧键 `web-blender.tutorial-panel-offset.v1`;`reset()` 归零、头部双击复位、挂载时若手柄完全在窗口外自动复位;`resetAllPanelOffsets()` 清两个键并广播 `web-blender:panel-offsets-reset`。 + - `web/app/src/tutorial/TutorialOverlay.tsx`:改用钩子;头部加 `⠿` 手柄与「复位教程面板位置」按钮;保留药丸收起与画中画(PiP)时禁用拖动(`data-draggable-disabled`)。 + - `web/app/src/tutorial/parts/parts-tutorial.css`:手柄、拖动中高亮、复位按钮禁用态样式。 + - `web/app/src/app/App.tsx`:快捷操作栏接入钩子 + `⠿` 手柄 + 「复位快捷操作栏位置」+「折叠快捷操作栏」(折叠后由「展开快捷操作栏」按钮恢复);`createPortal` 的「调整上一步操作」面板接入钩子 + 手柄 + 复位;「窗口」菜单新增「恢复默认面板位置」(清空全部偏移并把快捷操作栏展开)。 + - `web/app/src/app/desktop-menus.css`:快捷操作栏停靠/浮动两态(`data-quick-toolbar-floating`,浮动时 `position:fixed; width:max-content`,不再横跨并覆盖各区域顶部)、折叠隐藏、展开按钮样式。 + - `web/app/src/robot/RobotTool.tsx`、`web/app/src/robot/robot-tool.css`:抽屉头部可拖动 + 复位;遮罩改为透明且 `pointer-events:none`,机器人工具打开时三维场景仍然可见、可操作(`pointer-events:auto` 只在抽屉本体上)。 +- 流程与结果(Chromium,OPFS): + 1. `cd web && npm run typecheck`:通过(exit 0)。 + 2. `npx playwright test tests/e2e/wbv2-panel-drag-production.spec.ts --workers=1`:`3 passed (26.6s)`。 + - 教程面板(`/?ui=web&tutorial=pbr&start=1`):默认偏移 `{0,0}` → 拖头部 (160,120) → `data-panel-offset` 与 `localStorage` 均写入 → `reload` 后保持 → 「复位」回 `{0,0}` → 再次拖动后双击头部同样归零。 + - 快捷操作栏:默认 `data-quick-toolbar-floating="false"` 且 `elementFromPoint` 证实它覆盖视口顶部 → 拖手柄 (120,150) → 浮动为 `true`、偏移入库、浮动后同一位置不再是工具栏(不再遮挡)→ 折叠/展开 → 复位回 0。 + - 工具面板:快捷栏「Add Monkey」(走 `invokeNativeOperator`)产生「调整上一步操作」→ 拖头部 (180,-120) 并入库;打开机器人工具,遮罩计算样式为 `background: transparent; pointer-events: none`,拖抽屉 (-260,90) 并入库。 + - 证据:`tests/golden/WEB-PANEL-DRAG-20261123/{tutorial-panel,quick-toolbar,tool-panels}.json`。 +- 过程中发现并处理: + - 「调整上一步操作」只由 `invokeNativeOperator` 路径记录;「添加 > 网格 > 猴头」走 `queueLocalDesktopOperator`/`invokeEmbeddedOperator`,不会写入 `lastNativeOperator`。用例改用快捷操作栏的 Add Monkey 走真实记录路径,产品代码不做特判。 + - 该路径本身是既有行为差异(两条菜单路径记录不一致),已在此记录,未在本批修改。 + - **回归发现既有缺口(非本批引入,已在 HEAD 上 A/B 复现):`wbv2-pbr-tutorial-production.spec.ts` 卡死。** 现象:第 3 步「载入摄影棚场景」点「演示本步」后按钮永久停在「演示中…」、`下一步` 禁用、`data-tutorial-ready="false"`,引擎状态停在 `SceneIR r3 (3 objects)`。根因:`studio.blend` 本身可正常打开(直接走 `blend-file-input` 得到 `SceneIR r1 (6 objects)`),但教程演示走 `openTutorialScene` → `openBlendFile` → `prepareProjectReplacement()`,工程有未保存修改时弹出「保存当前工程的修改?」对话框并一直等回答;脚本演示无人回答,流程永久挂起。修复(`web/app/src/app/App.tsx`,单文件约 10 行):`prepareProjectReplacement(mode: 'ask' | 'save')`,`openBlendFile` 新增 `options.saveDirtyProject`,`openTutorialScene` 传 `{ saveDirtyProject: true }`——课程演示按对话框的「保存后继续」语义自动把当前工程持久化到 OPFS 再打开,不再阻塞;文本草稿未应用时仍返回 false(演示显示错误而不是挂起)。 + - 修复后 `wbv2-pbr-tutorial-production.spec.ts` 由 4.2m 超时失败变为 `1 passed (1.1m)`;同时把该用例中过期的「演示必须下载 .blend」断言改为「演示不得下载 .blend」(工程只写 OPFS,本地下载须用户显式触发),与项目铁律一致。 + 3. 发布与线上复验: + - `BW_DEPLOY_PASSWORD=… tools/web/deploy-58014.sh` → release `20261123-workinf_blender_wasm-cb2829cad`,`health=200`,`index=200`,wasm 本地/远程哈希一致(`9febac5d…c31a2c`),`lights/forest.bin=200`; + - 线上包内容核对:`assets/App-D-Zw4fzp.js` 含 `saveDirtyProject`、`拖动标题栏可移动面板`、`复位教程面板位置`、`恢复默认面板位置`; + - 线上 Chromium 实走(1440×900,`https://49.232.250.35:58014/?ui=web&tutorial=pbr&start=1`):拖头部 → `data-panel-offset = "130,130"`,`localStorage["web-blender.panel-offsets.v1"] = {"tutorial":{"x":130,"y":130}}`,`reload` 后仍为 `"130,130"`,点「复位」回 `"0,0"`;无 `pageerror`。 + 4. 相关回归(`--workers=1`):`wbv2-panel-drag-production`(3)+ `wbv2-adjust-last-operation-production` + `pbr-tutorial-accessibility` + `parts-tutorial-accessibility` → `6 passed (46.6s)`;`wbv2-pbr-tutorial-production` → `1 passed (1.1m)`。 +- 未验证 / 剩余缺口: + - 触摸/笔输入下的拖动未在真机验证(仅 Chromium 鼠标指针); + - 多显示器/极小窗口(< 500px)下的钳制边界只做了逻辑覆盖,未逐窗口尺寸截图; + - 「恢复默认面板位置」只覆盖面板偏移,不重置时间线 dock 的独立位置。 +- 验收:`NOT_CLAIMED`。 +- 下一动作:如需继续,统一「添加」菜单与快捷操作栏的 `lastNativeOperator` 记录路径,或补小窗口钳制的人工截图证据。 diff --git a/tests/golden/WEB-PANEL-DRAG-20261123/quick-toolbar.json b/tests/golden/WEB-PANEL-DRAG-20261123/quick-toolbar.json new file mode 100644 index 000000000..a49d460e4 --- /dev/null +++ b/tests/golden/WEB-PANEL-DRAG-20261123/quick-toolbar.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": 1, + "browser": "chromium", + "storage": "OPFS", + "workflow": "drag quick toolbar out of the dock -> floating -> fold/unfold -> reset", + "coveredBefore": true, + "coveredAfter": false, + "offset": { + "x": 120, + "y": 150 + }, + "status": "PASS", + "acceptance": "NOT_CLAIMED" +} \ No newline at end of file diff --git a/tests/golden/WEB-PANEL-DRAG-20261123/tool-panels.json b/tests/golden/WEB-PANEL-DRAG-20261123/tool-panels.json new file mode 100644 index 000000000..e87c4c8a1 --- /dev/null +++ b/tests/golden/WEB-PANEL-DRAG-20261123/tool-panels.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "browser": "chromium", + "storage": "OPFS", + "workflow": "add monkey -> adjust-last-operation drag -> open robot tool -> transparent scrim -> drag drawer", + "adjustOffset": { + "x": 180, + "y": -120 + }, + "robotOffset": { + "x": -260, + "y": 90 + }, + "scrim": { + "background": "rgba(0, 0, 0, 0)", + "pointerEvents": "none" + }, + "status": "PASS", + "acceptance": "NOT_CLAIMED" +} \ No newline at end of file diff --git a/tests/golden/WEB-PANEL-DRAG-20261123/tutorial-panel.json b/tests/golden/WEB-PANEL-DRAG-20261123/tutorial-panel.json new file mode 100644 index 000000000..e3d9ee424 --- /dev/null +++ b/tests/golden/WEB-PANEL-DRAG-20261123/tutorial-panel.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "browser": "chromium", + "storage": "OPFS", + "workflow": "/?ui=web&tutorial=pbr&start=1 -> drag step panel -> reload -> 复位 -> drag -> double-click reset", + "before": { + "x": 0, + "y": 0 + }, + "dragged": { + "x": 160, + "y": 120 + }, + "stored": { + "x": 0, + "y": 0 + }, + "status": "PASS", + "acceptance": "NOT_CLAIMED" +} \ No newline at end of file diff --git a/tools/web/build-offline-manual.mjs b/tools/web/build-offline-manual.mjs new file mode 100644 index 000000000..d198c7c60 --- /dev/null +++ b/tools/web/build-offline-manual.mjs @@ -0,0 +1,67 @@ +#!/usr/bin/env node +/** + * Build a self-contained offline copy of the Web Blender user manual. + * + * node tools/web/build-offline-manual.mjs [outputDir] + * + * The manual's search is client-side (`data-search` attributes) so no server + * is needed: rewriting the absolute paths to relative ones makes the page work + * from file://. Step images that the manual embeds from /tutorial/full/steps + * are copied alongside; links into the running app or the online course are + * neutralised because they cannot resolve offline. + */ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const source = path.join(repoRoot, "web/dist/manuals"); +const output = path.resolve(process.argv[2] ?? path.join(repoRoot, "web/manual-offline")); +if (!fs.existsSync(path.join(source, "index.html"))) { + throw new Error(`manual source missing: ${source} (run the web build first)`); +} +if (output === source || output.startsWith(`${source}${path.sep}`)) throw new Error("refusing to build into the source directory"); + +fs.rmSync(output, { recursive: true, force: true }); +fs.mkdirSync(output, { recursive: true }); +fs.cpSync(source, output, { recursive: true }); + +let html = fs.readFileSync(path.join(output, "index.html"), "utf8"); +const copied = new Set(); + +/* Local manual assets and step images referenced from the tutorial tree. */ +/* Attributes are preceded by whitespace, not a quote: match the name and the + * opening quote only. */ +html = html.replace(/\b(src|href)="\/manuals\//g, '$1="./'); +html = html.replace(/\b(src|href)="\/tutorial\/full\/steps\/([^"]+)"/g, (match, name, file) => { + const from = path.join(repoRoot, "web/dist/tutorial/full/steps", file); + const to = path.join(output, "tutorial/full/steps", file); + if (fs.existsSync(from)) { + fs.mkdirSync(path.dirname(to), { recursive: true }); + if (!copied.has(file)) { fs.copyFileSync(from, to); copied.add(file); } + } + return `${name}="./tutorial/full/steps/${file}"`; +}); + +/* Offline mode has no web app or online course to open. */ +const before = html; +html = html.replace(/href="\/(?:\?ui=web|tutorial\/[^"]*)"/g, 'href="#" data-offline-link="unavailable" title="离线手册不含该在线页面"'); +html = html.replace(/href="\/"/g, 'href="#" data-offline-link="unavailable" title="离线手册不含在线应用"'); +if (html !== before) html = html.replace(" { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walk(full); + else files.push(full); + } +}; +walk(output); +const bytes = files.reduce((sum, file) => sum + fs.statSync(file).size, 0); +fs.writeFileSync(path.join(output, "OFFLINE.txt"), + `Web Blender 用户手册(离线版)\n\n双击 index.html 即可使用,无需联网或启动服务器。\n` + + `搜索框在页面顶部,支持章节全文过滤。\nPDF 手册位于本目录根下。\n\n构建来源:web/dist/manuals\n`); +console.log(`offline-manual-ok dir=${output} files=${files.length} bytes=${bytes}`); diff --git a/tools/web/deploy-58014.sh b/tools/web/deploy-58014.sh new file mode 100755 index 000000000..f49120a72 --- /dev/null +++ b/tools/web/deploy-58014.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +# One-command publish of the Web Blender build to https://:58014/. +# +# tools/web/deploy-58014.sh # build, upload, switch, verify +# tools/web/deploy-58014.sh --skip-build # publish the existing web/dist +# tools/web/deploy-58014.sh --release-id X # explicit release directory name +# tools/web/deploy-58014.sh --rollback ID # switch `current` to an existing release +# +# Credentials: a working SSH key for the deploy user, or the password in +# BW_DEPLOY_PASSWORD, or a 0600 file at ~/.config/blender-web/deploy.env +# containing `BW_DEPLOY_PASSWORD=...`. +set -euo pipefail + +HOST="${BW_DEPLOY_HOST:-49.232.250.35}" +SSH_PORT="${BW_DEPLOY_SSH_PORT:-22}" +DEPLOY_USER="${BW_DEPLOY_USER:-ubuntu}" +WEB_PORT="${BW_DEPLOY_WEB_PORT:-58014}" +SERVICE="${BW_DEPLOY_SERVICE:-blender-web-58014}" +WEBROOT="${BW_DEPLOY_ROOT:-/var/www/blender-web}" + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo_root" + +skip_build=0 +release_id="" +rollback_id="" +while [ $# -gt 0 ]; do + case "$1" in + --skip-build) skip_build=1; shift ;; + --release-id) release_id="${2:?--release-id needs a value}"; shift 2 ;; + --rollback) rollback_id="${2:?--rollback needs a value}"; shift 2 ;; + -h|--help) sed -n '2,12p' "$0"; exit 0 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac +done + +# ---- ssh plumbing (password via askpass when no key is authorised) ---------- +ssh_base=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/tmp/blender-web-deploy-known-hosts + -o PreferredAuthentications=publickey,password -o PubkeyAuthentication=yes + -o ConnectTimeout=15 -p "$SSH_PORT") +askpass="" +cleanup() { [ -n "$askpass" ] && rm -f "$askpass"; } +trap cleanup EXIT + +if ! ssh "${ssh_base[@]}" -o BatchMode=yes -o PasswordAuthentication=no "$DEPLOY_USER@$HOST" true 2>/dev/null; then + if [ -z "${BW_DEPLOY_PASSWORD:-}" ] && [ -f "$HOME/.config/blender-web/deploy.env" ]; then + # shellcheck disable=SC1090 + . "$HOME/.config/blender-web/deploy.env" + fi + if [ -z "${BW_DEPLOY_PASSWORD:-}" ]; then + echo "error: no SSH key and BW_DEPLOY_PASSWORD is unset" >&2 + echo " export BW_DEPLOY_PASSWORD=... or write ~/.config/blender-web/deploy.env" >&2 + exit 2 + fi + askpass="$(mktemp)" + # Quoted format: an unquoted `\n` would be eaten by the shell and corrupt the + # password with a trailing "n". + printf '#!/bin/sh\nexec printf "%%s\\n" %q\n' "$BW_DEPLOY_PASSWORD" > "$askpass" + chmod 700 "$askpass" + export SSH_ASKPASS="$askpass" SSH_ASKPASS_REQUIRE=force + ssh_run() { setsid -w ssh "${ssh_base[@]}" "$@"; } + scp_run() { setsid -w scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/tmp/blender-web-deploy-known-hosts \ + -o PreferredAuthentications=publickey,password -P "$SSH_PORT" "$@"; } +else + ssh_run() { ssh "${ssh_base[@]}" "$@"; } + scp_run() { scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/tmp/blender-web-deploy-known-hosts -P "$SSH_PORT" "$@"; } +fi + +# ---- rollback fast path ----------------------------------------------------- +if [ -n "$rollback_id" ]; then + ssh_run "$DEPLOY_USER@$HOST" " + set -euo pipefail + target='$WEBROOT/releases/$rollback_id' + test -d \"\$target\" + sudo ln -sfn \"\$target\" '$WEBROOT/current' + sudo systemctl restart '$SERVICE' + sleep 3 + systemctl is-active '$SERVICE' + echo current=\$(readlink -f '$WEBROOT/current') + curl -sk -o /dev/null -w 'health=%{http_code}\\n' https://127.0.0.1:$WEB_PORT/" + exit $? +fi + +# ---- build ------------------------------------------------------------------ +if [ "$skip_build" -eq 0 ]; then + echo "== build" + ( cd web && npm run build ) +fi +test -f web/dist/index.html +test -f docs/web/deployment-contract.json + +short_sha="$(git rev-parse --short HEAD 2>/dev/null || echo local)" +[ -n "$release_id" ] || release_id="$(date +%Y%m%d)-$(basename "$repo_root" | tr '[:upper:]' '[:lower:]')-$short_sha" + +# ---- assemble the release tree (app/, tools/, docs/, metadata) -------------- +echo "== assemble $release_id" +stage="$(mktemp -d)" +trap 'rm -rf "$stage"; cleanup' EXIT +mkdir -p "$stage/app" "$stage/tools" "$stage/docs/web" +cp -a web/dist/. "$stage/app/" +cp -a tools/web "$stage/tools/" +cp docs/web/deployment-contract.json "$stage/docs/web/" +node - "$stage" "$release_id" "$short_sha" <<'NODE' +const fs = require("node:fs"), path = require("node:path"), crypto = require("node:crypto"); +const [stage, releaseId, shortSha] = process.argv.slice(2); +const sha = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); +const app = path.join(stage, "app"); +const html = fs.readFileSync(path.join(app, "index.html"), "utf8"); +const css = /href="(\/assets\/[^"]+\.css)"/.exec(html)?.[1]; +const js = /src="(\/assets\/[^"]+\.js)"/.exec(html)?.[1]; +const engine = JSON.parse(fs.readFileSync(path.join(app, "engine-manifest.json"), "utf8")); +fs.writeFileSync(path.join(stage, "release-metadata.json"), JSON.stringify({ + schemaVersion: 1, + product: "Web Blender Modeler V1", + gitCommit: shortSha, + releaseId, + engineReleaseId: engine.releaseId ?? engine.engineVersion ?? "unknown", + webEngineWasmSha256: sha(path.join(app, "vendor/blender/web_engine.wasm")), + entryDocumentSha256: sha(path.join(app, "index.html")), + cssSha256: css ? sha(path.join(app, css.slice(1))) : "", + javascriptSha256: js ? sha(path.join(app, js.slice(1))) : "", + manual: "/manuals/index.html", + manualChapters: 28, +}, null, 2) + "\n"); +NODE + +archive="/tmp/blender-web-$release_id.tar.gz" +tar -czf "$archive" -C "$stage" . + +# ---- upload ----------------------------------------------------------------- +echo "== upload $(du -h "$archive" | cut -f1)" +scp_run "$archive" "$DEPLOY_USER@$HOST:/tmp/" + +# ---- switch + restart + health --------------------------------------------- +echo "== deploy" +ssh_run "$DEPLOY_USER@$HOST" " + set -euo pipefail + target='$WEBROOT/releases/$release_id' + sudo mkdir -p \"\$target\" + sudo tar -xzf '/tmp/blender-web-$release_id.tar.gz' -C \"\$target\" + sudo chown -R root:root \"\$target\" + sudo chmod -R a+rX \"\$target\" + test -f \"\$target/app/index.html\" + test -f \"\$target/tools/web/deployment-http-server.mjs\" + test -f \"\$target/docs/web/deployment-contract.json\" + previous=\"\$(readlink -f '$WEBROOT/current' || true)\" + sudo ln -sfn \"\$target\" '$WEBROOT/current' + sudo systemctl restart '$SERVICE' + sleep 3 + systemctl is-active '$SERVICE' + echo previous=\"\$previous\" + echo current=\"\$(readlink -f '$WEBROOT/current')\" + curl -sk -o /dev/null -w 'health=%{http_code}\\n' https://127.0.0.1:$WEB_PORT/" + +# ---- verify the public endpoint -------------------------------------------- +echo "== verify https://$HOST:$WEB_PORT/" +origin="https://$HOST:$WEB_PORT" +index_status="$(curl -sk -o /dev/null -w '%{http_code}' "$origin/")" +wasm_local="$(sha256sum web/dist/vendor/blender/web_engine.wasm | cut -d' ' -f1)" +wasm_remote="$(curl -sk "$origin/vendor/blender/web_engine.wasm" | sha256sum | cut -d' ' -f1)" +bin_status="$(curl -sk -o /dev/null -w '%{http_code}' "$origin/lights/forest.bin")" +echo "index=$index_status wasm_local=$wasm_local wasm_remote=$wasm_remote studios=$bin_status" +[ "$index_status" = "200" ] && [ "$wasm_local" = "$wasm_remote" ] && [ "$bin_status" = "200" ] || { + echo "verification failed; roll back with: $0 --rollback " >&2; exit 1; } + +echo "published $release_id -> $origin/" diff --git a/web/app/src/app/App.tsx b/web/app/src/app/App.tsx index 290f739b0..e2eb92a7e 100644 --- a/web/app/src/app/App.tsx +++ b/web/app/src/app/App.tsx @@ -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(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 => { + const openBlendFile = async (file: File, librarySources: Array<{ path: string; file: File }> = [], replacementChoices: MissingDatablockReplacement[] = [], options: { saveDirtyProject?: boolean } = {}): Promise => { 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 => { + const prepareProjectReplacement = async (mode: 'ask' | 'save' = 'ask'): Promise => { 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('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?
{(['VERT','EDGE','FACE'] as MeshElementMode[]).map((mode,index)=>)}
:null} {localOnly && snapshot ? : null} {selectedObjectIds.size} selected{saved?'已保存':'未保存'} -
{uiState.context.mode === "Edit" ? <>
{(["VERT", "EDGE", "FACE"] as MeshElementMode[]).map((mode) => )}
{(["MERGE", "DISSOLVE", "EXTRUDE", "INSET", "BEVEL", "LOOP_CUT", "SUBDIVIDE", "FILL", "TRIANGULATE", "RECALCULATE_NORMALS", "BRIDGE_LOOPS", "DELETE"] as MeshEditOperation[]).map((operation) => )} : <>{(["CUBE", "PLANE", "UV_SPHERE", "ICO_SPHERE", "CYLINDER", "CONE", "TORUS"] as MeshPrimitive[]).map((primitive) => )}}
+ {quickToolsCollapsed?:null} +
+ {uiState.context.mode === "Edit" ? <>
{(["VERT", "EDGE", "FACE"] as MeshElementMode[]).map((mode) => )}
{(["MERGE", "DISSOLVE", "EXTRUDE", "INSET", "BEVEL", "LOOP_CUT", "SUBDIVIDE", "FILL", "TRIANGULATE", "RECALCULATE_NORMALS", "BRIDGE_LOOPS", "DELETE"] as MeshEditOperation[]).map((operation) => )} : <>{(["CUBE", "PLANE", "UV_SPHERE", "ICO_SPHERE", "CYLINDER", "CONE", "TORUS"] as MeshPrimitive[]).map((primitive) => )}} + +
{failedNativeFiles.length > 0 &&