release: SnapCAD Studio 1.0.10 (desktop menuler, macOS kisayollari, YakNet SSO)
Build and Push Docker Images / build (push) Canceled after 0s
Desktop Release / Build linux desktop (push) Canceled after 0s
Desktop Release / Build windows desktop (push) Canceled after 0s
Desktop Release / Attach packages to release (push) Canceled after 0s
Desktop Release / Build macos desktop (push) Canceled after 0s
CI / Typecheck and unit tests (push) Canceled after 0s

This commit is contained in:
Enes Yakıştır
2026-11-12 10:12:35 +03:00
parent d5cc023856
commit ee28672e23
81 changed files with 10729 additions and 821 deletions
+1 -1
View File
@@ -21,7 +21,7 @@ import {
type Point2D,
} from "@/lib/cad2dEngine";
describe("2D CAD Engine - Polygon Booleans via polygon-clipping", () => {
describe("2D CAD Engine - Polygon Booleans via Clipper2 (clipper2-js)", () => {
const squareA: Point2D[] = [
{ x: 0, y: 0 },
{ x: 20, y: 0 },
+121
View File
@@ -0,0 +1,121 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cloudApiFetch } from "../../apps/web/src/lib/cloudApi";
import type { SnapCadDesktopBridge } from "../../apps/web/src/types/desktop";
describe("cloudApiFetch", () => {
const globalAny = globalThis as unknown as {
window?: Partial<Window>;
fetch?: typeof fetch;
};
const originalWindow = globalAny.window;
const originalFetch = globalAny.fetch;
afterEach(() => {
globalAny.window = originalWindow;
globalAny.fetch = originalFetch;
vi.restoreAllMocks();
});
it("rejects non-cloud-api paths before attempting network or IPC", async () => {
await expect(cloudApiFetch("https://evil.example/api")).rejects.toThrow(/Geçersiz bulut API yolu/);
await expect(cloudApiFetch("/login.php")).rejects.toThrow(/Geçersiz bulut API yolu/);
});
it("routes /cloud-api.php requests through Electron IPC bridge in desktop runtime", async () => {
const cloudRequest = vi.fn(async () => ({
ok: true,
status: 200,
bodyText: JSON.stringify({ ok: true, authenticated: true, user: { id: 7, name: "Mimar", email: "[email protected]" } }),
contentType: "application/json; charset=utf-8",
}));
const webFetch = vi.fn();
globalAny.fetch = webFetch as unknown as typeof fetch;
globalAny.window = {
snapcadDesktop: {
isDesktop: true,
getVersion: async () => "1.0.10",
checkForUpdates: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
installUpdate: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
cloudRequest,
} satisfies SnapCadDesktopBridge,
};
const res = await cloudApiFetch("/cloud-api.php?action=session", { cache: "no-store" });
expect(res.ok).toBe(true);
expect(res.status).toBe(200);
expect(cloudRequest).toHaveBeenCalledWith({
path: "/cloud-api.php?action=session",
method: "GET",
headers: undefined,
body: undefined,
});
expect(webFetch).not.toHaveBeenCalled();
const json = (await res.json()) as { ok: boolean; user?: { name: string } };
expect(json.ok).toBe(true);
expect(json.user?.name).toBe("Mimar");
});
it("throws when Electron IPC cloud proxy encounters a transport error (status 0)", async () => {
globalAny.window = {
snapcadDesktop: {
isDesktop: true,
getVersion: async () => "1.0.10",
checkForUpdates: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
installUpdate: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
cloudRequest: async () => ({
ok: false,
status: 0,
bodyText: "",
error: "Ağ bağlantısı kesildi.",
}),
} satisfies SnapCadDesktopBridge,
};
await expect(cloudApiFetch("/cloud-api.php?action=session")).rejects.toThrow("Ağ bağlantısı kesildi.");
});
it("falls back to standard fetch in browser builds", async () => {
const mockResponse = new Response(JSON.stringify({ ok: true, authenticated: false }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
const webFetch = vi.fn(async () => mockResponse);
globalAny.window = {};
globalAny.fetch = webFetch as unknown as typeof fetch;
const res = await cloudApiFetch("/cloud-api.php?action=sync_all", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "sync_all", projects: [] }),
});
expect(webFetch).toHaveBeenCalledTimes(1);
expect(res.ok).toBe(true);
});
});
+200
View File
@@ -0,0 +1,200 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
exportFiltersForFilename,
formatFriendlyUpdateError,
getDesktopBridge,
isAllowedExternalUrl,
isDesktopRuntime,
isEditorOnlyMenuAction,
normalizeCloudApiPath,
parseMenuAction,
sanitizeDesktopTitle,
} from "../../apps/web/src/lib/desktopBridge";
import { SKF_CREATED_WITH_VERSION } from "../../apps/web/src/lib/skfProject";
import { SERVICE_WORKER_VERSION } from "../../apps/web/src/lib/serviceWorker";
import type { DesktopMenuAction, SnapCadDesktopBridge } from "../../apps/web/src/types/desktop";
describe("desktopBridge", () => {
it("sanitizes desktop window titles and formats dirty indicator", () => {
expect(sanitizeDesktopTitle(undefined, false)).toBe("SnapCAD Studio");
expect(sanitizeDesktopTitle("SnapCAD Studio", true)).toBe("* SnapCAD Studio");
expect(sanitizeDesktopTitle("Motor Braketi\n\r\t v2", false)).toBe("Motor Braketi v2 — SnapCAD Studio");
expect(sanitizeDesktopTitle("Motor Braketi", true)).toBe("* Motor Braketi — SnapCAD Studio");
expect(sanitizeDesktopTitle("Bileşen — SnapCAD Studio", false)).toBe("Bileşen — SnapCAD Studio");
expect(sanitizeDesktopTitle("A".repeat(200), false).length).toBeLessThanOrEqual(140);
});
it("validates desktop menu actions against allowlist", () => {
const samples: DesktopMenuAction[] = [
"file:open",
"file:save-as",
"file:export-stl",
"edit:make-component",
"edit:chamfer",
"view:zoom-extents",
"view:toggle-tray",
"view:style-blueprint",
"camera:isometric",
"camera:two-point",
"draw:shape-box",
"draw:sketch-extrude",
"tool:push-pull",
"tool:wall-opening",
"tool:physics-toggle",
"tray:entity-info",
"tray:outliner",
"window:settings",
"window:command-palette",
"window:keymap-classic",
"help:audit",
"help:tutorial",
];
for (const action of samples) {
expect(parseMenuAction(action)).toBe(action);
}
expect(parseMenuAction("file:delete-system32")).toBeNull();
expect(parseMenuAction(42)).toBeNull();
});
it("distinguishes global vs 3D-editor-only menu commands", () => {
expect(isEditorOnlyMenuAction("file:new")).toBe(false);
expect(isEditorOnlyMenuAction("file:open")).toBe(false);
expect(isEditorOnlyMenuAction("file:dashboard")).toBe(false);
expect(isEditorOnlyMenuAction("window:drawing")).toBe(false);
expect(isEditorOnlyMenuAction("window:classrooms")).toBe(false);
expect(isEditorOnlyMenuAction("window:shared")).toBe(false);
expect(isEditorOnlyMenuAction("window:command-palette")).toBe(false);
expect(isEditorOnlyMenuAction("window:a11y")).toBe(false);
expect(isEditorOnlyMenuAction("window:settings")).toBe(false);
expect(isEditorOnlyMenuAction("help:shortcuts")).toBe(false);
expect(isEditorOnlyMenuAction("file:export-stl")).toBe(true);
expect(isEditorOnlyMenuAction("edit:delete")).toBe(true);
expect(isEditorOnlyMenuAction("view:xray")).toBe(true);
expect(isEditorOnlyMenuAction("camera:isometric")).toBe(true);
expect(isEditorOnlyMenuAction("draw:shape-box")).toBe(true);
expect(isEditorOnlyMenuAction("tool:push-pull")).toBe(true);
expect(isEditorOnlyMenuAction("tool:physics-toggle")).toBe(true);
expect(isEditorOnlyMenuAction("tray:outliner")).toBe(true);
expect(isEditorOnlyMenuAction("window:workspace-settings")).toBe(true);
expect(isEditorOnlyMenuAction("help:audit")).toBe(true);
});
it("keeps native Electron menu items in parity with desktopBridge allowlist and renderer handlers", () => {
const repoRoot = path.resolve(__dirname, "../..");
const mainSource = fs.readFileSync(path.join(repoRoot, "apps/desktop/main.cjs"), "utf8");
const pageSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/app/page.tsx"), "utf8");
const editorSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/components/SketchForgeEditor.tsx"), "utf8");
const menuBlockMatch = mainSource.match(/function buildNativeApplicationMenu\(\)[\s\S]*?^function setupDesktopIpc\(\)/m);
expect(menuBlockMatch).not.toBeNull();
const menuBlock = menuBlockMatch![0];
for (const label of ["Dosya", "Düzenle", "Görünüm", "Kamera", "Çizim", "Araçlar", "Pencere", "Stüdyolar", "Yardım"]) {
expect(menuBlock).toContain(`label: "${label}"`);
expect(menuBlock).not.toContain(`label: "&${label}"`);
}
const emittedActions = Array.from(menuBlock.matchAll(/sendMenuCommand\("([^"]+)"\)/g)).map((m) => m[1]);
expect(emittedActions.length).toBeGreaterThanOrEqual(90);
for (const action of emittedActions) {
expect(parseMenuAction(action), `parseMenuAction failed for ${action}`).toBe(action);
const handledInPage = pageSource.includes(`case "${action}":`);
const handledInEditor =
editorSource.includes(`case "${action}":`) ||
action.startsWith("draw:shape-") ||
action.startsWith("tray:");
expect(handledInPage || handledInEditor, `Unhandled native menu action: ${action}`).toBe(true);
}
});
it("normalizes and allowlists only relative SnapCAD cloud API paths", () => {
expect(normalizeCloudApiPath("/cloud-api.php")).toBe("/cloud-api.php");
expect(normalizeCloudApiPath(" /cloud-api.php?action=session ")).toBe("/cloud-api.php?action=session");
expect(normalizeCloudApiPath("https://snap.yakhub.com.tr/cloud-api.php?action=session")).toBeNull();
expect(normalizeCloudApiPath("//evil.example/cloud-api.php")).toBeNull();
expect(normalizeCloudApiPath("/login.php")).toBeNull();
expect(normalizeCloudApiPath("/cloud-api.php.evil")).toBeNull();
expect(normalizeCloudApiPath("")).toBeNull();
});
it("formats updater transport errors into readable Turkish copy", () => {
expect(formatFriendlyUpdateError("")).toBe("Güncelleme denetlenemedi.");
expect(formatFriendlyUpdateError("HttpError: 404 Not Found latest.yml")).toContain("henüz yeni bir masaüstü kurulum paketi yayınlanmadı");
expect(formatFriendlyUpdateError("net::ERR_NETWORK")).toContain("İnternet bağlantınızı kontrol edin");
expect(formatFriendlyUpdateError("Özel sunucu mesajı")).toBe("Özel sunucu mesajı");
});
it("allows only http and https external URLs", () => {
expect(isAllowedExternalUrl("https://snap.yakhub.com.tr")).toBe(true);
expect(isAllowedExternalUrl("http://127.0.0.1:62158")).toBe(true);
expect(isAllowedExternalUrl("file:///C:/Windows/System32/cmd.exe")).toBe(false);
expect(isAllowedExternalUrl("javascript:alert(1)")).toBe(false);
expect(isAllowedExternalUrl("")).toBe(false);
});
it("selects appropriate Electron file filters by extension", () => {
expect(exportFiltersForFilename("parca.stl")[0].extensions).toEqual(["stl"]);
expect(exportFiltersForFilename("govde.STEP")[0].extensions).toEqual(["step", "stp"]);
expect(exportFiltersForFilename("proje.skf")[0].extensions).toEqual(["skf"]);
expect(exportFiltersForFilename("bilinmeyen.bin")[0].extensions).toEqual(["*"]);
});
it("detects web vs injected Electron preload bridges cleanly", () => {
const globalObj = globalThis as unknown as { window?: Partial<Window> };
const prevWindow = globalObj.window;
try {
globalObj.window = undefined;
expect(isDesktopRuntime()).toBe(false);
expect(getDesktopBridge()).toBeNull();
const mockBridge: SnapCadDesktopBridge = {
isDesktop: true,
getVersion: async () => "1.0.10",
checkForUpdates: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
installUpdate: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
};
globalObj.window = { snapcadDesktop: mockBridge };
expect(isDesktopRuntime()).toBe(true);
expect(getDesktopBridge()).toBe(mockBridge);
globalObj.window = { sketchforgeDesktop: mockBridge };
expect(isDesktopRuntime()).toBe(true);
expect(getDesktopBridge()).toBe(mockBridge);
} finally {
globalObj.window = prevWindow as Window | undefined;
}
});
it("keeps app version synchronized across package.json, lockfile, SKF metadata, and SW", () => {
const repoRoot = path.resolve(__dirname, "../..");
const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8")) as { version: string };
const lock = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8")) as {
version: string;
packages: Record<string, { version?: string }>;
};
const swSource = fs.readFileSync(path.join(repoRoot, "apps/web/public/sw.js"), "utf8");
expect(pkg.version).toBe("1.0.10");
expect(lock.version).toBe(pkg.version);
expect(lock.packages[""]?.version).toBe(pkg.version);
expect(SKF_CREATED_WITH_VERSION).toBe(pkg.version);
expect(swSource).toContain(`const CACHE_NAME = "snapcad-v${SERVICE_WORKER_VERSION}"`);
});
});
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { importedShapeFromIfc, importedShapeWithDetailsFromIfc } from "@/lib/ifcImport";
const SAMPLE_IFC4_BOX = [
"ISO-10303-21;",
"HEADER;",
"FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');",
"FILE_NAME('wall_block.ifc','2026-01-01T00:00:00',(''),(''),'SnapCAD','SnapCAD','');",
"FILE_SCHEMA(('IFC4'));",
"ENDSEC;",
"DATA;",
"#1=IFCPERSON($,$,'User',$,$,$,$,$);",
"#2=IFCORGANIZATION($,'SnapCAD',$,$,$);",
"#3=IFCPERSONANDORGANIZATION(#1,#2,$);",
"#4=IFCAPPLICATION(#2,'1.0','SnapCAD','SnapCAD');",
"#5=IFCOWNERHISTORY(#3,#4,$,.NOCHANGE.,$,$,$,0);",
"#6=IFCCARTESIANPOINT((0.,0.,0.));",
"#7=IFCDIRECTION((0.,0.,1.));",
"#8=IFCDIRECTION((1.,0.,0.));",
"#9=IFCAXIS2PLACEMENT3D(#6,#7,#8);",
"#10=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#9,$);",
"#12=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);",
"#13=IFCUNITASSIGNMENT((#12));",
"#14=IFCPROJECT('0001',#5,'Test',$,$,$,$,(#10),#13);",
"#15=IFCLOCALPLACEMENT($,#9);",
"#16=IFCBUILDINGELEMENTPROXY('0002',#5,'WallBlock',$,$,#15,#22,$,$);",
"#17=IFCCARTESIANPOINT((0.,0.));",
"#23=IFCAXIS2PLACEMENT2D(#17,$);",
"#18=IFCRECTANGLEPROFILEDEF(.AREA.,$,#23,200.,100.);",
"#19=IFCAXIS2PLACEMENT3D(#6,#7,#8);",
"#20=IFCEXTRUDEDAREASOLID(#18,#19,#7,50.);",
"#21=IFCSHAPEREPRESENTATION(#10,'Body','SweptSolid',(#20));",
"#22=IFCPRODUCTDEFINITIONSHAPE($,$,(#21));",
"ENDSEC;",
"END-ISO-10303-21;",
].join("\n");
describe("IFC BIM Importer via web-ifc WASM", () => {
it("rejects non-IFC arbitrary buffers cleanly before invoking WASM", async () => {
const garbage = new TextEncoder().encode("NOT AN IFC MODEL\n");
await expect(importedShapeFromIfc("bad.ifc", garbage)).rejects.toThrow(/IFC/i);
});
it("extracts extruded solid from IFC4 STEP text with exact millimeter dimensions", async () => {
const bytes = new TextEncoder().encode(SAMPLE_IFC4_BOX);
const details = await importedShapeWithDetailsFromIfc("wall_block.ifc", bytes);
expect(details.schema).toBe("IFC4");
expect(details.productCount).toBeGreaterThanOrEqual(1);
expect(details.triangleCount).toBeGreaterThanOrEqual(12);
expect(details.shape.importedMesh?.sourceFormat).toBe("ifc");
// 200 x 100 x 50 mm extruded solid (axes depend on Z->Y orientation, dimensions exact)
const dims = [details.shape.width, details.shape.height, details.shape.depth].sort((a, b) => a - b);
expect(dims[0]).toBeCloseTo(50, 0);
expect(dims[1]).toBeCloseTo(100, 0);
expect(dims[2]).toBeCloseTo(200, 0);
});
});
+19
View File
@@ -1,3 +1,5 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { appendEditorHistorySnapshot, editorHistoryEntry } from "@/lib/editorHistory";
import { createKeyboardMovementInteraction, moveShapesByKeyboard, type KeyboardMovementEvent } from "@/lib/keyboardMovement";
@@ -150,4 +152,21 @@ describe("keyboard movement interactions", () => {
const raised = moveShapesByKeyboard(nudged, ["box"], key("ArrowUp", { ctrlKey: true }), plane);
expect(raised[0]).toMatchObject({ x: 0, z: 1, elevation: 5 });
});
it("supports macOS Option (event.code) and Cmd modifier guards on global/viewport/studio shortcuts", () => {
const webSrc = path.resolve(__dirname, "../../apps/web/src");
const a11ySrc = fs.readFileSync(path.join(webSrc, "components/snapcad/AccessibilityCenter.tsx"), "utf8");
const viewportSrc = fs.readFileSync(path.join(webSrc, "components/WorkplaneViewport.tsx"), "utf8");
const circuitsSrc = fs.readFileSync(path.join(webSrc, "components/snapcad/CircuitsStudio.tsx"), "utf8");
const drawingSrc = fs.readFileSync(path.join(webSrc, "components/snapcad/TechnicalDrawingStudio.tsx"), "utf8");
expect(a11ySrc).toContain('event.code === "KeyK"');
expect(a11ySrc).toContain('event.code === "KeyA"');
expect(viewportSrc).toContain('!event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey && (event.code === "KeyZ"');
expect(viewportSrc).toContain('event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyZ"');
expect(viewportSrc).toContain('event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyP"');
expect(circuitsSrc).toContain('!e.ctrlKey && !e.metaKey && !e.altKey && (e.key === "r" || e.key === "R")');
expect(circuitsSrc).toContain('(e.ctrlKey || e.metaKey) && !e.shiftKey && (e.code === "KeyZ"');
expect(drawingSrc).toContain('!shortcut && !e.altKey && (key === "?" || key === "h" || e.code === "KeyH")');
});
});
+89
View File
@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import * as THREE from "three";
import {
cleanTriangleSoup,
computeSignedVolumeFromPositions,
isTriangleSoupWatertightClosed,
normalizeClosedMeshWinding,
sanitizeBufferGeometry,
} from "@/lib/meshSanitizer";
function makeBoxTriangleSoup(width: number, height: number, depth: number, invertWinding = false): number[] {
const geom = new THREE.BoxGeometry(width, height, depth);
const nonIndexed = geom.index ? geom.toNonIndexed() : geom;
const pos = nonIndexed.getAttribute("position");
const out: number[] = [];
for (let i = 0; i + 2 < pos.count; i += 3) {
const order = invertWinding ? [i, i + 2, i + 1] : [i, i + 1, i + 2];
for (const idx of order) {
out.push(pos.getX(idx), pos.getY(idx), pos.getZ(idx));
}
}
geom.dispose();
if (nonIndexed !== geom) nonIndexed.dispose();
return out;
}
describe("Mesh Sanitizer (NassCAD Data Integrity)", () => {
it("drops zero-area degenerate triangles and NaN coordinates cleanly", () => {
const validTri = [0, 0, 0, 10, 0, 0, 0, 10, 0];
const zeroAreaTri = [1, 1, 0, 2, 1, 0, 3, 1, 0]; // collinear
const repeatedVertexTri = [5, 5, 5, 5, 5, 5, 10, 5, 5];
const nanTri = [0, 0, 0, Number.NaN, 1, 0, 1, 1, 0];
const res = cleanTriangleSoup([
...validTri,
...zeroAreaTri,
...repeatedVertexTri,
...nanTri,
]);
expect(res.droppedTriangles).toBe(3);
expect(res.triangleCount).toBe(1);
expect(res.positions).toEqual(validTri);
});
it("detects closed watertight box and restores inverted closed winding", () => {
const outwardBox = makeBoxTriangleSoup(20, 10, 30, false);
const invertedBox = makeBoxTriangleSoup(20, 10, 30, true);
expect(isTriangleSoupWatertightClosed(outwardBox)).toBe(true);
expect(computeSignedVolumeFromPositions(outwardBox)).toBeCloseTo(6000, 1);
expect(computeSignedVolumeFromPositions(invertedBox)).toBeCloseTo(-6000, 1);
const fixed = normalizeClosedMeshWinding(invertedBox);
expect(fixed.closed).toBe(true);
expect(fixed.wasFlipped).toBe(true);
expect(fixed.signedVolume).toBeCloseTo(6000, 1);
expect(computeSignedVolumeFromPositions(fixed.positions)).toBeCloseTo(6000, 1);
});
it("sanitizes indexed THREE.BufferGeometry while updating material groups accurately", () => {
const geom = new THREE.BufferGeometry();
geom.setAttribute(
"position",
new THREE.Float32BufferAttribute(
[
0, 0, 0,
10, 0, 0,
0, 10, 0,
5, 5, 0, // degenerate duplicate triangle indices will reference this
],
3,
),
);
geom.setIndex([
0, 1, 2, // group 0: valid
0, 0, 1, // group 0: degenerate
0, 2, 1, // group 1: valid
]);
geom.addGroup(0, 6, 0);
geom.addGroup(6, 3, 1);
sanitizeBufferGeometry(geom);
expect(geom.getIndex()?.count).toBe(6);
expect(geom.groups[0]).toEqual({ start: 0, count: 3, materialIndex: 0 });
expect(geom.groups[1]).toEqual({ start: 3, count: 3, materialIndex: 1 });
geom.dispose();
});
});
+23
View File
@@ -71,4 +71,27 @@ describe("Offset Tool Kernel (Ofset Aracı & Duvar Kalınlığı)", () => {
expect(walledProfile.points.length).toBe(8); // 4 outer + 4 inner wall points
expect(walledProfile.segments.length).toBe(8); // 4 outer + 4 inner segments
});
it("handles concave L-shaped polygon inset cleanly without inverted bowties (Clipper2)", () => {
const lShape: Point2D[] = [
{ x: 0, z: 0 },
{ x: 100, z: 0 },
{ x: 100, z: 30 },
{ x: 40, z: 30 },
{ x: 40, z: 100 },
{ x: 0, z: 100 },
];
const inset = offsetPolygon(lShape, -5);
expect(inset.length).toBeGreaterThanOrEqual(6);
expect(Math.abs(polygonSignedArea(inset))).toBeLessThan(Math.abs(polygonSignedArea(lShape)));
// Collapsing a narrow 20x20 square inward by -15mm returns empty cleanly
const small: Point2D[] = [
{ x: 0, z: 0 },
{ x: 20, z: 0 },
{ x: 20, z: 20 },
{ x: 0, z: 20 },
];
expect(offsetPolygon(small, -15)).toEqual([]);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vitest";
import {
solveSketchConstraints,
autoConstrainAndSolveSnapCadProfile,
} from "@/lib/planegcsSolver";
import type { SketchProfile } from "@/types/sketchforge";
describe("FreeCAD PlaneGCS WASM 2D Constraint Solver", () => {
it("solves a constrained 3-4-5 right triangle from imprecise initial points", async () => {
const result = await solveSketchConstraints({
points: [
{ id: "p0", x: 0, y: 0, fixed: true },
{ id: "p1", x: 35, y: 2 },
{ id: "p2", x: 2, y: 45 },
],
lines: [
{ id: "l01", p1Id: "p0", p2Id: "p1" },
{ id: "l02", p1Id: "p0", p2Id: "p2" },
{ id: "l12", p1Id: "p1", p2Id: "p2" },
],
constraints: [
{ id: "c1", type: "horizontal", lineId: "l01" },
{ id: "c2", type: "vertical", lineId: "l02" },
{ id: "c3", type: "distance", p1Id: "p0", p2Id: "p1", distance: 30 },
{ id: "c4", type: "distance", p1Id: "p1", p2Id: "p2", distance: 50 },
],
});
expect(result.solved).toBe(true);
expect(result.dof).toBe(0);
const p1 = result.points.find((p) => p.id === "p1")!;
const p2 = result.points.find((p) => p.id === "p2")!;
expect(p1.x).toBeCloseTo(30, 3);
expect(p1.y).toBeCloseTo(0, 3);
expect(p2.x).toBeCloseTo(0, 3);
expect(p2.y).toBeCloseTo(40, 3);
});
it("solves a line tangent to a fixed-radius circle", async () => {
const result = await solveSketchConstraints({
points: [
{ id: "c_center", x: 50, y: 50, fixed: true },
{ id: "p_a", x: 0, y: 72, fixed: true },
{ id: "p_b", x: 100, y: 80 },
],
lines: [{ id: "l_ab", p1Id: "p_a", p2Id: "p_b" }],
circles: [{ id: "circle1", centerId: "c_center", radius: 20 }],
constraints: [
{ id: "c_rad", type: "circle_radius", circleId: "circle1", radius: 20 },
{ id: "c_tan", type: "tangent_lc", lineId: "l_ab", circleId: "circle1" },
],
});
expect(result.solved).toBe(true);
const pa = result.points.find((p) => p.id === "p_a")!;
const pb = result.points.find((p) => p.id === "p_b")!;
const dist =
Math.abs((pb.y - pa.y) * 50 - (pb.x - pa.x) * 50 + pb.x * pa.y - pb.y * pa.x) /
Math.hypot(pb.y - pa.y, pb.x - pa.x);
expect(dist).toBeCloseTo(20, 2);
});
it("auto-constrains nearly orthogonal SnapCAD sketch profiles to exact axis alignment", async () => {
const skewedRect: SketchProfile = {
points: [
{ id: "p1", x: 0, z: 0 },
{ id: "p2", x: 100, z: 2.5 },
{ id: "p3", x: 98, z: 51 },
{ id: "p4", x: -1.5, z: 49 },
],
segments: [
{ id: "s1", startId: "p1", endId: "p2", kind: "line" },
{ id: "s2", startId: "p2", endId: "p3", kind: "line" },
{ id: "s3", startId: "p3", endId: "p4", kind: "line" },
{ id: "s4", startId: "p4", endId: "p1", kind: "line" },
],
};
const solved = await autoConstrainAndSolveSnapCadProfile(skewedRect);
expect(solved.solved).toBe(true);
expect(solved.appliedConstraintsCount).toBe(4);
expect(solved.changedPointsCount).toBeGreaterThanOrEqual(2);
const p = new Map(solved.profile.points.map((pt) => [pt.id, pt]));
expect(p.get("p2")!.z).toBeCloseTo(p.get("p1")!.z, 1);
expect(p.get("p3")!.x).toBeCloseTo(p.get("p2")!.x, 1);
expect(p.get("p4")!.z).toBeCloseTo(p.get("p3")!.z, 1);
expect(p.get("p4")!.x).toBeCloseTo(p.get("p1")!.x, 1);
});
});
+138
View File
@@ -0,0 +1,138 @@
import { describe, expect, it } from "vitest";
import * as THREE from "three";
import { PlanarIntersectionGenerator, ProjectionGenerator } from "@/lib/projection";
import {
computeModelProjectionAsync,
computeModelProjectionSync,
generateSectionHatchSegments,
mapProjectionSegmentsToSheet,
} from "@/lib/technicalProjectionBridge";
import type { WorkplaneShape } from "@/types/sketchforge";
function makeBox(id: string, x: number, y: number, z: number, w: number, h: number, d: number, hole = false): WorkplaneShape {
return {
id,
name: id,
kind: "box",
color: hole ? "#ef4444" : "#0ea5e9",
hole,
x,
z,
elevation: y,
size: Math.max(w, d),
width: w,
depth: d,
height: h,
rotation: 0,
};
}
function makeCylinder(id: string, x: number, y: number, z: number, dia: number, h: number, hole = false): WorkplaneShape {
return {
id,
name: id,
kind: "cylinder",
color: hole ? "#ef4444" : "#0ea5e9",
hole,
x,
z,
elevation: y,
size: dia,
width: dia,
depth: dia,
height: h,
rotation: 0,
sides: 28,
};
}
describe("Stage C — three-edge-projection HLR & Section Cut", () => {
it("separates visible front faces from occluded rear edges with ProjectionGenerator", () => {
const group = new THREE.Group();
const frontMat = new THREE.MeshBasicMaterial();
const upperBox = new THREE.Mesh(new THREE.BoxGeometry(20, 4, 30), frontMat);
upperBox.position.set(0, 10, 0);
const lowerWideBox = new THREE.Mesh(new THREE.BoxGeometry(60, 4, 20), frontMat);
lowerWideBox.position.set(0, 0, 0);
group.add(upperBox, lowerWideBox);
group.updateMatrixWorld(true);
const projector = new ProjectionGenerator();
projector.angleThreshold = 28;
const result = projector.generateSync(group);
const visibleSegs = result.visibleEdges.getAllSegments();
const hiddenSegs = result.hiddenEdges.getAllSegments();
expect(visibleSegs.length).toBeGreaterThan(4);
// Parts of the wider lower box underneath x in [-10, 10] must be classified as hidden
expect(hiddenSegs.length).toBeGreaterThan(0);
upperBox.geometry.dispose();
lowerWideBox.geometry.dispose();
frontMat.dispose();
});
it("extracts closed cross-section edges with PlanarIntersectionGenerator", () => {
const box = new THREE.BoxGeometry(40, 20, 30);
const slicer = new PlanarIntersectionGenerator();
slicer.plane.set(new THREE.Vector3(0, 1, 0), 0);
const cutLines = slicer.generate(box);
const pos = cutLines.getAttribute("position");
expect(pos.count).toBeGreaterThanOrEqual(8);
cutLines.dispose();
box.dispose();
});
it("projects stepped flange with through-hole into ISO views and A-A hatched section", () => {
const flangeAssembly: WorkplaneShape[] = [
makeCylinder("base-flange", 0, 0, 0, 100, 12, false),
makeCylinder("boss-neck", 0, 12, 0, 46, 26, false),
makeCylinder("center-bore", 0, 0, 0, 24, 38, true),
];
const sectionProj = computeModelProjectionSync(flangeAssembly, { sectionAAEnabled: true, radialSegments: 24 });
expect(sectionProj.csgApplied).toBe(true);
expect(sectionProj.triangleCount).toBeGreaterThan(20);
expect(sectionProj.views.front.visible.length).toBeGreaterThan(4);
expect(sectionProj.views.front.sectionCut.length).toBeGreaterThan(6);
expect(sectionProj.views.top.visible.length).toBeGreaterThan(20);
expect(sectionProj.views.side.visible.length).toBeGreaterThan(4);
expect(sectionProj.views.isometric.visible.length).toBeGreaterThan(10);
// Check A-A section hatch lines stay outside the central Ø24 bore (x in [-12, 12])
const sheetSectionPrims = mapProjectionSegmentsToSheet(
sectionProj.views.front,
{ x: 0, y: 0 },
1,
{ includeHidden: false, includeSectionHatch: true },
);
const hatchPrims = sheetSectionPrims.filter((p) => p.layer === "HATCH");
expect(hatchPrims.length).toBeGreaterThan(4);
// Every hatch segment must sit cleanly in the solid steel walls (|x| >= 11.5) and never span across x=0 bore
for (const h of hatchPrims) {
const crossesZero = (h.x < -2 && (h.x2 ?? h.x) > 2) || ((h.x2 ?? h.x) < -2 && h.x > 2);
expect(crossesZero).toBe(false);
}
// Without section A-A, the internal Ø24 bore appears in front view hidden edges
const unsectionedProj = computeModelProjectionSync(flangeAssembly, { sectionAAEnabled: false, radialSegments: 24 });
expect(unsectionedProj.views.front.hidden.length).toBeGreaterThan(0);
});
it("supports async HLR projection and L-bracket with mounting holes", async () => {
const lBracket: WorkplaneShape[] = [
makeBox("base", 0, 0, 0, 100, 12, 60, false),
makeBox("wall", -42, 12, 0, 16, 40, 60, false),
makeCylinder("hole1", 25, 0, 15, 12, 12, true),
];
const proj = await computeModelProjectionAsync(lBracket, { sectionAAEnabled: true, radialSegments: 20 });
expect(proj.views.top.visible.length).toBeGreaterThan(8);
expect(proj.views.front.sectionCut.length).toBeGreaterThan(3);
const directHatch = generateSectionHatchSegments(proj.views.front.sectionCut, 6);
expect(directHatch.length).toBeGreaterThan(2);
});
});