Public: anyone can read this; the crew can change it.

Direction: full CAD in the forge, starting with opening and editing an STL #15737

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/15735-direction-full-cad-in-the-forge-starting → main 0 commits fork 4 threads · 4 unresolved

  • Merged. torque/15735-direction-full-cad-in-the-forge-starting was merged into main as b6e37a7.

Review

Sign in to review this change.
17 files changed +510 −15
docs/design/areas/model3d.md +1
@@ -5,3 +5,4 @@ The blob page's 3D view (`src/web/render/model3d.ts`), drawn for an STL, OBJ or
55 - `.model3d` — the view, with no box: a `.model3d-head` under a hairline carries a `dl` row (format, file size, then triangles and box once drawn) and the Wireframe and Axes toggles.
66 - `.model3d-tools` — the two toggles at the end of the head: `btn` with `pressed` (`aria-pressed`) and `js-only`. Hidden until the viewer has drawn the part.
77 - `.model3d-stage` — the drawing area, held at 4:3 (and at most 70% of the screen's height) before the viewer arrives, so nothing shifts when it does. It carries the empty state (`empty()`, the file icon) with Download until the canvas replaces it, and keeps it when there is no JavaScript or WebGL.
8 - `.model3d-cross` — the keyboard's crosshair for Measure: a ring in the one accent, placed over the canvas by the arrow keys and hidden until Measure is on. It takes no pointer events.
docs/features/file-media.md +1 −1
@@ -191,7 +191,7 @@ part, ready to turn (`src/web/render/model3d.ts`, #7335).
191191 - **Loaded only where needed:** three.js 0.186.1 is vendored, unedited, with
192192 its MIT licence, in `src/web/render/vendor/three/` (its README lists the
193193 files and their hashes). `model3d-client.ts` is bundled with it into
194 `/assets/model3d-<hash>.js` (648 KB, 166 KB gzipped, immutable), named by
194 `/assets/model3d-<hash>.js` (652 KB, 169 KB gzipped, immutable), named by
195195 a hash of its sources so the page knows the address without a build. The
196196 frame names it in `data-module`, and the shell loads it with its own nonce
197197 only when a figure asks, on a full load or when the code browser swaps the
docs/features/file-stl.md +14 −3
@@ -10,12 +10,23 @@ The first paint carries the triangle count and box, read by the server, so they
1010
1111 - `src/web/render/stl.ts` reads and checks the bytes (`readStl`); `mesh.ts` holds the shared parser; `model3d.ts`
1212 draws the frame; `model3d-client.ts` is the viewer script (the vendored three.js, loaded only by this page).
13 - Turn it with the pointer (drag to orbit, wheel to zoom) or the arrow keys once the canvas has focus; Wireframe and
14 Axes are buttons beside the facts.
13 - Turn it with the pointer (drag to orbit, wheel or pinch to zoom, right-drag or two fingers to pan) or the arrow keys
14 once the canvas has focus; it works by touch. Wireframe, Axes and **Measure** are buttons beside the facts.
15 - **Measure**: switch it on, pick two points on the part (tap it, or move the crosshair with the arrow keys, Shift
16 for bigger steps, and press Enter; the third pick starts again; a pinch or two-finger pan never picks), and the header reads the straight line between them,
17 `d = √(Δx² + Δy² + Δz²)`, with each axis's run and the unit (mm; `units` for an STL, which carries none).
18 A drag is an orbit, never a pick. The markers take the page's `--accent`. In the terminal, `m` on a model
19 asks for two points (`x y z x y z`) and answers with the same words. The arithmetic and the pick rules are
20 `measure.ts`, checked by hand in `test/model-measure.test.ts`.
21 - The **Box** row is the part's width × depth × height in that unit, shown for each format the viewer draws (STL, 3MF, OBJ, PLY, DAE, glTF).
22 - Editing a mesh is not built yet. The editor's refusal on a model or a STEP file says what opens it instead
23 (`opens_with.ts`); STEP still shows its part card, not geometry (that needs a CAD kernel in WebAssembly, a later pull).
1524 - The header and triangle count are checked against the byte length before any triangle is read. A truncated or
1625 damaged file, one with no triangles or a coordinate that is not a number, is refused with a sentence and Download.
1726 - Over 20 MB: refused with a sentence and never fetched; Download still streams it.
1827 - The server reads the whole file, up to 20 MB, for the first paint, so the facts show with JavaScript off at any size the page opens.
1928 - Try it: commit a `.stl` to a repository and open its file page.
2029
21 Pinned by `test/render-stl.test.ts` and `test/model3d.test.ts`. The viewer's neighbours: [mesh-files.md](mesh-files.md).
30 Pinned by `test/render-stl.test.ts`, `test/model3d.test.ts`, `test/tui-model3d.test.ts` (the `m` key) and
31 `test/model-edit-refusal.test.ts` (the edit page's sentence). The crosshair's keydown and the pointer wiring in
32 `model3d-client.ts` have no DOM test; the rules they call are pinned in `test/model-measure.test.ts`. The viewer's neighbours: [mesh-files.md](mesh-files.md).
src/tui/screens/workspace.ts +22 −1
@@ -56,6 +56,7 @@ import { tailOf, tailSentence } from "../../web/log_tail.ts";
5656 import { downloadHref } from "../../web/pages/media.ts";
5757 import { hexdump, HEX_BYTES } from "../../web/render/hexdump.ts";
5858 import { isModelPath, modelFacts } from "../../web/render/model-facts.ts";
59 import { measureTyped, unitFor } from "../../web/render/measure.ts";
5960 import type { RepoFacts, RepoSource } from "../../view/source.ts";
6061 import { detectLanguage, highlightLines } from "../../web/highlight.ts";
6162 import { MAX_COLUMNS, parseCsv, type Table } from "../../text/csv.ts";
@@ -1513,7 +1514,7 @@ export function workspaceScreen(
15131514 const facts = modelFacts(t.path, bytes, size);
15141515 noteTitle = facts.title;
15151516 note = facts.facts;
outdated

Both doors: this line only points at the web page. Measuring must be possible in the terminal too, or the pull must say it is web-only.

1516 noteDetail = downloadAt(t.path);
1517 noteDetail = `${downloadAt(t.path)}\nThe file page turns and measures it; m here measures two points you type; editing a mesh is not built yet.`;
15171518 };
15181519 let raw: Uint8Array | null = null;
15191520 let cut = "";
@@ -2296,6 +2297,7 @@ export function workspaceScreen(
22962297 ]),
22972298 ...(t !== undefined && t.tabular && isTablePath(t.path) ? [binding(["o"], "order rows by a column")] : []),
22982299 ...(t?.big == null ? [] : [binding(["m"], "open one key of the first level")]),
2300 ...(t !== undefined && isModelPath(t.path) && t.note !== "" && t.raw === null ? [binding(["m"], "measure between two points you type")] : []),
22992301 ...(t?.db == null ? [] : [binding([">", "<", "}", "{"], "next / previous 100 rows, next / previous table")]),
23002302 binding(["tab"], "focus explorer"),
23012303 binding(["e"], "edit", { disabled: !editable() }),
@@ -3142,6 +3144,24 @@ export function workspaceScreen(
31423144 return true;
31433145 }
31443146
3147 /** `m` on a model: type two points, read the distance in the page's words and the file's unit. */
3148 function measureModel(t: Tab): boolean {
3149 ctx.push(
3150 promptScreen(ctx, screen, {
3151 title: "Measure",
3152 label: "two points: x y z x y z",
3153 hint: `the straight line between them, in ${unitFor(t.path.slice(t.path.lastIndexOf(".") + 1))}`,
3154 onSubmit: (text) => {
3155 const said = measureTyped(text, t.path.slice(t.path.lastIndexOf(".") + 1));
3156 if (!said.startsWith("Distance")) return said;
3157 ctx.toast(said, "success");
3158 return undefined;
3159 },
3160 }),
3161 );
3162 return true;
3163 }
3164
31453165 /** Read mode: scroll, search, and the two keys that change what is open. */
31463166 function viewKey(t: Tab, e: KeyEvent): boolean {
31473167 if (e.key === "/") {
@@ -3151,6 +3171,7 @@ export function workspaceScreen(
31513171 if (e.key === "n" && !e.ctrl) return t.step(1);
31523172 if (e.key === "N") return t.step(-1);
31533173 if (e.key === "m" && !e.ctrl && t.big !== null) return openKey(t);
3174 if (e.key === "m" && !e.ctrl && isModelPath(t.path) && t.note !== "" && t.raw === null) return measureModel(t);
31543175 if (t.db !== null && t.asTable && (e.key === ">" || e.key === "<" || e.key === "}" || e.key === "{")) return pageDb(t, e.key);
31553176 // Horizontal scrolling belongs to code, which has long lines and a
31563177 // gutter; prose and pictures are already fitted to the pane.
src/web/pages/browse.ts +2 −1
@@ -25,6 +25,7 @@
2525 * labels and authors instead.
2626 */
2727
28 import { binaryRefusal } from "../render/opens_with.ts";
2829 import { mirrorJobFor, startMirrorJob } from "../../actions/origins.ts";
2930 import { forkOrigin } from "../../actions/contribute.ts";
3031 import { getOriginFor } from "../../core/origins.ts";
@@ -889,7 +890,7 @@ export async function browseEditPage(ctx: Ctx): Promise<Response> {
889890 tone: "danger",
890891 message:
891892 blob.value.kind === "binary"
892 ? "That file is binary — propose it with git, not a textarea."
893 ? binaryRefusal(path, "propose")
893894 : TOO_LARGE_TO_EDIT,
894895 },
895896 );
src/web/pages/edit.ts +2 −1
@@ -17,6 +17,7 @@
1717 * preview are `editorJs`, and none of them is load-bearing.
1818 */
1919
20 import { binaryRefusal } from "../render/opens_with.ts";
2021 import { fileKind, NO_BYTES } from "../render/kinds.ts";
2122 import { editFiles, MAX_FILE_BYTES } from "../../actions/contents.ts";
2223 import { shiftSubtitles } from "../../actions/subtitle_shift.ts";
@@ -626,7 +627,7 @@ export async function editPage(ctx: Ctx): Promise<Response> {
626627 tone: "danger",
627628 message:
628629 blob.value.kind === "binary"
629 ? "That file is binary — edit it with git, not a textarea."
630 ? binaryRefusal(path, "edit")
630631 : TOO_LARGE_TO_EDIT,
631632 },
632633 );
src/web/render/measure.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * Measuring on a model: the straight-line distance between two picked points,
3 * and the box a part fills, in the words the page already uses. Pure: the
4 * viewer (`model3d-client.ts`) picks the points, this does the arithmetic and
5 * the wording, and the tests check both against a hand calculation.
6 *
7 * Distance is the Euclidean norm, d = sqrt(dx² + dy² + dz²). Picking happens in
8 * world space, where the viewer only translates and rotates the part (never
9 * scales it), so a world distance is the model's own, in the file's unit.
10 */
11
12 export type Point = readonly [number, number, number];
13
14 /** d = sqrt(dx² + dy² + dz²), in the unit the points are in. */
15 export function distance(a: Point, b: Point): number {
16 return Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
17 }
18
19 /** The per-axis deltas of a measure, which is what a designer reads a dimension from. */
20 export function deltas(a: Point, b: Point): Point {
21 return [Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]), Math.abs(b[2] - a[2])];
22 }
23
24 const round = (v: number): string => String(Math.round(v * 100) / 100);
25
26 /** `5 mm (Δx 3 · Δy 4 · Δz 0)`: the length first, then where it runs. A unit is always stated. */
27 export function measureText(a: Point, b: Point, unit = "mm"): string {
28 const [dx, dy, dz] = deltas(a, b);
29 return `${round(distance(a, b))} ${unit} (Δx ${round(dx)} · Δy ${round(dy)} · Δz ${round(dz)})`;
30 }
31
32 /**
33 * The unit a measure is stated in: an STL carries none, so it says "units"; the rest are
34 * millimetres.
35 */
36 export const unitFor = (format: string): string => (format.toLowerCase() === "stl" ? "units" : "mm");
37
38 /** A pointer that moves this far (CSS px) between down and up is an orbit or a pan, not a pick. */
39 export const TAP_PX = 6;
40
41 /** A pick is the third point restarting: two points make a measure, a third begins another. */
42 export function nextPicks<T>(picks: readonly T[], p: T): T[] {
43 return picks.length >= 2 ? [p] : [...picks, p];
44 }
45
46 /**
47 * Tells a pick from a gesture. A pick is one pointer going down and up within TAP_PX; once a second
48 * pointer is down (a pinch or a two-finger pan) nothing is a pick until every pointer is up.
49 */
50 export class PickGesture {
51 private readonly down = new Map<number, readonly [number, number]>();
52 private spoiled = false;
53
54 press(id: number, x: number, y: number): void {
55 if (this.down.size > 0) this.spoiled = true;
56 this.down.set(id, [x, y]);
57 }
58
59 /** True when this release completes a pick. */
60 release(id: number, x: number, y: number): boolean {
61 const at = this.down.get(id);
62 this.down.delete(id);
63 const spoiled = this.spoiled;
64 if (this.down.size === 0) this.spoiled = false;
65 if (at === undefined || spoiled) return false;
66 return Math.hypot(x - at[0], y - at[1]) < TAP_PX;
67 }
68
69 /** A cancelled pointer (the browser took it for a scroll) is never a pick. */
70 cancel(id: number): void {
71 this.down.delete(id);
72 this.spoiled = this.down.size > 0;
73 }
74 }
75
76 /**
77 * The keyboard's crosshair, in the canvas's normalised coordinates (-1..1), moved by the arrow
78 * keys.
79 */
80 export function moveCrosshair(at: readonly [number, number], key: string, step = 0.05): readonly [number, number] | null {
81 const d: Record<string, readonly [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] };
82 const m = d[key];
83 if (m === undefined) return null;
84 const c = (v: number): number => Math.max(-1, Math.min(1, Math.round(v * 1000) / 1000));
85 return [c(at[0] + m[0]), c(at[1] + m[1])];
86 }
87
88 /** `1 2 3, 4 5 6` (commas or spaces) as two points, or why not: the terminal's way to measure. */
89 export function parseTwoPoints(text: string): readonly [Point, Point] | string {
90 const n = text.split(/[\s,;]+/).filter((s) => s !== "");
91 if (n.length !== 6) return "Give six numbers: x y z for the first point, then x y z for the second.";
92 const v = n.map((s) => (/^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(s) ? Number(s) : Number.NaN));
93 if (v.some((x) => !Number.isFinite(x))) return "Every coordinate must be a plain number.";
94 return [[v[0]!, v[1]!, v[2]!], [v[3]!, v[4]!, v[5]!]];
95 }
96
97 /** The terminal's measure: two points typed in, the page's words back. */
98 export function measureTyped(text: string, format: string): string {
99 const p = parseTwoPoints(text);
100 return typeof p === "string" ? p : `Distance ${measureText(p[0], p[1], unitFor(format))}`;
101 }
src/web/render/model3d-client.ts +112 −4
@@ -21,6 +21,8 @@ import {
2121 DirectionalLight,
2222 DoubleSide,
2323 Float32BufferAttribute,
24 Line,
25 LineBasicMaterial,
2426 GridHelper,
2527 HemisphereLight,
2628 LoadingManager,
@@ -28,6 +30,9 @@ import {
2830 MeshStandardMaterial,
2931 type Object3D,
3032 PerspectiveCamera,
33 Raycaster,
34 SphereGeometry,
35 Vector2,
3136 Scene,
3237 Vector3,
3338 WebGLRenderer,
@@ -40,6 +45,7 @@ import { daeFromText } from "./collada.ts";
4045 import { ObjFallback, objFromText } from "./obj.ts";
4146 import { bounds, indexedRows, OVER_CAP_NOTE, parseStl, sizeText, type Bounds, type Mesh as Parsed } from "./mesh.ts";
4247 import { parsePly } from "./ply.ts";
48 import { measureText, moveCrosshair, nextPicks, PickGesture, unitFor, type Point } from "./measure.ts";
4349
4450 /**
4551 * The little of the DOM this touches. The checker runs without the DOM
@@ -56,15 +62,29 @@ interface Element {
5662 querySelectorAll(selector: string): Iterable<Element>;
5763 getAttribute(name: string): string | null;
5864 setAttribute(name: string, value: string): void;
59 addEventListener(type: string, listener: () => void): void;
65 className: string;
66 readonly style: { left: string; top: string };
67 addEventListener(type: string, listener: (event: PointerLike) => void, capture?: boolean): void;
68 append(...nodes: Element[]): void;
69 focus(): void;
6070 replaceChildren(...nodes: Element[]): void;
61 getBoundingClientRect(): { width: number; height: number };
71 getBoundingClientRect(): { left: number; top: number; width: number; height: number };
72 }
73 /** The few fields of a pointer event the measure tool reads. */
74 interface PointerLike {
75 readonly clientX: number;
76 readonly clientY: number;
77 readonly pointerId: number;
78 readonly key: string;
79 readonly shiftKey: boolean;
80 preventDefault(): void;
81 stopImmediatePropagation(): void;
6282 }
6383 interface Browser {
6484 readonly document: Element & { createElement(tag: string): Element };
6585 readonly devicePixelRatio: number;
6686 readonly location: { readonly href: string };
67 getComputedStyle(element: Element): { color: string };
87 getComputedStyle(element: Element): { color: string; getPropertyValue(name: string): string };
6888 ResizeObserver: new (callback: () => void) => { observe(element: Element): void; disconnect(): void };
6989 }
7090 const { document, devicePixelRatio, location, getComputedStyle, ResizeObserver } = globalThis as unknown as Browser;
@@ -274,7 +294,17 @@ function mount(figure: Element): void {
274294 const on = button.getAttribute("aria-pressed") !== "true";
275295 button.setAttribute("aria-pressed", String(on));
276296 if (button.value === "axes") axes.visible = on;
277 else
297 else if (button.value === "measure") {
298 measuring = on;
299 clear();
300 cross.hidden = !on;
301 if (on) {
302 at = [0, 0];
303 place();
304 canvas.focus();
305 }
306 stats.textContent = on ? "Pick two points: tap the part, or arrows to move the crosshair and Enter." : "";
307 } else
278308 object.traverse((node) => {
279309 if (node instanceof Mesh)
280310 for (const m of [node.material].flat()) m.wireframe = on;
@@ -282,6 +312,84 @@ function mount(figure: Element): void {
282312 draw();
283313 });
284314 }
outdated

The pick is pointer-only (no keyboard path), and a single 'down' is overwritten by a second finger, so a pinch or pan can end as a pick. Track pointerId and ignore picks while more than one pointer is down.

315 // Measure: two picks give the distance between them, in the file's unit. A pick is a tap
316 // (one pointer, moved < TAP_PX; a drag is an orbit, two fingers are a pinch) or Enter at the
317 // crosshair the arrow keys move while Measure is on. The third pick starts again.
318 const unit = unitFor(format);
319 const raycaster = new Raycaster();
320 const marks: Object3D[] = [];
321 let picks: Vector3[] = [];
322 const markSize = span / 120;
323 // The one accent, from the page's token; the text colour if the token is not a colour here.
324 const accent = ((): Color => {
325 const token = getComputedStyle(figure).getPropertyValue("--accent").trim();
326 return token === "" ? ink : new Color(token);
327 })();
328 const clear = (): void => {
329 for (const m of marks.splice(0)) scene.remove(m);
330 picks = [];
331 };
332 const pick = (x: number, y: number): void => {
outdated

Principle 5: hard-coded 0xe5484d is a second accent. Use the --accent token's colour or keep the markers neutral.

333 raycaster.setFromCamera(new Vector2(x, y), camera);
334 const hit = raycaster.intersectObject(object, true)[0];
335 if (hit === undefined) return;
336 if (picks.length >= 2) clear();
337 picks = nextPicks(picks, hit.point.clone());
338 const dot = new Mesh(new SphereGeometry(markSize), new MeshStandardMaterial({ color: accent.getHex() }));
339 dot.position.copy(hit.point);
340 scene.add(dot);
341 marks.push(dot);
342 const [a, b] = picks;
343 if (a !== undefined && b !== undefined) {
344 const line = new Line(
345 new BufferGeometry().setFromPoints([a, b]),
346 new LineBasicMaterial({ color: accent.getHex(), depthTest: false }),
347 );
348 scene.add(line);
349 marks.push(line);
350 const p = (v: Vector3): Point => [v.x, v.y, v.z];
351 stats.textContent = `Distance ${measureText(p(a), p(b), unit)}`;
352 } else stats.textContent = "Pick a second point (Enter at the crosshair, or tap).";
353 draw();
354 };
355 let measuring = false;
356 const gesture = new PickGesture();
357 canvas.addEventListener("pointerdown", (e) => gesture.press(e.pointerId, e.clientX, e.clientY));
358 canvas.addEventListener("pointercancel", (e) => gesture.cancel(e.pointerId));
359 canvas.addEventListener("pointerup", (e) => {
360 const tap = gesture.release(e.pointerId, e.clientX, e.clientY);
361 if (!measuring || !tap) return;
362 const rect = canvas.getBoundingClientRect();
363 pick(((e.clientX - rect.left) / rect.width) * 2 - 1, -(((e.clientY - rect.top) / rect.height) * 2 - 1));
364 });
365 // The keyboard's way: a crosshair the arrows move (they pan the view otherwise), Enter picks.
366 const cross = document.createElement("span");
367 cross.className = "model3d-cross";
368 cross.hidden = true;
369 stage.append(cross);
370 let at: readonly [number, number] = [0, 0];
371 const place = (): void => {
372 cross.style.left = `${(at[0] + 1) * 50}%`;
373 cross.style.top = `${(1 - at[1]) * 50}%`;
374 };
375 canvas.addEventListener(
376 "keydown",
377 (e) => {
378 if (!measuring) return;
379 if (e.key === "Enter") {
380 e.preventDefault();
381 pick(at[0], at[1]);
382 return;
383 }
384 const moved = moveCrosshair(at, e.key, e.shiftKey ? 0.2 : 0.05);
385 if (moved === null) return;
386 e.preventDefault();
387 e.stopImmediatePropagation();
388 at = moved;
389 place();
390 },
391 true,
392 );
285393 tools.hidden = false;
286394 live.push({
287395 figure,
src/web/render/model3d-css.ts +2
@@ -8,6 +8,8 @@ export const model3dCss = /* css */ `
88 .model3d-head .row-facts { display: flex; flex-wrap: wrap; gap: 4px 16px; margin: 0; }
99 .model3d-tools { display: inline-flex; gap: 6px; }
1010 .model3d-stage { position: relative; aspect-ratio: 4 / 3; max-height: 70dvh; width: 100%; display: grid; place-items: center; touch-action: none; }
11 .model3d-cross { position: absolute; width: 20px; height: 20px; transform: translate(-50%, -50%); border: 2px solid var(--accent); border-radius: 50%; pointer-events: none; }
12 .model3d-cross[hidden] { display: none; }
1113 .model3d-stage > canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
1214 }
1315 `;
src/web/render/model3d.ts +2 −2
@@ -88,7 +88,7 @@ export function model3d(input: RenderInput): Rendered {
8888 <span class="muted" data-stats aria-live="polite"></span>
8989 <span class="spacer"></span>
9090 <span class="model3d-tools" data-tools hidden>
91 ${toggle("Wireframe", "wireframe")} ${toggle("Axes", "axes")}
91 ${toggle("Wireframe", "wireframe")} ${toggle("Axes", "axes")} ${toggle("Measure", "measure")}
9292 </span>
9393 </figcaption>
9494 <div class="model3d-stage" data-stage>
@@ -109,7 +109,7 @@ function sources(): string[] {
109109 readdirSync(dir, { withFileTypes: true })
110110 .flatMap((e) => (e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]))
111111 .sort();
112 return [ENTRY, join(import.meta.dir, "mesh.ts"), join(import.meta.dir, "collada.ts"), join(import.meta.dir, "ply.ts"), ...walk(VENDOR)];
112 return [ENTRY, join(import.meta.dir, "mesh.ts"), join(import.meta.dir, "measure.ts"), join(import.meta.dir, "collada.ts"), join(import.meta.dir, "ply.ts"), ...walk(VENDOR)];
113113 }
114114
115115 let path: string | null = null;
src/web/render/opens_with.ts added +21
@@ -0,0 +1,21 @@
1 /**
2 * What opens a file the editor refuses: a binary file has no textarea, but a
3 * model has a viewer, and a refusal names it instead of only saying no.
4 * Editing a mesh in the browser is not built yet (docs/features/file-stl.md);
5 * the sentence says so rather than promise it.
6 */
7
8 const VIEWABLE = new Set(["stl", "obj", "3mf", "ply", "dae", "glb", "gltf"]);
9 const CAD = new Set(["step", "stp"]);
10
11 const extension = (path: string): string => path.slice(path.lastIndexOf(".") + 1).toLowerCase();
12
13 /** The sentence over a binary file the editor will not open; `verb` is `edit` or `propose`. */
14 export function binaryRefusal(path: string, verb: "edit" | "propose" = "edit"): string {
15 const ext = extension(path);
16 if (VIEWABLE.has(ext))
17 return `That is a 3D model — the file page opens it in a viewer you can turn and measure. Editing meshes here is not built yet: download it, change it in a CAD or slicer tool, and ${verb === "edit" ? "upload the result with git" : "propose it with git"}.`;
18 if (CAD.has(ext))
19 return `That is a STEP file — the file page shows its parts and entity counts, and a CAD tool (FreeCAD, Fusion, Onshape) opens it whole. Download it to change it, then ${verb === "edit" ? "commit the result with git" : "propose it with git"}.`;
20 return `That file is binary — ${verb} it with git, not a textarea.`;
21 }
src/web/render/vendor/three.d.ts +20
@@ -19,9 +19,27 @@ declare module "three" {
1919 multiplyScalar(s: number): this;
2020 normalize(): this;
2121 length(): number;
22 clone(): Vector3;
23 }
24 export class Vector2 {
25 constructor(x?: number, y?: number);
26 }
27 export class Raycaster {
28 setFromCamera(coords: Vector2, camera: PerspectiveCamera): void;
29 intersectObject(object: Object3D, recursive?: boolean): { point: Vector3; distance: number }[];
30 }
31 export class SphereGeometry extends BufferGeometry {
32 constructor(radius?: number);
33 }
34 export class LineBasicMaterial extends Material {
35 constructor(parameters?: { color?: number; depthTest?: boolean });
36 }
37 export class Line extends Object3D {
38 constructor(geometry?: BufferGeometry, material?: Material);
2239 }
2340 export class Color {
2441 constructor(color: string | number);
42 getHex(): number;
2543 }
2644 export class Box3 {
2745 min: Vector3;
@@ -35,6 +53,7 @@ declare module "three" {
3553 rotation: { x: number; y: number; z: number };
3654 visible: boolean;
3755 add(...objects: Object3D[]): this;
56 remove(...objects: Object3D[]): this;
3857 traverse(callback: (object: Object3D) => void): void;
3958 updateMatrixWorld(force?: boolean): void;
4059 }
@@ -66,6 +85,7 @@ declare module "three" {
6685 setAttribute(name: string, attribute: BufferAttribute): this;
6786 getAttribute(name: string): BufferAttribute | undefined;
6887 computeVertexNormals(): void;
88 setFromPoints(points: Vector3[]): this;
6989 }
7090 export class Mesh extends Object3D {
7191 constructor(geometry?: BufferGeometry, material?: Material);
test/model-edit-refusal.test.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * The edit page refuses a model in words that name its viewer (#15735): the refusal is
3 * `binaryRefusal` wired into `src/web/pages/edit.ts`, carried as a flash to the file page.
4 */
5
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { seedAdmin } from "./helpers/admin.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dataDir = "";
20 let app: App;
21 let servers: Servers;
22 let cookie = "";
23
24 beforeAll(async () => {
25 dataDir = await mkdtemp(join(tmpdir(), "forge-model-edit-"));
26 app = createApp({ dataDir, port: 0 });
27 servers = await serve(app);
28 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-long-model-passphrase" });
29 if (!a.ok) throw new Error("signup failed");
30 cookie = `forge_session=${createSession(app.db, a.value.id).token}`;
31 const made = await createRepo(app, a.value, { name: "tower", visibility: "public" });
32 if (!made.ok) throw new Error("repo failed");
33 await commitToBranch(app, a.value, made.value, {
34 message: "parts",
35 files: [
36 { path: "README.md", content: "# tower\n" },
37 { path: "parts/cube.stl", content: await Bun.file(join(import.meta.dir, "fixtures", "model3d", "cube-binary.stl")).bytes() },
38 ],
39 });
40 });
41
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dataDir, { recursive: true, force: true });
46 });
47
48 test("editing a .stl sends you to its file page with the model sentence, not 'binary'", async () => {
49 const res = await fetch(`${servers.url}/alice/tower/edit/main/parts/cube.stl`, { redirect: "manual", headers: { cookie } });
50 expect(res.status).toBeGreaterThanOrEqual(300);
51 expect(res.status).toBeLessThan(400);
52 const to = res.headers.get("location") ?? "";
53 expect(to).toContain("/alice/tower/blob/main/parts/cube.stl");
54 const flash = (res.headers.get("set-cookie") ?? "").match(/forge_flash=([^;]*)/)?.[1] ?? "";
55 const page = await (await fetch(new URL(to, servers.url), { headers: { cookie: `${cookie}; forge_flash=${flash}` } })).text();
56 expect(page).toContain("That is a 3D model — the file page opens it in a viewer you can turn and measure.");
57 expect(page).toContain("download it, change it in a CAD or slicer tool, and upload the result with git.");
58 expect(page).not.toContain("That file is binary");
59 });
test/model-measure.test.ts added +101
@@ -0,0 +1,101 @@
1 /** Measuring on a model, and what a refused binary edit points at (#15735). */
2 import { describe, expect, test } from "bun:test";
3 import { deltas, distance, measureText, measureTyped, moveCrosshair, nextPicks, parseTwoPoints, PickGesture, unitFor } from "../src/web/render/measure.ts";
4 import { binaryRefusal } from "../src/web/render/opens_with.ts";
5 import { model3d } from "../src/web/render/model3d.ts";
6
7 describe("measure", () => {
8 test("a 3-4-5 triangle measures 5, by hand", () => {
9 expect(distance([0, 0, 0], [3, 4, 0])).toBe(5);
10 expect(distance([1, 1, 1], [3, 3, 2])).toBe(3); // sqrt(4 + 4 + 1)
11 });
12 test("the deltas are absolute, per axis", () => {
13 expect(deltas([5, 0, 2], [1, 3, 2])).toEqual([4, 3, 0]);
14 });
15 test("the words state the unit and the per-axis run", () => {
16 expect(measureText([0, 0, 0], [3, 4, 0])).toBe("5 mm (Δx 3 · Δy 4 · Δz 0)");
17 expect(measureText([0, 0, 0], [0, 0, 1.005], "units")).toContain("units");
18 });
19 });
20
21 describe("binaryRefusal", () => {
22 test("a model names its viewer and says editing is not built", () => {
23 for (const p of ["a/part.STL", "b.3mf", "c.obj"]) {
24 const said = binaryRefusal(p);
25 expect(said).toContain("viewer");
26 expect(said).toContain("not built yet");
27 }
28 });
29 test("a STEP file names the part card and a CAD tool", () => {
30 expect(binaryRefusal("x.step")).toContain("CAD tool");
31 });
32 test("any other binary keeps the old sentence, in either verb", () => {
33 expect(binaryRefusal("a.bin")).toBe("That file is binary — edit it with git, not a textarea.");
34 expect(binaryRefusal("a.bin", "propose")).toBe("That file is binary — propose it with git, not a textarea.");
35 });
36 });
37
38 describe("the viewer's frame", () => {
39 test("offers Measure beside Wireframe and Axes", () => {
40 const out = model3d({ path: "p.stl", body: new Uint8Array(0), size: 0, media: "/m", download: "/d" });
41 expect(String(out.content)).toContain('value="measure"');
42 });
43 });
44
45 describe("picking", () => {
46 test("an STL is measured in units, every other format in mm", () => {
47 expect(unitFor("stl")).toBe("units");
48 expect(unitFor("STL")).toBe("units");
49 for (const f of ["obj", "3mf", "ply", "glb"]) expect(unitFor(f)).toBe("mm");
50 });
51 test("a third pick starts a new measure", () => {
52 expect(nextPicks([], "a")).toEqual(["a"]);
53 expect(nextPicks(["a"], "b")).toEqual(["a", "b"]);
54 expect(nextPicks(["a", "b"], "c")).toEqual(["c"]);
55 });
56 test("a tap is a pick; a drag of 6 px or more is not", () => {
57 const g = new PickGesture();
58 g.press(1, 100, 100);
59 expect(g.release(1, 103, 104)).toBe(true); // 5 px
60 g.press(1, 100, 100);
61 expect(g.release(1, 106, 100)).toBe(false); // 6 px
62 });
63 test("a second finger spoils the gesture until every pointer is up", () => {
64 const g = new PickGesture();
65 g.press(1, 0, 0);
66 g.press(2, 50, 50);
67 expect(g.release(2, 50, 50)).toBe(false);
68 expect(g.release(1, 0, 0)).toBe(false);
69 g.press(3, 0, 0);
70 expect(g.release(3, 0, 0)).toBe(true);
71 });
72 test("a cancelled pointer is no pick, and a release with no press is none", () => {
73 const g = new PickGesture();
74 g.press(1, 0, 0);
75 g.cancel(1);
76 expect(g.release(1, 0, 0)).toBe(false);
77 });
78 });
79
80 describe("the keyboard's crosshair", () => {
81 test("arrows move it, up is +y, and it stays inside the canvas", () => {
82 expect(moveCrosshair([0, 0], "ArrowRight")).toEqual([0.05, 0]);
83 expect(moveCrosshair([0, 0], "ArrowUp")).toEqual([0, 0.05]);
84 expect(moveCrosshair([0, 0], "ArrowDown", 0.2)).toEqual([0, -0.2]);
85 expect(moveCrosshair([0.98, 0], "ArrowRight")).toEqual([1, 0]);
86 expect(moveCrosshair([0, 0], "a")).toBeNull();
87 });
88 });
89
90 describe("measuring in the terminal", () => {
91 test("two typed points give the page's words, in the file's unit", () => {
92 expect(measureTyped("0 0 0, 3 4 0", "stl")).toBe("Distance 5 units (Δx 3 · Δy 4 · Δz 0)");
93 expect(measureTyped("0,0,0 1,2,2", "3mf")).toBe("Distance 3 mm (Δx 1 · Δy 2 · Δz 2)");
94 });
95 test("anything but six plain numbers is refused with a sentence", () => {
96 expect(parseTwoPoints("1 2 3")).toContain("six numbers");
97 expect(parseTwoPoints("1 2 3 4 5 x")).toContain("plain number");
98 expect(parseTwoPoints("1 2 3 4 5 Infinity")).toContain("plain number");
99 expect(parseTwoPoints("1 2 3 4 5 6")).toEqual([[1, 2, 3], [4, 5, 6]]);
100 });
101 });
test/model3d.test.ts +1 −1
@@ -114,7 +114,7 @@ describe("which files the 3D view draws", () => {
114114 test("the toggles are script-only buttons that say whether they are held, and the note is the empty state", () => {
115115 const { content } = model3d({ path: "a.stl", size: 5, body, media: "/m", download: "/m?download=1" });
116116 const toggles = content.text.match(/<button[^>]*>/g) ?? [];
117 expect(toggles).toHaveLength(2);
117 expect(toggles).toHaveLength(3);
118118 for (const b of toggles) {
119119 expect(b).toContain('type="button"');
120120 expect(b).toMatch(/class="btn js-only"/);
test/render-css-client.test.ts +4 −1
@@ -42,7 +42,10 @@ describe.each(Object.entries(SHEETS))("%s-css", (name, css) => {
4242 });
4343
4444 describe("model3d-client", () => {
45 /** "(648 KB, 166 KB gzipped" in the feature page: the stated size is the budget. */
45 /**
46 * "(N KB, M KB gzipped" in the feature page (docs/features/file-media.md): the stated size is the
47 * budget.
48 */
4649 const stated = (): { raw: number; gzip: number } => {
4750 const doc = readFileSync(new URL("../docs/features/file-media.md", import.meta.url), "utf8").replace(/\s+/g, " ");
4851 const m = /model3d-<hash>\.js` \((\d+) KB, (\d+) KB gzipped/.exec(doc);
test/tui-model3d.test.ts +45
@@ -112,3 +112,48 @@ test("a guest in the terminal gets nothing of a model in a private repo", async
112112 app.stop();
113113 }
114114 });
115
116 test("m on a model asks for two points and answers with the distance, or with why not", async () => {
117 const user = getUserByName(forge.db, "alice");
118 if (user === undefined) throw new Error("no alice");
119 const { app } = createForgeApp(
120 forge,
121 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
122 { terminal: headlessTerminal(140, 40), exitHooks: false },
123 );
124 app.start();
125 const send = (key: string): void => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
126 const type = (text: string): void => {
127 for (const ch of text) send(ch);
128 };
129 try {
130 await settleApp(app);
131 send("/");
132 type("tower");
133 send("enter");
134 send("enter");
135 await settleUntil(app, "alice/tower");
136 send("t");
137 await settleApp(app);
138 type("cubestl");
139 send("enter");
140 await settleUntil(app, "12 triangles");
141 send("?");
142 await settleUntil(app, "measure between two points you type");
143 send("escape");
144 await settleApp(app);
145 send("m");
146 await settleUntil(app, "two points: x y z");
147 expect(app.screen.toText()).toContain("in units");
148 type("1 2 3");
149 send("enter");
150 await settleUntil(app, "Give six numbers");
151 for (let i = 0; i < 5; i++) send("backspace");
152 type("0 0 0 3 4 0");
153 send("enter");
154 await settleUntil(app, "Distance 5 units (Δx 3 · Δy 4 · Δz 0)");
155 expect(app.screen.toText()).not.toContain("two points: x y z");
156 } finally {
157 app.stop();
158 }
159 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs