From e9062fd9568d4d9eff9e2ef9abc118190681c296 Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Sun, 24 Sep 2023 20:24:09 -0700 Subject: [PATCH] Add "copy to clipboard" button for each code block --- index.html | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/index.html b/index.html index ba901a0..d513f98 100644 --- a/index.html +++ b/index.html @@ -85,6 +85,32 @@ line-height: 1.5; } + pre { + display: flex; + justify-content: space-between; + } + + button { + align-self: start; + min-inline-size: 26px; + padding: 0; + background: unset; + border: unset; + cursor: pointer; + } + + svg { + display: block; + pointer-events: none; + opacity: 0.5; + transition: opacity 400ms; + } + + :is(pre:hover, pre:focus-within) svg { + transition: opacity 200ms; + opacity: 0.9; + } + pre, code { border-radius: 4px; @@ -347,6 +373,31 @@ new ResizeObserver(debounce(() => { elem2.style.setProperty('--lines', lines); elem2.style.setProperty('height', `${lines * lineHeight}px`); }, 200)).observe(elem2); + + // Insert "Copy to clipboard" icon button to all code blocks + const clipboardSVG = ` + + + `; + const checkSVG = ''; + document.querySelectorAll('pre').forEach(pre => { + pre.insertAdjacentHTML('beforeend', ``); + }); + + function copy(event) { + const button = event.target; + const code = button.closest('pre').querySelector('code').textContent; + navigator.clipboard.writeText(code); + const svg = button.querySelector('svg'); + svg.style.setProperty('stroke', 'green'); + svg.innerHTML = checkSVG; + setTimeout(() => { + svg.innerHTML = clipboardSVG; + svg.style.setProperty('stroke', 'currentColor'); + }, 2000); + } + + document.querySelectorAll('button').forEach(button => button.addEventListener('click', copy)); -- 2.47.3