Checkpoint SKF project format and export updates

This commit is contained in:
Formsmith
2026-07-16 12:30:39 +03:00
parent 400c4bf86e
commit 70e45bb966
22 changed files with 3028 additions and 133 deletions
+15 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { appendEditorHistorySnapshot, boundedEditorHistory, editorHistoryEntry, hydrateEditorHistoryState, projectShapesFingerprint } from "@/lib/editorHistory";
import { appendEditorHistorySnapshot, boundedEditorHistory, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint } from "@/lib/editorHistory";
import type { WorkplaneShape } from "@/types/sketchforge";
function box(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
@@ -107,4 +107,18 @@ describe("editor history snapshots", () => {
expect(restored.entries).toHaveLength(1);
expect(restored.entries[0].shapes[0].x).toBe(9);
});
it("selects all history or the requested number of recent undo actions for project export", () => {
const entries = Array.from({ length: 140 }, (_, x) => editorHistoryEntry([box({ x })], []));
const unlimited = editorHistoryForExport(entries, 120, "unlimited");
expect(unlimited.entries).toBe(entries);
expect(unlimited.index).toBe(120);
const lastThirty = editorHistoryForExport(entries, 120, 30);
expect(lastThirty.entries).toHaveLength(31);
expect(lastThirty.index).toBe(30);
expect(lastThirty.entries[0].shapes[0].x).toBe(90);
expect(lastThirty.entries[30].shapes[0].x).toBe(120);
});
});
+2
View File
@@ -6,6 +6,8 @@ describe("project export filenames", () => {
expect(projectExportFileName("Gearbox Prototype", "stl")).toBe("Gearbox Prototype.stl");
expect(projectExportFileName("Gearbox Prototype", "obj")).toBe("Gearbox Prototype.obj");
expect(projectExportFileName("Gearbox Prototype", "step")).toBe("Gearbox Prototype.step");
expect(projectExportFileName("Gearbox Prototype", "svg")).toBe("Gearbox Prototype.svg");
expect(projectExportFileName("Gearbox Prototype", "skf")).toBe("Gearbox Prototype.skf");
});
it("removes filesystem-reserved characters without discarding the project name", () => {
+342
View File
@@ -0,0 +1,342 @@
import { describe, expect, it } from "vitest";
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
import { editorHistoryEntry } from "@/lib/editorHistory";
import { projectAssetFromBytes } from "@/lib/projectAssets";
import { canonicalizeShape } from "@/lib/workplaneShapes";
import {
exportSkfProject,
importSkfProject,
SKF_FORMAT_VERSION,
SKF_SCHEMA_ID,
type SkfProjectDocumentV1,
type SkfProjectExportInput,
} from "@/lib/skfProject";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { ShapeKind, WorkplaneShape } from "@/types/sketchforge";
function shape(kind: ShapeKind, id = `${kind}-1`, overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
return {
id,
name: kind,
kind,
color: "#12a4cc",
x: 1,
z: 2,
elevation: 3,
size: 20,
width: 20,
depth: 18,
height: 16,
rotation: 15,
rotationX: 5,
rotationZ: 10,
locked: false,
hidden: false,
...overrides,
};
}
function input(shapes: WorkplaneShape[], overrides: Partial<SkfProjectExportInput> = {}): SkfProjectExportInput {
const history = [editorHistoryEntry(shapes, [])];
return {
projectId: "project-original",
projectName: "Round trip",
createdAt: 1_700_000_000_000,
modifiedAt: 1_700_000_100_000,
shapes,
history,
historyIndex: 0,
assets: [],
workspace: DEFAULT_WORKPLANE_WORKSPACE,
snapGrid: DEFAULT_SNAP_GRID,
placementElevation: 12.5,
...overrides,
};
}
function packageDocument(bytes: Uint8Array) {
const files = unzipSync(bytes);
return { files, document: JSON.parse(strFromU8(files["project.json"])) as SkfProjectDocumentV1 };
}
function mutateProject(bytes: Uint8Array, mutate: (document: SkfProjectDocumentV1) => void) {
const files = unzipSync(bytes);
const document = JSON.parse(strFromU8(files["project.json"])) as SkfProjectDocumentV1;
mutate(document);
files["project.json"] = strToU8(JSON.stringify(document));
return zipSync(files);
}
describe("SketchForge .skf project packages", () => {
it("round-trips every supported native shape kind and editable properties", async () => {
const nativeKinds: ShapeKind[] = [
"box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
"halfSphere", "torus", "tube", "ring", "wedge", "polygon", "icosahedron",
];
const shapes = nativeKinds.map((kind, index) => shape(kind, `${kind}-${index}`, {
hole: index === 2,
locked: index === 3,
hidden: index === 4,
mirrorX: index === 5,
sides: index + 3,
text: kind === "text" ? "Editable" : undefined,
sketchProfile: kind === "sketch" ? {
points: [
{ id: "p1", x: 0, z: 0 },
{ id: "p2", x: 10, z: 0 },
{ id: "p3", x: 10, z: 10 },
],
segments: [
{ id: "s1", startId: "p1", endId: "p2", kind: "line" },
{ id: "s2", startId: "p2", endId: "p3", kind: "bezier" },
{ id: "s3", startId: "p3", endId: "p1", kind: "line" },
],
} : undefined,
}));
const exported = await exportSkfProject(input(shapes));
const { document } = packageDocument(exported);
const restored = await importSkfProject(exported);
expect(restored.projectName).toBe("Round trip");
expect(restored.sourceProjectId).toBe("project-original");
expect(JSON.stringify(restored.shapes)).toBe(JSON.stringify(shapes.map(canonicalizeShape)));
expect(restored.workspace).toEqual(DEFAULT_WORKPLANE_WORKSPACE);
expect(restored.snapGrid).toBe(DEFAULT_SNAP_GRID);
expect(restored.placementElevation).toBe(12.5);
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
});
it("preserves nested groups, holes, intersection metadata, edge history, B-Rep, and undo/redo", async () => {
const solid = shape("box", "solid", { x: 0 });
const hole = shape("cylinder", "hole", { hole: true, color: "#b8c2cc", x: 4 });
const group = shape("mesh", "group", {
name: "Intersection",
groupOperation: "intersection",
groupedBaseWidth: 30,
groupedBaseDepth: 30,
groupedBaseHeight: 20,
groupedShapes: [solid, hole],
importedMesh: {
positions: [0, 0, 0, 2, 0, 0, 0, 2, 0],
normals: [0, 0, 1, 0, 0, 1, 0, 0, 1],
baseWidth: 2,
baseDepth: 1,
baseHeight: 2,
triangleCount: 1,
sourceFormat: "json",
},
cadBrep: "BREP exact payload",
edgeTreatments: [{ kind: "fillet", amount: 1.25, edgeCount: 3 }],
edgeTreatmentHistory: [{
id: "edge-history-1",
createdAt: 1_700_000_050_000,
feature: { kind: "fillet", amount: 1.25, edgeCount: 3 },
before: shape("box", "group", { width: 30, depth: 30, height: 20 }),
}],
});
const before = editorHistoryEntry([solid, hole], ["solid", "hole"]);
const after = editorHistoryEntry([group], ["group"]);
const exported = await exportSkfProject(input([group], { history: [before, after], historyIndex: 1 }));
const { document } = packageDocument(exported);
expect(document.groups[0].operation).toBe("boolean-intersection");
expect(document.features.some((feature) => feature.type === "fillet")).toBe(true);
expect(document.exactCad).toHaveLength(1);
const restored = await importSkfProject(exported);
expect(restored.history).toHaveLength(2);
expect(restored.historyIndex).toBe(1);
expect(restored.shapes[0].groupedShapes).toEqual([solid, hole]);
expect(restored.shapes[0].groupOperation).toBe("intersection");
expect(restored.shapes[0].cadBrep).toBe("BREP exact payload");
expect(restored.shapes[0].edgeTreatmentHistory?.[0].before.kind).toBe("box");
});
it("stores one original source asset for repeated imported instances and regenerates it once", async () => {
const sourceBytes = strToU8("solid source");
const asset = await projectAssetFromBytes("shared.stl", "stl", sourceBytes);
const importedMesh: NonNullable<WorkplaneShape["importedMesh"]> = {
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
baseWidth: 1,
baseDepth: 1,
baseHeight: 1,
triangleCount: 1,
sourceFormat: "stl",
assetId: asset.id,
};
const instances = [
shape("mesh", "instance-a", { importedMesh, x: 0 }),
shape("mesh", "instance-b", { importedMesh, x: 30 }),
];
const exported = await exportSkfProject(input(instances, { assets: [asset] }));
const { document } = packageDocument(exported);
let importCalls = 0;
const restored = await importSkfProject(exported, {
sourceImporter: async () => {
importCalls += 1;
return { ...importedMesh, assetId: undefined };
},
});
expect(document.assets.filter((entry) => entry.kind === "source")).toHaveLength(1);
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
expect(restored.assets).toHaveLength(1);
expect(restored.shapes[0].importedMesh?.assetId).toBe(restored.shapes[1].importedMesh?.assetId);
expect(importCalls).toBe(1);
});
it.each(["svg", "step"] as const)("stores and restores original %s sources", async (sourceFormat) => {
const asset = await projectAssetFromBytes(`source.${sourceFormat}`, sourceFormat, strToU8(`${sourceFormat} source`));
const importedMesh: NonNullable<WorkplaneShape["importedMesh"]> = {
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
baseWidth: 1,
baseDepth: 1,
baseHeight: 1,
triangleCount: 1,
sourceFormat,
assetId: asset.id,
...(sourceFormat === "step" ? { brepStep: "exact STEP" } : {}),
};
const exported = await exportSkfProject(input([shape("mesh", `${sourceFormat}-object`, { importedMesh })], { assets: [asset] }));
const { document } = packageDocument(exported);
const restored = await importSkfProject(exported, { sourceImporter: async () => importedMesh });
expect(document.assets.filter((entry) => entry.kind === "source")).toHaveLength(1);
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
expect(restored.assets[0].sourceFormat).toBe(sourceFormat);
expect(restored.shapes[0].importedMesh?.sourceFormat).toBe(sourceFormat);
if (sourceFormat === "step") expect(document.exactCad[0].importedStepAssetId).toBeTruthy();
});
it("deduplicates and restores reference images stored in sketches and image plates", async () => {
const dataUrl = "data:image/png;base64,AAECAwQ=";
const imageShape = shape("sketch", "sketch-images", {
imagePlate: { dataUrl, mimeType: "image/png", pixelWidth: 2, pixelHeight: 2 },
sketchProfile: {
points: [
{ id: "p1", x: 0, z: 0 },
{ id: "p2", x: 10, z: 0 },
{ id: "p3", x: 0, z: 10 },
],
segments: [
{ id: "s1", startId: "p1", endId: "p2" },
{ id: "s2", startId: "p2", endId: "p3" },
{ id: "s3", startId: "p3", endId: "p1" },
],
images: [{
id: "image-1",
name: "Reference",
dataUrl,
mimeType: "image/png",
pixelWidth: 2,
pixelHeight: 2,
x: 0,
z: 0,
width: 10,
depth: 10,
}],
},
});
const exported = await exportSkfProject(input([imageShape]));
const { document } = packageDocument(exported);
const restored = await importSkfProject(exported);
expect(document.assets.filter((entry) => entry.kind === "image")).toHaveLength(1);
expect(restored.shapes[0].imagePlate?.dataUrl).toBe(dataUrl);
expect(restored.shapes[0].sketchProfile?.images?.[0].dataUrl).toBe(dataUrl);
});
it("deduplicates derived geometry when legacy imported objects share one mesh", async () => {
const mesh = {
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
baseWidth: 1,
baseDepth: 1,
baseHeight: 1,
triangleCount: 1,
sourceFormat: "json" as const,
};
const exported = await exportSkfProject(input([
shape("mesh", "legacy-a", { importedMesh: mesh }),
shape("mesh", "legacy-b", { importedMesh: mesh }),
]));
const { document } = packageDocument(exported);
const restored = await importSkfProject(exported);
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(1);
expect(restored.shapes[0].importedMesh?.positions).toEqual(mesh.positions);
expect(restored.shapes[1].importedMesh?.positions).toEqual(mesh.positions);
});
it("migrates the documented v0 JSON project without changing IDs", async () => {
const box = shape("box", "legacy-box");
const legacy = strToU8(JSON.stringify({
schema: SKF_SCHEMA_ID,
formatVersion: 0,
project: { id: "legacy-project", name: "Legacy", createdAt: 100, modifiedAt: 200 },
shapes: [box],
workspace: DEFAULT_WORKPLANE_WORKSPACE,
snapGrid: "0.5 mm",
}));
const restored = await importSkfProject(legacy);
expect(restored.migratedFromVersion).toBe(0);
expect(restored.sourceProjectId).toBe("legacy-project");
expect(restored.shapes[0].id).toBe("legacy-box");
expect(restored.snapGrid).toBe("0.5 mm");
});
it("rejects unsupported future versions before restoring any state", async () => {
const exported = await exportSkfProject(input([shape("box")]));
const future = mutateProject(exported, (document) => {
(document as { formatVersion: number }).formatVersion = SKF_FORMAT_VERSION + 1;
});
await expect(importSkfProject(future)).rejects.toThrow("requires a newer SketchForge version");
});
it("rejects missing references, duplicate IDs, cyclic groups, unknown operations, and corrupt assets", async () => {
const twoShapes = await exportSkfProject(input([shape("box", "one"), shape("box", "two")]));
const missing = mutateProject(twoShapes, (document) => {
document.states[0].rootNodeIds[0] = "missing-node";
});
await expect(importSkfProject(missing)).rejects.toThrow("missing node");
const duplicate = mutateProject(twoShapes, (document) => {
const [first, second] = document.states[0].nodes;
second.objectId = first.objectId;
second.definition.id = first.objectId;
});
await expect(importSkfProject(duplicate)).rejects.toThrow("duplicate object ID");
const grouped = await exportSkfProject(input([shape("mesh", "group-cycle", {
groupedShapes: [shape("box", "child-a"), shape("box", "child-b")],
})]));
const cyclic = mutateProject(grouped, (document) => {
const root = document.states[0].nodes.find((node) => node.objectId === "group-cycle")!;
root.groupedShapeNodeIds = [root.nodeId];
});
await expect(importSkfProject(cyclic)).rejects.toThrow("Cyclic group");
const unknownOperation = mutateProject(grouped, (document) => {
document.features[0].type = "unsupported-operation";
});
await expect(importSkfProject(unknownOperation)).rejects.toThrow("Unknown operation type");
const legacyMesh = await exportSkfProject(input([shape("mesh", "mesh", {
importedMesh: {
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
baseWidth: 1,
baseDepth: 1,
baseHeight: 1,
triangleCount: 1,
sourceFormat: "json",
},
})]));
const { files, document } = packageDocument(legacyMesh);
const asset = document.assets.find((entry) => entry.kind === "derived-mesh")!;
files[asset.path][20] ^= 0xff;
await expect(importSkfProject(zipSync(files))).rejects.toThrow("integrity check");
});
});
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { toSvgProjection } from "@/lib/svgExport";
describe("SVG projection export", () => {
it("writes an SVG 1.1 document with millimeter dimensions and even-odd contours", () => {
const svg = toSvgProjection([
{
name: "Plate & ring",
color: "#d41721",
polygons: [
[[-5, -3], [5, -3], [5, 3], [-5, 3]],
[[-2, -1], [-2, 1], [2, 1], [2, -1]],
],
},
], "Fixture <top>");
expect(svg).toContain('version="1.1"');
expect(svg).toContain('width="10mm" height="6mm" viewBox="-5 -3 10 6"');
expect(svg).toContain('fill-rule="evenodd"');
expect(svg).toContain('data-name="Plate &amp; ring"');
expect(svg).toContain("<title>Fixture &lt;top&gt;</title>");
expect(svg.match(/M/g)).toHaveLength(2);
});
it("rejects empty and zero-area projections", () => {
expect(() => toSvgProjection([])).toThrow(/no readable contours/i);
expect(() => toSvgProjection([{ name: "Line", color: "bad", polygons: [[[0, 0], [1, 0], [2, 0]]] }])).toThrow(/visible area/i);
});
});
+43 -7
View File
@@ -4,12 +4,13 @@ import {
MAX_SVG_GEOMETRY_ELEMENTS,
analyzeTriangleSoup,
buildSvgExtrusionFromPaths,
normalizeSvgDocumentType,
normalizeSvgUseReferences,
validateClosedSolidTriangleSoup,
validateSvgSourcePreflight,
} from "@/lib/svgImport";
function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill?: string; fillOpacity?: number; opacity?: number } = {}) {
function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill?: string; fillOpacity?: number; opacity?: number; stroke?: string; strokeOpacity?: number; strokeWidth?: number } = {}) {
const path = new THREE.ShapePath();
path.moveTo(points[0][0], points[0][1]);
for (const [x, y] of points.slice(1)) path.lineTo(x, y);
@@ -19,6 +20,9 @@ function shapePath(points: Array<[number, number]>, options: { closed?: boolean;
fill: options.fill ?? "#000",
fillOpacity: options.fillOpacity ?? 1,
opacity: options.opacity ?? 1,
stroke: options.stroke,
strokeOpacity: options.strokeOpacity ?? 1,
strokeWidth: options.strokeWidth ?? 1,
visibility: "visible",
},
};
@@ -50,11 +54,25 @@ function geometryPositions(geometry: THREE.BufferGeometry) {
}
describe("SVG source preflight", () => {
it("rejects XML entities and external references", () => {
expect(() => validateSvgSourcePreflight('<!DOCTYPE svg [<!ENTITY x "bad">]><svg/>')).toThrow(/document types and entities/i);
it("accepts and removes the standard SVG 1.1 document type", () => {
const source = `<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"/>`;
expect(() => validateSvgSourcePreflight(source)).not.toThrow();
expect(normalizeSvgDocumentType(source)).not.toMatch(/<!DOCTYPE/i);
});
it("continues to reject XML entities, non-SVG doctypes, and external references", () => {
expect(() => validateSvgSourcePreflight('<!DOCTYPE svg [<!ENTITY x "bad">]><svg/>')).toThrow(/entities/i);
expect(() => validateSvgSourcePreflight('<!DOCTYPE html><svg/>')).toThrow(/only the standard SVG 1\.1 document type/i);
expect(() => validateSvgSourcePreflight('<svg><use href="https://example.com/art.svg#part"/></svg>')).toThrow(/external references/i);
});
it("reports malformed Tinkercad cross-section geometry", () => {
expect(() => validateSvgSourcePreflight('<svg width="NaNmm" viewBox="NaN NaN NaN NaN"><path d="z"/></svg>')).toThrow(/workplane intersects the model/i);
});
it("rejects excessive geometry before SVGLoader runs", () => {
const source = `<svg>${"<rect width='1' height='1'/>".repeat(MAX_SVG_GEOMETRY_ELEMENTS + 1)}</svg>`;
expect(() => validateSvgSourcePreflight(source)).toThrow(/too many geometry elements/i);
@@ -85,10 +103,28 @@ describe("SVG path extrusion", () => {
});
it("ignores non-filled and fully transparent paths", () => {
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "none" })])).toThrow(/no readable visible filled paths/i);
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { opacity: 0 })])).toThrow(/no readable visible filled paths/i);
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fillOpacity: 0 })])).toThrow(/no readable visible filled paths/i);
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "#00000000" })])).toThrow(/no readable visible filled paths/i);
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "none" })])).toThrow(/no readable visible/i);
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { opacity: 0 })])).toThrow(/no readable visible/i);
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fillOpacity: 0 })])).toThrow(/no readable visible/i);
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "#00000000" })])).toThrow(/no readable visible/i);
});
it("imports a closed Tinkercad-style stroke as an extrusion profile", () => {
const tinkercadOutline = shapePath([[0, 0], [10, 0], [10, 6], [0, 6], [0, 0]], {
closed: false,
fill: "none",
stroke: "rgb(255,0,0)",
strokeWidth: 0.001,
});
const result = buildSvgExtrusionFromPaths([tinkercadOutline]);
expect(result.analysis.width).toBeCloseTo(10);
expect(result.analysis.depth).toBeCloseTo(6);
expect(result.analysis.volume).toBeCloseTo(240);
});
it("explains how to fix an open stroke-only SVG", () => {
const openStroke = shapePath([[0, 0], [10, 0], [5, 5]], { closed: false, fill: "none", stroke: "#000", strokeWidth: 1 });
expect(() => buildSvgExtrusionFromPaths([openStroke])).toThrow(/only open strokes/i);
});
it("imports open filled contours when they enclose usable area and skips lines", () => {