feat: improve shape tools and project previews

This commit is contained in:
Formsmith746
2026-08-28 13:24:32 +03:00
parent 2486b998c8
commit 34528e6393
33 changed files with 2071 additions and 343 deletions
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import {
projectThumbnailDimensions,
projectThumbnailSceneChanged,
} from "@/lib/projectThumbnail";
describe("project thumbnails", () => {
it("reduces a high-DPI editor canvas to the thumbnail bounds", () => {
expect(projectThumbnailDimensions(2048, 992)).toEqual({ width: 512, height: 248 });
expect(projectThumbnailDimensions(800, 1200)).toEqual({ width: 213, height: 320 });
expect(projectThumbnailDimensions(320, 180)).toEqual({ width: 320, height: 180 });
});
it("captures only changed scenes within the same project", () => {
const original = { projectId: "project-1", fingerprint: "scene-a" };
expect(projectThumbnailSceneChanged(null, original)).toBe(false);
expect(projectThumbnailSceneChanged(original, original)).toBe(false);
expect(projectThumbnailSceneChanged(original, { ...original, fingerprint: "scene-b" })).toBe(true);
expect(projectThumbnailSceneChanged(original, { projectId: "project-2", fingerprint: "scene-b" })).toBe(false);
});
});
+31
View File
@@ -54,6 +54,37 @@ describe("shape catalog", () => {
});
});
it("applies only explicitly customized creation dimensions", () => {
const asset: ShapeAsset = { id: "cone", name: "Cone", src: "cone.png", kind: "cone", color: "#6e2786" };
const appDefault = makeShapeFromAsset(asset);
const customized = makeShapeFromAsset(asset, undefined, { width: 320, depth: 240, height: 180 });
expect(appDefault).toMatchObject({ width: 20, depth: 20, height: 20, baseRadius: 10 });
expect(customized).toMatchObject({ width: 320, depth: 240, height: 180, size: 320, baseRadius: 160 });
});
it("applies shape-specific creation defaults only when customized", () => {
const cone = makeShapeFromAsset(
{ id: "cone", name: "Cone", src: "cone.png", kind: "cone", color: "#6e2786" },
undefined,
{ topRadius: 3, baseRadius: 18, sides: 48 },
);
const text = makeShapeFromAsset(
{ id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" },
undefined,
{ text: "HELLO", font: "Serif", bevel: 2, segments: 6 },
);
const gear = makeShapeFromAsset(
{ id: "gear", name: "Gear", src: "gear.svg", kind: "gear", color: "#6f7f8d" },
undefined,
{ gearType: "helical", teeth: 24, toothSize: 3, toothWidth: 2, centerHoleSize: 10, helixAngle: 30, helixQuality: 24 },
);
expect(cone).toMatchObject({ topRadius: 3, baseRadius: 18, sides: 48 });
expect(text).toMatchObject({ text: "HELLO", font: "Serif", bevel: 2, segments: 6 });
expect(gear).toMatchObject({ gearType: "helical", teeth: 24, toothSize: 3, toothWidth: 2, centerHoleSize: 10, helixAngle: 30, helixQuality: 24 });
});
it("creates canonical scene shapes with stable defaults", () => {
const created = sceneShape({
name: "Part",
+23 -21
View File
@@ -41,35 +41,38 @@ describe("sketch revolve", () => {
expect(Math.min(...mesh.positions.filter((_value, index) => index % 3 === 1))).toBeCloseTo(0, 6);
});
it("creates thickness automatically for an open profile", () => {
it("requires a closed profile", () => {
const profile: SketchProfile = {
points: [{ id: "a", x: -8, z: 0 }, { id: "b", x: -8, z: 20 }],
segments: [{ id: "ab", startId: "a", endId: "b", kind: "line" }],
};
const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 2 });
expect(polygons).toHaveLength(1);
expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(7, 6);
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeCloseTo(9, 6);
const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 2, sides: 24 });
expect(mesh.triangleCount).toBeGreaterThan(0);
expect(mesh.width).toBeCloseTo(18, 4);
expect(mesh.height).toBeCloseTo(20, 4);
expect(sketchProfileToRevolvePolygons(profile)).toEqual([]);
expect(() => buildSketchRevolveMesh(runtime, profile, { sides: 24 })).toThrow("Draw at least one closed profile");
});
it("allows construction points across the axis but only revolves the working-side segment", () => {
it("clips a closed profile at the revolve axis", () => {
const profile: SketchProfile = {
points: [{ id: "construction", x: 10, z: 0 }, { id: "profile", x: -10, z: 20 }],
segments: [{ id: "crossing", startId: "construction", endId: "profile", kind: "line" }],
points: [
{ id: "top-right", x: 10, z: 0 },
{ id: "top-left", x: -10, z: 0 },
{ id: "bottom-left", x: -10, z: 20 },
{ id: "bottom-right", x: 10, z: 20 },
],
segments: [
{ id: "top", startId: "top-right", endId: "top-left", kind: "line" },
{ id: "left", startId: "top-left", endId: "bottom-left", kind: "line" },
{ id: "bottom", startId: "bottom-left", endId: "bottom-right", kind: "line" },
{ id: "right", startId: "bottom-right", endId: "top-right", kind: "line" },
],
};
const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 1 });
const polygons = sketchProfileToRevolvePolygons(profile);
expect(polygons).toHaveLength(1);
expect(Math.max(...polygons[0].map((point) => point[1]))).toBeLessThan(11);
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeGreaterThan(10);
expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(0, 6);
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeCloseTo(10, 6);
const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 1, sides: 24 });
const mesh = buildSketchRevolveMesh(runtime, profile, { sides: 24 });
expect(mesh.triangleCount).toBeGreaterThan(0);
expect(mesh.height).toBeGreaterThan(9);
expect(mesh.height).toBeLessThan(11);
expect(mesh.height).toBeCloseTo(20, 4);
});
it("supports partial and reverse sweeps", () => {
@@ -82,12 +85,11 @@ describe("sketch revolve", () => {
});
it("normalizes unsafe revolve settings", () => {
expect(normalizeSketchRevolveSettings({ startAngle: -30, sweepAngle: 0, sides: 500, quality: 0, thickness: -2 })).toEqual({
expect(normalizeSketchRevolveSettings({ startAngle: -30, sweepAngle: 0, sides: 900, quality: 0 })).toEqual({
startAngle: 330,
sweepAngle: 1,
sides: 128,
sides: 512,
quality: 1,
thickness: 0.1,
});
});
});
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { rotateSketchPoints, selectedClosedSketchPoints } from "@/lib/sketchRotation";
import type { SketchProfile } from "@/types/sketchforge";
const rectangle: SketchProfile = {
points: [
{ id: "a", x: 0, z: 0, handleOut: { x: 1, z: 0 } },
{ id: "b", x: 4, z: 0 },
{ id: "c", x: 4, z: 2 },
{ id: "d", x: 0, z: 2 },
],
segments: [
{ id: "ab", startId: "a", endId: "b" },
{ id: "bc", startId: "b", endId: "c" },
{ id: "cd", startId: "c", endId: "d" },
{ id: "da", startId: "d", endId: "a" },
],
};
describe("sketch rotation", () => {
it("recognizes a complete closed sketch selection", () => {
const points = selectedClosedSketchPoints(rectangle, {
pointIds: ["a", "b", "c", "d"],
segmentIds: ["ab", "bc", "cd", "da"],
});
expect(points?.map((point) => point.id)).toEqual(["a", "b", "c", "d"]);
});
it("rejects an open, partial, or image-inclusive selection", () => {
expect(selectedClosedSketchPoints(rectangle, {
pointIds: ["a", "b", "c", "d"],
segmentIds: ["ab", "bc", "cd"],
})).toBeNull();
expect(selectedClosedSketchPoints(rectangle, {
pointIds: ["a", "b", "c", "d"],
segmentIds: ["ab", "bc", "cd", "da"],
imageIds: ["reference-image"],
})).toBeNull();
});
it("rotates points and bezier handles around the selection bounds center", () => {
const rotated = rotateSketchPoints(rectangle.points, 90);
const first = rotated.find((point) => point.id === "a");
expect(first?.x).toBeCloseTo(3, 8);
expect(first?.z).toBeCloseTo(-1, 8);
expect(first?.handleOut?.x).toBeCloseTo(3, 8);
expect(first?.handleOut?.z).toBeCloseTo(0, 8);
});
});
+67
View File
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
completeSketchForgeMcpCommand,
dispatchSketchForgeMcpCommand,
pollSketchForgeMcpCommand,
registerSketchForgeMcpEditor,
waitForSketchForgeMcpCommand,
} from "@/lib/sketchforgeMcpStore";
const editor = {
editorId: "editor-test",
editorNumber: 12345,
projectId: "project-test",
projectName: "MCP test",
url: "http://localhost:3000/?editor=1",
focused: true,
shapeCount: 0,
selectedCount: 0,
notice: "",
lastError: null,
};
beforeEach(() => {
delete (globalThis as { __sketchforgeMcpStore?: unknown }).__sketchforgeMcpStore;
registerSketchForgeMcpEditor(editor);
});
describe("SketchForge MCP long polling", () => {
it("delivers a command directly to a waiting editor", async () => {
const poll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "list_objects" });
const command = await poll;
expect(command).toMatchObject({ action: "list_objects", params: {} });
expect(pollSketchForgeMcpCommand(editor.editorId)).toBeNull();
completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true, data: [] });
await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true, data: [] });
});
it("allows only one pending poll per editor", async () => {
const firstPoll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
const secondPoll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
await expect(firstPoll).resolves.toBeNull();
const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "inspect_errors" });
const command = await secondPoll;
expect(command?.action).toBe("inspect_errors");
completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true });
await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true });
});
it("removes an aborted poll before queueing the next command", async () => {
const controller = new AbortController();
const poll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000, signal: controller.signal });
controller.abort();
await expect(poll).resolves.toBeNull();
const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "get_scene" });
const command = pollSketchForgeMcpCommand(editor.editorId);
expect(command?.action).toBe("get_scene");
completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true });
await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true });
});
});
+4 -1
View File
@@ -153,7 +153,7 @@ describe("SketchForge .skf project packages", () => {
const revolve = shape("mesh", "revolve-sketch", {
name: "Sketch revolve",
sketchOperation: "revolve",
sketchRevolve: { startAngle: 25, sweepAngle: -220, sides: 48, quality: 8, thickness: 1.5 },
sketchRevolve: { startAngle: 25, sweepAngle: -220, sides: 48, quality: 8 },
sketchProfile: {
points: [{ id: "p1", x: -4, z: 0 }, { id: "p2", x: -8, z: 0 }, { id: "p3", x: -8, z: 16 }, { id: "p4", x: -4, z: 16 }],
segments: [
@@ -402,6 +402,8 @@ describe("SketchForge .skf project packages", () => {
z: 0,
width: 10,
depth: 10,
lockAspect: true,
locked: true,
}],
},
});
@@ -412,6 +414,7 @@ describe("SketchForge .skf project packages", () => {
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);
expect(restored.shapes[0].sketchProfile?.images?.[0].locked).toBe(true);
});
it("deduplicates derived geometry when legacy imported objects share one mesh", async () => {
+71 -1
View File
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
import { normalizedRotationPlaneBasis } from "@/components/workplane/transformOverlayTypes";
import {
continuousSnappedWheelRotation,
normalizedRotationPlaneBasis,
rotationWheelDirectionSign,
snappedRotationDelta,
snappedWheelRotation,
} from "@/components/workplane/transformOverlayTypes";
describe("rotation handle projection", () => {
it("preserves face-plane foreshortening while normalizing icon size", () => {
@@ -28,4 +34,68 @@ describe("rotation handle projection", () => {
d: 1,
});
});
it("moves 45-degree rotation in the same screen direction as 22.5-degree rotation", () => {
const direction = rotationWheelDirectionSign(1);
expect(snappedWheelRotation(-52, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 });
expect(snappedWheelRotation(-58, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 });
expect(snappedWheelRotation(-69, -80, direction)).toEqual({ delta: 0, pointerAngle: -90 });
});
it("switches the wheel rotation and orange indicator to 22.5-degree marks with Shift", () => {
const direction = rotationWheelDirectionSign(1);
expect(snappedWheelRotation(-58, -80, direction, 22.5)).toEqual({ delta: -22.5, pointerAngle: -67.5 });
expect(snappedWheelRotation(-52, -80, direction, 22.5)).toEqual({ delta: -45, pointerAngle: -45 });
});
it("keeps the current result continuous when switching to 22.5-degree snapping", () => {
const direction = rotationWheelDirectionSign(1);
const coarse = snappedWheelRotation(-58, -80, direction);
const fineAtShift = continuousSnappedWheelRotation(
snappedWheelRotation(-58, -80, direction, 22.5),
22.5,
45,
coarse.delta,
coarse.pointerAngle,
);
expect(fineAtShift).toEqual({
delta: -45,
pointerAngle: -45,
deltaOffset: -22.5,
pointerOffset: 22.5,
});
const fineForward = continuousSnappedWheelRotation(
snappedWheelRotation(-52, -80, direction, 22.5),
22.5,
22.5,
fineAtShift.delta,
fineAtShift.pointerAngle,
fineAtShift.deltaOffset,
fineAtShift.pointerOffset,
);
expect(fineForward).toEqual({
delta: -67.5,
pointerAngle: -22.5,
deltaOffset: -22.5,
pointerOffset: 22.5,
});
});
it("keeps one-degree rotation outside the wheel", () => {
expect(snappedRotationDelta(28.4, false, false)).toBe(28);
});
it("retains the Shift 45-degree shortcut outside the wheel", () => {
expect(snappedRotationDelta(28, false, true)).toBe(45);
});
it("keeps absolute wheel snapping synchronized when screen rotation is inverted", () => {
expect(snappedWheelRotation(-134, -80, -1)).toEqual({ delta: 45, pointerAngle: -135 });
});
it("wraps wheel deltas across the -180/180 boundary", () => {
expect(snappedWheelRotation(-179, 179)).toEqual({ delta: 0, pointerAngle: -180 });
expect(snappedWheelRotation(-134, 179)).toEqual({ delta: 45, pointerAngle: -135 });
});
});
+38 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits } from "@/lib/measurementUnits";
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, shapeDimensionLimit, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
describe("workplane settings helpers", () => {
it("accepts known snap grid values and falls back for unknown values", () => {
@@ -63,6 +63,43 @@ describe("workplane settings helpers", () => {
expect(normalizeWorkspaceSettings({ gridColor: "not-a-color" }).gridColor).toBe(DEFAULT_WORKPLANE_WORKSPACE.gridColor);
});
it("keeps app limits until a shape receives an explicit customization", () => {
const untouched = normalizeWorkspaceSettings({});
const customized = normalizeWorkspaceSettings({
shapeCustomizations: {
box: { width: 48, maxDimension: 720 },
sphere: { height: Number.NaN, maxDimension: 9000 },
},
});
expect(untouched.shapeCustomizations).toEqual({});
expect(shapeDimensionLimit(untouched, "box", 160)).toBe(160);
expect(customized.shapeCustomizations.box).toEqual({ width: 48, maxDimension: 720 });
expect(customized.shapeCustomizations.sphere).toEqual({ maxDimension: 2000 });
expect(shapeDimensionLimit(customized, "box", 160)).toBe(720);
expect(shapeDimensionLimit(customized, "cylinder", 220)).toBe(220);
});
it("normalizes supported special-shape defaults", () => {
const customized = normalizeWorkspaceSettings({
shapeCustomizations: {
cylinder: { sides: 500 },
roundRoof: { sides: 900 },
sphere: { steps: 2 },
cone: { topRadius: -4, baseRadius: 9000, sides: 40 },
text: { text: "A custom label that is much too long", font: "Serif", bevel: 12, segments: 9.6 },
gear: { gearType: "helical", teeth: 23.7, toothSize: 3, centerHoleSize: -5, helixAngle: 90, helixQuality: 3 },
},
});
expect(customized.shapeCustomizations.cylinder).toEqual({ sides: 500 });
expect(customized.shapeCustomizations.roundRoof).toEqual({ sides: 512 });
expect(customized.shapeCustomizations.sphere).toEqual({ steps: 6 });
expect(customized.shapeCustomizations.cone).toEqual({ topRadius: 0, baseRadius: 1000, sides: 40 });
expect(customized.shapeCustomizations.text).toEqual({ text: "A custom label that is m", font: "Serif", bevel: 8, segments: 10 });
expect(customized.shapeCustomizations.gear).toEqual({ gearType: "helical", teeth: 24, toothSize: 3, centerHoleSize: 0, helixAngle: 45, helixQuality: 4 });
});
it("can require selection before a shape starts moving", () => {
expect(canBeginShapeDrag(false, false)).toBe(true);
expect(canBeginShapeDrag(true, false)).toBe(false);
+24
View File
@@ -19,6 +19,7 @@ import {
shapeDepth,
shapeHasTaper,
shapeOverallFootprintDimensions,
shapeTransformShouldRemainEditable,
shapeTaperDimensions,
shapeTaperScaleAt,
shapeWidth,
@@ -129,6 +130,29 @@ describe("workplane shape helpers", () => {
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined();
});
it("keeps rotated groups editable so they can still be ungrouped", () => {
const child = shape({ id: "child" });
const group = shape({
id: "group",
kind: "mesh",
rotation: 45,
groupedBaseWidth: 20,
groupedBaseDepth: 20,
groupedBaseHeight: 20,
groupedShapes: [child],
});
expect(shapeTransformShouldRemainEditable(group)).toBe(true);
expect(shapeTransformShouldRemainEditable(shape({ rotation: 45 }))).toBe(false);
expect(canonicalizeShape(group)).toMatchObject({
rotation: 45,
groupedBaseWidth: 20,
groupedBaseDepth: 20,
groupedBaseHeight: 20,
groupedShapes: [{ id: "child" }],
});
});
it("assigns fresh object IDs throughout duplicated group trees", () => {
const original = shape({
id: "outer-group",