Add workspace editor tools

This commit is contained in:
Formsmith
2026-06-14 22:08:55 +03:00
parent 9a889fdcb7
commit 753a1c2833
29 changed files with 2849 additions and 1397 deletions
+14
View File
@@ -0,0 +1,14 @@
let fallbackIdCounter = 0;
export function createLocalId(prefix: string) {
const uuid = globalThis.crypto?.randomUUID?.();
if (uuid) {
return `${prefix}-${uuid}`;
}
fallbackIdCounter = (fallbackIdCounter + 1) % Number.MAX_SAFE_INTEGER;
const timestamp = Date.now().toString(36);
const counter = fallbackIdCounter.toString(36);
const random = Math.random().toString(36).slice(2, 10);
return `${prefix}-${timestamp}-${counter}-${random}`;
}
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import type { ShapeAsset } from "@/types/sketchforge";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets } from "./shapeCatalog";
describe("shape catalog", () => {
it("does not expose removed decorative shapes in the toolbar catalog", () => {
const kinds = toolbarShapeAssets.map((asset) => asset.kind);
expect(kinds).not.toContain("star");
expect(kinds).not.toContain("heart");
});
it("creates placed shapes from toolbar assets", () => {
const asset: ShapeAsset = { id: "box", name: "Box", src: "box.png", kind: "box", color: "#d41721" };
const placed = makeShapeFromAsset(asset, { x: 12, z: -8, elevation: 4 });
expect(placed.id).toMatch(/^box-/);
expect(placed).toMatchObject({
name: "Box",
kind: "box",
color: "#d41721",
x: 12,
z: -8,
elevation: 4,
size: 20,
width: 20,
depth: 20,
height: 20,
radius: 0,
steps: 10,
locked: false,
hidden: false,
});
});
it("uses shape-specific defaults for text and round profiles", () => {
const text = makeShapeFromAsset({ id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" });
const torus = makeShapeFromAsset({ id: "torus", name: "Torus", src: "torus.png", kind: "torus", color: "#0098c7" });
expect(text).toMatchObject({ width: 86, depth: 28, height: 10, text: "TEXT", font: "Multilanguage" });
expect(torus).toMatchObject({ size: 22, width: 22, depth: 22, height: 5 });
});
it("creates canonical scene shapes with stable defaults", () => {
const created = sceneShape({
name: "Part",
kind: "box",
color: "#d41721",
width: 12,
depth: 18,
rotation: 359.9,
mirrorX: false,
});
expect(created.id).toMatch(/^shape-/);
expect(created).toMatchObject({
name: "Part",
kind: "box",
color: "#d41721",
x: 0,
z: 0,
elevation: 0,
width: 12,
depth: 18,
height: 20,
size: 18,
rotation: 0,
locked: false,
hidden: false,
});
expect(created.mirrorX).toBeUndefined();
});
});
+97
View File
@@ -0,0 +1,97 @@
import { canonicalizeShape } from "@/lib/workplaneShapes";
import { createLocalId } from "@/lib/localIds";
import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
export const toolbarShapeAssets: ToolbarShapeAsset[] = [
{ id: "box", name: "Box", src: "assets/sketchforge/shape-icons-gray/box.png", menuIcon: "assets/sketchforge/shape-icons-gray/box.png", kind: "box", color: "#d41721" },
{ id: "cylinder", name: "Cylinder", src: "assets/sketchforge/shape-icons-gray/cylinder.png", menuIcon: "assets/sketchforge/shape-icons-gray/cylinder.png", kind: "cylinder", color: "#d97813" },
{ id: "sphere", name: "Sphere", src: "assets/sketchforge/shape-icons-gray/sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/sphere.png", kind: "sphere", color: "#0098c7" },
{ id: "cone", name: "Cone", src: "assets/sketchforge/shape-icons-gray/cone.png", menuIcon: "assets/sketchforge/shape-icons-gray/cone.png", kind: "cone", color: "#6e2786" },
{ id: "pyramid", name: "Pyramid", src: "assets/sketchforge/shape-icons-gray/pyramid.png", menuIcon: "assets/sketchforge/shape-icons-gray/pyramid.png", kind: "pyramid", color: "#f2cf10" },
{ id: "wedge", name: "Wedge", src: "assets/sketchforge/shape-icons-gray/wedge.png", menuIcon: "assets/sketchforge/shape-icons-gray/wedge.png", kind: "wedge", color: "#33983d" },
{ id: "text", name: "Text", src: "assets/sketchforge/shape-icons-gray/text.png", menuIcon: "assets/sketchforge/shape-icons-gray/text.png", kind: "text", color: "#cf101b" },
{ id: "round-roof", name: "Round Roof", src: "assets/sketchforge/shape-icons-gray/round-roof.png", menuIcon: "assets/sketchforge/shape-icons-gray/round-roof.png", kind: "roundRoof", color: "#67c4ce" },
{ id: "half-sphere", name: "Half Sphere", src: "assets/sketchforge/shape-icons-gray/half-sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/half-sphere.png", kind: "halfSphere", color: "#c9009a" },
{ id: "torus", name: "Torus", src: "assets/sketchforge/shape-icons-gray/torus.png", menuIcon: "assets/sketchforge/shape-icons-gray/torus.png", kind: "torus", color: "#0098c7" },
{ id: "tube", name: "Tube", src: "assets/sketchforge/shape-icons-gray/tube.png", menuIcon: "assets/sketchforge/shape-icons-gray/tube.png", kind: "tube", color: "#ce7013" },
];
export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
const width = shape.width ?? shape.size ?? 20;
const depth = shape.depth ?? shape.size ?? 20;
const height = shape.height ?? 20;
return canonicalizeShape({
id: shape.id ?? createLocalId("shape"),
name: shape.name,
kind: shape.kind,
color: shape.color,
hole: shape.hole,
x: shape.x ?? 0,
z: shape.z ?? 0,
elevation: shape.elevation ?? 0,
size: shape.size ?? Math.max(width, depth),
width,
depth,
height,
rotation: shape.rotation ?? 0,
rotationX: shape.rotationX ?? 0,
rotationZ: shape.rotationZ ?? 0,
radius: shape.radius,
steps: shape.steps,
sides: shape.sides,
bevel: shape.bevel,
segments: shape.segments,
topRadius: shape.topRadius,
baseRadius: shape.baseRadius,
text: shape.text,
font: shape.font,
importedMesh: shape.importedMesh,
imagePlate: shape.imagePlate,
groupedShapes: shape.groupedShapes,
groupedBaseWidth: shape.groupedBaseWidth,
groupedBaseDepth: shape.groupedBaseDepth,
groupedBaseHeight: shape.groupedBaseHeight,
locked: shape.locked ?? false,
hidden: shape.hidden ?? false,
});
}
export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape {
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text";
const size = roundProfile ? 22 : 20;
const height = asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
const width = asset.kind === "text" ? 86 : size;
const depth = asset.kind === "text" ? 28 : size;
return {
id: createLocalId(asset.id),
name: asset.name,
kind: asset.kind,
color: asset.color,
hole: asset.hole,
x: point?.x ?? 0,
z: point?.z ?? 0,
elevation: point?.elevation ?? 0,
size,
width,
depth,
height,
rotation: 0,
rotationX: 0,
rotationZ: 0,
radius: asset.kind === "box" ? 0 : undefined,
text: asset.kind === "text" ? "TEXT" : undefined,
font: asset.kind === "text" ? "Multilanguage" : undefined,
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? 24 : asset.kind === "halfSphere" ? 32 : undefined,
sides: asset.kind === "cylinder" || asset.kind === "cone" ? 96 : asset.kind === "roundRoof" ? 64 : asset.kind === "pyramid" ? 4 : undefined,
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? 4 : undefined,
segments: asset.kind === "cylinder" ? 1 : undefined,
topRadius: asset.kind === "cone" ? 0 : undefined,
baseRadius: asset.kind === "cone" ? size / 2 : undefined,
locked: false,
hidden: false,
};
}
+72
View File
@@ -0,0 +1,72 @@
import * as THREE from "three";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
import { createLocalId } from "@/lib/localIds";
import type { WorkplaneShape } from "@/types/sketchforge";
const stlLoader = new STLLoader();
export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): WorkplaneShape {
const rawGeometry = stlLoader.parse(buffer);
const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry.clone();
geometry.computeBoundingBox();
const box = geometry.boundingBox;
if (!box) {
throw new Error("STL has no readable geometry");
}
const size = new THREE.Vector3();
const center = new THREE.Vector3();
box.getSize(size);
box.getCenter(center);
const maxDimension = Math.max(size.x, size.y, size.z);
if (!Number.isFinite(maxDimension) || maxDimension <= 0) {
throw new Error("STL geometry is empty");
}
const scale = 1;
const position = geometry.getAttribute("position");
const normal = geometry.getAttribute("normal");
const positions: number[] = [];
const normals: number[] = [];
for (let i = 0; i < position.count; i += 1) {
positions.push((position.getX(i) - center.x) * scale, (position.getY(i) - box.min.y) * scale, (position.getZ(i) - center.z) * scale);
if (normal) {
normals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
}
}
const width = Math.max(1, size.x * scale);
const height = Math.max(1, size.y * scale);
const depth = Math.max(1, size.z * scale);
const triangleCount = Math.floor(position.count / 3);
return {
id: createLocalId("uploaded-mesh"),
name: fileName.replace(/\.[^.]+$/, "") || "Imported STL",
kind: "mesh",
color: "#0098c7",
x: 10,
z: -10,
size: Math.max(width, depth),
width,
depth,
height,
rotation: 0,
rotationX: 0,
rotationZ: 0,
importedMesh: {
positions,
normals: normals.length ? normals : undefined,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
triangleCount,
sourceFormat: "stl",
},
locked: false,
hidden: false,
};
}
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "./workplaneSettings";
describe("workplane settings helpers", () => {
it("accepts known snap grid values and falls back for unknown values", () => {
expect(normalizeSnapGrid("0.5 mm")).toBe("0.5 mm");
expect(normalizeSnapGrid("Huge")).toBe(DEFAULT_SNAP_GRID);
expect(normalizeSnapGrid(null, "Off")).toBe("Off");
});
it("normalizes workspace settings from partial or invalid data", () => {
const fallback: WorkplaneWorkspaceSettings = {
...DEFAULT_WORKPLANE_WORKSPACE,
width: 300,
depth: 250,
background: "#ffffff",
};
expect(normalizeWorkspaceSettings(null, fallback)).toEqual(fallback);
expect(
normalizeWorkspaceSettings(
{
width: 500,
depth: Number.NaN,
sizePreset: "",
gridBlockSize: 2.5,
gridBlockPreset: "Custom",
background: "#123456",
showShadows: false,
showGrid: false,
cruiseShapes: false,
zoomSpeed: Infinity,
units: "Bricks",
scale: "1:10 (centimeters)",
},
fallback,
),
).toEqual({
...fallback,
width: 500,
gridBlockSize: 2.5,
gridBlockPreset: "Custom",
background: "#123456",
showShadows: false,
showGrid: false,
cruiseShapes: false,
units: "Bricks",
scale: "1:10 (centimeters)",
});
});
it("fingerprints workspace and snap settings together", () => {
const base = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm");
const changedSnap = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "5.0 mm");
const changedWorkspace = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE, width: 300 }, "1.0 mm");
expect(changedSnap).not.toBe(base);
expect(changedWorkspace).not.toBe(base);
});
});
+113
View File
@@ -0,0 +1,113 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneShape } from "@/types/sketchforge";
import {
canonicalizeShape,
cleanNearZero,
cleanRotationDegrees,
fallbackSolidColor,
mirroredAxisCount,
mirrorSign,
normalizeDegrees,
proportionalResizeScale,
resizedShapeSize,
serializeShapesForSync,
shapeDepth,
shapeWidth,
workplaneShapesEqual,
} from "./workplaneShapes";
function shape(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
return {
id: "box-1",
name: "Box",
kind: "box",
color: "#d41721",
x: 0,
z: 0,
elevation: 0,
size: 20,
width: 20,
depth: 20,
height: 20,
rotation: 0,
locked: false,
hidden: false,
...overrides,
};
}
describe("workplane shape helpers", () => {
it("normalizes and cleans rotations", () => {
expect(normalizeDegrees(-90)).toBe(270);
expect(normalizeDegrees(450)).toBe(90);
expect(cleanRotationDegrees(Number.NaN)).toBe(0);
expect(cleanRotationDegrees(-0.2)).toBe(0);
expect(cleanRotationDegrees(359.8)).toBe(0);
expect(cleanRotationDegrees(12.34)).toBe(12.3);
});
it("cleans near-zero values and derives dimensions", () => {
const base = shape({ size: 30, width: 18, depth: 24 });
expect(cleanNearZero(0.004)).toBe(0);
expect(cleanNearZero(0.006)).toBe(0.006);
expect(shapeWidth(base)).toBe(18);
expect(shapeDepth(base)).toBe(24);
expect(resizedShapeSize(18, 24)).toBe(24);
});
it("uses proportional scale instead of square dimensions while shift-resizing", () => {
expect(proportionalResizeScale(50, 100, 100, 150)).toBe(2);
expect(proportionalResizeScale(50, 100, 60, 200)).toBe(2);
expect(proportionalResizeScale(50, 100, 25, 80)).toBe(0.5);
});
it("canonicalizes mirror flags and nested group rotations", () => {
const canonical = canonicalizeShape(
shape({
rotation: 360,
rotationX: -0.1,
rotationZ: 45.04,
mirrorX: false,
mirrorY: true,
groupedShapes: [shape({ id: "child", rotation: 720, mirrorZ: false })],
}),
);
expect(canonical.rotation).toBe(0);
expect(canonical.rotationX).toBe(0);
expect(canonical.rotationZ).toBe(45);
expect(canonical.mirrorX).toBeUndefined();
expect(canonical.mirrorY).toBe(true);
expect(canonical.groupedShapes?.[0].rotation).toBe(0);
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined();
});
it("keeps shallow equality strict for shape payload references", () => {
const importedMesh = { positions: [0, 0, 0], baseWidth: 1, baseDepth: 1, baseHeight: 1, triangleCount: 0, sourceFormat: "json" as const };
const first = shape({ importedMesh });
const sameReference = shape({ importedMesh });
const sameValues = shape({ importedMesh: { ...importedMesh, positions: [...importedMesh.positions] } });
expect(workplaneShapesEqual(first, sameReference)).toBe(true);
expect(workplaneShapesEqual(first, sameValues)).toBe(false);
});
it("serializes canonical shapes for sync", () => {
expect(JSON.parse(serializeShapesForSync([shape({ rotation: 359.9, mirrorX: false })]))).toEqual([
expect.objectContaining({
id: "box-1",
rotation: 0,
rotationX: 0,
rotationZ: 0,
}),
]);
});
it("maps helper flags and fallback colors", () => {
expect(mirrorSign(true)).toBe(-1);
expect(mirrorSign(false)).toBe(1);
expect(mirroredAxisCount(shape({ mirrorX: true, mirrorY: true }))).toBe(2);
expect(fallbackSolidColor(shape({ kind: "sphere" }))).toBe("#0098c7");
expect(fallbackSolidColor(shape({ kind: "box" }))).toBe("#d41721");
});
});
+119
View File
@@ -0,0 +1,119 @@
import type { WorkplaneShape } from "@/types/sketchforge";
export function normalizeDegrees(value: number) {
return ((value % 360) + 360) % 360;
}
export function cleanRotationDegrees(value: number, precision = 1) {
if (!Number.isFinite(value)) {
return 0;
}
const normalized = normalizeDegrees(value);
const rounded = Number(normalized.toFixed(precision));
const zeroThreshold = precision <= 1 ? 0.5 : 0.05;
if (rounded < zeroThreshold || rounded >= 360 - zeroThreshold || Object.is(rounded, -0)) {
return 0;
}
return rounded;
}
export function cleanNearZero(value: number, epsilon = 0.005) {
return Math.abs(value) < epsilon ? 0 : value;
}
export function shapeWidth(shape: WorkplaneShape) {
return shape.width ?? shape.size;
}
export function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size;
}
export function resizedShapeSize(width: number, depth: number) {
return Math.max(width, depth);
}
export function proportionalResizeScale(startWidth: number, startDepth: number, nextWidth: number, nextDepth: number) {
const widthScale = nextWidth / Math.max(0.001, startWidth);
const depthScale = nextDepth / Math.max(0.001, startDepth);
if (!Number.isFinite(widthScale) || !Number.isFinite(depthScale)) {
return 1;
}
return Math.abs(widthScale - 1) >= Math.abs(depthScale - 1) ? widthScale : depthScale;
}
export function fallbackSolidColor(shape: WorkplaneShape) {
if (shape.kind === "cylinder") return "#d97813";
if (shape.kind === "sphere") return "#0098c7";
if (shape.kind === "cone") return "#6e2786";
if (shape.kind === "pyramid") return "#f2cf10";
return "#d41721";
}
export function mirrorSign(value?: boolean) {
return value ? -1 : 1;
}
export function mirroredAxisCount(shape: WorkplaneShape) {
return [shape.mirrorX, shape.mirrorY, shape.mirrorZ].filter(Boolean).length;
}
export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
const next: WorkplaneShape = {
...shape,
rotation: cleanRotationDegrees(shape.rotation ?? 0),
rotationX: cleanRotationDegrees(shape.rotationX ?? 0),
rotationZ: cleanRotationDegrees(shape.rotationZ ?? 0),
mirrorX: shape.mirrorX || undefined,
mirrorY: shape.mirrorY || undefined,
mirrorZ: shape.mirrorZ || undefined,
};
if (shape.groupedShapes) {
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
}
return next;
}
export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
return (
a.id === b.id &&
a.name === b.name &&
a.kind === b.kind &&
a.color === b.color &&
a.hole === b.hole &&
a.x === b.x &&
a.z === b.z &&
a.elevation === b.elevation &&
a.size === b.size &&
a.width === b.width &&
a.depth === b.depth &&
a.height === b.height &&
a.rotation === b.rotation &&
a.rotationX === b.rotationX &&
a.rotationZ === b.rotationZ &&
a.mirrorX === b.mirrorX &&
a.mirrorY === b.mirrorY &&
a.mirrorZ === b.mirrorZ &&
a.radius === b.radius &&
a.steps === b.steps &&
a.sides === b.sides &&
a.bevel === b.bevel &&
a.segments === b.segments &&
a.topRadius === b.topRadius &&
a.baseRadius === b.baseRadius &&
a.text === b.text &&
a.font === b.font &&
a.importedMesh === b.importedMesh &&
a.imagePlate === b.imagePlate &&
a.groupedShapes === b.groupedShapes &&
a.groupedBaseWidth === b.groupedBaseWidth &&
a.groupedBaseDepth === b.groupedBaseDepth &&
a.groupedBaseHeight === b.groupedBaseHeight &&
a.locked === b.locked &&
a.hidden === b.hidden
);
}
export function serializeShapesForSync(shapes: WorkplaneShape[]) {
return JSON.stringify(shapes.map(canonicalizeShape));
}