-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
index.ts
52 lines (43 loc) · 1.75 KB
/
index.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
42
43
44
45
46
47
48
49
50
51
52
import { elements } from '../definitions'
import { MarpAutoScaling } from './marp-auto-scaling'
import { createMarpCustomElement } from './marp-custom-element'
let _isSupportedCustomizedBuiltInElements: boolean | undefined
export const marpCustomElementsRegisteredSymbol = Symbol()
export const isSupportedCustomizedBuiltInElements = () =>
_isSupportedCustomizedBuiltInElements ??
(() => {
_isSupportedCustomizedBuiltInElements = !!document
.createElement('div', { is: 'marp-auto-scaling' })
.outerHTML.startsWith('<div is')
return _isSupportedCustomizedBuiltInElements
})()
export const applyCustomElements = (target: ParentNode = document) => {
const defined = window[marpCustomElementsRegisteredSymbol]
if (!defined) customElements.define('marp-auto-scaling', MarpAutoScaling)
for (const tag of Object.keys(elements)) {
const marpCustomElement = `marp-${tag}`
const proto: typeof HTMLElement = elements[tag].proto()
if (!isSupportedCustomizedBuiltInElements() || proto === HTMLElement) {
if (!defined) {
customElements.define(
marpCustomElement,
createMarpCustomElement(HTMLElement, elements[tag]),
)
}
target
.querySelectorAll(`${tag}[is="${marpCustomElement}"]`)
.forEach((customElm) => {
customElm.outerHTML = customElm.outerHTML
.replace(new RegExp(`^<${tag}`, 'i'), `<${marpCustomElement}`)
.replace(new RegExp(`</${tag}>$`, 'i'), `</${marpCustomElement}>`)
})
} else if (!defined) {
customElements.define(
marpCustomElement,
createMarpCustomElement(proto, { style: elements[tag].style }),
{ extends: tag },
)
}
}
window[marpCustomElementsRegisteredSymbol] = true
}