From 7b7064ad2be68e8d6d43123c12529ca94a325fcb Mon Sep 17 00:00:00 2001 From: Jacky Zhao Date: Sun, 20 Aug 2023 15:38:37 -0700 Subject: [PATCH] fix: ensure code exists inside pre before adding clipboard --- quartz/components/scripts/clipboard.inline.ts | 42 ++++++++++--------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/quartz/components/scripts/clipboard.inline.ts b/quartz/components/scripts/clipboard.inline.ts index 76d1b58..c604c9b 100644 --- a/quartz/components/scripts/clipboard.inline.ts +++ b/quartz/components/scripts/clipboard.inline.ts @@ -7,25 +7,27 @@ document.addEventListener("nav", () => { const els = document.getElementsByTagName("pre") for (let i = 0; i < els.length; i++) { const codeBlock = els[i].getElementsByTagName("code")[0] - const source = codeBlock.innerText.replace(/\n\n/g, "\n") - const button = document.createElement("button") - button.className = "clipboard-button" - button.type = "button" - button.innerHTML = svgCopy - button.ariaLabel = "Copy source" - button.addEventListener("click", () => { - navigator.clipboard.writeText(source).then( - () => { - button.blur() - button.innerHTML = svgCheck - setTimeout(() => { - button.innerHTML = svgCopy - button.style.borderColor = "" - }, 2000) - }, - (error) => console.error(error), - ) - }) - els[i].prepend(button) + if (codeBlock) { + const source = codeBlock.innerText.replace(/\n\n/g, "\n") + const button = document.createElement("button") + button.className = "clipboard-button" + button.type = "button" + button.innerHTML = svgCopy + button.ariaLabel = "Copy source" + button.addEventListener("click", () => { + navigator.clipboard.writeText(source).then( + () => { + button.blur() + button.innerHTML = svgCheck + setTimeout(() => { + button.innerHTML = svgCopy + button.style.borderColor = "" + }, 2000) + }, + (error) => console.error(error), + ) + }) + els[i].prepend(button) + } } })