@@ -61,32 +61,72 @@ class Choosealicense {
6161 } ) ;
6262 }
6363
64- // Initializes Clipboard.js
64+ // Initializes copy-to-clipboard behavior
6565 initClipboard ( ) {
6666 const buttons = document . querySelectorAll ( '.js-clipboard-button' ) ;
6767 buttons . forEach ( ( button ) => {
6868 button . dataset . clipboardPrompt = button . textContent ;
69- } ) ;
69+ button . addEventListener ( 'click' , ( event ) => {
70+ event . preventDefault ( ) ;
7071
71- const clip = new Clipboard ( '.js-clipboard-button' ) ;
72- clip . on ( 'mouseout' , ( event ) => this . clipboardMouseout ( event ) ) ;
73- clip . on ( 'complete' , ( event ) => this . clipboardComplete ( event ) ) ;
74- }
72+ const targetSelector = button . getAttribute ( 'data-clipboard-target' ) ;
73+ if ( ! targetSelector ) return ;
7574
76- // Callback to restore the clipboard button's original text
77- clipboardMouseout ( event ) {
78- const trigger = event && event . trigger ;
79- if ( trigger ) {
80- trigger . textContent = trigger . dataset . clipboardPrompt || '' ;
81- }
75+ const targetElement = document . querySelector ( targetSelector ) ;
76+ if ( ! targetElement ) return ;
77+
78+ this . selectText ( targetElement ) ;
79+
80+ const textToCopy = targetElement . textContent || '' ;
81+ if ( ! textToCopy ) return ;
82+
83+ this . copyText ( textToCopy )
84+ . then ( ( ) => {
85+ button . textContent = 'Copied!' ;
86+ } )
87+ . catch ( ( ) => {
88+ // If copying fails, leave the prompt unchanged.
89+ } ) ;
90+ } ) ;
91+
92+ const restorePrompt = ( ) => {
93+ button . textContent = button . dataset . clipboardPrompt || '' ;
94+ } ;
95+
96+ button . addEventListener ( 'mouseleave' , restorePrompt ) ;
97+ button . addEventListener ( 'blur' , restorePrompt ) ;
98+ } ) ;
8299 }
83100
84- // Post-copy user feedback callback
85- clipboardComplete ( event ) {
86- const trigger = event && event . trigger ;
87- if ( trigger ) {
88- trigger . textContent = 'Copied!' ;
101+ copyText ( text ) {
102+ if ( navigator . clipboard && window . isSecureContext ) {
103+ return navigator . clipboard . writeText ( text ) ;
89104 }
105+
106+ return new Promise ( ( resolve , reject ) => {
107+ const textarea = document . createElement ( 'textarea' ) ;
108+ textarea . value = text ;
109+ textarea . setAttribute ( 'readonly' , '' ) ;
110+ textarea . style . position = 'absolute' ;
111+ textarea . style . left = '-9999px' ;
112+ document . body . appendChild ( textarea ) ;
113+
114+ textarea . focus ( ) ;
115+ textarea . select ( ) ;
116+ textarea . setSelectionRange ( 0 , textarea . value . length ) ;
117+
118+ try {
119+ const successful = document . execCommand ( 'copy' ) ;
120+ if ( ! successful ) {
121+ throw new Error ( 'Copy command was unsuccessful' ) ;
122+ }
123+ resolve ( ) ;
124+ } catch ( error ) {
125+ reject ( error ) ;
126+ } finally {
127+ document . body . removeChild ( textarea ) ;
128+ }
129+ } ) ;
90130 }
91131
92132 // Initializes the repository suggestion feature
0 commit comments