Skip to content

Commit

Permalink
fix dropdown other behavior
Browse files Browse the repository at this point in the history
Removed display of 'Autre' field to allow user to enter directly a value.
  • Loading branch information
maatinito committed Feb 24, 2024
1 parent fb34388 commit aa2ebbc
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions app/javascript/shared/combobox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export enum Action {
Clear = 'clear',
Update = 'update'
}

export type Option = { value: string; label: string; data?: unknown };
export type Hint =
| {
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}

Expand Down Expand Up @@ -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) {
Expand All @@ -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':
Expand Down

0 comments on commit aa2ebbc

Please sign in to comment.