Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(code): Introduce copy code feature #1697

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion docs/themes/porter/assets/sass/docs-content.scss
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@
color: black;
border: none;
padding: 0.75em 1em;
margin: 0.25em 0 2.5em;
margin: 0 0 2.5em;
font-size: 1rem;

code {
Expand Down Expand Up @@ -280,3 +280,12 @@
min-height: 320px;
}
}

.copy-button-container {
display: flex;
justify-content: flex-end;
.copy-button {
margin-bottom: 0;
padding: 4px;
}
}
1 change: 1 addition & 0 deletions docs/themes/porter/layouts/partials/js.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
<script src="/js/main.min.js"></script>
<script src="/js/custom/app_init.js"></script>
<script src="/js/custom/prism.js"></script>
<script src="/js/custom/copy_code.js"></script>
30 changes: 30 additions & 0 deletions docs/themes/porter/static/js/custom/copy_code.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
document.querySelectorAll("pre").forEach(preElement => {
var codeElement = preElement.querySelector("code")

/* There should be code element inside pre element and
code element should not have language-console class */
if (codeElement != null && !codeElement.classList.contains("language-console")) {
var copyButtonContainer = document.createElement('div')
copyButtonContainer.classList.add("copy-button-container")
var copyButton = document.createElement('button');
copyButtonContainer.append(copyButton)

copyButton.className = "copy-button"
copyButton.innerText = 'copy';

copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(codeElement.innerText).then(e => {
copyButton.innerText = "copied"
}).catch(e => {
copyButton.innerText = "error"
})

// Restore original "copy" text on button after 900 milliseconds
setTimeout(() => innerText = "copy", 900)
});

// Insert before pre element so that it can appear in top of code block
preElement.parentElement.insertBefore(copyButtonContainer, preElement)
}
})