"use strict";
const $ = (id) => document.getElementById(id);
const state = {
layers: [], // see addLayerFromUpload
selectedLayerId: null,
panelWidthIn: 36,
panelHeightIn: 48,
intent: "cutouts",
composedToken: null,
composedPaths: null,
composedRawPaths: null,
composedW: 0,
composedH: 0,
composedInPerPx: null,
};
let nextLayerId = 1;
function newLayerId() { return `l${nextLayerId++}`; }
const els = {
dropzone: $("dropzone"),
fileInput: $("imageFile"),
layerList: $("layerList"),
layerEditor: $("layerEditor"),
editorName: $("editorName"),
modeSeg: $("modeSeg"),
thresholdRow: $("thresholdRow"),
threshold: $("threshold"),
thresholdOut: $("thresholdOut"),
blurRow: $("blurRow"),
blur: $("blur"),
blurOut: $("blurOut"),
invert: $("invert"),
layerWidthIn: $("layerWidthIn"),
layerXIn: $("layerXIn"),
layerYIn: $("layerYIn"),
layerCutSize: $("layerCutSize"),
panelWidthIn: $("panelWidthIn"),
panelHeightIn: $("panelHeightIn"),
intentSeg: $("intentSeg"),
kerfIn: $("kerfIn"),
minFeatureIn: $("minFeatureIn"),
maxGapIn: $("maxGapIn"),
warnings: $("warnings"),
steelMode: $("steelMode"),
showWarnings: $("showWarnings"),
measureBtn: $("measureBtn"),
measureSvg: $("measureSvg"),
measureLabel: $("measureLabel"),
cropOpenBtn: $("cropOpenBtn"),
cropResetBtn: $("cropResetBtn"),
cropModal: $("cropModal"),
cropArea: $("cropArea"),
cropImage: $("cropImage"),
cropRect: $("cropRect"),
cropDim: $("cropDim"),
cropApplyBtn: $("cropApplyBtn"),
cropCancelBtn: $("cropCancelBtn"),
cropClearBtn: $("cropClearBtn"),
genPrompt: $("genPrompt"),
genPlasmaStyle: $("genPlasmaStyle"),
genBtn: $("genBtn"),
composeBtn: $("composeBtn"),
exportSvgBtn: $("exportSvgBtn"),
exportDxfBtn: $("exportDxfBtn"),
status: $("status"),
stage: $("stage"),
stageInner: $("stageInner"),
layerPreviewWrap: $("layerPreviewWrap"),
traceSvg: $("traceSvg"),
warningOverlay: $("warningOverlay"),
dimsLabel: $("dimsLabel"),
};
// --- Status helper ---
function setStatus(msg, isError = false) {
els.status.textContent = msg || "";
els.status.classList.toggle("error", !!isError);
}
// --- Layer management ---
function selectedLayer() {
return state.layers.find((l) => l.id === state.selectedLayerId) || null;
}
async function addLayerFromGenerated(data, prompt) {
// The /generate endpoint already cached the image server-side and returned
// an image_token. Build a layer entry that mirrors what addLayerFromUpload
// produces, using the returned source_data_url so the crop modal works.
const defaultPolarity = "subtract";
const layer = {
id: newLayerId(),
name: data.name || (prompt.slice(0, 40)),
imageToken: data.image_token,
sourceUrl: data.source_data_url, // data URL of the full source PNG
originalWidth: data.width,
originalHeight: data.height,
sourceWidth: data.width,
sourceHeight: data.height,
thumbnail: data.thumbnail,
maskMode: "subject", // Plasma-friendly silhouettes work great with rembg
maskParams: { threshold: 128, blur: 0, invert: false, alpha_cutoff: 50, crop: null },
polarity: defaultPolarity,
maskPng: null,
visible: true,
xIn: state.panelWidthIn / 2 + state.layers.length * 2,
yIn: state.panelHeightIn / 2 + state.layers.length * 2,
// a panel drawing is the whole panel, not a motif dropped on one
widthIn: data.is_line_art
? state.panelWidthIn * 0.96
: Math.min(state.panelWidthIn, state.panelHeightIn) * 0.55,
aspect: data.width / Math.max(data.height, 1),
};
state.layers.push(layer);
state.selectedLayerId = layer.id;
await refreshLayerMask(layer);
renderLayerList();
renderEditor();
renderStageLayers();
els.composeBtn.disabled = false;
}
async function runGenerate() {
const prompt = els.genPrompt.value.trim();
if (!prompt) return;
const box = els.genBtn.closest(".generate-box");
box.classList.add("busy");
setStatus(`Generating "${prompt}"…`);
try {
const res = await fetch("/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
prompt,
plasma_style: els.genPlasmaStyle.checked,
size: "1K",
}),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
setStatus(err.error || `Generate failed (${res.status})`, true);
return;
}
const data = await res.json();
await addLayerFromGenerated(data, prompt);
setStatus(`Added "${data.name}" — extracting subject…`);
els.genPrompt.value = "";
} catch (err) {
setStatus(err.message || String(err), true);
} finally {
box.classList.remove("busy");
}
}
async function addLayerFromUpload(file) {
setStatus(`Uploading ${file.name}…`);
const fd = new FormData();
fd.append("image", file);
let res;
try {
res = await fetch("/upload", { method: "POST", body: fd });
} catch (err) {
setStatus(`Upload failed: ${err.message}`, true);
return;
}
if (!res.ok) {
setStatus(`Upload failed (${res.status})`, true);
return;
}
const data = await res.json();
const isFirst = state.layers.length === 0;
const sourceUrl = URL.createObjectURL(file);
const defaultPolarity = "subtract";
const layer = {
id: newLayerId(),
name: file.name.replace(/\.[^.]+$/, ""),
imageToken: data.image_token,
sourceUrl,
originalWidth: data.width,
originalHeight: data.height,
sourceWidth: data.width,
sourceHeight: data.height,
thumbnail: data.thumbnail,
// keep the bytes: a server restart drops the in-memory image cache and the
// layer has to be able to put itself back
sourceFile: file,
// Line art (an existing black-and-white drawing) must NOT go through rembg:
// it is a photo segmentation net and it smears fine linework into blobs.
// Threshold it instead, and invert, so the drawn black stays steel and the
// white around it is what gets cut.
maskMode: data.is_line_art ? "auto" : "subject",
maskParams: { threshold: 128, blur: 0, invert: !!data.is_line_art,
alpha_cutoff: 50, crop: null },
polarity: defaultPolarity,
maskPng: null,
visible: true,
xIn: state.panelWidthIn / 2 + state.layers.length * 2,
yIn: state.panelHeightIn / 2 + state.layers.length * 2,
widthIn: Math.min(state.panelWidthIn, state.panelHeightIn) * 0.55,
aspect: data.width / Math.max(data.height, 1),
};
state.layers.push(layer);
state.selectedLayerId = layer.id;
setStatus(data.is_line_art
? `Added ${layer.name}. Detected line art: using Auto Threshold + Invert (rembg would smear it).`
: `Added ${layer.name}. Computing mask…`);
await refreshLayerMask(layer);
renderLayerList();
renderEditor();
renderStageLayers();
els.composeBtn.disabled = false;
if (isFirst) {
setStatus(`Ready. Click "Compose & trace" to preview cuts.`);
}
}
// The image cache lives in memory, so a restart (or the HF Space waking from
// sleep) invalidates every token at once. Put the layer back from the bytes we
// still hold instead of showing "unknown image_token" and stopping.
async function reuploadLayer(layer) {
let blob = layer.sourceFile || null;
if (!blob && layer.sourceDataUrl) {
try { blob = await (await fetch(layer.sourceDataUrl)).blob(); } catch (e) { blob = null; }
}
if (!blob && layer.sourceUrl) {
try { blob = await (await fetch(layer.sourceUrl)).blob(); } catch (e) { blob = null; }
}
if (!blob) return false;
const fd = new FormData();
fd.append("image", blob, (layer.name || "layer") + ".png");
try {
const r = await fetch("/upload", { method: "POST", body: fd });
if (!r.ok) return false;
const d = await r.json();
layer.imageToken = d.image_token;
return true;
} catch (e) { return false; }
}
async function refreshLayerMask(layer, _retried) {
try {
const res = await fetch("/layer/preview", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
image_token: layer.imageToken,
mask_mode: layer.maskMode,
mask_params: layer.maskParams,
}),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
const stale = /unknown image_token|expired/i.test(err.error || "");
if (stale && !_retried) {
setStatus("Server restarted; re-sending the image…");
if (await reuploadLayer(layer)) return refreshLayerMask(layer, true);
setStatus("Server restarted and the image is gone. Please re-add the layer.", true);
return;
}
setStatus(`Mask failed: ${err.error || res.status}`, true);
return;
}
const data = await res.json();
layer.maskPng = data.mask_png;
layer.subjectBbox = data.subject_bbox || null;
updateLayerMaskImage(layer);
if (state.selectedLayerId === layer.id) updateCutSizeReadout(layer);
} catch (err) {
setStatus(`Mask failed: ${err.message}`, true);
}
}
function computeSubjectCutSize(layer) {
if (!layer || !layer.subjectBbox) return null;
const sw = layer.sourceWidth;
const sh = layer.sourceHeight;
const { x0, y0, x1, y1 } = layer.subjectBbox;
const layerWidthIn = layer.widthIn;
const layerHeightIn = layer.widthIn / layer.aspect;
const cutWidthIn = (x1 - x0 + 1) / sw * layerWidthIn;
const cutHeightIn = (y1 - y0 + 1) / sh * layerHeightIn;
return {
cutWidthIn,
cutHeightIn,
layerWidthIn,
layerHeightIn,
fillPct: ((x1 - x0 + 1) * (y1 - y0 + 1)) / (sw * sh) * 100,
};
}
function updateCutSizeReadout(layer) {
if (!els.layerCutSize) return;
const s = computeSubjectCutSize(layer);
if (!s) {
els.layerCutSize.innerHTML = "";
return;
}
const placeholder = `${s.layerWidthIn.toFixed(2)} × ${s.layerHeightIn.toFixed(2)}″`;
const actual = `${s.cutWidthIn.toFixed(2)} × ${s.cutHeightIn.toFixed(2)}″`;
els.layerCutSize.innerHTML =
`Placeholder rect: ${placeholder} · Actual cut: ${actual}`;
}
function deleteLayer(id) {
state.layers = state.layers.filter((l) => l.id !== id);
if (state.selectedLayerId === id) {
state.selectedLayerId = state.layers[0]?.id ?? null;
}
if (state.layers.length === 0) {
els.composeBtn.disabled = true;
state.composedRawPaths = null;
state.composedToken = null;
els.exportSvgBtn.disabled = true;
els.exportDxfBtn.disabled = true;
renderTracePaths([]);
renderWarnings({ warnings: [] });
setOverlay(null);
}
renderLayerList();
renderEditor();
renderStageLayers();
}
function toggleLayerVisible(id) {
const layer = state.layers.find((l) => l.id === id);
if (!layer) return;
layer.visible = !layer.visible;
renderLayerList();
renderStageLayers();
}
function selectLayer(id) {
state.selectedLayerId = id;
renderLayerList();
renderEditor();
updateLayerSelection();
}
// --- Rendering: layer list ---
function renderLayerList() {
els.layerList.innerHTML = "";
state.layers.forEach((layer) => {
const row = document.createElement("div");
row.className = "layer-row";
if (layer.id === state.selectedLayerId) row.classList.add("selected");
if (!layer.visible) row.classList.add("hidden-layer");
row.innerHTML = `
${escapeHtml(layer.name)}
`;
row.addEventListener("click", (e) => {
const btn = e.target.closest("button");
if (btn) {
e.stopPropagation();
if (btn.dataset.act === "visible") toggleLayerVisible(layer.id);
if (btn.dataset.act === "delete") deleteLayer(layer.id);
return;
}
selectLayer(layer.id);
});
els.layerList.appendChild(row);
});
}
// --- Rendering: editor for the selected layer ---
function renderEditor() {
const layer = selectedLayer();
if (!layer) {
els.layerEditor.classList.add("hidden");
return;
}
els.layerEditor.classList.remove("hidden");
els.editorName.textContent = layer.name;
// Mode segmented control
els.modeSeg.querySelectorAll(".seg-btn").forEach((b) => {
b.classList.toggle("active", b.dataset.mode === layer.maskMode);
});
document.getElementById("polaritySeg").querySelectorAll(".seg-btn").forEach((b) => {
b.classList.toggle("active", b.dataset.polarity === (layer.polarity || "subtract"));
});
syncMaskRowsVisibility(layer);
els.threshold.value = layer.maskParams.threshold;
els.thresholdOut.textContent = layer.maskParams.threshold;
els.blur.value = layer.maskParams.blur;
els.blurOut.textContent = layer.maskParams.blur;
els.invert.checked = !!layer.maskParams.invert;
els.layerWidthIn.value = layer.widthIn.toFixed(2);
els.layerXIn.value = layer.xIn.toFixed(2);
els.layerYIn.value = layer.yIn.toFixed(2);
updateCutSizeReadout(layer);
els.cropResetBtn.disabled = !layer.maskParams.crop;
}
function syncMaskRowsVisibility(layer) {
const subject = layer.maskMode === "subject";
const auto = layer.maskMode === "auto";
els.thresholdRow.style.display = subject || auto ? "none" : "";
els.blurRow.style.display = subject ? "none" : "";
}
// --- Rendering: stage / canvas with layered previews ---
function fitStageInner() {
// Size the stage inner to match the panel aspect ratio, fit within stage box.
const box = els.stage.getBoundingClientRect();
const padding = 24;
const availW = Math.max(box.width - padding, 100);
const availH = Math.max(box.height - padding, 100);
const aspect = state.panelWidthIn / state.panelHeightIn;
let w, h;
if (availW / availH > aspect) {
h = availH; w = h * aspect;
} else {
w = availW; h = w / aspect;
}
els.stageInner.style.width = `${w}px`;
els.stageInner.style.height = `${h}px`;
return { w, h };
}
function applyLayerTransform(node, layer, pxPerInX, pxPerInY) {
const wPx = layer.widthIn * pxPerInX;
const hPx = (layer.widthIn / layer.aspect) * pxPerInY;
node.style.width = `${wPx}px`;
node.style.height = `${hPx}px`;
node.style.left = `${layer.xIn * pxPerInX - wPx / 2}px`;
node.style.top = `${layer.yIn * pxPerInY - hPx / 2}px`;
}
function renderStageLayers() {
// Full rebuild — call only when the layer set or visibility changes.
// For position/scale updates during drag or input edits, use
// updateLayerTransforms() which leaves DOM nodes intact (otherwise we
// destroy the node we're dragging and the pointer capture dies with it).
const { w: stageW, h: stageH } = fitStageInner();
const pxPerInX = stageW / state.panelWidthIn;
const pxPerInY = stageH / state.panelHeightIn;
els.layerPreviewWrap.innerHTML = "";
els.stage.classList.toggle("has-layers", state.layers.length > 0);
state.layers.forEach((layer) => {
if (!layer.visible) return;
const wrap = document.createElement("div");
wrap.className = "layer-preview";
if (layer.id === state.selectedLayerId) wrap.classList.add("selected");
wrap.classList.add(layer.polarity === "add" ? "polarity-add" : "polarity-subtract");
wrap.dataset.layerId = layer.id;
applyLayerTransform(wrap, layer, pxPerInX, pxPerInY);
if (layer.maskPng) {
const img = document.createElement("img");
img.src = layer.maskPng;
wrap.appendChild(img);
}
const handle = document.createElement("div");
handle.className = "handle";
handle.dataset.role = "resize";
wrap.appendChild(handle);
wrap.addEventListener("pointerdown", onLayerPointerDown);
els.layerPreviewWrap.appendChild(wrap);
});
}
function updateLayerTransforms() {
// Light update: reposition/resize existing nodes without rebuilding the DOM.
const { w: stageW, h: stageH } = fitStageInner();
const pxPerInX = stageW / state.panelWidthIn;
const pxPerInY = stageH / state.panelHeightIn;
els.layerPreviewWrap.querySelectorAll(".layer-preview").forEach((node) => {
const layer = state.layers.find((l) => l.id === node.dataset.layerId);
if (layer) applyLayerTransform(node, layer, pxPerInX, pxPerInY);
});
}
function updateLayerSelection() {
els.layerPreviewWrap.querySelectorAll(".layer-preview").forEach((node) => {
node.classList.toggle("selected", node.dataset.layerId === state.selectedLayerId);
});
}
function updateLayerMaskImage(layer) {
const node = els.layerPreviewWrap.querySelector(
`.layer-preview[data-layer-id="${layer.id}"]`
);
if (!node) return;
let img = node.querySelector("img");
if (!layer.maskPng) {
if (img) img.remove();
return;
}
if (!img) {
img = document.createElement("img");
node.insertBefore(img, node.firstChild);
}
img.src = layer.maskPng;
}
let dragCtx = null;
function onLayerPointerDown(e) {
const node = e.currentTarget;
const layerId = node.dataset.layerId;
selectLayer(layerId);
const role = e.target.dataset?.role === "resize" ? "resize" : "move";
const box = els.stageInner.getBoundingClientRect();
const stageW = box.width;
const stageH = box.height;
const layer = selectedLayer();
dragCtx = {
role, layerId,
startX: e.clientX, startY: e.clientY,
startLayerX: layer.xIn, startLayerY: layer.yIn,
startWidthIn: layer.widthIn,
pxPerInX: stageW / state.panelWidthIn,
pxPerInY: stageH / state.panelHeightIn,
};
node.setPointerCapture(e.pointerId);
node.classList.add("dragging");
node.addEventListener("pointermove", onLayerPointerMove);
node.addEventListener("pointerup", onLayerPointerUp, { once: true });
node.addEventListener("pointercancel", onLayerPointerUp, { once: true });
}
function onLayerPointerMove(e) {
if (!dragCtx) return;
const layer = state.layers.find((l) => l.id === dragCtx.layerId);
if (!layer) return;
const dx = e.clientX - dragCtx.startX;
const dy = e.clientY - dragCtx.startY;
if (dragCtx.role === "move") {
layer.xIn = dragCtx.startLayerX + dx / dragCtx.pxPerInX;
layer.yIn = dragCtx.startLayerY + dy / dragCtx.pxPerInY;
} else if (dragCtx.role === "resize") {
const proposed = dragCtx.startWidthIn + dx / dragCtx.pxPerInX;
layer.widthIn = Math.max(0.5, proposed);
}
// Update editor inputs and node styles without rebuilding the DOM.
els.layerWidthIn.value = layer.widthIn.toFixed(2);
els.layerXIn.value = layer.xIn.toFixed(2);
els.layerYIn.value = layer.yIn.toFixed(2);
updateLayerTransforms();
if (dragCtx.role === "resize") updateCutSizeReadout(layer);
}
function onLayerPointerUp(e) {
if (!dragCtx) return;
const node = els.layerPreviewWrap.querySelector(
`.layer-preview[data-layer-id="${dragCtx.layerId}"]`
);
if (node) {
node.classList.remove("dragging");
node.removeEventListener("pointermove", onLayerPointerMove);
}
dragCtx = null;
}
// --- Compose / analyze / export ---
async function runCompose() {
if (state.layers.length === 0) return;
els.composeBtn.disabled = true;
setStatus("Composing & tracing…");
try {
const res = await fetch("/compose", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
panel_w_in: state.panelWidthIn,
panel_h_in: state.panelHeightIn,
intent: state.intent,
layers: state.layers.map((l) => ({
image_token: l.imageToken,
mask_mode: l.maskMode,
mask_params: l.maskParams,
polarity: l.polarity || (state.intent === "silhouette" ? "add" : "subtract"),
x_in: l.xIn,
y_in: l.yIn,
scale_in: l.widthIn,
visible: l.visible,
})),
turdsize: 8,
alphamax: 1.0,
opttolerance: 0.4,
}),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
setStatus(err.error || `Compose failed (${res.status})`, true);
return;
}
const data = await res.json();
state.composedToken = data.token;
state.composedRawPaths = data.paths;
state.composedPaths = data.svg_d;
state.composedW = data.width;
state.composedH = data.height;
state.composedInPerPx = data.in_per_px;
renderTracePaths(data.svg_d);
setStatus(`Composed — ${data.paths.length} cut path${data.paths.length === 1 ? "" : "s"}.`);
updateDimsLabel();
if (data.token) {
els.exportSvgBtn.disabled = false;
els.exportDxfBtn.disabled = false;
runAnalyze();
} else {
els.exportSvgBtn.disabled = true;
els.exportDxfBtn.disabled = true;
renderWarnings({ warnings: [] });
setOverlay(null);
}
} catch (err) {
setStatus(err.message || String(err), true);
} finally {
els.composeBtn.disabled = state.layers.length === 0;
}
}
function renderTracePaths(svgDs) {
if (!svgDs || !svgDs.length) {
els.traceSvg.innerHTML = "";
return;
}
els.traceSvg.setAttribute("viewBox", `0 0 ${state.composedW} ${state.composedH}`);
els.traceSvg.innerHTML = svgDs.map((d) => `
${(data && data.error) || ""}
`; return; } const ws = data.warnings || []; if (ws.length === 0) { els.warnings.classList.add("clean"); els.warnings.innerHTML = `Looks cuttable. No thin features, floating islands or oversized gaps detected.
`; return; } els.warnings.classList.remove("clean"); els.warnings.innerHTML = ws.map((w) => { const meta = []; if (w.kind === "thin_feature" && w.regions && w.regions.length) { meta.push(w.regions.slice(0, 3).map((r) => `${r.min_width_in.toFixed(3)}″ wide`).join(", ")); } if (w.kind === "gap_too_large" && w.regions && w.regions.length) { meta.push(`Widest ${w.worst_in.toFixed(2)}" of ${w.max_allowed_in.toFixed(2)}" allowed`); meta.push("Shown in blue on the panel"); } if (w.kind === "floating_island" && data.islands && data.islands.length) { meta.push("Sizes: " + data.islands.slice(0, 4).map((i) => `${i.area_in2.toFixed(2)} in²`).join(", ")); } return `