` }; const BREAKPOINT = 900; const MAX_IMAGES = 3; const IMAGE_EXT = ".jpg"; const app = document.getElementById("app"); let mode = null; let cachedImages = null; const imageRatio = {}; let cachedImageProbePromise = null; const escapeHTML = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); const AUTORI = { gigi: { img: "https://www.businesscommunity.it/m/lib/gigib_200.jpg", url: "https://businesscommunity.it/gigi", nome: "Gigi Beltrame" }, claudio: { img: "https://www.businesscommunity.it/m/lib/claudio.jpg", // <-- da verificare url: "https://businesscommunity.it/", // <-- da verificare nome: "Claudio Gandolfo" } }; function authorBoxHTML() { return (ARTICLE.autori || []).map(k => { const a = AUTORI[k]; if (!a) return ""; return `
${a.nome}

${a.nome}

`; }).join(""); } /* ============================================================ SOCIAL SHARE ============================================================ */ function socialShareHTML(size = 20) { const loc = window.location; const hostPath = loc.host + loc.pathname + loc.search; const hostPathEnc = encodeURIComponent(hostPath); const httpsUrlEnc = encodeURIComponent('https://' + hostPath); return `
`; } /* ============================================================ TOKENIZE ============================================================ */ function tokenize(html) { const tokens = []; const parser = new DOMParser(); const doc = parser.parseFromString(html, "text/html"); const INLINE = new Set(['em','strong','b','i','a','span','u','s','code','small','sub','sup','mark','cite','q','abbr','font','del','ins','kbd','var','time']); const BLOCK = new Set(['p','div','h1','h2','h3','h4','h5','h6','li','blockquote','section','article','header','footer','figure','figcaption','ul','ol','table','tr','td','th','pre']); let paraStart = true; let pendingSpace = false; function walk(node, openTags) { if (node.nodeType === Node.TEXT_NODE) { const text = node.textContent; if (!text) return; const parts = text.split(/(\s+)/); for (const part of parts) { if (!part) continue; if (/^\s+$/.test(part)) { pendingSpace = true; } else { tokens.push({ type: 'w', text: part, tags: openTags, paraStart: paraStart, spaceBefore: pendingSpace }); pendingSpace = false; paraStart = false; } } return; } if (node.nodeType !== Node.ELEMENT_NODE) return; const tag = node.tagName.toLowerCase(); if (tag === 'br') { tokens.push({ type: 'br' }); pendingSpace = false; return; } if (tag === 'h3') { tokens.push({ type: 'h3', html: node.innerHTML }); paraStart = true; pendingSpace = false; return; } if (tag === 'h1' || tag === 'h2') { return; } const isBlock = BLOCK.has(tag); const isInline = INLINE.has(tag); let newOpenTags = openTags; if (isInline) { const attrs = {}; for (const attr of node.attributes) attrs[attr.name] = attr.value; newOpenTags = [...openTags, { tag, attrs }]; } if (isBlock) paraStart = true; for (const child of node.childNodes) { walk(child, newOpenTags); } if (isBlock) paraStart = true; } for (const child of doc.body.childNodes) { walk(child, []); } tokens.push({ type: 'endmark' }); return tokens; } function sameTags(a, b) { if (a === b) return true; if (!a || !b || a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i].tag !== b[i].tag) return false; const ka = Object.keys(a[i].attrs); const kb = Object.keys(b[i].attrs); if (ka.length !== kb.length) return false; for (const k of ka) { if (a[i].attrs[k] !== b[i].attrs[k]) return false; } } return true; } function wrapInTags(html, tags) { if (!tags || !tags.length) return html; for (let i = tags.length - 1; i >= 0; i--) { const t = tags[i]; const attrs = Object.entries(t.attrs) .map(([k, v]) => ` ${k}="${escapeHTML(v)}"`).join(""); html = `<${t.tag}${attrs}>${html}`; } return html; } function renderTokens(tokens, start, end, opts = {}) { const { lede = false, mark = false } = opts; const out = []; let bufHTML = ""; let groupWords = []; let currentTags = null; let firstP = true; const flushGroup = () => { if (!groupWords.length) return; let groupHTML = ""; for (let i = 0; i < groupWords.length; i++) { const w = groupWords[i]; if (i > 0 && w.spaceBefore) groupHTML += " "; groupHTML += w.html; } const firstW = groupWords[0]; if (bufHTML && !firstW.paraStart && firstW.spaceBefore) { bufHTML += " "; } bufHTML += wrapInTags(groupHTML, currentTags); groupWords = []; currentTags = null; }; const flushParagraph = () => { flushGroup(); if (bufHTML) { const cls = lede && firstP ? ' class="lede"' : ""; out.push(`${bufHTML}

