Files
FreeCADWasmDev/web/tools/cad-ui-rebuild/lib/assembly.mjs
wangdequan 87b2a6cb8a feat(carrier): 航空母舰 PartDesign 有头创建工具包与初学者教学
- 新数据链 web/teaching/cases/carrier-partdesign:20 件零件(spec.json 唯一来源)、
  内核建造器 parts/*.mjs、traces/FCStd/replay 全量产物;装配 20 插入 + 19 关节。
- 工具包 tools/carrier:catalog / preflight / create-part / create-assembly /
  create-all / list / self-test / README,按零件与装配拆分为独立工具。
- 共享驱动扩展 web/tools/cad-ui-rebuild:Loft/Pipe/Hole/Fillet/Chamfer/Mirrored/
  LinearPattern 交互,Reversed 复选框补齐;装配 saveAssemblyBundle 先 Accept 再保存。
- 教学:lessons.mjs 新增 carrier 组(环境课 + 20 件 + 装配),suite-runner 增加
  carrier-part/carrier-assembly,生成 carrier-toolkit.html 并接入 index 与控制台证据。

验证:20 件 210 步全部有头通过(P05 修复后 39640 m³;P06 回归 8/8);
装配 20/20 插入、19/19 关节、20 组件 0 畸形、0 mismatch;check:carrier、
check:reducer、check-console --live 全绿。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 18:46:27 +08:00

279 lines
13 KiB
JavaScript

// Drive the assembly through the real UI.
//
// The part-building half of this tool is proven; assembly used to be built only
// through kernel probe calls because the insert-link task hardcoded the identity
// rotation. That is now a React control (`Insert link rotation W/X/Y/Z` plus
// presets), so creation + every insertion can go through the same surface a
// learner uses. Joints and solving still use the workbench parameter forms,
// following the order proven in tools/line-manual/ui-assemble.mjs.
//
// Ordering matters and is not obvious: the first inserted link becomes the
// grounded anchor, so the ground part must be inserted first, before anything
// else. `orderedInserts` enforces that.
import fs from "node:fs";
import path from "node:path";
/** Sort inserts so the ground part comes first, keeping the rest in authored order. */
export function orderedInserts(inserts, groundDocument) {
if (!groundDocument) return [...inserts];
const ground = inserts.filter(item => item.sourceDocument === groundDocument);
const rest = inserts.filter(item => item.sourceDocument !== groundDocument);
return [...ground, ...rest];
}
/** Wait for the assembly task surface to settle after an action. */
const settle = (page, ms = 700) => page.waitForTimeout(ms);
/**
* Copy the project's sample FCStd files into the browser's OPFS document
* directory, which is where the Insert Link task lists sources from
* (`listDocumentFiles()` in src/storage.ts reads `freecad-documents`, not
* `freecad-exports`; exports hold STEP/STL/etc, not editable documents).
*
* The web app never reads the host filesystem, so a UI-driven assembly needs the
* documents present in OPFS first. Documents are addressed by bare filename.
*/
export async function seedSources(page, files) {
await page.evaluate(async (entries) => {
const root = await navigator.storage.getDirectory();
const dir = await root.getDirectoryHandle("freecad-documents", { create: true });
for (const entry of entries) {
const handle = await dir.getFileHandle(entry.name, { create: true });
const writable = await handle.createWritable();
const binary = atob(entry.base64);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
await writable.write(bytes);
await writable.close();
}
}, files);
return files.map(entry => entry.name);
}
/**
* Open the assembly page and create the assembly document.
* Desktop equivalent: Assembly workbench → Create Assembly.
*/
export async function createAssembly(page, { appOrigin, pagePath, document, label }) {
await page.goto(`${appOrigin}/${pagePath}`, { waitUntil: "domcontentloaded", timeout: 180000 });
const create = page.locator('section[aria-label="Create assembly"]');
await create.waitFor({ timeout: 180000 });
await page.locator('input[aria-label="Assembly document name"]').first().fill(document);
if (label) await page.locator('input[aria-label="Assembly label"]').first().fill(label);
await create.getByRole("button", { name: "Create" }).first().click();
await settle(page, 3000);
}
/**
* Open the Insert Link task and load one source file from OPFS.
* The task loads one file per action; the kernel probe can batch, the UI cannot.
*/
export async function loadSource(page, fileName) {
const task = page.locator('section[aria-label="Insert assembly link"]');
await task.waitFor({ timeout: 120000 });
const select = page.locator('select[aria-label="Insert link source file"]');
await select.selectOption(fileName);
await settle(page, 300);
await task.getByRole("button", { name: "Load source", exact: true }).click();
// Loading parses the FCStd; a large document takes a few seconds. The
// "Insert" button is already visible before any load, so it is not a load
// signal. Wait for the candidate list itself to fill, and for the status
// line to name the file that was just loaded -- with several documents open
// the options from the previous load are still present until this one lands.
await page.waitForFunction(name => {
const status = document.querySelector('section[aria-label="Insert assembly link"] p[role="status"]');
const objects = document.querySelector('select[aria-label="Insert link source object"]');
return Boolean(status) && status.textContent.includes(`Loaded ${name}`)
&& Boolean(objects) && objects.options.length > 1;
}, fileName, { timeout: 180000 });
await settle(page, 600);
}
/**
* Insert the loaded document's object at a position and rotation.
*
* The rotation fields are the React control that replaced the hardcoded
* identity quaternion; passing [0,0,0,1] reproduces the old behaviour exactly.
*/
export async function insertLink(page, { sourceDocument, sourceObject, position, rotation, rigid = true }) {
const task = page.locator('section[aria-label="Insert assembly link"]');
const objectSelect = page.locator('select[aria-label="Insert link source object"]');
// Option values are `documentId:object`. Parts share object names across
// documents (`Body` exists in every reducer part), so the bare object name
// cannot be used as the value -- the task would always resolve to whichever
// document was opened first.
const key = `${sourceDocument}:${sourceObject}`;
const values = await objectSelect.evaluate(node => [...node.options].map(option => option.value));
if (!values.includes(key)) throw new Error(`source object ${key} not among ${values.join(", ")}`);
await objectSelect.selectOption(key);
for (const [index, axis] of ["X", "Y", "Z"].entries()) {
const input = page.locator(`input[aria-label="Insert link position ${axis}"]`).first();
await input.fill(String(position?.[index] ?? 0));
await input.press("Enter");
}
const quaternion = rotation ?? [0, 0, 0, 1];
for (const [index, axis] of ["W", "X", "Y", "Z"].entries()) {
const input = page.locator(`input[aria-label="Insert link rotation ${axis}"]`).first();
await input.fill(String(quaternion[index]));
await input.press("Enter");
}
const rigidBox = task.locator('input[type="checkbox"]').first();
if (await rigidBox.count()) await rigidBox.setChecked(rigid).catch(() => {});
await task.getByRole("button", { name: "Insert", exact: true }).click();
await settle(page, 400);
}
/** Commit the insertion session. */
export async function acceptLinks(page) {
const task = page.locator('section[aria-label="Insert assembly link"]');
await task.getByRole("button", { name: "Accept", exact: true }).click();
await settle(page, 2000);
}
/**
* Insert every link in the planned order, loading each source document once.
* Returns per-insert evidence so the caller can assert rotation was preserved.
*/
export async function insertAll(page, inserts, { groundDocument, loadOne = loadSource } = {}) {
const ordered = orderedInserts(inserts, groundDocument);
const loaded = new Set();
const done = [];
for (const item of ordered) {
const fileName = `${item.sourceDocument}.FCStd`;
if (!loaded.has(fileName)) { await loadOne(page, fileName); loaded.add(fileName); }
await insertLink(page, item);
done.push({ sourceDocument: item.sourceDocument, sourceObject: item.sourceObject,
position: item.position, rotation: item.rotation ?? [0, 0, 0, 1] });
}
await acceptLinks(page);
return done;
}
/**
* How many links the task reports, read from the visible list.
* Used as a cheap post-condition before the expensive joint and solve steps.
*/
export async function insertedLinkCount(page) {
return page.evaluate(() => document.querySelectorAll('ul[aria-label="Inserted links"] li').length);
}
/**
* Run one workbench command through the generic parameter form.
*
* Joints and the solve have no bespoke React control of their own, so they go
* through the help-page panel the same way the E18 course episode does: click
* the command, put its payload in #payload-editor, run it, wait for the state
* response to change, and return the native result.
*/
export async function executeCommand(page, command, payload, timeout = 300000) {
const before = await page.evaluate(() => window.__freecadWorkbenchState?.response?.requestId ?? null);
await page.locator(`button[data-help-page="${command}"]`).first().click();
await page.locator("#payload-editor").fill(JSON.stringify(payload));
await page.getByRole("button", { name: "执行选中命令" }).click();
await page.waitForFunction(id => {
const response = window.__freecadWorkbenchState?.response;
return Boolean(response) && response.requestId !== id;
}, before, { timeout });
const response = await page.evaluate(() => window.__freecadWorkbenchState?.response);
if (response?.kind !== "result") {
throw new Error(`${command}: ${response?.error?.code} ${response?.error?.message}`);
}
return response.result?.records?.find(record => record.status === "exposed")?.result ?? response.result;
}
/** Component names follow insertion order: Component, Component001, … */
export function componentName(index) {
return index === 0 ? "Component" : `Component${String(index).padStart(3, "0")}`;
}
/**
* Create every joint the replay records, in order. Each step already carries a
* complete payload (selection + references), so nothing is re-derived here.
*/
export async function createJoints(page, steps) {
const done = [];
for (const step of steps) {
const native = await executeCommand(page, step.action, step.args);
done.push({
label: step.label,
type: native?.jointType ?? null,
joint: native?.joint ?? null,
message: native?.message ?? null,
});
}
return done;
}
/** Run the solve and summarise what the solver returned for every component. */
export async function solveAssembly(page, step) {
const native = await executeCommand(page, step.action, step.args);
const components = (native?.components ?? []).map(component => ({
object: component.object ?? component.name ?? null,
position: component.placement?.position ?? null,
rotation: component.placement?.rotation ?? null,
}));
return { label: step.label, components, diagnostics: native?.diagnostics ?? native?.messages ?? null };
}
/**
* Save the assembly through the BOM task's own "Save FCStd" button, then read
* back what OPFS actually holds.
*
* Saving is OPFS-only by design (no automatic download). The bundle writes its
* FCStd files through storage.writeDocumentFile (`freecad-documents`) and the
* manifest `<documentId>.assembly.json` through writeRawStep (`freecad-1-2`),
* so both stores are checked here.
*/
export async function saveAssemblyBundle(page, { document, timeout = 300000 }) {
const section = page.locator('section[aria-label="Bill of materials task"]');
await section.waitFor({ timeout: 120000 });
const save = section.getByRole("button", { name: "Save FCStd", exact: true }).first();
const accept = section.getByRole("button", { name: "Accept", exact: true }).first();
// Native `save` refuses while the BOM task still owns an open session
// ("Accept or cancel the task first", AssemblyInsertLink.h), and the button is
// disabled for exactly that state -- clicking it blindly just times out.
// Accepting commits the table (columns, settings) before the bundle is built,
// so the saved FCStd carries what the task was showing.
await page.waitForFunction(() => {
const task = document.querySelector('section[aria-label="Bill of materials task"]');
if (!task) return false;
const buttons = [...task.querySelectorAll("button")];
const button = name => buttons.find(node => node.textContent?.trim() === name);
return Boolean(button("Save FCStd") && !button("Save FCStd").disabled)
|| Boolean(button("Accept") && !button("Accept").disabled);
}, null, { timeout: 120000 });
if (await save.isDisabled()) await accept.click();
await save.click();
await page.waitForFunction(() => {
const status = document.querySelector('section[aria-label="Bill of materials task"] p[role="status"]');
return Boolean(status) && /OPFS|保存/.test(status.textContent);
}, null, { timeout });
return page.evaluate(async (documentId) => {
const root = await navigator.storage.getDirectory();
const list = async name => {
try {
const dir = await root.getDirectoryHandle(name, { create: false });
const names = [];
for await (const [entry] of dir.entries()) names.push(entry);
return names.sort();
} catch {
return [];
}
};
const documents = (await list("freecad-documents")).filter(name => name.endsWith(".FCStd"));
const steps = await list("freecad-1-2");
const manifest = `${documentId}.assembly.json`;
return { files: documents, manifest, manifestStored: steps.includes(manifest) };
}, document);
}
/** Persist the assembly report next to the run evidence. */
export function writeAssemblyReport(runDir, document, report) {
fs.mkdirSync(runDir, { recursive: true });
const file = path.join(runDir, `${document}-assembly.json`);
fs.writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`);
return file;
}