From 530b6d336e5b9ecbe5b64b932e4c16e93037ac14 Mon Sep 17 00:00:00 2001 From: Esteban Gonzalez Date: Tue, 30 Aug 2022 09:07:16 -0700 Subject: [PATCH] feat(autocomplete): Add opening and closing upon interaction PiperOrigin-RevId: 471008353 --- autocomplete/filled-autocomplete.ts | 2 +- autocomplete/lib/autocomplete.ts | 42 ++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/autocomplete/filled-autocomplete.ts b/autocomplete/filled-autocomplete.ts index ca19eda8b3..4d8491c5ee 100644 --- a/autocomplete/filled-autocomplete.ts +++ b/autocomplete/filled-autocomplete.ts @@ -28,5 +28,5 @@ declare global { export class MdFilledAutocomplete extends Autocomplete { protected override readonly listTag = literal`md-list`; protected override readonly menuSurfaceTag = literal`md-menu-surface`; - protected override readonly textFieldTag = literal`md-filled-field`; + protected override readonly textFieldTag = literal`md-filled-text-field`; } diff --git a/autocomplete/lib/autocomplete.ts b/autocomplete/lib/autocomplete.ts index 9a2c2125d4..b7a567726e 100644 --- a/autocomplete/lib/autocomplete.ts +++ b/autocomplete/lib/autocomplete.ts @@ -45,7 +45,9 @@ export abstract class Autocomplete extends LitElement { /** @soyTemplate */ override render(): TemplateResult { - return html`
+ return html`
${this.renderTextField()} ${this.renderMenuSurface()}
`; } @@ -80,8 +82,46 @@ export abstract class Autocomplete extends LitElement { return staticHtml`<${this.menuSurfaceTag} class="md3-autocomplete__menu-surface" .corner=${'BOTTOM_START'} + ?stayOpenOnBodyClick=${true} > <${this.listTag}> `; } + + isOpen() { + return this.menuSurface?.open || false; + } + + open() { + this.menuSurface?.show(); + // TODO(b/242594859): Add once supported by textfield + // this.textField.ariaExpanded = true; + } + + close() { + this.menuSurface?.close(); + // TODO(b/242594859): Add once supported by textfield + // this.textField.ariaExpanded = false; + // this.setActiveDescendant(); + } + + protected handleClick(event: PointerEvent) { + // When clicking the list (not items nor text field) the menu should stay + // open. + if (this.isOpen() && + (event.target as Node)?.parentNode !== this.menuSurface) { + this.close(); + } else { + this.open(); + } + } + + // TODO(b/243389569): Revisit focus control when extending textfield + protected handleFocusout() { + if (this.matches(':focus-within')) { + this.textField?.focus(); + return; + } + this.close(); + } }