`); bufHTML = ""; if (lede && firstP) firstP = false; } }; for (let i = start; i < end; i++) { const t = tokens[i]; const isLast = i === end - 1; if (t.type === "h3") { flushParagraph(); let content = t.html; if (mark && isLast) content = `${content}`; out.push(`

${content}

`); } else if (t.type === "endmark") { flushParagraph(); out.push(`
Business Community
Sommario Magazine
`); out.push(`
${socialShareHTML(20)}
`); out.push(`
`); } else if (t.type === "br") { flushGroup(); bufHTML += "
"; } else { if (t.paraStart) flushParagraph(); if (currentTags === null) { currentTags = t.tags; } else if (!sameTags(currentTags, t.tags)) { flushGroup(); currentTags = t.tags; } let w = escapeHTML(t.text); if (mark && isLast) w = `${w}`; groupWords.push({ html: w, spaceBefore: t.spaceBefore, paraStart: t.paraStart }); } } flushParagraph(); return out.join(""); } function loadImages() { if (cachedImageProbePromise) return cachedImageProbePromise; cachedImageProbePromise = (async () => { const phpImages = ["Benessere_e_relax_esclusivo_alle_Seychelles.jpg"]; cachedImages = Array.isArray(phpImages) ? phpImages : []; return cachedImages; })(); return cachedImageProbePromise; } function mastheadHTML() { return `
${escapeHTML(ARTICLE.date)}
${escapeHTML(ARTICLE.category)}

${escapeHTML(ARTICLE.title)}

${escapeHTML(ARTICLE.standfirst || "")}

`; } function renderCoverHTML(imageSrc) { const src = imageSrc || ARTICLE.coverImage || ""; return `

${escapeHTML(ARTICLE.title)}

${escapeHTML(ARTICLE.standfirst || "")}

