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
Binary file not shown.

After

Width:  |  Height:  |  Size: 293 KiB

File diff suppressed because it is too large Load Diff
+351 -32
View File
@@ -3,10 +3,12 @@
import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import { applyAppTheme, readStoredAppTheme, resolveAppTheme, storeAppTheme, type AppThemePreference, type ResolvedAppTheme } from "@/lib/appTheme";
import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
import { createLocalId } from "@/lib/localIds";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
import { hydrateProjectShapeState, type ImportedMeshResource } from "@/lib/projectShapePersistence";
import { exportSkfProject, importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -55,20 +57,50 @@ type ProjectShapeCacheEntry = {
type ProjectShapeRecord = {
id: string;
revision: number;
shapes: WorkplaneShape[];
skfPackage?: Uint8Array;
shapes?: WorkplaneShape[];
history?: EditorHistoryEntry[];
historyIndex?: number;
assets?: ProjectAsset[];
meshResourceIds?: string[];
assetResourceIds?: string[];
updatedAt: number;
};
type ProjectShapeSaveContext = {
projectName: string;
createdAt: number;
workspace: WorkplaneWorkspaceSettings;
snapGrid: GridSize;
placementElevation: number;
};
type ProjectShapeResourceRecord =
| {
id: string;
projectId: string;
resourceId: string;
kind: "mesh";
mesh: ImportedMeshResource;
}
| {
id: string;
projectId: string;
resourceId: string;
kind: "asset";
asset: ProjectAsset;
};
const PROJECTS_STORAGE_KEY = "sketchForge.projects";
const PROJECT_SHAPES_DB_NAME = "sketchForge.projectShapes";
const PROJECT_SHAPES_STORE_NAME = "projectShapes";
const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources";
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"];
const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
const EDITOR_SKELETON_MIN_DURATION_MS = 320;
const knownProjectResourceKeys = new Map<string, Set<string>>();
function formatUpdated(timestamp: number) {
const age = Date.now() - timestamp;
@@ -101,6 +133,35 @@ function projectShapeCacheEntry(
};
}
function projectShapeCacheEntryFromEditor(
revision: number,
shapes: WorkplaneShape[],
history: EditorHistoryEntry[],
historyIndex: number,
assets: ProjectAsset[],
): ProjectShapeCacheEntry {
if (history.length === 0) {
return projectShapeCacheEntry(revision, shapes, history, historyIndex, assets);
}
return {
revision,
shapes,
history,
historyIndex: Math.min(Math.max(0, historyIndex), history.length - 1),
assets: dedupeProjectAssets(assets),
};
}
function projectShapeSaveContext(project: Pick<DashboardProject, "name" | "createdAt" | "workspace" | "snapGrid" | "placementElevation">): ProjectShapeSaveContext {
return {
projectName: project.name,
createdAt: project.createdAt,
workspace: normalizeWorkspaceSettings(project.workspace),
snapGrid: normalizeSnapGrid(project.snapGrid),
placementElevation: Number.isFinite(project.placementElevation) ? project.placementElevation ?? 0 : 0,
};
}
function openProjectShapesDb() {
return new Promise<IDBDatabase>((resolve, reject) => {
if (typeof window === "undefined" || !window.indexedDB) {
@@ -108,34 +169,123 @@ function openProjectShapesDb() {
return;
}
const request = window.indexedDB.open(PROJECT_SHAPES_DB_NAME, 1);
const request = window.indexedDB.open(PROJECT_SHAPES_DB_NAME, 3);
request.onupgradeneeded = () => {
const database = request.result;
if (!database.objectStoreNames.contains(PROJECT_SHAPES_STORE_NAME)) {
database.createObjectStore(PROJECT_SHAPES_STORE_NAME, { keyPath: "id" });
}
if (!database.objectStoreNames.contains(PROJECT_SHAPE_RESOURCES_STORE_NAME)) {
database.createObjectStore(PROJECT_SHAPE_RESOURCES_STORE_NAME, { keyPath: "id" });
}
};
request.onerror = () => reject(request.error ?? new Error("Could not open project shape storage"));
request.onsuccess = () => resolve(request.result);
});
}
function projectResourceKey(kind: ProjectShapeResourceRecord["kind"], resourceId: string) {
return `${kind}:${resourceId}`;
}
function projectResourceRecordId(projectId: string, kind: ProjectShapeResourceRecord["kind"], resourceId: string) {
return `${projectId}:${projectResourceKey(kind, resourceId)}`;
}
async function loadProjectShapes(projectId: string) {
const database = await openProjectShapesDb();
return new Promise<ProjectShapeRecord | null>((resolve, reject) => {
const record = await new Promise<ProjectShapeRecord | null>((resolve, reject) => {
const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readonly");
const request = transaction.objectStore(PROJECT_SHAPES_STORE_NAME).get(projectId);
request.onerror = () => reject(request.error ?? new Error("Could not load project shapes"));
request.onsuccess = () => resolve((request.result as ProjectShapeRecord | undefined) ?? null);
transaction.oncomplete = () => database.close();
transaction.onerror = () => {
transaction.onerror = () => reject(transaction.error ?? new Error("Could not load project shapes"));
});
if (!record) {
database.close();
reject(transaction.error ?? new Error("Could not load project shapes"));
return null;
}
if (record.skfPackage) {
database.close();
const restored = await importSkfProject(record.skfPackage);
return {
...record,
shapes: restored.shapes,
history: restored.history,
historyIndex: restored.historyIndex,
assets: restored.assets,
};
}
const meshResourceIds = record.meshResourceIds ?? [];
const assetResourceIds = record.assetResourceIds ?? [];
if (meshResourceIds.length === 0 && assetResourceIds.length === 0) {
database.close();
return {
...record,
shapes: record.shapes ?? [],
};
}
const resourceRecords = await new Promise<ProjectShapeResourceRecord[]>((resolve, reject) => {
const transaction = database.transaction(PROJECT_SHAPE_RESOURCES_STORE_NAME, "readonly");
const store = transaction.objectStore(PROJECT_SHAPE_RESOURCES_STORE_NAME);
const records: ProjectShapeResourceRecord[] = [];
const requests = [
...meshResourceIds.map((resourceId) => store.get(projectResourceRecordId(projectId, "mesh", resourceId))),
...assetResourceIds.map((resourceId) => store.get(projectResourceRecordId(projectId, "asset", resourceId))),
];
requests.forEach((request) => {
request.onsuccess = () => {
if (request.result) records.push(request.result as ProjectShapeResourceRecord);
};
request.onerror = () => {
transaction.abort();
};
});
transaction.oncomplete = () => resolve(records);
transaction.onerror = () => reject(transaction.error ?? new Error("Could not load project shape resources"));
transaction.onabort = () => reject(transaction.error ?? new Error("Could not load project shape resources"));
});
database.close();
const meshResources = new Map<string, ImportedMeshResource>();
const assets: ProjectAsset[] = [];
resourceRecords.forEach((resource) => {
if (resource.kind === "mesh") meshResources.set(resource.resourceId, resource.mesh);
else assets.push(resource.asset);
});
if (meshResources.size !== meshResourceIds.length || assets.length !== assetResourceIds.length) {
throw new Error("Project shape resources are incomplete");
}
knownProjectResourceKeys.set(projectId, new Set([
...meshResourceIds.map((resourceId) => projectResourceKey("mesh", resourceId)),
...assetResourceIds.map((resourceId) => projectResourceKey("asset", resourceId)),
]));
const hydrated = hydrateProjectShapeState(record.shapes ?? [], record.history, meshResources);
return {
...record,
shapes: hydrated.shapes,
history: hydrated.history,
assets,
};
}
async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntry) {
async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntry, context: ProjectShapeSaveContext) {
const skfPackage = await exportSkfProject({
projectId,
projectName: context.projectName,
createdAt: context.createdAt,
modifiedAt: entry.revision,
shapes: entry.shapes,
history: entry.history,
historyIndex: entry.historyIndex,
assets: entry.assets,
workspace: context.workspace,
snapGrid: context.snapGrid,
placementElevation: context.placementElevation,
compressionLevel: 1,
});
const database = await openProjectShapesDb();
return new Promise<void>((resolve, reject) => {
const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite");
@@ -149,7 +299,12 @@ async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntr
if (existing && existing.revision > entry.revision) {
return;
}
store.put({ id: projectId, ...entry, updatedAt: Date.now() } satisfies ProjectShapeRecord);
store.put({
id: projectId,
revision: entry.revision,
skfPackage,
updatedAt: Date.now(),
} satisfies ProjectShapeRecord);
};
transaction.oncomplete = () => {
database.close();
@@ -166,6 +321,23 @@ async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntr
});
}
function saveProjectShapesWhenIdle(projectId: string, entry: ProjectShapeCacheEntry, context: ProjectShapeSaveContext) {
return new Promise<void>((resolve, reject) => {
const save = () => {
void saveProjectShapes(projectId, entry, context).then(resolve, reject);
};
if (typeof window === "undefined") {
save();
return;
}
if ("requestIdleCallback" in window) {
window.requestIdleCallback(save, { timeout: 1200 });
return;
}
globalThis.setTimeout(save, 32);
});
}
async function deleteProjectShapes(projectId: string) {
const database = await openProjectShapesDb();
return new Promise<void>((resolve, reject) => {
@@ -241,9 +413,9 @@ function mergeProjectForStorage(project: DashboardProject, storedProject?: Dashb
thumbnailUrl: project.thumbnailUrl ?? storedProject.thumbnailUrl,
thumbnailVersion: project.thumbnailVersion ?? storedProject.thumbnailVersion,
updatedAt: Math.max(project.updatedAt, storedProject.updatedAt),
workspace: project.workspace ?? storedProject.workspace,
snapGrid: project.snapGrid ?? storedProject.snapGrid,
placementElevation: project.placementElevation ?? storedProject.placementElevation,
workspace: storedProject.workspace ?? project.workspace,
snapGrid: storedProject.snapGrid ?? project.snapGrid,
placementElevation: storedProject.placementElevation ?? project.placementElevation,
sharedProject: project.sharedProject ?? storedProject.sharedProject,
};
}
@@ -296,6 +468,7 @@ export default function Home() {
const [mounted, setMounted] = useState(false);
const [view, setView] = useState<AppView>("dashboard");
const [editorStarted, setEditorStarted] = useState(false);
const [editorLoading, setEditorLoading] = useState(false);
const [activeProjectId, setActiveProjectId] = useState<string | null>(null);
const [projects, setProjects] = useState<DashboardProject[]>([]);
const [dashboardSection, setDashboardSection] = useState<DashboardSection>("home");
@@ -303,6 +476,8 @@ export default function Home() {
const [viewMode, setViewMode] = useState<ViewMode>("grid");
const [sortMode, setSortMode] = useState("recent");
const [settingsOpen, setSettingsOpen] = useState(false);
const [themePreference, setThemePreference] = useState<AppThemePreference>("system");
const [resolvedTheme, setResolvedTheme] = useState<ResolvedAppTheme>("light");
const [downloadMode, setDownloadMode] = useState<DownloadMode>("browser");
const [downloadFolder, setDownloadFolder] = useState("");
const [dashboardNotice, setDashboardNotice] = useState("");
@@ -314,6 +489,12 @@ export default function Home() {
const dashboardImportInputRef = useRef<HTMLInputElement | null>(null);
const nextProjectRevisionRef = useRef(0);
const projectShapeSaveQueuesRef = useRef<Record<string, Promise<void>>>({});
const editorLoadingStartedAtRef = useRef(0);
const startEditorTransition = useCallback(() => {
editorLoadingStartedAtRef.current = Date.now();
setEditorLoading(true);
}, []);
const refreshSharedProjects = useCallback(async () => {
if (STATIC_EXPORT_BUILD) return;
@@ -333,19 +514,19 @@ export default function Home() {
}, []);
useEffect(() => {
document.documentElement.removeAttribute("data-theme");
document.documentElement.style.colorScheme = "light";
try {
window.localStorage.removeItem("sketchForge.theme");
} catch {
// Light mode still applies when browser storage is unavailable.
}
const storedTheme = readStoredAppTheme(window.localStorage);
setThemePreference(storedTheme);
const systemPrefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
setResolvedTheme(resolveAppTheme(storedTheme, systemPrefersDark));
applyAppTheme(storedTheme, systemPrefersDark);
const { projects: storedProjects, legacyShapes } = readStoredProjects();
setProjects(storedProjects);
if (Object.keys(legacyShapes).length > 0) {
setProjectShapesById(legacyShapes);
Object.entries(legacyShapes).forEach(([projectId, entry]) => {
void saveProjectShapes(projectId, entry).catch(() => {
const project = storedProjects.find((candidate) => candidate.id === projectId);
if (!project) return;
void saveProjectShapes(projectId, entry, projectShapeSaveContext(project)).catch(() => {
setDashboardNotice("Could not migrate project shapes to larger storage");
});
});
@@ -359,11 +540,26 @@ export default function Home() {
if (requestedProjectId && storedProjects.some((project) => project.id === requestedProjectId)) {
setActiveProjectId(requestedProjectId);
}
startEditorTransition();
setEditorStarted(true);
setView("editor");
}
setMounted(true);
}, []);
}, [startEditorTransition]);
useEffect(() => {
if (!mounted) return;
const media = window.matchMedia("(prefers-color-scheme: dark)");
const applyCurrentTheme = () => {
setResolvedTheme(resolveAppTheme(themePreference, media.matches));
applyAppTheme(themePreference, media.matches);
};
storeAppTheme(window.localStorage, themePreference);
applyCurrentTheme();
if (themePreference !== "system") return;
media.addEventListener("change", applyCurrentTheme);
return () => media.removeEventListener("change", applyCurrentTheme);
}, [mounted, themePreference]);
useEffect(() => {
if (!mounted) return;
@@ -419,7 +615,7 @@ export default function Home() {
const activeProject = projects.find((project) => project.id === activeProjectId);
if (!activeProject) return;
const cached = projectShapesById[activeProjectId];
if (cached && cached.revision === activeProject.revision) return;
if (cached && cached.revision >= (activeProject.revision ?? 0)) return;
let canceled = false;
void loadProjectShapes(activeProjectId)
@@ -431,6 +627,11 @@ export default function Home() {
...current,
[activeProjectId]: entry,
}));
if (record && !record.skfPackage) {
void saveProjectShapesWhenIdle(activeProjectId, entry, projectShapeSaveContext(activeProject)).catch(() => {
// The legacy record remains readable and migration can retry on the next load.
});
}
})
.catch((error) => {
if (!canceled) {
@@ -446,6 +647,22 @@ export default function Home() {
};
}, [activeProjectId, mounted, projectShapesById, projects]);
useEffect(() => {
if (!editorLoading || view !== "editor") return;
if (activeProjectId) {
const activeProject = projects.find((project) => project.id === activeProjectId);
const activeEntry = projectShapesById[activeProjectId];
if (!activeProject || !activeEntry) return;
}
const elapsed = Date.now() - editorLoadingStartedAtRef.current;
const remaining = Math.max(0, EDITOR_SKELETON_MIN_DURATION_MS - elapsed);
const timer = window.setTimeout(() => {
window.requestAnimationFrame(() => setEditorLoading(false));
}, remaining);
return () => window.clearTimeout(timer);
}, [activeProjectId, editorLoading, projectShapesById, projects, view]);
useEffect(() => {
if (!mounted) return;
window.localStorage.setItem(DOWNLOAD_MODE_STORAGE_KEY, downloadMode);
@@ -479,6 +696,7 @@ export default function Home() {
} else if (projectId) {
setProjects((current) => current.map((project) => (project.id === projectId ? { ...project, updatedAt: Date.now() } : project)));
}
startEditorTransition();
setActiveProjectId(projectId);
setEditorStarted(true);
setView("editor");
@@ -534,10 +752,15 @@ export default function Home() {
history: EditorHistoryEntry[];
historyIndex: number;
assets: ProjectAsset[];
projectName: string;
projectCreatedAt: number;
workspace: WorkplaneWorkspaceSettings;
snapGrid: GridSize;
placementElevation: number;
}) => {
const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1);
nextProjectRevisionRef.current = revision;
const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex, snapshot.assets);
const entry = projectShapeCacheEntryFromEditor(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex, snapshot.assets);
setProjectShapesById((current) => {
const existing = current[snapshot.projectId];
if (existing && existing.revision > revision) {
@@ -550,7 +773,14 @@ export default function Home() {
});
const previousSave = projectShapeSaveQueuesRef.current[snapshot.projectId] ?? Promise.resolve();
const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, entry));
const saveContext: ProjectShapeSaveContext = {
projectName: snapshot.projectName,
createdAt: snapshot.projectCreatedAt,
workspace: normalizeWorkspaceSettings(snapshot.workspace),
snapGrid: normalizeSnapGrid(snapshot.snapGrid),
placementElevation: Number.isFinite(snapshot.placementElevation) ? snapshot.placementElevation : 0,
};
const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapesWhenIdle(snapshot.projectId, entry, saveContext));
projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave;
void queuedSave
@@ -576,7 +806,8 @@ export default function Home() {
}, []);
const updateProjectWorkspace = useCallback((snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => {
const version = Date.now();
const version = Math.max(Date.now(), nextProjectRevisionRef.current + 1);
nextProjectRevisionRef.current = version;
const workspace = normalizeWorkspaceSettings(snapshot.workspace);
const snapGrid = normalizeSnapGrid(snapshot.snap);
const placementElevation = typeof snapshot.placementElevation === "number" && Number.isFinite(snapshot.placementElevation)
@@ -599,9 +830,19 @@ export default function Home() {
snapGrid,
placementElevation,
updatedAt: version,
revision: version,
};
});
return changed ? next : current;
if (!changed) return current;
try {
const storageProjects = mergeProjectsForStorage(next);
const serialized = JSON.stringify(storageProjects);
window.localStorage.setItem(PROJECTS_STORAGE_KEY, serialized);
projectsJsonRef.current = serialized;
return next;
} catch {
return next;
}
});
}, []);
@@ -611,7 +852,11 @@ export default function Home() {
...current,
[project.id]: projectShapeCacheEntry(project.revision ?? project.updatedAt, []),
}));
void saveProjectShapes(project.id, projectShapeCacheEntry(project.revision ?? project.updatedAt, [])).catch(() => {
void saveProjectShapes(
project.id,
projectShapeCacheEntry(project.revision ?? project.updatedAt, []),
projectShapeSaveContext(project),
).catch(() => {
setDashboardNotice("Could not prepare project shape storage");
});
setProjects((current) => [project, ...current]);
@@ -634,7 +879,7 @@ export default function Home() {
sharedProject: sharedProject ? { fileName: sharedProject.fileName, revision: sharedProject.revision } : undefined,
};
const entry = projectShapeCacheEntry(now, restored.shapes, restored.history, restored.historyIndex, restored.assets);
await saveProjectShapes(project.id, entry);
await saveProjectShapes(project.id, entry, projectShapeSaveContext(project));
setProjectShapesById((current) => ({ ...current, [project.id]: entry }));
setProjects((current) => [project, ...current]);
setDashboardNotice(sharedProject ? `Opened shared project ${sharedProject.name}; edits autosave locally until you save back to shared` : `Opened ${file.name} as a new editable local project`);
@@ -755,7 +1000,7 @@ export default function Home() {
const project = newProject(projectName, projects.length, importedShapes.length);
const revision = project.revision ?? project.updatedAt;
const entry = projectShapeCacheEntry(revision, importedShapes, undefined, undefined, dedupeProjectAssets(importedAssets));
await saveProjectShapes(project.id, entry);
await saveProjectShapes(project.id, entry, projectShapeSaveContext(project));
setProjectShapesById((current) => ({
...current,
[project.id]: entry,
@@ -787,6 +1032,7 @@ export default function Home() {
setProjects((current) => current.map((project) => (project.id === activeProjectId ? { ...project, updatedAt: Date.now() } : project)));
}
setDashboardSection("home");
setEditorLoading(false);
setView("dashboard");
if (typeof window !== "undefined") {
window.history.replaceState(null, "", "/");
@@ -919,13 +1165,86 @@ export default function Home() {
projectModifiedAt={activeProject?.updatedAt}
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
sharedProjectsEnabled={sharedProjectsEnabled}
themePreference={themePreference}
resolvedTheme={resolvedTheme}
onThemePreferenceChange={setThemePreference}
/>
</div>
) : null}
{view === "editor" && (editorLoading || !canRenderEditor) ? <EditorLoadingSkeleton /> : null}
</>
);
}
function EditorLoadingSkeleton() {
const leftToolbarSections = [
{ className: "home", controls: 1 },
{ className: "clipboard", controls: 4 },
{ className: "history", controls: 2 },
{ className: "shapes", controls: 1 },
];
const rightToolbarSections = [
{ className: "visibility", controls: 2 },
{ className: "combine", controls: 3 },
{ className: "modify", controls: 5 },
{ className: "arrange", controls: 2 },
{ className: "manage", controls: 3 },
];
const renderToolbarSection = ({ className, controls }: { className: string; controls: number }) => (
<div className={`editor-loading-tool-section ${className}`} key={className}>
<span className="editor-loading-section-label editor-skeleton-shimmer" />
<div className="editor-loading-section-controls">
{Array.from({ length: controls }, (_, index) => (
<span className="editor-loading-tool editor-skeleton-shimmer" key={index} />
))}
</div>
</div>
);
return (
<div className="editor-loading-screen" role="status" aria-label="Loading editor" aria-live="polite">
<div className="editor-loading-toolbar">
<div className="editor-loading-tabs">
<span className="editor-skeleton-shimmer" />
<span className="editor-skeleton-shimmer" />
</div>
<div className="editor-loading-tool-groups">
<div className="editor-loading-tool-cluster">
{leftToolbarSections.map(renderToolbarSection)}
</div>
<span className="editor-loading-toolbar-spacer" />
<div className="editor-loading-tool-cluster">
{rightToolbarSections.map(renderToolbarSection)}
</div>
</div>
</div>
<div className="editor-loading-body">
<div className="editor-loading-viewport">
<div className="editor-loading-view-cube">
<span className="editor-loading-cube-top editor-skeleton-shimmer" />
<span className="editor-loading-cube-left editor-skeleton-shimmer" />
<span className="editor-loading-cube-right editor-skeleton-shimmer" />
</div>
<div className="editor-loading-model" aria-hidden="true">
<span className="editor-loading-model-top editor-skeleton-shimmer" />
<span className="editor-loading-model-front editor-skeleton-shimmer" />
<span className="editor-loading-model-side editor-skeleton-shimmer" />
</div>
<div className="editor-loading-viewport-controls">
{Array.from({ length: 5 }, (_, index) => (
<span className="editor-skeleton-shimmer" key={index} />
))}
</div>
<span className="editor-loading-status editor-skeleton-shimmer" />
<span className="editor-loading-snap editor-skeleton-shimmer" />
</div>
</div>
</div>
);
}
function Dashboard({
dashboardSection,
dashboardNotice,
@@ -1030,10 +1349,10 @@ function Dashboard({
return (
<main className="dashboard-shell">
<header className="dashboard-topbar">
<button className="dashboard-brand" type="button" aria-label="Home">
<img src="assets/sketchforge/sketchforge-logo.png" alt="" />
<a className="dashboard-brand" href="./" aria-label="SketchForge home">
<img src="/assets/sketchforge/sketchforge-logo-white.png" alt="" />
<span>SketchForge</span>
</button>
</a>
<div className="dashboard-search">
<Search size={18} strokeWidth={2.4} />
<input value={query} onChange={(event) => onQueryChange(event.currentTarget.value)} placeholder="Search projects" aria-label="Search projects" />
+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;
+51
View File
@@ -0,0 +1,51 @@
export const APP_THEME_STORAGE_KEY = "sketchForge.theme";
export const APP_THEME_OPTIONS = [
{ value: "system", label: "System" },
{ value: "light", label: "Light" },
{ value: "dark", label: "Dark" },
] as const;
export type AppThemePreference = (typeof APP_THEME_OPTIONS)[number]["value"];
export type ResolvedAppTheme = Exclude<AppThemePreference, "system">;
export function normalizeAppThemePreference(value: unknown): AppThemePreference {
return value === "light" || value === "dark" || value === "system" ? value : "system";
}
export function resolveAppTheme(preference: AppThemePreference, prefersDark: boolean): ResolvedAppTheme {
return preference === "system" ? (prefersDark ? "dark" : "light") : preference;
}
export function readStoredAppTheme(storage: Pick<Storage, "getItem"> | null | undefined): AppThemePreference {
if (!storage) return "system";
try {
return normalizeAppThemePreference(storage.getItem(APP_THEME_STORAGE_KEY));
} catch {
return "system";
}
}
export function storeAppTheme(
storage: Pick<Storage, "setItem"> | null | undefined,
preference: AppThemePreference,
) {
if (!storage) return;
try {
storage.setItem(APP_THEME_STORAGE_KEY, preference);
} catch {
// The selected theme still applies for this session when storage is unavailable.
}
}
export function applyAppTheme(preference: AppThemePreference, prefersDark?: boolean) {
if (typeof document === "undefined") return;
const systemPrefersDark = prefersDark ?? (
typeof window !== "undefined" && typeof window.matchMedia === "function"
? window.matchMedia("(prefers-color-scheme: dark)").matches
: false
);
const resolved = resolveAppTheme(preference, systemPrefersDark);
document.documentElement.dataset.theme = resolved;
document.documentElement.style.colorScheme = resolved;
}
+33
View File
@@ -133,6 +133,39 @@ export function cadModifierPrimitiveForBakedShape(shape: WorkplaneShape): CadMod
};
}
export function bakedBoxSelectionFrame(shape: WorkplaneShape) {
const primitive = cadModifierPrimitiveForBakedShape(shape);
if (!primitive || primitive.kind !== "box") {
return null;
}
const matrix = cadTransformToMatrix(primitive.transform);
const xVector = new THREE.Vector3(primitive.width, 0, 0).applyMatrix3(new THREE.Matrix3().setFromMatrix4(matrix));
const yVector = new THREE.Vector3(0, primitive.height, 0).applyMatrix3(new THREE.Matrix3().setFromMatrix4(matrix));
const zVector = new THREE.Vector3(0, 0, primitive.depth).applyMatrix3(new THREE.Matrix3().setFromMatrix4(matrix));
const width = xVector.length();
const height = yVector.length();
const depth = zVector.length();
if (![width, height, depth].every((value) => Number.isFinite(value) && value > 0.001)) {
return null;
}
const xAxis = xVector.normalize();
const yAxis = yVector.normalize();
const zAxis = zVector.normalize();
const center = new THREE.Vector3(0, primitive.height / 2, 0).applyMatrix4(matrix);
const basis = new THREE.Matrix4().makeBasis(xAxis, yAxis, zAxis);
return {
center,
quaternion: new THREE.Quaternion().setFromRotationMatrix(basis),
xAxis,
yAxis,
zAxis,
width,
height,
depth,
};
}
export function cadBrepTransformForShape(shape: WorkplaneShape) {
const frame = shape.cadBrepFrame;
if (!frame) return undefined;
+48 -1
View File
@@ -1,16 +1,63 @@
import type { CadModifierEdge } from "@/lib/cadModifierTypes";
export const CAD_MODIFIER_RUNTIME_BASE = "/occt";
export const CAD_MODIFIER_REQUEST_TIMEOUT_MS = 30_000;
export const CAD_MODIFIER_MAX_SHARP_ANGLE = 90;
export type CadModifierRequestPhase = "prepare" | "preview";
export function cadTransformRequiresGeneralTransform(transform: number[]) {
if (transform.length !== 12 || !transform.every(Number.isFinite)) {
return false;
}
const x = [transform[0], transform[4], transform[8]];
const y = [transform[1], transform[5], transform[9]];
const z = [transform[2], transform[6], transform[10]];
const dot = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const xLengthSquared = dot(x, x);
const yLengthSquared = dot(y, y);
const zLengthSquared = dot(z, z);
const scaleSquared = Math.max(xLengthSquared, yLengthSquared, zLengthSquared);
if (scaleSquared <= 1e-18) {
return true;
}
const tolerance = scaleSquared * 1e-9;
return (
Math.abs(dot(x, y)) > tolerance ||
Math.abs(dot(x, z)) > tolerance ||
Math.abs(dot(y, z)) > tolerance ||
Math.abs(xLengthSquared - yLengthSquared) > tolerance ||
Math.abs(xLengthSquared - zLengthSquared) > tolerance ||
Math.abs(yLengthSquared - zLengthSquared) > tolerance
);
}
export function isCadModifierWasmMemoryFault(message: string, errorName = "") {
return (
/memory access out of bounds|out of bounds memory access|\bwasm\b|\babort(?:ed)?\b/i.test(message) ||
/memory access out of bounds|out of bounds memory access|\babort(?:ed)?\b/i.test(message) ||
/^(?:WebAssembly\.)?RuntimeError$/i.test(errorName)
);
}
export function defaultCadModifierTangentChain(appliedFeatureCount: number) {
return appliedFeatureCount === 0;
}
export function cadModifierTopologyEdgeIsSelectable(
edge: Pick<CadModifierEdge, "manifold" | "boundary" | "points">,
) {
return edge.manifold && !edge.boundary && edge.points.length >= 6;
}
export function selectableCadModifierEdge(
edge: Pick<CadModifierEdge, "display" | "selectable" | "manifold" | "boundary" | "angle">,
sharpAngle: number,
) {
return edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle;
}
export function edgeModifierSelectionStatus(prepared: boolean, selectedCount: number, availableCount: number) {
return prepared ? `${selectedCount} of ${availableCount} sharp edges selected` : "Preparing edges\u2026";
}
+109 -21
View File
@@ -1,9 +1,8 @@
import type { WorkplaneShape } from "@/types/sketchforge";
import { canonicalizeShape, serializeShapesForSync } from "@/lib/workplaneShapes";
import { canonicalizeShape } from "@/lib/workplaneShapes";
export const MAX_EDITOR_HISTORY_ENTRIES = 5000;
export const MAX_EDITOR_HISTORY_BYTES = 64 * 1024 * 1024;
export type EditorHistoryExportLimit = "unlimited" | 100 | 50 | 30;
export type EditorHistoryExportLimit = "unlimited" | number;
export type EditorHistoryEntry = {
shapes: WorkplaneShape[];
@@ -17,8 +16,24 @@ export type EditorHistoryState = {
index: number;
};
export function serializedSceneSignature(shapes: WorkplaneShape[]) {
const serialized = serializeShapesForSync(shapes);
type ResourceSignature = {
fingerprint: string;
estimatedBytes: number;
};
const resourceSignatureCache = new WeakMap<object, ResourceSignature>();
const stringSignatureCache = new Map<string, ResourceSignature>();
const MAX_CACHED_STRING_SIGNATURES = 64;
const COMPACT_RESOURCE_KEYS = new Set([
"cadDisplayEdges",
"edgeTreatmentHistory",
"imagePlate",
"importedMesh",
"sketchProfile",
]);
const COMPACT_STRING_KEYS = new Set(["cadBrep"]);
function signatureFromSerialized(serialized: string): ResourceSignature {
let hashA = 2166136261;
let hashB = 5381;
for (let index = 0; index < serialized.length; index += 1) {
@@ -32,6 +47,65 @@ export function serializedSceneSignature(shapes: WorkplaneShape[]) {
};
}
function objectResourceSignature(resource: object) {
const cached = resourceSignatureCache.get(resource);
if (cached) return cached;
const signature = signatureFromSerialized(JSON.stringify(resource));
resourceSignatureCache.set(resource, signature);
return signature;
}
export function immutableResourceFingerprint(resource: object) {
return objectResourceSignature(resource).fingerprint;
}
function stringResourceSignature(resource: string) {
const cached = stringSignatureCache.get(resource);
if (cached) {
stringSignatureCache.delete(resource);
stringSignatureCache.set(resource, cached);
return cached;
}
const signature = signatureFromSerialized(resource);
stringSignatureCache.set(resource, signature);
while (stringSignatureCache.size > MAX_CACHED_STRING_SIGNATURES) {
const oldest = stringSignatureCache.keys().next().value;
if (oldest === undefined) break;
stringSignatureCache.delete(oldest);
}
return signature;
}
export function serializedSceneSignature(shapes: WorkplaneShape[]) {
const countedObjects = new Set<object>();
const countedStrings = new Set<string>();
let resourceBytes = 0;
const serialized = JSON.stringify(shapes.map(canonicalizeShape), (key, value: unknown) => {
if (COMPACT_RESOURCE_KEYS.has(key) && value !== null && typeof value === "object") {
const signature = objectResourceSignature(value);
if (!countedObjects.has(value)) {
countedObjects.add(value);
resourceBytes += signature.estimatedBytes;
}
return { $resource: key, fingerprint: signature.fingerprint };
}
if (COMPACT_STRING_KEYS.has(key) && typeof value === "string" && value.length > 0) {
const signature = stringResourceSignature(value);
if (!countedStrings.has(value)) {
countedStrings.add(value);
resourceBytes += signature.estimatedBytes;
}
return { $resource: key, fingerprint: signature.fingerprint };
}
return value;
});
const signature = signatureFromSerialized(serialized);
return {
fingerprint: signature.fingerprint,
estimatedBytes: signature.estimatedBytes + resourceBytes,
};
}
export function projectShapesFingerprint(shapes: WorkplaneShape[]) {
return serializedSceneSignature(shapes).fingerprint;
}
@@ -46,17 +120,35 @@ export function editorHistoryEntry(shapes: WorkplaneShape[], selectedIds: string
};
}
export function boundedEditorHistory(entries: EditorHistoryEntry[]) {
const bounded = entries.slice(-MAX_EDITOR_HISTORY_ENTRIES);
let totalBytes = bounded.reduce((total, entry) => total + entry.estimatedBytes, 0);
while (bounded.length > 2 && totalBytes > MAX_EDITOR_HISTORY_BYTES) {
const removed = bounded.shift();
totalBytes -= removed?.estimatedBytes ?? 0;
}
return bounded;
export function boundedEditorHistory(entries: EditorHistoryEntry[], limit: EditorHistoryExportLimit = "unlimited") {
return boundedEditorHistoryState(entries, entries.length - 1, limit).entries;
}
export function appendEditorHistorySnapshot(entries: EditorHistoryEntry[], requestedIndex: number, entry: EditorHistoryEntry) {
export function boundedEditorHistoryState(
entries: EditorHistoryEntry[],
requestedIndex: number,
limit: EditorHistoryExportLimit = "unlimited",
): EditorHistoryState {
if (entries.length === 0) return { entries: [], index: 0 };
const index = Math.min(Math.max(0, requestedIndex), entries.length - 1);
const retainedActions = limit === "unlimited"
? MAX_EDITOR_HISTORY_ENTRIES - 1
: Math.min(MAX_EDITOR_HISTORY_ENTRIES - 1, Math.max(1, Math.round(limit)));
const maxEntries = retainedActions + 1;
if (entries.length <= maxEntries) return { entries, index };
let start = Math.max(0, index - retainedActions);
const end = Math.min(entries.length, start + maxEntries);
if (end - start < maxEntries) start = Math.max(0, end - maxEntries);
const bounded = entries.slice(start, end);
return { entries: bounded, index: index - start };
}
export function appendEditorHistorySnapshot(
entries: EditorHistoryEntry[],
requestedIndex: number,
entry: EditorHistoryEntry,
limit: EditorHistoryExportLimit = "unlimited",
) {
const index = Math.min(Math.max(0, requestedIndex), Math.max(0, entries.length - 1));
const current = entries[index];
if (current?.fingerprint === entry.fingerprint) {
@@ -68,7 +160,7 @@ export function appendEditorHistorySnapshot(entries: EditorHistoryEntry[], reque
};
}
const nextEntries = boundedEditorHistory([...entries.slice(0, index + 1), entry]);
const nextEntries = boundedEditorHistory([...entries.slice(0, index + 1), entry], limit);
return { entries: nextEntries, index: nextEntries.length - 1, changed: true };
}
@@ -76,6 +168,7 @@ export function hydrateEditorHistoryState(
currentShapes: WorkplaneShape[],
storedEntries: EditorHistoryEntry[] | undefined,
requestedIndex: number | undefined,
limit: EditorHistoryExportLimit = "unlimited",
): EditorHistoryState {
const fallback = editorHistoryEntry(currentShapes, []);
if (!Array.isArray(storedEntries) || storedEntries.length === 0) {
@@ -96,12 +189,7 @@ export function hydrateEditorHistoryState(
return { entries: [fallback], index: 0 };
}
const entries = boundedEditorHistory(normalized);
const boundedIndex = index - (normalized.length - entries.length);
if (boundedIndex < 0 || boundedIndex >= entries.length) {
return { entries: [fallback], index: 0 };
}
return { entries, index: boundedIndex };
return boundedEditorHistoryState(normalized, index, limit);
} catch {
return { entries: [fallback], index: 0 };
}
+13 -9
View File
@@ -3,11 +3,6 @@ import type { WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchf
const MIN_VISIBLE_GRID_STEP = 1;
const MAX_VISIBLE_GRID_STEP = 200;
export type GridFootprintBounds = {
minX: number;
minZ: number;
};
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
@@ -21,6 +16,13 @@ export function visibleGridStep(workspace: WorkplaneWorkspaceSettings) {
return clamp(workspace.gridBlockSize, MIN_VISIBLE_GRID_STEP, MAX_VISIBLE_GRID_STEP);
}
export type GridFootprintBounds = {
minX: number;
maxX: number;
minZ: number;
maxZ: number;
};
function nearestVisibleGridLine(value: number, workspaceSize: number, step: number) {
const gridOrigin = -workspaceSize / 2;
return gridOrigin + Math.round((value - gridOrigin) / step) * step;
@@ -32,11 +34,13 @@ export function snapShapeFootprintToVisibleGrid(
workspace: WorkplaneWorkspaceSettings,
) {
const step = visibleGridStep(workspace);
const snappedMinX = nearestVisibleGridLine(bounds.minX, workspace.width, step);
const snappedMinZ = nearestVisibleGridLine(bounds.minZ, workspace.depth, step);
const xOffsets = [bounds.minX, bounds.maxX].map((value) => nearestVisibleGridLine(value, workspace.width, step) - value);
const zOffsets = [bounds.minZ, bounds.maxZ].map((value) => nearestVisibleGridLine(value, workspace.depth, step) - value);
const deltaX = xOffsets.reduce((best, value) => Math.abs(value) < Math.abs(best) ? value : best);
const deltaZ = zOffsets.reduce((best, value) => Math.abs(value) < Math.abs(best) ? value : best);
return {
...shape,
x: cleanCoordinate(shape.x + snappedMinX - bounds.minX),
z: cleanCoordinate(shape.z + snappedMinZ - bounds.minZ),
x: cleanCoordinate(shape.x + deltaX),
z: cleanCoordinate(shape.z + deltaZ),
};
}
@@ -0,0 +1,92 @@
import { immutableResourceFingerprint, type EditorHistoryEntry } from "@/lib/editorHistory";
import type { WorkplaneShape } from "@/types/sketchforge";
export type ImportedMeshResource = NonNullable<WorkplaneShape["importedMesh"]>;
type CompactProjectShapeState = {
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
resources: Map<string, ImportedMeshResource>;
};
function compactImportedMesh(resource: ImportedMeshResource, resources: Map<string, ImportedMeshResource>): ImportedMeshResource {
const resourceId = immutableResourceFingerprint(resource);
if (!resources.has(resourceId)) {
resources.set(resourceId, {
...resource,
storageResourceId: undefined,
});
}
return {
positions: [],
baseWidth: resource.baseWidth,
baseDepth: resource.baseDepth,
baseHeight: resource.baseHeight,
triangleCount: resource.triangleCount,
sourceFormat: resource.sourceFormat,
assetId: resource.assetId,
storageResourceId: resourceId,
};
}
function compactShape(shape: WorkplaneShape, resources: Map<string, ImportedMeshResource>): WorkplaneShape {
const next: WorkplaneShape = {
...shape,
importedMesh: shape.importedMesh ? compactImportedMesh(shape.importedMesh, resources) : undefined,
};
if (shape.groupedShapes) {
next.groupedShapes = shape.groupedShapes.map((child) => compactShape(child, resources));
}
if (shape.edgeTreatmentHistory) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
before: compactShape(entry.before, resources),
}));
}
return next;
}
function hydrateShape(shape: WorkplaneShape, resources: ReadonlyMap<string, ImportedMeshResource>): WorkplaneShape {
const resourceId = shape.importedMesh?.storageResourceId;
const resource = resourceId ? resources.get(resourceId) : undefined;
const next: WorkplaneShape = {
...shape,
importedMesh: resource ?? shape.importedMesh,
};
if (shape.groupedShapes) {
next.groupedShapes = shape.groupedShapes.map((child) => hydrateShape(child, resources));
}
if (shape.edgeTreatmentHistory) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
before: hydrateShape(entry.before, resources),
}));
}
return next;
}
export function compactProjectShapeState(shapes: WorkplaneShape[], history: EditorHistoryEntry[]): CompactProjectShapeState {
const resources = new Map<string, ImportedMeshResource>();
return {
shapes: shapes.map((shape) => compactShape(shape, resources)),
history: history.map((entry) => ({
...entry,
shapes: entry.shapes.map((shape) => compactShape(shape, resources)),
})),
resources,
};
}
export function hydrateProjectShapeState(
shapes: WorkplaneShape[],
history: EditorHistoryEntry[] | undefined,
resources: ReadonlyMap<string, ImportedMeshResource>,
) {
return {
shapes: shapes.map((shape) => hydrateShape(shape, resources)),
history: history?.map((entry) => ({
...entry,
shapes: entry.shapes.map((shape) => hydrateShape(shape, resources)),
})),
};
}
+14 -4
View File
@@ -135,6 +135,7 @@ export type SkfProjectExportInput = {
workspace: WorkplaneWorkspaceSettings;
snapGrid: GridSize;
placementElevation: number;
compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
};
export type SkfRestoredProject = {
@@ -292,6 +293,7 @@ class SkfArchiveBuilder {
readonly assets: SkfAssetRecordV1[] = [];
readonly sourceIdMap = new Map<string, string>();
private readonly recordByKindAndHash = new Map<string, SkfAssetRecordV1>();
private readonly derivedMeshByResource = new WeakMap<object, Promise<SkfAssetRecordV1>>();
async addAsset(
kind: SkfAssetKind,
@@ -336,6 +338,14 @@ class SkfArchiveBuilder {
this.sourceIdMap.set(asset.id, record.id);
}
}
addDerivedMesh(mesh: NonNullable<WorkplaneShape["importedMesh"]>) {
const cached = this.derivedMeshByResource.get(mesh);
if (cached) return cached;
const pending = this.addAsset("derived-mesh", encodeMeshCache(mesh), "application/vnd.sketchforge.mesh");
this.derivedMeshByResource.set(mesh, pending);
return pending;
}
}
function assertUniqueRuntimeObjectIds(shapes: WorkplaneShape[], stateLabel: string) {
@@ -410,7 +420,7 @@ async function serializeShapeNode(
let meshAssetId: string | undefined;
let brepStepAssetId: string | undefined;
if (!canRegenerate) {
meshAssetId = (await builder.addAsset("derived-mesh", encodeMeshCache(importedMesh), "application/vnd.sketchforge.mesh")).id;
meshAssetId = (await builder.addDerivedMesh(importedMesh)).id;
if (importedMesh.brepStep) {
brepStepAssetId = (await builder.addAsset("brep", strToU8(importedMesh.brepStep), "application/step")).id;
}
@@ -600,9 +610,9 @@ function activeProjectIndexes(state: SkfStateV1) {
return { features, groups, sketches, exactCad };
}
function zipAsync(files: AsyncZippable) {
function zipAsync(files: AsyncZippable, level: NonNullable<SkfProjectExportInput["compressionLevel"]> = 6) {
return new Promise<Uint8Array>((resolve, reject) => {
zip(files, { level: 6, mtime: new Date("1980-01-01T00:00:00.000Z") }, (error, data) => {
zip(files, { level, mtime: new Date("1980-01-01T00:00:00.000Z") }, (error, data) => {
if (error) reject(error);
else resolve(data);
});
@@ -678,7 +688,7 @@ export async function exportSkfProject(input: SkfProjectExportInput) {
},
};
builder.files["project.json"] = strToU8(`${JSON.stringify(document, null, 2)}\n`);
return zipAsync(Object.fromEntries(Object.entries(builder.files).sort(([a], [b]) => a.localeCompare(b))));
return zipAsync(Object.fromEntries(Object.entries(builder.files).sort(([a], [b]) => a.localeCompare(b))), input.compressionLevel);
}
function inspectZipBeforeExpansion(bytes: Uint8Array) {
+47 -1
View File
@@ -1,7 +1,10 @@
import type { ResolvedAppTheme } from "@/lib/appTheme";
const WORKPLANE_BOUNDARY_EPSILON = 0.0001;
export const WORKPLANE_LINE_ELEVATION = 0;
export const WORKPLANE_MAJOR_GRID_INTERVAL = 5;
export const DEFAULT_WORKPLANE_GRID_COLOR = "#28b4de";
export type WorkplaneGridCoordinate = {
coordinate: number;
@@ -15,7 +18,32 @@ export type WorkplaneGridPalette = {
border: { color: string; opacity: number };
};
export function workplaneGridPalette(): WorkplaneGridPalette {
export type WorkplaneThemePalette = {
sceneBackground: string;
surface: { color: string; opacity: number };
grid: WorkplaneGridPalette;
};
export function workplaneGridPalette(
theme: ResolvedAppTheme = "light",
configuredColor: string = DEFAULT_WORKPLANE_GRID_COLOR,
): WorkplaneGridPalette {
if (configuredColor.toLowerCase() !== DEFAULT_WORKPLANE_GRID_COLOR) {
return {
minor: { color: configuredColor, opacity: theme === "dark" ? 0.42 : 0.38 },
major: { color: configuredColor, opacity: theme === "dark" ? 0.7 : 0.68 },
axis: { color: configuredColor, opacity: 0.94 },
border: { color: configuredColor, opacity: 0.9 },
};
}
if (theme === "dark") {
return {
minor: { color: "#397080", opacity: 0.5 },
major: { color: "#4d9caf", opacity: 0.72 },
axis: { color: "#65c9df", opacity: 0.92 },
border: { color: "#59b8cc", opacity: 0.88 },
};
}
return {
minor: { color: "#91dff0", opacity: 0.55 },
major: { color: "#4bbddf", opacity: 0.7 },
@@ -24,6 +52,24 @@ export function workplaneGridPalette(): WorkplaneGridPalette {
};
}
export function workplaneThemePalette(
theme: ResolvedAppTheme,
configuredBackground: string,
configuredGridColor: string = DEFAULT_WORKPLANE_GRID_COLOR,
): WorkplaneThemePalette {
return theme === "dark"
? {
sceneBackground: "#101820",
surface: { color: "#183640", opacity: 0.9 },
grid: workplaneGridPalette("dark", configuredGridColor),
}
: {
sceneBackground: configuredBackground,
surface: { color: "#ddf8ff", opacity: 0.68 },
grid: workplaneGridPalette("light", configuredGridColor),
};
}
export function interiorWorkplaneGridCoordinates(span: number, step: number): WorkplaneGridCoordinate[] {
if (!Number.isFinite(span) || !Number.isFinite(step) || span <= 0 || step <= 0) {
return [];
+16 -1
View File
@@ -1,5 +1,6 @@
import type { GridSize, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_GRID_COLOR } from "@/lib/workplaneGrid";
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
@@ -9,6 +10,7 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
sizePreset: "200 x 200 mm",
gridBlockSize: 5,
gridBlockPreset: "5 mm",
gridColor: DEFAULT_WORKPLANE_GRID_COLOR,
background: "#f8fbfc",
showShadows: true,
showGrid: true,
@@ -17,6 +19,7 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
units: "Metric (Default)",
scale: "1:1 (millimeters)",
accuracy: 2,
historyLimit: "unlimited",
};
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
@@ -29,6 +32,10 @@ function stringOrDefault(value: unknown, fallback: string) {
return typeof value === "string" && value.trim() ? value : fallback;
}
function colorOrDefault(value: unknown, fallback: string) {
return typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value.trim()) ? value : fallback;
}
function booleanOrDefault(value: unknown, fallback: boolean) {
return typeof value === "boolean" ? value : fallback;
}
@@ -37,6 +44,12 @@ function accuracyOrDefault(value: unknown, fallback: MeasurementAccuracy) {
return value === 1 || value === 2 || value === 3 ? value : fallback;
}
function historyLimitOrDefault(value: unknown, fallback: HistoryRetentionLimit): HistoryRetentionLimit {
if (value === "unlimited") return value;
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
return Math.min(5000, Math.max(1, Math.round(value)));
}
export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_SNAP_GRID): GridSize {
return snapGridOptions.includes(value as GridSize) ? (value as GridSize) : fallback;
}
@@ -50,6 +63,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
sizePreset: stringOrDefault(candidate.sizePreset, fallback.sizePreset),
gridBlockSize: numberOrDefault(candidate.gridBlockSize, fallback.gridBlockSize),
gridBlockPreset: stringOrDefault(candidate.gridBlockPreset, fallback.gridBlockPreset),
gridColor: colorOrDefault(candidate.gridColor, fallback.gridColor),
background: stringOrDefault(candidate.background, fallback.background),
showShadows: booleanOrDefault(candidate.showShadows, fallback.showShadows),
showGrid: booleanOrDefault(candidate.showGrid, fallback.showGrid),
@@ -58,6 +72,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
units,
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
};
}
+6
View File
@@ -42,6 +42,7 @@ export type ProjectAsset = {
export type GridSize = "Off" | "0.1 mm" | "0.25 mm" | "0.5 mm" | "1.0 mm" | "2.0 mm" | "5.0 mm" | "Brick";
export type MeasurementAccuracy = 1 | 2 | 3;
export type HistoryRetentionLimit = "unlimited" | number;
export type WorkplaneWorkspaceSettings = {
width: number;
@@ -49,6 +50,7 @@ export type WorkplaneWorkspaceSettings = {
sizePreset: string;
gridBlockSize: number;
gridBlockPreset: string;
gridColor: string;
background: string;
showShadows: boolean;
showGrid: boolean;
@@ -57,6 +59,7 @@ export type WorkplaneWorkspaceSettings = {
units: string;
scale: string;
accuracy: MeasurementAccuracy;
historyLimit: HistoryRetentionLimit;
};
export type AlignAxis = "x" | "y" | "z";
@@ -211,6 +214,9 @@ export type WorkplaneShape = {
baseHeight: number;
triangleCount: number;
sourceFormat: "stl" | "obj" | "svg" | "json" | "step";
// IndexedDB persistence uses this only in compact stored shape records.
// Runtime editor shapes are hydrated with the full immutable mesh resource.
storageResourceId?: string;
// Stable reference to the original imported file in the project's shared
// asset table. Copies and grouped operands reuse this reference.
assetId?: string;
+5 -6
View File
@@ -2,7 +2,7 @@
import { OcctKernel, type ShapeHandle } from "occt-wasm";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import { CAD_MODIFIER_RUNTIME_BASE, isCadModifierWasmMemoryFault } from "@/lib/cadModifierRuntime";
import { CAD_MODIFIER_RUNTIME_BASE, cadModifierTopologyEdgeIsSelectable, cadTransformRequiresGeneralTransform, isCadModifierWasmMemoryFault } from "@/lib/cadModifierRuntime";
const HASH_UPPER_BOUND = 2_147_483_647;
const CAD_EDGE_WIREFRAME_DEFLECTION = 0.035;
@@ -152,6 +152,9 @@ function isIdentityCadTransform(transform: number[]) {
function applyCadTransform(cad: OcctKernel, shape: ShapeHandle, transform: number[] | undefined) {
if (!isCadTransform(transform) || isIdentityCadTransform(transform)) return shape;
if (cadTransformRequiresGeneralTransform(transform)) {
return cad.generalTransform(shape, transform);
}
try {
return cad.transform(shape, transform);
} catch {
@@ -276,10 +279,6 @@ function isModifierDisplayCadEdge(edge: CollectedCadEdgeGeometry, treatmentAreaL
return isDisplayCadEdge(edge) && !touchesTreatmentDetailFace(edge, treatmentAreaLimit);
}
function isSelectableModifierEdge(edge: CollectedCadEdgeGeometry) {
return edge.manifold && !edge.boundary && edge.points.length >= 6;
}
function releaseHandles(cad: OcctKernel, handles: ShapeHandle[]) {
handles.forEach((handle) => {
try {
@@ -347,7 +346,7 @@ function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number, s
return {
...edge,
display,
selectable: isSelectableModifierEdge(edge) && (treatmentAreaLimit <= 0 || display),
selectable: cadModifierTopologyEdgeIsSelectable(edge),
};
});
const selectableEdgeIds = edges.filter((edge) => edge.selectable && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id);
+16 -5
View File
@@ -19,11 +19,13 @@
"next": "^15.3.2",
"occt-wasm": "^3.6.1",
"react": "^19.1.0",
"react-colorful": "^5.8.0",
"react-dom": "^19.1.0",
"tailwind-merge": "^3.3.0",
"tailwindcss": "^4.1.8",
"three": "^0.184.0",
"three-bvh-csg": "^0.0.18"
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.13"
},
"devDependencies": {
"@types/node": "^22.15.18",
@@ -2454,6 +2456,16 @@
"node": ">=0.10.0"
}
},
"node_modules/react-colorful": {
"version": "5.8.0",
"resolved": "https://registry.npmjs.org/react-colorful/-/react-colorful-5.8.0.tgz",
"integrity": "sha512-Wy9OzPfjSN9bF12OB8N7UQvlsZ0I+7wHxpN+bV5BjNQGxOj6IiwkRjevJK9yOBjJWGQvAaf1OXtn8rUeEatAng==",
"license": "MIT",
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/react-dom": {
"version": "19.2.6",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.6.tgz",
@@ -2679,11 +2691,10 @@
}
},
"node_modules/three-mesh-bvh": {
"version": "0.9.10",
"resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.10.tgz",
"integrity": "sha512-UOlTgPIeqUURcwaG8knxvBaruwZlC4X3/WSHEFO7rYvMVv/YNUrkfFEszvfj36pXV88dCHoHNnIp0PifkirnTQ==",
"version": "0.9.13",
"resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.13.tgz",
"integrity": "sha512-2zRh4iTFDmiTISanSVFofIw6J92DxFSqWn2qsQTtKp2ko5Ebk/JaI/wpMqNaBJ3F0qx7/NuP9GPK4jGDX99J2Q==",
"license": "MIT",
"peer": true,
"peerDependencies": {
"three": ">= 0.159.0"
}
+3 -1
View File
@@ -35,11 +35,13 @@
"next": "^15.3.2",
"occt-wasm": "^3.6.1",
"react": "^19.1.0",
"react-colorful": "^5.8.0",
"react-dom": "^19.1.0",
"tailwind-merge": "^3.3.0",
"tailwindcss": "^4.1.8",
"three": "^0.184.0",
"three-bvh-csg": "^0.0.18"
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.13"
},
"devDependencies": {
"@types/node": "^22.15.18",
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import {
APP_THEME_STORAGE_KEY,
normalizeAppThemePreference,
readStoredAppTheme,
resolveAppTheme,
storeAppTheme,
} from "@/lib/appTheme";
describe("application theme preference", () => {
it("normalizes stored values and resolves the system theme", () => {
expect(normalizeAppThemePreference("light")).toBe("light");
expect(normalizeAppThemePreference("dark")).toBe("dark");
expect(normalizeAppThemePreference("unexpected")).toBe("system");
expect(resolveAppTheme("system", true)).toBe("dark");
expect(resolveAppTheme("system", false)).toBe("light");
expect(resolveAppTheme("light", true)).toBe("light");
});
it("persists the selected preference and safely falls back for invalid storage", () => {
const values = new Map<string, string>();
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
};
storeAppTheme(storage, "dark");
expect(values.get(APP_THEME_STORAGE_KEY)).toBe("dark");
expect(readStoredAppTheme(storage)).toBe("dark");
values.set(APP_THEME_STORAGE_KEY, "neon");
expect(readStoredAppTheme(storage)).toBe("system");
});
});
+46
View File
@@ -3,9 +3,13 @@ import {
CAD_MODIFIER_MAX_SHARP_ANGLE,
CAD_MODIFIER_REQUEST_TIMEOUT_MS,
CAD_MODIFIER_RUNTIME_BASE,
cadModifierTopologyEdgeIsSelectable,
cadTransformRequiresGeneralTransform,
cadModifierTimeoutMessage,
defaultCadModifierTangentChain,
edgeModifierSelectionStatus,
isCadModifierWasmMemoryFault,
selectableCadModifierEdge,
} from "@/lib/cadModifierRuntime";
describe("CAD modifier runtime state", () => {
@@ -34,5 +38,47 @@ describe("CAD modifier runtime state", () => {
expect(isCadModifierWasmMemoryFault("toBREP: Out of bounds memory access (evaluating 'func(...args)')")).toBe(true);
expect(isCadModifierWasmMemoryFault("Unreachable code reached", "RuntimeError")).toBe(true);
expect(isCadModifierWasmMemoryFault("The selected edges cannot be filleted together", "Error")).toBe(false);
expect(isCadModifierWasmMemoryFault("fillet: [object WebAssembly.Exception]", "OcctError")).toBe(false);
expect(isCadModifierWasmMemoryFault("fillet: wasm exception", "OcctError")).toBe(false);
});
it("routes rotated non-uniform resize transforms through OCCT's general transform", () => {
const angle = Math.PI / 4;
const cosine = Math.cos(angle);
const sine = Math.sin(angle);
const rotatedNonUniformResize = [
2 * cosine, 0, 2 * sine, 12,
0, 1, 0, 4,
-sine, 0, cosine, -8,
];
const rigidRotation = [
cosine, 0, sine, 12,
0, 1, 0, 4,
-sine, 0, cosine, -8,
];
expect(cadTransformRequiresGeneralTransform(rotatedNonUniformResize)).toBe(true);
expect(cadTransformRequiresGeneralTransform(rigidRotation)).toBe(false);
});
it("does not auto-chain newly created edges after an applied edge treatment", () => {
expect(defaultCadModifierTangentChain(0)).toBe(true);
expect(defaultCadModifierTangentChain(1)).toBe(false);
expect(defaultCadModifierTangentChain(2)).toBe(false);
});
it("keeps valid post-treatment edges selectable when normal outline display suppresses them", () => {
const hiddenDetailEdge = {
display: false,
selectable: true,
manifold: true,
boundary: false,
angle: 45,
points: [0, 0, 0, 1, 0, 0],
};
expect(cadModifierTopologyEdgeIsSelectable(hiddenDetailEdge)).toBe(true);
expect(selectableCadModifierEdge(hiddenDetailEdge, 25)).toBe(true);
expect(selectableCadModifierEdge(hiddenDetailEdge, 60)).toBe(false);
});
});
+51 -6
View File
@@ -61,17 +61,52 @@ describe("editor history snapshots", () => {
expect(projectShapesFingerprint([changed])).not.toBe(projectShapesFingerprint([shape]));
});
it("bounds entry count and estimated memory while retaining undo depth", () => {
it("reuses an immutable mesh signature for transform-only history snapshots", () => {
let coordinateReads = 0;
const positions = new Proxy([0, 0, 0, 1, 0, 0, 0, 1, 0], {
get(target, property, receiver) {
if (typeof property === "string" && /^\d+$/.test(property)) coordinateReads += 1;
return Reflect.get(target, property, receiver);
},
});
const shape = box({
kind: "mesh",
importedMesh: {
positions,
baseWidth: 1,
baseDepth: 1,
baseHeight: 1,
triangleCount: 1,
sourceFormat: "stl",
},
});
const baseline = projectShapesFingerprint([shape]);
expect(coordinateReads).toBeGreaterThan(0);
coordinateReads = 0;
expect(projectShapesFingerprint([{ ...shape, x: 25 }])).not.toBe(baseline);
expect(coordinateReads).toBe(0);
expect(projectShapesFingerprint([{
...shape,
importedMesh: { ...shape.importedMesh!, positions: [...positions] },
}])).toBe(baseline);
});
it("keeps unlimited history and applies preset or custom action limits", () => {
const entries = Array.from({ length: 140 }, (_, index) => ({
...editorHistoryEntry([box({ id: `box-${index}`, x: index })], []),
estimatedBytes: 2 * 1024 * 1024,
}));
const bounded = boundedEditorHistory(entries);
const unlimited = boundedEditorHistory(entries);
const lastThirty = boundedEditorHistory(entries, 30);
const custom = boundedEditorHistory(entries, 7);
expect(bounded.length).toBeLessThanOrEqual(100);
expect(bounded.length).toBeGreaterThanOrEqual(2);
expect(bounded.reduce((total, entry) => total + entry.estimatedBytes, 0)).toBeLessThanOrEqual(64 * 1024 * 1024);
expect(bounded.at(-1)?.shapes[0].id).toBe("box-139");
expect(unlimited).toHaveLength(140);
expect(lastThirty).toHaveLength(31);
expect(lastThirty[0].shapes[0].id).toBe("box-109");
expect(custom).toHaveLength(8);
expect(custom.at(-1)?.shapes[0].id).toBe("box-139");
});
it("trims redo only for a real new edit and preserves it for a no-op", () => {
@@ -99,6 +134,16 @@ describe("editor history snapshots", () => {
expect(restored.entries[2].shapes[0].x).toBe(10);
});
it("restores only the configured number of saved actions without losing the active state", () => {
const entries = Array.from({ length: 80 }, (_, x) => editorHistoryEntry([box({ x })], []));
const restored = hydrateEditorHistoryState([box({ x: 60 })], entries, 60, 30);
expect(restored.entries).toHaveLength(31);
expect(restored.index).toBe(30);
expect(restored.entries[0].shapes[0].x).toBe(30);
expect(restored.entries[restored.index].shapes[0].x).toBe(60);
});
it("falls back to the loaded scene when persisted history is stale", () => {
const stale = [editorHistoryEntry([box({ x: 1 })], [])];
const restored = hydrateEditorHistoryState([box({ x: 9 })], stale, 0);
+9 -7
View File
@@ -54,17 +54,17 @@ function groupedShape(): WorkplaneShape {
}
describe("Snap to Grid", () => {
it("translates a group footprint to the visible grid without resizing it or changing child offsets", () => {
it("snaps the nearest footprint corner to the visible grid without resizing or changing child offsets", () => {
const group = groupedShape();
const snapped = snapShapeFootprintToVisibleGrid(
group,
{ minX: -17.3, minZ: -11.4 },
{ minX: -17.3, maxX: 26.2, minZ: -11.4, maxZ: 8.4 },
{ ...DEFAULT_WORKPLANE_WORKSPACE, gridBlockSize: 5 },
);
expect(snapped.x).toBe(5.5);
expect(snapped.x).toBe(2);
expect(snapped.z).toBe(-0.3);
expect(-17.3 + snapped.x - group.x).toBeCloseTo(-15, 6);
expect(26.2 + snapped.x - group.x).toBeCloseTo(25, 6);
expect(-11.4 + snapped.z - group.z).toBeCloseTo(-10, 6);
expect(snapped).toMatchObject({
elevation: 2.4,
@@ -80,11 +80,13 @@ describe("Snap to Grid", () => {
const group = groupedShape();
const snapped = snapShapeFootprintToVisibleGrid(
group,
{ minX: -18, minZ: -13 },
{ minX: -18, maxX: 25.5, minZ: -13, maxZ: 6.8 },
{ ...DEFAULT_WORKPLANE_WORKSPACE, width: 203, depth: 187, gridBlockSize: 10 },
);
expect(-18 + snapped.x - group.x).toBeCloseTo(-21.5, 6);
expect(-13 + snapped.z - group.z).toBeCloseTo(-13.5, 6);
expect(snapped.x).toBeCloseTo(6.2, 6);
expect(snapped.z).toBeCloseTo(-2, 6);
expect(25.5 + snapped.x - group.x).toBeCloseTo(28.5, 6);
expect(6.8 + snapped.z - group.z).toBeCloseTo(6.5, 6);
});
});
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { editorHistoryEntry } from "@/lib/editorHistory";
import { compactProjectShapeState, hydrateProjectShapeState } from "@/lib/projectShapePersistence";
import type { WorkplaneShape } from "@/types/sketchforge";
function importedShape(): WorkplaneShape {
return {
id: "mesh-1",
name: "Imported mesh",
kind: "mesh",
color: "#d41721",
x: 0,
z: 0,
elevation: 0,
size: 10,
width: 10,
depth: 10,
height: 10,
rotation: 0,
importedMesh: {
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
normals: [0, 0, 1, 0, 0, 1, 0, 0, 1],
baseWidth: 1,
baseDepth: 1,
baseHeight: 1,
triangleCount: 1,
sourceFormat: "stl",
},
};
}
describe("project shape persistence resources", () => {
it("stores one immutable mesh resource across current shapes and history", () => {
const mesh = importedShape();
const group: WorkplaneShape = {
...mesh,
id: "group-1",
name: "Group",
importedMesh: undefined,
groupedShapes: [mesh],
groupedBaseWidth: 10,
groupedBaseDepth: 10,
groupedBaseHeight: 10,
groupOperation: "group",
};
const history = [
editorHistoryEntry([{ ...group, x: 0 }], []),
editorHistoryEntry([{ ...group, x: 5 }], [group.id]),
];
const compact = compactProjectShapeState([{ ...group, x: 5 }], history);
const currentStub = compact.shapes[0].groupedShapes?.[0].importedMesh;
const historyStub = compact.history[0].shapes[0].groupedShapes?.[0].importedMesh;
expect(compact.resources.size).toBe(1);
expect(currentStub?.positions).toEqual([]);
expect(currentStub?.normals).toBeUndefined();
expect(currentStub?.storageResourceId).toBeTruthy();
expect(historyStub?.storageResourceId).toBe(currentStub?.storageResourceId);
const hydrated = hydrateProjectShapeState(compact.shapes, compact.history, compact.resources);
const currentMesh = hydrated.shapes[0].groupedShapes?.[0].importedMesh;
const historyMesh = hydrated.history?.[0].shapes[0].groupedShapes?.[0].importedMesh;
expect(currentMesh?.positions).toEqual(mesh.importedMesh?.positions);
expect(currentMesh?.normals).toEqual(mesh.importedMesh?.normals);
expect(currentMesh?.storageResourceId).toBeUndefined();
expect(historyMesh).toBe(currentMesh);
});
});
+177
View File
@@ -0,0 +1,177 @@
import { describe, expect, it } from "vitest";
import * as THREE from "three";
import { bakedBoxSelectionFrame, bakeCadMetadataForShapeTransform } from "@/lib/cadBakeMetadata";
import { exportSkfProject, importSkfProject } from "@/lib/skfProject";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { WorkplaneShape } from "@/types/sketchforge";
function cube(): WorkplaneShape {
return {
id: "cube",
name: "Cube",
kind: "box",
color: "#d41721",
x: 0,
z: 0,
elevation: 0,
size: 20,
width: 20,
depth: 20,
height: 20,
rotation: 0,
rotationX: 0,
rotationZ: 0,
};
}
function inverseRotationPatch(shape: Pick<WorkplaneShape, "rotation" | "rotationX" | "rotationZ">) {
const quaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
THREE.MathUtils.degToRad(shape.rotation),
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
"XYZ",
));
const inverse = new THREE.Euler().setFromQuaternion(quaternion.invert(), "XYZ");
return {
rotationX: THREE.MathUtils.radToDeg(inverse.x),
rotation: THREE.MathUtils.radToDeg(inverse.y),
rotationZ: THREE.MathUtils.radToDeg(inverse.z),
};
}
const cubeTriangles = [
0, 2, 1, 0, 3, 2,
4, 5, 6, 4, 6, 7,
0, 1, 5, 0, 5, 4,
1, 2, 6, 1, 6, 5,
2, 3, 7, 2, 7, 6,
3, 0, 4, 3, 4, 7,
];
function primitiveCubePositions() {
const vertices = [
[-10, 0, -10], [10, 0, -10], [10, 0, 10], [-10, 0, 10],
[-10, 20, -10], [10, 20, -10], [10, 20, 10], [-10, 20, 10],
];
return cubeTriangles.flatMap((index) => vertices[index]);
}
function bake(shape: WorkplaneShape, rotation: Pick<WorkplaneShape, "rotation" | "rotationX" | "rotationZ">) {
const source = shape.importedMesh?.positions ?? primitiveCubePositions();
const sourceWidth = shape.importedMesh?.baseWidth ?? shape.width;
const sourceDepth = shape.importedMesh?.baseDepth ?? shape.depth;
const sourceHeight = shape.importedMesh?.baseHeight ?? shape.height;
const matrix = new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(
THREE.MathUtils.degToRad(rotation.rotationX ?? 0),
THREE.MathUtils.degToRad(rotation.rotation),
THREE.MathUtils.degToRad(rotation.rotationZ ?? 0),
"XYZ",
));
const centerY = shape.height / 2;
const world = Array.from({ length: source.length / 3 }, (_, index) => new THREE.Vector3(
source[index * 3] * shape.width / sourceWidth,
source[index * 3 + 1] * shape.height / sourceHeight - centerY,
source[index * 3 + 2] * shape.depth / sourceDepth,
).applyMatrix4(matrix).add(new THREE.Vector3(shape.x, (shape.elevation ?? 0) + centerY, shape.z)));
const bounds = new THREE.Box3().setFromPoints(world);
const center = bounds.getCenter(new THREE.Vector3());
const size = bounds.getSize(new THREE.Vector3());
const positions = world.flatMap((point) => [point.x - center.x, point.y - bounds.min.y, point.z - center.z]);
const cadMetadata = bakeCadMetadataForShapeTransform(
{ ...shape, ...rotation },
{
centerX: center.x,
minY: bounds.min.y,
centerZ: center.z,
width: size.x,
depth: size.z,
height: size.y,
yawDegrees: rotation.rotation,
},
);
return {
...shape,
kind: "mesh" as const,
x: center.x,
z: center.z,
elevation: bounds.min.y,
size: Math.max(size.x, size.z),
width: size.x,
depth: size.z,
height: size.y,
rotation: 0,
rotationX: 0,
rotationZ: 0,
importedMesh: {
positions,
baseWidth: size.x,
baseDepth: size.z,
baseHeight: size.y,
triangleCount: positions.length / 9,
sourceFormat: "json" as const,
},
...cadMetadata,
};
}
function expectAxisAlignedCube(shape: WorkplaneShape) {
const positions = shape.importedMesh?.positions ?? [];
expect(positions.length).toBeGreaterThan(0);
const coordinates = [0, 1, 2].map((axis) =>
[...new Set(Array.from({ length: positions.length / 3 }, (_, index) => Number(positions[index * 3 + axis].toFixed(5))))].sort((a, b) => a - b),
);
coordinates.forEach((axisValues) => expect(axisValues).toHaveLength(2));
}
describe("selection outline after project reopen", () => {
it("restores the exact oriented box frame for a baked cube", async () => {
const rotated = bake(cube(), { rotationX: 31, rotation: 47, rotationZ: 19 });
const bytes = await exportSkfProject({
projectId: "oriented-selection-outline-project",
projectName: "Oriented selection outline",
createdAt: 1_700_000_000_000,
modifiedAt: 1_700_000_000_100,
shapes: [rotated],
assets: [],
workspace: DEFAULT_WORKPLANE_WORKSPACE,
snapGrid: DEFAULT_SNAP_GRID,
placementElevation: 0,
});
const restored = await importSkfProject(bytes);
const frame = bakedBoxSelectionFrame(restored.shapes[0]);
expect(frame).not.toBeNull();
expect(Math.abs(frame?.xAxis.x ?? 1)).toBeLessThan(0.99);
expect(frame?.width).toBeCloseTo(20, 5);
expect(frame?.height).toBeCloseTo(20, 5);
expect(frame?.depth).toBeCloseTo(20, 5);
});
it("keeps a cube axis-aligned after rotating it away and back, then round-tripping the project", async () => {
const firstRotation = { rotationX: 31, rotation: 47, rotationZ: 19 };
const rotated = bake(cube(), firstRotation);
const returned = bake(rotated, inverseRotationPatch(firstRotation));
expectAxisAlignedCube(returned);
const bytes = await exportSkfProject({
projectId: "selection-outline-project",
projectName: "Selection outline",
createdAt: 1_700_000_000_000,
modifiedAt: 1_700_000_000_100,
shapes: [returned],
assets: [],
workspace: DEFAULT_WORKPLANE_WORKSPACE,
snapGrid: DEFAULT_SNAP_GRID,
placementElevation: 0,
});
const restored = await importSkfProject(bytes);
expectAxisAlignedCube(restored.shapes[0]);
const frame = bakedBoxSelectionFrame(restored.shapes[0]);
expect(frame?.xAxis.x).toBeCloseTo(1, 5);
expect(frame?.yAxis.y).toBeCloseTo(1, 5);
expect(frame?.zAxis.z).toBeCloseTo(1, 5);
expect(restored.shapes[0].rotation).toBe(0);
expect(restored.shapes[0].rotationX).toBe(0);
expect(restored.shapes[0].rotationZ).toBe(0);
});
});
+49
View File
@@ -5,6 +5,7 @@ import {
cadModifierPrimitiveForAnalyticBox,
cadModifierPrimitiveForBakedShape,
} from "@/lib/cadBakeMetadata";
import { cadTransformRequiresGeneralTransform } from "@/lib/cadModifierRuntime";
import type { WorkplaneShape } from "@/types/sketchforge";
function expectTransformClose(actual: number[] | undefined, expected: number[]) {
@@ -185,4 +186,52 @@ describe("SketchForge transform baking", () => {
});
expectTransformClose(restoredPrimitive?.transform, directPrimitive?.transform ?? []);
});
it("uses a general CAD transform after resizing a baked rotated box", () => {
const shape = boxShape({
x: 0,
z: 0,
elevation: 0,
width: 20,
depth: 20,
height: 20,
rotation: 45,
rotationX: 0,
rotationZ: 0,
});
const diagonal = Math.sqrt(20 ** 2 + 20 ** 2);
const baked = bakeCadMetadataForShapeTransform(shape, {
centerX: 0,
minY: 0,
centerZ: 0,
width: diagonal,
depth: diagonal,
height: 20,
yawDegrees: 45,
});
const resizedBakedShape: WorkplaneShape = {
...shape,
...baked,
kind: "mesh",
width: diagonal * 1.8,
depth: diagonal * 0.75,
height: 26,
size: diagonal * 1.8,
rotation: 0,
rotationX: 0,
rotationZ: 0,
importedMesh: {
positions: [-10, 0, -10, 10, 0, -10, 10, 20, 10],
baseWidth: diagonal,
baseDepth: diagonal,
baseHeight: 20,
triangleCount: 1,
sourceFormat: "json",
},
};
const restoredPrimitive = cadModifierPrimitiveForBakedShape(resizedBakedShape);
expect(restoredPrimitive?.transform).toBeDefined();
expect(cadTransformRequiresGeneralTransform(restoredPrimitive?.transform ?? [])).toBe(true);
});
});
+27 -2
View File
@@ -104,7 +104,8 @@ describe("SketchForge .skf project packages", () => {
} : undefined,
}));
const exported = await exportSkfProject(input(shapes));
const customWorkspace = { ...DEFAULT_WORKPLANE_WORKSPACE, gridColor: "#a34fd1" };
const exported = await exportSkfProject(input(shapes, { workspace: customWorkspace }));
const { document } = packageDocument(exported);
const summary = await inspectSkfProjectPackage(exported);
const restored = await importSkfProject(exported);
@@ -112,7 +113,7 @@ describe("SketchForge .skf project packages", () => {
expect(restored.projectName).toBe("Round trip");
expect(restored.sourceProjectId).toBe("project-original");
expect(JSON.stringify(restored.shapes)).toBe(JSON.stringify(shapes.map(canonicalizeShape)));
expect(restored.workspace).toEqual(DEFAULT_WORKPLANE_WORKSPACE);
expect(restored.workspace).toEqual(customWorkspace);
expect(restored.snapGrid).toBe(DEFAULT_SNAP_GRID);
expect(restored.placementElevation).toBe(12.5);
expect(summary).toEqual({
@@ -200,6 +201,30 @@ describe("SketchForge .skf project packages", () => {
expect(restored.shapes[0].edgeTreatmentHistory?.[0].before.kind).toBe("box");
});
it("preserves every silently packaged undo and redo action", async () => {
const created = shape("box", "history-box", { width: 20, depth: 20, x: 0 });
const resized = { ...created, width: 30 };
const moved = { ...resized, x: 18 };
const history = [
editorHistoryEntry([created], ["history-box"]),
editorHistoryEntry([resized], ["history-box"]),
editorHistoryEntry([moved], ["history-box"]),
];
const restored = await importSkfProject(await exportSkfProject(input([resized], {
history,
historyIndex: 1,
compressionLevel: 1,
})));
expect(restored.history).toHaveLength(3);
expect(restored.historyIndex).toBe(1);
expect(restored.history[0].shapes[0]).toMatchObject({ width: 20, x: 0 });
expect(restored.history[1].shapes[0]).toMatchObject({ width: 30, x: 0 });
expect(restored.history[2].shapes[0]).toMatchObject({ width: 30, x: 18 });
expect(restored.shapes[0]).toMatchObject({ width: 30, x: 0 });
});
it("stores one original source asset for repeated imported instances and regenerates it once", async () => {
const sourceBytes = strToU8("solid source");
const asset = await projectAssetFromBytes("shared.stl", "stl", sourceBytes);
+23 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
import { interiorWorkplaneGridCoordinates, workplaneGridPalette, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
describe("workplane grid geometry", () => {
it("excludes both perimeter coordinates when spacing divides the workplane", () => {
@@ -33,4 +33,26 @@ describe("workplane grid geometry", () => {
expect(palette.major.opacity).toBeLessThan(palette.axis.opacity);
expect(palette.minor.color).not.toBe(palette.major.color);
});
it("uses a complete dark viewport palette without changing the configured project background", () => {
const configuredBackground = "#f8fbfc";
const dark = workplaneThemePalette("dark", configuredBackground);
const light = workplaneThemePalette("light", configuredBackground);
expect(dark.sceneBackground).not.toBe(configuredBackground);
expect(dark.surface.color).not.toBe(light.surface.color);
expect(dark.grid.minor.color).not.toBe(light.grid.minor.color);
expect(light.sceneBackground).toBe(configuredBackground);
});
it("applies a custom project grid color while retaining line hierarchy", () => {
const customColor = "#c23b72";
const palette = workplaneGridPalette("light", customColor);
expect(palette.minor.color).toBe(customColor);
expect(palette.major.color).toBe(customColor);
expect(palette.axis.color).toBe(customColor);
expect(palette.minor.opacity).toBeLessThan(palette.major.opacity);
expect(palette.major.opacity).toBeLessThan(palette.axis.opacity);
});
});
+6
View File
@@ -27,6 +27,7 @@ describe("workplane settings helpers", () => {
sizePreset: "",
gridBlockSize: 2.5,
gridBlockPreset: "Custom",
gridColor: "#a34fd1",
background: "#123456",
showShadows: false,
showGrid: false,
@@ -43,6 +44,7 @@ describe("workplane settings helpers", () => {
width: 500,
gridBlockSize: 2.5,
gridBlockPreset: "Custom",
gridColor: "#a34fd1",
background: "#123456",
showShadows: false,
showGrid: false,
@@ -53,6 +55,10 @@ describe("workplane settings helpers", () => {
});
expect(normalizeWorkspaceSettings({ accuracy: 9 }, fallback).accuracy).toBe(fallback.accuracy);
expect(normalizeWorkspaceSettings({ historyLimit: 73 }).historyLimit).toBe(73);
expect(normalizeWorkspaceSettings({ historyLimit: 9000 }).historyLimit).toBe(5000);
expect(normalizeWorkspaceSettings({ historyLimit: "invalid" }).historyLimit).toBe("unlimited");
expect(normalizeWorkspaceSettings({ gridColor: "not-a-color" }).gridColor).toBe(DEFAULT_WORKPLANE_WORKSPACE.gridColor);
});
it("keeps scale options in the selected unit family", () => {