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
feat: improve shape tools and project previews
This commit is contained in:
@@ -167,7 +167,7 @@ The container listens on port `3000`. It also accepts connections on port `80` f
|
|||||||
|
|
||||||
### Shared Docker Projects
|
### Shared Docker Projects
|
||||||
|
|
||||||
Docker deployments include a shared `.skf` project library. Private projects still autosave in each user's browser. The **Shared** dashboard section lists files stored in `/data/projects`, and **Export → SKF → Save to shared** writes the current project there.
|
Docker deployments include a shared `.skf` project library. Private projects still autosave in each user's browser. The **Shared** dashboard section lists files stored in `/data/projects`, and **Export → SKF → Save to shared** writes the current project there. Revision-matched PNG previews are stored beside the library in `/data/projects/.thumbnails` and appear on shared project cards.
|
||||||
|
|
||||||
Compose uses the persistent `sketchforge-shared-projects` volume by default. To use a directory on the Docker host instead, set `SKETCHFORGE_SHARED_PROJECTS_VOLUME` before starting Compose:
|
Compose uses the persistent `sketchforge-shared-projects` volume by default. To use a directory on the Docker host instead, set `SKETCHFORGE_SHARED_PROJECTS_VOLUME` before starting Compose:
|
||||||
|
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
/// <reference types="next" />
|
/// <reference types="next" />
|
||||||
/// <reference types="next/image-types/global" />
|
/// <reference types="next/image-types/global" />
|
||||||
/// <reference path="./.next/types/routes.d.ts" />
|
/// <reference path="./.next-dev/types/routes.d.ts" />
|
||||||
|
|
||||||
// NOTE: This file should not be edited
|
// NOTE: This file should not be edited
|
||||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||||
@@ -8,6 +8,10 @@ export const runtime = "nodejs";
|
|||||||
export const revalidate = false;
|
export const revalidate = false;
|
||||||
|
|
||||||
const SHARED_PROJECTS_ENV = "SKETCHFORGE_SHARED_PROJECTS_DIR";
|
const SHARED_PROJECTS_ENV = "SKETCHFORGE_SHARED_PROJECTS_DIR";
|
||||||
|
const SHARED_THUMBNAILS_DIR = ".thumbnails";
|
||||||
|
const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024;
|
||||||
|
const MAX_MULTIPART_OVERHEAD_BYTES = 1024 * 1024;
|
||||||
|
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||||
|
|
||||||
type SharedProjectFile = {
|
type SharedProjectFile = {
|
||||||
fileName: string;
|
fileName: string;
|
||||||
@@ -15,6 +19,7 @@ type SharedProjectFile = {
|
|||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
size: number;
|
size: number;
|
||||||
revision: string;
|
revision: string;
|
||||||
|
thumbnailUrl?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function sharedProjectsDirectory() {
|
function sharedProjectsDirectory() {
|
||||||
@@ -36,16 +41,50 @@ function revisionForStat(stat: { size: number; mtimeMs: number }) {
|
|||||||
return `${stat.size.toString(16)}-${Math.round(stat.mtimeMs * 1000).toString(16)}`;
|
return `${stat.size.toString(16)}-${Math.round(stat.mtimeMs * 1000).toString(16)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function projectRecord(fileName: string, stat: { size: number; mtimeMs: number }): SharedProjectFile {
|
function sharedThumbnailPath(root: string, fileName: string, revision: string) {
|
||||||
|
return path.join(root, SHARED_THUMBNAILS_DIR, `${fileName}.${revision}.png`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sharedThumbnailUrl(fileName: string, revision: string) {
|
||||||
|
const query = new URLSearchParams({ fileName, thumbnail: "1", v: revision });
|
||||||
|
return `/api/shared-projects?${query.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function projectRecord(fileName: string, stat: { size: number; mtimeMs: number }, hasThumbnail = false): SharedProjectFile {
|
||||||
|
const revision = revisionForStat(stat);
|
||||||
return {
|
return {
|
||||||
fileName,
|
fileName,
|
||||||
name: fileName.replace(/\.skf$/i, ""),
|
name: fileName.replace(/\.skf$/i, ""),
|
||||||
updatedAt: stat.mtimeMs,
|
updatedAt: stat.mtimeMs,
|
||||||
size: stat.size,
|
size: stat.size,
|
||||||
revision: revisionForStat(stat),
|
revision,
|
||||||
|
...(hasThumbnail ? { thumbnailUrl: sharedThumbnailUrl(fileName, revision) } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isPng(bytes: Uint8Array) {
|
||||||
|
return bytes.byteLength >= PNG_SIGNATURE.byteLength
|
||||||
|
&& PNG_SIGNATURE.every((value, index) => bytes[index] === value);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sharedProjectRequestBytes(request: Request) {
|
||||||
|
const contentType = request.headers.get("content-type") ?? "";
|
||||||
|
if (!contentType.toLowerCase().startsWith("multipart/form-data")) {
|
||||||
|
return { projectBytes: new Uint8Array(await request.arrayBuffer()), thumbnailBytes: null as Uint8Array | null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = await request.formData();
|
||||||
|
const project = formData.get("project");
|
||||||
|
const thumbnail = formData.get("thumbnail");
|
||||||
|
if (!(project instanceof Blob)) throw new Error("Shared project upload is missing its .skf file");
|
||||||
|
if (!(thumbnail instanceof Blob)) throw new Error("Shared project upload is missing its thumbnail");
|
||||||
|
const projectBytes = new Uint8Array(await project.arrayBuffer());
|
||||||
|
const thumbnailBytes = new Uint8Array(await thumbnail.arrayBuffer());
|
||||||
|
if (thumbnailBytes.byteLength > MAX_THUMBNAIL_BYTES) throw new Error("Shared project thumbnail exceeds the 5 MB size limit");
|
||||||
|
if (!isPng(thumbnailBytes)) throw new Error("Shared project thumbnail must be a PNG image");
|
||||||
|
return { projectBytes, thumbnailBytes };
|
||||||
|
}
|
||||||
|
|
||||||
function unquoteEtag(value: string | null) {
|
function unquoteEtag(value: string | null) {
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
return value.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
|
return value.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
|
||||||
@@ -97,6 +136,25 @@ export async function GET(request: Request) {
|
|||||||
const filePath = path.join(root, fileName);
|
const filePath = path.join(root, fileName);
|
||||||
const stat = await regularFileStat(filePath);
|
const stat = await regularFileStat(filePath);
|
||||||
if (!stat) return NextResponse.json({ error: "Shared project was not found" }, { status: 404 });
|
if (!stat) return NextResponse.json({ error: "Shared project was not found" }, { status: 404 });
|
||||||
|
if (requestUrl.searchParams.get("thumbnail") === "1") {
|
||||||
|
const revision = revisionForStat(stat);
|
||||||
|
const requestedRevision = requestUrl.searchParams.get("v");
|
||||||
|
if (requestedRevision && requestedRevision !== revision) {
|
||||||
|
return new NextResponse("Shared project thumbnail revision is stale", { status: 404 });
|
||||||
|
}
|
||||||
|
const imagePath = sharedThumbnailPath(root, fileName, revision);
|
||||||
|
const imageStat = await regularFileStat(imagePath);
|
||||||
|
if (!imageStat) return new NextResponse("Shared project thumbnail was not found", { status: 404 });
|
||||||
|
const image = await fs.readFile(imagePath);
|
||||||
|
return new NextResponse(image, {
|
||||||
|
headers: {
|
||||||
|
"Cache-Control": "public, max-age=31536000, immutable",
|
||||||
|
"Content-Length": String(image.byteLength),
|
||||||
|
"Content-Type": "image/png",
|
||||||
|
ETag: `"${revision}"`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
const bytes = await fs.readFile(filePath);
|
const bytes = await fs.readFile(filePath);
|
||||||
return new Response(bytes, {
|
return new Response(bytes, {
|
||||||
headers: {
|
headers: {
|
||||||
@@ -114,7 +172,10 @@ export async function GET(request: Request) {
|
|||||||
.filter((entry) => entry.isFile() && /\.skf$/i.test(entry.name))
|
.filter((entry) => entry.isFile() && /\.skf$/i.test(entry.name))
|
||||||
.map(async (entry) => {
|
.map(async (entry) => {
|
||||||
const stat = await regularFileStat(path.join(root, entry.name));
|
const stat = await regularFileStat(path.join(root, entry.name));
|
||||||
return stat ? projectRecord(entry.name, stat) : null;
|
if (!stat) return null;
|
||||||
|
const revision = revisionForStat(stat);
|
||||||
|
const thumbnailStat = await regularFileStat(sharedThumbnailPath(root, entry.name, revision));
|
||||||
|
return projectRecord(entry.name, stat, Boolean(thumbnailStat));
|
||||||
}));
|
}));
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ enabled: true, projects: projects.filter((entry): entry is SharedProjectFile => Boolean(entry)).sort((a, b) => b.updatedAt - a.updatedAt) },
|
{ enabled: true, projects: projects.filter((entry): entry is SharedProjectFile => Boolean(entry)).sort((a, b) => b.updatedAt - a.updatedAt) },
|
||||||
@@ -170,7 +231,11 @@ export async function DELETE(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const thumbnailPath = sharedThumbnailPath(root, fileName, currentRevision);
|
||||||
await fs.unlink(filePath);
|
await fs.unlink(filePath);
|
||||||
|
await fs.unlink(thumbnailPath).catch((error) => {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||||
|
});
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ deleted: true, fileName },
|
{ deleted: true, fileName },
|
||||||
{ headers: { "Cache-Control": "no-store" } },
|
{ headers: { "Cache-Control": "no-store" } },
|
||||||
@@ -189,15 +254,18 @@ export async function POST(request: Request) {
|
|||||||
if (!sameOriginRequest(request)) return NextResponse.json({ error: "Shared projects only accept same-origin saves" }, { status: 403 });
|
if (!sameOriginRequest(request)) return NextResponse.json({ error: "Shared projects only accept same-origin saves" }, { status: 403 });
|
||||||
|
|
||||||
const declaredLength = Number(request.headers.get("content-length") ?? 0);
|
const declaredLength = Number(request.headers.get("content-length") ?? 0);
|
||||||
if (Number.isFinite(declaredLength) && declaredLength > SKF_LIMITS.archiveBytes) {
|
const multipartRequest = request.headers.get("content-type")?.toLowerCase().startsWith("multipart/form-data") ?? false;
|
||||||
|
const requestLimit = SKF_LIMITS.archiveBytes + (multipartRequest ? MAX_THUMBNAIL_BYTES + MAX_MULTIPART_OVERHEAD_BYTES : 0);
|
||||||
|
if (Number.isFinite(declaredLength) && declaredLength > requestLimit) {
|
||||||
return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 });
|
return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 });
|
||||||
}
|
}
|
||||||
|
|
||||||
let lockHandle: Awaited<ReturnType<typeof fs.open>> | null = null;
|
let lockHandle: Awaited<ReturnType<typeof fs.open>> | null = null;
|
||||||
let lockPath = "";
|
let lockPath = "";
|
||||||
let temporaryPath = "";
|
let temporaryPath = "";
|
||||||
|
let temporaryThumbnailPath = "";
|
||||||
try {
|
try {
|
||||||
const bytes = new Uint8Array(await request.arrayBuffer());
|
const { projectBytes: bytes, thumbnailBytes } = await sharedProjectRequestBytes(request);
|
||||||
if (bytes.byteLength > SKF_LIMITS.archiveBytes) return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 });
|
if (bytes.byteLength > SKF_LIMITS.archiveBytes) return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 });
|
||||||
const summary = await inspectSkfProjectPackage(bytes);
|
const summary = await inspectSkfProjectPackage(bytes);
|
||||||
const requestUrl = new URL(request.url);
|
const requestUrl = new URL(request.url);
|
||||||
@@ -237,10 +305,31 @@ export async function POST(request: Request) {
|
|||||||
} finally {
|
} finally {
|
||||||
await temporaryHandle.close();
|
await temporaryHandle.close();
|
||||||
}
|
}
|
||||||
|
const pendingStat = await fs.stat(temporaryPath);
|
||||||
|
const savedRevision = revisionForStat(pendingStat);
|
||||||
|
let savedThumbnailPath = "";
|
||||||
|
if (thumbnailBytes) {
|
||||||
|
const thumbnailsRoot = path.join(root, SHARED_THUMBNAILS_DIR);
|
||||||
|
await fs.mkdir(thumbnailsRoot, { recursive: true });
|
||||||
|
savedThumbnailPath = sharedThumbnailPath(root, fileName, savedRevision);
|
||||||
|
temporaryThumbnailPath = path.join(thumbnailsRoot, `.${fileName}.${randomUUID()}.tmp`);
|
||||||
|
const thumbnailHandle = await fs.open(temporaryThumbnailPath, "wx");
|
||||||
|
try {
|
||||||
|
await thumbnailHandle.writeFile(thumbnailBytes);
|
||||||
|
await thumbnailHandle.sync();
|
||||||
|
} finally {
|
||||||
|
await thumbnailHandle.close();
|
||||||
|
}
|
||||||
|
await fs.rename(temporaryThumbnailPath, savedThumbnailPath);
|
||||||
|
temporaryThumbnailPath = "";
|
||||||
|
}
|
||||||
await fs.rename(temporaryPath, filePath);
|
await fs.rename(temporaryPath, filePath);
|
||||||
temporaryPath = "";
|
temporaryPath = "";
|
||||||
const savedStat = await fs.stat(filePath);
|
const savedStat = await fs.stat(filePath);
|
||||||
const project = projectRecord(fileName, savedStat);
|
const project = projectRecord(fileName, savedStat, Boolean(thumbnailBytes));
|
||||||
|
if (currentRevision && currentRevision !== project.revision) {
|
||||||
|
await fs.unlink(sharedThumbnailPath(root, fileName, currentRevision)).catch(() => undefined);
|
||||||
|
}
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ project: { ...project, name: summary.projectName } },
|
{ project: { ...project, name: summary.projectName } },
|
||||||
{ status: currentStat ? 200 : 201, headers: { "Cache-Control": "no-store", ETag: `"${project.revision}"` } },
|
{ status: currentStat ? 200 : 201, headers: { "Cache-Control": "no-store", ETag: `"${project.revision}"` } },
|
||||||
@@ -250,6 +339,7 @@ export async function POST(request: Request) {
|
|||||||
} finally {
|
} finally {
|
||||||
if (lockHandle) await lockHandle.close().catch(() => undefined);
|
if (lockHandle) await lockHandle.close().catch(() => undefined);
|
||||||
if (temporaryPath) await fs.unlink(temporaryPath).catch(() => undefined);
|
if (temporaryPath) await fs.unlink(temporaryPath).catch(() => undefined);
|
||||||
|
if (temporaryThumbnailPath) await fs.unlink(temporaryThumbnailPath).catch(() => undefined);
|
||||||
if (lockPath) await fs.unlink(lockPath).catch(() => undefined);
|
if (lockPath) await fs.unlink(lockPath).catch(() => undefined);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,9 +4,10 @@ import {
|
|||||||
completeSketchForgeMcpCommand,
|
completeSketchForgeMcpCommand,
|
||||||
dispatchSketchForgeMcpCommand,
|
dispatchSketchForgeMcpCommand,
|
||||||
listSketchForgeMcpEditors,
|
listSketchForgeMcpEditors,
|
||||||
pollSketchForgeMcpCommand,
|
|
||||||
registerSketchForgeMcpEditor,
|
registerSketchForgeMcpEditor,
|
||||||
|
waitForSketchForgeMcpCommand,
|
||||||
} from "@/lib/sketchforgeMcpStore";
|
} from "@/lib/sketchforgeMcpStore";
|
||||||
|
import { SKETCHFORGE_MCP_LONG_POLL_TIMEOUT_MS } from "@/lib/sketchforgeMcpProtocol";
|
||||||
|
|
||||||
export const revalidate = false;
|
export const revalidate = false;
|
||||||
|
|
||||||
@@ -81,7 +82,11 @@ export async function POST(request: Request) {
|
|||||||
if (typeof body.editorId !== "string") {
|
if (typeof body.editorId !== "string") {
|
||||||
return NextResponse.json({ error: "Invalid editor poll." }, { status: 400 });
|
return NextResponse.json({ error: "Invalid editor poll." }, { status: 400 });
|
||||||
}
|
}
|
||||||
return NextResponse.json({ command: pollSketchForgeMcpCommand(body.editorId) });
|
const command = await waitForSketchForgeMcpCommand(body.editorId, {
|
||||||
|
timeoutMs: SKETCHFORGE_MCP_LONG_POLL_TIMEOUT_MS,
|
||||||
|
signal: request.signal,
|
||||||
|
});
|
||||||
|
return NextResponse.json({ command });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body.type === "result") {
|
if (body.type === "result") {
|
||||||
|
|||||||
+401
-12
@@ -2288,6 +2288,41 @@ button {
|
|||||||
flex: 1;
|
flex: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.toolbar-project-name {
|
||||||
|
display: flex;
|
||||||
|
min-width: 220px;
|
||||||
|
height: var(--editor-toolbar-tools-height);
|
||||||
|
padding: 0 28px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-project-name-field {
|
||||||
|
display: flex;
|
||||||
|
width: min(420px, 100%);
|
||||||
|
height: 100%;
|
||||||
|
padding: 0;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: transparent;
|
||||||
|
cursor: text;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-project-name-field input {
|
||||||
|
min-width: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 58px;
|
||||||
|
padding: 6px 10px 0;
|
||||||
|
color: #294a63;
|
||||||
|
font: 500 22px/1.1 Arial, Helvetica, sans-serif;
|
||||||
|
text-align: center;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 1px solid rgba(96, 117, 137, 0.28);
|
||||||
|
outline: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.toolbar-icon {
|
.toolbar-icon {
|
||||||
display: grid;
|
display: grid;
|
||||||
width: 43px;
|
width: 43px;
|
||||||
@@ -2572,6 +2607,19 @@ button {
|
|||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.shape-menu-item .sketch-shape-menu-icon {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 42px;
|
||||||
|
height: 42px;
|
||||||
|
padding: 5px;
|
||||||
|
color: #45657d;
|
||||||
|
background: linear-gradient(145deg, #fff, #e9f0f5);
|
||||||
|
border: 1px solid #d2dfe8;
|
||||||
|
border-radius: 6px;
|
||||||
|
stroke-width: 1.7;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
.shape-menu-item span {
|
.shape-menu-item span {
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -3388,7 +3436,7 @@ button {
|
|||||||
width: clamp(210px, 25vw, 330px);
|
width: clamp(210px, 25vw, 330px);
|
||||||
height: clamp(170px, 28vh, 270px);
|
height: clamp(170px, 28vh, 270px);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: rgba(250, 253, 254, 0.94);
|
background: rgba(221, 248, 255, 0.96);
|
||||||
border: 1px solid rgba(166, 190, 204, 0.9);
|
border: 1px solid rgba(166, 190, 204, 0.9);
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
box-shadow: 0 12px 34px rgba(34, 67, 86, 0.16);
|
box-shadow: 0 12px 34px rgba(34, 67, 86, 0.16);
|
||||||
@@ -3411,7 +3459,7 @@ button {
|
|||||||
display: block;
|
display: block;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background: radial-gradient(circle at 50% 48%, rgba(255, 255, 255, 0.98), rgba(229, 240, 245, 0.92));
|
background: radial-gradient(circle at 50% 48%, rgba(221, 248, 255, 0.98), rgba(176, 224, 238, 0.96));
|
||||||
}
|
}
|
||||||
|
|
||||||
.sketch-revolve-preview-empty {
|
.sketch-revolve-preview-empty {
|
||||||
@@ -3474,14 +3522,6 @@ button {
|
|||||||
vector-effect: non-scaling-stroke;
|
vector-effect: non-scaling-stroke;
|
||||||
}
|
}
|
||||||
|
|
||||||
.sketch-profile-hit-targets path {
|
|
||||||
fill: transparent;
|
|
||||||
stroke: transparent;
|
|
||||||
stroke-width: 10;
|
|
||||||
vector-effect: non-scaling-stroke;
|
|
||||||
cursor: move;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sketch-primitive-source {
|
.sketch-primitive-source {
|
||||||
cursor: grab;
|
cursor: grab;
|
||||||
}
|
}
|
||||||
@@ -3571,7 +3611,7 @@ button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.sketch-revolve-guide rect {
|
.sketch-revolve-guide rect {
|
||||||
fill: rgba(248, 251, 252, 0.66);
|
fill: rgba(31, 105, 134, 0.12);
|
||||||
}
|
}
|
||||||
|
|
||||||
.sketch-revolve-guide line {
|
.sketch-revolve-guide line {
|
||||||
@@ -3874,6 +3914,11 @@ button {
|
|||||||
background: #fff0f1;
|
background: #fff0f1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.sketch-image-inspector .inspector-header-icon:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.38;
|
||||||
|
}
|
||||||
|
|
||||||
.sketch-image-preview-card {
|
.sketch-image-preview-card {
|
||||||
display: grid;
|
display: grid;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
@@ -3999,6 +4044,17 @@ button {
|
|||||||
border-color: #90cee2;
|
border-color: #90cee2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.sketch-image-aspect-toggle:disabled,
|
||||||
|
.sketch-image-position-field input:disabled,
|
||||||
|
.sketch-image-number-input:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.52;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sketch-reference-images image.locked {
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
.view-cube {
|
.view-cube {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 22px;
|
top: 22px;
|
||||||
@@ -5748,14 +5804,31 @@ button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.workspace-toggle {
|
.workspace-toggle {
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
align-items: start;
|
||||||
|
column-gap: 16px;
|
||||||
padding-bottom: 16px;
|
padding-bottom: 16px;
|
||||||
border-bottom: 1px solid #e2e9ee;
|
border-bottom: 1px solid #e2e9ee;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.workspace-toggle-copy {
|
||||||
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-toggle-copy small {
|
||||||
|
color: #718697;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 650;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
.workspace-toggle input {
|
.workspace-toggle input {
|
||||||
justify-self: end;
|
justify-self: end;
|
||||||
width: 18px;
|
width: 18px;
|
||||||
height: 18px;
|
height: 18px;
|
||||||
|
margin: 1px 0 0;
|
||||||
accent-color: #0098c7;
|
accent-color: #0098c7;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6066,6 +6139,181 @@ button {
|
|||||||
font-weight: 800;
|
font-weight: 800;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.workspace-shape-picker {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 145px minmax(0, 1fr);
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-picker-control {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 42px minmax(0, 1fr);
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-picker-control img {
|
||||||
|
width: 38px;
|
||||||
|
height: 38px;
|
||||||
|
padding: 4px;
|
||||||
|
object-fit: contain;
|
||||||
|
background: #f3f7f9;
|
||||||
|
border: 1px solid #d5e0e7;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-picker-control select {
|
||||||
|
width: 100%;
|
||||||
|
height: 38px;
|
||||||
|
padding: 0 30px 0 10px;
|
||||||
|
color: #2f4a61;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #cfd9e2;
|
||||||
|
border-radius: 5px;
|
||||||
|
font-weight: 750;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-card {
|
||||||
|
display: grid;
|
||||||
|
gap: 18px;
|
||||||
|
padding: 18px;
|
||||||
|
background: #f8fafc;
|
||||||
|
border: 1px solid #dce5eb;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-card-heading,
|
||||||
|
.workspace-shape-limit {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-card-heading > span,
|
||||||
|
.workspace-shape-limit > span {
|
||||||
|
display: grid;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-card-heading strong,
|
||||||
|
.workspace-shape-limit strong {
|
||||||
|
color: #27445b;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-card-heading small,
|
||||||
|
.workspace-shape-limit small,
|
||||||
|
.workspace-shape-dimensions small,
|
||||||
|
.workspace-shape-specials small {
|
||||||
|
color: #738898;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 650;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-card-heading button {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-height: 32px;
|
||||||
|
padding: 0 10px;
|
||||||
|
color: #3d5d72;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #cfdae2;
|
||||||
|
border-radius: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-card-heading button:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.48;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-dimensions {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-dimensions label {
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
color: #50677a;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-specials {
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
padding-top: 16px;
|
||||||
|
border-top: 1px solid #dce5eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-specials-heading {
|
||||||
|
display: grid;
|
||||||
|
gap: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-specials-heading strong {
|
||||||
|
color: #27445b;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-special-fields {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-special-fields label {
|
||||||
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
gap: 6px;
|
||||||
|
color: #50677a;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-dimensions input,
|
||||||
|
.workspace-shape-special-fields input,
|
||||||
|
.workspace-shape-special-fields select,
|
||||||
|
.workspace-shape-limit input {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
height: 36px;
|
||||||
|
padding: 0 9px;
|
||||||
|
color: #243d56;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #cbd7df;
|
||||||
|
border-radius: 5px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-limit {
|
||||||
|
padding-top: 16px;
|
||||||
|
border-top: 1px solid #dce5eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-limit input {
|
||||||
|
width: 132px;
|
||||||
|
flex: 0 0 132px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-shape-note {
|
||||||
|
margin: -4px 0 0;
|
||||||
|
color: #667e90;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 650;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
.make-default-button {
|
.make-default-button {
|
||||||
min-width: 128px;
|
min-width: 128px;
|
||||||
height: 34px;
|
height: 34px;
|
||||||
@@ -6599,6 +6847,48 @@ button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
|
.workspace-modal {
|
||||||
|
padding-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-modal-card {
|
||||||
|
width: calc(100vw - 16px);
|
||||||
|
height: calc(100vh - var(--editor-toolbar-height) - 24px);
|
||||||
|
max-height: calc(100vh - var(--editor-toolbar-height) - 24px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-modal-layout {
|
||||||
|
grid-template-rows: auto minmax(0, 1fr);
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-settings-nav {
|
||||||
|
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||||
|
gap: 3px;
|
||||||
|
padding: 7px;
|
||||||
|
border-right: 0;
|
||||||
|
border-bottom: 1px solid #d8e1e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-settings-nav button {
|
||||||
|
display: grid;
|
||||||
|
min-height: 52px;
|
||||||
|
place-items: center;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 5px 2px;
|
||||||
|
font-size: 9px;
|
||||||
|
line-height: 1.15;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-modal-body {
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-modal-footer {
|
||||||
|
padding-inline: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
.mode-tabs,
|
.mode-tabs,
|
||||||
.collaborator {
|
.collaborator {
|
||||||
display: none;
|
display: none;
|
||||||
@@ -6653,6 +6943,10 @@ button {
|
|||||||
width: 24px;
|
width: 24px;
|
||||||
height: 24px;
|
height: 24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .workspace-settings-nav {
|
||||||
|
border-bottom-color: #344854;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] {
|
html[data-theme="dark"] {
|
||||||
@@ -6929,6 +7223,15 @@ html[data-theme="dark"] .sketch-toolbar-ribbon {
|
|||||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.035), 0 1px 3px rgba(0, 0, 0, 0.25);
|
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.035), 0 1px 3px rgba(0, 0, 0, 0.25);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .toolbar-project-name-field {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .toolbar-project-name-field input {
|
||||||
|
color: #e0edf5;
|
||||||
|
border-bottom-color: rgba(183, 207, 222, 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] .editor-nav-group,
|
html[data-theme="dark"] .editor-nav-group,
|
||||||
html[data-theme="dark"] .toolbar-section,
|
html[data-theme="dark"] .toolbar-section,
|
||||||
html[data-theme="dark"] .toolbar-mode-content,
|
html[data-theme="dark"] .toolbar-mode-content,
|
||||||
@@ -7021,6 +7324,12 @@ html[data-theme="dark"] .snap-menu .selected {
|
|||||||
background: #253946;
|
background: #253946;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .shape-menu-item .sketch-shape-menu-icon {
|
||||||
|
color: #bcd2df;
|
||||||
|
background: linear-gradient(145deg, #2a3c48, #1d2d37);
|
||||||
|
border-color: #405765;
|
||||||
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] .camera-controls button,
|
html[data-theme="dark"] .camera-controls button,
|
||||||
html[data-theme="dark"] .snap-menu button,
|
html[data-theme="dark"] .snap-menu button,
|
||||||
html[data-theme="dark"] .snap-row {
|
html[data-theme="dark"] .snap-row {
|
||||||
@@ -7040,6 +7349,20 @@ html[data-theme="dark"] .shape-inspector {
|
|||||||
box-shadow: -3px 0 14px rgba(0, 0, 0, 0.28);
|
box-shadow: -3px 0 14px rgba(0, 0, 0, 0.28);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .shape-inspector .edit-sketch-button,
|
||||||
|
html[data-theme="dark"] .shape-inspector .inspector-action-button {
|
||||||
|
color: #d3e2ec;
|
||||||
|
background: #111b23;
|
||||||
|
border-color: #3a4e5c;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .shape-inspector .edit-sketch-button:hover:not(:disabled),
|
||||||
|
html[data-theme="dark"] .shape-inspector .inspector-action-button:hover:not(:disabled) {
|
||||||
|
color: #e0f2fa;
|
||||||
|
background: #1d303b;
|
||||||
|
border-color: #4f7181;
|
||||||
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] .shape-inspector-header,
|
html[data-theme="dark"] .shape-inspector-header,
|
||||||
html[data-theme="dark"] .shape-state-card,
|
html[data-theme="dark"] .shape-state-card,
|
||||||
html[data-theme="dark"] .color-card,
|
html[data-theme="dark"] .color-card,
|
||||||
@@ -7093,6 +7416,11 @@ html[data-theme="dark"] .transform-guides #dimension-arrow path {
|
|||||||
fill: rgba(222, 237, 244, 0.94);
|
fill: rgba(222, 237, 244, 0.94);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .rotate-handle,
|
||||||
|
html[data-theme="dark"] .rotate-handle:hover {
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] .inspector-snap-dock {
|
html[data-theme="dark"] .inspector-snap-dock {
|
||||||
background: linear-gradient(180deg, rgba(20, 30, 39, 0), rgba(20, 30, 39, 0.98) 18px, rgba(20, 30, 39, 0.98));
|
background: linear-gradient(180deg, rgba(20, 30, 39, 0), rgba(20, 30, 39, 0.98) 18px, rgba(20, 30, 39, 0.98));
|
||||||
border-color: #334753;
|
border-color: #334753;
|
||||||
@@ -7172,6 +7500,7 @@ html[data-theme="dark"] .workspace-range small,
|
|||||||
html[data-theme="dark"] .workspace-history-labels,
|
html[data-theme="dark"] .workspace-history-labels,
|
||||||
html[data-theme="dark"] .workspace-history-note,
|
html[data-theme="dark"] .workspace-history-note,
|
||||||
html[data-theme="dark"] .workspace-global-note,
|
html[data-theme="dark"] .workspace-global-note,
|
||||||
|
html[data-theme="dark"] .workspace-toggle-copy small,
|
||||||
html[data-theme="dark"] .workspace-section-heading span {
|
html[data-theme="dark"] .workspace-section-heading span {
|
||||||
color: #91a7b7;
|
color: #91a7b7;
|
||||||
}
|
}
|
||||||
@@ -7195,12 +7524,50 @@ html[data-theme="dark"] .workspace-history-custom {
|
|||||||
|
|
||||||
html[data-theme="dark"] .workspace-select select,
|
html[data-theme="dark"] .workspace-select select,
|
||||||
html[data-theme="dark"] .workspace-dimensions input,
|
html[data-theme="dark"] .workspace-dimensions input,
|
||||||
html[data-theme="dark"] .workspace-history-custom input {
|
html[data-theme="dark"] .workspace-history-custom input,
|
||||||
|
html[data-theme="dark"] .workspace-shape-picker-control select,
|
||||||
|
html[data-theme="dark"] .workspace-shape-dimensions input,
|
||||||
|
html[data-theme="dark"] .workspace-shape-special-fields input,
|
||||||
|
html[data-theme="dark"] .workspace-shape-special-fields select,
|
||||||
|
html[data-theme="dark"] .workspace-shape-limit input {
|
||||||
color: #d8e6ef;
|
color: #d8e6ef;
|
||||||
background: #0f1921;
|
background: #0f1921;
|
||||||
border-color: #3c505d;
|
border-color: #3c505d;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .workspace-shape-picker-control img,
|
||||||
|
html[data-theme="dark"] .workspace-shape-card {
|
||||||
|
background: #111b23;
|
||||||
|
border-color: #344854;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .workspace-shape-card-heading strong,
|
||||||
|
html[data-theme="dark"] .workspace-shape-limit strong,
|
||||||
|
html[data-theme="dark"] .workspace-shape-specials-heading strong {
|
||||||
|
color: #dceaf3;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .workspace-shape-card-heading small,
|
||||||
|
html[data-theme="dark"] .workspace-shape-limit small,
|
||||||
|
html[data-theme="dark"] .workspace-shape-dimensions label,
|
||||||
|
html[data-theme="dark"] .workspace-shape-dimensions small,
|
||||||
|
html[data-theme="dark"] .workspace-shape-special-fields label,
|
||||||
|
html[data-theme="dark"] .workspace-shape-specials small,
|
||||||
|
html[data-theme="dark"] .workspace-shape-note {
|
||||||
|
color: #91a7b7;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .workspace-shape-card-heading button {
|
||||||
|
color: #c8dbe7;
|
||||||
|
background: #1b2a35;
|
||||||
|
border-color: #3c505d;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .workspace-shape-limit,
|
||||||
|
html[data-theme="dark"] .workspace-shape-specials {
|
||||||
|
border-color: #344854;
|
||||||
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] .workspace-color-trigger {
|
html[data-theme="dark"] .workspace-color-trigger {
|
||||||
color: #d4e3ed;
|
color: #d4e3ed;
|
||||||
background: #0f1921;
|
background: #0f1921;
|
||||||
@@ -7281,10 +7648,32 @@ html[data-theme="dark"] .sketch-workspace-stage {
|
|||||||
background: #101820;
|
background: #101820;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .sketch-revolve-preview {
|
||||||
|
background: rgba(17, 33, 43, 0.97);
|
||||||
|
border-color: rgba(73, 126, 149, 0.8);
|
||||||
|
box-shadow: 0 12px 34px rgba(0, 0, 0, 0.38);
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .sketch-revolve-preview-title {
|
||||||
|
color: #b9d7e5;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .sketch-revolve-preview canvas {
|
||||||
|
background: radial-gradient(circle at 50% 48%, rgba(31, 58, 70, 0.98), rgba(12, 24, 32, 0.98));
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .sketch-revolve-preview-empty {
|
||||||
|
color: #9db9c7;
|
||||||
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] .sketch-plate-background {
|
html[data-theme="dark"] .sketch-plate-background {
|
||||||
fill: #18303a;
|
fill: #18303a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .sketch-revolve-guide rect {
|
||||||
|
fill: rgba(3, 10, 15, 0.38);
|
||||||
|
}
|
||||||
|
|
||||||
html[data-theme="dark"] .sketch-plate-border {
|
html[data-theme="dark"] .sketch-plate-border {
|
||||||
stroke: #43b8d7;
|
stroke: #43b8d7;
|
||||||
}
|
}
|
||||||
|
|||||||
+51
-33
@@ -51,6 +51,7 @@ type SharedProject = {
|
|||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
size: number;
|
size: number;
|
||||||
revision: string;
|
revision: string;
|
||||||
|
thumbnailUrl?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type StoredDashboardProject = Partial<DashboardProject> & {
|
type StoredDashboardProject = Partial<DashboardProject> & {
|
||||||
@@ -110,6 +111,7 @@ const PROJECT_SHAPES_STORE_NAME = "projectShapes";
|
|||||||
const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources";
|
const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources";
|
||||||
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
|
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
|
||||||
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
|
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
|
||||||
|
const PROJECT_NAME_TOOLBAR_STORAGE_KEY = "sketchForge.showProjectNameInToolbar";
|
||||||
const ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY = "sketchForge.activeChallengeTutorial";
|
const ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY = "sketchForge.activeChallengeTutorial";
|
||||||
const DISMISSED_UPDATE_VERSION_STORAGE_KEY = "sketchForge.dismissedUpdateVersion";
|
const DISMISSED_UPDATE_VERSION_STORAGE_KEY = "sketchForge.dismissedUpdateVersion";
|
||||||
const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"];
|
const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"];
|
||||||
@@ -509,6 +511,7 @@ export default function Home() {
|
|||||||
const [resolvedTheme, setResolvedTheme] = useState<ResolvedAppTheme>("light");
|
const [resolvedTheme, setResolvedTheme] = useState<ResolvedAppTheme>("light");
|
||||||
const [downloadMode, setDownloadMode] = useState<DownloadMode>("browser");
|
const [downloadMode, setDownloadMode] = useState<DownloadMode>("browser");
|
||||||
const [downloadFolder, setDownloadFolder] = useState("");
|
const [downloadFolder, setDownloadFolder] = useState("");
|
||||||
|
const [showProjectNameInToolbar, setShowProjectNameInToolbar] = useState(true);
|
||||||
const [dashboardNotice, setDashboardNotice] = useState("");
|
const [dashboardNotice, setDashboardNotice] = useState("");
|
||||||
const [sharedProjects, setSharedProjects] = useState<SharedProject[]>([]);
|
const [sharedProjects, setSharedProjects] = useState<SharedProject[]>([]);
|
||||||
const [sharedProjectsEnabled, setSharedProjectsEnabled] = useState(false);
|
const [sharedProjectsEnabled, setSharedProjectsEnabled] = useState(false);
|
||||||
@@ -563,6 +566,7 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
setDownloadMode(!STATIC_EXPORT_BUILD && window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY) === "folder" ? "folder" : "browser");
|
setDownloadMode(!STATIC_EXPORT_BUILD && window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY) === "folder" ? "folder" : "browser");
|
||||||
setDownloadFolder(window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY) ?? "");
|
setDownloadFolder(window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY) ?? "");
|
||||||
|
setShowProjectNameInToolbar(window.localStorage.getItem(PROJECT_NAME_TOOLBAR_STORAGE_KEY) !== "false");
|
||||||
|
|
||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
if (params.has("codexBooleanCase") || params.get("editor") === "1") {
|
if (params.has("codexBooleanCase") || params.get("editor") === "1") {
|
||||||
@@ -723,7 +727,8 @@ export default function Home() {
|
|||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
window.localStorage.setItem(DOWNLOAD_MODE_STORAGE_KEY, downloadMode);
|
window.localStorage.setItem(DOWNLOAD_MODE_STORAGE_KEY, downloadMode);
|
||||||
window.localStorage.setItem(DOWNLOAD_FOLDER_STORAGE_KEY, downloadFolder);
|
window.localStorage.setItem(DOWNLOAD_FOLDER_STORAGE_KEY, downloadFolder);
|
||||||
}, [downloadFolder, downloadMode, mounted]);
|
window.localStorage.setItem(PROJECT_NAME_TOOLBAR_STORAGE_KEY, String(showProjectNameInToolbar));
|
||||||
|
}, [downloadFolder, downloadMode, mounted, showProjectNameInToolbar]);
|
||||||
|
|
||||||
const visibleProjects = useMemo(() => {
|
const visibleProjects = useMemo(() => {
|
||||||
const normalizedQuery = query.trim().toLowerCase();
|
const normalizedQuery = query.trim().toLowerCase();
|
||||||
@@ -781,8 +786,9 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateProjectSnapshot = useCallback((snapshot: { image: string; projectId: string; shapes: number }) => {
|
const updateProjectSnapshot = useCallback(async (snapshot: { image: string; projectId: string; shapes: number }, signal?: AbortSignal) => {
|
||||||
const version = Date.now();
|
const version = Date.now();
|
||||||
|
if (signal?.aborted) throw new DOMException("Thumbnail upload aborted", "AbortError");
|
||||||
if (STATIC_EXPORT_BUILD) {
|
if (STATIC_EXPORT_BUILD) {
|
||||||
setProjects((current) =>
|
setProjects((current) =>
|
||||||
current.map((project) =>
|
current.map((project) =>
|
||||||
@@ -797,34 +803,35 @@ export default function Home() {
|
|||||||
setProjects((current) =>
|
setProjects((current) =>
|
||||||
current.map((project) => (project.id === snapshot.projectId ? { ...project, shapes: snapshot.shapes, updatedAt: version } : project)),
|
current.map((project) => (project.id === snapshot.projectId ? { ...project, shapes: snapshot.shapes, updatedAt: version } : project)),
|
||||||
);
|
);
|
||||||
void fetch("/api/project-thumbnail", {
|
try {
|
||||||
method: "POST",
|
const response = await fetch("/api/project-thumbnail", {
|
||||||
headers: { "Content-Type": "application/json" },
|
method: "POST",
|
||||||
body: JSON.stringify({ dataUrl: snapshot.image, projectId: snapshot.projectId }),
|
headers: { "Content-Type": "application/json" },
|
||||||
})
|
body: JSON.stringify({ dataUrl: snapshot.image, projectId: snapshot.projectId }),
|
||||||
.then(async (response) => {
|
signal,
|
||||||
if (!response.ok) {
|
|
||||||
const payload = await response.json().catch(() => null) as { error?: string } | null;
|
|
||||||
throw new Error(payload?.error ?? "Could not save project thumbnail");
|
|
||||||
}
|
|
||||||
return response.json() as Promise<{ version?: number }>;
|
|
||||||
})
|
|
||||||
.then((payload) => {
|
|
||||||
const nextVersion = payload?.version ?? Date.now();
|
|
||||||
const thumbnailUrl = `/api/project-thumbnail?projectId=${encodeURIComponent(snapshot.projectId)}&v=${nextVersion}`;
|
|
||||||
setProjects((current) =>
|
|
||||||
current.map((project) =>
|
|
||||||
project.id === snapshot.projectId
|
|
||||||
? { ...project, shapes: snapshot.shapes, thumbnailUrl, thumbnailVersion: nextVersion, updatedAt: nextVersion }
|
|
||||||
: project,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
setProjects((current) =>
|
|
||||||
current.map((project) => (project.id === snapshot.projectId ? { ...project, shapes: snapshot.shapes, updatedAt: version } : project)),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const payload = await response.json().catch(() => null) as { error?: string } | null;
|
||||||
|
throw new Error(payload?.error ?? "Could not save project thumbnail");
|
||||||
|
}
|
||||||
|
const payload = await response.json() as { version?: number };
|
||||||
|
if (signal?.aborted) throw new DOMException("Thumbnail upload aborted", "AbortError");
|
||||||
|
const nextVersion = payload?.version ?? Date.now();
|
||||||
|
const thumbnailUrl = `/api/project-thumbnail?projectId=${encodeURIComponent(snapshot.projectId)}&v=${nextVersion}`;
|
||||||
|
setProjects((current) =>
|
||||||
|
current.map((project) =>
|
||||||
|
project.id === snapshot.projectId
|
||||||
|
? { ...project, shapes: snapshot.shapes, thumbnailUrl, thumbnailVersion: nextVersion, updatedAt: nextVersion }
|
||||||
|
: project,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (signal?.aborted || (error instanceof DOMException && error.name === "AbortError")) throw error;
|
||||||
|
setProjects((current) =>
|
||||||
|
current.map((project) => (project.id === snapshot.projectId ? { ...project, shapes: snapshot.shapes, updatedAt: version } : project)),
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const updateProjectShapes = useCallback((snapshot: {
|
const updateProjectShapes = useCallback((snapshot: {
|
||||||
@@ -1027,7 +1034,7 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
}, [refreshSharedProjects]);
|
}, [refreshSharedProjects]);
|
||||||
|
|
||||||
const saveActiveProjectToShared = useCallback(async ({ exportName, bytes }: { exportName: string; bytes: Uint8Array }) => {
|
const saveActiveProjectToShared = useCallback(async ({ exportName, bytes, thumbnailDataUrl }: { exportName: string; bytes: Uint8Array; thumbnailDataUrl: string }) => {
|
||||||
const activeProject = projects.find((project) => project.id === activeProjectId);
|
const activeProject = projects.find((project) => project.id === activeProjectId);
|
||||||
if (!activeProject) throw new Error("Open a local project before saving it to the shared space");
|
if (!activeProject) throw new Error("Open a local project before saving it to the shared space");
|
||||||
const normalizedExportName = exportName.trim() || activeProject.name;
|
const normalizedExportName = exportName.trim() || activeProject.name;
|
||||||
@@ -1035,11 +1042,17 @@ export default function Home() {
|
|||||||
const fileName = saveBackToSource && activeProject.sharedProject
|
const fileName = saveBackToSource && activeProject.sharedProject
|
||||||
? activeProject.sharedProject.fileName
|
? activeProject.sharedProject.fileName
|
||||||
: `${normalizedExportName.replace(/\.skf$/i, "")}.skf`;
|
: `${normalizedExportName.replace(/\.skf$/i, "")}.skf`;
|
||||||
const headers: Record<string, string> = { "Content-Type": "application/vnd.sketchforge.project+zip" };
|
const headers: Record<string, string> = {};
|
||||||
if (saveBackToSource && activeProject.sharedProject) headers["If-Match"] = `"${activeProject.sharedProject.revision}"`;
|
if (saveBackToSource && activeProject.sharedProject) headers["If-Match"] = `"${activeProject.sharedProject.revision}"`;
|
||||||
else headers["If-None-Match"] = "*";
|
else headers["If-None-Match"] = "*";
|
||||||
const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
||||||
const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(fileName)}`, { method: "POST", headers, body });
|
const thumbnailResponse = await fetch(thumbnailDataUrl);
|
||||||
|
const thumbnail = await thumbnailResponse.blob();
|
||||||
|
if (thumbnail.type !== "image/png" || thumbnail.size === 0) throw new Error("Could not prepare the shared project thumbnail");
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("project", new Blob([body], { type: "application/vnd.sketchforge.project+zip" }), fileName);
|
||||||
|
formData.append("thumbnail", thumbnail, `${fileName}.png`);
|
||||||
|
const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(fileName)}`, { method: "POST", headers, body: formData });
|
||||||
const payload = await response.json().catch(() => ({})) as { error?: string; project?: SharedProject };
|
const payload = await response.json().catch(() => ({})) as { error?: string; project?: SharedProject };
|
||||||
if (!response.ok || !payload.project) throw new Error(payload.error ?? "Could not save the shared project");
|
if (!response.ok || !payload.project) throw new Error(payload.error ?? "Could not save the shared project");
|
||||||
const savedProject = payload.project;
|
const savedProject = payload.project;
|
||||||
@@ -1289,8 +1302,13 @@ export default function Home() {
|
|||||||
onProjectShapesChange={updateProjectShapes}
|
onProjectShapesChange={updateProjectShapes}
|
||||||
onProjectSnapshot={updateProjectSnapshot}
|
onProjectSnapshot={updateProjectSnapshot}
|
||||||
onProjectWorkspaceChange={updateProjectWorkspace}
|
onProjectWorkspaceChange={updateProjectWorkspace}
|
||||||
|
onProjectNameChange={(name) => {
|
||||||
|
if (activeProjectId) renameProject(activeProjectId, name);
|
||||||
|
}}
|
||||||
projectId={activeProjectId}
|
projectId={activeProjectId}
|
||||||
projectName={activeProject?.name}
|
projectName={activeProject?.name}
|
||||||
|
showProjectNameInToolbar={showProjectNameInToolbar}
|
||||||
|
onShowProjectNameInToolbarChange={setShowProjectNameInToolbar}
|
||||||
projectCreatedAt={activeProject?.createdAt}
|
projectCreatedAt={activeProject?.createdAt}
|
||||||
projectModifiedAt={activeProject?.updatedAt}
|
projectModifiedAt={activeProject?.updatedAt}
|
||||||
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
|
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
|
||||||
@@ -1745,7 +1763,7 @@ function Dashboard({
|
|||||||
{sharedProjects.map((project, index) => (
|
{sharedProjects.map((project, index) => (
|
||||||
<article className="project-card shared-project-card" key={project.fileName}>
|
<article className="project-card shared-project-card" key={project.fileName}>
|
||||||
<button className="project-card-open" type="button" onClick={() => onOpenSharedProject(project)}>
|
<button className="project-card-open" type="button" onClick={() => onOpenSharedProject(project)}>
|
||||||
<ProjectPreview accent={PROJECT_ACCENTS[index % PROJECT_ACCENTS.length]} />
|
<ProjectPreview accent={PROJECT_ACCENTS[index % PROJECT_ACCENTS.length]} thumbnailUrl={project.thumbnailUrl} />
|
||||||
<span className="project-card-title">{project.name}</span>
|
<span className="project-card-title">{project.name}</span>
|
||||||
<span className="project-card-meta">{formatUpdated(project.updatedAt)} - {formatFileSize(project.size)}</span>
|
<span className="project-card-meta">{formatUpdated(project.updatedAt)} - {formatFileSize(project.size)}</span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ import {
|
|||||||
serializeShapesForSync,
|
serializeShapesForSync,
|
||||||
shapeDepth,
|
shapeDepth,
|
||||||
shapeHasTaper,
|
shapeHasTaper,
|
||||||
|
shapeTransformShouldRemainEditable,
|
||||||
shapeTaperScaleAt,
|
shapeTaperScaleAt,
|
||||||
shapeWidth,
|
shapeWidth,
|
||||||
withHoleMode,
|
withHoleMode,
|
||||||
@@ -88,6 +89,8 @@ import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap
|
|||||||
import { createLocalId } from "@/lib/localIds";
|
import { createLocalId } from "@/lib/localIds";
|
||||||
import { projectExportFileName } from "@/lib/exportNames";
|
import { projectExportFileName } from "@/lib/exportNames";
|
||||||
import { exportMeshesToObj } from "@/lib/objExport";
|
import { exportMeshesToObj } from "@/lib/objExport";
|
||||||
|
import { rotateSketchPoints, selectedClosedSketchPoints } from "@/lib/sketchRotation";
|
||||||
|
import { PROJECT_THUMBNAIL_IDLE_MS, projectThumbnailSceneChanged, type ProjectThumbnailSceneKey } from "@/lib/projectThumbnail";
|
||||||
import { importedShapeFromObj } from "@/lib/objImport";
|
import { importedShapeFromObj } from "@/lib/objImport";
|
||||||
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
||||||
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
|
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
|
||||||
@@ -113,7 +116,8 @@ import {
|
|||||||
} from "@/lib/placementWorkplane";
|
} from "@/lib/placementWorkplane";
|
||||||
import { placeSketchExtrusion } from "@/lib/sketchPlacement";
|
import { placeSketchExtrusion } from "@/lib/sketchPlacement";
|
||||||
import {
|
import {
|
||||||
SKETCHFORGE_MCP_POLL_MS,
|
SKETCHFORGE_MCP_HEARTBEAT_MS,
|
||||||
|
SKETCHFORGE_MCP_POLL_RETRY_MS,
|
||||||
SKETCHFORGE_MCP_ROUTE,
|
SKETCHFORGE_MCP_ROUTE,
|
||||||
type SketchForgeMcpCommand,
|
type SketchForgeMcpCommand,
|
||||||
type SketchForgeMcpSceneSummary,
|
type SketchForgeMcpSceneSummary,
|
||||||
@@ -2375,10 +2379,9 @@ function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimiti
|
|||||||
}
|
}
|
||||||
|
|
||||||
function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
|
function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
|
||||||
// Rotation is a non-destructive transform for editable text. Baking it would
|
// Text and groups must retain their editable source data across transforms.
|
||||||
// change the shape to `kind: "mesh"`, hiding the Text and Font controls even
|
// Baking a group would discard groupedShapes and make Ungroup unavailable.
|
||||||
// though the user never grouped or otherwise converted the object.
|
if (shapeTransformShouldRemainEditable(shape) || !shapeHasTransformToBake(shape)) {
|
||||||
if (shape.kind === "text" || !shapeHasTransformToBake(shape)) {
|
|
||||||
return shape;
|
return shape;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5387,11 +5390,14 @@ export function SketchForgeEditor({
|
|||||||
onProjectShapesChange,
|
onProjectShapesChange,
|
||||||
onProjectSnapshot,
|
onProjectSnapshot,
|
||||||
onProjectWorkspaceChange,
|
onProjectWorkspaceChange,
|
||||||
|
onProjectNameChange,
|
||||||
|
onShowProjectNameInToolbarChange,
|
||||||
projectId,
|
projectId,
|
||||||
projectName = "SketchForge design",
|
projectName = "SketchForge design",
|
||||||
projectCreatedAt = Date.now(),
|
projectCreatedAt = Date.now(),
|
||||||
projectModifiedAt = Date.now(),
|
projectModifiedAt = Date.now(),
|
||||||
projectRevision = 0,
|
projectRevision = 0,
|
||||||
|
showProjectNameInToolbar = true,
|
||||||
sharedProjectsEnabled = false,
|
sharedProjectsEnabled = false,
|
||||||
challengeTutorial = null,
|
challengeTutorial = null,
|
||||||
onChallengeTutorialFinish,
|
onChallengeTutorialFinish,
|
||||||
@@ -5409,7 +5415,7 @@ export function SketchForgeEditor({
|
|||||||
initialPlacementWorkplane?: PlacementWorkplane;
|
initialPlacementWorkplane?: PlacementWorkplane;
|
||||||
onHome?: () => void;
|
onHome?: () => void;
|
||||||
onOpenSkfProjectFile?: (file: File) => Promise<{ ok: boolean; message: string } | void> | { ok: boolean; message: string } | void;
|
onOpenSkfProjectFile?: (file: File) => Promise<{ ok: boolean; message: string } | void> | { ok: boolean; message: string } | void;
|
||||||
onSaveSharedProject?: (request: { exportName: string; bytes: Uint8Array }) => Promise<string>;
|
onSaveSharedProject?: (request: { exportName: string; bytes: Uint8Array; thumbnailDataUrl: string }) => Promise<string>;
|
||||||
onProjectShapesChange?: (snapshot: {
|
onProjectShapesChange?: (snapshot: {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
shapes: WorkplaneShape[];
|
shapes: WorkplaneShape[];
|
||||||
@@ -5424,7 +5430,9 @@ export function SketchForgeEditor({
|
|||||||
placementWorkplane: PlacementWorkplane;
|
placementWorkplane: PlacementWorkplane;
|
||||||
sketchPlacementWorkplane: PlacementWorkplane;
|
sketchPlacementWorkplane: PlacementWorkplane;
|
||||||
}) => void;
|
}) => void;
|
||||||
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void;
|
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }, signal?: AbortSignal) => Promise<void> | void;
|
||||||
|
onProjectNameChange?: (name: string) => void;
|
||||||
|
onShowProjectNameInToolbarChange?: (show: boolean) => void;
|
||||||
onProjectWorkspaceChange?: (snapshot: {
|
onProjectWorkspaceChange?: (snapshot: {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
workspace: WorkplaneWorkspaceSettings;
|
workspace: WorkplaneWorkspaceSettings;
|
||||||
@@ -5438,6 +5446,7 @@ export function SketchForgeEditor({
|
|||||||
projectCreatedAt?: number;
|
projectCreatedAt?: number;
|
||||||
projectModifiedAt?: number;
|
projectModifiedAt?: number;
|
||||||
projectRevision?: number;
|
projectRevision?: number;
|
||||||
|
showProjectNameInToolbar?: boolean;
|
||||||
sharedProjectsEnabled?: boolean;
|
sharedProjectsEnabled?: boolean;
|
||||||
challengeTutorial?: ChallengeTutorialId | null;
|
challengeTutorial?: ChallengeTutorialId | null;
|
||||||
onChallengeTutorialFinish?: () => void;
|
onChallengeTutorialFinish?: () => void;
|
||||||
@@ -5495,6 +5504,7 @@ export function SketchForgeEditor({
|
|||||||
const lastProjectShapesEchoRef = useRef<string | null>(null);
|
const lastProjectShapesEchoRef = useRef<string | null>(null);
|
||||||
const lastProjectIdRef = useRef<string | null>(null);
|
const lastProjectIdRef = useRef<string | null>(null);
|
||||||
const projectSnapshotRunRef = useRef(0);
|
const projectSnapshotRunRef = useRef(0);
|
||||||
|
const lastProjectSnapshotRef = useRef<ProjectThumbnailSceneKey | null>(null);
|
||||||
const shapesRef = useRef(shapes);
|
const shapesRef = useRef(shapes);
|
||||||
const projectAssetsRef = useRef(projectAssets);
|
const projectAssetsRef = useRef(projectAssets);
|
||||||
const selectedIdsRef = useRef(selectedIds);
|
const selectedIdsRef = useRef(selectedIds);
|
||||||
@@ -5947,28 +5957,52 @@ export function SketchForgeEditor({
|
|||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
const runId = projectSnapshotRunRef.current + 1;
|
||||||
|
projectSnapshotRunRef.current = runId;
|
||||||
if (!projectId || !onProjectSnapshot || typeof window === "undefined") {
|
if (!projectId || !onProjectSnapshot || typeof window === "undefined") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const sceneKey = { projectId, fingerprint: projectShapesFingerprint(shapes) };
|
||||||
|
if (lastProjectSnapshotRef.current?.projectId !== projectId || projectHydratingRef.current) {
|
||||||
|
lastProjectSnapshotRef.current = sceneKey;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!projectThumbnailSceneChanged(lastProjectSnapshotRef.current, sceneKey)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (projectInteractionActive) {
|
if (projectInteractionActive) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const runId = projectSnapshotRunRef.current + 1;
|
let stopped = false;
|
||||||
projectSnapshotRunRef.current = runId;
|
let uploadController: AbortController | null = null;
|
||||||
const capture = async () => {
|
const capture = async () => {
|
||||||
if (projectSnapshotRunRef.current !== runId) {
|
if (stopped || projectSnapshotRunRef.current !== runId) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
const image = window.sketchforgeCaptureCanvasAsync
|
const image = window.sketchforgeCaptureCanvasAsync
|
||||||
? await window.sketchforgeCaptureCanvasAsync()
|
? await window.sketchforgeCaptureCanvasAsync()
|
||||||
: window.sketchforgeCaptureCanvas?.() ?? "";
|
: window.sketchforgeCaptureCanvas?.() ?? "";
|
||||||
if (projectSnapshotRunRef.current !== runId) {
|
if (stopped || projectSnapshotRunRef.current !== runId) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (image && image.length > 100) {
|
if (image && image.length > 100) {
|
||||||
onProjectSnapshot({ image, projectId, shapes: shapes.length });
|
const controller = new AbortController();
|
||||||
return true;
|
uploadController = controller;
|
||||||
|
try {
|
||||||
|
await onProjectSnapshot({ image, projectId, shapes: shapes.length }, controller.signal);
|
||||||
|
if (!stopped && projectSnapshotRunRef.current === runId && !controller.signal.aborted) {
|
||||||
|
lastProjectSnapshotRef.current = sceneKey;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
if (controller.signal.aborted || (error instanceof DOMException && error.name === "AbortError")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
if (uploadController === controller) uploadController = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
@@ -5988,8 +6022,10 @@ export function SketchForgeEditor({
|
|||||||
} else {
|
} else {
|
||||||
runCapture();
|
runCapture();
|
||||||
}
|
}
|
||||||
}, 850);
|
}, PROJECT_THUMBNAIL_IDLE_MS);
|
||||||
return () => {
|
return () => {
|
||||||
|
stopped = true;
|
||||||
|
uploadController?.abort();
|
||||||
window.clearTimeout(captureTimer);
|
window.clearTimeout(captureTimer);
|
||||||
if (retryTimer !== null) window.clearTimeout(retryTimer);
|
if (retryTimer !== null) window.clearTimeout(retryTimer);
|
||||||
if (idleId !== null && "cancelIdleCallback" in window) window.cancelIdleCallback(idleId);
|
if (idleId !== null && "cancelIdleCallback" in window) window.cancelIdleCallback(idleId);
|
||||||
@@ -6558,7 +6594,7 @@ export function SketchForgeEditor({
|
|||||||
const label = primitive[0]!.toUpperCase() + primitive.slice(1);
|
const label = primitive[0]!.toUpperCase() + primitive.slice(1);
|
||||||
commitSketchProfile(next, `${label} added to sketch`);
|
commitSketchProfile(next, `${label} added to sketch`);
|
||||||
setSketchActivePointId(null);
|
setSketchActivePointId(null);
|
||||||
setSketchSelection({ kind: "multiple", pointIds: points.map((point) => point.id), segmentIds: segments.map((segment) => segment.id), imageIds: [] });
|
setSketchSelection(null);
|
||||||
setSketchTool("select");
|
setSketchTool("select");
|
||||||
},
|
},
|
||||||
[commitSketchProfile, sketchProfile],
|
[commitSketchProfile, sketchProfile],
|
||||||
@@ -6626,6 +6662,10 @@ export function SketchForgeEditor({
|
|||||||
const updateSketchImage = useCallback((id: string, patch: Partial<SketchImage>, message = "Sketch image updated") => {
|
const updateSketchImage = useCallback((id: string, patch: Partial<SketchImage>, message = "Sketch image updated") => {
|
||||||
const image = (sketchProfile.images ?? []).find((entry) => entry.id === id);
|
const image = (sketchProfile.images ?? []).find((entry) => entry.id === id);
|
||||||
if (!image) return;
|
if (!image) return;
|
||||||
|
if (image.locked && patch.locked !== false) {
|
||||||
|
setNotice("Unlock the sketch image with L before editing it");
|
||||||
|
return;
|
||||||
|
}
|
||||||
commitSketchProfile({
|
commitSketchProfile({
|
||||||
...sketchProfile,
|
...sketchProfile,
|
||||||
images: (sketchProfile.images ?? []).map((entry) => entry.id === id ? { ...entry, ...patch } : entry),
|
images: (sketchProfile.images ?? []).map((entry) => entry.id === id ? { ...entry, ...patch } : entry),
|
||||||
@@ -6635,7 +6675,12 @@ export function SketchForgeEditor({
|
|||||||
}, [commitSketchProfile, sketchProfile]);
|
}, [commitSketchProfile, sketchProfile]);
|
||||||
|
|
||||||
const deleteSketchImage = useCallback((id: string) => {
|
const deleteSketchImage = useCallback((id: string) => {
|
||||||
if (!(sketchProfile.images ?? []).some((image) => image.id === id)) return;
|
const image = (sketchProfile.images ?? []).find((entry) => entry.id === id);
|
||||||
|
if (!image) return;
|
||||||
|
if (image.locked) {
|
||||||
|
setNotice("Unlock the sketch image with L before deleting it");
|
||||||
|
return;
|
||||||
|
}
|
||||||
commitSketchProfile({
|
commitSketchProfile({
|
||||||
...sketchProfile,
|
...sketchProfile,
|
||||||
images: (sketchProfile.images ?? []).filter((image) => image.id !== id),
|
images: (sketchProfile.images ?? []).filter((image) => image.id !== id),
|
||||||
@@ -6665,6 +6710,7 @@ export function SketchForgeEditor({
|
|||||||
depth: dimensions.depth,
|
depth: dimensions.depth,
|
||||||
opacity: 0.55,
|
opacity: 0.55,
|
||||||
lockAspect: true,
|
lockAspect: true,
|
||||||
|
locked: false,
|
||||||
};
|
};
|
||||||
commitSketchProfile({ ...sketchProfile, images: [...(sketchProfile.images ?? []), image] }, `Added ${file.name} to the sketch`);
|
commitSketchProfile({ ...sketchProfile, images: [...(sketchProfile.images ?? []), image] }, `Added ${file.name} to the sketch`);
|
||||||
setSketchSelection({ kind: "image", id: image.id });
|
setSketchSelection({ kind: "image", id: image.id });
|
||||||
@@ -6674,6 +6720,23 @@ export function SketchForgeEditor({
|
|||||||
}
|
}
|
||||||
}, [commitSketchProfile, sketchActive, sketchProfile, sketchTool]);
|
}, [commitSketchProfile, sketchActive, sketchProfile, sketchTool]);
|
||||||
|
|
||||||
|
const toggleSelectedSketchImageLock = useCallback(() => {
|
||||||
|
if (sketchSelection?.kind !== "image") {
|
||||||
|
setNotice("Select a sketch image to lock or unlock");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const image = (sketchProfile.images ?? []).find((entry) => entry.id === sketchSelection.id);
|
||||||
|
if (!image) {
|
||||||
|
setNotice("Select a sketch image to lock or unlock");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updateSketchImage(
|
||||||
|
image.id,
|
||||||
|
{ locked: !image.locked },
|
||||||
|
image.locked ? "Sketch image unlocked" : "Sketch image locked",
|
||||||
|
);
|
||||||
|
}, [sketchProfile.images, sketchSelection, updateSketchImage]);
|
||||||
|
|
||||||
const deleteSelectedSketchEntity = useCallback(() => {
|
const deleteSelectedSketchEntity = useCallback(() => {
|
||||||
if (!sketchSelection) {
|
if (!sketchSelection) {
|
||||||
setNotice("Select a sketch point or segment to remove it");
|
setNotice("Select a sketch point or segment to remove it");
|
||||||
@@ -6723,6 +6786,19 @@ export function SketchForgeEditor({
|
|||||||
}, message);
|
}, message);
|
||||||
}, [commitSketchProfile, sketchProfile]);
|
}, [commitSketchProfile, sketchProfile]);
|
||||||
|
|
||||||
|
const rotateSelectedClosedSketch45 = useCallback(() => {
|
||||||
|
if (sketchSelection?.kind !== "multiple") {
|
||||||
|
setNotice("Select a closed sketch object to rotate");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const selectedPoints = selectedClosedSketchPoints(sketchProfile, sketchSelection);
|
||||||
|
if (!selectedPoints) {
|
||||||
|
setNotice("Rotation is available only for closed sketch objects");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
transformSketchPoints(rotateSketchPoints(selectedPoints), "Rotated closed sketch selection by 45°");
|
||||||
|
}, [sketchProfile, sketchSelection, transformSketchPoints]);
|
||||||
|
|
||||||
const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => {
|
const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => {
|
||||||
const next = cloneSketchProfile(sketchProfile);
|
const next = cloneSketchProfile(sketchProfile);
|
||||||
const point = next.points.find((entry) => entry.id === id);
|
const point = next.points.find((entry) => entry.id === id);
|
||||||
@@ -6873,7 +6949,7 @@ export function SketchForgeEditor({
|
|||||||
|
|
||||||
const addShape = useCallback(
|
const addShape = useCallback(
|
||||||
(asset: ShapeAsset, point?: PlacementPoint) => {
|
(asset: ShapeAsset, point?: PlacementPoint) => {
|
||||||
const shape = makeShapeFromAsset(asset);
|
const shape = makeShapeFromAsset(asset, undefined, workspaceSettingsRef.current.shapeCustomizations[asset.kind]);
|
||||||
const nextShape = {
|
const nextShape = {
|
||||||
...shape,
|
...shape,
|
||||||
...placementPatchForNewShape(shape, placementWorkplane, point ?? placementWorkplane.origin),
|
...placementPatchForNewShape(shape, placementWorkplane, point ?? placementWorkplane.origin),
|
||||||
@@ -8226,6 +8302,8 @@ export function SketchForgeEditor({
|
|||||||
const identity = readMcpEditorIdentity();
|
const identity = readMcpEditorIdentity();
|
||||||
let stopped = false;
|
let stopped = false;
|
||||||
let polling = false;
|
let polling = false;
|
||||||
|
let pollAbortController: AbortController | null = null;
|
||||||
|
let pollRetryTimer: number | null = null;
|
||||||
|
|
||||||
const heartbeat = () => {
|
const heartbeat = () => {
|
||||||
const projectInfo = projectInfoRef.current;
|
const projectInfo = projectInfoRef.current;
|
||||||
@@ -8265,12 +8343,16 @@ export function SketchForgeEditor({
|
|||||||
const poll = async () => {
|
const poll = async () => {
|
||||||
if (polling || stopped) return;
|
if (polling || stopped) return;
|
||||||
polling = true;
|
polling = true;
|
||||||
|
let retry = false;
|
||||||
|
pollAbortController = new AbortController();
|
||||||
try {
|
try {
|
||||||
const response = await fetch(SKETCHFORGE_MCP_ROUTE, {
|
const response = await fetch(SKETCHFORGE_MCP_ROUTE, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ type: "poll", editorId: identity.editorId }),
|
body: JSON.stringify({ type: "poll", editorId: identity.editorId }),
|
||||||
|
signal: pollAbortController.signal,
|
||||||
});
|
});
|
||||||
|
if (!response.ok) throw new Error(`SketchForge MCP poll returned HTTP ${response.status}`);
|
||||||
const payload = (await response.json().catch(() => null)) as { command?: SketchForgeMcpCommand | null } | null;
|
const payload = (await response.json().catch(() => null)) as { command?: SketchForgeMcpCommand | null } | null;
|
||||||
const command = payload?.command;
|
const command = payload?.command;
|
||||||
if (command) {
|
if (command) {
|
||||||
@@ -8281,23 +8363,35 @@ export function SketchForgeEditor({
|
|||||||
submitResult(command.id, false, undefined, error instanceof Error ? error.message : String(error));
|
submitResult(command.id, false, undefined, error instanceof Error ? error.message : String(error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (error) {
|
||||||
// The local bridge may not exist while static builds or tests render the editor.
|
// The local bridge may not exist while static builds or tests render the editor.
|
||||||
|
retry = !stopped && (!(error instanceof DOMException) || error.name !== "AbortError");
|
||||||
} finally {
|
} finally {
|
||||||
|
pollAbortController = null;
|
||||||
polling = false;
|
polling = false;
|
||||||
|
if (!stopped) {
|
||||||
|
if (retry) {
|
||||||
|
pollRetryTimer = window.setTimeout(() => {
|
||||||
|
pollRetryTimer = null;
|
||||||
|
void poll();
|
||||||
|
}, SKETCHFORGE_MCP_POLL_RETRY_MS);
|
||||||
|
} else {
|
||||||
|
void poll();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
heartbeat();
|
heartbeat();
|
||||||
void poll();
|
void poll();
|
||||||
const heartbeatTimer = window.setInterval(heartbeat, 1000);
|
const heartbeatTimer = window.setInterval(heartbeat, SKETCHFORGE_MCP_HEARTBEAT_MS);
|
||||||
const pollTimer = window.setInterval(() => void poll(), SKETCHFORGE_MCP_POLL_MS);
|
|
||||||
window.addEventListener("focus", heartbeat);
|
window.addEventListener("focus", heartbeat);
|
||||||
document.addEventListener("visibilitychange", heartbeat);
|
document.addEventListener("visibilitychange", heartbeat);
|
||||||
return () => {
|
return () => {
|
||||||
stopped = true;
|
stopped = true;
|
||||||
window.clearInterval(heartbeatTimer);
|
window.clearInterval(heartbeatTimer);
|
||||||
window.clearInterval(pollTimer);
|
if (pollRetryTimer !== null) window.clearTimeout(pollRetryTimer);
|
||||||
|
pollAbortController?.abort();
|
||||||
window.removeEventListener("focus", heartbeat);
|
window.removeEventListener("focus", heartbeat);
|
||||||
document.removeEventListener("visibilitychange", heartbeat);
|
document.removeEventListener("visibilitychange", heartbeat);
|
||||||
};
|
};
|
||||||
@@ -8543,10 +8637,16 @@ export function SketchForgeEditor({
|
|||||||
setSkfExporting(true);
|
setSkfExporting(true);
|
||||||
setNotice(target === "shared" ? "Packaging project for Docker shared storage…" : "Packaging editable project, history, and deduplicated assets…");
|
setNotice(target === "shared" ? "Packaging project for Docker shared storage…" : "Packaging editable project, history, and deduplicated assets…");
|
||||||
try {
|
try {
|
||||||
|
const thumbnailDataUrl = target === "shared"
|
||||||
|
? await (window.sketchforgeCaptureCanvasAsync?.() ?? Promise.resolve(""))
|
||||||
|
: "";
|
||||||
|
if (target === "shared" && (!thumbnailDataUrl.startsWith("data:image/png;base64,") || thumbnailDataUrl.length <= 100)) {
|
||||||
|
throw new Error("Could not capture the current project preview");
|
||||||
|
}
|
||||||
const exportedHistory = editorHistoryForExport(historyRef.current, historyIndexRef.current, historyLimit);
|
const exportedHistory = editorHistoryForExport(historyRef.current, historyIndexRef.current, historyLimit);
|
||||||
const bytes = await exportSkfProject({
|
const bytes = await exportSkfProject({
|
||||||
projectId: projectInfoRef.current.projectId,
|
projectId: projectInfoRef.current.projectId,
|
||||||
projectName: exportName.trim() || projectName,
|
projectName,
|
||||||
createdAt: projectCreatedAt,
|
createdAt: projectCreatedAt,
|
||||||
modifiedAt: projectModifiedAt,
|
modifiedAt: projectModifiedAt,
|
||||||
shapes: shapesRef.current,
|
shapes: shapesRef.current,
|
||||||
@@ -8560,7 +8660,7 @@ export function SketchForgeEditor({
|
|||||||
sketchPlacementWorkplane: placementWorkplane,
|
sketchPlacementWorkplane: placementWorkplane,
|
||||||
});
|
});
|
||||||
if (target === "shared" && onSaveSharedProject) {
|
if (target === "shared" && onSaveSharedProject) {
|
||||||
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes }));
|
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes, thumbnailDataUrl }));
|
||||||
} else {
|
} else {
|
||||||
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
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 }));
|
const result = await downloadBlobFile(projectExportFileName(exportName, "skf"), new Blob([buffer], { type: SKF_MEDIA_TYPE }));
|
||||||
@@ -8864,6 +8964,12 @@ export function SketchForgeEditor({
|
|||||||
} else if (shortcut && key === "y") {
|
} else if (shortcut && key === "y") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
sketchRedo();
|
sketchRedo();
|
||||||
|
} else if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r")) {
|
||||||
|
event.preventDefault();
|
||||||
|
rotateSelectedClosedSketch45();
|
||||||
|
} else if (!shortcut && !event.altKey && (event.code === "KeyL" || key === "l")) {
|
||||||
|
event.preventDefault();
|
||||||
|
toggleSelectedSketchImageLock();
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -8953,12 +9059,6 @@ export function SketchForgeEditor({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r") && hasSelection) {
|
|
||||||
event.preventDefault();
|
|
||||||
rotateSelected45();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const step = event.shiftKey ? 5 : 1;
|
const step = event.shiftKey ? 5 : 1;
|
||||||
if (shortcut && event.key === "ArrowUp") {
|
if (shortcut && event.key === "ArrowUp") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -8987,9 +9087,6 @@ export function SketchForgeEditor({
|
|||||||
} else if (key === "s") {
|
} else if (key === "s") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setSelectionHoleMode(false);
|
setSelectionHoleMode(false);
|
||||||
} else if (key === "l") {
|
|
||||||
event.preventDefault();
|
|
||||||
toggleAlignMode();
|
|
||||||
} else if (key === "m") {
|
} else if (key === "m") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
toggleMirrorMode();
|
toggleMirrorMode();
|
||||||
@@ -9013,7 +9110,7 @@ export function SketchForgeEditor({
|
|||||||
pasteShape,
|
pasteShape,
|
||||||
raiseSelected,
|
raiseSelected,
|
||||||
redo,
|
redo,
|
||||||
rotateSelected45,
|
rotateSelectedClosedSketch45,
|
||||||
sketchActive,
|
sketchActive,
|
||||||
sketchRedo,
|
sketchRedo,
|
||||||
sketchMeasurement,
|
sketchMeasurement,
|
||||||
@@ -9021,10 +9118,10 @@ export function SketchForgeEditor({
|
|||||||
sketchUndo,
|
sketchUndo,
|
||||||
setSelectionHoleMode,
|
setSelectionHoleMode,
|
||||||
showHidden,
|
showHidden,
|
||||||
toggleAlignMode,
|
|
||||||
toggleHidden,
|
toggleHidden,
|
||||||
toggleMirrorMode,
|
toggleMirrorMode,
|
||||||
toggleLocked,
|
toggleLocked,
|
||||||
|
toggleSelectedSketchImageLock,
|
||||||
toolbarMode,
|
toolbarMode,
|
||||||
undo,
|
undo,
|
||||||
ungroupSelected,
|
ungroupSelected,
|
||||||
@@ -9034,6 +9131,9 @@ export function SketchForgeEditor({
|
|||||||
<div className="sketchforge-editor">
|
<div className="sketchforge-editor">
|
||||||
<SecondaryToolbar
|
<SecondaryToolbar
|
||||||
toolbarMode={toolbarMode}
|
toolbarMode={toolbarMode}
|
||||||
|
projectName={projectName}
|
||||||
|
onProjectNameChange={onProjectNameChange}
|
||||||
|
showProjectNameInToolbar={showProjectNameInToolbar}
|
||||||
onToolbarModeChange={(mode) => {
|
onToolbarModeChange={(mode) => {
|
||||||
setToolbarMode(mode);
|
setToolbarMode(mode);
|
||||||
setWorkplaneMode(false);
|
setWorkplaneMode(false);
|
||||||
@@ -9161,6 +9261,8 @@ export function SketchForgeEditor({
|
|||||||
initialSnap={snapGrid}
|
initialSnap={snapGrid}
|
||||||
initialWorkspace={workspaceSettings}
|
initialWorkspace={workspaceSettings}
|
||||||
workspaceSettingsKey={projectId ?? "local-workplane"}
|
workspaceSettingsKey={projectId ?? "local-workplane"}
|
||||||
|
showProjectNameInToolbar={showProjectNameInToolbar}
|
||||||
|
onShowProjectNameInToolbarChange={onShowProjectNameInToolbarChange}
|
||||||
onAddShape={addShape}
|
onAddShape={addShape}
|
||||||
onAlignAnchorChange={chooseAlignAnchor}
|
onAlignAnchorChange={chooseAlignAnchor}
|
||||||
onAlignPreview={previewAlignSelection}
|
onAlignPreview={previewAlignSelection}
|
||||||
@@ -9336,8 +9438,18 @@ function SketchReferenceIcon({ name }: { name: SketchReferenceIconName }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sketchShapeMenuItems = [
|
||||||
|
{ primitive: "rectangle", label: "Rectangle", icon: SquareIcon },
|
||||||
|
{ primitive: "circle", label: "Circle", icon: CircleIcon },
|
||||||
|
{ primitive: "triangle", label: "Triangle", icon: TriangleIcon },
|
||||||
|
{ primitive: "hexagon", label: "Hexagon", icon: HexagonIcon },
|
||||||
|
] satisfies Array<{ primitive: SketchPrimitive; label: string; icon: typeof SquareIcon }>;
|
||||||
|
|
||||||
function SecondaryToolbar({
|
function SecondaryToolbar({
|
||||||
toolbarMode,
|
toolbarMode,
|
||||||
|
projectName,
|
||||||
|
onProjectNameChange,
|
||||||
|
showProjectNameInToolbar,
|
||||||
onToolbarModeChange,
|
onToolbarModeChange,
|
||||||
alignMode,
|
alignMode,
|
||||||
canAlign,
|
canAlign,
|
||||||
@@ -9390,6 +9502,9 @@ function SecondaryToolbar({
|
|||||||
onAddShape,
|
onAddShape,
|
||||||
}: {
|
}: {
|
||||||
toolbarMode: ToolbarMode;
|
toolbarMode: ToolbarMode;
|
||||||
|
projectName: string;
|
||||||
|
onProjectNameChange?: (name: string) => void;
|
||||||
|
showProjectNameInToolbar: boolean;
|
||||||
onToolbarModeChange: (mode: ToolbarMode) => void;
|
onToolbarModeChange: (mode: ToolbarMode) => void;
|
||||||
alignMode: boolean;
|
alignMode: boolean;
|
||||||
canAlign: boolean;
|
canAlign: boolean;
|
||||||
@@ -9445,10 +9560,37 @@ function SecondaryToolbar({
|
|||||||
const [sketchCreateOpen, setSketchCreateOpen] = useState(false);
|
const [sketchCreateOpen, setSketchCreateOpen] = useState(false);
|
||||||
const [visibilityOpen, setVisibilityOpen] = useState(false);
|
const [visibilityOpen, setVisibilityOpen] = useState(false);
|
||||||
const [visibilityMenuPosition, setVisibilityMenuPosition] = useState({ top: 0, left: 0 });
|
const [visibilityMenuPosition, setVisibilityMenuPosition] = useState({ top: 0, left: 0 });
|
||||||
|
const shapesMenuRef = useRef<HTMLDivElement>(null);
|
||||||
const sketchCreateMenuRef = useRef<HTMLDivElement>(null);
|
const sketchCreateMenuRef = useRef<HTMLDivElement>(null);
|
||||||
const visibilityMenuRef = useRef<HTMLDivElement>(null);
|
const visibilityMenuRef = useRef<HTMLDivElement>(null);
|
||||||
const touchShapeStartRef = useRef<{ id: string; x: number; y: number } | null>(null);
|
const touchShapeStartRef = useRef<{ id: string; x: number; y: number } | null>(null);
|
||||||
const suppressNextShapeClickRef = useRef(false);
|
const suppressNextShapeClickRef = useRef(false);
|
||||||
|
const cancelProjectNameEditRef = useRef(false);
|
||||||
|
const projectNameFieldRef = useRef<HTMLLabelElement>(null);
|
||||||
|
const projectNameInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [projectNameDraft, setProjectNameDraft] = useState(projectName);
|
||||||
|
useEffect(() => {
|
||||||
|
setProjectNameDraft(projectName);
|
||||||
|
}, [projectName]);
|
||||||
|
useEffect(() => {
|
||||||
|
const finishProjectNameEdit = (event: PointerEvent) => {
|
||||||
|
const input = projectNameInputRef.current;
|
||||||
|
if (input && document.activeElement === input && !projectNameFieldRef.current?.contains(event.target as Node)) {
|
||||||
|
input.blur();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("pointerdown", finishProjectNameEdit, true);
|
||||||
|
return () => document.removeEventListener("pointerdown", finishProjectNameEdit, true);
|
||||||
|
}, []);
|
||||||
|
const commitProjectName = (value: string) => {
|
||||||
|
const nextName = value.trim().slice(0, 80);
|
||||||
|
if (!nextName) {
|
||||||
|
setProjectNameDraft(projectName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setProjectNameDraft(nextName);
|
||||||
|
if (nextName !== projectName) onProjectNameChange?.(nextName);
|
||||||
|
};
|
||||||
const selectToolbarMode = (mode: "geometry" | "sketch") => {
|
const selectToolbarMode = (mode: "geometry" | "sketch") => {
|
||||||
setShapesOpen(false);
|
setShapesOpen(false);
|
||||||
setSketchCreateOpen(false);
|
setSketchCreateOpen(false);
|
||||||
@@ -9460,6 +9602,10 @@ function SecondaryToolbar({
|
|||||||
onAddShape(shape);
|
onAddShape(shape);
|
||||||
setShapesOpen(false);
|
setShapesOpen(false);
|
||||||
};
|
};
|
||||||
|
const addSketchShapeFromMenu = (primitive: SketchPrimitive) => {
|
||||||
|
onSketchPrimitive(primitive);
|
||||||
|
setShapesOpen(false);
|
||||||
|
};
|
||||||
const startSketch = (operation: SketchOperation) => {
|
const startSketch = (operation: SketchOperation) => {
|
||||||
setSketchCreateOpen(false);
|
setSketchCreateOpen(false);
|
||||||
onStartSketch(operation);
|
onStartSketch(operation);
|
||||||
@@ -9481,7 +9627,23 @@ function SecondaryToolbar({
|
|||||||
}, [sketchCreateOpen]);
|
}, [sketchCreateOpen]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (sketchActive) setSketchCreateOpen(false);
|
if (sketchActive) setSketchCreateOpen(false);
|
||||||
|
else setShapesOpen(false);
|
||||||
}, [sketchActive]);
|
}, [sketchActive]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!shapesOpen) return;
|
||||||
|
const closeOnPointerDown = (event: PointerEvent) => {
|
||||||
|
if (!shapesMenuRef.current?.contains(event.target as Node)) setShapesOpen(false);
|
||||||
|
};
|
||||||
|
const closeOnEscape = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") setShapesOpen(false);
|
||||||
|
};
|
||||||
|
window.addEventListener("pointerdown", closeOnPointerDown);
|
||||||
|
window.addEventListener("keydown", closeOnEscape);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("pointerdown", closeOnPointerDown);
|
||||||
|
window.removeEventListener("keydown", closeOnEscape);
|
||||||
|
};
|
||||||
|
}, [shapesOpen]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!visibilityOpen) return;
|
if (!visibilityOpen) return;
|
||||||
const closeOnPointerDown = (event: PointerEvent) => {
|
const closeOnPointerDown = (event: PointerEvent) => {
|
||||||
@@ -9605,7 +9767,7 @@ function SecondaryToolbar({
|
|||||||
<div className="toolbar-section-label">History</div>
|
<div className="toolbar-section-label">History</div>
|
||||||
<div className="toolbar-section-tools">{leftTools.slice(4).map(renderToolButton)}</div>
|
<div className="toolbar-section-tools">{leftTools.slice(4).map(renderToolButton)}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="toolbar-section toolbar-shapes-section">
|
<div className="toolbar-section toolbar-shapes-section" ref={shapesMenuRef}>
|
||||||
<div className="toolbar-section-label">Shapes</div>
|
<div className="toolbar-section-label">Shapes</div>
|
||||||
<div className="toolbar-section-tools">
|
<div className="toolbar-section-tools">
|
||||||
<button
|
<button
|
||||||
@@ -9692,7 +9854,35 @@ function SecondaryToolbar({
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="toolbar-spacer" />
|
{showProjectNameInToolbar ? (
|
||||||
|
<div className="toolbar-spacer toolbar-project-name">
|
||||||
|
<label ref={projectNameFieldRef} className="toolbar-project-name-field" title="Rename project">
|
||||||
|
<input
|
||||||
|
ref={projectNameInputRef}
|
||||||
|
aria-label="Project name"
|
||||||
|
value={projectNameDraft}
|
||||||
|
maxLength={80}
|
||||||
|
spellCheck={false}
|
||||||
|
onChange={(event) => setProjectNameDraft(event.target.value)}
|
||||||
|
onBlur={(event) => {
|
||||||
|
if (cancelProjectNameEditRef.current) {
|
||||||
|
cancelProjectNameEditRef.current = false;
|
||||||
|
setProjectNameDraft(projectName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
commitProjectName(event.currentTarget.value);
|
||||||
|
}}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") event.currentTarget.blur();
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
cancelProjectNameEditRef.current = true;
|
||||||
|
event.currentTarget.blur();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
) : <div className="toolbar-spacer" />}
|
||||||
<div className="tool-group right">
|
<div className="tool-group right">
|
||||||
<div className="toolbar-section compact toolbar-visibility-section" ref={visibilityMenuRef}>
|
<div className="toolbar-section compact toolbar-visibility-section" ref={visibilityMenuRef}>
|
||||||
<div className="toolbar-section-label">Visibility</div>
|
<div className="toolbar-section-label">Visibility</div>
|
||||||
@@ -9784,22 +9974,50 @@ function SecondaryToolbar({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="toolbar-section sketch-shapes-section">
|
<div className="toolbar-section toolbar-shapes-section sketch-shapes-section" ref={shapesMenuRef}>
|
||||||
<div className="toolbar-section-label">Shapes</div>
|
<div className="toolbar-section-label">Shapes</div>
|
||||||
<div className="toolbar-section-tools">
|
<div className="toolbar-section-tools">
|
||||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Rectangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("rectangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "rectangle"); }}>
|
<button
|
||||||
<SquareIcon size={25} strokeWidth={1.8} />
|
className={`shape-menu-trigger ${shapesOpen ? "active" : ""}`}
|
||||||
</button>
|
type="button"
|
||||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Circle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("circle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "circle"); }}>
|
aria-label="Add sketch shape"
|
||||||
<CircleIcon size={25} strokeWidth={1.8} />
|
aria-haspopup="menu"
|
||||||
</button>
|
aria-expanded={shapesOpen}
|
||||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Triangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("triangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "triangle"); }}>
|
onClick={() => {
|
||||||
<TriangleIcon size={25} strokeWidth={1.8} />
|
setSketchCreateOpen(false);
|
||||||
</button>
|
setVisibilityOpen(false);
|
||||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Hexagon" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("hexagon")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "hexagon"); }}>
|
setShapesOpen((open) => !open);
|
||||||
<HexagonIcon size={25} strokeWidth={1.8} />
|
}}
|
||||||
|
>
|
||||||
|
<ToolbarShapeAddIcon />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
{shapesOpen ? (
|
||||||
|
<div className="shape-menu-dropdown sketch-shape-menu-dropdown" role="menu" aria-label="Sketch shapes">
|
||||||
|
<div className="shape-menu-title">Sketch Shapes</div>
|
||||||
|
<div className="shape-menu-list">
|
||||||
|
{sketchShapeMenuItems.map(({ primitive, label, icon: Icon }) => (
|
||||||
|
<button
|
||||||
|
className="shape-menu-item sketch-primitive-source"
|
||||||
|
key={primitive}
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
draggable
|
||||||
|
title={`Add ${label.toLowerCase()} at the sketch origin, or drag it onto the sketch`}
|
||||||
|
onClick={() => addSketchShapeFromMenu(primitive)}
|
||||||
|
onDragStart={(event) => {
|
||||||
|
event.dataTransfer.effectAllowed = "copy";
|
||||||
|
event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", primitive);
|
||||||
|
}}
|
||||||
|
onDragEnd={() => setShapesOpen(false)}
|
||||||
|
>
|
||||||
|
<Icon className="sketch-shape-menu-icon" aria-hidden="true" />
|
||||||
|
<span>{label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="toolbar-section sketch-edit-section">
|
<div className="toolbar-section sketch-edit-section">
|
||||||
<div className="toolbar-section-label">Select</div>
|
<div className="toolbar-section-label">Select</div>
|
||||||
@@ -9958,7 +10176,13 @@ function TopActionPanel({
|
|||||||
}) {
|
}) {
|
||||||
const [exportFormat, setExportFormat] = useState<ExportFormat>("stl");
|
const [exportFormat, setExportFormat] = useState<ExportFormat>("stl");
|
||||||
const [exportName, setExportName] = useState(projectName);
|
const [exportName, setExportName] = useState(projectName);
|
||||||
|
const previousProjectNameRef = useRef(projectName);
|
||||||
const [skfHistoryLimit, setSkfHistoryLimit] = useState<SkfHistoryLimit>("unlimited");
|
const [skfHistoryLimit, setSkfHistoryLimit] = useState<SkfHistoryLimit>("unlimited");
|
||||||
|
useEffect(() => {
|
||||||
|
const previousProjectName = previousProjectNameRef.current;
|
||||||
|
setExportName((current) => current === previousProjectName ? projectName : current);
|
||||||
|
previousProjectNameRef.current = projectName;
|
||||||
|
}, [projectName]);
|
||||||
const skfHistoryLimits: readonly SkfHistoryLimit[] = ["unlimited", 100, 50, 30];
|
const skfHistoryLimits: readonly SkfHistoryLimit[] = ["unlimited", 100, 50, 30];
|
||||||
const skfHistoryLimitIndex = skfHistoryLimits.indexOf(skfHistoryLimit);
|
const skfHistoryLimitIndex = skfHistoryLimits.indexOf(skfHistoryLimit);
|
||||||
const title =
|
const title =
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export function SketchRevolvePreview({ positions }: { positions: number[] | null
|
|||||||
return (
|
return (
|
||||||
<aside className="sketch-revolve-preview" aria-label="Revolve 3D preview">
|
<aside className="sketch-revolve-preview" aria-label="Revolve 3D preview">
|
||||||
<div className="sketch-revolve-preview-title">3D preview</div>
|
<div className="sketch-revolve-preview-title">3D preview</div>
|
||||||
{positions?.length ? <canvas ref={canvasRef} /> : <div className="sketch-revolve-preview-empty">Draw a profile left of the axis</div>}
|
{positions?.length ? <canvas ref={canvasRef} /> : <div className="sketch-revolve-preview-empty">Draw a closed profile left of the axis</div>}
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react";
|
import { ChevronUp, CornerDownRight, Home, Link, Link2Off, LockKeyhole, LockKeyholeOpen, Minus, Plus, Split, Trash2, Waves } from "lucide-react";
|
||||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";
|
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";
|
||||||
import { SnapGridControl } from "@/components/workplane/ShapeInspector";
|
import { SnapGridControl } from "@/components/workplane/ShapeInspector";
|
||||||
import { SketchRevolvePreview } from "@/components/SketchRevolvePreview";
|
import { SketchRevolvePreview } from "@/components/SketchRevolvePreview";
|
||||||
@@ -758,7 +758,7 @@ export function SketchWorkspace({
|
|||||||
minZ: selectedImage.z - selectedImage.depth / 2,
|
minZ: selectedImage.z - selectedImage.depth / 2,
|
||||||
maxZ: selectedImage.z + selectedImage.depth / 2,
|
maxZ: selectedImage.z + selectedImage.depth / 2,
|
||||||
} : null;
|
} : null;
|
||||||
const imageResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedImage && selectedImageBounds ? [
|
const imageResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedImage && selectedImageBounds && !selectedImage.locked ? [
|
||||||
{ id: "nw", x: selectedImageBounds.minX, z: selectedImageBounds.minZ },
|
{ id: "nw", x: selectedImageBounds.minX, z: selectedImageBounds.minZ },
|
||||||
{ id: "n", x: selectedImage.x, z: selectedImageBounds.minZ },
|
{ id: "n", x: selectedImage.x, z: selectedImageBounds.minZ },
|
||||||
{ id: "ne", x: selectedImageBounds.maxX, z: selectedImageBounds.minZ },
|
{ id: "ne", x: selectedImageBounds.maxX, z: selectedImageBounds.minZ },
|
||||||
@@ -770,13 +770,9 @@ export function SketchWorkspace({
|
|||||||
] : [];
|
] : [];
|
||||||
const selectionResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedGeometryBounds ? [
|
const selectionResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedGeometryBounds ? [
|
||||||
{ id: "nw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.minZ },
|
{ id: "nw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.minZ },
|
||||||
{ id: "n", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.minZ },
|
|
||||||
{ id: "ne", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.minZ },
|
{ id: "ne", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.minZ },
|
||||||
{ id: "e", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.cz },
|
|
||||||
{ id: "se", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.maxZ },
|
{ id: "se", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.maxZ },
|
||||||
{ id: "s", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.maxZ },
|
|
||||||
{ id: "sw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.maxZ },
|
{ id: "sw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.maxZ },
|
||||||
{ id: "w", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.cz },
|
|
||||||
] : [];
|
] : [];
|
||||||
const referenceFootprints = useMemo(
|
const referenceFootprints = useMemo(
|
||||||
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
|
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
|
||||||
@@ -839,6 +835,7 @@ export function SketchWorkspace({
|
|||||||
<image
|
<image
|
||||||
key={image.id}
|
key={image.id}
|
||||||
data-sketch-entity="image"
|
data-sketch-entity="image"
|
||||||
|
className={image.locked ? "locked" : undefined}
|
||||||
aria-label={image.name}
|
aria-label={image.name}
|
||||||
href={image.dataUrl}
|
href={image.dataUrl}
|
||||||
x={image.x - image.width / 2}
|
x={image.x - image.width / 2}
|
||||||
@@ -856,6 +853,8 @@ export function SketchWorkspace({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (event.button !== 0 || tool !== "select") return;
|
if (event.button !== 0 || tool !== "select") return;
|
||||||
|
onSelectImage(image.id);
|
||||||
|
if (image.locked) return;
|
||||||
const point = pointFromEvent(event);
|
const point = pointFromEvent(event);
|
||||||
if (!point) return;
|
if (!point) return;
|
||||||
beginEntityDrag(event, {
|
beginEntityDrag(event, {
|
||||||
@@ -903,29 +902,6 @@ export function SketchWorkspace({
|
|||||||
<g className="sketch-profile-fills" pointerEvents="none">
|
<g className="sketch-profile-fills" pointerEvents="none">
|
||||||
{paths.some((path) => path.closed) ? <path d={paths.filter((path) => path.closed).map(pathData).join(" ")} /> : null}
|
{paths.some((path) => path.closed) ? <path d={paths.filter((path) => path.closed).map(pathData).join(" ")} /> : null}
|
||||||
</g>
|
</g>
|
||||||
<g className="sketch-profile-hit-targets" pointerEvents={tool === "select" ? "auto" : "none"}>
|
|
||||||
{paths.filter((path) => path.closed).map((path) => (
|
|
||||||
<path
|
|
||||||
key={`hit-${path.id}`}
|
|
||||||
data-sketch-entity="closed-profile"
|
|
||||||
d={pathData(path)}
|
|
||||||
onPointerDown={(event) => {
|
|
||||||
if (event.button === 1) {
|
|
||||||
beginPan(event);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (event.button !== 0 || tool !== "select") return;
|
|
||||||
const point = pointFromEvent(event);
|
|
||||||
if (!point) return;
|
|
||||||
const pointIds = path.points.map((entry) => entry.id);
|
|
||||||
const segmentIds = path.steps.map((step) => step.segment.id);
|
|
||||||
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
|
||||||
onSelectMany(pointIds, segmentIds, []);
|
|
||||||
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</g>
|
|
||||||
<g className="sketch-segments">
|
<g className="sketch-segments">
|
||||||
{displayProfile.segments.map((segment) => (
|
{displayProfile.segments.map((segment) => (
|
||||||
<path
|
<path
|
||||||
@@ -959,16 +935,7 @@ export function SketchWorkspace({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (event.button === 0 && tool === "select" && point) {
|
else if (event.button === 0 && tool === "select" && point) {
|
||||||
const closedPath = paths.find((path) => path.closed && path.steps.some((step) => step.segment.id === segment.id));
|
onSelectSegment(segment.id);
|
||||||
if (!closedPath) {
|
|
||||||
onSelectSegment(segment.id);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const pointIds = closedPath.points.map((entry) => entry.id);
|
|
||||||
const segmentIds = closedPath.steps.map((step) => step.segment.id);
|
|
||||||
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
|
||||||
onSelectMany(pointIds, segmentIds, []);
|
|
||||||
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
|
|
||||||
} else if (event.button === 0) onSelectSegment(segment.id);
|
} else if (event.button === 0) onSelectSegment(segment.id);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -1130,17 +1097,8 @@ export function SketchWorkspace({
|
|||||||
} else if (tool === "erase" || tool === "refine") {
|
} else if (tool === "erase" || tool === "refine") {
|
||||||
onDeletePoint(point.id);
|
onDeletePoint(point.id);
|
||||||
} else if (event.button === 0 && tool === "select") {
|
} else if (event.button === 0 && tool === "select") {
|
||||||
const closedPath = paths.find((path) => path.closed && path.points.some((entry) => entry.id === point.id));
|
onPointPress(point.id);
|
||||||
if (closedPath) {
|
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
|
||||||
const pointIds = closedPath.points.map((entry) => entry.id);
|
|
||||||
const segmentIds = closedPath.steps.map((step) => step.segment.id);
|
|
||||||
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
|
||||||
onSelectMany(pointIds, segmentIds, []);
|
|
||||||
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: { x: point.x, z: point.z }, current: { x: point.x, z: point.z }, startPoints });
|
|
||||||
} else {
|
|
||||||
onPointPress(point.id);
|
|
||||||
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
|
|
||||||
}
|
|
||||||
} else if (event.button === 0) {
|
} else if (event.button === 0) {
|
||||||
onPointPress(point.id);
|
onPointPress(point.id);
|
||||||
}
|
}
|
||||||
@@ -1270,7 +1228,16 @@ function SketchImageInspector({
|
|||||||
</button>
|
</button>
|
||||||
<strong>{image.name}</strong>
|
<strong>{image.name}</strong>
|
||||||
<div className="inspector-header-actions">
|
<div className="inspector-header-actions">
|
||||||
<button className="inspector-header-icon danger" type="button" aria-label="Delete sketch image" title="Delete image" onClick={onDelete}>
|
<button
|
||||||
|
className={image.locked ? "inspector-header-icon active" : "inspector-header-icon"}
|
||||||
|
type="button"
|
||||||
|
aria-label={image.locked ? "Unlock sketch image" : "Lock sketch image"}
|
||||||
|
title={`${image.locked ? "Unlock" : "Lock"} image (L)`}
|
||||||
|
onClick={() => onUpdate({ locked: !image.locked }, image.locked ? "Sketch image unlocked" : "Sketch image locked")}
|
||||||
|
>
|
||||||
|
{image.locked ? <LockKeyhole size={25} strokeWidth={2.2} /> : <LockKeyholeOpen size={25} strokeWidth={2.2} />}
|
||||||
|
</button>
|
||||||
|
<button className="inspector-header-icon danger" type="button" aria-label="Delete sketch image" title={image.locked ? "Unlock image before deleting" : "Delete image"} onClick={onDelete} disabled={image.locked}>
|
||||||
<Trash2 size={25} strokeWidth={2.2} />
|
<Trash2 size={25} strokeWidth={2.2} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -1282,12 +1249,12 @@ function SketchImageInspector({
|
|||||||
<div className="property-card">
|
<div className="property-card">
|
||||||
<div className="property-card-header static"><span>Properties</span></div>
|
<div className="property-card-header static"><span>Properties</span></div>
|
||||||
<div className="property-list">
|
<div className="property-list">
|
||||||
<SketchImageRange label="Width" value={image.width} min={0.5} max={200} accuracy={accuracy} onChange={updateWidth} />
|
<SketchImageRange label="Width" value={image.width} min={0.5} max={200} accuracy={accuracy} disabled={image.locked} onChange={updateWidth} />
|
||||||
<SketchImageRange label="Height" value={image.depth} min={0.5} max={200} accuracy={accuracy} onChange={updateDepth} />
|
<SketchImageRange label="Height" value={image.depth} min={0.5} max={200} accuracy={accuracy} disabled={image.locked} onChange={updateDepth} />
|
||||||
<SketchImageRange label="Opacity" value={(image.opacity ?? 0.55) * 100} min={5} max={100} accuracy={1} suffix="%" onChange={(opacity) => onUpdate({ opacity: opacity / 100 }, "Sketch image opacity updated")} />
|
<SketchImageRange label="Opacity" value={(image.opacity ?? 0.55) * 100} min={5} max={100} accuracy={1} suffix="%" disabled={image.locked} onChange={(opacity) => onUpdate({ opacity: opacity / 100 }, "Sketch image opacity updated")} />
|
||||||
<SketchImagePositionField label="Position X" value={image.x} accuracy={accuracy} onChange={(x) => onUpdate({ x }, "Sketch image moved")} />
|
<SketchImagePositionField label="Position X" value={image.x} accuracy={accuracy} disabled={image.locked} onChange={(x) => onUpdate({ x }, "Sketch image moved")} />
|
||||||
<SketchImagePositionField label="Position Y" value={image.z} accuracy={accuracy} onChange={(z) => onUpdate({ z }, "Sketch image moved")} />
|
<SketchImagePositionField label="Position Y" value={image.z} accuracy={accuracy} disabled={image.locked} onChange={(z) => onUpdate({ z }, "Sketch image moved")} />
|
||||||
<button className={`sketch-image-aspect-toggle ${image.lockAspect !== false ? "active" : ""}`} type="button" onClick={() => onUpdate({ lockAspect: image.lockAspect === false }, "Image aspect ratio setting updated")}>
|
<button className={`sketch-image-aspect-toggle ${image.lockAspect !== false ? "active" : ""}`} type="button" disabled={image.locked} onClick={() => onUpdate({ lockAspect: image.lockAspect === false }, "Image aspect ratio setting updated")}>
|
||||||
{image.lockAspect !== false ? <Link size={17} /> : <Link2Off size={17} />}
|
{image.lockAspect !== false ? <Link size={17} /> : <Link2Off size={17} />}
|
||||||
<span>{image.lockAspect !== false ? "Aspect ratio locked" : "Aspect ratio unlocked"}</span>
|
<span>{image.lockAspect !== false ? "Aspect ratio locked" : "Aspect ratio unlocked"}</span>
|
||||||
</button>
|
</button>
|
||||||
@@ -1304,6 +1271,7 @@ function SketchImageRange({
|
|||||||
max,
|
max,
|
||||||
accuracy,
|
accuracy,
|
||||||
suffix = "mm",
|
suffix = "mm",
|
||||||
|
disabled = false,
|
||||||
onChange,
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -1312,6 +1280,7 @@ function SketchImageRange({
|
|||||||
max: number;
|
max: number;
|
||||||
accuracy: 1 | 2 | 3;
|
accuracy: 1 | 2 | 3;
|
||||||
suffix?: string;
|
suffix?: string;
|
||||||
|
disabled?: boolean;
|
||||||
onChange: (value: number) => void;
|
onChange: (value: number) => void;
|
||||||
}) {
|
}) {
|
||||||
const safeValue = clamp(Number.isFinite(value) ? value : min, min, max);
|
const safeValue = clamp(Number.isFinite(value) ? value : min, min, max);
|
||||||
@@ -1331,13 +1300,14 @@ function SketchImageRange({
|
|||||||
type="text"
|
type="text"
|
||||||
inputMode="decimal"
|
inputMode="decimal"
|
||||||
value={draft}
|
value={draft}
|
||||||
|
disabled={disabled}
|
||||||
onChange={(event) => setDraft(event.currentTarget.value)}
|
onChange={(event) => setDraft(event.currentTarget.value)}
|
||||||
onBlur={commit}
|
onBlur={commit}
|
||||||
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
||||||
/>
|
/>
|
||||||
<span>{suffix}</span>
|
<span>{suffix}</span>
|
||||||
</div>
|
</div>
|
||||||
<input type="range" min={min} max={max} step={accuracy === 1 ? 0.1 : 0.01} value={safeValue} onChange={(event) => onChange(Number(event.currentTarget.value))} />
|
<input type="range" min={min} max={max} step={accuracy === 1 ? 0.1 : 0.01} value={safeValue} disabled={disabled} onChange={(event) => onChange(Number(event.currentTarget.value))} />
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1346,11 +1316,13 @@ function SketchImagePositionField({
|
|||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
accuracy,
|
accuracy,
|
||||||
|
disabled = false,
|
||||||
onChange,
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
value: number;
|
value: number;
|
||||||
accuracy: 1 | 2 | 3;
|
accuracy: 1 | 2 | 3;
|
||||||
|
disabled?: boolean;
|
||||||
onChange: (value: number) => void;
|
onChange: (value: number) => void;
|
||||||
}) {
|
}) {
|
||||||
const formatted = formatDimension(value, accuracy);
|
const formatted = formatDimension(value, accuracy);
|
||||||
@@ -1370,6 +1342,7 @@ function SketchImagePositionField({
|
|||||||
type="text"
|
type="text"
|
||||||
inputMode="decimal"
|
inputMode="decimal"
|
||||||
value={draft}
|
value={draft}
|
||||||
|
disabled={disabled}
|
||||||
onChange={(event) => setDraft(event.currentTarget.value)}
|
onChange={(event) => setDraft(event.currentTarget.value)}
|
||||||
onBlur={commit}
|
onBlur={commit}
|
||||||
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
||||||
|
|||||||
@@ -42,16 +42,23 @@ import {
|
|||||||
type PlacementWorkplane,
|
type PlacementWorkplane,
|
||||||
} from "@/lib/placementWorkplane";
|
} from "@/lib/placementWorkplane";
|
||||||
import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint";
|
import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint";
|
||||||
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
|
import { projectThumbnailDimensions } from "@/lib/projectThumbnail";
|
||||||
|
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, shapeDimensionLimit, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
|
||||||
import { interiorWorkplaneGridCoordinates, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
|
import { interiorWorkplaneGridCoordinates, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
|
||||||
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeTaperScaleAt, shapeWidth } from "@/lib/workplaneShapes";
|
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeTaperScaleAt, shapeWidth } from "@/lib/workplaneShapes";
|
||||||
import { sphereTessellation } from "@/lib/sphereTessellation";
|
import { sphereTessellation } from "@/lib/sphereTessellation";
|
||||||
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
|
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
|
||||||
import {
|
import {
|
||||||
TransformOverlay,
|
TransformOverlay,
|
||||||
|
continuousSnappedWheelRotation,
|
||||||
getElevationMeasureKey,
|
getElevationMeasureKey,
|
||||||
measureKeyForHandle,
|
measureKeyForHandle,
|
||||||
normalizedRotationPlaneBasis,
|
normalizedRotationPlaneBasis,
|
||||||
|
rotationWheelDirectionSign,
|
||||||
|
ROTATION_WHEEL_SHIFT_SNAP_DEGREES,
|
||||||
|
ROTATION_WHEEL_SNAP_DEGREES,
|
||||||
|
snappedRotationDelta,
|
||||||
|
snappedWheelRotation,
|
||||||
type DimensionMark,
|
type DimensionMark,
|
||||||
type EditingDimension,
|
type EditingDimension,
|
||||||
type EditingRotation,
|
type EditingRotation,
|
||||||
@@ -182,6 +189,8 @@ type WorkplaneViewportProps = {
|
|||||||
initialSnap?: GridSize;
|
initialSnap?: GridSize;
|
||||||
initialWorkspace?: WorkplaneWorkspaceSettings;
|
initialWorkspace?: WorkplaneWorkspaceSettings;
|
||||||
workspaceSettingsKey?: string | null;
|
workspaceSettingsKey?: string | null;
|
||||||
|
showProjectNameInToolbar?: boolean;
|
||||||
|
onShowProjectNameInToolbarChange?: (show: boolean) => void;
|
||||||
onAddShape: (shape: ShapeAsset, point?: PlacementPoint) => void;
|
onAddShape: (shape: ShapeAsset, point?: PlacementPoint) => void;
|
||||||
onAlignAnchorChange: (id: string) => void;
|
onAlignAnchorChange: (id: string) => void;
|
||||||
onAlignPreview: (axis: AlignAxis, target: AlignTarget) => void;
|
onAlignPreview: (axis: AlignAxis, target: AlignTarget) => void;
|
||||||
@@ -439,10 +448,16 @@ type TransformDragState = {
|
|||||||
rotationPivot?: THREE.Vector3;
|
rotationPivot?: THREE.Vector3;
|
||||||
rotationPlaneCenter?: THREE.Vector3;
|
rotationPlaneCenter?: THREE.Vector3;
|
||||||
rotationPlaneView?: RotationPlaneView;
|
rotationPlaneView?: RotationPlaneView;
|
||||||
|
rotationStartPointerAngle?: number;
|
||||||
rotationStartVector?: THREE.Vector3;
|
rotationStartVector?: THREE.Vector3;
|
||||||
rotationScreenCenter?: { x: number; y: number };
|
rotationScreenCenter?: { x: number; y: number };
|
||||||
rotationScreenSign?: number;
|
rotationScreenSign?: number;
|
||||||
rotationStartQuaternion?: THREE.Quaternion;
|
rotationStartQuaternion?: THREE.Quaternion;
|
||||||
|
rotationWheelAppliedDelta?: number;
|
||||||
|
rotationWheelAppliedPointerAngle?: number;
|
||||||
|
rotationWheelDeltaOffset?: number;
|
||||||
|
rotationWheelPointerOffset?: number;
|
||||||
|
rotationWheelSnapDegrees?: number;
|
||||||
wheelCenter?: RotationWheelView;
|
wheelCenter?: RotationWheelView;
|
||||||
hasMoved?: boolean;
|
hasMoved?: boolean;
|
||||||
};
|
};
|
||||||
@@ -630,10 +645,6 @@ function rotationPatchFromQuaternion(quaternion: THREE.Quaternion): Partial<Work
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function shouldPreserveDrawingBufferForLocalAutomation() {
|
|
||||||
return typeof window !== "undefined";
|
|
||||||
}
|
|
||||||
|
|
||||||
function canvasPngDataUrl(canvas: HTMLCanvasElement) {
|
function canvasPngDataUrl(canvas: HTMLCanvasElement) {
|
||||||
return new Promise<string>((resolve) => {
|
return new Promise<string>((resolve) => {
|
||||||
canvas.toBlob((blob) => {
|
canvas.toBlob((blob) => {
|
||||||
@@ -649,6 +660,17 @@ function canvasPngDataUrl(canvas: HTMLCanvasElement) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function thumbnailPngDataUrl(source: HTMLCanvasElement) {
|
||||||
|
const dimensions = projectThumbnailDimensions(source.width, source.height);
|
||||||
|
const thumbnail = document.createElement("canvas");
|
||||||
|
thumbnail.width = dimensions.width;
|
||||||
|
thumbnail.height = dimensions.height;
|
||||||
|
const context = thumbnail.getContext("2d", { alpha: false });
|
||||||
|
if (!context) return Promise.resolve("");
|
||||||
|
context.drawImage(source, 0, 0, dimensions.width, dimensions.height);
|
||||||
|
return canvasPngDataUrl(thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
function rotationScreenSign(axisVector: THREE.Vector3, camera: THREE.Camera) {
|
function rotationScreenSign(axisVector: THREE.Vector3, camera: THREE.Camera) {
|
||||||
const cameraForward = camera.getWorldDirection(new THREE.Vector3());
|
const cameraForward = camera.getWorldDirection(new THREE.Vector3());
|
||||||
return axisVector.dot(cameraForward) >= 0 ? 1 : -1;
|
return axisVector.dot(cameraForward) >= 0 ? 1 : -1;
|
||||||
@@ -1978,6 +2000,7 @@ function resizeShapeFromFrameHandle(
|
|||||||
shiftKey: boolean,
|
shiftKey: boolean,
|
||||||
altKey: boolean,
|
altKey: boolean,
|
||||||
step: number,
|
step: number,
|
||||||
|
maxSize: number,
|
||||||
): Partial<WorkplaneShape> {
|
): Partial<WorkplaneShape> {
|
||||||
const shape = transform.startShape;
|
const shape = transform.startShape;
|
||||||
const frame = transform.selectionFrame;
|
const frame = transform.selectionFrame;
|
||||||
@@ -1986,8 +2009,6 @@ function resizeShapeFromFrameHandle(
|
|||||||
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
|
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
|
||||||
|
|
||||||
const signs = transform.scaleSigns ?? resizeSignsForHandle(handleKey);
|
const signs = transform.scaleSigns ?? resizeSignsForHandle(handleKey);
|
||||||
const maxSize = 220;
|
|
||||||
|
|
||||||
const axisResize = (current: number, delta: number, sign: number) => {
|
const axisResize = (current: number, delta: number, sign: number) => {
|
||||||
if (!sign) {
|
if (!sign) {
|
||||||
return current;
|
return current;
|
||||||
@@ -2203,6 +2224,7 @@ function resizeSelectionFromHandle(
|
|||||||
shiftKey: boolean,
|
shiftKey: boolean,
|
||||||
altKey: boolean,
|
altKey: boolean,
|
||||||
step: number,
|
step: number,
|
||||||
|
maxSize: number,
|
||||||
) {
|
) {
|
||||||
const frame = transform.selectionFrame;
|
const frame = transform.selectionFrame;
|
||||||
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
|
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
|
||||||
@@ -2213,11 +2235,11 @@ function resizeSelectionFromHandle(
|
|||||||
}
|
}
|
||||||
const signedDelta = sign * delta;
|
const signedDelta = sign * delta;
|
||||||
if (altKey) {
|
if (altKey) {
|
||||||
const size = snapDimension(current + signedDelta * 2, step, MIN_SHAPE_SIZE, 260);
|
const size = snapDimension(current + signedDelta * 2, step, MIN_SHAPE_SIZE, maxSize);
|
||||||
return { size, scale: size / Math.max(MIN_SHAPE_SIZE, current) };
|
return { size, scale: size / Math.max(MIN_SHAPE_SIZE, current) };
|
||||||
}
|
}
|
||||||
const rawSize = current + signedDelta;
|
const rawSize = current + signedDelta;
|
||||||
const size = snapDimension(rawSize, step, MIN_SHAPE_SIZE, 260);
|
const size = snapDimension(rawSize, step, MIN_SHAPE_SIZE, maxSize);
|
||||||
return {
|
return {
|
||||||
size,
|
size,
|
||||||
scale: size / Math.max(MIN_SHAPE_SIZE, current),
|
scale: size / Math.max(MIN_SHAPE_SIZE, current),
|
||||||
@@ -2228,9 +2250,9 @@ function resizeSelectionFromHandle(
|
|||||||
let nextZ = axisResize(frame.depth, localDelta.z, signs.z);
|
let nextZ = axisResize(frame.depth, localDelta.z, signs.z);
|
||||||
if (shiftKey && signs.x && signs.z) {
|
if (shiftKey && signs.x && signs.z) {
|
||||||
const scale = proportionalResizeScale(frame.width, frame.depth, nextX.size, nextZ.size);
|
const scale = proportionalResizeScale(frame.width, frame.depth, nextX.size, nextZ.size);
|
||||||
const limitedScale = clamp(scale, MIN_SHAPE_SIZE / Math.max(MIN_SHAPE_SIZE, Math.min(frame.width, frame.depth)), 260 / Math.max(frame.width, frame.depth));
|
const limitedScale = clamp(scale, MIN_SHAPE_SIZE / Math.max(MIN_SHAPE_SIZE, Math.min(frame.width, frame.depth)), maxSize / Math.max(frame.width, frame.depth));
|
||||||
const width = snapDimension(frame.width * limitedScale, step, MIN_SHAPE_SIZE, 260);
|
const width = snapDimension(frame.width * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
|
||||||
const depth = snapDimension(frame.depth * limitedScale, step, MIN_SHAPE_SIZE, 260);
|
const depth = snapDimension(frame.depth * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
|
||||||
nextX = {
|
nextX = {
|
||||||
size: width,
|
size: width,
|
||||||
scale: width / Math.max(MIN_SHAPE_SIZE, frame.width),
|
scale: width / Math.max(MIN_SHAPE_SIZE, frame.width),
|
||||||
@@ -2252,8 +2274,8 @@ function resizeSelectionFromHandle(
|
|||||||
.add(frame.xAxis.clone().multiplyScalar(localCenter.x * nextX.scale))
|
.add(frame.xAxis.clone().multiplyScalar(localCenter.x * nextX.scale))
|
||||||
.add(frame.yAxis.clone().multiplyScalar(localCenter.y))
|
.add(frame.yAxis.clone().multiplyScalar(localCenter.y))
|
||||||
.add(frame.zAxis.clone().multiplyScalar(localCenter.z * nextZ.scale));
|
.add(frame.zAxis.clone().multiplyScalar(localCenter.z * nextZ.scale));
|
||||||
const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, 260);
|
const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, maxSize);
|
||||||
const depth = snapDimension(shapeDepth(item.startShape) * nextZ.scale, step, MIN_SHAPE_SIZE, 260);
|
const depth = snapDimension(shapeDepth(item.startShape) * nextZ.scale, step, MIN_SHAPE_SIZE, maxSize);
|
||||||
const actualScaleX = width / Math.max(MIN_SHAPE_SIZE, shapeWidth(item.startShape));
|
const actualScaleX = width / Math.max(MIN_SHAPE_SIZE, shapeWidth(item.startShape));
|
||||||
const actualScaleZ = depth / Math.max(MIN_SHAPE_SIZE, shapeDepth(item.startShape));
|
const actualScaleZ = depth / Math.max(MIN_SHAPE_SIZE, shapeDepth(item.startShape));
|
||||||
const patch = {
|
const patch = {
|
||||||
@@ -2283,6 +2305,8 @@ export function WorkplaneViewport({
|
|||||||
initialSnap,
|
initialSnap,
|
||||||
initialWorkspace,
|
initialWorkspace,
|
||||||
workspaceSettingsKey,
|
workspaceSettingsKey,
|
||||||
|
showProjectNameInToolbar = true,
|
||||||
|
onShowProjectNameInToolbarChange,
|
||||||
onAddShape,
|
onAddShape,
|
||||||
onAlignAnchorChange,
|
onAlignAnchorChange,
|
||||||
onAlignPreview,
|
onAlignPreview,
|
||||||
@@ -2835,7 +2859,7 @@ export function WorkplaneViewport({
|
|||||||
window.sketchforgeCaptureCanvasAsync = () => {
|
window.sketchforgeCaptureCanvasAsync = () => {
|
||||||
state.camera.updateMatrixWorld();
|
state.camera.updateMatrixWorld();
|
||||||
state.renderer.render(state.scene, state.camera);
|
state.renderer.render(state.scene, state.camera);
|
||||||
return canvasPngDataUrl(state.renderer.domElement);
|
return thumbnailPngDataUrl(state.renderer.domElement);
|
||||||
};
|
};
|
||||||
window.sketchforgeCaptureView = (face = "current") => {
|
window.sketchforgeCaptureView = (face = "current") => {
|
||||||
if (face === "home") {
|
if (face === "home") {
|
||||||
@@ -3354,6 +3378,9 @@ export function WorkplaneViewport({
|
|||||||
const rotationCenter = kind === "rotate" ? wheel ?? (state ? projectToScreen(pivot, state) : { x: localClientX, y: localClientY }) : undefined;
|
const rotationCenter = kind === "rotate" ? wheel ?? (state ? projectToScreen(pivot, state) : { x: localClientX, y: localClientY }) : undefined;
|
||||||
const rotationStartPoint = kind === "rotate" && state ? rayPointOnRotationPlane(state, event.clientX, event.clientY, rotationPlaneCenter, axisVector) : null;
|
const rotationStartPoint = kind === "rotate" && state ? rayPointOnRotationPlane(state, event.clientX, event.clientY, rotationPlaneCenter, axisVector) : null;
|
||||||
const rotationStartVector = rotationStartPoint ? rotationStartPoint.sub(rotationPlaneCenter) : undefined;
|
const rotationStartVector = rotationStartPoint ? rotationStartPoint.sub(rotationPlaneCenter) : undefined;
|
||||||
|
const rotationStartPointerAngle = kind === "rotate"
|
||||||
|
? rotationPlanePointerAngle(rotationPlane, localClientX, localClientY, rotationCenter ?? { x: localClientX, y: localClientY })
|
||||||
|
: undefined;
|
||||||
const scalePlane = kind === "scale"
|
const scalePlane = kind === "scale"
|
||||||
? localResizePlaneForFrame(frame, workplaneFootprintY(frame, activeWorkplane))
|
? localResizePlaneForFrame(frame, workplaneFootprintY(frame, activeWorkplane))
|
||||||
: undefined;
|
: undefined;
|
||||||
@@ -3430,6 +3457,7 @@ export function WorkplaneViewport({
|
|||||||
rotationPivot: kind === "rotate" ? pivot : undefined,
|
rotationPivot: kind === "rotate" ? pivot : undefined,
|
||||||
rotationPlaneCenter: kind === "rotate" ? rotationPlaneCenter : undefined,
|
rotationPlaneCenter: kind === "rotate" ? rotationPlaneCenter : undefined,
|
||||||
rotationPlaneView: kind === "rotate" ? rotationPlane : undefined,
|
rotationPlaneView: kind === "rotate" ? rotationPlane : undefined,
|
||||||
|
rotationStartPointerAngle,
|
||||||
rotationStartVector: kind === "rotate" ? rotationStartVector : undefined,
|
rotationStartVector: kind === "rotate" ? rotationStartVector : undefined,
|
||||||
rotationScreenCenter: rotationCenter,
|
rotationScreenCenter: rotationCenter,
|
||||||
rotationScreenSign: kind === "rotate" && state ? rotationScreenSign(axisVector, state.camera) : 1,
|
rotationScreenSign: kind === "rotate" && state ? rotationScreenSign(axisVector, state.camera) : 1,
|
||||||
@@ -3558,10 +3586,11 @@ export function WorkplaneViewport({
|
|||||||
: 0;
|
: 0;
|
||||||
const resizingFromBottom = transform.handleKey === "bottom-height";
|
const resizingFromBottom = transform.handleKey === "bottom-height";
|
||||||
const rawFrameHeight = transform.selectionFrame.height + (resizingFromBottom ? -rawDelta : rawDelta);
|
const rawFrameHeight = transform.selectionFrame.height + (resizingFromBottom ? -rawDelta : rawDelta);
|
||||||
|
const maxHeight = Math.max(...transform.items.map((item) => shapeDimensionLimit(workspaceRef.current, item.startShape.kind, 180)));
|
||||||
const nextFrameHeight = clamp(
|
const nextFrameHeight = clamp(
|
||||||
transform.selectionFrame.height + snapValue(rawFrameHeight - transform.selectionFrame.height, step),
|
transform.selectionFrame.height + snapValue(rawFrameHeight - transform.selectionFrame.height, step),
|
||||||
MIN_SHAPE_SIZE,
|
MIN_SHAPE_SIZE,
|
||||||
180,
|
maxHeight,
|
||||||
);
|
);
|
||||||
transform.items.forEach((item) => {
|
transform.items.forEach((item) => {
|
||||||
onUpdateShape(
|
onUpdateShape(
|
||||||
@@ -3611,10 +3640,12 @@ export function WorkplaneViewport({
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (transform.items.length === 1) {
|
if (transform.items.length === 1) {
|
||||||
const next = resizeShapeFromFrameHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step);
|
const maxSize = shapeDimensionLimit(workspaceRef.current, transform.startShape.kind, 220);
|
||||||
|
const next = resizeShapeFromFrameHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step, maxSize);
|
||||||
onUpdateShape(transform.id, next);
|
onUpdateShape(transform.id, next);
|
||||||
} else {
|
} else {
|
||||||
resizeSelectionFromHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step).forEach(({ id, patch }) => onUpdateShape(id, patch));
|
const maxSize = Math.max(...transform.items.map((item) => shapeDimensionLimit(workspaceRef.current, item.startShape.kind, 260)));
|
||||||
|
resizeSelectionFromHandle(transform, worldPoint, transform.handleKey, shiftKey, altKey, step, maxSize).forEach(({ id, patch }) => onUpdateShape(id, patch));
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -3647,14 +3678,43 @@ export function WorkplaneViewport({
|
|||||||
transform.wheelCenter
|
transform.wheelCenter
|
||||||
&& Math.hypot(localClientX - transform.wheelCenter.x, localClientY - transform.wheelCenter.y) <= transform.wheelCenter.radius
|
&& Math.hypot(localClientX - transform.wheelCenter.x, localClientY - transform.wheelCenter.y) <= transform.wheelCenter.radius
|
||||||
);
|
);
|
||||||
let delta: number;
|
const rawPointerAngle = rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter);
|
||||||
if (shiftKey) {
|
const wheelSnapDegrees = shiftKey ? ROTATION_WHEEL_SHIFT_SNAP_DEGREES : ROTATION_WHEEL_SNAP_DEGREES;
|
||||||
delta = Math.round(rawDelta / 45) * 45;
|
const wheelScreenSign = rotationWheelDirectionSign(transform.rotationScreenSign ?? 1);
|
||||||
} else if (insideSnapWheel) {
|
const snappedWheel = insideSnapWheel
|
||||||
delta = Math.round(rawDelta / 22.5) * 22.5;
|
? snappedWheelRotation(
|
||||||
|
rawPointerAngle,
|
||||||
|
transform.rotationStartPointerAngle
|
||||||
|
?? rawPointerAngle - rawDelta * (transform.rotationScreenSign ?? 1),
|
||||||
|
wheelScreenSign,
|
||||||
|
wheelSnapDegrees,
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
const wheelRotation = snappedWheel
|
||||||
|
? continuousSnappedWheelRotation(
|
||||||
|
snappedWheel,
|
||||||
|
wheelSnapDegrees,
|
||||||
|
transform.rotationWheelSnapDegrees,
|
||||||
|
transform.rotationWheelAppliedDelta,
|
||||||
|
transform.rotationWheelAppliedPointerAngle,
|
||||||
|
transform.rotationWheelDeltaOffset,
|
||||||
|
transform.rotationWheelPointerOffset,
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
if (wheelRotation) {
|
||||||
|
transform.rotationWheelSnapDegrees = wheelSnapDegrees;
|
||||||
|
transform.rotationWheelDeltaOffset = wheelRotation.deltaOffset;
|
||||||
|
transform.rotationWheelPointerOffset = wheelRotation.pointerOffset;
|
||||||
|
transform.rotationWheelAppliedDelta = wheelRotation.delta;
|
||||||
|
transform.rotationWheelAppliedPointerAngle = wheelRotation.pointerAngle;
|
||||||
} else {
|
} else {
|
||||||
delta = Math.round(rawDelta);
|
transform.rotationWheelSnapDegrees = undefined;
|
||||||
|
transform.rotationWheelDeltaOffset = undefined;
|
||||||
|
transform.rotationWheelPointerOffset = undefined;
|
||||||
|
transform.rotationWheelAppliedDelta = undefined;
|
||||||
|
transform.rotationWheelAppliedPointerAngle = undefined;
|
||||||
}
|
}
|
||||||
|
const delta = wheelRotation?.delta ?? snappedRotationDelta(rawDelta, false, shiftKey);
|
||||||
|
|
||||||
const deltaQuaternion = new THREE.Quaternion().setFromAxisAngle(axisVector, THREE.MathUtils.degToRad(delta));
|
const deltaQuaternion = new THREE.Quaternion().setFromAxisAngle(axisVector, THREE.MathUtils.degToRad(delta));
|
||||||
const rotationDelta = deltaQuaternion.clone();
|
const rotationDelta = deltaQuaternion.clone();
|
||||||
@@ -3664,7 +3724,7 @@ export function WorkplaneViewport({
|
|||||||
y: transform.wheelCenter ? transform.wheelCenter.y - 92 : localClientY - 18,
|
y: transform.wheelCenter ? transform.wheelCenter.y - 92 : localClientY - 18,
|
||||||
text: `${Number(delta.toFixed(1))}°`,
|
text: `${Number(delta.toFixed(1))}°`,
|
||||||
angle: delta,
|
angle: delta,
|
||||||
pointerAngle: rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter),
|
pointerAngle: wheelRotation?.pointerAngle ?? rawPointerAngle,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
transform.items.forEach((item) => {
|
transform.items.forEach((item) => {
|
||||||
@@ -3798,7 +3858,8 @@ export function WorkplaneViewport({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (Number.isFinite(value) && value > 0) {
|
if (Number.isFinite(value) && value > 0) {
|
||||||
const nextValue = Math.max(MIN_SHAPE_SIZE, value);
|
const customLimit = workspaceRef.current.shapeCustomizations[shape.kind]?.maxDimension;
|
||||||
|
const nextValue = Math.min(customLimit ?? Number.POSITIVE_INFINITY, Math.max(MIN_SHAPE_SIZE, value));
|
||||||
if (edit.axis === "width") {
|
if (edit.axis === "width") {
|
||||||
const frame = selectionFrameForShapes([shape], [shape.id]);
|
const frame = selectionFrameForShapes([shape], [shape.id]);
|
||||||
if (shapeHasTaper(shape) && frame) {
|
if (shapeHasTaper(shape) && frame) {
|
||||||
@@ -4183,9 +4244,12 @@ export function WorkplaneViewport({
|
|||||||
liftStartValue,
|
liftStartValue,
|
||||||
rotationAxisVector: handle.kind === "rotate" ? axisVector : undefined,
|
rotationAxisVector: handle.kind === "rotate" ? axisVector : undefined,
|
||||||
rotationPivot: handle.kind === "rotate" ? pivot : undefined,
|
rotationPivot: handle.kind === "rotate" ? pivot : undefined,
|
||||||
rotationPlaneCenter: handle.kind === "rotate" ? rotationPlaneCenter : undefined,
|
rotationPlaneCenter: handle.kind === "rotate" ? rotationPlaneCenter : undefined,
|
||||||
rotationPlaneView: handle.kind === "rotate" ? rotationPlane : undefined,
|
rotationPlaneView: handle.kind === "rotate" ? rotationPlane : undefined,
|
||||||
rotationStartVector: handle.kind === "rotate" ? rotationStartVector : undefined,
|
rotationStartPointerAngle: handle.kind === "rotate"
|
||||||
|
? rotationPlanePointerAngle(rotationPlane, localClientX, localClientY, rotationCenter ?? { x: localClientX, y: localClientY })
|
||||||
|
: undefined,
|
||||||
|
rotationStartVector: handle.kind === "rotate" ? rotationStartVector : undefined,
|
||||||
rotationScreenCenter: rotationCenter,
|
rotationScreenCenter: rotationCenter,
|
||||||
rotationScreenSign: handle.kind === "rotate" ? rotationScreenSign(axisVector, state.camera) : 1,
|
rotationScreenSign: handle.kind === "rotate" ? rotationScreenSign(axisVector, state.camera) : 1,
|
||||||
rotationStartQuaternion: handle.kind === "rotate" ? quaternionForShape(shape) : undefined,
|
rotationStartQuaternion: handle.kind === "rotate" ? quaternionForShape(shape) : undefined,
|
||||||
@@ -5070,10 +5134,12 @@ export function WorkplaneViewport({
|
|||||||
snap={snap}
|
snap={snap}
|
||||||
themePreference={themePreference}
|
themePreference={themePreference}
|
||||||
moveDimensionsEnabled={moveDimensionsEnabled}
|
moveDimensionsEnabled={moveDimensionsEnabled}
|
||||||
|
showProjectNameInToolbar={showProjectNameInToolbar}
|
||||||
onWorkspaceChange={setWorkspace}
|
onWorkspaceChange={setWorkspace}
|
||||||
onSnapChange={setSnap}
|
onSnapChange={setSnap}
|
||||||
onThemePreferenceChange={onThemePreferenceChange}
|
onThemePreferenceChange={onThemePreferenceChange}
|
||||||
onMoveDimensionsEnabledChange={changeMoveDimensionsEnabled}
|
onMoveDimensionsEnabledChange={changeMoveDimensionsEnabled}
|
||||||
|
onShowProjectNameInToolbarChange={onShowProjectNameInToolbarChange}
|
||||||
onMakeDefault={makeWorkspaceDefault}
|
onMakeDefault={makeWorkspaceDefault}
|
||||||
onClose={() => setSettingsOpen(false)}
|
onClose={() => setSettingsOpen(false)}
|
||||||
/>
|
/>
|
||||||
@@ -5097,7 +5163,7 @@ export function WorkplaneViewport({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createThreeScene(host: HTMLDivElement): ThreeState {
|
function createThreeScene(host: HTMLDivElement): ThreeState {
|
||||||
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance", preserveDrawingBuffer: shouldPreserveDrawingBufferForLocalAutomation() });
|
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance", preserveDrawingBuffer: false });
|
||||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||||
renderer.setSize(host.clientWidth, host.clientHeight);
|
renderer.setSize(host.clientWidth, host.clientHeight);
|
||||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||||
@@ -7175,7 +7241,7 @@ function enableAcceleratedMeshPicking(mesh: THREE.Mesh, geometry: THREE.BufferGe
|
|||||||
mesh.raycast = acceleratedRaycast;
|
mesh.raycast = acceleratedRaycast;
|
||||||
const bvhGeometry = geometry as THREE.BufferGeometry & { boundsTree?: unknown };
|
const bvhGeometry = geometry as THREE.BufferGeometry & { boundsTree?: unknown };
|
||||||
if ((force || triangles >= BVH_PICKING_TRIANGLE_THRESHOLD) && !bvhGeometry.boundsTree) {
|
if ((force || triangles >= BVH_PICKING_TRIANGLE_THRESHOLD) && !bvhGeometry.boundsTree) {
|
||||||
computeBoundsTree.call(geometry, { maxLeafSize: 12 });
|
computeBoundsTree.call(geometry, { targetLeafSize: 12 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
|
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
|
||||||
import { resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeWidth } from "@/lib/workplaneShapes";
|
import { resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeWidth } from "@/lib/workplaneShapes";
|
||||||
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
|
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
|
||||||
|
import { MAX_HIGH_RESOLUTION_SIDES } from "@/lib/workplaneSettings";
|
||||||
import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||||
|
|
||||||
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
||||||
@@ -107,7 +108,7 @@ function propertyUsesLengthUnit(label: string) {
|
|||||||
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole", "Top Length", "Top Width", "Bottom Length", "Bottom Width"].includes(label);
|
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole", "Top Length", "Top Width", "Bottom Length", "Bottom Width"].includes(label);
|
||||||
}
|
}
|
||||||
|
|
||||||
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
|
function getShapePropertiesWithAppLimits(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate, textWidthMax = 260): ShapePropertyConfig[] {
|
||||||
const baseWidth = shapeWidth(shape);
|
const baseWidth = shapeWidth(shape);
|
||||||
const baseDepth = shapeDepth(shape);
|
const baseDepth = shapeDepth(shape);
|
||||||
const footprint = shapeOverallFootprintDimensions(shape);
|
const footprint = shapeOverallFootprintDimensions(shape);
|
||||||
@@ -159,8 +160,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
|
|||||||
return [
|
return [
|
||||||
{ label: "Start Angle", value: settings.startAngle, min: 0, max: 359, step: 1, onChange: (startAngle) => updateRevolve({ startAngle }) },
|
{ label: "Start Angle", value: settings.startAngle, min: 0, max: 359, step: 1, onChange: (startAngle) => updateRevolve({ startAngle }) },
|
||||||
{ label: "Sweep", value: settings.sweepAngle, min: -360, max: 360, step: 1, onChange: (sweepAngle) => updateRevolve({ sweepAngle }) },
|
{ label: "Sweep", value: settings.sweepAngle, min: -360, max: 360, step: 1, onChange: (sweepAngle) => updateRevolve({ sweepAngle }) },
|
||||||
{ label: "Sides", value: settings.sides, min: 3, max: 128, step: 1, onChange: (sides) => updateRevolve({ sides }) },
|
{ label: "Sides", value: settings.sides, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1, onChange: (sides) => updateRevolve({ sides }) },
|
||||||
{ label: "Thickness", value: settings.thickness, min: 0.1, max: 20, step: 0.1, onChange: (thickness) => updateRevolve({ thickness }) },
|
|
||||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
||||||
@@ -177,7 +177,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
|
|||||||
|
|
||||||
if (shape.kind === "cylinder") {
|
if (shape.kind === "cylinder") {
|
||||||
return [
|
return [
|
||||||
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
||||||
@@ -209,7 +209,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
|
|||||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setConeWidth },
|
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setConeWidth },
|
||||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
||||||
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -224,7 +224,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
|
|||||||
|
|
||||||
if (shape.kind === "roundRoof") {
|
if (shape.kind === "roundRoof") {
|
||||||
return [
|
return [
|
||||||
{ label: "Sides", value: shape.sides ?? 64, min: 4, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
{ label: "Sides", value: shape.sides ?? 64, min: 4, max: MAX_HIGH_RESOLUTION_SIDES, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
||||||
@@ -334,7 +334,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
|
|||||||
value: shape.text ?? "TEXT",
|
value: shape.text ?? "TEXT",
|
||||||
onChange: (text) => {
|
onChange: (text) => {
|
||||||
const nextText = text.slice(0, 24) || " ";
|
const nextText = text.slice(0, 24) || " ";
|
||||||
const nextWidth = clamp(Math.max(46, nextText.length * 19), 46, 260);
|
const nextWidth = clamp(Math.max(Math.min(46, textWidthMax), nextText.length * 19), MIN_SHAPE_SIZE, textWidthMax);
|
||||||
onUpdate({ text: nextText, width: nextWidth, size: nextWidth });
|
onUpdate({ text: nextText, width: nextWidth, size: nextWidth });
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -352,6 +352,18 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate, workspace: WorkplaneWorkspaceSettings): ShapePropertyConfig[] {
|
||||||
|
const customLimit = workspace.shapeCustomizations[shape.kind]?.maxDimension;
|
||||||
|
const properties = getShapePropertiesWithAppLimits(shape, onUpdate, customLimit ?? 260);
|
||||||
|
if (customLimit === undefined) return properties;
|
||||||
|
return properties.map((property) => {
|
||||||
|
if (property.type === "text" || property.type === "select") return property;
|
||||||
|
if (["Length", "Width", "Height"].includes(property.label)) return { ...property, max: customLimit };
|
||||||
|
if (["Top Radius", "Base Radius"].includes(property.label)) return { ...property, max: customLimit / 2 };
|
||||||
|
return property;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function ShapeInspector({
|
export function ShapeInspector({
|
||||||
shape,
|
shape,
|
||||||
snap,
|
snap,
|
||||||
@@ -379,7 +391,7 @@ export function ShapeInspector({
|
|||||||
}) {
|
}) {
|
||||||
const solidColor = shape.color;
|
const solidColor = shape.color;
|
||||||
const locked = Boolean(shape.locked);
|
const locked = Boolean(shape.locked);
|
||||||
const properties = getShapeProperties(shape, onUpdate);
|
const properties = getShapeProperties(shape, onUpdate, workspace);
|
||||||
const gearType = shape.kind === "gear" ? normalizeGearType(shape.gearType) : null;
|
const gearType = shape.kind === "gear" ? normalizeGearType(shape.gearType) : null;
|
||||||
const primaryProperties = shape.kind === "gear"
|
const primaryProperties = shape.kind === "gear"
|
||||||
? properties.filter((property) => ["Center Hole", "Length", "Width", "Height"].includes(property.label))
|
? properties.filter((property) => ["Center Hole", "Length", "Width", "Height"].includes(property.label))
|
||||||
@@ -391,33 +403,34 @@ export function ShapeInspector({
|
|||||||
? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label))
|
? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label))
|
||||||
: [];
|
: [];
|
||||||
const taper = shapeTaperDimensions(shape);
|
const taper = shapeTaperDimensions(shape);
|
||||||
|
const taperDimensionMax = workspace.shapeCustomizations[shape.kind]?.maxDimension ?? 480;
|
||||||
const taperProperties: ShapePropertyConfig[] = shape.kind === "gear" ? [] : [
|
const taperProperties: ShapePropertyConfig[] = shape.kind === "gear" ? [] : [
|
||||||
{
|
{
|
||||||
label: "Top Length",
|
label: "Top Length",
|
||||||
value: taper.topDepth,
|
value: taper.topDepth,
|
||||||
min: MIN_SHAPE_SIZE,
|
min: MIN_SHAPE_SIZE,
|
||||||
max: 480,
|
max: taperDimensionMax,
|
||||||
onChange: (taperTopDepth) => onUpdate({ taperTopDepth, taperTopWidth: taper.topWidth, taperTopScale: undefined }),
|
onChange: (taperTopDepth) => onUpdate({ taperTopDepth, taperTopWidth: taper.topWidth, taperTopScale: undefined }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Top Width",
|
label: "Top Width",
|
||||||
value: taper.topWidth,
|
value: taper.topWidth,
|
||||||
min: MIN_SHAPE_SIZE,
|
min: MIN_SHAPE_SIZE,
|
||||||
max: 480,
|
max: taperDimensionMax,
|
||||||
onChange: (taperTopWidth) => onUpdate({ taperTopWidth, taperTopDepth: taper.topDepth, taperTopScale: undefined }),
|
onChange: (taperTopWidth) => onUpdate({ taperTopWidth, taperTopDepth: taper.topDepth, taperTopScale: undefined }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Bottom Length",
|
label: "Bottom Length",
|
||||||
value: taper.bottomDepth,
|
value: taper.bottomDepth,
|
||||||
min: MIN_SHAPE_SIZE,
|
min: MIN_SHAPE_SIZE,
|
||||||
max: 480,
|
max: taperDimensionMax,
|
||||||
onChange: (taperBottomDepth) => onUpdate({ taperBottomDepth, taperBottomWidth: taper.bottomWidth, taperBottomScale: undefined }),
|
onChange: (taperBottomDepth) => onUpdate({ taperBottomDepth, taperBottomWidth: taper.bottomWidth, taperBottomScale: undefined }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Bottom Width",
|
label: "Bottom Width",
|
||||||
value: taper.bottomWidth,
|
value: taper.bottomWidth,
|
||||||
min: MIN_SHAPE_SIZE,
|
min: MIN_SHAPE_SIZE,
|
||||||
max: 480,
|
max: taperDimensionMax,
|
||||||
onChange: (taperBottomWidth) => onUpdate({ taperBottomWidth, taperBottomDepth: taper.bottomDepth, taperBottomScale: undefined }),
|
onChange: (taperBottomWidth) => onUpdate({ taperBottomWidth, taperBottomDepth: taper.bottomDepth, taperBottomScale: undefined }),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -7,9 +7,15 @@ import {
|
|||||||
} from "@/components/workplane/transformOverlayTypes";
|
} from "@/components/workplane/transformOverlayTypes";
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
continuousSnappedWheelRotation,
|
||||||
getElevationMeasureKey,
|
getElevationMeasureKey,
|
||||||
measureKeyForHandle,
|
measureKeyForHandle,
|
||||||
normalizedRotationPlaneBasis,
|
normalizedRotationPlaneBasis,
|
||||||
|
rotationWheelDirectionSign,
|
||||||
|
snappedRotationDelta,
|
||||||
|
snappedWheelRotation,
|
||||||
|
ROTATION_WHEEL_SHIFT_SNAP_DEGREES,
|
||||||
|
ROTATION_WHEEL_SNAP_DEGREES,
|
||||||
type DimensionMark,
|
type DimensionMark,
|
||||||
type EditingDimension,
|
type EditingDimension,
|
||||||
type EditingRotation,
|
type EditingRotation,
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { ChevronDown, Grid3X3, History, Palette, RotateCcw, Ruler, X } from "lucide-react";
|
import { Box as BoxIcon, ChevronDown, Grid3X3, History, Palette, RotateCcw, Ruler, X } from "lucide-react";
|
||||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { HexColorInput, HexColorPicker } from "react-colorful";
|
import { HexColorInput, HexColorPicker } from "react-colorful";
|
||||||
import { APP_THEME_OPTIONS, type AppThemePreference } from "@/lib/appTheme";
|
import { APP_THEME_OPTIONS, type AppThemePreference } from "@/lib/appTheme";
|
||||||
|
import { gearCenterHoleLimits, gearToothPitch } from "@/lib/gearGeometry";
|
||||||
import { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
|
import { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
|
||||||
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
|
import { shapeAssetDefaultDimensions, shapeAssetSpecialDefaults, toolbarShapeAssets } from "@/lib/shapeCatalog";
|
||||||
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
import { DEFAULT_WORKPLANE_WORKSPACE, MAX_CUSTOM_SHAPE_DIMENSION, MAX_HIGH_RESOLUTION_SIDES, MIN_CUSTOM_SHAPE_DIMENSION } from "@/lib/workplaneSettings";
|
||||||
|
import type { GearType, GridSize, ShapeCustomization, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||||
|
|
||||||
type WorkspaceSettings = WorkplaneWorkspaceSettings;
|
type WorkspaceSettings = WorkplaneWorkspaceSettings;
|
||||||
type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane" | "history";
|
type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane" | "shapes" | "history";
|
||||||
|
|
||||||
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
||||||
const MIN_WORKSPACE_SIZE = 60;
|
const MIN_WORKSPACE_SIZE = 60;
|
||||||
@@ -28,6 +30,18 @@ const WORKSPACE_SIZE_PRESETS = [
|
|||||||
const GRID_BLOCK_PRESETS = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const;
|
const GRID_BLOCK_PRESETS = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const;
|
||||||
const HISTORY_LIMIT_OPTIONS = [30, 50, 100, "unlimited", "custom"] as const;
|
const HISTORY_LIMIT_OPTIONS = [30, 50, 100, "unlimited", "custom"] as const;
|
||||||
const HISTORY_CUSTOM_DEFAULT = 250;
|
const HISTORY_CUSTOM_DEFAULT = 250;
|
||||||
|
const TEXT_FONT_OPTIONS = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
|
||||||
|
const GEAR_TYPE_OPTIONS: Array<{ value: GearType; label: string }> = [
|
||||||
|
{ value: "spur", label: "Spur gear" },
|
||||||
|
{ value: "helical", label: "Helical gear" },
|
||||||
|
{ value: "bevel", label: "Bevel gear" },
|
||||||
|
];
|
||||||
|
|
||||||
|
type ShapeSpecialNumberKey = "steps" | "sides" | "bevel" | "segments" | "topRadius" | "baseRadius" | "teeth" | "toothSize" | "toothWidth" | "centerHoleSize" | "helixAngle" | "helixQuality";
|
||||||
|
type ShapeSpecialField =
|
||||||
|
| { type: "number"; key: ShapeSpecialNumberKey; label: string; defaultValue: number; min: number; max: number; step?: number; unit?: string }
|
||||||
|
| { type: "select"; key: "font" | "gearType"; label: string; defaultValue: string; options: Array<{ value: string; label: string }> }
|
||||||
|
| { type: "text"; key: "text"; label: string; defaultValue: string; maxLength: number };
|
||||||
|
|
||||||
function clamp(value: number, min: number, max: number) {
|
function clamp(value: number, min: number, max: number) {
|
||||||
return Math.min(max, Math.max(min, value));
|
return Math.min(max, Math.max(min, value));
|
||||||
@@ -44,15 +58,67 @@ function isHistoryLimitPreset(value: unknown): value is 30 | 50 | 100 {
|
|||||||
return value === 30 || value === 50 || value === 100;
|
return value === 30 || value === 50 || value === 100;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function specialFieldsForShape(
|
||||||
|
kind: ShapeKind,
|
||||||
|
dimensions: { width: number; depth: number; height: number },
|
||||||
|
customization: ShapeCustomization,
|
||||||
|
): ShapeSpecialField[] {
|
||||||
|
const defaults = shapeAssetSpecialDefaults(kind, dimensions);
|
||||||
|
if (kind === "cylinder") return [{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1 }];
|
||||||
|
if (kind === "sphere" || kind === "halfSphere") return [{ type: "number", key: "steps", label: "Steps", defaultValue: defaults.steps ?? 24, min: 6, max: 64, step: 1 }];
|
||||||
|
if (kind === "cone") {
|
||||||
|
return [
|
||||||
|
{ type: "number", key: "topRadius", label: "Top radius", defaultValue: defaults.topRadius ?? 0, min: 0, max: MAX_CUSTOM_SHAPE_DIMENSION / 2, unit: "mm" },
|
||||||
|
{ type: "number", key: "baseRadius", label: "Base radius", defaultValue: defaults.baseRadius ?? dimensions.width / 2, min: MIN_CUSTOM_SHAPE_DIMENSION, max: MAX_CUSTOM_SHAPE_DIMENSION / 2, unit: "mm" },
|
||||||
|
{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 96, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1 },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (kind === "pyramid") return [{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 4, min: 3, max: 24, step: 1 }];
|
||||||
|
if (kind === "roundRoof") return [{ type: "number", key: "sides", label: "Sides", defaultValue: defaults.sides ?? 64, min: 4, max: MAX_HIGH_RESOLUTION_SIDES, step: 1 }];
|
||||||
|
if (kind === "tube" || kind === "ring") return [{ type: "number", key: "bevel", label: "Thickness", defaultValue: defaults.bevel ?? 4, min: 0.5, max: 20, unit: "mm" }];
|
||||||
|
if (kind === "text") {
|
||||||
|
return [
|
||||||
|
{ type: "text", key: "text", label: "Text", defaultValue: defaults.text ?? "TEXT", maxLength: 24 },
|
||||||
|
{ type: "select", key: "font", label: "Font", defaultValue: defaults.font ?? "Multilanguage", options: TEXT_FONT_OPTIONS.map((value) => ({ value, label: value })) },
|
||||||
|
{ type: "number", key: "bevel", label: "Bevel", defaultValue: defaults.bevel ?? 0, min: 0, max: 8, unit: "mm" },
|
||||||
|
{ type: "number", key: "segments", label: "Segments", defaultValue: defaults.segments ?? 0, min: 0, max: 24, step: 1 },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (kind === "gear") {
|
||||||
|
const teeth = customization.teeth ?? defaults.teeth ?? 12;
|
||||||
|
const toothSize = customization.toothSize ?? defaults.toothSize ?? 2.5;
|
||||||
|
const toothPitch = gearToothPitch(dimensions.width, dimensions.depth, teeth);
|
||||||
|
const centerHoleLimits = gearCenterHoleLimits(dimensions.width, dimensions.depth, toothSize);
|
||||||
|
const gearType = customization.gearType ?? defaults.gearType ?? "spur";
|
||||||
|
const fields: ShapeSpecialField[] = [
|
||||||
|
{ type: "select", key: "gearType", label: "Gear type", defaultValue: defaults.gearType ?? "spur", options: GEAR_TYPE_OPTIONS },
|
||||||
|
{ type: "number", key: "teeth", label: "Teeth", defaultValue: defaults.teeth ?? 12, min: 6, max: 64, step: 1 },
|
||||||
|
{ type: "number", key: "toothSize", label: "Tooth size", defaultValue: defaults.toothSize ?? 2.5, min: 0.2, max: Math.max(0.2, Math.min(dimensions.width, dimensions.depth) * 0.22), unit: "mm" },
|
||||||
|
{ type: "number", key: "toothWidth", label: "Tooth width", defaultValue: defaults.toothWidth ?? toothPitch * 0.54, min: toothPitch * 0.12, max: toothPitch * 0.82, unit: "mm" },
|
||||||
|
{ type: "number", key: "centerHoleSize", label: "Center hole", defaultValue: defaults.centerHoleSize ?? 6, min: centerHoleLimits.min, max: centerHoleLimits.max, unit: "mm" },
|
||||||
|
];
|
||||||
|
if (gearType === "helical") {
|
||||||
|
fields.push(
|
||||||
|
{ type: "number", key: "helixAngle", label: "Helix angle", defaultValue: defaults.helixAngle ?? 22.5, min: -45, max: 45, unit: "deg" },
|
||||||
|
{ type: "number", key: "helixQuality", label: "Helix quality", defaultValue: defaults.helixQuality ?? 16, min: 4, max: 32, step: 1 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return fields;
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
export function WorkspaceSettingsModal({
|
export function WorkspaceSettingsModal({
|
||||||
workspace,
|
workspace,
|
||||||
snap,
|
snap,
|
||||||
themePreference,
|
themePreference,
|
||||||
moveDimensionsEnabled,
|
moveDimensionsEnabled,
|
||||||
|
showProjectNameInToolbar,
|
||||||
onWorkspaceChange,
|
onWorkspaceChange,
|
||||||
onSnapChange,
|
onSnapChange,
|
||||||
onThemePreferenceChange,
|
onThemePreferenceChange,
|
||||||
onMoveDimensionsEnabledChange,
|
onMoveDimensionsEnabledChange,
|
||||||
|
onShowProjectNameInToolbarChange,
|
||||||
onMakeDefault,
|
onMakeDefault,
|
||||||
onClose,
|
onClose,
|
||||||
}: {
|
}: {
|
||||||
@@ -60,15 +126,18 @@ export function WorkspaceSettingsModal({
|
|||||||
snap: GridSize;
|
snap: GridSize;
|
||||||
themePreference: AppThemePreference;
|
themePreference: AppThemePreference;
|
||||||
moveDimensionsEnabled: boolean;
|
moveDimensionsEnabled: boolean;
|
||||||
|
showProjectNameInToolbar: boolean;
|
||||||
onWorkspaceChange: (next: WorkspaceSettings) => void;
|
onWorkspaceChange: (next: WorkspaceSettings) => void;
|
||||||
onSnapChange: (next: GridSize) => void;
|
onSnapChange: (next: GridSize) => void;
|
||||||
onThemePreferenceChange?: (preference: AppThemePreference) => void;
|
onThemePreferenceChange?: (preference: AppThemePreference) => void;
|
||||||
onMoveDimensionsEnabledChange: (enabled: boolean) => void;
|
onMoveDimensionsEnabledChange: (enabled: boolean) => void;
|
||||||
|
onShowProjectNameInToolbarChange?: (show: boolean) => void;
|
||||||
onMakeDefault: () => void;
|
onMakeDefault: () => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}) {
|
}) {
|
||||||
const [defaultSaved, setDefaultSaved] = useState(false);
|
const [defaultSaved, setDefaultSaved] = useState(false);
|
||||||
const [activeSection, setActiveSection] = useState<WorkspaceSettingsSection>("appearance");
|
const [activeSection, setActiveSection] = useState<WorkspaceSettingsSection>("appearance");
|
||||||
|
const [selectedShapeKind, setSelectedShapeKind] = useState<ShapeKind>(toolbarShapeAssets[0].kind);
|
||||||
const [dimensionDrafts, setDimensionDrafts] = useState(() => ({
|
const [dimensionDrafts, setDimensionDrafts] = useState(() => ({
|
||||||
width: workspace.width.toFixed(workspace.accuracy),
|
width: workspace.width.toFixed(workspace.accuracy),
|
||||||
depth: workspace.depth.toFixed(workspace.accuracy),
|
depth: workspace.depth.toFixed(workspace.accuracy),
|
||||||
@@ -88,6 +157,16 @@ export function WorkspaceSettingsModal({
|
|||||||
const gridColor = /^#[0-9a-f]{6}$/i.test(workspace.gridColor)
|
const gridColor = /^#[0-9a-f]{6}$/i.test(workspace.gridColor)
|
||||||
? workspace.gridColor
|
? workspace.gridColor
|
||||||
: DEFAULT_WORKPLANE_WORKSPACE.gridColor;
|
: DEFAULT_WORKPLANE_WORKSPACE.gridColor;
|
||||||
|
const selectedShapeAsset = toolbarShapeAssets.find((asset) => asset.kind === selectedShapeKind) ?? toolbarShapeAssets[0];
|
||||||
|
const selectedShapeAppDefaults = shapeAssetDefaultDimensions(selectedShapeKind);
|
||||||
|
const selectedShapeCustomization = workspace.shapeCustomizations[selectedShapeKind] ?? {};
|
||||||
|
const selectedShapeEffectiveDimensions = {
|
||||||
|
width: selectedShapeCustomization.width ?? selectedShapeAppDefaults.width,
|
||||||
|
depth: selectedShapeCustomization.depth ?? selectedShapeAppDefaults.depth,
|
||||||
|
height: selectedShapeCustomization.height ?? selectedShapeAppDefaults.height,
|
||||||
|
};
|
||||||
|
const selectedShapeSpecialFields = specialFieldsForShape(selectedShapeKind, selectedShapeEffectiveDimensions, selectedShapeCustomization);
|
||||||
|
const selectedShapeCustomized = Object.keys(selectedShapeCustomization).length > 0;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setDimensionDrafts({
|
setDimensionDrafts({
|
||||||
width: workspace.width.toFixed(workspace.accuracy),
|
width: workspace.width.toFixed(workspace.accuracy),
|
||||||
@@ -107,6 +186,56 @@ export function WorkspaceSettingsModal({
|
|||||||
const next = { ...workspace, ...patch };
|
const next = { ...workspace, ...patch };
|
||||||
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
|
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
|
||||||
};
|
};
|
||||||
|
const patchShapeCustomization = (kind: ShapeKind, patch: Partial<ShapeCustomization>) => {
|
||||||
|
const nextEntry = Object.fromEntries(
|
||||||
|
Object.entries({ ...workspace.shapeCustomizations[kind], ...patch }).filter(([, value]) => value !== undefined),
|
||||||
|
) as ShapeCustomization;
|
||||||
|
const nextCustomizations = { ...workspace.shapeCustomizations };
|
||||||
|
if (Object.keys(nextEntry).length > 0) nextCustomizations[kind] = nextEntry;
|
||||||
|
else delete nextCustomizations[kind];
|
||||||
|
patchWorkspace({ shapeCustomizations: nextCustomizations });
|
||||||
|
};
|
||||||
|
const setShapeDefaultDimension = (key: "width" | "depth" | "height", rawValue: string) => {
|
||||||
|
const parsed = parseMeasurementInput(rawValue);
|
||||||
|
if (!Number.isFinite(parsed)) return;
|
||||||
|
const nextValue = clamp(parsed, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION);
|
||||||
|
patchShapeCustomization(selectedShapeKind, key === "width" && selectedShapeKind === "cone"
|
||||||
|
? { width: nextValue, baseRadius: nextValue / 2 }
|
||||||
|
: { [key]: nextValue });
|
||||||
|
};
|
||||||
|
const setShapeSpecialNumber = (field: Extract<ShapeSpecialField, { type: "number" }>, rawValue: string) => {
|
||||||
|
if (!rawValue.trim()) {
|
||||||
|
patchShapeCustomization(selectedShapeKind, { [field.key]: undefined });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const parsed = parseMeasurementInput(rawValue);
|
||||||
|
if (!Number.isFinite(parsed)) return;
|
||||||
|
const clamped = clamp(parsed, field.min, field.max);
|
||||||
|
const nextValue = field.step === 1 ? Math.round(clamped) : clamped;
|
||||||
|
patchShapeCustomization(selectedShapeKind, field.key === "baseRadius" && selectedShapeKind === "cone"
|
||||||
|
? { baseRadius: nextValue, width: nextValue * 2 }
|
||||||
|
: { [field.key]: nextValue });
|
||||||
|
};
|
||||||
|
const setShapeSpecialText = (field: Extract<ShapeSpecialField, { type: "text" }>, rawValue: string) => {
|
||||||
|
const nextValue = rawValue.slice(0, field.maxLength);
|
||||||
|
patchShapeCustomization(selectedShapeKind, { [field.key]: nextValue || undefined });
|
||||||
|
};
|
||||||
|
const setShapeLimit = (rawValue: string) => {
|
||||||
|
if (!rawValue.trim()) {
|
||||||
|
patchShapeCustomization(selectedShapeKind, { maxDimension: undefined });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const parsed = parseMeasurementInput(rawValue);
|
||||||
|
if (!Number.isFinite(parsed)) return;
|
||||||
|
patchShapeCustomization(selectedShapeKind, {
|
||||||
|
maxDimension: clamp(parsed, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const resetSelectedShapeCustomization = () => {
|
||||||
|
const nextCustomizations = { ...workspace.shapeCustomizations };
|
||||||
|
delete nextCustomizations[selectedShapeKind];
|
||||||
|
patchWorkspace({ shapeCustomizations: nextCustomizations });
|
||||||
|
};
|
||||||
const setDimension = (key: "width" | "depth", value: string) => {
|
const setDimension = (key: "width" | "depth", value: string) => {
|
||||||
const parsed = parseMeasurementInput(value);
|
const parsed = parseMeasurementInput(value);
|
||||||
const next = clamp(Number.isFinite(parsed) ? parsed : workspace[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
|
const next = clamp(Number.isFinite(parsed) ? parsed : workspace[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
|
||||||
@@ -169,6 +298,10 @@ export function WorkspaceSettingsModal({
|
|||||||
<Grid3X3 size={18} />
|
<Grid3X3 size={18} />
|
||||||
<span>Workplane</span>
|
<span>Workplane</span>
|
||||||
</button>
|
</button>
|
||||||
|
<button className={activeSection === "shapes" ? "active" : ""} aria-current={activeSection === "shapes" ? "page" : undefined} onClick={() => setActiveSection("shapes")}>
|
||||||
|
<BoxIcon size={18} />
|
||||||
|
<span>Shape defaults</span>
|
||||||
|
</button>
|
||||||
<button className={activeSection === "history" ? "active" : ""} aria-current={activeSection === "history" ? "page" : undefined} onClick={() => setActiveSection("history")}>
|
<button className={activeSection === "history" ? "active" : ""} aria-current={activeSection === "history" ? "page" : undefined} onClick={() => setActiveSection("history")}>
|
||||||
<History size={18} />
|
<History size={18} />
|
||||||
<span>History</span>
|
<span>History</span>
|
||||||
@@ -197,6 +330,11 @@ export function WorkspaceSettingsModal({
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<p className="workspace-global-note">Theme applies across SketchForge and all projects.</p>
|
<p className="workspace-global-note">Theme applies across SketchForge and all projects.</p>
|
||||||
|
<WorkspaceToggle
|
||||||
|
label="Show project name in toolbar"
|
||||||
|
checked={showProjectNameInToolbar}
|
||||||
|
onChange={(show) => onShowProjectNameInToolbarChange?.(show)}
|
||||||
|
/>
|
||||||
<WorkspaceToggle
|
<WorkspaceToggle
|
||||||
label="Show movement dimensions"
|
label="Show movement dimensions"
|
||||||
checked={moveDimensionsEnabled}
|
checked={moveDimensionsEnabled}
|
||||||
@@ -334,6 +472,139 @@ export function WorkspaceSettingsModal({
|
|||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{activeSection === "shapes" ? (
|
||||||
|
<>
|
||||||
|
<div className="workspace-section-heading">
|
||||||
|
<strong>Shape defaults</strong>
|
||||||
|
<span>Customize how each toolbar shape starts. Existing limits stay unchanged until you enter a custom limit.</span>
|
||||||
|
</div>
|
||||||
|
<label className="workspace-shape-picker">
|
||||||
|
<span>Shape</span>
|
||||||
|
<span className="workspace-shape-picker-control">
|
||||||
|
<img src={selectedShapeAsset.menuIcon} alt="" />
|
||||||
|
<select value={selectedShapeKind} onChange={(event) => setSelectedShapeKind(event.currentTarget.value as ShapeKind)}>
|
||||||
|
{toolbarShapeAssets.map((asset) => (
|
||||||
|
<option key={asset.kind} value={asset.kind}>
|
||||||
|
{asset.name}{workspace.shapeCustomizations[asset.kind] ? " — customized" : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<div className="workspace-shape-card">
|
||||||
|
<div className="workspace-shape-card-heading">
|
||||||
|
<span>
|
||||||
|
<strong>{selectedShapeAsset.name}</strong>
|
||||||
|
<small>{selectedShapeCustomized ? "Custom settings active" : "Using SketchForge defaults"}</small>
|
||||||
|
</span>
|
||||||
|
<button type="button" onClick={resetSelectedShapeCustomization} disabled={!selectedShapeCustomized}>
|
||||||
|
<RotateCcw size={14} />
|
||||||
|
<span>Use app defaults</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="workspace-shape-dimensions">
|
||||||
|
{(["width", "depth", "height"] as const).map((key) => (
|
||||||
|
<label key={`${selectedShapeKind}-${key}`}>
|
||||||
|
<span>{key === "depth" ? "Length" : key[0].toUpperCase() + key.slice(1)}</span>
|
||||||
|
<input
|
||||||
|
key={`${selectedShapeKind}-${key}-${selectedShapeCustomization[key] ?? "app"}`}
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
defaultValue={(selectedShapeCustomization[key] ?? selectedShapeAppDefaults[key]).toFixed(workspace.accuracy)}
|
||||||
|
onBlur={(event) => setShapeDefaultDimension(key, event.currentTarget.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") event.currentTarget.blur();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<small>App: {selectedShapeAppDefaults[key]} mm</small>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{selectedShapeSpecialFields.length > 0 ? (
|
||||||
|
<div className="workspace-shape-specials">
|
||||||
|
<div className="workspace-shape-specials-heading">
|
||||||
|
<strong>Shape details</strong>
|
||||||
|
<small>Extra defaults used when this shape is added.</small>
|
||||||
|
</div>
|
||||||
|
<div className="workspace-shape-special-fields">
|
||||||
|
{selectedShapeSpecialFields.map((field) => {
|
||||||
|
const customizedValue = selectedShapeCustomization[field.key];
|
||||||
|
const effectiveValue = customizedValue ?? field.defaultValue;
|
||||||
|
if (field.type === "select") {
|
||||||
|
return (
|
||||||
|
<label key={`${selectedShapeKind}-${field.key}`}>
|
||||||
|
<span>{field.label}</span>
|
||||||
|
<select
|
||||||
|
value={String(effectiveValue)}
|
||||||
|
onChange={(event) => patchShapeCustomization(selectedShapeKind, { [field.key]: event.currentTarget.value })}
|
||||||
|
>
|
||||||
|
{field.options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
|
||||||
|
</select>
|
||||||
|
<small>App: {field.options.find((option) => option.value === field.defaultValue)?.label ?? field.defaultValue}</small>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (field.type === "text") {
|
||||||
|
return (
|
||||||
|
<label key={`${selectedShapeKind}-${field.key}`}>
|
||||||
|
<span>{field.label}</span>
|
||||||
|
<input
|
||||||
|
key={`${selectedShapeKind}-${field.key}-${String(customizedValue ?? "app")}`}
|
||||||
|
type="text"
|
||||||
|
maxLength={field.maxLength}
|
||||||
|
defaultValue={String(effectiveValue)}
|
||||||
|
onBlur={(event) => setShapeSpecialText(field, event.currentTarget.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") event.currentTarget.blur();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<small>App: {field.defaultValue}</small>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const numericValue = Number(effectiveValue);
|
||||||
|
return (
|
||||||
|
<label key={`${selectedShapeKind}-${field.key}`}>
|
||||||
|
<span>{field.label}</span>
|
||||||
|
<input
|
||||||
|
key={`${selectedShapeKind}-${field.key}-${String(customizedValue ?? "app")}-${field.defaultValue}`}
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
defaultValue={field.step === 1 ? String(Math.round(numericValue)) : numericValue.toFixed(workspace.accuracy)}
|
||||||
|
onBlur={(event) => setShapeSpecialNumber(field, event.currentTarget.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") event.currentTarget.blur();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<small>App: {field.step === 1 ? Math.round(field.defaultValue) : Number(field.defaultValue.toFixed(workspace.accuracy))}{field.unit ? ` ${field.unit}` : ""}</small>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<label className="workspace-shape-limit">
|
||||||
|
<span>
|
||||||
|
<strong>Custom size limit</strong>
|
||||||
|
<small>Leave blank to keep all current inspector and drag limits for this shape.</small>
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
key={`${selectedShapeKind}-limit-${selectedShapeCustomization.maxDimension ?? "app"}`}
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
defaultValue={selectedShapeCustomization.maxDimension?.toFixed(workspace.accuracy) ?? ""}
|
||||||
|
placeholder="App limits"
|
||||||
|
onBlur={(event) => setShapeLimit(event.currentTarget.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") event.currentTarget.blur();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p className="workspace-shape-note">Custom values apply to new shapes. A custom size limit also replaces this shape's existing resize ceilings, up to 2000 mm.</p>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{activeSection === "history" ? (
|
{activeSection === "history" ? (
|
||||||
<>
|
<>
|
||||||
<div className="workspace-section-heading">
|
<div className="workspace-section-heading">
|
||||||
@@ -618,10 +889,23 @@ function GridColorControl({ color, onChange }: { color: string; onChange: (color
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
|
function WorkspaceToggle({
|
||||||
|
label,
|
||||||
|
description,
|
||||||
|
checked,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
checked: boolean;
|
||||||
|
onChange: (checked: boolean) => void;
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<label className="workspace-toggle">
|
<label className="workspace-toggle">
|
||||||
<span>{label}</span>
|
<span className="workspace-toggle-copy">
|
||||||
|
<span>{label}</span>
|
||||||
|
{description ? <small>{description}</small> : null}
|
||||||
|
</span>
|
||||||
<input type="checkbox" checked={checked} onChange={(event) => onChange(event.currentTarget.checked)} />
|
<input type="checkbox" checked={checked} onChange={(event) => onChange(event.currentTarget.checked)} />
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -15,6 +15,65 @@ export type RotationPlaneView = {
|
|||||||
|
|
||||||
export type RotationPlaneBasis = Pick<RotationPlaneView, "a" | "b" | "c" | "d">;
|
export type RotationPlaneBasis = Pick<RotationPlaneView, "a" | "b" | "c" | "d">;
|
||||||
|
|
||||||
|
export const ROTATION_WHEEL_SNAP_DEGREES = 45;
|
||||||
|
export const ROTATION_WHEEL_SHIFT_SNAP_DEGREES = 22.5;
|
||||||
|
|
||||||
|
export function rotationWheelDirectionSign(screenSign: number) {
|
||||||
|
return screenSign < 0 ? 1 : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function snappedRotationDelta(rawDelta: number, insideSnapWheel: boolean, shiftKey: boolean) {
|
||||||
|
const step = insideSnapWheel || shiftKey ? ROTATION_WHEEL_SNAP_DEGREES : 1;
|
||||||
|
return Math.round(rawDelta / step) * step;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function snappedWheelRotation(
|
||||||
|
pointerAngle: number,
|
||||||
|
startPointerAngle: number,
|
||||||
|
screenSign = 1,
|
||||||
|
snapDegrees = ROTATION_WHEEL_SNAP_DEGREES,
|
||||||
|
) {
|
||||||
|
const snappedPointerAngle = Math.round(pointerAngle / snapDegrees) * snapDegrees;
|
||||||
|
const snappedStartPointerAngle = Math.round(startPointerAngle / snapDegrees) * snapDegrees;
|
||||||
|
let pointerDelta = snappedPointerAngle - snappedStartPointerAngle;
|
||||||
|
while (pointerDelta > 180) pointerDelta -= 360;
|
||||||
|
while (pointerDelta <= -180) pointerDelta += 360;
|
||||||
|
const direction = screenSign < 0 ? -1 : 1;
|
||||||
|
const delta = pointerDelta * direction;
|
||||||
|
return {
|
||||||
|
delta: delta === 0 ? 0 : delta,
|
||||||
|
pointerAngle: snappedPointerAngle,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function continuousSnappedWheelRotation(
|
||||||
|
rotation: { delta: number; pointerAngle: number },
|
||||||
|
snapDegrees: number,
|
||||||
|
previousSnapDegrees: number | undefined,
|
||||||
|
previousDelta: number | undefined,
|
||||||
|
previousPointerAngle: number | undefined,
|
||||||
|
previousDeltaOffset = 0,
|
||||||
|
previousPointerOffset = 0,
|
||||||
|
) {
|
||||||
|
const snapModeChanged = previousSnapDegrees !== undefined && previousSnapDegrees !== snapDegrees;
|
||||||
|
const deltaOffset = snapModeChanged && previousDelta !== undefined
|
||||||
|
? previousDelta - rotation.delta
|
||||||
|
: previousDeltaOffset;
|
||||||
|
const pointerOffset = snapModeChanged && previousPointerAngle !== undefined
|
||||||
|
? previousPointerAngle - rotation.pointerAngle
|
||||||
|
: previousPointerOffset;
|
||||||
|
let pointerAngle = rotation.pointerAngle + pointerOffset;
|
||||||
|
while (pointerAngle > 180) pointerAngle -= 360;
|
||||||
|
while (pointerAngle < -180) pointerAngle += 360;
|
||||||
|
const delta = rotation.delta + deltaOffset;
|
||||||
|
return {
|
||||||
|
delta: delta === 0 ? 0 : delta,
|
||||||
|
pointerAngle,
|
||||||
|
deltaOffset,
|
||||||
|
pointerOffset,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizedRotationPlaneBasis(plane: RotationPlaneView, invertVerticalAxis = false): RotationPlaneBasis {
|
export function normalizedRotationPlaneBasis(plane: RotationPlaneView, invertVerticalAxis = false): RotationPlaneBasis {
|
||||||
const longestAxis = Math.max(Math.hypot(plane.a, plane.b), Math.hypot(plane.c, plane.d));
|
const longestAxis = Math.max(Math.hypot(plane.a, plane.b), Math.hypot(plane.c, plane.d));
|
||||||
if (!Number.isFinite(longestAxis) || longestAxis < 0.000001) {
|
if (!Number.isFinite(longestAxis) || longestAxis < 0.000001) {
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
export const PROJECT_THUMBNAIL_IDLE_MS = 2_500;
|
||||||
|
export const PROJECT_THUMBNAIL_MAX_WIDTH = 512;
|
||||||
|
export const PROJECT_THUMBNAIL_MAX_HEIGHT = 320;
|
||||||
|
|
||||||
|
export type ProjectThumbnailSceneKey = {
|
||||||
|
projectId: string;
|
||||||
|
fingerprint: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function projectThumbnailDimensions(
|
||||||
|
sourceWidth: number,
|
||||||
|
sourceHeight: number,
|
||||||
|
maxWidth = PROJECT_THUMBNAIL_MAX_WIDTH,
|
||||||
|
maxHeight = PROJECT_THUMBNAIL_MAX_HEIGHT,
|
||||||
|
) {
|
||||||
|
const width = Math.max(1, Math.round(Number.isFinite(sourceWidth) ? sourceWidth : 1));
|
||||||
|
const height = Math.max(1, Math.round(Number.isFinite(sourceHeight) ? sourceHeight : 1));
|
||||||
|
const scale = Math.min(1, maxWidth / width, maxHeight / height);
|
||||||
|
return {
|
||||||
|
width: Math.max(1, Math.round(width * scale)),
|
||||||
|
height: Math.max(1, Math.round(height * scale)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectThumbnailSceneChanged(
|
||||||
|
previous: ProjectThumbnailSceneKey | null,
|
||||||
|
current: ProjectThumbnailSceneKey,
|
||||||
|
) {
|
||||||
|
return previous?.projectId === current.projectId && previous.fingerprint !== current.fingerprint;
|
||||||
|
}
|
||||||
@@ -1,7 +1,21 @@
|
|||||||
import { canonicalizeShape } from "@/lib/workplaneShapes";
|
import { canonicalizeShape } from "@/lib/workplaneShapes";
|
||||||
import { createLocalId } from "@/lib/localIds";
|
import { createLocalId } from "@/lib/localIds";
|
||||||
import { DEFAULT_GEAR_CENTER_HOLE_SIZE, DEFAULT_GEAR_HELIX_ANGLE, DEFAULT_GEAR_HELIX_QUALITY, DEFAULT_GEAR_TEETH, DEFAULT_GEAR_TOOTH_SIZE, DEFAULT_GEAR_TYPE } from "@/lib/gearGeometry";
|
import {
|
||||||
import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
|
DEFAULT_GEAR_CENTER_HOLE_SIZE,
|
||||||
|
DEFAULT_GEAR_HELIX_ANGLE,
|
||||||
|
DEFAULT_GEAR_HELIX_QUALITY,
|
||||||
|
DEFAULT_GEAR_TEETH,
|
||||||
|
DEFAULT_GEAR_TOOTH_SIZE,
|
||||||
|
DEFAULT_GEAR_TYPE,
|
||||||
|
normalizeGearCenterHoleSize,
|
||||||
|
normalizeGearHelixAngle,
|
||||||
|
normalizeGearHelixQuality,
|
||||||
|
normalizeGearTeeth,
|
||||||
|
normalizeGearToothSize,
|
||||||
|
normalizeGearToothWidth,
|
||||||
|
normalizeGearType,
|
||||||
|
} from "@/lib/gearGeometry";
|
||||||
|
import type { ShapeAsset, ShapeCustomization, ShapeKind, WorkplaneShape } from "@/types/sketchforge";
|
||||||
|
|
||||||
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
|
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
|
||||||
|
|
||||||
@@ -20,6 +34,42 @@ export const toolbarShapeAssets: ToolbarShapeAsset[] = [
|
|||||||
{ id: "gear", name: "Gear", src: "assets/sketchforge/gear-types/spur.png", menuIcon: "assets/sketchforge/gear-types/spur.png", kind: "gear", color: "#6f7f8d" },
|
{ id: "gear", name: "Gear", src: "assets/sketchforge/gear-types/spur.png", menuIcon: "assets/sketchforge/gear-types/spur.png", kind: "gear", color: "#6f7f8d" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
export function shapeAssetDefaultDimensions(kind: ShapeKind) {
|
||||||
|
const roundProfile = kind === "sphere" || kind === "torus" || kind === "ring" || kind === "halfSphere";
|
||||||
|
const flatProfile = kind === "torus" || kind === "ring" || kind === "text" || kind === "gear";
|
||||||
|
const size = kind === "gear" ? 30 : roundProfile ? 22 : 20;
|
||||||
|
return {
|
||||||
|
width: kind === "text" ? 86 : size,
|
||||||
|
depth: kind === "text" ? 28 : size,
|
||||||
|
height: kind === "gear" ? 6 : kind === "text" ? 10 : kind === "roundRoof" ? 10 : kind === "halfSphere" ? 11 : flatProfile ? 5 : 20,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shapeAssetSpecialDefaults(kind: ShapeKind, dimensions = shapeAssetDefaultDimensions(kind)): ShapeCustomization {
|
||||||
|
if (kind === "cylinder") return { sides: 96 };
|
||||||
|
if (kind === "sphere") return { steps: 24 };
|
||||||
|
if (kind === "halfSphere") return { steps: 32 };
|
||||||
|
if (kind === "cone") return { topRadius: 0, baseRadius: dimensions.width / 2, sides: 96 };
|
||||||
|
if (kind === "pyramid") return { sides: 4 };
|
||||||
|
if (kind === "roundRoof") return { sides: 64 };
|
||||||
|
if (kind === "tube" || kind === "ring") return { bevel: 4 };
|
||||||
|
if (kind === "text") return { text: "TEXT", font: "Multilanguage", bevel: 0, segments: 0 };
|
||||||
|
if (kind === "gear") {
|
||||||
|
const teeth = DEFAULT_GEAR_TEETH;
|
||||||
|
const toothSize = normalizeGearToothSize(DEFAULT_GEAR_TOOTH_SIZE, dimensions.width, dimensions.depth);
|
||||||
|
return {
|
||||||
|
teeth,
|
||||||
|
toothSize,
|
||||||
|
toothWidth: normalizeGearToothWidth(undefined, dimensions.width, dimensions.depth, teeth),
|
||||||
|
centerHoleSize: normalizeGearCenterHoleSize(DEFAULT_GEAR_CENTER_HOLE_SIZE, dimensions.width, dimensions.depth, toothSize),
|
||||||
|
gearType: DEFAULT_GEAR_TYPE,
|
||||||
|
helixAngle: DEFAULT_GEAR_HELIX_ANGLE,
|
||||||
|
helixQuality: DEFAULT_GEAR_HELIX_QUALITY,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
|
export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
|
||||||
const width = shape.width ?? shape.size ?? 20;
|
const width = shape.width ?? shape.size ?? 20;
|
||||||
const depth = shape.depth ?? shape.size ?? 20;
|
const depth = shape.depth ?? shape.size ?? 20;
|
||||||
@@ -77,13 +127,18 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape {
|
export function makeShapeFromAsset(
|
||||||
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
|
asset: ShapeAsset,
|
||||||
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text" || asset.kind === "gear";
|
point?: { x: number; z: number; elevation?: number },
|
||||||
const size = asset.kind === "gear" ? 30 : roundProfile ? 22 : 20;
|
customization: ShapeCustomization = {},
|
||||||
const height = asset.kind === "gear" ? 6 : asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
|
): WorkplaneShape {
|
||||||
const width = asset.kind === "text" ? 86 : size;
|
const defaults = shapeAssetDefaultDimensions(asset.kind);
|
||||||
const depth = asset.kind === "text" ? 28 : size;
|
const width = customization.width ?? defaults.width;
|
||||||
|
const depth = customization.depth ?? defaults.depth;
|
||||||
|
const height = customization.height ?? defaults.height;
|
||||||
|
const size = Math.max(width, depth);
|
||||||
|
const gearTeeth = asset.kind === "gear" ? normalizeGearTeeth(customization.teeth ?? DEFAULT_GEAR_TEETH) : undefined;
|
||||||
|
const gearToothSize = asset.kind === "gear" ? normalizeGearToothSize(customization.toothSize ?? DEFAULT_GEAR_TOOTH_SIZE, width, depth) : undefined;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: createLocalId(asset.id),
|
id: createLocalId(asset.id),
|
||||||
@@ -102,20 +157,23 @@ export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: nu
|
|||||||
rotationX: 0,
|
rotationX: 0,
|
||||||
rotationZ: 0,
|
rotationZ: 0,
|
||||||
radius: asset.kind === "box" ? 0 : undefined,
|
radius: asset.kind === "box" ? 0 : undefined,
|
||||||
text: asset.kind === "text" ? "TEXT" : undefined,
|
text: asset.kind === "text" ? customization.text ?? "TEXT" : undefined,
|
||||||
font: asset.kind === "text" ? "Multilanguage" : undefined,
|
font: asset.kind === "text" ? customization.font ?? "Multilanguage" : undefined,
|
||||||
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? 24 : asset.kind === "halfSphere" ? 32 : undefined,
|
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? customization.steps ?? 24 : asset.kind === "halfSphere" ? customization.steps ?? 32 : undefined,
|
||||||
sides: asset.kind === "cylinder" || asset.kind === "cone" ? 96 : asset.kind === "roundRoof" ? 64 : asset.kind === "pyramid" ? 4 : undefined,
|
sides: asset.kind === "cylinder" || asset.kind === "cone" ? customization.sides ?? 96 : asset.kind === "roundRoof" ? customization.sides ?? 64 : asset.kind === "pyramid" ? customization.sides ?? 4 : undefined,
|
||||||
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? 4 : undefined,
|
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? customization.bevel ?? 4 : asset.kind === "text" ? customization.bevel : undefined,
|
||||||
segments: asset.kind === "cylinder" ? 1 : undefined,
|
segments: asset.kind === "cylinder" ? 1 : asset.kind === "text" ? customization.segments : undefined,
|
||||||
topRadius: asset.kind === "cone" ? 0 : undefined,
|
topRadius: asset.kind === "cone" ? customization.topRadius ?? 0 : undefined,
|
||||||
baseRadius: asset.kind === "cone" ? size / 2 : undefined,
|
baseRadius: asset.kind === "cone" ? customization.baseRadius ?? width / 2 : undefined,
|
||||||
teeth: asset.kind === "gear" ? DEFAULT_GEAR_TEETH : undefined,
|
teeth: gearTeeth,
|
||||||
toothSize: asset.kind === "gear" ? DEFAULT_GEAR_TOOTH_SIZE : undefined,
|
toothSize: gearToothSize,
|
||||||
centerHoleSize: asset.kind === "gear" ? DEFAULT_GEAR_CENTER_HOLE_SIZE : undefined,
|
toothWidth: asset.kind === "gear" && customization.toothWidth !== undefined
|
||||||
gearType: asset.kind === "gear" ? DEFAULT_GEAR_TYPE : undefined,
|
? normalizeGearToothWidth(customization.toothWidth, width, depth, gearTeeth)
|
||||||
helixAngle: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_ANGLE : undefined,
|
: undefined,
|
||||||
helixQuality: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_QUALITY : undefined,
|
centerHoleSize: asset.kind === "gear" ? normalizeGearCenterHoleSize(customization.centerHoleSize ?? DEFAULT_GEAR_CENTER_HOLE_SIZE, width, depth, gearToothSize) : undefined,
|
||||||
|
gearType: asset.kind === "gear" ? normalizeGearType(customization.gearType ?? DEFAULT_GEAR_TYPE) : undefined,
|
||||||
|
helixAngle: asset.kind === "gear" ? normalizeGearHelixAngle(customization.helixAngle ?? DEFAULT_GEAR_HELIX_ANGLE) : undefined,
|
||||||
|
helixQuality: asset.kind === "gear" ? normalizeGearHelixQuality(customization.helixQuality ?? DEFAULT_GEAR_HELIX_QUALITY) : undefined,
|
||||||
locked: false,
|
locked: false,
|
||||||
hidden: false,
|
hidden: false,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import type { ManifoldToplevel } from "manifold-3d";
|
import type { ManifoldToplevel } from "manifold-3d";
|
||||||
import type { SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment } from "@/types/sketchforge";
|
import type { SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment } from "@/types/sketchforge";
|
||||||
|
import { MAX_HIGH_RESOLUTION_SIDES } from "@/lib/workplaneSettings";
|
||||||
|
|
||||||
export const DEFAULT_SKETCH_REVOLVE_SETTINGS: SketchRevolveSettings = {
|
export const DEFAULT_SKETCH_REVOLVE_SETTINGS: SketchRevolveSettings = {
|
||||||
startAngle: 0,
|
startAngle: 0,
|
||||||
sweepAngle: 360,
|
sweepAngle: 360,
|
||||||
sides: 64,
|
sides: 64,
|
||||||
quality: 6,
|
quality: 6,
|
||||||
thickness: 1,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type OrderedStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
|
type OrderedStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
|
||||||
@@ -36,9 +36,8 @@ export function normalizeSketchRevolveSettings(settings?: Partial<SketchRevolveS
|
|||||||
return {
|
return {
|
||||||
startAngle: ((finiteOr(settings?.startAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.startAngle) % 360) + 360) % 360,
|
startAngle: ((finiteOr(settings?.startAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.startAngle) % 360) + 360) % 360,
|
||||||
sweepAngle,
|
sweepAngle,
|
||||||
sides: Math.round(clamp(finiteOr(settings?.sides, DEFAULT_SKETCH_REVOLVE_SETTINGS.sides), 3, 128)),
|
sides: Math.round(clamp(finiteOr(settings?.sides, DEFAULT_SKETCH_REVOLVE_SETTINGS.sides), 3, MAX_HIGH_RESOLUTION_SIDES)),
|
||||||
quality: Math.round(clamp(finiteOr(settings?.quality, DEFAULT_SKETCH_REVOLVE_SETTINGS.quality), 1, 10)),
|
quality: Math.round(clamp(finiteOr(settings?.quality, DEFAULT_SKETCH_REVOLVE_SETTINGS.quality), 1, 10)),
|
||||||
thickness: clamp(finiteOr(settings?.thickness, DEFAULT_SKETCH_REVOLVE_SETTINGS.thickness), 0.1, 20),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,34 +151,6 @@ function clipClosedPathToRevolveSide(points: SampledPoint[]) {
|
|||||||
return compactSampledPath(clipped);
|
return compactSampledPath(clipped);
|
||||||
}
|
}
|
||||||
|
|
||||||
function clipOpenPathToRevolveSide(points: SampledPoint[]) {
|
|
||||||
const paths: SampledPoint[][] = [];
|
|
||||||
let current: SampledPoint[] = [];
|
|
||||||
const finishCurrent = () => {
|
|
||||||
const compact = compactSampledPath(current);
|
|
||||||
if (compact.length >= 2) paths.push(compact);
|
|
||||||
current = [];
|
|
||||||
};
|
|
||||||
for (let index = 0; index < points.length - 1; index += 1) {
|
|
||||||
const from = points[index];
|
|
||||||
const to = points[index + 1];
|
|
||||||
const fromInside = from.x <= 0;
|
|
||||||
const toInside = to.x <= 0;
|
|
||||||
if (fromInside && toInside) {
|
|
||||||
if (current.length === 0) current.push(from);
|
|
||||||
current.push(to);
|
|
||||||
} else if (fromInside) {
|
|
||||||
if (current.length === 0) current.push(from);
|
|
||||||
current.push(axisIntersection(from, to));
|
|
||||||
finishCurrent();
|
|
||||||
} else if (toInside) {
|
|
||||||
current = [axisIntersection(from, to), to];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finishCurrent();
|
|
||||||
return paths;
|
|
||||||
}
|
|
||||||
|
|
||||||
function distance(a: Point2, b: Point2) {
|
function distance(a: Point2, b: Point2) {
|
||||||
return Math.hypot(b[0] - a[0], b[1] - a[1]);
|
return Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||||
}
|
}
|
||||||
@@ -193,55 +164,19 @@ function compactPolygon(points: Point2[]) {
|
|||||||
return compact;
|
return compact;
|
||||||
}
|
}
|
||||||
|
|
||||||
function strokeOpenPath(points: Point2[], thickness: number) {
|
|
||||||
if (points.length < 2) return [];
|
|
||||||
const half = thickness / 2;
|
|
||||||
const normals: Point2[] = [];
|
|
||||||
for (let index = 0; index < points.length - 1; index += 1) {
|
|
||||||
const dx = points[index + 1][0] - points[index][0];
|
|
||||||
const dy = points[index + 1][1] - points[index][1];
|
|
||||||
const length = Math.hypot(dx, dy);
|
|
||||||
normals.push(length > 1e-8 ? [-dy / length, dx / length] : [0, 0]);
|
|
||||||
}
|
|
||||||
const offsetAt = (index: number): Point2 => {
|
|
||||||
const previous = normals[Math.max(0, index - 1)];
|
|
||||||
const next = normals[Math.min(normals.length - 1, index)];
|
|
||||||
const sumX = previous[0] + next[0];
|
|
||||||
const sumY = previous[1] + next[1];
|
|
||||||
const sumLength = Math.hypot(sumX, sumY);
|
|
||||||
if (sumLength <= 1e-8) return [next[0] * half, next[1] * half];
|
|
||||||
const unit: Point2 = [sumX / sumLength, sumY / sumLength];
|
|
||||||
const projection = Math.abs(unit[0] * next[0] + unit[1] * next[1]);
|
|
||||||
const miter = Math.min(half * 4, half / Math.max(0.25, projection));
|
|
||||||
return [unit[0] * miter, unit[1] * miter];
|
|
||||||
};
|
|
||||||
const left: Point2[] = [];
|
|
||||||
const right: Point2[] = [];
|
|
||||||
points.forEach((point, index) => {
|
|
||||||
const offset = offsetAt(index);
|
|
||||||
left.push([point[0] + offset[0], point[1] + offset[1]]);
|
|
||||||
right.push([point[0] - offset[0], point[1] - offset[1]]);
|
|
||||||
});
|
|
||||||
return compactPolygon([...left, ...right.reverse()]);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function sketchProfileToRevolvePolygons(profile: SketchProfile, settings?: Partial<SketchRevolveSettings>) {
|
export function sketchProfileToRevolvePolygons(profile: SketchProfile, settings?: Partial<SketchRevolveSettings>) {
|
||||||
const normalized = normalizeSketchRevolveSettings(settings);
|
const normalized = normalizeSketchRevolveSettings(settings);
|
||||||
const paths = orderedPaths(profile).flatMap((path) => {
|
const paths = orderedPaths(profile).filter((path) => path.closed).flatMap((path) => {
|
||||||
const sampled = samplePath(path, normalized.quality);
|
const sampled = samplePath(path, normalized.quality);
|
||||||
if (path.closed) {
|
const clipped = clipClosedPathToRevolveSide(sampled);
|
||||||
const clipped = clipClosedPathToRevolveSide(sampled);
|
return clipped.length >= 3 ? [clipped] : [];
|
||||||
return clipped.length >= 3 ? [{ closed: true, points: clipped }] : [];
|
|
||||||
}
|
|
||||||
return clipOpenPathToRevolveSide(sampled).map((points) => ({ closed: false, points }));
|
|
||||||
});
|
});
|
||||||
if (paths.length === 0) return [];
|
if (paths.length === 0) return [];
|
||||||
const maxZ = Math.max(...paths.flatMap((entry) => entry.points.map((point) => point.z)));
|
const maxZ = Math.max(...paths.flatMap((points) => points.map((point) => point.z)));
|
||||||
const toSectionPoint = (point: SampledPoint): Point2 => [-point.x, maxZ - point.z];
|
const toSectionPoint = (point: SampledPoint): Point2 => [-point.x, maxZ - point.z];
|
||||||
return paths.flatMap(({ closed, points }) => {
|
return paths.flatMap((points) => {
|
||||||
const sectionPoints = compactPolygon(points.map(toSectionPoint));
|
const sectionPoints = compactPolygon(points.map(toSectionPoint));
|
||||||
const polygon = closed ? sectionPoints : strokeOpenPath(sectionPoints, normalized.thickness).map((point) => [Math.max(0, point[0]), point[1]] as Point2);
|
return sectionPoints.length >= 3 ? [sectionPoints] : [];
|
||||||
return polygon.length >= 3 ? [compactPolygon(polygon)] : [];
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,7 +196,7 @@ function dispose(value: unknown) {
|
|||||||
export function buildSketchRevolveMesh(runtime: ManifoldToplevel, profile: SketchProfile, requestedSettings?: Partial<SketchRevolveSettings>): SketchRevolveMesh {
|
export function buildSketchRevolveMesh(runtime: ManifoldToplevel, profile: SketchProfile, requestedSettings?: Partial<SketchRevolveSettings>): SketchRevolveMesh {
|
||||||
const settings = normalizeSketchRevolveSettings(requestedSettings);
|
const settings = normalizeSketchRevolveSettings(requestedSettings);
|
||||||
const polygons = sketchProfileToRevolvePolygons(profile, settings);
|
const polygons = sketchProfileToRevolvePolygons(profile, settings);
|
||||||
if (polygons.length === 0) throw new Error("Draw at least one connected profile on the left side of the revolve axis");
|
if (polygons.length === 0) throw new Error("Draw at least one closed profile on the left side of the revolve axis");
|
||||||
const disposable: unknown[] = [];
|
const disposable: unknown[] = [];
|
||||||
try {
|
try {
|
||||||
const section = new runtime.CrossSection(polygons, "EvenOdd");
|
const section = new runtime.CrossSection(polygons, "EvenOdd");
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import type { SketchPoint, SketchProfile } from "@/types/sketchforge";
|
||||||
|
|
||||||
|
export type SketchGeometrySelection = {
|
||||||
|
pointIds: readonly string[];
|
||||||
|
segmentIds: readonly string[];
|
||||||
|
imageIds?: readonly string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function selectedClosedSketchPoints(
|
||||||
|
profile: SketchProfile,
|
||||||
|
selection: SketchGeometrySelection,
|
||||||
|
): SketchPoint[] | null {
|
||||||
|
if (selection.imageIds?.length) return null;
|
||||||
|
|
||||||
|
const pointIds = new Set(selection.pointIds);
|
||||||
|
const segmentIds = new Set(selection.segmentIds);
|
||||||
|
if (pointIds.size < 3 || segmentIds.size !== pointIds.size) return null;
|
||||||
|
|
||||||
|
const selectedPoints = profile.points.filter((point) => pointIds.has(point.id));
|
||||||
|
if (selectedPoints.length !== pointIds.size) return null;
|
||||||
|
|
||||||
|
const segmentById = new Map(profile.segments.map((segment) => [segment.id, segment]));
|
||||||
|
const adjacency = new Map([...pointIds].map((pointId) => [pointId, new Set<string>()]));
|
||||||
|
|
||||||
|
for (const segmentId of segmentIds) {
|
||||||
|
const segment = segmentById.get(segmentId);
|
||||||
|
if (
|
||||||
|
!segment
|
||||||
|
|| segment.startId === segment.endId
|
||||||
|
|| !pointIds.has(segment.startId)
|
||||||
|
|| !pointIds.has(segment.endId)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
adjacency.get(segment.startId)?.add(segment.endId);
|
||||||
|
adjacency.get(segment.endId)?.add(segment.startId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ([...adjacency.values()].some((neighbors) => neighbors.size !== 2)) return null;
|
||||||
|
|
||||||
|
const unvisited = new Set(pointIds);
|
||||||
|
while (unvisited.size > 0) {
|
||||||
|
const start = unvisited.values().next().value as string | undefined;
|
||||||
|
if (!start) return null;
|
||||||
|
const stack = [start];
|
||||||
|
let componentSize = 0;
|
||||||
|
while (stack.length > 0) {
|
||||||
|
const pointId = stack.pop();
|
||||||
|
if (!pointId || !unvisited.delete(pointId)) continue;
|
||||||
|
componentSize += 1;
|
||||||
|
adjacency.get(pointId)?.forEach((neighborId) => {
|
||||||
|
if (unvisited.has(neighborId)) stack.push(neighborId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (componentSize < 3) return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return selectedPoints;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rotateSketchPoints(points: readonly SketchPoint[], degrees = 45): SketchPoint[] {
|
||||||
|
if (points.length === 0) return [];
|
||||||
|
|
||||||
|
const minX = Math.min(...points.map((point) => point.x));
|
||||||
|
const maxX = Math.max(...points.map((point) => point.x));
|
||||||
|
const minZ = Math.min(...points.map((point) => point.z));
|
||||||
|
const maxZ = Math.max(...points.map((point) => point.z));
|
||||||
|
const pivot = { x: (minX + maxX) / 2, z: (minZ + maxZ) / 2 };
|
||||||
|
const radians = degrees * Math.PI / 180;
|
||||||
|
const cosine = Math.cos(radians);
|
||||||
|
const sine = Math.sin(radians);
|
||||||
|
const rotatePosition = (position: { x: number; z: number }) => {
|
||||||
|
const deltaX = position.x - pivot.x;
|
||||||
|
const deltaZ = position.z - pivot.z;
|
||||||
|
return {
|
||||||
|
x: pivot.x + deltaX * cosine - deltaZ * sine,
|
||||||
|
z: pivot.z + deltaX * sine + deltaZ * cosine,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
return points.map((point) => ({
|
||||||
|
...point,
|
||||||
|
...rotatePosition(point),
|
||||||
|
handleIn: point.handleIn ? rotatePosition(point.handleIn) : undefined,
|
||||||
|
handleOut: point.handleOut ? rotatePosition(point.handleOut) : undefined,
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
import type { GridSize, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
import type { GridSize, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||||
|
|
||||||
export const SKETCHFORGE_MCP_ROUTE = "/api/sketchforge-mcp";
|
export const SKETCHFORGE_MCP_ROUTE = "/api/sketchforge-mcp";
|
||||||
export const SKETCHFORGE_MCP_STALE_MS = 6500;
|
export const SKETCHFORGE_MCP_STALE_MS = 15_000;
|
||||||
export const SKETCHFORGE_MCP_POLL_MS = 220;
|
export const SKETCHFORGE_MCP_HEARTBEAT_MS = 5_000;
|
||||||
|
export const SKETCHFORGE_MCP_LONG_POLL_TIMEOUT_MS = 25_000;
|
||||||
|
export const SKETCHFORGE_MCP_POLL_RETRY_MS = 1_000;
|
||||||
|
|
||||||
export type SketchForgeMcpViewFace = "current" | "home" | "top" | "bottom" | "front" | "back" | "right" | "left";
|
export type SketchForgeMcpViewFace = "current" | "home" | "top" | "bottom" | "front" | "back" | "right" | "left";
|
||||||
|
|
||||||
|
|||||||
@@ -12,10 +12,18 @@ type PendingCommand = {
|
|||||||
timer: ReturnType<typeof setTimeout>;
|
timer: ReturnType<typeof setTimeout>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type PollWaiter = {
|
||||||
|
resolve: (command: SketchForgeMcpCommand | null) => void;
|
||||||
|
timer: ReturnType<typeof setTimeout>;
|
||||||
|
signal?: AbortSignal;
|
||||||
|
onAbort?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
type SketchForgeMcpStore = {
|
type SketchForgeMcpStore = {
|
||||||
editors: Map<string, SketchForgeMcpEditorSummary>;
|
editors: Map<string, SketchForgeMcpEditorSummary>;
|
||||||
queues: Map<string, SketchForgeMcpCommand[]>;
|
queues: Map<string, SketchForgeMcpCommand[]>;
|
||||||
pending: Map<string, PendingCommand>;
|
pending: Map<string, PendingCommand>;
|
||||||
|
pollWaiters: Map<string, PollWaiter>;
|
||||||
};
|
};
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
@@ -24,22 +32,42 @@ declare global {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function store() {
|
function store() {
|
||||||
globalThis.__sketchforgeMcpStore ??= {
|
const state = globalThis.__sketchforgeMcpStore ??= {
|
||||||
editors: new Map<string, SketchForgeMcpEditorSummary>(),
|
editors: new Map<string, SketchForgeMcpEditorSummary>(),
|
||||||
queues: new Map<string, SketchForgeMcpCommand[]>(),
|
queues: new Map<string, SketchForgeMcpCommand[]>(),
|
||||||
pending: new Map<string, PendingCommand>(),
|
pending: new Map<string, PendingCommand>(),
|
||||||
|
pollWaiters: new Map<string, PollWaiter>(),
|
||||||
};
|
};
|
||||||
return globalThis.__sketchforgeMcpStore;
|
// Development hot reload can preserve a store created before pollWaiters
|
||||||
|
// existed. Initialize it lazily so an already-open editor keeps working.
|
||||||
|
state.pollWaiters ??= new Map<string, PollWaiter>();
|
||||||
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createCommandId() {
|
function createCommandId() {
|
||||||
return globalThis.crypto?.randomUUID?.() ?? `sketchforge-mcp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
return globalThis.crypto?.randomUUID?.() ?? `sketchforge-mcp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function settlePollWaiter(
|
||||||
|
state: SketchForgeMcpStore,
|
||||||
|
editorId: string,
|
||||||
|
waiter: PollWaiter,
|
||||||
|
command: SketchForgeMcpCommand | null,
|
||||||
|
) {
|
||||||
|
if (state.pollWaiters.get(editorId) !== waiter) return false;
|
||||||
|
state.pollWaiters.delete(editorId);
|
||||||
|
clearTimeout(waiter.timer);
|
||||||
|
if (waiter.signal && waiter.onAbort) {
|
||||||
|
waiter.signal.removeEventListener("abort", waiter.onAbort);
|
||||||
|
}
|
||||||
|
waiter.resolve(command);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
function prune(current = Date.now()) {
|
function prune(current = Date.now()) {
|
||||||
const state = store();
|
const state = store();
|
||||||
for (const [editorId, editor] of state.editors) {
|
for (const [editorId, editor] of state.editors) {
|
||||||
if (current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
|
if (state.pollWaiters.has(editorId) || current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
state.editors.delete(editorId);
|
state.editors.delete(editorId);
|
||||||
@@ -79,6 +107,32 @@ export function pollSketchForgeMcpCommand(editorId: string) {
|
|||||||
return queue?.shift() ?? null;
|
return queue?.shift() ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function waitForSketchForgeMcpCommand(
|
||||||
|
editorId: string,
|
||||||
|
{ timeoutMs, signal }: { timeoutMs: number; signal?: AbortSignal },
|
||||||
|
) {
|
||||||
|
const state = store();
|
||||||
|
const current = Date.now();
|
||||||
|
const editor = state.editors.get(editorId);
|
||||||
|
if (editor) state.editors.set(editorId, { ...editor, lastSeen: current });
|
||||||
|
prune(current);
|
||||||
|
const queued = state.queues.get(editorId)?.shift();
|
||||||
|
if (queued) return Promise.resolve(queued);
|
||||||
|
if (signal?.aborted) return Promise.resolve(null);
|
||||||
|
|
||||||
|
const existing = state.pollWaiters.get(editorId);
|
||||||
|
if (existing) settlePollWaiter(state, editorId, existing, null);
|
||||||
|
|
||||||
|
return new Promise<SketchForgeMcpCommand | null>((resolve) => {
|
||||||
|
let waiter: PollWaiter;
|
||||||
|
const timer = setTimeout(() => settlePollWaiter(state, editorId, waiter, null), Math.max(1_000, Math.min(timeoutMs, 30_000)));
|
||||||
|
const onAbort = () => settlePollWaiter(state, editorId, waiter, null);
|
||||||
|
waiter = { resolve, timer, signal, onAbort };
|
||||||
|
state.pollWaiters.set(editorId, waiter);
|
||||||
|
signal?.addEventListener("abort", onAbort, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function completeSketchForgeMcpCommand(editorId: string, result: SketchForgeMcpCommandResult) {
|
export function completeSketchForgeMcpCommand(editorId: string, result: SketchForgeMcpCommandResult) {
|
||||||
const state = store();
|
const state = store();
|
||||||
const pending = state.pending.get(result.commandId);
|
const pending = state.pending.get(result.commandId);
|
||||||
@@ -124,9 +178,12 @@ export function dispatchSketchForgeMcpCommand({
|
|||||||
params,
|
params,
|
||||||
createdAt: Date.now(),
|
createdAt: Date.now(),
|
||||||
};
|
};
|
||||||
const queue = state.queues.get(editor.editorId) ?? [];
|
const waiter = state.pollWaiters.get(editor.editorId);
|
||||||
queue.push(command);
|
if (!waiter || !settlePollWaiter(state, editor.editorId, waiter, command)) {
|
||||||
state.queues.set(editor.editorId, queue);
|
const queue = state.queues.get(editor.editorId) ?? [];
|
||||||
|
queue.push(command);
|
||||||
|
state.queues.set(editor.editorId, queue);
|
||||||
|
}
|
||||||
|
|
||||||
return new Promise<SketchForgeMcpCommandResult>((resolve) => {
|
return new Promise<SketchForgeMcpCommandResult>((resolve) => {
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
|
|||||||
@@ -872,7 +872,7 @@ function validateShapeDefinition(definition: Record<string, unknown>, label: str
|
|||||||
}
|
}
|
||||||
if (definition.sketchRevolve !== undefined) {
|
if (definition.sketchRevolve !== undefined) {
|
||||||
const settings = objectRecord(definition.sketchRevolve, `${label}.sketchRevolve`);
|
const settings = objectRecord(definition.sketchRevolve, `${label}.sketchRevolve`);
|
||||||
["startAngle", "sweepAngle", "sides", "quality", "thickness"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
|
["startAngle", "sweepAngle", "sides", "quality"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
|
||||||
}
|
}
|
||||||
if (kind === "gear") {
|
if (kind === "gear") {
|
||||||
const teeth = finiteNumber(definition.teeth, `${label}.teeth`);
|
const teeth = finiteNumber(definition.teeth, `${label}.teeth`);
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, ShapeCustomization, ShapeCustomizationMap, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||||
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
|
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
|
||||||
import { DEFAULT_WORKPLANE_GRID_COLOR } from "@/lib/workplaneGrid";
|
import { DEFAULT_WORKPLANE_GRID_COLOR } from "@/lib/workplaneGrid";
|
||||||
|
|
||||||
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
|
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
|
||||||
|
export const MIN_CUSTOM_SHAPE_DIMENSION = 0.01;
|
||||||
|
export const MAX_CUSTOM_SHAPE_DIMENSION = 2000;
|
||||||
|
export const MAX_HIGH_RESOLUTION_SIDES = 512;
|
||||||
|
|
||||||
export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
|
export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
|
||||||
width: 200,
|
width: 200,
|
||||||
@@ -21,9 +24,14 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
|
|||||||
scale: "1:1 (millimeters)",
|
scale: "1:1 (millimeters)",
|
||||||
accuracy: 2,
|
accuracy: 2,
|
||||||
historyLimit: 100,
|
historyLimit: 100,
|
||||||
|
shapeCustomizations: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
||||||
|
const customizableShapeKinds: ShapeKind[] = [
|
||||||
|
"box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
|
||||||
|
"halfSphere", "torus", "tube", "gear", "ring", "wedge", "polygon", "icosahedron", "mesh",
|
||||||
|
];
|
||||||
|
|
||||||
function numberOrDefault(value: unknown, fallback: number) {
|
function numberOrDefault(value: unknown, fallback: number) {
|
||||||
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
||||||
@@ -51,6 +59,88 @@ function historyLimitOrDefault(value: unknown, fallback: HistoryRetentionLimit):
|
|||||||
return Math.min(5000, Math.max(1, Math.round(value)));
|
return Math.min(5000, Math.max(1, Math.round(value)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function optionalShapeDimension(value: unknown, fallback: number | undefined) {
|
||||||
|
if (value === undefined) return fallback;
|
||||||
|
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
||||||
|
return Math.min(MAX_CUSTOM_SHAPE_DIMENSION, Math.max(MIN_CUSTOM_SHAPE_DIMENSION, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalShapeNumber(value: unknown, fallback: number | undefined, min: number, max: number, integer = false) {
|
||||||
|
if (value === undefined) return fallback;
|
||||||
|
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
||||||
|
const normalized = Math.min(max, Math.max(min, value));
|
||||||
|
return integer ? Math.round(normalized) : normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalShapeText(value: unknown, fallback: string | undefined, maxLength: number) {
|
||||||
|
if (value === undefined) return fallback;
|
||||||
|
if (typeof value !== "string") return fallback;
|
||||||
|
return value.slice(0, maxLength) || " ";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeShapeCustomizations(value: unknown, fallback: ShapeCustomizationMap = {}): ShapeCustomizationMap {
|
||||||
|
const candidate = value && typeof value === "object" ? value as Partial<Record<ShapeKind, unknown>> : {};
|
||||||
|
const normalized: ShapeCustomizationMap = {};
|
||||||
|
customizableShapeKinds.forEach((kind) => {
|
||||||
|
const raw = candidate[kind];
|
||||||
|
const source = raw && typeof raw === "object" ? raw as Partial<ShapeCustomization> : {};
|
||||||
|
const fallbackEntry = fallback[kind];
|
||||||
|
const entry: ShapeCustomization = {
|
||||||
|
width: optionalShapeDimension(source.width, fallbackEntry?.width),
|
||||||
|
depth: optionalShapeDimension(source.depth, fallbackEntry?.depth),
|
||||||
|
height: optionalShapeDimension(source.height, fallbackEntry?.height),
|
||||||
|
maxDimension: optionalShapeDimension(source.maxDimension, fallbackEntry?.maxDimension),
|
||||||
|
};
|
||||||
|
if (kind === "sphere" || kind === "halfSphere") {
|
||||||
|
entry.steps = optionalShapeNumber(source.steps, fallbackEntry?.steps, 6, 64, true);
|
||||||
|
}
|
||||||
|
if (kind === "cylinder" || kind === "cone") {
|
||||||
|
entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 3, MAX_HIGH_RESOLUTION_SIDES, true);
|
||||||
|
} else if (kind === "pyramid") {
|
||||||
|
entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 3, 24, true);
|
||||||
|
} else if (kind === "roundRoof") {
|
||||||
|
entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 4, MAX_HIGH_RESOLUTION_SIDES, true);
|
||||||
|
}
|
||||||
|
if (kind === "cone") {
|
||||||
|
entry.topRadius = optionalShapeNumber(source.topRadius, fallbackEntry?.topRadius, 0, MAX_CUSTOM_SHAPE_DIMENSION / 2);
|
||||||
|
entry.baseRadius = optionalShapeNumber(source.baseRadius, fallbackEntry?.baseRadius, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION / 2);
|
||||||
|
}
|
||||||
|
if (kind === "tube" || kind === "ring") {
|
||||||
|
entry.bevel = optionalShapeNumber(source.bevel, fallbackEntry?.bevel, 0.5, 20);
|
||||||
|
}
|
||||||
|
if (kind === "text") {
|
||||||
|
entry.text = optionalShapeText(source.text, fallbackEntry?.text, 24);
|
||||||
|
entry.font = source.font === undefined
|
||||||
|
? fallbackEntry?.font
|
||||||
|
: ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"].includes(source.font)
|
||||||
|
? source.font
|
||||||
|
: fallbackEntry?.font;
|
||||||
|
entry.bevel = optionalShapeNumber(source.bevel, fallbackEntry?.bevel, 0, 8);
|
||||||
|
entry.segments = optionalShapeNumber(source.segments, fallbackEntry?.segments, 0, 24, true);
|
||||||
|
}
|
||||||
|
if (kind === "gear") {
|
||||||
|
entry.teeth = optionalShapeNumber(source.teeth, fallbackEntry?.teeth, 6, 64, true);
|
||||||
|
entry.toothSize = optionalShapeNumber(source.toothSize, fallbackEntry?.toothSize, 0.2, MAX_CUSTOM_SHAPE_DIMENSION / 2);
|
||||||
|
entry.toothWidth = optionalShapeNumber(source.toothWidth, fallbackEntry?.toothWidth, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION);
|
||||||
|
entry.centerHoleSize = optionalShapeNumber(source.centerHoleSize, fallbackEntry?.centerHoleSize, 0, MAX_CUSTOM_SHAPE_DIMENSION);
|
||||||
|
entry.gearType = source.gearType === undefined
|
||||||
|
? fallbackEntry?.gearType
|
||||||
|
: source.gearType === "spur" || source.gearType === "helical" || source.gearType === "bevel"
|
||||||
|
? source.gearType
|
||||||
|
: fallbackEntry?.gearType;
|
||||||
|
entry.helixAngle = optionalShapeNumber(source.helixAngle, fallbackEntry?.helixAngle, -45, 45);
|
||||||
|
entry.helixQuality = optionalShapeNumber(source.helixQuality, fallbackEntry?.helixQuality, 4, 32, true);
|
||||||
|
}
|
||||||
|
const compact = Object.fromEntries(Object.entries(entry).filter(([, entryValue]) => entryValue !== undefined)) as ShapeCustomization;
|
||||||
|
if (Object.keys(compact).length > 0) normalized[kind] = compact;
|
||||||
|
});
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shapeDimensionLimit(workspace: WorkplaneWorkspaceSettings, kind: ShapeKind, appDefault: number) {
|
||||||
|
return workspace.shapeCustomizations[kind]?.maxDimension ?? appDefault;
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_SNAP_GRID): GridSize {
|
export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_SNAP_GRID): GridSize {
|
||||||
return snapGridOptions.includes(value as GridSize) ? (value as GridSize) : fallback;
|
return snapGridOptions.includes(value as GridSize) ? (value as GridSize) : fallback;
|
||||||
}
|
}
|
||||||
@@ -75,6 +165,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
|
|||||||
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
|
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
|
||||||
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
|
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
|
||||||
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
|
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
|
||||||
|
shapeCustomizations: normalizeShapeCustomizations(candidate.shapeCustomizations, fallback.shapeCustomizations),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ export function cleanNearZero(value: number, epsilon = 0.005) {
|
|||||||
return Math.abs(value) < epsilon ? 0 : value;
|
return Math.abs(value) < epsilon ? 0 : value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function shapeTransformShouldRemainEditable(shape: WorkplaneShape) {
|
||||||
|
return shape.kind === "text" || Boolean(shape.groupedShapes?.length);
|
||||||
|
}
|
||||||
|
|
||||||
export function cloneWorkplaneShapeTreeWithFreshIds(shape: WorkplaneShape, suffix: string): WorkplaneShape {
|
export function cloneWorkplaneShapeTreeWithFreshIds(shape: WorkplaneShape, suffix: string): WorkplaneShape {
|
||||||
return {
|
return {
|
||||||
...shape,
|
...shape,
|
||||||
@@ -213,6 +217,14 @@ export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
|
|||||||
if (shape.groupedShapes) {
|
if (shape.groupedShapes) {
|
||||||
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
|
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
|
||||||
}
|
}
|
||||||
|
if (shape.sketchRevolve) {
|
||||||
|
next.sketchRevolve = {
|
||||||
|
startAngle: shape.sketchRevolve.startAngle,
|
||||||
|
sweepAngle: shape.sketchRevolve.sweepAngle,
|
||||||
|
sides: shape.sketchRevolve.sides,
|
||||||
|
quality: shape.sketchRevolve.quality,
|
||||||
|
};
|
||||||
|
}
|
||||||
if (shape.edgeTreatmentHistory) {
|
if (shape.edgeTreatmentHistory) {
|
||||||
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
|
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
|
||||||
...entry,
|
...entry,
|
||||||
|
|||||||
@@ -44,6 +44,30 @@ export type GridSize = "Off" | "0.1 mm" | "0.25 mm" | "0.5 mm" | "1.0 mm" | "2.0
|
|||||||
export type MeasurementAccuracy = 1 | 2 | 3;
|
export type MeasurementAccuracy = 1 | 2 | 3;
|
||||||
export type HistoryRetentionLimit = "unlimited" | number;
|
export type HistoryRetentionLimit = "unlimited" | number;
|
||||||
|
|
||||||
|
export type ShapeCustomization = {
|
||||||
|
width?: number;
|
||||||
|
depth?: number;
|
||||||
|
height?: number;
|
||||||
|
maxDimension?: number;
|
||||||
|
steps?: number;
|
||||||
|
sides?: number;
|
||||||
|
bevel?: number;
|
||||||
|
segments?: number;
|
||||||
|
topRadius?: number;
|
||||||
|
baseRadius?: number;
|
||||||
|
teeth?: number;
|
||||||
|
toothSize?: number;
|
||||||
|
toothWidth?: number;
|
||||||
|
centerHoleSize?: number;
|
||||||
|
gearType?: GearType;
|
||||||
|
helixAngle?: number;
|
||||||
|
helixQuality?: number;
|
||||||
|
text?: string;
|
||||||
|
font?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ShapeCustomizationMap = Partial<Record<ShapeKind, ShapeCustomization>>;
|
||||||
|
|
||||||
export type WorkplaneWorkspaceSettings = {
|
export type WorkplaneWorkspaceSettings = {
|
||||||
width: number;
|
width: number;
|
||||||
depth: number;
|
depth: number;
|
||||||
@@ -61,6 +85,7 @@ export type WorkplaneWorkspaceSettings = {
|
|||||||
scale: string;
|
scale: string;
|
||||||
accuracy: MeasurementAccuracy;
|
accuracy: MeasurementAccuracy;
|
||||||
historyLimit: HistoryRetentionLimit;
|
historyLimit: HistoryRetentionLimit;
|
||||||
|
shapeCustomizations: ShapeCustomizationMap;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AlignAxis = "x" | "y" | "z";
|
export type AlignAxis = "x" | "y" | "z";
|
||||||
@@ -102,6 +127,7 @@ export type SketchImage = {
|
|||||||
depth: number;
|
depth: number;
|
||||||
opacity?: number;
|
opacity?: number;
|
||||||
lockAspect?: boolean;
|
lockAspect?: boolean;
|
||||||
|
locked?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SketchProfile = {
|
export type SketchProfile = {
|
||||||
@@ -119,7 +145,6 @@ export type SketchRevolveSettings = {
|
|||||||
sweepAngle: number;
|
sweepAngle: number;
|
||||||
sides: number;
|
sides: number;
|
||||||
quality: number;
|
quality: number;
|
||||||
thickness: number;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type EdgeTreatmentFeature = {
|
export type EdgeTreatmentFeature = {
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
projectThumbnailDimensions,
|
||||||
|
projectThumbnailSceneChanged,
|
||||||
|
} from "@/lib/projectThumbnail";
|
||||||
|
|
||||||
|
describe("project thumbnails", () => {
|
||||||
|
it("reduces a high-DPI editor canvas to the thumbnail bounds", () => {
|
||||||
|
expect(projectThumbnailDimensions(2048, 992)).toEqual({ width: 512, height: 248 });
|
||||||
|
expect(projectThumbnailDimensions(800, 1200)).toEqual({ width: 213, height: 320 });
|
||||||
|
expect(projectThumbnailDimensions(320, 180)).toEqual({ width: 320, height: 180 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("captures only changed scenes within the same project", () => {
|
||||||
|
const original = { projectId: "project-1", fingerprint: "scene-a" };
|
||||||
|
expect(projectThumbnailSceneChanged(null, original)).toBe(false);
|
||||||
|
expect(projectThumbnailSceneChanged(original, original)).toBe(false);
|
||||||
|
expect(projectThumbnailSceneChanged(original, { ...original, fingerprint: "scene-b" })).toBe(true);
|
||||||
|
expect(projectThumbnailSceneChanged(original, { projectId: "project-2", fingerprint: "scene-b" })).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -54,6 +54,37 @@ describe("shape catalog", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("applies only explicitly customized creation dimensions", () => {
|
||||||
|
const asset: ShapeAsset = { id: "cone", name: "Cone", src: "cone.png", kind: "cone", color: "#6e2786" };
|
||||||
|
const appDefault = makeShapeFromAsset(asset);
|
||||||
|
const customized = makeShapeFromAsset(asset, undefined, { width: 320, depth: 240, height: 180 });
|
||||||
|
|
||||||
|
expect(appDefault).toMatchObject({ width: 20, depth: 20, height: 20, baseRadius: 10 });
|
||||||
|
expect(customized).toMatchObject({ width: 320, depth: 240, height: 180, size: 320, baseRadius: 160 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies shape-specific creation defaults only when customized", () => {
|
||||||
|
const cone = makeShapeFromAsset(
|
||||||
|
{ id: "cone", name: "Cone", src: "cone.png", kind: "cone", color: "#6e2786" },
|
||||||
|
undefined,
|
||||||
|
{ topRadius: 3, baseRadius: 18, sides: 48 },
|
||||||
|
);
|
||||||
|
const text = makeShapeFromAsset(
|
||||||
|
{ id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" },
|
||||||
|
undefined,
|
||||||
|
{ text: "HELLO", font: "Serif", bevel: 2, segments: 6 },
|
||||||
|
);
|
||||||
|
const gear = makeShapeFromAsset(
|
||||||
|
{ id: "gear", name: "Gear", src: "gear.svg", kind: "gear", color: "#6f7f8d" },
|
||||||
|
undefined,
|
||||||
|
{ gearType: "helical", teeth: 24, toothSize: 3, toothWidth: 2, centerHoleSize: 10, helixAngle: 30, helixQuality: 24 },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(cone).toMatchObject({ topRadius: 3, baseRadius: 18, sides: 48 });
|
||||||
|
expect(text).toMatchObject({ text: "HELLO", font: "Serif", bevel: 2, segments: 6 });
|
||||||
|
expect(gear).toMatchObject({ gearType: "helical", teeth: 24, toothSize: 3, toothWidth: 2, centerHoleSize: 10, helixAngle: 30, helixQuality: 24 });
|
||||||
|
});
|
||||||
|
|
||||||
it("creates canonical scene shapes with stable defaults", () => {
|
it("creates canonical scene shapes with stable defaults", () => {
|
||||||
const created = sceneShape({
|
const created = sceneShape({
|
||||||
name: "Part",
|
name: "Part",
|
||||||
|
|||||||
@@ -41,35 +41,38 @@ describe("sketch revolve", () => {
|
|||||||
expect(Math.min(...mesh.positions.filter((_value, index) => index % 3 === 1))).toBeCloseTo(0, 6);
|
expect(Math.min(...mesh.positions.filter((_value, index) => index % 3 === 1))).toBeCloseTo(0, 6);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("creates thickness automatically for an open profile", () => {
|
it("requires a closed profile", () => {
|
||||||
const profile: SketchProfile = {
|
const profile: SketchProfile = {
|
||||||
points: [{ id: "a", x: -8, z: 0 }, { id: "b", x: -8, z: 20 }],
|
points: [{ id: "a", x: -8, z: 0 }, { id: "b", x: -8, z: 20 }],
|
||||||
segments: [{ id: "ab", startId: "a", endId: "b", kind: "line" }],
|
segments: [{ id: "ab", startId: "a", endId: "b", kind: "line" }],
|
||||||
};
|
};
|
||||||
const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 2 });
|
expect(sketchProfileToRevolvePolygons(profile)).toEqual([]);
|
||||||
expect(polygons).toHaveLength(1);
|
expect(() => buildSketchRevolveMesh(runtime, profile, { sides: 24 })).toThrow("Draw at least one closed profile");
|
||||||
expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(7, 6);
|
|
||||||
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeCloseTo(9, 6);
|
|
||||||
const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 2, sides: 24 });
|
|
||||||
expect(mesh.triangleCount).toBeGreaterThan(0);
|
|
||||||
expect(mesh.width).toBeCloseTo(18, 4);
|
|
||||||
expect(mesh.height).toBeCloseTo(20, 4);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("allows construction points across the axis but only revolves the working-side segment", () => {
|
it("clips a closed profile at the revolve axis", () => {
|
||||||
const profile: SketchProfile = {
|
const profile: SketchProfile = {
|
||||||
points: [{ id: "construction", x: 10, z: 0 }, { id: "profile", x: -10, z: 20 }],
|
points: [
|
||||||
segments: [{ id: "crossing", startId: "construction", endId: "profile", kind: "line" }],
|
{ id: "top-right", x: 10, z: 0 },
|
||||||
|
{ id: "top-left", x: -10, z: 0 },
|
||||||
|
{ id: "bottom-left", x: -10, z: 20 },
|
||||||
|
{ id: "bottom-right", x: 10, z: 20 },
|
||||||
|
],
|
||||||
|
segments: [
|
||||||
|
{ id: "top", startId: "top-right", endId: "top-left", kind: "line" },
|
||||||
|
{ id: "left", startId: "top-left", endId: "bottom-left", kind: "line" },
|
||||||
|
{ id: "bottom", startId: "bottom-left", endId: "bottom-right", kind: "line" },
|
||||||
|
{ id: "right", startId: "bottom-right", endId: "top-right", kind: "line" },
|
||||||
|
],
|
||||||
};
|
};
|
||||||
const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 1 });
|
const polygons = sketchProfileToRevolvePolygons(profile);
|
||||||
expect(polygons).toHaveLength(1);
|
expect(polygons).toHaveLength(1);
|
||||||
expect(Math.max(...polygons[0].map((point) => point[1]))).toBeLessThan(11);
|
expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(0, 6);
|
||||||
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeGreaterThan(10);
|
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeCloseTo(10, 6);
|
||||||
|
|
||||||
const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 1, sides: 24 });
|
const mesh = buildSketchRevolveMesh(runtime, profile, { sides: 24 });
|
||||||
expect(mesh.triangleCount).toBeGreaterThan(0);
|
expect(mesh.triangleCount).toBeGreaterThan(0);
|
||||||
expect(mesh.height).toBeGreaterThan(9);
|
expect(mesh.height).toBeCloseTo(20, 4);
|
||||||
expect(mesh.height).toBeLessThan(11);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("supports partial and reverse sweeps", () => {
|
it("supports partial and reverse sweeps", () => {
|
||||||
@@ -82,12 +85,11 @@ describe("sketch revolve", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("normalizes unsafe revolve settings", () => {
|
it("normalizes unsafe revolve settings", () => {
|
||||||
expect(normalizeSketchRevolveSettings({ startAngle: -30, sweepAngle: 0, sides: 500, quality: 0, thickness: -2 })).toEqual({
|
expect(normalizeSketchRevolveSettings({ startAngle: -30, sweepAngle: 0, sides: 900, quality: 0 })).toEqual({
|
||||||
startAngle: 330,
|
startAngle: 330,
|
||||||
sweepAngle: 1,
|
sweepAngle: 1,
|
||||||
sides: 128,
|
sides: 512,
|
||||||
quality: 1,
|
quality: 1,
|
||||||
thickness: 0.1,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { rotateSketchPoints, selectedClosedSketchPoints } from "@/lib/sketchRotation";
|
||||||
|
import type { SketchProfile } from "@/types/sketchforge";
|
||||||
|
|
||||||
|
const rectangle: SketchProfile = {
|
||||||
|
points: [
|
||||||
|
{ id: "a", x: 0, z: 0, handleOut: { x: 1, z: 0 } },
|
||||||
|
{ id: "b", x: 4, z: 0 },
|
||||||
|
{ id: "c", x: 4, z: 2 },
|
||||||
|
{ id: "d", x: 0, z: 2 },
|
||||||
|
],
|
||||||
|
segments: [
|
||||||
|
{ id: "ab", startId: "a", endId: "b" },
|
||||||
|
{ id: "bc", startId: "b", endId: "c" },
|
||||||
|
{ id: "cd", startId: "c", endId: "d" },
|
||||||
|
{ id: "da", startId: "d", endId: "a" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("sketch rotation", () => {
|
||||||
|
it("recognizes a complete closed sketch selection", () => {
|
||||||
|
const points = selectedClosedSketchPoints(rectangle, {
|
||||||
|
pointIds: ["a", "b", "c", "d"],
|
||||||
|
segmentIds: ["ab", "bc", "cd", "da"],
|
||||||
|
});
|
||||||
|
expect(points?.map((point) => point.id)).toEqual(["a", "b", "c", "d"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an open, partial, or image-inclusive selection", () => {
|
||||||
|
expect(selectedClosedSketchPoints(rectangle, {
|
||||||
|
pointIds: ["a", "b", "c", "d"],
|
||||||
|
segmentIds: ["ab", "bc", "cd"],
|
||||||
|
})).toBeNull();
|
||||||
|
expect(selectedClosedSketchPoints(rectangle, {
|
||||||
|
pointIds: ["a", "b", "c", "d"],
|
||||||
|
segmentIds: ["ab", "bc", "cd", "da"],
|
||||||
|
imageIds: ["reference-image"],
|
||||||
|
})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rotates points and bezier handles around the selection bounds center", () => {
|
||||||
|
const rotated = rotateSketchPoints(rectangle.points, 90);
|
||||||
|
const first = rotated.find((point) => point.id === "a");
|
||||||
|
expect(first?.x).toBeCloseTo(3, 8);
|
||||||
|
expect(first?.z).toBeCloseTo(-1, 8);
|
||||||
|
expect(first?.handleOut?.x).toBeCloseTo(3, 8);
|
||||||
|
expect(first?.handleOut?.z).toBeCloseTo(0, 8);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
completeSketchForgeMcpCommand,
|
||||||
|
dispatchSketchForgeMcpCommand,
|
||||||
|
pollSketchForgeMcpCommand,
|
||||||
|
registerSketchForgeMcpEditor,
|
||||||
|
waitForSketchForgeMcpCommand,
|
||||||
|
} from "@/lib/sketchforgeMcpStore";
|
||||||
|
|
||||||
|
const editor = {
|
||||||
|
editorId: "editor-test",
|
||||||
|
editorNumber: 12345,
|
||||||
|
projectId: "project-test",
|
||||||
|
projectName: "MCP test",
|
||||||
|
url: "http://localhost:3000/?editor=1",
|
||||||
|
focused: true,
|
||||||
|
shapeCount: 0,
|
||||||
|
selectedCount: 0,
|
||||||
|
notice: "",
|
||||||
|
lastError: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
delete (globalThis as { __sketchforgeMcpStore?: unknown }).__sketchforgeMcpStore;
|
||||||
|
registerSketchForgeMcpEditor(editor);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("SketchForge MCP long polling", () => {
|
||||||
|
it("delivers a command directly to a waiting editor", async () => {
|
||||||
|
const poll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
|
||||||
|
const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "list_objects" });
|
||||||
|
|
||||||
|
const command = await poll;
|
||||||
|
expect(command).toMatchObject({ action: "list_objects", params: {} });
|
||||||
|
expect(pollSketchForgeMcpCommand(editor.editorId)).toBeNull();
|
||||||
|
|
||||||
|
completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true, data: [] });
|
||||||
|
await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true, data: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows only one pending poll per editor", async () => {
|
||||||
|
const firstPoll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
|
||||||
|
const secondPoll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
|
||||||
|
|
||||||
|
await expect(firstPoll).resolves.toBeNull();
|
||||||
|
const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "inspect_errors" });
|
||||||
|
const command = await secondPoll;
|
||||||
|
expect(command?.action).toBe("inspect_errors");
|
||||||
|
|
||||||
|
completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true });
|
||||||
|
await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes an aborted poll before queueing the next command", async () => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const poll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000, signal: controller.signal });
|
||||||
|
controller.abort();
|
||||||
|
await expect(poll).resolves.toBeNull();
|
||||||
|
|
||||||
|
const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "get_scene" });
|
||||||
|
const command = pollSketchForgeMcpCommand(editor.editorId);
|
||||||
|
expect(command?.action).toBe("get_scene");
|
||||||
|
|
||||||
|
completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true });
|
||||||
|
await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -153,7 +153,7 @@ describe("SketchForge .skf project packages", () => {
|
|||||||
const revolve = shape("mesh", "revolve-sketch", {
|
const revolve = shape("mesh", "revolve-sketch", {
|
||||||
name: "Sketch revolve",
|
name: "Sketch revolve",
|
||||||
sketchOperation: "revolve",
|
sketchOperation: "revolve",
|
||||||
sketchRevolve: { startAngle: 25, sweepAngle: -220, sides: 48, quality: 8, thickness: 1.5 },
|
sketchRevolve: { startAngle: 25, sweepAngle: -220, sides: 48, quality: 8 },
|
||||||
sketchProfile: {
|
sketchProfile: {
|
||||||
points: [{ id: "p1", x: -4, z: 0 }, { id: "p2", x: -8, z: 0 }, { id: "p3", x: -8, z: 16 }, { id: "p4", x: -4, z: 16 }],
|
points: [{ id: "p1", x: -4, z: 0 }, { id: "p2", x: -8, z: 0 }, { id: "p3", x: -8, z: 16 }, { id: "p4", x: -4, z: 16 }],
|
||||||
segments: [
|
segments: [
|
||||||
@@ -402,6 +402,8 @@ describe("SketchForge .skf project packages", () => {
|
|||||||
z: 0,
|
z: 0,
|
||||||
width: 10,
|
width: 10,
|
||||||
depth: 10,
|
depth: 10,
|
||||||
|
lockAspect: true,
|
||||||
|
locked: true,
|
||||||
}],
|
}],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -412,6 +414,7 @@ describe("SketchForge .skf project packages", () => {
|
|||||||
expect(document.assets.filter((entry) => entry.kind === "image")).toHaveLength(1);
|
expect(document.assets.filter((entry) => entry.kind === "image")).toHaveLength(1);
|
||||||
expect(restored.shapes[0].imagePlate?.dataUrl).toBe(dataUrl);
|
expect(restored.shapes[0].imagePlate?.dataUrl).toBe(dataUrl);
|
||||||
expect(restored.shapes[0].sketchProfile?.images?.[0].dataUrl).toBe(dataUrl);
|
expect(restored.shapes[0].sketchProfile?.images?.[0].dataUrl).toBe(dataUrl);
|
||||||
|
expect(restored.shapes[0].sketchProfile?.images?.[0].locked).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("deduplicates derived geometry when legacy imported objects share one mesh", async () => {
|
it("deduplicates derived geometry when legacy imported objects share one mesh", async () => {
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { normalizedRotationPlaneBasis } from "@/components/workplane/transformOverlayTypes";
|
import {
|
||||||
|
continuousSnappedWheelRotation,
|
||||||
|
normalizedRotationPlaneBasis,
|
||||||
|
rotationWheelDirectionSign,
|
||||||
|
snappedRotationDelta,
|
||||||
|
snappedWheelRotation,
|
||||||
|
} from "@/components/workplane/transformOverlayTypes";
|
||||||
|
|
||||||
describe("rotation handle projection", () => {
|
describe("rotation handle projection", () => {
|
||||||
it("preserves face-plane foreshortening while normalizing icon size", () => {
|
it("preserves face-plane foreshortening while normalizing icon size", () => {
|
||||||
@@ -28,4 +34,68 @@ describe("rotation handle projection", () => {
|
|||||||
d: 1,
|
d: 1,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("moves 45-degree rotation in the same screen direction as 22.5-degree rotation", () => {
|
||||||
|
const direction = rotationWheelDirectionSign(1);
|
||||||
|
expect(snappedWheelRotation(-52, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 });
|
||||||
|
expect(snappedWheelRotation(-58, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 });
|
||||||
|
expect(snappedWheelRotation(-69, -80, direction)).toEqual({ delta: 0, pointerAngle: -90 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("switches the wheel rotation and orange indicator to 22.5-degree marks with Shift", () => {
|
||||||
|
const direction = rotationWheelDirectionSign(1);
|
||||||
|
expect(snappedWheelRotation(-58, -80, direction, 22.5)).toEqual({ delta: -22.5, pointerAngle: -67.5 });
|
||||||
|
expect(snappedWheelRotation(-52, -80, direction, 22.5)).toEqual({ delta: -45, pointerAngle: -45 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the current result continuous when switching to 22.5-degree snapping", () => {
|
||||||
|
const direction = rotationWheelDirectionSign(1);
|
||||||
|
const coarse = snappedWheelRotation(-58, -80, direction);
|
||||||
|
const fineAtShift = continuousSnappedWheelRotation(
|
||||||
|
snappedWheelRotation(-58, -80, direction, 22.5),
|
||||||
|
22.5,
|
||||||
|
45,
|
||||||
|
coarse.delta,
|
||||||
|
coarse.pointerAngle,
|
||||||
|
);
|
||||||
|
expect(fineAtShift).toEqual({
|
||||||
|
delta: -45,
|
||||||
|
pointerAngle: -45,
|
||||||
|
deltaOffset: -22.5,
|
||||||
|
pointerOffset: 22.5,
|
||||||
|
});
|
||||||
|
|
||||||
|
const fineForward = continuousSnappedWheelRotation(
|
||||||
|
snappedWheelRotation(-52, -80, direction, 22.5),
|
||||||
|
22.5,
|
||||||
|
22.5,
|
||||||
|
fineAtShift.delta,
|
||||||
|
fineAtShift.pointerAngle,
|
||||||
|
fineAtShift.deltaOffset,
|
||||||
|
fineAtShift.pointerOffset,
|
||||||
|
);
|
||||||
|
expect(fineForward).toEqual({
|
||||||
|
delta: -67.5,
|
||||||
|
pointerAngle: -22.5,
|
||||||
|
deltaOffset: -22.5,
|
||||||
|
pointerOffset: 22.5,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps one-degree rotation outside the wheel", () => {
|
||||||
|
expect(snappedRotationDelta(28.4, false, false)).toBe(28);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retains the Shift 45-degree shortcut outside the wheel", () => {
|
||||||
|
expect(snappedRotationDelta(28, false, true)).toBe(45);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps absolute wheel snapping synchronized when screen rotation is inverted", () => {
|
||||||
|
expect(snappedWheelRotation(-134, -80, -1)).toEqual({ delta: 45, pointerAngle: -135 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("wraps wheel deltas across the -180/180 boundary", () => {
|
||||||
|
expect(snappedWheelRotation(-179, 179)).toEqual({ delta: 0, pointerAngle: -180 });
|
||||||
|
expect(snappedWheelRotation(-134, 179)).toEqual({ delta: 45, pointerAngle: -135 });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||||
import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits } from "@/lib/measurementUnits";
|
import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits } from "@/lib/measurementUnits";
|
||||||
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
|
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, shapeDimensionLimit, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
|
||||||
|
|
||||||
describe("workplane settings helpers", () => {
|
describe("workplane settings helpers", () => {
|
||||||
it("accepts known snap grid values and falls back for unknown values", () => {
|
it("accepts known snap grid values and falls back for unknown values", () => {
|
||||||
@@ -63,6 +63,43 @@ describe("workplane settings helpers", () => {
|
|||||||
expect(normalizeWorkspaceSettings({ gridColor: "not-a-color" }).gridColor).toBe(DEFAULT_WORKPLANE_WORKSPACE.gridColor);
|
expect(normalizeWorkspaceSettings({ gridColor: "not-a-color" }).gridColor).toBe(DEFAULT_WORKPLANE_WORKSPACE.gridColor);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps app limits until a shape receives an explicit customization", () => {
|
||||||
|
const untouched = normalizeWorkspaceSettings({});
|
||||||
|
const customized = normalizeWorkspaceSettings({
|
||||||
|
shapeCustomizations: {
|
||||||
|
box: { width: 48, maxDimension: 720 },
|
||||||
|
sphere: { height: Number.NaN, maxDimension: 9000 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(untouched.shapeCustomizations).toEqual({});
|
||||||
|
expect(shapeDimensionLimit(untouched, "box", 160)).toBe(160);
|
||||||
|
expect(customized.shapeCustomizations.box).toEqual({ width: 48, maxDimension: 720 });
|
||||||
|
expect(customized.shapeCustomizations.sphere).toEqual({ maxDimension: 2000 });
|
||||||
|
expect(shapeDimensionLimit(customized, "box", 160)).toBe(720);
|
||||||
|
expect(shapeDimensionLimit(customized, "cylinder", 220)).toBe(220);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes supported special-shape defaults", () => {
|
||||||
|
const customized = normalizeWorkspaceSettings({
|
||||||
|
shapeCustomizations: {
|
||||||
|
cylinder: { sides: 500 },
|
||||||
|
roundRoof: { sides: 900 },
|
||||||
|
sphere: { steps: 2 },
|
||||||
|
cone: { topRadius: -4, baseRadius: 9000, sides: 40 },
|
||||||
|
text: { text: "A custom label that is much too long", font: "Serif", bevel: 12, segments: 9.6 },
|
||||||
|
gear: { gearType: "helical", teeth: 23.7, toothSize: 3, centerHoleSize: -5, helixAngle: 90, helixQuality: 3 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(customized.shapeCustomizations.cylinder).toEqual({ sides: 500 });
|
||||||
|
expect(customized.shapeCustomizations.roundRoof).toEqual({ sides: 512 });
|
||||||
|
expect(customized.shapeCustomizations.sphere).toEqual({ steps: 6 });
|
||||||
|
expect(customized.shapeCustomizations.cone).toEqual({ topRadius: 0, baseRadius: 1000, sides: 40 });
|
||||||
|
expect(customized.shapeCustomizations.text).toEqual({ text: "A custom label that is m", font: "Serif", bevel: 8, segments: 10 });
|
||||||
|
expect(customized.shapeCustomizations.gear).toEqual({ gearType: "helical", teeth: 24, toothSize: 3, centerHoleSize: 0, helixAngle: 45, helixQuality: 4 });
|
||||||
|
});
|
||||||
|
|
||||||
it("can require selection before a shape starts moving", () => {
|
it("can require selection before a shape starts moving", () => {
|
||||||
expect(canBeginShapeDrag(false, false)).toBe(true);
|
expect(canBeginShapeDrag(false, false)).toBe(true);
|
||||||
expect(canBeginShapeDrag(true, false)).toBe(false);
|
expect(canBeginShapeDrag(true, false)).toBe(false);
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
shapeDepth,
|
shapeDepth,
|
||||||
shapeHasTaper,
|
shapeHasTaper,
|
||||||
shapeOverallFootprintDimensions,
|
shapeOverallFootprintDimensions,
|
||||||
|
shapeTransformShouldRemainEditable,
|
||||||
shapeTaperDimensions,
|
shapeTaperDimensions,
|
||||||
shapeTaperScaleAt,
|
shapeTaperScaleAt,
|
||||||
shapeWidth,
|
shapeWidth,
|
||||||
@@ -129,6 +130,29 @@ describe("workplane shape helpers", () => {
|
|||||||
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined();
|
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps rotated groups editable so they can still be ungrouped", () => {
|
||||||
|
const child = shape({ id: "child" });
|
||||||
|
const group = shape({
|
||||||
|
id: "group",
|
||||||
|
kind: "mesh",
|
||||||
|
rotation: 45,
|
||||||
|
groupedBaseWidth: 20,
|
||||||
|
groupedBaseDepth: 20,
|
||||||
|
groupedBaseHeight: 20,
|
||||||
|
groupedShapes: [child],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(shapeTransformShouldRemainEditable(group)).toBe(true);
|
||||||
|
expect(shapeTransformShouldRemainEditable(shape({ rotation: 45 }))).toBe(false);
|
||||||
|
expect(canonicalizeShape(group)).toMatchObject({
|
||||||
|
rotation: 45,
|
||||||
|
groupedBaseWidth: 20,
|
||||||
|
groupedBaseDepth: 20,
|
||||||
|
groupedBaseHeight: 20,
|
||||||
|
groupedShapes: [{ id: "child" }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("assigns fresh object IDs throughout duplicated group trees", () => {
|
it("assigns fresh object IDs throughout duplicated group trees", () => {
|
||||||
const original = shape({
|
const original = shape({
|
||||||
id: "outer-group",
|
id: "outer-group",
|
||||||
|
|||||||
Reference in New Issue
Block a user