refactor: use Web Components without native class support detection (#836)

This commit is contained in:
Yue JIN
2025-06-01 17:43:06 +08:00
committed by GU Yiling
parent 5b39c47102
commit 6ef3fd8f52
5 changed files with 14 additions and 36 deletions

View File

@ -41,8 +41,7 @@ import type { EChartsElement } from "./wc";
import "./style.css";
const __CSP__ = false;
const wcRegistered = __CSP__ ? false : register();
const wcRegistered = register();
export const THEME_KEY: InjectionKey<ThemeInjection> = Symbol();
export const INIT_OPTIONS_KEY: InjectionKey<InitOptionsInjection> = Symbol();

View File

@ -19,18 +19,19 @@ export function register(): boolean {
}
try {
// Class definitions cannot be transpiled to ES5
// so we are doing a little trick here to ensure
// we are using native classes. As we use this as
// a progressive enhancement, it will be fine even
// if the browser doesn't support native classes.
const reg = new Function(
"tag",
// Use esbuild repl to keep build process simple
// https://esbuild.github.io/try/#dAAwLjIzLjAALS1taW5pZnkAY2xhc3MgRUNoYXJ0c0VsZW1lbnQgZXh0ZW5kcyBIVE1MRWxlbWVudCB7CiAgX19kaXNwb3NlID0gbnVsbDsKCiAgZGlzY29ubmVjdGVkQ2FsbGJhY2soKSB7CiAgICBpZiAodGhpcy5fX2Rpc3Bvc2UpIHsKICAgICAgdGhpcy5fX2Rpc3Bvc2UoKTsKICAgICAgdGhpcy5fX2Rpc3Bvc2UgPSBudWxsOwogICAgfQogIH0KfQoKaWYgKGN1c3RvbUVsZW1lbnRzLmdldCh0YWcpID09IG51bGwpIHsKICBjdXN0b21FbGVtZW50cy5kZWZpbmUodGFnLCBFQ2hhcnRzRWxlbWVudCk7Cn0K
"class EChartsElement extends HTMLElement{__dispose=null;disconnectedCallback(){this.__dispose&&(this.__dispose(),this.__dispose=null)}}customElements.get(tag)==null&&customElements.define(tag,EChartsElement);",
);
reg(TAG_NAME);
class ECElement extends HTMLElement implements EChartsElement {
__dispose: (() => void) | null = null;
disconnectedCallback() {
if (this.__dispose) {
this.__dispose();
this.__dispose = null;
}
}
}
if (customElements.get(TAG_NAME) == null) {
customElements.define(TAG_NAME, ECElement);
}
} catch {
return (registered = false);
}