Skip to content

Commit

Permalink
tools: add button to copy code example to clipboard
Browse files Browse the repository at this point in the history
  • Loading branch information
jakecastelli committed Mar 3, 2023
1 parent c4103c1 commit 403718c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
26 changes: 26 additions & 0 deletions doc/api_assets/api.js
Expand Up @@ -136,6 +136,30 @@
updateHashes();
}

function setCopyButton() {
const buttons = document.querySelectorAll('.copy-button');
buttons.forEach((button) => {
button.addEventListener('click', (el) => {
const parentNode = el.target.parentNode;

const flavorSelector = parentNode.querySelector('.js-flavor-selector');

let code = '';

if (flavorSelector) {
if (flavorSelector.checked) {
code = parentNode.querySelector('.mjs').textContent;
} else {
code = parentNode.querySelector('.cjs').textContent;
}
} else {
code = parentNode.querySelector('code').textContent;
}
navigator.clipboard.writeText(code);
});
});
}

function bootstrap() {
// Check if we have JavaScript support.
document.documentElement.classList.add('has-js');
Expand All @@ -151,6 +175,8 @@

// Make link to other versions of the doc open to the same hash target (if it exists).
setupAltDocsLink();

setCopyButton();
}

if (document.readyState === 'loading') {
Expand Down
8 changes: 6 additions & 2 deletions tools/doc/html.mjs
Expand Up @@ -226,10 +226,13 @@ export function preprocessElements({ filename }) {
const className = isJSFlavorSnippet(node) ?
`language-js ${node.lang}` :
`language-${node.lang}`;

const highlighted =
`<code class='${className}'>${(getLanguage(node.lang || '') ? highlight(node.value, { language: node.lang }) : node).value}</code>`;
node.type = 'html';

const button = '<button class="copy-button">copy</button>';

if (isJSFlavorSnippet(node)) {
const previousNode = parent.children[index - 1] || {};
const nextNode = parent.children[index + 1] || {};
Expand All @@ -253,16 +256,17 @@ export function preprocessElements({ filename }) {
' aria-label="Show modern ES modules syntax">' +
previousNode.value +
highlighted +
button +
'</pre>';
node.lang = null;
previousNode.value = '';
previousNode.lang = null;
} else {
// Isolated JS snippet, no need to add the checkbox.
node.value = `<pre>${highlighted}</pre>`;
node.value = `<pre>${highlighted} ${button}</pre>`;
}
} else {
node.value = `<pre>${highlighted}</pre>`;
node.value = `<pre>${highlighted} ${button}</pre>`;
}
} else if (node.type === 'html' && common.isYAMLBlock(node.value)) {
node.value = parseYAML(node.value);
Expand Down

0 comments on commit 403718c

Please sign in to comment.