Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove side effects from CustomAttributeRegistry.js #4

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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