Skip to content

Commit f0e3902

Browse files
authored
docs: add copy button to code snippets (#9053)
* feat(web): add copy button to code snippets Closes #8994
1 parent a0b8c89 commit f0e3902

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

docs/src/code.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,43 @@ function codeWrap(){
111111
}
112112
}
113113
codeWrap();
114+
115+
function addCodeCopyButtons() {
116+
if (!navigator.clipboard.writeText) return;
117+
118+
function copyCodeFor(codeElement) {
119+
return () => {
120+
navigator.clipboard.writeText(codeElement.textContent);
121+
122+
const success = addButton('✅', codeElement);
123+
success.disabled = true;
124+
success.style.transition = 'opacity 1.5s ease';
125+
setTimeout(() => {
126+
success.style.opacity = 0;
127+
setTimeout(() => codeElement.removeChild(success), 1500);
128+
}, 500);
129+
};
130+
}
131+
132+
function addButton(txt, parent) {
133+
const btn = document.createElement('button');
134+
btn.style.position = 'absolute';
135+
btn.style.top = '11.5px';
136+
btn.style.right = '15px';
137+
btn.textContent = txt;
138+
139+
parent.appendChild(btn);
140+
141+
return btn;
142+
}
143+
144+
document
145+
.querySelectorAll('code[data-lang]')
146+
.forEach(codeElement => {
147+
codeElement.parentElement.style.position = 'relative';
148+
149+
const btn = addButton('📎', codeElement);
150+
btn.onclick = copyCodeFor(codeElement);
151+
});
152+
}
153+
addCodeCopyButtons();

0 commit comments

Comments
 (0)