pixrick / web /mobile.js
Algorick's picture
63284da8f919
4e63905 verified
Raw History Blame Contribute Delete
14.9 kB
/* Telefono: barra in basso con menu, fogli dal basso, tastiera, confronto a scorrimento, tasto indietro. */
(() => {
"use strict";
const $ = (s) => document.querySelector(s);
const $$ = (s) => [...document.querySelectorAll(s)];
const phone = window.matchMedia("(max-width: 760px)");
const body = document.body;
const { el, icon } = window.PixRick || {};
/* ---------- foglio impostazioni ---------- */
const sheet = $("#inspector");
const scrim = $("#inspector-scrim");
function openSheet() {
if (!phone.matches || body.dataset.sheet === "open") return;
body.dataset.sheet = "open";
scrim.hidden = false;
sheet.setAttribute("role", "dialog");
sheet.setAttribute("aria-modal", "true");
sheet.scrollTop = 0;
history.pushState({ ...history.state, sheet: true }, "");
}
function closeSheet(fromHistory = false) {
if (body.dataset.sheet !== "open") return;
delete body.dataset.sheet;
scrim.hidden = true;
sheet.removeAttribute("role");
sheet.removeAttribute("aria-modal");
if (!fromHistory && history.state?.sheet) history.back();
}
const focusPanel = window.focusPanel;
if (typeof focusPanel === "function") {
window.focusPanel = (id) => {
openSheet();
requestAnimationFrame(() => focusPanel(id));
};
}
$("#settings-btn").addEventListener("click", openSheet);
$("#inspector-close").addEventListener("click", () => closeSheet());
scrim.addEventListener("click", () => closeSheet());
document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeSheet(); });
$("#generate-btn").addEventListener("click", () => closeSheet(), true);
phone.addEventListener("change", () => { if (!phone.matches) closeSheet(); });
let startY = null;
const head = $(".inspector-head");
head.addEventListener("touchstart", (e) => { startY = e.touches[0].clientY; }, { passive: true });
head.addEventListener("touchmove", (e) => {
if (startY === null) return;
sheet.style.transform = `translateY(${Math.max(0, e.touches[0].clientY - startY)}px)`;
}, { passive: true });
head.addEventListener("touchend", (e) => {
const dy = startY === null ? 0 : e.changedTouches[0].clientY - startY;
startY = null;
sheet.style.transform = "";
if (dy > 80) closeSheet();
});
/* ---------- riepilogo delle impostazioni sul pulsante ---------- */
const summary = $("#settings-summary");
const label = $("#settings-btn .settings-text small");
function syncSummary() {
const pills = $$("#pills .pill");
const find = (re) => pills.find((p) => re.test(p.querySelector(".pill-k")?.textContent.trim() || ""));
const zone = find(/^(Zona|Area)$/);
if (zone) {
const on = zone.classList.contains("on");
label.textContent = "Zona e impostazioni";
summary.textContent = on ? "Solo la parte dipinta" : "Dipingi una zona";
$("#settings-btn").classList.toggle("is-empty", !on);
return;
}
const value = find(/^(Stile|Style)$/)?.querySelector(".pill-v")?.textContent.trim() || "";
const none = !value || /^(Nessuno|None|Come la foto|Like the photo)$/.test(value);
label.textContent = "Stile e impostazioni";
summary.textContent = none ? "Scegli uno stile" : value;
$("#settings-btn").classList.toggle("is-empty", none);
}
new MutationObserver(syncSummary).observe($("#pills"), { childList: true, subtree: true, characterData: true });
syncSummary();
/* ---------- menu nella barra in basso ---------- */
const menu = $("#account-menu");
const navMenu = $("#nav-menu");
const menuScrim = document.createElement("div");
menuScrim.className = "inspector-scrim menu-scrim";
menuScrim.hidden = true;
menuScrim.style.zIndex = "44";
body.append(menuScrim);
navMenu.addEventListener("click", (e) => {
e.stopPropagation();
$("#menu-btn").click();
});
menuScrim.addEventListener("click", () => { menu.hidden = true; });
new MutationObserver(() => {
const open = !menu.hidden;
navMenu.setAttribute("aria-expanded", String(open));
menuScrim.hidden = !open || !phone.matches;
if (open && phone.matches && !history.state?.menu) history.pushState({ ...history.state, menu: true }, "");
if (!open && history.state?.menu) history.back();
}).observe(menu, { attributes: true, attributeFilter: ["hidden"] });
const langButtons = $$(".menu-lang button");
function syncLang() {
const lang = window.PixI18n?.lang || document.documentElement.lang || "it";
langButtons.forEach((b) => b.setAttribute("aria-checked", String(b.dataset.lang === lang)));
}
langButtons.forEach((b) => b.addEventListener("click", async (e) => {
e.stopPropagation();
await window.PixI18n?.set?.(b.dataset.lang);
syncLang();
}));
new MutationObserver(syncLang).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
window.PixI18n?.ready?.then(syncLang);
/* ---------- tastiera: lo studio si stringe sopra di lei ---------- */
const vv = window.visualViewport;
function fitViewport() {
if (!vv || !phone.matches) return;
const keyboard = window.innerHeight - vv.height > 140 && document.activeElement?.matches("textarea, input[type=text], input:not([type])");
if (keyboard) {
body.dataset.keyboard = "";
document.documentElement.style.setProperty("--app-h", `${vv.height}px`);
$$(".studio, .poster, .gallery").forEach((m) => { m.style.top = `${vv.offsetTop}px`; m.style.height = `${vv.height}px`; m.style.bottom = "auto"; });
} else if ("keyboard" in body.dataset) {
delete body.dataset.keyboard;
document.documentElement.style.removeProperty("--app-h");
$$(".studio, .poster, .gallery").forEach((m) => { m.style.top = ""; m.style.height = ""; m.style.bottom = ""; });
}
}
vv?.addEventListener("resize", fitViewport);
vv?.addEventListener("scroll", fitViewport);
document.addEventListener("focusout", () => setTimeout(fitViewport, 120));
/* ---------- confronto: indicatore della foto visibile ---------- */
const compare = $("#compare");
const count = $("#compare-count");
function syncDots() {
const cards = compare.children.length;
if (count.children.length !== cards) count.replaceChildren(...Array.from({ length: cards }, () => document.createElement("i")));
const index = compare.clientWidth ? Math.round(compare.scrollLeft / compare.clientWidth) : 0;
[...count.children].forEach((dot, i) => dot.setAttribute("aria-current", String(i === index)));
}
compare.addEventListener("scroll", () => requestAnimationFrame(syncDots), { passive: true });
new MutationObserver(() => { compare.scrollLeft = 0; syncDots(); }).observe(compare, { childList: true });
/* ---------- "Altro": tutte le azioni sull'immagine, spiegate ---------- */
const ACTIONS = [
["act-download", "i-download", "Salva sul dispositivo", "Nelle Foto del telefono o tra i download"],
null,
["act-variant", "i-shuffle", "Varia", "Stesse impostazioni, risultato nuovo"],
["act-edit", "i-wand", "Modifica", "Cambiala a comando, anche solo in una zona"],
["act-restyle", "i-palette", "Ristila", "Stessa composizione, stile diverso"],
["m-story", "i-book", "Continua la storia", "Nuova scena con gli stessi personaggi"],
["act-other", "i-swap", null, "Stesse impostazioni con l'altro modello"],
["act-refine", "i-sparkle", "Rifinisci con Z-Image", "Più dettaglio e realismo, vedi prima e dopo"],
["act-upscale", "i-expand", "Ingrandisci ×2", "Raddoppia la risoluzione"],
["act-cutout", "i-scissors", "Scontorna", "Toglie lo sfondo e lascia il soggetto"],
["act-vector", "i-vector", "Vettorizza in SVG", "Per stampa, taglio e loghi"],
["act-poster", "i-poster", "Usa per una locandina", "Come sfondo, con testi e logo"],
["act-views", "i-layers", "Viste 3D", "Lato e retro, per Tripo, Meshy o Hunyuan3D"],
["m-style", "i-bookmark", "Salva come stile", "Per rifare immagini con questo aspetto"],
null,
["act-info", "i-info", "Info sull'immagine", "Modello, misura, seme e prompt completo"],
["act-copy", "i-copy", "Copia il prompt", null],
["act-reuse", "i-reuse", "Riusa le impostazioni", null],
null,
["act-trash", "i-trash", null, null, "danger"],
];
const DETAIL_ACTIONS = [
["d-download", "i-download", "Salva sul dispositivo", "Nelle Foto del telefono o tra i download"],
null,
["d-edit", "i-wand", "Modifica", "Cambiala a comando, anche solo in una zona"],
["d-restyle", "i-palette", "Ristila", "Stessa composizione, stile diverso"],
["d-variant", "i-shuffle", "Varia", "Stesse impostazioni, risultato nuovo"],
["d-story", "i-book", "Continua la storia", "Nuova scena con gli stessi personaggi"],
["d-refine", "i-sparkle", "Rifinisci con Z-Image", "Più dettaglio e realismo, vedi prima e dopo"],
["d-upscale", "i-expand", "Ingrandisci ×2", "Raddoppia la risoluzione"],
["d-cutout", "i-scissors", "Scontorna", "Toglie lo sfondo e lascia il soggetto"],
["d-vector", "i-vector", "Vettorizza in SVG", "Per stampa, taglio e loghi"],
["d-poster", "i-poster", "Usa per una locandina", "Come sfondo, con testi e logo"],
["d-views", "i-layers", "Viste 3D", "Lato e retro, per Tripo, Meshy o Hunyuan3D"],
["d-style", "i-bookmark", "Salva come stile", "Per rifare immagini con questo aspetto"],
["d-fav", "i-star", null, null],
null,
["d-info", "i-info", "Info sull'immagine", "Modello, misura, seme e prompt completo"],
null,
["d-trash", "i-trash", null, null, "danger"],
["d-discard", "i-trash", null, null, "danger"],
];
const moreDlg = $("#more-dlg");
/** Chiude il foglio e poi esegue l'azione, dopo che il tasto indietro ha sistemato la cronologia. */
function afterClose(dlg, action) {
let done = false;
const go = () => { if (!done) { done = true; action(); } };
window.addEventListener("popstate", () => setTimeout(go, 0), { once: true });
setTimeout(go, 400);
dlg.close();
}
function openActions(list, run = (target) => target.click()) {
const items = [];
for (const entry of list) {
if (!entry) {
if (items.length && !items.at(-1).classList.contains("action-sep")) items.push(el("span", { class: "action-sep", "aria-hidden": "true" }));
continue;
}
const [id, ico, label, note, tone] = entry;
const target = document.getElementById(id) || (id === "d-info" ? { virtual: true } : null);
if (!target || target.hidden || target.disabled) continue;
if (!target.virtual && target.closest("[hidden]")) continue;
if (target.dataset?.scope && target.dataset.scope !== $("#detail").dataset.scope) continue;
const text = label || target.querySelector?.("span")?.textContent.trim() || target.textContent?.trim() || target.title;
const children = [icon(ico), el("b", { text })];
if (note) children.push(el("small", { text: note }));
const item = el("button", { type: "button", class: `action-item${tone ? ` ${tone}` : ""}` }, children);
item.addEventListener("click", () => {
if (target.tagName === "A") {
target.click();
moreDlg.close();
return;
}
afterClose(moreDlg, () => run(target, id));
});
items.push(item);
}
while (items.length && items.at(-1).classList.contains("action-sep")) items.pop();
$("#more-list").replaceChildren(...items);
moreDlg.showModal();
}
const openMore = () => openActions(ACTIONS);
$("#d-more").addEventListener("click", () => openActions(DETAIL_ACTIONS, (target, id) => {
if (id === "d-info") window.PixRick?.showInfo(window.PixRick.detailItem());
else target.click();
}));
/* scorrere tra le immagini del dettaglio con il dito */
const media = $(".detail-media");
let swipeX = null;
media.addEventListener("touchstart", (e) => { swipeX = media.classList.contains("zoomed") ? null : e.touches[0].clientX; }, { passive: true });
media.addEventListener("touchend", (e) => {
if (swipeX === null) return;
const dx = e.changedTouches[0].clientX - swipeX;
swipeX = null;
if (Math.abs(dx) < 50) return;
const btn = $(dx < 0 ? "#detail-next" : "#detail-prev");
if (!btn.disabled) btn.click();
});
$("#act-more").addEventListener("click", openMore);
$("#shot-img").addEventListener("click", (e) => {
if (!phone.matches) return;
e.stopImmediatePropagation();
openMore();
}, true);
/* ---------- locandina: una scheda alla volta, anteprima sempre visibile ---------- */
const posterTabs = $$("#poster-tabs [data-tab]");
function showTab(tab) {
posterTabs.forEach((b) => b.setAttribute("aria-selected", String(b.dataset.tab === tab)));
$$(".poster-scroll > .panel").forEach((p) => p.toggleAttribute("data-active", p.dataset.tab === tab));
$(".poster-scroll").scrollTop = 0;
}
posterTabs.forEach((b) => b.addEventListener("click", () => showTab(b.dataset.tab)));
document.addEventListener("poster:campo", () => { if (phone.matches) showTab("testi"); });
showTab("testi");
/* ---------- tasto indietro: viste, fogli e finestre ---------- */
const setView = window.setView;
if (typeof setView === "function") {
window.setView = (view, fromHistory = false) => {
const changed = body.dataset.view !== view;
setView(view);
menu.hidden = true;
if (changed && !fromHistory) history.pushState({ view }, "", view === "studio" ? location.pathname : `#${view}`);
};
const initial = location.hash.slice(1);
history.replaceState({ view: ["galleria", "locandina"].includes(initial) ? initial : "studio" }, "");
if (["galleria", "locandina"].includes(initial)) requestAnimationFrame(() => window.setView(initial, true));
}
const dialogs = ["#detail", "#style-dlg", "#vector-dlg", "#picker", "#guide", "#info-dlg", "#more-dlg"].map((s) => $(s)).filter(Boolean);
for (const dlg of dialogs) {
new MutationObserver(() => {
if (dlg.open && history.state?.dialog !== dlg.id) history.pushState({ ...history.state, dialog: dlg.id }, "");
if (!dlg.open && history.state?.dialog === dlg.id && !dlg.dataset.backing) history.back();
delete dlg.dataset.backing;
}).observe(dlg, { attributes: true, attributeFilter: ["open"] });
}
window.addEventListener("popstate", (e) => {
const state = e.state || {};
if (!menu.hidden && !state.menu) { menu.hidden = true; return; }
if (body.dataset.sheet === "open" && !state.sheet) { closeSheet(true); return; }
const open = dialogs.find((d) => d.open && d.id !== state.dialog);
if (open) {
open.dataset.backing = "1";
open.close();
return;
}
const view = state.view || "studio";
if (body.dataset.view !== view && typeof window.setView === "function") window.setView(view, true);
});
})();