Files
workinf_Blender_Wasm/web/tests/deployed/support/teach-checks.ts
mes123456 c47fa79102
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled
feat(web): viewport transform parity — offscreen backend, per-island pivots, ortho sizing
- Offscreen worker backend publishes the camera probe, so the G/R/S modal's
  pointer basis, transform gizmo and wireframe work on both renderers.
- Edit-mode INDIVIDUAL_ORIGINS pivots every connected island on its own centre,
  committed as one grouped transaction (T(P)·R·S·T(-P) in object space).
- Gizmo hits carry the pivot index; orthographic views size the axes from the
  visible world height instead of the 45° fov fallback.
- View-menu navigation no longer switches workspace when a viewport is already
  on screen (the engine workspace transaction dropped the editor out of Edit).
- Modal commits queue behind the shared command tail, so a trailing
  editEditorContext cannot consume the user's first Ctrl+Z.
- Floating sidebar rotation field confirmed in degrees; headed cases for the
  offscreen path, per-island pivots and the sidebar unit, plus receipts/docs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 07:48:17 +08:00

226 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { type Locator, type Page } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";
import { REPO_ROOT } from "./deployed";
import type { TeachAction, TeachCheck, TeachLesson, TeachStep, TeachTargetSpec } from "../../../app/src/teach/types";
/**
* Playwright twin of `web/app/src/teach/checks.ts`.
*
* The 31 lessons are replayed here against the deployed bundle: the same JSON
* that drives the in-page coach is evaluated through locators, so a lesson that
* no longer matches the product fails a case instead of quietly rotting.
* Scene checks read the facts the app already exposes to the DOM
* (`data-workspace`, `data-object-mode`, `scene-stats`, `dirty-status`).
*/
export const PUBLIC_ROOT = path.join(REPO_ROOT, "web/app/public");
const LESSONS_DIR = path.join(PUBLIC_ROOT, "teach/lessons");
export function loadLessons(): TeachLesson[] {
const files = fs.readdirSync(LESSONS_DIR).filter((name) => /^ch\d{2}\.json$/.test(name)).sort();
return files.map((name) => JSON.parse(fs.readFileSync(path.join(LESSONS_DIR, name), "utf8")) as TeachLesson);
}
/** The standalone PBR course lives beside the chapters, not inside them. */
export function loadPbrLessons(): TeachLesson[] {
const dir = path.join(PUBLIC_ROOT, "teach/pbr/lessons");
const files = fs.readdirSync(dir).filter((name) => /^pbr-\d{2}\.json$/.test(name)).sort();
return files.map((name) => JSON.parse(fs.readFileSync(path.join(dir, name), "utf8")) as TeachLesson);
}
/** `/teach/fixtures/x.blend` → the file the bundle serves from that URL. */
export function servedPath(url: string): string {
if (!url.startsWith("/")) throw new Error(`教学资源必须是站内绝对路径:${url}`);
const file = path.join(PUBLIC_ROOT, url.slice(1));
if (!fs.existsSync(file)) throw new Error(`教学资源不存在:${url} → ${file}`);
return file;
}
/**
* Mirrors `resolveTarget`: testid → css → role+name → name, exact accessible
* name first and substring second, `nth` over the matches.
*/
function candidates(page: Page, spec: TeachTargetSpec, exact: boolean): Locator {
if (spec.testid) return page.getByTestId(spec.testid);
if (spec.css) return page.locator(spec.css);
if (spec.role && spec.name) return page.getByRole(spec.role as Parameters<Page["getByRole"]>[0], { name: spec.name, exact });
if (spec.role) return page.getByRole(spec.role as Parameters<Page["getByRole"]>[0]);
if (spec.name) return page.getByText(spec.name, { exact });
throw new Error("教学 target 没有定位条件");
}
/** All matches, for `count` checks. */
export async function resolveAll(page: Page, spec: TeachTargetSpec): Promise<Locator> {
let locator = candidates(page, spec, true);
/* Exact name first, substring second — the coach's order. `getByRole`'s
* `name` is already a substring match, so only the named branch retries. */
if (spec.role && spec.name && !(await locator.count().catch(() => 0))) locator = candidates(page, spec, false);
return spec.nth === undefined ? locator : locator.nth(spec.nth);
}
/** The single element a click or read acts on; ambiguity resolves like the coach. */
export async function resolveOne(page: Page, spec: TeachTargetSpec): Promise<Locator> {
return (await resolveAll(page, spec)).first();
}
function normalize(text: string | null | undefined): string {
return (text ?? "").replace(/\s+/g, " ").trim();
}
function matches(actual: string, check: { matches?: string; equals?: string }): boolean {
if (check.equals !== undefined) return actual === check.equals;
if (check.matches === undefined) return true;
try { return new RegExp(check.matches, "u").test(actual); } catch { return actual.includes(check.matches); }
}
export interface ReplayCheckResult {
label: string;
ok: boolean;
actual: string;
}
/** A check is a poll: a missing element must cost milliseconds, not the 30 s
* default action timeout that would burn the whole case budget in one tick. */
const PROBE = { timeout: 2_000 };
async function textOf(locator: Locator): Promise<string> {
return normalize(await locator.first().evaluate((element) => element.textContent, undefined, PROBE).catch(() => ""));
}
async function sceneFacts(page: Page) {
const main = page.locator("main.blender-app").first();
const stats = normalize(await page.getByTestId("scene-stats").innerText(PROBE).catch(() => ""));
const dirty = normalize(await page.getByTestId("dirty-status").innerText(PROBE).catch(() => ""));
return {
workspace: await main.getAttribute("data-workspace").catch(() => null),
mode: await main.getAttribute("data-object-mode").catch(() => null),
objects: Number(/Objects (\d+)/.exec(stats)?.[1] ?? -1),
stats,
saved: /已保存/.test(dirty),
dirty: /未保存/.test(dirty),
};
}
async function objectRows(page: Page, name: string): Promise<Locator> {
return page.getByRole("treeitem", { name, exact: true });
}
/** Same meaning as the in-page `sceneField`, using only what the DOM shows. */
async function evaluateScene(page: Page, check: Extract<TeachCheck, { kind: "scene" }>): Promise<ReplayCheckResult> {
const label = check.label ?? "场景状态";
const facts = await sceneFacts(page);
if (check.active !== undefined) {
const rows = check.object ? await objectRows(page, check.object) : page.locator('[role="treeitem"]');
const selected = await rows.evaluateAll((nodes) => nodes.some((node) => node.getAttribute("aria-selected") === "true")).catch(() => false);
return { label, ok: selected === check.active, actual: `aria-selected=${selected}` };
}
if (check.object !== undefined) {
const count = await (await objectRows(page, check.object)).count().catch(() => 0);
return { label, ok: count > 0, actual: `${count} 行` };
}
if (check.mode !== undefined) {
const mode = (facts.mode ?? "").replace(/\s*mode$/i, "");
return { label, ok: mode.toLowerCase() === check.mode.toLowerCase(), actual: `data-object-mode=${facts.mode}` };
}
if (check.workspace !== undefined) return { label, ok: facts.workspace === check.workspace, actual: `data-workspace=${facts.workspace}` };
if (check.dirty !== undefined) return { label, ok: facts.dirty === check.dirty, actual: facts.dirty ? "未保存" : "已保存" };
if (check.saved !== undefined) return { label, ok: facts.saved === check.saved, actual: facts.saved ? "已保存" : "未保存" };
if (check.objectCount !== undefined) return { label, ok: facts.objects === check.objectCount, actual: `Objects ${facts.objects}` };
if (check.minObjects !== undefined) return { label, ok: facts.objects >= check.minObjects, actual: `Objects ${facts.objects}` };
return { label, ok: true, actual: facts.stats };
}
export async function evaluateCheck(page: Page, check: TeachCheck): Promise<ReplayCheckResult> {
if (check.kind === "scene") return evaluateScene(page, check);
if (check.kind === "event") {
const facts = await sceneFacts(page);
const label = check.label ?? check.event;
/* Save is the only event the DOM states directly; export and render land as
* downloads, which the case itself asserts when it triggers them. */
if (check.event === "saved") return { label, ok: facts.saved, actual: facts.saved ? "已保存" : "未保存" };
return { label, ok: true, actual: "事件由用例自身验证" };
}
const all = await resolveAll(page, check.target);
const label = check.label ?? "";
if (check.kind === "exists") {
const count = await all.count().catch(() => 0);
return { label: label || `${check.target.name ?? check.target.testid ?? check.target.css} 存在`, ok: count > 0, actual: `${count} 个` };
}
if (check.kind === "count") {
const count = await all.count().catch(() => 0);
const ok = check.equals !== undefined ? count === check.equals : count >= (check.atLeast ?? 1);
return { label: label || `数量满足(当前 ${count})`, ok, actual: `${count} 个` };
}
if (check.kind === "value") {
const value = await all.first().inputValue(PROBE).catch(() => null);
return { label: label || `值 ${value ?? "(无)"}`, ok: value !== null && matches(value, check), actual: value ?? null };
}
if (check.kind === "attr") {
const value = await all.first().getAttribute(check.attribute, PROBE).catch(() => null);
return { label: label || `${check.attribute}=${value}`, ok: value !== null && matches(value, check), actual: `${check.attribute}=${value}` };
}
const present = await all.count().catch(() => 0) > 0;
const text = await textOf(await resolveOne(page, check.target));
return { label: label || text.slice(0, 40), ok: present && matches(text, check), actual: text.slice(0, 160) };
}
export async function evaluateStep(page: Page, step: TeachStep): Promise<ReplayCheckResult[]> {
const results: ReplayCheckResult[] = [];
for (const check of step.checks) results.push(await evaluateCheck(page, check));
return results;
}
export function stepPassed(results: ReplayCheckResult[]): boolean {
return results.length === 0 || results.every((item) => item.ok);
}
/** Demo action replay. Only the vocabulary the lessons use is implemented; any
* new kind must be added here or the case fails loudly instead of skipping. */
export async function runTeachAction(page: Page, action: TeachAction): Promise<void> {
if (action.kind === "click") {
const control = await resolveOne(page, action.target);
/* Asset cards are disabled until the library finishes seeding; `force` skips
* that check, so wait for enabled first and only then bypass occlusion. */
await control.isEnabled().then((enabled) => enabled ? undefined : expect(control).toBeEnabled({ timeout: 20_000 }));
await control.click({ timeout: 15_000, force: true });
await page.waitForTimeout(250);
return;
}
if (action.kind === "wait") {
await page.waitForTimeout(action.ms ?? 500);
return;
}
if (action.kind === "dblclick") {
const control = await resolveOne(page, action.target);
await control.isEnabled().then((enabled) => enabled ? undefined : expect(control).toBeEnabled({ timeout: 20_000 }));
await control.dblclick({ timeout: 15_000, force: true });
await page.waitForTimeout(250);
return;
}
if (action.kind === "importFile") {
/* Deliver the served file under its declared name, so the product routes it
* exactly as a user-picked file would. */
const buffer = fs.readFileSync(servedPath(action.url));
const mimeType = /\.glb$/i.test(action.fileName) ? "model/gltf-binary" : "application/octet-stream";
await page.getByTestId("blend-file-input").setInputFiles({ name: action.fileName, mimeType, buffer });
return;
}
if (action.kind === "fill") {
const field = await resolveOne(page, action.target);
await field.click({ timeout: 15_000, force: true });
await field.fill(action.value);
await page.waitForTimeout(150);
return;
}
if (action.kind === "selectOption") {
await (await resolveOne(page, action.target)).selectOption(action.value);
return;
}
if (action.kind === "openScene") {
await page.getByTestId("blend-file-input").setInputFiles(servedPath(action.url));
return;
}
throw new Error(`教学回放未实现动作 ${action.kind};请在 deployedsupport/teach-checks.ts 中补齐`);
}