Ship shared projects and CAD reliability updates

This commit is contained in:
Formsmith
2026-07-19 15:58:52 +03:00
parent 3a7db063e7
commit c5ce5a80f0
23 changed files with 999 additions and 83 deletions
+26 -1
View File
@@ -117,7 +117,11 @@ docker compose -f deploy/docker/compose-ghcr.yaml up -d
#### Standalone (Prebuilt)
```bash
docker run -d --name sketchforge --restart unless-stopped -p 3000:80 ghcr.io/formsmith746/sketchforge-3d:latest
docker run -d --name sketchforge --restart unless-stopped \
-p 3000:3000 \
-e SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects \
-v sketchforge-shared-projects:/data/projects \
ghcr.io/formsmith746/sketchforge-3d:latest
```
After running, open this on the same computer:
@@ -128,6 +132,27 @@ http://127.0.0.1:3000/
If that works, SketchForge is running.
### Shared Docker Projects
Docker deployments include a shared `.skf` project library. Private projects still autosave in each user's browser. The **Shared** dashboard section lists files stored in `/data/projects`, and **Export → SKF → Save to shared** writes the current project there.
Compose uses the persistent `sketchforge-shared-projects` volume by default. To use a directory on the Docker host instead, set `SKETCHFORGE_SHARED_PROJECTS_VOLUME` before starting Compose:
Windows PowerShell:
```powershell
$env:SKETCHFORGE_SHARED_PROJECTS_VOLUME = "C:/SketchForge/shared-projects"
docker compose -f deploy/docker/compose.yaml up --build -d
```
Linux or macOS:
```bash
SKETCHFORGE_SHARED_PROJECTS_VOLUME=/srv/sketchforge-projects docker compose -f deploy/docker/compose.yaml up --build -d
```
Opening a shared file creates a private local working copy. Saving back checks the server revision first; if another user has changed the file, SketchForge refuses to overwrite it and asks the user to reload or save with another name. This is shared file storage, not simultaneous live editing.
### Let Other Computers Join
Other computers on the same Wi-Fi or LAN need the server computer's local IP address.
+5
View File
@@ -1,12 +1,15 @@
import type { NextConfig } from "next";
import path from "node:path";
const isStaticExport = process.env.STATIC_EXPORT === "true";
const isDockerBuild = process.env.SKETCHFORGE_DOCKER_BUILD === "true";
const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? "")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean);
const nextConfig: NextConfig = {
outputFileTracingRoot: path.resolve(process.cwd()),
devIndicators: false,
// Keep the live development compiler isolated from `next build`. Sharing
// `.next` lets a production verification build invalidate chunks used by a
@@ -35,6 +38,8 @@ const nextConfig: NextConfig = {
output: "export" as const,
trailingSlash: true,
}
: isDockerBuild
? { output: "standalone" as const }
: {}),
};
@@ -0,0 +1,197 @@
import { randomUUID } from "crypto";
import { promises as fs } from "fs";
import path from "path";
import { NextResponse } from "next/server";
import { inspectSkfProjectPackage, SKF_LIMITS, SKF_MEDIA_TYPE } from "@/lib/skfProject";
export const runtime = "nodejs";
export const revalidate = false;
const SHARED_PROJECTS_ENV = "SKETCHFORGE_SHARED_PROJECTS_DIR";
type SharedProjectFile = {
fileName: string;
name: string;
updatedAt: number;
size: number;
revision: string;
};
function sharedProjectsDirectory() {
const configured = process.env[SHARED_PROJECTS_ENV]?.trim();
return configured ? path.resolve(configured) : null;
}
function safeProjectFileName(requestedName: string) {
const withoutExtension = requestedName.replace(/\.skf$/i, "");
const stem = path.basename(withoutExtension)
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_")
.replace(/\s+/g, " ")
.trim()
.slice(0, 115);
return `${stem || "Untitled project"}.skf`;
}
function revisionForStat(stat: { size: number; mtimeMs: number }) {
return `${stat.size.toString(16)}-${Math.round(stat.mtimeMs * 1000).toString(16)}`;
}
function projectRecord(fileName: string, stat: { size: number; mtimeMs: number }): SharedProjectFile {
return {
fileName,
name: fileName.replace(/\.skf$/i, ""),
updatedAt: stat.mtimeMs,
size: stat.size,
revision: revisionForStat(stat),
};
}
function unquoteEtag(value: string | null) {
if (!value) return null;
return value.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
}
function sameOriginRequest(request: Request) {
const origin = request.headers.get("origin");
if (!origin) return true;
try {
const requestUrl = new URL(request.url);
const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
const host = forwardedHost || request.headers.get("host") || requestUrl.host;
const protocol = forwardedProtocol || requestUrl.protocol.replace(/:$/, "");
return new URL(origin).origin === `${protocol}://${host}`;
} catch {
return false;
}
}
async function regularFileStat(filePath: string) {
try {
const stat = await fs.lstat(filePath);
if (stat.isSymbolicLink() || !stat.isFile()) return null;
return stat;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
}
function disabledResponse() {
return NextResponse.json(
{ enabled: false, projects: [], error: `${SHARED_PROJECTS_ENV} is not configured` },
{ headers: { "Cache-Control": "no-store" } },
);
}
export async function GET(request: Request) {
const root = sharedProjectsDirectory();
if (!root) return disabledResponse();
try {
await fs.mkdir(root, { recursive: true });
const requestUrl = new URL(request.url);
const requestedFile = requestUrl.searchParams.get("fileName");
if (requestedFile) {
const fileName = safeProjectFileName(requestedFile);
if (fileName !== requestedFile) return NextResponse.json({ error: "Invalid shared project name" }, { status: 400 });
const filePath = path.join(root, fileName);
const stat = await regularFileStat(filePath);
if (!stat) return NextResponse.json({ error: "Shared project was not found" }, { status: 404 });
const bytes = await fs.readFile(filePath);
return new Response(bytes, {
headers: {
"Cache-Control": "no-store",
"Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`,
"Content-Length": String(bytes.byteLength),
"Content-Type": SKF_MEDIA_TYPE,
ETag: `"${revisionForStat(stat)}"`,
},
});
}
const entries = await fs.readdir(root, { withFileTypes: true });
const projects = await Promise.all(entries
.filter((entry) => entry.isFile() && /\.skf$/i.test(entry.name))
.map(async (entry) => {
const stat = await regularFileStat(path.join(root, entry.name));
return stat ? projectRecord(entry.name, stat) : null;
}));
return NextResponse.json(
{ enabled: true, projects: projects.filter((entry): entry is SharedProjectFile => Boolean(entry)).sort((a, b) => b.updatedAt - a.updatedAt) },
{ headers: { "Cache-Control": "no-store" } },
);
} catch (error) {
return NextResponse.json({ enabled: true, projects: [], error: error instanceof Error ? error.message : "Could not read shared projects" }, { status: 500 });
}
}
export async function POST(request: Request) {
const root = sharedProjectsDirectory();
if (!root) return NextResponse.json({ error: "Shared project storage is disabled" }, { status: 404 });
if (!sameOriginRequest(request)) return NextResponse.json({ error: "Shared projects only accept same-origin saves" }, { status: 403 });
const declaredLength = Number(request.headers.get("content-length") ?? 0);
if (Number.isFinite(declaredLength) && declaredLength > SKF_LIMITS.archiveBytes) {
return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 });
}
let lockHandle: Awaited<ReturnType<typeof fs.open>> | null = null;
let lockPath = "";
let temporaryPath = "";
try {
const bytes = new Uint8Array(await request.arrayBuffer());
if (bytes.byteLength > SKF_LIMITS.archiveBytes) return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 });
const summary = await inspectSkfProjectPackage(bytes);
const requestUrl = new URL(request.url);
const fileName = safeProjectFileName(requestUrl.searchParams.get("fileName") ?? summary.projectName);
await fs.mkdir(root, { recursive: true });
const filePath = path.join(root, fileName);
lockPath = `${filePath}.lock`;
temporaryPath = path.join(root, `.${fileName}.${randomUUID()}.tmp`);
try {
lockHandle = await fs.open(lockPath, "wx");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "EEXIST") {
return NextResponse.json({ error: "This shared project is currently being saved by someone else" }, { status: 409 });
}
throw error;
}
const currentStat = await regularFileStat(filePath);
const currentRevision = currentStat ? revisionForStat(currentStat) : null;
const expectedRevision = unquoteEtag(request.headers.get("if-match"));
const createOnly = request.headers.get("if-none-match") === "*";
if (currentStat && (createOnly || !expectedRevision || expectedRevision !== currentRevision)) {
return NextResponse.json(
{ error: "The shared project changed after you opened it. Reload it or save under a different name.", currentRevision },
{ status: 409 },
);
}
if (!currentStat && expectedRevision) {
return NextResponse.json({ error: "The shared project no longer exists. Save it under a different name." }, { status: 409 });
}
const temporaryHandle = await fs.open(temporaryPath, "wx");
try {
await temporaryHandle.writeFile(bytes);
await temporaryHandle.sync();
} finally {
await temporaryHandle.close();
}
await fs.rename(temporaryPath, filePath);
temporaryPath = "";
const savedStat = await fs.stat(filePath);
const project = projectRecord(fileName, savedStat);
return NextResponse.json(
{ project: { ...project, name: summary.projectName } },
{ status: currentStat ? 200 : 201, headers: { "Cache-Control": "no-store", ETag: `"${project.revision}"` } },
);
} catch (error) {
return NextResponse.json({ error: error instanceof Error ? error.message : "Could not save shared project" }, { status: 400 });
} finally {
if (lockHandle) await lockHandle.close().catch(() => undefined);
if (temporaryPath) await fs.unlink(temporaryPath).catch(() => undefined);
if (lockPath) await fs.unlink(lockPath).catch(() => undefined);
}
}
+82 -3
View File
@@ -328,6 +328,39 @@ button {
font-size: 13px;
}
.shared-projects-refresh {
display: inline-flex;
min-height: 36px;
align-items: center;
gap: 7px;
padding: 0 12px;
color: #31536a;
font-size: 12px;
font-weight: 800;
background: #fff;
border: 1px solid #d3e0e7;
border-radius: 8px;
cursor: pointer;
}
.shared-projects-refresh:hover:not(:disabled) {
color: #087f9f;
border-color: #89d0e1;
}
.shared-projects-refresh:disabled {
cursor: default;
opacity: 0.6;
}
.shared-projects-refresh .spinning {
animation: shared-project-spin 850ms linear infinite;
}
@keyframes shared-project-spin {
to { transform: rotate(360deg); }
}
.dashboard-controls {
display: flex;
flex-wrap: wrap;
@@ -403,6 +436,23 @@ button {
box-shadow: 0 1px 2px rgba(31, 52, 71, 0.05);
}
.shared-project-badge {
position: absolute;
top: 10px;
right: 10px;
z-index: 2;
padding: 4px 7px;
color: #087f9f;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
pointer-events: none;
background: rgba(237, 251, 255, 0.94);
border: 1px solid #a9dfeb;
border-radius: 999px;
}
.project-list .project-card {
padding-right: 50px;
}
@@ -2370,6 +2420,29 @@ button {
box-shadow: 0 5px 14px rgba(4, 145, 183, 0.22);
}
.export-dialog-footer .export-shared-button {
min-width: 122px;
color: #087f9f;
background: #eefafd;
border: 1px solid #a9dce9;
}
.export-dialog-footer .export-shared-button:hover:not(:disabled) {
color: #056c87;
background: #e2f7fc;
border-color: #6dc7dc;
}
.export-dialog-footer .export-shared-button:disabled {
cursor: default;
opacity: 0.55;
}
.export-shared-button svg {
width: 16px;
height: 16px;
}
.export-dialog-footer .export-primary-button:hover:not(:disabled) {
background: linear-gradient(180deg, #0eadd4, #058db2);
}
@@ -3632,7 +3705,7 @@ button {
text-align: center;
pointer-events: auto;
cursor: text;
transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%);
transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%) rotate(var(--rotate-handle-angle, 0deg));
will-change: transform;
box-shadow: 0 1px 4px rgba(20, 42, 58, 0.09);
}
@@ -3791,7 +3864,7 @@ button {
box-shadow: none;
cursor: grab;
opacity: 1;
transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%) rotate(var(--rotate-handle-angle, 0deg));
transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%);
}
.rotate-handle:hover {
@@ -3892,6 +3965,12 @@ button {
box-shadow: -2px 0 10px rgba(36, 61, 86, 0.08);
}
.shape-inspector.minimized {
bottom: auto;
height: 50px;
overflow: hidden;
}
.shape-inspector-header {
display: flex;
align-items: center;
@@ -3978,7 +4057,7 @@ button {
display: block;
width: 64px;
height: 64px;
border-radius: 999px;
border-radius: 10px;
}
.large-solid-swatch {
+160 -6
View File
@@ -1,6 +1,6 @@
"use client";
import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
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 { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
@@ -13,7 +13,7 @@ import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings
type AppView = "dashboard" | "editor";
type ViewMode = "grid" | "list";
type DashboardSection = "home" | "challenges";
type DashboardSection = "home" | "shared" | "challenges";
type DownloadMode = "browser" | "folder";
type DashboardProject = {
@@ -29,6 +29,15 @@ type DashboardProject = {
workspace?: WorkplaneWorkspaceSettings;
snapGrid?: GridSize;
placementElevation?: number;
sharedProject?: { fileName: string; revision: string };
};
type SharedProject = {
fileName: string;
name: string;
updatedAt: number;
size: number;
revision: string;
};
type StoredDashboardProject = Partial<DashboardProject> & {
@@ -69,6 +78,12 @@ function formatUpdated(timestamp: number) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(new Date(timestamp));
}
function formatFileSize(bytes: number) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
}
function projectShapeCacheEntry(
revision: number,
shapes: WorkplaneShape[],
@@ -195,6 +210,9 @@ function readStoredProjects() {
workspace: normalizeWorkspaceSettings(project.workspace),
snapGrid: normalizeSnapGrid(project.snapGrid),
placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0,
sharedProject: typeof project.sharedProject?.fileName === "string" && typeof project.sharedProject.revision === "string"
? { fileName: project.sharedProject.fileName, revision: project.sharedProject.revision }
: undefined,
};
});
return { projects, legacyShapes };
@@ -226,6 +244,7 @@ function mergeProjectForStorage(project: DashboardProject, storedProject?: Dashb
workspace: project.workspace ?? storedProject.workspace,
snapGrid: project.snapGrid ?? storedProject.snapGrid,
placementElevation: project.placementElevation ?? storedProject.placementElevation,
sharedProject: project.sharedProject ?? storedProject.sharedProject,
};
}
@@ -243,6 +262,7 @@ function projectForStorage(project: DashboardProject): DashboardProject {
workspace: normalizeWorkspaceSettings(project.workspace),
snapGrid: normalizeSnapGrid(project.snapGrid),
placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0,
sharedProject: project.sharedProject,
};
}
@@ -286,12 +306,32 @@ export default function Home() {
const [downloadMode, setDownloadMode] = useState<DownloadMode>("browser");
const [downloadFolder, setDownloadFolder] = useState("");
const [dashboardNotice, setDashboardNotice] = useState("");
const [sharedProjects, setSharedProjects] = useState<SharedProject[]>([]);
const [sharedProjectsEnabled, setSharedProjectsEnabled] = useState(false);
const [sharedProjectsLoading, setSharedProjectsLoading] = useState(false);
const [projectShapesById, setProjectShapesById] = useState<Record<string, ProjectShapeCacheEntry>>({});
const projectsJsonRef = useRef("");
const dashboardImportInputRef = useRef<HTMLInputElement | null>(null);
const nextProjectRevisionRef = useRef(0);
const projectShapeSaveQueuesRef = useRef<Record<string, Promise<void>>>({});
const refreshSharedProjects = useCallback(async () => {
if (STATIC_EXPORT_BUILD) return;
setSharedProjectsLoading(true);
try {
const response = await fetch("/api/shared-projects", { cache: "no-store" });
const payload = await response.json() as { enabled?: boolean; projects?: SharedProject[]; error?: string };
setSharedProjectsEnabled(Boolean(payload.enabled));
setSharedProjects(Array.isArray(payload.projects) ? payload.projects : []);
if (!response.ok && payload.enabled) setDashboardNotice(payload.error ?? "Could not load shared projects");
} catch {
setSharedProjectsEnabled(false);
setSharedProjects([]);
} finally {
setSharedProjectsLoading(false);
}
}, []);
useEffect(() => {
document.documentElement.removeAttribute("data-theme");
document.documentElement.style.colorScheme = "light";
@@ -325,6 +365,11 @@ export default function Home() {
setMounted(true);
}, []);
useEffect(() => {
if (!mounted) return;
void refreshSharedProjects();
}, [mounted, refreshSharedProjects]);
useEffect(() => {
if (!mounted) return;
const localSerialized = JSON.stringify(projects);
@@ -413,6 +458,12 @@ export default function Home() {
return sortMode === "name" ? [...filtered].sort((a, b) => a.name.localeCompare(b.name)) : [...filtered].sort((a, b) => b.updatedAt - a.updatedAt);
}, [projects, query, sortMode]);
const visibleSharedProjects = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase();
const filtered = normalizedQuery ? sharedProjects.filter((project) => project.name.toLowerCase().includes(normalizedQuery)) : sharedProjects;
return sortMode === "name" ? [...filtered].sort((a, b) => a.name.localeCompare(b.name)) : [...filtered].sort((a, b) => b.updatedAt - a.updatedAt);
}, [query, sharedProjects, sortMode]);
const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean } = {}) => {
if (projectId && typeof window !== "undefined" && !options.allowMissingFromStorage) {
const storedProjects = readProjects();
@@ -567,7 +618,7 @@ export default function Home() {
openEditor(project.id, { allowMissingFromStorage: true });
};
const openSkfProjectFromFile = useCallback(async (file: File) => {
const openSkfProjectFromFile = useCallback(async (file: File, sharedProject?: SharedProject) => {
setDashboardNotice(`Validating ${file.name} before opening it as a new project`);
try {
const restored = await importSkfProject(await file.arrayBuffer());
@@ -580,14 +631,15 @@ export default function Home() {
workspace: restored.workspace,
snapGrid: restored.snapGrid,
placementElevation: restored.placementElevation,
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);
setProjectShapesById((current) => ({ ...current, [project.id]: entry }));
setProjects((current) => [project, ...current]);
setDashboardNotice(`Opened ${file.name} as a new editable local project`);
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`);
openEditor(project.id, { allowMissingFromStorage: true });
return { ok: true, message: `Opened ${file.name} as a new editable local project` };
return { ok: true, message: sharedProject ? `Opened shared project ${sharedProject.name}` : `Opened ${file.name} as a new editable local project` };
} catch (error) {
const message = error instanceof Error ? error.message : "Could not open SketchForge project";
setDashboardNotice(message);
@@ -595,6 +647,45 @@ export default function Home() {
}
}, [projects.length]);
const openSharedProject = useCallback(async (sharedProject: SharedProject) => {
setDashboardNotice(`Opening shared project ${sharedProject.name}`);
try {
const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(sharedProject.fileName)}`, { cache: "no-store" });
if (!response.ok) {
const payload = await response.json().catch(() => ({})) as { error?: string };
throw new Error(payload.error ?? "Could not download shared project");
}
const revision = response.headers.get("etag")?.replace(/^W\//, "").replace(/^"|"$/g, "") || sharedProject.revision;
const file = new File([await response.blob()], sharedProject.fileName, { type: "application/vnd.sketchforge.project+zip" });
await openSkfProjectFromFile(file, { ...sharedProject, revision });
} catch (error) {
setDashboardNotice(error instanceof Error ? error.message : "Could not open shared project");
}
}, [openSkfProjectFromFile]);
const saveActiveProjectToShared = useCallback(async ({ exportName, bytes }: { exportName: string; bytes: Uint8Array }) => {
const activeProject = projects.find((project) => project.id === activeProjectId);
if (!activeProject) throw new Error("Open a local project before saving it to the shared space");
const normalizedExportName = exportName.trim() || activeProject.name;
const saveBackToSource = Boolean(activeProject.sharedProject && normalizedExportName === activeProject.name);
const fileName = saveBackToSource && activeProject.sharedProject
? activeProject.sharedProject.fileName
: `${normalizedExportName.replace(/\.skf$/i, "")}.skf`;
const headers: Record<string, string> = { "Content-Type": "application/vnd.sketchforge.project+zip" };
if (saveBackToSource && activeProject.sharedProject) headers["If-Match"] = `"${activeProject.sharedProject.revision}"`;
else headers["If-None-Match"] = "*";
const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(fileName)}`, { method: "POST", headers, body });
const payload = await response.json().catch(() => ({})) as { error?: string; project?: SharedProject };
if (!response.ok || !payload.project) throw new Error(payload.error ?? "Could not save the shared project");
const savedProject = payload.project;
setProjects((current) => current.map((project) => project.id === activeProject.id
? { ...project, sharedProject: { fileName: savedProject.fileName, revision: savedProject.revision } }
: project));
await refreshSharedProjects();
return `Saved ${savedProject.name} to the Docker shared project space`;
}, [activeProjectId, projects, refreshSharedProjects]);
const importFilesFromDashboard = useCallback(
async (files: File[]) => {
if (!files.length) return;
@@ -773,6 +864,9 @@ export default function Home() {
projects={visibleProjects}
query={query}
settingsOpen={settingsOpen}
sharedProjects={visibleSharedProjects}
sharedProjectsEnabled={sharedProjectsEnabled}
sharedProjectsLoading={sharedProjectsLoading}
staticExportBuild={STATIC_EXPORT_BUILD}
sortMode={sortMode}
viewMode={viewMode}
@@ -787,10 +881,17 @@ export default function Home() {
setDashboardNotice("");
}}
onDashboardHome={() => setDashboardSection("home")}
onOpenSharedProject={(project) => void openSharedProject(project)}
onOpenProject={openEditor}
onOpenSettings={() => setSettingsOpen(true)}
onQueryChange={setQuery}
onRenameProject={renameProject}
onRefreshSharedProjects={() => void refreshSharedProjects()}
onSharedProjects={() => {
setDashboardSection("shared");
setDashboardNotice("");
void refreshSharedProjects();
}}
onSortModeChange={setSortMode}
onViewModeChange={setViewMode}
onWorkspace={openLatestProject}
@@ -808,6 +909,7 @@ export default function Home() {
initialPlacementElevation={activeProject?.placementElevation ?? 0}
onHome={openDashboard}
onOpenSkfProjectFile={openSkfProjectFromFile}
onSaveSharedProject={saveActiveProjectToShared}
onProjectShapesChange={updateProjectShapes}
onProjectSnapshot={updateProjectSnapshot}
onProjectWorkspaceChange={updateProjectWorkspace}
@@ -816,6 +918,7 @@ export default function Home() {
projectCreatedAt={activeProject?.createdAt}
projectModifiedAt={activeProject?.updatedAt}
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
sharedProjectsEnabled={sharedProjectsEnabled}
/>
</div>
) : null}
@@ -831,6 +934,9 @@ function Dashboard({
projects,
query,
settingsOpen,
sharedProjects,
sharedProjectsEnabled,
sharedProjectsLoading,
staticExportBuild,
sortMode,
viewMode,
@@ -842,10 +948,13 @@ function Dashboard({
onImportFile,
onChallenges,
onDashboardHome,
onOpenSharedProject,
onOpenProject,
onOpenSettings,
onQueryChange,
onRenameProject,
onRefreshSharedProjects,
onSharedProjects,
onSortModeChange,
onViewModeChange,
onWorkspace,
@@ -857,6 +966,9 @@ function Dashboard({
projects: DashboardProject[];
query: string;
settingsOpen: boolean;
sharedProjects: SharedProject[];
sharedProjectsEnabled: boolean;
sharedProjectsLoading: boolean;
staticExportBuild: boolean;
sortMode: string;
viewMode: ViewMode;
@@ -868,10 +980,13 @@ function Dashboard({
onImportFile: () => void;
onChallenges: () => void;
onDashboardHome: () => void;
onOpenSharedProject: (project: SharedProject) => void;
onOpenProject: (projectId: string) => void;
onOpenSettings: () => void;
onQueryChange: (value: string) => void;
onRenameProject: (projectId: string, name: string) => void;
onRefreshSharedProjects: () => void;
onSharedProjects: () => void;
onSortModeChange: (value: string) => void;
onViewModeChange: (value: ViewMode) => void;
onWorkspace: () => void;
@@ -936,6 +1051,12 @@ function Dashboard({
<HomeIcon size={20} />
<span>Home</span>
</button>
{sharedProjectsEnabled ? (
<button className={`dashboard-nav-item ${dashboardSection === "shared" ? "active" : ""}`} type="button" aria-label="Shared projects" title="Shared projects" onClick={onSharedProjects}>
<FolderKanban size={20} />
<span>Shared</span>
</button>
) : null}
<button className={`dashboard-nav-item ${dashboardSection === "challenges" ? "active" : ""}`} type="button" aria-label="Challenges" title="Challenges" onClick={onChallenges}>
<SlidersHorizontal size={20} />
<span>Challenges</span>
@@ -947,11 +1068,44 @@ function Dashboard({
</button>
</aside>
<section className="dashboard-main" aria-label={dashboardSection === "challenges" ? "Challenges" : "Dashboard"}>
<section className="dashboard-main" aria-label={dashboardSection === "challenges" ? "Challenges" : dashboardSection === "shared" ? "Shared projects" : "Dashboard"}>
{dashboardSection === "challenges" ? (
<div className="dashboard-coming-soon" role="status">
<strong>Coming soon</strong>
</div>
) : dashboardSection === "shared" ? (
<>
{dashboardNotice ? <div className="dashboard-import-notice" role="status">{dashboardNotice}</div> : null}
<div className="dashboard-section-header shared-projects-header">
<div>
<h1>Shared projects</h1>
<span>{sharedProjects.length} available from Docker storage</span>
</div>
<button className="shared-projects-refresh" type="button" onClick={onRefreshSharedProjects} disabled={sharedProjectsLoading}>
<RefreshCw size={16} className={sharedProjectsLoading ? "spinning" : undefined} />
<span>Refresh</span>
</button>
</div>
{sharedProjects.length > 0 ? (
<div className={viewMode === "grid" ? "project-grid" : "project-list"}>
{sharedProjects.map((project, index) => (
<article className="project-card shared-project-card" key={project.fileName}>
<button className="project-card-open" type="button" onClick={() => onOpenSharedProject(project)}>
<ProjectPreview accent={PROJECT_ACCENTS[index % PROJECT_ACCENTS.length]} />
<span className="project-card-title">{project.name}</span>
<span className="project-card-meta">{formatUpdated(project.updatedAt)} - {formatFileSize(project.size)}</span>
</button>
<span className="shared-project-badge">Shared</span>
</article>
))}
</div>
) : (
<div className="project-empty">
<strong>{sharedProjectsLoading ? "Loading shared projects" : "No shared projects yet"}</strong>
<span>Save an SKF project to the shared space from the Export window.</span>
</div>
)}
</>
) : (
<>
<div className="dashboard-actions-band">
+146 -26
View File
@@ -1,6 +1,6 @@
"use client";
import { Check, Download, FolderOpen, X } from "lucide-react";
import { Check, CloudUpload, Download, FolderOpen, X } from "lucide-react";
import type manifoldModule from "manifold-3d";
import type { ManifoldToplevel } from "manifold-3d";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -52,6 +52,7 @@ import {
cleanNearZero,
cleanRotationDegrees,
fallbackSolidColor,
meshYawDegrees,
mirroredAxisCount,
mirrorSign,
normalizeDegrees,
@@ -78,6 +79,7 @@ import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap
import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
@@ -101,6 +103,7 @@ type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null;
type ExportFormat = "stl" | "obj" | "step" | "svg" | "skf";
type DirectExportFormat = Exclude<ExportFormat, "step" | "skf">;
type SkfHistoryLimit = EditorHistoryExportLimit;
type SkfExportTarget = "download" | "shared";
type ToolbarMode = "geometry" | "sketch";
type Vec3 = [number, number, number];
type MeshData = { name: string; vertices: Vec3[]; faces: [number, number, number][] };
@@ -311,7 +314,89 @@ function pointInSketchPolygon(point: THREE.Vector2, polygon: THREE.Vector2[]) {
return inside;
}
function shapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) {
async function shapeFromResolvedSketchProfile(
profile: SketchProfile,
polygons: Array<Array<[number, number]>>,
height: number,
centerX: number,
centerZ: number,
existing?: WorkplaneShape | null,
) {
const runtime = await getManifoldRuntime();
const disposable: unknown[] = [];
try {
const section = new runtime.CrossSection(polygons, "EvenOdd");
disposable.push(section);
const coordinateScale = polygons.reduce(
(largest, polygon) => polygon.reduce((polygonLargest, point) => Math.max(polygonLargest, Math.abs(point[0]), Math.abs(point[1])), largest),
1,
);
const simplified = section.simplify(Math.max(1e-7, coordinateScale * 1e-8));
disposable.push(simplified);
if (simplified.toPolygons().length === 0) throw new Error("The sketch has no filled area after resolving its crossings");
const solid = simplified.extrude(height);
disposable.push(solid);
if (solid.status() !== "NoError" || solid.numTri() < 1) {
throw new Error("The crossing sketch could not be converted into a valid solid");
}
const manifoldPositions = manifoldMeshToPositions(solid.getMesh());
const positions = new Array<number>(manifoldPositions.length);
let minX = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let index = 0; index + 2 < manifoldPositions.length; index += 3) {
const x = manifoldPositions[index];
const y = manifoldPositions[index + 2];
const z = -manifoldPositions[index + 1];
positions[index] = x;
positions[index + 1] = y;
positions[index + 2] = z;
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minZ = Math.min(minZ, z);
maxZ = Math.max(maxZ, z);
}
const localCenterX = (minX + maxX) / 2;
const localCenterZ = (minZ + maxZ) / 2;
for (let index = 0; index + 2 < positions.length; index += 3) {
positions[index] -= localCenterX;
positions[index + 2] -= localCenterZ;
}
const meshWidth = Math.max(0.01, maxX - minX);
const meshDepth = Math.max(0.01, maxZ - minZ);
return canonicalizeShape({
id: existing?.id ?? createLocalId("sketch-extrusion"),
name: existing?.name ?? "Sketch extrusion",
kind: "mesh",
color: existing?.color ?? "#d41721",
hole: existing?.hole,
x: centerX + localCenterX,
z: centerZ + localCenterZ,
elevation: 0,
size: Math.max(meshWidth, meshDepth),
width: meshWidth,
depth: meshDepth,
height,
rotation: 0,
importedMesh: {
positions,
baseWidth: meshWidth,
baseDepth: meshDepth,
baseHeight: height,
triangleCount: Math.floor(positions.length / 9),
sourceFormat: "json",
},
sketchProfile: cloneSketchProfile(profile),
} satisfies WorkplaneShape);
} finally {
[...new Set(disposable)].reverse().forEach(disposeManifold);
}
}
async function shapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) {
const closedPaths = orderedSketchPaths(profile).filter((path) => path.closed);
if (closedPaths.length === 0) return null;
const profilePoints = closedPaths.flatMap((path) => path.points);
@@ -349,6 +434,25 @@ function shapeFromSketchProfile(profile: SketchProfile, height: number, existing
const polygon = outline.extractPoints(16).shape;
return { outline, polygon, area: Math.abs(THREE.ShapeUtils.area(polygon)) };
});
const hasCurves = profile.segments.some((segment) => segment.kind === "bezier" || segment.kind === "smooth");
const longestHandle = profile.points.reduce((longest, point) => Math.max(
longest,
point.handleIn ? Math.hypot(point.handleIn.x - point.x, point.handleIn.z - point.z) : 0,
point.handleOut ? Math.hypot(point.handleOut.x - point.x, point.handleOut.z - point.z) : 0,
), 0);
const curveScale = Math.max(width, depth, longestHandle * 2);
const curveSegments = hasCurves ? Math.min(256, Math.max(32, Math.ceil(curveScale * 1.25))) : 1;
const sampledPolygons = outlineRecords.map((record) => record.outline.extractPoints(curveSegments).shape);
if (findSketchOutlineIntersection(sampledPolygons)) {
return shapeFromResolvedSketchProfile(
profile,
sampledPolygons.map((polygon) => polygon.map((point) => [point.x, point.y] as [number, number])),
safeHeight,
centerX,
centerZ,
existing,
);
}
const sortedOutlines = [...outlineRecords].sort((a, b) => b.area - a.area);
const outlines: THREE.Shape[] = [];
sortedOutlines.forEach((record) => {
@@ -361,14 +465,6 @@ function shapeFromSketchProfile(profile: SketchProfile, height: number, existing
if (parent) parent.outline.holes.push(record.outline);
else outlines.push(record.outline);
});
const hasCurves = profile.segments.some((segment) => segment.kind === "bezier" || segment.kind === "smooth");
const longestHandle = profile.points.reduce((longest, point) => Math.max(
longest,
point.handleIn ? Math.hypot(point.handleIn.x - point.x, point.handleIn.z - point.z) : 0,
point.handleOut ? Math.hypot(point.handleOut.x - point.x, point.handleOut.z - point.z) : 0,
), 0);
const curveScale = Math.max(width, depth, longestHandle * 2);
const curveSegments = hasCurves ? Math.min(256, Math.max(32, Math.ceil(curveScale * 1.25))) : 1;
const geometry = new THREE.ExtrudeGeometry(outlines, { depth: safeHeight, bevelEnabled: false, steps: 1, curveSegments });
geometry.rotateX(-Math.PI / 2);
geometry.computeVertexNormals();
@@ -416,14 +512,6 @@ function cleanModelDimension(value: number) {
return Math.max(MIN_SHAPE_DIMENSION, Number(value.toFixed(MODEL_DIMENSION_PRECISION)));
}
function meshYawDegrees(shape: WorkplaneShape) {
const isRoundPrimitive = !shape.importedMesh && (shape.kind === "cylinder" || shape.kind === "cone");
const isCircular = Math.abs(shapeWidth(shape) - shapeDepth(shape)) < 0.0005;
// A circular cylinder/cone is invariant around Y. Ignoring that purely visual
// yaw keeps its tessellated export at the requested diameter after grouping.
return isRoundPrimitive && isCircular ? 0 : shape.rotation;
}
function parseClipboardShapes(serialized: string) {
try {
const parsed = JSON.parse(serialized);
@@ -5048,6 +5136,7 @@ export function SketchForgeEditor({
initialPlacementElevation = 0,
onHome,
onOpenSkfProjectFile,
onSaveSharedProject,
onProjectShapesChange,
onProjectSnapshot,
onProjectWorkspaceChange,
@@ -5056,6 +5145,7 @@ export function SketchForgeEditor({
projectCreatedAt = Date.now(),
projectModifiedAt = Date.now(),
projectRevision = 0,
sharedProjectsEnabled = false,
}: {
initialAssets?: ProjectAsset[];
initialShapes?: WorkplaneShape[];
@@ -5066,6 +5156,7 @@ export function SketchForgeEditor({
initialPlacementElevation?: number;
onHome?: () => void;
onOpenSkfProjectFile?: (file: File) => Promise<{ ok: boolean; message: string } | void> | { ok: boolean; message: string } | void;
onSaveSharedProject?: (request: { exportName: string; bytes: Uint8Array }) => Promise<string>;
onProjectShapesChange?: (snapshot: {
projectId: string;
shapes: WorkplaneShape[];
@@ -5080,6 +5171,7 @@ export function SketchForgeEditor({
projectCreatedAt?: number;
projectModifiedAt?: number;
projectRevision?: number;
sharedProjectsEnabled?: boolean;
} = {}) {
const initialSceneRef = useRef<WorkplaneShape[] | null>(null);
if (initialSceneRef.current === null) {
@@ -6133,10 +6225,16 @@ export function SketchForgeEditor({
setSketchTool("select");
}, [commitSketchProfile, sketchProfile]);
const finishSketch = useCallback(() => {
const finishSketch = useCallback(async () => {
const existing = editingSketchShapeId ? shapes.find((shape) => shape.id === editingSketchShapeId) ?? null : null;
const height = existing?.height ?? 10;
const extruded = shapeFromSketchProfile(sketchProfile, height, existing);
let extruded: WorkplaneShape | null;
try {
extruded = await shapeFromSketchProfile(sketchProfile, height, existing);
} catch (error) {
setNotice(error instanceof Error ? error.message : "The sketch profile cannot be converted to 3D");
return;
}
if (!extruded) {
setNotice("Close at least one profile before finishing the sketch");
return;
@@ -7162,7 +7260,7 @@ export function SketchForgeEditor({
let shape: WorkplaneShape;
if (kind === "sketch") {
const profile = defaultMcpSketchProfile(width, depth);
const extruded = shapeFromSketchProfile(profile, height);
const extruded = await shapeFromSketchProfile(profile, height);
if (!extruded) throw new Error("Could not create the sketch profile");
shape = canonicalizeShape({
...extruded,
@@ -7762,14 +7860,18 @@ export function SketchForgeEditor({
}
}, [hasSelection, projectName, selectedShapes, shapes, stepExporting]);
const exportSkfDesign = useCallback(async (exportName: string, historyLimit: SkfHistoryLimit) => {
const exportSkfDesign = useCallback(async (exportName: string, historyLimit: SkfHistoryLimit, target: SkfExportTarget = "download") => {
if (skfExporting) return;
if (target === "shared" && !onSaveSharedProject) {
setNotice("Shared project storage is not available in this deployment");
return;
}
if (projectInteractionActiveRef.current) {
setNotice("Finish the current drag or transform before saving the project file");
return;
}
setSkfExporting(true);
setNotice("Packaging editable project, history, and deduplicated assets…");
setNotice(target === "shared" ? "Packaging project for Docker shared storage…" : "Packaging editable project, history, and deduplicated assets…");
try {
const exportedHistory = editorHistoryForExport(historyRef.current, historyIndexRef.current, historyLimit);
const bytes = await exportSkfProject({
@@ -7785,15 +7887,19 @@ export function SketchForgeEditor({
snapGrid,
placementElevation,
});
if (target === "shared" && onSaveSharedProject) {
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes }));
} else {
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
const result = await downloadBlobFile(projectExportFileName(exportName, "skf"), new Blob([buffer], { type: SKF_MEDIA_TYPE }));
setNotice(result.mode === "folder" ? `Saved editable SketchForge project to ${result.path}` : "Saved editable SketchForge project (.skf)");
}
} catch (error) {
setNotice(error instanceof Error ? error.message : "Could not save SketchForge project");
} finally {
setSkfExporting(false);
}
}, [placementElevation, projectCreatedAt, projectModifiedAt, projectName, skfExporting, snapGrid]);
}, [onSaveSharedProject, placementElevation, projectCreatedAt, projectModifiedAt, projectName, skfExporting, snapGrid]);
const clearDesign = useCallback(() => {
commitShapes([], [], "New empty design");
@@ -8245,7 +8351,7 @@ export function SketchForgeEditor({
onWorkplaneTool={activateWorkplaneTool}
workplaneMode={workplaneMode}
onTopPanel={(panel) => {
setTopPanel(panel);
setTopPanel((current) => (current === panel ? null : panel));
setMenuOpen(false);
}}
onAddShape={(shape) => {
@@ -8392,6 +8498,7 @@ export function SketchForgeEditor({
onExport={exportDesign}
onExportSkf={exportSkfDesign}
onExportStep={exportStepDesign}
sharedProjectsEnabled={sharedProjectsEnabled}
skfExporting={skfExporting}
stepExporting={stepExporting}
onImportFiles={selectFiles}
@@ -8898,6 +9005,7 @@ function TopActionPanel({
onExport,
onExportSkf,
onExportStep,
sharedProjectsEnabled,
skfExporting,
stepExporting,
onImportFiles,
@@ -8911,8 +9019,9 @@ function TopActionPanel({
scopeLabel: "selected" | "total";
onClose: () => void;
onExport: (format: DirectExportFormat, exportName: string) => void;
onExportSkf: (exportName: string, historyLimit: SkfHistoryLimit) => void;
onExportSkf: (exportName: string, historyLimit: SkfHistoryLimit, target?: SkfExportTarget) => void;
onExportStep: (exportName: string) => void;
sharedProjectsEnabled: boolean;
skfExporting: boolean;
stepExporting: boolean;
onImportFiles: (files: FileList | File[]) => void;
@@ -9099,6 +9208,17 @@ function TopActionPanel({
<footer className="export-dialog-footer">
<div>
{exportFormat === "skf" && sharedProjectsEnabled ? (
<button
className="export-shared-button"
type="button"
onClick={() => onExportSkf(exportName, skfHistoryLimit, "shared")}
disabled={skfExporting || stepExporting}
>
<CloudUpload />
<span>Save to shared</span>
</button>
) : null}
<button className="export-primary-button" onClick={runSelectedExport} disabled={(shapeCount === 0 && exportFormat !== "skf") || stepExporting || skfExporting}>
<Download />
{exportFormat === "skf" ? (skfExporting ? "Saving project…" : "Save SketchForge Project") : null}
+39 -2
View File
@@ -1271,7 +1271,6 @@ const ROTATION_HANDLE_SIDE_HYSTERESIS = 0.22;
const ROTATION_HANDLE_DOMINANCE_HYSTERESIS = 0.18;
const ROTATION_UPPER_HANDLE_ICON_ANGLE = 0;
const ROTATION_BOTTOM_HANDLE_ICON_ANGLE = 0;
function signedRotationSide(value: number, previous: RotationHandleSide | undefined, positiveSide: RotationHandleSide, negativeSide: RotationHandleSide) {
if (previous === positiveSide && value > -ROTATION_HANDLE_SIDE_HYSTERESIS) {
return previous;
@@ -2477,6 +2476,44 @@ export function WorkplaneViewport({
[onInteractionActiveChange, rememberResizeAnchor, toRawPlanePoint],
);
const beginCameraDragFromOverlay = useCallback((event: ReactPointerEvent<Element>) => {
if (event.button !== 2) {
return;
}
event.preventDefault();
event.stopPropagation();
const state = threeRef.current;
const canvas = state?.renderer.domElement;
const PointerEventConstructor = canvas?.ownerDocument.defaultView?.PointerEvent;
if (!canvas || !PointerEventConstructor) {
return;
}
const source = event.nativeEvent;
canvas.dispatchEvent(
new PointerEventConstructor("pointerdown", {
bubbles: true,
cancelable: true,
composed: true,
pointerId: source.pointerId,
pointerType: source.pointerType,
isPrimary: source.isPrimary,
button: source.button,
buttons: source.buttons,
clientX: source.clientX,
clientY: source.clientY,
screenX: source.screenX,
screenY: source.screenY,
ctrlKey: source.ctrlKey,
shiftKey: source.shiftKey,
altKey: source.altKey,
metaKey: source.metaKey,
}),
);
}, []);
const updateTransform = useCallback(
(clientX: number, clientY: number, shiftKey = false, altKey = false) => {
const transform = transformRef.current;
@@ -3634,6 +3671,7 @@ export function WorkplaneViewport({
hideDimensionMarks={activeTransformKind === "scale"}
rotationWheelAxis={rotationWheelAxis}
pinnedRotationWheelView={pinnedRotationWheelView}
onBeginCameraDrag={beginCameraDragFromOverlay}
onBeginTransform={beginTransform}
onMoveTransform={updateTransform}
onFinishTransform={finishTransform}
@@ -3675,7 +3713,6 @@ export function WorkplaneViewport({
snapOpen={snapOpen}
workspace={workspace}
onUpdate={(patch, options) => onUpdateShape(selectedShape.id, patchWithResizeAnchor(selectedShape, patch, options?.resizeAxis, lastResizeAnchorRef.current))}
onClose={() => onSelectShape(null)}
onSnapChange={setSnap}
onSnapOpenChange={setSnapOpen}
onEditSketch={selectedShape.sketchProfile ? onEditSketch : undefined}
@@ -200,7 +200,6 @@ export function ShapeInspector({
snapOpen,
workspace,
onUpdate,
onClose,
onSnapChange,
onSnapOpenChange,
onEditSketch,
@@ -213,7 +212,6 @@ export function ShapeInspector({
snapOpen: boolean;
workspace: WorkplaneWorkspaceSettings;
onUpdate: ShapeInspectorUpdate;
onClose: () => void;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
onEditSketch?: () => void;
@@ -226,14 +224,20 @@ export function ShapeInspector({
const properties = getShapeProperties(shape, onUpdate);
const [propertiesOpen, setPropertiesOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
const [minimized, setMinimized] = useState(false);
useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]);
return (
<aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<aside className={`shape-inspector ${minimized ? "minimized" : ""}`} aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header">
<button className="inspector-header-icon" aria-label="Close shape settings" onClick={onClose}>
<ChevronUp size={26} strokeWidth={2.8} />
<button
className="inspector-header-icon"
aria-label={minimized ? "Expand shape settings" : "Minimize shape settings"}
aria-expanded={!minimized}
onClick={() => setMinimized((current) => !current)}
>
{minimized ? <ChevronDown size={26} strokeWidth={2.8} /> : <ChevronUp size={26} strokeWidth={2.8} />}
</button>
<strong>{shape.name}</strong>
<div className="inspector-header-actions">
@@ -246,6 +250,8 @@ export function ShapeInspector({
</div>
</div>
{!minimized ? (
<>
<div className="shape-state-card" role="group" aria-label="Shape mode">
<button
className={!shape.hole ? "active solid-choice" : "solid-choice"}
@@ -356,6 +362,8 @@ export function ShapeInspector({
<div className="inspector-snap-dock">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
</div>
</>
) : null}
</aside>
);
}
@@ -32,6 +32,7 @@ export function TransformOverlay({
hideDimensionMarks,
rotationWheelAxis,
pinnedRotationWheelView,
onBeginCameraDrag,
onBeginTransform,
onMoveTransform,
onFinishTransform,
@@ -75,10 +76,22 @@ export function TransformOverlay({
const plane = pinnedWheel?.plane ?? box.rotationPlanes[rotationWheelAxis];
const wheel = pinnedWheel?.wheel ?? box.rotationWheels[rotationWheelAxis] ?? box.rotationWheel;
return (
<div className={`transform-overlay ${hideSelectionChrome ? "hide-selection-chrome" : ""}`} aria-hidden="true">
<div
className={`transform-overlay ${hideSelectionChrome ? "hide-selection-chrome" : ""}`}
onPointerDownCapture={(event) => {
if (event.button === 2) {
onBeginCameraDrag(event);
}
}}
onContextMenu={(event) => {
event.preventDefault();
event.stopPropagation();
}}
>
{showRotationWheel && wheel && plane ? (
<svg
className={`rotation-protractor-plane axis-${rotationWheelAxis}`}
aria-hidden="true"
viewBox={`0 0 ${box.width} ${box.height}`}
preserveAspectRatio="none"
onPointerDown={(event) => onBeginTransform("rotate", `rotate-wheel-${rotationWheelAxis}`, event)}
@@ -107,7 +120,7 @@ export function TransformOverlay({
</g>
</svg>
) : null}
<svg className="transform-guides" viewBox={`0 0 ${box.width} ${box.height}`} preserveAspectRatio="none">
<svg className="transform-guides" viewBox={`0 0 ${box.width} ${box.height}`} preserveAspectRatio="none" aria-hidden="true">
<defs>
<marker id="dimension-arrow" markerWidth="8" markerHeight="8" refX="4" refY="4" orient="auto" markerUnits="strokeWidth">
<path d="M0 4 L8 0 L5.2 4 L8 8 Z" />
@@ -88,6 +88,7 @@ export type TransformOverlayProps = {
hideDimensionMarks: boolean;
rotationWheelAxis: RotationAxis;
pinnedRotationWheelView: PinnedRotationWheelView | null;
onBeginCameraDrag: (event: ReactPointerEvent<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;
+7
View File
@@ -4,6 +4,13 @@ export const CAD_MODIFIER_MAX_SHARP_ANGLE = 90;
export type CadModifierRequestPhase = "prepare" | "preview";
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) ||
/^(?:WebAssembly\.)?RuntimeError$/i.test(errorName)
);
}
export function edgeModifierSelectionStatus(prepared: boolean, selectedCount: number, availableCount: number) {
return prepared ? `${selectedCount} of ${availableCount} sharp edges selected` : "Preparing edges\u2026";
}
+115
View File
@@ -0,0 +1,115 @@
export type SketchOutlinePoint = Readonly<{ x: number; y: number }>;
export type SketchOutlineIntersection = {
outlineA: number;
edgeA: number;
outlineB: number;
edgeB: number;
};
function distanceSquared(a: SketchOutlinePoint, b: SketchOutlinePoint) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return dx * dx + dy * dy;
}
function normalizedOutline(points: readonly SketchOutlinePoint[], epsilon: number) {
const epsilonSquared = epsilon * epsilon;
const result: SketchOutlinePoint[] = [];
points.forEach((point) => {
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) return;
if (!result.length || distanceSquared(result[result.length - 1], point) > epsilonSquared) result.push(point);
});
if (result.length > 1 && distanceSquared(result[0], result[result.length - 1]) <= epsilonSquared) result.pop();
return result;
}
function orientation(a: SketchOutlinePoint, b: SketchOutlinePoint, c: SketchOutlinePoint) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
function pointOnSegment(point: SketchOutlinePoint, start: SketchOutlinePoint, end: SketchOutlinePoint, epsilon: number) {
if (Math.abs(orientation(start, end, point)) > epsilon) return false;
return point.x >= Math.min(start.x, end.x) - epsilon
&& point.x <= Math.max(start.x, end.x) + epsilon
&& point.y >= Math.min(start.y, end.y) - epsilon
&& point.y <= Math.max(start.y, end.y) + epsilon;
}
function segmentsIntersect(
a: SketchOutlinePoint,
b: SketchOutlinePoint,
c: SketchOutlinePoint,
d: SketchOutlinePoint,
epsilon: number,
) {
if (Math.max(a.x, b.x) + epsilon < Math.min(c.x, d.x)
|| Math.max(c.x, d.x) + epsilon < Math.min(a.x, b.x)
|| Math.max(a.y, b.y) + epsilon < Math.min(c.y, d.y)
|| Math.max(c.y, d.y) + epsilon < Math.min(a.y, b.y)) {
return false;
}
const abC = orientation(a, b, c);
const abD = orientation(a, b, d);
const cdA = orientation(c, d, a);
const cdB = orientation(c, d, b);
const crossesAB = (abC > epsilon && abD < -epsilon) || (abC < -epsilon && abD > epsilon);
const crossesCD = (cdA > epsilon && cdB < -epsilon) || (cdA < -epsilon && cdB > epsilon);
if (crossesAB && crossesCD) return true;
return (Math.abs(abC) <= epsilon && pointOnSegment(c, a, b, epsilon))
|| (Math.abs(abD) <= epsilon && pointOnSegment(d, a, b, epsilon))
|| (Math.abs(cdA) <= epsilon && pointOnSegment(a, c, d, epsilon))
|| (Math.abs(cdB) <= epsilon && pointOnSegment(b, c, d, epsilon));
}
function outlineEpsilon(outlines: readonly (readonly SketchOutlinePoint[])[]) {
const points = outlines.flatMap((outline) => [...outline]);
if (!points.length) return 1e-8;
const minX = Math.min(...points.map((point) => point.x));
const maxX = Math.max(...points.map((point) => point.x));
const minY = Math.min(...points.map((point) => point.y));
const maxY = Math.max(...points.map((point) => point.y));
return Math.max(1e-8, Math.hypot(maxX - minX, maxY - minY) * 1e-8);
}
function adjacentEdges(first: number, second: number, edgeCount: number) {
return first === second
|| Math.abs(first - second) === 1
|| (first === 0 && second === edgeCount - 1)
|| (second === 0 && first === edgeCount - 1);
}
/**
* Finds crossings that make closed sketch contours unsafe to triangulate.
* Adjacent edges may share their intended endpoint; all other touching,
* crossing, or overlapping edges are rejected.
*/
export function findSketchOutlineIntersection(outlines: readonly (readonly SketchOutlinePoint[])[]): SketchOutlineIntersection | null {
const epsilon = outlineEpsilon(outlines);
const clean = outlines.map((outline) => normalizedOutline(outline, epsilon));
for (let outlineA = 0; outlineA < clean.length; outlineA += 1) {
const a = clean[outlineA];
if (a.length < 3) continue;
for (let edgeA = 0; edgeA < a.length; edgeA += 1) {
const aStart = a[edgeA];
const aEnd = a[(edgeA + 1) % a.length];
for (let outlineB = outlineA; outlineB < clean.length; outlineB += 1) {
const b = clean[outlineB];
if (b.length < 3) continue;
const firstEdgeB = outlineA === outlineB ? edgeA + 1 : 0;
for (let edgeB = firstEdgeB; edgeB < b.length; edgeB += 1) {
if (outlineA === outlineB && adjacentEdges(edgeA, edgeB, a.length)) continue;
const bStart = b[edgeB];
const bEnd = b[(edgeB + 1) % b.length];
if (segmentsIntersect(aStart, aEnd, bStart, bEnd, epsilon)) {
return { outlineA, edgeA, outlineB, edgeB };
}
}
}
}
}
return null;
}
+44 -15
View File
@@ -152,6 +152,13 @@ export type SkfRestoredProject = {
migratedFromVersion?: number;
};
export type SkfProjectPackageSummary = {
projectName: string;
createdAt: number;
modifiedAt: number;
formatVersion: number;
};
export type SkfSourceImporter = (asset: ProjectAsset) => Promise<NonNullable<WorkplaneShape["importedMesh"]>>;
export type ImportSkfOptions = {
@@ -1102,9 +1109,44 @@ function validateLegacyRuntimeShape(shape: WorkplaneShape, label: string) {
if (cadBrep !== undefined && typeof cadBrep !== "string") throw new Error(`${label}.cadBrep is invalid`);
}
export async function importSkfProject(input: ArrayBuffer | Uint8Array, options: ImportSkfOptions = {}): Promise<SkfRestoredProject> {
function skfInputBytes(input: ArrayBuffer | Uint8Array) {
const bytes = input instanceof Uint8Array ? new Uint8Array(input) : new Uint8Array(input.slice(0));
if (!bytes.byteLength) throw new Error(".skf file is empty");
return bytes;
}
async function readPackagedSkf(bytes: Uint8Array) {
inspectZipBeforeExpansion(bytes);
let files: ArchiveFiles;
try {
files = await unzipAsync(bytes);
} catch (error) {
throw new Error(`Could not expand .skf package: ${error instanceof Error ? error.message : "corrupt ZIP data"}`);
}
let raw: unknown;
try {
raw = JSON.parse(strFromU8(files["project.json"]));
} catch {
throw new Error("project.json is malformed");
}
return { files, validated: await validateDocumentAndAssets(raw, files) };
}
export async function inspectSkfProjectPackage(input: ArrayBuffer | Uint8Array): Promise<SkfProjectPackageSummary> {
const bytes = skfInputBytes(input);
const prefix = strFromU8(bytes.subarray(0, Math.min(bytes.length, 64))).trimStart();
if (prefix.startsWith("{")) throw new Error("Shared storage accepts packaged .skf files, not legacy JSON projects");
const { validated } = await readPackagedSkf(bytes);
return {
projectName: validated.document.metadata.projectName,
createdAt: Date.parse(validated.document.metadata.createdAt),
modifiedAt: Date.parse(validated.document.metadata.modifiedAt),
formatVersion: validated.document.formatVersion,
};
}
export async function importSkfProject(input: ArrayBuffer | Uint8Array, options: ImportSkfOptions = {}): Promise<SkfRestoredProject> {
const bytes = skfInputBytes(input);
const prefix = strFromU8(bytes.subarray(0, Math.min(bytes.length, 64))).trimStart();
if (prefix.startsWith("{")) {
if (bytes.byteLength > SKF_LIMITS.projectJsonBytes) throw new Error("Legacy .skf JSON exceeds the supported size limit");
@@ -1123,19 +1165,6 @@ export async function importSkfProject(input: ArrayBuffer | Uint8Array, options:
throw new Error("This legacy .skf version is not supported");
}
inspectZipBeforeExpansion(bytes);
let files: ArchiveFiles;
try {
files = await unzipAsync(bytes);
} catch (error) {
throw new Error(`Could not expand .skf package: ${error instanceof Error ? error.message : "corrupt ZIP data"}`);
}
let raw: unknown;
try {
raw = JSON.parse(strFromU8(files["project.json"]));
} catch {
throw new Error("project.json is malformed");
}
const validated = await validateDocumentAndAssets(raw, files);
const { files, validated } = await readPackagedSkf(bytes);
return restoreV1(validated.document, validated.assetById, validated.stateById, files, options);
}
+17
View File
@@ -29,6 +29,23 @@ export function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size;
}
export function meshYawDegrees(shape: WorkplaneShape) {
const isRoundPrimitive = !shape.importedMesh && (shape.kind === "cylinder" || shape.kind === "cone");
const isCircular = Math.abs(shapeWidth(shape) - shapeDepth(shape)) < 0.0005;
if (!isRoundPrimitive || !isCircular) {
return shape.rotation;
}
// A tessellated circular primitive is only invariant by one whole side step.
// Preserve the remaining yaw so low-sided cylinders (for example a triangular
// prism) are baked and used in booleans at the same angle shown in the viewport.
const sides = Math.max(3, Math.round(shape.sides ?? 96));
const sideStep = 360 / sides;
const normalized = normalizeDegrees(shape.rotation);
const equivalentYaw = normalized - Math.round(normalized / sideStep) * sideStep;
return Math.abs(equivalentYaw) < 1e-9 ? 0 : equivalentYaw;
}
function edgeTreatmentPreserveZone(shape: WorkplaneShape): number {
const own = Math.max(...(shape.edgeTreatments ?? []).map((feature) => feature.amount), 0);
const child = Math.max(...(shape.groupedShapes ?? []).map(edgeTreatmentPreserveZone), 0);
+3 -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 } from "@/lib/cadModifierRuntime";
import { CAD_MODIFIER_RUNTIME_BASE, isCadModifierWasmMemoryFault } from "@/lib/cadModifierRuntime";
const HASH_UPPER_BOUND = 2_147_483_647;
const CAD_EDGE_WIREFRAME_DEFLECTION = 0.035;
@@ -381,10 +381,6 @@ function copyCadMesh(mesh: { positions: Float32Array; normals: Float32Array; ind
};
}
function isWasmMemoryFault(message: string) {
return /memory access out of bounds|WebAssembly\.RuntimeError|wasm|abort/i.test(message);
}
function isImportStlWasmFault(message: string) {
return /importStl:.*WebAssembly\.Exception/i.test(message);
}
@@ -492,7 +488,8 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
}
} catch (error) {
const rawMessage = error instanceof Error ? error.message : String(error ?? "");
if (isWasmMemoryFault(rawMessage) || isImportStlWasmFault(rawMessage) || isMissingValidatorFault(rawMessage)) {
const errorName = error instanceof Error ? error.name : "";
if (isCadModifierWasmMemoryFault(rawMessage, errorName) || isImportStlWasmFault(rawMessage) || isMissingValidatorFault(rawMessage)) {
if (cad) releaseSession(cad);
kernelPromise = null;
const message = isImportStlWasmFault(rawMessage)
+22 -10
View File
@@ -1,28 +1,40 @@
# syntax=docker/dockerfile:1
# The exported web app is architecture-independent. Build it once on the
# native GitHub runner instead of repeating npm/Next.js under arm64 QEMU.
FROM --platform=$BUILDPLATFORM node:22-alpine AS builder
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
ENV STATIC_EXPORT=true
ENV SKETCHFORGE_DOCKER_BUILD=true
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm run verify:static-worker-assets
RUN npm run build
FROM nginx:stable-alpine AS runner
FROM node:22-alpine AS runner
COPY deploy/docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/apps/web/.next-export /usr/share/nginx/html
WORKDIR /app
EXPOSE 80
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV HOSTNAME=0.0.0.0
ENV PORT=3000
ENV SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects
RUN mkdir -p /data/projects && chown node:node /data/projects
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
USER node
EXPOSE 3000
VOLUME ["/data/projects"]
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget -q -O - http://127.0.0.1/healthz | grep -q '^ok$' || exit 1
CMD wget -q -O - http://127.0.0.1:3000/api/shared-projects | grep -q '"enabled":true' || exit 1
CMD ["nginx", "-g", "daemon off;"]
CMD ["node", "apps/web/server.js"]
+8 -1
View File
@@ -2,5 +2,12 @@ services:
sketchforge:
image: ghcr.io/formsmith746/sketchforge-3d:latest
ports:
- "${SKETCHFORGE_PORT:-3000}:80"
- "${SKETCHFORGE_PORT:-3000}:3000"
environment:
SKETCHFORGE_SHARED_PROJECTS_DIR: /data/projects
volumes:
- "${SKETCHFORGE_SHARED_PROJECTS_VOLUME:-sketchforge-shared-projects}:/data/projects"
restart: unless-stopped
volumes:
sketchforge-shared-projects:
+8 -1
View File
@@ -5,5 +5,12 @@ services:
context: ../..
dockerfile: deploy/docker/Dockerfile
ports:
- "${SKETCHFORGE_PORT:-3000}:80"
- "${SKETCHFORGE_PORT:-3000}:3000"
environment:
SKETCHFORGE_SHARED_PROJECTS_DIR: /data/projects
volumes:
- "${SKETCHFORGE_SHARED_PROJECTS_VOLUME:-sketchforge-shared-projects}:/data/projects"
restart: unless-stopped
volumes:
sketchforge-shared-projects:
+1 -1
View File
@@ -19,7 +19,7 @@
"perf": "vitest run --config tests/vitest.perf.config.ts --reporter verbose",
"ci": "npm run typecheck && npm run test",
"docker:build": "docker build -f deploy/docker/Dockerfile -t sketchforge:local .",
"docker:run": "docker run --rm -p 3000:80 sketchforge:local",
"docker:run": "docker run --rm -p 3000:3000 -e SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects -v sketchforge-shared-projects:/data/projects sketchforge:local",
"docker:up": "docker compose -f deploy/docker/compose.yaml up --build -d",
"docker:down": "docker compose -f deploy/docker/compose.yaml down",
"mcp:sketchforge": "node scripts/sketchforge-mcp-server.mjs"
+8
View File
@@ -5,6 +5,7 @@ import {
CAD_MODIFIER_RUNTIME_BASE,
cadModifierTimeoutMessage,
edgeModifierSelectionStatus,
isCadModifierWasmMemoryFault,
} from "@/lib/cadModifierRuntime";
describe("CAD modifier runtime state", () => {
@@ -27,4 +28,11 @@ describe("CAD modifier runtime state", () => {
it("does not expose thresholds above the worker's folded edge-angle range", () => {
expect(CAD_MODIFIER_MAX_SHARP_ANGLE).toBe(90);
});
it("recognizes browser-specific WebAssembly memory fault messages", () => {
expect(isCadModifierWasmMemoryFault("toBREP: memory access out of bounds")).toBe(true);
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);
});
});
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import manifoldModule from "manifold-3d";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
describe("sketch profile validation", () => {
it("rejects a bow-tie profile whose non-adjacent edges cross", () => {
expect(findSketchOutlineIntersection([[
{ x: 0, y: 10 },
{ x: 37, y: 10 },
{ x: 3, y: 0 },
{ x: 34, y: 0 },
]])).toEqual({ outlineA: 0, edgeA: 1, outlineB: 0, edgeB: 3 });
});
it("accepts a normal simple profile", () => {
expect(findSketchOutlineIntersection([[
{ x: 0, y: 10 },
{ x: 37, y: 10 },
{ x: 34, y: 0 },
{ x: 3, y: 0 },
]])).toBeNull();
});
it("allows disjoint and nested profiles", () => {
expect(findSketchOutlineIntersection([
[{ x: 0, y: 0 }, { x: 20, y: 0 }, { x: 20, y: 20 }, { x: 0, y: 20 }],
[{ x: 5, y: 5 }, { x: 15, y: 5 }, { x: 15, y: 15 }, { x: 5, y: 15 }],
[{ x: 30, y: 0 }, { x: 40, y: 0 }, { x: 40, y: 10 }, { x: 30, y: 10 }],
])).toBeNull();
});
it("rejects closed profiles that cross or touch each other", () => {
expect(findSketchOutlineIntersection([
[{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }, { x: 0, y: 10 }],
[{ x: 5, y: -5 }, { x: 15, y: -5 }, { x: 15, y: 5 }, { x: 5, y: 5 }],
])).not.toBeNull();
});
it("resolves a bow-tie into valid even-odd regions that can be extruded", async () => {
const runtime = await manifoldModule();
runtime.setup();
const section = new runtime.CrossSection([[
[-18.5, -5],
[18.5, -5],
[-15.5, 5],
[15.5, 5],
]], "EvenOdd");
const solid = section.extrude(10);
try {
expect(section.toPolygons()).toHaveLength(2);
expect(solid.status()).toBe("NoError");
expect(solid.numTri()).toBeGreaterThan(0);
} finally {
solid.delete();
section.delete();
}
});
});
+8
View File
@@ -6,6 +6,7 @@ import { canonicalizeShape } from "@/lib/workplaneShapes";
import {
exportSkfProject,
importSkfProject,
inspectSkfProjectPackage,
SKF_FORMAT_VERSION,
SKF_SCHEMA_ID,
type SkfProjectDocumentV1,
@@ -96,6 +97,7 @@ describe("SketchForge .skf project packages", () => {
const exported = await exportSkfProject(input(shapes));
const { document } = packageDocument(exported);
const summary = await inspectSkfProjectPackage(exported);
const restored = await importSkfProject(exported);
expect(restored.projectName).toBe("Round trip");
@@ -104,6 +106,12 @@ describe("SketchForge .skf project packages", () => {
expect(restored.workspace).toEqual(DEFAULT_WORKPLANE_WORKSPACE);
expect(restored.snapGrid).toBe(DEFAULT_SNAP_GRID);
expect(restored.placementElevation).toBe(12.5);
expect(summary).toEqual({
projectName: "Round trip",
createdAt: 1_700_000_000_000,
modifiedAt: 1_700_000_100_000,
formatVersion: SKF_FORMAT_VERSION,
});
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
});
+12
View File
@@ -5,6 +5,7 @@ import {
cleanNearZero,
cleanRotationDegrees,
fallbackSolidColor,
meshYawDegrees,
mirroredAxisCount,
mirrorSign,
normalizeDegrees,
@@ -50,6 +51,17 @@ describe("workplane shape helpers", () => {
expect(cleanRotationDegrees(12.34)).toBe(12.3);
});
it("preserves the meaningful yaw of low-sided circular primitives", () => {
const triangularPrism = shape({ kind: "cylinder", width: 10, depth: 10, sides: 3 });
expect(meshYawDegrees({ ...triangularPrism, rotation: 30 })).toBeCloseTo(30);
expect(meshYawDegrees({ ...triangularPrism, rotation: 150 })).toBeCloseTo(30);
expect(meshYawDegrees({ ...triangularPrism, rotation: 90 })).toBeCloseTo(-30);
expect(meshYawDegrees({ ...triangularPrism, width: 12, rotation: 150 })).toBe(150);
expect(meshYawDegrees({ ...triangularPrism, kind: "box", rotation: 30 })).toBe(30);
expect(meshYawDegrees({ ...triangularPrism, sides: 96, rotation: 90 })).toBe(0);
});
it("cleans near-zero values and derives dimensions", () => {
const base = shape({ size: 30, width: 18, depth: 24 });
expect(cleanNearZero(0.004)).toBe(0);