From aa2ebbcf5b1cfb413e60667cbae8c788cc8e4c4b Mon Sep 17 00:00:00 2001 From: Christian Lautier <15379878+maatinito@users.noreply.github.com> Date: Fri, 23 Feb 2024 08:53:11 -1000 Subject: [PATCH] fix dropdown other behavior Removed display of 'Autre' field to allow user to enter directly a value. --- app/javascript/shared/combobox.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/app/javascript/shared/combobox.ts b/app/javascript/shared/combobox.ts index 9e78127ca23..3926eeb824f 100644 --- a/app/javascript/shared/combobox.ts +++ b/app/javascript/shared/combobox.ts @@ -9,6 +9,7 @@ export enum Action { Clear = 'clear', Update = 'update' } + export type Option = { value: string; label: string; data?: unknown }; export type Hint = | { @@ -41,6 +42,7 @@ export class Combobox { #inputValue = ''; #selectedOption: Option | null = null; #focusedOption: Option | null = null; + #otherOption: Option | null = null; #options: Option[] = []; #visibleOptions: Option[] = []; #render: (state: State) => void; @@ -65,6 +67,8 @@ export class Combobox { if (this.#selectedOption) { this.#inputValue = this.#selectedOption.label; } + this.#otherOption = + this.#options.find((o) => o.value == '__other__') ?? null; this.#render = render; } @@ -139,6 +143,8 @@ export class Combobox { } else { this.#selectedOption = null; this.#visibleOptions = this._filterOptions(); + if (this.#otherOption && this.displaysOther()) + this.#visibleOptions.unshift(this.#otherOption); } if (this.#visibleOptions.length > 0) { @@ -156,6 +162,16 @@ export class Combobox { } } + private displaysOther() { + const includeInput = (o: Option) => + o.label.toLowerCase().indexOf(this.#inputValue.toLowerCase()) > 0; + const includeOther = (o: Option) => o.value == this.#otherOption?.value; + return ( + !this.#visibleOptions.find(includeInput) && + !this.#visibleOptions.find(includeOther) + ); + } + keyboard(key: string) { switch (key) { case 'Enter':