Skip to content

feat: add copy button into code blocks #6601

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var replace = require( '@stdlib/string/replace' );
var RE_VIEW_BOX = /(?:(view-box)(=".*?"))/g;
var RE_CLIP_PATH_OPEN = /(?:<(clip-path)(.*?>))/g;
var RE_CLIP_PATH_CLOSE = /<\/clip-path>/g;
var RE_CODE_BLOCKS = /<pre>\s*<code class="([^"]*)">\s*([\s\S]*?)\s*<\/code>\s*<\/pre>/g;


// MAIN //
Expand All @@ -53,9 +54,38 @@ function postProcess( html ) {
html = replace( html, RE_VIEW_BOX, 'viewBox$2' );
html = replace( html, RE_CLIP_PATH_OPEN, '<clipPath$2' );
html = replace( html, RE_CLIP_PATH_CLOSE, '</clipPath>' );
html = replace( html, RE_CODE_BLOCKS, injectCopyButton );
html += getCopyButtonStyles();
return html;
}

/**
* Injects a "Copy" button into a code block.
*
* This function wraps a `<pre><code>` block in a container div and inserts a
* "Copy" button above it. The button uses the Clipboard API to copy the visible
* text content (`innerText`) of the `<code>` element when clicked.
*
* @private
* @param {string} match The entire matched HTML
* @param {string} lang The language class
* @param {string} code The raw HTML contents of the code block
* @returns {string} copy button HTML
*/
function injectCopyButton( match, lang, code ) {
return '<div class="code-container"><button class="copy-button" onclick="const codeContainer = this.closest(\'.code-container\');if ( codeContainer ) { const codeElement = codeContainer.querySelector( \'code\' ); if ( codeElement ) { try { navigator.clipboard.writeText( codeElement.innerText ); this.innerText = \'Copied\'; setTimeout(() => { this.innerText = \'Copy\' }, 2000); } catch (err) { console.error(err); } } }">Copy</button><pre><code class="' + lang + '">' + code + '</code></pre></div>';
}

/**
* Returns copy button styles.
*
* @private
* @returns {string} copy button styles
*/
function getCopyButtonStyles() {
return '<style>.code-container { position: relative; } .copy-button { position: absolute; top: 8px; right: 8px; background: #eee; border: none; padding: 5px 10px; cursor: pointer; font-size: 0.8em; border-radius: 4px; } .copy-button:hover { background: #ddd; }</style>';
}


// EXPORTS //

Expand Down
Loading