-
Notifications
You must be signed in to change notification settings - Fork 26
/
index.mjs
52 lines (45 loc) · 2.07 KB
/
index.mjs
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
import { THEME_KEY, Themes, copyToClipboardButtonStrings } from './constants.mjs';
import ThemeToggle from './components/ThemeToggle/index.mjs';
const themeToggleElement = document.getElementById('theme-toggle');
const cachedTheme = localStorage.getItem(THEME_KEY);
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? Themes.DARK : Themes.LIGHT;
// eslint-disable-next-line no-unused-vars
const themeToggle = new ThemeToggle({
toggleElement: themeToggleElement,
initialTheme: cachedTheme ?? preferredTheme,
setTheme: (theme) => {
document.documentElement.dataset[THEME_KEY] = theme;
themeToggleElement.setAttribute('aria-pressed', theme === Themes.DARK);
},
setCachedTheme: (theme) => localStorage.setItem(THEME_KEY, theme),
themes: {
[Themes.LIGHT]: Themes.DARK,
[Themes.DARK]: Themes.LIGHT,
},
});
const copyableCodeBlocks = document.querySelectorAll('code[data-copyable="true"]');
copyableCodeBlocks.forEach((codeBlock) => {
const code = codeBlock.innerText;
const copyCodeButton = document.createElement('button');
copyCodeButton.className = 'copy-code-button fs-sm';
copyCodeButton.innerText = copyToClipboardButtonStrings.default;
copyCodeButton.setAttribute('aria-label', copyToClipboardButtonStrings.ariaLabel);
copyCodeButton.type = 'button';
codeBlock.parentElement.append(copyCodeButton);
// Accessible alert whose inner text changes when we copy.
const copiedAlert = document.createElement('span');
copiedAlert.setAttribute('role', 'alert');
copiedAlert.classList.add('screen-reader-only');
codeBlock.parentElement.append(copiedAlert);
copyCodeButton.addEventListener('click', () => {
window.navigator.clipboard.writeText(code);
copyCodeButton.classList.add('copied');
copyCodeButton.innerText = copyToClipboardButtonStrings.copied;
copiedAlert.innerText = copyToClipboardButtonStrings.copied;
setTimeout(() => {
copyCodeButton.classList.remove('copied');
copyCodeButton.innerText = copyToClipboardButtonStrings.default;
copiedAlert.innerText = '';
}, 2000);
});
});