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
+161 -533
View File
@@ -1,6 +1,6 @@
"use client";
import { Code2, Download, Home, Menu, Settings, UserRoundPlus, X } from "lucide-react";
import { Download, Home, Menu, Settings, UserRoundPlus, X } from "lucide-react";
import type manifoldModule from "manifold-3d";
import type { ManifoldToplevel } from "manifold-3d";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -8,7 +8,6 @@ import { ADDITION, Brush, Evaluator, HOLLOW_SUBTRACTION, SUBTRACTION, type CSGOp
import * as THREE from "three";
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js";
import { FontLoader, type Font, type FontData } from "three/examples/jsm/loaders/FontLoader.js";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js";
import droidMonoFontJson from "three/examples/fonts/droid/droid_sans_mono_regular.typeface.json";
import droidSansBoldFontJson from "three/examples/fonts/droid/droid_sans_bold.typeface.json";
@@ -42,16 +41,33 @@ import {
ToolbarVectorExportIcon,
} from "./icons";
import { WorkplaneViewport } from "./WorkplaneViewport";
import {
canonicalizeShape,
cleanNearZero,
cleanRotationDegrees,
fallbackSolidColor,
mirroredAxisCount,
mirrorSign,
normalizeDegrees,
serializeShapesForSync,
shapeDepth,
shapeWidth,
workplaneShapesEqual,
} from "@/lib/workplaneShapes";
import { createLocalId } from "@/lib/localIds";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl } from "@/lib/stlImport";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
type TopPanel = "import" | "export" | "builder" | "tips" | "profile" | "settings" | null;
export { importedShapeFromStl };
type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null;
type ExportFormat = "stl" | "obj";
type Vec3 = [number, number, number];
type MeshData = { name: string; vertices: Vec3[]; faces: [number, number, number][] };
type Cuboid = { minX: number; maxX: number; minY: number; maxY: number; minZ: number; maxZ: number };
type ShapeUpdatePatch = Partial<WorkplaneShape> & { bakeTransform?: boolean };
type ManifoldSolid = ReturnType<ManifoldToplevel["Manifold"]["cube"]>;
type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
type DownloadResult = { mode: "browser" } | { mode: "folder"; path: string };
type GroupBuildResult = {
group: WorkplaneShape | null;
@@ -76,36 +92,13 @@ type BooleanAutomationResult = {
groupId?: string;
error?: string;
};
type AiCommandPayload = {
shape?: Partial<WorkplaneShape>;
shapes?: Partial<WorkplaneShape>[];
id?: string;
ids?: string[];
patch?: Partial<WorkplaneShape>;
replace?: boolean;
count?: number;
};
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
const SHARED_CLIPBOARD_STORAGE_KEY = "sketchForge.clipboard";
type SketchForgeAiBridge = {
getState: () => { shapes: WorkplaneShape[]; selectedIds: string[]; notice: string };
setShapes: (nextShapes: Partial<WorkplaneShape>[], nextSelection?: string[] | string | null) => WorkplaneShape[];
addShape: (shape: Partial<WorkplaneShape>) => WorkplaneShape;
updateShape: (id: string, patch: Partial<WorkplaneShape>) => WorkplaneShape | null;
deleteShape: (id: string) => boolean;
select: (ids: string[] | string | null) => string[];
clear: () => void;
createHouse: (options?: { replace?: boolean }) => WorkplaneShape[];
createPerfScene: (count?: number) => WorkplaneShape[];
run: (command: string, payload?: AiCommandPayload) => unknown;
};
const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
declare global {
interface Window {
sketchforgeAI?: SketchForgeAiBridge;
sketchforgeBridge?: SketchForgeAiBridge;
__sketchforgeBooleanTest?: BooleanAutomationResult;
__sketchforgeBooleanTestImage?: string;
}
@@ -117,7 +110,6 @@ const CUTTER_RESIDUAL_INSET = CUTTER_PADDING * 0.4;
const MIN_SHAPE_DIMENSION = 0.01;
const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000;
const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02;
const stlLoader = new STLLoader();
const svgLoader = new SVGLoader();
const booleanFontLoader = new FontLoader();
const booleanTextFonts: Record<string, Font> = {
@@ -131,87 +123,6 @@ const booleanTextFonts: Record<string, Font> = {
};
let manifoldRuntimePromise: Promise<ManifoldToplevel> | null = null;
function normalizeDegrees(value: number) {
return ((value % 360) + 360) % 360;
}
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;
}
function cleanNearZero(value: number, epsilon = 0.005) {
return Math.abs(value) < epsilon ? 0 : value;
}
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;
}
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
);
}
function serializeShapesForSync(shapes: WorkplaneShape[]) {
return JSON.stringify(shapes.map(canonicalizeShape));
}
function readSharedClipboard() {
if (typeof window === "undefined") {
return [];
@@ -261,7 +172,7 @@ async function importBundledManifoldModule() {
function getManifoldRuntime() {
const assetBase = typeof window === "undefined" ? "/" : new URL(".", window.location.href).href;
const isFileBuild = typeof window !== "undefined" && window.location.protocol === "file:";
const manifoldScriptUrl = isFileBuild ? new URL("manifold.js", assetBase).href : "/manifold.js";
const manifoldScriptUrl = new URL("manifold.js", assetBase).href;
const runtimeModule = isFileBuild
? importBundledManifoldModule().then((module) => module.default)
: import(/* webpackIgnore: true */ manifoldScriptUrl).then((module) => (module as { default: typeof manifoldModule }).default);
@@ -273,7 +184,7 @@ function getManifoldRuntime() {
});
}
return module({
locateFile: ((file: string) => (file.endsWith(".wasm") ? "/manifold.wasm" : file)) as () => string,
locateFile: ((file: string) => (file.endsWith(".wasm") ? new URL("manifold.wasm", assetBase).href : new URL(file, assetBase).href)) as () => string,
});
})
.then((runtime) => {
@@ -282,98 +193,6 @@ function getManifoldRuntime() {
});
return manifoldRuntimePromise;
}
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" },
];
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 === "star" || asset.kind === "heart" || 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: `${asset.id}-${crypto.randomUUID()}`,
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,
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,
text: asset.kind === "text" ? "TEXT" : undefined,
font: asset.kind === "text" ? "Multilanguage" : undefined,
locked: false,
hidden: false,
};
}
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 ?? `ai-shape-${crypto.randomUUID()}`,
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,
});
}
function stlBoxTrianglePositions(width: number, depth: number, height: number) {
const x = width / 2;
const z = depth / 2;
@@ -847,72 +666,6 @@ function makeBlockPerfScene(count = 500): WorkplaneShape[] {
});
}
const AI_BUILD_PROMPT = `Create a SketchForge 3D build as JSON only.
Return this exact shape:
{"shapes":[{"name":"Part name","kind":"box","color":"#d41721","x":0,"z":0,"elevation":0,"width":20,"depth":20,"height":20,"rotation":0}]}
Allowed kind values: box, cylinder, sphere, cone, pyramid, roof, roundRoof, halfSphere, torus, tube, ring, wedge, polygon, icosahedron, star, heart, text.
Use millimeters. Use x and z for the workplane position. Use elevation for height above the workplane. Return valid JSON with no markdown.`;
function extractJsonBuild(source: string): Partial<WorkplaneShape>[] {
const trimmed = source.trim();
if (!trimmed) {
throw new Error("Paste build code first");
}
const candidates = [trimmed];
const fenced = trimmed.match(/```(?:json|js|javascript)?\s*([\s\S]*?)```/i);
if (fenced?.[1]) {
candidates.unshift(fenced[1].trim());
}
const buildCall = trimmed.match(/(?:build|createBuild|setShapes)\s*\(\s*(\[[\s\S]*\]|\{[\s\S]*\})\s*\)\s*;?/);
if (buildCall?.[1]) {
candidates.unshift(buildCall[1].trim());
}
const firstObject = trimmed.match(/\{[\s\S]*\}/);
if (firstObject?.[0]) {
candidates.push(firstObject[0]);
}
const firstArray = trimmed.match(/\[[\s\S]*\]/);
if (firstArray?.[0]) {
candidates.push(firstArray[0]);
}
for (const candidate of candidates) {
try {
const parsed = JSON.parse(candidate) as unknown;
if (Array.isArray(parsed)) {
return parsed as Partial<WorkplaneShape>[];
}
if (parsed && typeof parsed === "object" && Array.isArray((parsed as { shapes?: unknown }).shapes)) {
return (parsed as { shapes: Partial<WorkplaneShape>[] }).shapes;
}
} catch {
// Try the next candidate.
}
}
throw new Error("Could not read the build code. Use JSON with a shapes array.");
}
function shapeWidth(shape: WorkplaneShape) {
return shape.width ?? shape.size;
}
function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size;
}
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";
}
function withHoleMode(shape: WorkplaneShape, hole: boolean, parentColor?: string): WorkplaneShape {
const color = hole ? "#b8c2cc" : (parentColor ?? fallbackSolidColor(shape));
return {
@@ -927,14 +680,6 @@ function sanitizeName(name: string) {
return name.replace(/[^a-z0-9_-]+/gi, "_") || "shape";
}
function mirrorSign(value?: boolean) {
return value ? -1 : 1;
}
function mirroredAxisCount(shape: WorkplaneShape) {
return [shape.mirrorX, shape.mirrorY, shape.mirrorZ].filter(Boolean).length;
}
function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData {
const centerY = shape.height / 2;
const matrix = new THREE.Matrix4().makeRotationFromEuler(
@@ -1516,75 +1261,6 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
};
}
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);
return {
id: `uploaded-mesh-${crypto.randomUUID()}`,
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: Math.floor(position.count / 3),
sourceFormat: "stl",
},
locked: false,
hidden: false,
};
}
function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
const parsed = svgLoader.parse(source);
const rawPositions: number[] = [];
@@ -1638,7 +1314,7 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
}
return {
id: `uploaded-svg-${crypto.randomUUID()}`,
id: createLocalId("uploaded-svg"),
name: fileName.replace(/\.[^.]+$/, "") || "Imported SVG",
kind: "mesh",
color: "#0098c7",
@@ -1759,7 +1435,7 @@ async function importedShapeFromImage(file: File): Promise<WorkplaneShape> {
const imagePlate = await prepareImportedImage(file);
const dimensions = imagePlateDimensions(imagePlate.pixelWidth, imagePlate.pixelHeight);
return {
id: `uploaded-image-${crypto.randomUUID()}`,
id: createLocalId("uploaded-image"),
name: file.name.replace(/\.[^.]+$/, "") || "Imported Image",
kind: "box",
color: "#f4f7f9",
@@ -1844,7 +1520,7 @@ function triggerBrowserDownload(filename: string, content: string, type: string)
async function downloadTextFile(filename: string, content: string, type: string): Promise<DownloadResult> {
const mode = window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY);
const folder = window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY)?.trim() ?? "";
if (mode === "folder" && folder) {
if (!STATIC_EXPORT_BUILD && mode === "folder" && folder) {
const response = await fetch("/api/local-download", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -2930,7 +2606,7 @@ function booleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
}
return {
id: `grouped-boolean-${crypto.randomUUID()}`,
id: createLocalId("grouped-boolean"),
name: "Group",
kind: "mesh",
color: firstSolid.color,
@@ -2989,7 +2665,7 @@ function resultGeometryToMeshShape(
const firstSolid = solids[0];
return {
id: `${idPrefix}-${crypto.randomUUID()}`,
id: createLocalId(idPrefix),
name: "Group",
kind: "mesh",
color: firstSolid.color,
@@ -3069,7 +2745,7 @@ function coplanarRescueCutterShape(shape: WorkplaneShape): WorkplaneShape {
function cloneAsGroupChild(shape: WorkplaneShape, centerX: number, centerZ: number, minY: number): WorkplaneShape {
return {
...shape,
id: `${shape.id}-group-child-${crypto.randomUUID()}`,
id: createLocalId(`${shape.id}-group-child`),
x: shape.x - centerX,
z: shape.z - centerZ,
elevation: (shape.elevation ?? 0) - minY,
@@ -3316,7 +2992,7 @@ function meshPositionsToGroupShape(selection: WorkplaneShape[], solids: Workplan
const firstSolid = solids[0];
return {
id: `${idPrefix}-${crypto.randomUUID()}`,
id: createLocalId(idPrefix),
name: "Group",
kind: "mesh",
color: firstSolid.color,
@@ -3576,7 +3252,7 @@ function boxedBooleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | nu
const firstSolid = solids[0];
return {
id: `grouped-boolean-${crypto.randomUUID()}`,
id: createLocalId("grouped-boolean"),
name: "Group",
kind: "mesh",
color: firstSolid.color,
@@ -3631,7 +3307,7 @@ function aabbBooleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | nul
const firstSolid = solids[0];
return {
id: `grouped-boolean-${crypto.randomUUID()}`,
id: createLocalId("grouped-boolean"),
name: "Group",
kind: "mesh",
color: firstSolid.color,
@@ -3754,7 +3430,7 @@ function hollowClipMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null
const firstSolid = solids[0];
return {
id: `grouped-import-clip-${crypto.randomUUID()}`,
id: createLocalId("grouped-import-clip"),
name: "Group",
kind: "mesh",
color: firstSolid.color,
@@ -3860,7 +3536,7 @@ function mergedMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
const holeOnly = groupable.every((shape) => shape.hole);
return {
id: `grouped-mesh-${crypto.randomUUID()}`,
id: createLocalId("grouped-mesh"),
name: "Group",
kind: "mesh",
color: holeOnly ? "#b8c2cc" : firstSolid.color,
@@ -3912,7 +3588,7 @@ function groupedShape(selection: WorkplaneShape[]): WorkplaneShape | null {
const holeOnly = groupable.every((shape) => shape.hole);
return {
id: `group-${crypto.randomUUID()}`,
id: createLocalId("group"),
name: "Group",
kind: "mesh",
color: firstSolid.color,
@@ -4008,7 +3684,7 @@ function restoreGroupedChildren(group: WorkplaneShape): WorkplaneShape[] {
const childRotation = rotationFromQuaternion(new THREE.Quaternion().setFromRotationMatrix(childRotationMatrix));
const restored: WorkplaneShape = {
...child,
id: `${child.id}-ungroup-${crypto.randomUUID()}`,
id: createLocalId(`${child.id}-ungroup`),
x: worldCenter.x,
z: worldCenter.z,
elevation: worldCenter.y - height / 2,
@@ -4187,6 +3863,11 @@ export function SketchForgeEditor({
const lastProjectShapesEchoRef = useRef<string | null>(null);
const lastProjectIdRef = useRef<string | null>(null);
const projectSnapshotRunRef = useRef(0);
const shapesRef = useRef(shapes);
const historyIndexRef = useRef(historyIndex);
const interactionHistoryStartRef = useRef("");
const interactionHistoryChangedRef = useRef(false);
const interactionHistoryTimerRef = useRef<number | null>(null);
const [projectInteractionActive, setProjectInteractionActive] = useState(false);
useEffect(() => {
@@ -4219,6 +3900,14 @@ export function SketchForgeEditor({
return () => window.removeEventListener("storage", onStorage);
}, []);
useEffect(() => {
shapesRef.current = shapes;
}, [shapes]);
useEffect(() => {
historyIndexRef.current = historyIndex;
}, [historyIndex]);
const selectedShapes = useMemo(() => shapes.filter((shape) => selectedIds.includes(shape.id)), [selectedIds, shapes]);
const selectedShape = selectedShapes.at(-1) ?? null;
const hasSelection = selectedShapes.length > 0;
@@ -4324,6 +4013,38 @@ export function SketchForgeEditor({
[onProjectShapesChange, projectId],
);
const finalizeInteractionHistory = useCallback(() => {
const startFingerprint = interactionHistoryStartRef.current;
const hadChanges = interactionHistoryChangedRef.current;
interactionHistoryStartRef.current = "";
interactionHistoryChangedRef.current = false;
if (!hadChanges) {
return;
}
const canonicalNext = shapesRef.current.map(canonicalizeShape);
const nextFingerprint = projectShapesFingerprint(canonicalNext);
if (!startFingerprint || startFingerprint === nextFingerprint) {
return;
}
setHistory((current) => {
const historyIndex = Math.min(historyIndexRef.current, Math.max(0, current.length - 1));
const trimmed = current.slice(0, historyIndex + 1);
const latestHistory = trimmed.at(-1) ?? [];
if (projectShapesFingerprint(latestHistory) === nextFingerprint) {
historyIndexRef.current = Math.max(0, trimmed.length - 1);
setHistoryIndex(historyIndexRef.current);
return trimmed;
}
const nextHistory = [...trimmed, canonicalNext];
historyIndexRef.current = nextHistory.length - 1;
setHistoryIndex(historyIndexRef.current);
return nextHistory;
});
}, []);
useEffect(() => {
if (projectInteractionActive || !pendingProjectShapesRef.current) {
return;
@@ -4334,10 +4055,34 @@ export function SketchForgeEditor({
return () => window.clearTimeout(timer);
}, [projectInteractionActive, syncProjectShapes]);
const updateProjectInteractionActive = useCallback((active: boolean) => {
projectInteractionActiveRef.current = active;
setProjectInteractionActive((current) => (current === active ? current : active));
}, []);
const updateProjectInteractionActive = useCallback(
(active: boolean) => {
if (active) {
if (interactionHistoryTimerRef.current !== null) {
window.clearTimeout(interactionHistoryTimerRef.current);
interactionHistoryTimerRef.current = null;
}
if (!projectInteractionActiveRef.current) {
interactionHistoryStartRef.current = projectShapesFingerprint(shapesRef.current);
interactionHistoryChangedRef.current = false;
}
projectInteractionActiveRef.current = true;
setProjectInteractionActive((current) => (current ? current : true));
return;
}
projectInteractionActiveRef.current = false;
setProjectInteractionActive((current) => (current ? false : current));
if (interactionHistoryTimerRef.current !== null) {
window.clearTimeout(interactionHistoryTimerRef.current);
}
interactionHistoryTimerRef.current = window.setTimeout(() => {
interactionHistoryTimerRef.current = null;
finalizeInteractionHistory();
}, 0);
},
[finalizeInteractionHistory],
);
const updateProjectWorkspaceSettings = useCallback(
(settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => {
@@ -4354,11 +4099,13 @@ export function SketchForgeEditor({
const canonicalNext = next.map(canonicalizeShape);
const requestedSelection = Array.isArray(nextSelection) ? nextSelection : nextSelection ? [nextSelection] : [];
const validSelection = requestedSelection.filter((id, index) => requestedSelection.indexOf(id) === index && canonicalNext.some((shape) => shape.id === id));
shapesRef.current = canonicalNext;
setShapes(canonicalNext);
setSelectedIds(validSelection);
setHistory((current) => {
const trimmed = current.slice(0, historyIndex + 1);
setHistoryIndex(trimmed.length);
historyIndexRef.current = trimmed.length;
setHistoryIndex(historyIndexRef.current);
return [...trimmed, canonicalNext];
});
if (message) {
@@ -4423,6 +4170,9 @@ export function SketchForgeEditor({
if (projectSyncTimerRef.current !== null) {
window.clearTimeout(projectSyncTimerRef.current);
}
if (interactionHistoryTimerRef.current !== null) {
window.clearTimeout(interactionHistoryTimerRef.current);
}
};
}, []);
@@ -4434,28 +4184,49 @@ export function SketchForgeEditor({
[commitShapes, placementElevation, shapes],
);
const updateShape = useCallback((id: string, patch: ShapeUpdatePatch) => {
const bakeTransform = Boolean(patch.bakeTransform);
const cleanedPatch = cleanShapePatch(patch);
setShapes((current) => {
let changed = false;
const next = current.map((shape) => {
if (shape.id !== id) {
return shape;
}
const updateShape = useCallback(
(id: string, patch: ShapeUpdatePatch) => {
const bakeTransform = Boolean(patch.bakeTransform);
const cleanedPatch = cleanShapePatch(patch);
const applyPatch = (current: WorkplaneShape[]) => {
let changed = false;
const next = current.map((shape) => {
if (shape.id !== id) {
return shape;
}
const patched = { ...shape, ...cleanedPatch };
const canonicalBase = canonicalizeShape("hole" in cleanedPatch ? withHoleMode(patched, Boolean(cleanedPatch.hole), cleanedPatch.color) : patched);
const canonical = bakeTransform ? canonicalizeShape(bakeShapeTransformIntoMesh(canonicalBase)) : canonicalBase;
if (workplaneShapesEqual(shape, canonical)) {
return shape;
}
changed = true;
return canonical;
});
return changed ? next : current;
});
}, []);
const patched = { ...shape, ...cleanedPatch };
const canonicalBase = canonicalizeShape("hole" in cleanedPatch ? withHoleMode(patched, Boolean(cleanedPatch.hole), cleanedPatch.color) : patched);
const canonical = bakeTransform ? canonicalizeShape(bakeShapeTransformIntoMesh(canonicalBase)) : canonicalBase;
if (workplaneShapesEqual(shape, canonical)) {
return shape;
}
changed = true;
return canonical;
});
return { changed, next };
};
if (projectInteractionActiveRef.current) {
setShapes((current) => {
const { changed, next } = applyPatch(current);
if (!changed) {
return current;
}
interactionHistoryChangedRef.current = true;
shapesRef.current = next;
return next;
});
return;
}
const { changed, next } = applyPatch(shapes);
if (changed) {
commitShapes(next, selectedIds);
}
},
[commitShapes, selectedIds, shapes],
);
const deleteSelected = useCallback(() => {
if (!hasSelection) {
@@ -4477,7 +4248,7 @@ export function SketchForgeEditor({
}
const duplicates = selectedShapes.map((shape) => ({
...shape,
id: `${shape.id}-copy-${crypto.randomUUID()}`,
id: createLocalId(`${shape.id}-copy`),
x: Math.min(110, shape.x + 8),
z: Math.min(110, shape.z + 8),
}));
@@ -4506,7 +4277,7 @@ export function SketchForgeEditor({
}
const pasted = sourceClipboard.map((shape) => ({
...shape,
id: `${shape.id}-paste-${crypto.randomUUID()}`,
id: createLocalId(`${shape.id}-paste`),
x: Math.min(110, shape.x + 12),
z: Math.min(110, shape.z + 12),
}));
@@ -5040,32 +4811,6 @@ export function SketchForgeEditor({
[commitShapes],
);
const buildFromCode = useCallback(
(source: string) => {
try {
const parsedShapes = extractJsonBuild(source);
const generated = parsedShapes.map((shape, index) =>
sceneShape({
name: shape.name ?? `AI part ${index + 1}`,
kind: shape.kind ?? "box",
color: shape.color ?? "#d41721",
...shape,
id: shape.id ?? `ai-build-${crypto.randomUUID()}`,
}),
);
if (generated.length === 0) {
setNotice("Build code had no shapes");
return;
}
commitShapes([...shapes, ...generated], generated.map((shape) => shape.id), `Built ${generated.length} AI shape${generated.length === 1 ? "" : "s"}`);
setTopPanel(null);
} catch (error) {
setNotice(error instanceof Error ? error.message : "Could not build from code");
}
},
[commitShapes, shapes],
);
const saveDesign = useCallback(() => {
setNotice(`Saved design with ${shapes.length} shape${shapes.length === 1 ? "" : "s"}`);
setMenuOpen(false);
@@ -5079,7 +4824,7 @@ export function SketchForgeEditor({
}
const copies = shapes.map((shape) => ({
...shape,
id: `${shape.id}-copy-${crypto.randomUUID()}`,
id: createLocalId(`${shape.id}-copy`),
x: Math.min(110, shape.x + 12),
z: Math.min(110, shape.z + 12),
}));
@@ -5129,101 +4874,6 @@ export function SketchForgeEditor({
});
}, []);
useEffect(() => {
const normalizeShape = (shape: Partial<WorkplaneShape>) =>
sceneShape({
name: shape.name ?? "AI shape",
kind: shape.kind ?? "box",
color: shape.color ?? "#d41721",
...shape,
id: shape.id ?? `ai-${crypto.randomUUID()}`,
});
const api: SketchForgeAiBridge = {
getState: () => ({ shapes, selectedIds, notice }),
setShapes: (nextShapes, nextSelection = null) => {
const normalized = nextShapes.map(normalizeShape);
commitShapes(normalized, nextSelection, `AI set ${normalized.length} shape${normalized.length === 1 ? "" : "s"}`);
return normalized;
},
addShape: (shape) => {
const nextShape = normalizeShape(shape);
commitShapes([...shapes, nextShape], nextShape.id, `AI added ${nextShape.name}`);
return nextShape;
},
updateShape: (id, patch) => {
const exists = shapes.some((shape) => shape.id === id);
if (!exists) {
setNotice(`AI could not find ${id}`);
return null;
}
const next = shapes.map((shape) => (shape.id === id ? normalizeShape({ ...shape, ...patch, id }) : shape));
commitShapes(next, id, "AI updated shape");
return next.find((shape) => shape.id === id) ?? null;
},
deleteShape: (id) => {
const exists = shapes.some((shape) => shape.id === id);
if (!exists) {
setNotice(`AI could not find ${id}`);
return false;
}
commitShapes(shapes.filter((shape) => shape.id !== id), selectedIds.filter((selectedId) => selectedId !== id), "AI deleted shape");
return true;
},
select: (ids) => {
const requested = Array.isArray(ids) ? ids : ids ? [ids] : [];
const valid = requested.filter((id) => shapes.some((shape) => shape.id === id));
setSelectedIds(valid);
setNotice(valid.length ? `AI selected ${valid.length} shape${valid.length === 1 ? "" : "s"}` : "AI cleared selection");
return valid;
},
clear: clearDesign,
createHouse: (options) => createHouseScene(options?.replace ?? true),
createPerfScene: (count) => createPerfScene(count),
run: (command, payload = {}) => {
if (command === "createHouse") return api.createHouse({ replace: payload.replace });
if (command === "createPerfScene" || command === "perfScene") return api.createPerfScene(payload.count);
if (command === "clear") return api.clear();
if (command === "addShape" && payload.shape) return api.addShape(payload.shape);
if (command === "setShapes" && payload.shapes) return api.setShapes(payload.shapes, payload.ids ?? null);
if (command === "updateShape" && payload.id && payload.patch) return api.updateShape(payload.id, payload.patch);
if (command === "deleteShape" && payload.id) return api.deleteShape(payload.id);
if (command === "select") return api.select(payload.ids ?? payload.id ?? null);
throw new Error(`Unknown AI command: ${command}`);
},
};
const handleCommand = (event: Event) => {
const detail = (event as CustomEvent<{ command?: string; payload?: AiCommandPayload }>).detail;
if (!detail?.command) {
return;
}
try {
const result = api.run(detail.command, detail.payload);
window.dispatchEvent(new CustomEvent("sketchforge:ai-result", { detail: { command: detail.command, ok: true, result } }));
} catch (error) {
window.dispatchEvent(
new CustomEvent("sketchforge:ai-result", {
detail: { command: detail.command, ok: false, error: error instanceof Error ? error.message : "AI command failed" },
}),
);
}
};
window.sketchforgeAI = api;
window.sketchforgeBridge = api;
window.addEventListener("sketchforge:ai-command", handleCommand);
return () => {
window.removeEventListener("sketchforge:ai-command", handleCommand);
if (window.sketchforgeAI === api) {
delete window.sketchforgeAI;
}
if (window.sketchforgeBridge === api) {
delete window.sketchforgeBridge;
}
};
}, [clearDesign, commitShapes, createHouseScene, createPerfScene, notice, selectedIds, shapes]);
const nudgeSelected = useCallback(
(deltaX: number, deltaZ: number) => {
if (!hasSelection) {
@@ -5492,7 +5142,6 @@ export function SketchForgeEditor({
onExport={exportDesign}
onImportFiles={selectFiles}
onPickFile={() => fileInputRef.current?.click()}
onBuildFromCode={buildFromCode}
onNotice={setNotice}
/>
) : null}
@@ -5824,7 +5473,6 @@ function TopActionPanel({
panel,
shapeCount,
scopeLabel,
onBuildFromCode,
onClose,
onExport,
onImportFiles,
@@ -5834,14 +5482,12 @@ function TopActionPanel({
panel: Exclude<TopPanel, null>;
shapeCount: number;
scopeLabel: "selected" | "total";
onBuildFromCode: (source: string) => void;
onClose: () => void;
onExport: (format: ExportFormat) => void;
onImportFiles: (files: FileList | File[]) => void;
onPickFile: () => void;
onNotice: (message: string) => void;
}) {
const [buildCode, setBuildCode] = useState("");
const title =
panel === "profile"
? "Profile"
@@ -5851,9 +5497,7 @@ function TopActionPanel({
? "Tips"
: panel === "export"
? "Export"
: panel === "builder"
? "AI Build"
: "Import";
: "Import";
return (
<div className="top-action-panel" role="dialog" aria-label={title}>
@@ -5898,22 +5542,6 @@ function TopActionPanel({
</button>
</div>
) : null}
{panel === "builder" ? (
<div className="top-action-body ai-build-body">
<label>
<span>Prompt for AI</span>
<textarea readOnly value={AI_BUILD_PROMPT} />
</label>
<label>
<span>Paste AI code</span>
<textarea value={buildCode} onChange={(event) => setBuildCode(event.currentTarget.value)} placeholder='{"shapes":[{"name":"Box","kind":"box","color":"#d41721","width":20,"depth":20,"height":20}]}' />
</label>
<button onClick={() => onBuildFromCode(buildCode)}>
<Code2 size={18} />
Build
</button>
</div>
) : null}
{panel === "tips" ? (
<div className="top-action-body">
<p>Click a shape to select it. Use the inspector for dimensions, rotation, solid/hole, color, duplicate, and delete.</p>
+71 -781
View File
@@ -1,7 +1,7 @@
"use client";
import { Box, Check, ChevronDown, ChevronUp, Expand, Home, LockKeyhole, LockKeyholeOpen, Minus, Plus, X } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react";
import { Box, Check, Expand, Home, Minus, Plus } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";
@@ -13,9 +13,11 @@ import droidSerifBoldFontJson from "three/examples/fonts/droid/droid_serif_bold.
import gentilisBoldFontJson from "three/examples/fonts/gentilis_bold.typeface.json";
import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typeface.json";
import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json";
import { ToolbarHideSelectedIcon } from "@/components/icons";
import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays";
import { ShapeInspector, SnapGridControl } from "@/components/workplane/ShapeInspector";
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, proportionalResizeScale, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import {
TransformOverlay,
getElevationMeasureKey,
@@ -33,23 +35,11 @@ import {
} from "@/components/workplane/TransformOverlay";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const gridSizes: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
const WORKPLANE_WIDTH = 200;
const WORKPLANE_DEPTH = 140;
const MIN_WORKSPACE_SIZE = 60;
const MAX_WORKSPACE_SIZE = 2000;
const MIN_GRID_BLOCK_SIZE = 1;
const MAX_GRID_BLOCK_SIZE = 200;
const DEFAULT_WORKSPACE = DEFAULT_WORKPLANE_WORKSPACE;
const workspaceSizePresets = [
{ label: "200 x 200 mm", width: 200, depth: 200 },
{ label: "300 x 300 mm", width: 300, depth: 300 },
{ label: "500 x 500 mm", width: 500, depth: 500 },
{ label: "1000 x 1000 mm", width: 1000, depth: 1000 },
{ label: "2000 x 2000 mm", width: 2000, depth: 2000 },
{ label: "Custom", width: 200, depth: 200 },
];
const gridBlockPresets = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const;
const CAMERA_HOME = new THREE.Vector3(118, 96, 118);
const CAMERA_TARGET = new THREE.Vector3(0, 0, 0);
const MIN_SHAPE_SIZE = 0.01;
@@ -57,37 +47,26 @@ const MIN_ELEVATION = -180;
const MAX_ELEVATION = 220;
const CAMERA_MIN_TARGET_Y = -70;
const CAMERA_MAX_TARGET_Y = 120;
const solidColors = [
"#d41721",
"#ff4b4b",
"#ff7a1a",
"#d97813",
"#f6a21a",
"#f2cf10",
"#f7e65a",
"#a8d642",
"#33983d",
"#1fb66d",
"#18b99a",
"#0098c7",
"#49c7ef",
"#3b82f6",
"#294c93",
"#5b5ce2",
"#6e2786",
"#9b3bd2",
"#c9009a",
"#f062b6",
"#8a5a2b",
"#b98254",
"#f2caa0",
"#ffffff",
"#cfd8df",
"#8a98a6",
"#4b5563",
"#111111",
];
const textFontOptions = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
const SHAPE_KINDS = new Set<ShapeAsset["kind"]>([
"box",
"cylinder",
"sphere",
"sketch",
"scribble",
"cone",
"pyramid",
"roof",
"text",
"roundRoof",
"halfSphere",
"torus",
"tube",
"ring",
"wedge",
"polygon",
"icosahedron",
"mesh",
]);
const fontLoader = new FontLoader();
const textFonts: Record<string, Font> = {
Multilanguage: fontLoader.parse(helvetikerBoldFontJson as FontData),
@@ -105,6 +84,36 @@ const importedGeometryCache = new WeakMap<
const imageTextureLoader = new THREE.TextureLoader();
const IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT = 40000;
function parseDroppedShapeAsset(raw: string): ShapeAsset | null {
try {
const value: unknown = JSON.parse(raw);
if (!value || typeof value !== "object") {
return null;
}
const asset = value as Partial<ShapeAsset>;
if (
typeof asset.id !== "string" ||
typeof asset.name !== "string" ||
typeof asset.src !== "string" ||
typeof asset.color !== "string" ||
!SHAPE_KINDS.has(asset.kind as ShapeAsset["kind"]) ||
(asset.hole !== undefined && typeof asset.hole !== "boolean")
) {
return null;
}
return {
id: asset.id,
name: asset.name,
src: asset.src,
kind: asset.kind as ShapeAsset["kind"],
color: asset.color,
hole: asset.hole,
};
} catch {
return null;
}
}
type WorkplaneViewportProps = {
shapes: WorkplaneShape[];
selectedIds: string[];
@@ -313,13 +322,6 @@ function snapPositionValue(value: number, step: number, min: number, max: number
return clamp(step > 0 ? snapValue(value, step) : value, min, max);
}
function gridBlockSizeForPreset(preset: string, fallback: number) {
if (preset === "Custom") {
return clamp(fallback, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
}
return clamp(Number.parseFloat(preset) || DEFAULT_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
}
function projectedScreenY(state: ThreeState, shape: WorkplaneShape, y: number) {
return projectedScreenYAt(state, shape.x, shape.z, y);
}
@@ -347,19 +349,6 @@ function screenAngle(clientX: number, clientY: number, center: { x: number; y: n
return Math.atan2(clientY - center.y, clientX - center.x);
}
function normalizeDegrees(value: number) {
return ((value % 360) + 360) % 360;
}
function cleanRotationDegrees(value: number) {
if (!Number.isFinite(value)) {
return 0;
}
const normalized = normalizeDegrees(value);
const rounded = Number(normalized.toFixed(1));
return rounded < 0.5 || rounded >= 359.5 || Object.is(rounded, -0) ? 0 : rounded;
}
function unwrapRadians(value: number) {
if (value > Math.PI) {
return value - Math.PI * 2;
@@ -551,10 +540,6 @@ function selectionFrameCorners(frame: SelectionFrame) {
return corners;
}
function cleanNearZero(value: number, epsilon = 0.005) {
return Math.abs(value) < epsilon ? 0 : value;
}
function selectionWorldYBounds(frame: SelectionFrame) {
const corners = selectionFrameCorners(frame);
const min = cleanNearZero(Math.min(...corners.map((corner) => corner.y)));
@@ -594,10 +579,6 @@ function resizeCenterFromAnchor(frame: SelectionFrame, anchor: THREE.Vector3, si
.add(frame.zAxis.clone().multiplyScalar(signs.z ? (signs.z * depth) / 2 : 0));
}
function resizedShapeSize(width: number, depth: number) {
return Math.max(width, depth);
}
function resizedShapePatchFromFrame(shape: WorkplaneShape, center: THREE.Vector3, width: number, depth: number): Partial<WorkplaneShape> {
const patch: Partial<WorkplaneShape> = {
x: cleanNearZero(center.x, 0.0005),
@@ -779,9 +760,10 @@ function resizeShapeFromFrameHandle(
let nextDepth = axisResize(depth, localDelta.z, signs.z);
if (shiftKey && signs.x && signs.z) {
const uniform = Math.max(nextWidth, nextDepth);
nextWidth = uniform;
nextDepth = uniform;
const scale = proportionalResizeScale(width, depth, nextWidth, nextDepth);
const limitedScale = clamp(scale, MIN_SHAPE_SIZE / Math.max(MIN_SHAPE_SIZE, Math.min(width, depth)), maxSize / Math.max(width, depth));
nextWidth = snapDimension(width * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
nextDepth = snapDimension(depth * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
}
const nextCenter = altKey
@@ -821,14 +803,17 @@ function resizeSelectionFromHandle(
let nextX = axisResize(frame.width, localDelta.x, signs.x);
let nextZ = axisResize(frame.depth, localDelta.z, signs.z);
if (shiftKey && signs.x && signs.z) {
const uniform = Math.max(nextX.size, nextZ.size);
const scale = proportionalResizeScale(frame.width, frame.depth, nextX.size, nextZ.size);
const limitedScale = clamp(scale, MIN_SHAPE_SIZE / Math.max(MIN_SHAPE_SIZE, Math.min(frame.width, frame.depth)), 260 / Math.max(frame.width, frame.depth));
const width = snapDimension(frame.width * limitedScale, step, MIN_SHAPE_SIZE, 260);
const depth = snapDimension(frame.depth * limitedScale, step, MIN_SHAPE_SIZE, 260);
nextX = {
size: uniform,
scale: uniform / Math.max(MIN_SHAPE_SIZE, frame.width),
size: width,
scale: width / Math.max(MIN_SHAPE_SIZE, frame.width),
};
nextZ = {
size: uniform,
scale: uniform / Math.max(MIN_SHAPE_SIZE, frame.depth),
size: depth,
scale: depth / Math.max(MIN_SHAPE_SIZE, frame.depth),
};
}
@@ -2114,7 +2099,10 @@ export function WorkplaneViewport({
return;
}
const asset = JSON.parse(raw) as ShapeAsset;
const asset = parseDroppedShapeAsset(raw);
if (!asset) {
return;
}
const point = toPlanePoint(event.clientX, event.clientY);
onAddShape(asset, point ? { ...point, elevation: placementElevationRef.current } : { x: 0, z: 0, elevation: placementElevationRef.current });
},
@@ -2285,647 +2273,6 @@ export function WorkplaneViewport({
);
}
function ShapeInspector({
shape,
snap,
snapOpen,
onUpdate,
onClose,
onSnapChange,
onSnapOpenChange,
}: {
shape: WorkplaneShape;
snap: GridSize;
snapOpen: boolean;
onUpdate: (patch: Partial<WorkplaneShape>) => void;
onClose: () => void;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
}) {
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
const properties = getShapeProperties(shape, onUpdate);
const [propertiesOpen, setPropertiesOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
return (
<aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header">
<button className="inspector-header-icon" aria-label="Close shape settings" onClick={onClose}>
<ChevronUp size={26} strokeWidth={2.8} />
</button>
<strong>{shape.name}</strong>
<div className="inspector-header-actions">
<button className={locked ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={locked ? "Unlock shape" : "Lock shape"} onClick={() => onUpdate({ locked: !locked })}>
{locked ? <LockKeyhole size={31} strokeWidth={2.4} /> : <LockKeyholeOpen size={31} strokeWidth={2.4} />}
</button>
<button className={shape.hidden ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={shape.hidden ? "Show shape" : "Hide shape"} onClick={() => onUpdate({ hidden: !shape.hidden })}>
<ToolbarHideSelectedIcon />
</button>
</div>
</div>
<div className="shape-state-card" role="group" aria-label="Shape mode">
<button
className={!shape.hole ? "active solid-choice" : "solid-choice"}
onClick={() => {
const wasHole = Boolean(shape.hole);
onUpdate({ hole: false, color: solidColor });
setColorOpen((open) => (wasHole ? false : !open));
}}
disabled={locked}
aria-pressed={!shape.hole}
aria-expanded={colorOpen}
>
<span className="large-solid-swatch" style={{ "--swatch": solidColor } as CSSProperties} />
<span>Solid</span>
</button>
<button
className={shape.hole ? "active hole-choice" : "hole-choice"}
onClick={() => {
onUpdate({ hole: true, color: "#b8c2cc" });
setColorOpen(false);
}}
disabled={locked}
aria-pressed={shape.hole}
>
<span className="large-hole-swatch" />
<span>Hole</span>
</button>
</div>
{colorOpen ? (
<div className="color-card" aria-label="Shape color">
<div className="color-card-header">
<span>Color</span>
<span className="color-value">{solidColor.toUpperCase()}</span>
</div>
<div className="color-grid">
{solidColors.map((color) => (
<button
key={color}
className={solidColor.toLowerCase() === color.toLowerCase() && !shape.hole ? "selected" : ""}
type="button"
style={{ "--shape-swatch": color } as CSSProperties}
title={color.toUpperCase()}
aria-label={`Set color ${color}`}
disabled={locked}
onClick={() => {
onUpdate({ color, hole: false });
setColorOpen(false);
}}
/>
))}
<label className={locked ? "custom-color disabled" : "custom-color"} title="Custom color">
<input
type="color"
value={solidColor}
disabled={locked}
onChange={(event) => {
onUpdate({ color: event.target.value, hole: false });
setColorOpen(false);
}}
/>
<span>Custom</span>
</label>
</div>
</div>
) : null}
<div className="property-card">
<button
className="property-card-header"
type="button"
aria-expanded={propertiesOpen}
aria-controls={`properties-${shape.id}`}
onClick={() => setPropertiesOpen((open) => !open)}
>
<span>Properties</span>
<ChevronUp className={propertiesOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
</button>
{propertiesOpen ? (
<div className="property-list" id={`properties-${shape.id}`}>
{properties.map((property) => {
if (property.type === "text") {
return <TextProperty key={property.label} {...property} disabled={locked} />;
}
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={locked} />;
}
return <RangeProperty key={property.label} {...property} disabled={locked} />;
})}
</div>
) : null}
</div>
<div className="inspector-snap-dock">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
</div>
</aside>
);
}
function SnapGridControl({
snap,
snapOpen,
onSnapChange,
onSnapOpenChange,
}: {
snap: GridSize;
snapOpen: boolean;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
}) {
return (
<div className="snap-row">
<span>Snap Grid</span>
<button className="snap-select" onClick={() => onSnapOpenChange((value) => !value)}>
{snap}
<ChevronDown size={12} fill="currentColor" />
</button>
{snapOpen ? (
<div className="snap-menu">
{gridSizes.map((size) => (
<button
key={size}
className={size === snap ? "selected" : ""}
onClick={() => {
onSnapChange(size);
onSnapOpenChange(false);
}}
>
{size}
</button>
))}
</div>
) : null}
</div>
);
}
type RangePropertyConfig = {
type?: "range";
label: string;
value: number;
min: number;
max: number;
step?: number;
onChange: (value: number) => void;
};
type TextPropertyConfig = {
type: "text";
label: string;
value: string;
onChange: (value: string) => void;
};
type SelectPropertyConfig = {
type: "select";
label: string;
value: string;
options: string[];
onChange: (value: string) => void;
};
type ShapePropertyConfig = RangePropertyConfig | TextPropertyConfig | SelectPropertyConfig;
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";
}
function formatPanelNumber(value: number) {
return (Math.abs(value) < 0.005 ? 0 : value).toFixed(2);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: (patch: Partial<WorkplaneShape>) => void): ShapePropertyConfig[] {
const width = shapeWidth(shape);
const depth = shapeDepth(shape);
const setWidth = (value: number) => onUpdate({ width: value, size: resizedShapeSize(value, depth) });
const setDepth = (value: number) => onUpdate({ depth: value, size: resizedShapeSize(width, value) });
const setConeWidth = (value: number) => onUpdate({ width: value, baseRadius: value / 2, size: resizedShapeSize(value, depth) });
const setBaseRadius = (value: number) => onUpdate({ baseRadius: value, width: value * 2, depth: value * 2, size: value * 2 });
if (shape.kind === "box") {
return [
{ label: "Radius", value: shape.radius ?? 0, min: 0, max: 10, onChange: (radius) => onUpdate({ radius }) },
{ label: "Steps", value: shape.steps ?? 10, min: 1, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "cylinder") {
return [
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 10, onChange: (bevel) => onUpdate({ bevel }) },
{ label: "Segments", value: shape.segments ?? 1, min: 1, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "sphere") {
return [
{ label: "Steps", value: shape.steps ?? 24, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "halfSphere") {
return [
{ label: "Steps", value: shape.steps ?? 32, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "cone") {
return [
{ label: "Top Radius", value: shape.topRadius ?? 0, min: 0, max: 40, onChange: (topRadius) => onUpdate({ topRadius }) },
{ label: "Base Radius", value: shape.baseRadius ?? width / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setConeWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
];
}
if (shape.kind === "pyramid") {
return [
{ label: "Sides", value: shape.sides ?? 4, min: 3, max: 24, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "roundRoof") {
return [
{ label: "Sides", value: shape.sides ?? 64, min: 4, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "tube" || shape.kind === "ring") {
return [
{ label: "Thickness", value: shape.bevel ?? 4, min: 0.5, max: 20, onChange: (bevel) => onUpdate({ bevel }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "text") {
return [
{
type: "text",
label: "Text",
value: shape.text ?? "TEXT",
onChange: (text) => {
const nextText = text.slice(0, 24) || " ";
const nextWidth = clamp(Math.max(46, nextText.length * 19), 46, 260);
onUpdate({ text: nextText, width: nextWidth, size: nextWidth });
},
},
{ type: "select", label: "Font", value: shape.font ?? "Multilanguage", options: textFontOptions, onChange: (font) => onUpdate({ font }) },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 40, onChange: (height) => onUpdate({ height }) },
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 8, onChange: (bevel) => onUpdate({ bevel }) },
{ label: "Segments", value: shape.segments ?? 0, min: 0, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
];
}
return [
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange }: RangePropertyConfig & { disabled?: boolean }) {
const safeValue = clamp(value, min, max);
const position = ((safeValue - min) / Math.max(1, max - min)) * 100;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatPanelNumber(safeValue));
const commitDraft = () => {
const next = Number(draft);
onChange(clamp(Number.isFinite(next) ? next : safeValue, min, max));
setEditing(false);
};
return (
<label className="range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
<span>{label}</span>
<div className="range-control">
{editing ? (
<input
className="range-value-input"
type="number"
min={min}
max={max}
step={step}
value={draft}
autoFocus
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.currentTarget.blur();
} else if (event.key === "Escape") {
setDraft(formatPanelNumber(safeValue));
setEditing(false);
}
}}
/>
) : (
<output
onDoubleClick={(event) => {
if (disabled) {
return;
}
event.preventDefault();
setDraft(formatPanelNumber(safeValue));
setEditing(true);
}}
>
{formatPanelNumber(safeValue)}
</output>
)}
<input
type="range"
min={min}
max={max}
step={step}
value={safeValue}
disabled={disabled}
onChange={(event) => {
const next = Number(event.currentTarget.value);
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
}}
/>
</div>
</label>
);
}
function TextProperty({ label, value, disabled, onChange }: TextPropertyConfig & { disabled?: boolean }) {
return (
<label className="text-property">
<span>{label}</span>
<input
type="text"
value={value}
disabled={disabled}
maxLength={24}
spellCheck={false}
onChange={(event) => onChange(event.currentTarget.value)}
/>
</label>
);
}
function SelectProperty({ label, value, options, disabled, onChange }: SelectPropertyConfig & { disabled?: boolean }) {
return (
<label className="select-property">
<span>{label}</span>
<select value={value} disabled={disabled} onChange={(event) => onChange(event.currentTarget.value)}>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</label>
);
}
function DimensionInput({
label,
value,
min,
max,
step = 0.01,
unit = "mm",
onChange,
}: {
label: string;
value: number;
min: number;
max: number;
step?: number;
unit?: string;
onChange: (value: number) => void;
}) {
return (
<label className="dimension-input">
<span>{label}</span>
<input
type="number"
min={min}
max={max}
step={step}
value={formatPanelNumber(value)}
onChange={(event) => {
const next = Number(event.currentTarget.value);
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
}}
/>
<span>{unit}</span>
</label>
);
}
function WorkspaceSettingsModal({
workspace,
snap,
onWorkspaceChange,
onSnapChange,
onClose,
}: {
workspace: WorkspaceSettings;
snap: GridSize;
onWorkspaceChange: (next: WorkspaceSettings) => void;
onSnapChange: (next: GridSize) => void;
onClose: () => void;
}) {
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => onWorkspaceChange({ ...workspace, ...patch });
const setDimension = (key: "width" | "depth", value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKSPACE[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
};
const setWorkspaceSizePreset = (sizePreset: string) => {
const preset = workspaceSizePresets.find((entry) => entry.label === sizePreset);
if (!preset || sizePreset === "Custom") {
patchWorkspace({ sizePreset: "Custom" });
return;
}
patchWorkspace({ sizePreset, width: preset.width, depth: preset.depth });
};
const setGridBlockPreset = (gridBlockPreset: string) => {
patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) });
};
const setGridBlockSize = (value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
};
return (
<div className="workspace-modal" role="dialog" aria-modal="true" aria-label="Workspace settings">
<div className="workspace-modal-card" onPointerDown={(event) => event.stopPropagation()}>
<header className="workspace-modal-header">
<strong>Workspace settings</strong>
<button aria-label="Close settings" onClick={onClose}>
<X size={18} />
</button>
</header>
<div className="workspace-modal-body">
<div className="workspace-row">
<span>Background color</span>
<button
className="workspace-color-button"
style={{ "--workspace-bg": workspace.background } as CSSProperties}
aria-label="Background color"
onClick={() => patchWorkspace({ background: workspace.background === "#f8fbfc" ? "#eaf7fb" : "#f8fbfc" })}
/>
</div>
<WorkspaceToggle label="Show shadows" checked={workspace.showShadows} onChange={(showShadows) => patchWorkspace({ showShadows })} />
<WorkspaceToggle label="Show grid" checked={workspace.showGrid} onChange={(showGrid) => patchWorkspace({ showGrid })} />
<WorkspaceToggle
label="Cruise when adding new shapes"
checked={workspace.cruiseShapes}
onChange={(cruiseShapes) => patchWorkspace({ cruiseShapes })}
/>
<label className="workspace-range">
<span>Zoom speed</span>
<input
type="range"
min={1}
max={10}
value={workspace.zoomSpeed}
onChange={(event) => patchWorkspace({ zoomSpeed: Number(event.currentTarget.value) })}
/>
<small>
<span>Slow</span>
<span>Fast</span>
</small>
</label>
<WorkspaceSelect
label="Units"
value={workspace.units}
options={["Metric (Default)", "Imperial", "Bricks"]}
onChange={(units) => patchWorkspace({ units })}
/>
<WorkspaceSelect
label="Scale"
value={workspace.scale}
options={["1:1 (millimeters)", "1:10 (centimeters)", "1:100 (meters)", "1:1000 (meters)"]}
onChange={(scale) => patchWorkspace({ scale })}
/>
<WorkspaceSelect label="Snap Grid" value={snap} options={gridSizes} onChange={(next) => onSnapChange(next as GridSize)} />
<WorkspaceSelect
label="Workplane size"
value={workspace.sizePreset}
options={workspaceSizePresets.map((preset) => preset.label)}
onChange={setWorkspaceSizePreset}
/>
<div className="workspace-dimensions">
<label>
<span>Width</span>
<input
type="number"
value={workspace.width.toFixed(2)}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => setDimension("width", event.currentTarget.value)}
/>
</label>
<label>
<span>Length</span>
<input
type="number"
value={workspace.depth.toFixed(2)}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => setDimension("depth", event.currentTarget.value)}
/>
</label>
</div>
<WorkspaceSelect label="Grid block size" value={workspace.gridBlockPreset} options={gridBlockPresets} onChange={setGridBlockPreset} />
{workspace.gridBlockPreset === "Custom" ? (
<div className="workspace-dimensions workspace-grid-dimensions">
<label>
<span>Block size</span>
<input
type="number"
value={workspace.gridBlockSize.toFixed(2)}
min={MIN_GRID_BLOCK_SIZE}
max={MAX_GRID_BLOCK_SIZE}
step={0.5}
onChange={(event) => setGridBlockSize(event.currentTarget.value)}
/>
</label>
</div>
) : null}
<button className="make-default-button" onClick={() => onWorkspaceChange(DEFAULT_WORKSPACE)}>
Make default
</button>
</div>
</div>
<button className="workspace-modal-backdrop" aria-label="Close settings" onClick={onClose} />
</div>
);
}
function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
return (
<label className="workspace-toggle">
<span>{label}</span>
<input type="checkbox" checked={checked} onChange={(event) => onChange(event.currentTarget.checked)} />
</label>
);
}
function WorkspaceSelect({
label,
value,
options,
onChange,
}: {
label: string;
value: string;
options: readonly string[];
onChange: (value: string) => void;
}) {
return (
<label className="workspace-select">
<span>{label}</span>
<select value={value} onChange={(event) => onChange(event.currentTarget.value)}>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</label>
);
}
function createThreeScene(host: HTMLDivElement): ThreeState {
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance", preserveDrawingBuffer: shouldPreserveDrawingBufferForLocalAutomation() });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
@@ -3995,22 +3342,6 @@ function createRotateArc(center: THREE.Vector3, radius: number, start: number, e
return new THREE.Line(new THREE.BufferGeometry().setFromPoints(points), material);
}
function shapeWidth(shape: WorkplaneShape) {
return shape.width ?? shape.size;
}
function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size;
}
function mirrorSign(value?: boolean) {
return value ? -1 : 1;
}
function mirroredAxisCount(shape: WorkplaneShape) {
return [shape.mirrorX, shape.mirrorY, shape.mirrorZ].filter(Boolean).length;
}
function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureReady?: () => void) {
const group = new THREE.Group();
group.name = shape.name;
@@ -4118,12 +3449,6 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
case "icosahedron":
addMesh(group, new THREE.IcosahedronGeometry(size / 2, 1), material, shape);
break;
case "star":
addMesh(group, createExtrudedShapeGeometry(createStarShape(size / 2), height), material, shape);
break;
case "heart":
addMesh(group, createExtrudedShapeGeometry(createHeartShape(size * 0.95), height), material, shape);
break;
case "text":
addTextShape(group, material, shape);
break;
@@ -4528,41 +3853,6 @@ function createHalfSphereGeometry(width: number, height: number, depth: number,
return geometry;
}
function createExtrudedShapeGeometry(shape: THREE.Shape, height: number) {
const geometry = new THREE.ExtrudeGeometry(shape, { depth: height, bevelEnabled: false, steps: 1 });
geometry.rotateX(-Math.PI / 2);
return geometry;
}
function createStarShape(radius: number) {
const shape = new THREE.Shape();
const inner = radius * 0.44;
for (let i = 0; i < 10; i += 1) {
const angle = -Math.PI / 2 + (i * Math.PI) / 5;
const r = i % 2 === 0 ? radius : inner;
const x = Math.cos(angle) * r;
const y = Math.sin(angle) * r;
if (i === 0) {
shape.moveTo(x, y);
} else {
shape.lineTo(x, y);
}
}
shape.closePath();
return shape;
}
function createHeartShape(size: number) {
const s = size / 24;
const shape = new THREE.Shape();
shape.moveTo(0, -9 * s);
shape.bezierCurveTo(-13 * s, -1 * s, -12 * s, 8 * s, -5 * s, 8 * s);
shape.bezierCurveTo(-2 * s, 8 * s, 0, 5 * s, 0, 3 * s);
shape.bezierCurveTo(0, 5 * s, 2 * s, 8 * s, 5 * s, 8 * s);
shape.bezierCurveTo(12 * s, 8 * s, 13 * s, -1 * s, 0, -9 * s);
return shape;
}
function disposeChildren(group: THREE.Group) {
while (group.children.length > 0) {
const child = group.children.pop();
@@ -0,0 +1,463 @@
"use client";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen } from "lucide-react";
import { useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { ToolbarHideSelectedIcon } from "@/components/icons";
import { fallbackSolidColor, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { GridSize, WorkplaneShape } from "@/types/sketchforge";
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
const MIN_SHAPE_SIZE = 0.01;
const SOLID_COLORS = [
"#d41721",
"#ff4b4b",
"#ff7a1a",
"#d97813",
"#f6a21a",
"#f2cf10",
"#f7e65a",
"#a8d642",
"#33983d",
"#1fb66d",
"#18b99a",
"#0098c7",
"#49c7ef",
"#3b82f6",
"#294c93",
"#5b5ce2",
"#6e2786",
"#9b3bd2",
"#c9009a",
"#f062b6",
"#8a5a2b",
"#b98254",
"#f2caa0",
"#ffffff",
"#cfd8df",
"#8a98a6",
"#4b5563",
"#111111",
];
const TEXT_FONT_OPTIONS = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
type RangePropertyConfig = {
type?: "range";
label: string;
value: number;
min: number;
max: number;
step?: number;
onChange: (value: number) => void;
};
type TextPropertyConfig = {
type: "text";
label: string;
value: string;
onChange: (value: string) => void;
};
type SelectPropertyConfig = {
type: "select";
label: string;
value: string;
options: string[];
onChange: (value: string) => void;
};
type ShapePropertyConfig = RangePropertyConfig | TextPropertyConfig | SelectPropertyConfig;
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function formatPanelNumber(value: number) {
return (Math.abs(value) < 0.005 ? 0 : value).toFixed(2);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: (patch: Partial<WorkplaneShape>) => void): ShapePropertyConfig[] {
const width = shapeWidth(shape);
const depth = shapeDepth(shape);
const setWidth = (value: number) => onUpdate({ width: value, size: resizedShapeSize(value, depth) });
const setDepth = (value: number) => onUpdate({ depth: value, size: resizedShapeSize(width, value) });
const setConeWidth = (value: number) => onUpdate({ width: value, baseRadius: value / 2, size: resizedShapeSize(value, depth) });
const setBaseRadius = (value: number) => {
const diameter = value * 2;
onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, depth) });
};
if (shape.kind === "box") {
return [
{ label: "Radius", value: shape.radius ?? 0, min: 0, max: 10, onChange: (radius) => onUpdate({ radius }) },
{ label: "Steps", value: shape.steps ?? 10, min: 1, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "cylinder") {
return [
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 10, onChange: (bevel) => onUpdate({ bevel }) },
{ label: "Segments", value: shape.segments ?? 1, min: 1, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "sphere") {
return [
{ label: "Steps", value: shape.steps ?? 24, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "halfSphere") {
return [
{ label: "Steps", value: shape.steps ?? 32, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "cone") {
return [
{ label: "Top Radius", value: shape.topRadius ?? 0, min: 0, max: 40, onChange: (topRadius) => onUpdate({ topRadius }) },
{ label: "Base Radius", value: shape.baseRadius ?? width / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setConeWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
];
}
if (shape.kind === "pyramid") {
return [
{ label: "Sides", value: shape.sides ?? 4, min: 3, max: 24, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "roundRoof") {
return [
{ label: "Sides", value: shape.sides ?? 64, min: 4, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "tube" || shape.kind === "ring") {
return [
{ label: "Thickness", value: shape.bevel ?? 4, min: 0.5, max: 20, onChange: (bevel) => onUpdate({ bevel }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
if (shape.kind === "text") {
return [
{
type: "text",
label: "Text",
value: shape.text ?? "TEXT",
onChange: (text) => {
const nextText = text.slice(0, 24) || " ";
const nextWidth = clamp(Math.max(46, nextText.length * 19), 46, 260);
onUpdate({ text: nextText, width: nextWidth, size: nextWidth });
},
},
{ type: "select", label: "Font", value: shape.font ?? "Multilanguage", options: TEXT_FONT_OPTIONS, onChange: (font) => onUpdate({ font }) },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 40, onChange: (height) => onUpdate({ height }) },
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 8, onChange: (bevel) => onUpdate({ bevel }) },
{ label: "Segments", value: shape.segments ?? 0, min: 0, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
];
}
return [
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
];
}
export function ShapeInspector({
shape,
snap,
snapOpen,
onUpdate,
onClose,
onSnapChange,
onSnapOpenChange,
}: {
shape: WorkplaneShape;
snap: GridSize;
snapOpen: boolean;
onUpdate: (patch: Partial<WorkplaneShape>) => void;
onClose: () => void;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
}) {
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
const properties = getShapeProperties(shape, onUpdate);
const [propertiesOpen, setPropertiesOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
return (
<aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header">
<button className="inspector-header-icon" aria-label="Close shape settings" onClick={onClose}>
<ChevronUp size={26} strokeWidth={2.8} />
</button>
<strong>{shape.name}</strong>
<div className="inspector-header-actions">
<button className={locked ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={locked ? "Unlock shape" : "Lock shape"} onClick={() => onUpdate({ locked: !locked })}>
{locked ? <LockKeyhole size={31} strokeWidth={2.4} /> : <LockKeyholeOpen size={31} strokeWidth={2.4} />}
</button>
<button className={shape.hidden ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={shape.hidden ? "Show shape" : "Hide shape"} onClick={() => onUpdate({ hidden: !shape.hidden })}>
<ToolbarHideSelectedIcon />
</button>
</div>
</div>
<div className="shape-state-card" role="group" aria-label="Shape mode">
<button
className={!shape.hole ? "active solid-choice" : "solid-choice"}
onClick={() => {
const wasHole = Boolean(shape.hole);
onUpdate({ hole: false, color: solidColor });
setColorOpen((open) => (wasHole ? false : !open));
}}
disabled={locked}
aria-pressed={!shape.hole}
aria-expanded={colorOpen}
>
<span className="large-solid-swatch" style={{ "--swatch": solidColor } as CSSProperties} />
<span>Solid</span>
</button>
<button
className={shape.hole ? "active hole-choice" : "hole-choice"}
onClick={() => {
onUpdate({ hole: true, color: "#b8c2cc" });
setColorOpen(false);
}}
disabled={locked}
aria-pressed={shape.hole}
>
<span className="large-hole-swatch" />
<span>Hole</span>
</button>
</div>
{colorOpen ? (
<div className="color-card" aria-label="Shape color">
<div className="color-card-header">
<span>Color</span>
<span className="color-value">{solidColor.toUpperCase()}</span>
</div>
<div className="color-grid">
{SOLID_COLORS.map((color) => (
<button
key={color}
className={solidColor.toLowerCase() === color.toLowerCase() && !shape.hole ? "selected" : ""}
type="button"
style={{ "--shape-swatch": color } as CSSProperties}
title={color.toUpperCase()}
aria-label={`Set color ${color}`}
disabled={locked}
onClick={() => {
onUpdate({ color, hole: false });
setColorOpen(false);
}}
/>
))}
<label className={locked ? "custom-color disabled" : "custom-color"} title="Custom color">
<input
type="color"
value={solidColor}
disabled={locked}
onChange={(event) => {
onUpdate({ color: event.target.value, hole: false });
setColorOpen(false);
}}
/>
<span>Custom</span>
</label>
</div>
</div>
) : null}
<div className="property-card">
<button
className="property-card-header"
type="button"
aria-expanded={propertiesOpen}
aria-controls={`properties-${shape.id}`}
onClick={() => setPropertiesOpen((open) => !open)}
>
<span>Properties</span>
<ChevronUp className={propertiesOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
</button>
{propertiesOpen ? (
<div className="property-list" id={`properties-${shape.id}`}>
{properties.map((property) => {
if (property.type === "text") {
return <TextProperty key={property.label} {...property} disabled={locked} />;
}
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={locked} />;
}
return <RangeProperty key={property.label} {...property} disabled={locked} />;
})}
</div>
) : null}
</div>
<div className="inspector-snap-dock">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
</div>
</aside>
);
}
export function SnapGridControl({
snap,
snapOpen,
onSnapChange,
onSnapOpenChange,
}: {
snap: GridSize;
snapOpen: boolean;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
}) {
return (
<div className="snap-row">
<span>Snap Grid</span>
<button className="snap-select" onClick={() => onSnapOpenChange((value) => !value)}>
{snap}
<ChevronDown size={12} fill="currentColor" />
</button>
{snapOpen ? (
<div className="snap-menu">
{GRID_SIZES.map((size) => (
<button
key={size}
className={size === snap ? "selected" : ""}
onClick={() => {
onSnapChange(size);
onSnapOpenChange(false);
}}
>
{size}
</button>
))}
</div>
) : null}
</div>
);
}
function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange }: RangePropertyConfig & { disabled?: boolean }) {
const safeValue = clamp(value, min, max);
const position = ((safeValue - min) / Math.max(1, max - min)) * 100;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatPanelNumber(safeValue));
const commitDraft = () => {
const next = Number(draft);
onChange(clamp(Number.isFinite(next) ? next : safeValue, min, max));
setEditing(false);
};
return (
<label className="range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
<span>{label}</span>
<div className="range-control">
{editing ? (
<input
className="range-value-input"
type="number"
min={min}
max={max}
step={step}
value={draft}
autoFocus
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.currentTarget.blur();
} else if (event.key === "Escape") {
setDraft(formatPanelNumber(safeValue));
setEditing(false);
}
}}
/>
) : (
<output
onDoubleClick={(event) => {
if (disabled) {
return;
}
event.preventDefault();
setDraft(formatPanelNumber(safeValue));
setEditing(true);
}}
>
{formatPanelNumber(safeValue)}
</output>
)}
<input
type="range"
min={min}
max={max}
step={step}
value={safeValue}
disabled={disabled}
onChange={(event) => {
const next = Number(event.currentTarget.value);
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
}}
/>
</div>
</label>
);
}
function TextProperty({ label, value, disabled, onChange }: TextPropertyConfig & { disabled?: boolean }) {
return (
<label className="text-property">
<span>{label}</span>
<input
type="text"
value={value}
disabled={disabled}
maxLength={24}
spellCheck={false}
onChange={(event) => onChange(event.currentTarget.value)}
/>
</label>
);
}
function SelectProperty({ label, value, options, disabled, onChange }: SelectPropertyConfig & { disabled?: boolean }) {
return (
<label className="select-property">
<span>{label}</span>
<select value={value} disabled={disabled} onChange={(event) => onChange(event.currentTarget.value)}>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</label>
);
}
@@ -102,7 +102,7 @@ export function TransformOverlay({
<line className="rotation-zero-line" x1="0" y1="0" x2="0" y2="-92" />
<line className="rotation-current-line" x1="0" y1="0" x2={activeLine.x} y2={activeLine.y} />
<text className="rotation-zero-label" x="0" y="-75">
0Β°
0&deg;
</text>
</g>
</svg>
@@ -173,7 +173,7 @@ export function TransformOverlay({
}
}}
/>
<span>Β°</span>
<span>&deg;</span>
</label>
) : null}
{box.handles.map((handle) => (
@@ -0,0 +1,216 @@
"use client";
import { X } from "lucide-react";
import type { CSSProperties } from "react";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
type WorkspaceSettings = WorkplaneWorkspaceSettings;
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
const MIN_WORKSPACE_SIZE = 60;
const MAX_WORKSPACE_SIZE = 2000;
const MIN_GRID_BLOCK_SIZE = 1;
const MAX_GRID_BLOCK_SIZE = 200;
const WORKSPACE_SIZE_PRESETS = [
{ label: "200 x 200 mm", width: 200, depth: 200 },
{ label: "300 x 300 mm", width: 300, depth: 300 },
{ label: "500 x 500 mm", width: 500, depth: 500 },
{ label: "1000 x 1000 mm", width: 1000, depth: 1000 },
{ label: "2000 x 2000 mm", width: 2000, depth: 2000 },
{ label: "Custom", width: 200, depth: 200 },
];
const GRID_BLOCK_PRESETS = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const;
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function gridBlockSizeForPreset(preset: string, fallback: number) {
if (preset === "Custom") {
return clamp(fallback, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
}
return clamp(Number.parseFloat(preset) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
}
export function WorkspaceSettingsModal({
workspace,
snap,
onWorkspaceChange,
onSnapChange,
onClose,
}: {
workspace: WorkspaceSettings;
snap: GridSize;
onWorkspaceChange: (next: WorkspaceSettings) => void;
onSnapChange: (next: GridSize) => void;
onClose: () => void;
}) {
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => onWorkspaceChange({ ...workspace, ...patch });
const setDimension = (key: "width" | "depth", value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
};
const setWorkspaceSizePreset = (sizePreset: string) => {
const preset = WORKSPACE_SIZE_PRESETS.find((entry) => entry.label === sizePreset);
if (!preset || sizePreset === "Custom") {
patchWorkspace({ sizePreset: "Custom" });
return;
}
patchWorkspace({ sizePreset, width: preset.width, depth: preset.depth });
};
const setGridBlockPreset = (gridBlockPreset: string) => {
patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) });
};
const setGridBlockSize = (value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
};
return (
<div className="workspace-modal" role="dialog" aria-modal="true" aria-label="Workspace settings">
<div className="workspace-modal-card" onPointerDown={(event) => event.stopPropagation()}>
<header className="workspace-modal-header">
<strong>Workspace settings</strong>
<button aria-label="Close settings" onClick={onClose}>
<X size={18} />
</button>
</header>
<div className="workspace-modal-body">
<div className="workspace-row">
<span>Background color</span>
<button
className="workspace-color-button"
style={{ "--workspace-bg": workspace.background } as CSSProperties}
aria-label="Background color"
onClick={() => patchWorkspace({ background: workspace.background === "#f8fbfc" ? "#eaf7fb" : "#f8fbfc" })}
/>
</div>
<WorkspaceToggle label="Show shadows" checked={workspace.showShadows} onChange={(showShadows) => patchWorkspace({ showShadows })} />
<WorkspaceToggle label="Show grid" checked={workspace.showGrid} onChange={(showGrid) => patchWorkspace({ showGrid })} />
<WorkspaceToggle
label="Cruise when adding new shapes"
checked={workspace.cruiseShapes}
onChange={(cruiseShapes) => patchWorkspace({ cruiseShapes })}
/>
<label className="workspace-range">
<span>Zoom speed</span>
<input
type="range"
min={1}
max={10}
value={workspace.zoomSpeed}
onChange={(event) => patchWorkspace({ zoomSpeed: Number(event.currentTarget.value) })}
/>
<small>
<span>Slow</span>
<span>Fast</span>
</small>
</label>
<WorkspaceSelect
label="Units"
value={workspace.units}
options={["Metric (Default)", "Imperial", "Bricks"]}
onChange={(units) => patchWorkspace({ units })}
/>
<WorkspaceSelect
label="Scale"
value={workspace.scale}
options={["1:1 (millimeters)", "1:10 (centimeters)", "1:100 (meters)", "1:1000 (meters)"]}
onChange={(scale) => patchWorkspace({ scale })}
/>
<WorkspaceSelect label="Snap Grid" value={snap} options={GRID_SIZES} onChange={(next) => onSnapChange(next as GridSize)} />
<WorkspaceSelect
label="Workplane size"
value={workspace.sizePreset}
options={WORKSPACE_SIZE_PRESETS.map((preset) => preset.label)}
onChange={setWorkspaceSizePreset}
/>
<div className="workspace-dimensions">
<label>
<span>Width</span>
<input
type="number"
value={workspace.width.toFixed(2)}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => setDimension("width", event.currentTarget.value)}
/>
</label>
<label>
<span>Length</span>
<input
type="number"
value={workspace.depth.toFixed(2)}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => setDimension("depth", event.currentTarget.value)}
/>
</label>
</div>
<WorkspaceSelect label="Grid block size" value={workspace.gridBlockPreset} options={GRID_BLOCK_PRESETS} onChange={setGridBlockPreset} />
{workspace.gridBlockPreset === "Custom" ? (
<div className="workspace-dimensions workspace-grid-dimensions">
<label>
<span>Block size</span>
<input
type="number"
value={workspace.gridBlockSize.toFixed(2)}
min={MIN_GRID_BLOCK_SIZE}
max={MAX_GRID_BLOCK_SIZE}
step={0.5}
onChange={(event) => setGridBlockSize(event.currentTarget.value)}
/>
</label>
</div>
) : null}
<button className="make-default-button" onClick={() => onWorkspaceChange(DEFAULT_WORKPLANE_WORKSPACE)}>
Make default
</button>
</div>
</div>
<button className="workspace-modal-backdrop" aria-label="Close settings" onClick={onClose} />
</div>
);
}
function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
return (
<label className="workspace-toggle">
<span>{label}</span>
<input type="checkbox" checked={checked} onChange={(event) => onChange(event.currentTarget.checked)} />
</label>
);
}
function WorkspaceSelect({
label,
value,
options,
onChange,
}: {
label: string;
value: string;
options: readonly string[];
onChange: (value: string) => void;
}) {
return (
<label className="workspace-select">
<span>{label}</span>
<select value={value} onChange={(event) => onChange(event.currentTarget.value)}>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</label>
);
}