@@ -58,7 +58,9 @@ class App extends Component {
5858 this . handleCopyNote = this . handleCopyNote . bind ( this ) ;
5959 this . handleCopyEvent = this . handleCopyEvent . bind ( this ) ;
6060 this . handleSortNotes = this . handleSortNotes . bind ( this ) ;
61- this . updateCodeSyntaxHighlighting ( ) ;
61+ this . updateCodeSyntaxHighlighting ;
62+ this . addCopyButtons ;
63+ this . handleCopyCodeButtonClick ;
6264 }
6365
6466 async componentDidMount ( ) {
@@ -71,11 +73,13 @@ class App extends Component {
7173 } ) ;
7274 document . getElementById ( getnotes [ 0 ] . noteid ) . click ( ) ;
7375 }
74- // this.updateCodeSyntaxHighlighting();
76+ this . updateCodeSyntaxHighlighting ( ) ;
77+ this . handleCopyCodeButtonClick ( ) ;
7578 }
7679
7780 componentDidUpdate ( ) {
78- // this.updateCodeSyntaxHighlighting();
81+ this . updateCodeSyntaxHighlighting ( ) ;
82+ this . handleCopyCodeButtonClick ( ) ;
7983 }
8084
8185 updateCodeSyntaxHighlighting = ( ) => {
@@ -84,6 +88,56 @@ class App extends Component {
8488 } ) ;
8589 } ;
8690
91+ handleCopyCodeButtonClick = ( ) => {
92+ if ( navigator && navigator . clipboard ) {
93+ this . addCopyButtons ( navigator . clipboard ) ;
94+ } else {
95+ var script = document . createElement ( "script" ) ;
96+ script . src =
97+ "https://cdnjs.cloudflare.com/ajax/libs/clipboard-polyfill/2.7.0/clipboard-polyfill.promise.js" ;
98+ script . integrity = "sha256-waClS2re9NUbXRsryKoof+F9qc1gjjIhc2eT7ZbIv94=" ;
99+ script . crossOrigin = "anonymous" ;
100+ script . onload = function ( ) {
101+ this . addCopyButtons ( clipboard ) ;
102+ } ;
103+ document . body . appendChild ( script ) ;
104+ }
105+ } ;
106+
107+ addCopyButtons = ( clipboard ) => {
108+ document . querySelectorAll ( "pre code" ) . forEach ( function ( codeBlock ) {
109+ var button = document . createElement ( "button" ) ;
110+ button . className = "copy-code-button" ;
111+ button . type = "button" ;
112+ button . innerText = "Copy" ;
113+
114+ button . addEventListener ( "click" , function ( ) {
115+ clipboard . writeText ( codeBlock . innerText ) . then (
116+ function ( ) {
117+ /* Chrome doesn't seem to blur automatically,
118+ leaving the button in a focused state. */
119+ button . blur ( ) ;
120+ button . innerText = "Copied!" ;
121+ setTimeout ( function ( ) {
122+ button . innerText = "Copy" ;
123+ } , 2000 ) ;
124+ } ,
125+ function ( error ) {
126+ button . innerText = "Error" ;
127+ }
128+ ) ;
129+ } ) ;
130+
131+ var pre = codeBlock . parentNode ;
132+ if ( pre . parentNode . classList . contains ( "highlight" ) ) {
133+ var highlight = pre . parentNode ;
134+ highlight . parentNode . insertBefore ( button , highlight ) ;
135+ } else {
136+ pre . parentNode . insertBefore ( button , pre ) ;
137+ }
138+ } ) ;
139+ } ;
140+
87141 // Indexed DB class
88142 async handleIndexedDB ( cmd = "" , note = "" ) {
89143 const db = await openDB ( "notesdb" , 1 , {
0 commit comments