docs: Correct scope of copied material from copy button.

This traverses the DOM to the <pre> element containing the
copyable material of interest.

The button is attached to the .codehilite element to ensure
that the button does not move with horizontally-scrolling
code content that exceeds the width of the content column,
as happens frequently at mobile scales or for very long
lines of content.

Fixes #26093.
This commit is contained in:
Karl Stolley 2023-06-23 14:05:00 -05:00 committed by Tim Abbott
parent 04ead84c4d
commit d6c21c2237
2 changed files with 11 additions and 7 deletions

View File

@ -30,17 +30,19 @@ function registerCodeSection($codeSection) {
});
}
// Display the copy-to-clipboard button inside the markdown.pre element
// Display the copy-to-clipboard button inside the .codehilite element
// within the API and Help Center docs using clipboard.js
function add_copy_to_clipboard_element($pre) {
function add_copy_to_clipboard_element($codehilite) {
const $copy_button = $("<button>").addClass("copy-codeblock");
$copy_button.html(copy_to_clipboard_svg());
$($pre).append($copy_button);
$($codehilite).append($copy_button);
const clipboard = new ClipboardJS($copy_button[0], {
text(copy_element) {
return $(copy_element).siblings("code").text();
// trim to remove trailing whitespace introduced
// by additional elements inside <pre>
return $(copy_element).siblings("pre").text().trim();
},
});
@ -90,8 +92,8 @@ function render_code_sections() {
registerCodeSection($(this));
});
// Add a copy-to-clipboard button for each pre element
$(".markdown pre").each(function () {
// Add a copy-to-clipboard button for each .codehilite element
$(".markdown .codehilite").each(function () {
add_copy_to_clipboard_element($(this));
});

View File

@ -381,11 +381,13 @@
background-color: hsl(0deg 0% 93%);
}
& pre {
.codehilite {
/* Relative positioning is used to place the copy-to-clipboard button
in the top-right corner. */
position: relative;
}
& pre {
& code {
font-size: 14px;
white-space: pre-wrap;