diff options
| author | Iris Shi <0.0@owo.li> | 2025-09-22 15:02:02 +0800 |
|---|---|---|
| committer | Iris Shi <0.0@owo.li> | 2025-09-23 13:26:19 +0800 |
| commit | 9ae7aef06d1146ee30190fb399d548e1db3652dd (patch) | |
| tree | 8a9d5bd5d300282746cb6c10d45558dd4182bbbd /src/librustdoc/html/static/js | |
| parent | 1d23da6b7304d9e2a2c3dcb1b0aaa709cb9bc4ad (diff) | |
| download | rust-9ae7aef06d1146ee30190fb399d548e1db3652dd.tar.gz rust-9ae7aef06d1146ee30190fb399d548e1db3652dd.zip | |
prevent line number from being copied in chrome
Diffstat (limited to 'src/librustdoc/html/static/js')
| -rw-r--r-- | src/librustdoc/html/static/js/main.js | 25 |
1 files changed, 18 insertions, 7 deletions
diff --git a/src/librustdoc/html/static/js/main.js b/src/librustdoc/html/static/js/main.js index 75febd6f737..3ea9de381ec 100644 --- a/src/librustdoc/html/static/js/main.js +++ b/src/librustdoc/html/static/js/main.js @@ -2227,11 +2227,18 @@ function preLoadCss(cssUrl) { }); }()); -// This section is a bugfix for firefox: when copying text with `user-select: none`, it adds -// extra backline characters. + +// Workaround for browser-specific bugs when copying code snippets. +// +// * In Firefox, copying text that includes elements with `user-select: none` +// inserts extra blank lines. +// - Firefox issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1273836 +// - Rust issue: https://github.com/rust-lang/rust/issues/141464 // -// Rustdoc issue: Workaround for https://github.com/rust-lang/rust/issues/141464 -// Firefox issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1273836 +// * In Chromium-based browsers, `document.getSelection()` includes elements +// with `user-select: none`, causing unwanted line numbers to be copied. +// - Chromium issue: https://issues.chromium.org/issues/446539520 +// - Rust issue: https://github.com/rust-lang/rust/issues/146816 (function() { document.body.addEventListener("copy", event => { let target = nonnull(event.target); @@ -2248,9 +2255,13 @@ function preLoadCss(cssUrl) { if (!isInsideCode) { return; } - const selection = document.getSelection(); - // @ts-expect-error - nonnull(event.clipboardData).setData("text/plain", selection.toString()); + const selection = nonnull(document.getSelection()); + const text = Array.from({ length: selection.rangeCount }, (_, i) => { + const fragment = selection.getRangeAt(i).cloneContents(); + fragment.querySelectorAll("[data-nosnippet]").forEach(el => el.remove()); + return fragment.textContent; + }).join(""); + nonnull(event.clipboardData).setData("text/plain", text); event.preventDefault(); }); }()); |
