"use strict"; const $ = (s) => document.querySelector(s); const $$ = (s) => [...document.querySelectorAll(s)]; const PAGE = 60; const MAX_STYLES = 3; const BOTH = "entrambi"; const REFINE = "klein+z"; const REFINE_MODES = ["ristila", "modifica", "continua"]; const TOOL_MODES = ["ingrandisci", "scontorna"]; const USER_CATEGORY = "I tuoi stili"; const STYLE_COLORS = ["#cbbcff", "#ffc9a8", "#9fe3da", "#ffd600", "#ff7a7a", "#7aa7ff"]; const MODES = { crea: { hint: "Un'immagine nuova da una descrizione.", placeholder: "Descrivi la scena: soggetto, ambiente, luce, stile. Il testo da scrivere nell'immagine va tra virgolette.", maxRefs: 0, button: "Genera", }, ristila: { hint: "Stessa foto, stile nuovo.", placeholder: "Scegli uno stile a destra. Se vuoi, aggiungi cosa cambiare: «di notte», «sotto la neve», «con un sorriso».", maxRefs: 1, button: "Ristila", }, modifica: { hint: "Cambia quello che scrivi: in tutta la foto o solo nella zona che dipingi.", placeholder: "Cosa cambiare: «togli la persona a sinistra», «metti un cappello rosso». Con più foto: «il gatto della foto 2 sul divano della foto 1».", maxRefs: 4, button: "Modifica", }, continua: { hint: "Una nuova scena con lo stesso stile, mondo e personaggi della foto.", placeholder: "La nuova scena: «lo stesso personaggio di notte sul tetto», «la piazza vista dall'alto con la folla».", maxRefs: 1, button: "Crea la scena", }, }; const MODE_LABEL = { crea: "Creata", ristila: "Ristilizzata", modifica: "Modificata", continua: "Stessa storia", ingrandisci: "Ingrandita ×2", scontorna: "Scontornata", locandina: "Locandina", viste: "Vista per il 3D", }; const PRINT_CATEGORY = "Stampa 3D"; const isTool = (item) => TOOL_MODES.includes(item?.modalita); const isPoster = (item) => item?.modalita === "locandina"; const isView = (item) => item?.modalita === "viste"; const isFixed = (item) => isTool(item) || isPoster(item) || isView(item); const canRefine = (item) => item && item.modello === "klein" && !isFixed(item) && !item.rifinita; const isPrintable = (item) => !isFixed(item) && stylesOf(item).some((id) => templateById(id)?.categoria === PRINT_CATEGORY); const prefs = { get(key, fallback) { try { const v = localStorage.getItem(`pixrick.${key}`); return v === null ? fallback : JSON.parse(v); } catch { return fallback; } }, set(key, value) { try { localStorage.setItem(`pixrick.${key}`, JSON.stringify(value)); } catch { /* spazio pieno o non disponibile */ } }, }; const state = { models: {}, auto: {}, templates: [], mode: "crea", model: "auto", styles: [], fieldValues: {}, aspect: "1:1", aspectTouched: false, aspects: {}, quality: "bilanciata", count: 1, refs: [], current: null, session: [], refineFrom: null, nextDismissed: "", userStylesOpen: false, tools: {}, batch: [], lastPrompt: "", busy: false, polling: null, gallery: { filter: "tutte", items: [], offset: 0, full: false, selected: new Set(), detailIndex: -1 }, }; /* ---------- utilità ---------- */ async function api(path, body, extraHeaders = {}) { if (window.PixBackend) { try { return await window.PixBackend.api(path, body, extraHeaders); } catch (e) { throw e instanceof Error ? e : new Error(String(e)); } } const opts = body === undefined ? {} : { method: "POST", headers: { "X-ImgAI": "1", ...extraHeaders }, body: body instanceof Blob ? body : JSON.stringify(body), }; if (body !== undefined && !(body instanceof Blob)) opts.headers["Content-Type"] = "application/json"; const res = await fetch(path, opts); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.errore || `Errore ${res.status}`); return data; } function toast(text, action) { const box = $("#toast"); const btn = $("#toast-action"); $("#toast-text").textContent = text; btn.hidden = !action; btn.onclick = null; if (action) { btn.textContent = action.label; btn.onclick = () => { box.classList.remove("show"); action.run(); }; } box.classList.add("show"); clearTimeout(toast.t); toast.t = setTimeout(() => box.classList.remove("show"), action ? 6000 : 2800); } function radio(container, attr, value) { container.querySelectorAll("[role=radio]").forEach((b) => b.setAttribute("aria-checked", String(b.dataset[attr] === String(value)))); } const mediaUrl = (path) => "/" + path.split("/").map(encodeURIComponent).join("/"); const outputUrl = (file) => mediaUrl("outputs/" + file); function el(tag, props = {}, children = []) { const n = document.createElement(tag); for (const [k, v] of Object.entries(props)) { if (k === "class") n.className = v; else if (k === "text") n.textContent = v; else if (k.startsWith("on")) n.addEventListener(k.slice(2), v); else if (k === "data") Object.assign(n.dataset, v); else n.setAttribute(k, v); } n.append(...children); return n; } function icon(id) { const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); const use = document.createElementNS("http://www.w3.org/2000/svg", "use"); use.setAttribute("href", `#${id}`); svg.append(use); return svg; } const templateById = (id) => state.templates.find((t) => t.id === id); const stylesOf = (item) => item.stili || (item.template && item.template !== "libero" ? [item.template] : []); const styleNames = (ids) => ids.map((id) => templateById(id)?.nome || "stile eliminato").join(" + "); const titleOf = (item) => item.titolo || item.prompt || (stylesOf(item).length ? `${styleNames(stylesOf(item))}, da una foto` : "") || item.prompt_finale || "Senza titolo"; function resolvedModels(mode = state.mode, wanted = state.model) { if (mode === "modifica" && mask.hasStrokes() && wanted !== REFINE) return ["klein"]; if (wanted === REFINE) return REFINE_MODES.includes(mode) ? ["klein", "z-image"] : [state.auto[mode]]; if (wanted === BOTH) return Object.keys(state.models).filter((k) => state.models[k].modalita.includes(mode)); const m = state.models[wanted]; return [m && m.modalita.includes(mode) ? wanted : state.auto[mode]]; } const resolvedModel = (mode, wanted) => resolvedModels(mode, wanted)[0]; const otherModel = (key) => Object.keys(state.models).find((k) => k !== key); /* ---------- stato motore ---------- */ async function refreshStatus() { try { return await api("/api/status"); } catch { return null; } } /* ---------- pannello modello ---------- */ function renderModels() { const box = $("#models"); box.replaceChildren(); const autoKey = state.auto[state.mode]; const zoned = state.mode === "modifica" && mask.hasStrokes(); const options = [ { key: "auto", nome: "Automatico", note: state.models[autoKey]?.nome, descrizione: "Sceglie il modello giusto per quello che stai facendo." }, ...Object.entries(state.models).map(([key, m]) => ({ key, ...m })), { key: BOTH, nome: "Entrambi", modalita: ["crea", "ristila"], descrizione: "Stesso prompt e stesso seme con i due modelli, affiancati." }, { key: REFINE, nome: "Klein + rifinitura Z-Image", modalita: REFINE_MODES, descrizione: "Klein capisce la foto e fa il lavoro, poi Z-Image ripassa pelle, luce e dettagli. Ricevi solo le immagini finite." }, ]; for (const o of options) { const supported = o.key === "auto" || (o.modalita.includes(state.mode) && !(zoned && !["klein", REFINE].includes(o.key))); if (o.key === REFINE && !supported) continue; box.append(el("button", { type: "button", class: "model", role: "radio", "aria-checked": String(state.model === o.key), "aria-disabled": String(!supported), title: supported ? "" : "Le modifiche a comando le fa solo FLUX.2 Klein", onclick: () => { if (!supported) return; state.model = o.key; syncAll(); if (state.mode === "ristila" && o.key === "z-image") warnBlindModel(); }, }, [ el("span", { class: "model-name" }, [o.nome, ...(o.note ? [el("small", { text: o.note })] : [])]), el("span", { class: "model-desc", text: o.descrizione }), ])); } } /* ---------- stili combinabili ---------- */ function renderTemplates() { const box = $("#templates"); box.replaceChildren(); const groups = new Map([[USER_CATEGORY, []]]); for (const t of state.templates) { if (!groups.has(t.categoria)) groups.set(t.categoria, []); groups.get(t.categoria).push(t); } const ordered = new Map(); for (const [name, items] of groups) { if (name === USER_CATEGORY) continue; ordered.set(name, items); if (ordered.size === 1) ordered.set(USER_CATEGORY, groups.get(USER_CATEGORY)); } const USER_VISIBLE = 6; for (const [name, all] of ordered) { const chips = el("div", { class: "tpl-chips", "aria-label": name }); let items = all; const hiddenCount = name === USER_CATEGORY && !state.userStylesOpen ? Math.max(0, all.length - USER_VISIBLE) : 0; if (hiddenCount) { const picked = all.filter((t) => state.styles.includes(t.id)); const rest = all.filter((t) => !state.styles.includes(t.id)); items = [...picked, ...rest].slice(0, Math.max(USER_VISIBLE, picked.length)); } for (const t of items) { const c = el("button", { type: "button", class: "chip", "aria-checked": "false", data: { id: t.id }, text: t.nome, title: t.descrizione || "", onclick: () => toggleStyle(t.id) }); c.style.setProperty("--c", t.colore); if (t.utente) { chips.append(el("span", { class: "chip-wrap" }, [ c, el("button", { type: "button", class: "chip-edit", title: `Modifica «${t.nome}»`, "aria-label": `Modifica lo stile ${t.nome}`, onclick: () => openStyleDialog(t) }, [icon("i-pencil")]), ])); } else { chips.append(c); } } if (name === USER_CATEGORY && all.length > USER_VISIBLE) { const extra = all.length - items.length; chips.append(el("button", { type: "button", class: "chip chip-more", onclick: () => { state.userStylesOpen = !state.userStylesOpen; renderTemplates(); }, }, [state.userStylesOpen ? "Mostra meno" : `Altri ${extra}`])); } if (name === USER_CATEGORY) { chips.append(el("button", { type: "button", class: "chip chip-add", title: "Salva un tuo stile da riusare e combinare", onclick: () => openStyleDialog() }, [icon("i-plus"), items.length ? "Nuovo" : "Crea il tuo stile"])); } box.append(el("div", { class: "tpl-group" + (name === USER_CATEGORY ? " user" : "") }, [el("p", { class: "tpl-group-name", text: name }), chips])); } renderStyleState(); } function toggleStyle(id) { saveFieldValues(); if (id === "libero") { state.styles = []; } else if (state.styles.includes(id)) { state.styles = state.styles.filter((s) => s !== id); } else if (state.styles.length >= MAX_STYLES) { toast(`Al massimo ${MAX_STYLES} stili insieme`); return; } else { state.styles.push(id); const t = templateById(id); if (state.styles.length === 1 && !state.aspectTouched && (state.mode === "crea" || (state.mode === "ristila" && t.forma))) selectAspect(t.formato); if (t.utente && (t.modello || t.qualita)) { const usable = t.modello && (t.modello === BOTH ? state.mode !== "modifica" : state.models[t.modello]?.modalita.includes(state.mode)); if (usable) state.model = t.modello; if (t.qualita) { state.quality = t.qualita; radio($("#quality"), "v", state.quality); } syncAll(); toast(`«${t.nome}» ha impostato anche ${usable ? "modello e " : ""}qualità`); } } renderStyleState(); } function renderStyleState() { state.styles = state.styles.filter((id) => templateById(id)); const multi = state.styles.length > 1; $$("#templates .chip[data-id]").forEach((c) => { const id = c.dataset.id; const idx = state.styles.indexOf(id); const on = id === "libero" ? state.styles.length === 0 : idx >= 0; c.setAttribute("aria-checked", String(on)); if (multi && idx >= 0) c.dataset.order = String(idx + 1); else delete c.dataset.order; }); let desc = "Nessuno stile: usa esattamente quello che scrivi."; if (state.styles.length === 1) desc = templateById(state.styles[0]).descrizione; if (multi) desc = `${styleNames(state.styles)}. Il primo decide il tipo di immagine, gli altri aggiungono il loro stile.`; $("#tpl-desc").textContent = desc; const fields = $("#tpl-fields"); fields.replaceChildren(); const seen = new Set(); for (const id of state.styles) { for (const f of templateById(id)?.campi || []) { if (seen.has(f.id)) continue; seen.add(f.id); const input = el("input", { type: "text", maxlength: "200", autocomplete: "off", placeholder: f.placeholder || "", data: { field: f.id } }); input.value = state.fieldValues[f.id] || ""; fields.append(el("label", {}, [f.etichetta, input])); } } renderPills(); } function saveFieldValues() { $$("[data-field]").forEach((i) => (state.fieldValues[i.dataset.field] = i.value)); } async function reloadTemplates() { state.templates = (await api("/api/templates")).template; renderTemplates(); } /* ---------- stili salvati ---------- */ const styleDlg = { editing: null, color: STYLE_COLORS[0], aspect: "1:1", model: "", quality: "" }; function openStyleDialog(style = null, fromItem = null) { styleDlg.editing = style; styleDlg.model = style?.modello || fromItem?.modello || ""; styleDlg.quality = style?.qualita || fromItem?.qualita || ""; const modelName = state.models[styleDlg.model]?.nome || (styleDlg.model === BOTH ? "Entrambi" : ""); $("#sd-model-row").hidden = !modelName; $("#sd-model").checked = Boolean(style ? style.modello : fromItem); $("#sd-model-label").textContent = `Ricorda anche modello e qualità (${modelName}${styleDlg.quality ? `, ${styleDlg.quality}` : ""})`; styleDlg.color = style?.colore || STYLE_COLORS[Math.floor(Math.random() * STYLE_COLORS.length)]; const itemAspect = fromItem && state.aspects[fromItem.formato] ? fromItem.formato : null; styleDlg.aspect = style?.formato || itemAspect || (state.aspect !== "originale" ? state.aspect : "1:1"); $("#style-dlg-title").textContent = style ? "Modifica stile" : "Nuovo stile"; $("#sd-name").value = style?.nome || ""; $("#sd-text").value = style?.testo || ""; $("#sd-delete").hidden = !style; $("#sd-error").textContent = ""; const sw = $("#sd-colors"); sw.replaceChildren(...STYLE_COLORS.map((c) => { const b = el("button", { type: "button", class: "swatch", role: "radio", "aria-checked": String(c === styleDlg.color), "aria-label": c, data: { v: c }, onclick: () => { styleDlg.color = c; radio(sw, "v", c); } }); b.style.setProperty("--c", c); return b; })); const asp = $("#sd-aspect"); asp.replaceChildren(...Object.keys(state.aspects).map((k) => el("button", { type: "button", role: "radio", "aria-checked": String(k === styleDlg.aspect), data: { v: k }, text: k, onclick: () => { styleDlg.aspect = k; radio(asp, "v", k); }, }))); $("#style-dlg").showModal(); $("#sd-name").focus(); if (fromItem) extractStyle(fromItem); } async function extractStyle(item) { const field = $("#sd-text"); field.value = ""; field.placeholder = "Ricavo lo stile dall'immagine…"; field.disabled = true; try { const { testo } = await api("/api/styles/extract", { prompt: item.prompt_finale || item.prompt || "", stili: stylesOf(item) }); field.value = testo || ""; if (!testo) $("#sd-error").textContent = "Il prompt non descriveva lo stile: scrivilo tu in poche parole (luce, colori, resa)."; } catch (e) { $("#sd-error").textContent = e.message; } finally { field.disabled = false; field.placeholder = "Notte, luci calde ambra e bianche, fumo di palco, folla in controluce, contrasto forte"; } } async function saveStyleDialog() { const name = $("#sd-name").value.trim(); const text = $("#sd-text").value.trim(); const err = $("#sd-error"); if (!name || !text) { err.textContent = "Servono un nome e una descrizione."; return; } const btn = $("#sd-save"); btn.disabled = true; btn.textContent = "Salvo…"; try { const saved = await api("/api/styles/save", { id: styleDlg.editing?.id || "", nome: name, testo: text, formato: styleDlg.aspect, colore: styleDlg.color, modello: $("#sd-model").checked && !$("#sd-model-row").hidden ? styleDlg.model : "", qualita: $("#sd-model").checked && !$("#sd-model-row").hidden ? styleDlg.quality : "", }); $("#style-dlg").close(); await reloadTemplates(); if (!styleDlg.editing && !state.styles.includes(saved.id) && state.styles.length < MAX_STYLES) { if (state.mode !== "crea" && state.mode !== "ristila") setMode("crea"); toggleStyle(saved.id); } toast(styleDlg.editing ? "Stile aggiornato" : `Stile «${saved.nome}» salvato e selezionato`); } catch (e) { err.textContent = e.message; } finally { btn.disabled = false; btn.textContent = "Salva stile"; } } async function deleteStyleDialog() { const style = styleDlg.editing; if (!style) return; $("#style-dlg").close(); const ok = await confirmDialog({ title: `Eliminare «${style.nome}»?`, text: "Le immagini già fatte con questo stile restano.", confirm: "Elimina stile", danger: true }); if (!ok) return; await api("/api/styles/delete", { id: style.id }); state.styles = state.styles.filter((s) => s !== style.id); await reloadTemplates(); toast("Stile eliminato"); } /* ---------- formato e qualità ---------- */ function renderAspects() { const box = $("#aspects"); box.replaceChildren(); const entries = Object.entries(state.aspects); if (state.mode !== "crea") entries.unshift(["originale", null]); for (const [key, dims] of entries) { const [w, h] = dims || [3, 4]; const shape = el("span", { class: "aspect-box" }); const scale = 22 / Math.max(w, h); shape.style.width = `${Math.round(w * scale)}px`; shape.style.height = `${Math.round(h * scale)}px`; box.append(el("button", { type: "button", class: "aspect" + (dims ? "" : " aspect-original"), role: "radio", "aria-checked": "false", data: { v: key }, title: dims ? `${dims[0]}×${dims[1]}` : "Stesse proporzioni della prima foto", onclick: () => { state.aspectTouched = true; selectAspect(key); }, }, [shape, el("span", { text: dims ? key : "Originale" })])); } radio(box, "v", state.aspect); } function selectAspect(key) { if (key !== "originale" && !state.aspects[key]) return; state.aspect = key; radio($("#aspects"), "v", key); renderPills(); } function updateQualityNote() { const keys = resolvedModels().filter((k) => state.models[k]); if (!keys.length) return; const notes = { rapida: "Per provare idee al volo.", bilanciata: "Il punto giusto tra resa e tempo.", massima: "Più dettaglio, un po' più di attesa." }; const steps = keys.map((k) => `${state.models[k].nome} ${state.models[k].qualita[state.quality]} passi`).join(", "); $("#quality-note").textContent = `${notes[state.quality]} ${steps}.`; $("#count-note").textContent = state.model === REFINE && keys.length > 1 ? `Ogni immagine passa da Klein e poi da Z-Image: ricevi ${state.count} ${state.count === 1 ? "immagine finita" : "immagini finite"}.` : keys.length > 1 ? `Con Entrambi: ${state.count} per modello, ${state.count * keys.length} in tutto, su due righe.` : ""; } /* ---------- riepilogo impostazioni nel composer ---------- */ function renderPills() { const box = $("#pills"); if (!box) return; const pills = []; const zoned = state.mode === "modifica" && mask.hasStrokes(); if (state.mode === "modifica") { pills.push({ k: "Zona", v: zoned ? "Solo la parte dipinta" : "Tutta l'immagine", target: "panel-zone", on: zoned }); } else if (state.mode === "continua") { pills.push({ k: "Stile", v: "Come la foto", target: "panel-aspect", on: true }); } else { pills.push({ k: "Stile", v: state.styles.length ? styleNames(state.styles) : "Nessuno", target: "panel-style", on: state.styles.length > 0 }); } if (!zoned) pills.push({ k: "Formato", v: state.aspect === "originale" ? "Come la foto" : state.aspect, target: "panel-aspect" }); const models = resolvedModels(); const modelText = state.model === REFINE && models.length > 1 ? "Klein + Z-Image" : state.model === BOTH && models.length > 1 ? "Entrambi" : (state.models[models[0]]?.nome || "").replace(" Turbo", ""); const autoText = state.mode === "ristila" && state.refs.length ? "Auto · sceglie PixRick" : `Auto · ${modelText}`; pills.push({ k: "Modello", v: state.model === "auto" && !zoned ? autoText : modelText, target: "panel-model" }); const n = state.model === REFINE ? state.count : models.length * state.count; pills.push({ k: "Qualità", v: `${state.quality[0].toUpperCase()}${state.quality.slice(1)}${n > 1 ? ` · ${n} immagini` : ""}`, target: "panel-quality" }); box.replaceChildren(...pills.map((p) => el("button", { type: "button", class: "pill" + (p.on ? " on" : ""), title: "Cambia", onclick: () => focusPanel(p.target), }, [el("span", { class: "pill-k", text: p.k }), el("span", { class: "pill-v", text: p.v })]))); } function focusPanel(id) { const panel = document.getElementById(id); if (!panel) return; if (panel.tagName === "DETAILS") panel.open = true; panel.scrollIntoView({ behavior: "smooth", block: "nearest" }); panel.classList.remove("flash"); void panel.offsetWidth; panel.classList.add("flash"); } /* ---------- modalità e foto di partenza ---------- */ function setMode(mode) { state.mode = mode; document.body.dataset.mode = mode; $$(".modes [role=tab]").forEach((t) => t.setAttribute("aria-selected", String(t.dataset.mode === mode))); const cfg = MODES[mode]; $("#mode-hint").textContent = cfg.hint; $("#prompt").placeholder = matchMedia("(max-width: 760px)").matches ? cfg.placeholder.replace("a destra", "in «Stile e impostazioni»") : cfg.placeholder; $("#generate-label").textContent = cfg.button; $("#ref-add-label").textContent = mode === "ristila" ? "Foto" : "Foto"; const supports = state.model === BOTH ? !["modifica", "continua"].includes(mode) : state.model === REFINE ? REFINE_MODES.includes(mode) : state.model === "auto" || state.models[state.model]?.modalita.includes(mode); if (!supports) { state.model = "auto"; toast(mode === "continua" ? "Le storie le fa solo FLUX.2 Klein: l'ho selezionato io" : "Le modifiche a comando le fa solo FLUX.2 Klein: l'ho selezionato io"); } if (!state.aspectTouched || (mode === "crea" && state.aspect === "originale")) { state.aspect = mode === "crea" ? (templateById(state.styles[0])?.formato || "1:1") : "originale"; state.aspectTouched = false; } if (mode !== "modifica") brush.stop(); renderAspects(); syncAll(); syncBase(); updateNextBar(); } function syncAll() { document.body.dataset.modelResolved = resolvedModel(); document.body.dataset.model = state.model; renderModels(); renderRefs(); updateQualityNote(); updateShotActions(); renderZone(); renderPills(); } function renderRefs() { const list = $("#ref-list"); list.replaceChildren(); const max = MODES[state.mode].maxRefs; const shown = state.refs.slice(0, max); shown.forEach((r, i) => { list.append(el("div", { class: "ref" + (i === 0 ? " main" : "") }, [ el("img", { src: mediaUrl(r.file), alt: r.nome || `Foto ${i + 1}` }), ...(state.mode === "modifica" && shown.length > 1 ? [el("span", { class: "ref-index", text: String(i + 1) })] : []), el("button", { type: "button", "aria-label": "Togli questa foto", onclick: () => { state.refs.splice(i, 1); refsChanged(); } }, [icon("i-x")]), ])); }); $("#refs").classList.toggle("full", shown.length >= max); } function refsChanged() { renderRefs(); if (state.mode !== "crea" && state.refs[0]) sessionAddStart(state.refs[0]); syncBase(); updateNextBar(); sessionRender(); } async function addFiles(files) { const images = [...files].filter((f) => f.type.startsWith("image/")); if (!images.length) return; const fromScratch = state.mode === "crea"; if (fromScratch) setMode(images.length > 1 ? "modifica" : "ristila"); const max = MODES[state.mode].maxRefs; if (state.mode === "ristila" || state.mode === "continua") state.refs = []; for (const f of images) { if (state.refs.length >= max) { toast(`Al massimo ${max} foto in questa modalità`); break; } try { const info = await api("/api/upload", f, { "Content-Type": f.type || "application/octet-stream", "X-Filename": encodeURIComponent(f.name || "incollata") }); state.refs.push(info); refsChanged(); } catch (e) { toast(e.message); } } if (fromScratch && images.length === 1 && state.refs.length) { askStart(); return; } $("#prompt").focus(); } function askStart() { const dlg = $("#start-dlg"); dlg.returnValue = ""; dlg.showModal(); dlg.addEventListener("close", () => { const mode = dlg.returnValue; if (mode && mode !== state.mode) setMode(mode); refsChanged(); $("#prompt").focus(); }, { once: true }); } function useAsRef(item, mode) { state.refs = [{ file: "outputs/" + item.file, nome: titleOf(item) }]; setView("studio"); setMode(mode); refsChanged(); $("#prompt").value = ""; autosize(); $("#prompt").focus(); const tips = { modifica: "Scrivi cosa cambiare, o dipingi prima la zona", ristila: "Scegli uno stile o descrivi la trasformazione", continua: "Scrivi la nuova scena: stile e personaggi restano quelli", }; toast(tips[mode]); } /* ---------- sessione: tutto quello che hai fatto da quando hai aperto la pagina ---------- */ const fileName = (f) => (f || "").split("/").pop(); function sessionAdd(items, group = "", kind = "risultato") { for (const item of items) { if (state.session.some((e) => fileName(e.item.file) === fileName(item.file))) continue; state.session.push({ item, group, kind }); } sessionRender(); } function sessionAddStart(ref) { if (!ref?.file) return; const name = fileName(ref.file); const existing = state.session.find((e) => fileName(e.item.file) === name); if (existing) { existing.kind = "partenza"; sessionRender(); return; } state.session.push({ item: { file: ref.file, nome: ref.nome || "Foto", esterna: true }, group: "", kind: "partenza" }); sessionRender(); } function sessionSwap(byName) { for (const e of state.session) { const n = fileName(e.item.file); if (byName.has(n)) e.item = byName.get(n); } sessionRender(); } function sessionRemove(files) { const gone = new Set(files.map(fileName)); state.session = state.session.filter((e) => !gone.has(fileName(e.item.file))); sessionRender(); } const sessionSrc = (e) => (e.item.esterna ? mediaUrl(e.item.file) : outputUrl(e.item.miniatura || e.item.file)); function sessionActiveName() { const st = $("#stage").dataset.state; if (st === "base") return fileName(state.refs[0]?.file); if (st === "foto") return fileName(state.current?.file); return ""; } function sessionRender() { const nav = $("#session"); const list = $("#session-list"); nav.hidden = state.session.length === 0; list.replaceChildren(); const active = sessionActiveName(); const compareGroup = $("#stage").dataset.state === "confronto" ? state.batch.map((b) => fileName(b.file)) : []; let lastGroup = null; state.session.forEach((e, i) => { const name = fileName(e.item.file); const siblings = e.group ? state.session.filter((x) => x.group === e.group) : []; if (e.group && e.group !== lastGroup && siblings.length > 1) { list.append(el("button", { type: "button", class: "session-group", title: "Confronta queste immagini affiancate", onclick: () => { state.batch = siblings.map((x) => x.item); showCompare(state.batch); }, }, [`${siblings.length} insieme`])); } lastGroup = e.group; const isOn = name === active || compareGroup.includes(name); list.append(el("button", { type: "button", class: "session-item" + (isOn ? " on" : "") + (e.item.bozza === false ? " saved" : ""), title: e.kind === "partenza" ? "Immagine di partenza" : (MODE_LABEL[e.item.modalita] || "Creata") + (e.item.bozza === false ? " · in galleria" : " · bozza"), data: { i: String(i) }, onclick: () => sessionOpen(i), }, [ el("img", { src: sessionSrc(e), alt: "" }), ...(e.kind === "partenza" ? [el("span", { class: "session-tag", text: "partenza" })] : []), ])); }); list.querySelector(".session-item.on")?.scrollIntoView({ block: "nearest" }); } function sessionOpen(i) { const e = state.session[i]; if (!e) return; const isStart = state.mode !== "crea" && fileName(state.refs[0]?.file) === fileName(e.item.file); if (isStart) { state.current = null; $("#stage").dataset.state = ""; syncBase(); } else if (e.item.esterna) { if (state.mode === "crea") setMode("ristila"); state.refs = [{ file: e.item.file, nome: e.item.nome }]; refsChanged(); } else { showShot(e.item); } sessionRender(); } function sessionStep(delta) { if (!state.session.length) return; const active = sessionActiveName(); let i = state.session.findIndex((e) => fileName(e.item.file) === active); i = i < 0 ? state.session.length - 1 : Math.max(0, Math.min(state.session.length - 1, i + delta)); sessionOpen(i); } /* ---------- lavoro a cascata: continua dalla nuova versione ---------- */ function updateNextBar() { const bar = $("#next-bar"); const it = state.current; const ref = state.refs[0]?.file; const show = Boolean( it && ref && state.mode !== "crea" && !state.busy && $("#stage").dataset.state === "foto" && `outputs/${it.file}` !== ref && state.nextDismissed !== it.file && !isPoster(it), ); bar.hidden = !show; if (show) $("#next-thumb").src = outputUrl(it.miniatura || it.file); } function continueFromCurrent() { const it = state.current; if (!it) return; const others = state.refs.slice(1); state.refs = [{ file: "outputs/" + it.file, nome: titleOf(it) }, ...others]; if (it.modalita === "scontorna" && state.mode === "ristila" && !state.aspectTouched) state.aspect = "originale"; refsChanged(); $("#next-bar").hidden = true; $("#prompt").focus(); toast("Ora lavori sulla nuova versione"); } /* ---------- menu sull'immagine ---------- */ const shotMenu = { open(e) { const item = state.current; if (!item || $("#stage").dataset.state !== "foto") return; const menu = $("#shot-menu"); const hasPrompt = Boolean(item.prompt_finale || item.prompt) && !isPoster(item) && !isView(item); $("#m-style").disabled = !hasPrompt; $("#m-story").disabled = isPoster(item); $("#m-refine").hidden = !canRefine(item); const r = $("#stage").getBoundingClientRect(); menu.hidden = false; const w = menu.offsetWidth; const h = menu.offsetHeight; menu.style.left = `${Math.min(r.width - w - 12, Math.max(12, e.clientX - r.left))}px`; menu.style.top = `${Math.min(r.height - h - 12, Math.max(12, e.clientY - r.top))}px`; menu.querySelector("button:not([disabled])")?.focus(); }, close() { $("#shot-menu").hidden = true; }, wire() { $("#shot-img").addEventListener("click", (e) => { e.stopPropagation(); this.open(e); }); document.addEventListener("click", (e) => { if (!e.target.closest("#shot-menu")) this.close(); }); document.addEventListener("keydown", (e) => { if (e.key === "Escape") this.close(); }); const act = (id, fn) => $(id).addEventListener("click", () => { const it = state.current; this.close(); if (it) fn(it); }); act("#m-story", (it) => useAsRef(it, "continua")); act("#m-style", (it) => openStyleDialog(null, it)); act("#m-refine", runRefine); act("#m-zone", (it) => { useAsRef(it, "modifica"); setTimeout(() => brush.start(), 80); }); act("#m-poster", openInPoster); }, }; /* ---------- immagine di partenza e zona dipinta ---------- */ function syncBase() { const stage = $("#stage"); const ref = state.mode !== "crea" ? state.refs[0] : null; if (ref) { const img = $("#base-img"); if (img.dataset.file !== ref.file) { img.dataset.file = ref.file; img.src = mediaUrl(ref.file); mask.reset(); } $("#base-label").textContent = { modifica: "Immagine da modificare", continua: "La storia parte da qui" }[state.mode] || "Immagine di partenza"; if (!state.busy) { stage.dataset.state = "base"; $("#shot-bar").hidden = true; $("#next-bar").hidden = true; $("#base-bar").hidden = brush.active; $("#b-upscale").disabled = !state.tools.ingrandisci; $("#b-cutout").disabled = !state.tools.scontorna; } } else { brush.stop(); mask.reset(); $("#base-img").removeAttribute("src"); delete $("#base-img").dataset.file; if (stage.dataset.state === "base") restoreStage(); } if (stage.dataset.state !== "base") $("#base-bar").hidden = true; } function restoreStage() { if (state.batch.length > 1 && document.body.dataset.stage === "confronto") showCompare(state.batch); else if (state.current) showShot(state.current); else clearStage(); } const mask = { strokes: [], canvas: null, ctx: null, hasStrokes() { return this.strokes.some((s) => !s.erase); }, init() { this.canvas = $("#mask-canvas"); this.ctx = this.canvas.getContext("2d"); }, size() { const img = $("#base-img"); return [img.naturalWidth || 1, img.naturalHeight || 1]; }, fit() { const [w, h] = this.size(); if (this.canvas.width !== w || this.canvas.height !== h) { this.canvas.width = w; this.canvas.height = h; this.redraw(); } }, reset() { this.strokes = []; if (this.ctx) this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); renderZone(); }, undo() { this.strokes.pop(); this.redraw(); renderZone(); }, drawStroke(ctx, s, color) { ctx.save(); ctx.globalCompositeOperation = s.erase && !color ? "destination-out" : "source-over"; ctx.strokeStyle = color ? (s.erase ? "#000" : "#fff") : "#cbbcff"; ctx.fillStyle = ctx.strokeStyle; ctx.lineWidth = s.size; ctx.lineCap = "round"; ctx.lineJoin = "round"; if (s.pts.length === 1) { ctx.beginPath(); ctx.arc(s.pts[0][0], s.pts[0][1], s.size / 2, 0, Math.PI * 2); ctx.fill(); } else { ctx.beginPath(); ctx.moveTo(...s.pts[0]); for (const p of s.pts.slice(1)) ctx.lineTo(...p); ctx.stroke(); } ctx.restore(); }, redraw() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); for (const s of this.strokes) this.drawStroke(this.ctx, s); }, async upload() { const [w, h] = this.size(); const off = document.createElement("canvas"); off.width = w; off.height = h; const c = off.getContext("2d"); c.fillStyle = "#000"; c.fillRect(0, 0, w, h); for (const s of this.strokes) this.drawStroke(c, s, true); const probe = document.createElement("canvas"); probe.width = 96; probe.height = Math.max(1, Math.round((96 * h) / w)); const pc = probe.getContext("2d"); pc.drawImage(off, 0, 0, probe.width, probe.height); const px = pc.getImageData(0, 0, probe.width, probe.height).data; let painted = false; for (let i = 0; i < px.length; i += 4) if (px[i] > 40) { painted = true; break; } if (!painted) return null; const blob = await new Promise((r) => off.toBlob(r, "image/png")); const info = await api("/api/upload", blob, { "Content-Type": "image/png", "X-Filename": "zona.png" }); return info.file; }, }; const brush = { active: false, tool: "pennello", drawing: null, sizeFraction() { return Number($("#brush-size").value); }, px() { const [w, h] = mask.size(); return Math.max(4, this.sizeFraction() * Math.min(w, h)); }, start() { if (state.mode !== "modifica" || !state.refs[0]) { toast("Aggiungi prima la foto da modificare"); return; } if (state.busy) return; syncBase(); mask.fit(); this.active = true; $("#stage").dataset.brush = "on"; $("#base-bar").hidden = true; renderZone(); }, stop() { this.active = false; $("#stage").dataset.brush = "off"; if ($("#stage").dataset.state === "base") $("#base-bar").hidden = false; $("#brush-cursor").classList.remove("show"); renderZone(); }, setTool(tool) { this.tool = tool; radio($("#brush-bar .seg"), "tool", tool); }, pos(e) { const r = mask.canvas.getBoundingClientRect(); const [w, h] = mask.size(); return [((e.clientX - r.left) / r.width) * w, ((e.clientY - r.top) / r.height) * h]; }, cursor(e) { const cur = $("#brush-cursor"); if (!this.active || !e) { cur.classList.remove("show"); return; } const r = mask.canvas.getBoundingClientRect(); const d = (this.px() * r.width) / mask.size()[0]; const stage = $("#stage").getBoundingClientRect(); cur.style.width = cur.style.height = `${d}px`; cur.style.transform = `translate(${e.clientX - stage.left - d / 2}px, ${e.clientY - stage.top - d / 2}px)`; cur.classList.toggle("erase", this.tool === "gomma"); cur.classList.add("show"); }, wire() { const cv = $("#mask-canvas"); cv.addEventListener("pointerdown", (e) => { if (!this.active) return; e.preventDefault(); cv.setPointerCapture(e.pointerId); this.drawing = { erase: this.tool === "gomma", size: this.px(), pts: [this.pos(e)] }; mask.strokes.push(this.drawing); mask.drawStroke(mask.ctx, this.drawing); }); cv.addEventListener("pointermove", (e) => { this.cursor(e); if (!this.drawing) return; const p = this.pos(e); const last = this.drawing.pts[this.drawing.pts.length - 1]; if (Math.hypot(p[0] - last[0], p[1] - last[1]) < 2) return; this.drawing.pts.push(p); const seg = { ...this.drawing, pts: [last, p] }; mask.drawStroke(mask.ctx, seg); }); const end = () => { if (!this.drawing) return; this.drawing = null; renderZone(); }; cv.addEventListener("pointerup", end); cv.addEventListener("pointercancel", end); cv.addEventListener("pointerleave", () => this.cursor(null)); $("#base-img").addEventListener("load", () => mask.fit()); $("#brush-bar .seg").addEventListener("click", (e) => { const b = e.target.closest("[data-tool]"); if (b) this.setTool(b.dataset.tool); }); $("#brush-undo").addEventListener("click", () => mask.undo()); $("#brush-clear").addEventListener("click", () => mask.reset()); $("#brush-done").addEventListener("click", () => { this.stop(); $("#prompt").focus(); }); $("#zone-btn").addEventListener("click", () => (this.active ? this.stop() : this.start())); $("#zone-clear").addEventListener("click", () => mask.reset()); document.addEventListener("keydown", (e) => { if (!this.active || e.target.closest("input, textarea")) return; if (e.key === "Escape") this.stop(); else if (e.key === "b" || e.key === "B") this.setTool("pennello"); else if (e.key === "e" || e.key === "E") this.setTool("gomma"); else if (e.key === "[" || e.key === "]") { const r = $("#brush-size"); r.value = String(Number(r.value) + (e.key === "]" ? 0.01 : -0.01)); } else if (e.key === "z" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); mask.undo(); } }); }, }; function renderZone() { const zoned = mask.hasStrokes(); $("#zone-text").textContent = zoned ? "Cambio solo la parte dipinta: il resto della foto resta identico." : "Senza zona cambia tutta l'immagine. Dipingi una parte e il resto resterà identico."; $("#zone-btn-label").textContent = brush.active ? "Ho finito di dipingere" : zoned ? "Ritocca la zona" : "Dipingi la zona"; $("#zone-btn").setAttribute("aria-pressed", String(brush.active)); $("#zone-clear").hidden = !zoned; document.body.dataset.zoned = String(zoned && state.mode === "modifica"); if (state.models.klein) { document.body.dataset.modelResolved = resolvedModel(); renderPills(); } } /* ---------- palco: sviluppo, foto, confronto ---------- */ function grainTile() { if (grainTile.url) return grainTile.url; const c = document.createElement("canvas"); c.width = c.height = 160; const ctx = c.getContext("2d"); const img = ctx.createImageData(160, 160); for (let i = 0; i < img.data.length; i += 4) { const v = Math.random() * 255; img.data[i] = img.data[i + 1] = img.data[i + 2] = v; img.data[i + 3] = 255; } ctx.putImageData(img, 0, 0); grainTile.url = c.toDataURL("image/png"); return grainTile.url; } function showWorking(job) { const stage = $("#stage"); brush.stop(); stage.dataset.state = "lavoro"; const bar = $("#shot-bar"); bar.hidden = false; bar.dataset.working = ""; $("#shot-prompt").textContent = job.request.prompt || MODE_LABEL[job.request.mode] || ""; $("#shot-meta").replaceChildren(el("span", { text: "In lavorazione" })); $("#base-bar").hidden = true; const frame = $("#develop-frame"); frame.style.setProperty("--ar", String(job.width / job.height)); $("#develop-grain").style.backgroundImage = `url(${grainTile()})`; let title = "In coda"; let sub = "Parte appena si libera una GPU."; if (job.status === "invio") { title = "Invio la richiesta"; sub = "Un attimo."; } else if (job.status === "in_coda" && job.position != null) { title = job.position === 0 ? "Sei il prossimo" : `In coda: ${job.position} prima di te`; sub = job.eta ? `Circa ${Math.max(1, Math.round(job.eta))} s` : "Parte appena si libera una GPU."; } else if (job.status === "salvataggio") { title = "Quasi fatto"; sub = "Salvo l'immagine nel tuo browser."; } const tool = TOOL_MODES.includes(job.request.mode); if (job.status === "traduzione") { title = "Traduco il prompt"; sub = "Il testo in italiano diventa inglese."; } else if (job.status === "caricamento") { title = `Preparo ${job.model_name}`; sub = "Succede la prima volta o quando cambi modello."; } else if (job.status === "generazione" && job.request.mode === "rifinisci") { title = "Z-Image ripassa la resa"; sub = `passo ${Math.min(job.current_steps, Math.max(1, Math.ceil(job.progress * job.current_steps)))} di ${job.current_steps} · ${Math.round(job.elapsed)} s`; } else if (job.status === "generazione" && job.refine && job.request.mode !== "rifinisci") { const n = job.request.count; const k = job.current_model === "klein"; const idx = k ? job.current + 1 : job.current - n + 1; title = k ? `Klein prepara ${n > 1 ? `l'immagine ${idx} di ${n}` : "l'immagine"}` : `Z-Image rifinisce ${n > 1 ? `l'immagine ${idx} di ${n}` : "l'immagine"}`; sub = `${Math.round(job.elapsed)} s`; } else if (job.status === "generazione" && job.request.mode === "viste") { const names = ["lato sinistro", "retro", "lato destro"]; title = `Giro la figura: ${names[job.current] || ""}`; sub = `Vista ${job.current + 1} di ${job.total} · ${Math.round(job.elapsed)} s`; } else if (job.status === "generazione" && tool) { title = job.request.mode === "ingrandisci" ? "Raddoppio la risoluzione" : "Tolgo lo sfondo"; sub = `${Math.round(job.elapsed)} s`; } else if (job.status === "generazione") { const total = job.total; const within = Math.max(0, job.progress * total - job.current); const steps = job.current_steps; const step = Math.min(steps, Math.max(1, Math.ceil(within * steps))); title = job.confronto ? `${job.model_name}, ${job.current + 1} di ${total}` : total > 1 ? `Immagine ${job.current + 1} di ${total}` : job.request.mask ? "Ridipingo la zona" : "Sto sviluppando l'immagine"; sub = `${job.model_name} · passo ${step} di ${steps} · ${Math.round(job.elapsed)} s`; } $("#develop-title").textContent = title; $("#develop-sub").textContent = sub; const progress = job.status === "generazione" ? job.progress : job.status === "caricamento" || job.status === "traduzione" ? 0.02 : 0; $("#develop-bar").style.transform = `scaleX(${Math.max(0, Math.min(1, progress))})`; frame.dataset.phase = job.status; } function describe(item) { if (isPoster(item)) return ["Locandina", `${item.larghezza}×${item.altezza}`]; if (isView(item)) return ["Vista per il 3D", item.vista || "", `${item.larghezza}×${item.altezza}`]; const parts = [MODE_LABEL[item.modalita] || "Creata", item.modello_nome || "Z-Image Turbo"]; if (isTool(item)) return [...parts, `${item.larghezza}×${item.altezza}`]; if (item.maschera) parts.push("solo una zona"); if (item.fedelta) parts.push(`fedeltà ${Number(item.fedelta).toFixed(2)}${item.fedelta_auto ? " auto" : ""}`); const styles = stylesOf(item); if (styles.length) parts.push(styleNames(styles)); parts.push(`${item.larghezza}×${item.altezza}`); return parts; } const metaSpans = (item) => describe(item).map((t) => el("span", { text: t })); function showShot(item, fresh = false) { state.current = item; $("#base-bar").hidden = true; document.body.dataset.stage = "foto"; const stage = $("#stage"); const img = $("#shot-img"); img.classList.remove("fresh"); img.onload = () => { stage.dataset.state = "foto"; if (fresh) { void img.offsetWidth; img.classList.add("fresh"); } updateNextBar(); sessionRender(); }; img.src = outputUrl(item.file); img.alt = titleOf(item); img.classList.toggle("checker", Boolean(item.trasparente)); if (img.complete && img.naturalWidth) img.onload(); $("#shot-bar").hidden = false; delete $("#shot-bar").dataset.working; $("#shot-prompt").textContent = titleOf(item); $("#shot-prompt").title = item.prompt_finale || ""; $("#shot-meta").replaceChildren(...metaSpans(item)); prepareDownload($("#act-download"), item); const save = $("#act-save"); save.dataset.saved = String(!item.bozza); const short = matchMedia("(max-width: 760px)").matches; $("#act-save-label").textContent = item.bozza ? (short ? "Salva" : "Salva in galleria") : "In galleria"; $("#act-trash").title = item.bozza ? "Elimina la bozza" : "Sposta nel cestino"; $("#act-back").hidden = !(state.batch.length > 1 && state.batch.some((b) => b.file === item.file)); updateShotActions(); updateNextBar(); } function showCompare(items = state.batch, fresh = false) { state.batch = items; state.current = items[0]; document.body.dataset.stage = "confronto"; $("#stage").dataset.state = "confronto"; $("#base-bar").hidden = true; $("#next-bar").hidden = true; const box = $("#compare"); box.replaceChildren(); const byModel = [...new Set(items.map((i) => i.modello))]; const rows = !isView(items[0]) && byModel.length > 1 && items.length > byModel.length ? byModel.length : 1; box.dataset.rows = String(rows); box.dataset.models = String(byModel.length); box.style.setProperty("--cols", String(Math.ceil(items.length / rows))); for (const item of items) { const save = el("button", { type: "button", class: "save-btn", "data-saved": String(!item.bozza), onclick: () => saveItems([item]), }, [icon("i-check"), el("span", { text: item.bozza ? "Salva" : "In galleria" })]); box.append(el("div", { class: "card" }, [ el("button", { type: "button", class: "card-media", title: "Guarda da sola", onclick: () => showShot(item) }, [ el("img", { src: outputUrl(item.file), alt: titleOf(item), class: fresh ? "fresh" : "" }), ]), el("div", { class: "card-foot" }, [ el("span", { class: "card-name" }, isView(item) ? [item.vista, el("small", { text: `${item.larghezza}×${item.altezza}` })] : [item.modello_nome]), save, ]), ])); } $("#shot-bar").hidden = false; delete $("#shot-bar").dataset.working; $("#act-back").hidden = true; $("#shot-prompt").textContent = isView(items[0]) ? "La stessa figura da altre angolazioni" : titleOf(items[0]); $("#shot-prompt").title = items[0].prompt_finale || ""; const first = isView(items[0]) ? ["Viste per il 3D", "da dare insieme alla frontale"] : describe(items[0]).filter((p, i) => i !== 1); $("#shot-meta").replaceChildren(...first.map((t) => el("span", { text: t }))); sessionRender(); const allSaved = items.every((i) => !i.bozza); const all = $("#act-save-all"); all.dataset.saved = String(allSaved); all.querySelector("span").textContent = allSaved ? "Tutte in galleria" : "Salva tutte"; } async function saveItems(items) { const drafts = items.filter((i) => i.bozza); if (!drafts.length) return; const { salvate } = await api("/api/keep", { files: drafts.map((d) => d.file) }); const byName = new Map(salvate.map((s) => [s.file.split("/").pop(), s])); const swap = (it) => (it && it.bozza && byName.has(it.file.split("/").pop()) ? byName.get(it.file.split("/").pop()) : it); state.batch = state.batch.map(swap); const current = swap(state.current); sessionSwap(new Map(salvate.map((x) => [fileName(x.file), x]))); if (document.body.dataset.stage === "confronto" && $("#stage").dataset.state === "confronto") showCompare(state.batch); else if (current && $("#stage").dataset.state === "foto") showShot(current); else state.current = current; refreshDraftCount(); toast(salvate.length === 1 ? "Salvata in galleria" : `${salvate.length} immagini salvate in galleria`); } function updateShotActions() { const it = state.current; if (!it) return; const other = otherModel(it.modello || "z-image"); const mode = it.modalita || "crea"; const canSwitch = !isFixed(it) && mode !== "modifica" && state.models[other]?.modalita.includes(mode); $("#act-variant").disabled = isFixed(it); $("#act-views").hidden = !isPrintable(it); $("#act-refine").hidden = !canRefine(it); $("#act-upscale").disabled = !state.tools.ingrandisci; $("#act-cutout").disabled = !state.tools.scontorna || Boolean(it.trasparente); $("#act-reuse").disabled = isFixed(it); const btn = $("#act-other"); btn.disabled = !canSwitch; btn.title = canSwitch ? "Stesse impostazioni e stesso seme con l'altro modello" : isFixed(it) ? "Non serve per questa immagine" : "Solo FLUX.2 Klein sa modificare a comando"; $("#act-other-label").textContent = canSwitch ? `Prova con ${state.models[other].nome.split(" ")[0]}` : "Altro modello"; } function clearStage() { state.current = null; $("#base-bar").hidden = true; $("#next-bar").hidden = true; state.batch = []; $("#stage").dataset.state = "vuoto"; $("#shot-bar").hidden = true; delete $("#shot-bar").dataset.working; } /* ---------- bozze ---------- */ async function refreshDraftCount() { try { const { immagini } = await api("/api/history?limit=200&vista=bozze"); $("#drafts-count").textContent = immagini.length ? String(immagini.length) : ""; } catch { /* server spento */ } } async function discardDraft(item) { await api("/api/discard", { files: [item.file] }); sessionRemove([item.file]); state.batch = state.batch.filter((b) => b.file !== item.file); if (state.batch.length > 1) showCompare(state.batch); else if (state.batch[0]) showShot(state.batch[0]); else clearStage(); syncBase(); refreshDraftCount(); toast("Bozza eliminata"); } async function discardFiles(files, all = false) { const n = all ? Number($("#drafts-count").textContent || 0) : files.length; if (!n) return; if (n > 1 || all) { const ok = await confirmDialog({ title: all ? "Eliminare tutte le bozze?" : `Eliminare ${n} bozze?`, text: "Le bozze eliminate non passano dal cestino: spariscono subito.", confirm: "Elimina", danger: true, }); if (!ok) return; } const { scartate } = await api("/api/discard", all ? { tutto: true } : { files }); if (all) { state.session = state.session.filter((e) => e.item.bozza === false || e.item.esterna); sessionRender(); } else sessionRemove(files); g.selected.clear(); const gone = all ? null : new Set(files); if (state.current?.bozza && (all || gone.has(state.current.file))) { state.batch = all ? [] : state.batch.filter((b) => !gone.has(b.file)); if ($("#stage").dataset.state !== "base") restoreStage(); if (!state.batch.length && state.current?.bozza) clearStage(); } await Promise.all([loadGallery(), refreshDraftCount()]); toast(scartate === 1 ? "Bozza eliminata" : `${scartate} bozze eliminate`); } async function keepFiles(files) { if (!files.length) return; const { salvate } = await api("/api/keep", { files }); sessionSwap(new Map(salvate.map((x) => [fileName(x.file), x]))); g.selected.clear(); await Promise.all([loadGallery(), refreshDraftCount()]); toast(salvate.length === 1 ? "Salvata in galleria" : `${salvate.length} immagini salvate in galleria`); } /* ---------- galleria ---------- */ const g = state.gallery; const serverScope = (f) => (["cestino", "preferite", "bozze"].includes(f) ? f : "galleria"); function galleryVisible() { if (["tutte", "preferite", "cestino", "bozze"].includes(g.filter)) return g.items; return g.items.filter((i) => (i.modalita || "crea") === g.filter); } async function loadGallery(reset = true) { if (reset) { g.offset = 0; g.items = []; g.selected.clear(); } const { immagini } = await api(`/api/history?limit=${PAGE}&offset=${g.offset}&vista=${serverScope(g.filter)}`); g.items = g.items.concat(immagini); g.offset += immagini.length; g.full = immagini.length < PAGE; renderGallery(); } function renderGallery() { const scope = serverScope(g.filter); const inTrash = scope === "cestino"; const inDrafts = scope === "bozze"; document.body.dataset.scope = inTrash ? "cestino" : inDrafts ? "bozze" : "galleria"; $("#gallery-title").textContent = inTrash ? "Cestino" : inDrafts ? "Bozze" : g.filter === "preferite" ? "Preferite" : "Galleria"; $("#trash-note").hidden = !inTrash || g.items.length === 0; $("#drafts-note").hidden = !inDrafts || g.items.length === 0; const box = $("#masonry"); box.replaceChildren(); const items = galleryVisible(); items.forEach((item, index) => { const img = el("img", { src: outputUrl(item.miniatura || item.file), alt: titleOf(item), loading: "lazy" }); img.width = item.larghezza; img.height = item.altezza; const tile = el("div", { class: "tile", tabindex: "0", role: "button", "aria-label": titleOf(item), "aria-selected": String(g.selected.has(item.file)), data: { file: item.file, fav: String(Boolean(item.preferita)) }, onclick: () => (g.selected.size ? toggleSelect(item.file) : openDetail(index)), onkeydown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openDetail(index); } }, }, [ img, el("button", { type: "button", class: "tile-check", "aria-label": "Seleziona", onclick: (e) => { e.stopPropagation(); toggleSelect(item.file); } }, [icon("i-check")]), ...(scope === "galleria" || scope === "preferite" ? [el("button", { type: "button", class: "tile-star", "aria-label": "Preferita", onclick: (e) => { e.stopPropagation(); setFavorite([item], !item.preferita); } }, [icon("i-star")])] : []), el("div", { class: "tile-info" }, [el("p", { class: "tile-title", text: titleOf(item) }), el("p", { class: "tile-meta" }, metaSpans(item))]), ]); box.append(tile); }); const empty = $("#gallery-empty"); empty.hidden = items.length > 0; empty.textContent = inTrash ? "Il cestino è vuoto." : inDrafts ? "Nessuna bozza: quello che generi e non salvi finisce qui per 24 ore." : g.filter === "preferite" ? "Nessuna preferita. Tocca la stella su un'immagine per aggiungerla." : g.filter === "locandina" ? "Nessuna locandina. Componi la prima dalla scheda Locandina." : "Nessuna immagine qui. Torna nello Studio e genera la prima."; $("#more-btn").hidden = g.full; updateSelectionBar(); } function toggleSelect(file) { if (g.selected.has(file)) g.selected.delete(file); else g.selected.add(file); $$(".tile").forEach((t) => t.setAttribute("aria-selected", String(g.selected.has(t.dataset.file)))); updateSelectionBar(); } function updateSelectionBar() { const n = g.selected.size; $("#selection-bar").hidden = n === 0; $("#masonry").dataset.selecting = String(n > 0); $("#selection-count").textContent = n === 1 ? "1 selezionata" : `${n} selezionate`; } async function setFavorite(items, value) { for (const item of items) { const updated = await api("/api/update", { file: item.file, modifiche: { preferita: value } }); Object.assign(item, { preferita: updated.preferita }); } if (g.filter === "preferite" && !value) g.items = g.items.filter((i) => !items.includes(i)); renderGallery(); if (detailItem()) renderDetail(); } async function moveToTrash(files) { if (!files.length) return; await api("/api/trash", { files }); sessionRemove(files); const gone = new Set(files); g.items = g.items.filter((i) => !gone.has(i.file)); g.selected.clear(); renderGallery(); if (state.current && gone.has(state.current.file)) { state.batch = state.batch.filter((b) => !gone.has(b.file)); if ($("#stage").dataset.state !== "base") { if (state.batch.length) restoreStage(); else clearStage(); } } const label = files.length === 1 ? "Spostata nel cestino" : `${files.length} immagini nel cestino`; toast(label, { label: "Annulla", run: () => restoreFiles(files.map((f) => `_cestino/${f}`), true) }); } async function restoreFiles(trashFiles, silent = false) { if (!trashFiles.length) return; const { ripristinate } = await api("/api/restore", { files: trashFiles }); g.selected.clear(); if (document.body.dataset.view === "galleria") await loadGallery(); if (!silent) toast(ripristinate === 1 ? "Immagine ripristinata" : `${ripristinate} immagini ripristinate`); } async function purgeFiles(trashFiles, all = false) { const n = all ? g.items.length : trashFiles.length; if (!n) return; const what = n === 1 ? "questa immagine" : `${n} immagini`; const ok = await confirmDialog({ title: "Eliminare per sempre?", text: `Stai per eliminare ${what} dal cestino. Non si può annullare.`, confirm: "Elimina per sempre", danger: true, }); if (!ok) return; const { eliminate } = await api("/api/purge", all ? { tutto: true } : { files: trashFiles }); g.selected.clear(); await loadGallery(); toast(eliminate === 1 ? "Eliminata per sempre" : `${eliminate} immagini eliminate per sempre`); } /* ---------- conferma a tema ---------- */ function confirmDialog({ title, text, confirm = "Conferma", cancel = "Annulla", danger = false }) { const dlg = $("#confirm"); $("#confirm-title").textContent = title; $("#confirm-text").textContent = text; $("#confirm-no").textContent = cancel; const yes = $("#confirm-yes"); yes.textContent = confirm; yes.classList.toggle("danger", danger); yes.classList.toggle("primary", !danger); dlg.returnValue = ""; dlg.showModal(); $("#confirm-no").focus(); return new Promise((resolve) => dlg.addEventListener("close", () => resolve(dlg.returnValue === "si"), { once: true })); } async function warnBlindModel() { const keep = await confirmDialog({ title: "Z-Image non vede la foto", text: "Ne prende colori e composizione, ma non capisce chi o cosa c'è. Scrivi nel prompt i dettagli che contano, per esempio «uomo con barba lunga, maglietta nera e chitarra rossa». Klein invece capisce la foto da solo.", confirm: "Uso Z-Image", cancel: "Torna a Klein", }); if (!keep) { state.model = "auto"; syncAll(); return; } $("#prompt").focus(); } /* ---------- salvare sul dispositivo ---------- */ // Su iPhone e iPad il foglio di condivisione offre "Salva immagine" e la mette nelle Foto; // altrove si scarica il file vero, letto dall'archivio del browser. const APPLE_TOUCH = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1); const ready = new Map(); async function fileFor(item) { const name = item.file.split("/").pop(); if (ready.has(name)) return ready.get(name); const blob = await window.PixBackend?.readBlob?.(`outputs/${item.file}`) || await fetch(outputUrl(item.file)).then((r) => r.blob()); const file = new File([blob], name, { type: blob.type || "image/png" }); ready.clear(); ready.set(name, file); return file; } function saveFile(file) { if (APPLE_TOUCH && navigator.canShare?.({ files: [file] })) { return navigator.share({ files: [file] }).catch(() => {}); } const url = URL.createObjectURL(file); const a = el("a", { href: url, download: file.name }); document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000); return Promise.resolve(); } function prepareDownload(link, item) { link.href = outputUrl(item.file); link.download = item.file.split("/").pop(); link.onclick = (e) => { e.preventDefault(); const name = item.file.split("/").pop(); const cached = ready.get(name); if (cached) saveFile(cached); else fileFor(item).then(saveFile).catch(() => toast("Non riesco a leggere l'immagine. Riprova.")); }; fileFor(item).catch(() => {}); } /* ---------- scheda dettaglio ---------- */ const detailItem = () => galleryVisible()[g.detailIndex]; function openDetail(index) { g.detailIndex = index; $(".detail-media").classList.remove("zoomed"); renderDetail(); const dlg = $("#detail"); if (!dlg.open) dlg.showModal(); } function renderDetail() { const item = detailItem(); if (!item) { $("#detail").close(); return; } const dlg = $("#detail"); const scope = serverScope(g.filter); dlg.dataset.scope = scope === "preferite" ? "galleria" : scope; $("#detail-img").src = outputUrl(item.file); $("#detail-img").classList.toggle("checker", Boolean(item.trasparente)); $("#d-variant").disabled = isFixed(item); $("#d-style").disabled = !(item.prompt_finale || item.prompt) || isPoster(item) || isView(item); $("#d-story").disabled = isPoster(item); $("#d-views").hidden = !isPrintable(item); $("#d-refine").hidden = !canRefine(item); $("#d-upscale").disabled = !state.tools.ingrandisci; $("#d-cutout").disabled = !state.tools.scontorna || Boolean(item.trasparente); $("#detail-img").alt = titleOf(item); const title = $("#detail-title"); title.value = item.titolo || ""; title.readOnly = scope !== "galleria" && scope !== "preferite"; title.placeholder = item.prompt ? item.prompt.slice(0, 60) : "Senza titolo"; $("#detail-prompt").textContent = item.prompt_finale || item.prompt || ""; $("#detail-meta").replaceChildren(...infoRows(item).flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: v })])); const fav = $("#d-fav"); fav.setAttribute("aria-pressed", String(Boolean(item.preferita))); $("#d-fav-label").textContent = item.preferita ? "Tra le preferite" : "Preferita"; prepareDownload($("#d-download"), item); const total = galleryVisible().length; $("#detail-prev").disabled = g.detailIndex <= 0; $("#detail-next").disabled = g.detailIndex >= total - 1; } function infoRows(item) { if (isPoster(item)) return [["Tipo", "Locandina"], ["Misura", `${item.larghezza}×${item.altezza}`], ["Creata", item.creata]]; return [ ["Modalità", MODE_LABEL[item.modalita] || "Creata"], ...(item.vista ? [["Vista", item.vista]] : []), ["Modello", item.modello_nome || "Z-Image Turbo"], ...(item.maschera ? [["Zona", "Solo la parte dipinta"]] : []), ...(stylesOf(item).length ? [["Stili", styleNames(stylesOf(item))]] : []), ["Misura", `${item.larghezza}×${item.altezza}`], ...(isTool(item) || isView(item) ? [] : [["Qualità", `${item.qualita || "bilanciata"}, ${item.passi} passi`], ["Seme", String(item.seed)]]), ["Creata", `${item.creata}${item.origine === "claude" ? " da Claude" : ""}`], ]; } let infoItem = null; function showInfo(item = state.current) { if (!item) return; infoItem = item; $("#info-prompt").textContent = item.prompt_finale || item.prompt || titleOf(item); $("#info-list").replaceChildren(...infoRows(item).flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: v })])); $("#info-reuse").disabled = isFixed(item); $("#info-dlg").showModal(); } async function saveTitle() { const item = detailItem(); if (!item || !["galleria", "preferite"].includes(serverScope(g.filter))) return; const value = $("#detail-title").value.trim(); if (value === (item.titolo || "")) return; const updated = await api("/api/update", { file: item.file, modifiche: { titolo: value } }); item.titolo = updated.titolo; if (state.current?.file === item.file) state.current.titolo = updated.titolo; renderGallery(); toast(value ? "Titolo salvato" : "Titolo tolto"); } function stepDetail(delta) { const next = g.detailIndex + delta; if (next < 0 || next >= galleryVisible().length) return; saveTitle(); g.detailIndex = next; renderDetail(); } /* ---------- viste ---------- */ function setView(view) { document.body.dataset.view = view; $$(".views button[data-view]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.view === view))); $("#studio").hidden = view !== "studio"; $("#gallery").hidden = view !== "galleria"; $("#poster").hidden = view !== "locandina"; if (view === "galleria") { loadGallery(); refreshDraftCount(); } if (view === "locandina") window.PosterStudio?.show(); } /* ---------- generazione ---------- */ async function readForm() { saveFieldValues(); const campi = {}; for (const id of state.styles) for (const f of templateById(id)?.campi || []) campi[f.id] = state.fieldValues[f.id] || ""; const seed = $("#seed").value.trim(); const payload = { modalita: state.mode, modello: state.model, prompt: $("#prompt").value, stili: ["modifica", "continua"].includes(state.mode) ? [] : state.styles, campi, riferimenti: state.refs.slice(0, MODES[state.mode].maxRefs).map((r) => r.file), formato: state.aspect, qualita: state.quality, fedelta: $("#fidelity-auto").checked ? null : Number($("#fidelity").value), seed: seed === "" ? null : Number(seed), quantita: state.count, traduci: $("#translate").checked, }; if (state.mode === "modifica" && mask.hasStrokes() && payload.prompt.trim() && payload.riferimenti.length) { payload.maschera = await mask.upload(); } return payload; } function runRefine(item) { if (!canRefine(item)) return; state.refineFrom = item; submit({ modalita: "rifinisci", riferimenti: ["outputs/" + item.file], prompt: item.prompt || "", stili: stylesOf(item).filter((id) => templateById(id)), qualita: state.quality, }); } function runViews(item) { if (!item) return; submit({ modalita: "viste", riferimenti: ["outputs/" + item.file], qualita: state.quality }); } function runTool(item, tool) { if (!item) return; submit({ modalita: tool, riferimenti: ["outputs/" + item.file] }); } /* ---------- vettorizza: PNG → SVG ---------- */ const vectorizer = { source: null, style: "colori", svg: "", ticket: 0, open(path, name) { if (!state.tools.vettorizza) { toast("Manca il vettorizzatore: rilancia Installa.command una volta."); return; } this.source = path; this.name = (name || path.split("/").pop()).replace(/\.[a-z0-9]+$/i, ""); $("#vector-dlg").showModal(); this.run(); }, async run() { const ticket = ++this.ticket; const view = $("#vector-view"); view.dataset.state = "lavoro"; $("#vector-download").disabled = true; $("#vector-stats").textContent = ""; try { const res = await api("/api/vectorize", { file: this.source, stile: this.style, trasparente: $("#vector-transparent").checked }); if (ticket !== this.ticket) return; this.svg = res.svg; $("#vector-art").innerHTML = res.svg; $("#vector-stats").textContent = `${res.tracciati} forme · ${res.kb.toLocaleString("it-IT")} KB`; $("#vector-warn").hidden = !res.foto || this.style === "contorno"; $("#vector-download").disabled = false; view.dataset.state = "pronto"; } catch (err) { if (ticket !== this.ticket) return; view.dataset.state = "errore"; $("#vector-stats").textContent = err.message; } }, download() { const url = URL.createObjectURL(new Blob([this.svg], { type: "image/svg+xml" })); const a = Object.assign(document.createElement("a"), { href: url, download: `${this.name}_${this.style}.svg` }); a.click(); setTimeout(() => URL.revokeObjectURL(url), 2000); }, bind() { $("#vector-styles").addEventListener("click", (e) => { const btn = e.target.closest("[role=radio]"); if (!btn || btn.dataset.v === this.style) return; this.style = btn.dataset.v; radio($("#vector-styles"), "v", this.style); this.run(); }); $("#vector-transparent").addEventListener("change", () => this.run()); $("#vector-dark").addEventListener("change", (e) => $("#vector-view").classList.toggle("dark", e.target.checked)); $("#vector-close").addEventListener("click", () => $("#vector-dlg").close()); $("#vector-download").addEventListener("click", () => this.download()); $("#vector-dlg").addEventListener("close", () => { this.ticket++; $("#vector-art").innerHTML = ""; }); }, }; /* ---------- prompt migliorato: inglese per il modello, italiano per te ---------- */ const bilingual = { on: false, syncedIt: "", syncedEn: "", open(en, it) { this.on = true; $("#prompt").value = en; $("#prompt-it").value = it; this.syncedIt = it; this.syncedEn = en; $("#prompt-area").classList.add("bilingual"); this.check(); autosize(); }, close() { this.on = false; $("#prompt-area").classList.remove("bilingual"); $("#prompt-it").value = ""; autosize(); }, check() { $("#sync-en").hidden = !this.on || $("#prompt-it").value.trim() === this.syncedIt.trim(); $("#sync-it").hidden = !this.on || $("#prompt").value.trim() === this.syncedEn.trim(); }, async sync(direction) { const from = direction === "en" ? $("#prompt-it") : $("#prompt"); const to = direction === "en" ? $("#prompt") : $("#prompt-it"); const btn = direction === "en" ? $("#sync-en") : $("#sync-it"); btn.textContent = "Traduco…"; btn.disabled = true; try { const { testo } = await api("/api/translate", { testo: from.value, verso: direction }); to.value = testo; this.syncedIt = $("#prompt-it").value; this.syncedEn = $("#prompt").value; autosize(); } catch (e) { $("#form-error").textContent = e.message; } finally { btn.textContent = direction === "en" ? "Aggiorna l'inglese" : "Aggiorna l'italiano"; btn.disabled = false; this.check(); } }, wire() { $("#prompt-it").addEventListener("input", () => { this.check(); autosize(); }); $("#prompt").addEventListener("input", () => this.check()); $("#sync-en").addEventListener("click", () => this.sync("en")); $("#sync-it").addEventListener("click", () => this.sync("it")); $("#bilingual-close").addEventListener("click", () => this.close()); }, }; async function enhancePrompt() { const field = $("#prompt"); const before = bilingual.on ? $("#prompt-it").value : field.value; if (!before.trim()) { $("#form-error").textContent = "Scrivi prima un'idea, anche in italiano: la trasformo in un prompt dettagliato."; return; } const btn = $("#enhance-btn"); btn.setAttribute("aria-busy", "true"); $("#form-error").textContent = ""; try { const { prompt, italiano } = await api("/api/enhance", { prompt: before, modalita: state.mode }); bilingual.open(prompt, italiano || ""); toast("A sinistra in italiano, a destra quello che va al modello. Correggi pure, poi genera", { label: "Annulla", run: () => { bilingual.close(); field.value = before; autosize(); }, }); } catch (e) { $("#form-error").textContent = e.message; } finally { btn.removeAttribute("aria-busy"); } } function payloadFromItem(item, overrides = {}) { return { modalita: item.modalita || "crea", modello: item.modello || "auto", prompt: item.prompt, stili: stylesOf(item).filter((id) => templateById(id)), campi: item.campi || {}, riferimenti: item.riferimenti || [], maschera: item.maschera || null, formato: item.formato, qualita: item.qualita || "bilanciata", fedelta: item.fedelta_auto ? null : item.fedelta ?? null, seed: item.seed, quantita: 1, ...overrides, }; } const EMPTY_PROMPT = { crea: "Scrivi cosa vuoi vedere.", continua: "Scrivi la nuova scena.", modifica: "Scrivi cosa cambiare." }; $("#prompt").addEventListener("input", () => { if (Object.values(EMPTY_PROMPT).includes($("#form-error").textContent)) $("#form-error").textContent = ""; }); async function submitFromComposer() { if (state.busy) return; const missing = EMPTY_PROMPT[state.mode]; if (missing && !$("#prompt").value.trim()) { $("#form-error").textContent = missing; $("#prompt").focus(); return; } try { $("#form-error").textContent = ""; submit(await readForm(), true); } catch (e) { $("#form-error").textContent = e.message; } } async function submit(payload, fromComposer = false) { if (state.busy) return; const err = $("#form-error"); err.textContent = ""; state.busy = true; $("#generate-btn").disabled = true; try { const job = await api("/api/generate", payload); if (fromComposer && payload.prompt.trim()) { state.lastPrompt = payload.prompt; $("#prompt").value = ""; bilingual.close(); autosize(); } setView("studio"); showWorking(job); track(job.id); } catch (e) { err.textContent = e.message; state.busy = false; $("#generate-btn").disabled = false; } } function finishJob() { state.busy = false; $("#generate-btn").disabled = false; refreshStatus(); refreshDraftCount(); } function track(jobId) { clearInterval(state.polling); state.polling = setInterval(async () => { let job; try { job = await api(`/api/jobs/${jobId}`); } catch { return; } if (job.status === "fatto" || job.status === "errore") { clearInterval(state.polling); finishJob(); if (job.status === "errore") { if (job.error_code === "quota") window.PixOnline?.quota(job.retry_in); else $("#form-error").textContent = job.error; if (state.lastPrompt && !$("#prompt").value && !Object.values(EMPTY_PROMPT).includes(job.error)) { $("#prompt").value = state.lastPrompt; autosize(); } if (state.mode !== "crea" && state.refs[0]) syncBase(); else restoreStage(); return; } const n = job.results.length; sessionAdd(job.results, job.id); if (job.request.mode === "rifinisci" && state.refineFrom) { state.batch = [state.refineFrom, ...job.results]; state.refineFrom = null; showCompare(state.batch, true); toast("Prima e dopo: tieni quella che ti piace di più"); return; } state.batch = job.results; if (n > 1) showCompare(job.results, true); else showShot(job.results[0], true); if (job.results[0]?.nota) { toast(job.results[0].nota); return; } if (job.request.mode === "viste") { toast("Viste pronte: salva quelle buone e dalle a Tripo, Meshy o Hunyuan3D insieme alla frontale"); return; } toast(n > 1 ? `${n} immagini pronte in ${job.elapsed} s: salva quelle che ti piacciono` : `Pronta in ${job.elapsed} s`); return; } showWorking(job); if (job.status === "caricamento") refreshStatus(); }, 600); } /* ---------- azioni sullo scatto ---------- */ function reuse(item = state.current) { if (!item || isFixed(item)) return; setView("studio"); state.refs = (item.riferimenti || []).map((file) => ({ file })); state.model = item.modello || "auto"; state.styles = stylesOf(item).filter((id) => templateById(id)); state.fieldValues = { ...(item.campi || {}) }; state.quality = item.qualita || "bilanciata"; radio($("#quality"), "v", state.quality); $("#fidelity-auto").checked = item.fedelta_auto !== false || !item.fedelta; if (item.fedelta) $("#fidelity").value = item.fedelta; $("#fidelity").dispatchEvent(new Event("input")); $("#prompt").value = item.prompt || ""; $("#seed").value = item.seed; setMode(item.modalita || "crea"); renderStyleState(); state.aspectTouched = true; renderAspects(); selectAspect(item.formato); autosize(); if (state.mode === "crea") showShot(item); toast("Impostazioni caricate, seme compreso"); } function openInPoster(item) { if (!item) return; setView("locandina"); window.PosterStudio?.setBackground("outputs/" + item.file); } /* ---------- eventi ---------- */ function autosize() { for (const t of [$("#prompt"), $("#prompt-it")]) { t.style.height = "auto"; t.style.height = `${Math.min(bilingual.on ? 220 : 180, t.scrollHeight)}px`; } } function wire() { $("#generate-btn").addEventListener("click", () => submitFromComposer()); document.addEventListener("keydown", (e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && document.body.dataset.view === "studio" && !document.querySelector("dialog[open]:not(#guide)")) { e.preventDefault(); submitFromComposer(); } if ($("#detail").open && document.activeElement !== $("#detail-title")) { if (e.key === "ArrowLeft") stepDetail(-1); if (e.key === "ArrowRight") stepDetail(1); } }); const prompt = $("#prompt"); prompt.addEventListener("input", autosize); prompt.addEventListener("keydown", (e) => { if (e.key === "ArrowUp" && !prompt.value && state.lastPrompt) { e.preventDefault(); prompt.value = state.lastPrompt; autosize(); } }); $$(".modes [role=tab]").forEach((t) => t.addEventListener("click", () => setMode(t.dataset.mode))); $$(".views button[data-view]").forEach((b) => b.addEventListener("click", () => setView(b.dataset.view))); $("#file-input").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; }); $("#empty-file").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; }); const stage = $("#stage"); let depth = 0; const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes("Files"); document.addEventListener("dragenter", (e) => { if (hasFiles(e) && document.body.dataset.view === "studio") { depth++; stage.classList.add("dragging"); } }); document.addEventListener("dragleave", () => { depth = Math.max(0, depth - 1); if (!depth) stage.classList.remove("dragging"); }); document.addEventListener("dragover", (e) => { if (hasFiles(e)) e.preventDefault(); }); document.addEventListener("drop", (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth = 0; stage.classList.remove("dragging"); if (document.body.dataset.view === "locandina") return; setView("studio"); addFiles(e.dataTransfer.files); }); document.addEventListener("paste", (e) => { if (document.body.dataset.view !== "studio") return; const files = [...(e.clipboardData?.files || [])].filter((f) => f.type.startsWith("image/")); if (files.length) { e.preventDefault(); addFiles(files); } }); $("#quality").addEventListener("click", (e) => { const b = e.target.closest("[data-v]"); if (!b) return; state.quality = b.dataset.v; radio($("#quality"), "v", state.quality); updateQualityNote(); renderPills(); }); $("#count").addEventListener("click", (e) => { const b = e.target.closest("[data-v]"); if (!b) return; state.count = Number(b.dataset.v); radio($("#count"), "v", b.dataset.v); renderPills(); }); const fid = $("#fidelity"); const fidAuto = $("#fidelity-auto"); const fidNote = () => { const v = Number(fid.value); const auto = fidAuto.checked; $("#fidelity-manual").hidden = auto; $("#fidelity-auto-note").hidden = !auto; $("#fidelity-out").textContent = auto ? "Auto" : v.toFixed(2); $("#fidelity-note").textContent = v <= 0.25 ? "Molto libero: tiene colori e posa, ridisegna il resto." : v <= 0.4 ? "Equilibrato: riconoscibile, ma con spazio per cambiare." : v <= 0.6 ? "Fedele: cambia lo stile, forme e proporzioni restano quelle." : "Quasi identica: solo un ritocco di stile."; }; fid.addEventListener("input", fidNote); fidAuto.addEventListener("change", fidNote); fidNote(); $("#seed-dice").addEventListener("click", () => ($("#seed").value = Math.floor(Math.random() * 2147483647))); // scatto nello studio $("#act-variant").addEventListener("click", () => state.current && submit(payloadFromItem(state.current, { seed: null }))); $("#act-other").addEventListener("click", () => { const it = state.current; if (it) submit(payloadFromItem(it, { modello: otherModel(it.modello || "z-image") })); }); $("#act-edit").addEventListener("click", () => state.current && useAsRef(state.current, "modifica")); $("#act-restyle").addEventListener("click", () => state.current && useAsRef(state.current, "ristila")); $("#act-reuse").addEventListener("click", () => reuse()); $("#act-info").addEventListener("click", () => showInfo()); $("#info-copy").addEventListener("click", async () => { if (!infoItem) return; await navigator.clipboard.writeText(infoItem.prompt_finale || infoItem.prompt || ""); $("#info-dlg").close(); toast("Prompt completo copiato"); }); $("#info-reuse").addEventListener("click", () => { $("#info-dlg").close(); if ($("#detail").open) $("#detail").close(); reuse(infoItem); }); $("#act-upscale").addEventListener("click", () => runTool(state.current, "ingrandisci")); $("#act-cutout").addEventListener("click", () => runTool(state.current, "scontorna")); $("#act-poster").addEventListener("click", () => openInPoster(state.current)); $("#act-vector").addEventListener("click", () => state.current && vectorizer.open("outputs/" + state.current.file, state.current.file)); $("#b-vector").addEventListener("click", () => baseRef() && vectorizer.open(baseRef(), state.refs[0]?.name)); vectorizer.bind(); $("#act-views").addEventListener("click", () => runViews(state.current)); $("#act-refine").addEventListener("click", () => runRefine(state.current)); const baseRef = () => state.refs[0]?.file; $("#b-upscale").addEventListener("click", () => baseRef() && submit({ modalita: "ingrandisci", riferimenti: [baseRef()] })); $("#b-cutout").addEventListener("click", () => baseRef() && submit({ modalita: "scontorna", riferimenti: [baseRef()] })); $("#b-poster").addEventListener("click", () => { if (baseRef()) { setView("locandina"); window.PosterStudio?.setBackground(baseRef()); } }); $("#enhance-btn").addEventListener("click", enhancePrompt); const translate = $("#translate"); translate.checked = prefs.get("traduci", true); translate.addEventListener("change", () => prefs.set("traduci", translate.checked)); $("#act-copy").addEventListener("click", async () => { if (!state.current) return; await navigator.clipboard.writeText(state.current.prompt_finale || state.current.prompt); toast("Prompt completo copiato"); }); $("#act-trash").addEventListener("click", () => { const it = state.current; if (!it) return; if (it.bozza) discardDraft(it); else moveToTrash([it.file]); }); $("#act-save").addEventListener("click", () => state.current && saveItems([state.current])); $("#act-save-all").addEventListener("click", () => saveItems(state.batch)); $("#act-back").addEventListener("click", () => showCompare(state.batch)); // stili salvati $("#sd-save").addEventListener("click", saveStyleDialog); $("#sd-delete").addEventListener("click", deleteStyleDialog); $("#style-form").addEventListener("submit", (e) => { if (e.submitter?.value !== "no") { e.preventDefault(); saveStyleDialog(); } }); $("#sd-from-prompt").addEventListener("click", () => { const text = $("#prompt").value.trim() || state.lastPrompt; if (text) $("#sd-text").value = text; else $("#sd-error").textContent = "Nel campo del prompt non c'è ancora niente."; }); // galleria $("#filters").addEventListener("click", (e) => { const b = e.target.closest("[data-f]"); if (!b) return; const was = serverScope(g.filter); g.filter = b.dataset.f; radio($("#filters"), "f", g.filter); g.selected.clear(); if (serverScope(g.filter) !== was) loadGallery(); else renderGallery(); }); $("#more-btn").addEventListener("click", () => loadGallery(false)); $("#empty-trash").addEventListener("click", () => purgeFiles([], true)); $("#drafts-clear").addEventListener("click", () => discardFiles([], true)); $("#sel-clear").addEventListener("click", () => { g.selected.clear(); renderGallery(); }); $("#sel-trash").addEventListener("click", () => moveToTrash([...g.selected])); $("#sel-keep").addEventListener("click", () => keepFiles([...g.selected])); $("#sel-discard").addEventListener("click", () => discardFiles([...g.selected])); $("#sel-fav").addEventListener("click", () => { const items = g.items.filter((i) => g.selected.has(i.file)); const value = !items.every((i) => i.preferita); g.selected.clear(); setFavorite(items, value); }); $("#sel-restore").addEventListener("click", () => restoreFiles([...g.selected])); $("#sel-purge").addEventListener("click", () => purgeFiles([...g.selected])); // scheda dettaglio const dlg = $("#detail"); $("#detail-close").addEventListener("click", () => dlg.close()); dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); dlg.addEventListener("close", saveTitle); $("#detail-title").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); saveTitle(); e.target.blur(); } }); $("#detail-title").addEventListener("blur", saveTitle); $("#detail-img").addEventListener("click", () => $(".detail-media").classList.toggle("zoomed")); $("#detail-prev").addEventListener("click", () => stepDetail(-1)); $("#detail-next").addEventListener("click", () => stepDetail(1)); const fromDetail = (fn) => () => { const it = detailItem(); if (!it) return; dlg.close(); fn(it); }; const openStudio = (it) => { setView("studio"); state.batch = [it]; if (state.mode !== "crea" && state.refs.length) setMode("crea"); showShot(it); }; $("#d-open").addEventListener("click", fromDetail(openStudio)); $("#d-open-draft").addEventListener("click", fromDetail(openStudio)); $("#d-keep").addEventListener("click", fromDetail((it) => keepFiles([it.file]))); $("#d-discard").addEventListener("click", fromDetail((it) => discardFiles([it.file]))); $("#d-edit").addEventListener("click", fromDetail((it) => useAsRef(it, "modifica"))); $("#d-restyle").addEventListener("click", fromDetail((it) => useAsRef(it, "ristila"))); $("#d-variant").addEventListener("click", fromDetail((it) => submit(payloadFromItem(it, { seed: null })))); $("#d-upscale").addEventListener("click", fromDetail((it) => runTool(it, "ingrandisci"))); $("#d-cutout").addEventListener("click", fromDetail((it) => runTool(it, "scontorna"))); $("#d-poster").addEventListener("click", fromDetail(openInPoster)); $("#d-vector").addEventListener("click", () => { const it = detailItem(); if (it) vectorizer.open("outputs/" + it.file, it.file); }); $("#d-views").addEventListener("click", fromDetail(runViews)); $("#d-refine").addEventListener("click", fromDetail(runRefine)); $("#d-story").addEventListener("click", fromDetail((it) => useAsRef(it, "continua"))); $("#d-style").addEventListener("click", fromDetail((it) => openStyleDialog(null, it))); $("#d-fav").addEventListener("click", () => { const it = detailItem(); if (it) setFavorite([it], !it.preferita); }); $("#d-trash").addEventListener("click", fromDetail((it) => moveToTrash([it.file]))); $("#d-restore").addEventListener("click", fromDetail((it) => restoreFiles([it.file]))); $("#d-purge").addEventListener("click", fromDetail((it) => purgeFiles([it.file]))); mask.init(); brush.wire(); shotMenu.wire(); bilingual.wire(); $("#next-use").addEventListener("click", continueFromCurrent); $("#next-stay").addEventListener("click", () => { state.nextDismissed = state.current?.file || ""; state.current = null; $("#stage").dataset.state = ""; syncBase(); updateNextBar(); sessionRender(); toast("Sei sull'originale: la nuova versione resta nella colonna Sessione a sinistra"); }); $("#session-clear").addEventListener("click", () => { state.session = []; sessionRender(); }); document.addEventListener("keydown", (e) => { if (document.body.dataset.view !== "studio" || document.querySelector("dialog[open]:not(#guide)") || brush.active) return; if (e.target.closest("input, textarea, select")) return; if (e.key === "ArrowLeft" || e.key === "ArrowUp") { e.preventDefault(); sessionStep(-1); } if (e.key === "ArrowRight" || e.key === "ArrowDown") { e.preventDefault(); sessionStep(1); } }); } // Le viste restano invisibili finché non sono composte: niente salti di layout all'apertura. function reveal() { requestAnimationFrame(() => document.body.removeAttribute("data-booting")); } setTimeout(reveal, 8000); async function init() { try { await boot(); } finally { await window.PixI18n?.ready?.catch(() => {}); reveal(); } } async function boot() { if (window.PixBackend) await window.PixBackend.ready; wire(); const s = await refreshStatus(); if (s) { state.aspects = s.formati; state.tools = s.strumenti || {}; if (!s.traduttore) $("#enhance-btn").hidden = true; state.models = s.modelli; state.auto = s.automatico; } state.templates = (await api("/api/templates")).template; renderTemplates(); setMode("crea"); refreshDraftCount(); setInterval(refreshStatus, 10000); } window.PixRick = { api, toast, el, icon, radio, prefs, mediaUrl, outputUrl, confirmDialog, setView, refreshDraftCount, showInfo, saveFile, detailItem: () => detailItem() }; init();