summaryrefslogtreecommitdiff
path: root/packages/webapi/src/lib/CustomElementRegistry.ts
blob: 21f775d5e527a3dd3d103dfde608b498e0b0b01f (plain) (blame)
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
import * as _ from './utils'

export class CustomElementRegistry {
	/** Defines a new custom element using the given tag name and HTMLElement constructor. */
	define(
		name: string,
		constructor: Function,
		options?: ElementDefinitionOptions
	) {
		const internals = _.internalsOf<CustomElementRegistryInternals>(
			this,
			'CustomElementRegistry',
			'define'
		)

		name = String(name)

		if (/[A-Z]/.test(name))
			throw new SyntaxError(
				'Custom element name cannot contain an uppercase ASCII letter'
			)
		if (!/^[a-z]/.test(name))
			throw new SyntaxError(
				'Custom element name must have a lowercase ASCII letter as its first character'
			)
		if (!/-/.test(name))
			throw new SyntaxError('Custom element name must contain a hyphen')

		_.INTERNALS.set(constructor, {
			attributes: {},
			localName: name,
		} as any)

		internals.constructorByName.set(name, constructor)
		internals.nameByConstructor.set(constructor, name)

		void options
	}

	/** Returns the constructor associated with the given tag name. */
	get(name: string) {
		const internals = _.internalsOf<CustomElementRegistryInternals>(
			this,
			'CustomElementRegistry',
			'get'
		)

		name = String(name).toLowerCase()

		return internals.constructorByName.get(name)
	}

	getName(constructor: Function) {
		const internals = _.internalsOf<CustomElementRegistryInternals>(
			this,
			'CustomElementRegistry',
			'getName'
		)

		return internals.nameByConstructor.get(constructor)
	}
}

_.allowStringTag(CustomElementRegistry)

interface CustomElementRegistryInternals {
	constructorByName: Map<string, Function>
	nameByConstructor: Map<Function, string>
}

interface ElementDefinitionOptions {
	extends?: string | undefined
}

export const initCustomElementRegistry = (
	target: Record<any, any>,
	exclude: Set<string>
) => {
	if (exclude.has('customElements')) return

	const CustomElementRegistry =
		target.CustomElementRegistry || globalThis.CustomElementRegistry

	const customElements: CustomElementRegistry =
		target.customElements ||
		(target.customElements = new CustomElementRegistry())

	_.INTERNALS.set(customElements, {
		constructorByName: new Map(),
		nameByConstructor: new Map(),
	} as CustomElementRegistryInternals)
}