Skip to content

Commit

Permalink
remove side effects from CustomAttributeRegistry.js
Browse files Browse the repository at this point in the history
  • Loading branch information
mayank99 authored Dec 14, 2024
1 parent 067c8f4 commit 6a912d8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 14 deletions.
13 changes: 0 additions & 13 deletions src/CustomAttributeRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,16 +136,3 @@ export interface CustomAttribute {
disconnectedCallback?(): void
changedCallback?(oldValue: string, newValue: string): void
}

// Avoid errors trying to use DOM APIs in non-DOM environments (f.e. server-side rendering).
if (globalThis.window?.document) {
const original = Element.prototype.attachShadow

Element.prototype.attachShadow = function attachShadow(options) {
const root = original.call(this, options)

if (!root.customAttributes) root.customAttributes = new CustomAttributeRegistry(root)

return root
}
}
14 changes: 13 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,19 @@ export * from './CustomAttributeRegistry.js'
export let customAttributes: CustomAttributeRegistry

// Avoid errors trying to use DOM APIs in non-DOM environments (f.e. server-side rendering).
if (globalThis.window?.document) customAttributes = globalThis.customAttributes = new CustomAttributeRegistry(document)
if (globalThis.window?.document) {
customAttributes = globalThis.customAttributes = new CustomAttributeRegistry(document)

const originalAttachShadow = Element.prototype.attachShadow

Element.prototype.attachShadow = function attachShadow(options) {
const root = originalAttachShadow.call(this, options)

if (!root.customAttributes) root.customAttributes = new CustomAttributeRegistry(root)

return root
}
}

declare global {
// const doesn't always work (TS bug). At time of writing this, it doesn't work in this TS playground example:
Expand Down

0 comments on commit 6a912d8

Please sign in to comment.