Skip to content

Commit

Permalink
Introduce getHideableCopyButtonElements()
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner committed Apr 11, 2023
1 parent 31e06fc commit 5cf2065
Showing 1 changed file with 37 additions and 15 deletions.
52 changes: 37 additions & 15 deletions python_docs_theme/static/copybutton.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
// ``function*`` denotes a generator in JavaScript, see
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
function* getHideableCopyButtonElements(rootElement) {
// yield all elements with the "go" (Generic.Output),
// "gp" (Generic.Prompt), or "gt" (Generic.Traceback) CSS class
for (const el of rootElement.querySelectorAll('.go, .gp, .gt')) {
yield el
}
// tracebacks (.gt) contain bare text elements that need to be
// wrapped in a span to hide or show the element
for (let el of rootElement.querySelectorAll('.gt')) {
while ((el = el.nextSibling) && el.nodeType !== Node.DOCUMENT_NODE) {
// stop wrapping text nodes when we hit the next output or
// prompt element
if (el.nodeType === Node.ELEMENT_NODE && el.matches(".gp, .go")) {
break
}
// if the node is a text node with content, wrap it in a
// span element so that we can control visibility
if (el.nodeType === Node.TEXT_NODE && el.textContent.trim()) {
const wrapper = document.createElement('span')
el.after(wrapper)
wrapper.appendChild(el)
el = wrapper
}
yield el
}
}
}


const loadCopyButton = () => {
/* Add a [>>>] button on the top-right corner of code samples to hide
/* Add a [>>>] button in the top-right corner of code samples to hide
* the >>> and ... prompts and the output and thus make the code
* copyable. */
const hide_text = 'Hide the prompts and output'
Expand All @@ -18,24 +48,16 @@ const loadCopyButton = () => {
const codeEl = buttonEl.nextElementSibling
if (buttonEl.dataset.hidden === 'false') {
// hide the code output
codeEl.querySelectorAll('.go, .gp, .gt').forEach(el => el.hidden = true)
codeEl.querySelectorAll('.gt').forEach(el => {
while ((el = el.nextSibling) && el.nodeType !== Node.DOCUMENT_NODE) {
if (el.nodeType === Node.ELEMENT_NODE && el.matches(".gp, .go")) break;
if (el.nodeType === Node.TEXT_NODE && el.textContent.trim()) {
const wrapper = document.createElement('span');
el.after(wrapper);
wrapper.appendChild(el);
el = wrapper
}
el.hidden = true
}
})
for (const el of getHideableCopyButtonElements(codeEl)) {
el.hidden = true
}
buttonEl.title = show_text
buttonEl.dataset.hidden = "true"
} else {
// show the code output
codeEl.childNodes.forEach(el => el.hidden = false)
for (const el of getHideableCopyButtonElements(codeEl)) {
el.hidden = false
}
buttonEl.title = hide_text
buttonEl.dataset.hidden = "false"
}
Expand Down

0 comments on commit 5cf2065

Please sign in to comment.