Skip to content

Commit

Permalink
fix(esl-base-element): more accurate check for element redeclaration …
Browse files Browse the repository at this point in the history
…(detects both: tag and class inconsistency)
  • Loading branch information
ala-n committed Jul 4, 2023
1 parent c63befc commit 66266a9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
14 changes: 7 additions & 7 deletions src/modules/esl-base-element/core/esl-base-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,16 @@ export abstract class ESLBaseElement extends HTMLElement implements ESLBaseCompo
*/
public static register(this: typeof ESLBaseElement, tagName?: string): void {
tagName = tagName || this.is;
if (!tagName) throw new Error('Can not define custom element');
const constructor: any = customElements.get(tagName);
if (constructor) {
if (constructor.is !== tagName) throw new Error('Element declaration tag inconsistency');
return;
if (!tagName) {
throw new DOMException('[ESL]: Incorrect tag name', 'NotSupportedError');
}
if (this.is !== tagName) {
this.is = tagName;
const constructor: any = customElements.get(tagName);
if (constructor && (constructor !== this || constructor.is !== tagName)) {
throw new DOMException('[ESL]: Element tag already occupied or inconsistent', 'NotSupportedError');
}
if (constructor) return;
customElements.define(tagName, this as any as CustomElementConstructor);
Object.defineProperty(this, 'is', {value: tagName, writable: false});
}

/** Shortcut for `customElements.whenDefined(currentCustomElement)` */
Expand Down
14 changes: 6 additions & 8 deletions src/modules/esl-base-element/test/element.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,15 @@ describe('ESLBaseElement', () => {
}, 0);
}, 100);

test('ESLBaseElement register validate', () => {
test('ESLBaseElement register validate', async () => {
// Tag is not empty
expect(() => TestElement2.register('')).toThrowError();
TestElement2.register('test-test');
return customElements.whenDefined('test-test')
.then(() => {
expect(() => TestElement2.register('test-test')).not.toThrowError();
TestElement2.is = 'test-test-2';
// Tag inconsistency
expect(() => TestElement2.register('test-test')).toThrowError();
});
await customElements.whenDefined('test-test');
expect(() => TestElement2.register('test-test')).not.toThrowError();
expect(() => TestElement2.register('test-test-2')).toThrowError();
try {TestElement2.is = 'test-test-2';} catch { /* empty */ }
expect(TestElement2.is).toBe('test-test');
});

describe('ESLBaseElement prototype', () => {
Expand Down

0 comments on commit 66266a9

Please sign in to comment.