Repository navigation
Expand file tree
/
Copy pathcreate-element.ts
More file actions
74 lines (64 loc) · 2.28 KB
/
Copy pathcreate-element.ts
File metadata and controls
74 lines (64 loc) · 2.28 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
export const NAMESPACE = {
XUL: 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul',
HTML: 'http://www.w3.org/1999/xhtml',
}
type Handler = (event?: any) => void | Promise<void>
export class Elements {
static all: WeakRef<Elements>[] = []
static removeAll(): void {
for (const ref of this.all) {
try {
const elements = ref.deref()
if (elements) elements.document.querySelectorAll(`.${elements.className}`).forEach(e => e.remove())
}
catch {}
}
this.all = []
}
private className: string
constructor(prefix: string, private document: Document) {
this.className = `${prefix}-${Math.random()}-${Date.now()}`.replace('.', '-')
if ((this.document as any).createXULElement) Elements.all.push(new WeakRef(this))
}
public serialize(node: HTMLElement): string {
const s = new XMLSerializer()
return s.serializeToString(node)
}
create(name: string, attrs: Record<string, number | string | Handler | HTMLElement[]> = {}): HTMLElement {
const children: HTMLElement[] = (attrs.$ as unknown as HTMLElement[]) || []
delete attrs.$
const namespace = name.startsWith('html:') ? NAMESPACE.HTML : NAMESPACE.XUL
name = name.replace('html:', '')
const elt: HTMLElement = (this.document as any).createXULElement
? this.document[namespace === NAMESPACE.XUL ? 'createXULElement' : 'createElement'](name) as HTMLElement
: this.document.createElementNS(namespace, name) as HTMLElement
attrs.class = `${this.className} ${attrs.class || ''}`.trim()
for (const [a, v] of Object.entries(attrs)) {
if (typeof v === 'string') {
elt.setAttribute(a, v)
}
else if (typeof v === 'number') {
elt.setAttribute(a, `${v}`)
}
else if (a.startsWith('on') && typeof v === 'function') {
elt.addEventListener(a.replace('on', ''), event => {
;(v(event) as Promise<void>)?.catch?.(err => {
throw err
})
})
}
else {
throw new Error(`unexpected attribute ${a} of type ${typeof v}`)
}
}
for (const child of children) {
elt.appendChild(child)
}
return elt
}
remove(): void {
for (const elt of Array.from(this.document.getElementsByClassName(this.className))) {
elt.remove()
}
}
}