-
Notifications
You must be signed in to change notification settings - Fork 897
Expand file tree
/
Copy pathsetupUpdateHead.ts
More file actions
168 lines (152 loc) · 4.35 KB
/
Copy pathsetupUpdateHead.ts
File metadata and controls
168 lines (152 loc) · 4.35 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import type { HeadConfig, VuepressSSRContext } from '@vuepress/shared'
import { isPlainObject, isString } from '@vuepress/shared'
import { onMounted, provide, useSSRContext, watch } from 'vue'
import type { UpdateHead } from './composables/index.js'
import {
updateHeadSymbol,
usePageHead,
usePageLang,
} from './composables/index.js'
/**
* Query the matched head element of head config
*/
export const queryHeadElement = ([
tagName,
attrs,
content = '',
]: HeadConfig): HTMLElement | null => {
const attrsSelector = Object.entries(attrs)
.map(([key, value]) => {
if (isString(value)) {
return `[${key}=${JSON.stringify(value)}]`
}
if (value) {
return `[${key}]`
}
return ''
})
.join('')
const selector = `head > ${tagName}${attrsSelector}`
const headElements = Array.from(
document.querySelectorAll<HTMLElement>(selector),
)
const matchedHeadElement = headElements.find(
(item) => item.textContent === content,
)
return matchedHeadElement ?? null
}
/**
* Create head element from head config
*/
export const createHeadElement = ([
tagName,
attrs,
content,
]: HeadConfig): HTMLElement | null => {
if (!isString(tagName)) {
return null
}
// create element
const headElement = document.createElement(tagName)
// set attributes
if (isPlainObject(attrs)) {
Object.entries(attrs).forEach(([key, value]) => {
if (isString(value)) {
headElement.setAttribute(key, value)
} else if (value) {
headElement.setAttribute(key, '')
}
})
}
// set content
if (isString(content)) {
headElement.append(document.createTextNode(content))
}
return headElement
}
/**
* Auto update head and provide as global util
*/
export const setupUpdateHead = (): void => {
const head = usePageHead()
const lang = usePageLang()
// ssr-only, extract page meta info to ssrContext
if (__VUEPRESS_SSR__) {
const ssrContext = useSSRContext<VuepressSSRContext>()
if (ssrContext) {
ssrContext.head = head.value
ssrContext.lang = lang.value
}
return
}
let managedHeadElements: HTMLElement[] = []
/**
* Take over the existing head elements
*/
const takeOverHeadElements = (): void => {
head.value.forEach((item) => {
const headElement = queryHeadElement(item)
if (headElement) {
managedHeadElements.push(headElement)
}
})
}
/**
* Generate head elements from current head config
*/
const generateHeadElements = (): HTMLElement[] => {
const result: HTMLElement[] = []
head.value.forEach((item) => {
const headElement = createHeadElement(item)
if (headElement) {
result.push(headElement)
}
})
return result
}
/**
* Update head elements
*/
const updateHead: UpdateHead = () => {
// set html lang attribute
document.documentElement.lang = lang.value
// generate new head elements from current head config
const newHeadElements = generateHeadElements()
// find the intersection of old and new head elements
managedHeadElements.forEach((oldEl, oldIndex) => {
const matchedIndex = newHeadElements.findIndex((newEl) =>
oldEl.isEqualNode(newEl),
)
// remove the non-intersection from old elements
if (matchedIndex === -1) {
oldEl.remove()
// eslint-disable-next-line @typescript-eslint/no-array-delete -- use delete to make the index consistent
delete managedHeadElements[oldIndex]
}
// keep the intersection in old elements, and remove it from new elements
else {
// use splice to avoid empty item in next loop
newHeadElements.splice(matchedIndex, 1)
}
})
// append the rest new elements to head
newHeadElements.forEach((el) => {
document.head.append(el)
})
// update managed head elements
managedHeadElements = [
// filter out empty deleted items
...managedHeadElements.filter((item: HTMLElement | undefined) => !!item),
...newHeadElements,
]
}
provide(updateHeadSymbol, updateHead)
onMounted(() => {
// in production, the initial head elements are already pre-rendered,
// so we need to skip the first update and take over the existing elements.
if (!__VUEPRESS_DEV__) {
takeOverHeadElements()
}
watch(head, updateHead, { immediate: __VUEPRESS_DEV__ })
})
}