File size: 90,570 Bytes
8af7605 32d5440 8af7605 9784e1d 8af7605 ac35f84 8af7605 32d5440 8af7605 b61c694 8af7605 b61c694 8af7605 b61c694 8af7605 b61c694 8af7605 b9efad2 8af7605 fdaac23 8af7605 b9efad2 8af7605 4e63905 8af7605 fdaac23 8af7605 fdaac23 8af7605 fdaac23 8af7605 b9efad2 8af7605 b9efad2 8af7605 ac35f84 8af7605 ac35f84 8af7605 ac35f84 4e63905 8af7605 fdaac23 8af7605 4e63905 8af7605 fdaac23 ac35f84 fdaac23 ac35f84 fdaac23 8af7605 fdaac23 8af7605 6a9c0cd 8af7605 6a9c0cd 8af7605 6a9c0cd 8af7605 6a9c0cd 8af7605 814ee46 8af7605 fdaac23 8af7605 b61c694 8af7605 fdaac23 ac35f84 8af7605 b9efad2 8af7605 b9efad2 8af7605 4e63905 8af7605 | 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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 | "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();
|