Skip to content

Commit

Permalink
feat: add copy button for markdown code blocks (#2799)
Browse files Browse the repository at this point in the history
Co-authored-by: Fons van der Plas <[email protected]>
  • Loading branch information
chayandatta and fonsp authored Apr 11, 2024
1 parent 6a61511 commit ad6306d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
36 changes: 36 additions & 0 deletions frontend/components/CellOutput.js
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,18 @@ export let RawHTMLContainer = ({ body, className = "", persist_js_state = false,
} catch (err) {
console.warn("Highlighting failed", err)
}

// Find code blocks and add a copy button:
try {
if (container.firstElementChild?.matches("div.markdown")) {
container.querySelectorAll("pre > code").forEach((code_element) => {
const pre = code_element.parentElement
generateCopyCodeButton(pre)
})
}
} catch (err) {
console.warn("Adding markdown code copy button failed", err)
}
} finally {
js_init_set?.delete(container)
}
Expand Down Expand Up @@ -688,3 +700,27 @@ export let highlight = (code_element, language) => {
}
}
}

/**
* Generates a copy button for Markdown code blocks.
*/
export const generateCopyCodeButton = (/** @type {HTMLElement?} */ pre) => {
if (!pre) return

// create copy button
const button = document.createElement("button")
button.title = "Copy to Clipboard"
button.className = "markdown-code-block-button"
button.addEventListener("click", (e) => {
const txt = pre.textContent ?? ""
navigator.clipboard.writeText(txt)

button.classList.add("markdown-code-block-copied-code-button")
setTimeout(() => {
button.classList.remove("markdown-code-block-copied-code-button")
}, 2000)
})

// Append copy button to the code block element
pre.prepend(button)
}
29 changes: 29 additions & 0 deletions frontend/editor.css
Original file line number Diff line number Diff line change
Expand Up @@ -3681,3 +3681,32 @@ pluto-cell.hooked_up pluto-output {
justify-content: flex-end;
gap: 0.5em;
}

/* Styles for markdown copy Button*/
.markdown-code-block-button {
position: relative;
cursor: pointer;
justify-content: center;
align-items: center;
display: block;
padding: 0;
float: right;
border: none;
background: none;
}

.markdown-code-block-button::before {
content: "";
display: block;
width: 14px;
height: 14px;
filter: var(--image-filters);
}

.markdown-code-block-button::before {
background-image: url("https://unpkg.com/[email protected]/dist/svg/copy-outline.svg");
}

.markdown-code-block-copied-code-button::before {
background-image: url("https://unpkg.com/[email protected]/dist/svg/checkmark-outline.svg");
}

0 comments on commit ad6306d

Please sign in to comment.