Files
FreeCADWasmDev/web/tools/cad-ui-rebuild/lib/assembly.mjs
Claude fd37b92fd9 teaching: run lessons in-app through an iframe-driven console
The teaching console now lives inside Web FreeCAD: web/teaching-console.html
hosts the workbench in a same-origin iframe and drives its DOM directly, with
no Node server and no spawned Chrome. The driver modules run in the framed
page's own realm (bridge.ts publishes window.__teaching), so the proven
driver/assembly code is reused unchanged and the CSP without 'unsafe-eval' is
never crossed.

- steps.ts globs both courses' ui-steps records (skipping their index.json
  manifests) so each lesson downloads only its own chunk
- runner.ts checks prerequisites in dependency order, then runs part or
  assembly lessons; a pass stores the FCStd in OPFS freecad-documents under
  the course document name, which is what assembly lessons consume
- assembly lessons insert, joint, solve and save through lib/assembly.mjs;
  insertLink falls back to UI-suffixed object names (Body1 for Body)
- check-inapp-console.mjs (npm run check:console-inapp) is green: preflight,
  P01 volume within 6e-13, OPFS evidence, both viewports
- run-inapp-lessons.mjs runs a whole course in one browser; reducer 23 parts
  + assembly and carrier 20 parts + assembly all pass in-browser

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

292 lines
14 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.
// No Node imports here on purpose: this module is also loaded inside the
// teaching console's workbench frame, where `document` is the real workspace.
// Filesystem reporting lives in `assembly-report.mjs`.
/** 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.
let key = `${sourceDocument}:${sourceObject}`;
const values = await objectSelect.evaluate(node => [...node.options].map(option => option.value));
if (!values.includes(key)) {
// Documents built through the workbench UI suffix their object names --
// its `unique()` always yields `Body1`, `Sketch1`, … -- while the course
// data was captured from kernel-built reference files that use the bare
// names (`Body`). Fall back to the lowest suffixed match so one replay
// drives both kinds of source document.
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const suffixed = values
.map(value => ({ value, index: Number(new RegExp(`^${escaped}(\\d+)$`).exec(value)?.[1] ?? NaN) }))
.filter(entry => Number.isFinite(entry.index))
.sort((a, b) => a.index - b.index);
if (suffixed.length) key = suffixed[0].value;
}
if (!values.includes(key)) throw new Error(`source object ${sourceDocument}:${sourceObject} 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.
* @param {unknown} page
* @param {Array<{sourceDocument: string, sourceObject: string, position: number[], rotation: number[]}>} inserts
* @param {{groundDocument?: string | null, loadOne?: (page: unknown, fileName: string) => Promise<void>}} [options]
*/
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.
*/
// The option is `documentId`, not `document`: the callbacks below run through
// `page.waitForFunction`, and in the in-app console they execute in this very
// scope. A parameter named `document` would shadow the page's global `document`
// there and turn `document.querySelector` into a call on a string.
export async function saveAssemblyBundle(page, { document: documentId, 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) };
}, documentId);
}