Files
fleet/website/assets/js/components/code-block-copy-buttons.component.js
EricandCopilot Autofix powered by AI ad3ab6b613 Website: Add copy button to code blocks in articles, handbook, and osquery table documentation pages (#44778)
Closes: https://github.com/fleetdm/confidential/issues/15273

Changes:
- Added a new component `<code-block-copy-buttons>`, a component that
adds copy buttons to code blocks on pages it is added to.
- Added the new component to the handbook, articles, and osquery table
documentation pages


Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-05-05 16:20:47 -05:00

43 lines
2.0 KiB
JavaScript
Vendored

/**
* <code-block-copy-buttons>
* -----------------------------------------------------------------------------
* A hovering copy button injected into code blocks that copies the text content when clicked.
*
* @type {Component}
*
* -----------------------------------------------------------------------------
*/
parasails.registerComponent('code-block-copy-buttons', {
// ╦ ╦╔╦╗╔╦╗╦
// ╠═╣ ║ ║║║║
// ╩ ╩ ╩ ╩ ╩╩═╝
template: `<span></span>`,
// ╦ ╦╔═╗╔═╗╔═╗╦ ╦╔═╗╦ ╔═╗
// ║ ║╠╣ ║╣ ║ ╚╦╝║ ║ ║╣
// ╩═╝╩╚ ╚═╝╚═╝ ╩ ╚═╝╩═╝╚═╝
mounted: async function(){
// Only add copy buttons if the clipboard method is available.
if(typeof navigator.clipboard !== 'undefined' && typeof navigator.clipboard.writeText === 'function'){
// Prepend all <pre><code> elements with a code-block-copy-button element, and add the has-copy-button class.
$('pre:has(code)').not('.has-copy-button')
.prepend('<button type="button" purpose="code-block-copy-button" aria-label="Copy code" title="Copy code"></button>')
.addClass('has-copy-button');// Note: we set this bootstrap class to correctly position the copy button without needing to adjust the styles of the page it is added to.
// Now add click events to each code-block-copy-button element that copies the text content of the neighboring <code> element.
$('[purpose="code-block-copy-button"]').on('click', async function() {
// Get the text content of the closest <code> element to the copy button.
let code = $(this).closest('pre').find('code').text();
// Add the copied class to the copy button (which replaces the icon with a checkmark).
$(this).addClass('copied');
// Remove the copied class after 2 seconds.
setTimeout(()=>{
$(this).removeClass('copied');
}, 2000);
navigator.clipboard.writeText(code);
});
}
},
});