`; } /* ============================================================ AD BANNER (Sovrapposti: Google davanti, Iframe dietro) ============================================================ */ let adCounter = 0; let divAdIndex = 0; function adProbeHTML() { return ``; } function adHTML() { const adId = `div-gpt-ad-box_inside_content_0${divAdIndex}`; divAdIndex = (divAdIndex + 1) % 10; return `
`; } /* ============================================================ MISURAZIONE COLONNA ============================================================ */ function measureSingleColumn(tokens, start, total, width, height, lede = false, cls = "text-style") { const wrapper = document.createElement("div"); wrapper.style.cssText = "position:fixed;left:-9999px;top:0;visibility:hidden;pointer-events:none;z-index:-1;"; const m = document.createElement("div"); m.className = cls; m.style.width = width + "px"; m.style.height = height + "px"; m.style.overflow = "hidden"; m.style.display = "block"; wrapper.appendChild(m); document.body.appendChild(wrapper); const fits = (n) => { m.innerHTML = renderTokens(tokens, start, start + n, { mark: true, lede }); let lastEl = m.querySelector(".marker"); if (!lastEl) lastEl = m.lastElementChild; if (!lastEl) return true; const box = m.getBoundingClientRect(); const rect = lastEl.getBoundingClientRect(); return rect.bottom <= box.bottom +2; }; let lo = 0, hi = total - start; while (lo < hi) { const mid = Math.ceil((lo + hi) / 2); if (fits(mid)) lo = mid; else hi = mid - 1; } wrapper.remove(); return Math.max(1, lo); } function avoidOrphanHeading(tokens, start, n) { if (n <= 1) return n; if (tokens[start + n - 1] && tokens[start + n - 1].type === "h3") return n - 1; return n; } /* ============================================================ BUILD PAGINATED (schermo) ============================================================ */ async function buildPaginated(images, colsPerPage) { const tokens = tokenize(ARTICLE.text); const total = tokens.length; const isDesktop = colsPerPage > 1; const probeHero = document.createElement("section"); probeHero.className = "spread spread--first measurer"; probeHero.innerHTML = ` ${mastheadHTML()}
${Array.from({length: colsPerPage}, (_, i) => { const hasAd = (i === colsPerPage - 1) && isDesktop; return `
${i === 0 ? `
${socialShareHTML(20)}
` : ''} ${i === 0 ? authorBoxHTML() : ''}
${hasAd ? adProbeHTML() : ''}
`; }).join('')}
`; document.body.appendChild(probeHero); const heroColEls = probeHero.querySelectorAll(".hero-col"); const colW = heroColEls[0].getBoundingClientRect().width; const heroTextEls = probeHero.querySelectorAll(".hero-text"); const heroTextH = Array.from(heroTextEls).map(el => el.getBoundingClientRect().height); probeHero.remove(); const probePage = document.createElement("section"); probePage.className = "spread spread--page measurer"; probePage.innerHTML = `
${Array.from({length: colsPerPage}, (_, i) => { const hasAd = (i === colsPerPage - 1) && isDesktop; return `
${hasAd ? adProbeHTML() : ''}
`; }).join('')}
`; document.body.appendChild(probePage); const pageTextEls = probePage.querySelectorAll(".page-text"); const pageTextH = Array.from(pageTextEls).map(el => el.getBoundingClientRect().height); probePage.remove(); /* Misura altezza testo su mobile CON annuncio */ let pageTextWithAdH = 0; if (!isDesktop) { const probePageWithAd = document.createElement("section"); probePageWithAd.className = "spread spread--page measurer"; probePageWithAd.innerHTML = `
${adProbeHTML()}
`; document.body.appendChild(probePageWithAd); pageTextWithAdH = probePageWithAd.querySelector(".page-text").getBoundingClientRect().height; probePageWithAd.remove(); } let figH = 0; { const probeFig = document.createElement("section"); probeFig.className = "spread spread--figure spread--figtext measurer"; probeFig.innerHTML = `
${Array.from({length: colsPerPage}, () => `
`).join('')}
`; document.body.appendChild(probeFig); figH = probeFig.querySelector(".page-text").getBoundingClientRect().height; probeFig.remove(); } if (colW < 40) return; const pagesData = []; let cursor = 0; if (!ARTICLE.cover) { const heroCols = []; for (let i = 0; i < colsPerPage; i++) { const h = Math.max(40, heroTextH[i] || 0); if (cursor >= total) { heroCols.push({ start: cursor, end: cursor }); } else { const start = cursor; const isLede = (i === 0); let n = measureSingleColumn(tokens, cursor, total, colW, h, isLede); n = Math.max(1, avoidOrphanHeading(tokens, cursor, n)); cursor += n; heroCols.push({ start, end: cursor }); } } pagesData.push({ isHero: true, isFigure: false, cols: heroCols }); } const makeFigure = (imgSrc) => { if (cursor >= total || figH < 30) { return { isHero: false, isFigure: true, imageSrc: imgSrc }; } const figCols = []; for (let i = 0; i < colsPerPage; i++) { if (cursor >= total) { figCols.push({ start: cursor, end: cursor }); } else { const start = cursor; const h = Math.max(40, figH); let n = measureSingleColumn(tokens, cursor, total, colW, h, false); n = Math.max(1, avoidOrphanHeading(tokens, cursor, n)); cursor += n; figCols.push({ start, end: cursor }); } } return { isHero: false, isFigure: true, imageSrc: imgSrc, cols: figCols }; }; const textPage = (withLede = false, withAd = true) => { const pageCols = []; for (let i = 0; i < colsPerPage; i++) { let h; if (isDesktop) { h = Math.max(40, pageTextH[i] || 0); } else { h = withAd ? pageTextWithAdH : (pageTextH[0] || 0); } if (cursor >= total) { pageCols.push({ start: cursor, end: cursor }); } else { const start = cursor; const isLede = withLede && i === 0; let n = measureSingleColumn(tokens, cursor, total, colW, h, isLede); n = Math.max(1, avoidOrphanHeading(tokens, cursor, n)); cursor += n; pageCols.push({ start, end: cursor }); } } return { isHero: false, isFigure: false, hasAd: withAd, withLede, cols: pageCols }; }; if (ARTICLE.cover) { pagesData.push({ isCover: true, imageSrc: images.length > 0 ? images[0] : ARTICLE.coverImage }); if (cursor < total) pagesData.push(textPage(true, true)); const remaining = images.slice(1); if (isDesktop) { const figs = remaining.map(src => makeFigure(src)); let k = 0; while (k < figs.length) { const f = figs[k]; if (k >= 1 && !f.cols) { const group = [f.imageSrc]; while (k + 1 < figs.length && !figs[k + 1].cols) group.push(figs[++k].imageSrc); pagesData.push(group.length > 1 ? { isHero: false, isFigure: true, multi: group } : f); } else { pagesData.push(f); } k++; } while (cursor < total && pagesData.length < 50) pagesData.push(textPage()); } else { const queue = remaining.slice(); let mobileAdCounter = 1; while (pagesData.length < 50) { const isEvenPage = (pagesData.length + 1) % 2 === 0; if (isEvenPage && queue.length) { if (cursor >= total && queue.length > 1) { pagesData.push({ isHero: false, isFigure: true, multi: queue.splice(0) }); } else { pagesData.push(makeFigure(queue.shift())); } } else if (cursor < total) { const showAd = mobileAdCounter % 2 === 0; mobileAdCounter++; pagesData.push(textPage(false, showAd)); } else { break; } } if (queue.length) { pagesData.push(queue.length > 1 ? { isHero: false, isFigure: true, multi: queue.splice(0) } : { isHero: false, isFigure: true, imageSrc: queue.shift() }); } } } else if (isDesktop) { const figs = images.map(src => makeFigure(src)); let k = 0; while (k < figs.length) { const f = figs[k]; if (k >= 1 && !f.cols) { const group = [f.imageSrc]; while (k + 1 < figs.length && !figs[k + 1].cols) group.push(figs[++k].imageSrc); pagesData.push(group.length > 1 ? { isHero: false, isFigure: true, multi: group } : f); } else { pagesData.push(f); } k++; } while (cursor < total && pagesData.length < 50) pagesData.push(textPage()); } else { const queue = images.slice(); let mobileAdCounter = 0; while (pagesData.length < 50) { const isEvenPage = (pagesData.length + 1) % 2 === 0; if (isEvenPage && queue.length) { if (cursor >= total && queue.length > 1) { pagesData.push({ isHero: false, isFigure: true, multi: queue.splice(0) }); } else { pagesData.push(makeFigure(queue.shift())); } } else if (cursor < total) { const showAd = mobileAdCounter % 2 === 0; mobileAdCounter++; pagesData.push(textPage(false, showAd)); } else { break; } } if (queue.length) { pagesData.push(queue.length > 1 ? { isHero: false, isFigure: true, multi: queue.splice(0) } : { isHero: false, isFigure: true, imageSrc: queue.shift() }); } } app.innerHTML = pagesData.map(p => { if (p.isCover) return renderCoverHTML(p.imageSrc); if (p.isHero) { const cols = []; for (let j = 0; j < colsPerPage; j++) { const isLastCol = j === colsPerPage - 1; const hasAd = isLastCol && isDesktop; const colClass = `hero-col${hasAd ? ' page-col--ad' : ''}`; const c = p.cols[j] || { start: 0, end: 0 }; cols.push(`
${j === 0 ? `
${socialShareHTML(20)}
` : ''} ${j === 0 ? authorBoxHTML() : ''}
${renderTokens(tokens, c.start, c.end, { lede: j === 0 })}
${hasAd ? adHTML() : ''}
`); } return `
${mastheadHTML()}
${cols.join('')}
`; } if (p.multi) { return `
${p.multi.map(src => `
`).join('')}
`; } if (p.isFigure && p.cols) { return `
${p.cols.map(c => `
${renderTokens(tokens, c.start, c.end)}
`).join('')}
`; } if (p.isFigure) { return `
`; } const cols = []; for (let j = 0; j < colsPerPage; j++) { const isLastCol = j === colsPerPage - 1; const hasAd = isLastCol && p.hasAd; const colClass = `page-col${hasAd ? ' page-col--ad' : ''}`; const c = p.cols[j] || { start: 0, end: 0 }; cols.push(`
${renderTokens(tokens, c.start, c.end, { lede: p.withLede && j === 0 })}
${hasAd ? adHTML() : ''}
`); } return `
${cols.join('')}
`; }).join(""); } async function build() { adCounter = 0; divAdIndex = 0; const isDesktop = window.innerWidth >= BREAKPOINT; mode = isDesktop ? "desktop" : "mobile"; const images = await loadImages(); await Promise.all((ARTICLE.autori || []).map(k => new Promise(r => { const im = new Image(); im.onload = im.onerror = r; im.src = AUTORI[k].img; }))); try { await Promise.race([document.fonts.ready, new Promise(r => setTimeout(r, 2500))]); } catch (e) {} await buildPaginated(images, isDesktop ? 3 : 1); } let resizeTimer; window.addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { const next = window.innerWidth >= BREAKPOINT ? "desktop" : "mobile"; if (next !== mode) build(); }, 200); }); const bar = document.getElementById("progressBar"); window.addEventListener("scroll", () => { const el = document.documentElement; const max = el.scrollHeight - el.clientHeight; const p = max > 0 ? el.scrollTop / max : 0; bar.style.transform = `scaleX(${Math.min(1, Math.max(0, p))})`; }, { passive: true }); function renderPrintLayout() { const images = cachedImages || []; const tokens = tokenize(ARTICLE.text); const img1 = images.length > 0 ? images[0] : null; const MM = 96 / 25.4; const GAP = 6; const COL = (190 - 2 * GAP) / 3; const TWO_COLS = 2 * COL + GAP; let topHTML = ""; let n = 0; if (img1) { const ratio = imageRatio[img1] || 0.6; const hMM = Math.min(TWO_COLS * ratio, 105); n = measureSingleColumn(tokens, 0, tokens.length, COL * MM, hMM * MM, true, "print-measure"); n = Math.max(1, avoidOrphanHeading(tokens, 0, n)); topHTML = ` `; } const extra = images.slice(1); let restHTML = renderTokens(tokens, n, tokens.length, { lede: !img1 }); if (n > 0 && tokens[n] && tokens[n].type === "w" && tokens[n].paraStart) { restHTML = restHTML.replace("

", '

'); } const blocks = restHTML.split(/(?<=<\/p>|<\/h3>|<\/div>)/); const paraEnds = []; blocks.forEach((b, i) => { if (b.endsWith("

") && i < blocks.length - 2) paraEnds.push(i); }); const inserts = new Map(); extra.forEach((src, k) => { let pos = paraEnds.length ? paraEnds[Math.min(paraEnds.length - 1, Math.floor(paraEnds.length * (k + 1) / (extra.length + 1)))] : Math.max(0, blocks.length - 1); inserts.set(pos, (inserts.get(pos) || "") + ``); }); const flowHTML = blocks.map((b, i) => b + (inserts.get(i) || "")).join(""); app.innerHTML = ` ${topHTML} `; } let wasDesktop = false; window.addEventListener("beforeprint", () => { wasDesktop = true; const consenso = document.getElementById("consenso"); if (consenso) consenso.remove(); const tcfLocator = document.querySelector('iframe[name="__tcfapiLocator"]'); if (tcfLocator) tcfLocator.remove(); document.querySelectorAll('iframe').forEach(iframe => { if (iframe.src.includes('doubleclick') || iframe.src.includes('themoneytizer') || iframe.src.includes('win.businesscommunity') || iframe.name === '__tcfapiLocator') { iframe.remove(); } }); renderPrintLayout(); }); window.addEventListener("afterprint", () => { if (wasDesktop) build(); wasDesktop = false; }); build();