Checkpoint SKF project format and export updates

This commit is contained in:
Formsmith
2026-07-16 12:30:39 +03:00
parent 400c4bf86e
commit 70e45bb966
22 changed files with 3028 additions and 133 deletions
+35 -11
View File
@@ -5,7 +5,8 @@ import { NextResponse } from "next/server";
export const revalidate = false;
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
const MAX_LOCAL_DOWNLOAD_BYTES = 25 * 1024 * 1024;
const MAX_TEXT_DOWNLOAD_BYTES = 25 * 1024 * 1024;
const MAX_BINARY_DOWNLOAD_BYTES = 512 * 1024 * 1024;
function safeFileName(filename: string) {
const base = path.basename(filename).replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_").trim();
@@ -40,28 +41,51 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "Local folder downloads are only available from this localhost app" }, { status: 403 });
}
const body = (await request.json()) as { content?: unknown; filename?: unknown; folder?: unknown };
if (typeof body.content !== "string" || typeof body.filename !== "string" || typeof body.folder !== "string") {
return NextResponse.json({ error: "Invalid download request" }, { status: 400 });
const contentType = request.headers.get("content-type") ?? "";
let filename: string;
let folder: string;
let content: string | Buffer;
if (contentType.toLowerCase().startsWith("multipart/form-data")) {
const formData = await request.formData();
const file = formData.get("file");
const requestedName = formData.get("filename");
const requestedFolder = formData.get("folder");
if (!(file instanceof Blob) || typeof requestedName !== "string" || typeof requestedFolder !== "string") {
return NextResponse.json({ error: "Invalid binary download request" }, { status: 400 });
}
if (file.size > MAX_BINARY_DOWNLOAD_BYTES) {
return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 });
}
filename = requestedName;
folder = requestedFolder;
content = Buffer.from(await file.arrayBuffer());
} else {
const body = (await request.json()) as { content?: unknown; filename?: unknown; folder?: unknown };
if (typeof body.content !== "string" || typeof body.filename !== "string" || typeof body.folder !== "string") {
return NextResponse.json({ error: "Invalid download request" }, { status: 400 });
}
if (Buffer.byteLength(body.content, "utf8") > MAX_TEXT_DOWNLOAD_BYTES) {
return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 });
}
filename = body.filename;
folder = body.folder;
content = body.content;
}
if (Buffer.byteLength(body.content, "utf8") > MAX_LOCAL_DOWNLOAD_BYTES) {
return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 });
}
const trimmedFolder = body.folder.trim();
const trimmedFolder = folder.trim();
if (!trimmedFolder) {
return NextResponse.json({ error: "Choose a folder first" }, { status: 400 });
}
const targetDirectory = path.resolve(path.isAbsolute(trimmedFolder) ? trimmedFolder : path.join(process.cwd(), trimmedFolder));
await fs.mkdir(targetDirectory, { recursive: true });
const targetPath = path.resolve(targetDirectory, safeFileName(body.filename));
const targetPath = path.resolve(targetDirectory, safeFileName(filename));
const relativeTarget = path.relative(targetDirectory, targetPath);
if (relativeTarget.startsWith("..") || path.isAbsolute(relativeTarget)) {
return NextResponse.json({ error: "Invalid file path" }, { status: 400 });
}
await fs.writeFile(targetPath, body.content, "utf8");
if (typeof content === "string") await fs.writeFile(targetPath, content, "utf8");
else await fs.writeFile(targetPath, content);
return NextResponse.json({ path: targetPath });
} catch (error) {
+499 -5
View File
@@ -1965,6 +1965,441 @@ button {
background: #eef8fc;
}
.top-action-heading {
display: grid;
gap: 2px;
}
.top-action-heading > span {
color: #6b7f91;
font-size: 11px;
font-weight: 700;
}
.top-action-panel.export-action-panel,
.top-action-panel.import-action-panel {
width: min(440px, calc(100vw - 28px));
overflow: hidden;
border-color: #d8e1e8;
border-radius: 12px;
box-shadow: 0 18px 55px rgba(19, 37, 55, 0.24);
}
.export-action-panel header,
.import-action-panel header {
height: 52px;
padding: 0 12px 0 15px;
background: #fff;
}
.import-action-panel .top-action-body {
padding: 14px;
background: #f7f9fb;
}
.export-dialog-body {
display: grid;
max-height: calc(100vh - var(--editor-toolbar-height) - 96px);
overflow-y: auto;
background: #f7f9fb;
}
.export-setting-section {
display: grid;
gap: 8px;
padding: 12px 14px;
background: #fff;
border-bottom: 1px solid #e5ebf0;
}
.export-file-section {
grid-template-columns: 72px minmax(0, 1fr);
align-items: center;
}
.export-file-section label,
.export-section-heading strong {
color: #20384d;
font-size: 13px;
font-weight: 800;
}
.export-file-input-wrap {
display: flex;
min-width: 0;
overflow: hidden;
background: #f7f9fb;
border: 1px solid #d9e2e9;
border-radius: 6px;
}
.export-file-input-wrap:focus-within {
background: #fff;
border-color: #10a8d0;
box-shadow: 0 0 0 2px rgba(16, 168, 208, 0.12);
}
.export-file-input {
min-width: 0;
flex: 1;
height: 32px;
padding: 0 2px 0 10px;
color: #263e52;
font: inherit;
font-size: 12px;
font-weight: 750;
background: transparent;
border: 0;
outline: 0;
}
.export-file-input-wrap > span {
display: inline-flex;
flex: none;
align-items: center;
padding: 0 9px 0 4px;
color: #6d8090;
font-size: 11px;
font-weight: 800;
text-transform: lowercase;
}
.export-section-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
}
.export-section-heading > div {
display: grid;
gap: 3px;
}
.export-section-heading > div > span {
color: #718494;
font-size: 11px;
font-weight: 650;
}
.export-scope-badge {
flex: none;
padding: 4px 8px;
color: #137897;
font-size: 10px;
font-weight: 850;
text-transform: uppercase;
background: #eaf9fd;
border: 1px solid #c5edf7;
border-radius: 999px;
}
.export-format-slider {
position: relative;
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
height: 38px;
padding: 3px;
overflow: hidden;
background: #edf2f5;
border: 1px solid #dbe4eb;
border-radius: 8px;
}
.export-format-slider::before {
position: absolute;
top: 3px;
bottom: 3px;
left: 3px;
width: calc((100% - 6px) / 5);
content: "";
background: #fff;
border: 1px solid #a9dce9;
border-radius: 6px;
box-shadow: 0 2px 7px rgba(27, 65, 89, 0.12);
transition: transform 180ms ease;
}
.export-format-slider[data-format="obj"]::before {
transform: translateX(100%);
}
.export-format-slider[data-format="step"]::before {
transform: translateX(200%);
}
.export-format-slider[data-format="svg"]::before {
transform: translateX(300%);
}
.export-format-slider[data-format="skf"]::before {
transform: translateX(400%);
}
.export-format-slider button {
position: relative;
z-index: 1;
min-width: 0;
padding: 0 5px;
color: #6f8291;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.02em;
background: transparent;
border: 0;
border-radius: 6px;
cursor: pointer;
transition: color 160ms ease;
}
.export-format-slider button:hover {
color: #22546a;
}
.export-format-slider button[aria-checked="true"] {
color: #087f9f;
}
.skf-history-section {
gap: 9px;
}
.skf-history-range-control {
position: relative;
height: 26px;
}
.skf-history-range-control::before,
.skf-history-range-control::after {
position: absolute;
top: 10px;
left: 9px;
height: 6px;
content: "";
border-radius: 999px;
}
.skf-history-range-control::before {
right: 9px;
background: #dbe5eb;
box-shadow: inset 0 1px 2px rgba(40, 65, 82, 0.12);
}
.skf-history-range-control::after {
width: 0;
background: linear-gradient(90deg, #22b9dc, #079bc2);
transition: width 140ms ease;
}
.skf-history-range-control[data-limit="100"]::after {
width: calc(33.333333% - 6px);
}
.skf-history-range-control[data-limit="50"]::after {
width: calc(66.666667% - 12px);
}
.skf-history-range-control[data-limit="30"]::after {
width: calc(100% - 18px);
}
.skf-history-range {
position: absolute;
inset: 0;
z-index: 1;
width: 100%;
height: 26px;
margin: 0;
appearance: none;
background: transparent;
border: 0;
cursor: grab;
}
.skf-history-range:active {
cursor: grabbing;
}
.skf-history-range:focus {
outline: 0;
}
.skf-history-range::-webkit-slider-runnable-track {
height: 6px;
background: transparent;
}
.skf-history-range::-webkit-slider-thumb {
width: 18px;
height: 18px;
margin-top: -6px;
appearance: none;
background: #fff;
border: 2px solid #0ba4ca;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(22, 82, 108, 0.25);
}
.skf-history-range::-moz-range-track {
height: 6px;
background: transparent;
}
.skf-history-range::-moz-range-thumb {
width: 14px;
height: 14px;
background: #fff;
border: 2px solid #0ba4ca;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(22, 82, 108, 0.25);
}
.skf-history-range:focus-visible::-webkit-slider-thumb {
box-shadow: 0 0 0 4px rgba(11, 164, 202, 0.17), 0 2px 6px rgba(22, 82, 108, 0.25);
}
.skf-history-range:focus-visible::-moz-range-thumb {
box-shadow: 0 0 0 4px rgba(11, 164, 202, 0.17), 0 2px 6px rgba(22, 82, 108, 0.25);
}
.skf-history-range-labels {
position: relative;
height: 14px;
margin-top: -3px;
}
.skf-history-range-labels span {
position: absolute;
top: 0;
color: #718494;
font-size: 10px;
font-weight: 750;
transform: translateX(-50%);
transition: color 140ms ease;
}
.skf-history-range-labels span:first-child {
left: 0;
transform: none;
}
.skf-history-range-labels span:nth-child(2) {
left: calc(33.333333% + 3px);
}
.skf-history-range-labels span:nth-child(3) {
left: calc(66.666667% - 3px);
}
.skf-history-range-labels span:last-child {
right: 0;
transform: none;
}
.skf-history-range-labels span.active {
color: #087f9f;
font-weight: 850;
}
.export-format-summary {
display: grid;
gap: 5px;
margin: 10px 14px;
padding: 9px 11px;
background: #eef4f7;
border: 1px solid #dde7ed;
border-radius: 7px;
}
.export-format-summary > div {
display: flex;
align-items: baseline;
gap: 8px;
}
.export-format-summary strong {
color: #1f3c52;
font-size: 12px;
font-weight: 850;
}
.export-format-summary span,
.export-format-summary p {
margin: 0;
color: #627789;
font-size: 11px;
font-weight: 700;
line-height: 1.4;
}
.export-dialog-footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
padding: 10px 14px 12px;
background: #fff;
border-top: 1px solid #e2e9ee;
}
.export-dialog-footer > div {
display: flex;
justify-content: flex-end;
gap: 9px;
}
.export-dialog-footer button {
display: inline-flex;
min-width: 78px;
min-height: 34px;
align-items: center;
justify-content: center;
gap: 7px;
padding: 0 13px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
font-weight: 850;
}
.export-dialog-footer .export-primary-button {
min-width: 118px;
color: #fff;
background: linear-gradient(180deg, #14b4dc, #0799c1);
border: 1px solid #078daf;
box-shadow: 0 5px 14px rgba(4, 145, 183, 0.22);
}
.export-dialog-footer .export-primary-button:hover:not(:disabled) {
background: linear-gradient(180deg, #0eadd4, #058db2);
}
.export-dialog-footer .export-primary-button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.export-primary-button svg {
width: 16px;
height: 16px;
}
@media (max-width: 560px) {
.top-action-panel.export-action-panel,
.top-action-panel.import-action-panel {
right: 10px;
width: calc(100vw - 20px);
}
.export-file-section {
grid-template-columns: 1fr;
}
.export-dialog-footer {
align-items: flex-end;
}
}
.top-action-body {
display: grid;
gap: 10px;
@@ -1999,6 +2434,65 @@ button {
background: #eef8fc;
}
.top-action-body .open-skf-project-button {
display: grid;
grid-template-columns: 38px minmax(0, 1fr);
min-height: 66px;
justify-content: stretch;
padding: 10px 12px;
color: #173b5a;
background: #fff;
border-color: #cfe2eb;
border-radius: 8px;
text-align: left;
}
.open-skf-project-button > span:last-child {
display: grid;
gap: 3px;
}
.open-skf-project-button strong,
.open-skf-project-button small {
display: block;
}
.open-skf-project-button small {
color: #667d8e;
font-size: 11px;
font-weight: 700;
line-height: 1.35;
}
.open-skf-project-icon {
display: grid;
width: 34px;
height: 34px;
place-items: center;
color: #087f9f;
background: #eaf9fd;
border: 1px solid #c5edf7;
border-radius: 8px;
}
.import-kind-divider {
display: flex;
align-items: center;
gap: 9px;
color: #7a8c9a;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
}
.import-kind-divider::before,
.import-kind-divider::after {
height: 1px;
flex: 1;
content: "";
background: #dfe7ed;
}
.top-action-body button svg,
.top-action-body button .vector-toolbar-sprite-icon,
.top-action-body button .toolbar-command-icon {
@@ -2013,16 +2507,16 @@ button {
align-content: center;
justify-items: center;
gap: 8px;
padding: 17px 14px;
padding: 20px 14px;
color: #244057;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.86), rgba(244, 248, 251, 0.96));
border: 1.5px dashed rgba(93, 124, 150, 0.62);
border-radius: 5px;
background: #fff;
border: 1.5px dashed #b8cbd8;
border-radius: 8px;
text-align: center;
}
.top-action-body .import-drop-zone:hover {
background: #fff;
background: #fafeff;
border-color: rgba(0, 159, 227, 0.76);
box-shadow: inset 0 0 0 1px rgba(0, 159, 227, 0.12), 0 4px 14px rgba(30, 50, 70, 0.1);
}
+132 -25
View File
@@ -5,9 +5,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
import { createLocalId } from "@/lib/localIds";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { importSkfProject } from "@/lib/skfProject";
import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
type AppView = "dashboard" | "editor";
type ViewMode = "grid" | "list";
@@ -26,6 +28,7 @@ type DashboardProject = {
revision?: number;
workspace?: WorkplaneWorkspaceSettings;
snapGrid?: GridSize;
placementElevation?: number;
};
type StoredDashboardProject = Partial<DashboardProject> & {
@@ -37,6 +40,7 @@ type ProjectShapeCacheEntry = {
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
historyIndex: number;
assets: ProjectAsset[];
};
type ProjectShapeRecord = {
@@ -45,6 +49,7 @@ type ProjectShapeRecord = {
shapes: WorkplaneShape[];
history?: EditorHistoryEntry[];
historyIndex?: number;
assets?: ProjectAsset[];
updatedAt: number;
};
@@ -69,6 +74,7 @@ function projectShapeCacheEntry(
shapes: WorkplaneShape[],
history?: EditorHistoryEntry[],
historyIndex?: number,
assets: ProjectAsset[] = [],
): ProjectShapeCacheEntry {
const hydrated = hydrateEditorHistoryState(shapes, history, historyIndex);
return {
@@ -76,6 +82,7 @@ function projectShapeCacheEntry(
shapes: hydrated.entries[hydrated.index]?.shapes ?? shapes,
history: hydrated.entries,
historyIndex: hydrated.index,
assets: dedupeProjectAssets(assets),
};
}
@@ -187,6 +194,7 @@ function readStoredProjects() {
revision,
workspace: normalizeWorkspaceSettings(project.workspace),
snapGrid: normalizeSnapGrid(project.snapGrid),
placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0,
};
});
return { projects, legacyShapes };
@@ -217,6 +225,7 @@ function mergeProjectForStorage(project: DashboardProject, storedProject?: Dashb
updatedAt: Math.max(project.updatedAt, storedProject.updatedAt),
workspace: project.workspace ?? storedProject.workspace,
snapGrid: project.snapGrid ?? storedProject.snapGrid,
placementElevation: project.placementElevation ?? storedProject.placementElevation,
};
}
@@ -233,6 +242,7 @@ function projectForStorage(project: DashboardProject): DashboardProject {
revision: project.revision,
workspace: normalizeWorkspaceSettings(project.workspace),
snapGrid: normalizeSnapGrid(project.snapGrid),
placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0,
};
}
@@ -254,6 +264,7 @@ function newProject(name: string, index: number, shapeCount = 0): DashboardProje
revision: now,
workspace: DEFAULT_WORKPLANE_WORKSPACE,
snapGrid: DEFAULT_SNAP_GRID,
placementElevation: 0,
};
}
@@ -370,7 +381,7 @@ export default function Home() {
.then((record) => {
if (canceled) return;
const revision = activeProject.revision ?? record?.revision ?? Date.now();
const entry = projectShapeCacheEntry(revision, record?.shapes ?? [], record?.history, record?.historyIndex);
const entry = projectShapeCacheEntry(revision, record?.shapes ?? [], record?.history, record?.historyIndex, record?.assets);
setProjectShapesById((current) => ({
...current,
[activeProjectId]: entry,
@@ -471,10 +482,11 @@ export default function Home() {
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
historyIndex: number;
assets: ProjectAsset[];
}) => {
const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1);
nextProjectRevisionRef.current = revision;
const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex);
const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex, snapshot.assets);
setProjectShapesById((current) => {
const existing = current[snapshot.projectId];
if (existing && existing.revision > revision) {
@@ -512,25 +524,29 @@ export default function Home() {
});
}, []);
const updateProjectWorkspace = useCallback((snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => {
const updateProjectWorkspace = useCallback((snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => {
const version = Date.now();
const workspace = normalizeWorkspaceSettings(snapshot.workspace);
const snapGrid = normalizeSnapGrid(snapshot.snap);
const nextFingerprint = workplaneSettingsFingerprint(workspace, snapGrid);
const placementElevation = typeof snapshot.placementElevation === "number" && Number.isFinite(snapshot.placementElevation)
? snapshot.placementElevation
: 0;
const nextFingerprint = `${workplaneSettingsFingerprint(workspace, snapGrid)}:${placementElevation}`;
setProjects((current) => {
let changed = false;
const next = current.map((project) => {
if (project.id !== snapshot.projectId) return project;
const currentFingerprint = workplaneSettingsFingerprint(
const currentFingerprint = `${workplaneSettingsFingerprint(
normalizeWorkspaceSettings(project.workspace),
normalizeSnapGrid(project.snapGrid),
);
)}:${project.placementElevation ?? 0}`;
if (currentFingerprint === nextFingerprint) return project;
changed = true;
return {
...project,
workspace,
snapGrid,
placementElevation,
updatedAt: version,
};
});
@@ -551,34 +567,119 @@ export default function Home() {
openEditor(project.id, { allowMissingFromStorage: true });
};
const importFileFromDashboard = useCallback(
async (file: File) => {
const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml";
if (!isSvg && !importExtensionSupported(file.name)) {
setDashboardNotice("Unsupported file type. Use STL or SVG.");
const openSkfProjectFromFile = useCallback(async (file: File) => {
setDashboardNotice(`Validating ${file.name} before opening it as a new project`);
try {
const restored = await importSkfProject(await file.arrayBuffer());
const now = Date.now();
const project: DashboardProject = {
...newProject(restored.projectName, projects.length, restored.shapes.length),
createdAt: restored.createdAt,
updatedAt: now,
revision: now,
workspace: restored.workspace,
snapGrid: restored.snapGrid,
placementElevation: restored.placementElevation,
};
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`);
openEditor(project.id, { allowMissingFromStorage: true });
return { ok: true, message: `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);
return { ok: false, message };
}
}, [projects.length]);
const importFilesFromDashboard = useCallback(
async (files: File[]) => {
if (!files.length) return;
const projectFiles = files.filter((file) => /\.skf$/i.test(file.name));
if (projectFiles.length) {
if (files.length !== 1) {
setDashboardNotice("Open one .skf project at a time; import STL, STEP, and SVG geometry separately");
return;
}
await openSkfProjectFromFile(projectFiles[0]);
return;
}
const importedShapes: WorkplaneShape[] = [];
const importedAssets: ProjectAsset[] = [];
const importedFileNames: string[] = [];
const failures: Array<{ fileName: string; reason: string }> = [];
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null);
const isSvg = sourceFormat === "svg";
const isStep = sourceFormat === "step";
if (!sourceFormat || sourceFormat === "obj" || (!isSvg && !isStep && !importExtensionSupported(file.name))) {
failures.push({ fileName: file.name, reason: "Unsupported file type" });
continue;
}
setDashboardNotice(`Importing ${index + 1} of ${files.length}: ${file.name}`);
try {
const bytes = new Uint8Array(await file.arrayBuffer());
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
const parsedShape = isStep
? await import("@/lib/stepImport").then(({ importedShapeFromStep }) => importedShapeFromStep(file.name, buffer))
: isSvg
? importedShapeFromSvg(file.name, new TextDecoder().decode(bytes))
: importedShapeFromStl(file.name, buffer);
const asset = await projectAssetFromBytes(file.name, sourceFormat, bytes, file.type);
importedShapes.push(attachProjectAsset(parsedShape, asset.id));
importedAssets.push(asset);
importedFileNames.push(file.name);
} catch (error) {
failures.push({
fileName: file.name,
reason: error instanceof Error ? error.message : "Could not read file",
});
}
}
const failureDetails = failures
.slice(0, 3)
.map((failure) => `${failure.fileName}: ${failure.reason}`)
.join("; ");
const remainingFailureCount = Math.max(0, failures.length - 3);
const failureSummary = failures.length
? ` Failed: ${failureDetails}${remainingFailureCount ? `; plus ${remainingFailureCount} more` : ""}`
: "";
if (!importedShapes.length) {
setDashboardNotice(files.length === 1 && failures[0] ? failures[0].reason : `Could not import any of the ${files.length} selected files.${failureSummary}`);
return;
}
try {
const shape = isSvg
? importedShapeFromSvg(file.name, await file.text())
: importedShapeFromStl(file.name, await file.arrayBuffer());
const project = newProject(projectNameFromFileName(file.name), projects.length, 1);
const projectName = importedShapes.length === 1
? projectNameFromFileName(importedFileNames[0])
: `Imported design (${importedShapes.length} files)`;
const project = newProject(projectName, projects.length, importedShapes.length);
const revision = project.revision ?? project.updatedAt;
const entry = projectShapeCacheEntry(revision, [shape]);
const entry = projectShapeCacheEntry(revision, importedShapes, undefined, undefined, dedupeProjectAssets(importedAssets));
await saveProjectShapes(project.id, entry);
setProjectShapesById((current) => ({
...current,
[project.id]: entry,
}));
setDashboardNotice(`Imported ${file.name}`);
const successSummary = importedShapes.length === 1 && files.length === 1
? `Imported ${files[0].name}`
: `Imported ${importedShapes.length} of ${files.length} files`;
setDashboardNotice(`${successSummary}.${failureSummary}`.trim());
setProjects((current) => [project, ...current]);
openEditor(project.id, { allowMissingFromStorage: true });
} catch (error) {
setDashboardNotice(error instanceof Error ? error.message : `Could not import ${file.name}`);
setDashboardNotice(error instanceof Error ? error.message : "Could not create a project for the imported files");
}
},
[projects.length],
[openSkfProjectFromFile, projects.length],
);
const openLatestProject = () => {
@@ -653,11 +754,12 @@ export default function Home() {
ref={dashboardImportInputRef}
className="hidden-file-input"
type="file"
accept=".stl,.svg,image/svg+xml"
multiple
accept=".skf,.stl,.step,.stp,.svg,image/svg+xml"
onChange={(event) => {
const file = event.currentTarget.files?.[0];
if (file) {
void importFileFromDashboard(file);
const files = event.currentTarget.files ? Array.from(event.currentTarget.files) : [];
if (files.length) {
void importFilesFromDashboard(files);
}
event.currentTarget.value = "";
}}
@@ -697,17 +799,22 @@ export default function Home() {
{editorStarted && canRenderEditor ? (
<div className={view === "editor" ? "editor-stage active" : "editor-stage"} aria-hidden={view !== "editor"}>
<SketchForgeEditor
initialAssets={activeProjectShapeEntry?.assets ?? []}
initialShapes={activeProjectShapeEntry?.shapes ?? []}
initialHistory={activeProjectShapeEntry?.history}
initialHistoryIndex={activeProjectShapeEntry?.historyIndex}
initialSnap={activeProject?.snapGrid ?? DEFAULT_SNAP_GRID}
initialWorkspace={activeProject?.workspace ?? DEFAULT_WORKPLANE_WORKSPACE}
initialPlacementElevation={activeProject?.placementElevation ?? 0}
onHome={openDashboard}
onOpenSkfProjectFile={openSkfProjectFromFile}
onProjectShapesChange={updateProjectShapes}
onProjectSnapshot={updateProjectSnapshot}
onProjectWorkspaceChange={updateProjectWorkspace}
projectId={activeProjectId}
projectName={activeProject?.name}
projectCreatedAt={activeProject?.createdAt}
projectModifiedAt={activeProject?.updatedAt}
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
/>
</div>
@@ -858,7 +965,7 @@ function Dashboard({
<span className="dashboard-action-icon">
<FileUp size={24} strokeWidth={2.4} />
</span>
<span>Import STL/SVG</span>
<span>Open SKF or import geometry</span>
</button>
<button className="dashboard-action-tile" type="button" onClick={onWorkspace}>
<span className="dashboard-action-icon">
+434 -72
View File
@@ -1,6 +1,6 @@
"use client";
import { Check, Download, X } from "lucide-react";
import { Check, 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";
@@ -73,14 +73,17 @@ import {
type CadModifierRequestPhase,
} from "@/lib/cadModifierRuntime";
import { cloneWorkplaneShapeSnapshot, compactEdgeTreatmentHistory, edgeTreatmentAppliedFrame, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory";
import { appendEditorHistorySnapshot, editorHistoryEntry, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryState } from "@/lib/editorHistory";
import { appendEditorHistorySnapshot, 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";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
import { normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
import { normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import {
SKETCHFORGE_MCP_POLL_MS,
SKETCHFORGE_MCP_ROUTE,
@@ -90,12 +93,14 @@ import {
type SketchForgeMcpViewFace,
} from "@/lib/sketchforgeMcpProtocol";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export { importedShapeFromStl, importedShapeFromSvg };
type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null;
type ExportFormat = "stl" | "obj";
type ExportFormat = "stl" | "obj" | "step" | "svg" | "skf";
type DirectExportFormat = Exclude<ExportFormat, "step" | "skf">;
type SkfHistoryLimit = EditorHistoryExportLimit;
type ToolbarMode = "geometry" | "sketch";
type Vec3 = [number, number, number];
type MeshData = { name: string; vertices: Vec3[]; faces: [number, number, number][] };
@@ -1519,6 +1524,7 @@ async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[]
locked: shape.locked,
hidden: shape.hidden,
edgeResizeMode: shape.edgeResizeMode,
groupOperation: shape.groupOperation,
edgeTreatments: shape.edgeTreatments,
edgeTreatmentHistory: shape.edgeTreatmentHistory?.length ? compactEdgeTreatmentHistory(shape.edgeTreatmentHistory) : undefined,
}),
@@ -2280,6 +2286,36 @@ function toObj(meshes: MeshData[]) {
return lines.join("\n");
}
async function toSvg(shapes: WorkplaneShape[], title: string) {
const runtime = await getManifoldRuntime();
const layers: SvgProjectionLayer[] = [];
for (const shape of shapes) {
const created: ManifoldSolid[] = [];
const projectedObjects: unknown[] = [];
try {
const solid = shapeToManifoldSolid(runtime, shape, created);
if (!solid || solid.status() !== "NoError" || solid.numTri() < 1) {
throw new Error(`Could not convert ${shape.name} into a watertight SVG outline`);
}
const topView = solid.rotate([90, 0, 0]);
if (topView !== solid) created.push(topView);
const projection = topView.project();
projectedObjects.push(projection);
const simplified = projection.simplify(0.00001);
if (simplified !== projection) projectedObjects.push(simplified);
const polygons = simplified.toPolygons();
if (!polygons.length) throw new Error(`Top view of ${shape.name} has no exportable area`);
layers.push({ name: shape.name, color: shape.color, polygons });
} finally {
[...new Set([...projectedObjects, ...created])].reverse().forEach(disposeManifold);
}
}
return toSvgProjection(layers, title);
}
function triggerBrowserDownload(filename: string, content: string, type: string) {
const blob = new Blob([content], { type });
const url = URL.createObjectURL(blob);
@@ -2313,6 +2349,31 @@ async function downloadTextFile(filename: string, content: string, type: string)
return { mode: "browser" };
}
async function downloadBlobFile(filename: string, blob: Blob): Promise<DownloadResult> {
const mode = window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY);
const folder = window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY)?.trim() ?? "";
if (!STATIC_EXPORT_BUILD && mode === "folder" && folder) {
const formData = new FormData();
formData.set("file", blob, filename);
formData.set("filename", filename);
formData.set("folder", folder);
const response = await fetch("/api/local-download", { method: "POST", body: formData });
const payload = (await response.json().catch(() => null)) as { error?: string; path?: string } | null;
if (!response.ok || !payload?.path) throw new Error(payload?.error ?? "Could not save export");
return { mode: "folder", path: payload.path };
}
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
link.style.display = "none";
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
return { mode: "browser" };
}
function shapeAabb(shape: WorkplaneShape): Cuboid {
const halfWidth = shapeWidth(shape) / 2;
const halfDepth = shapeDepth(shape) / 2;
@@ -4978,35 +5039,46 @@ function readMcpEditorIdentity() {
}
export function SketchForgeEditor({
initialAssets = [],
initialShapes = [],
initialHistory,
initialHistoryIndex,
initialSnap,
initialWorkspace,
initialPlacementElevation = 0,
onHome,
onOpenSkfProjectFile,
onProjectShapesChange,
onProjectSnapshot,
onProjectWorkspaceChange,
projectId,
projectName = "SketchForge design",
projectCreatedAt = Date.now(),
projectModifiedAt = Date.now(),
projectRevision = 0,
}: {
initialAssets?: ProjectAsset[];
initialShapes?: WorkplaneShape[];
initialHistory?: EditorHistoryEntry[];
initialHistoryIndex?: number;
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
initialPlacementElevation?: number;
onHome?: () => void;
onOpenSkfProjectFile?: (file: File) => Promise<{ ok: boolean; message: string } | void> | { ok: boolean; message: string } | void;
onProjectShapesChange?: (snapshot: {
projectId: string;
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
historyIndex: number;
assets: ProjectAsset[];
}) => void;
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void;
onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void;
onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => void;
projectId?: string | null;
projectName?: string;
projectCreatedAt?: number;
projectModifiedAt?: number;
projectRevision?: number;
} = {}) {
const initialSceneRef = useRef<WorkplaneShape[] | null>(null);
@@ -5018,17 +5090,20 @@ export function SketchForgeEditor({
initialHistoryStateRef.current = hydrateEditorHistoryState(initialSceneRef.current, initialHistory, initialHistoryIndex);
}
const [shapes, setShapes] = useState<WorkplaneShape[]>(() => initialSceneRef.current as WorkplaneShape[]);
const [projectAssets, setProjectAssets] = useState<ProjectAsset[]>(() => dedupeProjectAssets(initialAssets));
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [clipboard, setClipboard] = useState<WorkplaneShape[]>([]);
const [systemClipboardSupported, setSystemClipboardSupported] = useState(false);
const [history, setHistory] = useState<EditorHistoryEntry[]>(() => (initialHistoryStateRef.current as EditorHistoryState).entries);
const [historyIndex, setHistoryIndex] = useState(() => (initialHistoryStateRef.current as EditorHistoryState).index);
const [placementElevation, setPlacementElevation] = useState(0);
const [placementElevation, setPlacementElevation] = useState(() => Number.isFinite(initialPlacementElevation) ? initialPlacementElevation : 0);
const [workspaceSettings, setWorkspaceSettings] = useState<WorkplaneWorkspaceSettings>(() => normalizeWorkspaceSettings(initialWorkspace));
const [snapGrid, setSnapGrid] = useState<GridSize>(() => normalizeSnapGrid(initialSnap));
const [workplaneMode, setWorkplaneMode] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
const [topPanel, setTopPanel] = useState<TopPanel>(null);
const [stepExporting, setStepExporting] = useState(false);
const [skfExporting, setSkfExporting] = useState(false);
const [alignMode, setAlignMode] = useState(false);
const [alignAnchorId, setAlignAnchorId] = useState<string | null>(null);
const [alignPreview, setAlignPreview] = useState<{ axis: AlignAxis; target: AlignTarget } | null>(null);
@@ -5037,6 +5112,7 @@ export function SketchForgeEditor({
const [activeMode, setActiveMode] = useState("3D Design");
const [notice, setNotice] = useState("Ready");
const fileInputRef = useRef<HTMLInputElement | null>(null);
const projectFileInputRef = useRef<HTMLInputElement | null>(null);
const sketchImageInputRef = useRef<HTMLInputElement | null>(null);
const booleanAutomationRunRef = useRef<string | null>(null);
const projectHydratingRef = useRef(false);
@@ -5048,6 +5124,7 @@ export function SketchForgeEditor({
const lastProjectIdRef = useRef<string | null>(null);
const projectSnapshotRunRef = useRef(0);
const shapesRef = useRef(shapes);
const projectAssetsRef = useRef(projectAssets);
const selectedIdsRef = useRef(selectedIds);
const workspaceSettingsRef = useRef(workspaceSettings);
const noticeRef = useRef(notice);
@@ -5315,6 +5392,10 @@ export function SketchForgeEditor({
shapesRef.current = shapes;
}, [shapes]);
useEffect(() => {
projectAssetsRef.current = projectAssets;
}, [projectAssets]);
useEffect(() => {
selectedIdsRef.current = selectedIds;
const currentHistory = historyRef.current;
@@ -5363,6 +5444,10 @@ export function SketchForgeEditor({
setWorkspaceSettings(normalizeWorkspaceSettings(initialWorkspace));
}, [initialWorkspace]);
useEffect(() => {
setSnapGrid(normalizeSnapGrid(initialSnap));
}, [initialSnap]);
const selectedShapes = useMemo(() => shapes.filter((shape) => selectedIds.includes(shape.id)), [selectedIds, shapes]);
const selectedShape = selectedShapes.at(-1) ?? null;
const hasSelection = selectedShapes.length > 0;
@@ -5501,6 +5586,7 @@ export function SketchForgeEditor({
shapes: canonicalNext,
history: historyRef.current,
historyIndex: historyIndexRef.current,
assets: projectAssetsRef.current,
});
projectSyncTimerRef.current = null;
}, 120);
@@ -5581,14 +5667,25 @@ export function SketchForgeEditor({
const updateProjectWorkspaceSettings = useCallback(
(settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => {
setWorkspaceSettings(settings.workspace);
setSnapGrid(settings.snap);
if (!projectId || !onProjectWorkspaceChange) {
return;
}
onProjectWorkspaceChange({ projectId, ...settings });
onProjectWorkspaceChange({ projectId, ...settings, placementElevation });
},
[onProjectWorkspaceChange, projectId],
[onProjectWorkspaceChange, placementElevation, projectId],
);
useEffect(() => {
if (!projectId || !onProjectWorkspaceChange) return;
onProjectWorkspaceChange({
projectId,
workspace: workspaceSettingsRef.current,
snap: snapGrid,
placementElevation,
});
}, [onProjectWorkspaceChange, placementElevation, projectId, snapGrid]);
const commitShapes = useCallback(
(next: WorkplaneShape[], nextSelection: string | string[] | null = selectedIds, message?: string) => {
const canonicalNext = next.map(canonicalizeShape);
@@ -6066,6 +6163,10 @@ export function SketchForgeEditor({
lastProjectIdRef.current = projectId;
lastProjectShapesSyncRef.current = "";
lastProjectShapesEchoRef.current = null;
const nextAssets = dedupeProjectAssets(initialAssets);
projectAssetsRef.current = nextAssets;
setProjectAssets(nextAssets);
setPlacementElevation(Number.isFinite(initialPlacementElevation) ? initialPlacementElevation : 0);
}
const incoming = initialShapes.map(canonicalizeShape);
const incomingSerialized = projectShapesFingerprint(incoming);
@@ -6093,7 +6194,7 @@ export function SketchForgeEditor({
setHistory(hydratedHistory.entries);
setHistoryIndex(hydratedHistory.index);
setNotice(incoming.length ? "Project synced" : "Ready");
}, [initialHistory, initialHistoryIndex, initialShapes, projectId, projectInteractionActive, projectRevision]);
}, [initialAssets, initialHistory, initialHistoryIndex, initialPlacementElevation, initialShapes, projectId, projectInteractionActive, projectRevision]);
useEffect(() => {
if (!projectId || !onProjectShapesChange) {
@@ -6926,7 +7027,8 @@ export function SketchForgeEditor({
return;
}
const selected = new Set(selectedIds);
commitShapes([...shapesRef.current.filter((shape) => !selected.has(shape.id)), group], group.id, `Grouped ${selectedShapes.length} shapes`);
const editableGroup = canonicalizeShape({ ...group, groupOperation: "group" });
commitShapes([...shapesRef.current.filter((shape) => !selected.has(shape.id)), editableGroup], editableGroup.id, `Grouped ${selectedShapes.length} shapes`);
}, [commitShapes, selectedIds, selectedShapes]);
const intersectSelected = useCallback(async () => {
@@ -6957,7 +7059,7 @@ export function SketchForgeEditor({
return;
}
const intersection = result.group;
const intersection = result.group ? canonicalizeShape({ ...result.group, groupOperation: "intersection" }) : null;
if (!intersection) {
return;
}
@@ -7234,8 +7336,9 @@ export function SketchForgeEditor({
}
throw new Error(result.failureNotice);
}
commitShapes([...currentShapes().filter((shape) => !ids.has(shape.id)), result.group], result.group.id, `MCP grouped ${groupable.length} objects`);
return { object: mcpShapeSummary(result.group) };
const editableGroup = canonicalizeShape({ ...result.group, groupOperation: "group" });
commitShapes([...currentShapes().filter((shape) => !ids.has(shape.id)), editableGroup], editableGroup.id, `MCP grouped ${groupable.length} objects`);
return { object: mcpShapeSummary(editableGroup) };
}
if (command.action === "ungroup_objects") {
@@ -7276,8 +7379,9 @@ export function SketchForgeEditor({
if (!result.group) {
throw new Error(result.failureNotice);
}
commitShapes([...remainingShapes, result.group], result.group.id, "MCP boolean cut complete");
return { object: mcpShapeSummary(result.group) };
const editableGroup = canonicalizeShape({ ...result.group, groupOperation: "group" });
commitShapes([...remainingShapes, editableGroup], editableGroup.id, "MCP boolean cut complete");
return { object: mcpShapeSummary(editableGroup) };
}
if (command.action === "separate_parts") {
@@ -7586,7 +7690,7 @@ export function SketchForgeEditor({
void run();
}, [commitShapes]);
const exportDesign = useCallback((format: ExportFormat) => {
const exportDesign = useCallback((format: DirectExportFormat, exportName: string) => {
const sourceShapes = hasSelection ? selectedShapes : shapes;
const exportable = sourceShapes.filter((shape) => !shape.hole);
if (exportable.length === 0) {
@@ -7598,7 +7702,6 @@ export function SketchForgeEditor({
setNotice(`${invalidSvg}. Re-import the source SVG after fixing its contours`);
return;
}
const meshes = exportable.map(meshForShape);
const selectedNotice = `Exported ${exportable.length} selected shape${exportable.length === 1 ? "" : "s"}`;
const finishNotice = (label: string, result: DownloadResult) => {
if (result.mode === "folder") {
@@ -7610,18 +7713,27 @@ export function SketchForgeEditor({
const failNotice = (label: string, error: unknown) => {
setNotice(error instanceof Error ? error.message : `Could not export ${label}`);
};
if (format === "svg") {
setNotice("Building SVG top-view projection…");
void toSvg(exportable, exportName.trim() || projectName)
.then((content) => downloadTextFile(projectExportFileName(exportName, "svg"), content, "image/svg+xml;charset=utf-8"))
.then((result) => finishNotice("SVG", result))
.catch((error: unknown) => failNotice("SVG", error));
return;
}
const meshes = exportable.map(meshForShape);
if (format === "stl") {
void downloadTextFile(projectExportFileName(projectName, "stl"), toStl(meshes), "model/stl")
void downloadTextFile(projectExportFileName(exportName, "stl"), toStl(meshes), "model/stl")
.then((result) => finishNotice("STL", result))
.catch((error: unknown) => failNotice("STL", error));
return;
}
void downloadTextFile(projectExportFileName(projectName, "obj"), toObj(meshes), "text/plain")
void downloadTextFile(projectExportFileName(exportName, "obj"), toObj(meshes), "text/plain")
.then((result) => finishNotice("OBJ", result))
.catch((error: unknown) => failNotice("OBJ", error));
}, [hasSelection, projectName, selectedShapes, shapes]);
const exportStepDesign = useCallback(async () => {
const exportStepDesign = useCallback(async (exportName: string) => {
if (stepExporting) {
return;
}
@@ -7636,7 +7748,7 @@ export function SketchForgeEditor({
const { exportShapesToStep } = await import("@/lib/stepExport");
const { blob, exportedCount, skipped } = await exportShapesToStep(sourceShapes);
const text = await blob.text();
const result = await downloadTextFile(projectExportFileName(projectName, "step"), text, "application/step");
const result = await downloadTextFile(projectExportFileName(exportName, "step"), text, "application/step");
const skipNote = skipped.length > 0 ? `; skipped ${skipped.length} non-primitive shape${skipped.length === 1 ? "" : "s"}` : "";
if (result.mode === "folder") {
setNotice(`Saved STEP (${exportedCount} bod${exportedCount === 1 ? "y" : "ies"}) to ${result.path}${skipNote}`);
@@ -7650,6 +7762,39 @@ export function SketchForgeEditor({
}
}, [hasSelection, projectName, selectedShapes, shapes, stepExporting]);
const exportSkfDesign = useCallback(async (exportName: string, historyLimit: SkfHistoryLimit) => {
if (skfExporting) 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…");
try {
const exportedHistory = editorHistoryForExport(historyRef.current, historyIndexRef.current, historyLimit);
const bytes = await exportSkfProject({
projectId: projectInfoRef.current.projectId,
projectName: exportName.trim() || projectName,
createdAt: projectCreatedAt,
modifiedAt: projectModifiedAt,
shapes: shapesRef.current,
history: exportedHistory.entries,
historyIndex: exportedHistory.index,
assets: projectAssetsRef.current,
workspace: workspaceSettingsRef.current,
snapGrid,
placementElevation,
});
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]);
const clearDesign = useCallback(() => {
commitShapes([], [], "New empty design");
setClipboard([]);
@@ -7701,45 +7846,107 @@ export function SketchForgeEditor({
setMenuOpen(false);
}, [commitShapes, shapes]);
const selectFile = useCallback(async (file: File) => {
const isStep = /\.(step|stp)$/i.test(file.name);
const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml";
if (!isStep && !isSvg && !importExtensionSupported(file.name)) {
setNotice("Unsupported file type. Use STL, STEP, or SVG.");
const importFiles = useCallback(async (files: File[]) => {
if (!files.length) return;
const projectFiles = files.filter((file) => /\.skf$/i.test(file.name));
if (projectFiles.length) {
if (files.length !== 1) {
setNotice("Open one .skf project at a time; import STL, STEP, and SVG geometry separately");
return;
}
if (!onOpenSkfProjectFile) {
setNotice("Opening SketchForge project files is unavailable here");
return;
}
setNotice(`Validating ${projectFiles[0].name} before opening it as a new project`);
const result = await onOpenSkfProjectFile(projectFiles[0]);
if (result?.message) setNotice(result.message);
if (result?.ok !== false) setTopPanel(null);
return;
}
const sourceProjectId = projectInfoRef.current.projectId;
const importedShapes: WorkplaneShape[] = [];
const importedAssets: ProjectAsset[] = [];
const failures: Array<{ fileName: string; reason: string }> = [];
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
if (projectInfoRef.current.projectId !== sourceProjectId) {
setNotice(`Import of ${files.length} files cancelled because the project changed`);
return;
}
const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null);
const isStep = sourceFormat === "step";
const isSvg = sourceFormat === "svg";
if (!sourceFormat || sourceFormat === "obj" || (!isStep && !isSvg && !importExtensionSupported(file.name))) {
failures.push({ fileName: file.name, reason: "Unsupported file type" });
continue;
}
setNotice(`Importing ${index + 1} of ${files.length}: ${file.name}${isStep ? "… first STEP import loads the OpenCascade kernel (~22 MB)" : ""}`);
try {
const bytes = new Uint8Array(await file.arrayBuffer());
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
let nextShape: WorkplaneShape;
if (isStep) {
const { importedShapeFromStep } = await import("@/lib/stepImport");
nextShape = await importedShapeFromStep(file.name, buffer);
} else if (isSvg) {
nextShape = importedShapeFromSvg(file.name, new TextDecoder().decode(bytes));
} else {
nextShape = importedShapeFromStl(file.name, buffer);
}
const asset = await projectAssetFromBytes(file.name, sourceFormat, bytes, file.type);
importedShapes.push(attachProjectAsset(nextShape, asset.id));
importedAssets.push(asset);
} catch (error) {
failures.push({
fileName: file.name,
reason: error instanceof Error ? error.message : "Could not read file",
});
}
}
if (projectInfoRef.current.projectId !== sourceProjectId) {
setNotice(`Import of ${files.length} files cancelled because the project changed`);
return;
}
const sourceProjectId = projectInfoRef.current.projectId;
try {
let nextShape: WorkplaneShape;
if (isStep) {
setNotice("Reading STEP… first import loads the OpenCascade kernel (~22 MB), one time per session");
const { importedShapeFromStep } = await import("@/lib/stepImport");
nextShape = await importedShapeFromStep(file.name, await file.arrayBuffer());
} else if (isSvg) {
nextShape = importedShapeFromSvg(file.name, await file.text());
} else {
nextShape = importedShapeFromStl(file.name, await file.arrayBuffer());
}
if (projectInfoRef.current.projectId !== sourceProjectId) {
setNotice(`Import of ${file.name} cancelled because the project changed`);
return;
}
commitShapes([...shapesRef.current, nextShape], nextShape.id, `Imported ${file.name}`);
setTopPanel(null);
} catch (error) {
setNotice(error instanceof Error ? error.message : `Could not import ${file.name}`);
const failureDetails = failures
.slice(0, 3)
.map((failure) => `${failure.fileName}: ${failure.reason}`)
.join("; ");
const remainingFailureCount = Math.max(0, failures.length - 3);
const failureSummary = failures.length
? ` Failed: ${failureDetails}${remainingFailureCount ? `; plus ${remainingFailureCount} more` : ""}`
: "";
if (!importedShapes.length) {
setNotice(files.length === 1 && failures[0] ? failures[0].reason : `Could not import any of the ${files.length} selected files.${failureSummary}`);
return;
}
}, [commitShapes]);
const successSummary = importedShapes.length === 1 && files.length === 1
? `Imported ${files[0].name}`
: `Imported ${importedShapes.length} of ${files.length} files`;
const nextAssets = dedupeProjectAssets([...projectAssetsRef.current, ...importedAssets]);
projectAssetsRef.current = nextAssets;
setProjectAssets(nextAssets);
commitShapes(
[...shapesRef.current, ...importedShapes],
importedShapes.map((shape) => shape.id),
`${successSummary}.${failureSummary}`.trim(),
);
setTopPanel(null);
}, [commitShapes, onOpenSkfProjectFile]);
const selectFiles = useCallback(
(files: FileList | File[]) => {
const file = Array.from(files)[0];
if (file) {
void selectFile(file);
}
const selectedFiles = Array.from(files);
if (selectedFiles.length) void importFiles(selectedFiles);
},
[selectFile],
[importFiles],
);
const selectShape = useCallback((id: string | string[] | null, mode: "replace" | "toggle" = "replace") => {
@@ -8178,14 +8385,18 @@ export function SketchForgeEditor({
{topPanel ? (
<TopActionPanel
panel={topPanel}
projectName={projectName}
shapeCount={exportableShapeCount}
scopeLabel={exportScopeLabel}
onClose={() => setTopPanel(null)}
onExport={exportDesign}
onExportSkf={exportSkfDesign}
onExportStep={exportStepDesign}
skfExporting={skfExporting}
stepExporting={stepExporting}
onImportFiles={selectFiles}
onPickFile={() => fileInputRef.current?.click()}
onPickProjectFile={() => projectFileInputRef.current?.click()}
onNotice={setNotice}
/>
) : null}
@@ -8200,10 +8411,22 @@ export function SketchForgeEditor({
event.currentTarget.value = "";
}}
/>
<input
ref={projectFileInputRef}
className="hidden-file-input"
type="file"
accept=".skf"
onChange={(event) => {
const file = event.currentTarget.files?.[0];
if (file) selectFiles([file]);
event.currentTarget.value = "";
}}
/>
<input
ref={fileInputRef}
className="hidden-file-input"
type="file"
multiple
accept=".stl,.step,.stp,.svg,image/svg+xml"
onChange={(event) => {
if (event.currentTarget.files) {
@@ -8668,27 +8891,40 @@ function SecondaryToolbar({
function TopActionPanel({
panel,
projectName,
shapeCount,
scopeLabel,
onClose,
onExport,
onExportSkf,
onExportStep,
skfExporting,
stepExporting,
onImportFiles,
onPickFile,
onPickProjectFile,
onNotice,
}: {
panel: Exclude<TopPanel, null>;
projectName: string;
shapeCount: number;
scopeLabel: "selected" | "total";
onClose: () => void;
onExport: (format: ExportFormat) => void;
onExportStep: () => void;
onExport: (format: DirectExportFormat, exportName: string) => void;
onExportSkf: (exportName: string, historyLimit: SkfHistoryLimit) => void;
onExportStep: (exportName: string) => void;
skfExporting: boolean;
stepExporting: boolean;
onImportFiles: (files: FileList | File[]) => void;
onPickFile: () => void;
onPickProjectFile: () => void;
onNotice: (message: string) => void;
}) {
const [exportFormat, setExportFormat] = useState<ExportFormat>("stl");
const [exportName, setExportName] = useState(projectName);
const [skfHistoryLimit, setSkfHistoryLimit] = useState<SkfHistoryLimit>("unlimited");
const skfHistoryLimits: readonly SkfHistoryLimit[] = ["unlimited", 100, 50, 30];
const skfHistoryLimitIndex = skfHistoryLimits.indexOf(skfHistoryLimit);
const title =
panel === "profile"
? "Profile"
@@ -8700,16 +8936,64 @@ function TopActionPanel({
? "Export"
: "Import";
const exportDetails: Record<ExportFormat, { label: string; description: string; note: string }> = {
stl: {
label: "STL",
description: "3D print mesh",
note: "Best for slicers and 3D printing. Geometry is exported as a triangulated mesh.",
},
obj: {
label: "OBJ",
description: "Universal 3D mesh",
note: "A broadly compatible mesh format for modeling, rendering, and interchange.",
},
step: {
label: "STEP",
description: "CAD / B-Rep",
note: "Keeps supported boxes, cylinders, spheres, and cones as precise CAD geometry.",
},
svg: {
label: "SVG",
description: "Top-view vector",
note: "Exports a clean top-view silhouette in millimeters, including holes and curved contours.",
},
skf: {
label: "SKF",
description: "Editable project",
note: "Preserves the editable project, undo/redo history, sketches, groups, CAD data, and imported sources.",
},
};
const selectedExport = exportDetails[exportFormat];
const runSelectedExport = () => {
if (exportFormat === "step") onExportStep(exportName);
else if (exportFormat === "skf") onExportSkf(exportName, skfHistoryLimit);
else onExport(exportFormat, exportName);
};
return (
<div className="top-action-panel" role="dialog" aria-label={title}>
<div
className={`top-action-panel ${panel === "export" ? "export-action-panel" : panel === "import" ? "import-action-panel" : ""}`}
role="dialog"
aria-label={title}
>
<header>
<strong>{title}</strong>
<div className="top-action-heading">
<strong>{title}</strong>
</div>
<button aria-label={`Close ${title}`} onClick={onClose}>
<X size={18} />
</button>
</header>
{panel === "import" ? (
<div className="top-action-body">
<button className="open-skf-project-button" type="button" onClick={onPickProjectFile}>
<span className="open-skf-project-icon"><FolderOpen size={18} /></span>
<span>
<strong>Open SketchForge Project</strong>
<small>Restore an editable .skf file as a new local project</small>
</span>
</button>
<div className="import-kind-divider"><span>or add geometry</span></div>
<button
className="import-drop-zone"
onClick={onPickFile}
@@ -8731,21 +9015,99 @@ function TopActionPanel({
</div>
) : null}
{panel === "export" ? (
<div className="top-action-body">
<p>{shapeCount} {scopeLabel} solid shape{shapeCount === 1 ? "" : "s"} ready to export.</p>
<button onClick={() => onExport("stl")}>
<Download size={18} />
Download STL
</button>
<button onClick={() => onExport("obj")}>
<ToolbarExportIcon />
Download OBJ
</button>
<button onClick={onExportStep} disabled={stepExporting}>
<ToolbarExportIcon />
{stepExporting ? "Building STEP…" : "Download STEP (B-Rep)"}
</button>
<p className="export-step-note">STEP keeps boxes, cylinders, spheres and cones as exact CAD geometry (OpenCascade). Other shapes are skipped.</p>
<div className="export-dialog-body">
<section className="export-setting-section export-file-section">
<label htmlFor="export-file-name">File name</label>
<div className="export-file-input-wrap">
<input
id="export-file-name"
className="export-file-input"
value={exportName}
maxLength={120}
spellCheck={false}
onChange={(event) => setExportName(event.target.value)}
onFocus={(event) => event.currentTarget.select()}
onKeyDown={(event) => {
if (event.key === "Enter" && (shapeCount > 0 || exportFormat === "skf") && !stepExporting && !skfExporting) runSelectedExport();
}}
/>
<span>.{exportFormat}</span>
</div>
</section>
<section className="export-setting-section">
<div className="export-section-heading">
<div>
<strong>Format</strong>
</div>
<span className="export-scope-badge">{exportFormat === "skf" ? "Full project" : `${shapeCount} ${scopeLabel}`}</span>
</div>
<div className="export-format-slider" data-format={exportFormat} role="radiogroup" aria-label="Export format">
{(["stl", "obj", "step", "svg", "skf"] as const).map((format) => (
<button
key={format}
type="button"
role="radio"
aria-checked={exportFormat === format}
aria-label={`${exportDetails[format].label}: ${exportDetails[format].description}`}
onClick={() => setExportFormat(format)}
>
{exportDetails[format].label}
</button>
))}
</div>
</section>
{exportFormat === "skf" ? (
<section className="export-setting-section skf-history-section">
<div className="export-section-heading">
<div>
<strong>Saved action history</strong>
<span>Choose how many recent undo actions travel with the project</span>
</div>
</div>
<div className="skf-history-range-control" data-limit={String(skfHistoryLimit)}>
<input
className="skf-history-range"
type="range"
min={0}
max={skfHistoryLimits.length - 1}
step={1}
value={skfHistoryLimitIndex}
aria-label="Saved SKF action history"
aria-valuetext={skfHistoryLimit === "unlimited" ? "Unlimited" : `${skfHistoryLimit} actions`}
onChange={(event) => setSkfHistoryLimit(skfHistoryLimits[Number(event.currentTarget.value)] ?? "unlimited")}
/>
</div>
<div className="skf-history-range-labels" aria-hidden="true">
{skfHistoryLimits.map((limit) => (
<span key={limit} className={skfHistoryLimit === limit ? "active" : undefined}>
{limit === "unlimited" ? "Unlimited" : limit}
</span>
))}
</div>
</section>
) : null}
<div className="export-format-summary">
<div>
<strong>{selectedExport.label}</strong>
<span>{selectedExport.description}</span>
</div>
<p>{selectedExport.note}</p>
</div>
<footer className="export-dialog-footer">
<div>
<button className="export-primary-button" onClick={runSelectedExport} disabled={(shapeCount === 0 && exportFormat !== "skf") || stepExporting || skfExporting}>
<Download />
{exportFormat === "skf" ? (skfExporting ? "Saving project…" : "Save SketchForge Project") : null}
<span hidden={exportFormat === "skf"}>
{stepExporting && exportFormat === "step" ? "Building STEP…" : `Export ${selectedExport.label}`}
</span>
</button>
</div>
</footer>
</div>
) : null}
{panel === "tips" ? (
+17 -1
View File
@@ -1,8 +1,9 @@
import type { WorkplaneShape } from "@/types/sketchforge";
import { canonicalizeShape, serializeShapesForSync } from "@/lib/workplaneShapes";
export const MAX_EDITOR_HISTORY_ENTRIES = 100;
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 EditorHistoryEntry = {
shapes: WorkplaneShape[];
@@ -105,3 +106,18 @@ export function hydrateEditorHistoryState(
return { entries: [fallback], index: 0 };
}
}
export function editorHistoryForExport(
entries: EditorHistoryEntry[],
requestedIndex: number,
limit: EditorHistoryExportLimit,
): EditorHistoryState {
if (entries.length === 0) return { entries: [], index: 0 };
const index = Math.min(Math.max(0, requestedIndex), entries.length - 1);
if (limit === "unlimited") return { entries, index };
const start = Math.max(0, index - limit);
return {
entries: entries.slice(start, index + 1),
index: index - start,
};
}
+1 -1
View File
@@ -1,4 +1,4 @@
export type ProjectExportFormat = "stl" | "obj" | "step";
export type ProjectExportFormat = "stl" | "obj" | "step" | "svg" | "skf";
export function projectExportFileName(projectName: string, format: ProjectExportFormat) {
const safeProjectName = projectName
+93
View File
@@ -0,0 +1,93 @@
import type { ProjectAsset, ProjectAssetSourceFormat, WorkplaneShape } from "@/types/sketchforge";
function exactArrayBuffer(bytes: Uint8Array) {
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
}
export async function sha256Hex(bytes: Uint8Array) {
if (!globalThis.crypto?.subtle) {
throw new Error("Secure hashing is unavailable in this browser");
}
const digest = await globalThis.crypto.subtle.digest("SHA-256", exactArrayBuffer(bytes));
return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join("");
}
export function sourceFormatForFileName(fileName: string): ProjectAssetSourceFormat | null {
const extension = fileName.split(".").pop()?.toLowerCase();
if (extension === "stl" || extension === "obj" || extension === "svg") return extension;
if (extension === "step" || extension === "stp") return "step";
return null;
}
export function defaultMediaTypeForSource(format: ProjectAssetSourceFormat) {
if (format === "svg") return "image/svg+xml";
if (format === "step") return "application/step";
if (format === "obj") return "model/obj";
return "model/stl";
}
export async function projectAssetFromBytes(
name: string,
sourceFormat: ProjectAssetSourceFormat,
bytes: Uint8Array,
mediaType = defaultMediaTypeForSource(sourceFormat),
): Promise<ProjectAsset> {
const stableBytes = new Uint8Array(bytes);
const sha256 = await sha256Hex(stableBytes);
return {
id: `asset-${sha256.slice(0, 32)}`,
name: name.trim() || `Imported ${sourceFormat.toUpperCase()}`,
mediaType: mediaType.trim() || defaultMediaTypeForSource(sourceFormat),
sourceFormat,
bytes: stableBytes,
byteLength: stableBytes.byteLength,
sha256,
};
}
export async function projectAssetFromFile(file: File, sourceFormat = sourceFormatForFileName(file.name)) {
if (!sourceFormat) throw new Error("Unsupported project asset type");
const bytes = new Uint8Array(await file.arrayBuffer());
return projectAssetFromBytes(file.name, sourceFormat, bytes, file.type);
}
export function normalizeProjectAsset(value: ProjectAsset): ProjectAsset {
const candidate = value.bytes as Uint8Array | ArrayBuffer | number[];
const bytes = candidate instanceof Uint8Array
? new Uint8Array(candidate)
: candidate instanceof ArrayBuffer
? new Uint8Array(candidate.slice(0))
: new Uint8Array(Array.isArray(candidate) ? candidate : []);
return { ...value, bytes, byteLength: bytes.byteLength };
}
export function dedupeProjectAssets(assets: ProjectAsset[]) {
const byHash = new Map<string, ProjectAsset>();
assets.forEach((asset) => {
const normalized = normalizeProjectAsset(asset);
if (!byHash.has(normalized.sha256)) byHash.set(normalized.sha256, normalized);
});
return [...byHash.values()].sort((a, b) => a.id.localeCompare(b.id));
}
export function attachProjectAsset(shape: WorkplaneShape, assetId: string): WorkplaneShape {
if (!shape.importedMesh) return shape;
return {
...shape,
importedMesh: {
...shape.importedMesh,
assetId,
},
};
}
export function projectAssetIdsInShapes(shapes: WorkplaneShape[]) {
const ids = new Set<string>();
const visit = (shape: WorkplaneShape) => {
if (shape.importedMesh?.assetId) ids.add(shape.importedMesh.assetId);
shape.groupedShapes?.forEach(visit);
shape.edgeTreatmentHistory?.forEach((entry) => visit(entry.before));
};
shapes.forEach(visit);
return ids;
}
+1
View File
@@ -53,6 +53,7 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
groupedBaseWidth: shape.groupedBaseWidth,
groupedBaseDepth: shape.groupedBaseDepth,
groupedBaseHeight: shape.groupedBaseHeight,
groupOperation: shape.groupOperation,
locked: shape.locked ?? false,
hidden: shape.hidden ?? false,
});
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
export type SvgProjectionPolygon = ReadonlyArray<readonly [number, number]>;
export type SvgProjectionLayer = {
name: string;
color: string;
polygons: ReadonlyArray<SvgProjectionPolygon>;
};
function xmlEscape(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
function svgNumber(value: number) {
const rounded = Math.abs(value) < 1e-9 ? 0 : Number(value.toFixed(6));
return String(rounded);
}
function safeFillColor(value: string) {
return /^(?:#[0-9a-f]{3,8}|(?:rgb|hsl)a?\([^<>]+\))$/i.test(value.trim()) ? value.trim() : "#0098c7";
}
export function toSvgProjection(layers: ReadonlyArray<SvgProjectionLayer>, title = "SketchForge design") {
const cleanLayers = layers.flatMap((layer) => {
const polygons = layer.polygons.filter(
(polygon) => polygon.length >= 3 && polygon.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y)),
);
return polygons.length ? [{ ...layer, polygons }] : [];
});
let pointCount = 0;
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
cleanLayers.forEach((layer) => layer.polygons.forEach((polygon) => polygon.forEach(([x, y]) => {
pointCount += 1;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
})));
if (!pointCount) throw new Error("SVG projection contains no readable contours");
const width = maxX - minX;
const height = maxY - minY;
if (width <= 0 || height <= 0) throw new Error("SVG projection does not enclose a visible area");
const body = cleanLayers.map((layer) => {
const pathData = layer.polygons
.map((polygon) => polygon.map(([x, y], index) => `${index === 0 ? "M" : "L"}${svgNumber(x)} ${svgNumber(y)}`).join(" ") + " Z")
.join(" ");
return ` <path data-name="${xmlEscape(layer.name)}" d="${pathData}" fill="${safeFillColor(layer.color)}" fill-rule="evenodd"/>`;
});
return [
'<?xml version="1.0" encoding="UTF-8"?>',
`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${svgNumber(width)}mm" height="${svgNumber(height)}mm" viewBox="${svgNumber(minX)} ${svgNumber(minY)} ${svgNumber(width)} ${svgNumber(height)}">`,
` <title>${xmlEscape(title)}</title>`,
" <desc>Top-view vector projection exported by SketchForge</desc>",
...body,
"</svg>",
].join("\n");
}
+83 -10
View File
@@ -18,6 +18,9 @@ type SvgPathStyle = {
fill?: string;
fillOpacity?: number;
opacity?: number;
stroke?: string;
strokeOpacity?: number;
strokeWidth?: number;
visibility?: string;
};
@@ -54,13 +57,34 @@ function attributeValues(source: string, name: string) {
return values;
}
const SVG_DOCUMENT_TYPE_PATTERN = /<!DOCTYPE\b[^>]*>/gi;
const SVG_11_DOCUMENT_TYPE_PATTERN = /^<!DOCTYPE\s+svg(?:\s+PUBLIC\s+(["'])-\/\/W3C\/\/DTD SVG 1\.1\/\/EN\1\s+(["'])https?:\/\/www\.w3\.org\/Graphics\/SVG\/1\.1\/DTD\/svg11\.dtd\2)?\s*>$/i;
function svgDocumentTypes(source: string) {
return source.match(SVG_DOCUMENT_TYPE_PATTERN) ?? [];
}
export function normalizeSvgDocumentType(source: string) {
return source.replace(SVG_DOCUMENT_TYPE_PATTERN, "");
}
export function validateSvgSourcePreflight(source: string) {
if (!source.trim()) throw new Error("SVG file is empty");
if (sourceByteLength(source) > MAX_SVG_BYTES) {
throw new Error(`SVG is too large. The maximum supported size is ${MAX_SVG_BYTES / 1024 / 1024} MB`);
}
if (/<!DOCTYPE|<!ENTITY/i.test(source)) {
throw new Error("SVG document types and entities are not supported");
if (/<!ENTITY/i.test(source)) {
throw new Error("SVG entities are not supported");
}
const documentTypes = svgDocumentTypes(source);
const documentTypeStarts = source.match(/<!DOCTYPE\b/gi)?.length ?? 0;
if (documentTypes.length !== documentTypeStarts || documentTypes.some((declaration) => !SVG_11_DOCUMENT_TYPE_PATTERN.test(declaration))) {
throw new Error("Only the standard SVG 1.1 document type is supported");
}
if (/\b(?:width|height|viewBox|d)\s*=\s*(["'])[^"']*\bNaN\b[^"']*\1/i.test(source)) {
throw new Error("SVG contains invalid NaN geometry. In Tinkercad, make sure the workplane intersects the model before exporting the cross-section");
}
const xmlElementCount = source.match(/<[a-z][^!?/\s>]*/gi)?.length ?? 0;
@@ -122,6 +146,10 @@ function fillAlpha(fill: string | undefined) {
return Number.parseFloat(functional);
}
function strokeAlpha(stroke: string | undefined) {
return stroke ? fillAlpha(stroke) : 0;
}
function elementStyleValue(element: Element, property: string) {
const style = (element as Element & { style?: CSSStyleDeclaration }).style;
const fromStyle = style?.getPropertyValue(property);
@@ -143,15 +171,55 @@ function elementOrAncestorSuppressesRendering(element: Element | null | undefine
return false;
}
function pathIsFilledAndVisible(path: THREE.ShapePath) {
function pathStyleAndNode(path: THREE.ShapePath) {
const userData = (path as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData;
const style = userData?.style ?? {};
return { style: userData?.style ?? {}, node: userData?.node };
}
function pathIsVisible(path: THREE.ShapePath) {
const { style, node } = pathStyleAndNode(path);
const visibility = style.visibility?.trim().toLowerCase();
if (visibility === "hidden" || visibility === "collapse") return false;
if (numericStyleValue(style.opacity) <= MIN_VISIBLE_ALPHA) return false;
return !elementOrAncestorSuppressesRendering(node);
}
function pathHasVisibleFill(path: THREE.ShapePath) {
if (!pathIsVisible(path)) return false;
const { style } = pathStyleAndNode(path);
if (numericStyleValue(style.fillOpacity) <= MIN_VISIBLE_ALPHA) return false;
if (fillAlpha(style.fill) <= MIN_VISIBLE_ALPHA) return false;
return !elementOrAncestorSuppressesRendering(userData?.node);
return fillAlpha(style.fill) > MIN_VISIBLE_ALPHA;
}
function pathHasVisibleStroke(path: THREE.ShapePath) {
if (!pathIsVisible(path)) return false;
const { style } = pathStyleAndNode(path);
if (numericStyleValue(style.strokeOpacity) <= MIN_VISIBLE_ALPHA) return false;
if (numericStyleValue(style.strokeWidth, 0) <= MIN_VISIBLE_ALPHA) return false;
return strokeAlpha(style.stroke) > MIN_VISIBLE_ALPHA;
}
function subPathIsClosed(path: THREE.Path) {
const points = path.getPoints(SVG_CURVE_SEGMENTS);
if (points.length < 3) return false;
if (path.autoClose) return true;
const extent = points.reduce((largest, point) => Math.max(largest, Math.abs(point.x), Math.abs(point.y)), 1);
const tolerance = extent * 1e-9;
return points[0].distanceToSquared(points[points.length - 1]) <= tolerance * tolerance;
}
function extrusionProfileFromPath(path: THREE.ShapePath) {
if (pathHasVisibleFill(path)) return path;
if (!pathHasVisibleStroke(path)) return null;
const closedSubPaths = path.subPaths.filter(subPathIsClosed);
if (!closedSubPaths.length) return null;
const profile = new THREE.ShapePath();
profile.color.copy(path.color);
profile.subPaths.push(...closedSubPaths);
const userData = (path as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData;
(profile as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData = userData;
return profile;
}
function cleanRingPoints(points: THREE.Vector2[]) {
@@ -422,10 +490,15 @@ export function validateClosedSolidTriangleSoup(positions: readonly number[], la
}
export function buildSvgExtrusionFromPaths(paths: readonly THREE.ShapePath[]) {
const visiblePaths = paths.filter(pathIsFilledAndVisible);
if (!visiblePaths.length) throw new Error("SVG has no readable visible filled paths");
const profilePaths = paths.map(extrusionProfileFromPath).filter((path): path is THREE.ShapePath => Boolean(path));
if (!profilePaths.length) {
if (paths.some(pathHasVisibleStroke)) {
throw new Error("SVG contains only open strokes. Close the paths or convert the strokes to filled outlines before importing");
}
throw new Error("SVG has no readable visible filled or closed-stroke paths");
}
const sourceShapes = visiblePaths.flatMap((path) => SVGLoader.createShapes(path));
const sourceShapes = profilePaths.flatMap((path) => SVGLoader.createShapes(path));
const shapes = composeNestedRings(sourceShapes);
const rawPositions: number[] = [];
const acceptedAnalyses: TriangleSoupAnalysis[] = [];
@@ -485,7 +558,7 @@ export function buildSvgExtrusionFromPaths(paths: readonly THREE.ShapePath[]) {
export function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
validateSvgSourcePreflight(source);
const parsed = svgLoader.parse(normalizeSvgUseReferences(source));
const parsed = svgLoader.parse(normalizeSvgUseReferences(normalizeSvgDocumentType(source)));
const parsedXml = parsed.xml as unknown as XMLDocument | Element;
const root = "documentElement" in parsedXml ? parsedXml.documentElement : parsedXml;
if (root.localName !== "svg" || root.querySelector("parsererror")) {
+1
View File
@@ -188,6 +188,7 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
a.groupedBaseWidth === b.groupedBaseWidth &&
a.groupedBaseDepth === b.groupedBaseDepth &&
a.groupedBaseHeight === b.groupedBaseHeight &&
a.groupOperation === b.groupOperation &&
a.locked === b.locked &&
a.hidden === b.hidden
);
+16
View File
@@ -27,6 +27,18 @@ export type ShapeAsset = {
hole?: boolean;
};
export type ProjectAssetSourceFormat = "stl" | "obj" | "svg" | "step";
export type ProjectAsset = {
id: string;
name: string;
mediaType: string;
sourceFormat: ProjectAssetSourceFormat;
bytes: Uint8Array;
byteLength: number;
sha256: string;
};
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;
@@ -179,6 +191,9 @@ export type WorkplaneShape = {
baseHeight: number;
triangleCount: number;
sourceFormat: "stl" | "obj" | "svg" | "json" | "step";
// Stable reference to the original imported file in the project's shared
// asset table. Copies and grouped operands reuse this reference.
assetId?: string;
// Exact OpenCascade B-Rep of the body (single-shape STEP text) in the same
// local frame as `positions`. Set only for STEP imports; lets the exporter
// re-emit the original analytic geometry instead of the tessellation.
@@ -203,6 +218,7 @@ export type WorkplaneShape = {
groupedBaseWidth?: number;
groupedBaseDepth?: number;
groupedBaseHeight?: number;
groupOperation?: "group" | "intersection";
locked?: boolean;
hidden?: boolean;
};