-
Notifications
You must be signed in to change notification settings - Fork 917
/
Copy pathstyleInjection.ts
41 lines (35 loc) · 1.13 KB
/
styleInjection.ts
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
interface ComponentOptions {
beforeMount?(): void
__cssBlocks: Record<string, CSSBlock>
shadowRoot?: HTMLElement
}
interface ComponentInstance {
$options: ComponentOptions
$root: ComponentInstance
}
interface CSSBlock {
id: string
}
function getStyleElement(id: string, parent: HTMLElement) {
var existing = parent.querySelector("[data-style-id='" + id + "']")
if (existing) return existing
var styleElement = document.createElement('style')
styleElement.setAttribute('data-style-id', id)
styleElement.setAttribute('type', 'text/css')
parent.appendChild(styleElement)
return styleElement
}
function injectStyles(component: ComponentInstance) {
const parent = component.$root.$options.shadowRoot || document.head
Object.values(component.$options.__cssBlocks).forEach(function (cssBlock) {
var styleElement = getStyleElement(cssBlock.id, parent)
styleElement.innerHTML = cssBlock.toString()
})
}
export default function addStyleInjectionCode(script: ComponentOptions) {
var existing = script.beforeMount
script.beforeMount = function beforeMount() {
injectStyles(this)
existing && existing()
}
}