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

Commit

Permalink
make lang getter more extensible
Browse files Browse the repository at this point in the history
  • Loading branch information
ys2843 committed Jul 1, 2020
1 parent 3da73c8 commit 63df50d
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions docs/static_site/src/assets/js/copycode.js
Expand Up @@ -20,7 +20,7 @@
/* Copy code to clipboard */

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

/* Functions to get the language of a code block related to a copy button
* called one by one until a valid lang is returned
* new callbacks should be added before "default"
*/
const LANG_GETTER = [
(copyBtn) => copyBtn.nextElementSibling.children[0].dataset.lang,
(copyBtn) => copyBtn.parentNode.parentNode.classList[0].split("-")[1],
() => "default",
];

// Append a copy button to each code block on the page
$("figure.highlight, div.highlight").each(function () {
const copyBtn = $('<button type="button" class="copy-btn">copy</button>');
Expand All @@ -58,16 +68,16 @@ $(document).ready(function () {
return res + "\n";
};

const getCodeBlockLang = function (copyBtn, langGetFunc) {
return langGetFunc.reduce((res, getter) => res || getter(copyBtn), "");
}

const clipboard = new ClipboardJS(".copy-btn", {
text: function (trigger) {
const lang = trigger.nextElementSibling.children[0].dataset.lang ||
trigger.parentNode.parentNode.classList[0].split("-")[1] ||
"default";
const lang = getCodeBlockLang(trigger, LANG_GETTER);
const langPrompts = LANG_GP[lang] || [];
const lines = trigger.parentNode.querySelector("code").textContent.split("\n");
const cleanedCode = lines.reduce(
(content, line) => content.concat(cleanPrompt(line, langPrompts)),
"");
const cleanedCode = lines.reduce((content, line) => content.concat(cleanPrompt(line, langPrompts)), "");
return cleanedCode.replace(/\n$/, "");
},
});
Expand Down

0 comments on commit 63df50d

Please sign in to comment.