File size: 14,869 Bytes
fdaac23
23852d4
 
 
 
fdaac23
23852d4
fdaac23
 
23852d4
3477b96
 
fdaac23
 
 
3477b96
fdaac23
 
23852d4
 
 
fdaac23
3477b96
23852d4
 
3477b96
fdaac23
 
23852d4
 
 
3477b96
23852d4
 
 
 
 
3477b96
23852d4
 
 
 
3477b96
 
 
 
fdaac23
3477b96
23852d4
 
 
 
 
 
3477b96
23852d4
 
 
 
 
3477b96
 
 
fdaac23
 
 
b61c694
fdaac23
b61c694
 
 
 
 
 
 
 
 
 
 
fdaac23
b61c694
fdaac23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e63905
 
fdaac23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac35f84
4e63905
 
ac35f84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdaac23
ac35f84
 
 
 
 
 
 
 
 
fdaac23
ac35f84
fdaac23
 
 
 
 
ac35f84
fdaac23
ac35f84
 
 
fdaac23
 
4e63905
fdaac23
4e63905
 
 
 
 
ac35f84
fdaac23
 
 
 
 
 
3477b96
ac35f84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdaac23
 
 
 
 
 
3477b96
b61c694
 
 
 
 
 
 
 
 
 
 
 
fdaac23
3477b96
 
 
 
fdaac23
3477b96
fdaac23
3477b96
 
 
 
 
 
 
fdaac23
3477b96
 
 
 
 
 
 
 
 
 
fdaac23
 
3477b96
 
 
 
 
 
 
fdaac23
23852d4
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/* 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);
  });
})();