2024-10-16 11:33:02 +00:00
|
|
|
/**
|
|
|
|
* Safari doesn't support inheriting from HTML tags on web components
|
|
|
|
* The technique is to:
|
|
|
|
* create a new web component
|
|
|
|
* create the desired type inside
|
|
|
|
* pass all attributes to the child component
|
2024-10-16 12:59:02 +00:00
|
|
|
* store is at as `node` inside the parent
|
2024-10-16 11:33:02 +00:00
|
|
|
*
|
|
|
|
* To use this, you must use the tag name twice, once for creating the class
|
|
|
|
* and the second time while calling super to pass it to the constructor
|
|
|
|
**/
|
|
|
|
export class InheritedComponent<
|
|
|
|
K extends keyof HTMLElementTagNameMap,
|
|
|
|
> extends HTMLElement {
|
2024-10-16 12:59:02 +00:00
|
|
|
node: HTMLElementTagNameMap[K];
|
2024-10-16 11:33:02 +00:00
|
|
|
|
|
|
|
constructor(tagName: K) {
|
|
|
|
super();
|
2024-10-16 12:59:02 +00:00
|
|
|
this.node = document.createElement(tagName);
|
2024-10-16 11:33:02 +00:00
|
|
|
const attributes: Attr[] = []; // We need to make a copy to delete while iterating
|
|
|
|
for (const attr of this.attributes) {
|
2024-10-16 12:59:02 +00:00
|
|
|
if (attr.name in this.node) {
|
|
|
|
attributes.push(attr);
|
|
|
|
}
|
2024-10-16 11:33:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for (const attr of attributes) {
|
|
|
|
this.removeAttributeNode(attr);
|
2024-10-16 12:59:02 +00:00
|
|
|
this.node.setAttributeNode(attr);
|
2024-10-16 11:33:02 +00:00
|
|
|
}
|
2024-10-16 12:59:02 +00:00
|
|
|
this.appendChild(this.node);
|
2024-10-16 11:33:02 +00:00
|
|
|
}
|
|
|
|
}
|