Skip to content

Commit 9da67a5

Browse files
committed
refactor: focus-visible
1 parent 97aa5e0 commit 9da67a5

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@zag-js/focus-visible": patch
3+
---
4+
5+
Fix `"Cannot assign to read only property 'focus'"` console error by gracefully handling environments where
6+
`HTMLElement.prototype.focus` is non-configurable.

packages/utilities/focus-visible/src/index.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -148,10 +148,15 @@ function setupGlobalFocusEvents(root?: RootNode) {
148148

149149
// Overwrite via assignment does not work in happy dom:
150150
// https://github.com/capricorn86/happy-dom/issues/1214
151-
Object.defineProperty(win.HTMLElement.prototype, "focus", {
152-
configurable: true,
153-
value: patchedFocus,
154-
})
151+
try {
152+
Object.defineProperty(win.HTMLElement.prototype, "focus", {
153+
configurable: true,
154+
value: patchedFocus,
155+
})
156+
} catch {
157+
// Failed to patch - property may be non-configurable or already patched
158+
// The focus tracking will still work via keyboard/pointer event listeners
159+
}
155160

156161
doc.addEventListener("keydown", handleKeyboardEvent, true)
157162
doc.addEventListener("keyup", handleKeyboardEvent, true)
@@ -190,11 +195,19 @@ const tearDownWindowFocusTracking = (root?: RootNode, loadListener?: () => void)
190195
doc.removeEventListener("DOMContentLoaded", loadListener)
191196
}
192197

193-
if (!listenerMap.has(win)) {
198+
const listenerData = listenerMap.get(win)
199+
if (!listenerData) {
194200
return
195201
}
196202

197-
win.HTMLElement.prototype.focus = listenerMap.get(win)!.focus
203+
try {
204+
Object.defineProperty(win.HTMLElement.prototype, "focus", {
205+
configurable: true,
206+
value: listenerData.focus,
207+
})
208+
} catch {
209+
// Failed to restore - ignore silently
210+
}
198211

199212
doc.removeEventListener("keydown", handleKeyboardEvent, true)
200213
doc.removeEventListener("keyup", handleKeyboardEvent, true)

0 commit comments

Comments
 (0)