Repository navigation
Expand file tree
/
Copy pathupdateTheme.ts
More file actions
97 lines (83 loc) · 2.6 KB
/
Copy pathupdateTheme.ts
File metadata and controls
97 lines (83 loc) · 2.6 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const commentNodeType = 8
export function findCommentNode(comment: string) {
for (const node of document.head.childNodes) {
if (node.nodeType === commentNodeType && node?.nodeValue?.trim() === comment) {
return node;
}
}
return null;
}
export function createLinkElement(attributes: Partial<HTMLLinkElement>) {
const elements = document.createElement('link')
for (const [attribute, value] of Object.entries(attributes)) {
// @ts-ignore
elements[attribute] = value;
}
return elements
}
function insertStyle(linkElement: HTMLElement, insertionPoint?: string) {
const insert = insertionPoint
? selectInsertionMethod(insertionPoint)
: insertToHead
insert(linkElement)
}
function insertToHead(element: Node) {
return document.head.appendChild(element)
}
function insertBefore(parent: Node, point: Node) {
return (element: Node) => parent.insertBefore(element, point?.nextSibling)
}
function selectInsertionMethod(name: string): (element: Node) => void {
const point = findCommentNode(name)
const parent = point?.parentNode
return parent && point
? insertBefore(parent, point)
: insertToHead
}
function createStyleLink(id: string, link: string, callback?: Callback) {
const temporaryId = id + '_temp'
return createLinkElement({
type: 'text/css',
rel: 'stylesheet',
id: temporaryId,
href: link,
onload: () => {
document.getElementById(id)?.remove()
const nextStyle = document.getElementById(temporaryId)
nextStyle?.setAttribute('id', id)
callback?.()
}
})
}
type ThemeSources = Record<string, string>
function *listPrefetches(themeSources: ThemeSources) {
for (const [theme, link] of Object.entries(themeSources)) {
const id = `theme-prefetch-${theme}`;
if (document.getElementById(id)) {
continue
}
yield createPrefetch(theme, id, link)
}
}
function createPrefetch(theme: string, id: string, link: string) {
const prefetch = document.createElement('link');
prefetch.rel = 'prefetch'
prefetch.type = 'text/css'
prefetch.id = id;
prefetch.href = link
return prefetch
}
const activeThemeId = 'active-theme'
const insertionPoint = 'active-theme'
type Callback = () => void
export function updateTheme(theme: string, link: string, callback?: Callback) {
const element = createStyleLink(activeThemeId, link, callback)
insertStyle(element, insertionPoint)
document.body.setAttribute('data-theme', theme)
}
export function insertPrefetches(themes: ThemeSources) {
const insert = selectInsertionMethod(insertionPoint)
for (const prefetch of listPrefetches(themes)) {
insert(prefetch)
}
}