Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
feat: add automated desktop release pipeline
This commit is contained in:
@@ -0,0 +1,198 @@
|
|||||||
|
name: Desktop Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*.*.*"
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: "Version to release (for example 1.0.4)"
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: desktop-release
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-release:
|
||||||
|
name: Build and publish Windows desktop
|
||||||
|
runs-on: windows-latest
|
||||||
|
timeout-minutes: 45
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out source
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
|
||||||
|
- name: Resolve release version
|
||||||
|
id: version
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
if ("${{ github.event_name }}" -eq "workflow_dispatch") {
|
||||||
|
$version = "${{ inputs.version }}".Trim().TrimStart("v")
|
||||||
|
$tag = "v$version"
|
||||||
|
} else {
|
||||||
|
$tag = "${{ github.ref_name }}"
|
||||||
|
$version = $tag.TrimStart("v")
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($version -notmatch '^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$') {
|
||||||
|
throw "Invalid release version: $version"
|
||||||
|
}
|
||||||
|
|
||||||
|
"version=$version" >> $env:GITHUB_OUTPUT
|
||||||
|
"tag=$tag" >> $env:GITHUB_OUTPUT
|
||||||
|
Write-Host "Building SketchForge $version ($tag)"
|
||||||
|
|
||||||
|
- name: Ensure release tag exists
|
||||||
|
if: github.event_name == 'workflow_dispatch'
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
git fetch --tags --force
|
||||||
|
if (git rev-parse $env:TAG 2>$null) {
|
||||||
|
Write-Host "$env:TAG already exists."
|
||||||
|
} else {
|
||||||
|
git tag $env:TAG $env:GITHUB_SHA
|
||||||
|
git push origin $env:TAG
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: Set package version from release tag
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
VERSION: ${{ steps.version.outputs.version }}
|
||||||
|
run: npm version $env:VERSION --no-git-tag-version --allow-same-version
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: npm run typecheck
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: npm test
|
||||||
|
|
||||||
|
- name: Build Windows desktop update
|
||||||
|
run: npm run desktop:dist
|
||||||
|
|
||||||
|
- name: Verify updater artifacts
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
VERSION: ${{ steps.version.outputs.version }}
|
||||||
|
run: |
|
||||||
|
$installer = "dist/desktop/SketchForge-Setup-$env:VERSION-x64.exe"
|
||||||
|
$blockmap = "$installer.blockmap"
|
||||||
|
$latest = "dist/desktop/latest.yml"
|
||||||
|
|
||||||
|
foreach ($file in @($installer, $blockmap, $latest)) {
|
||||||
|
if (-not (Test-Path $file -PathType Leaf)) {
|
||||||
|
throw "Missing updater artifact: $file"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$metadata = Get-Content $latest -Raw
|
||||||
|
if ($metadata -notmatch "version:\s*$([regex]::Escape($env:VERSION))") {
|
||||||
|
throw "latest.yml does not contain version $env:VERSION"
|
||||||
|
}
|
||||||
|
|
||||||
|
$hash = (Get-FileHash $installer -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||||
|
Write-Host "Installer SHA-256: $hash"
|
||||||
|
Write-Host "Installer size: $((Get-Item $installer).Length) bytes"
|
||||||
|
|
||||||
|
- name: Create draft release
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
|
VERSION: ${{ steps.version.outputs.version }}
|
||||||
|
run: |
|
||||||
|
$existing = gh release view $env:TAG --json isDraft 2>$null
|
||||||
|
if ($LASTEXITCODE -eq 0) {
|
||||||
|
$release = $existing | ConvertFrom-Json
|
||||||
|
if (-not $release.isDraft) {
|
||||||
|
throw "Release $env:TAG is already published. Refusing to replace a live updater release."
|
||||||
|
}
|
||||||
|
Write-Host "Using existing draft release $env:TAG."
|
||||||
|
} else {
|
||||||
|
gh release create $env:TAG --draft --verify-tag --title "SketchForge $env:VERSION" --notes "SketchForge desktop $env:VERSION"
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: Upload updater assets to draft
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
|
VERSION: ${{ steps.version.outputs.version }}
|
||||||
|
run: |
|
||||||
|
$installer = "dist/desktop/SketchForge-Setup-$env:VERSION-x64.exe"
|
||||||
|
gh release upload $env:TAG `
|
||||||
|
$installer `
|
||||||
|
"$installer.blockmap" `
|
||||||
|
"dist/desktop/latest.yml" `
|
||||||
|
--clobber
|
||||||
|
|
||||||
|
- name: Verify GitHub release assets
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
|
VERSION: ${{ steps.version.outputs.version }}
|
||||||
|
run: |
|
||||||
|
$release = gh release view $env:TAG --json isDraft,assets | ConvertFrom-Json
|
||||||
|
if (-not $release.isDraft) {
|
||||||
|
throw "Release became public before verification."
|
||||||
|
}
|
||||||
|
|
||||||
|
$expected = @(
|
||||||
|
"SketchForge-Setup-$env:VERSION-x64.exe",
|
||||||
|
"SketchForge-Setup-$env:VERSION-x64.exe.blockmap",
|
||||||
|
"latest.yml"
|
||||||
|
)
|
||||||
|
$actual = @($release.assets | ForEach-Object { $_.name })
|
||||||
|
|
||||||
|
foreach ($name in $expected) {
|
||||||
|
if ($actual -notcontains $name) {
|
||||||
|
throw "GitHub release is missing $name"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($release.assets.Count -lt 3) {
|
||||||
|
throw "Expected at least 3 release assets."
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: Publish release as Latest
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
|
run: gh release edit $env:TAG --draft=false --latest
|
||||||
|
|
||||||
|
- name: Final release check
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
$release = gh release view $env:TAG --json tagName,isDraft,publishedAt,assets | ConvertFrom-Json
|
||||||
|
if ($release.isDraft) {
|
||||||
|
throw "Release $env:TAG is still a draft."
|
||||||
|
}
|
||||||
|
$latestTag = gh api "repos/$env:GITHUB_REPOSITORY/releases/latest" --jq '.tag_name'
|
||||||
|
if ($latestTag -ne $env:TAG) {
|
||||||
|
throw "Latest release is $latestTag instead of $env:TAG"
|
||||||
|
}
|
||||||
|
Write-Host "$env:TAG is published as Latest with $($release.assets.Count) assets."
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const desktopDir = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const repoRoot = path.resolve(desktopDir, "..", "..");
|
||||||
|
const nextBin = path.join(repoRoot, "node_modules", "next", "dist", "bin", "next");
|
||||||
|
const copyOcctScript = path.join(repoRoot, "scripts", "copy-occt-wasm.mjs");
|
||||||
|
|
||||||
|
function runNode(args, env = process.env) {
|
||||||
|
const result = spawnSync(process.execPath, args, {
|
||||||
|
cwd: repoRoot,
|
||||||
|
stdio: "inherit",
|
||||||
|
env,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
console.error(result.error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.status !== 0) {
|
||||||
|
process.exit(result.status ?? 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runNode([copyOcctScript]);
|
||||||
|
runNode([nextBin, "build", "apps/web"], {
|
||||||
|
...process.env,
|
||||||
|
SKETCHFORGE_DOCKER_BUILD: "true",
|
||||||
|
NEXT_TELEMETRY_DISABLED: "1",
|
||||||
|
});
|
||||||
|
|
||||||
|
const requiredPaths = [
|
||||||
|
path.join(repoRoot, "apps", "web", ".next", "standalone", "apps", "web", "server.js"),
|
||||||
|
path.join(repoRoot, "apps", "web", ".next", "static"),
|
||||||
|
path.join(repoRoot, "apps", "web", "public"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const requiredPath of requiredPaths) {
|
||||||
|
if (!fs.existsSync(requiredPath)) {
|
||||||
|
console.error(`[desktop:web:build] Missing expected build output: ${requiredPath}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("[desktop:web:build] Standalone SketchForge web bundle is ready.");
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
|
import net from "node:net";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import electronPath from "electron";
|
||||||
|
|
||||||
|
const desktopDir = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const repoRoot = path.resolve(desktopDir, "..", "..");
|
||||||
|
const nextBin = path.join(repoRoot, "node_modules", "next", "dist", "bin", "next");
|
||||||
|
const copyOcctScript = path.join(repoRoot, "scripts", "copy-occt-wasm.mjs");
|
||||||
|
const electronMain = path.join(desktopDir, "main.cjs");
|
||||||
|
|
||||||
|
function findFreePort() {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const server = net.createServer();
|
||||||
|
server.unref();
|
||||||
|
server.once("error", reject);
|
||||||
|
server.listen(0, "127.0.0.1", () => {
|
||||||
|
const address = server.address();
|
||||||
|
const port = typeof address === "object" && address ? address.port : 0;
|
||||||
|
server.close((error) => {
|
||||||
|
if (error) reject(error);
|
||||||
|
else if (!port) reject(new Error("Could not reserve a local development port."));
|
||||||
|
else resolve(port);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForUrl(url, child, timeoutMs = 45_000) {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
let lastError = null;
|
||||||
|
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (child.exitCode !== null) {
|
||||||
|
throw new Error(`Next.js exited with code ${child.exitCode}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, { redirect: "manual" });
|
||||||
|
if (response.status >= 200 && response.status < 500) return;
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 180));
|
||||||
|
}
|
||||||
|
|
||||||
|
const detail = lastError instanceof Error ? ` ${lastError.message}` : "";
|
||||||
|
throw new Error(`Timed out waiting for SketchForge dev server.${detail}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyResult = spawnSync(process.execPath, [copyOcctScript], {
|
||||||
|
cwd: repoRoot,
|
||||||
|
stdio: "inherit",
|
||||||
|
env: process.env,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (copyResult.status !== 0) {
|
||||||
|
process.exit(copyResult.status ?? 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = await findFreePort();
|
||||||
|
const url = `http://127.0.0.1:${port}`;
|
||||||
|
|
||||||
|
const nextProcess = spawn(
|
||||||
|
process.execPath,
|
||||||
|
[nextBin, "dev", "apps/web", "-H", "127.0.0.1", "-p", String(port)],
|
||||||
|
{
|
||||||
|
cwd: repoRoot,
|
||||||
|
stdio: "inherit",
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
SKETCHFORGE_SHARED_PROJECTS_DIR: "",
|
||||||
|
NEXT_TELEMETRY_DISABLED: "1",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let electronProcess = null;
|
||||||
|
let shuttingDown = false;
|
||||||
|
|
||||||
|
function shutdown(exitCode = 0) {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
|
||||||
|
if (electronProcess && electronProcess.exitCode === null) {
|
||||||
|
try {
|
||||||
|
electronProcess.kill();
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nextProcess.exitCode === null) {
|
||||||
|
try {
|
||||||
|
nextProcess.kill();
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => process.exit(exitCode), 100).unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
process.on("SIGINT", () => shutdown(130));
|
||||||
|
process.on("SIGTERM", () => shutdown(143));
|
||||||
|
|
||||||
|
nextProcess.on("exit", (code) => {
|
||||||
|
if (!shuttingDown && (!electronProcess || electronProcess.exitCode === null)) {
|
||||||
|
shutdown(code ?? 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await waitForUrl(url, nextProcess);
|
||||||
|
|
||||||
|
electronProcess = spawn(electronPath, [electronMain], {
|
||||||
|
cwd: repoRoot,
|
||||||
|
stdio: "inherit",
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
SKETCHFORGE_DESKTOP_DEV_URL: url,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
electronProcess.on("exit", (code) => {
|
||||||
|
shutdown(code ?? 0);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error instanceof Error ? error.stack || error.message : error);
|
||||||
|
shutdown(1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
appId: com.sketchforge.desktop
|
||||||
|
productName: SketchForge
|
||||||
|
asar: true
|
||||||
|
|
||||||
|
directories:
|
||||||
|
output: dist/desktop
|
||||||
|
|
||||||
|
publish:
|
||||||
|
provider: github
|
||||||
|
owner: Formsmith746
|
||||||
|
repo: SketchForge-3D
|
||||||
|
releaseType: release
|
||||||
|
|
||||||
|
files:
|
||||||
|
- apps/desktop/main.cjs
|
||||||
|
- apps/desktop/preload.cjs
|
||||||
|
- package.json
|
||||||
|
|
||||||
|
extraResources:
|
||||||
|
- from: apps/web/.next/standalone
|
||||||
|
to: web
|
||||||
|
- from: apps/web/.next/static
|
||||||
|
to: web/apps/web/.next/static
|
||||||
|
- from: apps/web/public
|
||||||
|
to: web/apps/web/public
|
||||||
|
|
||||||
|
win:
|
||||||
|
icon: apps/web/public/assets/sketchforge/sketchforge-logo.png
|
||||||
|
target:
|
||||||
|
- target: nsis
|
||||||
|
arch:
|
||||||
|
- x64
|
||||||
|
artifactName: ${productName}-Setup-${version}-${arch}.${ext}
|
||||||
|
|
||||||
|
nsis:
|
||||||
|
oneClick: false
|
||||||
|
allowToChangeInstallationDirectory: true
|
||||||
|
createDesktopShortcut: true
|
||||||
|
createStartMenuShortcut: true
|
||||||
|
|
||||||
|
mac:
|
||||||
|
icon: apps/web/public/assets/sketchforge/sketchforge-logo.png
|
||||||
|
target:
|
||||||
|
- dmg
|
||||||
|
category: public.app-category.graphics-design
|
||||||
|
artifactName: ${productName}-${version}-${arch}.${ext}
|
||||||
|
|
||||||
|
linux:
|
||||||
|
icon: apps/web/public/assets/sketchforge/sketchforge-logo.png
|
||||||
|
target:
|
||||||
|
- AppImage
|
||||||
|
category: Graphics
|
||||||
|
artifactName: ${productName}-${version}-${arch}.${ext}
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
const { app, BrowserWindow, Menu, Tray, dialog, ipcMain, nativeImage, shell } = require("electron");
|
||||||
|
const { autoUpdater } = require("electron-updater");
|
||||||
|
const { spawn } = require("node:child_process");
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const path = require("node:path");
|
||||||
|
|
||||||
|
const devUrl = process.env.SKETCHFORGE_DESKTOP_DEV_URL?.trim() || "";
|
||||||
|
// Keep the desktop origin stable. localStorage and IndexedDB are scoped to the
|
||||||
|
// full origin (including the port), so a random port made projects appear to
|
||||||
|
// vanish after every restart.
|
||||||
|
const DESKTOP_PORT = Number.parseInt(process.env.SKETCHFORGE_DESKTOP_PORT || "62158", 10);
|
||||||
|
|
||||||
|
let mainWindow = null;
|
||||||
|
let tray = null;
|
||||||
|
let webServer = null;
|
||||||
|
let webServerOutput = "";
|
||||||
|
let isQuitting = false;
|
||||||
|
let updaterConfigured = false;
|
||||||
|
let desktopIpcConfigured = false;
|
||||||
|
let updateCheckInFlight = false;
|
||||||
|
let manualUpdateCheck = false;
|
||||||
|
let downloadedUpdateReady = false;
|
||||||
|
let updateInstallRequested = false;
|
||||||
|
let lastUpdateCheckResult = null;
|
||||||
|
let lastUpdateCheckError = "";
|
||||||
|
|
||||||
|
function appendServerOutput(chunk) {
|
||||||
|
webServerOutput += String(chunk);
|
||||||
|
if (webServerOutput.length > 12_000) {
|
||||||
|
webServerOutput = webServerOutput.slice(-12_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForServer(url, timeoutMs = 30_000) {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
let lastError = null;
|
||||||
|
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (webServer && webServer.exitCode !== null) {
|
||||||
|
throw new Error(`SketchForge web process exited with code ${webServer.exitCode}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, { redirect: "manual" });
|
||||||
|
if (response.status >= 200 && response.status < 500) return;
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 180));
|
||||||
|
}
|
||||||
|
|
||||||
|
const detail = lastError instanceof Error ? ` ${lastError.message}` : "";
|
||||||
|
throw new Error(`SketchForge did not start its local web process in time.${detail}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startPackagedWebServer() {
|
||||||
|
const webRoot = path.join(process.resourcesPath, "web");
|
||||||
|
const serverPath = path.join(webRoot, "apps", "web", "server.js");
|
||||||
|
if (!fs.existsSync(serverPath)) {
|
||||||
|
throw new Error(`Desktop web bundle is missing: ${serverPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = DESKTOP_PORT;
|
||||||
|
const packagedNodeModules = path.join(process.resourcesPath, "app.asar", "node_modules");
|
||||||
|
|
||||||
|
webServer = spawn(process.execPath, [serverPath], {
|
||||||
|
cwd: path.dirname(serverPath),
|
||||||
|
windowsHide: true,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
ELECTRON_RUN_AS_NODE: "1",
|
||||||
|
NODE_PATH: [packagedNodeModules, process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
|
||||||
|
HOSTNAME: "127.0.0.1",
|
||||||
|
PORT: String(port),
|
||||||
|
SKETCHFORGE_DESKTOP: "1",
|
||||||
|
SKETCHFORGE_DESKTOP_VERSION: app.getVersion(),
|
||||||
|
SKETCHFORGE_SHARED_PROJECTS_DIR: "",
|
||||||
|
NEXT_TELEMETRY_DISABLED: "1",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
webServer.stdout?.on("data", appendServerOutput);
|
||||||
|
webServer.stderr?.on("data", appendServerOutput);
|
||||||
|
|
||||||
|
const url = `http://127.0.0.1:${port}`;
|
||||||
|
await waitForServer(url);
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopPackagedWebServer() {
|
||||||
|
if (!webServer || webServer.exitCode !== null) return;
|
||||||
|
try {
|
||||||
|
webServer.kill();
|
||||||
|
} catch {
|
||||||
|
// The process may already be gone while Electron is shutting down.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function appIconPath() {
|
||||||
|
return devUrl
|
||||||
|
? path.join(__dirname, "..", "web", "public", "assets", "sketchforge", "sketchforge-logo.png")
|
||||||
|
: path.join(process.resourcesPath, "web", "apps", "web", "public", "assets", "sketchforge", "sketchforge-logo.png");
|
||||||
|
}
|
||||||
|
|
||||||
|
function showMainWindow() {
|
||||||
|
if (!mainWindow || mainWindow.isDestroyed()) return;
|
||||||
|
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||||
|
mainWindow.show();
|
||||||
|
mainWindow.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function installDownloadedUpdate() {
|
||||||
|
if (!downloadedUpdateReady) return;
|
||||||
|
isQuitting = true;
|
||||||
|
stopPackagedWebServer();
|
||||||
|
setImmediate(() => autoUpdater.quitAndInstall(false, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadAndInstallDesktopUpdate() {
|
||||||
|
if (!app.isPackaged) {
|
||||||
|
return desktopUpdatePayload(null, "Updates can only be installed from the packaged SketchForge app.");
|
||||||
|
}
|
||||||
|
|
||||||
|
lastUpdateCheckError = "";
|
||||||
|
try {
|
||||||
|
let result = lastUpdateCheckResult;
|
||||||
|
if (!result?.isUpdateAvailable) {
|
||||||
|
result = await autoUpdater.checkForUpdates();
|
||||||
|
lastUpdateCheckResult = result;
|
||||||
|
}
|
||||||
|
if (!result?.isUpdateAvailable) {
|
||||||
|
return desktopUpdatePayload(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateInstallRequested = true;
|
||||||
|
await autoUpdater.downloadUpdate();
|
||||||
|
return desktopUpdatePayload(result);
|
||||||
|
} catch (error) {
|
||||||
|
updateInstallRequested = false;
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
lastUpdateCheckError = message;
|
||||||
|
return desktopUpdatePayload(lastUpdateCheckResult, message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function desktopUpdatePayload(result = lastUpdateCheckResult, errorMessage = lastUpdateCheckError) {
|
||||||
|
return {
|
||||||
|
currentVersion: app.getVersion(),
|
||||||
|
latestVersion: result?.updateInfo?.version || null,
|
||||||
|
updateAvailable: Boolean(result?.isUpdateAvailable),
|
||||||
|
downloaded: downloadedUpdateReady,
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
error: errorMessage || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkForDesktopUpdates(manual = false) {
|
||||||
|
if (!app.isPackaged) {
|
||||||
|
if (manual) {
|
||||||
|
await dialog.showMessageBox({
|
||||||
|
type: "info",
|
||||||
|
title: "SketchForge updates",
|
||||||
|
message: "Automatic updates are tested from the installed SketchForge app.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return desktopUpdatePayload(null);
|
||||||
|
}
|
||||||
|
if (downloadedUpdateReady) {
|
||||||
|
return desktopUpdatePayload();
|
||||||
|
}
|
||||||
|
if (updateCheckInFlight) {
|
||||||
|
return desktopUpdatePayload();
|
||||||
|
}
|
||||||
|
|
||||||
|
manualUpdateCheck = manualUpdateCheck || manual;
|
||||||
|
updateCheckInFlight = true;
|
||||||
|
lastUpdateCheckError = "";
|
||||||
|
try {
|
||||||
|
const result = await autoUpdater.checkForUpdates();
|
||||||
|
lastUpdateCheckResult = result;
|
||||||
|
return desktopUpdatePayload(result);
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
lastUpdateCheckError = message;
|
||||||
|
if (manualUpdateCheck) {
|
||||||
|
dialog.showErrorBox("Could not check for updates", message);
|
||||||
|
manualUpdateCheck = false;
|
||||||
|
}
|
||||||
|
return desktopUpdatePayload(null, message);
|
||||||
|
} finally {
|
||||||
|
updateCheckInFlight = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupDesktopIpc() {
|
||||||
|
if (desktopIpcConfigured) return;
|
||||||
|
desktopIpcConfigured = true;
|
||||||
|
|
||||||
|
ipcMain.handle("sketchforge:get-version", () => app.getVersion());
|
||||||
|
ipcMain.handle("sketchforge:check-for-updates", () => checkForDesktopUpdates(false));
|
||||||
|
ipcMain.handle("sketchforge:install-update", () => downloadAndInstallDesktopUpdate());
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupDesktopUpdater() {
|
||||||
|
if (updaterConfigured || !app.isPackaged) return;
|
||||||
|
updaterConfigured = true;
|
||||||
|
|
||||||
|
autoUpdater.autoDownload = false;
|
||||||
|
autoUpdater.autoInstallOnAppQuit = false;
|
||||||
|
autoUpdater.allowPrerelease = false;
|
||||||
|
|
||||||
|
autoUpdater.on("update-available", (info) => {
|
||||||
|
if (!manualUpdateCheck) return;
|
||||||
|
manualUpdateCheck = false;
|
||||||
|
void dialog.showMessageBox({
|
||||||
|
type: "info",
|
||||||
|
title: "SketchForge update",
|
||||||
|
message: `SketchForge ${info.version} is available.`,
|
||||||
|
detail: "Open Settings and press Update to install it.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on("update-not-available", () => {
|
||||||
|
if (!manualUpdateCheck) return;
|
||||||
|
manualUpdateCheck = false;
|
||||||
|
void dialog.showMessageBox({
|
||||||
|
type: "info",
|
||||||
|
title: "SketchForge updates",
|
||||||
|
message: "SketchForge is up to date.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on("download-progress", (progress) => {
|
||||||
|
if (tray) tray.setToolTip(`SketchForge - downloading update ${Math.round(progress.percent)}%`);
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on("update-downloaded", (info) => {
|
||||||
|
downloadedUpdateReady = true;
|
||||||
|
if (tray) tray.setToolTip(`SketchForge ${info.version} ready to install`);
|
||||||
|
if (updateInstallRequested) installDownloadedUpdate();
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on("error", (error) => {
|
||||||
|
if (tray) tray.setToolTip("SketchForge");
|
||||||
|
if (!manualUpdateCheck) return;
|
||||||
|
manualUpdateCheck = false;
|
||||||
|
dialog.showErrorBox("Could not update SketchForge", error instanceof Error ? error.message : String(error));
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => void checkForDesktopUpdates(false), 4_000).unref();
|
||||||
|
setInterval(() => void checkForDesktopUpdates(false), 6 * 60 * 60 * 1000).unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTray() {
|
||||||
|
if (tray) return;
|
||||||
|
|
||||||
|
const icon = nativeImage.createFromPath(appIconPath()).resize({ width: 20, height: 20 });
|
||||||
|
tray = new Tray(icon);
|
||||||
|
tray.setToolTip("SketchForge");
|
||||||
|
tray.setContextMenu(Menu.buildFromTemplate([
|
||||||
|
{
|
||||||
|
label: "Open SketchForge",
|
||||||
|
click: showMainWindow,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Check for Updates",
|
||||||
|
click: () => void checkForDesktopUpdates(true),
|
||||||
|
},
|
||||||
|
{ type: "separator" },
|
||||||
|
{
|
||||||
|
label: "Quit SketchForge",
|
||||||
|
click: () => {
|
||||||
|
if (downloadedUpdateReady) {
|
||||||
|
installDownloadedUpdate();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
isQuitting = true;
|
||||||
|
app.quit();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]));
|
||||||
|
tray.on("click", showMainWindow);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMainWindow(url) {
|
||||||
|
const appOrigin = new URL(url).origin;
|
||||||
|
const iconPath = appIconPath();
|
||||||
|
|
||||||
|
mainWindow = new BrowserWindow({
|
||||||
|
width: 1500,
|
||||||
|
height: 960,
|
||||||
|
minWidth: 1100,
|
||||||
|
minHeight: 700,
|
||||||
|
show: false,
|
||||||
|
title: "SketchForge",
|
||||||
|
icon: iconPath,
|
||||||
|
webPreferences: {
|
||||||
|
contextIsolation: true,
|
||||||
|
nodeIntegration: false,
|
||||||
|
sandbox: true,
|
||||||
|
preload: path.join(__dirname, "preload.cjs"),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
mainWindow.removeMenu();
|
||||||
|
|
||||||
|
mainWindow.webContents.setWindowOpenHandler(({ url: targetUrl }) => {
|
||||||
|
try {
|
||||||
|
const target = new URL(targetUrl);
|
||||||
|
if (target.origin === appOrigin) return { action: "allow" };
|
||||||
|
if (target.protocol === "http:" || target.protocol === "https:") {
|
||||||
|
void shell.openExternal(targetUrl);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed URLs instead of handing them to the OS.
|
||||||
|
}
|
||||||
|
return { action: "deny" };
|
||||||
|
});
|
||||||
|
|
||||||
|
mainWindow.webContents.on("will-navigate", (event, targetUrl) => {
|
||||||
|
try {
|
||||||
|
const target = new URL(targetUrl);
|
||||||
|
if (target.origin === appOrigin) return;
|
||||||
|
event.preventDefault();
|
||||||
|
if (target.protocol === "http:" || target.protocol === "https:") {
|
||||||
|
void shell.openExternal(targetUrl);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
mainWindow.once("ready-to-show", () => {
|
||||||
|
mainWindow?.show();
|
||||||
|
});
|
||||||
|
|
||||||
|
mainWindow.on("close", (event) => {
|
||||||
|
if (isQuitting) return;
|
||||||
|
event.preventDefault();
|
||||||
|
mainWindow?.hide();
|
||||||
|
});
|
||||||
|
|
||||||
|
mainWindow.on("closed", () => {
|
||||||
|
mainWindow = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
void mainWindow.loadURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startDesktop() {
|
||||||
|
Menu.setApplicationMenu(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = devUrl || await startPackagedWebServer();
|
||||||
|
setupDesktopIpc();
|
||||||
|
createTray();
|
||||||
|
createMainWindow(url);
|
||||||
|
setupDesktopUpdater();
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
const detail = webServerOutput.trim();
|
||||||
|
dialog.showErrorBox(
|
||||||
|
"SketchForge could not start",
|
||||||
|
detail ? `${message}\n\n${detail}` : message,
|
||||||
|
);
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasSingleInstanceLock = app.requestSingleInstanceLock();
|
||||||
|
|
||||||
|
if (!hasSingleInstanceLock) {
|
||||||
|
app.quit();
|
||||||
|
} else {
|
||||||
|
app.on("second-instance", showMainWindow);
|
||||||
|
|
||||||
|
app.whenReady().then(() => {
|
||||||
|
if (process.platform === "win32") app.setAppUserModelId("com.sketchforge.desktop");
|
||||||
|
void startDesktop();
|
||||||
|
|
||||||
|
app.on("activate", () => {
|
||||||
|
if (mainWindow) {
|
||||||
|
showMainWindow();
|
||||||
|
} else if (BrowserWindow.getAllWindows().length === 0) {
|
||||||
|
void startDesktop();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
app.on("before-quit", () => {
|
||||||
|
isQuitting = true;
|
||||||
|
stopPackagedWebServer();
|
||||||
|
});
|
||||||
|
|
||||||
|
app.on("window-all-closed", () => {
|
||||||
|
// Keep SketchForge available from the system tray. Use Quit SketchForge
|
||||||
|
// from the tray menu when the user wants to fully stop the application.
|
||||||
|
});
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
const { contextBridge, ipcRenderer } = require("electron");
|
||||||
|
|
||||||
|
contextBridge.exposeInMainWorld("sketchforgeDesktop", {
|
||||||
|
getVersion: () => ipcRenderer.invoke("sketchforge:get-version"),
|
||||||
|
checkForUpdates: () => ipcRenderer.invoke("sketchforge:check-for-updates"),
|
||||||
|
installUpdate: () => ipcRenderer.invoke("sketchforge:install-update"),
|
||||||
|
});
|
||||||
@@ -125,6 +125,64 @@ export async function GET(request: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function DELETE(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 deletes" }, { status: 403 });
|
||||||
|
|
||||||
|
let lockHandle: Awaited<ReturnType<typeof fs.open>> | null = null;
|
||||||
|
let lockPath = "";
|
||||||
|
try {
|
||||||
|
const requestUrl = new URL(request.url);
|
||||||
|
const requestedFile = requestUrl.searchParams.get("fileName");
|
||||||
|
if (!requestedFile) return NextResponse.json({ error: "Shared project name is required" }, { status: 400 });
|
||||||
|
const fileName = safeProjectFileName(requestedFile);
|
||||||
|
if (fileName !== requestedFile) return NextResponse.json({ error: "Invalid shared project name" }, { status: 400 });
|
||||||
|
|
||||||
|
await fs.mkdir(root, { recursive: true });
|
||||||
|
const filePath = path.join(root, fileName);
|
||||||
|
lockPath = `${filePath}.lock`;
|
||||||
|
|
||||||
|
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 changed by someone else" }, { status: 409 });
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentStat = await regularFileStat(filePath);
|
||||||
|
if (!currentStat) return NextResponse.json({ error: "Shared project was not found" }, { status: 404 });
|
||||||
|
|
||||||
|
const currentRevision = revisionForStat(currentStat);
|
||||||
|
const expectedRevision = unquoteEtag(request.headers.get("if-match"));
|
||||||
|
if (!expectedRevision) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Reload shared projects before deleting so the current revision can be verified", currentRevision },
|
||||||
|
{ status: 428 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (expectedRevision !== currentRevision) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "The shared project changed after you loaded it. Refresh the shared projects list and try again.", currentRevision },
|
||||||
|
{ status: 409 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.unlink(filePath);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ deleted: true, fileName },
|
||||||
|
{ headers: { "Cache-Control": "no-store" } },
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return NextResponse.json({ error: error instanceof Error ? error.message : "Could not delete shared project" }, { status: 500 });
|
||||||
|
} finally {
|
||||||
|
if (lockHandle) await lockHandle.close().catch(() => undefined);
|
||||||
|
if (lockPath) await fs.unlink(lockPath).catch(() => undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const root = sharedProjectsDirectory();
|
const root = sharedProjectsDirectory();
|
||||||
if (!root) return NextResponse.json({ error: "Shared project storage is disabled" }, { status: 404 });
|
if (!root) return NextResponse.json({ error: "Shared project storage is disabled" }, { status: 404 });
|
||||||
|
|||||||
@@ -803,8 +803,8 @@ button {
|
|||||||
|
|
||||||
.shared-project-badge {
|
.shared-project-badge {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 10px;
|
top: 18px;
|
||||||
right: 10px;
|
right: 54px;
|
||||||
z-index: 2;
|
z-index: 2;
|
||||||
padding: 4px 7px;
|
padding: 4px 7px;
|
||||||
color: #087f9f;
|
color: #087f9f;
|
||||||
|
|||||||
+182
-10
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Palette, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
|
import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Palette, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
|
import { SketchForgeEditor, importedShapeFromObj, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
|
||||||
import ChallengesDashboard from "@/components/official/ChallengesDashboard";
|
import ChallengesDashboard from "@/components/official/ChallengesDashboard";
|
||||||
import { applyAppTheme, readStoredAppTheme, resolveAppTheme, storeAppTheme, type AppThemePreference, type ResolvedAppTheme } from "@/lib/appTheme";
|
import { applyAppTheme, readStoredAppTheme, resolveAppTheme, storeAppTheme, type AppThemePreference, type ResolvedAppTheme } from "@/lib/appTheme";
|
||||||
import type { AppUpdateStatus } from "@/lib/appUpdates";
|
import type { AppUpdateStatus } from "@/lib/appUpdates";
|
||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
||||||
import { hydrateProjectShapeState, type ImportedMeshResource } from "@/lib/projectShapePersistence";
|
import { hydrateProjectShapeState, type ImportedMeshResource } from "@/lib/projectShapePersistence";
|
||||||
import { exportSkfProject, importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
|
import { exportSkfProject, importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
|
||||||
import { importExtensionSupported } from "@/lib/stlImport";
|
import { importExtensionSupported } from "@/lib/importExtensions";
|
||||||
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
|
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
|
||||||
import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||||
|
|
||||||
@@ -982,6 +982,25 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
}, [openSkfProjectFromFile]);
|
}, [openSkfProjectFromFile]);
|
||||||
|
|
||||||
|
const deleteSharedProject = useCallback(async (sharedProject: SharedProject) => {
|
||||||
|
setDashboardNotice(`Deleting shared project ${sharedProject.name}`);
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/shared-projects?fileName=${encodeURIComponent(sharedProject.fileName)}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: { "If-Match": `"${sharedProject.revision}"` },
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const payload = await response.json().catch(() => ({})) as { error?: string };
|
||||||
|
throw new Error(payload.error ?? "Could not delete shared project");
|
||||||
|
}
|
||||||
|
setSharedProjects((current) => current.filter((project) => project.fileName !== sharedProject.fileName));
|
||||||
|
setDashboardNotice(`Deleted shared project ${sharedProject.name}`);
|
||||||
|
} catch (error) {
|
||||||
|
setDashboardNotice(error instanceof Error ? error.message : "Could not delete shared project");
|
||||||
|
await refreshSharedProjects();
|
||||||
|
}
|
||||||
|
}, [refreshSharedProjects]);
|
||||||
|
|
||||||
const saveActiveProjectToShared = useCallback(async ({ exportName, bytes }: { exportName: string; bytes: Uint8Array }) => {
|
const saveActiveProjectToShared = useCallback(async ({ exportName, bytes }: { exportName: string; bytes: Uint8Array }) => {
|
||||||
const activeProject = projects.find((project) => project.id === activeProjectId);
|
const activeProject = projects.find((project) => project.id === activeProjectId);
|
||||||
if (!activeProject) throw new Error("Open a local project before saving it to the shared space");
|
if (!activeProject) throw new Error("Open a local project before saving it to the shared space");
|
||||||
@@ -1011,7 +1030,7 @@ export default function Home() {
|
|||||||
const projectFiles = files.filter((file) => /\.skf$/i.test(file.name));
|
const projectFiles = files.filter((file) => /\.skf$/i.test(file.name));
|
||||||
if (projectFiles.length) {
|
if (projectFiles.length) {
|
||||||
if (files.length !== 1) {
|
if (files.length !== 1) {
|
||||||
setDashboardNotice("Open one .skf project at a time; import STL, STEP, and SVG geometry separately");
|
setDashboardNotice("Open one .skf project at a time; import STL, OBJ, STEP, and SVG geometry separately");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await openSkfProjectFromFile(projectFiles[0]);
|
await openSkfProjectFromFile(projectFiles[0]);
|
||||||
@@ -1025,9 +1044,10 @@ export default function Home() {
|
|||||||
for (let index = 0; index < files.length; index += 1) {
|
for (let index = 0; index < files.length; index += 1) {
|
||||||
const file = files[index];
|
const file = files[index];
|
||||||
const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null);
|
const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null);
|
||||||
|
const isObj = sourceFormat === "obj";
|
||||||
const isSvg = sourceFormat === "svg";
|
const isSvg = sourceFormat === "svg";
|
||||||
const isStep = sourceFormat === "step";
|
const isStep = sourceFormat === "step";
|
||||||
if (!sourceFormat || sourceFormat === "obj" || (!isSvg && !isStep && !importExtensionSupported(file.name))) {
|
if (!sourceFormat || (!isSvg && !isStep && !importExtensionSupported(file.name))) {
|
||||||
failures.push({ fileName: file.name, reason: "Unsupported file type" });
|
failures.push({ fileName: file.name, reason: "Unsupported file type" });
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1038,9 +1058,11 @@ export default function Home() {
|
|||||||
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
||||||
const parsedShape = isStep
|
const parsedShape = isStep
|
||||||
? await import("@/lib/stepImport").then(({ importedShapeFromStep }) => importedShapeFromStep(file.name, buffer))
|
? await import("@/lib/stepImport").then(({ importedShapeFromStep }) => importedShapeFromStep(file.name, buffer))
|
||||||
: isSvg
|
: isObj
|
||||||
? importedShapeFromSvg(file.name, new TextDecoder().decode(bytes))
|
? importedShapeFromObj(file.name, new TextDecoder().decode(bytes))
|
||||||
: importedShapeFromStl(file.name, buffer);
|
: isSvg
|
||||||
|
? importedShapeFromSvg(file.name, new TextDecoder().decode(bytes))
|
||||||
|
: importedShapeFromStl(file.name, buffer);
|
||||||
const asset = await projectAssetFromBytes(file.name, sourceFormat, bytes, file.type);
|
const asset = await projectAssetFromBytes(file.name, sourceFormat, bytes, file.type);
|
||||||
importedShapes.push(attachProjectAsset(parsedShape, asset.id));
|
importedShapes.push(attachProjectAsset(parsedShape, asset.id));
|
||||||
importedAssets.push(asset);
|
importedAssets.push(asset);
|
||||||
@@ -1167,7 +1189,7 @@ export default function Home() {
|
|||||||
className="hidden-file-input"
|
className="hidden-file-input"
|
||||||
type="file"
|
type="file"
|
||||||
multiple
|
multiple
|
||||||
accept=".skf,.stl,.step,.stp,.svg,image/svg+xml"
|
accept=".skf,.stl,.obj,.step,.stp,.svg,image/svg+xml"
|
||||||
onChange={(event) => {
|
onChange={(event) => {
|
||||||
const files = event.currentTarget.files ? Array.from(event.currentTarget.files) : [];
|
const files = event.currentTarget.files ? Array.from(event.currentTarget.files) : [];
|
||||||
if (files.length) {
|
if (files.length) {
|
||||||
@@ -1195,6 +1217,7 @@ export default function Home() {
|
|||||||
onCreate={() => createAndOpenProject()}
|
onCreate={() => createAndOpenProject()}
|
||||||
onStartChallenge={(challenge) => createAndOpenProject(challenge === "nameplate" ? "Personalized Nameplate" : "Key Tag", challenge)}
|
onStartChallenge={(challenge) => createAndOpenProject(challenge === "nameplate" ? "Personalized Nameplate" : "Key Tag", challenge)}
|
||||||
onDeleteProject={deleteProject}
|
onDeleteProject={deleteProject}
|
||||||
|
onDeleteSharedProject={(project) => void deleteSharedProject(project)}
|
||||||
onDownloadFolderChange={setDownloadFolder}
|
onDownloadFolderChange={setDownloadFolder}
|
||||||
onDownloadModeChange={setDownloadMode}
|
onDownloadModeChange={setDownloadMode}
|
||||||
onImportFile={() => dashboardImportInputRef.current?.click()}
|
onImportFile={() => dashboardImportInputRef.current?.click()}
|
||||||
@@ -1349,6 +1372,7 @@ function Dashboard({
|
|||||||
onCreate,
|
onCreate,
|
||||||
onStartChallenge,
|
onStartChallenge,
|
||||||
onDeleteProject,
|
onDeleteProject,
|
||||||
|
onDeleteSharedProject,
|
||||||
onDownloadFolderChange,
|
onDownloadFolderChange,
|
||||||
onDownloadModeChange,
|
onDownloadModeChange,
|
||||||
onImportFile,
|
onImportFile,
|
||||||
@@ -1383,6 +1407,7 @@ function Dashboard({
|
|||||||
onCreate: () => void;
|
onCreate: () => void;
|
||||||
onStartChallenge: (challenge: ChallengeTutorialId) => void;
|
onStartChallenge: (challenge: ChallengeTutorialId) => void;
|
||||||
onDeleteProject: (projectId: string) => void;
|
onDeleteProject: (projectId: string) => void;
|
||||||
|
onDeleteSharedProject: (project: SharedProject) => void;
|
||||||
onDownloadFolderChange: (value: string) => void;
|
onDownloadFolderChange: (value: string) => void;
|
||||||
onDownloadModeChange: (value: DownloadMode) => void;
|
onDownloadModeChange: (value: DownloadMode) => void;
|
||||||
onImportFile: () => void;
|
onImportFile: () => void;
|
||||||
@@ -1401,10 +1426,14 @@ function Dashboard({
|
|||||||
onWorkspace: () => void;
|
onWorkspace: () => void;
|
||||||
}) {
|
}) {
|
||||||
const [openProjectMenuId, setOpenProjectMenuId] = useState<string | null>(null);
|
const [openProjectMenuId, setOpenProjectMenuId] = useState<string | null>(null);
|
||||||
|
const [openSharedProjectMenuFileName, setOpenSharedProjectMenuFileName] = useState<string | null>(null);
|
||||||
const [projectPendingDeleteId, setProjectPendingDeleteId] = useState<string | null>(null);
|
const [projectPendingDeleteId, setProjectPendingDeleteId] = useState<string | null>(null);
|
||||||
|
const [sharedProjectPendingDeleteFileName, setSharedProjectPendingDeleteFileName] = useState<string | null>(null);
|
||||||
const [projectPendingRenameId, setProjectPendingRenameId] = useState<string | null>(null);
|
const [projectPendingRenameId, setProjectPendingRenameId] = useState<string | null>(null);
|
||||||
const [projectNameDraft, setProjectNameDraft] = useState("");
|
const [projectNameDraft, setProjectNameDraft] = useState("");
|
||||||
const [updateStatus, setUpdateStatus] = useState<AppUpdateStatus | null>(null);
|
const [updateStatus, setUpdateStatus] = useState<AppUpdateStatus | null>(null);
|
||||||
|
const [desktopAppVersion, setDesktopAppVersion] = useState<string | null>(null);
|
||||||
|
const [desktopUpdaterConnected, setDesktopUpdaterConnected] = useState(false);
|
||||||
const [updateChecking, setUpdateChecking] = useState(false);
|
const [updateChecking, setUpdateChecking] = useState(false);
|
||||||
const [updatePromptOpen, setUpdatePromptOpen] = useState(false);
|
const [updatePromptOpen, setUpdatePromptOpen] = useState(false);
|
||||||
const [updateKey, setUpdateKey] = useState("");
|
const [updateKey, setUpdateKey] = useState("");
|
||||||
@@ -1412,20 +1441,40 @@ function Dashboard({
|
|||||||
const [updateMessage, setUpdateMessage] = useState("");
|
const [updateMessage, setUpdateMessage] = useState("");
|
||||||
const updateCheckedRef = useRef(false);
|
const updateCheckedRef = useRef(false);
|
||||||
const projectPendingDelete = projects.find((project) => project.id === projectPendingDeleteId) ?? null;
|
const projectPendingDelete = projects.find((project) => project.id === projectPendingDeleteId) ?? null;
|
||||||
|
const sharedProjectPendingDelete = sharedProjects.find((project) => project.fileName === sharedProjectPendingDeleteFileName) ?? null;
|
||||||
const projectPendingRename = projects.find((project) => project.id === projectPendingRenameId) ?? null;
|
const projectPendingRename = projects.find((project) => project.id === projectPendingRenameId) ?? null;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const desktop = window.sketchforgeDesktop;
|
||||||
|
if (!desktop) return;
|
||||||
|
setDesktopUpdaterConnected(true);
|
||||||
|
void desktop.getVersion().then(setDesktopAppVersion).catch(() => undefined);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!projectPendingDeleteId) return;
|
if (!projectPendingDeleteId) return;
|
||||||
if (projects.some((project) => project.id === projectPendingDeleteId)) return;
|
if (projects.some((project) => project.id === projectPendingDeleteId)) return;
|
||||||
setProjectPendingDeleteId(null);
|
setProjectPendingDeleteId(null);
|
||||||
}, [projectPendingDeleteId, projects]);
|
}, [projectPendingDeleteId, projects]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!sharedProjectPendingDeleteFileName) return;
|
||||||
|
if (sharedProjects.some((project) => project.fileName === sharedProjectPendingDeleteFileName)) return;
|
||||||
|
setSharedProjectPendingDeleteFileName(null);
|
||||||
|
}, [sharedProjectPendingDeleteFileName, sharedProjects]);
|
||||||
|
|
||||||
const confirmProjectDelete = () => {
|
const confirmProjectDelete = () => {
|
||||||
if (!projectPendingDelete) return;
|
if (!projectPendingDelete) return;
|
||||||
onDeleteProject(projectPendingDelete.id);
|
onDeleteProject(projectPendingDelete.id);
|
||||||
setProjectPendingDeleteId(null);
|
setProjectPendingDeleteId(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const confirmSharedProjectDelete = () => {
|
||||||
|
if (!sharedProjectPendingDelete) return;
|
||||||
|
onDeleteSharedProject(sharedProjectPendingDelete);
|
||||||
|
setSharedProjectPendingDeleteFileName(null);
|
||||||
|
};
|
||||||
|
|
||||||
const startProjectRename = (project: DashboardProject) => {
|
const startProjectRename = (project: DashboardProject) => {
|
||||||
setOpenProjectMenuId(null);
|
setOpenProjectMenuId(null);
|
||||||
setProjectPendingRenameId(project.id);
|
setProjectPendingRenameId(project.id);
|
||||||
@@ -1448,6 +1497,34 @@ function Dashboard({
|
|||||||
setUpdateChecking(true);
|
setUpdateChecking(true);
|
||||||
setUpdateMessage("");
|
setUpdateMessage("");
|
||||||
try {
|
try {
|
||||||
|
const desktop = window.sketchforgeDesktop;
|
||||||
|
if (desktop) {
|
||||||
|
setDesktopUpdaterConnected(true);
|
||||||
|
const result = await desktop.checkForUpdates();
|
||||||
|
setDesktopAppVersion(result.currentVersion);
|
||||||
|
if (result.error) throw new Error(result.error);
|
||||||
|
const payload: AppUpdateStatus = {
|
||||||
|
currentVersion: result.currentVersion,
|
||||||
|
latestVersion: result.latestVersion,
|
||||||
|
updateAvailable: result.updateAvailable,
|
||||||
|
checkedAt: result.checkedAt,
|
||||||
|
updateUrl: "",
|
||||||
|
installationReady: true,
|
||||||
|
requiresUpdateKey: false,
|
||||||
|
};
|
||||||
|
setUpdateStatus(payload);
|
||||||
|
if (result.updateAvailable && result.latestVersion) {
|
||||||
|
setUpdateMessage(
|
||||||
|
result.downloaded
|
||||||
|
? `SketchForge ${result.latestVersion} is ready to install.`
|
||||||
|
: `SketchForge ${result.latestVersion} is available. Press Update to download, install, and restart.`,
|
||||||
|
);
|
||||||
|
} else if (alwaysPrompt) {
|
||||||
|
setUpdateMessage("SketchForge is up to date.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const response = await fetch(`/api/app-update${force ? "?force=1" : ""}`, { cache: "no-store" });
|
const response = await fetch(`/api/app-update${force ? "?force=1" : ""}`, { cache: "no-store" });
|
||||||
const payload = await response.json() as AppUpdateStatus & { error?: string };
|
const payload = await response.json() as AppUpdateStatus & { error?: string };
|
||||||
if (!response.ok) throw new Error(payload.error || "Could not check for updates");
|
if (!response.ok) throw new Error(payload.error || "Could not check for updates");
|
||||||
@@ -1485,6 +1562,36 @@ function Dashboard({
|
|||||||
|
|
||||||
const requestUpdate = async () => {
|
const requestUpdate = async () => {
|
||||||
if (!updateStatus?.updateAvailable) return;
|
if (!updateStatus?.updateAvailable) return;
|
||||||
|
|
||||||
|
const desktop = window.sketchforgeDesktop;
|
||||||
|
if (desktop) {
|
||||||
|
setUpdateStarting(true);
|
||||||
|
setUpdateMessage(`Downloading SketchForge ${updateStatus.latestVersion ?? "update"}…`);
|
||||||
|
try {
|
||||||
|
const result = await desktop.installUpdate();
|
||||||
|
if (result.error) throw new Error(result.error);
|
||||||
|
if (!result.updateAvailable) {
|
||||||
|
setUpdateStatus({
|
||||||
|
currentVersion: result.currentVersion,
|
||||||
|
latestVersion: result.latestVersion,
|
||||||
|
updateAvailable: false,
|
||||||
|
checkedAt: result.checkedAt,
|
||||||
|
updateUrl: "",
|
||||||
|
installationReady: true,
|
||||||
|
requiresUpdateKey: false,
|
||||||
|
});
|
||||||
|
setUpdateMessage("SketchForge is already up to date.");
|
||||||
|
} else {
|
||||||
|
setUpdateMessage("Update downloaded. SketchForge is restarting to install it…");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setUpdateMessage(error instanceof Error ? error.message : "Could not install the update");
|
||||||
|
} finally {
|
||||||
|
setUpdateStarting(false);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!updateStatus.installationReady) {
|
if (!updateStatus.installationReady) {
|
||||||
window.open(updateStatus.updateUrl, "_blank", "noopener,noreferrer");
|
window.open(updateStatus.updateUrl, "_blank", "noopener,noreferrer");
|
||||||
dismissUpdate();
|
dismissUpdate();
|
||||||
@@ -1593,6 +1700,35 @@ function Dashboard({
|
|||||||
<span className="project-card-meta">{formatUpdated(project.updatedAt)} - {formatFileSize(project.size)}</span>
|
<span className="project-card-meta">{formatUpdated(project.updatedAt)} - {formatFileSize(project.size)}</span>
|
||||||
</button>
|
</button>
|
||||||
<span className="shared-project-badge">Shared</span>
|
<span className="shared-project-badge">Shared</span>
|
||||||
|
<button
|
||||||
|
className="project-menu-trigger"
|
||||||
|
type="button"
|
||||||
|
aria-label={`Shared project options for ${project.name}`}
|
||||||
|
aria-expanded={openSharedProjectMenuFileName === project.fileName}
|
||||||
|
title="Shared project options"
|
||||||
|
onClick={() => {
|
||||||
|
setOpenProjectMenuId(null);
|
||||||
|
setOpenSharedProjectMenuFileName((current) => (current === project.fileName ? null : project.fileName));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<EllipsisVertical size={19} strokeWidth={2.5} />
|
||||||
|
</button>
|
||||||
|
{openSharedProjectMenuFileName === project.fileName ? (
|
||||||
|
<div className="project-card-menu" role="menu" aria-label={`Options for shared project ${project.name}`}>
|
||||||
|
<button
|
||||||
|
className="delete"
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
onClick={() => {
|
||||||
|
setOpenSharedProjectMenuFileName(null);
|
||||||
|
setSharedProjectPendingDeleteFileName(project.fileName);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Trash2 size={16} />
|
||||||
|
<span>Delete</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</article>
|
</article>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -1672,7 +1808,10 @@ function Dashboard({
|
|||||||
aria-label={`Project options for ${project.name}`}
|
aria-label={`Project options for ${project.name}`}
|
||||||
aria-expanded={openProjectMenuId === project.id}
|
aria-expanded={openProjectMenuId === project.id}
|
||||||
title="Project options"
|
title="Project options"
|
||||||
onClick={() => setOpenProjectMenuId((current) => (current === project.id ? null : project.id))}
|
onClick={() => {
|
||||||
|
setOpenSharedProjectMenuFileName(null);
|
||||||
|
setOpenProjectMenuId((current) => (current === project.id ? null : project.id));
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<EllipsisVertical size={19} strokeWidth={2.5} />
|
<EllipsisVertical size={19} strokeWidth={2.5} />
|
||||||
</button>
|
</button>
|
||||||
@@ -1734,6 +1873,30 @@ function Dashboard({
|
|||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{sharedProjectPendingDelete ? (
|
||||||
|
<section className="dashboard-confirm-overlay" role="dialog" aria-modal="true" aria-labelledby="delete-shared-project-title">
|
||||||
|
<div className="dashboard-confirm-dialog">
|
||||||
|
<header>
|
||||||
|
<strong id="delete-shared-project-title">Delete shared project?</strong>
|
||||||
|
<button type="button" aria-label="Cancel shared project deletion" onClick={() => setSharedProjectPendingDeleteFileName(null)}>
|
||||||
|
<X size={18} />
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<p>
|
||||||
|
Delete <span>{sharedProjectPendingDelete.name}</span> from shared storage? This removes it for everyone using this shared space.
|
||||||
|
</p>
|
||||||
|
<div className="dashboard-confirm-actions">
|
||||||
|
<button className="dashboard-confirm-cancel" type="button" onClick={() => setSharedProjectPendingDeleteFileName(null)}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button className="dashboard-confirm-delete" type="button" onClick={confirmSharedProjectDelete}>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{projectPendingRename ? (
|
{projectPendingRename ? (
|
||||||
<section className="dashboard-confirm-overlay" role="dialog" aria-modal="true" aria-labelledby="rename-project-title">
|
<section className="dashboard-confirm-overlay" role="dialog" aria-modal="true" aria-labelledby="rename-project-title">
|
||||||
<form
|
<form
|
||||||
@@ -1843,7 +2006,7 @@ function Dashboard({
|
|||||||
</label>
|
</label>
|
||||||
<div className="dashboard-version-row">
|
<div className="dashboard-version-row">
|
||||||
<span>SketchForge version</span>
|
<span>SketchForge version</span>
|
||||||
<strong>{SKF_CREATED_WITH_VERSION}</strong>
|
<strong>{desktopAppVersion ?? SKF_CREATED_WITH_VERSION}</strong>
|
||||||
</div>
|
</div>
|
||||||
<section className="dashboard-update-settings" aria-label="Software updates">
|
<section className="dashboard-update-settings" aria-label="Software updates">
|
||||||
<div>
|
<div>
|
||||||
@@ -1854,6 +2017,15 @@ function Dashboard({
|
|||||||
<span className="dashboard-update-status">Managed by the website owner</span>
|
<span className="dashboard-update-status">Managed by the website owner</span>
|
||||||
) : updateStatus?.checkError ? (
|
) : updateStatus?.checkError ? (
|
||||||
<span className="dashboard-update-status error">{updateStatus.checkError}</span>
|
<span className="dashboard-update-status error">{updateStatus.checkError}</span>
|
||||||
|
) : desktopUpdaterConnected && updateStatus?.updateAvailable && updateStatus.latestVersion ? (
|
||||||
|
<button
|
||||||
|
className="dashboard-update-available"
|
||||||
|
type="button"
|
||||||
|
onClick={() => void requestUpdate()}
|
||||||
|
disabled={updateStarting}
|
||||||
|
>
|
||||||
|
{updateStarting ? "Downloading update…" : `Update to ${updateStatus.latestVersion}`}
|
||||||
|
</button>
|
||||||
) : updateStatus?.updateAvailable && updateStatus.latestVersion ? (
|
) : updateStatus?.updateAvailable && updateStatus.latestVersion ? (
|
||||||
<button
|
<button
|
||||||
className="dashboard-update-available"
|
className="dashboard-update-available"
|
||||||
|
|||||||
@@ -86,12 +86,14 @@ import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap
|
|||||||
import { createLocalId } from "@/lib/localIds";
|
import { createLocalId } from "@/lib/localIds";
|
||||||
import { projectExportFileName } from "@/lib/exportNames";
|
import { projectExportFileName } from "@/lib/exportNames";
|
||||||
import { exportMeshesToObj } from "@/lib/objExport";
|
import { exportMeshesToObj } from "@/lib/objExport";
|
||||||
|
import { importedShapeFromObj } from "@/lib/objImport";
|
||||||
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
||||||
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
|
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
|
||||||
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
|
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
|
||||||
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
|
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
|
||||||
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
|
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
|
||||||
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
|
import { importExtensionSupported } from "@/lib/importExtensions";
|
||||||
|
import { importedShapeFromStl } from "@/lib/stlImport";
|
||||||
import { exportMeshesToStl } from "@/lib/stlExport";
|
import { exportMeshesToStl } from "@/lib/stlExport";
|
||||||
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
|
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
|
||||||
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
|
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
|
||||||
@@ -119,7 +121,7 @@ import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge,
|
|||||||
import type { SketchCadBuildResponse } from "@/lib/sketchCadTypes";
|
import type { SketchCadBuildResponse } from "@/lib/sketchCadTypes";
|
||||||
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||||
|
|
||||||
export { importedShapeFromStl, importedShapeFromSvg };
|
export { importedShapeFromObj, importedShapeFromStl, importedShapeFromSvg };
|
||||||
|
|
||||||
type TopPanel = "import" | "export" | "profile" | "settings" | null;
|
type TopPanel = "import" | "export" | "profile" | "settings" | null;
|
||||||
type ExportFormat = "stl" | "obj" | "step" | "svg" | "skf";
|
type ExportFormat = "stl" | "obj" | "step" | "svg" | "skf";
|
||||||
@@ -2642,6 +2644,40 @@ function boundsForShapes(shapes: WorkplaneShape[]): Cuboid {
|
|||||||
return boundsForCuboids(bounds);
|
return boundsForCuboids(bounds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function selectionCenterOnWorkplane(shapes: WorkplaneShape[], workplane: PlacementWorkplane) {
|
||||||
|
const xAxis = new THREE.Vector3(workplane.xAxis.x, workplane.xAxis.y, workplane.xAxis.z).normalize();
|
||||||
|
const yAxis = new THREE.Vector3(workplane.normal.x, workplane.normal.y, workplane.normal.z).normalize();
|
||||||
|
const zAxis = new THREE.Vector3(workplane.zAxis.x, workplane.zAxis.y, workplane.zAxis.z).normalize();
|
||||||
|
const min = new THREE.Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
|
||||||
|
const max = new THREE.Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
|
||||||
|
|
||||||
|
shapes.forEach((shape) => {
|
||||||
|
meshForShape(shape).vertices.forEach(([x, y, z]) => {
|
||||||
|
const point = new THREE.Vector3(x, y, z);
|
||||||
|
min.x = Math.min(min.x, point.dot(xAxis));
|
||||||
|
min.y = Math.min(min.y, point.dot(yAxis));
|
||||||
|
min.z = Math.min(min.z, point.dot(zAxis));
|
||||||
|
max.x = Math.max(max.x, point.dot(xAxis));
|
||||||
|
max.y = Math.max(max.y, point.dot(yAxis));
|
||||||
|
max.z = Math.max(max.z, point.dot(zAxis));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
if ([min.x, min.y, min.z, max.x, max.y, max.z].every(Number.isFinite)) {
|
||||||
|
return new THREE.Vector3()
|
||||||
|
.addScaledVector(xAxis, (min.x + max.x) / 2)
|
||||||
|
.addScaledVector(yAxis, (min.y + max.y) / 2)
|
||||||
|
.addScaledVector(zAxis, (min.z + max.z) / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const bounds = boundsForShapes(shapes);
|
||||||
|
return new THREE.Vector3(
|
||||||
|
(bounds.minX + bounds.maxX) / 2,
|
||||||
|
(bounds.minY + bounds.maxY) / 2,
|
||||||
|
(bounds.minZ + bounds.maxZ) / 2,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function boundsForCuboids(bounds: Cuboid[]): Cuboid {
|
function boundsForCuboids(bounds: Cuboid[]): Cuboid {
|
||||||
return {
|
return {
|
||||||
minX: Math.min(...bounds.map((box) => box.minX)),
|
minX: Math.min(...bounds.map((box) => box.minX)),
|
||||||
@@ -8461,7 +8497,7 @@ export function SketchForgeEditor({
|
|||||||
const projectFiles = files.filter((file) => /\.skf$/i.test(file.name));
|
const projectFiles = files.filter((file) => /\.skf$/i.test(file.name));
|
||||||
if (projectFiles.length) {
|
if (projectFiles.length) {
|
||||||
if (files.length !== 1) {
|
if (files.length !== 1) {
|
||||||
setNotice("Open one .skf project at a time; import STL, STEP, and SVG geometry separately");
|
setNotice("Open one .skf project at a time; import STL, OBJ, STEP, and SVG geometry separately");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!onOpenSkfProjectFile) {
|
if (!onOpenSkfProjectFile) {
|
||||||
@@ -8488,8 +8524,9 @@ export function SketchForgeEditor({
|
|||||||
|
|
||||||
const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null);
|
const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null);
|
||||||
const isStep = sourceFormat === "step";
|
const isStep = sourceFormat === "step";
|
||||||
|
const isObj = sourceFormat === "obj";
|
||||||
const isSvg = sourceFormat === "svg";
|
const isSvg = sourceFormat === "svg";
|
||||||
if (!sourceFormat || sourceFormat === "obj" || (!isStep && !isSvg && !importExtensionSupported(file.name))) {
|
if (!sourceFormat || (!isStep && !isSvg && !importExtensionSupported(file.name))) {
|
||||||
failures.push({ fileName: file.name, reason: "Unsupported file type" });
|
failures.push({ fileName: file.name, reason: "Unsupported file type" });
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -8502,6 +8539,8 @@ export function SketchForgeEditor({
|
|||||||
if (isStep) {
|
if (isStep) {
|
||||||
const { importedShapeFromStep } = await import("@/lib/stepImport");
|
const { importedShapeFromStep } = await import("@/lib/stepImport");
|
||||||
nextShape = await importedShapeFromStep(file.name, buffer);
|
nextShape = await importedShapeFromStep(file.name, buffer);
|
||||||
|
} else if (isObj) {
|
||||||
|
nextShape = importedShapeFromObj(file.name, new TextDecoder().decode(bytes));
|
||||||
} else if (isSvg) {
|
} else if (isSvg) {
|
||||||
nextShape = importedShapeFromSvg(file.name, new TextDecoder().decode(bytes));
|
nextShape = importedShapeFromSvg(file.name, new TextDecoder().decode(bytes));
|
||||||
} else {
|
} else {
|
||||||
@@ -8604,6 +8643,61 @@ export function SketchForgeEditor({
|
|||||||
[commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes.length, shapes],
|
[commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes.length, shapes],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const rotateSelected45 = useCallback(() => {
|
||||||
|
if (!hasSelection) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selected = new Set(selectedIds);
|
||||||
|
const rotatableShapes = selectedShapes.filter((shape) => !shape.locked);
|
||||||
|
if (rotatableShapes.length === 0) {
|
||||||
|
setNotice("Selection is locked");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const axis = new THREE.Vector3(
|
||||||
|
placementWorkplane.normal.x,
|
||||||
|
placementWorkplane.normal.y,
|
||||||
|
placementWorkplane.normal.z,
|
||||||
|
);
|
||||||
|
if (axis.lengthSq() < 0.000001) {
|
||||||
|
axis.set(0, 1, 0);
|
||||||
|
} else {
|
||||||
|
axis.normalize();
|
||||||
|
}
|
||||||
|
const rotationDelta = new THREE.Quaternion().setFromAxisAngle(axis, THREE.MathUtils.degToRad(45));
|
||||||
|
const pivot = rotatableShapes.length > 1 ? selectionCenterOnWorkplane(rotatableShapes, placementWorkplane) : null;
|
||||||
|
|
||||||
|
const nextShapes = shapes.map((shape) => {
|
||||||
|
if (!selected.has(shape.id) || shape.locked) {
|
||||||
|
return shape;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextQuaternion = rotationDelta.clone().multiply(quaternionForShape(shape));
|
||||||
|
const rotationPatch = rotationFromQuaternion(nextQuaternion);
|
||||||
|
let rotated = canonicalizeShape({ ...shape, ...rotationPatch });
|
||||||
|
|
||||||
|
if (pivot) {
|
||||||
|
const startCenter = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z);
|
||||||
|
const nextCenter = pivot.clone().add(startCenter.sub(pivot).applyQuaternion(rotationDelta));
|
||||||
|
rotated = canonicalizeShape({
|
||||||
|
...rotated,
|
||||||
|
x: cleanNearZero(nextCenter.x, 0.0005),
|
||||||
|
z: cleanNearZero(nextCenter.z, 0.0005),
|
||||||
|
elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return canonicalizeShape(bakeShapeTransformIntoMesh(rotated));
|
||||||
|
});
|
||||||
|
|
||||||
|
commitShapes(
|
||||||
|
nextShapes,
|
||||||
|
selectedIds,
|
||||||
|
`Rotated ${rotatableShapes.length} shape${rotatableShapes.length === 1 ? "" : "s"} by 45°`,
|
||||||
|
);
|
||||||
|
}, [commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes, shapes]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const isTypingTarget = (target: EventTarget | null) => {
|
const isTypingTarget = (target: EventTarget | null) => {
|
||||||
if (!(target instanceof HTMLElement)) {
|
if (!(target instanceof HTMLElement)) {
|
||||||
@@ -8727,6 +8821,12 @@ export function SketchForgeEditor({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!shortcut && !event.altKey && key === "r" && hasSelection) {
|
||||||
|
event.preventDefault();
|
||||||
|
rotateSelected45();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const step = event.shiftKey ? 5 : 1;
|
const step = event.shiftKey ? 5 : 1;
|
||||||
if (shortcut && event.key === "ArrowUp") {
|
if (shortcut && event.key === "ArrowUp") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -8781,6 +8881,7 @@ export function SketchForgeEditor({
|
|||||||
pasteShape,
|
pasteShape,
|
||||||
raiseSelected,
|
raiseSelected,
|
||||||
redo,
|
redo,
|
||||||
|
rotateSelected45,
|
||||||
sketchActive,
|
sketchActive,
|
||||||
sketchRedo,
|
sketchRedo,
|
||||||
sketchMeasurement,
|
sketchMeasurement,
|
||||||
@@ -9051,7 +9152,7 @@ export function SketchForgeEditor({
|
|||||||
className="hidden-file-input"
|
className="hidden-file-input"
|
||||||
type="file"
|
type="file"
|
||||||
multiple
|
multiple
|
||||||
accept=".stl,.step,.stp,.svg,image/svg+xml"
|
accept=".stl,.obj,.step,.stp,.svg,image/svg+xml"
|
||||||
onChange={(event) => {
|
onChange={(event) => {
|
||||||
if (event.currentTarget.files) {
|
if (event.currentTarget.files) {
|
||||||
selectFiles(event.currentTarget.files);
|
selectFiles(event.currentTarget.files);
|
||||||
@@ -9788,7 +9889,7 @@ function TopActionPanel({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ToolbarImportIcon />
|
<ToolbarImportIcon />
|
||||||
<strong>Drop STL, STEP, or SVG files</strong>
|
<strong>Drop STL, OBJ, STEP, or SVG files</strong>
|
||||||
<span>or click to choose from your computer</span>
|
<span>or click to choose from your computer</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl", "obj", "svg"]);
|
||||||
|
|
||||||
|
function fileExtension(fileName: string) {
|
||||||
|
return fileName.split(".").pop()?.toLowerCase() ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importExtensionSupported(fileName: string) {
|
||||||
|
return SUPPORTED_IMPORT_EXTENSIONS.has(fileExtension(fileName));
|
||||||
|
}
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import * as THREE from "three";
|
||||||
|
import { createLocalId } from "@/lib/localIds";
|
||||||
|
import { zUpToSketchForge } from "@/lib/meshCoordinates";
|
||||||
|
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||||
|
|
||||||
|
type ObjFaceVertex = {
|
||||||
|
vertexIndex: number;
|
||||||
|
normalIndex?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function resolveObjIndex(token: string, count: number, label: string) {
|
||||||
|
const parsed = Number.parseInt(token, 10);
|
||||||
|
if (!Number.isInteger(parsed) || parsed === 0) throw new Error(`OBJ has an invalid ${label} index`);
|
||||||
|
const index = parsed > 0 ? parsed - 1 : count + parsed;
|
||||||
|
if (index < 0 || index >= count) throw new Error(`OBJ ${label} index is out of range`);
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
function faceNormal(points: readonly THREE.Vector3[]) {
|
||||||
|
const normal = new THREE.Vector3();
|
||||||
|
for (let index = 0; index < points.length; index += 1) {
|
||||||
|
const current = points[index];
|
||||||
|
const next = points[(index + 1) % points.length];
|
||||||
|
normal.x += (current.y - next.y) * (current.z + next.z);
|
||||||
|
normal.y += (current.z - next.z) * (current.x + next.x);
|
||||||
|
normal.z += (current.x - next.x) * (current.y + next.y);
|
||||||
|
}
|
||||||
|
return normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
function projectedFace(points: readonly THREE.Vector3[], normal: THREE.Vector3) {
|
||||||
|
const absX = Math.abs(normal.x);
|
||||||
|
const absY = Math.abs(normal.y);
|
||||||
|
const absZ = Math.abs(normal.z);
|
||||||
|
if (absX >= absY && absX >= absZ) return points.map((point) => new THREE.Vector2(point.y, point.z));
|
||||||
|
if (absY >= absZ) return points.map((point) => new THREE.Vector2(point.x, point.z));
|
||||||
|
return points.map((point) => new THREE.Vector2(point.x, point.y));
|
||||||
|
}
|
||||||
|
|
||||||
|
function triangulateFace(points: readonly THREE.Vector3[]) {
|
||||||
|
if (points.length === 3) return [[0, 1, 2] as const];
|
||||||
|
|
||||||
|
const polygonNormal = faceNormal(points);
|
||||||
|
if (polygonNormal.lengthSq() <= 1e-20) throw new Error("OBJ contains a degenerate polygon face");
|
||||||
|
const triangles = THREE.ShapeUtils.triangulateShape(projectedFace(points, polygonNormal), []);
|
||||||
|
if (!triangles.length) throw new Error("OBJ contains a polygon face that could not be triangulated");
|
||||||
|
|
||||||
|
return triangles.map(([a, b, c]) => {
|
||||||
|
const triangleNormal = new THREE.Vector3()
|
||||||
|
.subVectors(points[b], points[a])
|
||||||
|
.cross(new THREE.Vector3().subVectors(points[c], points[a]));
|
||||||
|
return triangleNormal.dot(polygonNormal) < 0 ? [a, c, b] as const : [a, b, c] as const;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function orientTriangleToObjNormals(
|
||||||
|
triangle: readonly [number, number, number],
|
||||||
|
refs: readonly ObjFaceVertex[],
|
||||||
|
vertices: readonly THREE.Vector3[],
|
||||||
|
normals: readonly THREE.Vector3[],
|
||||||
|
): readonly [number, number, number] {
|
||||||
|
const [aIndex, bIndex, cIndex] = triangle;
|
||||||
|
const aRef = refs[aIndex];
|
||||||
|
const bRef = refs[bIndex];
|
||||||
|
const cRef = refs[cIndex];
|
||||||
|
if (aRef.normalIndex === undefined || bRef.normalIndex === undefined || cRef.normalIndex === undefined) {
|
||||||
|
return triangle;
|
||||||
|
}
|
||||||
|
|
||||||
|
const a = vertices[aRef.vertexIndex];
|
||||||
|
const b = vertices[bRef.vertexIndex];
|
||||||
|
const c = vertices[cRef.vertexIndex];
|
||||||
|
const geometricNormal = new THREE.Vector3()
|
||||||
|
.subVectors(b, a)
|
||||||
|
.cross(new THREE.Vector3().subVectors(c, a));
|
||||||
|
if (geometricNormal.lengthSq() <= 1e-20) return triangle;
|
||||||
|
|
||||||
|
const objNormal = new THREE.Vector3()
|
||||||
|
.add(normals[aRef.normalIndex])
|
||||||
|
.add(normals[bRef.normalIndex])
|
||||||
|
.add(normals[cRef.normalIndex]);
|
||||||
|
if (objNormal.lengthSq() <= 1e-20) return triangle;
|
||||||
|
|
||||||
|
return geometricNormal.dot(objNormal) < 0
|
||||||
|
? [aIndex, cIndex, bIndex] as const
|
||||||
|
: triangle;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generatedFaceNormals(positions: readonly number[]) {
|
||||||
|
const normals: number[] = [];
|
||||||
|
for (let index = 0; index + 8 < positions.length; index += 9) {
|
||||||
|
const a = new THREE.Vector3(positions[index], positions[index + 1], positions[index + 2]);
|
||||||
|
const b = new THREE.Vector3(positions[index + 3], positions[index + 4], positions[index + 5]);
|
||||||
|
const c = new THREE.Vector3(positions[index + 6], positions[index + 7], positions[index + 8]);
|
||||||
|
const normal = new THREE.Vector3()
|
||||||
|
.subVectors(b, a)
|
||||||
|
.cross(new THREE.Vector3().subVectors(c, a));
|
||||||
|
if (normal.lengthSq() > 1e-20) normal.normalize();
|
||||||
|
for (let vertex = 0; vertex < 3; vertex += 1) normals.push(normal.x, normal.y, normal.z);
|
||||||
|
}
|
||||||
|
return normals;
|
||||||
|
}
|
||||||
|
|
||||||
|
function importedObjShapeFromTriangles(
|
||||||
|
fileName: string,
|
||||||
|
rawPositions: number[],
|
||||||
|
rawNormals: number[] | undefined,
|
||||||
|
): WorkplaneShape {
|
||||||
|
if (rawPositions.length < 9 || rawPositions.length % 9 !== 0) {
|
||||||
|
throw new Error("OBJ has no readable mesh geometry");
|
||||||
|
}
|
||||||
|
|
||||||
|
let minX = Number.POSITIVE_INFINITY;
|
||||||
|
let minY = Number.POSITIVE_INFINITY;
|
||||||
|
let minZ = Number.POSITIVE_INFINITY;
|
||||||
|
let maxX = Number.NEGATIVE_INFINITY;
|
||||||
|
let maxY = Number.NEGATIVE_INFINITY;
|
||||||
|
let maxZ = Number.NEGATIVE_INFINITY;
|
||||||
|
|
||||||
|
for (let index = 0; index < rawPositions.length; index += 3) {
|
||||||
|
const x = rawPositions[index];
|
||||||
|
const y = rawPositions[index + 1];
|
||||||
|
const z = rawPositions[index + 2];
|
||||||
|
minX = Math.min(minX, x);
|
||||||
|
minY = Math.min(minY, y);
|
||||||
|
minZ = Math.min(minZ, z);
|
||||||
|
maxX = Math.max(maxX, x);
|
||||||
|
maxY = Math.max(maxY, y);
|
||||||
|
maxZ = Math.max(maxZ, z);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizeX = maxX - minX;
|
||||||
|
const sizeY = maxY - minY;
|
||||||
|
const sizeZ = maxZ - minZ;
|
||||||
|
const maxDimension = Math.max(sizeX, sizeY, sizeZ);
|
||||||
|
if (!Number.isFinite(maxDimension) || maxDimension <= 0) throw new Error("OBJ geometry is empty");
|
||||||
|
|
||||||
|
const centerX = (minX + maxX) / 2;
|
||||||
|
const centerZ = (minZ + maxZ) / 2;
|
||||||
|
const positions: number[] = [];
|
||||||
|
for (let index = 0; index < rawPositions.length; index += 3) {
|
||||||
|
positions.push(
|
||||||
|
rawPositions[index] - centerX,
|
||||||
|
rawPositions[index + 1] - minY,
|
||||||
|
rawPositions[index + 2] - centerZ,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const normals = rawNormals?.length === rawPositions.length
|
||||||
|
? [...rawNormals]
|
||||||
|
: generatedFaceNormals(rawPositions);
|
||||||
|
const width = Math.max(1, sizeX);
|
||||||
|
const height = Math.max(1, sizeY);
|
||||||
|
const depth = Math.max(1, sizeZ);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: createLocalId("uploaded-mesh"),
|
||||||
|
name: fileName.replace(/\.[^.]+$/, "") || "Imported OBJ",
|
||||||
|
kind: "mesh",
|
||||||
|
color: "#0098c7",
|
||||||
|
x: 10,
|
||||||
|
z: -10,
|
||||||
|
size: Math.max(width, depth),
|
||||||
|
width,
|
||||||
|
depth,
|
||||||
|
height,
|
||||||
|
rotation: 0,
|
||||||
|
rotationX: 0,
|
||||||
|
rotationZ: 0,
|
||||||
|
importedMesh: {
|
||||||
|
positions,
|
||||||
|
normals,
|
||||||
|
baseWidth: width,
|
||||||
|
baseDepth: depth,
|
||||||
|
baseHeight: height,
|
||||||
|
triangleCount: rawPositions.length / 9,
|
||||||
|
sourceFormat: "obj",
|
||||||
|
},
|
||||||
|
locked: false,
|
||||||
|
hidden: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importedShapeFromObj(fileName: string, source: string): WorkplaneShape {
|
||||||
|
const sketchForgeZUpExport = /^# SketchForge OBJ export\b/m.test(source);
|
||||||
|
const vertices: THREE.Vector3[] = [];
|
||||||
|
const normals: THREE.Vector3[] = [];
|
||||||
|
const rawPositions: number[] = [];
|
||||||
|
const rawNormals: number[] = [];
|
||||||
|
let hasCompleteNormals = true;
|
||||||
|
let faceCount = 0;
|
||||||
|
|
||||||
|
source.split(/\r?\n/).forEach((sourceLine) => {
|
||||||
|
const line = sourceLine.split("#", 1)[0].trim();
|
||||||
|
if (!line) return;
|
||||||
|
const parts = line.split(/\s+/);
|
||||||
|
const keyword = parts[0];
|
||||||
|
|
||||||
|
if (keyword === "v") {
|
||||||
|
if (parts.length < 4) throw new Error("OBJ contains an invalid vertex");
|
||||||
|
const values = parts.slice(1, 4).map(Number);
|
||||||
|
if (values.some((value) => !Number.isFinite(value))) throw new Error("OBJ contains a non-finite vertex");
|
||||||
|
vertices.push(new THREE.Vector3(values[0], values[1], values[2]));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keyword === "vn") {
|
||||||
|
if (parts.length < 4) throw new Error("OBJ contains an invalid normal");
|
||||||
|
const values = parts.slice(1, 4).map(Number);
|
||||||
|
if (values.some((value) => !Number.isFinite(value))) throw new Error("OBJ contains a non-finite normal");
|
||||||
|
normals.push(new THREE.Vector3(values[0], values[1], values[2]).normalize());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keyword !== "f") return;
|
||||||
|
if (parts.length < 4) throw new Error("OBJ contains a face with fewer than three vertices");
|
||||||
|
|
||||||
|
const refs: ObjFaceVertex[] = parts.slice(1).map((token) => {
|
||||||
|
const fields = token.split("/");
|
||||||
|
const vertexIndex = resolveObjIndex(fields[0], vertices.length, "vertex");
|
||||||
|
const normalIndex = fields.length >= 3 && fields[2]
|
||||||
|
? resolveObjIndex(fields[2], normals.length, "normal")
|
||||||
|
: undefined;
|
||||||
|
return { vertexIndex, normalIndex };
|
||||||
|
});
|
||||||
|
if (refs.length > 3 && refs[0].vertexIndex === refs[refs.length - 1].vertexIndex) refs.pop();
|
||||||
|
if (refs.length < 3) throw new Error("OBJ contains a degenerate face");
|
||||||
|
|
||||||
|
const points = refs.map((ref) => vertices[ref.vertexIndex]);
|
||||||
|
triangulateFace(points).forEach((triangle) => {
|
||||||
|
const orientedTriangle = orientTriangleToObjNormals(triangle, refs, vertices, normals);
|
||||||
|
orientedTriangle.forEach((faceIndex) => {
|
||||||
|
const ref = refs[faceIndex];
|
||||||
|
const point = vertices[ref.vertexIndex];
|
||||||
|
const position: [number, number, number] = [point.x, point.y, point.z];
|
||||||
|
rawPositions.push(...(sketchForgeZUpExport ? zUpToSketchForge(position) : position));
|
||||||
|
if (ref.normalIndex === undefined) {
|
||||||
|
hasCompleteNormals = false;
|
||||||
|
} else {
|
||||||
|
const normal = normals[ref.normalIndex];
|
||||||
|
const sourceNormal: [number, number, number] = [normal.x, normal.y, normal.z];
|
||||||
|
rawNormals.push(...(sketchForgeZUpExport ? zUpToSketchForge(sourceNormal) : sourceNormal));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
faceCount += 1;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!vertices.length || !faceCount || !rawPositions.length) {
|
||||||
|
throw new Error("OBJ has no readable mesh geometry");
|
||||||
|
}
|
||||||
|
|
||||||
|
return importedObjShapeFromTriangles(
|
||||||
|
fileName,
|
||||||
|
rawPositions,
|
||||||
|
hasCompleteNormals && rawNormals.length === rawPositions.length ? rawNormals : undefined,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { strFromU8, strToU8, unzip, zip, type AsyncZippable } from "fflate";
|
import { strFromU8, strToU8, unzip, zip, type AsyncZippable } from "fflate";
|
||||||
import { editorHistoryEntry, hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
|
import { editorHistoryEntry, hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
|
||||||
import { normalizePlacementWorkplane, placementWorkplaneIsBase, type PlacementWorkplane } from "@/lib/placementWorkplane";
|
import { normalizePlacementWorkplane, placementWorkplaneIsBase, type PlacementWorkplane } from "@/lib/placementWorkplane";
|
||||||
|
import { importedShapeFromObj } from "@/lib/objImport";
|
||||||
import { normalizeProjectAsset, sha256Hex } from "@/lib/projectAssets";
|
import { normalizeProjectAsset, sha256Hex } from "@/lib/projectAssets";
|
||||||
import { canonicalizeShape } from "@/lib/workplaneShapes";
|
import { canonicalizeShape } from "@/lib/workplaneShapes";
|
||||||
import { importedShapeFromStl } from "@/lib/stlImport";
|
import { importedShapeFromStl } from "@/lib/stlImport";
|
||||||
@@ -11,7 +12,7 @@ import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation,
|
|||||||
export const SKF_SCHEMA_ID = "com.sketchforge.project";
|
export const SKF_SCHEMA_ID = "com.sketchforge.project";
|
||||||
export const SKF_FORMAT_VERSION = 1;
|
export const SKF_FORMAT_VERSION = 1;
|
||||||
export const SKF_MINIMUM_READER_VERSION = 1;
|
export const SKF_MINIMUM_READER_VERSION = 1;
|
||||||
export const SKF_CREATED_WITH_VERSION = "1.0.0";
|
export const SKF_CREATED_WITH_VERSION = "1.0.2";
|
||||||
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
|
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
|
||||||
|
|
||||||
export const SKF_LIMITS = {
|
export const SKF_LIMITS = {
|
||||||
@@ -1047,12 +1048,13 @@ async function validateDocumentAndAssets(raw: unknown, files: ArchiveFiles) {
|
|||||||
|
|
||||||
async function defaultSourceImporter(asset: ProjectAsset) {
|
async function defaultSourceImporter(asset: ProjectAsset) {
|
||||||
if (asset.sourceFormat === "stl") return importedShapeFromStl(asset.name, exactArrayBuffer(asset.bytes)).importedMesh as NonNullable<WorkplaneShape["importedMesh"]>;
|
if (asset.sourceFormat === "stl") return importedShapeFromStl(asset.name, exactArrayBuffer(asset.bytes)).importedMesh as NonNullable<WorkplaneShape["importedMesh"]>;
|
||||||
|
if (asset.sourceFormat === "obj") return importedShapeFromObj(asset.name, strFromU8(asset.bytes)).importedMesh as NonNullable<WorkplaneShape["importedMesh"]>;
|
||||||
if (asset.sourceFormat === "svg") return importedShapeFromSvg(asset.name, strFromU8(asset.bytes)).importedMesh as NonNullable<WorkplaneShape["importedMesh"]>;
|
if (asset.sourceFormat === "svg") return importedShapeFromSvg(asset.name, strFromU8(asset.bytes)).importedMesh as NonNullable<WorkplaneShape["importedMesh"]>;
|
||||||
if (asset.sourceFormat === "step") {
|
if (asset.sourceFormat === "step") {
|
||||||
const { importedShapeFromStep } = await import("@/lib/stepImport");
|
const { importedShapeFromStep } = await import("@/lib/stepImport");
|
||||||
return (await importedShapeFromStep(asset.name, exactArrayBuffer(asset.bytes))).importedMesh as NonNullable<WorkplaneShape["importedMesh"]>;
|
return (await importedShapeFromStep(asset.name, exactArrayBuffer(asset.bytes))).importedMesh as NonNullable<WorkplaneShape["importedMesh"]>;
|
||||||
}
|
}
|
||||||
throw new Error(`SketchForge cannot reconstruct ${asset.sourceFormat.toUpperCase()} source assets yet`);
|
throw new Error("SketchForge cannot reconstruct this source asset format");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function restoreShapeFromNode(
|
async function restoreShapeFromNode(
|
||||||
|
|||||||
Vendored
+20
@@ -0,0 +1,20 @@
|
|||||||
|
export {};
|
||||||
|
|
||||||
|
type SketchForgeDesktopUpdateResult = {
|
||||||
|
currentVersion: string;
|
||||||
|
latestVersion: string | null;
|
||||||
|
updateAvailable: boolean;
|
||||||
|
downloaded: boolean;
|
||||||
|
checkedAt: string;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
sketchforgeDesktop?: {
|
||||||
|
getVersion: () => Promise<string>;
|
||||||
|
checkForUpdates: () => Promise<SketchForgeDesktopUpdateResult>;
|
||||||
|
installUpdate: () => Promise<SketchForgeDesktopUpdateResult>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+3528
-2
File diff suppressed because it is too large
Load Diff
+61
-1
@@ -1 +1,61 @@
|
|||||||
{ "name": "sketchforge", "version": "1.0.3", "private": true, "license": "AGPL-3.0-only", "scripts": { "copy:occt": "node scripts/copy-occt-wasm.mjs", "predev": "npm run copy:occt", "dev": "next dev apps/web", "prebuild": "npm run copy:occt", "build": "next build apps/web", "export": "set STATIC_EXPORT=true&& next build apps/web && node scripts/verify-static-worker-assets.mjs", "verify:static-worker-assets": "node scripts/verify-static-worker-assets.mjs", "start": "next start apps/web", "typecheck": "tsc -p apps/web/tsconfig.json --noEmit", "test": "vitest run --config tests/vitest.config.ts", "test:watch": "vitest --config tests/vitest.config.ts", "test:e2e": "vitest run --config tests/vitest.e2e.config.ts", "perf": "vitest run --config tests/vitest.perf.config.ts --reporter verbose", "ci": "npm run typecheck && npm run test", "docker:build": "docker build -f deploy/docker/Dockerfile -t sketchforge:local .", "docker:run": "docker run --rm -p 3000:3000 -e SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects -v sketchforge-shared-projects:/data/projects sketchforge:local", "docker:up": "docker compose -f deploy/docker/compose.yaml up --build -d", "docker:down": "docker compose -f deploy/docker/compose.yaml down", "mcp:sketchforge": "node scripts/sketchforge-mcp-server.mjs" }, "dependencies": { "@tailwindcss/postcss": "^4.1.8", "@types/three": "^0.184.1", "brepjs": "^18.118.0", "clsx": "^2.1.1", "fflate": "^0.8.2", "lucide-react": "^0.511.0", "manifold-3d": "^3.5.0", "next": "^15.3.2", "occt-wasm": "^3.6.1", "react": "^19.1.0", "react-colorful": "^5.8.0", "react-dom": "^19.1.0", "tailwind-merge": "^3.3.0", "tailwindcss": "^4.1.8", "three": "^0.184.0", "three-bvh-csg": "^0.0.18", "three-mesh-bvh": "^0.9.13" }, "devDependencies": { "@types/node": "^22.15.18", "@types/react": "^19.1.4", "@types/react-dom": "^19.1.5", "typescript": "^5.8.3", "vitest": "^4.1.8" } }
|
{
|
||||||
|
"name": "sketchforge",
|
||||||
|
"version": "1.0.3",
|
||||||
|
"private": true,
|
||||||
|
"main": "apps/desktop/main.cjs",
|
||||||
|
"license": "AGPL-3.0-only",
|
||||||
|
"scripts": {
|
||||||
|
"copy:occt": "node scripts/copy-occt-wasm.mjs",
|
||||||
|
"predev": "npm run copy:occt",
|
||||||
|
"dev": "next dev apps/web",
|
||||||
|
"prebuild": "npm run copy:occt",
|
||||||
|
"build": "next build apps/web",
|
||||||
|
"export": "set STATIC_EXPORT=true&& next build apps/web && node scripts/verify-static-worker-assets.mjs",
|
||||||
|
"verify:static-worker-assets": "node scripts/verify-static-worker-assets.mjs",
|
||||||
|
"start": "next start apps/web",
|
||||||
|
"typecheck": "tsc -p apps/web/tsconfig.json --noEmit",
|
||||||
|
"test": "vitest run --config tests/vitest.config.ts",
|
||||||
|
"test:watch": "vitest --config tests/vitest.config.ts",
|
||||||
|
"test:e2e": "vitest run --config tests/vitest.e2e.config.ts",
|
||||||
|
"perf": "vitest run --config tests/vitest.perf.config.ts --reporter verbose",
|
||||||
|
"ci": "npm run typecheck && npm run test",
|
||||||
|
"docker:build": "docker build -f deploy/docker/Dockerfile -t sketchforge:local .",
|
||||||
|
"docker:run": "docker run --rm -p 3000:3000 -e SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects -v sketchforge-shared-projects:/data/projects sketchforge:local",
|
||||||
|
"docker:up": "docker compose -f deploy/docker/compose.yaml up --build -d",
|
||||||
|
"docker:down": "docker compose -f deploy/docker/compose.yaml down",
|
||||||
|
"desktop:dev": "node apps/desktop/dev.mjs",
|
||||||
|
"desktop:web:build": "node apps/desktop/build-web.mjs",
|
||||||
|
"desktop:pack": "npm run desktop:web:build && electron-builder --dir --config apps/desktop/electron-builder.yml",
|
||||||
|
"desktop:dist": "npm run desktop:web:build && electron-builder --config apps/desktop/electron-builder.yml",
|
||||||
|
"mcp:sketchforge": "node scripts/sketchforge-mcp-server.mjs"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tailwindcss/postcss": "^4.1.8",
|
||||||
|
"@types/three": "^0.184.1",
|
||||||
|
"brepjs": "^18.118.0",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"electron-updater": "^6.8.9",
|
||||||
|
"fflate": "^0.8.2",
|
||||||
|
"lucide-react": "^0.511.0",
|
||||||
|
"manifold-3d": "^3.5.0",
|
||||||
|
"next": "^15.3.2",
|
||||||
|
"occt-wasm": "^3.6.1",
|
||||||
|
"react": "^19.1.0",
|
||||||
|
"react-colorful": "^5.8.0",
|
||||||
|
"react-dom": "^19.1.0",
|
||||||
|
"tailwind-merge": "^3.3.0",
|
||||||
|
"tailwindcss": "^4.1.8",
|
||||||
|
"three": "^0.184.0",
|
||||||
|
"three-bvh-csg": "^0.0.18",
|
||||||
|
"three-mesh-bvh": "^0.9.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.15.18",
|
||||||
|
"@types/react": "^19.1.4",
|
||||||
|
"@types/react-dom": "^19.1.5",
|
||||||
|
"electron": "^43.4.0",
|
||||||
|
"electron-builder": "^26.15.3",
|
||||||
|
"typescript": "^5.8.3",
|
||||||
|
"vitest": "^4.1.8"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { importExtensionSupported } from "@/lib/stlImport";
|
import { importExtensionSupported } from "@/lib/importExtensions";
|
||||||
|
|
||||||
describe("importExtensionSupported", () => {
|
describe("importExtensionSupported", () => {
|
||||||
it("accepts STL and SVG imports", () => {
|
it("accepts STL, OBJ, and SVG imports", () => {
|
||||||
expect(importExtensionSupported("part.stl")).toBe(true);
|
expect(importExtensionSupported("part.stl")).toBe(true);
|
||||||
|
expect(importExtensionSupported("assembly.obj")).toBe(true);
|
||||||
|
expect(importExtensionSupported("MODEL.OBJ")).toBe(true);
|
||||||
expect(importExtensionSupported("logo.svg")).toBe(true);
|
expect(importExtensionSupported("logo.svg")).toBe(true);
|
||||||
expect(importExtensionSupported("profile.SVG")).toBe(true);
|
expect(importExtensionSupported("profile.SVG")).toBe(true);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { importedShapeFromObj } from "@/lib/objImport";
|
||||||
|
|
||||||
|
describe("importedShapeFromObj", () => {
|
||||||
|
it("imports triangulated OBJ geometry as a SketchForge mesh", () => {
|
||||||
|
const shape = importedShapeFromObj("panel.obj", [
|
||||||
|
"v 0 0 0",
|
||||||
|
"v 2 0 0",
|
||||||
|
"v 2 3 0",
|
||||||
|
"v 0 3 0",
|
||||||
|
"f 1 2 3 4",
|
||||||
|
].join("\n"));
|
||||||
|
|
||||||
|
expect(shape.name).toBe("panel");
|
||||||
|
expect(shape.kind).toBe("mesh");
|
||||||
|
expect(shape.width).toBe(2);
|
||||||
|
expect(shape.height).toBe(3);
|
||||||
|
expect(shape.depth).toBe(1);
|
||||||
|
expect(shape.importedMesh?.sourceFormat).toBe("obj");
|
||||||
|
expect(shape.importedMesh?.triangleCount).toBe(2);
|
||||||
|
expect(shape.importedMesh?.positions).toHaveLength(18);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("triangulates concave OBJ polygons without filling their cutout", () => {
|
||||||
|
const shape = importedShapeFromObj("concave.obj", [
|
||||||
|
"v 0 0 0",
|
||||||
|
"v 3 0 0",
|
||||||
|
"v 3 3 0",
|
||||||
|
"v 2 3 0",
|
||||||
|
"v 2 1 0",
|
||||||
|
"v 1 1 0",
|
||||||
|
"v 1 3 0",
|
||||||
|
"v 0 3 0",
|
||||||
|
"f 1 2 3 4 5 6 7 8",
|
||||||
|
].join("\n"));
|
||||||
|
|
||||||
|
const positions = shape.importedMesh?.positions ?? [];
|
||||||
|
let triangleArea = 0;
|
||||||
|
for (let index = 0; index < positions.length; index += 9) {
|
||||||
|
const ax = positions[index];
|
||||||
|
const ay = positions[index + 1];
|
||||||
|
const bx = positions[index + 3];
|
||||||
|
const by = positions[index + 4];
|
||||||
|
const cx = positions[index + 6];
|
||||||
|
const cy = positions[index + 7];
|
||||||
|
triangleArea += Math.abs((bx - ax) * (cy - ay) - (by - ay) * (cx - ax)) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(shape.importedMesh?.triangleCount).toBe(6);
|
||||||
|
expect(triangleArea).toBeCloseTo(7, 6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("re-imports SketchForge Z-up OBJ exports into the editor's Y-up coordinates", () => {
|
||||||
|
const shape = importedShapeFromObj("roundtrip.obj", [
|
||||||
|
"# SketchForge OBJ export",
|
||||||
|
"# Z-up triangle soup, matching SketchForge STL export",
|
||||||
|
"v 0 0 0",
|
||||||
|
"v 2 0 0",
|
||||||
|
"v 0 0 3",
|
||||||
|
"vn 0 1 0",
|
||||||
|
"f 1//1 2//1 3//1",
|
||||||
|
].join("\n"));
|
||||||
|
|
||||||
|
expect(shape.width).toBe(2);
|
||||||
|
expect(shape.height).toBe(3);
|
||||||
|
expect(shape.depth).toBe(1);
|
||||||
|
expect(shape.importedMesh?.positions).toEqual([
|
||||||
|
-1, 0, 0,
|
||||||
|
-1, 3, 0,
|
||||||
|
1, 0, 0,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
it("uses OBJ normals to correct reversed triangle winding", () => {
|
||||||
|
const shape = importedShapeFromObj("reversed.obj", [
|
||||||
|
"v 0 0 0",
|
||||||
|
"v 2 0 0",
|
||||||
|
"v 0 2 0",
|
||||||
|
"vt 0 0",
|
||||||
|
"vt 1 0",
|
||||||
|
"vt 0 1",
|
||||||
|
"vn 0 0 -1",
|
||||||
|
"f 1/1/1 2/2/1 3/3/1",
|
||||||
|
].join("\n"));
|
||||||
|
|
||||||
|
const positions = shape.importedMesh?.positions ?? [];
|
||||||
|
const normals = shape.importedMesh?.normals ?? [];
|
||||||
|
const ab = [
|
||||||
|
positions[3] - positions[0],
|
||||||
|
positions[4] - positions[1],
|
||||||
|
positions[5] - positions[2],
|
||||||
|
];
|
||||||
|
const ac = [
|
||||||
|
positions[6] - positions[0],
|
||||||
|
positions[7] - positions[1],
|
||||||
|
positions[8] - positions[2],
|
||||||
|
];
|
||||||
|
const geometricNormal = [
|
||||||
|
ab[1] * ac[2] - ab[2] * ac[1],
|
||||||
|
ab[2] * ac[0] - ab[0] * ac[2],
|
||||||
|
ab[0] * ac[1] - ab[1] * ac[0],
|
||||||
|
];
|
||||||
|
const dot = geometricNormal[0] * normals[0] + geometricNormal[1] * normals[1] + geometricNormal[2] * normals[2];
|
||||||
|
|
||||||
|
expect(dot).toBeGreaterThan(0);
|
||||||
|
expect(shape.importedMesh?.triangleCount).toBe(1);
|
||||||
|
});
|
||||||
|
it("rejects OBJ files without mesh faces", () => {
|
||||||
|
expect(() => importedShapeFromObj("points.obj", "v 0 0 0\nv 1 1 1")).toThrow("OBJ has no readable mesh geometry");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { DELETE, GET } from "@/app/api/shared-projects/route";
|
||||||
|
|
||||||
|
const SHARED_PROJECTS_ENV = "SKETCHFORGE_SHARED_PROJECTS_DIR";
|
||||||
|
|
||||||
|
let sharedProjectsRoot = "";
|
||||||
|
let previousSharedProjectsRoot: string | undefined;
|
||||||
|
|
||||||
|
async function createSharedProject(fileName: string, content = "shared project") {
|
||||||
|
await fs.writeFile(path.join(sharedProjectsRoot, fileName), content);
|
||||||
|
const response = await GET(new Request("http://localhost/api/shared-projects"));
|
||||||
|
const payload = await response.json() as { projects: Array<{ fileName: string; revision: string }> };
|
||||||
|
const project = payload.projects.find((candidate) => candidate.fileName === fileName);
|
||||||
|
if (!project) throw new Error(`Could not find ${fileName} in shared project listing`);
|
||||||
|
return project;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteRequest(fileName: string, revision?: string, origin = "http://localhost") {
|
||||||
|
const headers = new Headers({ Origin: origin });
|
||||||
|
if (revision) headers.set("If-Match", `"${revision}"`);
|
||||||
|
return new Request(`http://localhost/api/shared-projects?fileName=${encodeURIComponent(fileName)}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("shared project deletion", () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
previousSharedProjectsRoot = process.env[SHARED_PROJECTS_ENV];
|
||||||
|
sharedProjectsRoot = await fs.mkdtemp(path.join(os.tmpdir(), "sketchforge-shared-delete-"));
|
||||||
|
process.env[SHARED_PROJECTS_ENV] = sharedProjectsRoot;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
if (previousSharedProjectsRoot === undefined) delete process.env[SHARED_PROJECTS_ENV];
|
||||||
|
else process.env[SHARED_PROJECTS_ENV] = previousSharedProjectsRoot;
|
||||||
|
await fs.rm(sharedProjectsRoot, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("deletes a shared project when the listed revision still matches", async () => {
|
||||||
|
const project = await createSharedProject("Delete me.skf");
|
||||||
|
|
||||||
|
const response = await DELETE(deleteRequest(project.fileName, project.revision));
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
await expect(fs.access(path.join(sharedProjectsRoot, project.fileName))).rejects.toThrow();
|
||||||
|
expect(await response.json()).toEqual({ deleted: true, fileName: project.fileName });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses to delete from a stale dashboard revision", async () => {
|
||||||
|
const project = await createSharedProject("Changed model.skf");
|
||||||
|
|
||||||
|
const response = await DELETE(deleteRequest(project.fileName, "stale-revision"));
|
||||||
|
|
||||||
|
expect(response.status).toBe(409);
|
||||||
|
await expect(fs.access(path.join(sharedProjectsRoot, project.fileName))).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires a revision precondition before deleting", async () => {
|
||||||
|
const project = await createSharedProject("Needs revision.skf");
|
||||||
|
|
||||||
|
const response = await DELETE(deleteRequest(project.fileName));
|
||||||
|
|
||||||
|
expect(response.status).toBe(428);
|
||||||
|
await expect(fs.access(path.join(sharedProjectsRoot, project.fileName))).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects cross-origin delete requests", async () => {
|
||||||
|
const project = await createSharedProject("Protected model.skf");
|
||||||
|
|
||||||
|
const response = await DELETE(deleteRequest(project.fileName, project.revision, "https://example.invalid"));
|
||||||
|
|
||||||
|
expect(response.status).toBe(403);
|
||||||
|
await expect(fs.access(path.join(sharedProjectsRoot, project.fileName))).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user