Debian Codegraph @

python_docs_theme/static/copybutton.js

raw
1 // Extract copyable text from the code block ignoring the
2 // prompts and output.
3 function getCopyableText(rootElement) {
4 rootElement = rootElement.cloneNode(true)
5 // tracebacks (.gt) contain bare text elements that
6 // need to be removed
7 const tracebacks = rootElement.querySelectorAll(".gt")
8 for (const el of tracebacks) {
9 while (
10 el.nextSibling &&
11 (el.nextSibling.nodeType !== Node.ELEMENT_NODE ||
12 !el.nextSibling.matches(".gp, .go"))
13 ) {
14 el.nextSibling.remove()
15 }
16 }
17 // Remove all elements with the "go" (Generic.Output),
18 // "gp" (Generic.Prompt), or "gt" (Generic.Traceback) CSS class
19 const elements = rootElement.querySelectorAll(".gp, .go, .gt, .linenos")
20 for (const el of elements) {
21 el.remove()
22 }
23 return rootElement.innerText.trim()
24 }
25
26 const loadCopyButton = () => {
27 const button = document.createElement("button")
28 button.classList.add("copybutton")
29 button.type = "button"
30 button.innerText = _("Copy")
31 button.title = _("Copy to clipboard")
32
33 const makeOnButtonClick = () => {
34 let timeout = null
35 // define the behavior of the button when it's clicked
36 return async event => {
37 // check if the clipboard is available
38 if (!navigator.clipboard || !navigator.clipboard.writeText) {
39 return;
40 }
41
42 clearTimeout(timeout)
43 const buttonEl = event.currentTarget
44 const codeEl = buttonEl.nextElementSibling
45
46 try {
47 await navigator.clipboard.writeText(getCopyableText(codeEl))
48 } catch (e) {
49 console.error(e.message)
50 return
51 }
52
53 buttonEl.innerText = _("Copied!")
54 timeout = setTimeout(() => {
55 buttonEl.innerText = _("Copy")
56 }, 1500)
57 }
58 }
59
60 const highlightedElements = document.querySelectorAll(
61 ".highlight-python .highlight,"
62 + ".highlight-python3 .highlight,"
63 + ".highlight-pycon .highlight,"
64 + ".highlight-pycon3 .highlight,"
65 + ".highlight-bash .highlight,"
66 + ".highlight-console .highlight,"
67 + ".highlight-doscon .highlight,"
68 + ".highlight-ps1con .highlight,"
69 + ".highlight-sh .highlight,"
70 + ".highlight-shell-session .highlight,"
71 + ".highlight-default .highlight"
72 )
73
74 // create and add the button to all the code blocks that contain >>>
75 highlightedElements.forEach(el => {
76 el.style.position = "relative"
77
78 // if we find a console prompt (.gp), prepend the (deeply cloned) button
79 const clonedButton = button.cloneNode(true)
80 // the onclick attribute is not cloned, set it on the new element
81 clonedButton.onclick = makeOnButtonClick()
82 el.prepend(clonedButton)
83 })
84 }
85
86 if (document.readyState !== "loading") {
87 loadCopyButton()
88 } else {
89 document.addEventListener("DOMContentLoaded", loadCopyButton)
90 }