feat: improve shape tools and project previews

This commit is contained in:
Formsmith746
2026-08-28 13:24:32 +03:00
parent 2486b998c8
commit 34528e6393
33 changed files with 2071 additions and 343 deletions
+272 -48
View File
@@ -65,6 +65,7 @@ import {
serializeShapesForSync,
shapeDepth,
shapeHasTaper,
shapeTransformShouldRemainEditable,
shapeTaperScaleAt,
shapeWidth,
withHoleMode,
@@ -88,6 +89,8 @@ import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap
import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
import { exportMeshesToObj } from "@/lib/objExport";
import { rotateSketchPoints, selectedClosedSketchPoints } from "@/lib/sketchRotation";
import { PROJECT_THUMBNAIL_IDLE_MS, projectThumbnailSceneChanged, type ProjectThumbnailSceneKey } from "@/lib/projectThumbnail";
import { importedShapeFromObj } from "@/lib/objImport";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
@@ -113,7 +116,8 @@ import {
} from "@/lib/placementWorkplane";
import { placeSketchExtrusion } from "@/lib/sketchPlacement";
import {
SKETCHFORGE_MCP_POLL_MS,
SKETCHFORGE_MCP_HEARTBEAT_MS,
SKETCHFORGE_MCP_POLL_RETRY_MS,
SKETCHFORGE_MCP_ROUTE,
type SketchForgeMcpCommand,
type SketchForgeMcpSceneSummary,
@@ -2375,10 +2379,9 @@ function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimiti
}
function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
// Rotation is a non-destructive transform for editable text. Baking it would
// change the shape to `kind: "mesh"`, hiding the Text and Font controls even
// though the user never grouped or otherwise converted the object.
if (shape.kind === "text" || !shapeHasTransformToBake(shape)) {
// Text and groups must retain their editable source data across transforms.
// Baking a group would discard groupedShapes and make Ungroup unavailable.
if (shapeTransformShouldRemainEditable(shape) || !shapeHasTransformToBake(shape)) {
return shape;
}
@@ -5387,11 +5390,14 @@ export function SketchForgeEditor({
onProjectShapesChange,
onProjectSnapshot,
onProjectWorkspaceChange,
onProjectNameChange,
onShowProjectNameInToolbarChange,
projectId,
projectName = "SketchForge design",
projectCreatedAt = Date.now(),
projectModifiedAt = Date.now(),
projectRevision = 0,
showProjectNameInToolbar = true,
sharedProjectsEnabled = false,
challengeTutorial = null,
onChallengeTutorialFinish,
@@ -5409,7 +5415,7 @@ export function SketchForgeEditor({
initialPlacementWorkplane?: PlacementWorkplane;
onHome?: () => void;
onOpenSkfProjectFile?: (file: File) => Promise<{ ok: boolean; message: string } | void> | { ok: boolean; message: string } | void;
onSaveSharedProject?: (request: { exportName: string; bytes: Uint8Array }) => Promise<string>;
onSaveSharedProject?: (request: { exportName: string; bytes: Uint8Array; thumbnailDataUrl: string }) => Promise<string>;
onProjectShapesChange?: (snapshot: {
projectId: string;
shapes: WorkplaneShape[];
@@ -5424,7 +5430,9 @@ export function SketchForgeEditor({
placementWorkplane: PlacementWorkplane;
sketchPlacementWorkplane: PlacementWorkplane;
}) => void;
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void;
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }, signal?: AbortSignal) => Promise<void> | void;
onProjectNameChange?: (name: string) => void;
onShowProjectNameInToolbarChange?: (show: boolean) => void;
onProjectWorkspaceChange?: (snapshot: {
projectId: string;
workspace: WorkplaneWorkspaceSettings;
@@ -5438,6 +5446,7 @@ export function SketchForgeEditor({
projectCreatedAt?: number;
projectModifiedAt?: number;
projectRevision?: number;
showProjectNameInToolbar?: boolean;
sharedProjectsEnabled?: boolean;
challengeTutorial?: ChallengeTutorialId | null;
onChallengeTutorialFinish?: () => void;
@@ -5495,6 +5504,7 @@ export function SketchForgeEditor({
const lastProjectShapesEchoRef = useRef<string | null>(null);
const lastProjectIdRef = useRef<string | null>(null);
const projectSnapshotRunRef = useRef(0);
const lastProjectSnapshotRef = useRef<ProjectThumbnailSceneKey | null>(null);
const shapesRef = useRef(shapes);
const projectAssetsRef = useRef(projectAssets);
const selectedIdsRef = useRef(selectedIds);
@@ -5947,28 +5957,52 @@ export function SketchForgeEditor({
);
useEffect(() => {
const runId = projectSnapshotRunRef.current + 1;
projectSnapshotRunRef.current = runId;
if (!projectId || !onProjectSnapshot || typeof window === "undefined") {
return;
}
const sceneKey = { projectId, fingerprint: projectShapesFingerprint(shapes) };
if (lastProjectSnapshotRef.current?.projectId !== projectId || projectHydratingRef.current) {
lastProjectSnapshotRef.current = sceneKey;
return;
}
if (!projectThumbnailSceneChanged(lastProjectSnapshotRef.current, sceneKey)) {
return;
}
if (projectInteractionActive) {
return;
}
const runId = projectSnapshotRunRef.current + 1;
projectSnapshotRunRef.current = runId;
let stopped = false;
let uploadController: AbortController | null = null;
const capture = async () => {
if (projectSnapshotRunRef.current !== runId) {
if (stopped || projectSnapshotRunRef.current !== runId) {
return true;
}
const image = window.sketchforgeCaptureCanvasAsync
? await window.sketchforgeCaptureCanvasAsync()
: window.sketchforgeCaptureCanvas?.() ?? "";
if (projectSnapshotRunRef.current !== runId) {
if (stopped || projectSnapshotRunRef.current !== runId) {
return true;
}
if (image && image.length > 100) {
onProjectSnapshot({ image, projectId, shapes: shapes.length });
return true;
const controller = new AbortController();
uploadController = controller;
try {
await onProjectSnapshot({ image, projectId, shapes: shapes.length }, controller.signal);
if (!stopped && projectSnapshotRunRef.current === runId && !controller.signal.aborted) {
lastProjectSnapshotRef.current = sceneKey;
}
return true;
} catch (error) {
if (controller.signal.aborted || (error instanceof DOMException && error.name === "AbortError")) {
return true;
}
return false;
} finally {
if (uploadController === controller) uploadController = null;
}
}
return false;
};
@@ -5988,8 +6022,10 @@ export function SketchForgeEditor({
} else {
runCapture();
}
}, 850);
}, PROJECT_THUMBNAIL_IDLE_MS);
return () => {
stopped = true;
uploadController?.abort();
window.clearTimeout(captureTimer);
if (retryTimer !== null) window.clearTimeout(retryTimer);
if (idleId !== null && "cancelIdleCallback" in window) window.cancelIdleCallback(idleId);
@@ -6558,7 +6594,7 @@ export function SketchForgeEditor({
const label = primitive[0]!.toUpperCase() + primitive.slice(1);
commitSketchProfile(next, `${label} added to sketch`);
setSketchActivePointId(null);
setSketchSelection({ kind: "multiple", pointIds: points.map((point) => point.id), segmentIds: segments.map((segment) => segment.id), imageIds: [] });
setSketchSelection(null);
setSketchTool("select");
},
[commitSketchProfile, sketchProfile],
@@ -6626,6 +6662,10 @@ export function SketchForgeEditor({
const updateSketchImage = useCallback((id: string, patch: Partial<SketchImage>, message = "Sketch image updated") => {
const image = (sketchProfile.images ?? []).find((entry) => entry.id === id);
if (!image) return;
if (image.locked && patch.locked !== false) {
setNotice("Unlock the sketch image with L before editing it");
return;
}
commitSketchProfile({
...sketchProfile,
images: (sketchProfile.images ?? []).map((entry) => entry.id === id ? { ...entry, ...patch } : entry),
@@ -6635,7 +6675,12 @@ export function SketchForgeEditor({
}, [commitSketchProfile, sketchProfile]);
const deleteSketchImage = useCallback((id: string) => {
if (!(sketchProfile.images ?? []).some((image) => image.id === id)) return;
const image = (sketchProfile.images ?? []).find((entry) => entry.id === id);
if (!image) return;
if (image.locked) {
setNotice("Unlock the sketch image with L before deleting it");
return;
}
commitSketchProfile({
...sketchProfile,
images: (sketchProfile.images ?? []).filter((image) => image.id !== id),
@@ -6665,6 +6710,7 @@ export function SketchForgeEditor({
depth: dimensions.depth,
opacity: 0.55,
lockAspect: true,
locked: false,
};
commitSketchProfile({ ...sketchProfile, images: [...(sketchProfile.images ?? []), image] }, `Added ${file.name} to the sketch`);
setSketchSelection({ kind: "image", id: image.id });
@@ -6674,6 +6720,23 @@ export function SketchForgeEditor({
}
}, [commitSketchProfile, sketchActive, sketchProfile, sketchTool]);
const toggleSelectedSketchImageLock = useCallback(() => {
if (sketchSelection?.kind !== "image") {
setNotice("Select a sketch image to lock or unlock");
return;
}
const image = (sketchProfile.images ?? []).find((entry) => entry.id === sketchSelection.id);
if (!image) {
setNotice("Select a sketch image to lock or unlock");
return;
}
updateSketchImage(
image.id,
{ locked: !image.locked },
image.locked ? "Sketch image unlocked" : "Sketch image locked",
);
}, [sketchProfile.images, sketchSelection, updateSketchImage]);
const deleteSelectedSketchEntity = useCallback(() => {
if (!sketchSelection) {
setNotice("Select a sketch point or segment to remove it");
@@ -6723,6 +6786,19 @@ export function SketchForgeEditor({
}, message);
}, [commitSketchProfile, sketchProfile]);
const rotateSelectedClosedSketch45 = useCallback(() => {
if (sketchSelection?.kind !== "multiple") {
setNotice("Select a closed sketch object to rotate");
return;
}
const selectedPoints = selectedClosedSketchPoints(sketchProfile, sketchSelection);
if (!selectedPoints) {
setNotice("Rotation is available only for closed sketch objects");
return;
}
transformSketchPoints(rotateSketchPoints(selectedPoints), "Rotated closed sketch selection by 45°");
}, [sketchProfile, sketchSelection, transformSketchPoints]);
const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => {
const next = cloneSketchProfile(sketchProfile);
const point = next.points.find((entry) => entry.id === id);
@@ -6873,7 +6949,7 @@ export function SketchForgeEditor({
const addShape = useCallback(
(asset: ShapeAsset, point?: PlacementPoint) => {
const shape = makeShapeFromAsset(asset);
const shape = makeShapeFromAsset(asset, undefined, workspaceSettingsRef.current.shapeCustomizations[asset.kind]);
const nextShape = {
...shape,
...placementPatchForNewShape(shape, placementWorkplane, point ?? placementWorkplane.origin),
@@ -8226,6 +8302,8 @@ export function SketchForgeEditor({
const identity = readMcpEditorIdentity();
let stopped = false;
let polling = false;
let pollAbortController: AbortController | null = null;
let pollRetryTimer: number | null = null;
const heartbeat = () => {
const projectInfo = projectInfoRef.current;
@@ -8265,12 +8343,16 @@ export function SketchForgeEditor({
const poll = async () => {
if (polling || stopped) return;
polling = true;
let retry = false;
pollAbortController = new AbortController();
try {
const response = await fetch(SKETCHFORGE_MCP_ROUTE, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "poll", editorId: identity.editorId }),
signal: pollAbortController.signal,
});
if (!response.ok) throw new Error(`SketchForge MCP poll returned HTTP ${response.status}`);
const payload = (await response.json().catch(() => null)) as { command?: SketchForgeMcpCommand | null } | null;
const command = payload?.command;
if (command) {
@@ -8281,23 +8363,35 @@ export function SketchForgeEditor({
submitResult(command.id, false, undefined, error instanceof Error ? error.message : String(error));
}
}
} catch {
} catch (error) {
// The local bridge may not exist while static builds or tests render the editor.
retry = !stopped && (!(error instanceof DOMException) || error.name !== "AbortError");
} finally {
pollAbortController = null;
polling = false;
if (!stopped) {
if (retry) {
pollRetryTimer = window.setTimeout(() => {
pollRetryTimer = null;
void poll();
}, SKETCHFORGE_MCP_POLL_RETRY_MS);
} else {
void poll();
}
}
}
};
heartbeat();
void poll();
const heartbeatTimer = window.setInterval(heartbeat, 1000);
const pollTimer = window.setInterval(() => void poll(), SKETCHFORGE_MCP_POLL_MS);
const heartbeatTimer = window.setInterval(heartbeat, SKETCHFORGE_MCP_HEARTBEAT_MS);
window.addEventListener("focus", heartbeat);
document.addEventListener("visibilitychange", heartbeat);
return () => {
stopped = true;
window.clearInterval(heartbeatTimer);
window.clearInterval(pollTimer);
if (pollRetryTimer !== null) window.clearTimeout(pollRetryTimer);
pollAbortController?.abort();
window.removeEventListener("focus", heartbeat);
document.removeEventListener("visibilitychange", heartbeat);
};
@@ -8543,10 +8637,16 @@ export function SketchForgeEditor({
setSkfExporting(true);
setNotice(target === "shared" ? "Packaging project for Docker shared storage…" : "Packaging editable project, history, and deduplicated assets…");
try {
const thumbnailDataUrl = target === "shared"
? await (window.sketchforgeCaptureCanvasAsync?.() ?? Promise.resolve(""))
: "";
if (target === "shared" && (!thumbnailDataUrl.startsWith("data:image/png;base64,") || thumbnailDataUrl.length <= 100)) {
throw new Error("Could not capture the current project preview");
}
const exportedHistory = editorHistoryForExport(historyRef.current, historyIndexRef.current, historyLimit);
const bytes = await exportSkfProject({
projectId: projectInfoRef.current.projectId,
projectName: exportName.trim() || projectName,
projectName,
createdAt: projectCreatedAt,
modifiedAt: projectModifiedAt,
shapes: shapesRef.current,
@@ -8560,7 +8660,7 @@ export function SketchForgeEditor({
sketchPlacementWorkplane: placementWorkplane,
});
if (target === "shared" && onSaveSharedProject) {
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes }));
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes, thumbnailDataUrl }));
} else {
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
const result = await downloadBlobFile(projectExportFileName(exportName, "skf"), new Blob([buffer], { type: SKF_MEDIA_TYPE }));
@@ -8864,6 +8964,12 @@ export function SketchForgeEditor({
} else if (shortcut && key === "y") {
event.preventDefault();
sketchRedo();
} else if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r")) {
event.preventDefault();
rotateSelectedClosedSketch45();
} else if (!shortcut && !event.altKey && (event.code === "KeyL" || key === "l")) {
event.preventDefault();
toggleSelectedSketchImageLock();
}
return;
}
@@ -8953,12 +9059,6 @@ export function SketchForgeEditor({
return;
}
if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r") && hasSelection) {
event.preventDefault();
rotateSelected45();
return;
}
const step = event.shiftKey ? 5 : 1;
if (shortcut && event.key === "ArrowUp") {
event.preventDefault();
@@ -8987,9 +9087,6 @@ export function SketchForgeEditor({
} else if (key === "s") {
event.preventDefault();
setSelectionHoleMode(false);
} else if (key === "l") {
event.preventDefault();
toggleAlignMode();
} else if (key === "m") {
event.preventDefault();
toggleMirrorMode();
@@ -9013,7 +9110,7 @@ export function SketchForgeEditor({
pasteShape,
raiseSelected,
redo,
rotateSelected45,
rotateSelectedClosedSketch45,
sketchActive,
sketchRedo,
sketchMeasurement,
@@ -9021,10 +9118,10 @@ export function SketchForgeEditor({
sketchUndo,
setSelectionHoleMode,
showHidden,
toggleAlignMode,
toggleHidden,
toggleMirrorMode,
toggleLocked,
toggleSelectedSketchImageLock,
toolbarMode,
undo,
ungroupSelected,
@@ -9034,6 +9131,9 @@ export function SketchForgeEditor({
<div className="sketchforge-editor">
<SecondaryToolbar
toolbarMode={toolbarMode}
projectName={projectName}
onProjectNameChange={onProjectNameChange}
showProjectNameInToolbar={showProjectNameInToolbar}
onToolbarModeChange={(mode) => {
setToolbarMode(mode);
setWorkplaneMode(false);
@@ -9161,6 +9261,8 @@ export function SketchForgeEditor({
initialSnap={snapGrid}
initialWorkspace={workspaceSettings}
workspaceSettingsKey={projectId ?? "local-workplane"}
showProjectNameInToolbar={showProjectNameInToolbar}
onShowProjectNameInToolbarChange={onShowProjectNameInToolbarChange}
onAddShape={addShape}
onAlignAnchorChange={chooseAlignAnchor}
onAlignPreview={previewAlignSelection}
@@ -9336,8 +9438,18 @@ function SketchReferenceIcon({ name }: { name: SketchReferenceIconName }) {
);
}
const sketchShapeMenuItems = [
{ primitive: "rectangle", label: "Rectangle", icon: SquareIcon },
{ primitive: "circle", label: "Circle", icon: CircleIcon },
{ primitive: "triangle", label: "Triangle", icon: TriangleIcon },
{ primitive: "hexagon", label: "Hexagon", icon: HexagonIcon },
] satisfies Array<{ primitive: SketchPrimitive; label: string; icon: typeof SquareIcon }>;
function SecondaryToolbar({
toolbarMode,
projectName,
onProjectNameChange,
showProjectNameInToolbar,
onToolbarModeChange,
alignMode,
canAlign,
@@ -9390,6 +9502,9 @@ function SecondaryToolbar({
onAddShape,
}: {
toolbarMode: ToolbarMode;
projectName: string;
onProjectNameChange?: (name: string) => void;
showProjectNameInToolbar: boolean;
onToolbarModeChange: (mode: ToolbarMode) => void;
alignMode: boolean;
canAlign: boolean;
@@ -9445,10 +9560,37 @@ function SecondaryToolbar({
const [sketchCreateOpen, setSketchCreateOpen] = useState(false);
const [visibilityOpen, setVisibilityOpen] = useState(false);
const [visibilityMenuPosition, setVisibilityMenuPosition] = useState({ top: 0, left: 0 });
const shapesMenuRef = useRef<HTMLDivElement>(null);
const sketchCreateMenuRef = useRef<HTMLDivElement>(null);
const visibilityMenuRef = useRef<HTMLDivElement>(null);
const touchShapeStartRef = useRef<{ id: string; x: number; y: number } | null>(null);
const suppressNextShapeClickRef = useRef(false);
const cancelProjectNameEditRef = useRef(false);
const projectNameFieldRef = useRef<HTMLLabelElement>(null);
const projectNameInputRef = useRef<HTMLInputElement>(null);
const [projectNameDraft, setProjectNameDraft] = useState(projectName);
useEffect(() => {
setProjectNameDraft(projectName);
}, [projectName]);
useEffect(() => {
const finishProjectNameEdit = (event: PointerEvent) => {
const input = projectNameInputRef.current;
if (input && document.activeElement === input && !projectNameFieldRef.current?.contains(event.target as Node)) {
input.blur();
}
};
document.addEventListener("pointerdown", finishProjectNameEdit, true);
return () => document.removeEventListener("pointerdown", finishProjectNameEdit, true);
}, []);
const commitProjectName = (value: string) => {
const nextName = value.trim().slice(0, 80);
if (!nextName) {
setProjectNameDraft(projectName);
return;
}
setProjectNameDraft(nextName);
if (nextName !== projectName) onProjectNameChange?.(nextName);
};
const selectToolbarMode = (mode: "geometry" | "sketch") => {
setShapesOpen(false);
setSketchCreateOpen(false);
@@ -9460,6 +9602,10 @@ function SecondaryToolbar({
onAddShape(shape);
setShapesOpen(false);
};
const addSketchShapeFromMenu = (primitive: SketchPrimitive) => {
onSketchPrimitive(primitive);
setShapesOpen(false);
};
const startSketch = (operation: SketchOperation) => {
setSketchCreateOpen(false);
onStartSketch(operation);
@@ -9481,7 +9627,23 @@ function SecondaryToolbar({
}, [sketchCreateOpen]);
useEffect(() => {
if (sketchActive) setSketchCreateOpen(false);
else setShapesOpen(false);
}, [sketchActive]);
useEffect(() => {
if (!shapesOpen) return;
const closeOnPointerDown = (event: PointerEvent) => {
if (!shapesMenuRef.current?.contains(event.target as Node)) setShapesOpen(false);
};
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") setShapesOpen(false);
};
window.addEventListener("pointerdown", closeOnPointerDown);
window.addEventListener("keydown", closeOnEscape);
return () => {
window.removeEventListener("pointerdown", closeOnPointerDown);
window.removeEventListener("keydown", closeOnEscape);
};
}, [shapesOpen]);
useEffect(() => {
if (!visibilityOpen) return;
const closeOnPointerDown = (event: PointerEvent) => {
@@ -9605,7 +9767,7 @@ function SecondaryToolbar({
<div className="toolbar-section-label">History</div>
<div className="toolbar-section-tools">{leftTools.slice(4).map(renderToolButton)}</div>
</div>
<div className="toolbar-section toolbar-shapes-section">
<div className="toolbar-section toolbar-shapes-section" ref={shapesMenuRef}>
<div className="toolbar-section-label">Shapes</div>
<div className="toolbar-section-tools">
<button
@@ -9692,7 +9854,35 @@ function SecondaryToolbar({
) : null}
</div>
</div>
<div className="toolbar-spacer" />
{showProjectNameInToolbar ? (
<div className="toolbar-spacer toolbar-project-name">
<label ref={projectNameFieldRef} className="toolbar-project-name-field" title="Rename project">
<input
ref={projectNameInputRef}
aria-label="Project name"
value={projectNameDraft}
maxLength={80}
spellCheck={false}
onChange={(event) => setProjectNameDraft(event.target.value)}
onBlur={(event) => {
if (cancelProjectNameEditRef.current) {
cancelProjectNameEditRef.current = false;
setProjectNameDraft(projectName);
return;
}
commitProjectName(event.currentTarget.value);
}}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
if (event.key === "Escape") {
cancelProjectNameEditRef.current = true;
event.currentTarget.blur();
}
}}
/>
</label>
</div>
) : <div className="toolbar-spacer" />}
<div className="tool-group right">
<div className="toolbar-section compact toolbar-visibility-section" ref={visibilityMenuRef}>
<div className="toolbar-section-label">Visibility</div>
@@ -9784,22 +9974,50 @@ function SecondaryToolbar({
</button>
</div>
</div>
<div className="toolbar-section sketch-shapes-section">
<div className="toolbar-section toolbar-shapes-section sketch-shapes-section" ref={shapesMenuRef}>
<div className="toolbar-section-label">Shapes</div>
<div className="toolbar-section-tools">
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Rectangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("rectangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "rectangle"); }}>
<SquareIcon size={25} strokeWidth={1.8} />
</button>
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Circle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("circle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "circle"); }}>
<CircleIcon size={25} strokeWidth={1.8} />
</button>
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Triangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("triangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "triangle"); }}>
<TriangleIcon size={25} strokeWidth={1.8} />
</button>
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Hexagon" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("hexagon")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "hexagon"); }}>
<HexagonIcon size={25} strokeWidth={1.8} />
<button
className={`shape-menu-trigger ${shapesOpen ? "active" : ""}`}
type="button"
aria-label="Add sketch shape"
aria-haspopup="menu"
aria-expanded={shapesOpen}
onClick={() => {
setSketchCreateOpen(false);
setVisibilityOpen(false);
setShapesOpen((open) => !open);
}}
>
<ToolbarShapeAddIcon />
</button>
</div>
{shapesOpen ? (
<div className="shape-menu-dropdown sketch-shape-menu-dropdown" role="menu" aria-label="Sketch shapes">
<div className="shape-menu-title">Sketch Shapes</div>
<div className="shape-menu-list">
{sketchShapeMenuItems.map(({ primitive, label, icon: Icon }) => (
<button
className="shape-menu-item sketch-primitive-source"
key={primitive}
type="button"
role="menuitem"
draggable
title={`Add ${label.toLowerCase()} at the sketch origin, or drag it onto the sketch`}
onClick={() => addSketchShapeFromMenu(primitive)}
onDragStart={(event) => {
event.dataTransfer.effectAllowed = "copy";
event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", primitive);
}}
onDragEnd={() => setShapesOpen(false)}
>
<Icon className="sketch-shape-menu-icon" aria-hidden="true" />
<span>{label}</span>
</button>
))}
</div>
</div>
) : null}
</div>
<div className="toolbar-section sketch-edit-section">
<div className="toolbar-section-label">Select</div>
@@ -9958,7 +10176,13 @@ function TopActionPanel({
}) {
const [exportFormat, setExportFormat] = useState<ExportFormat>("stl");
const [exportName, setExportName] = useState(projectName);
const previousProjectNameRef = useRef(projectName);
const [skfHistoryLimit, setSkfHistoryLimit] = useState<SkfHistoryLimit>("unlimited");
useEffect(() => {
const previousProjectName = previousProjectNameRef.current;
setExportName((current) => current === previousProjectName ? projectName : current);
previousProjectNameRef.current = projectName;
}, [projectName]);
const skfHistoryLimits: readonly SkfHistoryLimit[] = ["unlimited", 100, 50, 30];
const skfHistoryLimitIndex = skfHistoryLimits.indexOf(skfHistoryLimit);
const title =
@@ -66,7 +66,7 @@ export function SketchRevolvePreview({ positions }: { positions: number[] | null
return (
<aside className="sketch-revolve-preview" aria-label="Revolve 3D preview">
<div className="sketch-revolve-preview-title">3D preview</div>
{positions?.length ? <canvas ref={canvasRef} /> : <div className="sketch-revolve-preview-empty">Draw a profile left of the axis</div>}
{positions?.length ? <canvas ref={canvasRef} /> : <div className="sketch-revolve-preview-empty">Draw a closed profile left of the axis</div>}
</aside>
);
}
+31 -58
View File
@@ -1,6 +1,6 @@
"use client";
import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react";
import { ChevronUp, CornerDownRight, Home, Link, Link2Off, LockKeyhole, LockKeyholeOpen, Minus, Plus, Split, Trash2, Waves } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";
import { SnapGridControl } from "@/components/workplane/ShapeInspector";
import { SketchRevolvePreview } from "@/components/SketchRevolvePreview";
@@ -758,7 +758,7 @@ export function SketchWorkspace({
minZ: selectedImage.z - selectedImage.depth / 2,
maxZ: selectedImage.z + selectedImage.depth / 2,
} : null;
const imageResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedImage && selectedImageBounds ? [
const imageResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedImage && selectedImageBounds && !selectedImage.locked ? [
{ id: "nw", x: selectedImageBounds.minX, z: selectedImageBounds.minZ },
{ id: "n", x: selectedImage.x, z: selectedImageBounds.minZ },
{ id: "ne", x: selectedImageBounds.maxX, z: selectedImageBounds.minZ },
@@ -770,13 +770,9 @@ export function SketchWorkspace({
] : [];
const selectionResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedGeometryBounds ? [
{ id: "nw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.minZ },
{ id: "n", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.minZ },
{ id: "ne", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.minZ },
{ id: "e", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.cz },
{ id: "se", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.maxZ },
{ id: "s", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.maxZ },
{ id: "sw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.maxZ },
{ id: "w", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.cz },
] : [];
const referenceFootprints = useMemo(
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
@@ -839,6 +835,7 @@ export function SketchWorkspace({
<image
key={image.id}
data-sketch-entity="image"
className={image.locked ? "locked" : undefined}
aria-label={image.name}
href={image.dataUrl}
x={image.x - image.width / 2}
@@ -856,6 +853,8 @@ export function SketchWorkspace({
return;
}
if (event.button !== 0 || tool !== "select") return;
onSelectImage(image.id);
if (image.locked) return;
const point = pointFromEvent(event);
if (!point) return;
beginEntityDrag(event, {
@@ -903,29 +902,6 @@ export function SketchWorkspace({
<g className="sketch-profile-fills" pointerEvents="none">
{paths.some((path) => path.closed) ? <path d={paths.filter((path) => path.closed).map(pathData).join(" ")} /> : null}
</g>
<g className="sketch-profile-hit-targets" pointerEvents={tool === "select" ? "auto" : "none"}>
{paths.filter((path) => path.closed).map((path) => (
<path
key={`hit-${path.id}`}
data-sketch-entity="closed-profile"
d={pathData(path)}
onPointerDown={(event) => {
if (event.button === 1) {
beginPan(event);
return;
}
if (event.button !== 0 || tool !== "select") return;
const point = pointFromEvent(event);
if (!point) return;
const pointIds = path.points.map((entry) => entry.id);
const segmentIds = path.steps.map((step) => step.segment.id);
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
onSelectMany(pointIds, segmentIds, []);
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
}}
/>
))}
</g>
<g className="sketch-segments">
{displayProfile.segments.map((segment) => (
<path
@@ -959,16 +935,7 @@ export function SketchWorkspace({
}
}
else if (event.button === 0 && tool === "select" && point) {
const closedPath = paths.find((path) => path.closed && path.steps.some((step) => step.segment.id === segment.id));
if (!closedPath) {
onSelectSegment(segment.id);
return;
}
const pointIds = closedPath.points.map((entry) => entry.id);
const segmentIds = closedPath.steps.map((step) => step.segment.id);
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
onSelectMany(pointIds, segmentIds, []);
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
onSelectSegment(segment.id);
} else if (event.button === 0) onSelectSegment(segment.id);
}}
/>
@@ -1130,17 +1097,8 @@ export function SketchWorkspace({
} else if (tool === "erase" || tool === "refine") {
onDeletePoint(point.id);
} else if (event.button === 0 && tool === "select") {
const closedPath = paths.find((path) => path.closed && path.points.some((entry) => entry.id === point.id));
if (closedPath) {
const pointIds = closedPath.points.map((entry) => entry.id);
const segmentIds = closedPath.steps.map((step) => step.segment.id);
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
onSelectMany(pointIds, segmentIds, []);
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: { x: point.x, z: point.z }, current: { x: point.x, z: point.z }, startPoints });
} else {
onPointPress(point.id);
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
}
onPointPress(point.id);
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
} else if (event.button === 0) {
onPointPress(point.id);
}
@@ -1270,7 +1228,16 @@ function SketchImageInspector({
</button>
<strong>{image.name}</strong>
<div className="inspector-header-actions">
<button className="inspector-header-icon danger" type="button" aria-label="Delete sketch image" title="Delete image" onClick={onDelete}>
<button
className={image.locked ? "inspector-header-icon active" : "inspector-header-icon"}
type="button"
aria-label={image.locked ? "Unlock sketch image" : "Lock sketch image"}
title={`${image.locked ? "Unlock" : "Lock"} image (L)`}
onClick={() => onUpdate({ locked: !image.locked }, image.locked ? "Sketch image unlocked" : "Sketch image locked")}
>
{image.locked ? <LockKeyhole size={25} strokeWidth={2.2} /> : <LockKeyholeOpen size={25} strokeWidth={2.2} />}
</button>
<button className="inspector-header-icon danger" type="button" aria-label="Delete sketch image" title={image.locked ? "Unlock image before deleting" : "Delete image"} onClick={onDelete} disabled={image.locked}>
<Trash2 size={25} strokeWidth={2.2} />
</button>
</div>
@@ -1282,12 +1249,12 @@ function SketchImageInspector({
<div className="property-card">
<div className="property-card-header static"><span>Properties</span></div>
<div className="property-list">
<SketchImageRange label="Width" value={image.width} min={0.5} max={200} accuracy={accuracy} onChange={updateWidth} />
<SketchImageRange label="Height" value={image.depth} min={0.5} max={200} accuracy={accuracy} onChange={updateDepth} />
<SketchImageRange label="Opacity" value={(image.opacity ?? 0.55) * 100} min={5} max={100} accuracy={1} suffix="%" onChange={(opacity) => onUpdate({ opacity: opacity / 100 }, "Sketch image opacity updated")} />
<SketchImagePositionField label="Position X" value={image.x} accuracy={accuracy} onChange={(x) => onUpdate({ x }, "Sketch image moved")} />
<SketchImagePositionField label="Position Y" value={image.z} accuracy={accuracy} onChange={(z) => onUpdate({ z }, "Sketch image moved")} />
<button className={`sketch-image-aspect-toggle ${image.lockAspect !== false ? "active" : ""}`} type="button" onClick={() => onUpdate({ lockAspect: image.lockAspect === false }, "Image aspect ratio setting updated")}>
<SketchImageRange label="Width" value={image.width} min={0.5} max={200} accuracy={accuracy} disabled={image.locked} onChange={updateWidth} />
<SketchImageRange label="Height" value={image.depth} min={0.5} max={200} accuracy={accuracy} disabled={image.locked} onChange={updateDepth} />
<SketchImageRange label="Opacity" value={(image.opacity ?? 0.55) * 100} min={5} max={100} accuracy={1} suffix="%" disabled={image.locked} onChange={(opacity) => onUpdate({ opacity: opacity / 100 }, "Sketch image opacity updated")} />
<SketchImagePositionField label="Position X" value={image.x} accuracy={accuracy} disabled={image.locked} onChange={(x) => onUpdate({ x }, "Sketch image moved")} />
<SketchImagePositionField label="Position Y" value={image.z} accuracy={accuracy} disabled={image.locked} onChange={(z) => onUpdate({ z }, "Sketch image moved")} />
<button className={`sketch-image-aspect-toggle ${image.lockAspect !== false ? "active" : ""}`} type="button" disabled={image.locked} onClick={() => onUpdate({ lockAspect: image.lockAspect === false }, "Image aspect ratio setting updated")}>
{image.lockAspect !== false ? <Link size={17} /> : <Link2Off size={17} />}
<span>{image.lockAspect !== false ? "Aspect ratio locked" : "Aspect ratio unlocked"}</span>
</button>
@@ -1304,6 +1271,7 @@ function SketchImageRange({
max,
accuracy,
suffix = "mm",
disabled = false,
onChange,
}: {
label: string;
@@ -1312,6 +1280,7 @@ function SketchImageRange({
max: number;
accuracy: 1 | 2 | 3;
suffix?: string;
disabled?: boolean;
onChange: (value: number) => void;
}) {
const safeValue = clamp(Number.isFinite(value) ? value : min, min, max);
@@ -1331,13 +1300,14 @@ function SketchImageRange({
type="text"
inputMode="decimal"
value={draft}
disabled={disabled}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
/>
<span>{suffix}</span>
</div>
<input type="range" min={min} max={max} step={accuracy === 1 ? 0.1 : 0.01} value={safeValue} onChange={(event) => onChange(Number(event.currentTarget.value))} />
<input type="range" min={min} max={max} step={accuracy === 1 ? 0.1 : 0.01} value={safeValue} disabled={disabled} onChange={(event) => onChange(Number(event.currentTarget.value))} />
</label>
);
}
@@ -1346,11 +1316,13 @@ function SketchImagePositionField({
label,
value,
accuracy,
disabled = false,
onChange,
}: {
label: string;
value: number;
accuracy: 1 | 2 | 3;
disabled?: boolean;
onChange: (value: number) => void;
}) {
const formatted = formatDimension(value, accuracy);
@@ -1370,6 +1342,7 @@ function SketchImagePositionField({
type="text"
inputMode="decimal"
value={draft}
disabled={disabled}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
+97 -31
View File
@@ -42,16 +42,23 @@ import {
type PlacementWorkplane,
} from "@/lib/placementWorkplane";
import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint";
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
import { projectThumbnailDimensions } from "@/lib/projectThumbnail";
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, shapeDimensionLimit, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
import { interiorWorkplaneGridCoordinates, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeTaperScaleAt, shapeWidth } from "@/lib/workplaneShapes";
import { sphereTessellation } from "@/lib/sphereTessellation";
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
import {
TransformOverlay,
continuousSnappedWheelRotation,
getElevationMeasureKey,
measureKeyForHandle,
normalizedRotationPlaneBasis,
rotationWheelDirectionSign,
ROTATION_WHEEL_SHIFT_SNAP_DEGREES,
ROTATION_WHEEL_SNAP_DEGREES,
snappedRotationDelta,
snappedWheelRotation,
type DimensionMark,
type EditingDimension,
type EditingRotation,
@@ -182,6 +189,8 @@ type WorkplaneViewportProps = {
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
workspaceSettingsKey?: string | null;
showProjectNameInToolbar?: boolean;
onShowProjectNameInToolbarChange?: (show: boolean) => void;
onAddShape: (shape: ShapeAsset, point?: PlacementPoint) => void;
onAlignAnchorChange: (id: string) => void;
onAlignPreview: (axis: AlignAxis, target: AlignTarget) => void;
@@ -439,10 +448,16 @@ type TransformDragState = {
rotationPivot?: THREE.Vector3;
rotationPlaneCenter?: THREE.Vector3;
rotationPlaneView?: RotationPlaneView;
rotationStartPointerAngle?: number;
rotationStartVector?: THREE.Vector3;
rotationScreenCenter?: { x: number; y: number };
rotationScreenSign?: number;
rotationStartQuaternion?: THREE.Quaternion;
rotationWheelAppliedDelta?: number;
rotationWheelAppliedPointerAngle?: number;
rotationWheelDeltaOffset?: number;
rotationWheelPointerOffset?: number;
rotationWheelSnapDegrees?: number;
wheelCenter?: RotationWheelView;
hasMoved?: boolean;
};
@@ -630,10 +645,6 @@ function rotationPatchFromQuaternion(quaternion: THREE.Quaternion): Partial<Work
};
}
function shouldPreserveDrawingBufferForLocalAutomation() {
return typeof window !== "undefined";
}
function canvasPngDataUrl(canvas: HTMLCanvasElement) {
return new Promise<string>((resolve) => {
canvas.toBlob((blob) => {
@@ -649,6 +660,17 @@ function canvasPngDataUrl(canvas: HTMLCanvasElement) {
});
}
function thumbnailPngDataUrl(source: HTMLCanvasElement) {
const dimensions = projectThumbnailDimensions(source.width, source.height);
const thumbnail = document.createElement("canvas");
thumbnail.width = dimensions.width;
thumbnail.height = dimensions.height;
const context = thumbnail.getContext("2d", { alpha: false });
if (!context) return Promise.resolve("");
context.drawImage(source, 0, 0, dimensions.width, dimensions.height);
return canvasPngDataUrl(thumbnail);
}
function rotationScreenSign(axisVector: THREE.Vector3, camera: THREE.Camera) {
const cameraForward = camera.getWorldDirection(new THREE.Vector3());
return axisVector.dot(cameraForward) >= 0 ? 1 : -1;
@@ -1978,6 +2000,7 @@ function resizeShapeFromFrameHandle(
shiftKey: boolean,
altKey: boolean,
step: number,
maxSize: number,
): Partial<WorkplaneShape> {
const shape = transform.startShape;
const frame = transform.selectionFrame;
@@ -1986,8 +2009,6 @@ function resizeShapeFromFrameHandle(
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
const signs = transform.scaleSigns ?? resizeSignsForHandle(handleKey);
const maxSize = 220;
const axisResize = (current: number, delta: number, sign: number) => {
if (!sign) {
return current;
@@ -2203,6 +2224,7 @@ function resizeSelectionFromHandle(
shiftKey: boolean,
altKey: boolean,
step: number,
maxSize: number,
) {
const frame = transform.selectionFrame;
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
@@ -2213,11 +2235,11 @@ function resizeSelectionFromHandle(
}
const signedDelta = sign * delta;
if (altKey) {
const size = snapDimension(current + signedDelta * 2, step, MIN_SHAPE_SIZE, 260);
const size = snapDimension(current + signedDelta * 2, step, MIN_SHAPE_SIZE, maxSize);
return { size, scale: size / Math.max(MIN_SHAPE_SIZE, current) };
}
const rawSize = current + signedDelta;
const size = snapDimension(rawSize, step, MIN_SHAPE_SIZE, 260);
const size = snapDimension(rawSize, step, MIN_SHAPE_SIZE, maxSize);
return {
size,
scale: size / Math.max(MIN_SHAPE_SIZE, current),
@@ -2228,9 +2250,9 @@ function resizeSelectionFromHandle(
let nextZ = axisResize(frame.depth, localDelta.z, signs.z);
if (shiftKey && signs.x && signs.z) {
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);
const limitedScale = clamp(scale, MIN_SHAPE_SIZE / Math.max(MIN_SHAPE_SIZE, Math.min(frame.width, frame.depth)), maxSize / Math.max(frame.width, frame.depth));
const width = snapDimension(frame.width * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
const depth = snapDimension(frame.depth * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
nextX = {
size: width,
scale: width / Math.max(MIN_SHAPE_SIZE, frame.width),
@@ -2252,8 +2274,8 @@ function resizeSelectionFromHandle(
.add(frame.xAxis.clone().multiplyScalar(localCenter.x * nextX.scale))
.add(frame.yAxis.clone().multiplyScalar(localCenter.y))
.add(frame.zAxis.clone().multiplyScalar(localCenter.z * nextZ.scale));
const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, 260);
const depth = snapDimension(shapeDepth(item.startShape) * nextZ.scale, step, MIN_SHAPE_SIZE, 260);
const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, maxSize);
const depth = snapDimension(shapeDepth(item.startShape) * nextZ.scale, step, MIN_SHAPE_SIZE, maxSize);
const actualScaleX = width / Math.max(MIN_SHAPE_SIZE, shapeWidth(item.startShape));
const actualScaleZ = depth / Math.max(MIN_SHAPE_SIZE, shapeDepth(item.startShape));
const patch = {
@@ -2283,6 +2305,8 @@ export function WorkplaneViewport({
initialSnap,
initialWorkspace,
workspaceSettingsKey,
showProjectNameInToolbar = true,
onShowProjectNameInToolbarChange,
onAddShape,
onAlignAnchorChange,
onAlignPreview,
@@ -2835,7 +2859,7 @@ export function WorkplaneViewport({
window.sketchforgeCaptureCanvasAsync = () => {
state.camera.updateMatrixWorld();
state.renderer.render(state.scene, state.camera);
return canvasPngDataUrl(state.renderer.domElement);
return thumbnailPngDataUrl(state.renderer.domElement);
};
window.sketchforgeCaptureView = (face = "current") => {
if (face === "home") {
@@ -3354,6 +3378,9 @@ export function WorkplaneViewport({
const rotationCenter = kind === "rotate" ? wheel ?? (state ? projectToScreen(pivot, state) : { x: localClientX, y: localClientY }) : undefined;
const rotationStartPoint = kind === "rotate" && state ? rayPointOnRotationPlane(state, event.clientX, event.clientY, rotationPlaneCenter, axisVector) : null;
const rotationStartVector = rotationStartPoint ? rotationStartPoint.sub(rotationPlaneCenter) : undefined;
const rotationStartPointerAngle = kind === "rotate"
? rotationPlanePointerAngle(rotationPlane, localClientX, localClientY, rotationCenter ?? { x: localClientX, y: localClientY })
: undefined;
const scalePlane = kind === "scale"
? localResizePlaneForFrame(frame, workplaneFootprintY(frame, activeWorkplane))
: undefined;
@@ -3430,6 +3457,7 @@ export function WorkplaneViewport({
rotationPivot: kind === "rotate" ? pivot : undefined,
rotationPlaneCenter: kind === "rotate" ? rotationPlaneCenter : undefined,
rotationPlaneView: kind === "rotate" ? rotationPlane : undefined,
rotationStartPointerAngle,
rotationStartVector: kind === "rotate" ? rotationStartVector : undefined,
rotationScreenCenter: rotationCenter,
rotationScreenSign: kind === "rotate" && state ? rotationScreenSign(axisVector, state.camera) : 1,
@@ -3558,10 +3586,11 @@ export function WorkplaneViewport({
: 0;
const resizingFromBottom = transform.handleKey === "bottom-height";
const rawFrameHeight = transform.selectionFrame.height + (resizingFromBottom ? -rawDelta : rawDelta);
const maxHeight = Math.max(...transform.items.map((item) => shapeDimensionLimit(workspaceRef.current, item.startShape.kind, 180)));
const nextFrameHeight = clamp(
transform.selectionFrame.height + snapValue(rawFrameHeight - transform.selectionFrame.height, step),
MIN_SHAPE_SIZE,
180,
maxHeight,
);
transform.items.forEach((item) => {
onUpdateShape(
@@ -3611,10 +3640,12 @@ export function WorkplaneViewport({
return true;
}
if (transform.items.length === 1) {
const next = resizeShapeFromFrameHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step);
const maxSize = shapeDimensionLimit(workspaceRef.current, transform.startShape.kind, 220);
const next = resizeShapeFromFrameHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step, maxSize);
onUpdateShape(transform.id, next);
} else {
resizeSelectionFromHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step).forEach(({ id, patch }) => onUpdateShape(id, patch));
const maxSize = Math.max(...transform.items.map((item) => shapeDimensionLimit(workspaceRef.current, item.startShape.kind, 260)));
resizeSelectionFromHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step, maxSize).forEach(({ id, patch }) => onUpdateShape(id, patch));
}
return true;
}
@@ -3647,14 +3678,43 @@ export function WorkplaneViewport({
transform.wheelCenter
&& Math.hypot(localClientX - transform.wheelCenter.x, localClientY - transform.wheelCenter.y) <= transform.wheelCenter.radius
);
let delta: number;
if (shiftKey) {
delta = Math.round(rawDelta / 45) * 45;
} else if (insideSnapWheel) {
delta = Math.round(rawDelta / 22.5) * 22.5;
const rawPointerAngle = rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter);
const wheelSnapDegrees = shiftKey ? ROTATION_WHEEL_SHIFT_SNAP_DEGREES : ROTATION_WHEEL_SNAP_DEGREES;
const wheelScreenSign = rotationWheelDirectionSign(transform.rotationScreenSign ?? 1);
const snappedWheel = insideSnapWheel
? snappedWheelRotation(
rawPointerAngle,
transform.rotationStartPointerAngle
?? rawPointerAngle - rawDelta * (transform.rotationScreenSign ?? 1),
wheelScreenSign,
wheelSnapDegrees,
)
: null;
const wheelRotation = snappedWheel
? continuousSnappedWheelRotation(
snappedWheel,
wheelSnapDegrees,
transform.rotationWheelSnapDegrees,
transform.rotationWheelAppliedDelta,
transform.rotationWheelAppliedPointerAngle,
transform.rotationWheelDeltaOffset,
transform.rotationWheelPointerOffset,
)
: null;
if (wheelRotation) {
transform.rotationWheelSnapDegrees = wheelSnapDegrees;
transform.rotationWheelDeltaOffset = wheelRotation.deltaOffset;
transform.rotationWheelPointerOffset = wheelRotation.pointerOffset;
transform.rotationWheelAppliedDelta = wheelRotation.delta;
transform.rotationWheelAppliedPointerAngle = wheelRotation.pointerAngle;
} else {
delta = Math.round(rawDelta);
transform.rotationWheelSnapDegrees = undefined;
transform.rotationWheelDeltaOffset = undefined;
transform.rotationWheelPointerOffset = undefined;
transform.rotationWheelAppliedDelta = undefined;
transform.rotationWheelAppliedPointerAngle = undefined;
}
const delta = wheelRotation?.delta ?? snappedRotationDelta(rawDelta, false, shiftKey);
const deltaQuaternion = new THREE.Quaternion().setFromAxisAngle(axisVector, THREE.MathUtils.degToRad(delta));
const rotationDelta = deltaQuaternion.clone();
@@ -3664,7 +3724,7 @@ export function WorkplaneViewport({
y: transform.wheelCenter ? transform.wheelCenter.y - 92 : localClientY - 18,
text: `${Number(delta.toFixed(1))}°`,
angle: delta,
pointerAngle: rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter),
pointerAngle: wheelRotation?.pointerAngle ?? rawPointerAngle,
});
}
transform.items.forEach((item) => {
@@ -3798,7 +3858,8 @@ export function WorkplaneViewport({
return;
}
if (Number.isFinite(value) && value > 0) {
const nextValue = Math.max(MIN_SHAPE_SIZE, value);
const customLimit = workspaceRef.current.shapeCustomizations[shape.kind]?.maxDimension;
const nextValue = Math.min(customLimit ?? Number.POSITIVE_INFINITY, Math.max(MIN_SHAPE_SIZE, value));
if (edit.axis === "width") {
const frame = selectionFrameForShapes([shape], [shape.id]);
if (shapeHasTaper(shape) && frame) {
@@ -4183,9 +4244,12 @@ export function WorkplaneViewport({
liftStartValue,
rotationAxisVector: handle.kind === "rotate" ? axisVector : undefined,
rotationPivot: handle.kind === "rotate" ? pivot : undefined,
rotationPlaneCenter: handle.kind === "rotate" ? rotationPlaneCenter : undefined,
rotationPlaneView: handle.kind === "rotate" ? rotationPlane : undefined,
rotationStartVector: handle.kind === "rotate" ? rotationStartVector : undefined,
rotationPlaneCenter: handle.kind === "rotate" ? rotationPlaneCenter : undefined,
rotationPlaneView: handle.kind === "rotate" ? rotationPlane : undefined,
rotationStartPointerAngle: handle.kind === "rotate"
? rotationPlanePointerAngle(rotationPlane, localClientX, localClientY, rotationCenter ?? { x: localClientX, y: localClientY })
: undefined,
rotationStartVector: handle.kind === "rotate" ? rotationStartVector : undefined,
rotationScreenCenter: rotationCenter,
rotationScreenSign: handle.kind === "rotate" ? rotationScreenSign(axisVector, state.camera) : 1,
rotationStartQuaternion: handle.kind === "rotate" ? quaternionForShape(shape) : undefined,
@@ -5070,10 +5134,12 @@ export function WorkplaneViewport({
snap={snap}
themePreference={themePreference}
moveDimensionsEnabled={moveDimensionsEnabled}
showProjectNameInToolbar={showProjectNameInToolbar}
onWorkspaceChange={setWorkspace}
onSnapChange={setSnap}
onThemePreferenceChange={onThemePreferenceChange}
onMoveDimensionsEnabledChange={changeMoveDimensionsEnabled}
onShowProjectNameInToolbarChange={onShowProjectNameInToolbarChange}
onMakeDefault={makeWorkspaceDefault}
onClose={() => setSettingsOpen(false)}
/>
@@ -5097,7 +5163,7 @@ export function WorkplaneViewport({
}
function createThreeScene(host: HTMLDivElement): ThreeState {
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance", preserveDrawingBuffer: shouldPreserveDrawingBufferForLocalAutomation() });
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance", preserveDrawingBuffer: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(host.clientWidth, host.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
@@ -7175,7 +7241,7 @@ function enableAcceleratedMeshPicking(mesh: THREE.Mesh, geometry: THREE.BufferGe
mesh.raycast = acceleratedRaycast;
const bvhGeometry = geometry as THREE.BufferGeometry & { boundsTree?: unknown };
if ((force || triangles >= BVH_PICKING_TRIANGLE_THRESHOLD) && !bvhGeometry.boundsTree) {
computeBoundsTree.call(geometry, { maxLeafSize: 12 });
computeBoundsTree.call(geometry, { targetLeafSize: 12 });
}
}
@@ -24,6 +24,7 @@ import {
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
import { resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeWidth } from "@/lib/workplaneShapes";
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
import { MAX_HIGH_RESOLUTION_SIDES } from "@/lib/workplaneSettings";
import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } 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"];
@@ -107,7 +108,7 @@ function propertyUsesLengthUnit(label: string) {
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole", "Top Length", "Top Width", "Bottom Length", "Bottom Width"].includes(label);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
function getShapePropertiesWithAppLimits(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate, textWidthMax = 260): ShapePropertyConfig[] {
const baseWidth = shapeWidth(shape);
const baseDepth = shapeDepth(shape);
const footprint = shapeOverallFootprintDimensions(shape);
@@ -159,8 +160,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
return [
{ label: "Start Angle", value: settings.startAngle, min: 0, max: 359, step: 1, onChange: (startAngle) => updateRevolve({ startAngle }) },
{ label: "Sweep", value: settings.sweepAngle, min: -360, max: 360, step: 1, onChange: (sweepAngle) => updateRevolve({ sweepAngle }) },
{ label: "Sides", value: settings.sides, min: 3, max: 128, step: 1, onChange: (sides) => updateRevolve({ sides }) },
{ label: "Thickness", value: settings.thickness, min: 0.1, max: 20, step: 0.1, onChange: (thickness) => updateRevolve({ thickness }) },
{ label: "Sides", value: settings.sides, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1, onChange: (sides) => updateRevolve({ 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: setHeight },
@@ -177,7 +177,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
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: "Sides", value: shape.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, 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: setHeight },
@@ -209,7 +209,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
{ 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: setHeight },
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
];
}
@@ -224,7 +224,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
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: "Sides", value: shape.sides ?? 64, min: 4, max: MAX_HIGH_RESOLUTION_SIDES, 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: setHeight },
@@ -334,7 +334,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
value: shape.text ?? "TEXT",
onChange: (text) => {
const nextText = text.slice(0, 24) || " ";
const nextWidth = clamp(Math.max(46, nextText.length * 19), 46, 260);
const nextWidth = clamp(Math.max(Math.min(46, textWidthMax), nextText.length * 19), MIN_SHAPE_SIZE, textWidthMax);
onUpdate({ text: nextText, width: nextWidth, size: nextWidth });
},
},
@@ -352,6 +352,18 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
];
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate, workspace: WorkplaneWorkspaceSettings): ShapePropertyConfig[] {
const customLimit = workspace.shapeCustomizations[shape.kind]?.maxDimension;
const properties = getShapePropertiesWithAppLimits(shape, onUpdate, customLimit ?? 260);
if (customLimit === undefined) return properties;
return properties.map((property) => {
if (property.type === "text" || property.type === "select") return property;
if (["Length", "Width", "Height"].includes(property.label)) return { ...property, max: customLimit };
if (["Top Radius", "Base Radius"].includes(property.label)) return { ...property, max: customLimit / 2 };
return property;
});
}
export function ShapeInspector({
shape,
snap,
@@ -379,7 +391,7 @@ export function ShapeInspector({
}) {
const solidColor = shape.color;
const locked = Boolean(shape.locked);
const properties = getShapeProperties(shape, onUpdate);
const properties = getShapeProperties(shape, onUpdate, workspace);
const gearType = shape.kind === "gear" ? normalizeGearType(shape.gearType) : null;
const primaryProperties = shape.kind === "gear"
? properties.filter((property) => ["Center Hole", "Length", "Width", "Height"].includes(property.label))
@@ -391,33 +403,34 @@ export function ShapeInspector({
? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label))
: [];
const taper = shapeTaperDimensions(shape);
const taperDimensionMax = workspace.shapeCustomizations[shape.kind]?.maxDimension ?? 480;
const taperProperties: ShapePropertyConfig[] = shape.kind === "gear" ? [] : [
{
label: "Top Length",
value: taper.topDepth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperTopDepth) => onUpdate({ taperTopDepth, taperTopWidth: taper.topWidth, taperTopScale: undefined }),
},
{
label: "Top Width",
value: taper.topWidth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperTopWidth) => onUpdate({ taperTopWidth, taperTopDepth: taper.topDepth, taperTopScale: undefined }),
},
{
label: "Bottom Length",
value: taper.bottomDepth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperBottomDepth) => onUpdate({ taperBottomDepth, taperBottomWidth: taper.bottomWidth, taperBottomScale: undefined }),
},
{
label: "Bottom Width",
value: taper.bottomWidth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperBottomWidth) => onUpdate({ taperBottomWidth, taperBottomDepth: taper.bottomDepth, taperBottomScale: undefined }),
},
];
@@ -7,9 +7,15 @@ import {
} from "@/components/workplane/transformOverlayTypes";
export {
continuousSnappedWheelRotation,
getElevationMeasureKey,
measureKeyForHandle,
normalizedRotationPlaneBasis,
rotationWheelDirectionSign,
snappedRotationDelta,
snappedWheelRotation,
ROTATION_WHEEL_SHIFT_SNAP_DEGREES,
ROTATION_WHEEL_SNAP_DEGREES,
type DimensionMark,
type EditingDimension,
type EditingRotation,
@@ -1,16 +1,18 @@
"use client";
import { ChevronDown, Grid3X3, History, Palette, RotateCcw, Ruler, X } from "lucide-react";
import { Box as BoxIcon, ChevronDown, Grid3X3, History, Palette, RotateCcw, Ruler, X } from "lucide-react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { HexColorInput, HexColorPicker } from "react-colorful";
import { APP_THEME_OPTIONS, type AppThemePreference } from "@/lib/appTheme";
import { gearCenterHoleLimits, gearToothPitch } from "@/lib/gearGeometry";
import { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { shapeAssetDefaultDimensions, shapeAssetSpecialDefaults, toolbarShapeAssets } from "@/lib/shapeCatalog";
import { DEFAULT_WORKPLANE_WORKSPACE, MAX_CUSTOM_SHAPE_DIMENSION, MAX_HIGH_RESOLUTION_SIDES, MIN_CUSTOM_SHAPE_DIMENSION } from "@/lib/workplaneSettings";
import type { GearType, GridSize, ShapeCustomization, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
type WorkspaceSettings = WorkplaneWorkspaceSettings;
type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane" | "history";
type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane" | "shapes" | "history";
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;
@@ -28,6 +30,18 @@ const WORKSPACE_SIZE_PRESETS = [
const GRID_BLOCK_PRESETS = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const;
const HISTORY_LIMIT_OPTIONS = [30, 50, 100, "unlimited", "custom"] as const;
const HISTORY_CUSTOM_DEFAULT = 250;
const TEXT_FONT_OPTIONS = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
const GEAR_TYPE_OPTIONS: Array<{ value: GearType; label: string }> = [
{ value: "spur", label: "Spur gear" },
{ value: "helical", label: "Helical gear" },
{ value: "bevel", label: "Bevel gear" },
];
type ShapeSpecialNumberKey = "steps" | "sides" | "bevel" | "segments" | "topRadius" | "baseRadius" | "teeth" | "toothSize" | "toothWidth" | "centerHoleSize" | "helixAngle" | "helixQuality";
type ShapeSpecialField =
| { type: "number"; key: ShapeSpecialNumberKey; label: string; defaultValue: number; min: number; max: number; step?: number; unit?: string }
| { type: "select"; key: "font" | "gearType"; label: string; defaultValue: string; options: Array<{ value: string; label: string }> }
| { type: "text"; key: "text"; label: string; defaultValue: string; maxLength: number };
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
@@ -44,15 +58,67 @@ function isHistoryLimitPreset(value: unknown): value is 30 | 50 | 100 {
return value === 30 || value === 50 || value === 100;
}
function specialFieldsForShape(
kind: ShapeKind,
dimensions: { width: number; depth: number; height: number },
customization: ShapeCustomization,
): ShapeSpecialField[] {
const defaults = shapeAssetSpecialDefaults(kind, dimensions);
if (kind === "cylinder") return [{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1 }];
if (kind === "sphere" || kind === "halfSphere") return [{ type: "number", key: "steps", label: "Steps", defaultValue: defaults.steps ?? 24, min: 6, max: 64, step: 1 }];
if (kind === "cone") {
return [
{ type: "number", key: "topRadius", label: "Top radius", defaultValue: defaults.topRadius ?? 0, min: 0, max: MAX_CUSTOM_SHAPE_DIMENSION / 2, unit: "mm" },
{ type: "number", key: "baseRadius", label: "Base radius", defaultValue: defaults.baseRadius ?? dimensions.width / 2, min: MIN_CUSTOM_SHAPE_DIMENSION, max: MAX_CUSTOM_SHAPE_DIMENSION / 2, unit: "mm" },
{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1 },
];
}
if (kind === "pyramid") return [{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 4, min: 3, max: 24, step: 1 }];
if (kind === "roundRoof") return [{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 64, min: 4, max: MAX_HIGH_RESOLUTION_SIDES, step: 1 }];
if (kind === "tube" || kind === "ring") return [{ type: "number", key: "bevel", label: "Thickness", defaultValue: defaults.bevel ?? 4, min: 0.5, max: 20, unit: "mm" }];
if (kind === "text") {
return [
{ type: "text", key: "text", label: "Text", defaultValue: defaults.text ?? "TEXT", maxLength: 24 },
{ type: "select", key: "font", label: "Font", defaultValue: defaults.font ?? "Multilanguage", options: TEXT_FONT_OPTIONS.map((value) => ({ value, label: value })) },
{ type: "number", key: "bevel", label: "Bevel", defaultValue: defaults.bevel ?? 0, min: 0, max: 8, unit: "mm" },
{ type: "number", key: "segments", label: "Segments", defaultValue: defaults.segments ?? 0, min: 0, max: 24, step: 1 },
];
}
if (kind === "gear") {
const teeth = customization.teeth ?? defaults.teeth ?? 12;
const toothSize = customization.toothSize ?? defaults.toothSize ?? 2.5;
const toothPitch = gearToothPitch(dimensions.width, dimensions.depth, teeth);
const centerHoleLimits = gearCenterHoleLimits(dimensions.width, dimensions.depth, toothSize);
const gearType = customization.gearType ?? defaults.gearType ?? "spur";
const fields: ShapeSpecialField[] = [
{ type: "select", key: "gearType", label: "Gear type", defaultValue: defaults.gearType ?? "spur", options: GEAR_TYPE_OPTIONS },
{ type: "number", key: "teeth", label: "Teeth", defaultValue: defaults.teeth ?? 12, min: 6, max: 64, step: 1 },
{ type: "number", key: "toothSize", label: "Tooth size", defaultValue: defaults.toothSize ?? 2.5, min: 0.2, max: Math.max(0.2, Math.min(dimensions.width, dimensions.depth) * 0.22), unit: "mm" },
{ type: "number", key: "toothWidth", label: "Tooth width", defaultValue: defaults.toothWidth ?? toothPitch * 0.54, min: toothPitch * 0.12, max: toothPitch * 0.82, unit: "mm" },
{ type: "number", key: "centerHoleSize", label: "Center hole", defaultValue: defaults.centerHoleSize ?? 6, min: centerHoleLimits.min, max: centerHoleLimits.max, unit: "mm" },
];
if (gearType === "helical") {
fields.push(
{ type: "number", key: "helixAngle", label: "Helix angle", defaultValue: defaults.helixAngle ?? 22.5, min: -45, max: 45, unit: "deg" },
{ type: "number", key: "helixQuality", label: "Helix quality", defaultValue: defaults.helixQuality ?? 16, min: 4, max: 32, step: 1 },
);
}
return fields;
}
return [];
}
export function WorkspaceSettingsModal({
workspace,
snap,
themePreference,
moveDimensionsEnabled,
showProjectNameInToolbar,
onWorkspaceChange,
onSnapChange,
onThemePreferenceChange,
onMoveDimensionsEnabledChange,
onShowProjectNameInToolbarChange,
onMakeDefault,
onClose,
}: {
@@ -60,15 +126,18 @@ export function WorkspaceSettingsModal({
snap: GridSize;
themePreference: AppThemePreference;
moveDimensionsEnabled: boolean;
showProjectNameInToolbar: boolean;
onWorkspaceChange: (next: WorkspaceSettings) => void;
onSnapChange: (next: GridSize) => void;
onThemePreferenceChange?: (preference: AppThemePreference) => void;
onMoveDimensionsEnabledChange: (enabled: boolean) => void;
onShowProjectNameInToolbarChange?: (show: boolean) => void;
onMakeDefault: () => void;
onClose: () => void;
}) {
const [defaultSaved, setDefaultSaved] = useState(false);
const [activeSection, setActiveSection] = useState<WorkspaceSettingsSection>("appearance");
const [selectedShapeKind, setSelectedShapeKind] = useState<ShapeKind>(toolbarShapeAssets[0].kind);
const [dimensionDrafts, setDimensionDrafts] = useState(() => ({
width: workspace.width.toFixed(workspace.accuracy),
depth: workspace.depth.toFixed(workspace.accuracy),
@@ -88,6 +157,16 @@ export function WorkspaceSettingsModal({
const gridColor = /^#[0-9a-f]{6}$/i.test(workspace.gridColor)
? workspace.gridColor
: DEFAULT_WORKPLANE_WORKSPACE.gridColor;
const selectedShapeAsset = toolbarShapeAssets.find((asset) => asset.kind === selectedShapeKind) ?? toolbarShapeAssets[0];
const selectedShapeAppDefaults = shapeAssetDefaultDimensions(selectedShapeKind);
const selectedShapeCustomization = workspace.shapeCustomizations[selectedShapeKind] ?? {};
const selectedShapeEffectiveDimensions = {
width: selectedShapeCustomization.width ?? selectedShapeAppDefaults.width,
depth: selectedShapeCustomization.depth ?? selectedShapeAppDefaults.depth,
height: selectedShapeCustomization.height ?? selectedShapeAppDefaults.height,
};
const selectedShapeSpecialFields = specialFieldsForShape(selectedShapeKind, selectedShapeEffectiveDimensions, selectedShapeCustomization);
const selectedShapeCustomized = Object.keys(selectedShapeCustomization).length > 0;
useEffect(() => {
setDimensionDrafts({
width: workspace.width.toFixed(workspace.accuracy),
@@ -107,6 +186,56 @@ export function WorkspaceSettingsModal({
const next = { ...workspace, ...patch };
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
};
const patchShapeCustomization = (kind: ShapeKind, patch: Partial<ShapeCustomization>) => {
const nextEntry = Object.fromEntries(
Object.entries({ ...workspace.shapeCustomizations[kind], ...patch }).filter(([, value]) => value !== undefined),
) as ShapeCustomization;
const nextCustomizations = { ...workspace.shapeCustomizations };
if (Object.keys(nextEntry).length > 0) nextCustomizations[kind] = nextEntry;
else delete nextCustomizations[kind];
patchWorkspace({ shapeCustomizations: nextCustomizations });
};
const setShapeDefaultDimension = (key: "width" | "depth" | "height", rawValue: string) => {
const parsed = parseMeasurementInput(rawValue);
if (!Number.isFinite(parsed)) return;
const nextValue = clamp(parsed, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION);
patchShapeCustomization(selectedShapeKind, key === "width" && selectedShapeKind === "cone"
? { width: nextValue, baseRadius: nextValue / 2 }
: { [key]: nextValue });
};
const setShapeSpecialNumber = (field: Extract<ShapeSpecialField, { type: "number" }>, rawValue: string) => {
if (!rawValue.trim()) {
patchShapeCustomization(selectedShapeKind, { [field.key]: undefined });
return;
}
const parsed = parseMeasurementInput(rawValue);
if (!Number.isFinite(parsed)) return;
const clamped = clamp(parsed, field.min, field.max);
const nextValue = field.step === 1 ? Math.round(clamped) : clamped;
patchShapeCustomization(selectedShapeKind, field.key === "baseRadius" && selectedShapeKind === "cone"
? { baseRadius: nextValue, width: nextValue * 2 }
: { [field.key]: nextValue });
};
const setShapeSpecialText = (field: Extract<ShapeSpecialField, { type: "text" }>, rawValue: string) => {
const nextValue = rawValue.slice(0, field.maxLength);
patchShapeCustomization(selectedShapeKind, { [field.key]: nextValue || undefined });
};
const setShapeLimit = (rawValue: string) => {
if (!rawValue.trim()) {
patchShapeCustomization(selectedShapeKind, { maxDimension: undefined });
return;
}
const parsed = parseMeasurementInput(rawValue);
if (!Number.isFinite(parsed)) return;
patchShapeCustomization(selectedShapeKind, {
maxDimension: clamp(parsed, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION),
});
};
const resetSelectedShapeCustomization = () => {
const nextCustomizations = { ...workspace.shapeCustomizations };
delete nextCustomizations[selectedShapeKind];
patchWorkspace({ shapeCustomizations: nextCustomizations });
};
const setDimension = (key: "width" | "depth", value: string) => {
const parsed = parseMeasurementInput(value);
const next = clamp(Number.isFinite(parsed) ? parsed : workspace[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
@@ -169,6 +298,10 @@ export function WorkspaceSettingsModal({
<Grid3X3 size={18} />
<span>Workplane</span>
</button>
<button className={activeSection === "shapes" ? "active" : ""} aria-current={activeSection === "shapes" ? "page" : undefined} onClick={() => setActiveSection("shapes")}>
<BoxIcon size={18} />
<span>Shape defaults</span>
</button>
<button className={activeSection === "history" ? "active" : ""} aria-current={activeSection === "history" ? "page" : undefined} onClick={() => setActiveSection("history")}>
<History size={18} />
<span>History</span>
@@ -197,6 +330,11 @@ export function WorkspaceSettingsModal({
</select>
</label>
<p className="workspace-global-note">Theme applies across SketchForge and all projects.</p>
<WorkspaceToggle
label="Show project name in toolbar"
checked={showProjectNameInToolbar}
onChange={(show) => onShowProjectNameInToolbarChange?.(show)}
/>
<WorkspaceToggle
label="Show movement dimensions"
checked={moveDimensionsEnabled}
@@ -334,6 +472,139 @@ export function WorkspaceSettingsModal({
</>
) : null}
{activeSection === "shapes" ? (
<>
<div className="workspace-section-heading">
<strong>Shape defaults</strong>
<span>Customize how each toolbar shape starts. Existing limits stay unchanged until you enter a custom limit.</span>
</div>
<label className="workspace-shape-picker">
<span>Shape</span>
<span className="workspace-shape-picker-control">
<img src={selectedShapeAsset.menuIcon} alt="" />
<select value={selectedShapeKind} onChange={(event) => setSelectedShapeKind(event.currentTarget.value as ShapeKind)}>
{toolbarShapeAssets.map((asset) => (
<option key={asset.kind} value={asset.kind}>
{asset.name}{workspace.shapeCustomizations[asset.kind] ? " — customized" : ""}
</option>
))}
</select>
</span>
</label>
<div className="workspace-shape-card">
<div className="workspace-shape-card-heading">
<span>
<strong>{selectedShapeAsset.name}</strong>
<small>{selectedShapeCustomized ? "Custom settings active" : "Using SketchForge defaults"}</small>
</span>
<button type="button" onClick={resetSelectedShapeCustomization} disabled={!selectedShapeCustomized}>
<RotateCcw size={14} />
<span>Use app defaults</span>
</button>
</div>
<div className="workspace-shape-dimensions">
{(["width", "depth", "height"] as const).map((key) => (
<label key={`${selectedShapeKind}-${key}`}>
<span>{key === "depth" ? "Length" : key[0].toUpperCase() + key.slice(1)}</span>
<input
key={`${selectedShapeKind}-${key}-${selectedShapeCustomization[key] ?? "app"}`}
type="text"
inputMode="decimal"
defaultValue={(selectedShapeCustomization[key] ?? selectedShapeAppDefaults[key]).toFixed(workspace.accuracy)}
onBlur={(event) => setShapeDefaultDimension(key, event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
<small>App: {selectedShapeAppDefaults[key]} mm</small>
</label>
))}
</div>
{selectedShapeSpecialFields.length > 0 ? (
<div className="workspace-shape-specials">
<div className="workspace-shape-specials-heading">
<strong>Shape details</strong>
<small>Extra defaults used when this shape is added.</small>
</div>
<div className="workspace-shape-special-fields">
{selectedShapeSpecialFields.map((field) => {
const customizedValue = selectedShapeCustomization[field.key];
const effectiveValue = customizedValue ?? field.defaultValue;
if (field.type === "select") {
return (
<label key={`${selectedShapeKind}-${field.key}`}>
<span>{field.label}</span>
<select
value={String(effectiveValue)}
onChange={(event) => patchShapeCustomization(selectedShapeKind, { [field.key]: event.currentTarget.value })}
>
{field.options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
</select>
<small>App: {field.options.find((option) => option.value === field.defaultValue)?.label ?? field.defaultValue}</small>
</label>
);
}
if (field.type === "text") {
return (
<label key={`${selectedShapeKind}-${field.key}`}>
<span>{field.label}</span>
<input
key={`${selectedShapeKind}-${field.key}-${String(customizedValue ?? "app")}`}
type="text"
maxLength={field.maxLength}
defaultValue={String(effectiveValue)}
onBlur={(event) => setShapeSpecialText(field, event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
<small>App: {field.defaultValue}</small>
</label>
);
}
const numericValue = Number(effectiveValue);
return (
<label key={`${selectedShapeKind}-${field.key}`}>
<span>{field.label}</span>
<input
key={`${selectedShapeKind}-${field.key}-${String(customizedValue ?? "app")}-${field.defaultValue}`}
type="text"
inputMode="decimal"
defaultValue={field.step === 1 ? String(Math.round(numericValue)) : numericValue.toFixed(workspace.accuracy)}
onBlur={(event) => setShapeSpecialNumber(field, event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
<small>App: {field.step === 1 ? Math.round(field.defaultValue) : Number(field.defaultValue.toFixed(workspace.accuracy))}{field.unit ? ` ${field.unit}` : ""}</small>
</label>
);
})}
</div>
</div>
) : null}
<label className="workspace-shape-limit">
<span>
<strong>Custom size limit</strong>
<small>Leave blank to keep all current inspector and drag limits for this shape.</small>
</span>
<input
key={`${selectedShapeKind}-limit-${selectedShapeCustomization.maxDimension ?? "app"}`}
type="text"
inputMode="decimal"
defaultValue={selectedShapeCustomization.maxDimension?.toFixed(workspace.accuracy) ?? ""}
placeholder="App limits"
onBlur={(event) => setShapeLimit(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
</label>
<p className="workspace-shape-note">Custom values apply to new shapes. A custom size limit also replaces this shape&apos;s existing resize ceilings, up to 2000 mm.</p>
</div>
</>
) : null}
{activeSection === "history" ? (
<>
<div className="workspace-section-heading">
@@ -618,10 +889,23 @@ function GridColorControl({ color, onChange }: { color: string; onChange: (color
);
}
function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
function WorkspaceToggle({
label,
description,
checked,
onChange,
}: {
label: string;
description?: string;
checked: boolean;
onChange: (checked: boolean) => void;
}) {
return (
<label className="workspace-toggle">
<span>{label}</span>
<span className="workspace-toggle-copy">
<span>{label}</span>
{description ? <small>{description}</small> : null}
</span>
<input type="checkbox" checked={checked} onChange={(event) => onChange(event.currentTarget.checked)} />
</label>
);
@@ -15,6 +15,65 @@ export type RotationPlaneView = {
export type RotationPlaneBasis = Pick<RotationPlaneView, "a" | "b" | "c" | "d">;
export const ROTATION_WHEEL_SNAP_DEGREES = 45;
export const ROTATION_WHEEL_SHIFT_SNAP_DEGREES = 22.5;
export function rotationWheelDirectionSign(screenSign: number) {
return screenSign < 0 ? 1 : -1;
}
export function snappedRotationDelta(rawDelta: number, insideSnapWheel: boolean, shiftKey: boolean) {
const step = insideSnapWheel || shiftKey ? ROTATION_WHEEL_SNAP_DEGREES : 1;
return Math.round(rawDelta / step) * step;
}
export function snappedWheelRotation(
pointerAngle: number,
startPointerAngle: number,
screenSign = 1,
snapDegrees = ROTATION_WHEEL_SNAP_DEGREES,
) {
const snappedPointerAngle = Math.round(pointerAngle / snapDegrees) * snapDegrees;
const snappedStartPointerAngle = Math.round(startPointerAngle / snapDegrees) * snapDegrees;
let pointerDelta = snappedPointerAngle - snappedStartPointerAngle;
while (pointerDelta > 180) pointerDelta -= 360;
while (pointerDelta <= -180) pointerDelta += 360;
const direction = screenSign < 0 ? -1 : 1;
const delta = pointerDelta * direction;
return {
delta: delta === 0 ? 0 : delta,
pointerAngle: snappedPointerAngle,
};
}
export function continuousSnappedWheelRotation(
rotation: { delta: number; pointerAngle: number },
snapDegrees: number,
previousSnapDegrees: number | undefined,
previousDelta: number | undefined,
previousPointerAngle: number | undefined,
previousDeltaOffset = 0,
previousPointerOffset = 0,
) {
const snapModeChanged = previousSnapDegrees !== undefined && previousSnapDegrees !== snapDegrees;
const deltaOffset = snapModeChanged && previousDelta !== undefined
? previousDelta - rotation.delta
: previousDeltaOffset;
const pointerOffset = snapModeChanged && previousPointerAngle !== undefined
? previousPointerAngle - rotation.pointerAngle
: previousPointerOffset;
let pointerAngle = rotation.pointerAngle + pointerOffset;
while (pointerAngle > 180) pointerAngle -= 360;
while (pointerAngle < -180) pointerAngle += 360;
const delta = rotation.delta + deltaOffset;
return {
delta: delta === 0 ? 0 : delta,
pointerAngle,
deltaOffset,
pointerOffset,
};
}
export function normalizedRotationPlaneBasis(plane: RotationPlaneView, invertVerticalAxis = false): RotationPlaneBasis {
const longestAxis = Math.max(Math.hypot(plane.a, plane.b), Math.hypot(plane.c, plane.d));
if (!Number.isFinite(longestAxis) || longestAxis < 0.000001) {