Download web/poster.js from Algorick/pixrick: direct link, hf CLI and curl.
- Browser
- Download file 55.4 kB
-
https://huggingface.co/spaces/Algorick/pixrick/resolve/main/web/poster.js
- Command line
-
hf download hf://spaces/Algorick/pixrick/web/poster.js
-
curl -L -o poster.js https://huggingface.co/spaces/Algorick/pixrick/resolve/main/web/poster.js
55.4 kB
"use strict";
/* Locandina: template con strutture diverse, testi con font veri, loghi e foto come livelli
da spostare e ridimensionare sulla tela. */
(() => {
const FONTS = [
{ id: "oswald", nome: "Oswald", heavy: [700, "PR Oswald"], medium: [500, "PR Oswald"], track: 0.01 },
{ id: "anton", nome: "Anton", heavy: [400, "PR Anton"], medium: [500, "PR Oswald"], track: 0.01 },
{ id: "bebas", nome: "Bebas Neue", heavy: [400, "PR Bebas"], medium: [400, "PR Bebas"], track: 0.04 },
{ id: "archivo", nome: "Archivo Black", heavy: [400, "PR Archivo"], medium: [600, "PR Inter"], track: 0 },
{ id: "inter", nome: "Inter", heavy: [800, "PR Inter"], medium: [600, "PR Inter"], track: -0.01 },
{ id: "playfair", nome: "Playfair", heavy: [900, "PR Playfair"], medium: [700, "PR Playfair"], track: 0 },
{ id: "marker", nome: "Marker", heavy: [400, "PR Marker"], medium: [500, "PR Oswald"], track: 0 },
];
const BODY = [600, "PR Inter"];
const FORMATS = { "2:3": [2000, 3000], A4: [2000, 2828], "4:5": [2000, 2500], "9:16": [1800, 3200], "1:1": [2000, 2000] };
const TEXT_COLORS = ["#f6f5f0", "#ffffff", "#111111", "#ffd600"];
const ACCENT_COLORS = ["#ffd600", "#ff3b3b", "#ff7a1a", "#cbbcff", "#4dd4ff", "#f6f5f0"];
const FIELDS = ["titolo", "tag", "lineup", "data", "ora", "luogo", "info"];
const SAMPLE = {
titolo: "Notte acustica",
tag: "Live in bottega",
lineup: "The Lanterns\nMara Vento\nI Cortili",
data: "Venerdì 12 dicembre",
ora: "Ore 21:00",
luogo: "Teatro comunale",
info: "Ingresso libero",
};
const MONTHS = ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"];
const TEMPLATES = [
{ id: "classica", nome: "Classica", desc: "Logo o titolo in alto, foto naturale, informazioni a colonne.", fields: ["titolo", "tag", "data", "ora", "luogo", "info"], bleed: true, font: "oswald", treatment: "naturale" },
{ id: "lineup", nome: "Line-up", desc: "Festival: più band in evidenza, dalla principale alle altre.", fields: FIELDS, bleed: true, font: "bebas", treatment: "duotono" },
{ id: "headliner", nome: "Headliner", desc: "Un nome enorme in basso, gli altri in supporto, data in alto.", fields: ["tag", "lineup", "data", "ora", "luogo", "info"], bleed: true, font: "archivo", treatment: "bn" },
{ id: "data", nome: "Data gigante", desc: "Il giorno diventa la grafica, testi in colonna.", fields: FIELDS, bleed: true, font: "anton", treatment: "duotono" },
{ id: "fascia", nome: "Fascia", desc: "Foto sopra, fascia di colore pieno con i testi.", fields: FIELDS, bleed: false, font: "oswald", treatment: "naturale" },
{ id: "minimal", nome: "Minimal", desc: "Carta chiara, foto incorniciata, griglia tipografica.", fields: FIELDS, bleed: false, light: true, font: "inter", treatment: "bn" },
];
const defaults = {
template: "classica",
bg: null,
bgY: 0.5,
bgZoom: 1,
texts: { ...SAMPLE },
upper: true,
font: "oswald",
textScale: 1,
textColor: "#f6f5f0",
accent: "#ffd600",
format: "2:3",
treatment: "naturale",
shade: 0.85,
grain: true,
};
const S = { ...structuredClone(defaults), ...prefs.get("poster", {}) };
S.texts = { ...defaults.texts, ...(S.texts || {}) };
if (!TEMPLATES.some((t) => t.id === S.template)) S.template = "classica";
delete S.layout;
let layers = [];
const processed = new Map();
let rects = new Map();
let textRects = [];
let selected = null;
let bgImg = null;
let grain = null;
let pending = 0;
let thumbTimer = 0;
let wired = false;
const canvas = () => $("#poster-canvas");
const tpl = (id = S.template) => TEMPLATES.find((t) => t.id === id) || TEMPLATES[0];
const font = () => FONTS.find((f) => f.id === S.font) || FONTS[0];
const fontCss = ([weight, family], size) => `${weight} ${Math.round(size)}px "${family}"`;
const persist = () => prefs.set("poster", S);
const persistLayers = () => prefs.set("posterLayers", layers.map(({ id, kind, nome, src, mode, key, shape, scale, manual, x, y, w }) => ({ id, kind, nome, src, mode, key, shape, scale, manual, x, y, w })));
const upper = (v) => (S.upper ? v.toLocaleUpperCase("it-IT") : v);
const txt = (id) => upper((S.texts[id] || "").trim());
const lineup = () => (S.texts.lineup || "").split("\n").map((l) => upper(l.trim())).filter(Boolean);
/** I loghi prendono il posto dei primi nomi della line-up: a testo restano le band senza logo. */
const rest = (auto) => lineup().slice(auto.length);
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error("Immagine non leggibile"));
img.src = src;
});
}
function hexRgb(hex) {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
const isLight = (hex) => {
const [r, g, b] = hexRgb(hex);
return 0.299 * r + 0.587 * g + 0.114 * b > 150;
};
const onAccent = () => (isLight(S.accent) ? "#0b0b0b" : "#ffffff");
function grainPattern(ctx) {
if (!grain) {
const c = document.createElement("canvas");
c.width = c.height = 256;
const g = c.getContext("2d");
const d = g.createImageData(256, 256);
for (let i = 0; i < d.data.length; i += 4) {
const v = 128 + (Math.random() - 0.5) * 140;
d.data[i] = d.data[i + 1] = d.data[i + 2] = v;
d.data[i + 3] = 255;
}
g.putImageData(d, 0, 0);
grain = c;
}
return ctx.createPattern(grain, "repeat");
}
/* ---------- livelli: loghi e foto ---------- */
function alphaBounds(ctx, w, h) {
const px = ctx.getImageData(0, 0, w, h).data;
let x0 = w, y0 = h, x1 = -1, y1 = -1;
for (let y = 0; y < h; y += 2) {
for (let x = 0; x < w; x += 2) {
if (px[(y * w + x) * 4 + 3] > 16) {
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
}
}
if (x1 < 0) return null;
const left = Math.max(0, x0 - 2);
const top = Math.max(0, y0 - 2);
return [left, top, Math.min(w, x1 + 4) - left, Math.min(h, y1 + 4) - top];
}
function processLayer(layer) {
const src = layer.img;
if (!src) return;
processed.delete(`${layer.id}:ink`);
const max = 1600;
const k = Math.min(1, max / Math.max(src.naturalWidth, src.naturalHeight));
const w = Math.max(1, Math.round(src.naturalWidth * k));
const h = Math.max(1, Math.round(src.naturalHeight * k));
const c = document.createElement("canvas");
c.width = w;
c.height = h;
const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.drawImage(src, 0, 0, w, h);
if (layer.key || layer.mode !== "originale") {
const data = ctx.getImageData(0, 0, w, h);
const px = data.data;
const tint = layer.mode === "bianco" ? [255, 255, 255] : layer.mode === "nero" ? [12, 12, 12] : layer.mode === "accento" ? hexRgb(S.accent) : null;
for (let i = 0; i < px.length; i += 4) {
if (layer.key) {
const lum = 0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2];
px[i + 3] = Math.round(px[i + 3] * Math.max(0, Math.min(1, (250 - lum) / 45)));
}
if (tint) [px[i], px[i + 1], px[i + 2]] = tint;
}
ctx.putImageData(data, 0, 0);
}
let out = c;
if (layer.kind === "logo") {
const b = alphaBounds(ctx, w, h);
if (b) {
out = document.createElement("canvas");
out.width = b[2];
out.height = b[3];
out.getContext("2d").drawImage(c, b[0], b[1], b[2], b[3], 0, 0, b[2], b[3]);
}
}
if (layer.shape === "cerchio") {
const s = Math.min(out.width, out.height);
const sq = document.createElement("canvas");
sq.width = sq.height = s;
sq.getContext("2d").drawImage(out, (out.width - s) / 2, (out.height - s) / 2, s, s, 0, 0, s, s);
out = sq;
}
processed.set(layer.id, out);
}
const ratio = (layer) => {
const c = processed.get(layer.id);
return c ? c.height / c.width : 1;
};
/** Rettangolo che contiene il livello dentro un box, centrato. */
function fitBox(layer, cx, cy, maxW, maxH) {
let w = maxW * (layer.scale || 1);
let h = w * ratio(layer);
const lim = maxH * (layer.scale || 1);
if (h > lim) { h = lim; w = h / ratio(layer); }
return { x: cx - w / 2, y: cy - h / 2, w, h };
}
/** Mette i loghi in fila con lo stesso peso visivo: conta l'area, non la larghezza,
così un logo lungo e uno tondo sembrano grandi uguali. */
function logoRow(list, x, y, w, maxH, perRow = 4, align = "center") {
const rows = [];
for (let i = 0; i < list.length; i += perRow) rows.push(list.slice(i, i + perRow));
const gapX = w * 0.07;
const gapY = maxH * 0.35;
const items = [];
let yy = y;
for (const row of rows) {
const roots = row.map((l) => Math.sqrt(1 / ratio(l)));
const k = Math.min((w - gapX * (row.length - 1)) / roots.reduce((a, b) => a + b, 0), maxH * Math.min(...roots));
const boxes = row.map((l, i) => {
const sc = l.scale || 1;
return { w: k * roots[i] * sc, h: (k / roots[i]) * sc };
});
const rowH = Math.max(...boxes.map((b) => b.h));
const used = boxes.reduce((s, b) => s + b.w, 0) + gapX * (row.length - 1);
let cx = align === "left" ? x : align === "right" ? x + w - used : x + (w - used) / 2;
boxes.forEach((b, i) => {
items.push([row[i], { x: cx, y: yy + (rowH - b.h) / 2, w: b.w, h: b.h }]);
cx += b.w + gapX;
});
yy += rowH + gapY;
}
return { items, h: yy - y - gapY };
}
/* ---------- testo ---------- */
function setFont(ctx, spec, size, track) {
ctx.font = fontCss(spec, size);
const t = track ?? (spec === BODY ? 0.02 : font().track);
if ("letterSpacing" in ctx) ctx.letterSpacing = `${(t * size).toFixed(1)}px`;
}
function fit(ctx, str, spec, size, maxW, track) {
setFont(ctx, spec, size, track);
const w = ctx.measureText(str).width;
if (w > maxW) {
size *= maxW / w;
setFont(ctx, spec, size, track);
}
return size;
}
function write(ctx, str, { spec, size, x, y, maxW, align = "center", color = S.textColor, base = "alphabetic", track }) {
if (!str) return 0;
const s = fit(ctx, str, spec, size, maxW, track);
ctx.fillStyle = color;
ctx.textAlign = align;
ctx.textBaseline = base;
ctx.fillText(str, x, y);
return s;
}
/** Etichetta piccola e spaziata, come nei manifesti tipografici. */
function label(ctx, str, { x, y, maxW, align = "left", color, size }) {
if (!str) return 0;
ctx.save();
ctx.globalAlpha = 0.72;
write(ctx, str.toLocaleUpperCase("it-IT"), { spec: BODY, size, x, y, maxW, align, color, base: "alphabetic", track: 0.2 });
ctx.restore();
return size;
}
function rule(ctx, x, y, w, t, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, w, Math.max(1.5, t));
}
/** Riga di informazioni a colonne: etichetta sopra, valore sotto, filetto in testa. */
function infoGrid(ctx, W, { x, y, w, items, ink, labelInk, valueSize, align = "left" }) {
const cols = items.filter((i) => i.value);
if (!cols.length) return 0;
const ls = W * 0.0165;
const vs = valueSize;
rule(ctx, x, y, w, W * 0.0018, ink);
const cw = w / cols.length;
const size = Math.min(...cols.map((c) => fit(ctx, c.value, font().heavy, vs, cw - W * 0.03)));
cols.forEach((c, i) => {
const cx = align === "center" ? x + cw * i + cw / 2 : x + cw * i;
label(ctx, c.label, { x: cx, y: y + ls * 2.6, maxW: cw - W * 0.02, align, color: labelInk || ink, size: ls });
write(ctx, c.value, { spec: font().heavy, size, x: cx, y: y + ls * 2.9 + vs * 1.02, maxW: cw - W * 0.03, align, color: ink });
});
return ls * 2.9 + vs * 1.2;
}
const infoItems = (keys = ["data", "ora", "luogo"]) => keys.map((k) => ({
label: { data: "Data", ora: "Ore", luogo: "Dove", info: "Info" }[k],
value: k === "ora" ? txt("ora").replace(/^ORE\s+|^ore\s+/i, "") : txt(k),
}));
/** Giorno e mese ricavati dal testo della data («Venerdì 12 dicembre» → 12, DIC, VENERDÌ). */
function dayParts() {
const raw = (S.texts.data || "").trim();
const day = raw.match(/\b(\d{1,2})\b/)?.[1] || "";
const low = raw.toLowerCase();
const mi = MONTHS.findIndex((m) => low.includes(m));
const first = raw.split(/\s+/)[0] || "";
const full = mi >= 0 ? raw.split(/\s+/).find((w) => w.toLowerCase().startsWith(MONTHS[mi])) || MONTHS[mi] : "";
return { day, month: mi >= 0 ? MONTHS[mi] : "", fullMonth: full, weekday: first && !/\d/.test(first) ? first : "" };
}
/* ---------- sfondo e trattamenti ---------- */
const treated = new Map();
/** L'immagine ritagliata sull'area, con il trattamento scelto: naturale, bianco e nero o duotono. */
function treatedImage(w, h, mode) {
const key = [S.bg, Math.round(w), Math.round(h), mode, S.accent, S.bgY, S.bgZoom].join("|");
if (treated.has(key)) return treated.get(key);
const c = document.createElement("canvas");
c.width = Math.max(1, Math.round(w));
c.height = Math.max(1, Math.round(h));
const ctx = c.getContext("2d", { willReadFrequently: mode !== "naturale" });
const scale = Math.max(c.width / bgImg.naturalWidth, c.height / bgImg.naturalHeight) * S.bgZoom;
const dw = bgImg.naturalWidth * scale;
const dh = bgImg.naturalHeight * scale;
ctx.imageSmoothingQuality = "high";
ctx.drawImage(bgImg, (c.width - dw) / 2, (c.height - dh) * S.bgY, dw, dh);
if (mode !== "naturale") {
const data = ctx.getImageData(0, 0, c.width, c.height);
const px = data.data;
const [ar, ag, ab] = hexRgb(S.accent);
const dark = [Math.round(ar * 0.08), Math.round(ag * 0.08), Math.round(ab * 0.1)];
for (let i = 0; i < px.length; i += 4) {
let l = (0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2]) / 255;
l = Math.min(1, Math.max(0, (l - 0.04) * 1.18));
if (mode === "bn") {
const v = Math.round(Math.pow(l, 1.05) * 255);
px[i] = px[i + 1] = px[i + 2] = v;
} else {
const t = Math.pow(l, 1.15);
px[i] = dark[0] + (ar - dark[0]) * t;
px[i + 1] = dark[1] + (ag - dark[1]) * t;
px[i + 2] = dark[2] + (ab - dark[2]) * t;
}
}
ctx.putImageData(data, 0, 0);
}
treated.set(key, c);
if (treated.size > 14) treated.delete(treated.keys().next().value);
return c;
}
function cover(ctx, x, y, w, h, mode = S.treatment) {
if (!bgImg) {
const g = ctx.createLinearGradient(x, y, x + w * 0.3, y + h);
const [r, gg, b] = hexRgb(S.accent);
g.addColorStop(0, `rgb(${Math.round(r * 0.3)},${Math.round(gg * 0.3)},${Math.round(b * 0.3)})`);
g.addColorStop(0.55, "#121216");
g.addColorStop(1, "#08080a");
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
return;
}
const tr = ctx.getTransform();
const k = Math.hypot(tr.a, tr.b) || 1;
ctx.drawImage(treatedImage(w * k, h * k, mode), x, y, w, h);
}
function shade(ctx, W, H, stops) {
const a = S.shade;
if (a <= 0) return;
const g = ctx.createLinearGradient(0, 0, 0, H);
for (const [t, v] of stops) g.addColorStop(t, `rgba(6,6,8,${(v * a).toFixed(3)})`);
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
/* ---------- template ---------- */
const M = (W) => W * 0.07;
const RENDER = {
/* Logo o titolo in alto, foto naturale, informazioni a colonne in basso. */
classica(ctx, W, H, auto) {
cover(ctx, 0, 0, W, H);
shade(ctx, W, H, [[0, 0.75], [0.3, 0.15], [0.55, 0.1], [0.78, 0.7], [1, 0.95]]);
const f = font();
const s = S.textScale;
const m = M(W);
const place = [];
let y = m * 1.1;
if (auto.length) {
const row = logoRow(auto, m, y, W - m * 2, H * 0.17, 3);
place.push(...row.items);
y += row.h;
} else if (txt("titolo")) {
for (const line of txt("titolo").split(/\s*\|\s*/).filter(Boolean)) {
const size = write(ctx, line, { spec: f.heavy, size: W * 0.16 * s, x: W / 2, y, maxW: W - m * 2, base: "top" });
y += size * 0.95;
}
}
if (txt("tag")) {
y += W * 0.045;
const ts = W * 0.022 * s;
setFont(ctx, BODY, ts, 0.28);
const tw = Math.min(ctx.measureText(txt("tag")).width, W * 0.6);
write(ctx, txt("tag"), { spec: BODY, size: ts, x: W / 2, y, maxW: W * 0.6, base: "middle", color: S.textColor, track: 0.28 });
rule(ctx, W / 2 - tw / 2 - W * 0.12, y, W * 0.08, W * 0.002, S.accent);
rule(ctx, W / 2 + tw / 2 + W * 0.04, y, W * 0.08, W * 0.002, S.accent);
}
const bottom = H - m;
if (txt("info")) label(ctx, txt("info"), { x: W / 2, y: bottom, maxW: W - m * 2, align: "center", color: S.textColor, size: W * 0.019 * s });
const gridY = bottom - W * 0.06 - W * 0.15 * s;
infoGrid(ctx, W, { x: m, y: gridY, w: W - m * 2, items: infoItems(), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.052 * s, align: "center" });
return place;
},
/* Festival: intestazione a filetti, line-up tipografica a scalare, griglia in fondo. */
lineup(ctx, W, H, auto) {
cover(ctx, 0, 0, W, H);
shade(ctx, W, H, [[0, 0.7], [0.25, 0.35], [0.6, 0.45], [1, 0.9]]);
const f = font();
const s = S.textScale;
const m = M(W);
const ls = W * 0.0175 * s;
const { day, month, weekday } = dayParts();
const head = [weekday && weekday.slice(0, 3), day, month].filter(Boolean).join(" ");
label(ctx, head || txt("data"), { x: m, y: m + ls, maxW: W * 0.4, color: S.textColor, size: ls });
label(ctx, txt("luogo"), { x: W - m, y: m + ls, maxW: W * 0.45, align: "right", color: S.textColor, size: ls });
rule(ctx, m, m + ls * 2, W - m * 2, W * 0.0018, S.textColor);
let y = m + ls * 2 + W * 0.08;
if (txt("tag")) {
label(ctx, txt("tag"), { x: W / 2, y, maxW: W * 0.7, align: "center", color: S.accent, size: W * 0.024 * s });
y += W * 0.03;
}
if (txt("titolo")) {
const size = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.15 * s, x: W / 2, y, maxW: W - m * 2, base: "top" });
y += size * 0.95;
}
const gridH = W * 0.15 * s;
const bottom = H - m - (txt("info") ? W * 0.05 : 0);
const gridY = bottom - gridH;
const place = [];
const names = auto.length ? rest(auto) : lineup();
let blockTop = y + W * 0.06;
const blockBottom = gridY - W * 0.07;
if (auto.length) {
const row = logoRow(auto, m, 0, W - m * 2, Math.min(H * 0.17, (blockBottom - blockTop) * 0.7), auto.length > 4 ? 3 : 4);
const namesH = names.length ? W * 0.09 : 0;
const top = blockTop + Math.max(0, (blockBottom - blockTop - row.h - namesH) / 2);
row.items.forEach(([l, r]) => { r.y += top; });
place.push(...row.items);
if (names.length) write(ctx, names.join(" • "), { spec: f.heavy, size: W * 0.055 * s, x: W / 2, y: top + row.h + W * 0.085, maxW: W - m * 2 });
} else if (names.length) {
const first = names[0];
const others = names.slice(1);
const big = fit(ctx, first, f.heavy, W * 0.17 * s, W - m * 2);
const lines = [];
let cur = [];
for (const n of others) {
const test = [...cur, n].join(" • ");
setFont(ctx, f.heavy, W * 0.07 * s);
if (cur.length && ctx.measureText(test).width > W - m * 2) { lines.push(cur.join(" • ")); cur = [n]; } else cur.push(n);
}
if (cur.length) lines.push(cur.join(" • "));
const total = big * 0.95 + lines.length * W * 0.085 * s + (lines.length ? W * 0.05 : 0);
let yy = blockTop + Math.max(0, (blockBottom - blockTop - total) / 2);
write(ctx, first, { spec: f.heavy, size: big, x: W / 2, y: yy, maxW: W - m * 2, base: "top" });
yy += big * 0.95 + W * 0.05;
for (const ln of lines) {
write(ctx, ln, { spec: f.heavy, size: W * 0.07 * s, x: W / 2, y: yy, maxW: W - m * 2, base: "top", color: S.accent });
yy += W * 0.085 * s;
}
}
infoGrid(ctx, W, { x: m, y: gridY, w: W - m * 2, items: infoItems(), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.05 * s, align: "center" });
if (txt("info")) label(ctx, txt("info"), { x: W / 2, y: H - m, maxW: W - m * 2, align: "center", color: S.textColor, size: W * 0.019 * s });
return place;
},
/* Svizzero: tutto a sinistra, il protagonista enorme in basso, la data in alto a destra. */
headliner(ctx, W, H, auto) {
cover(ctx, 0, 0, W, H);
shade(ctx, W, H, [[0, 0.55], [0.3, 0.1], [0.5, 0.25], [0.8, 0.85], [1, 0.95]]);
const f = font();
const s = S.textScale;
const m = M(W);
const { day, month } = dayParts();
if (txt("tag")) label(ctx, txt("tag"), { x: m, y: m + W * 0.02, maxW: W * 0.5, color: S.accent, size: W * 0.022 * s });
if (day) {
const ds = write(ctx, day, { spec: f.heavy, size: W * 0.2, x: W - m, y: m * 0.8, maxW: W * 0.4, align: "right", base: "top" });
if (month) write(ctx, upper(month), { spec: f.heavy, size: W * 0.07, x: W - m, y: m * 0.8 + ds * 0.92, maxW: W * 0.4, align: "right", base: "top", color: S.accent });
}
const place = [];
let b = H - m;
if (txt("info")) { label(ctx, txt("info"), { x: m, y: b, maxW: W - m * 2, color: S.textColor, size: W * 0.019 * s }); b -= W * 0.05; }
const gh = W * 0.13 * s;
infoGrid(ctx, W, { x: m, y: b - gh, w: W - m * 2, items: infoItems(["data", "ora", "luogo"]), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.042 * s });
b -= gh + W * 0.06;
const head = auto[0] || null;
const support = auto.slice(1);
const supportNames = head ? rest(auto) : lineup().slice(1);
if (support.length) {
const row = logoRow(support, m, 0, W * 0.6, H * 0.065, 4, "left");
row.items.forEach(([, r]) => { r.y += b - row.h; });
place.push(...row.items);
b -= row.h + W * 0.03;
}
for (const n of [...supportNames].reverse()) {
const sz = write(ctx, n, { spec: f.heavy, size: W * 0.06 * s, x: m, y: b, maxW: W - m * 2, align: "left" });
b -= sz * 1.1;
}
if (support.length || supportNames.length) {
label(ctx, "con", { x: m, y: b, maxW: W * 0.3, color: S.accent, size: W * 0.02 * s });
b -= W * 0.06;
}
if (head) {
const r = fitBox(head, 0, 0, W * 0.72, H * 0.24);
r.x = m;
r.y = b - r.h;
place.push([head, r]);
} else if (lineup()[0]) {
const words = lineup()[0].split(/\s+/);
const lines = [];
for (const w of words) {
const test = [lines.at(-1), w].filter(Boolean).join(" ");
setFont(ctx, f.heavy, W * 0.24 * s);
if (lines.length && ctx.measureText(test).width <= W - m * 2) lines[lines.length - 1] = test; else lines.push(w);
}
const size = Math.min(...lines.map((l) => fit(ctx, l, f.heavy, W * 0.24 * s, W - m * 2)));
for (const ln of [...lines].reverse()) {
write(ctx, ln, { spec: f.heavy, size, x: m - W * 0.006, y: b, maxW: W - m * 2, align: "left" });
b -= size * 0.9;
}
}
return place;
},
/* Il giorno enorme che esce dal bordo, il mese in verticale, testi in colonna. */
data(ctx, W, H, auto) {
cover(ctx, 0, 0, W, H);
shade(ctx, W, H, [[0, 0.35], [0.45, 0.2], [0.7, 0.75], [1, 0.95]]);
const f = font();
const s = S.textScale;
const m = M(W);
const { day, fullMonth, weekday } = dayParts();
if (day) {
ctx.save();
ctx.globalAlpha = 0.96;
write(ctx, day, { spec: f.heavy, size: W * 0.74, x: -W * 0.04, y: W * 0.01, maxW: W * 1.05, align: "left", base: "top", color: S.accent });
ctx.restore();
}
if (fullMonth || weekday) {
ctx.save();
ctx.translate(W - m * 0.62, m);
ctx.rotate(Math.PI / 2);
write(ctx, [weekday, fullMonth].filter(Boolean).join(" · ").toLocaleUpperCase("it-IT"), { spec: f.heavy, size: W * 0.055, x: 0, y: 0, maxW: H * 0.55, align: "left", base: "alphabetic" });
ctx.restore();
}
const place = [];
let b = H - m;
if (txt("info")) { label(ctx, txt("info"), { x: m, y: b, maxW: W - m * 2, color: S.textColor, size: W * 0.019 * s }); b -= W * 0.05; }
const gh = W * 0.13 * s;
infoGrid(ctx, W, { x: m, y: b - gh, w: W - m * 2, items: infoItems(["ora", "luogo"]), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.045 * s });
b -= gh + W * 0.06;
const names = rest(auto);
for (const n of [...names].reverse()) {
const sz = write(ctx, n, { spec: f.heavy, size: W * 0.058 * s, x: m, y: b, maxW: W * 0.62, align: "left" });
b -= sz * 1.12;
}
if (names.length) b -= W * 0.015;
if (txt("titolo")) {
const sz = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.12 * s, x: m - W * 0.005, y: b, maxW: W - m * 2, align: "left" });
b -= sz * 1.0;
}
if (txt("tag")) { label(ctx, txt("tag"), { x: m, y: b - W * 0.01, maxW: W * 0.6, color: S.accent, size: W * 0.022 * s }); b -= W * 0.06; }
if (auto.length) {
const slot = Math.min(H * 0.085, (b - H * 0.42) / auto.length);
let yy = b - W * 0.04 - slot * auto.length;
for (const l of auto) {
const r = fitBox(l, 0, 0, W * 0.26, slot * 0.8);
r.x = W - m - r.w;
r.y = yy + (slot - r.h) / 2;
place.push([l, r]);
yy += slot;
}
}
return place;
},
/* Foto naturale sopra, fascia di colore pieno sotto con testi a sinistra. */
fascia(ctx, W, H, auto) {
const split = H * 0.6;
cover(ctx, 0, 0, W, split);
ctx.fillStyle = S.accent;
ctx.fillRect(0, split, W, H - split);
const ink = onAccent();
const f = font();
const s = S.textScale;
const m = M(W);
const place = [];
if (auto.length) {
const row = logoRow(auto, m, 0, W * 0.5, H * 0.07, 4, "right");
row.items.forEach(([, r]) => { r.x += W - m * 2 - W * 0.5; r.y += split - m * 0.6 - row.h; });
place.push(...row.items);
}
if (txt("tag")) {
const ts = W * 0.022 * s;
setFont(ctx, BODY, ts, 0.24);
const tw = Math.min(ctx.measureText(txt("tag")).width, W * 0.6) + ts * 1.6;
ctx.fillStyle = ink;
ctx.fillRect(m, split - ts * 1.25, tw, ts * 2.5);
write(ctx, txt("tag"), { spec: BODY, size: ts, x: m + ts * 0.8, y: split + ts * 0.05, maxW: W * 0.6, align: "left", base: "middle", color: S.accent, track: 0.24 });
}
let y = split + W * 0.075;
if (txt("titolo")) {
const size = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.14 * s, x: m - W * 0.006, y, maxW: W - m * 2, align: "left", base: "top", color: ink });
y += size * 0.95;
}
const names = rest(auto);
if (names.length) write(ctx, names.join(" / "), { spec: f.heavy, size: W * 0.048 * s, x: m, y: y + W * 0.015, maxW: W - m * 2, align: "left", base: "top", color: ink });
const gh = W * 0.12 * s;
const gy = H - m - gh - (txt("info") ? W * 0.045 : 0);
infoGrid(ctx, W, { x: m, y: gy, w: W - m * 2, items: infoItems(), ink, valueSize: W * 0.042 * s });
if (txt("info")) label(ctx, txt("info"), { x: m, y: H - m, maxW: W - m * 2, color: ink, size: W * 0.018 * s });
return place;
},
/* Carta chiara, foto in bianco e nero incorniciata, griglia tipografica. */
minimal(ctx, W, H, auto) {
const paper = "#f1f0ec";
const ink = isLight(S.textColor) ? "#141414" : S.textColor;
const mark = isLight(S.accent) && S.accent !== "#ffd600" ? ink : S.accent;
ctx.fillStyle = paper;
ctx.fillRect(0, 0, W, H);
const m = M(W);
const f = font();
const s = S.textScale;
label(ctx, txt("tag"), { x: m, y: m + W * 0.012, maxW: W * 0.55, color: ink, size: W * 0.018 * s });
label(ctx, txt("data"), { x: W - m, y: m + W * 0.012, maxW: W * 0.4, align: "right", color: ink, size: W * 0.018 * s });
const top = m + W * 0.04;
const photoH = H * 0.47;
cover(ctx, m, top, W - m * 2, photoH, S.treatment === "naturale" ? "naturale" : "bn");
ctx.fillStyle = mark;
ctx.fillRect(m, top + photoH + W * 0.045, W * 0.045, W * 0.045);
let y = top + photoH + W * 0.12;
if (txt("titolo")) {
const size = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.13 * s, x: m - W * 0.006, y, maxW: W - m * 2, align: "left", base: "top", color: ink });
y += size * 1.0;
}
for (const n of rest(auto).slice(0, 4)) {
const size = write(ctx, n, { spec: f.medium, size: W * 0.046 * s, x: m, y, maxW: W - m * 2, align: "left", base: "top", color: ink });
y += size * 1.18;
}
const gh = W * 0.12 * s;
const gy = H - m - gh - (txt("info") ? W * 0.04 : 0);
infoGrid(ctx, W, { x: m, y: gy, w: W - m * 2, items: infoItems(), ink, valueSize: W * 0.04 * s });
if (txt("info")) label(ctx, txt("info"), { x: m, y: H - m, maxW: W * 0.6, color: ink, size: W * 0.017 * s });
if (!auto.length) return [];
const row = logoRow(auto, W * 0.5, 0, W * 0.5 - m, W * 0.11, 4, "right");
row.items.forEach(([, r]) => { r.y += gy - W * 0.05 - row.h; });
return row.items;
},
};
/* ---------- disegno ---------- */
/** Su fondo chiaro un logo reso bianco sparirebbe: lo disegno color inchiostro. */
function inked(layer) {
const key = `${layer.id}:ink`;
if (!processed.has(key)) {
const ink = { ...layer, id: key, mode: "nero" };
processLayer(ink);
}
return processed.get(key);
}
function drawLayer(ctx, layer, r, W, light) {
const c = light && layer.mode === "bianco" ? inked(layer) : processed.get(layer.id);
if (!c) return;
ctx.save();
if (layer.kind === "foto") {
ctx.shadowColor = "rgba(0,0,0,0.45)";
ctx.shadowBlur = W * 0.02;
ctx.shadowOffsetY = W * 0.006;
ctx.beginPath();
if (layer.shape === "cerchio") ctx.arc(r.x + r.w / 2, r.y + r.h / 2, Math.min(r.w, r.h) / 2, 0, Math.PI * 2);
else if (layer.shape === "arrotondata") ctx.roundRect(r.x, r.y, r.w, r.h, Math.min(r.w, r.h) * 0.06);
else ctx.rect(r.x, r.y, r.w, r.h);
ctx.fillStyle = "#000";
ctx.fill();
ctx.shadowColor = "transparent";
ctx.clip();
} else if (!light) {
ctx.shadowColor = "rgba(0,0,0,0.45)";
ctx.shadowBlur = W * 0.012;
ctx.shadowOffsetY = W * 0.004;
}
ctx.drawImage(c, r.x, r.y, r.w, r.h);
ctx.restore();
}
/** Registra dove finisce ogni testo, per portare al campo giusto chi lo tocca. */
function recordTexts(ctx, out) {
const fill = ctx.fillText;
ctx.fillText = function (text, x, y, maxWidth) {
const m = ctx.measureText(text);
const w = Math.min(m.width, maxWidth ?? Infinity);
const align = ctx.textAlign;
const left = align === "center" ? x - w / 2 : align === "right" || align === "end" ? x - w : x;
const top = y - (m.actualBoundingBoxAscent || 0);
const h = (m.actualBoundingBoxAscent || 0) + (m.actualBoundingBoxDescent || 0);
const t = ctx.getTransform();
const pts = [[left, top], [left + w, top], [left, top + h], [left + w, top + h]].map(([px, py]) => [t.a * px + t.c * py + t.e, t.b * px + t.d * py + t.f]);
const xs = pts.map((p) => p[0]);
const ys = pts.map((p) => p[1]);
out.push({ text: String(text), x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) });
return fill.call(ctx, text, x, y, maxWidth);
};
return () => { delete ctx.fillText; };
}
function paint(cv, W, H, templateId, main) {
const ctx = cv.getContext("2d");
const texts = [];
const stop = main ? recordTexts(ctx, texts) : null;
ctx.save();
ctx.clearRect(0, 0, W, H);
const ready = layers.filter((l) => processed.has(l.id));
const auto = ready.filter((l) => !l.manual);
const fixed = ready.filter((l) => l.manual);
const place = RENDER[templateId](ctx, W, H, auto) || [];
const drawn = new Map(place.map(([l, r]) => [l.id, r]));
for (const l of fixed) {
const w = l.w * W;
const h = w * ratio(l);
drawn.set(l.id, { x: l.x * W - w / 2, y: l.y * H - h / 2, w, h });
}
for (const l of ready) {
const r = drawn.get(l.id);
if (r) drawLayer(ctx, l, r, W, tpl(templateId).light);
}
if (main && S.grain) {
ctx.globalCompositeOperation = "overlay";
ctx.globalAlpha = 0.2;
ctx.fillStyle = grainPattern(ctx);
ctx.fillRect(0, 0, W, H);
}
ctx.restore();
if (stop) { stop(); textRects = texts; }
return drawn;
}
const norm = (v) => v.toLocaleLowerCase("it-IT").replace(/\s+/g, " ").trim();
function fieldAt(x, y) {
const pad = 20;
const hits = textRects.filter((r) => x >= r.x - pad && x <= r.x + r.w + pad && y >= r.y - pad && y <= r.y + r.h + pad);
for (const r of hits.reverse()) {
const shown = norm(r.text);
if (shown.length < 2) continue;
for (const id of FIELDS) {
const values = id === "lineup" ? (S.texts.lineup || "").split("\n") : [S.texts[id] || ""];
if (values.some((v) => { const n = norm(v); return n.length > 1 && (n.includes(shown) || shown.includes(n)); })) return id;
}
}
return null;
}
function focusField(id) {
document.dispatchEvent(new CustomEvent("poster:campo", { detail: id }));
const input = $(`#pp-${id}`);
input.scrollIntoView({ block: "center", behavior: "smooth" });
input.focus({ preventScroll: true });
input.closest("label")?.classList.add("flash");
setTimeout(() => input.closest("label")?.classList.remove("flash"), 900);
}
function render() {
pending = 0;
const cv = canvas();
const [W, H] = FORMATS[S.format] || FORMATS["2:3"];
if (cv.width !== W || cv.height !== H) { cv.width = W; cv.height = H; }
rects = paint(cv, W, H, S.template, true);
syncOverlay();
clearTimeout(thumbTimer);
thumbTimer = setTimeout(renderThumbs, 260);
}
function renderThumbs() {
const [W, H] = FORMATS[S.format] || FORMATS["2:3"];
const tw = 300;
const th = Math.round((tw * H) / W);
for (const c of document.querySelectorAll("#pp-templates canvas")) {
if (c.width !== tw || c.height !== th) { c.width = tw; c.height = th; }
const ctx = c.getContext("2d");
ctx.save();
ctx.scale(tw / W, th / H);
const tmp = { getContext: () => ctx };
paint(tmp, W, H, c.dataset.tpl, false);
ctx.restore();
}
}
function schedule() {
if (pending) return;
pending = requestAnimationFrame(render);
}
async function ensureFonts() {
const f = font();
await Promise.all([fontCss(f.heavy, 40), fontCss(f.medium, 40), fontCss(BODY, 40)].map((s) => document.fonts.load(s))).catch(() => {});
}
/* ---------- tela interattiva: seleziona, sposta, ridimensiona ---------- */
function canvasPoint(e) {
const cv = canvas();
const r = cv.getBoundingClientRect();
return [((e.clientX - r.left) / r.width) * cv.width, ((e.clientY - r.top) / r.height) * cv.height];
}
function hit(x, y) {
for (const l of [...layers].reverse()) {
const r = rects.get(l.id);
if (r && x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) return l;
}
return null;
}
function syncOverlay() {
const box = $("#pp-overlay");
const cv = canvas();
const wrap = $("#poster-wrap").getBoundingClientRect();
const cr = cv.getBoundingClientRect();
box.style.left = `${cr.left - wrap.left}px`;
box.style.top = `${cr.top - wrap.top}px`;
box.style.width = `${cr.width}px`;
box.style.height = `${cr.height}px`;
const k = cr.width / cv.width;
const sel = selected && rects.get(selected.id);
const frame = $("#pp-frame");
frame.hidden = !sel;
if (sel) {
frame.style.left = `${sel.x * k}px`;
frame.style.top = `${sel.y * k}px`;
frame.style.width = `${sel.w * k}px`;
frame.style.height = `${sel.h * k}px`;
}
}
function select(layer) {
selected = layer;
renderLayerList();
syncOverlay();
}
function pinLayer(layer) {
if (layer.manual) return;
const r = rects.get(layer.id);
const [W, H] = FORMATS[S.format];
if (!r) return;
Object.assign(layer, { manual: true, x: (r.x + r.w / 2) / W, y: (r.y + r.h / 2) / H, w: r.w / W });
}
function wireCanvas() {
const wrap = $("#poster-wrap");
let drag = null;
let tapField = null;
wrap.addEventListener("pointerdown", (e) => {
const [x, y] = canvasPoint(e);
const onHandle = e.target.closest(".pp-handle");
const layer = onHandle ? selected : hit(x, y);
if (!layer) {
if (selected) select(null);
tapField = fieldAt(x, y);
return;
}
tapField = null;
if (layer !== selected) select(layer);
pinLayer(layer);
const [W, H] = FORMATS[S.format];
drag = { layer, resize: Boolean(onHandle), x0: x, y0: y, lx: layer.x, ly: layer.y, lw: layer.w, W, H };
wrap.setPointerCapture(e.pointerId);
wrap.classList.add("dragging");
e.preventDefault();
});
wrap.addEventListener("pointermove", (e) => {
if (!drag) {
const [x, y] = canvasPoint(e);
const over = hit(x, y);
wrap.classList.toggle("can-move", Boolean(over));
wrap.classList.toggle("can-edit", !over && Boolean(fieldAt(x, y)));
return;
}
const [x, y] = canvasPoint(e);
const { layer, W, H } = drag;
if (drag.resize) {
const cx = drag.lx * W;
layer.w = Math.max(0.05, Math.min(1.4, (Math.abs(x - cx) * 2) / W));
} else {
layer.x = Math.max(0, Math.min(1, drag.lx + (x - drag.x0) / W));
layer.y = Math.max(0, Math.min(1, drag.ly + (y - drag.y0) / H));
}
schedule();
});
const end = () => {
if (!drag) return;
drag = null;
wrap.classList.remove("dragging");
persistLayers();
renderLayerList();
};
wrap.addEventListener("pointerup", end);
wrap.addEventListener("click", () => {
if (tapField) focusField(tapField);
tapField = null;
});
wrap.addEventListener("pointercancel", end);
window.addEventListener("resize", () => syncOverlay());
document.addEventListener("keydown", (e) => {
if ($("#poster").hidden || !selected || e.target.closest("input, textarea, [contenteditable]") || document.querySelector("dialog[open]:not(#guide)")) return;
const step = e.shiftKey ? 0.02 : 0.004;
const moves = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
if (moves[e.key]) {
pinLayer(selected);
selected.x += moves[e.key][0];
selected.y += moves[e.key][1];
persistLayers();
schedule();
e.preventDefault();
} else if (e.key === "Delete" || e.key === "Backspace") {
removeLayer(selected);
e.preventDefault();
} else if (e.key === "Escape") {
select(null);
}
});
}
/* ---------- gestione dei livelli ---------- */
const newId = () => `l${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
function hasLightBackground(img) {
const c = document.createElement("canvas");
c.width = c.height = 32;
const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.drawImage(img, 0, 0, 32, 32);
const px = ctx.getImageData(0, 0, 32, 32).data;
return [[0, 0], [31, 0], [0, 31], [31, 31]].every(([x, y]) => {
const i = (y * 32 + x) * 4;
return px[i + 3] > 245 && 0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2] > 225;
});
}
/** Riduce l'immagine prima di tenerla in memoria: un logo non serve oltre i 1600 px. */
async function compact(src) {
const img = await loadImage(src);
const k = Math.min(1, 1600 / Math.max(img.naturalWidth, img.naturalHeight));
if (k === 1 && String(src).length < 1_400_000) return { img, src };
const c = document.createElement("canvas");
c.width = Math.round(img.naturalWidth * k);
c.height = Math.round(img.naturalHeight * k);
c.getContext("2d").drawImage(img, 0, 0, c.width, c.height);
const out = c.toDataURL("image/png");
return { img: await loadImage(out), src: out };
}
async function addLayer(kind, src, nome) {
let res;
try { res = await compact(src); } catch { toast("Questa immagine non si apre"); return; }
const layer = {
id: newId(), kind, nome: nome || (kind === "logo" ? "Logo" : "Foto"),
src: res.src, img: res.img,
mode: "originale", key: kind === "logo" && hasLightBackground(res.img),
shape: kind === "foto" ? "arrotondata" : "libera",
scale: 1, manual: false, x: 0.5, y: 0.5, w: 0.4,
};
processLayer(layer);
layers.push(layer);
persistLayers();
select(layer);
schedule();
}
async function addFromFile(kind, file) {
if (!file) return;
const url = await new Promise((resolve) => {
const r = new FileReader();
r.onload = () => resolve(r.result);
r.readAsDataURL(file);
});
await addLayer(kind, url, file.name.replace(/\.[a-z0-9]+$/i, ""));
}
function removeLayer(layer) {
layers = layers.filter((l) => l !== layer);
processed.delete(layer.id);
if (selected === layer) selected = null;
persistLayers();
renderLayerList();
schedule();
}
function moveLayer(layer, delta) {
const i = layers.indexOf(layer);
const j = i + delta;
if (j < 0 || j >= layers.length) return;
[layers[i], layers[j]] = [layers[j], layers[i]];
persistLayers();
renderLayerList();
schedule();
}
function renderLayerList() {
const list = $("#pp-layer-list");
list.replaceChildren(...layers.map((l) => {
const thumb = el("img", { src: l.src, alt: "" });
const row = el("button", {
type: "button",
class: "pp-layer",
"aria-pressed": String(l === selected),
onclick: () => select(l === selected ? null : l),
}, [thumb, el("span", { text: l.nome }), el("small", { text: l.manual ? "a mano" : "automatico" })]);
return row;
}));
$("#pp-layers-empty").hidden = layers.length > 0;
const opts = $("#pp-layer-opts");
opts.hidden = !selected;
if (!selected) return;
radio($("#pp-layer-color"), "v", selected.mode);
radio($("#pp-layer-shape"), "v", selected.shape);
$("#pp-layer-key").checked = selected.key;
$("#pp-layer-shape").hidden = selected.kind !== "foto";
$("#pp-layer-size").value = String(selected.manual ? selected.w / 0.4 : selected.scale);
$("#pp-layer-reset").hidden = !selected.manual;
}
function relayer() {
if (!selected) return;
processLayer(selected);
persistLayers();
renderLayerList();
schedule();
}
/* ---------- sfondo ---------- */
async function setBackground(path) {
try {
bgImg = await loadImage(mediaUrl(path));
S.bg = path;
S.bgY = 0.5;
S.bgZoom = 1;
$("#pp-bg-y").value = "0.5";
$("#pp-bg-zoom").value = "1";
$("#pp-bg-label").textContent = "Cambia immagine";
persist();
schedule();
} catch {
toast("Non riesco ad aprire quell'immagine");
}
}
let pickerScope = "galleria";
let pickerTarget = "sfondo";
async function openPicker(target = "sfondo") {
pickerTarget = target;
$("#picker-title").textContent = target === "sfondo" ? "Scegli l'immagine di sfondo" : "Aggiungi una foto";
const dlg = $("#picker");
if (!dlg.open) dlg.showModal();
await fillPicker();
}
function pick(path, nome) {
$("#picker").close();
if (pickerTarget === "sfondo") setBackground(path);
else addLayer("foto", mediaUrl(path), nome);
}
async function fillPicker() {
const grid = $("#picker-grid");
grid.replaceChildren(el("p", { class: "picker-empty", text: "Carico…" }));
radio($("#picker-scope"), "v", pickerScope);
const { immagini } = await api(`/api/history?limit=120&vista=${pickerScope}`);
const items = immagini.filter((i) => i.modalita !== "locandina");
grid.replaceChildren();
if (!items.length) {
grid.append(el("p", { class: "picker-empty", text: pickerScope === "bozze" ? "Nessuna bozza." : "La galleria è vuota: genera o carica un'immagine." }));
return;
}
for (const item of items) {
grid.append(el("button", {
type: "button",
class: "picker-item",
title: item.titolo || item.prompt || "",
onclick: () => pick("outputs/" + item.file, item.titolo || "Foto"),
}, [el("img", { src: outputUrl(item.miniatura || item.file), alt: "", loading: "lazy" })]));
}
}
async function uploadPicked(file) {
if (!file) return;
if (pickerTarget !== "sfondo") {
$("#picker").close();
addFromFile("foto", file);
return;
}
try {
const info = await api("/api/upload", file, { "Content-Type": file.type || "application/octet-stream", "X-Filename": encodeURIComponent(file.name || "sfondo") });
$("#picker").close();
setBackground(info.file);
} catch (e) {
toast(e.message);
}
}
/* ---------- esporta ---------- */
async function blob() {
const keep = selected;
selected = null;
render();
selected = keep;
return new Promise((r) => canvas().toBlob(r, "image/png"));
}
function posterTitle() {
return S.texts.titolo || lineup()[0] || [S.texts.tag, S.texts.data].filter(Boolean).join(" · ") || "Locandina";
}
async function save() {
const btn = $("#pp-save");
btn.disabled = true;
try {
const data = await blob();
const meta = encodeURIComponent(JSON.stringify({ titolo: posterTitle(), sfondo: S.bg, formato: S.format }));
await api("/api/poster", data, { "Content-Type": "image/png", "X-Meta": meta });
toast("Locandina salvata in galleria", { label: "Apri galleria", run: () => window.PixRick.setView("galleria") });
} catch (e) {
toast(e.message);
} finally {
btn.disabled = false;
}
}
async function download(e) {
e.preventDefault();
const data = await blob();
const name = `locandina-${posterTitle().toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40)}.png`;
await window.PixRick.saveFile(new File([data], name, { type: "image/png" }));
}
/* ---------- pannello ---------- */
function swatches(box, colors, key) {
box.replaceChildren();
const custom = el("input", { type: "color", class: "swatch-custom", "aria-label": "Altro colore", value: S[key] });
for (const c of colors) {
const b = el("button", { type: "button", class: "swatch", role: "radio", "aria-checked": String(S[key] === c), "aria-label": c, data: { v: c } });
b.style.setProperty("--c", c);
b.addEventListener("click", () => { S[key] = c; radio(box, "v", c); custom.value = c; colorChanged(key); });
box.append(b);
}
custom.addEventListener("input", () => { S[key] = custom.value; radio(box, "v", custom.value); colorChanged(key); });
box.append(custom);
}
function colorChanged(key) {
if (key === "accent") layers.filter((l) => l.mode === "accento").forEach(processLayer);
changed();
}
function changed() {
persist();
schedule();
}
function syncFields() {
const t = tpl();
for (const id of FIELDS) $(`#pp-f-${id}`).hidden = !t.fields.includes(id);
$("#pp-shade-row").hidden = !t.bleed;
radio($("#pp-templates"), "v", t.id);
$("#pp-template-desc").textContent = t.desc;
}
function buildPanel() {
const tpls = $("#pp-templates");
tpls.replaceChildren(...TEMPLATES.map((t) => el("button", {
type: "button", class: "pp-tpl", role: "radio", "aria-checked": String(S.template === t.id), data: { v: t.id }, title: t.desc,
onclick: async () => {
S.template = t.id;
S.font = t.font;
S.treatment = t.treatment;
radio($("#pp-fonts"), "v", S.font);
radio($("#pp-treatment"), "v", S.treatment);
syncFields();
await ensureFonts();
changed();
},
}, [el("canvas", { data: { tpl: t.id } }), el("span", { text: t.nome })])));
const fonts = $("#pp-fonts");
fonts.replaceChildren(...FONTS.map((f) => {
const b = el("button", { type: "button", class: "font-opt", role: "radio", "aria-checked": String(S.font === f.id), data: { v: f.id }, text: f.nome });
b.style.fontFamily = `"${f.heavy[1]}"`;
b.style.fontWeight = String(f.heavy[0]);
b.addEventListener("click", async () => { S.font = f.id; radio(fonts, "v", f.id); await ensureFonts(); changed(); });
return b;
}));
const formats = $("#pp-format");
formats.replaceChildren(...Object.keys(FORMATS).map((k) => el("button", {
type: "button", role: "radio", "aria-checked": String(S.format === k), data: { v: k }, text: k,
title: `${FORMATS[k][0]}×${FORMATS[k][1]}`,
onclick: () => { S.format = k; radio(formats, "v", k); changed(); },
})));
swatches($("#pp-text-colors"), TEXT_COLORS, "textColor");
swatches($("#pp-accent-colors"), ACCENT_COLORS, "accent");
syncFields();
}
function syncInputs() {
for (const id of FIELDS) $(`#pp-${id}`).value = S.texts[id] || "";
$("#pp-upper").checked = S.upper;
$("#pp-bg-y").value = String(S.bgY);
$("#pp-bg-zoom").value = String(S.bgZoom);
$("#pp-text-scale").value = String(S.textScale);
$("#pp-shade").value = String(S.shade);
$("#pp-grain").checked = S.grain;
radio($("#pp-treatment"), "v", S.treatment);
}
function wire() {
if (wired) return;
wired = true;
buildPanel();
syncInputs();
for (const id of FIELDS) $(`#pp-${id}`).addEventListener("input", (e) => { S.texts[id] = e.target.value; changed(); });
const num = (id, key) => $(id).addEventListener("input", (e) => { S[key] = Number(e.target.value); changed(); });
num("#pp-bg-y", "bgY");
num("#pp-bg-zoom", "bgZoom");
num("#pp-text-scale", "textScale");
num("#pp-shade", "shade");
$("#pp-upper").addEventListener("change", (e) => { S.upper = e.target.checked; changed(); });
$("#pp-treatment").addEventListener("click", (e) => {
const b = e.target.closest("[data-v]");
if (!b) return;
S.treatment = b.dataset.v;
radio($("#pp-treatment"), "v", S.treatment);
changed();
});
$("#pp-grain").addEventListener("change", (e) => { S.grain = e.target.checked; changed(); });
$("#pp-clear-texts").addEventListener("click", () => {
for (const id of FIELDS) S.texts[id] = "";
syncInputs();
changed();
});
$("#pp-add-logo").addEventListener("change", async (e) => {
const files = [...e.target.files];
e.target.value = "";
for (const f of files) await addFromFile("logo", f);
});
$("#pp-add-photo").addEventListener("click", () => openPicker("livello"));
$("#pp-layer-color").addEventListener("click", (e) => {
const b = e.target.closest("[data-v]");
if (!b || !selected) return;
selected.mode = b.dataset.v;
relayer();
});
$("#pp-layer-shape").addEventListener("click", (e) => {
const b = e.target.closest("[data-v]");
if (!b || !selected) return;
selected.shape = b.dataset.v;
relayer();
});
$("#pp-layer-key").addEventListener("change", (e) => { if (selected) { selected.key = e.target.checked; relayer(); } });
$("#pp-layer-size").addEventListener("input", (e) => {
if (!selected) return;
const v = Number(e.target.value);
if (selected.manual) selected.w = 0.4 * v; else selected.scale = v;
persistLayers();
schedule();
});
$("#pp-layer-reset").addEventListener("click", () => { if (selected) { selected.manual = false; selected.scale = 1; relayer(); } });
$("#pp-layer-up").addEventListener("click", () => selected && moveLayer(selected, 1));
$("#pp-layer-down").addEventListener("click", () => selected && moveLayer(selected, -1));
$("#pp-layer-remove").addEventListener("click", () => selected && removeLayer(selected));
$("#poster-pick").addEventListener("click", () => openPicker("sfondo"));
$("#pp-bg-remove").addEventListener("click", () => { bgImg = null; S.bg = null; $("#pp-bg-label").textContent = "Scegli immagine"; changed(); });
$("#picker-close").addEventListener("click", () => $("#picker").close());
$("#picker").addEventListener("click", (e) => { if (e.target === $("#picker")) $("#picker").close(); });
$("#picker-scope").addEventListener("click", (e) => {
const b = e.target.closest("[data-v]");
if (!b) return;
pickerScope = b.dataset.v;
fillPicker();
});
$("#picker-file").addEventListener("change", (e) => { uploadPicked(e.target.files[0]); e.target.value = ""; });
$("#pp-save").addEventListener("click", save);
$("#pp-download").addEventListener("click", download);
const stage = $("#poster-stage");
stage.addEventListener("dragover", (e) => e.preventDefault());
stage.addEventListener("drop", (e) => {
const files = [...(e.dataTransfer?.files || [])].filter((f) => f.type.startsWith("image/"));
if (!files.length) return;
e.preventDefault();
(async () => { for (const f of files) await addFromFile("logo", f); })();
});
wireCanvas();
new ResizeObserver(() => syncOverlay()).observe($("#poster-wrap"));
}
async function restore() {
if (!layers.length) {
const saved = prefs.get("posterLayers", null);
const legacy = prefs.get("posterLogo", null);
const list = saved || (legacy ? [{ id: newId(), kind: "logo", nome: "Logo", src: legacy, mode: "originale", key: true, shape: "libera", scale: 1, manual: false, x: 0.5, y: 0.5, w: 0.4 }] : []);
for (const l of list) {
try {
l.img = await loadImage(l.src);
processLayer(l);
layers.push(l);
} catch { /* livello illeggibile: lo salto */ }
}
if (legacy) prefs.set("posterLogo", null);
persistLayers();
renderLayerList();
}
if (S.bg && !bgImg) {
try {
bgImg = await loadImage(mediaUrl(S.bg));
$("#pp-bg-label").textContent = "Cambia immagine";
} catch { S.bg = null; }
}
}
window.PosterStudio = {
async show() {
wire();
const [W, H] = FORMATS[S.format] || FORMATS["2:3"];
const cv = canvas();
if (cv.width !== W || cv.height !== H) { cv.width = W; cv.height = H; }
await Promise.all([ensureFonts(), restore()]);
render();
},
async setBackground(path) {
wire();
await Promise.all([ensureFonts(), restore()]);
await setBackground(path);
},
};
})();
;
/* Locandina: template con strutture diverse, testi con font veri, loghi e foto come livelli
da spostare e ridimensionare sulla tela. */
(() => {
const FONTS = [
{ id: "oswald", nome: "Oswald", heavy: [700, "PR Oswald"], medium: [500, "PR Oswald"], track: 0.01 },
{ id: "anton", nome: "Anton", heavy: [400, "PR Anton"], medium: [500, "PR Oswald"], track: 0.01 },
{ id: "bebas", nome: "Bebas Neue", heavy: [400, "PR Bebas"], medium: [400, "PR Bebas"], track: 0.04 },
{ id: "archivo", nome: "Archivo Black", heavy: [400, "PR Archivo"], medium: [600, "PR Inter"], track: 0 },
{ id: "inter", nome: "Inter", heavy: [800, "PR Inter"], medium: [600, "PR Inter"], track: -0.01 },
{ id: "playfair", nome: "Playfair", heavy: [900, "PR Playfair"], medium: [700, "PR Playfair"], track: 0 },
{ id: "marker", nome: "Marker", heavy: [400, "PR Marker"], medium: [500, "PR Oswald"], track: 0 },
];
const BODY = [600, "PR Inter"];
const FORMATS = { "2:3": [2000, 3000], A4: [2000, 2828], "4:5": [2000, 2500], "9:16": [1800, 3200], "1:1": [2000, 2000] };
const TEXT_COLORS = ["#f6f5f0", "#ffffff", "#111111", "#ffd600"];
const ACCENT_COLORS = ["#ffd600", "#ff3b3b", "#ff7a1a", "#cbbcff", "#4dd4ff", "#f6f5f0"];
const FIELDS = ["titolo", "tag", "lineup", "data", "ora", "luogo", "info"];
const SAMPLE = {
titolo: "Notte acustica",
tag: "Live in bottega",
lineup: "The Lanterns\nMara Vento\nI Cortili",
data: "Venerdì 12 dicembre",
ora: "Ore 21:00",
luogo: "Teatro comunale",
info: "Ingresso libero",
};
const MONTHS = ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"];
const TEMPLATES = [
{ id: "classica", nome: "Classica", desc: "Logo o titolo in alto, foto naturale, informazioni a colonne.", fields: ["titolo", "tag", "data", "ora", "luogo", "info"], bleed: true, font: "oswald", treatment: "naturale" },
{ id: "lineup", nome: "Line-up", desc: "Festival: più band in evidenza, dalla principale alle altre.", fields: FIELDS, bleed: true, font: "bebas", treatment: "duotono" },
{ id: "headliner", nome: "Headliner", desc: "Un nome enorme in basso, gli altri in supporto, data in alto.", fields: ["tag", "lineup", "data", "ora", "luogo", "info"], bleed: true, font: "archivo", treatment: "bn" },
{ id: "data", nome: "Data gigante", desc: "Il giorno diventa la grafica, testi in colonna.", fields: FIELDS, bleed: true, font: "anton", treatment: "duotono" },
{ id: "fascia", nome: "Fascia", desc: "Foto sopra, fascia di colore pieno con i testi.", fields: FIELDS, bleed: false, font: "oswald", treatment: "naturale" },
{ id: "minimal", nome: "Minimal", desc: "Carta chiara, foto incorniciata, griglia tipografica.", fields: FIELDS, bleed: false, light: true, font: "inter", treatment: "bn" },
];
const defaults = {
template: "classica",
bg: null,
bgY: 0.5,
bgZoom: 1,
texts: { ...SAMPLE },
upper: true,
font: "oswald",
textScale: 1,
textColor: "#f6f5f0",
accent: "#ffd600",
format: "2:3",
treatment: "naturale",
shade: 0.85,
grain: true,
};
const S = { ...structuredClone(defaults), ...prefs.get("poster", {}) };
S.texts = { ...defaults.texts, ...(S.texts || {}) };
if (!TEMPLATES.some((t) => t.id === S.template)) S.template = "classica";
delete S.layout;
let layers = [];
const processed = new Map();
let rects = new Map();
let textRects = [];
let selected = null;
let bgImg = null;
let grain = null;
let pending = 0;
let thumbTimer = 0;
let wired = false;
const canvas = () => $("#poster-canvas");
const tpl = (id = S.template) => TEMPLATES.find((t) => t.id === id) || TEMPLATES[0];
const font = () => FONTS.find((f) => f.id === S.font) || FONTS[0];
const fontCss = ([weight, family], size) => `${weight} ${Math.round(size)}px "${family}"`;
const persist = () => prefs.set("poster", S);
const persistLayers = () => prefs.set("posterLayers", layers.map(({ id, kind, nome, src, mode, key, shape, scale, manual, x, y, w }) => ({ id, kind, nome, src, mode, key, shape, scale, manual, x, y, w })));
const upper = (v) => (S.upper ? v.toLocaleUpperCase("it-IT") : v);
const txt = (id) => upper((S.texts[id] || "").trim());
const lineup = () => (S.texts.lineup || "").split("\n").map((l) => upper(l.trim())).filter(Boolean);
/** I loghi prendono il posto dei primi nomi della line-up: a testo restano le band senza logo. */
const rest = (auto) => lineup().slice(auto.length);
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error("Immagine non leggibile"));
img.src = src;
});
}
function hexRgb(hex) {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
const isLight = (hex) => {
const [r, g, b] = hexRgb(hex);