Skip to content

Commit

Permalink
fix(popover): consistent restore focus
Browse files Browse the repository at this point in the history
  • Loading branch information
segunadebayo committed Sep 3, 2024
1 parent 4ecff96 commit a931be7
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/healthy-zebras-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@zag-js/popover": patch
---

Fix issue where popover does not restore focus when open state is changed programmatically
40 changes: 40 additions & 0 deletions examples/next-ts/pages/popover-controlled.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Fragment, useId, useState } from "react"
import * as popover from "@zag-js/popover"
import { useMachine, normalizeProps, Portal } from "@zag-js/react"

export default function Page() {
const [open, setOpen] = useState(false)

const initialContext = {
id: useId(),
open: false,
"open.controlled": true,
}

const [state, send] = useMachine(popover.machine(initialContext), {
context: {
...initialContext,
onOpenChange: (details) => setOpen(details.open),
open: open,
},
})

const api = popover.connect(state, send, normalizeProps)

const Wrapper = api.portalled ? Portal : Fragment

return (
<main>
<button {...api.getTriggerProps()}>Click me</button>
<Wrapper>
<div {...api.getPositionerProps()}>
<div {...api.getContentProps()}>
<div {...api.getTitleProps()}>Presenters</div>
<div {...api.getDescriptionProps()}>Description</div>
<button onClick={() => setOpen(false)}>Action Button</button>
</div>
</div>
</Wrapper>
</main>
)
}
2 changes: 1 addition & 1 deletion packages/machines/popover/src/popover.connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export function connect<T extends PropTypes>(state: State, send: Send, normalize
"aria-label": "close",
onClick(event) {
if (event.defaultPrevented) return
send({ type: "CLOSE", restoreFocus: true })
send("CLOSE")
},
})
},
Expand Down
2 changes: 1 addition & 1 deletion packages/machines/popover/src/popover.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export function machine(userContext: UserDefinedContext) {
},
setFinalFocus(ctx, evt) {
const restoreFocus = evt.restoreFocus ?? evt.previousEvent?.restoreFocus
if (!restoreFocus) return
if (restoreFocus != null && !restoreFocus) return
raf(() => {
const element = dom.getTriggerEl(ctx)
element?.focus({ preventScroll: true })
Expand Down

0 comments on commit a931be7

Please sign in to comment.