UNPKG

@surface/custom-element

Version:

Provides support of directives and data binding on custom elements.

57 lines (56 loc) 2.12 kB
var _a; import { DisposableMetadata, HookableMetadata } from "@surface/core"; import StaticMetadata from "./metadata/static-metadata.js"; import { globalCustomDirectives } from "./singletons.js"; const CUSTOM_ELEMENT = Symbol("custom-element:instance"); export default class CustomElement extends HTMLElement { // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor() { super(); CustomElement.applyMetadata(this); } static applyMetadata(instance) { const staticMetadata = StaticMetadata.from(instance.constructor); instance.attachShadow(staticMetadata.shadowRootInit); instance.shadowRoot.adoptedStyleSheets = staticMetadata.styles; const content = staticMetadata.template.content.cloneNode(true); instance.shadowRoot.appendChild(content); HookableMetadata.from(instance.constructor).initialize(instance); } static [(_a = CUSTOM_ELEMENT, Symbol.hasInstance)](instance) { return Reflect.get(instance.constructor, CUSTOM_ELEMENT); } /** * Extends a HTML element. * @param base Element to be extended. */ static as(base) { var _b, _c; return _c = class CustomElementExtends extends base { // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(...args) { super(...args); CustomElement.applyMetadata(this); } dispose() { DisposableMetadata.from(this).dispose(); } }, _b = CUSTOM_ELEMENT, _c[_b] = true, _c; } /** * Registers a custom directive. * @param name Custom directive name. * @param handler An directive constructor or factory. */ static registerDirective(name, handler) { globalCustomDirectives.set(name, handler); } /** Disposes resources. */ dispose() { DisposableMetadata.from(this).dispose(); } } CustomElement[_a] = true;