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