From: Ardis Lu Date: Mon, 25 Sep 2023 03:24:09 +0000 (-0700) Subject: Add "copy to clipboard" button for each code block X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=e9062fd9568d4d9eff9e2ef9abc118190681c296;p=css-for-line-clamp-ellipsis Add "copy to clipboard" button for each code block --- 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));