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:
35
docs/status/WEB-PANEL-DRAG-20261123.md
Normal file
35
docs/status/WEB-PANEL-DRAG-20261123.md
Normal file
@@ -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<panelId,{x,y}>`,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` 记录路径,或补小窗口钳制的人工截图证据。
|
||||
14
tests/golden/WEB-PANEL-DRAG-20261123/quick-toolbar.json
Normal file
14
tests/golden/WEB-PANEL-DRAG-20261123/quick-toolbar.json
Normal file
@@ -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"
|
||||
}
|
||||
20
tests/golden/WEB-PANEL-DRAG-20261123/tool-panels.json
Normal file
20
tests/golden/WEB-PANEL-DRAG-20261123/tool-panels.json
Normal file
@@ -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"
|
||||
}
|
||||
20
tests/golden/WEB-PANEL-DRAG-20261123/tutorial-panel.json
Normal file
20
tests/golden/WEB-PANEL-DRAG-20261123/tutorial-panel.json
Normal file
@@ -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"
|
||||
}
|
||||
67
tools/web/build-offline-manual.mjs
Normal file
67
tools/web/build-offline-manual.mjs
Normal file
@@ -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("<body", '<body data-offline="1"');
|
||||
|
||||
fs.writeFileSync(path.join(output, "index.html"), html);
|
||||
|
||||
const files = [];
|
||||
const walk = (dir) => {
|
||||
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}`);
|
||||
166
tools/web/deploy-58014.sh
Executable file
166
tools/web/deploy-58014.sh
Executable file
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-command publish of the Web Blender build to https://<host>: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 <previous-release>" >&2; exit 1; }
|
||||
|
||||
echo "published $release_id -> $origin/"
|
||||
@@ -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