Skip to content
This repository was archived by the owner on Nov 17, 2023. It is now read-only.

Commit 63df50d

Browse files
committed
make lang getter more extensible
1 parent 3da73c8 commit 63df50d

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

docs/static_site/src/assets/js/copycode.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
/* Copy code to clipboard */
2121

2222
$(document).ready(function () {
23-
// Omitted prompts in Regex for each language
23+
// Regex of prompts to be omitted when copy
2424
const LANG_GP = {
2525
default: [">>> ", "\\.\\.\\."],
2626
python: [">>> ", "\\.\\.\\."],
@@ -33,6 +33,16 @@ $(document).ready(function () {
3333
bash: ["\\$ "],
3434
};
3535

36+
/* Functions to get the language of a code block related to a copy button
37+
* called one by one until a valid lang is returned
38+
* new callbacks should be added before "default"
39+
*/
40+
const LANG_GETTER = [
41+
(copyBtn) => copyBtn.nextElementSibling.children[0].dataset.lang,
42+
(copyBtn) => copyBtn.parentNode.parentNode.classList[0].split("-")[1],
43+
() => "default",
44+
];
45+
3646
// Append a copy button to each code block on the page
3747
$("figure.highlight, div.highlight").each(function () {
3848
const copyBtn = $('<button type="button" class="copy-btn">copy</button>');
@@ -58,16 +68,16 @@ $(document).ready(function () {
5868
return res + "\n";
5969
};
6070

71+
const getCodeBlockLang = function (copyBtn, langGetFunc) {
72+
return langGetFunc.reduce((res, getter) => res || getter(copyBtn), "");
73+
}
74+
6175
const clipboard = new ClipboardJS(".copy-btn", {
6276
text: function (trigger) {
63-
const lang = trigger.nextElementSibling.children[0].dataset.lang ||
64-
trigger.parentNode.parentNode.classList[0].split("-")[1] ||
65-
"default";
77+
const lang = getCodeBlockLang(trigger, LANG_GETTER);
6678
const langPrompts = LANG_GP[lang] || [];
6779
const lines = trigger.parentNode.querySelector("code").textContent.split("\n");
68-
const cleanedCode = lines.reduce(
69-
(content, line) => content.concat(cleanPrompt(line, langPrompts)),
70-
"");
80+
const cleanedCode = lines.reduce((content, line) => content.concat(cleanPrompt(line, langPrompts)), "");
7181
return cleanedCode.replace(/\n$/, "");
7282
},
7383
});

0 commit comments

Comments
 (0)