-
Notifications
You must be signed in to change notification settings - Fork 0
/
CopyCodeInjector.svelte
54 lines (50 loc) · 1.31 KB
/
CopyCodeInjector.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<script lang="ts">
import { onMount } from "svelte";
import { fly } from "svelte/transition";
// used to display copy tooltip
let copiedText = false;
let copyTimeout: NodeJS.Timeout;
onMount(() => {
// will add a children to any <pre> element with class language-*
let pres: HTMLCollection = document.getElementsByTagName("pre");
for (let _ of pres) {
const pre = _ as HTMLPreElement;
if (![...pre.classList].some((el) => el.startsWith("language-"))) {
continue;
}
const text = pre.innerText;
let copyButton = document.createElement("button");
copyButton.addEventListener(
"click",
() => (
navigator.clipboard.writeText(text),
(copiedText = true),
copyTimeout && clearTimeout(copyTimeout),
(copyTimeout = setTimeout(() => (copiedText = false), 1500))
)
);
copyButton.className = "copy";
copyButton.innerText = "Copy";
pre.appendChild(copyButton);
}
});
</script>
{#if copiedText}
<div in:fly={{ x: -100 }} out:fly={{ x: 100 }} class="copy-tooltip">
Copied to clipboard! 📚
</div>
{/if}
<slot />
<style>
.copy-tooltip {
background-color: var(--secondary);
color: var(--body);
position: fixed;
top: 1em;
right: 1em;
padding: 0.4em 0.7em;
border-radius: 0.4em;
z-index: 1;
box-shadow: 0px 2px 10px -2px var(--code-copy);
}
</style>