Skip to content

Commit

Permalink
docs: avoid copying >>> and ... from clipboard (#1375)
Browse files Browse the repository at this point in the history
* modify mkdocs.yml

* added js file

* add source attribution

---------

Co-authored-by: FBruzzesi <[email protected]>
  • Loading branch information
DeaMariaLeon and FBruzzesi authored Nov 14, 2024
1 parent 4c2b60e commit 4f20d10
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
67 changes: 67 additions & 0 deletions docs/javascripts/extra.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Copied from Ruff https://github.com/astral-sh/ruff/blob/924741cb11a68ed037899f9db1bea6969c48385e/docs/js/extra.js
*
* @author Astral Software Inc. <[email protected]>
* @license MIT
*/


function cleanupClipboardText(targetSelector) {
const targetElement = document.querySelector(targetSelector);

// exclude "Generic Prompt" and "Generic Output" spans from copy
const excludedClasses = ["gp", "go"];

const clipboardText = Array.from(targetElement.childNodes)
.filter(
(node) =>
!excludedClasses.some((className) =>
node?.classList?.contains(className),
),
)
.map((node) => node.textContent)
.filter((s) => s !== "");
return clipboardText.join("").trim();
}

// Sets copy text to attributes lazily using an Intersection Observer.
function setCopyText() {
// The `data-clipboard-text` attribute allows for customized content in the copy
// See: https://www.npmjs.com/package/clipboard#copy-text-from-attribute
const attr = "clipboardText";
// all "copy" buttons whose target selector is a <code> element
const elements = document.querySelectorAll(
'button[data-clipboard-target$="code"]',
);

if (elements.length === 0) {
return;
}

const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
// target in the viewport that have not been patched
if (
entry.intersectionRatio > 0 &&
entry.target.dataset[attr] === undefined
) {
entry.target.dataset[attr] = cleanupClipboardText(
entry.target.dataset.clipboardTarget,
);
}
});
});

elements.forEach((elt) => {
observer.observe(elt);
});
}

// Using the document$ observable is particularly important if you are using instant loading since
// it will not result in a page refresh in the browser
// See `How to integrate with third-party JavaScript libraries` guideline:
// https://squidfunk.github.io/mkdocs-material/customization/?h=javascript#additional-javascript
document$.subscribe(function () {
setCopyText();
});

2 changes: 2 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ plugins:
members_order: alphabetical
enable_inventory: true

extra_javascript:
- javascripts/extra.js

hooks:
- utils/generate_backend_completeness.py
Expand Down

0 comments on commit 4f20d10

Please sign in to comment.