4,476
edits
No edit summary |
No edit summary |
||
Line 1,368: | Line 1,368: | ||
// Inject the printable HTML | // Inject the printable HTML | ||
doc.body.innerHTML = $print.prop("outerHTML"); | doc.body.innerHTML = $print.prop("outerHTML"); | ||
// Remove “empty” optional sections so they don’t leave gaps in print. | |||
(function pruneEmptySections(doc) { | |||
function isEffectivelyEmpty(el) { | |||
// Text with whitespace-only (incl. NBSP/zero-width) & no images/links | |||
var txt = (el.textContent || "") | |||
.replace(/\u00A0/g, " ") // NBSP | |||
.replace(/\u200B/g, "") // zero-width space | |||
.replace(/\s+/g, " ") // compress whitespace | |||
.trim(); | |||
var hasImg = el.getElementsByTagName("img").length > 0; | |||
var hasLink = el.getElementsByTagName("a").length > 0; | |||
return !txt && !hasImg && !hasLink; | |||
} | |||
function removeIfEmpty(selector, labelSelector) { | |||
var node = doc.querySelector(selector); | |||
if (node && isEffectivelyEmpty(node)) { | |||
// remove paired label just before the node, if present | |||
if (labelSelector) { | |||
var prev = node.previousElementSibling; | |||
if (prev && prev.matches && prev.matches(labelSelector)) { | |||
if (prev.parentNode) prev.parentNode.removeChild(prev); | |||
} | |||
} | |||
if (node.parentNode) node.parentNode.removeChild(node); | |||
} | |||
} | |||
// Image block: kill if there is no <img src> inside | |||
(function () { | |||
var imgWrap = doc.querySelector(".article-images"); | |||
if (!imgWrap) return; | |||
var imgs = imgWrap.getElementsByTagName("img"); | |||
var hasRealImg = false; | |||
for (var i = 0; i < imgs.length; i++) { | |||
if (imgs[i].getAttribute("src")) { | |||
hasRealImg = true; | |||
break; | |||
} | |||
} | |||
if (!hasRealImg && imgWrap.parentNode) { | |||
imgWrap.parentNode.removeChild(imgWrap); | |||
} | |||
})(); | |||
// Description / Reflection / External reference / Quote | |||
removeIfEmpty(".article-description", ".article-label-description"); | |||
removeIfEmpty(".article-reflection", ".article-label-reflection"); | |||
removeIfEmpty( | |||
".article-external-reference", | |||
".article-label-external-reference" | |||
); | |||
removeIfEmpty(".article-quote", ".article-label-quote"); | |||
// Metadata: if all values are empty, remove the whole grid | |||
(function () { | |||
var meta = doc.querySelector(".article-metadata"); | |||
if (!meta) return; | |||
var values = meta.querySelectorAll(".article-metadata-value"); | |||
var allEmpty = true; | |||
for (var i = 0; i < values.length; i++) { | |||
if (!isEffectivelyEmpty(values[i])) { | |||
allEmpty = false; | |||
break; | |||
} | |||
} | |||
if (allEmpty && meta.parentNode) { | |||
meta.parentNode.removeChild(meta); | |||
} | |||
})(); | |||
})(doc); | |||
// --- PDF-friendly links for Chrome on macOS --- | // --- PDF-friendly links for Chrome on macOS --- |