-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement built-in
customElements
proxy
- Loading branch information
1 parent
d718256
commit 8466115
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
import { customElements } from './registry'; | ||
import { createElement, render } from './runtime'; | ||
|
||
/** | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
/** | ||
* Internal weak mapping of all registered elements to their name. | ||
*/ | ||
const elements = new WeakMap<CustomElementConstructor, string>(); | ||
|
||
/** | ||
* Proxy around the built-in `customElements` object, maintaining a mapping of | ||
* all registered elements and their corresponding names, which can be queried | ||
* by calling `customElements.getName()`. | ||
* | ||
* @see https://github.com/WICG/webcomponents/issues/566 | ||
*/ | ||
const registry = new Proxy(customElements, { | ||
get: (_, propertyKey: keyof CustomElementRegistry | 'getName') => { | ||
switch (propertyKey) { | ||
case 'define': return ( | ||
name: string, | ||
constructor: CustomElementConstructor, | ||
options?: ElementDefinitionOptions | ||
) => { | ||
customElements.define(name, constructor, options); | ||
elements.set(constructor, name); | ||
}; | ||
|
||
case 'getName': return ( | ||
constructor: CustomElementConstructor | ||
) => { | ||
let name = elements.get(constructor); | ||
|
||
if (!name) { | ||
try { | ||
name = Reflect.construct(HTMLElement, [], constructor).localName; | ||
elements.set(constructor, name as string); | ||
} catch { | ||
return undefined; | ||
} | ||
} | ||
|
||
return name; | ||
}; | ||
|
||
default: return customElements[propertyKey].bind(customElements); | ||
} | ||
} | ||
}) as CustomElementRegistry & { | ||
getName(constructor: CustomElementConstructor): string | undefined; | ||
}; | ||
|
||
export { registry as customElements }; |