diff --git a/.changeset/sweet-monkeys-visit.md b/.changeset/sweet-monkeys-visit.md
new file mode 100644
index 0000000000..6ab1bf6d08
--- /dev/null
+++ b/.changeset/sweet-monkeys-visit.md
@@ -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
diff --git a/examples/next-ts/pages/compositions b/examples/next-ts/pages/compositions
index 89312973f0..048170007b 160000
--- a/examples/next-ts/pages/compositions
+++ b/examples/next-ts/pages/compositions
@@ -1 +1 @@
-Subproject commit 89312973f0e153bdb13072b48321d92b28c560d4
+Subproject commit 048170007bd30252a030e9de759138fa59d8ae6b
diff --git a/examples/next-ts/pages/menu.tsx b/examples/next-ts/pages/menu.tsx
index 6ffbed53ed..8860fc4916 100644
--- a/examples/next-ts/pages/menu.tsx
+++ b/examples/next-ts/pages/menu.tsx
@@ -21,16 +21,18 @@ export default function Page() {
-
-
-
- - Edit
- - Duplicate
- - Delete
- - Export...
-
-
-
+ {api.open && (
+
+
+
+ - Edit
+ - Duplicate
+ - Delete
+ - Export...
+
+
+
+ )}
diff --git a/packages/machines/menu/src/menu.machine.ts b/packages/machines/menu/src/menu.machine.ts
index 00754d3828..bab42e5c10 100644
--- a/packages/machines/menu/src/menu.machine.ts
+++ b/packages/machines/menu/src/menu.machine.ts
@@ -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)