Skip to content

Commit b6e757f

Browse files
committed
Attempted to change copy result depending on toggle visibility
1 parent bf42e4b commit b6e757f

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

doc/source/_static/js/custom-copy.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
document.addEventListener("DOMContentLoaded", function () {
2+
document.querySelectorAll(".copybtn").forEach((btn) => {
3+
btn.addEventListener("click", async function (event) {
4+
event.preventDefault();
5+
6+
const codeBlock = btn.closest("div.highlight");
7+
if (!codeBlock) return;
8+
9+
const clone = codeBlock.cloneNode(true);
10+
11+
// Remove spans with data-hidden="true"
12+
clone.querySelectorAll("span.copybutton").forEach((el) => {
13+
if (el.getAttribute("data-hidden") === "true") {
14+
el.remove();
15+
}
16+
});
17+
18+
const text = clone.innerText;
19+
20+
try {
21+
await navigator.clipboard.writeText(text);
22+
console.log("Copied cleaned code to clipboard.");
23+
} catch (err) {
24+
console.warn("Clipboard API failed, using fallback.");
25+
fallbackCopy(text);
26+
}
27+
});
28+
});
29+
30+
function fallbackCopy(text) {
31+
const textarea = document.createElement("textarea");
32+
textarea.value = text;
33+
document.body.appendChild(textarea);
34+
textarea.select();
35+
try {
36+
document.execCommand("copy");
37+
console.log("Copied using fallback.");
38+
} catch (err) {
39+
console.error("Fallback copy failed:", err);
40+
}
41+
document.body.removeChild(textarea);
42+
}
43+
});

doc/source/conf.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
"matplotlib.sphinxext.plot_directive",
5858
"numpydoc",
5959
"sphinx_copybutton",
60+
'sphinx_toggleprompt',
6061
"sphinx_design",
6162
"sphinx.ext.autodoc",
6263
"sphinx.ext.autosummary",
@@ -296,6 +297,10 @@
296297
"css/pandas.css",
297298
]
298299

300+
html_js_files = [
301+
'js/custom-copy.js'
302+
]
303+
299304
# The name of an image file (within the static path) to use as favicon of the
300305
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
301306
# pixels large.
@@ -462,8 +467,11 @@
462467
# latex_use_modindex = True
463468

464469
# Configure copybutton to strip Python REPL prompts and output when copying
465-
copybutton_prompt_text = r">>> |\.\.\.:|In \[\d+\]:?|Out\[\d+\]:?"
466-
copybutton_prompt_is_regexp = True
470+
toggleprompt_prompt_text = r">>> |\.\.\.:|In \[\d+\]:|Out\[\d+\]:"
471+
toggleprompt_is_regexp = True
472+
473+
copybutton_prompt_text = ''
474+
copybutton_is_regexp = False
467475

468476
if include_api:
469477
intersphinx_mapping = {

0 commit comments

Comments
 (0)