Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/selfish-parrots-think.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@emotion/sheet': patch
---

Prevent NotFoundError being thrown when a stale `before` element reference is set
15 changes: 15 additions & 0 deletions packages/sheet/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,4 +243,19 @@ describe('StyleSheet', () => {

expect(() => sheet.flush()).not.toThrowError()
})

test('should not throw when `before` is stale', () => {
const head = safeQuerySelector('head')
const beforeStyle = document.createElement('style')
beforeStyle.setAttribute('id', 'beforeStyle')
head.appendChild(beforeStyle)

const sheet = new StyleSheet({ ...defaultOptions })
sheet.before = beforeStyle

// Simulate a stale `before` node
head.removeChild(sheet.before)

expect(() => sheet.insert(rule)).not.toThrow()
})
})
8 changes: 6 additions & 2 deletions packages/sheet/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,17 @@ export class StyleSheet {
}

private _insertTag = (tag: HTMLStyleElement): void => {
let before
let before = null
if (this.tags.length === 0) {
if (this.insertionPoint) {
before = this.insertionPoint.nextSibling
} else if (this.prepend) {
before = this.container.firstChild
} else {
} else if (this.before && this.before.parentNode === this.container) {
// We check whether the designated `before` node still exists
// and is a child of the container to avoid NotFoundError being thrown.
// If either is false, we let it be null and insert the `tag` node
// as the last child instead.
before = this.before
}
} else {
Expand Down
Loading