From 700c75cbbe56c40e45394379941146ed2071b4ba Mon Sep 17 00:00:00 2001 From: Segun Adebayo Date: Tue, 10 Sep 2024 20:25:19 +0100 Subject: [PATCH] fix(menu): defer focus when content is lazy mounted --- .changeset/sweet-monkeys-visit.md | 5 +++++ examples/next-ts/pages/compositions | 2 +- examples/next-ts/pages/menu.tsx | 22 ++++++++++++---------- packages/machines/menu/src/menu.machine.ts | 20 ++++++++++++++------ 4 files changed, 32 insertions(+), 17 deletions(-) create mode 100644 .changeset/sweet-monkeys-visit.md 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)