refactor(ui): autocomplete pagination and infinite scroll (#1965)

This commit is contained in:
Alex
2026-07-09 20:23:52 +01:00
committed by GitHub
parent b4570e3366
commit 0b1fa83a65
28 changed files with 518 additions and 209 deletions
@@ -1,6 +1,7 @@
import { import {
booleanAttribute, booleanAttribute,
computed, computed,
contentChild,
Directive, Directive,
inject, inject,
input, input,
@@ -10,23 +11,16 @@ import {
viewChild, viewChild,
} from '@angular/core'; } from '@angular/core';
import { Combobox } from '@angular/aria/combobox'; import { Combobox } from '@angular/aria/combobox';
import { CdkConnectedOverlay, Overlay } from '@angular/cdk/overlay';
import { cn } from '../cn';
import {
connectedOverlayPanelClass,
connectedOverlayPositions,
connectedOverlayScrollStrategy,
refreshConnectedOverlayPosition,
} from '../connected-overlay';
import { APP_FIELD } from '../field/app-field.context'; import { APP_FIELD } from '../field/app-field.context';
import { type AppInputSize } from '../input/app-input.variants'; import { type AppInputSize } from '../input/app-input.variants';
import { type TagSize } from '../tag/app-tag.variants';
import { import {
overlayListEmptyItemClass, toAutocompleteOption,
overlayListOptionClass, type AppAutocompleteOption,
overlayListRootClass, type AppAutocompleteSuggestion,
overlayListSurfaceClass, } from './app-autocomplete-option';
} from '../overlay-list.styles'; import { AppAutocompleteOptionTemplateDirective } from './app-autocomplete-option-template.directive';
import { autocompleteBoxVariants } from './app-autocomplete.variants'; import { autocompleteBoxVariants } from './app-autocomplete.variants';
@Directive() @Directive()
@@ -35,12 +29,15 @@ export abstract class AppAutocompleteBaseDirective {
readonly required = input(false, { transform: booleanAttribute }); readonly required = input(false, { transform: booleanAttribute });
readonly invalid = input(false, { transform: booleanAttribute }); readonly invalid = input(false, { transform: booleanAttribute });
readonly pending = input(false, { transform: booleanAttribute }); readonly pending = input(false, { transform: booleanAttribute });
readonly loadingMore = input(false, { transform: booleanAttribute });
readonly hasMore = input(false, { transform: booleanAttribute });
readonly errored = input(false, { transform: booleanAttribute });
readonly readonly = input(false, { transform: booleanAttribute }); readonly readonly = input(false, { transform: booleanAttribute });
readonly touched = model(false); readonly touched = model(false);
readonly name = input(''); readonly name = input('');
readonly allowCustom = input(true, { transform: booleanAttribute }); readonly allowCustom = input(true, { transform: booleanAttribute });
readonly suggestions = input<readonly string[]>([]); readonly suggestions = input<readonly AppAutocompleteSuggestion[]>([]);
readonly size = input<AppInputSize>('md'); readonly size = input<AppInputSize>('md');
readonly placeholder = input(''); readonly placeholder = input('');
readonly emptyMessage = input(''); readonly emptyMessage = input('');
@@ -49,12 +46,13 @@ export abstract class AppAutocompleteBaseDirective {
readonly ariaDescribedBy = input(''); readonly ariaDescribedBy = input('');
readonly complete = output<string>(); readonly complete = output<string>();
readonly opened = output<void>();
readonly loadMore = output<void>();
private readonly fieldContext = inject(APP_FIELD, { optional: true }); private readonly fieldContext = inject(APP_FIELD, { optional: true });
private readonly overlayService = inject(Overlay);
protected readonly combobox = viewChild(Combobox); protected readonly combobox = viewChild(Combobox);
private readonly overlay = viewChild(CdkConnectedOverlay);
private readonly input = viewChild<ElementRef<HTMLInputElement>>('input'); private readonly input = viewChild<ElementRef<HTMLInputElement>>('input');
protected readonly optionTemplate = contentChild(AppAutocompleteOptionTemplateDirective);
protected readonly resolvedInputId = computed(() => this.inputId() || this.fieldContext?.controlId() || null); protected readonly resolvedInputId = computed(() => this.inputId() || this.fieldContext?.controlId() || null);
protected readonly resolvedDescribedBy = computed( protected readonly resolvedDescribedBy = computed(
@@ -62,15 +60,12 @@ export abstract class AppAutocompleteBaseDirective {
); );
protected readonly showInvalid = computed(() => this.invalid() && (this.fieldContext?.validationVisible() ?? true)); protected readonly showInvalid = computed(() => this.invalid() && (this.fieldContext?.validationVisible() ?? true));
protected readonly isUnavailable = computed(() => this.disabled() || this.readonly()); protected readonly isUnavailable = computed(() => this.disabled() || this.readonly());
protected readonly normalizedSuggestions = computed<readonly AppAutocompleteOption[]>(() =>
protected readonly overlayPositions = connectedOverlayPositions; this.suggestions().map(toAutocompleteOption),
protected readonly overlayScrollStrategy = connectedOverlayScrollStrategy(this.overlayService); );
protected readonly selectedTagSize = computed<TagSize>(() => (this.size() === 'sm' ? 'sm' : 'md'));
protected readonly innerInputClass = protected readonly innerInputClass =
'min-w-[6rem] flex-1 border-0 bg-transparent p-0 text-inherit outline-hidden placeholder:text-text-muted disabled:cursor-default'; 'min-w-[6rem] flex-1 border-0 bg-transparent p-0 text-inherit outline-hidden placeholder:text-text-muted disabled:cursor-default';
protected readonly surfaceClass = cn(overlayListSurfaceClass, connectedOverlayPanelClass, 'box-border w-full p-0');
protected readonly listClass = cn(overlayListRootClass, 'max-h-60 overflow-y-auto overscroll-contain p-1');
protected readonly optionClass = overlayListOptionClass;
protected readonly emptyClass = overlayListEmptyItemClass;
protected readonly boxClass = computed(() => protected readonly boxClass = computed(() =>
autocompleteBoxVariants({ size: this.size(), disabled: this.disabled(), invalid: this.showInvalid() }), autocompleteBoxVariants({ size: this.size(), disabled: this.disabled(), invalid: this.showInvalid() }),
@@ -82,8 +77,13 @@ export abstract class AppAutocompleteBaseDirective {
input.focus(); input.focus();
} }
protected onOverlayAttach(): void { protected onInputFocus(): void {
refreshConnectedOverlayPosition(this.overlay()); if (this.isUnavailable()) return;
this.opened.emit();
}
protected closePopup(): void {
this.combobox()?.close();
} }
focus(options?: FocusOptions): void { focus(options?: FocusOptions): void {
@@ -0,0 +1,15 @@
import { Directive, TemplateRef, inject } from '@angular/core';
import { type AppAutocompleteOption } from './app-autocomplete-option';
export interface AppAutocompleteOptionContext<T = unknown> {
$implicit: AppAutocompleteOption<T>;
}
@Directive({
selector: 'ng-template[appAutocompleteOption]',
standalone: true,
})
export class AppAutocompleteOptionTemplateDirective<T = unknown> {
readonly template = inject<TemplateRef<AppAutocompleteOptionContext<T>>>(TemplateRef);
}
@@ -0,0 +1,11 @@
export interface AppAutocompleteOption<T = unknown> {
value: string;
label: string;
data?: T;
}
export type AppAutocompleteSuggestion = string | AppAutocompleteOption;
export function toAutocompleteOption(suggestion: AppAutocompleteSuggestion): AppAutocompleteOption {
return typeof suggestion === 'string' ? { value: suggestion, label: suggestion } : suggestion;
}
@@ -0,0 +1,248 @@
import {
afterRenderEffect,
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
input,
linkedSignal,
output,
viewChild,
viewChildren,
type ElementRef,
type TemplateRef,
} from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { ComboboxPopupContainer } from '@angular/aria/combobox';
import { Listbox, Option } from '@angular/aria/listbox';
import {
CdkConnectedOverlay,
type ConnectedPosition,
Overlay,
OverlayModule,
type ScrollStrategy,
} from '@angular/cdk/overlay';
import { TranslocoPipe } from '@jsverse/transloco';
import { LucideLoaderCircle } from '@lucide/angular';
import { cn } from '../cn';
import {
connectedOverlayPanelClass,
connectedOverlayPositions,
connectedOverlayScrollStrategy,
refreshConnectedOverlayPosition,
} from '../connected-overlay';
import {
overlayListEmptyItemClass,
overlayListOptionClass,
overlayListRootClass,
overlayListSurfaceClass,
} from '../overlay-list.styles';
import { type AppAutocompleteOption } from './app-autocomplete-option';
import { type AppAutocompleteOptionContext } from './app-autocomplete-option-template.directive';
const LOAD_MORE_PREFETCH_PX = 240;
@Component({
selector: 'app-autocomplete-popup',
standalone: true,
imports: [NgTemplateOutlet, OverlayModule, ComboboxPopupContainer, Listbox, Option, TranslocoPipe, LucideLoaderCircle],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-template ngComboboxPopupContainer>
<ng-template
[cdkConnectedOverlay]="{
origin: origin(),
usePopover: 'inline',
matchWidth: true,
positions: overlayPositions,
viewportMargin: 8,
push: true
}"
[cdkConnectedOverlayOpen]="open()"
[cdkConnectedOverlayScrollStrategy]="overlayScrollStrategy"
(attach)="onOverlayAttach()">
<div [class]="surfaceClass">
<ul
ngListbox
#list
tabindex="-1"
focusMode="activedescendant"
selectionMode="explicit"
[readonly]="readonly()"
[disabled]="disabled()"
[attr.aria-busy]="isBusy() ? 'true' : null"
(valuesChange)="onValuesChange($event)"
[class]="listClass">
@for (option of options(); track option.value) {
<li
ngOption
tabindex="-1"
[value]="option.value"
[label]="option.label"
[class]="optionClass"
(pointerdown)="onOptionPointerdown($event, option)">
@if (optionTemplate(); as template) {
<ng-container *ngTemplateOutlet="template; context: { $implicit: option }" />
} @else {
<span class="truncate leading-5">{{ option.label }}</span>
}
</li>
} @empty {
@if (pending()) {
<li [class]="loadingRowClass" role="presentation">
<svg lucideLoaderCircle class="size-4 animate-spin text-text-muted motion-reduce:animate-none" aria-hidden="true"></svg>
<span class="sr-only">{{ 'shared.ui.spinner.loading' | transloco }}</span>
</li>
} @else if (errored()) {
<li [class]="emptyClass" role="presentation">{{ 'shared.ui.autocomplete.loadFailed' | transloco }}</li>
} @else {
<li [class]="emptyClass" role="presentation">{{ emptyMessage() || ('shared.ui.autocomplete.noResults' | transloco) }}</li>
}
}
@if (showLoadError()) {
<li [class]="emptyClass" role="presentation">{{ 'shared.ui.autocomplete.loadFailed' | transloco }}</li>
} @else if (showSentinel()) {
<li #sentinel [class]="loadingRowClass" role="presentation" aria-hidden="true">
<svg lucideLoaderCircle class="size-4 animate-spin text-text-muted motion-reduce:animate-none" aria-hidden="true"></svg>
</li>
}
</ul>
</div>
</ng-template>
</ng-template>
`,
})
export class AppAutocompletePopupComponent {
readonly origin = input.required<ElementRef<HTMLElement> | HTMLElement>();
readonly open = input(false);
readonly disabled = input(false);
readonly readonly = input(false);
readonly pending = input(false);
readonly loadingMore = input(false);
readonly hasMore = input(false);
readonly errored = input(false);
readonly suggestions = input<readonly AppAutocompleteOption[]>([]);
readonly emptyMessage = input('');
readonly optionTemplate = input<TemplateRef<AppAutocompleteOptionContext> | null>(null);
readonly optionSelected = output<AppAutocompleteOption>();
readonly loadMore = output<void>();
private readonly overlay = viewChild(CdkConnectedOverlay);
private readonly listbox = viewChild<Listbox<string>>(Listbox);
private readonly optionRefs = viewChildren<Option<string>>(Option);
private readonly listRef = viewChild<ElementRef<HTMLElement>>('list');
private readonly sentinelRef = viewChild<ElementRef<HTMLElement>>('sentinel');
private readonly overlayService = inject(Overlay);
protected readonly overlayPositions: ConnectedPosition[] = connectedOverlayPositions;
protected readonly overlayScrollStrategy: ScrollStrategy = connectedOverlayScrollStrategy(this.overlayService);
protected readonly surfaceClass = cn(overlayListSurfaceClass, connectedOverlayPanelClass, 'box-border w-full p-0');
protected readonly optionClass = cn(overlayListOptionClass, 'shrink-0');
protected readonly emptyClass = overlayListEmptyItemClass;
protected readonly loadingRowClass = cn(overlayListEmptyItemClass, 'justify-center');
protected readonly listClass = cn(
overlayListRootClass,
'max-h-60 overflow-y-auto overscroll-contain p-1 [scrollbar-gutter:stable]',
);
protected readonly options = computed(() => {
const seen = new Set<string>();
return this.suggestions().filter((option) => {
if (seen.has(option.value)) return false;
seen.add(option.value);
return true;
});
});
protected readonly showSentinel = computed(() => this.hasMore() && this.options().length > 0);
protected readonly showLoadError = computed(() => this.errored() && this.options().length > 0 && !this.loadingMore());
protected readonly isBusy = computed(() => this.pending() || this.loadingMore());
private readonly loadMoreRequested = linkedSignal({
source: () => ({ options: this.options(), loadingMore: this.loadingMore() }),
computation: () => false,
});
private leadingOptionValue: string | null = null;
constructor() {
effect((onCleanup) => {
this.options();
const list = this.listRef()?.nativeElement;
const sentinel = this.sentinelRef()?.nativeElement;
if (!list || !sentinel) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) this.requestLoadMore();
},
{ root: list, rootMargin: `0px 0px ${LOAD_MORE_PREFETCH_PX}px 0px` },
);
observer.observe(sentinel);
onCleanup(() => observer.disconnect());
});
afterRenderEffect(() => {
const leading = this.options()[0]?.value ?? null;
this.pending();
this.errored();
this.showSentinel();
const list = this.listRef()?.nativeElement;
if (list && leading !== this.leadingOptionValue) list.scrollTop = 0;
this.leadingOptionValue = leading;
refreshConnectedOverlayPosition(this.overlay());
});
}
activeOption(): AppAutocompleteOption | null {
const active = this.optionRefs().find((option) => option.active());
if (!active) return null;
const value = active.value();
return this.options().find((option) => option.value === value) ?? null;
}
clearSelection(): void {
this.listbox()?.values.set([]);
}
protected onOverlayAttach(): void {
refreshConnectedOverlayPosition(this.overlay());
}
protected onValuesChange(values: readonly string[] | Set<string>): void {
const picked = this.lastSelectedValue(values);
if (!picked) return;
this.clearSelection();
const option = this.options().find((candidate) => candidate.value === picked);
if (option) this.optionSelected.emit(option);
}
protected onOptionPointerdown(event: PointerEvent, option: AppAutocompleteOption): void {
event.preventDefault();
event.stopPropagation();
this.clearSelection();
this.optionSelected.emit(option);
}
private requestLoadMore(): void {
if (
this.disabled() ||
this.readonly() ||
this.pending() ||
this.loadingMore() ||
this.errored() ||
!this.hasMore() ||
this.loadMoreRequested()
) return;
this.loadMoreRequested.set(true);
this.loadMore.emit();
}
private lastSelectedValue(values: readonly string[] | Set<string>): string | null {
const selected = Array.isArray(values) ? values : [...values];
return selected[selected.length - 1] ?? null;
}
}
@@ -0,0 +1,31 @@
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
import { AppTagComponent } from '../tag/app-tag.component';
import { type TagSize } from '../tag/app-tag.variants';
import { type AppAutocompleteOption } from './app-autocomplete-option';
@Component({
selector: 'app-autocomplete-selected-tags',
standalone: true,
imports: [AppTagComponent],
host: { class: 'contents' },
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@for (tag of tags(); track tag.value) {
<app-tag
[size]="size()"
[removable]="removable()"
[label]="tag.label"
[removeLabel]="removeTagLabel()"
(remove)="remove.emit(tag.value)" />
}
`,
})
export class AppAutocompleteSelectedTagsComponent {
readonly tags = input<readonly AppAutocompleteOption[]>([]);
readonly size = input<TagSize>('md');
readonly removable = input(true);
readonly removeTagLabel = input('');
readonly remove = output<string>();
}
@@ -1,26 +1,19 @@
import { ChangeDetectionStrategy, Component, linkedSignal, model } from '@angular/core'; import { ChangeDetectionStrategy, Component, computed, input, linkedSignal, model, signal, viewChild } from '@angular/core';
import { type FormValueControl } from '@angular/forms/signals'; import { type FormValueControl } from '@angular/forms/signals';
import { Combobox, ComboboxInput, ComboboxPopupContainer } from '@angular/aria/combobox'; import { Combobox, ComboboxInput } from '@angular/aria/combobox';
import { Listbox, Option } from '@angular/aria/listbox';
import { OverlayModule } from '@angular/cdk/overlay';
import { TranslocoPipe } from '@jsverse/transloco';
import { LucideLoaderCircle } from '@lucide/angular'; import { LucideLoaderCircle } from '@lucide/angular';
import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'; import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive';
import { type AppAutocompleteOption } from './app-autocomplete-option';
import { AppAutocompletePopupComponent } from './app-autocomplete-popup.component';
import { AppAutocompleteSelectedTagsComponent } from './app-autocomplete-selected-tags.component';
type AppAutocompleteSelectedDisplay = 'text' | 'tag';
@Component({ @Component({
selector: 'app-autocomplete', selector: 'app-autocomplete',
standalone: true, standalone: true,
imports: [ imports: [Combobox, ComboboxInput, LucideLoaderCircle, AppAutocompletePopupComponent, AppAutocompleteSelectedTagsComponent],
OverlayModule,
Combobox,
ComboboxInput,
ComboboxPopupContainer,
Listbox,
Option,
TranslocoPipe,
LucideLoaderCircle,
],
host: { class: 'block w-full' }, host: { class: 'block w-full' },
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
template: ` template: `
@@ -35,6 +28,14 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
#origin #origin
[class]="boxClass()" [class]="boxClass()"
(pointerdown)="focusInputOnPointerdown($event, input)"> (pointerdown)="focusInputOnPointerdown($event, input)">
@if (selectedTags().length) {
<app-autocomplete-selected-tags
[tags]="selectedTags()"
[size]="selectedTagSize()"
[removable]="!isUnavailable()"
[removeTagLabel]="removeTagLabel()"
(remove)="clearSelectedTag(input)" />
}
<input <input
ngComboboxInput ngComboboxInput
#input #input
@@ -44,87 +45,127 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
[(value)]="query" [(value)]="query"
[attr.id]="resolvedInputId()" [attr.id]="resolvedInputId()"
[attr.name]="name() || null" [attr.name]="name() || null"
[placeholder]="placeholder()" [placeholder]="placeholderText()"
[attr.aria-label]="ariaLabel() || null" [attr.aria-label]="ariaLabel() || null"
[attr.aria-invalid]="showInvalid() ? 'true' : null" [attr.aria-invalid]="showInvalid() ? 'true' : null"
[attr.aria-readonly]="readonly() ? 'true' : null" [attr.aria-readonly]="inputReadonly() ? 'true' : null"
[attr.aria-busy]="pending() ? 'true' : null" [attr.aria-busy]="pending() ? 'true' : null"
[attr.aria-describedby]="resolvedDescribedBy()" [attr.aria-describedby]="resolvedDescribedBy()"
[disabled]="disabled()" [disabled]="disabled()"
[required]="required()" [required]="required()"
[readonly]="readonly()" [readonly]="inputReadonly()"
(input)="onType(input.value)" (input)="onType(input.value)"
(focus)="onInputFocus()"
(keydown.enter)="onEnter($event)"
(blur)="onInputBlur()" (blur)="onInputBlur()"
[class]="innerInputClass" /> [class]="innerInputClass" />
@if (pending()) { <svg
<svg lucideLoaderCircle class="size-4 shrink-0 animate-spin text-text-muted" aria-hidden="true"></svg> lucideLoaderCircle
} class="size-4 shrink-0 text-text-muted motion-reduce:animate-none"
[class.animate-spin]="pending()"
[class.invisible]="!pending()"
aria-hidden="true"></svg>
</div> </div>
<ng-template ngComboboxPopupContainer> <app-autocomplete-popup
<ng-template [origin]="origin"
[cdkConnectedOverlay]="{ [open]="cb.expanded()"
origin, [disabled]="disabled()"
usePopover: 'inline', [readonly]="readonly()"
matchWidth: true, [pending]="pending()"
positions: overlayPositions, [loadingMore]="loadingMore()"
viewportMargin: 8, [hasMore]="hasMore()"
push: true [errored]="errored()"
}" [suggestions]="normalizedSuggestions()"
[cdkConnectedOverlayOpen]="cb.expanded()" [emptyMessage]="emptyMessage()"
[cdkConnectedOverlayScrollStrategy]="overlayScrollStrategy" [optionTemplate]="optionTemplate()?.template ?? null"
(attach)="onOverlayAttach()"> (optionSelected)="selectOption($event)"
<div [class]="surfaceClass"> (loadMore)="loadMore.emit()" />
<ul
ngListbox
tabindex="-1"
focusMode="activedescendant"
selectionMode="explicit"
[readonly]="readonly()"
[disabled]="disabled()"
(valuesChange)="onSelect($event)"
[class]="listClass">
@for (option of suggestions(); track option) {
<li ngOption tabindex="-1" [value]="option" [label]="option" [class]="optionClass">
<span class="truncate leading-5">{{ option }}</span>
</li>
} @empty {
<li [class]="emptyClass">{{ emptyMessage() || ('shared.ui.autocomplete.noResults' | transloco) }}</li>
}
</ul>
</div>
</ng-template>
</ng-template>
</div> </div>
`, `,
}) })
export class AppAutocompleteComponent extends AppAutocompleteBaseDirective implements FormValueControl<string> { export class AppAutocompleteComponent extends AppAutocompleteBaseDirective implements FormValueControl<string> {
readonly value = model(''); readonly value = model('');
readonly selectedDisplay = input<AppAutocompleteSelectedDisplay>('text');
readonly removeTagLabel = input('');
protected readonly query = linkedSignal(() => this.value()); private readonly popup = viewChild(AppAutocompletePopupComponent);
private readonly committedOption = signal<AppAutocompleteOption | null>(null);
protected readonly selectedLabel = computed(() => {
const value = this.value();
const committed = this.committedOption();
if (committed && committed.value === value) return committed.label;
return this.normalizedSuggestions().find((option) => option.value === value)?.label ?? value;
});
protected readonly query = linkedSignal({
source: () => ({ display: this.selectedDisplay(), label: this.selectedLabel() }),
computation: ({ display, label }) => (display === 'tag' && label.trim() ? '' : label),
});
protected readonly showSelectedTag = computed(() => this.selectedDisplay() === 'tag' && !!this.value().trim());
protected readonly selectedTags = computed<readonly AppAutocompleteOption[]>(() =>
this.showSelectedTag() ? [{ value: this.value(), label: this.selectedLabel() }] : [],
);
protected readonly inputReadonly = computed(() => this.readonly() || this.showSelectedTag());
protected readonly placeholderText = computed(() => (this.showSelectedTag() ? '' : this.placeholder()));
protected onType(text: string): void { protected onType(text: string): void {
if (this.isUnavailable()) return; if (this.isUnavailable() || this.showSelectedTag()) return;
if (this.allowCustom() || !text.trim()) this.value.set(text); if (this.selectedDisplay() !== 'tag' && (this.allowCustom() || !text.trim())) this.value.set(text);
this.complete.emit(text); this.complete.emit(text);
} }
protected onEnter(event: Event): void {
if (this.isUnavailable() || this.selectedDisplay() !== 'tag' || this.showSelectedTag()) return;
event.preventDefault();
event.stopPropagation();
const active = this.popup()?.activeOption();
if (active) {
this.selectOption(active);
return;
}
const trimmed = this.query().trim();
if (!trimmed) return;
const match = this.normalizedSuggestions().find((option) => option.label === trimmed);
if (match) {
this.selectOption(match);
return;
}
if (this.allowCustom()) this.selectOption({ value: trimmed, label: trimmed });
}
protected override onInputFocus(): void {
if (this.showSelectedTag()) return;
super.onInputFocus();
}
protected onInputBlur(): void { protected onInputBlur(): void {
this.touched.set(true); this.touched.set(true);
if (this.allowCustom()) return; if (this.allowCustom()) return;
queueMicrotask(() => { queueMicrotask(() => {
if (!this.allowCustom()) this.query.set(this.value()); if (!this.allowCustom()) this.query.set(this.selectedLabel());
}); });
} }
protected onSelect(values: readonly string[]): void { protected selectOption(option: AppAutocompleteOption): void {
if (this.isUnavailable() || !values.length) return; if (this.isUnavailable()) return;
const picked = values[values.length - 1]; this.committedOption.set(option);
this.value.set(picked); this.value.set(option.value);
this.query.set(picked); this.query.set(this.selectedDisplay() === 'tag' ? '' : option.label);
this.touched.set(true); this.touched.set(true);
this.combobox()?.close(); this.closePopup();
}
protected clearSelectedTag(input: HTMLInputElement): void {
if (this.isUnavailable()) return;
this.committedOption.set(null);
this.value.set('');
this.query.set('');
this.touched.set(true);
this.complete.emit('');
queueMicrotask(() => input.focus());
} }
} }
@@ -6,32 +6,20 @@ import {
linkedSignal, linkedSignal,
model, model,
viewChild, viewChild,
viewChildren,
} from '@angular/core'; } from '@angular/core';
import { type FormValueControl } from '@angular/forms/signals'; import { type FormValueControl } from '@angular/forms/signals';
import { Combobox, ComboboxInput, ComboboxPopupContainer } from '@angular/aria/combobox'; import { Combobox, ComboboxInput } from '@angular/aria/combobox';
import { Listbox, Option } from '@angular/aria/listbox';
import { OverlayModule } from '@angular/cdk/overlay';
import { TranslocoPipe } from '@jsverse/transloco';
import { LucideLoaderCircle } from '@lucide/angular'; import { LucideLoaderCircle } from '@lucide/angular';
import { AppTagComponent } from '../tag/app-tag.component';
import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'; import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive';
import { type AppAutocompleteOption } from './app-autocomplete-option';
import { AppAutocompletePopupComponent } from './app-autocomplete-popup.component';
import { AppAutocompleteSelectedTagsComponent } from './app-autocomplete-selected-tags.component';
@Component({ @Component({
selector: 'app-multi-autocomplete', selector: 'app-multi-autocomplete',
standalone: true, standalone: true,
imports: [ imports: [Combobox, ComboboxInput, LucideLoaderCircle, AppAutocompletePopupComponent, AppAutocompleteSelectedTagsComponent],
OverlayModule,
Combobox,
ComboboxInput,
ComboboxPopupContainer,
Listbox,
Option,
AppTagComponent,
TranslocoPipe,
LucideLoaderCircle,
],
host: { class: 'block w-full' }, host: { class: 'block w-full' },
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
template: ` template: `
@@ -46,13 +34,13 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
#origin #origin
[class]="boxClass()" [class]="boxClass()"
(pointerdown)="focusInputOnPointerdown($event, input)"> (pointerdown)="focusInputOnPointerdown($event, input)">
@for (tag of value(); track tag) { @if (selectedTags().length) {
<app-tag <app-autocomplete-selected-tags
size="sm" [tags]="selectedTags()"
[size]="selectedTagSize()"
[removable]="!isUnavailable()" [removable]="!isUnavailable()"
[label]="tag" [removeTagLabel]="removeTagLabel()"
[removeLabel]="removeTagLabel() || ('shared.ui.autocomplete.removeTag' | transloco: { tag })" (remove)="removeChip($event)" />
(remove)="removeChip(tag)" />
} }
<input <input
ngComboboxInput ngComboboxInput
@@ -73,49 +61,33 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
[required]="required()" [required]="required()"
[readonly]="readonly()" [readonly]="readonly()"
(input)="onType(input.value)" (input)="onType(input.value)"
(focus)="onInputFocus()"
(keydown.enter)="onEnter($event)" (keydown.enter)="onEnter($event)"
(keydown.backspace)="onBackspace()" (keydown.backspace)="onBackspace()"
(blur)="touched.set(true)" (blur)="touched.set(true)"
[class]="innerInputClass" /> [class]="innerInputClass" />
@if (pending()) { <svg
<svg lucideLoaderCircle class="size-4 shrink-0 animate-spin text-text-muted" aria-hidden="true"></svg> lucideLoaderCircle
} class="size-4 shrink-0 text-text-muted motion-reduce:animate-none"
[class.animate-spin]="pending()"
[class.invisible]="!pending()"
aria-hidden="true"></svg>
</div> </div>
<ng-template ngComboboxPopupContainer> <app-autocomplete-popup
<ng-template [origin]="origin"
[cdkConnectedOverlay]="{ [open]="cb.expanded()"
origin, [disabled]="disabled()"
usePopover: 'inline', [readonly]="readonly()"
matchWidth: true, [pending]="pending()"
positions: overlayPositions, [loadingMore]="loadingMore()"
viewportMargin: 8, [hasMore]="hasMore()"
push: true [errored]="errored()"
}" [suggestions]="normalizedSuggestions()"
[cdkConnectedOverlayOpen]="cb.expanded()" [emptyMessage]="emptyMessage()"
[cdkConnectedOverlayScrollStrategy]="overlayScrollStrategy" [optionTemplate]="optionTemplate()?.template ?? null"
(attach)="onOverlayAttach()"> (optionSelected)="selectOption($event)"
<div [class]="surfaceClass"> (loadMore)="loadMore.emit()" />
<ul
ngListbox
tabindex="-1"
focusMode="activedescendant"
selectionMode="explicit"
[readonly]="readonly()"
[disabled]="disabled()"
(valuesChange)="onSelect($event)"
[class]="listClass">
@for (option of suggestions(); track option) {
<li ngOption tabindex="-1" [value]="option" [label]="option" [class]="optionClass">
<span class="truncate leading-5">{{ option }}</span>
</li>
} @empty {
<li [class]="emptyClass">{{ emptyMessage() || ('shared.ui.autocomplete.noResults' | transloco) }}</li>
}
</ul>
</div>
</ng-template>
</ng-template>
</div> </div>
`, `,
}) })
@@ -124,14 +96,20 @@ export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective
readonly removeTagLabel = input(''); readonly removeTagLabel = input('');
private readonly listbox = viewChild<Listbox<string>>(Listbox); private readonly popup = viewChild(AppAutocompletePopupComponent);
protected readonly optionRefs = viewChildren(Option); private readonly chipLabels = new Map<string, string>();
protected readonly query = linkedSignal<string[], string>({ protected readonly query = linkedSignal<string[], string>({
source: this.value, source: this.value,
computation: () => '', computation: () => '',
}); });
protected readonly selectedTags = computed<readonly AppAutocompleteOption[]>(() =>
this.value().map((value) => ({
value,
label: this.chipLabels.get(value) ?? this.normalizedSuggestions().find((option) => option.value === value)?.label ?? value,
})),
);
protected readonly placeholderText = computed(() => (this.value().length ? '' : this.placeholder())); protected readonly placeholderText = computed(() => (this.value().length ? '' : this.placeholder()));
protected onType(text: string): void { protected onType(text: string): void {
@@ -143,12 +121,19 @@ export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective
if (this.isUnavailable()) return; if (this.isUnavailable()) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const active = this.optionRefs().find((option) => option.active()); const active = this.popup()?.activeOption();
if (active) { if (active) {
this.addChip(String(active.value()), true); this.addChip(active);
return; return;
} }
this.addChip(this.query()); const trimmed = this.query().trim();
if (!trimmed) return;
const match = this.normalizedSuggestions().find((option) => option.label === trimmed);
if (match) {
this.addChip(match);
return;
}
if (this.allowCustom()) this.addChip({ value: trimmed, label: trimmed });
} }
protected onBackspace(): void { protected onBackspace(): void {
@@ -159,35 +144,33 @@ export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective
this.touched.set(true); this.touched.set(true);
} }
protected onSelect(values: readonly string[]): void { protected selectOption(option: AppAutocompleteOption): void {
if (this.isUnavailable() || !values.length) return; this.addChip(option);
this.addChip(values[values.length - 1], true);
} }
protected removeChip(tag: string): void { protected removeChip(value: string): void {
this.value.set(this.value().filter((existing) => existing !== tag)); this.chipLabels.delete(value);
this.value.set(this.value().filter((existing) => existing !== value));
this.touched.set(true); this.touched.set(true);
} }
private addChip(text: string, fromSuggestion = false): void { private addChip(option: AppAutocompleteOption): void {
if (this.isUnavailable()) return; if (this.isUnavailable()) return;
const trimmed = text.trim();
if (!trimmed) return;
if (!fromSuggestion && !this.allowCustom() && !this.suggestions().includes(trimmed)) return;
const current = this.value(); const current = this.value();
if (current.includes(trimmed)) { if (current.includes(option.value)) {
this.clearTagInput(); this.clearTagInput();
return; return;
} }
this.value.set([...current, trimmed]); this.chipLabels.set(option.value, option.label);
this.value.set([...current, option.value]);
this.clearTagInput(); this.clearTagInput();
this.touched.set(true); this.touched.set(true);
this.complete.emit(''); this.complete.emit('');
} }
private clearTagInput(): void { private clearTagInput(): void {
this.combobox()?.close(); this.closePopup();
this.listbox()?.values.set([]); this.popup()?.clearSelection();
this.query.set(''); this.query.set('');
} }
} }
+1 -2
View File
@@ -159,8 +159,7 @@
}, },
"ui": { "ui": {
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"previousMonth": "", "previousMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -1
View File
@@ -160,7 +160,7 @@
"ui": { "ui": {
"autocomplete": { "autocomplete": {
"noResults": "No results", "noResults": "No results",
"removeTag": "Remove {{ tag }}" "loadFailed": "Couldn't load results"
}, },
"datePicker": { "datePicker": {
"previousMonth": "Previous month", "previousMonth": "Previous month",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -159,8 +159,7 @@
}, },
"ui": { "ui": {
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"previousMonth": "", "previousMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",
+1 -2
View File
@@ -192,8 +192,7 @@
"loading": "" "loading": ""
}, },
"autocomplete": { "autocomplete": {
"noResults": "", "noResults": ""
"removeTag": ""
}, },
"datePicker": { "datePicker": {
"nextMonth": "", "nextMonth": "",