Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
Checkpoint SKF project format and export updates
This commit is contained in:
@@ -23,6 +23,8 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
SketchForge projects can be saved as native editable `.skf` packages and opened later on another browser or device. Unlike STL/OBJ mesh exports, `.skf` preserves shapes, sketches, groups and boolean operands, exact CAD data where available, imported sources, workspace settings, and undo/redo history. See [the `.skf` project format documentation](docs/SKF_PROJECT_FORMAT.md).
|
||||
|
||||

|
||||
|
||||
## Why SketchForge
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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">
|
||||
|
||||
@@ -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" ? (
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
@@ -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")) {
|
||||
|
||||
@@ -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
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
# SketchForge project files (`.skf`)
|
||||
|
||||
`.skf` is SketchForge's native, editable project format. It is an additional backup, transfer, and sharing mechanism; IndexedDB autosave remains the normal local persistence system, and STL, OBJ, STEP, and SVG remain geometry exports.
|
||||
|
||||
## Architecture decision
|
||||
|
||||
SketchForge uses a packaged container (format option B). A `.skf` file is a ZIP archive containing `project.json` and deduplicated files below `assets/`.
|
||||
|
||||
This was selected over pure JSON because imported STL/STEP data and exact B-Rep can be large, Base64 would add size and parsing overhead, and an archive lets SketchForge validate and hash each asset independently. The editable model is still JSON and can be inspected by opening `project.json` from the package.
|
||||
|
||||
## Version 1 layout
|
||||
|
||||
```text
|
||||
project.skf
|
||||
├── project.json
|
||||
└── assets/
|
||||
├── source/ Original imported STL, SVG, or STEP files
|
||||
├── derived-mesh/ Exact caches for baked operations or legacy imports
|
||||
├── brep/ Exact STEP/B-Rep payloads
|
||||
└── image/ Deduplicated sketch/reference images
|
||||
```
|
||||
|
||||
`project.json` contains these top-level sections:
|
||||
|
||||
- `schema`, `formatVersion`, `minimumReaderVersion`, and `createdWithVersion`
|
||||
- `metadata`: project name, source project ID, units, and timestamps
|
||||
- `assets`: path, type, byte length, SHA-256, source format, and media type
|
||||
- `states`: explicit root node IDs and editable object graphs for the active scene and undo/redo states
|
||||
- `history`: ordered state references, selection per state, and current undo/redo index
|
||||
- `sketches`: sketch/extrusion indexes
|
||||
- `features`: supported group, subtraction, intersection, mirror, sketch-extrusion, fillet, and chamfer operations used by the active project
|
||||
- `groups`: explicit parent/member references and operation type
|
||||
- `workplanes`: base and selected offset workplanes
|
||||
- `exactCad`: objects with exact B-Rep or imported STEP sources
|
||||
- `editor`: workspace dimensions, units, snap grid, and selected workplane elevation
|
||||
|
||||
Object nodes keep stable SketchForge object IDs. Groups refer to child node IDs instead of array positions. Fillet/chamfer history refers to explicit “before” nodes. Feature dependencies are explicit and checked for cycles.
|
||||
|
||||
## What is preserved
|
||||
|
||||
- All current native shape kinds and their editable parameters
|
||||
- Position, rotation, dimensions, mirrors, colour, solid/hole role, visibility, and lock state
|
||||
- Nested groups, boolean operands, subtraction results, and intersection metadata
|
||||
- Sketch points, lines, Bezier/smooth handles, disjoint profiles, reference images, and extrusion depth
|
||||
- Imported STL, SVG, and STEP sources, stored once and reused by instances
|
||||
- Exact imported STEP data, current exact CAD B-Rep, display edges, chamfer/fillet settings, and reversible edge-treatment history
|
||||
- Undo and redo states according to the export choice: Unlimited, 100, 50, or 30 recent actions. Unlimited means every state still retained by the editor, including available redo states.
|
||||
- Workspace units, grid/snap settings, dimensions, and active offset workplane
|
||||
|
||||
Native primitives are regenerated from definitions and do not receive mesh assets. Source-backed STL, SVG, and STEP objects are regenerated from their original asset. Derived mesh assets are written only when the current editor has genuinely baked geometry (for example a boolean or edge treatment), or when an older local project no longer has its original imported source.
|
||||
|
||||
## Opening safely
|
||||
|
||||
SketchForge inspects ZIP metadata before expansion and validates the entire project before changing local state. It rejects unsafe paths, encrypted or unsupported compression, excessive expansion, malformed shapes/sketches, duplicate IDs, missing assets, hash mismatches, invalid transforms, unknown shape or operation types, cyclic groups/features, and unsupported versions.
|
||||
|
||||
Opening a valid `.skf` creates a new local project. It does not overwrite the project that is currently open. The imported project is then saved through the existing dashboard, thumbnail, IndexedDB, history, and editor lifecycle.
|
||||
|
||||
Current safety limits are 512 MB compressed, 1 GB expanded, 256 MB per asset, 32 MB for `project.json`, 4,096 archive entries, 100,000 object nodes per state, and 5,001 distinct states. The live editor retains at most 5,000 history entries and 64 MB of serialized history, so Unlimited means all history currently available inside those safety limits.
|
||||
|
||||
## Compatibility and migrations
|
||||
|
||||
The current format is version 1. Readers refuse a higher `formatVersion` or `minimumReaderVersion` instead of partially loading it. The importer also contains an explicit migration for the documented version 0 pure-JSON prototype and preserves its object IDs and valid history.
|
||||
|
||||
Future schema changes should add a version-to-version migration, run validation after every migration, and never mutate the user's original file.
|
||||
|
||||
## Current limitations
|
||||
|
||||
- Projects created before source-asset tracking cannot recover the exact original STL/SVG file. Their existing normalized editable mesh is preserved as a deduplicated legacy cache and is identified by the absence of a source asset.
|
||||
- SketchForge currently bakes the displayed result of booleans and edge treatments. `.skf` preserves the operands, group hierarchy, feature metadata, reversible history, exact B-Rep where available, and a derived-result cache; it does not add a new live parametric feature editor that the application does not yet have.
|
||||
- The current workplane system stores a base plane plus numeric offset. It does not expose persistent associative face-workplane references, so `.skf` cannot preserve an association that the editor itself does not model.
|
||||
- Geometric sketch constraints and dimensions are not yet part of SketchForge's sketch data model. Existing points, segments, curve handles, profiles, and extrusion depth are preserved exactly.
|
||||
- Camera position is intentionally omitted because the current project persistence system does not own it. It can be added as optional editor state in a compatible future version.
|
||||
- OBJ is currently an export format, not an import format. An OBJ source-asset record is reserved in the schema for future import support.
|
||||
Generated
+1
@@ -13,6 +13,7 @@
|
||||
"@types/three": "^0.184.1",
|
||||
"brepjs": "^18.118.0",
|
||||
"clsx": "^2.1.1",
|
||||
"fflate": "^0.8.2",
|
||||
"lucide-react": "^0.511.0",
|
||||
"manifold-3d": "^3.5.0",
|
||||
"next": "^15.3.2",
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"@types/three": "^0.184.1",
|
||||
"brepjs": "^18.118.0",
|
||||
"clsx": "^2.1.1",
|
||||
"fflate": "^0.8.2",
|
||||
"lucide-react": "^0.511.0",
|
||||
"manifold-3d": "^3.5.0",
|
||||
"next": "^15.3.2",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { appendEditorHistorySnapshot, boundedEditorHistory, editorHistoryEntry, hydrateEditorHistoryState, projectShapesFingerprint } from "@/lib/editorHistory";
|
||||
import { appendEditorHistorySnapshot, boundedEditorHistory, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint } from "@/lib/editorHistory";
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
function box(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
|
||||
@@ -107,4 +107,18 @@ describe("editor history snapshots", () => {
|
||||
expect(restored.entries).toHaveLength(1);
|
||||
expect(restored.entries[0].shapes[0].x).toBe(9);
|
||||
});
|
||||
|
||||
it("selects all history or the requested number of recent undo actions for project export", () => {
|
||||
const entries = Array.from({ length: 140 }, (_, x) => editorHistoryEntry([box({ x })], []));
|
||||
|
||||
const unlimited = editorHistoryForExport(entries, 120, "unlimited");
|
||||
expect(unlimited.entries).toBe(entries);
|
||||
expect(unlimited.index).toBe(120);
|
||||
|
||||
const lastThirty = editorHistoryForExport(entries, 120, 30);
|
||||
expect(lastThirty.entries).toHaveLength(31);
|
||||
expect(lastThirty.index).toBe(30);
|
||||
expect(lastThirty.entries[0].shapes[0].x).toBe(90);
|
||||
expect(lastThirty.entries[30].shapes[0].x).toBe(120);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,8 @@ describe("project export filenames", () => {
|
||||
expect(projectExportFileName("Gearbox Prototype", "stl")).toBe("Gearbox Prototype.stl");
|
||||
expect(projectExportFileName("Gearbox Prototype", "obj")).toBe("Gearbox Prototype.obj");
|
||||
expect(projectExportFileName("Gearbox Prototype", "step")).toBe("Gearbox Prototype.step");
|
||||
expect(projectExportFileName("Gearbox Prototype", "svg")).toBe("Gearbox Prototype.svg");
|
||||
expect(projectExportFileName("Gearbox Prototype", "skf")).toBe("Gearbox Prototype.skf");
|
||||
});
|
||||
|
||||
it("removes filesystem-reserved characters without discarding the project name", () => {
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
||||
import { editorHistoryEntry } from "@/lib/editorHistory";
|
||||
import { projectAssetFromBytes } from "@/lib/projectAssets";
|
||||
import { canonicalizeShape } from "@/lib/workplaneShapes";
|
||||
import {
|
||||
exportSkfProject,
|
||||
importSkfProject,
|
||||
SKF_FORMAT_VERSION,
|
||||
SKF_SCHEMA_ID,
|
||||
type SkfProjectDocumentV1,
|
||||
type SkfProjectExportInput,
|
||||
} from "@/lib/skfProject";
|
||||
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
|
||||
import type { ShapeKind, WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
function shape(kind: ShapeKind, id = `${kind}-1`, overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
|
||||
return {
|
||||
id,
|
||||
name: kind,
|
||||
kind,
|
||||
color: "#12a4cc",
|
||||
x: 1,
|
||||
z: 2,
|
||||
elevation: 3,
|
||||
size: 20,
|
||||
width: 20,
|
||||
depth: 18,
|
||||
height: 16,
|
||||
rotation: 15,
|
||||
rotationX: 5,
|
||||
rotationZ: 10,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function input(shapes: WorkplaneShape[], overrides: Partial<SkfProjectExportInput> = {}): SkfProjectExportInput {
|
||||
const history = [editorHistoryEntry(shapes, [])];
|
||||
return {
|
||||
projectId: "project-original",
|
||||
projectName: "Round trip",
|
||||
createdAt: 1_700_000_000_000,
|
||||
modifiedAt: 1_700_000_100_000,
|
||||
shapes,
|
||||
history,
|
||||
historyIndex: 0,
|
||||
assets: [],
|
||||
workspace: DEFAULT_WORKPLANE_WORKSPACE,
|
||||
snapGrid: DEFAULT_SNAP_GRID,
|
||||
placementElevation: 12.5,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function packageDocument(bytes: Uint8Array) {
|
||||
const files = unzipSync(bytes);
|
||||
return { files, document: JSON.parse(strFromU8(files["project.json"])) as SkfProjectDocumentV1 };
|
||||
}
|
||||
|
||||
function mutateProject(bytes: Uint8Array, mutate: (document: SkfProjectDocumentV1) => void) {
|
||||
const files = unzipSync(bytes);
|
||||
const document = JSON.parse(strFromU8(files["project.json"])) as SkfProjectDocumentV1;
|
||||
mutate(document);
|
||||
files["project.json"] = strToU8(JSON.stringify(document));
|
||||
return zipSync(files);
|
||||
}
|
||||
|
||||
describe("SketchForge .skf project packages", () => {
|
||||
it("round-trips every supported native shape kind and editable properties", async () => {
|
||||
const nativeKinds: ShapeKind[] = [
|
||||
"box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
|
||||
"halfSphere", "torus", "tube", "ring", "wedge", "polygon", "icosahedron",
|
||||
];
|
||||
const shapes = nativeKinds.map((kind, index) => shape(kind, `${kind}-${index}`, {
|
||||
hole: index === 2,
|
||||
locked: index === 3,
|
||||
hidden: index === 4,
|
||||
mirrorX: index === 5,
|
||||
sides: index + 3,
|
||||
text: kind === "text" ? "Editable" : undefined,
|
||||
sketchProfile: kind === "sketch" ? {
|
||||
points: [
|
||||
{ id: "p1", x: 0, z: 0 },
|
||||
{ id: "p2", x: 10, z: 0 },
|
||||
{ id: "p3", x: 10, z: 10 },
|
||||
],
|
||||
segments: [
|
||||
{ id: "s1", startId: "p1", endId: "p2", kind: "line" },
|
||||
{ id: "s2", startId: "p2", endId: "p3", kind: "bezier" },
|
||||
{ id: "s3", startId: "p3", endId: "p1", kind: "line" },
|
||||
],
|
||||
} : undefined,
|
||||
}));
|
||||
|
||||
const exported = await exportSkfProject(input(shapes));
|
||||
const { document } = packageDocument(exported);
|
||||
const restored = await importSkfProject(exported);
|
||||
|
||||
expect(restored.projectName).toBe("Round trip");
|
||||
expect(restored.sourceProjectId).toBe("project-original");
|
||||
expect(JSON.stringify(restored.shapes)).toBe(JSON.stringify(shapes.map(canonicalizeShape)));
|
||||
expect(restored.workspace).toEqual(DEFAULT_WORKPLANE_WORKSPACE);
|
||||
expect(restored.snapGrid).toBe(DEFAULT_SNAP_GRID);
|
||||
expect(restored.placementElevation).toBe(12.5);
|
||||
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("preserves nested groups, holes, intersection metadata, edge history, B-Rep, and undo/redo", async () => {
|
||||
const solid = shape("box", "solid", { x: 0 });
|
||||
const hole = shape("cylinder", "hole", { hole: true, color: "#b8c2cc", x: 4 });
|
||||
const group = shape("mesh", "group", {
|
||||
name: "Intersection",
|
||||
groupOperation: "intersection",
|
||||
groupedBaseWidth: 30,
|
||||
groupedBaseDepth: 30,
|
||||
groupedBaseHeight: 20,
|
||||
groupedShapes: [solid, hole],
|
||||
importedMesh: {
|
||||
positions: [0, 0, 0, 2, 0, 0, 0, 2, 0],
|
||||
normals: [0, 0, 1, 0, 0, 1, 0, 0, 1],
|
||||
baseWidth: 2,
|
||||
baseDepth: 1,
|
||||
baseHeight: 2,
|
||||
triangleCount: 1,
|
||||
sourceFormat: "json",
|
||||
},
|
||||
cadBrep: "BREP exact payload",
|
||||
edgeTreatments: [{ kind: "fillet", amount: 1.25, edgeCount: 3 }],
|
||||
edgeTreatmentHistory: [{
|
||||
id: "edge-history-1",
|
||||
createdAt: 1_700_000_050_000,
|
||||
feature: { kind: "fillet", amount: 1.25, edgeCount: 3 },
|
||||
before: shape("box", "group", { width: 30, depth: 30, height: 20 }),
|
||||
}],
|
||||
});
|
||||
const before = editorHistoryEntry([solid, hole], ["solid", "hole"]);
|
||||
const after = editorHistoryEntry([group], ["group"]);
|
||||
const exported = await exportSkfProject(input([group], { history: [before, after], historyIndex: 1 }));
|
||||
const { document } = packageDocument(exported);
|
||||
|
||||
expect(document.groups[0].operation).toBe("boolean-intersection");
|
||||
expect(document.features.some((feature) => feature.type === "fillet")).toBe(true);
|
||||
expect(document.exactCad).toHaveLength(1);
|
||||
|
||||
const restored = await importSkfProject(exported);
|
||||
expect(restored.history).toHaveLength(2);
|
||||
expect(restored.historyIndex).toBe(1);
|
||||
expect(restored.shapes[0].groupedShapes).toEqual([solid, hole]);
|
||||
expect(restored.shapes[0].groupOperation).toBe("intersection");
|
||||
expect(restored.shapes[0].cadBrep).toBe("BREP exact payload");
|
||||
expect(restored.shapes[0].edgeTreatmentHistory?.[0].before.kind).toBe("box");
|
||||
});
|
||||
|
||||
it("stores one original source asset for repeated imported instances and regenerates it once", async () => {
|
||||
const sourceBytes = strToU8("solid source");
|
||||
const asset = await projectAssetFromBytes("shared.stl", "stl", sourceBytes);
|
||||
const importedMesh: NonNullable<WorkplaneShape["importedMesh"]> = {
|
||||
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
|
||||
baseWidth: 1,
|
||||
baseDepth: 1,
|
||||
baseHeight: 1,
|
||||
triangleCount: 1,
|
||||
sourceFormat: "stl",
|
||||
assetId: asset.id,
|
||||
};
|
||||
const instances = [
|
||||
shape("mesh", "instance-a", { importedMesh, x: 0 }),
|
||||
shape("mesh", "instance-b", { importedMesh, x: 30 }),
|
||||
];
|
||||
const exported = await exportSkfProject(input(instances, { assets: [asset] }));
|
||||
const { document } = packageDocument(exported);
|
||||
let importCalls = 0;
|
||||
const restored = await importSkfProject(exported, {
|
||||
sourceImporter: async () => {
|
||||
importCalls += 1;
|
||||
return { ...importedMesh, assetId: undefined };
|
||||
},
|
||||
});
|
||||
|
||||
expect(document.assets.filter((entry) => entry.kind === "source")).toHaveLength(1);
|
||||
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
|
||||
expect(restored.assets).toHaveLength(1);
|
||||
expect(restored.shapes[0].importedMesh?.assetId).toBe(restored.shapes[1].importedMesh?.assetId);
|
||||
expect(importCalls).toBe(1);
|
||||
});
|
||||
|
||||
it.each(["svg", "step"] as const)("stores and restores original %s sources", async (sourceFormat) => {
|
||||
const asset = await projectAssetFromBytes(`source.${sourceFormat}`, sourceFormat, strToU8(`${sourceFormat} source`));
|
||||
const importedMesh: NonNullable<WorkplaneShape["importedMesh"]> = {
|
||||
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
|
||||
baseWidth: 1,
|
||||
baseDepth: 1,
|
||||
baseHeight: 1,
|
||||
triangleCount: 1,
|
||||
sourceFormat,
|
||||
assetId: asset.id,
|
||||
...(sourceFormat === "step" ? { brepStep: "exact STEP" } : {}),
|
||||
};
|
||||
const exported = await exportSkfProject(input([shape("mesh", `${sourceFormat}-object`, { importedMesh })], { assets: [asset] }));
|
||||
const { document } = packageDocument(exported);
|
||||
const restored = await importSkfProject(exported, { sourceImporter: async () => importedMesh });
|
||||
|
||||
expect(document.assets.filter((entry) => entry.kind === "source")).toHaveLength(1);
|
||||
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
|
||||
expect(restored.assets[0].sourceFormat).toBe(sourceFormat);
|
||||
expect(restored.shapes[0].importedMesh?.sourceFormat).toBe(sourceFormat);
|
||||
if (sourceFormat === "step") expect(document.exactCad[0].importedStepAssetId).toBeTruthy();
|
||||
});
|
||||
|
||||
it("deduplicates and restores reference images stored in sketches and image plates", async () => {
|
||||
const dataUrl = "data:image/png;base64,AAECAwQ=";
|
||||
const imageShape = shape("sketch", "sketch-images", {
|
||||
imagePlate: { dataUrl, mimeType: "image/png", pixelWidth: 2, pixelHeight: 2 },
|
||||
sketchProfile: {
|
||||
points: [
|
||||
{ id: "p1", x: 0, z: 0 },
|
||||
{ id: "p2", x: 10, z: 0 },
|
||||
{ id: "p3", x: 0, z: 10 },
|
||||
],
|
||||
segments: [
|
||||
{ id: "s1", startId: "p1", endId: "p2" },
|
||||
{ id: "s2", startId: "p2", endId: "p3" },
|
||||
{ id: "s3", startId: "p3", endId: "p1" },
|
||||
],
|
||||
images: [{
|
||||
id: "image-1",
|
||||
name: "Reference",
|
||||
dataUrl,
|
||||
mimeType: "image/png",
|
||||
pixelWidth: 2,
|
||||
pixelHeight: 2,
|
||||
x: 0,
|
||||
z: 0,
|
||||
width: 10,
|
||||
depth: 10,
|
||||
}],
|
||||
},
|
||||
});
|
||||
const exported = await exportSkfProject(input([imageShape]));
|
||||
const { document } = packageDocument(exported);
|
||||
const restored = await importSkfProject(exported);
|
||||
|
||||
expect(document.assets.filter((entry) => entry.kind === "image")).toHaveLength(1);
|
||||
expect(restored.shapes[0].imagePlate?.dataUrl).toBe(dataUrl);
|
||||
expect(restored.shapes[0].sketchProfile?.images?.[0].dataUrl).toBe(dataUrl);
|
||||
});
|
||||
|
||||
it("deduplicates derived geometry when legacy imported objects share one mesh", async () => {
|
||||
const mesh = {
|
||||
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
|
||||
baseWidth: 1,
|
||||
baseDepth: 1,
|
||||
baseHeight: 1,
|
||||
triangleCount: 1,
|
||||
sourceFormat: "json" as const,
|
||||
};
|
||||
const exported = await exportSkfProject(input([
|
||||
shape("mesh", "legacy-a", { importedMesh: mesh }),
|
||||
shape("mesh", "legacy-b", { importedMesh: mesh }),
|
||||
]));
|
||||
const { document } = packageDocument(exported);
|
||||
const restored = await importSkfProject(exported);
|
||||
|
||||
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(1);
|
||||
expect(restored.shapes[0].importedMesh?.positions).toEqual(mesh.positions);
|
||||
expect(restored.shapes[1].importedMesh?.positions).toEqual(mesh.positions);
|
||||
});
|
||||
|
||||
it("migrates the documented v0 JSON project without changing IDs", async () => {
|
||||
const box = shape("box", "legacy-box");
|
||||
const legacy = strToU8(JSON.stringify({
|
||||
schema: SKF_SCHEMA_ID,
|
||||
formatVersion: 0,
|
||||
project: { id: "legacy-project", name: "Legacy", createdAt: 100, modifiedAt: 200 },
|
||||
shapes: [box],
|
||||
workspace: DEFAULT_WORKPLANE_WORKSPACE,
|
||||
snapGrid: "0.5 mm",
|
||||
}));
|
||||
|
||||
const restored = await importSkfProject(legacy);
|
||||
|
||||
expect(restored.migratedFromVersion).toBe(0);
|
||||
expect(restored.sourceProjectId).toBe("legacy-project");
|
||||
expect(restored.shapes[0].id).toBe("legacy-box");
|
||||
expect(restored.snapGrid).toBe("0.5 mm");
|
||||
});
|
||||
|
||||
it("rejects unsupported future versions before restoring any state", async () => {
|
||||
const exported = await exportSkfProject(input([shape("box")]));
|
||||
const future = mutateProject(exported, (document) => {
|
||||
(document as { formatVersion: number }).formatVersion = SKF_FORMAT_VERSION + 1;
|
||||
});
|
||||
|
||||
await expect(importSkfProject(future)).rejects.toThrow("requires a newer SketchForge version");
|
||||
});
|
||||
|
||||
it("rejects missing references, duplicate IDs, cyclic groups, unknown operations, and corrupt assets", async () => {
|
||||
const twoShapes = await exportSkfProject(input([shape("box", "one"), shape("box", "two")]));
|
||||
const missing = mutateProject(twoShapes, (document) => {
|
||||
document.states[0].rootNodeIds[0] = "missing-node";
|
||||
});
|
||||
await expect(importSkfProject(missing)).rejects.toThrow("missing node");
|
||||
|
||||
const duplicate = mutateProject(twoShapes, (document) => {
|
||||
const [first, second] = document.states[0].nodes;
|
||||
second.objectId = first.objectId;
|
||||
second.definition.id = first.objectId;
|
||||
});
|
||||
await expect(importSkfProject(duplicate)).rejects.toThrow("duplicate object ID");
|
||||
|
||||
const grouped = await exportSkfProject(input([shape("mesh", "group-cycle", {
|
||||
groupedShapes: [shape("box", "child-a"), shape("box", "child-b")],
|
||||
})]));
|
||||
const cyclic = mutateProject(grouped, (document) => {
|
||||
const root = document.states[0].nodes.find((node) => node.objectId === "group-cycle")!;
|
||||
root.groupedShapeNodeIds = [root.nodeId];
|
||||
});
|
||||
await expect(importSkfProject(cyclic)).rejects.toThrow("Cyclic group");
|
||||
|
||||
const unknownOperation = mutateProject(grouped, (document) => {
|
||||
document.features[0].type = "unsupported-operation";
|
||||
});
|
||||
await expect(importSkfProject(unknownOperation)).rejects.toThrow("Unknown operation type");
|
||||
|
||||
const legacyMesh = await exportSkfProject(input([shape("mesh", "mesh", {
|
||||
importedMesh: {
|
||||
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
|
||||
baseWidth: 1,
|
||||
baseDepth: 1,
|
||||
baseHeight: 1,
|
||||
triangleCount: 1,
|
||||
sourceFormat: "json",
|
||||
},
|
||||
})]));
|
||||
const { files, document } = packageDocument(legacyMesh);
|
||||
const asset = document.assets.find((entry) => entry.kind === "derived-mesh")!;
|
||||
files[asset.path][20] ^= 0xff;
|
||||
await expect(importSkfProject(zipSync(files))).rejects.toThrow("integrity check");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { toSvgProjection } from "@/lib/svgExport";
|
||||
|
||||
describe("SVG projection export", () => {
|
||||
it("writes an SVG 1.1 document with millimeter dimensions and even-odd contours", () => {
|
||||
const svg = toSvgProjection([
|
||||
{
|
||||
name: "Plate & ring",
|
||||
color: "#d41721",
|
||||
polygons: [
|
||||
[[-5, -3], [5, -3], [5, 3], [-5, 3]],
|
||||
[[-2, -1], [-2, 1], [2, 1], [2, -1]],
|
||||
],
|
||||
},
|
||||
], "Fixture <top>");
|
||||
|
||||
expect(svg).toContain('version="1.1"');
|
||||
expect(svg).toContain('width="10mm" height="6mm" viewBox="-5 -3 10 6"');
|
||||
expect(svg).toContain('fill-rule="evenodd"');
|
||||
expect(svg).toContain('data-name="Plate & ring"');
|
||||
expect(svg).toContain("<title>Fixture <top></title>");
|
||||
expect(svg.match(/M/g)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rejects empty and zero-area projections", () => {
|
||||
expect(() => toSvgProjection([])).toThrow(/no readable contours/i);
|
||||
expect(() => toSvgProjection([{ name: "Line", color: "bad", polygons: [[[0, 0], [1, 0], [2, 0]]] }])).toThrow(/visible area/i);
|
||||
});
|
||||
});
|
||||
@@ -4,12 +4,13 @@ import {
|
||||
MAX_SVG_GEOMETRY_ELEMENTS,
|
||||
analyzeTriangleSoup,
|
||||
buildSvgExtrusionFromPaths,
|
||||
normalizeSvgDocumentType,
|
||||
normalizeSvgUseReferences,
|
||||
validateClosedSolidTriangleSoup,
|
||||
validateSvgSourcePreflight,
|
||||
} from "@/lib/svgImport";
|
||||
|
||||
function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill?: string; fillOpacity?: number; opacity?: number } = {}) {
|
||||
function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill?: string; fillOpacity?: number; opacity?: number; stroke?: string; strokeOpacity?: number; strokeWidth?: number } = {}) {
|
||||
const path = new THREE.ShapePath();
|
||||
path.moveTo(points[0][0], points[0][1]);
|
||||
for (const [x, y] of points.slice(1)) path.lineTo(x, y);
|
||||
@@ -19,6 +20,9 @@ function shapePath(points: Array<[number, number]>, options: { closed?: boolean;
|
||||
fill: options.fill ?? "#000",
|
||||
fillOpacity: options.fillOpacity ?? 1,
|
||||
opacity: options.opacity ?? 1,
|
||||
stroke: options.stroke,
|
||||
strokeOpacity: options.strokeOpacity ?? 1,
|
||||
strokeWidth: options.strokeWidth ?? 1,
|
||||
visibility: "visible",
|
||||
},
|
||||
};
|
||||
@@ -50,11 +54,25 @@ function geometryPositions(geometry: THREE.BufferGeometry) {
|
||||
}
|
||||
|
||||
describe("SVG source preflight", () => {
|
||||
it("rejects XML entities and external references", () => {
|
||||
expect(() => validateSvgSourcePreflight('<!DOCTYPE svg [<!ENTITY x "bad">]><svg/>')).toThrow(/document types and entities/i);
|
||||
it("accepts and removes the standard SVG 1.1 document type", () => {
|
||||
const source = `<?xml version="1.0" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
|
||||
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"/>`;
|
||||
expect(() => validateSvgSourcePreflight(source)).not.toThrow();
|
||||
expect(normalizeSvgDocumentType(source)).not.toMatch(/<!DOCTYPE/i);
|
||||
});
|
||||
|
||||
it("continues to reject XML entities, non-SVG doctypes, and external references", () => {
|
||||
expect(() => validateSvgSourcePreflight('<!DOCTYPE svg [<!ENTITY x "bad">]><svg/>')).toThrow(/entities/i);
|
||||
expect(() => validateSvgSourcePreflight('<!DOCTYPE html><svg/>')).toThrow(/only the standard SVG 1\.1 document type/i);
|
||||
expect(() => validateSvgSourcePreflight('<svg><use href="https://example.com/art.svg#part"/></svg>')).toThrow(/external references/i);
|
||||
});
|
||||
|
||||
it("reports malformed Tinkercad cross-section geometry", () => {
|
||||
expect(() => validateSvgSourcePreflight('<svg width="NaNmm" viewBox="NaN NaN NaN NaN"><path d="z"/></svg>')).toThrow(/workplane intersects the model/i);
|
||||
});
|
||||
|
||||
it("rejects excessive geometry before SVGLoader runs", () => {
|
||||
const source = `<svg>${"<rect width='1' height='1'/>".repeat(MAX_SVG_GEOMETRY_ELEMENTS + 1)}</svg>`;
|
||||
expect(() => validateSvgSourcePreflight(source)).toThrow(/too many geometry elements/i);
|
||||
@@ -85,10 +103,28 @@ describe("SVG path extrusion", () => {
|
||||
});
|
||||
|
||||
it("ignores non-filled and fully transparent paths", () => {
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "none" })])).toThrow(/no readable visible filled paths/i);
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { opacity: 0 })])).toThrow(/no readable visible filled paths/i);
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fillOpacity: 0 })])).toThrow(/no readable visible filled paths/i);
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "#00000000" })])).toThrow(/no readable visible filled paths/i);
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "none" })])).toThrow(/no readable visible/i);
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { opacity: 0 })])).toThrow(/no readable visible/i);
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fillOpacity: 0 })])).toThrow(/no readable visible/i);
|
||||
expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "#00000000" })])).toThrow(/no readable visible/i);
|
||||
});
|
||||
|
||||
it("imports a closed Tinkercad-style stroke as an extrusion profile", () => {
|
||||
const tinkercadOutline = shapePath([[0, 0], [10, 0], [10, 6], [0, 6], [0, 0]], {
|
||||
closed: false,
|
||||
fill: "none",
|
||||
stroke: "rgb(255,0,0)",
|
||||
strokeWidth: 0.001,
|
||||
});
|
||||
const result = buildSvgExtrusionFromPaths([tinkercadOutline]);
|
||||
expect(result.analysis.width).toBeCloseTo(10);
|
||||
expect(result.analysis.depth).toBeCloseTo(6);
|
||||
expect(result.analysis.volume).toBeCloseTo(240);
|
||||
});
|
||||
|
||||
it("explains how to fix an open stroke-only SVG", () => {
|
||||
const openStroke = shapePath([[0, 0], [10, 0], [5, 5]], { closed: false, fill: "none", stroke: "#000", strokeWidth: 1 });
|
||||
expect(() => buildSvgExtrusionFromPaths([openStroke])).toThrow(/only open strokes/i);
|
||||
});
|
||||
|
||||
it("imports open filled contours when they enclose usable area and skips lines", () => {
|
||||
|
||||
Reference in New Issue
Block a user