diff --git a/README.md b/README.md index 5904765..56a27bf 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,11 @@ docker compose -f deploy/docker/compose-ghcr.yaml up -d #### Standalone (Prebuilt) ```bash -docker run -d --name sketchforge --restart unless-stopped -p 3000:80 ghcr.io/formsmith746/sketchforge-3d:latest +docker run -d --name sketchforge --restart unless-stopped \ + -p 3000:3000 \ + -e SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects \ + -v sketchforge-shared-projects:/data/projects \ + ghcr.io/formsmith746/sketchforge-3d:latest ``` After running, open this on the same computer: @@ -128,6 +132,27 @@ http://127.0.0.1:3000/ If that works, SketchForge is running. +### Shared Docker Projects + +Docker deployments include a shared `.skf` project library. Private projects still autosave in each user's browser. The **Shared** dashboard section lists files stored in `/data/projects`, and **Export → SKF → Save to shared** writes the current project there. + +Compose uses the persistent `sketchforge-shared-projects` volume by default. To use a directory on the Docker host instead, set `SKETCHFORGE_SHARED_PROJECTS_VOLUME` before starting Compose: + +Windows PowerShell: + +```powershell +$env:SKETCHFORGE_SHARED_PROJECTS_VOLUME = "C:/SketchForge/shared-projects" +docker compose -f deploy/docker/compose.yaml up --build -d +``` + +Linux or macOS: + +```bash +SKETCHFORGE_SHARED_PROJECTS_VOLUME=/srv/sketchforge-projects docker compose -f deploy/docker/compose.yaml up --build -d +``` + +Opening a shared file creates a private local working copy. Saving back checks the server revision first; if another user has changed the file, SketchForge refuses to overwrite it and asks the user to reload or save with another name. This is shared file storage, not simultaneous live editing. + ### Let Other Computers Join Other computers on the same Wi-Fi or LAN need the server computer's local IP address. diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 1a026b0..1fb0e0e 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -1,12 +1,15 @@ import type { NextConfig } from "next"; +import path from "node:path"; const isStaticExport = process.env.STATIC_EXPORT === "true"; +const isDockerBuild = process.env.SKETCHFORGE_DOCKER_BUILD === "true"; const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? "") .split(",") .map((origin) => origin.trim()) .filter(Boolean); const nextConfig: NextConfig = { + outputFileTracingRoot: path.resolve(process.cwd()), devIndicators: false, // Keep the live development compiler isolated from `next build`. Sharing // `.next` lets a production verification build invalidate chunks used by a @@ -35,7 +38,9 @@ const nextConfig: NextConfig = { output: "export" as const, trailingSlash: true, } - : {}), + : isDockerBuild + ? { output: "standalone" as const } + : {}), }; export default nextConfig; diff --git a/apps/web/src/app/api/shared-projects/route.ts b/apps/web/src/app/api/shared-projects/route.ts new file mode 100644 index 0000000..61bb648 --- /dev/null +++ b/apps/web/src/app/api/shared-projects/route.ts @@ -0,0 +1,197 @@ +import { randomUUID } from "crypto"; +import { promises as fs } from "fs"; +import path from "path"; +import { NextResponse } from "next/server"; +import { inspectSkfProjectPackage, SKF_LIMITS, SKF_MEDIA_TYPE } from "@/lib/skfProject"; + +export const runtime = "nodejs"; +export const revalidate = false; + +const SHARED_PROJECTS_ENV = "SKETCHFORGE_SHARED_PROJECTS_DIR"; + +type SharedProjectFile = { + fileName: string; + name: string; + updatedAt: number; + size: number; + revision: string; +}; + +function sharedProjectsDirectory() { + const configured = process.env[SHARED_PROJECTS_ENV]?.trim(); + return configured ? path.resolve(configured) : null; +} + +function safeProjectFileName(requestedName: string) { + const withoutExtension = requestedName.replace(/\.skf$/i, ""); + const stem = path.basename(withoutExtension) + .replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_") + .replace(/\s+/g, " ") + .trim() + .slice(0, 115); + return `${stem || "Untitled project"}.skf`; +} + +function revisionForStat(stat: { size: number; mtimeMs: number }) { + return `${stat.size.toString(16)}-${Math.round(stat.mtimeMs * 1000).toString(16)}`; +} + +function projectRecord(fileName: string, stat: { size: number; mtimeMs: number }): SharedProjectFile { + return { + fileName, + name: fileName.replace(/\.skf$/i, ""), + updatedAt: stat.mtimeMs, + size: stat.size, + revision: revisionForStat(stat), + }; +} + +function unquoteEtag(value: string | null) { + if (!value) return null; + return value.trim().replace(/^W\//, "").replace(/^"|"$/g, ""); +} + +function sameOriginRequest(request: Request) { + const origin = request.headers.get("origin"); + if (!origin) return true; + try { + const requestUrl = new URL(request.url); + const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim(); + const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(); + const host = forwardedHost || request.headers.get("host") || requestUrl.host; + const protocol = forwardedProtocol || requestUrl.protocol.replace(/:$/, ""); + return new URL(origin).origin === `${protocol}://${host}`; + } catch { + return false; + } +} + +async function regularFileStat(filePath: string) { + try { + const stat = await fs.lstat(filePath); + if (stat.isSymbolicLink() || !stat.isFile()) return null; + return stat; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +function disabledResponse() { + return NextResponse.json( + { enabled: false, projects: [], error: `${SHARED_PROJECTS_ENV} is not configured` }, + { headers: { "Cache-Control": "no-store" } }, + ); +} + +export async function GET(request: Request) { + const root = sharedProjectsDirectory(); + if (!root) return disabledResponse(); + try { + await fs.mkdir(root, { recursive: true }); + const requestUrl = new URL(request.url); + const requestedFile = requestUrl.searchParams.get("fileName"); + if (requestedFile) { + const fileName = safeProjectFileName(requestedFile); + if (fileName !== requestedFile) return NextResponse.json({ error: "Invalid shared project name" }, { status: 400 }); + const filePath = path.join(root, fileName); + const stat = await regularFileStat(filePath); + if (!stat) return NextResponse.json({ error: "Shared project was not found" }, { status: 404 }); + const bytes = await fs.readFile(filePath); + return new Response(bytes, { + headers: { + "Cache-Control": "no-store", + "Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`, + "Content-Length": String(bytes.byteLength), + "Content-Type": SKF_MEDIA_TYPE, + ETag: `"${revisionForStat(stat)}"`, + }, + }); + } + + const entries = await fs.readdir(root, { withFileTypes: true }); + const projects = await Promise.all(entries + .filter((entry) => entry.isFile() && /\.skf$/i.test(entry.name)) + .map(async (entry) => { + const stat = await regularFileStat(path.join(root, entry.name)); + return stat ? projectRecord(entry.name, stat) : null; + })); + return NextResponse.json( + { enabled: true, projects: projects.filter((entry): entry is SharedProjectFile => Boolean(entry)).sort((a, b) => b.updatedAt - a.updatedAt) }, + { headers: { "Cache-Control": "no-store" } }, + ); + } catch (error) { + return NextResponse.json({ enabled: true, projects: [], error: error instanceof Error ? error.message : "Could not read shared projects" }, { status: 500 }); + } +} + +export async function POST(request: Request) { + const root = sharedProjectsDirectory(); + if (!root) return NextResponse.json({ error: "Shared project storage is disabled" }, { status: 404 }); + if (!sameOriginRequest(request)) return NextResponse.json({ error: "Shared projects only accept same-origin saves" }, { status: 403 }); + + const declaredLength = Number(request.headers.get("content-length") ?? 0); + if (Number.isFinite(declaredLength) && declaredLength > SKF_LIMITS.archiveBytes) { + return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 }); + } + + let lockHandle: Awaited> | null = null; + let lockPath = ""; + let temporaryPath = ""; + try { + const bytes = new Uint8Array(await request.arrayBuffer()); + if (bytes.byteLength > SKF_LIMITS.archiveBytes) return NextResponse.json({ error: ".skf file exceeds the shared storage size limit" }, { status: 413 }); + const summary = await inspectSkfProjectPackage(bytes); + const requestUrl = new URL(request.url); + const fileName = safeProjectFileName(requestUrl.searchParams.get("fileName") ?? summary.projectName); + await fs.mkdir(root, { recursive: true }); + const filePath = path.join(root, fileName); + lockPath = `${filePath}.lock`; + temporaryPath = path.join(root, `.${fileName}.${randomUUID()}.tmp`); + + try { + lockHandle = await fs.open(lockPath, "wx"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "EEXIST") { + return NextResponse.json({ error: "This shared project is currently being saved by someone else" }, { status: 409 }); + } + throw error; + } + + const currentStat = await regularFileStat(filePath); + const currentRevision = currentStat ? revisionForStat(currentStat) : null; + const expectedRevision = unquoteEtag(request.headers.get("if-match")); + const createOnly = request.headers.get("if-none-match") === "*"; + if (currentStat && (createOnly || !expectedRevision || expectedRevision !== currentRevision)) { + return NextResponse.json( + { error: "The shared project changed after you opened it. Reload it or save under a different name.", currentRevision }, + { status: 409 }, + ); + } + if (!currentStat && expectedRevision) { + return NextResponse.json({ error: "The shared project no longer exists. Save it under a different name." }, { status: 409 }); + } + + const temporaryHandle = await fs.open(temporaryPath, "wx"); + try { + await temporaryHandle.writeFile(bytes); + await temporaryHandle.sync(); + } finally { + await temporaryHandle.close(); + } + await fs.rename(temporaryPath, filePath); + temporaryPath = ""; + const savedStat = await fs.stat(filePath); + const project = projectRecord(fileName, savedStat); + return NextResponse.json( + { project: { ...project, name: summary.projectName } }, + { status: currentStat ? 200 : 201, headers: { "Cache-Control": "no-store", ETag: `"${project.revision}"` } }, + ); + } catch (error) { + return NextResponse.json({ error: error instanceof Error ? error.message : "Could not save shared project" }, { status: 400 }); + } finally { + if (lockHandle) await lockHandle.close().catch(() => undefined); + if (temporaryPath) await fs.unlink(temporaryPath).catch(() => undefined); + if (lockPath) await fs.unlink(lockPath).catch(() => undefined); + } +} diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 20a2bdf..2ee3c25 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -328,6 +328,39 @@ button { font-size: 13px; } +.shared-projects-refresh { + display: inline-flex; + min-height: 36px; + align-items: center; + gap: 7px; + padding: 0 12px; + color: #31536a; + font-size: 12px; + font-weight: 800; + background: #fff; + border: 1px solid #d3e0e7; + border-radius: 8px; + cursor: pointer; +} + +.shared-projects-refresh:hover:not(:disabled) { + color: #087f9f; + border-color: #89d0e1; +} + +.shared-projects-refresh:disabled { + cursor: default; + opacity: 0.6; +} + +.shared-projects-refresh .spinning { + animation: shared-project-spin 850ms linear infinite; +} + +@keyframes shared-project-spin { + to { transform: rotate(360deg); } +} + .dashboard-controls { display: flex; flex-wrap: wrap; @@ -403,6 +436,23 @@ button { box-shadow: 0 1px 2px rgba(31, 52, 71, 0.05); } +.shared-project-badge { + position: absolute; + top: 10px; + right: 10px; + z-index: 2; + padding: 4px 7px; + color: #087f9f; + font-size: 9px; + font-weight: 900; + letter-spacing: 0.04em; + text-transform: uppercase; + pointer-events: none; + background: rgba(237, 251, 255, 0.94); + border: 1px solid #a9dfeb; + border-radius: 999px; +} + .project-list .project-card { padding-right: 50px; } @@ -2370,6 +2420,29 @@ button { box-shadow: 0 5px 14px rgba(4, 145, 183, 0.22); } +.export-dialog-footer .export-shared-button { + min-width: 122px; + color: #087f9f; + background: #eefafd; + border: 1px solid #a9dce9; +} + +.export-dialog-footer .export-shared-button:hover:not(:disabled) { + color: #056c87; + background: #e2f7fc; + border-color: #6dc7dc; +} + +.export-dialog-footer .export-shared-button:disabled { + cursor: default; + opacity: 0.55; +} + +.export-shared-button svg { + width: 16px; + height: 16px; +} + .export-dialog-footer .export-primary-button:hover:not(:disabled) { background: linear-gradient(180deg, #0eadd4, #058db2); } @@ -3632,7 +3705,7 @@ button { text-align: center; pointer-events: auto; cursor: text; - transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%); + transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%) rotate(var(--rotate-handle-angle, 0deg)); will-change: transform; box-shadow: 0 1px 4px rgba(20, 42, 58, 0.09); } @@ -3791,7 +3864,7 @@ button { box-shadow: none; cursor: grab; opacity: 1; - transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%) rotate(var(--rotate-handle-angle, 0deg)); + transform: translate3d(var(--overlay-x, 0), var(--overlay-y, 0), 0) translate(-50%, -50%); } .rotate-handle:hover { @@ -3892,6 +3965,12 @@ button { box-shadow: -2px 0 10px rgba(36, 61, 86, 0.08); } +.shape-inspector.minimized { + bottom: auto; + height: 50px; + overflow: hidden; +} + .shape-inspector-header { display: flex; align-items: center; @@ -3978,7 +4057,7 @@ button { display: block; width: 64px; height: 64px; - border-radius: 999px; + border-radius: 10px; } .large-solid-swatch { diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 99aedb4..0ee1909 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; +import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor"; import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory"; @@ -13,7 +13,7 @@ import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings type AppView = "dashboard" | "editor"; type ViewMode = "grid" | "list"; -type DashboardSection = "home" | "challenges"; +type DashboardSection = "home" | "shared" | "challenges"; type DownloadMode = "browser" | "folder"; type DashboardProject = { @@ -29,6 +29,15 @@ type DashboardProject = { workspace?: WorkplaneWorkspaceSettings; snapGrid?: GridSize; placementElevation?: number; + sharedProject?: { fileName: string; revision: string }; +}; + +type SharedProject = { + fileName: string; + name: string; + updatedAt: number; + size: number; + revision: string; }; type StoredDashboardProject = Partial & { @@ -69,6 +78,12 @@ function formatUpdated(timestamp: number) { return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(new Date(timestamp)); } +function formatFileSize(bytes: number) { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`; +} + function projectShapeCacheEntry( revision: number, shapes: WorkplaneShape[], @@ -195,6 +210,9 @@ function readStoredProjects() { workspace: normalizeWorkspaceSettings(project.workspace), snapGrid: normalizeSnapGrid(project.snapGrid), placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0, + sharedProject: typeof project.sharedProject?.fileName === "string" && typeof project.sharedProject.revision === "string" + ? { fileName: project.sharedProject.fileName, revision: project.sharedProject.revision } + : undefined, }; }); return { projects, legacyShapes }; @@ -226,6 +244,7 @@ function mergeProjectForStorage(project: DashboardProject, storedProject?: Dashb workspace: project.workspace ?? storedProject.workspace, snapGrid: project.snapGrid ?? storedProject.snapGrid, placementElevation: project.placementElevation ?? storedProject.placementElevation, + sharedProject: project.sharedProject ?? storedProject.sharedProject, }; } @@ -243,6 +262,7 @@ function projectForStorage(project: DashboardProject): DashboardProject { workspace: normalizeWorkspaceSettings(project.workspace), snapGrid: normalizeSnapGrid(project.snapGrid), placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0, + sharedProject: project.sharedProject, }; } @@ -286,12 +306,32 @@ export default function Home() { const [downloadMode, setDownloadMode] = useState("browser"); const [downloadFolder, setDownloadFolder] = useState(""); const [dashboardNotice, setDashboardNotice] = useState(""); + const [sharedProjects, setSharedProjects] = useState([]); + const [sharedProjectsEnabled, setSharedProjectsEnabled] = useState(false); + const [sharedProjectsLoading, setSharedProjectsLoading] = useState(false); const [projectShapesById, setProjectShapesById] = useState>({}); const projectsJsonRef = useRef(""); const dashboardImportInputRef = useRef(null); const nextProjectRevisionRef = useRef(0); const projectShapeSaveQueuesRef = useRef>>({}); + const refreshSharedProjects = useCallback(async () => { + if (STATIC_EXPORT_BUILD) return; + setSharedProjectsLoading(true); + try { + const response = await fetch("/api/shared-projects", { cache: "no-store" }); + const payload = await response.json() as { enabled?: boolean; projects?: SharedProject[]; error?: string }; + setSharedProjectsEnabled(Boolean(payload.enabled)); + setSharedProjects(Array.isArray(payload.projects) ? payload.projects : []); + if (!response.ok && payload.enabled) setDashboardNotice(payload.error ?? "Could not load shared projects"); + } catch { + setSharedProjectsEnabled(false); + setSharedProjects([]); + } finally { + setSharedProjectsLoading(false); + } + }, []); + useEffect(() => { document.documentElement.removeAttribute("data-theme"); document.documentElement.style.colorScheme = "light"; @@ -325,6 +365,11 @@ export default function Home() { setMounted(true); }, []); + useEffect(() => { + if (!mounted) return; + void refreshSharedProjects(); + }, [mounted, refreshSharedProjects]); + useEffect(() => { if (!mounted) return; const localSerialized = JSON.stringify(projects); @@ -413,6 +458,12 @@ export default function Home() { return sortMode === "name" ? [...filtered].sort((a, b) => a.name.localeCompare(b.name)) : [...filtered].sort((a, b) => b.updatedAt - a.updatedAt); }, [projects, query, sortMode]); + const visibleSharedProjects = useMemo(() => { + const normalizedQuery = query.trim().toLowerCase(); + const filtered = normalizedQuery ? sharedProjects.filter((project) => project.name.toLowerCase().includes(normalizedQuery)) : sharedProjects; + return sortMode === "name" ? [...filtered].sort((a, b) => a.name.localeCompare(b.name)) : [...filtered].sort((a, b) => b.updatedAt - a.updatedAt); + }, [query, sharedProjects, sortMode]); + const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean } = {}) => { if (projectId && typeof window !== "undefined" && !options.allowMissingFromStorage) { const storedProjects = readProjects(); @@ -567,7 +618,7 @@ export default function Home() { openEditor(project.id, { allowMissingFromStorage: true }); }; - const openSkfProjectFromFile = useCallback(async (file: File) => { + const openSkfProjectFromFile = useCallback(async (file: File, sharedProject?: SharedProject) => { setDashboardNotice(`Validating ${file.name} before opening it as a new project`); try { const restored = await importSkfProject(await file.arrayBuffer()); @@ -580,14 +631,15 @@ export default function Home() { workspace: restored.workspace, snapGrid: restored.snapGrid, placementElevation: restored.placementElevation, + sharedProject: sharedProject ? { fileName: sharedProject.fileName, revision: sharedProject.revision } : undefined, }; const entry = projectShapeCacheEntry(now, restored.shapes, restored.history, restored.historyIndex, restored.assets); await saveProjectShapes(project.id, entry); setProjectShapesById((current) => ({ ...current, [project.id]: entry })); setProjects((current) => [project, ...current]); - setDashboardNotice(`Opened ${file.name} as a new editable local project`); + setDashboardNotice(sharedProject ? `Opened shared project ${sharedProject.name}; edits autosave locally until you save back to shared` : `Opened ${file.name} as a new editable local project`); openEditor(project.id, { allowMissingFromStorage: true }); - return { ok: true, message: `Opened ${file.name} as a new editable local project` }; + return { ok: true, message: sharedProject ? `Opened shared project ${sharedProject.name}` : `Opened ${file.name} as a new editable local project` }; } catch (error) { const message = error instanceof Error ? error.message : "Could not open SketchForge project"; setDashboardNotice(message); @@ -595,6 +647,45 @@ export default function Home() { } }, [projects.length]); + const openSharedProject = useCallback(async (sharedProject: SharedProject) => { + setDashboardNotice(`Opening shared project ${sharedProject.name}`); + try { + const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(sharedProject.fileName)}`, { cache: "no-store" }); + if (!response.ok) { + const payload = await response.json().catch(() => ({})) as { error?: string }; + throw new Error(payload.error ?? "Could not download shared project"); + } + const revision = response.headers.get("etag")?.replace(/^W\//, "").replace(/^"|"$/g, "") || sharedProject.revision; + const file = new File([await response.blob()], sharedProject.fileName, { type: "application/vnd.sketchforge.project+zip" }); + await openSkfProjectFromFile(file, { ...sharedProject, revision }); + } catch (error) { + setDashboardNotice(error instanceof Error ? error.message : "Could not open shared project"); + } + }, [openSkfProjectFromFile]); + + const saveActiveProjectToShared = useCallback(async ({ exportName, bytes }: { exportName: string; bytes: Uint8Array }) => { + const activeProject = projects.find((project) => project.id === activeProjectId); + if (!activeProject) throw new Error("Open a local project before saving it to the shared space"); + const normalizedExportName = exportName.trim() || activeProject.name; + const saveBackToSource = Boolean(activeProject.sharedProject && normalizedExportName === activeProject.name); + const fileName = saveBackToSource && activeProject.sharedProject + ? activeProject.sharedProject.fileName + : `${normalizedExportName.replace(/\.skf$/i, "")}.skf`; + const headers: Record = { "Content-Type": "application/vnd.sketchforge.project+zip" }; + if (saveBackToSource && activeProject.sharedProject) headers["If-Match"] = `"${activeProject.sharedProject.revision}"`; + else headers["If-None-Match"] = "*"; + const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; + const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(fileName)}`, { method: "POST", headers, body }); + const payload = await response.json().catch(() => ({})) as { error?: string; project?: SharedProject }; + if (!response.ok || !payload.project) throw new Error(payload.error ?? "Could not save the shared project"); + const savedProject = payload.project; + setProjects((current) => current.map((project) => project.id === activeProject.id + ? { ...project, sharedProject: { fileName: savedProject.fileName, revision: savedProject.revision } } + : project)); + await refreshSharedProjects(); + return `Saved ${savedProject.name} to the Docker shared project space`; + }, [activeProjectId, projects, refreshSharedProjects]); + const importFilesFromDashboard = useCallback( async (files: File[]) => { if (!files.length) return; @@ -773,6 +864,9 @@ export default function Home() { projects={visibleProjects} query={query} settingsOpen={settingsOpen} + sharedProjects={visibleSharedProjects} + sharedProjectsEnabled={sharedProjectsEnabled} + sharedProjectsLoading={sharedProjectsLoading} staticExportBuild={STATIC_EXPORT_BUILD} sortMode={sortMode} viewMode={viewMode} @@ -787,10 +881,17 @@ export default function Home() { setDashboardNotice(""); }} onDashboardHome={() => setDashboardSection("home")} + onOpenSharedProject={(project) => void openSharedProject(project)} onOpenProject={openEditor} onOpenSettings={() => setSettingsOpen(true)} onQueryChange={setQuery} onRenameProject={renameProject} + onRefreshSharedProjects={() => void refreshSharedProjects()} + onSharedProjects={() => { + setDashboardSection("shared"); + setDashboardNotice(""); + void refreshSharedProjects(); + }} onSortModeChange={setSortMode} onViewModeChange={setViewMode} onWorkspace={openLatestProject} @@ -808,6 +909,7 @@ export default function Home() { initialPlacementElevation={activeProject?.placementElevation ?? 0} onHome={openDashboard} onOpenSkfProjectFile={openSkfProjectFromFile} + onSaveSharedProject={saveActiveProjectToShared} onProjectShapesChange={updateProjectShapes} onProjectSnapshot={updateProjectSnapshot} onProjectWorkspaceChange={updateProjectWorkspace} @@ -816,6 +918,7 @@ export default function Home() { projectCreatedAt={activeProject?.createdAt} projectModifiedAt={activeProject?.updatedAt} projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0} + sharedProjectsEnabled={sharedProjectsEnabled} /> ) : null} @@ -831,6 +934,9 @@ function Dashboard({ projects, query, settingsOpen, + sharedProjects, + sharedProjectsEnabled, + sharedProjectsLoading, staticExportBuild, sortMode, viewMode, @@ -842,10 +948,13 @@ function Dashboard({ onImportFile, onChallenges, onDashboardHome, + onOpenSharedProject, onOpenProject, onOpenSettings, onQueryChange, onRenameProject, + onRefreshSharedProjects, + onSharedProjects, onSortModeChange, onViewModeChange, onWorkspace, @@ -857,6 +966,9 @@ function Dashboard({ projects: DashboardProject[]; query: string; settingsOpen: boolean; + sharedProjects: SharedProject[]; + sharedProjectsEnabled: boolean; + sharedProjectsLoading: boolean; staticExportBuild: boolean; sortMode: string; viewMode: ViewMode; @@ -868,10 +980,13 @@ function Dashboard({ onImportFile: () => void; onChallenges: () => void; onDashboardHome: () => void; + onOpenSharedProject: (project: SharedProject) => void; onOpenProject: (projectId: string) => void; onOpenSettings: () => void; onQueryChange: (value: string) => void; onRenameProject: (projectId: string, name: string) => void; + onRefreshSharedProjects: () => void; + onSharedProjects: () => void; onSortModeChange: (value: string) => void; onViewModeChange: (value: ViewMode) => void; onWorkspace: () => void; @@ -936,6 +1051,12 @@ function Dashboard({ Home + {sharedProjectsEnabled ? ( + + ) : null} -
+
{dashboardSection === "challenges" ? (
Coming soon
+ ) : dashboardSection === "shared" ? ( + <> + {dashboardNotice ?
{dashboardNotice}
: null} +
+
+

Shared projects

+ {sharedProjects.length} available from Docker storage +
+ +
+ {sharedProjects.length > 0 ? ( +
+ {sharedProjects.map((project, index) => ( +
+ + Shared +
+ ))} +
+ ) : ( +
+ {sharedProjectsLoading ? "Loading shared projects" : "No shared projects yet"} + Save an SKF project to the shared space from the Export window. +
+ )} + ) : ( <>
diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index be134a4..f19c5d3 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -1,6 +1,6 @@ "use client"; -import { Check, Download, FolderOpen, X } from "lucide-react"; +import { Check, CloudUpload, Download, FolderOpen, X } from "lucide-react"; import type manifoldModule from "manifold-3d"; import type { ManifoldToplevel } from "manifold-3d"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -52,6 +52,7 @@ import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, + meshYawDegrees, mirroredAxisCount, mirrorSign, normalizeDegrees, @@ -78,6 +79,7 @@ import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap import { createLocalId } from "@/lib/localIds"; import { projectExportFileName } from "@/lib/exportNames"; import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets"; +import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation"; import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject"; import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog"; import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"; @@ -101,6 +103,7 @@ type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null; type ExportFormat = "stl" | "obj" | "step" | "svg" | "skf"; type DirectExportFormat = Exclude; type SkfHistoryLimit = EditorHistoryExportLimit; +type SkfExportTarget = "download" | "shared"; type ToolbarMode = "geometry" | "sketch"; type Vec3 = [number, number, number]; type MeshData = { name: string; vertices: Vec3[]; faces: [number, number, number][] }; @@ -311,7 +314,89 @@ function pointInSketchPolygon(point: THREE.Vector2, polygon: THREE.Vector2[]) { return inside; } -function shapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) { +async function shapeFromResolvedSketchProfile( + profile: SketchProfile, + polygons: Array>, + height: number, + centerX: number, + centerZ: number, + existing?: WorkplaneShape | null, +) { + const runtime = await getManifoldRuntime(); + const disposable: unknown[] = []; + try { + const section = new runtime.CrossSection(polygons, "EvenOdd"); + disposable.push(section); + const coordinateScale = polygons.reduce( + (largest, polygon) => polygon.reduce((polygonLargest, point) => Math.max(polygonLargest, Math.abs(point[0]), Math.abs(point[1])), largest), + 1, + ); + const simplified = section.simplify(Math.max(1e-7, coordinateScale * 1e-8)); + disposable.push(simplified); + if (simplified.toPolygons().length === 0) throw new Error("The sketch has no filled area after resolving its crossings"); + + const solid = simplified.extrude(height); + disposable.push(solid); + if (solid.status() !== "NoError" || solid.numTri() < 1) { + throw new Error("The crossing sketch could not be converted into a valid solid"); + } + + const manifoldPositions = manifoldMeshToPositions(solid.getMesh()); + const positions = new Array(manifoldPositions.length); + let minX = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let minZ = Number.POSITIVE_INFINITY; + let maxZ = Number.NEGATIVE_INFINITY; + for (let index = 0; index + 2 < manifoldPositions.length; index += 3) { + const x = manifoldPositions[index]; + const y = manifoldPositions[index + 2]; + const z = -manifoldPositions[index + 1]; + positions[index] = x; + positions[index + 1] = y; + positions[index + 2] = z; + minX = Math.min(minX, x); + maxX = Math.max(maxX, x); + minZ = Math.min(minZ, z); + maxZ = Math.max(maxZ, z); + } + const localCenterX = (minX + maxX) / 2; + const localCenterZ = (minZ + maxZ) / 2; + for (let index = 0; index + 2 < positions.length; index += 3) { + positions[index] -= localCenterX; + positions[index + 2] -= localCenterZ; + } + const meshWidth = Math.max(0.01, maxX - minX); + const meshDepth = Math.max(0.01, maxZ - minZ); + return canonicalizeShape({ + id: existing?.id ?? createLocalId("sketch-extrusion"), + name: existing?.name ?? "Sketch extrusion", + kind: "mesh", + color: existing?.color ?? "#d41721", + hole: existing?.hole, + x: centerX + localCenterX, + z: centerZ + localCenterZ, + elevation: 0, + size: Math.max(meshWidth, meshDepth), + width: meshWidth, + depth: meshDepth, + height, + rotation: 0, + importedMesh: { + positions, + baseWidth: meshWidth, + baseDepth: meshDepth, + baseHeight: height, + triangleCount: Math.floor(positions.length / 9), + sourceFormat: "json", + }, + sketchProfile: cloneSketchProfile(profile), + } satisfies WorkplaneShape); + } finally { + [...new Set(disposable)].reverse().forEach(disposeManifold); + } +} + +async function shapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) { const closedPaths = orderedSketchPaths(profile).filter((path) => path.closed); if (closedPaths.length === 0) return null; const profilePoints = closedPaths.flatMap((path) => path.points); @@ -349,6 +434,25 @@ function shapeFromSketchProfile(profile: SketchProfile, height: number, existing const polygon = outline.extractPoints(16).shape; return { outline, polygon, area: Math.abs(THREE.ShapeUtils.area(polygon)) }; }); + const hasCurves = profile.segments.some((segment) => segment.kind === "bezier" || segment.kind === "smooth"); + const longestHandle = profile.points.reduce((longest, point) => Math.max( + longest, + point.handleIn ? Math.hypot(point.handleIn.x - point.x, point.handleIn.z - point.z) : 0, + point.handleOut ? Math.hypot(point.handleOut.x - point.x, point.handleOut.z - point.z) : 0, + ), 0); + const curveScale = Math.max(width, depth, longestHandle * 2); + const curveSegments = hasCurves ? Math.min(256, Math.max(32, Math.ceil(curveScale * 1.25))) : 1; + const sampledPolygons = outlineRecords.map((record) => record.outline.extractPoints(curveSegments).shape); + if (findSketchOutlineIntersection(sampledPolygons)) { + return shapeFromResolvedSketchProfile( + profile, + sampledPolygons.map((polygon) => polygon.map((point) => [point.x, point.y] as [number, number])), + safeHeight, + centerX, + centerZ, + existing, + ); + } const sortedOutlines = [...outlineRecords].sort((a, b) => b.area - a.area); const outlines: THREE.Shape[] = []; sortedOutlines.forEach((record) => { @@ -361,14 +465,6 @@ function shapeFromSketchProfile(profile: SketchProfile, height: number, existing if (parent) parent.outline.holes.push(record.outline); else outlines.push(record.outline); }); - const hasCurves = profile.segments.some((segment) => segment.kind === "bezier" || segment.kind === "smooth"); - const longestHandle = profile.points.reduce((longest, point) => Math.max( - longest, - point.handleIn ? Math.hypot(point.handleIn.x - point.x, point.handleIn.z - point.z) : 0, - point.handleOut ? Math.hypot(point.handleOut.x - point.x, point.handleOut.z - point.z) : 0, - ), 0); - const curveScale = Math.max(width, depth, longestHandle * 2); - const curveSegments = hasCurves ? Math.min(256, Math.max(32, Math.ceil(curveScale * 1.25))) : 1; const geometry = new THREE.ExtrudeGeometry(outlines, { depth: safeHeight, bevelEnabled: false, steps: 1, curveSegments }); geometry.rotateX(-Math.PI / 2); geometry.computeVertexNormals(); @@ -416,14 +512,6 @@ function cleanModelDimension(value: number) { return Math.max(MIN_SHAPE_DIMENSION, Number(value.toFixed(MODEL_DIMENSION_PRECISION))); } -function meshYawDegrees(shape: WorkplaneShape) { - const isRoundPrimitive = !shape.importedMesh && (shape.kind === "cylinder" || shape.kind === "cone"); - const isCircular = Math.abs(shapeWidth(shape) - shapeDepth(shape)) < 0.0005; - // A circular cylinder/cone is invariant around Y. Ignoring that purely visual - // yaw keeps its tessellated export at the requested diameter after grouping. - return isRoundPrimitive && isCircular ? 0 : shape.rotation; -} - function parseClipboardShapes(serialized: string) { try { const parsed = JSON.parse(serialized); @@ -5048,6 +5136,7 @@ export function SketchForgeEditor({ initialPlacementElevation = 0, onHome, onOpenSkfProjectFile, + onSaveSharedProject, onProjectShapesChange, onProjectSnapshot, onProjectWorkspaceChange, @@ -5056,6 +5145,7 @@ export function SketchForgeEditor({ projectCreatedAt = Date.now(), projectModifiedAt = Date.now(), projectRevision = 0, + sharedProjectsEnabled = false, }: { initialAssets?: ProjectAsset[]; initialShapes?: WorkplaneShape[]; @@ -5066,6 +5156,7 @@ export function SketchForgeEditor({ initialPlacementElevation?: number; onHome?: () => void; onOpenSkfProjectFile?: (file: File) => Promise<{ ok: boolean; message: string } | void> | { ok: boolean; message: string } | void; + onSaveSharedProject?: (request: { exportName: string; bytes: Uint8Array }) => Promise; onProjectShapesChange?: (snapshot: { projectId: string; shapes: WorkplaneShape[]; @@ -5080,6 +5171,7 @@ export function SketchForgeEditor({ projectCreatedAt?: number; projectModifiedAt?: number; projectRevision?: number; + sharedProjectsEnabled?: boolean; } = {}) { const initialSceneRef = useRef(null); if (initialSceneRef.current === null) { @@ -6133,10 +6225,16 @@ export function SketchForgeEditor({ setSketchTool("select"); }, [commitSketchProfile, sketchProfile]); - const finishSketch = useCallback(() => { + const finishSketch = useCallback(async () => { const existing = editingSketchShapeId ? shapes.find((shape) => shape.id === editingSketchShapeId) ?? null : null; const height = existing?.height ?? 10; - const extruded = shapeFromSketchProfile(sketchProfile, height, existing); + let extruded: WorkplaneShape | null; + try { + extruded = await shapeFromSketchProfile(sketchProfile, height, existing); + } catch (error) { + setNotice(error instanceof Error ? error.message : "The sketch profile cannot be converted to 3D"); + return; + } if (!extruded) { setNotice("Close at least one profile before finishing the sketch"); return; @@ -7162,7 +7260,7 @@ export function SketchForgeEditor({ let shape: WorkplaneShape; if (kind === "sketch") { const profile = defaultMcpSketchProfile(width, depth); - const extruded = shapeFromSketchProfile(profile, height); + const extruded = await shapeFromSketchProfile(profile, height); if (!extruded) throw new Error("Could not create the sketch profile"); shape = canonicalizeShape({ ...extruded, @@ -7762,14 +7860,18 @@ export function SketchForgeEditor({ } }, [hasSelection, projectName, selectedShapes, shapes, stepExporting]); - const exportSkfDesign = useCallback(async (exportName: string, historyLimit: SkfHistoryLimit) => { + const exportSkfDesign = useCallback(async (exportName: string, historyLimit: SkfHistoryLimit, target: SkfExportTarget = "download") => { if (skfExporting) return; + if (target === "shared" && !onSaveSharedProject) { + setNotice("Shared project storage is not available in this deployment"); + return; + } if (projectInteractionActiveRef.current) { setNotice("Finish the current drag or transform before saving the project file"); return; } setSkfExporting(true); - setNotice("Packaging editable project, history, and deduplicated assets…"); + setNotice(target === "shared" ? "Packaging project for Docker shared storage…" : "Packaging editable project, history, and deduplicated assets…"); try { const exportedHistory = editorHistoryForExport(historyRef.current, historyIndexRef.current, historyLimit); const bytes = await exportSkfProject({ @@ -7785,15 +7887,19 @@ export function SketchForgeEditor({ snapGrid, placementElevation, }); - const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; - const result = await downloadBlobFile(projectExportFileName(exportName, "skf"), new Blob([buffer], { type: SKF_MEDIA_TYPE })); - setNotice(result.mode === "folder" ? `Saved editable SketchForge project to ${result.path}` : "Saved editable SketchForge project (.skf)"); + if (target === "shared" && onSaveSharedProject) { + setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes })); + } else { + const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; + const result = await downloadBlobFile(projectExportFileName(exportName, "skf"), new Blob([buffer], { type: SKF_MEDIA_TYPE })); + setNotice(result.mode === "folder" ? `Saved editable SketchForge project to ${result.path}` : "Saved editable SketchForge project (.skf)"); + } } catch (error) { setNotice(error instanceof Error ? error.message : "Could not save SketchForge project"); } finally { setSkfExporting(false); } - }, [placementElevation, projectCreatedAt, projectModifiedAt, projectName, skfExporting, snapGrid]); + }, [onSaveSharedProject, placementElevation, projectCreatedAt, projectModifiedAt, projectName, skfExporting, snapGrid]); const clearDesign = useCallback(() => { commitShapes([], [], "New empty design"); @@ -8245,7 +8351,7 @@ export function SketchForgeEditor({ onWorkplaneTool={activateWorkplaneTool} workplaneMode={workplaneMode} onTopPanel={(panel) => { - setTopPanel(panel); + setTopPanel((current) => (current === panel ? null : panel)); setMenuOpen(false); }} onAddShape={(shape) => { @@ -8392,6 +8498,7 @@ export function SketchForgeEditor({ onExport={exportDesign} onExportSkf={exportSkfDesign} onExportStep={exportStepDesign} + sharedProjectsEnabled={sharedProjectsEnabled} skfExporting={skfExporting} stepExporting={stepExporting} onImportFiles={selectFiles} @@ -8898,6 +9005,7 @@ function TopActionPanel({ onExport, onExportSkf, onExportStep, + sharedProjectsEnabled, skfExporting, stepExporting, onImportFiles, @@ -8911,8 +9019,9 @@ function TopActionPanel({ scopeLabel: "selected" | "total"; onClose: () => void; onExport: (format: DirectExportFormat, exportName: string) => void; - onExportSkf: (exportName: string, historyLimit: SkfHistoryLimit) => void; + onExportSkf: (exportName: string, historyLimit: SkfHistoryLimit, target?: SkfExportTarget) => void; onExportStep: (exportName: string) => void; + sharedProjectsEnabled: boolean; skfExporting: boolean; stepExporting: boolean; onImportFiles: (files: FileList | File[]) => void; @@ -9099,6 +9208,17 @@ function TopActionPanel({