release: improve rendering architecture and dark mode

This commit is contained in:
Formsmith
2026-07-28 14:52:59 +03:00
parent 33671c1aae
commit edbb11c97d
32 changed files with 3944 additions and 310 deletions
+143 -41
View File
@@ -15,6 +15,7 @@ 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 type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme";
import { manifoldModuleSource } from "@/generated/manifoldModuleSource";
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
import { sphereTessellation } from "@/lib/sphereTessellation";
@@ -72,10 +73,12 @@ import {
CAD_MODIFIER_REQUEST_TIMEOUT_MS,
cadModifierTimeoutMessage,
cadModifierWorkerFailureMessage,
defaultCadModifierTangentChain,
selectableCadModifierEdge,
type CadModifierRequestPhase,
} from "@/lib/cadModifierRuntime";
import { cloneWorkplaneShapeSnapshot, compactEdgeTreatmentHistory, edgeTreatmentAppliedFrame, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory";
import { appendEditorHistorySnapshot, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryExportLimit, type EditorHistoryState } from "@/lib/editorHistory";
import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryExportLimit, type EditorHistoryState } from "@/lib/editorHistory";
import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap";
import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
@@ -87,7 +90,7 @@ import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAs
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
import { normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import {
SKETCHFORGE_MCP_POLL_MS,
SKETCHFORGE_MCP_ROUTE,
@@ -188,6 +191,7 @@ declare global {
__sketchforgeBooleanTest?: BooleanAutomationResult;
__sketchforgeBooleanTestImage?: string;
sketchforgeCaptureCanvas?: () => string;
sketchforgeCaptureCanvasAsync?: () => Promise<string>;
sketchforgeCaptureView?: (face?: SketchForgeMcpViewFace) => Promise<string> | string;
}
}
@@ -1380,10 +1384,6 @@ function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedI
return [...selected];
}
function selectableCadModifierEdge(edge: CadModifierEdge, sharpAngle: number) {
return edge.display && edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle;
}
function cadDisplayEdgesAfterTreatment(shape: WorkplaneShape, session: EdgeModifierSession) {
const removed = new Set(session.selectedEdgeIds);
const elevation = shape.elevation ?? 0;
@@ -5207,6 +5207,9 @@ export function SketchForgeEditor({
projectModifiedAt = Date.now(),
projectRevision = 0,
sharedProjectsEnabled = false,
themePreference = "system",
resolvedTheme = "light",
onThemePreferenceChange,
}: {
initialAssets?: ProjectAsset[];
initialShapes?: WorkplaneShape[];
@@ -5224,6 +5227,11 @@ export function SketchForgeEditor({
history: EditorHistoryEntry[];
historyIndex: number;
assets: ProjectAsset[];
projectName: string;
projectCreatedAt: number;
workspace: WorkplaneWorkspaceSettings;
snapGrid: GridSize;
placementElevation: number;
}) => void;
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void;
onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => void;
@@ -5233,6 +5241,9 @@ export function SketchForgeEditor({
projectModifiedAt?: number;
projectRevision?: number;
sharedProjectsEnabled?: boolean;
themePreference?: AppThemePreference;
resolvedTheme?: ResolvedAppTheme;
onThemePreferenceChange?: (preference: AppThemePreference) => void;
} = {}) {
const initialSceneRef = useRef<WorkplaneShape[] | null>(null);
if (initialSceneRef.current === null) {
@@ -5240,7 +5251,12 @@ export function SketchForgeEditor({
}
const initialHistoryStateRef = useRef<EditorHistoryState | null>(null);
if (initialHistoryStateRef.current === null) {
initialHistoryStateRef.current = hydrateEditorHistoryState(initialSceneRef.current, initialHistory, initialHistoryIndex);
initialHistoryStateRef.current = hydrateEditorHistoryState(
initialSceneRef.current,
initialHistory,
initialHistoryIndex,
normalizeWorkspaceSettings(initialWorkspace).historyLimit,
);
}
const [shapes, setShapes] = useState<WorkplaneShape[]>(() => initialSceneRef.current as WorkplaneShape[]);
const [projectAssets, setProjectAssets] = useState<ProjectAsset[]>(() => dedupeProjectAssets(initialAssets));
@@ -5280,10 +5296,13 @@ export function SketchForgeEditor({
const projectAssetsRef = useRef(projectAssets);
const selectedIdsRef = useRef(selectedIds);
const workspaceSettingsRef = useRef(workspaceSettings);
const snapGridRef = useRef(snapGrid);
const placementElevationRef = useRef(placementElevation);
const noticeRef = useRef(notice);
const projectInfoRef = useRef({ projectId: projectId ?? null, projectName });
const projectInfoRef = useRef({ projectId: projectId ?? null, projectName, projectCreatedAt });
const historyIndexRef = useRef(historyIndex);
const historyRef = useRef(history);
const historyLimitRef = useRef(workspaceSettings.historyLimit);
const interactionHistoryStartRef = useRef("");
const interactionHistoryChangedRef = useRef(false);
const interactionHistoryTimerRef = useRef<number | null>(null);
@@ -5571,13 +5590,21 @@ export function SketchForgeEditor({
workspaceSettingsRef.current = workspaceSettings;
}, [workspaceSettings]);
useEffect(() => {
snapGridRef.current = snapGrid;
}, [snapGrid]);
useEffect(() => {
placementElevationRef.current = placementElevation;
}, [placementElevation]);
useEffect(() => {
noticeRef.current = notice;
}, [notice]);
useEffect(() => {
projectInfoRef.current = { projectId: projectId ?? null, projectName };
}, [projectId, projectName]);
projectInfoRef.current = { projectId: projectId ?? null, projectName, projectCreatedAt };
}, [projectCreatedAt, projectId, projectName]);
useEffect(() => {
historyIndexRef.current = historyIndex;
@@ -5620,11 +5647,19 @@ export function SketchForgeEditor({
}, [sketchActive, sketchOperation, sketchProfile, sketchRevolveSettings]);
useEffect(() => {
setWorkspaceSettings(normalizeWorkspaceSettings(initialWorkspace));
const nextWorkspace = normalizeWorkspaceSettings(initialWorkspace);
workspaceSettingsRef.current = nextWorkspace;
setWorkspaceSettings((current) => (
workplaneSettingsFingerprint(current, snapGridRef.current) === workplaneSettingsFingerprint(nextWorkspace, snapGridRef.current)
? current
: nextWorkspace
));
}, [initialWorkspace]);
useEffect(() => {
setSnapGrid(normalizeSnapGrid(initialSnap));
const nextSnap = normalizeSnapGrid(initialSnap);
snapGridRef.current = nextSnap;
setSnapGrid((current) => (current === nextSnap ? current : nextSnap));
}, [initialSnap]);
const selectedShapes = useMemo(() => shapes.filter((shape) => selectedIds.includes(shape.id)), [selectedIds, shapes]);
@@ -5702,21 +5737,43 @@ export function SketchForgeEditor({
const runId = projectSnapshotRunRef.current + 1;
projectSnapshotRunRef.current = runId;
const capture = () => {
const capture = async () => {
if (projectSnapshotRunRef.current !== runId) {
return;
return true;
}
const image = window.sketchforgeCaptureCanvasAsync
? await window.sketchforgeCaptureCanvasAsync()
: window.sketchforgeCaptureCanvas?.() ?? "";
if (projectSnapshotRunRef.current !== runId) {
return true;
}
const image = window.sketchforgeCaptureCanvas?.();
if (image && image.length > 100) {
onProjectSnapshot({ image, projectId, shapes: shapes.length });
return true;
}
return false;
};
const firstTimer = window.setTimeout(capture, 850);
const secondTimer = window.setTimeout(capture, 1500);
let idleId: number | null = null;
let retryTimer: number | null = null;
const runCapture = () => {
void capture().then((captured) => {
if (!captured) {
retryTimer = window.setTimeout(() => void capture(), 650);
}
});
};
const captureTimer = window.setTimeout(() => {
if ("requestIdleCallback" in window) {
idleId = window.requestIdleCallback(runCapture, { timeout: 1200 });
} else {
runCapture();
}
}, 850);
return () => {
window.clearTimeout(firstTimer);
window.clearTimeout(secondTimer);
window.clearTimeout(captureTimer);
if (retryTimer !== null) window.clearTimeout(retryTimer);
if (idleId !== null && "cancelIdleCallback" in window) window.cancelIdleCallback(idleId);
};
}, [onProjectSnapshot, projectId, projectInteractionActive, shapes]);
@@ -5737,7 +5794,7 @@ export function SketchForgeEditor({
}, [alignAnchorId, selectedIds, selectedShapes.length]);
const syncProjectShapes = useCallback(
(nextShapes: WorkplaneShape[]) => {
(nextShapes: WorkplaneShape[], force = false) => {
if (!projectId || !onProjectShapesChange) {
return;
}
@@ -5751,7 +5808,7 @@ export function SketchForgeEditor({
}
const canonicalNext = nextShapes.map(canonicalizeShape);
const serialized = projectShapesFingerprint(canonicalNext);
if (lastProjectShapesSyncRef.current === serialized) {
if (!force && lastProjectShapesSyncRef.current === serialized) {
return;
}
if (projectSyncTimerRef.current !== null) {
@@ -5766,6 +5823,11 @@ export function SketchForgeEditor({
history: historyRef.current,
historyIndex: historyIndexRef.current,
assets: projectAssetsRef.current,
projectName: projectInfoRef.current.projectName,
projectCreatedAt: projectInfoRef.current.projectCreatedAt,
workspace: workspaceSettingsRef.current,
snapGrid: snapGridRef.current,
placementElevation: placementElevationRef.current,
});
projectSyncTimerRef.current = null;
}, 120);
@@ -5773,9 +5835,30 @@ export function SketchForgeEditor({
[onProjectShapesChange, projectId],
);
const appendHistorySnapshot = useCallback((nextShapes: WorkplaneShape[], nextSelection: string[]) => {
const entry = editorHistoryEntry(nextShapes, nextSelection);
const result = appendEditorHistorySnapshot(historyRef.current, historyIndexRef.current, entry);
useEffect(() => {
const limitChanged = historyLimitRef.current !== workspaceSettings.historyLimit;
historyLimitRef.current = workspaceSettings.historyLimit;
const bounded = boundedEditorHistoryState(
historyRef.current,
historyIndexRef.current,
workspaceSettings.historyLimit,
);
if (bounded.entries !== historyRef.current || bounded.index !== historyIndexRef.current) {
historyRef.current = bounded.entries;
historyIndexRef.current = bounded.index;
setHistory(bounded.entries);
setHistoryIndex(bounded.index);
}
if (limitChanged) syncProjectShapes(shapesRef.current, true);
}, [syncProjectShapes, workspaceSettings.historyLimit]);
const appendHistoryEntry = useCallback((entry: EditorHistoryEntry) => {
const result = appendEditorHistorySnapshot(
historyRef.current,
historyIndexRef.current,
entry,
workspaceSettingsRef.current.historyLimit,
);
if (result.entries !== historyRef.current) {
historyRef.current = result.entries;
setHistory(result.entries);
@@ -5785,6 +5868,12 @@ export function SketchForgeEditor({
return result.changed;
}, []);
const appendHistorySnapshot = useCallback(
(nextShapes: WorkplaneShape[], nextSelection: string[]) =>
appendHistoryEntry(editorHistoryEntry(nextShapes, nextSelection)),
[appendHistoryEntry],
);
const finalizeInteractionHistory = useCallback(() => {
const startFingerprint = interactionHistoryStartRef.current;
const hadChanges = interactionHistoryChangedRef.current;
@@ -5794,22 +5883,20 @@ export function SketchForgeEditor({
return;
}
const canonicalNext = shapesRef.current.map(canonicalizeShape);
const nextFingerprint = projectShapesFingerprint(canonicalNext);
if (!startFingerprint || startFingerprint === nextFingerprint) {
const entry = editorHistoryEntry(shapesRef.current, selectedIdsRef.current);
if (!startFingerprint || startFingerprint === entry.fingerprint) {
return;
}
appendHistorySnapshot(canonicalNext, selectedIdsRef.current);
}, [appendHistorySnapshot]);
appendHistoryEntry(entry);
}, [appendHistoryEntry]);
useEffect(() => {
if (projectInteractionActive || !pendingProjectShapesRef.current) {
return;
}
const pendingShapes = pendingProjectShapesRef.current;
pendingProjectShapesRef.current = null;
const timer = window.setTimeout(() => syncProjectShapes(pendingShapes), 180);
const timer = window.setTimeout(() => syncProjectShapes(shapesRef.current), 180);
return () => window.clearTimeout(timer);
}, [projectInteractionActive, syncProjectShapes]);
@@ -5845,12 +5932,19 @@ export function SketchForgeEditor({
const updateProjectWorkspaceSettings = useCallback(
(settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => {
setWorkspaceSettings(settings.workspace);
const nextWorkspace = normalizeWorkspaceSettings(settings.workspace);
workspaceSettingsRef.current = nextWorkspace;
snapGridRef.current = settings.snap;
setWorkspaceSettings((current) => (
workplaneSettingsFingerprint(current, settings.snap) === workplaneSettingsFingerprint(nextWorkspace, settings.snap)
? current
: nextWorkspace
));
setSnapGrid(settings.snap);
if (!projectId || !onProjectWorkspaceChange) {
return;
}
onProjectWorkspaceChange({ projectId, ...settings, placementElevation });
onProjectWorkspaceChange({ projectId, workspace: nextWorkspace, snap: settings.snap, placementElevation });
},
[onProjectWorkspaceChange, placementElevation, projectId],
);
@@ -6377,7 +6471,12 @@ export function SketchForgeEditor({
if (!projectChanged && incomingSerialized === projectShapesFingerprint(shapes)) {
return;
}
const hydratedHistory = hydrateEditorHistoryState(incoming, initialHistory, initialHistoryIndex);
const hydratedHistory = hydrateEditorHistoryState(
incoming,
initialHistory,
initialHistoryIndex,
normalizeWorkspaceSettings(initialWorkspace).historyLimit,
);
projectHydratingRef.current = true;
shapesRef.current = incoming;
selectedIdsRef.current = [];
@@ -6387,8 +6486,8 @@ export function SketchForgeEditor({
setSelectedIds([]);
setHistory(hydratedHistory.entries);
setHistoryIndex(hydratedHistory.index);
setNotice(incoming.length ? "Project synced" : "Ready");
}, [initialAssets, initialHistory, initialHistoryIndex, initialPlacementElevation, initialShapes, projectId, projectInteractionActive, projectRevision]);
setNotice("Ready");
}, [initialAssets, initialHistory, initialHistoryIndex, initialPlacementElevation, initialShapes, projectId, projectRevision]);
useEffect(() => {
if (!projectId || !onProjectShapesChange) {
@@ -6850,7 +6949,7 @@ export function SketchForgeEditor({
sharpAngle: 25,
chamferAngle: 45,
quality: "standard",
tangentChain: true,
tangentChain: defaultCadModifierTangentChain(appliedEdgeTreatmentCount),
preserveEdgeSize: selectedShape.edgeResizeMode === "preserve",
busy: true,
prepared: false,
@@ -8533,8 +8632,8 @@ export function SketchForgeEditor({
selected={sketchSelection}
measurement={sketchMeasurement}
pendingMeasurementStart={sketchMeasureStart}
initialSnap={initialSnap}
initialWorkspace={initialWorkspace}
initialSnap={snapGrid}
initialWorkspace={workspaceSettings}
onPlanePoint={addSketchPlanePoint}
onPointPress={pressSketchPoint}
onSelectSegment={(id) => {
@@ -8574,8 +8673,8 @@ export function SketchForgeEditor({
mirrorReferenceShapes={shapes}
placementElevation={placementElevation}
workplaneMode={workplaneMode}
initialSnap={initialSnap}
initialWorkspace={initialWorkspace}
initialSnap={snapGrid}
initialWorkspace={workspaceSettings}
workspaceSettingsKey={projectId ?? "local-workplane"}
onAddShape={addShape}
onAlignAnchorChange={chooseAlignAnchor}
@@ -8599,6 +8698,9 @@ export function SketchForgeEditor({
modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []}
selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []}
onModifierEdgeToggle={toggleModifierEdge}
themePreference={themePreference}
resolvedTheme={resolvedTheme}
onThemePreferenceChange={onThemePreferenceChange}
/>
)}
</div>
File diff suppressed because it is too large Load Diff
@@ -363,8 +363,24 @@ export function ShapeInspector({
const [gearHelixOpen, setGearHelixOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
const [minimized, setMinimized] = useState(false);
const customColorInputRef = useRef<HTMLInputElement>(null);
useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]);
useEffect(() => {
const input = customColorInputRef.current;
if (!colorOpen || !input) {
return;
}
// React's color-input onChange follows the native input event and fires for
// every movement in the picker. Commit only the native change event, which
// fires after the user finishes choosing, so dragging stays responsive.
const commitCustomColor = () => {
onUpdate({ color: input.value, hole: false });
};
input.addEventListener("change", commitCustomColor);
return () => input.removeEventListener("change", commitCustomColor);
}, [colorOpen, onUpdate]);
useLayoutEffect(() => {
inspectorRef.current?.scrollTo({ top: 0, left: 0 });
}, [isSketchRevolve, shape.id]);
@@ -446,15 +462,13 @@ export function ShapeInspector({
))}
<label className={locked ? "custom-color disabled" : "custom-color"} title="Custom color">
<input
key={`${shape.id}-${solidColor}`}
ref={customColorInputRef}
type="color"
value={solidColor}
defaultValue={solidColor}
disabled={locked}
onFocus={() => onInteractionActiveChange?.(true)}
onBlur={() => onInteractionActiveChange?.(false)}
onChange={(event) => {
onUpdate({ color: event.target.value, hole: false });
setColorOpen(false);
}}
/>
<span>Custom</span>
</label>
@@ -33,6 +33,7 @@ export function TransformOverlay({
rotationWheelAxis,
pinnedRotationWheelView,
onBeginCameraDrag,
onCameraWheel,
onBeginTransform,
onMoveTransform,
onFinishTransform,
@@ -67,7 +68,9 @@ export function TransformOverlay({
};
});
const activeAngle = rotationReadout?.angle ?? 0;
const activeRadians = THREE.MathUtils.degToRad(activeAngle - 90);
const activeRadians = rotationReadout?.pointerAngle === undefined
? THREE.MathUtils.degToRad(activeAngle - 90)
: THREE.MathUtils.degToRad(rotationReadout.pointerAngle);
const activeLine = {
x: Math.cos(activeRadians) * 92,
y: Math.sin(activeRadians) * 92,
@@ -79,10 +82,13 @@ export function TransformOverlay({
<div
className={`transform-overlay ${hideSelectionChrome ? "hide-selection-chrome" : ""}`}
onPointerDownCapture={(event) => {
if (event.button === 2) {
if (event.button === 1 || event.button === 2) {
onHoverMeasure(null);
onPinMeasure(null);
onBeginCameraDrag(event);
}
}}
onWheelCapture={onCameraWheel}
onContextMenu={(event) => {
event.preventDefault();
event.stopPropagation();
@@ -94,7 +100,11 @@ export function TransformOverlay({
aria-hidden="true"
viewBox={`0 0 ${box.width} ${box.height}`}
preserveAspectRatio="none"
onPointerDown={(event) => onBeginTransform("rotate", `rotate-wheel-${rotationWheelAxis}`, event)}
onPointerDown={(event) => {
if (event.button === 0) {
onBeginTransform("rotate", `rotate-wheel-${rotationWheelAxis}`, event);
}
}}
onPointerMove={(event) => onMoveTransform(event.clientX, event.clientY, event.shiftKey, event.altKey)}
onPointerUp={onFinishTransform}
onPointerCancel={onFinishTransform}
@@ -196,9 +206,18 @@ export function TransformOverlay({
className={`transform-handle ${handle.className}`}
style={{ "--overlay-x": `${handle.x}px`, "--overlay-y": `${handle.y}px` } as CSSProperties}
title={handle.title}
onPointerEnter={() => onHoverMeasure(handle.kind === "lift" ? null : handleMeasureKey(handle))}
onPointerEnter={(event) => {
if ((event.buttons & 4) !== 0) {
onHoverMeasure(null);
return;
}
onHoverMeasure(handle.kind === "lift" ? null : handleMeasureKey(handle));
}}
onPointerLeave={() => onHoverMeasure(null)}
onPointerDown={(event) => {
if (event.button !== 0) {
return;
}
onPinMeasure(handleMeasureKey(handle));
onBeginTransform(handle.kind, handle.key, event);
}}
@@ -219,7 +238,11 @@ export function TransformOverlay({
className={`rotate-handle ${handle.className}`}
style={{ "--overlay-x": `${handle.x}px`, "--overlay-y": `${handle.y}px`, "--rotate-handle-angle": `${handle.angle}deg` } as CSSProperties}
title="Rotate"
onPointerDown={(event) => onBeginTransform("rotate", handle.key, event)}
onPointerDown={(event) => {
if (event.button === 0) {
onBeginTransform("rotate", handle.key, event);
}
}}
onPointerMove={(event) => onMoveTransform(event.clientX, event.clientY, event.shiftKey, event.altKey)}
onPointerUp={onFinishTransform}
onPointerCancel={onFinishTransform}
@@ -1,13 +1,16 @@
"use client";
import { Grid3X3, Palette, Ruler, X } from "lucide-react";
import { useEffect, useState } from "react";
import { 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 { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
type WorkspaceSettings = WorkplaneWorkspaceSettings;
type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane";
type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane" | "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;
@@ -23,6 +26,8 @@ const WORKSPACE_SIZE_PRESETS = [
{ 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;
const HISTORY_LIMIT_OPTIONS = [30, 50, 100, "unlimited", "custom"] as const;
const HISTORY_CUSTOM_DEFAULT = 250;
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
@@ -35,18 +40,26 @@ function gridBlockSizeForPreset(preset: string, fallback: number) {
return clamp(Number.parseFloat(preset) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
}
function isHistoryLimitPreset(value: unknown): value is 30 | 50 | 100 {
return value === 30 || value === 50 || value === 100;
}
export function WorkspaceSettingsModal({
workspace,
snap,
themePreference,
onWorkspaceChange,
onSnapChange,
onThemePreferenceChange,
onMakeDefault,
onClose,
}: {
workspace: WorkspaceSettings;
snap: GridSize;
themePreference: AppThemePreference;
onWorkspaceChange: (next: WorkspaceSettings) => void;
onSnapChange: (next: GridSize) => void;
onThemePreferenceChange?: (preference: AppThemePreference) => void;
onMakeDefault: () => void;
onClose: () => void;
}) {
@@ -57,8 +70,20 @@ export function WorkspaceSettingsModal({
depth: workspace.depth.toFixed(workspace.accuracy),
}));
const [gridBlockSizeDraft, setGridBlockSizeDraft] = useState(() => workspace.gridBlockSize.toFixed(workspace.accuracy));
const [customHistoryDraft, setCustomHistoryDraft] = useState(() =>
typeof workspace.historyLimit === "number" && !isHistoryLimitPreset(workspace.historyLimit)
? String(workspace.historyLimit)
: String(HISTORY_CUSTOM_DEFAULT),
);
const historyLimitMode: (typeof HISTORY_LIMIT_OPTIONS)[number] = workspace.historyLimit === "unlimited" || isHistoryLimitPreset(workspace.historyLimit)
? workspace.historyLimit
: "custom";
const historyLimitIndex = HISTORY_LIMIT_OPTIONS.indexOf(historyLimitMode);
const scaleOptions = scaleOptionsForUnits(workspace.units);
const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale);
const gridColor = /^#[0-9a-f]{6}$/i.test(workspace.gridColor)
? workspace.gridColor
: DEFAULT_WORKPLANE_WORKSPACE.gridColor;
useEffect(() => {
setDimensionDrafts({
width: workspace.width.toFixed(workspace.accuracy),
@@ -68,6 +93,11 @@ export function WorkspaceSettingsModal({
useEffect(() => {
setGridBlockSizeDraft(workspace.gridBlockSize.toFixed(workspace.accuracy));
}, [workspace.accuracy, workspace.gridBlockSize]);
useEffect(() => {
if (typeof workspace.historyLimit === "number" && !isHistoryLimitPreset(workspace.historyLimit)) {
setCustomHistoryDraft(String(workspace.historyLimit));
}
}, [workspace.historyLimit]);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false);
const next = { ...workspace, ...patch };
@@ -96,6 +126,20 @@ export function WorkspaceSettingsModal({
setGridBlockSizeDraft(next.toFixed(workspace.accuracy));
patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
};
const setHistoryLimitMode = (mode: (typeof HISTORY_LIMIT_OPTIONS)[number]) => {
if (mode === "custom") {
const parsed = Number.parseInt(customHistoryDraft, 10);
patchWorkspace({ historyLimit: Number.isFinite(parsed) ? clamp(parsed, 1, 5000) : HISTORY_CUSTOM_DEFAULT });
return;
}
patchWorkspace({ historyLimit: mode });
};
const setCustomHistoryLimit = (value: string) => {
const parsed = Number.parseInt(value, 10);
const next = Number.isFinite(parsed) ? Math.round(clamp(parsed, 1, 5000)) : HISTORY_CUSTOM_DEFAULT;
setCustomHistoryDraft(String(next));
patchWorkspace({ historyLimit: next });
};
return (
<div className="workspace-modal" role="dialog" aria-modal="true" aria-label="Workspace settings">
@@ -121,6 +165,10 @@ export function WorkspaceSettingsModal({
<Grid3X3 size={18} />
<span>Workplane</span>
</button>
<button className={activeSection === "history" ? "active" : ""} aria-current={activeSection === "history" ? "page" : undefined} onClick={() => setActiveSection("history")}>
<History size={18} />
<span>History</span>
</button>
</nav>
<div className="workspace-modal-content">
@@ -131,8 +179,21 @@ export function WorkspaceSettingsModal({
<strong>Appearance</strong>
<span>Adjust the canvas and navigation behavior.</span>
</div>
<label className="workspace-select">
<span>Theme</span>
<select
value={themePreference}
onChange={(event) => onThemePreferenceChange?.(event.currentTarget.value as AppThemePreference)}
>
{APP_THEME_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
<p className="workspace-global-note">Theme applies across SketchForge and all projects.</p>
<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}
@@ -238,6 +299,7 @@ export function WorkspaceSettingsModal({
</label>
</div>
<WorkspaceSelect label="Grid block size" value={workspace.gridBlockPreset} options={GRID_BLOCK_PRESETS} onChange={setGridBlockPreset} />
<GridColorControl color={gridColor} onChange={(nextGridColor) => patchWorkspace({ gridColor: nextGridColor })} />
{workspace.gridBlockPreset === "Custom" ? (
<div className="workspace-dimensions workspace-grid-dimensions">
<label>
@@ -257,6 +319,59 @@ export function WorkspaceSettingsModal({
) : null}
</>
) : null}
{activeSection === "history" ? (
<>
<div className="workspace-section-heading">
<strong>Saved history</strong>
<span>Choose how many completed actions remain available after saving or reopening this project.</span>
</div>
<div className="workspace-history-setting">
<div
className="workspace-history-range-control"
data-limit={String(historyLimitMode)}
>
<input
type="range"
min={0}
max={HISTORY_LIMIT_OPTIONS.length - 1}
step={1}
value={historyLimitIndex}
aria-label="Saved history actions"
aria-valuetext={historyLimitMode === "unlimited" ? "Unlimited" : historyLimitMode === "custom" ? `${workspace.historyLimit} actions` : `${historyLimitMode} actions`}
onChange={(event) => setHistoryLimitMode(HISTORY_LIMIT_OPTIONS[Number(event.currentTarget.value)] ?? "unlimited")}
/>
</div>
<div className="workspace-history-labels" aria-hidden="true">
{HISTORY_LIMIT_OPTIONS.map((option) => (
<span key={option} className={historyLimitMode === option ? "active" : undefined}>
{option === "unlimited" ? "Unlimited" : option === "custom" ? "Custom" : option}
</span>
))}
</div>
{historyLimitMode === "custom" ? (
<label className="workspace-history-custom">
<span>Actions to retain</span>
<input
type="number"
min={1}
max={5000}
step={1}
value={customHistoryDraft}
onChange={(event) => setCustomHistoryDraft(event.currentTarget.value)}
onBlur={(event) => setCustomHistoryLimit(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
</label>
) : null}
<p className="workspace-history-note">
Unlimited is the default. Lower limits permanently discard older Undo states from this project.
</p>
</div>
</>
) : null}
</div>
<div className="workspace-modal-footer">
@@ -279,6 +394,216 @@ export function WorkspaceSettingsModal({
);
}
const GRID_COLOR_PRESETS = [
DEFAULT_WORKPLANE_WORKSPACE.gridColor,
"#0e69f1",
"#23a66f",
"#e0842f",
"#dc5252",
"#945bd4",
"#718695",
] as const;
function GridColorControl({ color, onChange }: { color: string; onChange: (color: string) => void }) {
const [open, setOpen] = useState(false);
const [draftColor, setDraftColor] = useState(color);
const draftColorRef = useRef(color);
const pickerCommitAbortRef = useRef<AbortController | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const popoverRef = useRef<HTMLDivElement>(null);
const previewColor = (nextColor: string) => {
draftColorRef.current = nextColor;
setDraftColor(nextColor);
};
const commitDraftColor = () => {
onChange(draftColorRef.current);
};
const armPickerCommit = (event: React.PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
pickerCommitAbortRef.current?.abort();
const controller = new AbortController();
pickerCommitAbortRef.current = controller;
const finish = () => {
commitDraftColor();
controller.abort();
if (pickerCommitAbortRef.current === controller) {
pickerCommitAbortRef.current = null;
}
};
window.addEventListener("pointerup", finish, { once: true, signal: controller.signal });
window.addEventListener("pointercancel", finish, { once: true, signal: controller.signal });
};
useEffect(() => () => pickerCommitAbortRef.current?.abort(), []);
useEffect(() => {
if (!open) {
previewColor(color);
}
}, [color, open]);
useEffect(() => {
if (!open) return;
const closeOnOutsidePointer = (event: PointerEvent) => {
const target = event.target as Node;
if (!rootRef.current?.contains(target) && !popoverRef.current?.contains(target)) {
setOpen(false);
}
};
document.addEventListener("pointerdown", closeOnOutsidePointer);
return () => document.removeEventListener("pointerdown", closeOnOutsidePointer);
}, [open]);
useLayoutEffect(() => {
if (!open) return;
const updatePopoverPosition = () => {
const trigger = triggerRef.current;
if (!trigger) return;
const triggerRect = trigger.getBoundingClientRect();
const viewportPadding = 12;
const gap = 8;
const width = Math.min(286, Math.max(220, window.innerWidth - viewportPadding * 2));
const measuredHeight = popoverRef.current?.offsetHeight ?? 320;
const roomBelow = window.innerHeight - triggerRect.bottom - viewportPadding;
const roomAbove = triggerRect.top - viewportPadding;
const openAbove = roomBelow < measuredHeight + gap && roomAbove > roomBelow;
const preferredTop = openAbove
? triggerRect.top - measuredHeight - gap
: triggerRect.bottom + gap;
const top = Math.min(
Math.max(viewportPadding, preferredTop),
Math.max(viewportPadding, window.innerHeight - measuredHeight - viewportPadding),
);
const left = Math.min(
Math.max(viewportPadding, triggerRect.right - width),
Math.max(viewportPadding, window.innerWidth - width - viewportPadding),
);
const popover = popoverRef.current;
if (!popover) return;
popover.style.top = `${top}px`;
popover.style.left = `${left}px`;
popover.style.width = `${width}px`;
popover.style.visibility = "visible";
};
updatePopoverPosition();
window.addEventListener("resize", updatePopoverPosition);
window.addEventListener("scroll", updatePopoverPosition, true);
return () => {
window.removeEventListener("resize", updatePopoverPosition);
window.removeEventListener("scroll", updatePopoverPosition, true);
};
}, [open]);
const popover = open && typeof document !== "undefined"
? createPortal(
<div
ref={popoverRef}
className="workspace-color-popover"
role="group"
aria-label="Grid color picker"
onKeyDown={(event) => {
if (event.key === "Escape") {
setOpen(false);
triggerRef.current?.focus();
}
}}
>
<div onPointerDownCapture={armPickerCommit}>
<HexColorPicker
className="workspace-hex-color-picker"
color={draftColor}
onChange={previewColor}
onChangeEnd={(nextColor) => {
previewColor(nextColor);
onChange(nextColor);
}}
/>
</div>
<div className="workspace-color-presets" aria-label="Grid color presets">
{GRID_COLOR_PRESETS.map((preset) => (
<button
key={preset}
className={preset.toLowerCase() === draftColor.toLowerCase() ? "selected" : ""}
type="button"
aria-label={`Use grid color ${preset}`}
aria-pressed={preset.toLowerCase() === draftColor.toLowerCase()}
style={{ backgroundColor: preset }}
onClick={() => {
previewColor(preset);
onChange(preset);
}}
/>
))}
</div>
<div className="workspace-color-popover-footer">
<label>
<span>HEX</span>
<HexColorInput
color={draftColor}
onChange={previewColor}
onBlur={commitDraftColor}
prefixed
aria-label="Grid color hexadecimal value"
/>
</label>
<button
className="workspace-color-reset"
type="button"
title="Reset grid color"
aria-label="Reset grid color"
onClick={() => {
previewColor(DEFAULT_WORKPLANE_WORKSPACE.gridColor);
onChange(DEFAULT_WORKPLANE_WORKSPACE.gridColor);
}}
>
<RotateCcw size={15} />
</button>
</div>
</div>,
document.body,
)
: null;
return (
<div className="workspace-row workspace-grid-color-row">
<span>Grid color</span>
<div
className="workspace-color-control"
ref={rootRef}
onKeyDown={(event) => {
if (event.key === "Escape") setOpen(false);
}}
>
<button
ref={triggerRef}
className="workspace-color-trigger"
type="button"
aria-label={`Grid color ${color}`}
aria-haspopup="dialog"
aria-expanded={open}
onClick={() => {
if (!open) {
previewColor(color);
}
setOpen((current) => !current);
}}
>
<span className="workspace-color-swatch" style={{ backgroundColor: color }} aria-hidden="true" />
<span>{color.toUpperCase()}</span>
<ChevronDown className={open ? "open" : ""} size={15} aria-hidden="true" />
</button>
{popover}
</div>
</div>
);
}
function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
return (
<label className="workspace-toggle">
@@ -1,4 +1,4 @@
import type { PointerEvent as ReactPointerEvent } from "react";
import type { PointerEvent as ReactPointerEvent, WheelEvent as ReactWheelEvent } from "react";
export type TransformHandleKind = "scale" | "height" | "lift" | "rotate";
export type RotationAxis = "x" | "y" | "z";
@@ -59,6 +59,7 @@ export type RotationReadout = {
y: number;
text: string;
angle?: number;
pointerAngle?: number;
} | null;
export type EditingDimension = {
@@ -89,6 +90,7 @@ export type TransformOverlayProps = {
rotationWheelAxis: RotationAxis;
pinnedRotationWheelView: PinnedRotationWheelView | null;
onBeginCameraDrag: (event: ReactPointerEvent<Element>) => void;
onCameraWheel: (event: ReactWheelEvent<Element>) => void;
onBeginTransform: (kind: TransformHandleKind, handleKey: string, event: ReactPointerEvent<Element>) => void;
onMoveTransform: (clientX: number, clientY: number, shiftKey?: boolean, altKey?: boolean) => boolean;
onFinishTransform: (event: ReactPointerEvent<Element>) => void;