Skip to content

Commit 403718c

Browse files
committed
tools: add button to copy code example to clipboard
1 parent c4103c1 commit 403718c

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

doc/api_assets/api.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,30 @@
136136
updateHashes();
137137
}
138138

139+
function setCopyButton() {
140+
const buttons = document.querySelectorAll('.copy-button');
141+
buttons.forEach((button) => {
142+
button.addEventListener('click', (el) => {
143+
const parentNode = el.target.parentNode;
144+
145+
const flavorSelector = parentNode.querySelector('.js-flavor-selector');
146+
147+
let code = '';
148+
149+
if (flavorSelector) {
150+
if (flavorSelector.checked) {
151+
code = parentNode.querySelector('.mjs').textContent;
152+
} else {
153+
code = parentNode.querySelector('.cjs').textContent;
154+
}
155+
} else {
156+
code = parentNode.querySelector('code').textContent;
157+
}
158+
navigator.clipboard.writeText(code);
159+
});
160+
});
161+
}
162+
139163
function bootstrap() {
140164
// Check if we have JavaScript support.
141165
document.documentElement.classList.add('has-js');
@@ -151,6 +175,8 @@
151175

152176
// Make link to other versions of the doc open to the same hash target (if it exists).
153177
setupAltDocsLink();
178+
179+
setCopyButton();
154180
}
155181

156182
if (document.readyState === 'loading') {

tools/doc/html.mjs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,10 +226,13 @@ export function preprocessElements({ filename }) {
226226
const className = isJSFlavorSnippet(node) ?
227227
`language-js ${node.lang}` :
228228
`language-${node.lang}`;
229+
229230
const highlighted =
230231
`<code class='${className}'>${(getLanguage(node.lang || '') ? highlight(node.value, { language: node.lang }) : node).value}</code>`;
231232
node.type = 'html';
232233

234+
const button = '<button class="copy-button">copy</button>';
235+
233236
if (isJSFlavorSnippet(node)) {
234237
const previousNode = parent.children[index - 1] || {};
235238
const nextNode = parent.children[index + 1] || {};
@@ -253,16 +256,17 @@ export function preprocessElements({ filename }) {
253256
' aria-label="Show modern ES modules syntax">' +
254257
previousNode.value +
255258
highlighted +
259+
button +
256260
'</pre>';
257261
node.lang = null;
258262
previousNode.value = '';
259263
previousNode.lang = null;
260264
} else {
261265
// Isolated JS snippet, no need to add the checkbox.
262-
node.value = `<pre>${highlighted}</pre>`;
266+
node.value = `<pre>${highlighted} ${button}</pre>`;
263267
}
264268
} else {
265-
node.value = `<pre>${highlighted}</pre>`;
269+
node.value = `<pre>${highlighted} ${button}</pre>`;
266270
}
267271
} else if (node.type === 'html' && common.isYAMLBlock(node.value)) {
268272
node.value = parseYAML(node.value);

0 commit comments

Comments
 (0)