From 5d554506fc15f8768fa0c3bfe1db69889bf70e57 Mon Sep 17 00:00:00 2001 From: Mu-An Chiou Date: Wed, 23 Oct 2019 14:04:29 -0400 Subject: [PATCH] Expose API for clearing focus and selecting item These two functions are useful when there are 3rd party script behaviors that alters menu items. This allows those behaviors to interact with details-menu without getting into the implementation details of details-menu. For example, - A filtering behavior would want to clear focus after filter. With this change, it will be able to call detailsMenu.clearFocus() instead of 1. duplicating details-menu's logic for querying menu items 2. clearing focus states based on details-menu's implementation - A filtering input would want to trigger an implicit selection for the the first filtered result. With this change, it will be able to invoke detailsMenu.selectFocusOrFirst() instead of 1. duplicating details-menu's logic for querying menu items 2. simulate a click() on the item --- index.d.ts | 2 ++ index.js | 11 +++++++++++ index.js.flow | 2 ++ 3 files changed, 15 insertions(+) diff --git a/index.d.ts b/index.d.ts index ef87173..459f1ac 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,6 +1,8 @@ export default class DetailsMenuElement extends HTMLElement { preload: boolean; src: string; + clearFocus(): void; + selectFocusOrFirst(): void; } declare global { diff --git a/index.js b/index.js index ee618b8..788c619 100644 --- a/index.js +++ b/index.js @@ -31,6 +31,17 @@ class DetailsMenuElement extends HTMLElement { return input instanceof HTMLInputElement ? input : null } + clearFocus() { + clearFocus(this) + } + + selectFocusOrFirst() { + const details = this.parentElement + if (!details) return + const element = getFocusedMenuItem(details) || sibling(details, true) + if (element) element.click() + } + connectedCallback() { if (!this.hasAttribute('role') && !this.hasAttribute('input')) this.setAttribute('role', 'menu') diff --git a/index.js.flow b/index.js.flow index 0c275f3..a9f68e2 100644 --- a/index.js.flow +++ b/index.js.flow @@ -6,6 +6,8 @@ declare class DetailsMenuElement extends HTMLElement { get src(): string; set src(url: string): void; get input(): ?HTMLInputElement; + clearFocus(): void; + selectFocusOrFirst(): void; } declare module '@github/details-menu-element' {