Skip to content

Commit

Permalink
fix(menu): defer focus when content is lazy mounted
Browse files Browse the repository at this point in the history
  • Loading branch information
segunadebayo committed Sep 10, 2024
1 parent 934aac6 commit 700c75c
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 17 deletions.
5 changes: 5 additions & 0 deletions .changeset/sweet-monkeys-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@zag-js/menu": patch
---

Fix issue where lazy mounting the content causes first menu item to not be focused when opened with keyboard
2 changes: 1 addition & 1 deletion examples/next-ts/pages/compositions
22 changes: 12 additions & 10 deletions examples/next-ts/pages/menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,18 @@ export default function Page() {
<button {...api.getTriggerProps()}>
Actions <span {...api.getIndicatorProps()}></span>
</button>
<Portal>
<div {...api.getPositionerProps()}>
<ul {...api.getContentProps()}>
<li {...api.getItemProps({ value: "edit" })}>Edit</li>
<li {...api.getItemProps({ value: "duplicate" })}>Duplicate</li>
<li {...api.getItemProps({ value: "delete" })}>Delete</li>
<li {...api.getItemProps({ value: "export" })}>Export...</li>
</ul>
</div>
</Portal>
{api.open && (
<Portal>
<div {...api.getPositionerProps()}>
<ul {...api.getContentProps()}>
<li {...api.getItemProps({ value: "edit" })}>Edit</li>
<li {...api.getItemProps({ value: "duplicate" })}>Duplicate</li>
<li {...api.getItemProps({ value: "delete" })}>Delete</li>
<li {...api.getItemProps({ value: "export" })}>Export...</li>
</ul>
</div>
</Portal>
)}
</div>
</main>
<Toolbar controls={controls.ui}>
Expand Down
20 changes: 14 additions & 6 deletions packages/machines/menu/src/menu.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,14 +630,22 @@ export function machine(userContext: UserDefinedContext) {
})
},
highlightFirstItem(ctx) {
const first = dom.getFirstEl(ctx)
if (!first) return
set.highlighted(ctx, first.id)
// use raf in event content is lazy mounted
const fn = !!dom.getContentEl(ctx) ? queueMicrotask : raf
fn(() => {
const first = dom.getFirstEl(ctx)
if (!first) return
set.highlighted(ctx, first.id)
})
},
highlightLastItem(ctx) {
const last = dom.getLastEl(ctx)
if (!last) return
set.highlighted(ctx, last.id)
// use raf in event content is lazy mounted
const fn = !!dom.getContentEl(ctx) ? queueMicrotask : raf
fn(() => {
const last = dom.getLastEl(ctx)
if (!last) return
set.highlighted(ctx, last.id)
})
},
highlightNextItem(ctx, evt) {
const next = dom.getNextEl(ctx, evt.loop)
Expand Down

0 comments on commit 700c75c

Please sign in to comment.