Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "fix: focus menu items immediately after connecting a menu list",
"packageName": "@fluentui/web-components",
"email": "machi@microsoft.com",
"dependentChangeType": "patch"
}
20 changes: 19 additions & 1 deletion packages/web-components/src/menu-list/menu-list.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,25 @@ export class BaseMenuList extends FASTElement {
* @public
*/
public focus(): void {
this.menuItems?.find(item => !item.disabled)?.focus();
// Queue the focus() call so that browesr gets enough time to execute
// `.setItems()` and set `.menuItems`.
//
// This is useful for:
//
// ```
// const list = document.createElement("fluent-menu-list");
// const option = document.createElement("fluent-menu-item");
// list.append(option);
// document.body.append(list);
// list.focus();
// ```
//
// Without `Updates.enqueu()`, the above `focus()` call would fail because
// in `connectedCallback()`, `.setItems()` is called in an
// `Updates.enqueue()`.
Updates.enqueue(() => {
this.menuItems?.find(item => !item.disabled)?.focus();
});
}

protected setItems(): void {
Expand Down
22 changes: 22 additions & 0 deletions packages/web-components/src/menu-list/menu-list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,28 @@ test.describe('MenuList', () => {
await expect(firstItem).toBeFocused();
});

test('should focus before the queued item refresh completes', async ({ fastPage, page }) => {
await fastPage.setTemplate('');
await page.evaluate(
({ menuItemTagName, menuListTagName }) => {
const menuList = document.createElement(menuListTagName);
menuList.dataset.immediateFocus = '';
for (const label of ['Menu item 1', 'Menu item 2']) {
const menuItem = document.createElement(menuItemTagName);
menuItem.textContent = label;
menuList.append(menuItem);
}
document.body.append(menuList);
menuList.focus();
},
{ menuItemTagName: MenuItemTagName, menuListTagName: tagName },
);
const menuItems = page.locator(`${tagName}[data-immediate-focus]`).locator(MenuItemTagName);
await expect(menuItems.first()).toBeFocused();
await page.keyboard.press('ArrowDown');
await expect(menuItems.nth(1)).toBeFocused();
});

test('should not throw when `focus()` is called with no items', async ({ fastPage }) => {
const { element } = fastPage;

Expand Down
Loading