Skip to content

Commit

Permalink
add copy codeblock button
Browse files Browse the repository at this point in the history
Apply suggestions from code review

Co-authored-by: Danny <Rapptz@users.noreply.github.com>

Change to icon, change according to slice's review
  • Loading branch information
NCPlayz authored and Rapptz committed Dec 19, 2020
1 parent c21919c commit ce0d0a2
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
31 changes: 31 additions & 0 deletions docs/_static/copy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const COPY = "fa-copy";
const COPIED = "fa-clipboard-check";

const copy = async (obj) => {
// <div><span class="copy"> <i class="fas ...">the icon element</i> </span><pre> code </pre></div>
await navigator.clipboard.writeText(obj.children[1].innerText).then(
() => {
let icon = obj.children[0].children[0];
icon.className = icon.className.replace(COPY, COPIED);
setTimeout(() => (icon.className = icon.className.replace(COPIED, COPY)), 2500);
},
(r) => alert('Could not copy codeblock:\n' + r.toString())
);
};

document.addEventListener("DOMContentLoaded", () => {
let allCodeblocks = document.querySelectorAll("div[class='highlight']");

for (let codeblock of allCodeblocks) {
codeblock.parentNode.className += " relative-copy";
let copyEl = document.createElement("span");
copyEl.addEventListener('click', () => copy(codeblock));
copyEl.className = "copy";

let copyIcon = document.createElement("i");
copyIcon.className = "fas " + COPY;
copyEl.append(copyIcon);

codeblock.prepend(copyEl);
}
});
30 changes: 28 additions & 2 deletions docs/_static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ label.toggle input:checked + span.toggle-slider:before {
transform: translateX(18px);
}


div.related {
padding: 10px 10px;
width: 100%;
Expand Down Expand Up @@ -703,4 +703,30 @@ div.code-block-caption {
background-color: transparent;
border-left: none;
}
}
}

.relative-copy {
position: relative;
}

.copy {
cursor: pointer;
position: absolute;
width: 16px;
height: 16px;
top: 0px;
right: 0px;
border: 1px solid #C6C9CB;
line-height: 0.8em;
font-size: 0.9em;
font-family: monospace;
padding-left: 0.2em;
padding-right: 0.2em;
border-radius: 0px 3px 0px 0px;
text-align: center;
}

.copy i {
display: inline;
vertical-align: middle;
}
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,5 +320,6 @@

def setup(app):
app.add_js_file('custom.js')
app.add_js_file('copy.js')
if app.config.language == 'ja':
app.config.intersphinx_mapping['py'] = ('https://docs.python.org/ja/3', None)

0 comments on commit ce0d0a2

Please sign in to comment.