feat: improve shape tools and project previews

This commit is contained in:
Formsmith746
2026-08-28 13:24:32 +03:00
parent 2486b998c8
commit 34528e6393
33 changed files with 2071 additions and 343 deletions
+1 -1
View File
@@ -167,7 +167,7 @@ The container listens on port `3000`. It also accepts connections on port `80` f
### 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:
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <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
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+96 -6
View File
@@ -8,6 +8,10 @@ export const runtime = "nodejs";
export const revalidate = false;
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 = {
fileName: string;
@@ -15,6 +19,7 @@ type SharedProjectFile = {
updatedAt: number;
size: number;
revision: string;
thumbnailUrl?: string;
};
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)}`;
}
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 {
fileName,
name: fileName.replace(/\.skf$/i, ""),
updatedAt: stat.mtimeMs,
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) {
if (!value) return null;
return value.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
@@ -97,6 +136,25 @@ export async function GET(request: Request) {
const filePath = path.join(root, fileName);
const stat = await regularFileStat(filePath);
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);
return new Response(bytes, {
headers: {
@@ -114,7 +172,10 @@ export async function GET(request: Request) {
.filter((entry) => entry.isFile() && /\.skf$/i.test(entry.name))
.map(async (entry) => {
const stat = await regularFileStat(path.join(root, entry.name));
return stat ? projectRecord(entry.name, stat) : null;
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(
{ 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(thumbnailPath).catch((error) => {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
});
return NextResponse.json(
{ deleted: true, fileName },
{ 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 });
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 });
}
let lockHandle: Awaited<ReturnType<typeof fs.open>> | null = null;
let lockPath = "";
let temporaryPath = "";
let temporaryThumbnailPath = "";
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 });
const summary = await inspectSkfProjectPackage(bytes);
const requestUrl = new URL(request.url);
@@ -237,10 +305,31 @@ export async function POST(request: Request) {
} finally {
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);
temporaryPath = "";
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(
{ project: { ...project, name: summary.projectName } },
{ status: currentStat ? 200 : 201, headers: { "Cache-Control": "no-store", ETag: `"${project.revision}"` } },
@@ -250,6 +339,7 @@ export async function POST(request: Request) {
} finally {
if (lockHandle) await lockHandle.close().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);
}
}
@@ -4,9 +4,10 @@ import {
completeSketchForgeMcpCommand,
dispatchSketchForgeMcpCommand,
listSketchForgeMcpEditors,
pollSketchForgeMcpCommand,
registerSketchForgeMcpEditor,
waitForSketchForgeMcpCommand,
} from "@/lib/sketchforgeMcpStore";
import { SKETCHFORGE_MCP_LONG_POLL_TIMEOUT_MS } from "@/lib/sketchforgeMcpProtocol";
export const revalidate = false;
@@ -81,7 +82,11 @@ export async function POST(request: Request) {
if (typeof body.editorId !== "string") {
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") {
+401 -12
View File
@@ -2288,6 +2288,41 @@ button {
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 {
display: grid;
width: 43px;
@@ -2572,6 +2607,19 @@ button {
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 {
overflow: hidden;
min-width: 0;
@@ -3388,7 +3436,7 @@ button {
width: clamp(210px, 25vw, 330px);
height: clamp(170px, 28vh, 270px);
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-radius: 12px;
box-shadow: 0 12px 34px rgba(34, 67, 86, 0.16);
@@ -3411,7 +3459,7 @@ button {
display: block;
width: 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 {
@@ -3474,14 +3522,6 @@ button {
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 {
cursor: grab;
}
@@ -3571,7 +3611,7 @@ button {
}
.sketch-revolve-guide rect {
fill: rgba(248, 251, 252, 0.66);
fill: rgba(31, 105, 134, 0.12);
}
.sketch-revolve-guide line {
@@ -3874,6 +3914,11 @@ button {
background: #fff0f1;
}
.sketch-image-inspector .inspector-header-icon:disabled {
cursor: default;
opacity: 0.38;
}
.sketch-image-preview-card {
display: grid;
place-items: center;
@@ -3999,6 +4044,17 @@ button {
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 {
position: absolute;
top: 22px;
@@ -5748,14 +5804,31 @@ button {
}
.workspace-toggle {
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
column-gap: 16px;
padding-bottom: 16px;
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 {
justify-self: end;
width: 18px;
height: 18px;
margin: 1px 0 0;
accent-color: #0098c7;
}
@@ -6066,6 +6139,181 @@ button {
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 {
min-width: 128px;
height: 34px;
@@ -6599,6 +6847,48 @@ button {
}
@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,
.collaborator {
display: none;
@@ -6653,6 +6943,10 @@ button {
width: 24px;
height: 24px;
}
html[data-theme="dark"] .workspace-settings-nav {
border-bottom-color: #344854;
}
}
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);
}
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"] .toolbar-section,
html[data-theme="dark"] .toolbar-mode-content,
@@ -7021,6 +7324,12 @@ html[data-theme="dark"] .snap-menu .selected {
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"] .snap-menu button,
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);
}
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-state-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);
}
html[data-theme="dark"] .rotate-handle,
html[data-theme="dark"] .rotate-handle:hover {
color: #ffffff;
}
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));
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-note,
html[data-theme="dark"] .workspace-global-note,
html[data-theme="dark"] .workspace-toggle-copy small,
html[data-theme="dark"] .workspace-section-heading span {
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-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;
background: #0f1921;
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 {
color: #d4e3ed;
background: #0f1921;
@@ -7281,10 +7648,32 @@ html[data-theme="dark"] .sketch-workspace-stage {
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 {
fill: #18303a;
}
html[data-theme="dark"] .sketch-revolve-guide rect {
fill: rgba(3, 10, 15, 0.38);
}
html[data-theme="dark"] .sketch-plate-border {
stroke: #43b8d7;
}
+33 -15
View File
@@ -51,6 +51,7 @@ type SharedProject = {
updatedAt: number;
size: number;
revision: string;
thumbnailUrl?: string;
};
type StoredDashboardProject = Partial<DashboardProject> & {
@@ -110,6 +111,7 @@ const PROJECT_SHAPES_STORE_NAME = "projectShapes";
const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources";
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
const PROJECT_NAME_TOOLBAR_STORAGE_KEY = "sketchForge.showProjectNameInToolbar";
const ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY = "sketchForge.activeChallengeTutorial";
const DISMISSED_UPDATE_VERSION_STORAGE_KEY = "sketchForge.dismissedUpdateVersion";
const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"];
@@ -509,6 +511,7 @@ export default function Home() {
const [resolvedTheme, setResolvedTheme] = useState<ResolvedAppTheme>("light");
const [downloadMode, setDownloadMode] = useState<DownloadMode>("browser");
const [downloadFolder, setDownloadFolder] = useState("");
const [showProjectNameInToolbar, setShowProjectNameInToolbar] = useState(true);
const [dashboardNotice, setDashboardNotice] = useState("");
const [sharedProjects, setSharedProjects] = useState<SharedProject[]>([]);
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");
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);
if (params.has("codexBooleanCase") || params.get("editor") === "1") {
@@ -723,7 +727,8 @@ export default function Home() {
if (!mounted) return;
window.localStorage.setItem(DOWNLOAD_MODE_STORAGE_KEY, downloadMode);
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 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();
if (signal?.aborted) throw new DOMException("Thumbnail upload aborted", "AbortError");
if (STATIC_EXPORT_BUILD) {
setProjects((current) =>
current.map((project) =>
@@ -797,19 +803,19 @@ export default function Home() {
setProjects((current) =>
current.map((project) => (project.id === snapshot.projectId ? { ...project, shapes: snapshot.shapes, updatedAt: version } : project)),
);
void fetch("/api/project-thumbnail", {
try {
const response = await fetch("/api/project-thumbnail", {
method: "POST",
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 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) =>
@@ -819,12 +825,13 @@ export default function Home() {
: project,
),
);
})
.catch(() => {
} 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: {
@@ -1027,7 +1034,7 @@ export default function Home() {
}
}, [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);
if (!activeProject) throw new Error("Open a local project before saving it to the shared space");
const normalizedExportName = exportName.trim() || activeProject.name;
@@ -1035,11 +1042,17 @@ export default function Home() {
const fileName = saveBackToSource && activeProject.sharedProject
? activeProject.sharedProject.fileName
: `${normalizedExportName.replace(/\.skf$/i, "")}.skf`;
const headers: Record<string, string> = { "Content-Type": "application/vnd.sketchforge.project+zip" };
const headers: Record<string, string> = {};
if (saveBackToSource && activeProject.sharedProject) headers["If-Match"] = `"${activeProject.sharedProject.revision}"`;
else headers["If-None-Match"] = "*";
const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(fileName)}`, { method: "POST", headers, body });
const 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 };
if (!response.ok || !payload.project) throw new Error(payload.error ?? "Could not save the shared project");
const savedProject = payload.project;
@@ -1289,8 +1302,13 @@ export default function Home() {
onProjectShapesChange={updateProjectShapes}
onProjectSnapshot={updateProjectSnapshot}
onProjectWorkspaceChange={updateProjectWorkspace}
onProjectNameChange={(name) => {
if (activeProjectId) renameProject(activeProjectId, name);
}}
projectId={activeProjectId}
projectName={activeProject?.name}
showProjectNameInToolbar={showProjectNameInToolbar}
onShowProjectNameInToolbarChange={setShowProjectNameInToolbar}
projectCreatedAt={activeProject?.createdAt}
projectModifiedAt={activeProject?.updatedAt}
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
@@ -1745,7 +1763,7 @@ function Dashboard({
{sharedProjects.map((project, index) => (
<article className="project-card shared-project-card" key={project.fileName}>
<button className="project-card-open" type="button" onClick={() => onOpenSharedProject(project)}>
<ProjectPreview accent={PROJECT_ACCENTS[index % PROJECT_ACCENTS.length]} />
<ProjectPreview accent={PROJECT_ACCENTS[index % PROJECT_ACCENTS.length]} thumbnailUrl={project.thumbnailUrl} />
<span className="project-card-title">{project.name}</span>
<span className="project-card-meta">{formatUpdated(project.updatedAt)} - {formatFileSize(project.size)}</span>
</button>
+271 -47
View File
@@ -65,6 +65,7 @@ import {
serializeShapesForSync,
shapeDepth,
shapeHasTaper,
shapeTransformShouldRemainEditable,
shapeTaperScaleAt,
shapeWidth,
withHoleMode,
@@ -88,6 +89,8 @@ import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap
import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
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 { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
@@ -113,7 +116,8 @@ import {
} from "@/lib/placementWorkplane";
import { placeSketchExtrusion } from "@/lib/sketchPlacement";
import {
SKETCHFORGE_MCP_POLL_MS,
SKETCHFORGE_MCP_HEARTBEAT_MS,
SKETCHFORGE_MCP_POLL_RETRY_MS,
SKETCHFORGE_MCP_ROUTE,
type SketchForgeMcpCommand,
type SketchForgeMcpSceneSummary,
@@ -2375,10 +2379,9 @@ function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimiti
}
function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
// Rotation is a non-destructive transform for editable text. Baking it would
// change the shape to `kind: "mesh"`, hiding the Text and Font controls even
// though the user never grouped or otherwise converted the object.
if (shape.kind === "text" || !shapeHasTransformToBake(shape)) {
// Text and groups must retain their editable source data across transforms.
// Baking a group would discard groupedShapes and make Ungroup unavailable.
if (shapeTransformShouldRemainEditable(shape) || !shapeHasTransformToBake(shape)) {
return shape;
}
@@ -5387,11 +5390,14 @@ export function SketchForgeEditor({
onProjectShapesChange,
onProjectSnapshot,
onProjectWorkspaceChange,
onProjectNameChange,
onShowProjectNameInToolbarChange,
projectId,
projectName = "SketchForge design",
projectCreatedAt = Date.now(),
projectModifiedAt = Date.now(),
projectRevision = 0,
showProjectNameInToolbar = true,
sharedProjectsEnabled = false,
challengeTutorial = null,
onChallengeTutorialFinish,
@@ -5409,7 +5415,7 @@ export function SketchForgeEditor({
initialPlacementWorkplane?: PlacementWorkplane;
onHome?: () => 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: {
projectId: string;
shapes: WorkplaneShape[];
@@ -5424,7 +5430,9 @@ export function SketchForgeEditor({
placementWorkplane: PlacementWorkplane;
sketchPlacementWorkplane: PlacementWorkplane;
}) => 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: {
projectId: string;
workspace: WorkplaneWorkspaceSettings;
@@ -5438,6 +5446,7 @@ export function SketchForgeEditor({
projectCreatedAt?: number;
projectModifiedAt?: number;
projectRevision?: number;
showProjectNameInToolbar?: boolean;
sharedProjectsEnabled?: boolean;
challengeTutorial?: ChallengeTutorialId | null;
onChallengeTutorialFinish?: () => void;
@@ -5495,6 +5504,7 @@ export function SketchForgeEditor({
const lastProjectShapesEchoRef = useRef<string | null>(null);
const lastProjectIdRef = useRef<string | null>(null);
const projectSnapshotRunRef = useRef(0);
const lastProjectSnapshotRef = useRef<ProjectThumbnailSceneKey | null>(null);
const shapesRef = useRef(shapes);
const projectAssetsRef = useRef(projectAssets);
const selectedIdsRef = useRef(selectedIds);
@@ -5947,28 +5957,52 @@ export function SketchForgeEditor({
);
useEffect(() => {
const runId = projectSnapshotRunRef.current + 1;
projectSnapshotRunRef.current = runId;
if (!projectId || !onProjectSnapshot || typeof window === "undefined") {
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) {
return;
}
const runId = projectSnapshotRunRef.current + 1;
projectSnapshotRunRef.current = runId;
let stopped = false;
let uploadController: AbortController | null = null;
const capture = async () => {
if (projectSnapshotRunRef.current !== runId) {
if (stopped || projectSnapshotRunRef.current !== runId) {
return true;
}
const image = window.sketchforgeCaptureCanvasAsync
? await window.sketchforgeCaptureCanvasAsync()
: window.sketchforgeCaptureCanvas?.() ?? "";
if (projectSnapshotRunRef.current !== runId) {
if (stopped || projectSnapshotRunRef.current !== runId) {
return true;
}
if (image && image.length > 100) {
onProjectSnapshot({ image, projectId, shapes: shapes.length });
const controller = new AbortController();
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;
};
@@ -5988,8 +6022,10 @@ export function SketchForgeEditor({
} else {
runCapture();
}
}, 850);
}, PROJECT_THUMBNAIL_IDLE_MS);
return () => {
stopped = true;
uploadController?.abort();
window.clearTimeout(captureTimer);
if (retryTimer !== null) window.clearTimeout(retryTimer);
if (idleId !== null && "cancelIdleCallback" in window) window.cancelIdleCallback(idleId);
@@ -6558,7 +6594,7 @@ export function SketchForgeEditor({
const label = primitive[0]!.toUpperCase() + primitive.slice(1);
commitSketchProfile(next, `${label} added to sketch`);
setSketchActivePointId(null);
setSketchSelection({ kind: "multiple", pointIds: points.map((point) => point.id), segmentIds: segments.map((segment) => segment.id), imageIds: [] });
setSketchSelection(null);
setSketchTool("select");
},
[commitSketchProfile, sketchProfile],
@@ -6626,6 +6662,10 @@ export function SketchForgeEditor({
const updateSketchImage = useCallback((id: string, patch: Partial<SketchImage>, message = "Sketch image updated") => {
const image = (sketchProfile.images ?? []).find((entry) => entry.id === id);
if (!image) return;
if (image.locked && patch.locked !== false) {
setNotice("Unlock the sketch image with L before editing it");
return;
}
commitSketchProfile({
...sketchProfile,
images: (sketchProfile.images ?? []).map((entry) => entry.id === id ? { ...entry, ...patch } : entry),
@@ -6635,7 +6675,12 @@ export function SketchForgeEditor({
}, [commitSketchProfile, sketchProfile]);
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({
...sketchProfile,
images: (sketchProfile.images ?? []).filter((image) => image.id !== id),
@@ -6665,6 +6710,7 @@ export function SketchForgeEditor({
depth: dimensions.depth,
opacity: 0.55,
lockAspect: true,
locked: false,
};
commitSketchProfile({ ...sketchProfile, images: [...(sketchProfile.images ?? []), image] }, `Added ${file.name} to the sketch`);
setSketchSelection({ kind: "image", id: image.id });
@@ -6674,6 +6720,23 @@ export function SketchForgeEditor({
}
}, [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(() => {
if (!sketchSelection) {
setNotice("Select a sketch point or segment to remove it");
@@ -6723,6 +6786,19 @@ export function SketchForgeEditor({
}, message);
}, [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 next = cloneSketchProfile(sketchProfile);
const point = next.points.find((entry) => entry.id === id);
@@ -6873,7 +6949,7 @@ export function SketchForgeEditor({
const addShape = useCallback(
(asset: ShapeAsset, point?: PlacementPoint) => {
const shape = makeShapeFromAsset(asset);
const shape = makeShapeFromAsset(asset, undefined, workspaceSettingsRef.current.shapeCustomizations[asset.kind]);
const nextShape = {
...shape,
...placementPatchForNewShape(shape, placementWorkplane, point ?? placementWorkplane.origin),
@@ -8226,6 +8302,8 @@ export function SketchForgeEditor({
const identity = readMcpEditorIdentity();
let stopped = false;
let polling = false;
let pollAbortController: AbortController | null = null;
let pollRetryTimer: number | null = null;
const heartbeat = () => {
const projectInfo = projectInfoRef.current;
@@ -8265,12 +8343,16 @@ export function SketchForgeEditor({
const poll = async () => {
if (polling || stopped) return;
polling = true;
let retry = false;
pollAbortController = new AbortController();
try {
const response = await fetch(SKETCHFORGE_MCP_ROUTE, {
method: "POST",
headers: { "Content-Type": "application/json" },
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 command = payload?.command;
if (command) {
@@ -8281,23 +8363,35 @@ export function SketchForgeEditor({
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.
retry = !stopped && (!(error instanceof DOMException) || error.name !== "AbortError");
} finally {
pollAbortController = null;
polling = false;
if (!stopped) {
if (retry) {
pollRetryTimer = window.setTimeout(() => {
pollRetryTimer = null;
void poll();
}, SKETCHFORGE_MCP_POLL_RETRY_MS);
} else {
void poll();
}
}
}
};
heartbeat();
void poll();
const heartbeatTimer = window.setInterval(heartbeat, 1000);
const pollTimer = window.setInterval(() => void poll(), SKETCHFORGE_MCP_POLL_MS);
const heartbeatTimer = window.setInterval(heartbeat, SKETCHFORGE_MCP_HEARTBEAT_MS);
window.addEventListener("focus", heartbeat);
document.addEventListener("visibilitychange", heartbeat);
return () => {
stopped = true;
window.clearInterval(heartbeatTimer);
window.clearInterval(pollTimer);
if (pollRetryTimer !== null) window.clearTimeout(pollRetryTimer);
pollAbortController?.abort();
window.removeEventListener("focus", heartbeat);
document.removeEventListener("visibilitychange", heartbeat);
};
@@ -8543,10 +8637,16 @@ export function SketchForgeEditor({
setSkfExporting(true);
setNotice(target === "shared" ? "Packaging project for Docker shared storage…" : "Packaging editable project, history, and deduplicated assets…");
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 bytes = await exportSkfProject({
projectId: projectInfoRef.current.projectId,
projectName: exportName.trim() || projectName,
projectName,
createdAt: projectCreatedAt,
modifiedAt: projectModifiedAt,
shapes: shapesRef.current,
@@ -8560,7 +8660,7 @@ export function SketchForgeEditor({
sketchPlacementWorkplane: placementWorkplane,
});
if (target === "shared" && onSaveSharedProject) {
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes }));
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes, thumbnailDataUrl }));
} else {
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
const result = await downloadBlobFile(projectExportFileName(exportName, "skf"), new Blob([buffer], { type: SKF_MEDIA_TYPE }));
@@ -8864,6 +8964,12 @@ export function SketchForgeEditor({
} else if (shortcut && key === "y") {
event.preventDefault();
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;
}
@@ -8953,12 +9059,6 @@ export function SketchForgeEditor({
return;
}
if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r") && hasSelection) {
event.preventDefault();
rotateSelected45();
return;
}
const step = event.shiftKey ? 5 : 1;
if (shortcut && event.key === "ArrowUp") {
event.preventDefault();
@@ -8987,9 +9087,6 @@ export function SketchForgeEditor({
} else if (key === "s") {
event.preventDefault();
setSelectionHoleMode(false);
} else if (key === "l") {
event.preventDefault();
toggleAlignMode();
} else if (key === "m") {
event.preventDefault();
toggleMirrorMode();
@@ -9013,7 +9110,7 @@ export function SketchForgeEditor({
pasteShape,
raiseSelected,
redo,
rotateSelected45,
rotateSelectedClosedSketch45,
sketchActive,
sketchRedo,
sketchMeasurement,
@@ -9021,10 +9118,10 @@ export function SketchForgeEditor({
sketchUndo,
setSelectionHoleMode,
showHidden,
toggleAlignMode,
toggleHidden,
toggleMirrorMode,
toggleLocked,
toggleSelectedSketchImageLock,
toolbarMode,
undo,
ungroupSelected,
@@ -9034,6 +9131,9 @@ export function SketchForgeEditor({
<div className="sketchforge-editor">
<SecondaryToolbar
toolbarMode={toolbarMode}
projectName={projectName}
onProjectNameChange={onProjectNameChange}
showProjectNameInToolbar={showProjectNameInToolbar}
onToolbarModeChange={(mode) => {
setToolbarMode(mode);
setWorkplaneMode(false);
@@ -9161,6 +9261,8 @@ export function SketchForgeEditor({
initialSnap={snapGrid}
initialWorkspace={workspaceSettings}
workspaceSettingsKey={projectId ?? "local-workplane"}
showProjectNameInToolbar={showProjectNameInToolbar}
onShowProjectNameInToolbarChange={onShowProjectNameInToolbarChange}
onAddShape={addShape}
onAlignAnchorChange={chooseAlignAnchor}
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({
toolbarMode,
projectName,
onProjectNameChange,
showProjectNameInToolbar,
onToolbarModeChange,
alignMode,
canAlign,
@@ -9390,6 +9502,9 @@ function SecondaryToolbar({
onAddShape,
}: {
toolbarMode: ToolbarMode;
projectName: string;
onProjectNameChange?: (name: string) => void;
showProjectNameInToolbar: boolean;
onToolbarModeChange: (mode: ToolbarMode) => void;
alignMode: boolean;
canAlign: boolean;
@@ -9445,10 +9560,37 @@ function SecondaryToolbar({
const [sketchCreateOpen, setSketchCreateOpen] = useState(false);
const [visibilityOpen, setVisibilityOpen] = useState(false);
const [visibilityMenuPosition, setVisibilityMenuPosition] = useState({ top: 0, left: 0 });
const shapesMenuRef = useRef<HTMLDivElement>(null);
const sketchCreateMenuRef = useRef<HTMLDivElement>(null);
const visibilityMenuRef = useRef<HTMLDivElement>(null);
const touchShapeStartRef = useRef<{ id: string; x: number; y: number } | null>(null);
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") => {
setShapesOpen(false);
setSketchCreateOpen(false);
@@ -9460,6 +9602,10 @@ function SecondaryToolbar({
onAddShape(shape);
setShapesOpen(false);
};
const addSketchShapeFromMenu = (primitive: SketchPrimitive) => {
onSketchPrimitive(primitive);
setShapesOpen(false);
};
const startSketch = (operation: SketchOperation) => {
setSketchCreateOpen(false);
onStartSketch(operation);
@@ -9481,7 +9627,23 @@ function SecondaryToolbar({
}, [sketchCreateOpen]);
useEffect(() => {
if (sketchActive) setSketchCreateOpen(false);
else setShapesOpen(false);
}, [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(() => {
if (!visibilityOpen) return;
const closeOnPointerDown = (event: PointerEvent) => {
@@ -9605,7 +9767,7 @@ function SecondaryToolbar({
<div className="toolbar-section-label">History</div>
<div className="toolbar-section-tools">{leftTools.slice(4).map(renderToolButton)}</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-tools">
<button
@@ -9692,7 +9854,35 @@ function SecondaryToolbar({
) : null}
</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="toolbar-section compact toolbar-visibility-section" ref={visibilityMenuRef}>
<div className="toolbar-section-label">Visibility</div>
@@ -9784,22 +9974,50 @@ function SecondaryToolbar({
</button>
</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-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"); }}>
<SquareIcon size={25} strokeWidth={1.8} />
</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"); }}>
<CircleIcon size={25} strokeWidth={1.8} />
</button>
<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"); }}>
<TriangleIcon size={25} strokeWidth={1.8} />
</button>
<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"); }}>
<HexagonIcon size={25} strokeWidth={1.8} />
<button
className={`shape-menu-trigger ${shapesOpen ? "active" : ""}`}
type="button"
aria-label="Add sketch shape"
aria-haspopup="menu"
aria-expanded={shapesOpen}
onClick={() => {
setSketchCreateOpen(false);
setVisibilityOpen(false);
setShapesOpen((open) => !open);
}}
>
<ToolbarShapeAddIcon />
</button>
</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 className="toolbar-section sketch-edit-section">
<div className="toolbar-section-label">Select</div>
@@ -9958,7 +10176,13 @@ function TopActionPanel({
}) {
const [exportFormat, setExportFormat] = useState<ExportFormat>("stl");
const [exportName, setExportName] = useState(projectName);
const previousProjectNameRef = useRef(projectName);
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 skfHistoryLimitIndex = skfHistoryLimits.indexOf(skfHistoryLimit);
const title =
@@ -66,7 +66,7 @@ export function SketchRevolvePreview({ positions }: { positions: number[] | null
return (
<aside className="sketch-revolve-preview" aria-label="Revolve 3D preview">
<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>
);
}
+28 -55
View File
@@ -1,6 +1,6 @@
"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 { SnapGridControl } from "@/components/workplane/ShapeInspector";
import { SketchRevolvePreview } from "@/components/SketchRevolvePreview";
@@ -758,7 +758,7 @@ export function SketchWorkspace({
minZ: selectedImage.z - selectedImage.depth / 2,
maxZ: selectedImage.z + selectedImage.depth / 2,
} : 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: "n", x: selectedImage.x, 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 ? [
{ 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: "e", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.cz },
{ 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: "w", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.cz },
] : [];
const referenceFootprints = useMemo(
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
@@ -839,6 +835,7 @@ export function SketchWorkspace({
<image
key={image.id}
data-sketch-entity="image"
className={image.locked ? "locked" : undefined}
aria-label={image.name}
href={image.dataUrl}
x={image.x - image.width / 2}
@@ -856,6 +853,8 @@ export function SketchWorkspace({
return;
}
if (event.button !== 0 || tool !== "select") return;
onSelectImage(image.id);
if (image.locked) return;
const point = pointFromEvent(event);
if (!point) return;
beginEntityDrag(event, {
@@ -903,29 +902,6 @@ export function SketchWorkspace({
<g className="sketch-profile-fills" pointerEvents="none">
{paths.some((path) => path.closed) ? <path d={paths.filter((path) => path.closed).map(pathData).join(" ")} /> : null}
</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">
{displayProfile.segments.map((segment) => (
<path
@@ -959,16 +935,7 @@ export function SketchWorkspace({
}
}
else if (event.button === 0 && tool === "select" && point) {
const closedPath = paths.find((path) => path.closed && path.steps.some((step) => step.segment.id === 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);
}}
/>
@@ -1130,17 +1097,8 @@ export function SketchWorkspace({
} else if (tool === "erase" || tool === "refine") {
onDeletePoint(point.id);
} else if (event.button === 0 && tool === "select") {
const closedPath = paths.find((path) => path.closed && path.points.some((entry) => entry.id === point.id));
if (closedPath) {
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) {
onPointPress(point.id);
}
@@ -1270,7 +1228,16 @@ function SketchImageInspector({
</button>
<strong>{image.name}</strong>
<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} />
</button>
</div>
@@ -1282,12 +1249,12 @@ function SketchImageInspector({
<div className="property-card">
<div className="property-card-header static"><span>Properties</span></div>
<div className="property-list">
<SketchImageRange label="Width" value={image.width} min={0.5} max={200} accuracy={accuracy} onChange={updateWidth} />
<SketchImageRange label="Height" value={image.depth} min={0.5} max={200} accuracy={accuracy} 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")} />
<SketchImagePositionField label="Position X" value={image.x} accuracy={accuracy} onChange={(x) => onUpdate({ x }, "Sketch image moved")} />
<SketchImagePositionField label="Position Y" value={image.z} accuracy={accuracy} 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")}>
<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} disabled={image.locked} onChange={updateDepth} />
<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} disabled={image.locked} onChange={(x) => onUpdate({ x }, "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" disabled={image.locked} onClick={() => onUpdate({ lockAspect: image.lockAspect === false }, "Image aspect ratio setting updated")}>
{image.lockAspect !== false ? <Link size={17} /> : <Link2Off size={17} />}
<span>{image.lockAspect !== false ? "Aspect ratio locked" : "Aspect ratio unlocked"}</span>
</button>
@@ -1304,6 +1271,7 @@ function SketchImageRange({
max,
accuracy,
suffix = "mm",
disabled = false,
onChange,
}: {
label: string;
@@ -1312,6 +1280,7 @@ function SketchImageRange({
max: number;
accuracy: 1 | 2 | 3;
suffix?: string;
disabled?: boolean;
onChange: (value: number) => void;
}) {
const safeValue = clamp(Number.isFinite(value) ? value : min, min, max);
@@ -1331,13 +1300,14 @@ function SketchImageRange({
type="text"
inputMode="decimal"
value={draft}
disabled={disabled}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
/>
<span>{suffix}</span>
</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>
);
}
@@ -1346,11 +1316,13 @@ function SketchImagePositionField({
label,
value,
accuracy,
disabled = false,
onChange,
}: {
label: string;
value: number;
accuracy: 1 | 2 | 3;
disabled?: boolean;
onChange: (value: number) => void;
}) {
const formatted = formatDimension(value, accuracy);
@@ -1370,6 +1342,7 @@ function SketchImagePositionField({
type="text"
inputMode="decimal"
value={draft}
disabled={disabled}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
+94 -28
View File
@@ -42,16 +42,23 @@ import {
type PlacementWorkplane,
} from "@/lib/placementWorkplane";
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 { 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 type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
import {
TransformOverlay,
continuousSnappedWheelRotation,
getElevationMeasureKey,
measureKeyForHandle,
normalizedRotationPlaneBasis,
rotationWheelDirectionSign,
ROTATION_WHEEL_SHIFT_SNAP_DEGREES,
ROTATION_WHEEL_SNAP_DEGREES,
snappedRotationDelta,
snappedWheelRotation,
type DimensionMark,
type EditingDimension,
type EditingRotation,
@@ -182,6 +189,8 @@ type WorkplaneViewportProps = {
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
workspaceSettingsKey?: string | null;
showProjectNameInToolbar?: boolean;
onShowProjectNameInToolbarChange?: (show: boolean) => void;
onAddShape: (shape: ShapeAsset, point?: PlacementPoint) => void;
onAlignAnchorChange: (id: string) => void;
onAlignPreview: (axis: AlignAxis, target: AlignTarget) => void;
@@ -439,10 +448,16 @@ type TransformDragState = {
rotationPivot?: THREE.Vector3;
rotationPlaneCenter?: THREE.Vector3;
rotationPlaneView?: RotationPlaneView;
rotationStartPointerAngle?: number;
rotationStartVector?: THREE.Vector3;
rotationScreenCenter?: { x: number; y: number };
rotationScreenSign?: number;
rotationStartQuaternion?: THREE.Quaternion;
rotationWheelAppliedDelta?: number;
rotationWheelAppliedPointerAngle?: number;
rotationWheelDeltaOffset?: number;
rotationWheelPointerOffset?: number;
rotationWheelSnapDegrees?: number;
wheelCenter?: RotationWheelView;
hasMoved?: boolean;
};
@@ -630,10 +645,6 @@ function rotationPatchFromQuaternion(quaternion: THREE.Quaternion): Partial<Work
};
}
function shouldPreserveDrawingBufferForLocalAutomation() {
return typeof window !== "undefined";
}
function canvasPngDataUrl(canvas: HTMLCanvasElement) {
return new Promise<string>((resolve) => {
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) {
const cameraForward = camera.getWorldDirection(new THREE.Vector3());
return axisVector.dot(cameraForward) >= 0 ? 1 : -1;
@@ -1978,6 +2000,7 @@ function resizeShapeFromFrameHandle(
shiftKey: boolean,
altKey: boolean,
step: number,
maxSize: number,
): Partial<WorkplaneShape> {
const shape = transform.startShape;
const frame = transform.selectionFrame;
@@ -1986,8 +2009,6 @@ function resizeShapeFromFrameHandle(
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
const signs = transform.scaleSigns ?? resizeSignsForHandle(handleKey);
const maxSize = 220;
const axisResize = (current: number, delta: number, sign: number) => {
if (!sign) {
return current;
@@ -2203,6 +2224,7 @@ function resizeSelectionFromHandle(
shiftKey: boolean,
altKey: boolean,
step: number,
maxSize: number,
) {
const frame = transform.selectionFrame;
const localDelta = transform.scaleStartPoint ? frameLocalDelta(frame, transform.scaleStartPoint, point) : new THREE.Vector3();
@@ -2213,11 +2235,11 @@ function resizeSelectionFromHandle(
}
const signedDelta = sign * delta;
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) };
}
const rawSize = current + signedDelta;
const size = snapDimension(rawSize, step, MIN_SHAPE_SIZE, 260);
const size = snapDimension(rawSize, step, MIN_SHAPE_SIZE, maxSize);
return {
size,
scale: size / Math.max(MIN_SHAPE_SIZE, current),
@@ -2228,9 +2250,9 @@ function resizeSelectionFromHandle(
let nextZ = axisResize(frame.depth, localDelta.z, signs.z);
if (shiftKey && signs.x && signs.z) {
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 width = snapDimension(frame.width * limitedScale, step, MIN_SHAPE_SIZE, 260);
const depth = snapDimension(frame.depth * limitedScale, step, MIN_SHAPE_SIZE, 260);
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, maxSize);
const depth = snapDimension(frame.depth * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
nextX = {
size: 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.yAxis.clone().multiplyScalar(localCenter.y))
.add(frame.zAxis.clone().multiplyScalar(localCenter.z * nextZ.scale));
const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, 260);
const depth = snapDimension(shapeDepth(item.startShape) * nextZ.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, maxSize);
const actualScaleX = width / Math.max(MIN_SHAPE_SIZE, shapeWidth(item.startShape));
const actualScaleZ = depth / Math.max(MIN_SHAPE_SIZE, shapeDepth(item.startShape));
const patch = {
@@ -2283,6 +2305,8 @@ export function WorkplaneViewport({
initialSnap,
initialWorkspace,
workspaceSettingsKey,
showProjectNameInToolbar = true,
onShowProjectNameInToolbarChange,
onAddShape,
onAlignAnchorChange,
onAlignPreview,
@@ -2835,7 +2859,7 @@ export function WorkplaneViewport({
window.sketchforgeCaptureCanvasAsync = () => {
state.camera.updateMatrixWorld();
state.renderer.render(state.scene, state.camera);
return canvasPngDataUrl(state.renderer.domElement);
return thumbnailPngDataUrl(state.renderer.domElement);
};
window.sketchforgeCaptureView = (face = "current") => {
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 rotationStartPoint = kind === "rotate" && state ? rayPointOnRotationPlane(state, event.clientX, event.clientY, rotationPlaneCenter, axisVector) : null;
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"
? localResizePlaneForFrame(frame, workplaneFootprintY(frame, activeWorkplane))
: undefined;
@@ -3430,6 +3457,7 @@ export function WorkplaneViewport({
rotationPivot: kind === "rotate" ? pivot : undefined,
rotationPlaneCenter: kind === "rotate" ? rotationPlaneCenter : undefined,
rotationPlaneView: kind === "rotate" ? rotationPlane : undefined,
rotationStartPointerAngle,
rotationStartVector: kind === "rotate" ? rotationStartVector : undefined,
rotationScreenCenter: rotationCenter,
rotationScreenSign: kind === "rotate" && state ? rotationScreenSign(axisVector, state.camera) : 1,
@@ -3558,10 +3586,11 @@ export function WorkplaneViewport({
: 0;
const resizingFromBottom = transform.handleKey === "bottom-height";
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(
transform.selectionFrame.height + snapValue(rawFrameHeight - transform.selectionFrame.height, step),
MIN_SHAPE_SIZE,
180,
maxHeight,
);
transform.items.forEach((item) => {
onUpdateShape(
@@ -3611,10 +3640,12 @@ export function WorkplaneViewport({
return true;
}
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);
} 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;
}
@@ -3647,14 +3678,43 @@ export function WorkplaneViewport({
transform.wheelCenter
&& Math.hypot(localClientX - transform.wheelCenter.x, localClientY - transform.wheelCenter.y) <= transform.wheelCenter.radius
);
let delta: number;
if (shiftKey) {
delta = Math.round(rawDelta / 45) * 45;
} else if (insideSnapWheel) {
delta = Math.round(rawDelta / 22.5) * 22.5;
const rawPointerAngle = rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter);
const wheelSnapDegrees = shiftKey ? ROTATION_WHEEL_SHIFT_SNAP_DEGREES : ROTATION_WHEEL_SNAP_DEGREES;
const wheelScreenSign = rotationWheelDirectionSign(transform.rotationScreenSign ?? 1);
const snappedWheel = insideSnapWheel
? 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 {
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 rotationDelta = deltaQuaternion.clone();
@@ -3664,7 +3724,7 @@ export function WorkplaneViewport({
y: transform.wheelCenter ? transform.wheelCenter.y - 92 : localClientY - 18,
text: `${Number(delta.toFixed(1))}°`,
angle: delta,
pointerAngle: rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter),
pointerAngle: wheelRotation?.pointerAngle ?? rawPointerAngle,
});
}
transform.items.forEach((item) => {
@@ -3798,7 +3858,8 @@ export function WorkplaneViewport({
return;
}
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") {
const frame = selectionFrameForShapes([shape], [shape.id]);
if (shapeHasTaper(shape) && frame) {
@@ -4185,6 +4246,9 @@ export function WorkplaneViewport({
rotationPivot: handle.kind === "rotate" ? pivot : undefined,
rotationPlaneCenter: handle.kind === "rotate" ? rotationPlaneCenter : undefined,
rotationPlaneView: handle.kind === "rotate" ? rotationPlane : undefined,
rotationStartPointerAngle: handle.kind === "rotate"
? rotationPlanePointerAngle(rotationPlane, localClientX, localClientY, rotationCenter ?? { x: localClientX, y: localClientY })
: undefined,
rotationStartVector: handle.kind === "rotate" ? rotationStartVector : undefined,
rotationScreenCenter: rotationCenter,
rotationScreenSign: handle.kind === "rotate" ? rotationScreenSign(axisVector, state.camera) : 1,
@@ -5070,10 +5134,12 @@ export function WorkplaneViewport({
snap={snap}
themePreference={themePreference}
moveDimensionsEnabled={moveDimensionsEnabled}
showProjectNameInToolbar={showProjectNameInToolbar}
onWorkspaceChange={setWorkspace}
onSnapChange={setSnap}
onThemePreferenceChange={onThemePreferenceChange}
onMoveDimensionsEnabledChange={changeMoveDimensionsEnabled}
onShowProjectNameInToolbarChange={onShowProjectNameInToolbarChange}
onMakeDefault={makeWorkspaceDefault}
onClose={() => setSettingsOpen(false)}
/>
@@ -5097,7 +5163,7 @@ export function WorkplaneViewport({
}
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.setSize(host.clientWidth, host.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
@@ -7175,7 +7241,7 @@ function enableAcceleratedMeshPicking(mesh: THREE.Mesh, geometry: THREE.BufferGe
mesh.raycast = acceleratedRaycast;
const bvhGeometry = geometry as THREE.BufferGeometry & { boundsTree?: unknown };
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 { resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeWidth } from "@/lib/workplaneShapes";
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
import { MAX_HIGH_RESOLUTION_SIDES } from "@/lib/workplaneSettings";
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"];
@@ -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);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
function getShapePropertiesWithAppLimits(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate, textWidthMax = 260): ShapePropertyConfig[] {
const baseWidth = shapeWidth(shape);
const baseDepth = shapeDepth(shape);
const footprint = shapeOverallFootprintDimensions(shape);
@@ -159,8 +160,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
return [
{ 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: "Sides", value: settings.sides, min: 3, max: 128, step: 1, onChange: (sides) => updateRevolve({ sides }) },
{ label: "Thickness", value: settings.thickness, min: 0.1, max: 20, step: 0.1, onChange: (thickness) => updateRevolve({ thickness }) },
{ label: "Sides", value: settings.sides, min: 3, max: MAX_HIGH_RESOLUTION_SIDES, step: 1, onChange: (sides) => updateRevolve({ sides }) },
{ 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: "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") {
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: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ 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: "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: "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") {
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: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ 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",
onChange: (text) => {
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 });
},
},
@@ -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({
shape,
snap,
@@ -379,7 +391,7 @@ export function ShapeInspector({
}) {
const solidColor = shape.color;
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 primaryProperties = shape.kind === "gear"
? 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))
: [];
const taper = shapeTaperDimensions(shape);
const taperDimensionMax = workspace.shapeCustomizations[shape.kind]?.maxDimension ?? 480;
const taperProperties: ShapePropertyConfig[] = shape.kind === "gear" ? [] : [
{
label: "Top Length",
value: taper.topDepth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperTopDepth) => onUpdate({ taperTopDepth, taperTopWidth: taper.topWidth, taperTopScale: undefined }),
},
{
label: "Top Width",
value: taper.topWidth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperTopWidth) => onUpdate({ taperTopWidth, taperTopDepth: taper.topDepth, taperTopScale: undefined }),
},
{
label: "Bottom Length",
value: taper.bottomDepth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperBottomDepth) => onUpdate({ taperBottomDepth, taperBottomWidth: taper.bottomWidth, taperBottomScale: undefined }),
},
{
label: "Bottom Width",
value: taper.bottomWidth,
min: MIN_SHAPE_SIZE,
max: 480,
max: taperDimensionMax,
onChange: (taperBottomWidth) => onUpdate({ taperBottomWidth, taperBottomDepth: taper.bottomDepth, taperBottomScale: undefined }),
},
];
@@ -7,9 +7,15 @@ import {
} from "@/components/workplane/transformOverlayTypes";
export {
continuousSnappedWheelRotation,
getElevationMeasureKey,
measureKeyForHandle,
normalizedRotationPlaneBasis,
rotationWheelDirectionSign,
snappedRotationDelta,
snappedWheelRotation,
ROTATION_WHEEL_SHIFT_SNAP_DEGREES,
ROTATION_WHEEL_SNAP_DEGREES,
type DimensionMark,
type EditingDimension,
type EditingRotation,
@@ -1,16 +1,18 @@
"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 { createPortal } from "react-dom";
import { HexColorInput, HexColorPicker } from "react-colorful";
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 { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { shapeAssetDefaultDimensions, shapeAssetSpecialDefaults, toolbarShapeAssets } from "@/lib/shapeCatalog";
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 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 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 HISTORY_LIMIT_OPTIONS = [30, 50, 100, "unlimited", "custom"] as const;
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) {
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;
}
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({
workspace,
snap,
themePreference,
moveDimensionsEnabled,
showProjectNameInToolbar,
onWorkspaceChange,
onSnapChange,
onThemePreferenceChange,
onMoveDimensionsEnabledChange,
onShowProjectNameInToolbarChange,
onMakeDefault,
onClose,
}: {
@@ -60,15 +126,18 @@ export function WorkspaceSettingsModal({
snap: GridSize;
themePreference: AppThemePreference;
moveDimensionsEnabled: boolean;
showProjectNameInToolbar: boolean;
onWorkspaceChange: (next: WorkspaceSettings) => void;
onSnapChange: (next: GridSize) => void;
onThemePreferenceChange?: (preference: AppThemePreference) => void;
onMoveDimensionsEnabledChange: (enabled: boolean) => void;
onShowProjectNameInToolbarChange?: (show: boolean) => void;
onMakeDefault: () => void;
onClose: () => void;
}) {
const [defaultSaved, setDefaultSaved] = useState(false);
const [activeSection, setActiveSection] = useState<WorkspaceSettingsSection>("appearance");
const [selectedShapeKind, setSelectedShapeKind] = useState<ShapeKind>(toolbarShapeAssets[0].kind);
const [dimensionDrafts, setDimensionDrafts] = useState(() => ({
width: workspace.width.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)
? 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(() => {
setDimensionDrafts({
width: workspace.width.toFixed(workspace.accuracy),
@@ -107,6 +186,56 @@ export function WorkspaceSettingsModal({
const next = { ...workspace, ...patch };
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 parsed = parseMeasurementInput(value);
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} />
<span>Workplane</span>
</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")}>
<History size={18} />
<span>History</span>
@@ -197,6 +330,11 @@ export function WorkspaceSettingsModal({
</select>
</label>
<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
label="Show movement dimensions"
checked={moveDimensionsEnabled}
@@ -334,6 +472,139 @@ export function WorkspaceSettingsModal({
</>
) : 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&apos;s existing resize ceilings, up to 2000 mm.</p>
</div>
</>
) : null}
{activeSection === "history" ? (
<>
<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 (
<label className="workspace-toggle">
<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)} />
</label>
);
@@ -15,6 +15,65 @@ export type RotationPlaneView = {
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 {
const longestAxis = Math.max(Math.hypot(plane.a, plane.b), Math.hypot(plane.c, plane.d));
if (!Number.isFinite(longestAxis) || longestAxis < 0.000001) {
+30
View File
@@ -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;
}
+81 -23
View File
@@ -1,7 +1,21 @@
import { canonicalizeShape } from "@/lib/workplaneShapes";
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 type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
import {
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 };
@@ -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" },
];
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 {
const width = shape.width ?? 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 {
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text" || asset.kind === "gear";
const size = asset.kind === "gear" ? 30 : roundProfile ? 22 : 20;
const height = asset.kind === "gear" ? 6 : asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
const width = asset.kind === "text" ? 86 : size;
const depth = asset.kind === "text" ? 28 : size;
export function makeShapeFromAsset(
asset: ShapeAsset,
point?: { x: number; z: number; elevation?: number },
customization: ShapeCustomization = {},
): WorkplaneShape {
const defaults = shapeAssetDefaultDimensions(asset.kind);
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 {
id: createLocalId(asset.id),
@@ -102,20 +157,23 @@ export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: nu
rotationX: 0,
rotationZ: 0,
radius: asset.kind === "box" ? 0 : undefined,
text: asset.kind === "text" ? "TEXT" : undefined,
font: asset.kind === "text" ? "Multilanguage" : undefined,
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? 24 : asset.kind === "halfSphere" ? 32 : undefined,
sides: asset.kind === "cylinder" || asset.kind === "cone" ? 96 : asset.kind === "roundRoof" ? 64 : asset.kind === "pyramid" ? 4 : undefined,
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? 4 : undefined,
segments: asset.kind === "cylinder" ? 1 : undefined,
topRadius: asset.kind === "cone" ? 0 : undefined,
baseRadius: asset.kind === "cone" ? size / 2 : undefined,
teeth: asset.kind === "gear" ? DEFAULT_GEAR_TEETH : undefined,
toothSize: asset.kind === "gear" ? DEFAULT_GEAR_TOOTH_SIZE : undefined,
centerHoleSize: asset.kind === "gear" ? DEFAULT_GEAR_CENTER_HOLE_SIZE : undefined,
gearType: asset.kind === "gear" ? DEFAULT_GEAR_TYPE : undefined,
helixAngle: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_ANGLE : undefined,
helixQuality: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_QUALITY : undefined,
text: asset.kind === "text" ? customization.text ?? "TEXT" : undefined,
font: asset.kind === "text" ? customization.font ?? "Multilanguage" : 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" ? 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" ? customization.bevel ?? 4 : asset.kind === "text" ? customization.bevel : undefined,
segments: asset.kind === "cylinder" ? 1 : asset.kind === "text" ? customization.segments : undefined,
topRadius: asset.kind === "cone" ? customization.topRadius ?? 0 : undefined,
baseRadius: asset.kind === "cone" ? customization.baseRadius ?? width / 2 : undefined,
teeth: gearTeeth,
toothSize: gearToothSize,
toothWidth: asset.kind === "gear" && customization.toothWidth !== undefined
? normalizeGearToothWidth(customization.toothWidth, width, depth, gearTeeth)
: 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,
hidden: false,
};
+8 -73
View File
@@ -1,12 +1,12 @@
import type { ManifoldToplevel } from "manifold-3d";
import type { SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment } from "@/types/sketchforge";
import { MAX_HIGH_RESOLUTION_SIDES } from "@/lib/workplaneSettings";
export const DEFAULT_SKETCH_REVOLVE_SETTINGS: SketchRevolveSettings = {
startAngle: 0,
sweepAngle: 360,
sides: 64,
quality: 6,
thickness: 1,
};
type OrderedStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
@@ -36,9 +36,8 @@ export function normalizeSketchRevolveSettings(settings?: Partial<SketchRevolveS
return {
startAngle: ((finiteOr(settings?.startAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.startAngle) % 360) + 360) % 360,
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)),
thickness: clamp(finiteOr(settings?.thickness, DEFAULT_SKETCH_REVOLVE_SETTINGS.thickness), 0.1, 20),
};
}
@@ -152,34 +151,6 @@ function clipClosedPathToRevolveSide(points: SampledPoint[]) {
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) {
return Math.hypot(b[0] - a[0], b[1] - a[1]);
}
@@ -193,55 +164,19 @@ function compactPolygon(points: Point2[]) {
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>) {
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);
if (path.closed) {
const clipped = clipClosedPathToRevolveSide(sampled);
return clipped.length >= 3 ? [{ closed: true, points: clipped }] : [];
}
return clipOpenPathToRevolveSide(sampled).map((points) => ({ closed: false, points }));
return clipped.length >= 3 ? [clipped] : [];
});
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];
return paths.flatMap(({ closed, points }) => {
return paths.flatMap((points) => {
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 polygon.length >= 3 ? [compactPolygon(polygon)] : [];
return sectionPoints.length >= 3 ? [sectionPoints] : [];
});
}
@@ -261,7 +196,7 @@ function dispose(value: unknown) {
export function buildSketchRevolveMesh(runtime: ManifoldToplevel, profile: SketchProfile, requestedSettings?: Partial<SketchRevolveSettings>): SketchRevolveMesh {
const settings = normalizeSketchRevolveSettings(requestedSettings);
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[] = [];
try {
const section = new runtime.CrossSection(polygons, "EvenOdd");
+87
View File
@@ -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,
}));
}
+4 -2
View File
@@ -1,8 +1,10 @@
import type { GridSize, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export const SKETCHFORGE_MCP_ROUTE = "/api/sketchforge-mcp";
export const SKETCHFORGE_MCP_STALE_MS = 6500;
export const SKETCHFORGE_MCP_POLL_MS = 220;
export const SKETCHFORGE_MCP_STALE_MS = 15_000;
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";
+60 -3
View File
@@ -12,10 +12,18 @@ type PendingCommand = {
timer: ReturnType<typeof setTimeout>;
};
type PollWaiter = {
resolve: (command: SketchForgeMcpCommand | null) => void;
timer: ReturnType<typeof setTimeout>;
signal?: AbortSignal;
onAbort?: () => void;
};
type SketchForgeMcpStore = {
editors: Map<string, SketchForgeMcpEditorSummary>;
queues: Map<string, SketchForgeMcpCommand[]>;
pending: Map<string, PendingCommand>;
pollWaiters: Map<string, PollWaiter>;
};
declare global {
@@ -24,22 +32,42 @@ declare global {
}
function store() {
globalThis.__sketchforgeMcpStore ??= {
const state = globalThis.__sketchforgeMcpStore ??= {
editors: new Map<string, SketchForgeMcpEditorSummary>(),
queues: new Map<string, SketchForgeMcpCommand[]>(),
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() {
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()) {
const state = store();
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;
}
state.editors.delete(editorId);
@@ -79,6 +107,32 @@ export function pollSketchForgeMcpCommand(editorId: string) {
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) {
const state = store();
const pending = state.pending.get(result.commandId);
@@ -124,9 +178,12 @@ export function dispatchSketchForgeMcpCommand({
params,
createdAt: Date.now(),
};
const waiter = state.pollWaiters.get(editor.editorId);
if (!waiter || !settlePollWaiter(state, editor.editorId, waiter, command)) {
const queue = state.queues.get(editor.editorId) ?? [];
queue.push(command);
state.queues.set(editor.editorId, queue);
}
return new Promise<SketchForgeMcpCommandResult>((resolve) => {
const timer = setTimeout(() => {
+1 -1
View File
@@ -872,7 +872,7 @@ function validateShapeDefinition(definition: Record<string, unknown>, label: str
}
if (definition.sketchRevolve !== undefined) {
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") {
const teeth = finiteNumber(definition.teeth, `${label}.teeth`);
+92 -1
View File
@@ -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 { DEFAULT_WORKPLANE_GRID_COLOR } from "@/lib/workplaneGrid";
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 = {
width: 200,
@@ -21,9 +24,14 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
scale: "1:1 (millimeters)",
accuracy: 2,
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 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) {
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)));
}
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 {
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)),
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
shapeCustomizations: normalizeShapeCustomizations(candidate.shapeCustomizations, fallback.shapeCustomizations),
};
}
+12
View File
@@ -22,6 +22,10 @@ export function cleanNearZero(value: number, epsilon = 0.005) {
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 {
return {
...shape,
@@ -213,6 +217,14 @@ export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
if (shape.groupedShapes) {
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) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
+26 -1
View File
@@ -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 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 = {
width: number;
depth: number;
@@ -61,6 +85,7 @@ export type WorkplaneWorkspaceSettings = {
scale: string;
accuracy: MeasurementAccuracy;
historyLimit: HistoryRetentionLimit;
shapeCustomizations: ShapeCustomizationMap;
};
export type AlignAxis = "x" | "y" | "z";
@@ -102,6 +127,7 @@ export type SketchImage = {
depth: number;
opacity?: number;
lockAspect?: boolean;
locked?: boolean;
};
export type SketchProfile = {
@@ -119,7 +145,6 @@ export type SketchRevolveSettings = {
sweepAngle: number;
sides: number;
quality: number;
thickness: number;
};
export type EdgeTreatmentFeature = {
+21
View File
@@ -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);
});
});
+31
View File
@@ -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", () => {
const created = sceneShape({
name: "Part",
+23 -21
View File
@@ -41,35 +41,38 @@ describe("sketch revolve", () => {
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 = {
points: [{ id: "a", x: -8, z: 0 }, { id: "b", x: -8, z: 20 }],
segments: [{ id: "ab", startId: "a", endId: "b", kind: "line" }],
};
const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 2 });
expect(polygons).toHaveLength(1);
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);
expect(sketchProfileToRevolvePolygons(profile)).toEqual([]);
expect(() => buildSketchRevolveMesh(runtime, profile, { sides: 24 })).toThrow("Draw at least one closed profile");
});
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 = {
points: [{ id: "construction", x: 10, z: 0 }, { id: "profile", x: -10, z: 20 }],
segments: [{ id: "crossing", startId: "construction", endId: "profile", kind: "line" }],
points: [
{ 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(Math.max(...polygons[0].map((point) => point[1]))).toBeLessThan(11);
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeGreaterThan(10);
expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(0, 6);
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.height).toBeGreaterThan(9);
expect(mesh.height).toBeLessThan(11);
expect(mesh.height).toBeCloseTo(20, 4);
});
it("supports partial and reverse sweeps", () => {
@@ -82,12 +85,11 @@ describe("sketch revolve", () => {
});
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,
sweepAngle: 1,
sides: 128,
sides: 512,
quality: 1,
thickness: 0.1,
});
});
});
+49
View File
@@ -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);
});
});
+67
View File
@@ -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 });
});
});
+4 -1
View File
@@ -153,7 +153,7 @@ describe("SketchForge .skf project packages", () => {
const revolve = shape("mesh", "revolve-sketch", {
name: "Sketch 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: {
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: [
@@ -402,6 +402,8 @@ describe("SketchForge .skf project packages", () => {
z: 0,
width: 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(restored.shapes[0].imagePlate?.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 () => {
+71 -1
View File
@@ -1,5 +1,11 @@
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", () => {
it("preserves face-plane foreshortening while normalizing icon size", () => {
@@ -28,4 +34,68 @@ describe("rotation handle projection", () => {
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 });
});
});
+38 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
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", () => {
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);
});
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", () => {
expect(canBeginShapeDrag(false, false)).toBe(true);
expect(canBeginShapeDrag(true, false)).toBe(false);
+24
View File
@@ -19,6 +19,7 @@ import {
shapeDepth,
shapeHasTaper,
shapeOverallFootprintDimensions,
shapeTransformShouldRemainEditable,
shapeTaperDimensions,
shapeTaperScaleAt,
shapeWidth,
@@ -129,6 +130,29 @@ describe("workplane shape helpers", () => {
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", () => {
const original = shape({
id: "outer-group",