Public: anyone can read this; the crew can change it.
An .stl can be scaled, moved or turned 90° from its file page and saved as a commit #15842
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15822-an-stl-can-be-scaled-moved-or-turned-90 → main 0 commits fork 3 threads · 3 unresolved
7 files
changed +733
−6
docs/features/file-stl.md +15 −3
| @@ -19,14 +19,26 @@ The first paint carries the triangle count and box, read by the server, so they | ||
| 19 | 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 | 20 | `measure.ts`, checked by hand in `test/model-measure.test.ts`. |
| 21 | 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). | |
| 22 | - **Edit (STL only, writers only)**: under the part, a form with **Scale** (a factor, or a target size for one axis, | |
| 23 | which scales all three alike), **Move** (dx dy dz) and **Turn** (90° about x, y or z, right-hand rule). The order is | |
| 24 | fixed: scale and turn about the origin, then move. **Preview the new Box** shows the triangle count and the new | |
| 25 | Box and writes nothing; **Commit** saves the part as a binary STL (normals rewritten from the winding) in one commit | |
| 26 | whose message names the change (`a.stl: scale ×2, turn 90° about z, move 1, 0, 0`). On a protected default branch | |
| 27 | the commit goes to a new branch and a pull, as the subtitle shift does. Numbers are bounded (factor 0.001 to 1000, | |
| 28 | moves ±1,000,000); the post is same-origin and writer-only. `src/web/render/mesh_edit.ts` is the pure transform, | |
| 29 | `src/actions/mesh_edit.ts` the preview-or-commit action, the route is the file edit route's `mesh` form. | |
| 30 | A tag or commit as the ref also goes to a new branch and a pull, forked from the default branch. | |
| 31 | In the terminal, with a repository open, the palette's "Scale, move or turn an STL" (`src/tui/screens/mesh_edit.ts`) | |
| 32 | asks for the path, a factor, a turn and a move, and commits through the same action. | |
| 33 | A commit holds 2 MB a file, so over that the form says so instead; the 20 MB limit still governs viewing. Other | |
| 34 | model formats, and STEP, are not editable here; the text editor's refusal says what opens them (`opens_with.ts`); | |
| 35 | STEP still shows its part card, not geometry (that needs a CAD kernel in WebAssembly, a later pull). | |
| 24 | 36 | - The header and triangle count are checked against the byte length before any triangle is read. A truncated or |
| 25 | 37 | damaged file, one with no triangles or a coordinate that is not a number, is refused with a sentence and Download. |
| 26 | 38 | - Over 20 MB: refused with a sentence and never fetched; Download still streams it. |
| 27 | 39 | - 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. |
| 28 | 40 | - Try it: commit a `.stl` to a repository and open its file page. |
| 29 | 41 | |
| 30 | Pinned by `test/render-stl.test.ts`, `test/model3d.test.ts`, `test/tui-model3d.test.ts` (the `m` key) and | |
| 42 | Pinned by `test/mesh-edit.test.ts` (the transform, the form, the commit, the protected branch, the terminal), `test/render-stl.test.ts`, `test/model3d.test.ts`, `test/tui-model3d.test.ts` (the `m` key) and | |
| 31 | 43 | `test/model-edit-refusal.test.ts` (the edit page's sentence). The crosshair's keydown and the pointer wiring in |
| 32 | 44 | `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). |
src/actions/mesh_edit.ts added +221
| @@ -0,0 +1,221 @@ | ||
| 1 | /** | |
| 2 | * Scale, move or turn an STL and (when asked) save it as one commit. The page's Preview and Commit | |
| 3 | * buttons both call this, so what was previewed is what is committed: the gate (a writer only), | |
| 4 | * the bounds on every number and the message are one thing. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { canAdmin, type Repo } from "../core/repos.ts"; | |
| 9 | import { isSafeRef, isSafeTreePath } from "../git/guard.ts"; | |
| 10 | import { blobForRender, refTip } from "../git/read.ts"; | |
| 11 | import { repoDir } from "../git/repos.ts"; | |
| 12 | import type { User } from "../core/users.ts"; | |
| 13 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 14 | import { bounds, parseStl, type Bounds } from "../web/render/mesh.ts"; | |
| 15 | import { requireWriter } from "./access.ts"; | |
| 16 | import { editFiles, MAX_FILE_BYTES, type EditFilesError, type EditResult } from "./contents.ts"; | |
| 17 | ||
| 18 | export type Axis = "x" | "y" | "z"; | |
| 19 | export type Scale = { readonly factor: number } | { readonly axis: Axis; readonly size: number }; | |
| 20 | ||
| 21 | export interface MeshEdit { | |
| 22 | readonly scale?: Scale; | |
| 23 | readonly move?: readonly [number, number, number]; | |
| 24 | /** A quarter turn counter-clockwise (right-hand rule) about this axis; `times` is 1 to 3. */ | |
| 25 | readonly turn?: { readonly axis: Axis; readonly times: number }; | |
| 26 | } | |
| 27 | ||
| 28 | export interface Edited { | |
| 29 | readonly bytes: Uint8Array; | |
| 30 | readonly triangles: number; | |
| 31 | readonly box: Bounds; | |
| 32 | } | |
| 33 | ||
| 34 | /** The largest number any field takes: far past a printer, short of float trouble. */ | |
| 35 | export const EDIT_LIMIT = 1_000_000; | |
| 36 | ||
| 37 | const AXES: readonly Axis[] = ["x", "y", "z"]; | |
| 38 | const index = (axis: Axis): number => AXES.indexOf(axis); | |
| 39 | ||
| 40 | /** A bounded number from form text, or the sentence that says why not. */ | |
| 41 | export function parseNumber(label: string, text: string, opts: { min?: number; max?: number } = {}): { ok: true; value: number } | { ok: false; why: string } { | |
| 42 | const t = text.trim(); | |
| 43 | if (!/^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i.test(t)) return { ok: false, why: `${label} must be a number.` }; | |
| 44 | const value = Number(t); | |
| 45 | const min = opts.min ?? -EDIT_LIMIT; | |
| 46 | const max = opts.max ?? EDIT_LIMIT; | |
| 47 | if (!Number.isFinite(value) || value < min || value > max) return { ok: false, why: `${label} must be between ${min} and ${max}.` }; | |
| 48 | return { ok: true, value }; | |
| 49 | } | |
| 50 | ||
| 51 | /** Apply `edit` to an STL (either form). Throws only what `parseStl` throws. */ | |
| 52 | export function editStl(source: Uint8Array, edit: MeshEdit): { ok: true; value: Edited } | { ok: false; why: string } { | |
| 53 | const mesh = parseStl(source); | |
| 54 | if (mesh.triangles === 0) return { ok: false, why: "This STL holds no triangles." }; | |
| 55 | const p = Float64Array.from(mesh.positions); | |
| 56 | let factor = 1; | |
| 57 | if (edit.scale !== undefined) { | |
| 58 | if ("factor" in edit.scale) factor = edit.scale.factor; | |
| 59 | else { | |
| 60 | const current = bounds(mesh.positions).size[index(edit.scale.axis)]!; | |
| 61 | if (current <= 0) return { ok: false, why: `The part has no size along ${edit.scale.axis}, so it cannot be scaled to one.` }; | |
| 62 | factor = edit.scale.size / current; | |
| 63 | } | |
| 64 | } | |
| 65 | if (!(factor > 0) || !Number.isFinite(factor)) return { ok: false, why: "The scale must be greater than zero." }; | |
| 66 | const move = edit.move ?? [0, 0, 0]; | |
| 67 | const times = edit.turn === undefined ? 0 : ((edit.turn.times % 4) + 4) % 4; | |
| 68 | const a = edit.turn === undefined ? 0 : index(edit.turn.axis); | |
| 69 | const b = (a + 1) % 3; | |
| 70 | const c = (a + 2) % 3; | |
| 71 | for (let i = 0; i < p.length; i += 3) { | |
| 72 | let u = p[i + b]! * factor; | |
| 73 | let v = p[i + c]! * factor; | |
| 74 | // One right-handed quarter turn about axis a takes b to c and c to -b. | |
| 75 | for (let t = 0; t < times; t++) [u, v] = [-v, u]; | |
| 76 | const out = [0, 0, 0]; | |
| 77 | out[a] = p[i + a]! * factor; | |
| 78 | out[b] = u; | |
| 79 | out[c] = v; | |
| 80 | for (let k = 0; k < 3; k++) p[i + k] = out[k]! + move[k]!; | |
| 81 | } | |
| 82 | const f32 = Float32Array.from(p); | |
| 83 | for (const v of f32) if (!Number.isFinite(v)) return { ok: false, why: "That change takes a coordinate out of range." }; | |
| 84 | return { ok: true, value: { bytes: writeBinaryStl(f32), triangles: mesh.triangles, box: bounds(f32) } }; | |
| 85 | } | |
| 86 | ||
| 87 | /** Nine floats a triangle to a binary STL, normals from the winding. */ | |
| 88 | export function writeBinaryStl(positions: Float32Array): Uint8Array { | |
| 89 | const n = positions.length / 9; | |
| 90 | const out = new Uint8Array(84 + n * 50); | |
| 91 | const view = new DataView(out.buffer); | |
| 92 | out.set(new TextEncoder().encode("binary STL written by the forge"), 0); | |
| 93 | view.setUint32(80, n, true); | |
| 94 | for (let t = 0; t < n; t++) { | |
| 95 | const o = t * 9; | |
| 96 | const at = 84 + t * 50; | |
| 97 | const e = (k: number): number => positions[o + 3 + k]! - positions[o + k]!; | |
| 98 | const f = (k: number): number => positions[o + 6 + k]! - positions[o + k]!; | |
| 99 | const nx = e(1) * f(2) - e(2) * f(1); | |
| 100 | const ny = e(2) * f(0) - e(0) * f(2); | |
| 101 | const nz = e(0) * f(1) - e(1) * f(0); | |
| 102 | const len = Math.hypot(nx, ny, nz) || 1; | |
| 103 | view.setFloat32(at, nx / len, true); | |
| 104 | view.setFloat32(at + 4, ny / len, true); | |
| 105 | view.setFloat32(at + 8, nz / len, true); | |
| 106 | for (let k = 0; k < 9; k++) view.setFloat32(at + 12 + k * 4, positions[o + k]!, true); | |
| 107 | } | |
| 108 | return out; | |
| 109 | } | |
| 110 | ||
| 111 | /** The commit subject: what was done, in the order it was done. */ | |
| 112 | export function editMessage(edit: MeshEdit, path: string): string { | |
| 113 | const parts: string[] = []; | |
| 114 | if (edit.scale !== undefined) | |
| 115 | parts.push("factor" in edit.scale ? `scale ×${edit.scale.factor}` : `scale to ${edit.scale.size} along ${edit.scale.axis}`); | |
| 116 | if (edit.turn !== undefined) parts.push(`turn ${90 * (((edit.turn.times % 4) + 4) % 4)}° about ${edit.turn.axis}`); | |
| 117 | if (edit.move !== undefined) parts.push(`move ${edit.move.join(", ")}`); | |
| 118 | const leaf = path.slice(path.lastIndexOf("/") + 1); | |
| 119 | return `${leaf}: ${parts.join(", ")}`.slice(0, 120); | |
| 120 | } | |
| 121 | ||
| 122 | export type MeshEditError = | |
| 123 | | { readonly kind: "refused"; readonly why: string } | |
| 124 | | { readonly kind: "missing" } | |
| 125 | | EditFilesError; | |
| 126 | ||
| 127 | /** The form's raw text, unchecked. */ | |
| 128 | export interface MeshForm { | |
| 129 | readonly ref: string; | |
| 130 | readonly path: string; | |
| 131 | readonly factor: string; | |
| 132 | readonly sizeAxis: string; | |
| 133 | readonly size: string; | |
| 134 | readonly dx: string; | |
| 135 | readonly dy: string; | |
| 136 | readonly dz: string; | |
| 137 | readonly turn: string; | |
| 138 | } | |
| 139 | ||
| 140 | const isAxis = (v: string): v is Axis => v === "x" || v === "y" || v === "z"; | |
| 141 | ||
| 142 | /** The form's text as one bounded edit, or the sentence that refuses it. */ | |
| 143 | export function parseMeshForm(form: MeshForm): { ok: true; edit: MeshEdit } | { ok: false; why: string } { | |
| 144 | let scale: MeshEdit["scale"]; | |
| 145 | if (form.factor.trim() !== "" && form.size.trim() !== "") return { ok: false, why: "Scale by a factor or to a size, not both." }; | |
| 146 | if (form.factor.trim() !== "") { | |
| 147 | const f = parseNumber("The scale factor", form.factor, { min: 0.001, max: 1000 }); | |
| 148 | if (!f.ok) return f; | |
| 149 | if (f.value !== 1) scale = { factor: f.value }; | |
| 150 | } else if (form.size.trim() !== "") { | |
| 151 | if (!isAxis(form.sizeAxis)) return { ok: false, why: "Pick x, y or z for the size." }; | |
| 152 | const s = parseNumber("The target size", form.size, { min: 0.001, max: 1_000_000 }); | |
| 153 | if (!s.ok) return s; | |
| 154 | scale = { axis: form.sizeAxis, size: s.value }; | |
| 155 | } | |
| 156 | const d = [form.dx, form.dy, form.dz].map((t, i) => (t.trim() === "" ? { ok: true as const, value: 0 } : parseNumber(`Move ${"xyz"[i]}`, t))); | |
| 157 | for (const r of d) if (!r.ok) return r; | |
| 158 | const move = d.map((r) => (r.ok ? r.value : 0)) as [number, number, number]; | |
| 159 | let turn: MeshEdit["turn"]; | |
| 160 | if (form.turn !== "") { | |
| 161 | if (!isAxis(form.turn)) return { ok: false, why: "Turn about x, y or z." }; | |
| 162 | turn = { axis: form.turn, times: 1 }; | |
| 163 | } | |
| 164 | const edit: MeshEdit = { | |
| 165 | ...(scale !== undefined ? { scale } : {}), | |
| 166 | ...(turn !== undefined ? { turn } : {}), | |
| 167 | ...(move.some((v) => v !== 0) ? { move } : {}), | |
| 168 | }; | |
| 169 | if (Object.keys(edit).length === 0) return { ok: false, why: "Nothing to change: give a scale, a move or a turn." }; | |
| 170 | return { ok: true, edit }; | |
| 171 | } | |
| 172 | ||
| 173 | export const isStlPath = (path: string): boolean => /\.stl$/i.test(path) && isSafeTreePath(path); | |
| 174 | ||
| 175 | /** Read, change and (with `commit`) save. A preview returns the new box and writes nothing. */ | |
| 176 | export async function editMesh( | |
| 177 | app: App, | |
| 178 | actor: User | undefined, | |
| 179 | repo: Repo, | |
| 180 | form: MeshForm, | |
| 181 | commit: boolean, | |
| 182 | ): Promise<Result<{ readonly edited: Edited; readonly message: string; readonly landed?: EditResult }, MeshEditError>> { | |
| 183 | const writer = requireWriter(app, actor, repo); | |
| 184 | if (!writer.ok) return writer; | |
| 185 | const { ref, path } = form; | |
| 186 | if (!isSafeRef(ref)) return err({ kind: "missing" }); | |
| 187 | if (!isStlPath(path)) return err({ kind: "refused", why: "Only an .stl file can be changed here." }); | |
| 188 | const parsed = parseMeshForm(form); | |
| 189 | if (!parsed.ok) return err({ kind: "refused", why: parsed.why }); | |
| 190 | ||
| 191 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 192 | const blob = await blobForRender(dir, ref, path, MAX_FILE_BYTES); | |
| 193 | if (blob.kind === "too_large") | |
| 194 | return err({ kind: "refused", why: "This STL is over 2 MB, more than one commit here can hold; change it in a CAD tool and commit it with git." }); | |
| 195 | if (blob.kind === "missing") return err({ kind: "missing" }); | |
| 196 | let edited; | |
| 197 | try { | |
| 198 | edited = editStl(blob.body, parsed.edit); | |
| 199 | } catch { | |
| 200 | return err({ kind: "refused", why: "This is not a readable STL file." }); | |
| 201 | } | |
| 202 | if (!edited.ok) return err({ kind: "refused", why: edited.why }); | |
| 203 | const message = editMessage(parsed.edit, path); | |
| 204 | if (!commit) return ok({ edited: edited.value, message }); | |
| 205 | ||
| 206 | const isBranch = (await refTip(dir, `refs/heads/${ref}`)) !== undefined; | |
| 207 | const mustBranch = !isBranch || (ref === repo.defaultBranch && repo.protectDefault && !canAdmin(app.db, repo, writer.value)); | |
| 208 | const leaf = (path.split("/").pop() ?? path).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40); | |
| 209 | const landed = await editFiles(app, writer.value, repo, { | |
| 210 | // A tag or commit cannot be a pull's base: its edit forks from the default branch. | |
| 211 | branch: isBranch ? ref : repo.defaultBranch, | |
| 212 | base: isBranch ? ref : repo.defaultBranch, | |
| 213 | message, | |
| 214 | files: [{ path, content: edited.value.bytes }], | |
| 215 | ...(mustBranch | |
| 216 | ? { newBranch: `${writer.value.username}/mesh-${leaf === "" ? "file" : leaf}-${Date.now().toString(36)}`, openPull: { title: message, body: "" } } | |
| 217 | : {}), | |
| 218 | }); | |
| 219 | if (!landed.ok) return landed; | |
| 220 | return ok({ edited: edited.value, message, landed: landed.value }); | |
| 221 | } |
src/tui/screens/mesh_edit.ts added +66
| @@ -0,0 +1,66 @@ | ||
| 1 | /** | |
| 2 | * Scale, move or turn an STL, in the terminal: the same action as the file page's form | |
| 3 | * (`actions/mesh_edit.ts`), so the same gate (a writer only; a reader or guest is offered nothing), | |
| 4 | * the same bounds, the same commit message and the same protected-branch rule. The write goes | |
| 5 | * through `editFiles`, which announces a push, so an open web page of the file follows. | |
| 6 | */ | |
| 7 | ||
| 8 | import { requireWriter } from "../../actions/access.ts"; | |
| 9 | import { editMesh, isStlPath, type MeshForm } from "../../actions/mesh_edit.ts"; | |
| 10 | import type { Repo } from "../../core/repos.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import type { Command } from "../app/palette.ts"; | |
| 13 | import type { Session } from "../session.ts"; | |
| 14 | import { later, promptScreen } from "./common.ts"; | |
| 15 | ||
| 16 | /** The palette's command while a repository is open and this viewer may write to it. */ | |
| 17 | export function meshEditCommands(f: Session, ctx: Ctx, repo: Repo | undefined, parent: () => Screen): Command[] { | |
| 18 | if (repo === undefined || !requireWriter(f.app, f.user, repo).ok) return []; | |
| 19 | const ask = (label: string, value: string, hint: string, next: (v: string) => string | undefined | Promise<void>): Screen => | |
| 20 | promptScreen(ctx, parent(), { title: "Edit an STL", label, value, hint, onSubmit: next }); | |
| 21 | return [ | |
| 22 | { | |
| 23 | id: "mesh-edit", | |
| 24 | title: `${repo.ownerName}/${repo.name} — Scale, move or turn an STL`, | |
| 25 | hint: "change a .stl file and save it as a commit", | |
| 26 | run: () => | |
| 27 | ctx.push( | |
| 28 | promptScreen(ctx, parent(), { | |
| 29 | title: "Edit an STL", | |
| 30 | label: "Path of the .stl file", | |
| 31 | placeholder: "parts/box.stl", | |
| 32 | onSubmit: (path) => { | |
| 33 | if (!isStlPath(path)) return "Give the path of a .stl file."; | |
| 34 | return later(ctx, () => | |
| 35 | ask("Scale factor, like 2 or 0.5 (blank: none)", "", "", (factor) => | |
| 36 | later(ctx, () => | |
| 37 | ask("Turn 90° about x, y or z (blank: none)", "", "", (turn) => | |
| 38 | later(ctx, () => | |
| 39 | ask("Move dx dy dz, like 1 0 0 (blank: none)", "", "", async (move) => { | |
| 40 | const [dx = "", dy = "", dz = ""] = move.trim().split(/\s+/); | |
| 41 | const form: MeshForm = { | |
| 42 | ref: repo.defaultBranch, path, factor, sizeAxis: "", size: "", dx, dy, dz, turn: turn.trim().toLowerCase(), | |
| 43 | }; | |
| 44 | const done = await editMesh(f.app, f.user, repo, form, true); | |
| 45 | if (done.ok) { | |
| 46 | const landed = done.value.landed; | |
| 47 | ctx.toast(landed?.pull === undefined ? `Committed to ${landed?.branch ?? repo.defaultBranch}.` : `Opened a pull from ${landed.branch}.`); | |
| 48 | return; | |
| 49 | } | |
| 50 | const e = done.error; | |
| 51 | ctx.toast( | |
| 52 | typeof e === "object" && e.kind === "refused" ? e.why : typeof e === "object" && e.kind === "missing" ? "No such file." : "That edit could not be saved.", | |
| 53 | "danger", | |
| 54 | ); | |
| 55 | }), | |
| 56 | ), | |
| 57 | ), | |
| 58 | ), | |
| 59 | ), | |
| 60 | ); | |
| 61 | }, | |
| 62 | }), | |
| 63 | ), | |
| 64 | }, | |
| 65 | ]; | |
| 66 | } |
src/tui/screens/workspace.ts +2
| @@ -215,6 +215,7 @@ import { recheckWindowCommands } from "./recheckwindow.ts"; | ||
| 215 | 215 | import { deskCommands } from "./desk.ts"; |
| 216 | 216 | import { landCommands } from "./landasis.ts"; |
| 217 | 217 | import { shiftCommands } from "./subtitle_shift.ts"; |
| 218 | import { meshEditCommands } from "./mesh_edit.ts"; | |
| 218 | 219 | import { dataImportCommands } from "./dataimport.ts"; |
| 219 | 220 | import { dataMoveCommands } from "./datamove.ts"; |
| 220 | 221 | import { jobsCommands } from "./jobs.ts"; |
| @@ -2363,6 +2364,7 @@ export function workspaceScreen( | ||
| 2363 | 2364 | ...buildCacheCommands(f, ctx, repo), |
| 2364 | 2365 | ...landCommands(f, ctx, repo), |
| 2365 | 2366 | ...shiftCommands(f, ctx, repo, () => screen), |
| 2367 | ...meshEditCommands(f, ctx, repo, () => screen), | |
| 2366 | 2368 | ...dataImportCommands(f, ctx, repo), |
| 2367 | 2369 | ...dataMoveCommands(f, ctx, repo), |
| 2368 | 2370 | ...jobsCommands(f, ctx, repo), |
src/web/pages/edit.ts +51
| @@ -20,6 +20,8 @@ | ||
| 20 | 20 | import { binaryRefusal } from "../render/opens_with.ts"; |
| 21 | 21 | import { fileKind, NO_BYTES } from "../render/kinds.ts"; |
| 22 | 22 | import { editFiles, MAX_FILE_BYTES } from "../../actions/contents.ts"; |
| 23 | import { editMesh, type MeshForm } from "../../actions/mesh_edit.ts"; | |
| 24 | import { sizeText } from "../render/mesh.ts"; | |
| 23 | 25 | import { shiftSubtitles } from "../../actions/subtitle_shift.ts"; |
| 24 | 26 | import { contribute } from "../../actions/contribute.ts"; |
| 25 | 27 | import { NO_WRITE_ACCESS } from "../../actions/pull_words.ts"; |
| @@ -883,6 +885,54 @@ async function shiftSubmit(ctx: Ctx, scope: RepoScope, repo: Repo, form: Form): | ||
| 883 | 885 | }); |
| 884 | 886 | } |
| 885 | 887 | |
| 888 | /** The STL form: Preview shows the new Box and asks again; Commit writes the file as one commit. */ | |
| 889 | async function meshSubmit(ctx: Ctx, scope: RepoScope, repo: Repo, form: Form): Promise<Response> { | |
| 890 | const ref = formValue(form, "ref"); | |
| 891 | const path = formValue(form, "path").trim().replace(/^\/+/, ""); | |
| 892 | const raw: MeshForm = { | |
| 893 | ref, | |
| 894 | path, | |
| 895 | factor: formValue(form, "factor"), | |
| 896 | sizeAxis: formValue(form, "sizeAxis"), | |
| 897 | size: formValue(form, "size"), | |
| 898 | dx: formValue(form, "dx"), | |
| 899 | dy: formValue(form, "dy"), | |
| 900 | dz: formValue(form, "dz"), | |
| 901 | turn: formValue(form, "turn"), | |
| 902 | }; | |
| 903 | const save = formValue(form, "do") === "save"; | |
| 904 | const done = await editMesh(ctx.app, ctx.auth.user, repo, raw, save); | |
| 905 | if (!done.ok) { | |
| 906 | const e = done.error; | |
| 907 | if (typeof e === "object" && e.kind === "refused") return shiftRefused(ctx, scope, ref, path, e.why); | |
| 908 | if (typeof e === "object" && e.kind === "missing") return notFoundPage(ctx); | |
| 909 | if (e === "not_found" || e === "unauthorized") return notFoundPage(ctx); | |
| 910 | return shiftRefused(ctx, scope, ref, path, editErrorText(e)); | |
| 911 | } | |
| 912 | const { edited, landed } = done.value; | |
| 913 | if (landed === undefined) { | |
| 914 | const hidden = Object.entries(raw).map(([k, v]) => html`<input type="hidden" name="${k}" value="${v}">`); | |
| 915 | return page({ | |
| 916 | ctx, | |
| 917 | title: "New Box", | |
| 918 | crumbs: scope.crumbs, | |
| 919 | palette: scope.palette, | |
| 920 | body: html`${pageHead("The new Box")} | |
| 921 | <p>${done.value.message}</p> | |
| 922 | <dl class="row-facts"><div><dt>Triangles</dt><dd>${edited.triangles.toLocaleString("en")}</dd></div> | |
| 923 | <div><dt>Box</dt><dd>${sizeText(edited.box.size, "units")}</dd></div></dl> | |
| 924 | <form method="post" action="${scope.base}/edit"> | |
| 925 | <input type="hidden" name="mesh" value="1"><input type="hidden" name="do" value="save">${hidden} | |
| 926 | <p>${btn("Commit", { type: "submit", variant: "primary" })} | |
| 927 | ${btn("Back to the file", { href: `${scope.base}/blob/${encodeURIComponent(ref)}/${path}`, variant: "outline" })}</p> | |
| 928 | </form>`, | |
| 929 | }); | |
| 930 | } | |
| 931 | if (landed.pull !== undefined) | |
| 932 | return flashTo(ctx, `${scope.base}/pulls/${landed.pull.number}`, { message: `Committed to ${landed.branch} and opened this pull request.` }); | |
| 933 | return flashTo(ctx, `${scope.base}/blob/${encodeURIComponent(landed.branch)}/${path}`, { message: `Committed to ${landed.branch}.` }); | |
| 934 | } | |
| 935 | ||
| 886 | 936 | /** |
| 887 | 937 | * POST /:owner/:name/edit — the one write. |
| 888 | 938 | * |
| @@ -898,6 +948,7 @@ export async function editSubmit(ctx: Ctx): Promise<Response> { | ||
| 898 | 948 | const scope = localScope(ctx, repo); |
| 899 | 949 | if (!scope.caps.write) return notFoundPage(ctx); |
| 900 | 950 | if (form.has("shift")) return shiftSubmit(ctx, scope, repo, form); |
| 951 | if (form.has("mesh")) return meshSubmit(ctx, scope, repo, form); | |
| 901 | 952 | |
| 902 | 953 | const ref = formValue(form, "ref"); |
| 903 | 954 | const path = formValue(form, "path").trim().replace(/^\/+/, ""); |
src/web/render/model3d.ts +29 −3
| @@ -21,7 +21,7 @@ import { sha256 } from "../../kernel/hash.ts"; | ||
| 21 | 21 | import { createLog } from "../../kernel/log.ts"; |
| 22 | 22 | import type { BuiltAsset } from "../asset.ts"; |
| 23 | 23 | import { html, type Html } from "../html.ts"; |
| 24 | import { btn, empty, fileSize } from "../ui.ts"; | |
| 24 | import { btn, empty, field, fileSize } from "../ui.ts"; | |
| 25 | 25 | import { indexedRows } from "./mesh.ts"; |
| 26 | 26 | import { readDae } from "./collada.ts"; |
| 27 | 27 | import { readObj } from "./obj.ts"; |
| @@ -66,6 +66,32 @@ export function model3d(input: RenderInput): Rendered { | ||
| 66 | 66 | : stl !== undefined && "error" in stl |
| 67 | 67 | ? stl.error |
| 68 | 68 | : "Turning it needs JavaScript and WebGL; Download opens it elsewhere."; |
| 69 | // A writer sees the edit form under a readable STL; one over what a commit holds is told why. | |
| 70 | const editable = input.shift !== undefined && stlFacts !== undefined && format === "stl"; | |
| 71 | const axisSelect = (name: string, label: string, none: string): Html => | |
| 72 | html`<label class="field"><span class="field-label">${label}</span> | |
| 73 | <select class="input" name="${name}"><option value="">${none}</option><option value="x">x</option><option value="y">y</option><option value="z">z</option></select></label>`; | |
| 74 | const edit = | |
| 75 | !editable || input.shift === undefined | |
| 76 | ? html`` | |
| 77 | : input.size > 2 * 1024 * 1024 | |
| 78 | ? html`<p class="muted small">This STL is over 2 MB, more than one commit here can hold: change it in a CAD tool and commit it with git.</p>` | |
| 79 | : html`<form method="post" action="${input.shift.action}" class="mt mesh-edit"> | |
| 80 | <input type="hidden" name="ref" value="${input.shift.ref}"> | |
| 81 | <input type="hidden" name="path" value="${input.shift.path}"> | |
| 82 | <input type="hidden" name="mesh" value="1"> | |
| 83 | <div class="stack"> | |
| 84 | ${field({ name: "factor", label: "Scale by a factor", placeholder: "2 or 0.5", autocomplete: "off" })} | |
| 85 | ${field({ name: "size", label: "or scale one axis to a size", placeholder: "40", autocomplete: "off" })} | |
| 86 | ${axisSelect("sizeAxis", "Size axis", "axis")} | |
| 87 | ${field({ name: "dx", label: "Move x", placeholder: "0", autocomplete: "off" })} | |
| 88 | ${field({ name: "dy", label: "Move y", placeholder: "0", autocomplete: "off" })} | |
| 89 | ${field({ name: "dz", label: "Move z", placeholder: "0", autocomplete: "off" })} | |
| 90 | ${axisSelect("turn", "Turn 90° about", "no turn")} | |
| 91 | </div> | |
| 92 | <p>${btn("Preview the new Box", { type: "submit", name: "do", value: "preview", variant: "outline" })} | |
| 93 | ${btn("Commit", { type: "submit", name: "do", value: "save", variant: "primary" })}</p> | |
| 94 | </form>`; | |
outdated
Principle 1: this sentence explains the form a second time (docs and the preview page already say the order). Cut it or fold it into the legend. |
||
| 69 | 95 | return { |
| 70 | 96 | lines: 0, |
outdated
Principle 5: Commit is primary next to Download, which is also primary; one accent per page. Make Download outline here, or use the primary only on the preview page. |
||
| 71 | 97 | content: html`<figure |
| @@ -96,10 +122,10 @@ export function model3d(input: RenderInput): Rendered { | ||
| 96 | 122 | icon: "file", |
| 97 | 123 | title: "A 3D model", |
| 98 | 124 | note, |
| 99 | action: btn("Download", { href: input.download, variant: "primary", icon: "download" }), | |
| 125 | action: btn("Download", { href: input.download, variant: editable ? "outline" : "primary", icon: "download" }), | |
| 100 | 126 | })} |
| 101 | 127 | </div> |
| 102 | </figure>`, | |
| 128 | </figure>${edit}`, | |
| 103 | 129 | }; |
| 104 | 130 | } |
| 105 | 131 |
test/mesh-edit.test.ts added +349
| @@ -0,0 +1,349 @@ | ||
| 1 | /** | |
| 2 | * Scale, move and turn an STL: the pure module, and the file page's form that saves it as a commit. | |
| 3 | */ | |
| 4 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 5 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 6 | import { tmpdir } from "node:os"; | |
| 7 | import { join } from "node:path"; | |
| 8 | import { createApp, type App } from "../src/app.ts"; | |
| 9 | import { editMesh, editStl, parseNumber, type MeshForm } from "../src/actions/mesh_edit.ts"; | |
| 10 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 12 | import { updateRepoSettings } from "../src/core/repos.ts"; | |
| 13 | import { getUserByName } from "../src/core/users.ts"; | |
| 14 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 15 | import { meshEditCommands } from "../src/tui/screens/mesh_edit.ts"; | |
| 16 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 17 | import type { Screen } from "../src/tui/app/app.ts"; | |
| 18 | import { settleApp } from "./helpers/tui.ts"; | |
| 19 | import { signUp } from "../src/actions/users.ts"; | |
| 20 | import { createSession } from "../src/core/sessions.ts"; | |
| 21 | import { getRepo } from "../src/core/repos.ts"; | |
| 22 | import { commitLog } from "../src/git/read.ts"; | |
| 23 | import { repoDir } from "../src/git/repos.ts"; | |
| 24 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 25 | import { localSource } from "../src/view/local.ts"; | |
| 26 | import { model3d } from "../src/web/render/model3d.ts"; | |
| 27 | import type { RenderInput } from "../src/web/render/renderers.ts"; | |
| 28 | import { readStl } from "../src/web/render/stl.ts"; | |
| 29 | import { fixtureSlot } from "./helpers/slot.ts"; | |
| 30 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 31 | import { quietLogs } from "./helpers/globals.ts"; | |
| 32 | ||
| 33 | quietLogs(); | |
| 34 | ||
| 35 | /** A 10 × 20 × 30 box's two end faces are enough: four triangles spanning it. */ | |
| 36 | const ascii = `solid t | |
| 37 | facet normal 0 0 1 | |
| 38 | outer loop | |
| 39 | vertex 0 0 0 | |
| 40 | vertex 10 0 0 | |
| 41 | vertex 10 20 30 | |
| 42 | endloop | |
| 43 | endfacet | |
| 44 | facet normal 0 0 1 | |
| 45 | outer loop | |
| 46 | vertex 0 0 0 | |
| 47 | vertex 10 20 30 | |
| 48 | vertex 0 20 30 | |
| 49 | endloop | |
| 50 | endfacet | |
| 51 | endsolid t | |
| 52 | `; | |
| 53 | const STL = new TextEncoder().encode(ascii); | |
| 54 | ||
| 55 | const boxOf = (bytes: Uint8Array): string => { | |
| 56 | const r = readStl(bytes); | |
| 57 | if ("error" in r) throw new Error(r.error); | |
| 58 | return r.size; | |
| 59 | }; | |
| 60 | ||
| 61 | describe("editStl", () => { | |
| 62 | test("writes a binary STL that reads back", () => { | |
| 63 | const r = editStl(STL, { move: [0, 0, 0] }); | |
| 64 | if (!r.ok) throw new Error(r.why); | |
| 65 | expect(r.value.bytes.length).toBe(84 + 2 * 50); | |
| 66 | expect(r.value.triangles).toBe(2); | |
| 67 | expect(boxOf(r.value.bytes)).toBe("10 × 20 × 30 units"); | |
| 68 | }); | |
| 69 | test("scale by a factor", () => { | |
| 70 | const r = editStl(STL, { scale: { factor: 2 } }); | |
| 71 | expect(r.ok && boxOf(r.value.bytes)).toBe("20 × 40 × 60 units"); | |
| 72 | }); | |
| 73 | test("scale to a size on one axis scales every axis alike", () => { | |
| 74 | const r = editStl(STL, { scale: { axis: "y", size: 40 } }); | |
| 75 | expect(r.ok && boxOf(r.value.bytes)).toBe("20 × 40 × 60 units"); | |
| 76 | }); | |
| 77 | test("move shifts the box, not its size", () => { | |
| 78 | const r = editStl(STL, { move: [5, -5, 100] }); | |
| 79 | if (!r.ok) throw new Error(r.why); | |
| 80 | expect(r.value.box.min).toEqual([5, -5, 100]); | |
| 81 | expect(r.value.box.size).toEqual([10, 20, 30]); | |
| 82 | }); | |
| 83 | test("a 90° turn about each axis swaps the other two sizes", () => { | |
| 84 | const sizes = (axis: "x" | "y" | "z") => { | |
| 85 | const r = editStl(STL, { turn: { axis, times: 1 } }); | |
| 86 | if (!r.ok) throw new Error(r.why); | |
| 87 | return r.value.box.size; | |
| 88 | }; | |
| 89 | expect(sizes("x")).toEqual([10, 30, 20]); | |
| 90 | expect(sizes("y")).toEqual([30, 20, 10]); | |
| 91 | expect(sizes("z")).toEqual([20, 10, 30]); | |
| 92 | }); | |
| 93 | test("a turn about z takes +x to +y", () => { | |
| 94 | const r = editStl(STL, { turn: { axis: "z", times: 1 } }); | |
| 95 | if (!r.ok) throw new Error(r.why); | |
| 96 | expect(r.value.box.min).toEqual([-20, 0, 0]); | |
| 97 | expect(r.value.box.max).toEqual([0, 10, 30]); | |
| 98 | }); | |
| 99 | test("four turns come home; scale, turn, then move", () => { | |
| 100 | const r = editStl(STL, { turn: { axis: "x", times: 4 } }); | |
| 101 | expect(r.ok && r.value.box.size).toEqual([10, 20, 30]); | |
| 102 | const c = editStl(STL, { scale: { factor: 2 }, turn: { axis: "z", times: 1 }, move: [1, 1, 1] }); | |
| 103 | if (!c.ok) throw new Error(c.why); | |
| 104 | expect(c.value.box.min).toEqual([-39, 1, 1]); | |
| 105 | }); | |
| 106 | test("normals follow the winding", () => { | |
| 107 | const r = editStl(STL, { turn: { axis: "x", times: 1 } }); | |
| 108 | if (!r.ok) throw new Error(r.why); | |
| 109 | const v = new DataView(r.value.bytes.buffer); | |
| 110 | const len = Math.hypot(v.getFloat32(84, true), v.getFloat32(88, true), v.getFloat32(92, true)); | |
| 111 | expect(len).toBeCloseTo(1, 5); | |
| 112 | }); | |
| 113 | test("a size on a flat axis is refused", () => { | |
| 114 | const flat = new TextEncoder().encode(ascii.replaceAll("30", "0").replaceAll("20", "0")); | |
| 115 | const r = editStl(flat, { scale: { axis: "z", size: 5 } }); | |
| 116 | expect(r.ok).toBe(false); | |
| 117 | }); | |
| 118 | }); | |
| 119 | ||
| 120 | describe("parseNumber", () => { | |
| 121 | test("bounded plain numbers only", () => { | |
| 122 | expect(parseNumber("n", " 2.5 ")).toEqual({ ok: true, value: 2.5 }); | |
| 123 | for (const bad of ["", "abc", "NaN", "Infinity", "0x10", "1,5", "2000000", "--1"]) expect(parseNumber("n", bad).ok).toBe(false); | |
| 124 | expect(parseNumber("n", "0", { min: 0.001 }).ok).toBe(false); | |
| 125 | }); | |
| 126 | }); | |
| 127 | ||
| 128 | describe("the file page's STL form", () => { | |
| 129 | let dataDir: string; | |
| 130 | let app: App; | |
| 131 | let servers: Servers; | |
| 132 | let base = ""; | |
| 133 | let origin = ""; | |
| 134 | let alice = ""; | |
| 135 | let kim = ""; | |
| 136 | const post = (fields: Record<string, string>, cookie?: string, from = origin) => | |
| 137 | fetch(`${base}/alice/parts/edit`, { | |
| 138 | method: "POST", | |
| 139 | redirect: "manual", | |
| 140 | headers: { origin: from, ...(cookie === undefined ? {} : { cookie }) }, | |
| 141 | body: new URLSearchParams({ ref: "main", path: "a.stl", mesh: "1", ...fields }), | |
| 142 | }); | |
| 143 | const stored = async (path = "a.stl"): Promise<Uint8Array> => { | |
| 144 | const repo = getRepo(app.db, "alice", "parts")!; | |
| 145 | const blob = await localSource(app, repo, undefined).blob("main", path); | |
| 146 | if (!blob.ok || blob.value.kind === "too_large") throw new Error("no file"); | |
| 147 | return blob.value.body as Uint8Array; | |
| 148 | }; | |
| 149 | const page = async (path: string, cookie?: string) => | |
| 150 | await (await fetch(`${base}/alice/parts/blob/main/${path}`, { headers: cookie === undefined ? {} : { cookie } })).text(); | |
| 151 | ||
| 152 | beforeAll(async () => { | |
| 153 | dataDir = await mkdtemp(join(tmpdir(), "forge-mesh-")); | |
| 154 | app = createApp({ dataDir, port: 0 }); | |
| 155 | servers = await serve(app); | |
| 156 | base = servers.url; | |
| 157 | origin = new URL(base).origin; | |
| 158 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-long-mesh-passphrase" }); | |
| 159 | const k = await signUp(app, { username: "kim", email: "[email protected]", password: "a-long-mesh-passphrase" }, { slot: fixtureSlot(app) }); | |
| 160 | if (!a.ok || !k.ok) throw new Error("signup failed"); | |
| 161 | alice = `forge_session=${createSession(app.db, a.value.id).token}`; | |
| 162 | kim = `forge_session=${createSession(app.db, k.value.id).token}`; | |
| 163 | const made = await createRepo(app, a.value, { name: "parts", visibility: "public" }); | |
| 164 | if (!made.ok) throw new Error("repo failed"); | |
| 165 | await commitToBranch(app, a.value, made.value, { message: "first", files: [{ path: "a.stl", content: STL }] }); | |
| 166 | }); | |
| 167 | afterAll(async () => { | |
| 168 | servers.stop(); | |
| 169 | app.close(); | |
| 170 | await rm(dataDir, { recursive: true, force: true }); | |
| 171 | }); | |
| 172 | ||
| 173 | test("a writer sees the form, a reader does not", async () => { | |
| 174 | expect(await page("a.stl", alice)).toContain('name="mesh"'); | |
| 175 | expect(await page("a.stl", kim)).not.toContain('name="mesh"'); | |
| 176 | expect(await page("a.stl")).not.toContain('name="mesh"'); | |
| 177 | }); | |
| 178 | ||
| 179 | test("a preview shows the new Box and writes nothing", async () => { | |
| 180 | const res = await post({ do: "preview", factor: "2", dz: "5" }, alice); | |
| 181 | expect(res.status).toBe(200); | |
| 182 | expect(await res.text()).toContain("20 × 40 × 60 units"); | |
| 183 | expect(await stored()).toEqual(STL); | |
| 184 | }); | |
| 185 | ||
| 186 | test("bad numbers, no change, both scales: refused with a reason, nothing written", async () => { | |
| 187 | for (const f of [{ factor: "soon" }, { factor: "0" }, { factor: "2000" }, {}, { factor: "2", size: "3", sizeAxis: "x" }, { dx: "1e9" }, { turn: "w" }]) { | |
| 188 | const res = await post({ do: "save", ...f }, alice); | |
| 189 | expect(res.status).toBe(400); | |
| 190 | } | |
| 191 | expect(await stored()).toEqual(STL); | |
| 192 | }); | |
| 193 | ||
| 194 | test("a non-writer and a cross-origin post write nothing", async () => { | |
| 195 | expect((await post({ do: "save", factor: "2" }, kim)).status).toBe(404); | |
| 196 | expect((await post({ do: "save", factor: "2" }, alice, "https://evil.example")).status).toBe(403); | |
| 197 | expect(await stored()).toEqual(STL); | |
| 198 | }); | |
| 199 | ||
| 200 | test("a path that is not an .stl is refused", async () => { | |
| 201 | expect((await post({ do: "save", factor: "2", path: "README.md" }, alice)).status).toBe(400); | |
| 202 | }); | |
| 203 | ||
| 204 | test("a save is a commit whose message names the change", async () => { | |
| 205 | const res = await post({ do: "save", factor: "2", turn: "z", dx: "1" }, alice); | |
| 206 | expect(res.status).toBe(303); | |
| 207 | expect(boxOf(await stored())).toBe("40 × 20 × 60 units"); | |
| 208 | const log = await commitLog(repoDir(app.reposRoot, "alice", "parts"), "main", { limit: 1 }); | |
| 209 | expect(log.ok && log.value[0]?.subject).toBe("a.stl: scale ×2, turn 90° about z, move 1, 0, 0"); | |
| 210 | }); | |
| 211 | ||
| 212 | test("a file over what a commit holds gets a sentence, not a form", () => { | |
| 213 | const big = new Uint8Array(84 + 50 * 50_000); | |
| 214 | new DataView(big.buffer).setUint32(80, 50_000, true); | |
| 215 | const input: RenderInput = { path: "big.stl", body: big, size: big.length, media: "/m", download: "/d", shift: { action: "/e", ref: "main", path: "big.stl" } }; | |
| 216 | const out = String(model3d(input).content); | |
| 217 | expect(out).not.toContain('name="mesh"'); | |
| 218 | expect(out).toContain("over 2 MB"); | |
| 219 | expect(String(model3d({ ...input, body: STL, size: STL.length }).content)).toContain('name="mesh"'); | |
| 220 | }); | |
| 221 | }); | |
| 222 | ||
| 223 | describe("the action, past the happy path", () => { | |
| 224 | let dataDir: string; | |
| 225 | let app: App; | |
| 226 | const git = (cwd: string, args: string[], input?: Uint8Array): string => { | |
| 227 | const r = Bun.spawnSync(["git", ...args], { | |
| 228 | cwd, | |
| 229 | ...(input === undefined ? {} : { stdin: input }), | |
| 230 | env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "[email protected]", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "[email protected]" }, | |
| 231 | }); | |
| 232 | if (r.exitCode !== 0) throw new Error(r.stderr.toString()); | |
| 233 | return r.stdout.toString().trim(); | |
| 234 | }; | |
| 235 | const form = (over: Partial<MeshForm> = {}): MeshForm => ({ | |
| 236 | ref: "main", path: "a.stl", factor: "2", sizeAxis: "", size: "", dx: "", dy: "", dz: "", turn: "", ...over, | |
| 237 | }); | |
| 238 | const repoOf = (owner: string, name: string) => getRepo(app.db, owner, name)!; | |
| 239 | const user = (name: string) => getUserByName(app.db, name)!; | |
| 240 | ||
| 241 | beforeAll(async () => { | |
| 242 | dataDir = await mkdtemp(join(tmpdir(), "forge-mesh-act-")); | |
| 243 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 244 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-long-mesh-passphrase" }); | |
| 245 | const b = await signUp(app, { username: "bob", email: "[email protected]", password: "a-long-mesh-passphrase" }, { slot: fixtureSlot(app) }); | |
| 246 | if (!a.ok || !b.ok) throw new Error("signup failed"); | |
| 247 | const org = createOrg(app.db, "acme", a.value.id); | |
| 248 | if (!org.ok) throw new Error("org failed"); | |
| 249 | const team = createTeam(app.db, org.value.id, "devs", "write"); | |
| 250 | if (!team.ok) throw new Error("team failed"); | |
| 251 | addTeamMember(app.db, team.value, b.value.id); | |
| 252 | const made = await createRepo(app, a.value, { name: "widget", owner: "acme", visibility: "public" }); | |
| 253 | if (!made.ok) throw new Error("repo failed"); | |
| 254 | await commitToBranch(app, a.value, made.value, { message: "first", files: [{ path: "a.stl", content: STL }] }); | |
| 255 | updateRepoSettings(app.db, repoOf("acme", "widget"), { protectDefault: true }); | |
| 256 | const dir = repoDir(app.reposRoot, "acme", "widget"); | |
| 257 | git(dir, ["tag", "v1", "main"]); | |
| 258 | // A file over what one commit holds cannot come in through the app, so make it with git. | |
| 259 | const big = new Uint8Array(84 + 50 * 50_000); | |
| 260 | new DataView(big.buffer).setUint32(80, 50_000, true); | |
| 261 | const blob = git(dir, ["hash-object", "-w", "--stdin"], big); | |
| 262 | const tree = git(dir, ["mktree"], new TextEncoder().encode(`100644 blob ${blob}\tbig.stl\n`)); | |
| 263 | git(dir, ["update-ref", "refs/heads/big", git(dir, ["commit-tree", tree, "-m", "big"])]); | |
| 264 | }); | |
| 265 | afterAll(async () => { | |
| 266 | app.close(); | |
| 267 | await rm(dataDir, { recursive: true, force: true }); | |
| 268 | }); | |
| 269 | ||
| 270 | test("on a protected default an ordinary writer's save is a new branch and a pull", async () => { | |
| 271 | const done = await editMesh(app, user("bob"), repoOf("acme", "widget"), form({ turn: "z" }), true); | |
| 272 | if (!done.ok) throw new Error(JSON.stringify(done.error)); | |
| 273 | expect(done.value.landed?.branch).toMatch(/^bob\/mesh-a\.stl-/); | |
| 274 | expect(done.value.landed?.pull).toBeDefined(); | |
| 275 | const main = await localSource(app, repoOf("acme", "widget"), undefined).blob("main", "a.stl"); | |
| 276 | if (!main.ok || main.value.kind === "too_large") throw new Error("no file"); | |
| 277 | expect(main.value.body as Uint8Array).toEqual(STL); | |
| 278 | }); | |
| 279 | ||
| 280 | test("a ref that is not a branch also goes to a new branch and a pull", async () => { | |
| 281 | const done = await editMesh(app, user("alice"), repoOf("acme", "widget"), form({ ref: "v1" }), true); | |
| 282 | if (!done.ok) throw new Error(JSON.stringify(done.error)); | |
| 283 | expect(done.value.landed?.branch).toMatch(/^alice\/mesh-a\.stl-/); | |
| 284 | expect(done.value.landed?.pull).toBeDefined(); | |
| 285 | }); | |
| 286 | ||
| 287 | test("an admin's save on the protected default lands on it", async () => { | |
| 288 | const done = await editMesh(app, user("alice"), repoOf("acme", "widget"), form({ dx: "1" }), true); | |
| 289 | if (!done.ok) throw new Error(JSON.stringify(done.error)); | |
| 290 | expect(done.value.landed?.branch).toBe("main"); | |
| 291 | expect(done.value.landed?.pull).toBeUndefined(); | |
| 292 | }); | |
| 293 | ||
| 294 | test("a file over 2 MB is refused with the sentence, preview or commit", async () => { | |
| 295 | for (const commit of [false, true]) { | |
| 296 | const done = await editMesh(app, user("alice"), repoOf("acme", "widget"), form({ ref: "big", path: "big.stl" }), commit); | |
| 297 | expect(!done.ok && (done.error as { why?: string }).why).toContain("over 2 MB"); | |
| 298 | } | |
| 299 | }); | |
| 300 | ||
| 301 | test("an unsafe ref and a missing file are missing", async () => { | |
| 302 | for (const f of [form({ ref: "../x" }), form({ path: "gone.stl" })]) { | |
| 303 | const done = await editMesh(app, user("alice"), repoOf("acme", "widget"), f, true); | |
| 304 | expect(!done.ok && (done.error as { kind?: string }).kind).toBe("missing"); | |
| 305 | } | |
| 306 | }); | |
| 307 | ||
| 308 | test("the terminal's command is for a writer and makes the same commit", async () => { | |
| 309 | const open = (username: string) => { | |
| 310 | const { app: tui, session } = createForgeApp( | |
| 311 | app, | |
| 312 | { sshUsername: username, remoteAddress: "127.0.0.1", fingerprint: `SHA256:${username}`, user: user(username) }, | |
| 313 | { terminal: headlessTerminal(100, 30), exitHooks: false }, | |
| 314 | ); | |
| 315 | tui.start(); | |
| 316 | const parent: Screen = { title: "parent", keys: [], render() {}, key: () => false }; | |
| 317 | return { tui, command: meshEditCommands(session, tui.ctx, repoOf("acme", "widget"), () => parent) }; | |
| 318 | }; | |
| 319 | const type = async (tui: ReturnType<typeof open>["tui"], text: string) => { | |
| 320 | for (const key of text) tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 321 | tui.dispatch({ type: "key", key: "enter", ctrl: false, alt: false, shift: false }); | |
| 322 | await settleApp(tui); | |
| 323 | }; | |
| 324 | const nobody = await signUp(app, { username: "kim", email: "[email protected]", password: "a-long-mesh-passphrase" }, { slot: fixtureSlot(app) }); | |
| 325 | if (!nobody.ok) throw new Error("signup failed"); | |
| 326 | const reader = open("kim"); | |
| 327 | expect(reader.command).toEqual([]); | |
| 328 | reader.tui.stop(); | |
| 329 | const { tui, command } = open("alice"); | |
| 330 | expect(command.map((c) => c.id)).toEqual(["mesh-edit"]); | |
| 331 | let announce = () => {}; | |
| 332 | const announced = new Promise<void>((resolve) => (announce = resolve)); | |
| 333 | const off = app.bus.subscribe((e) => e.kind === "push" && announce()); | |
| 334 | try { | |
| 335 | void command[0]!.run(); | |
| 336 | await settleApp(tui); | |
| 337 | await type(tui, "a.stl"); | |
| 338 | await type(tui, "3"); | |
| 339 | await type(tui, ""); | |
| 340 | await type(tui, ""); | |
| 341 | await announced; | |
| 342 | const log = await commitLog(repoDir(app.reposRoot, "acme", "widget"), "main", { limit: 1 }); | |
| 343 | expect(log.ok && log.value[0]?.subject).toBe("a.stl: scale ×3"); | |
| 344 | } finally { | |
| 345 | off(); | |
| 346 | tui.stop(); | |
| 347 | } | |
| 348 | }); | |
| 349 | }); |
new above
offline
Principle 6: a fieldset is a bordered box around a group. Use plain labelled rows with space between (3) and a hairline at the end.