From d7e9d717c28bd92910d1fe64c60172c821914ad0 Mon Sep 17 00:00:00 2001 From: Konnor Rogers Date: Fri, 21 Jun 2024 13:32:38 -0400 Subject: [PATCH] try registering without anonymous classes first (#2079) * try registering without anonymous classes first * Add comment * Add comment * Add changelog note * prettier --- docs/pages/resources/changelog.md | 1 + src/internal/shoelace-element.ts | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/pages/resources/changelog.md b/docs/pages/resources/changelog.md index 44204ac1..a2860a86 100644 --- a/docs/pages/resources/changelog.md +++ b/docs/pages/resources/changelog.md @@ -14,6 +14,7 @@ New versions of Shoelace are released as-needed and generally occur when a criti ## Next +- When calling `customElements.define` we no longer register with anonymous classes by default [#2079] - `` `closable` property now reflects. [#2041] - `` now implements a proper "roving tabindex" and `` is no longer tabbable by default. This aligns closer to the APG pattern for tabs. [#2041] - Fixed a bug in the submenu controller that prevented submenus from rendering in RTL without explicitly setting `dir` on the parent menu item [#1992] diff --git a/src/internal/shoelace-element.ts b/src/internal/shoelace-element.ts index 1d6ae5ba..219ebdac 100644 --- a/src/internal/shoelace-element.ts +++ b/src/internal/shoelace-element.ts @@ -104,7 +104,15 @@ export default class ShoelaceElement extends LitElement { | typeof ShoelaceElement; if (!currentlyRegisteredConstructor) { - customElements.define(name, class extends elementConstructor {} as unknown as CustomElementConstructor, options); + // We try to register as the actual class first. If for some reason that fails, we fall back to anonymous classes. + // customElements can only have 1 class of the same "object id" per registry, so that is why the try {} catch {} exists. + // Some tools like Jest Snapshots and if you import the constructor and call `new SlButton()` they will fail with + // the anonymous class version. + try { + customElements.define(name, elementConstructor, options); + } catch (_err) { + customElements.define(name, class extends elementConstructor {}, options); + } return; }