Public: anyone can read this; the crew can change it.
A DXF drawing measures: pick two points and read the distance in the drawing's units #16827
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/16314-a-dxf-drawing-measures-pick-two-points-a → main 0 commits fork 5 threads · 5 unresolved
- docs/features/file-dxf.md
- scripts/unreached.ts
- src/http/server.ts
- src/tui/screens/workspace.ts
- src/web/asset.ts
- src/web/render/dxf-asset.ts
- src/web/render/dxf-client.ts
- src/web/render/dxf.ts
- src/web/render/measure.ts
- src/web/render/model3d.ts
- src/web/style/content.ts
- test/render-dxf.test.ts
- test/tui-dxf-measure.test.ts
docs/features/file-dxf.md +17
| @@ -18,3 +18,20 @@ Source is one tap away. | ||
| 18 | 18 | - No ENTITIES section, no EOF, no drawable entity, or a file past the size |
| 19 | 19 | cap: the source view, with the reason. |
| 20 | 20 | - Try it: commit a `.dxf` to a repository and open its file page. |
| 21 | ||
| 22 | ## Measuring | |
| 23 | ||
| 24 | Tap two points on the drawing and the distance reads under it, in the unit the | |
| 25 | file names: `$INSUNITS` in the header (`4` is mm, `1` inches, and so on, the | |
| 26 | DXF reference's table in `src/web/render/measure.ts`). A file whose `$INSUNITS` | |
| 27 | is absent or 0 says it names no unit and shows `raw units`. A third tap starts | |
| 28 | over. The readout is text in a live region, so a screen reader hears it. | |
| 29 | ||
| 30 | - Keyboard: focus the drawing, arrows move a crosshair, Enter or Space picks. | |
| 31 | - Distance is d = sqrt(dx² + dy²) on the drawing's plane, seven significant | |
| 32 | digits; the points come from the SVG's own fit back to drawing coordinates | |
| 33 | (`toDrawing`), so it is the file's distance, not the screen's. | |
| 34 | - Terminal: `m` on an open `.dxf` asks for `x y x y` and answers in the same | |
| 35 | words (`measureDxfTyped`). | |
| 36 | - The script is `dxf-client.ts`, bundled once as `/assets/dxf-<hash>.js` and | |
| 37 | loaded only on a page with a drawing. The render caps are unchanged. |
scripts/unreached.ts +2
| @@ -29,6 +29,8 @@ export const ENTRIES = [ | ||
| 29 | 29 | "src/tui/gallery.ts", |
| 30 | 30 | // Bundled for the browser by Bun.build in src/web/asset.ts, named there by a template path. |
| 31 | 31 | "src/web/highlight-client.ts", |
| 32 | // Bundled for the browser by Bun.build in src/web/render/dxf-asset.ts, named there by path. | |
| 33 | "src/web/render/dxf-client.ts", | |
| 32 | 34 | ]; |
| 33 | 35 | |
| 34 | 36 | /** Loaded by listing the directory, so nothing imports them: the duty roster (#14355). */ |
src/http/server.ts +5 −4
| @@ -255,6 +255,7 @@ import { | ||
| 255 | 255 | } from "../web/pages/repo.ts"; |
| 256 | 256 | import { mediaBlob } from "../web/pages/media.ts"; |
| 257 | 257 | import { model3dAsset } from "../web/render/model3d.ts"; |
| 258 | import { dxfAsset } from "../web/render/dxf-asset.ts"; | |
| 258 | 259 | import { |
| 259 | 260 | branchCreate, |
| 260 | 261 | branchDelete, |
| @@ -941,10 +942,10 @@ export function buildRouter(): Router<Handler> { | ||
| 941 | 942 | const term = await machineTermAsset(); |
| 942 | 943 | return term !== null && ctx.params.name === term.name ? assetResponse(ctx.request, term) : assetNotFound(); |
| 943 | 944 | } |
| 944 | if (ctx.params.name!.startsWith("model3d-")) { | |
| 945 | const viewer = await model3dAsset(); | |
| 946 | if (viewer === null || ctx.params.name !== viewer.name) return assetNotFound(); | |
| 947 | return assetResponse(ctx.request, viewer); | |
| 945 | for (const [prefix, load] of [["model3d-", model3dAsset], ["dxf-", dxfAsset]] as const) { | |
| 946 | if (!ctx.params.name!.startsWith(prefix)) continue; | |
| 947 | const built = await load(); | |
| 948 | return built === null || ctx.params.name !== built.name ? assetNotFound() : assetResponse(ctx.request, built); | |
| 948 | 949 | } |
| 949 | 950 | const asset = await highlightAsset(); |
| 950 | 951 | if (asset === null || ctx.params.name !== asset.name) return assetNotFound(); |
src/tui/screens/workspace.ts +23 −4
| @@ -60,6 +60,7 @@ import { hexdump, HEX_BYTES } from "../../web/render/hexdump.ts"; | ||
| 60 | 60 | import { STL_LIMIT } from "../../web/render/stl.ts"; |
| 61 | 61 | import { stlForm, stlHref } from "../../web/render/stl_convert.ts"; |
| 62 | 62 | import { isModelPath, modelFacts } from "../../web/render/model-facts.ts"; |
| 63 | import { measureDxfTyped, parseDxf } from "../../web/render/dxf.ts"; | |
| 63 | 64 | import { measureTyped, unitFor } from "../../web/render/measure.ts"; |
| 64 | 65 | import type { RepoFacts, RepoSource } from "../../view/source.ts"; |
| 65 | 66 | import { detectLanguage, highlightLines } from "../../web/highlight.ts"; |
| @@ -2402,6 +2403,7 @@ export function workspaceScreen( | ||
| 2402 | 2403 | ...(t !== undefined && t.tabular && isTablePath(t.path) ? [binding(["o"], "order rows by a column")] : []), |
| 2403 | 2404 | ...(t?.big == null ? [] : [binding(["m"], "open one key of the first level")]), |
| 2404 | 2405 | ...(t !== undefined && isModelPath(t.path) && t.note !== "" && t.raw === null ? [binding(["m"], "measure between two points you type")] : []), |
| 2406 | ...(t !== undefined && isDrawing(t) ? [binding(["m"], "measure between two points on the drawing")] : []), | |
| 2405 | 2407 | ...(t?.db == null ? [] : [binding([">", "<", "}", "{"], "next / previous 100 rows, next / previous table")]), |
| 2406 | 2408 | binding(["tab"], "focus explorer"), |
| 2407 | 2409 | binding(["e"], "edit", { disabled: !editable() }), |
| @@ -3289,15 +3291,31 @@ export function workspaceScreen( | ||
| 3289 | 3291 | return true; |
| 3290 | 3292 | } |
| 3291 | 3293 | |
| 3292 | /** `m` on a model: type two points, read the distance in the page's words and the file's unit. */ | |
| 3294 | /** A .dxf the tab shows as a drawing: no note, and its text reads as DXF (not a binary's hex). */ | |
| 3295 | const drawn = new WeakMap<Tab, { plain: readonly string[]; ok: boolean }>(); | |
| 3296 | function isDrawing(t: Tab): boolean { | |
| 3297 | if (!/\.dxf$/i.test(t.path) || t.note !== "") return false; | |
| 3298 | const seen = drawn.get(t); | |
| 3299 | if (seen !== undefined && seen.plain === t.plain) return seen.ok; | |
| 3300 | const ok = !("error" in parseDxf(t.plain.join("\n"))); | |
| 3301 | drawn.set(t, { plain: t.plain, ok }); | |
| 3302 | return ok; | |
| 3303 | } | |
| 3304 | ||
| 3305 | /** | |
| 3306 | * `m` on a model or a drawing: type two points, read the distance in the page's words and the | |
| 3307 | * file's unit. | |
| 3308 | */ | |
| 3293 | 3309 | function measureModel(t: Tab): boolean { |
| 3310 | const dxf = /\.dxf$/i.test(t.path); | |
| 3311 | const ext = t.path.slice(t.path.lastIndexOf(".") + 1); | |
| 3294 | 3312 | ctx.push( |
| 3295 | 3313 | promptScreen(ctx, screen, { |
| 3296 | 3314 | title: "Measure", |
| 3297 | label: "two points: x y z x y z", | |
| 3298 | hint: `the straight line between them, in ${unitFor(t.path.slice(t.path.lastIndexOf(".") + 1))}`, | |
| 3315 | label: dxf ? "two points: x y x y" : "two points: x y z x y z", | |
| 3316 | hint: `the straight line between them, in ${dxf ? "the unit the file names" : unitFor(ext)}`, | |
| 3299 | 3317 | onSubmit: (text) => { |
| 3300 | const said = measureTyped(text, t.path.slice(t.path.lastIndexOf(".") + 1)); | |
| 3318 | const said = dxf ? measureDxfTyped(text, t.plain.join("\n")) : measureTyped(text, ext); | |
| 3301 | 3319 | if (!said.startsWith("Distance")) return said; |
| 3302 | 3320 | ctx.toast(said, "success"); |
| 3303 | 3321 | return undefined; |
| @@ -3317,6 +3335,7 @@ export function workspaceScreen( | ||
| 3317 | 3335 | if (e.key === "N") return t.step(-1); |
| 3318 | 3336 | if (e.key === "m" && !e.ctrl && t.big !== null) return openKey(t); |
| 3319 | 3337 | if (e.key === "m" && !e.ctrl && isModelPath(t.path) && t.note !== "" && t.raw === null) return measureModel(t); |
| 3338 | if (e.key === "m" && !e.ctrl && isDrawing(t)) return measureModel(t); | |
| 3320 | 3339 | if (t.db !== null && t.asTable && (e.key === ">" || e.key === "<" || e.key === "}" || e.key === "{")) return pageDb(t, e.key); |
| 3321 | 3340 | // Horizontal scrolling belongs to code, which has long lines and a |
| 3322 | 3341 | // gutter; prose and pictures are already fitted to the pane. |
src/web/asset.ts +20 −10
| @@ -49,24 +49,34 @@ export function highlightAsset(): Promise<BuiltAsset | null> { | ||
| 49 | 49 | } |
| 50 | 50 | |
| 51 | 51 | async function build(): Promise<BuiltAsset | null> { |
| 52 | return bundleEntry(`${import.meta.dir}/highlight-client.ts`, (hash) => `highlight-${hash.slice(0, 16)}`, "web.highlight_asset_failed"); | |
| 53 | } | |
| 54 | ||
| 55 | /** | |
| 56 | * Bundles one browser entry with `Bun.build` into a `BuiltAsset`: the one implementation of the | |
| 57 | * build, the hash and the strong ETag, for the highlighter, the 3D viewer and the DXF tool. `name` | |
| 58 | * is a fixed asset name, or made from the code's own hash; null (and a warning named `event`) when | |
| 59 | * the build fails. | |
| 60 | */ | |
| 61 | export async function bundleEntry( | |
| 62 | entry: string, | |
| 63 | name: string | ((hash: string) => string), | |
| 64 | event: string, | |
| 65 | plugins: Bun.BunPlugin[] = [], | |
| 66 | ): Promise<BuiltAsset | null> { | |
| 52 | 67 | try { |
| 53 | const built = await Bun.build({ | |
| 54 | entrypoints: [`${import.meta.dir}/highlight-client.ts`], | |
| 55 | target: "browser", | |
| 56 | format: "esm", | |
| 57 | minify: true, | |
| 58 | }); | |
| 68 | const built = await Bun.build({ entrypoints: [entry], target: "browser", format: "esm", minify: true, plugins }); | |
| 59 | 69 | const first = built.outputs[0]; |
| 60 | 70 | if (!built.success || first === undefined) { |
| 61 | log.warn("web.highlight_asset_failed", { logs: built.logs.length }); | |
| 71 | log.warn(event, { logs: built.logs.length }); | |
| 62 | 72 | return null; |
| 63 | 73 | } |
| 64 | 74 | const code = await first.text(); |
| 65 | 75 | const hash = sha256(code); |
| 66 | const name = `highlight-${hash.slice(0, 16)}`; | |
| 67 | return { path: `/assets/${name}.js`, name, code, etag: `"${hash}"` }; | |
| 76 | const named = typeof name === "string" ? name : name(hash); | |
| 77 | return { path: `/assets/${named}.js`, name: named, code, etag: `"${hash}"` }; | |
| 68 | 78 | } catch (error) { |
| 69 | log.warn("web.highlight_asset_failed", { error: String(error) }); | |
| 79 | log.warn(event, { error: String(error) }); | |
| 70 | 80 | return null; |
| 71 | 81 | } |
| 72 | 82 | } |
src/web/render/dxf-asset.ts added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | /** | |
| 2 | * The DXF measure tool's script (`dxf-client.ts` bundled with `measure.ts`), loaded by the shell | |
| 3 | * only on a page that carries a `.dxf-view` figure. Named by a hash of its sources, so the page | |
| 4 | * knows the address before any build, as `model3d.ts` does for the 3D viewer. | |
| 5 | */ | |
| 6 | ||
| 7 | import { readFileSync } from "node:fs"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { sha256 } from "../../kernel/hash.ts"; | |
| 10 | import { bundleEntry, type BuiltAsset } from "../asset.ts"; | |
| 11 | ||
| 12 | const ENTRY = join(import.meta.dir, "dxf-client.ts"); | |
| 13 | const SOURCES = [ENTRY, join(import.meta.dir, "measure.ts")]; | |
| 14 | ||
| 15 | let path: string | null = null; | |
| 16 | ||
| 17 | /** `/assets/dxf-<hash>.js`, from the sources alone. */ | |
| 18 | export function dxfAssetPath(): string { | |
| 19 | path ??= `/assets/dxf-${sha256(SOURCES.map((f) => sha256(readFileSync(f))).join("\n")).slice(0, 16)}.js`; | |
| 20 | return path; | |
| 21 | } | |
| 22 | ||
| 23 | let pending: Promise<BuiltAsset | null> | null = null; | |
| 24 | ||
| 25 | /** The bundle, built once per process; null when the build fails. */ | |
| 26 | export function dxfAsset(): Promise<BuiltAsset | null> { | |
| 27 | pending ??= build(); | |
| 28 | return pending; | |
| 29 | } | |
| 30 | ||
| 31 | function build(): Promise<BuiltAsset | null> { | |
| 32 | return bundleEntry(ENTRY, dxfAssetPath().slice("/assets/".length, -".js".length), "web.dxf_asset_failed"); | |
| 33 | } | |
src/web/render/dxf-client.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | /** | |
| 2 | * The DXF measure tool, in the browser: two taps on the drawing (or the arrow keys and Enter at a | |
| 3 | * crosshair) set two points; the distance is read in the unit the file names, as text in a live | |
| 4 | * region. The arithmetic and the words are `measure.ts`; this only turns events into points. | |
| 5 | * A third pick starts again. Without JavaScript the drawing and its unit line are all there is. | |
| 6 | */ | |
| 7 | import { crosshairPoint, moveCrosshair, pick, pickPrompt, type ViewFrame } from "./measure.ts"; | |
| 8 | ||
| 9 | const NS = "http://www.w3.org/2000/svg"; | |
| 10 | ||
| 11 | /** | |
| 12 | * The checker runs without the DOM library (it would retype the whole server), so the page's | |
| 13 | * document is reached untyped here, in this one browser-only file. | |
| 14 | */ | |
| 15 | type Dom = any; | |
| 16 | const document: Dom = (globalThis as unknown as { document: Dom }).document; | |
| 17 | ||
| 18 | function mount(figure: Dom): void { | |
| 19 | if (figure.dataset.mounted !== undefined) return; | |
| 20 | figure.dataset.mounted = ""; | |
| 21 | const svg = figure.querySelector("svg"); | |
| 22 | const readout = figure.querySelector("[data-readout]"); | |
| 23 | const box = svg?.viewBox.baseVal; | |
| 24 | if (!svg || !readout || !box) return; | |
| 25 | const num = (k: string): number => Number(figure.dataset[k]); | |
| 26 | const frame: ViewFrame = { minX: num("minX"), maxY: num("maxY"), scale: num("scale"), pad: num("pad") }; | |
| 27 | if (![frame.minX, frame.maxY, frame.scale, frame.pad].every(Number.isFinite) || frame.scale <= 0) return; | |
| 28 | const unit = figure.dataset.unit === "" ? undefined : figure.dataset.unit; | |
| 29 | const layer = document.createElementNS(NS, "g"); | |
| 30 | layer.setAttribute("stroke", "var(--accent, currentColor)"); | |
| 31 | layer.setAttribute("fill", "var(--accent, currentColor)"); | |
| 32 | layer.setAttribute("stroke-width", "1.5"); | |
| 33 | svg.append(layer); | |
| 34 | svg.setAttribute("tabindex", "0"); | |
| 35 | // The drawing keeps its role="img" and its label; the readout describes what picking does. | |
role="application" replaces the server-rendered role="img", so a screen reader loses the drawing's aria-label (it is the only description of the drawing). Keep role="img" and add aria-describedby pointing at the readout, or wrap the interactive layer in a separate focusable element with its own label and the arrow-key hint. |
||
| 36 | if (readout.id !== "") svg.setAttribute("aria-describedby", readout.id); | |
| 37 | readout.textContent = pickPrompt(unit); | |
| 38 | svg.style.cursor = "crosshair"; | |
| 39 | const cross = document.createElementNS(NS, "path"); | |
| 40 | cross.setAttribute("fill", "none"); | |
| 41 | cross.setAttribute("opacity", "0.6"); | |
| 42 | cross.setAttribute("d", `M-6 0H6M0 -6V6`); | |
| 43 | cross.setAttribute("display", "none"); | |
| 44 | svg.append(cross); | |
| 45 | ||
| 46 | let marks: (readonly [number, number])[] = []; | |
| 47 | let at: readonly [number, number] = [0, 0]; | |
| 48 | const redraw = (): void => { | |
| 49 | layer.replaceChildren(); | |
| 50 | for (const [x, y] of marks) { | |
| 51 | const dot = document.createElementNS(NS, "circle"); | |
| 52 | dot.setAttribute("cx", String(x)); | |
| 53 | dot.setAttribute("cy", String(y)); | |
| 54 | dot.setAttribute("r", "3.5"); | |
| 55 | layer.append(dot); | |
| 56 | } | |
| 57 | if (marks.length === 2) { | |
| 58 | const line = document.createElementNS(NS, "path"); | |
| 59 | line.setAttribute("d", `M${marks[0]![0]} ${marks[0]![1]}L${marks[1]![0]} ${marks[1]![1]}`); | |
| 60 | line.setAttribute("stroke-dasharray", "4 3"); | |
| 61 | layer.append(line); | |
| 62 | } | |
| 63 | }; | |
| 64 | const choose = (sx: number, sy: number): void => { | |
| 65 | const step = pick(marks, sx, sy, frame, unit); | |
| 66 | marks = step.marks; | |
| 67 | redraw(); | |
| 68 | readout.textContent = step.text; | |
| 69 | }; | |
| 70 | const place = (): void => { | |
| 71 | const [x, y] = crosshairPoint(at, box.width, box.height); | |
| 72 | cross.setAttribute("transform", `translate(${x} ${y})`); | |
| 73 | }; | |
| 74 | svg.addEventListener("click", (e: Dom) => { | |
| 75 | const r = svg.getBoundingClientRect(); | |
| 76 | if (r.width === 0 || r.height === 0) return; | |
| 77 | choose(((e.clientX - r.left) * box.width) / r.width, ((e.clientY - r.top) * box.height) / r.height); | |
| 78 | }); | |
| 79 | svg.addEventListener("focus", () => { | |
| 80 | cross.removeAttribute("display"); | |
| 81 | place(); | |
| 82 | }); | |
| 83 | svg.addEventListener("blur", () => cross.setAttribute("display", "none")); | |
| 84 | svg.addEventListener("keydown", (e: Dom) => { | |
| 85 | const moved = moveCrosshair(at, e.key); | |
| 86 | if (moved !== null) { | |
| 87 | at = moved; | |
| 88 | place(); | |
| 89 | e.preventDefault(); | |
| 90 | } else if (e.key === "Enter" || e.key === " ") { | |
| 91 | choose(...crosshairPoint(at, box.width, box.height)); | |
| 92 | e.preventDefault(); | |
| 93 | } | |
| 94 | }); | |
| 95 | } | |
| 96 | ||
| 97 | function mountAll(): void { | |
| 98 | for (const figure of document.querySelectorAll(".dxf-view[data-measure]") as Dom[]) mount(figure); | |
| 99 | } | |
| 100 | ||
| 101 | mountAll(); | |
| 102 | // The code browser swaps files in place; a module runs once. | |
| 103 | document.addEventListener("code:swap", mountAll); |
src/web/render/dxf.ts +32 −4
| @@ -17,6 +17,8 @@ import type { Rendered, RenderInput } from "./renderers.ts"; | ||
| 17 | 17 | import { RENDER_CAP } from "./kinds.ts"; |
| 18 | 18 | import { fileSize } from "../ui.ts"; |
| 19 | 19 | import { within } from "./bounds.ts"; |
| 20 | import { dxfUnitName, type ViewFrame, measureXY, parseTwoPoints2d, unitNote } from "./measure.ts"; | |
| 21 | import { dxfAssetPath } from "./dxf-asset.ts"; | |
| 20 | 22 | |
| 21 | 23 | /** Entities drawn in all; the rest are counted but not drawn. */ |
| 22 | 24 | export const ENTITY_CAP = 50_000; |
| @@ -39,6 +41,8 @@ export interface Drawing { | ||
| 39 | 41 | readonly layers: string[]; |
| 40 | 42 | /** Drawable entities left out past ENTITY_CAP. */ |
| 41 | 43 | readonly dropped: number; |
| 44 | /** The header's `$INSUNITS` code; undefined when the file has none. */ | |
| 45 | readonly units: number | undefined; | |
| 42 | 46 | } |
| 43 | 47 | |
| 44 | 48 | const DRAWN = new Set(["LINE", "CIRCLE", "ARC", "LWPOLYLINE"]); |
| @@ -59,6 +63,8 @@ export function parseDxf(text: string): Drawing | { error: string } { | ||
| 59 | 63 | let cur: Cur | undefined; |
| 60 | 64 | let expectName = false; |
| 61 | 65 | let dropped = 0; |
| 66 | let units: number | undefined; | |
| 67 | let headerVar = ""; | |
| 62 | 68 | |
| 63 | 69 | const finish = (): void => { |
| 64 | 70 | if (cur === undefined) return; |
| @@ -131,6 +137,13 @@ export function parseDxf(text: string): Drawing | { error: string } { | ||
| 131 | 137 | if (inEntities) sawEntities = true; |
| 132 | 138 | continue; |
| 133 | 139 | } |
| 140 | // The header is pairs too: code 9 names a variable, the next value is its own. | |
| 141 | if (!inEntities && code === 9) headerVar = value; | |
| 142 | else if (!inEntities && headerVar === "$INSUNITS" && code === 70) { | |
| 143 | const n = Number(value); | |
| 144 | if (Number.isInteger(n)) units = n; | |
| 145 | headerVar = ""; | |
| 146 | } | |
| 134 | 147 | if (cur === undefined) continue; |
| 135 | 148 | if (code === 8) cur.layer = value.slice(0, NAME_CHARS); |
| 136 | 149 | else if (cur.codes.length < 100_000) cur.codes.push([code, value]); |
| @@ -138,7 +151,7 @@ export function parseDxf(text: string): Drawing | { error: string } { | ||
| 138 | 151 | if (!sawEntities) return { error: "it has no ENTITIES section" }; |
| 139 | 152 | if (!sawEof) return { error: "it is cut short (no EOF)" }; |
| 140 | 153 | if (shapes.length === 0) return { error: "it has no line, circle, arc or polyline to draw" }; |
| 141 | return { shapes, counts, layers: [...layers].sort(), dropped }; | |
| 154 | return { shapes, counts, layers: [...layers].sort(), dropped, units }; | |
| 142 | 155 | } |
| 143 | 156 | |
| 144 | 157 | const W = 640; |
| @@ -169,7 +182,7 @@ function extent(s: Shape): Pt[] { | ||
| 169 | 182 | } |
| 170 | 183 | |
| 171 | 184 | /** The SVG body and its size, fitted to the shapes' bounds. */ |
| 172 | export function draw(shapes: readonly Shape[]): { width: number; height: number; body: string; lines: number; rounds: number } { | |
| 185 | export function draw(shapes: readonly Shape[]): { width: number; height: number; body: string; lines: number; rounds: number; frame: ViewFrame } { | |
| 173 | 186 | let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; |
| 174 | 187 | for (const s of shapes) |
| 175 | 188 | for (const p of extent(s)) { |
| @@ -211,7 +224,7 @@ export function draw(shapes: readonly Shape[]): { width: number; height: number; | ||
| 211 | 224 | } |
| 212 | 225 | } |
| 213 | 226 | const body = (d === "" ? "" : `<path d="${d}"/>`) + circles; |
| 214 | return { width: Math.round(width), height: Math.round(height), body, lines, rounds }; | |
| 227 | return { width: Math.round(width), height: Math.round(height), body, lines, rounds, frame: { minX, maxY, scale, pad: PAD } }; | |
| 215 | 228 | } |
| 216 | 229 | |
| 217 | 230 | const plural = (n: number, one: string): string => `${n.toLocaleString("en")} ${one}${n === 1 ? "" : "s"}`; |
| @@ -231,10 +244,25 @@ export function dxf(input: RenderInput): Rendered { | ||
| 231 | 244 | ["Layers", shownLayers.join(", ") + (more > 0 ? ` and ${more} more` : "")], |
| 232 | 245 | ]; |
| 233 | 246 | const label = `Drawing of ${plural(total, "entity").replace("entitys", "entities")}`; |
| 234 | const content = html`<figure class="dxf-view"> | |
| 247 | const unit = dxfUnitName(parsed.units); | |
| 248 | const f = drawn.frame; | |
| 249 | const content = html`<figure class="dxf-view" data-measure data-module="${dxfAssetPath()}" data-min-x="${f.minX}" data-max-y="${f.maxY}" data-scale="${f.scale}" data-pad="${f.pad}" data-unit="${unit ?? ""}"> | |
| 235 | 250 | <svg viewBox="0 0 ${drawn.width} ${drawn.height}" role="img" aria-label="${label}" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none">${raw(drawn.body)}</svg> |
| 251 | <p class="small" id="dxf-readout" data-readout aria-live="polite">${unitNote(unit)}</p> | |
Principle 1: the figure now explains itself three times. The unit note, the readout's starting instruction and the existing 'Lines, circles, arcs...' note are three paragraphs under one drawing, and the live readout then repeats 'the file names no unit' (see dxf-client.ts). Say the unit once, in the readout line (for example 'Tap two points. Distances are in mm.' or '... in raw units, the file names none.'). Drop the separate unit paragraph and the suffix on the result. |
||
| 236 | 252 | <p class="muted small">Lines, circles, arcs and polylines are drawn; other entities are only counted.${parsed.dropped > 0 ? ` ${parsed.dropped.toLocaleString("en")} more past the first ${ENTITY_CAP.toLocaleString("en")} are not drawn.` : ""}</p> |
| 237 | 253 | <dl class="status-rows">${facts.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}</dl> |
| 238 | 254 | </figure>`; |
| 239 | 255 | return { content, lines: 0, summary: `${plural(total, "entity").replace("entitys", "entities")} · ${fileSize(input.size)}` }; |
| 240 | 256 | } |
| 257 | ||
| 258 | /** | |
| 259 | * The terminal's measure on a .dxf: two points typed in as `x y x y`, the page's words back, in the | |
| 260 | * unit the file names. `source` is the file's text. | |
| 261 | */ | |
| 262 | export function measureDxfTyped(text: string, source: string): string { | |
| 263 | const p = parseTwoPoints2d(text); | |
| 264 | if (typeof p === "string") return p; | |
| 265 | const parsed = parseDxf(source); | |
| 266 | const unit = "error" in parsed ? undefined : dxfUnitName(parsed.units); | |
| 267 | return `Distance ${measureXY(p[0], p[1], unit)}`; | |
| 268 | } |
src/web/render/measure.ts +90 −5
| @@ -85,13 +85,18 @@ export function moveCrosshair(at: readonly [number, number], key: string, step = | ||
| 85 | 85 | return [c(at[0] + m[0]), c(at[1] + m[1])]; |
| 86 | 86 | } |
| 87 | 87 | |
| 88 | /** `n` plain numbers split on commas, spaces or semicolons, or the sentence saying why not. */ | |
| 89 | function plainNumbers(text: string, n: number, give: string): number[] | string { | |
| 90 | const parts = text.split(/[\s,;]+/).filter((x) => x !== ""); | |
| 91 | if (parts.length !== n) return give; | |
| 92 | const v = parts.map((x) => (/^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(x) ? Number(x) : Number.NaN)); | |
| 93 | return v.some((x) => !Number.isFinite(x)) ? "Every coordinate must be a plain number." : v; | |
| 94 | } | |
| 95 | ||
| 88 | 96 | /** `1 2 3, 4 5 6` (commas or spaces) as two points, or why not: the terminal's way to measure. */ |
| 89 | 97 | 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]!]]; | |
| 98 | const v = plainNumbers(text, 6, "Give six numbers: x y z for the first point, then x y z for the second."); | |
| 99 | return typeof v === "string" ? v : [[v[0]!, v[1]!, v[2]!], [v[3]!, v[4]!, v[5]!]]; | |
| 95 | 100 | } |
| 96 | 101 | |
| 97 | 102 | /** The terminal's measure: two points typed in, the page's words back. */ |
| @@ -99,3 +104,83 @@ export function measureTyped(text: string, format: string): string { | ||
| 99 | 104 | const p = parseTwoPoints(text); |
| 100 | 105 | return typeof p === "string" ? p : `Distance ${measureText(p[0], p[1], unitFor(format))}`; |
| 101 | 106 | } |
| 107 | ||
| 108 | /** | |
| 109 | * A DXF drawing's unit: the header variable `$INSUNITS` (group code 70), named by the DXF | |
| 110 | * reference's table. 0 is "unitless" and an absent variable is the same: the file names no unit. | |
| 111 | */ | |
| 112 | const DXF_UNITS: Readonly<Record<number, string>> = { | |
| 113 | 1: "in", 2: "ft", 3: "mi", 4: "mm", 5: "cm", 6: "m", 7: "km", 8: "µin", 9: "mil", 10: "yd", 11: "Å", 12: "nm", | |
| 114 | 13: "µm", 14: "dm", 15: "dam", 16: "hm", 17: "Gm", 18: "AU", 19: "ly", 20: "pc", | |
| 115 | }; | |
| 116 | ||
| 117 | /** | |
| 118 | * The unit a drawing's `$INSUNITS` names, or undefined when it is 0, absent or not in the table. | |
| 119 | */ | |
| 120 | export const dxfUnitName = (code: number | undefined): string | undefined => (code === undefined ? undefined : DXF_UNITS[code]); | |
| 121 | ||
| 122 | /** Up to seven significant digits, no trailing zeros: 5, 0.0005, 1234.568. */ | |
| 123 | const sig = (v: number): string => String(Number(v.toPrecision(7))); | |
| 124 | ||
| 125 | /** What a drawing says about its unit: the one place the page says it (the readout's line). */ | |
| 126 | export const unitNote = (unit: string | undefined): string => | |
| 127 | unit === undefined | |
| 128 | ? "This file names no unit ($INSUNITS is absent or 0), so distances are in raw drawing units." | |
| 129 | : `Distances are in ${unit}, the unit this file names ($INSUNITS).`; | |
| 130 | ||
| 131 | /** | |
| 132 | * `5 mm (Δx 3 · Δy 4)`: the straight-line distance of two points on the drawing's plane | |
| 133 | * (d = sqrt(dx² + dy²)). With no unit the length says `raw units`, never a guess. | |
| 134 | */ | |
| 135 | export function measureXY(a: readonly [number, number], b: readonly [number, number], unit: string | undefined): string { | |
| 136 | const [dx, dy] = deltas([a[0], a[1], 0], [b[0], b[1], 0]); | |
| 137 | return `${sig(distance([a[0], a[1], 0], [b[0], b[1], 0]))} ${unit ?? "raw units"} (Δx ${sig(dx)} · Δy ${sig(dy)})`; | |
| 138 | } | |
| 139 | ||
| 140 | /** | |
| 141 | * How the drawn SVG maps back to the drawing: x = minX + (px - pad) / scale, y = maxY - (py - pad) | |
| 142 | * / scale. | |
| 143 | */ | |
| 144 | export interface ViewFrame { | |
| 145 | readonly minX: number; | |
| 146 | readonly maxY: number; | |
| 147 | readonly scale: number; | |
| 148 | readonly pad: number; | |
| 149 | } | |
| 150 | ||
| 151 | /** A point of the SVG's own coordinates as a point of the drawing, in the drawing's units. */ | |
| 152 | export function toDrawing(px: number, py: number, f: ViewFrame): readonly [number, number] { | |
| 153 | return [f.minX + (px - f.pad) / f.scale, f.maxY - (py - f.pad) / f.scale]; | |
| 154 | } | |
| 155 | ||
| 156 | /** The crosshair's place (-1..1 each way, y up) as a point of the SVG's own `width` x `height`. */ | |
| 157 | export const crosshairPoint = (at: readonly [number, number], width: number, height: number): readonly [number, number] => [ | |
| 158 | ((at[0] + 1) / 2) * width, | |
| 159 | ((1 - at[1]) / 2) * height, | |
| 160 | ]; | |
| 161 | ||
| 162 | /** What the readout says before a pick: the instruction and the unit, once (the script adds it). */ | |
| 163 | export const pickPrompt = (unit: string | undefined): string => `Tap two points, or focus the drawing and use the arrow keys and Enter. ${unitNote(unit)}`; | |
| 164 | ||
| 165 | /** | |
| 166 | * One pick on a drawing, as a pure step: the marks so far (SVG coordinates) and the point picked | |
| 167 | * give the marks to draw and the sentence to read out. The first pick sets a point, the second | |
| 168 | * reads the distance in the file's unit, the third begins again. | |
| 169 | */ | |
| 170 | export function pick( | |
| 171 | marks: readonly (readonly [number, number])[], | |
| 172 | sx: number, | |
| 173 | sy: number, | |
| 174 | frame: ViewFrame, | |
| 175 | unit: string | undefined, | |
| 176 | ): { marks: (readonly [number, number])[]; text: string } { | |
| 177 | const next = nextPicks(marks, [sx, sy] as const); | |
| 178 | const [a, b] = next.map(([x, y]) => toDrawing(x, y, frame)); | |
| 179 | return { marks: next, text: a !== undefined && b !== undefined ? `Distance ${measureXY(a, b, unit)}` : "First point set. Pick a second point." }; | |
| 180 | } | |
| 181 | ||
| 182 | /** `1 2 3 4` (commas or spaces) as two points on the plane, or why not. */ | |
| 183 | export function parseTwoPoints2d(text: string): readonly [readonly [number, number], readonly [number, number]] | string { | |
| 184 | const v = plainNumbers(text, 4, "Give four numbers: x y for the first point, then x y for the second."); | |
| 185 | return typeof v === "string" ? v : [[v[0]!, v[1]!], [v[2]!, v[3]!]]; | |
| 186 | } |
src/web/render/model3d.ts +15 −35
| @@ -18,8 +18,7 @@ | ||
| 18 | 18 | import { readdirSync, readFileSync } from "node:fs"; |
| 19 | 19 | import { join } from "node:path"; |
| 20 | 20 | import { sha256 } from "../../kernel/hash.ts"; |
| 21 | import { createLog } from "../../kernel/log.ts"; | |
| 22 | import type { BuiltAsset } from "../asset.ts"; | |
| 21 | import { bundleEntry, type BuiltAsset } from "../asset.ts"; | |
| 23 | 22 | import { html, type Html } from "../html.ts"; |
| 24 | 23 | import { btn, empty, field, fileSize } from "../ui.ts"; |
| 25 | 24 | import { indexedRows } from "./mesh.ts"; |
| @@ -30,7 +29,6 @@ import { stlForm, stlHref } from "./stl_convert.ts"; | ||
| 30 | 29 | import { readStl, STL_LIMIT, STL_TOO_BIG } from "./stl.ts"; |
| 31 | 30 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 32 | 31 | |
| 33 | const log = createLog("web"); | |
| 34 | 32 | |
| 35 | 33 | const ENTRY = Bun.fileURLToPath(new URL("./model3d-client.ts", import.meta.url)); |
| 36 | 34 | const VENDOR = join(import.meta.dir, "vendor", "three"); |
| @@ -172,37 +170,19 @@ export function model3dAsset(): Promise<BuiltAsset | null> { | ||
| 172 | 170 | return pending; |
| 173 | 171 | } |
| 174 | 172 | |
| 175 | async function build(): Promise<BuiltAsset | null> { | |
| 173 | function build(): Promise<BuiltAsset | null> { | |
| 176 | 174 | const name = model3dAssetPath().slice("/assets/".length, -".js".length); |
| 177 | try { | |
| 178 | const built = await Bun.build({ | |
| 179 | entrypoints: [Bun.fileURLToPath(new URL("./model3d-client.ts", import.meta.url))], | |
| 180 | target: "browser", | |
| 181 | format: "esm", | |
| 182 | minify: true, | |
| 183 | plugins: [ | |
| 184 | { | |
| 185 | name: "vendored-three", | |
| 186 | setup(b) { | |
| 187 | // The vendored files are three's own, unedited: they import | |
| 188 | // `three`, which is the vendored build. | |
| 189 | b.onResolve({ filter: /^three$/ }, () => ({ path: join(VENDOR, "build", "three.module.js") })); | |
| 190 | b.onResolve({ filter: /^three\/addons\// }, (args) => ({ | |
| 191 | path: join(VENDOR, "examples", "jsm", args.path.slice("three/addons/".length)), | |
| 192 | })); | |
| 193 | }, | |
| 194 | }, | |
| 195 | ], | |
| 196 | }); | |
| 197 | const first = built.outputs[0]; | |
| 198 | if (!built.success || first === undefined) { | |
| 199 | log.warn("web.model3d_asset_failed", { logs: built.logs.length }); | |
| 200 | return null; | |
| 201 | } | |
| 202 | const code = await first.text(); | |
| 203 | return { path: `/assets/${name}.js`, name, code, etag: `"${sha256(code)}"` }; | |
| 204 | } catch (error) { | |
| 205 | log.warn("web.model3d_asset_failed", { error: String(error) }); | |
| 206 | return null; | |
| 207 | } | |
| 175 | return bundleEntry(ENTRY, name, "web.model3d_asset_failed", [ | |
| 176 | { | |
| 177 | name: "vendored-three", | |
| 178 | setup(b) { | |
| 179 | // The vendored files are three's own, unedited: they import | |
| 180 | // `three`, which is the vendored build. | |
| 181 | b.onResolve({ filter: /^three$/ }, () => ({ path: join(VENDOR, "build", "three.module.js") })); | |
| 182 | b.onResolve({ filter: /^three\/addons\// }, (args) => ({ | |
| 183 | path: join(VENDOR, "examples", "jsm", args.path.slice("three/addons/".length)), | |
| 184 | })); | |
| 185 | }, | |
| 186 | }, | |
| 187 | ]); | |
| 208 | 188 | } |
src/web/style/content.ts +1
| @@ -624,6 +624,7 @@ img.img-box, .prose img.img-box, .tell-picture.img-box { display: block; width: | ||
| 624 | 624 | .dxf-view { margin: 0; } |
| 625 | 625 | .dxf-view svg { display: block; max-width: 100%; height: auto; margin: 0 auto; color: var(--fg); } |
| 626 | 626 | .dxf-view .status-rows { margin-top: 12px; } |
| 627 | .dxf-view svg:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } | |
| 627 | 628 | .gerber-view { margin: 0; } |
| 628 | 629 | .gerber-view svg { display: block; max-width: 100%; height: auto; margin: 0 auto; color: var(--fg); } |
| 629 | 630 | .gerber-view .status-rows { margin-top: 12px; } |
test/render-dxf.test.ts +117 −1
| @@ -1,7 +1,9 @@ | ||
| 1 | 1 | /** DXF drawings as inline SVG. */ |
| 2 | 2 | import { describe, expect, test } from "bun:test"; |
| 3 | import { dxf, ENTITY_CAP, parseDxf } from "../src/web/render/dxf.ts"; | |
| 3 | import { draw as drawDxf, dxf, ENTITY_CAP, measureDxfTyped, parseDxf } from "../src/web/render/dxf.ts"; | |
| 4 | import { dxfAssetPath } from "../src/web/render/dxf-asset.ts"; | |
| 4 | 5 | import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts"; |
| 6 | import { crosshairPoint, dxfUnitName, measureXY, moveCrosshair, parseTwoPoints2d, pick, pickPrompt, toDrawing } from "../src/web/render/measure.ts"; | |
| 5 | 7 | import { RENDERERS } from "../src/web/render/renderers.ts"; |
| 6 | 8 | |
| 7 | 9 | const enc = (s: string): Uint8Array => new TextEncoder().encode(s); |
| @@ -107,3 +109,117 @@ describe("entity cap note", () => { | ||
| 107 | 109 | expect(out).toContain("2 more past the first 50,000 are not drawn."); |
| 108 | 110 | }); |
| 109 | 111 | }); |
| 112 | ||
| 113 | const withUnits = (code: number | undefined, entities: string): string => | |
| 114 | pairs(0, "SECTION", 2, "HEADER") + | |
| 115 | (code === undefined ? "" : pairs(9, "$INSUNITS", 70, code)) + | |
| 116 | pairs(0, "ENDSEC", 0, "SECTION", 2, "ENTITIES") + entities + pairs(0, "ENDSEC", 0, "EOF"); | |
| 117 | const ONE_LINE = pairs(0, "LINE", 10, 0, 20, 0, 11, 30, 21, 40); | |
| 118 | ||
| 119 | describe("dxf measure", () => { | |
| 120 | test("a 3-4-5 drawing measures 5, in the unit the file names", () => { | |
| 121 | expect(measureXY([0, 0], [3, 4], "mm")).toBe("5 mm (Δx 3 · Δy 4)"); | |
| 122 | expect(measureXY([10, 10], [7, 6], "in")).toBe("5 in (Δx 3 · Δy 4)"); | |
| 123 | expect(measureXY([0, 0], [0.0003, 0.0004], "m")).toBe("0.0005 m (Δx 0.0003 · Δy 0.0004)"); | |
| 124 | }); | |
| 125 | ||
| 126 | test("$INSUNITS is read from the header and named", () => { | |
| 127 | const d = parseDxf(withUnits(4, ONE_LINE)); | |
| 128 | if ("error" in d) throw new Error(d.error); | |
| 129 | expect(d.units).toBe(4); | |
| 130 | expect(dxfUnitName(d.units)).toBe("mm"); | |
| 131 | expect(dxfUnitName(1)).toBe("in"); | |
| 132 | const page = String(draw(withUnits(4, ONE_LINE)).content); | |
| 133 | expect(page).toContain("Distances are in mm"); | |
| 134 | expect(page).toContain('data-unit="mm"'); | |
| 135 | }); | |
| 136 | ||
| 137 | test("a file with no unit, or unitless, says so and shows raw units", () => { | |
| 138 | for (const code of [undefined, 0]) { | |
| 139 | const text = withUnits(code, ONE_LINE); | |
| 140 | const page = String(draw(text).content); | |
| 141 | expect(page).toContain("names no unit"); | |
| 142 | expect(page.match(/names no unit/g)).toHaveLength(1); | |
| 143 | expect(page).toContain('data-unit=""'); | |
| 144 | expect(measureDxfTyped("0 0 30 40", text)).toBe("Distance 50 raw units (Δx 30 · Δy 40)"); | |
| 145 | } | |
| 146 | expect(dxfUnitName(99)).toBeUndefined(); | |
| 147 | }); | |
| 148 | ||
| 149 | test("the terminal measures in the file's unit and refuses bad input", () => { | |
| 150 | expect(measureDxfTyped("0,0 3,4", withUnits(4, ONE_LINE))).toBe("Distance 5 mm (Δx 3 · Δy 4)"); | |
| 151 | expect(measureDxfTyped("1 2 3", ONE_LINE)).toContain("four numbers"); | |
| 152 | expect(parseTwoPoints2d("1 x 3 4")).toBe("Every coordinate must be a plain number."); | |
| 153 | }); | |
| 154 | ||
| 155 | test("a tap maps back to drawing coordinates, y up", () => { | |
| 156 | const d = parseDxf(withUnits(4, ONE_LINE)); | |
| 157 | if ("error" in d) throw new Error(d.error); | |
| 158 | const f = drawDxf(d.shapes).frame; | |
| 159 | // the line runs (0,0)-(30,40): its start sits at the pad, bottom left | |
| 160 | const bottomLeft = toDrawing(f.pad, f.pad + 40 * f.scale, f); | |
| 161 | expect(bottomLeft[0]).toBeCloseTo(0, 9); | |
| 162 | expect(bottomLeft[1]).toBeCloseTo(0, 9); | |
| 163 | const topRight = toDrawing(f.pad + 30 * f.scale, f.pad, f); | |
| 164 | expect(topRight[0]).toBeCloseTo(30, 9); | |
| 165 | expect(topRight[1]).toBeCloseTo(40, 9); | |
| 166 | }); | |
| 167 | ||
| 168 | test("picks: the first sets a point, the second reads the distance, the third begins again", () => { | |
| 169 | const d = parseDxf(withUnits(4, ONE_LINE)); | |
| 170 | if ("error" in d) throw new Error(d.error); | |
| 171 | const f = drawDxf(d.shapes).frame; | |
| 172 | const at = (x: number, y: number): [number, number] => [f.pad + (x - f.minX) * f.scale, f.pad + (f.maxY - y) * f.scale]; | |
| 173 | const one = pick([], ...at(0, 0), f, "mm"); | |
| 174 | expect(one.marks).toHaveLength(1); | |
| 175 | expect(one.text).toBe("First point set. Pick a second point."); | |
| 176 | const two = pick(one.marks, ...at(30, 40), f, "mm"); | |
| 177 | expect(two.marks).toHaveLength(2); | |
| 178 | expect(two.text).toBe("Distance 50 mm (Δx 30 · Δy 40)"); | |
| 179 | const three = pick(two.marks, ...at(10, 10), f, "mm"); | |
| 180 | expect(three.marks).toEqual([at(10, 10)]); | |
| 181 | expect(three.text).toBe("First point set. Pick a second point."); | |
| 182 | expect(pick(one.marks, ...at(30, 40), f, undefined).text).toBe("Distance 50 raw units (Δx 30 · Δy 40)"); | |
| 183 | }); | |
Tests: the behaviour this issue asks for (two taps set two points, a third restarts, Enter/Space and the arrows pick, the readout text) lives only in dxf-client.ts and no test fails if it breaks. |
||
| 184 | ||
| 185 | test("the keyboard moves the crosshair, then Enter picks where it is", () => { | |
| 186 | const f = { minX: 0, maxY: 100, scale: 1, pad: 0 }; | |
| 187 | // an SVG 200 x 100: the middle is (100, 50) -> drawing (100, 50) | |
| 188 | expect(crosshairPoint([0, 0], 200, 100)).toEqual([100, 50]); | |
| 189 | const right = moveCrosshair([0, 0], "ArrowRight", 0.5)!; | |
| 190 | const up = moveCrosshair(right, "ArrowUp", 0.5)!; | |
| 191 | expect(up).toEqual([0.5, 0.5]); | |
| 192 | expect(moveCrosshair(up, "x")).toBeNull(); | |
| 193 | const first = pick([], ...crosshairPoint([0, 0], 200, 100), f, "mm"); | |
| 194 | const second = pick(first.marks, ...crosshairPoint(up, 200, 100), f, "mm"); | |
| 195 | expect(second.text).toBe("Distance 55.90170 mm (Δx 50 · Δy 25)".replace("55.90170", "55.9017")); | |
| 196 | }); | |
| 197 | ||
| 198 | test("the readout says the unit once, and the figure keeps its img role and label", () => { | |
| 199 | expect(pickPrompt("mm")).toContain("Tap two points"); | |
| 200 | expect(pickPrompt("mm")).toContain("Distances are in mm"); | |
| 201 | expect(pickPrompt(undefined)).toContain("names no unit"); | |
| 202 | const page = String(draw(withUnits(4, ONE_LINE)).content); | |
| 203 | // no instruction in the server's HTML: the script adds it | |
| 204 | expect(page).not.toContain("Tap two points"); | |
| 205 | expect(page.match(/Distances are in mm/g)).toHaveLength(1); | |
| 206 | expect(page).toContain('role="img"'); | |
| 207 | expect(page).toContain('id="dxf-readout"'); | |
| 208 | }); | |
| 209 | ||
| 210 | test("the figure carries a readout and the tool's script", () => { | |
| 211 | const page = String(draw(withUnits(4, ONE_LINE)).content); | |
| 212 | expect(page).toContain("data-readout"); | |
| 213 | expect(page).toContain('aria-live="polite"'); | |
| 214 | expect(page).toContain(`data-module="${dxfAssetPath()}"`); | |
| 215 | expect(dxfAssetPath()).toMatch(/^\/assets\/dxf-[0-9a-f]{16}\.js$/); | |
| 216 | }); | |
| 217 | }); | |
| 218 | ||
| 219 | test("the measure script builds and carries the pure helpers", async () => { | |
| 220 | const { dxfAsset } = await import("../src/web/render/dxf-asset.ts"); | |
| 221 | const built = await dxfAsset(); | |
| 222 | expect(built).not.toBeNull(); | |
| 223 | expect(built!.path).toBe(dxfAssetPath()); | |
| 224 | expect(built!.code).toContain("data-measure"); | |
| 225 | }); |
test/tui-dxf-measure.test.ts added +101
| @@ -0,0 +1,101 @@ | ||
| 1 | /** | |
| 2 | * The terminal's door to a DXF drawing: `m` takes two points on the plane and answers in the unit | |
| 3 | * the file names, and is bound only when the file is shown as a drawing (it has no note). | |
| 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 as Forge } from "../src/app.ts"; | |
| 12 | import { getUserByName } from "../src/core/users.ts"; | |
| 13 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 14 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 15 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | import { settleApp, settleUntil } from "./helpers/tui.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | const pairs = (...p: (string | number)[]): string => p.join("\n") + "\n"; | |
| 22 | const DRAWING = | |
| 23 | pairs(0, "SECTION", 2, "HEADER", 9, "$INSUNITS", 70, 4, 0, "ENDSEC", 0, "SECTION", 2, "ENTITIES") + | |
| 24 | pairs(0, "LINE", 8, "Walls", 10, 0, 20, 0, 11, 30, 21, 40, 0, "ENDSEC", 0, "EOF"); | |
| 25 | ||
| 26 | let dataDir = ""; | |
| 27 | let forge: Forge; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | dataDir = await mkdtemp(join(tmpdir(), "forge-tui-dxf-")); | |
| 31 | forge = createApp({ dataDir, port: 0, url: "https://forge.test" }); | |
| 32 | const a = await seedAdmin(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" }); | |
| 33 | if (!a.ok) throw new Error("signup failed"); | |
| 34 | const made = await createRepo(forge, a.value, { name: "plans", visibility: "public" }); | |
| 35 | if (!made.ok) throw new Error("repo failed"); | |
| 36 | await commitToBranch(forge, a.value, made.value, { | |
| 37 | message: "plans", | |
| 38 | files: [ | |
| 39 | { path: "README.md", content: "# plans\n" }, | |
| 40 | { path: "plan.dxf", content: DRAWING }, | |
| 41 | // Not text at all: the file view puts a note where the drawing would be. | |
| 42 | { path: "broken.dxf", content: new Uint8Array([0, 1, 2, 0, 255, 254, 0, 0, 1, 2, 3]) }, | |
| 43 | ], | |
| 44 | }); | |
| 45 | }); | |
| 46 | ||
| 47 | afterAll(async () => { | |
| 48 | forge.close(); | |
| 49 | await rm(dataDir, { recursive: true, force: true }); | |
| 50 | }); | |
| 51 | ||
| 52 | async function open(file: string) { | |
| 53 | const user = getUserByName(forge.db, "alice"); | |
| 54 | if (user === undefined) throw new Error("no alice"); | |
| 55 | const { app } = createForgeApp( | |
| 56 | forge, | |
| 57 | { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, | |
| 58 | { terminal: headlessTerminal(140, 40), exitHooks: false }, | |
| 59 | ); | |
| 60 | app.start(); | |
| 61 | const send = (key: string): void => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 62 | const type = (text: string): void => { | |
| 63 | for (const ch of text) send(ch); | |
| 64 | }; | |
| 65 | await settleApp(app); | |
| 66 | send("/"); | |
| 67 | type("plans"); | |
| 68 | send("enter"); | |
| 69 | send("enter"); | |
| 70 | await settleUntil(app, "alice/plans"); | |
| 71 | send("t"); | |
| 72 | await settleApp(app); | |
| 73 | type(file); | |
| 74 | send("enter"); | |
| 75 | await settleApp(app); | |
| 76 | return { app, send, type }; | |
| 77 | } | |
| 78 | ||
| 79 | test("m on a drawn .dxf asks for two points and answers in the file's unit", async () => { | |
| 80 | const { app, send, type } = await open("plandxf"); | |
| 81 | try { | |
| 82 | send("m"); | |
| 83 | await settleUntil(app, "two points: x y x y"); | |
| 84 | type("0 0 3 4"); | |
| 85 | send("enter"); | |
| 86 | await settleUntil(app, "Distance 5 mm (Δx 3 · Δy 4)"); | |
| 87 | } finally { | |
| 88 | app.stop(); | |
| 89 | } | |
| 90 | }); | |
| 91 | ||
| 92 | test("m on a .dxf the page cannot draw is not bound", async () => { | |
| 93 | const { app, send } = await open("brokendxf"); | |
| 94 | try { | |
| 95 | send("m"); | |
| 96 | await settleApp(app); | |
| 97 | expect(app.screen.toText()).not.toContain("two points: x y x y"); | |
| 98 | } finally { | |
| 99 | app.stop(); | |
| 100 | } | |
| 101 | }); |
Only one way to do the thing: this build() is the same Bun.build, hash, etag and log code as asset.ts#build and the 3D viewer's (gate.ts said so, and it was left). Take one shared helper from asset.ts, such as 'bundle this entry to a BuiltAsset', and make the highlight, 3D and DXF assets call it. The new route branch in server.ts then collapses with the 3D one.