| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
class CodeCopyManager |
| 23 |
{ |
| 24 |
|
| 25 |
static accessibility = null; |
| 26 |
|
| 27 |
|
| 28 |
static initialize() |
| 29 |
{ |
| 30 |
|
| 31 |
if ( !this.accessibility ) { |
| 32 |
this.accessibility = new globalThis.fheroes2.AccessibilityManager(); |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
document.querySelectorAll( "div.highlight" ).forEach( block => this.initializeCodeBlock( block ) ); |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
static createCopyButton() |
| 42 |
{ |
| 43 |
return this.accessibility.createAccessibleButton( { text : 'Copy', ariaLabel : 'Copy code to clipboard', className : 'btn btn-primary copy-btn' } ); |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
static updateButtonState( button, success, code ) |
| 52 |
{ |
| 53 |
|
| 54 |
const truncatedCode = code.length > 50 ? `${code.substring( 0, 50 )}...` : code; |
| 55 |
|
| 56 |
this.accessibility.updateElementState( { |
| 57 |
element : button, |
| 58 |
success : success, |
| 59 |
successMessage : `Code copied to clipboard: ${truncatedCode}`, |
| 60 |
errorMessage : 'Failed to copy code to clipboard', |
| 61 |
successText : 'Copied!', |
| 62 |
errorText : 'Failed to copy', |
| 63 |
defaultText : 'Copy', |
| 64 |
resetDelay : 2000 |
| 65 |
} ); |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
static handleCopyCode( block, button ) |
| 73 |
{ |
| 74 |
try { |
| 75 |
const code = block.querySelector( "pre" ).innerText; |
| 76 |
navigator.clipboard.writeText( code ).then( () => { this.updateButtonState( button, true, code ); } ).catch( err => { |
| 77 |
console.error( "Failed to copy code:", err ); |
| 78 |
this.updateButtonState( button, false, code ); |
| 79 |
} ); |
| 80 |
} |
| 81 |
catch ( err ) { |
| 82 |
console.error( "Failed to copy code:", err ); |
| 83 |
this.updateButtonState( button, false, '' ); |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
static setupEventListeners( button, block ) |
| 92 |
{ |
| 93 |
|
| 94 |
button.addEventListener( "click", () => this.handleCopyCode( block, button ) ); |
| 95 |
|
| 96 |
|
| 97 |
this.accessibility.setupKeyboardEvents( button, () => this.handleCopyCode( block, button ) ); |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
static initializeCodeBlock( block ) |
| 104 |
{ |
| 105 |
const button = this.createCopyButton(); |
| 106 |
block.appendChild( button ); |
| 107 |
this.setupEventListeners( button, block ); |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
document.addEventListener( "DOMContentLoaded", () => { CodeCopyManager.initialize(); } ); |