Add anchors to samples (#35906)

This adds an "anchor button" to each of the samples so that the user can link to individual samples instead of having to link to just the page. Clicking on the anchor button jumps to the anchor, as well as copying the anchor URL to the clipboard.

There is some oddness in the implementation: because dartdoc uses a <base> tag, the href for the link can't just be "#id", it has to calculate the URL from the current window href. I do that in the onmouseenter and onclick because onload doesn't get triggered for <a> tags (and onmouseenter doesn't get triggered for mobile platforms), but I still want the href to be updated before someone right-clicks it to copy the URL.
This commit is contained in:
Greg Spencer
2019-07-10 16:48:20 -07:00
committed by GitHub
parent b5c1b61c73
commit 67ee3e191e
7 changed files with 87 additions and 15 deletions

View File

@@ -83,6 +83,26 @@
font-family: courier, lucidia;
}
.anchor-container {
position: relative;
}
.anchor-button-overlay {
position: absolute;
top: 0px;
right: 5px;
height: 28px;
width: 28px;
transition: .3s ease;
background-color: #2372a3;
}
.anchor-button {
border-style: none;
background: none;
cursor: pointer;
}
/* Styles for the copy-to-clipboard button */
.copyable-container {
position: relative;

View File

@@ -57,6 +57,30 @@ function supportsCopying() {
!!document.queryCommandSupported('copy');
}
// Copies the given string to the clipboard.
function copyStringToClipboard(string) {
var textArea = document.createElement("textarea");
textArea.value = string;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
if (!supportsCopying()) {
alert('Unable to copy to clipboard (not supported by browser)');
return;
}
try {
document.execCommand('copy');
} finally {
document.body.removeChild(textArea);
}
}
function fixHref(anchor, id) {
anchor.href = window.location.href.replace(/#.*$/, '') + '#' + id;
}
// Copies the text inside the currently visible snippet to the clipboard, or the
// given element, if any.
function copyTextToClipboard(element) {