refactor(ui): autocomplete pagination and infinite scroll (#1965)
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
computed,
|
||||
contentChild,
|
||||
Directive,
|
||||
inject,
|
||||
input,
|
||||
@@ -10,23 +11,16 @@ import {
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
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 { type AppInputSize } from '../input/app-input.variants';
|
||||
import { type TagSize } from '../tag/app-tag.variants';
|
||||
import {
|
||||
overlayListEmptyItemClass,
|
||||
overlayListOptionClass,
|
||||
overlayListRootClass,
|
||||
overlayListSurfaceClass,
|
||||
} from '../overlay-list.styles';
|
||||
toAutocompleteOption,
|
||||
type AppAutocompleteOption,
|
||||
type AppAutocompleteSuggestion,
|
||||
} from './app-autocomplete-option';
|
||||
import { AppAutocompleteOptionTemplateDirective } from './app-autocomplete-option-template.directive';
|
||||
import { autocompleteBoxVariants } from './app-autocomplete.variants';
|
||||
|
||||
@Directive()
|
||||
@@ -35,12 +29,15 @@ export abstract class AppAutocompleteBaseDirective {
|
||||
readonly required = input(false, { transform: booleanAttribute });
|
||||
readonly invalid = 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 touched = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly allowCustom = input(true, { transform: booleanAttribute });
|
||||
readonly suggestions = input<readonly string[]>([]);
|
||||
readonly suggestions = input<readonly AppAutocompleteSuggestion[]>([]);
|
||||
readonly size = input<AppInputSize>('md');
|
||||
readonly placeholder = input('');
|
||||
readonly emptyMessage = input('');
|
||||
@@ -49,12 +46,13 @@ export abstract class AppAutocompleteBaseDirective {
|
||||
readonly ariaDescribedBy = input('');
|
||||
|
||||
readonly complete = output<string>();
|
||||
readonly opened = output<void>();
|
||||
readonly loadMore = output<void>();
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
private readonly overlayService = inject(Overlay);
|
||||
protected readonly combobox = viewChild(Combobox);
|
||||
private readonly overlay = viewChild(CdkConnectedOverlay);
|
||||
private readonly input = viewChild<ElementRef<HTMLInputElement>>('input');
|
||||
protected readonly optionTemplate = contentChild(AppAutocompleteOptionTemplateDirective);
|
||||
|
||||
protected readonly resolvedInputId = computed(() => this.inputId() || this.fieldContext?.controlId() || null);
|
||||
protected readonly resolvedDescribedBy = computed(
|
||||
@@ -62,15 +60,12 @@ export abstract class AppAutocompleteBaseDirective {
|
||||
);
|
||||
protected readonly showInvalid = computed(() => this.invalid() && (this.fieldContext?.validationVisible() ?? true));
|
||||
protected readonly isUnavailable = computed(() => this.disabled() || this.readonly());
|
||||
|
||||
protected readonly overlayPositions = connectedOverlayPositions;
|
||||
protected readonly overlayScrollStrategy = connectedOverlayScrollStrategy(this.overlayService);
|
||||
protected readonly normalizedSuggestions = computed<readonly AppAutocompleteOption[]>(() =>
|
||||
this.suggestions().map(toAutocompleteOption),
|
||||
);
|
||||
protected readonly selectedTagSize = computed<TagSize>(() => (this.size() === 'sm' ? 'sm' : 'md'));
|
||||
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';
|
||||
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(() =>
|
||||
autocompleteBoxVariants({ size: this.size(), disabled: this.disabled(), invalid: this.showInvalid() }),
|
||||
@@ -82,8 +77,13 @@ export abstract class AppAutocompleteBaseDirective {
|
||||
input.focus();
|
||||
}
|
||||
|
||||
protected onOverlayAttach(): void {
|
||||
refreshConnectedOverlayPosition(this.overlay());
|
||||
protected onInputFocus(): void {
|
||||
if (this.isUnavailable()) return;
|
||||
this.opened.emit();
|
||||
}
|
||||
|
||||
protected closePopup(): void {
|
||||
this.combobox()?.close();
|
||||
}
|
||||
|
||||
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 { Combobox, ComboboxInput, ComboboxPopupContainer } from '@angular/aria/combobox';
|
||||
import { Listbox, Option } from '@angular/aria/listbox';
|
||||
import { OverlayModule } from '@angular/cdk/overlay';
|
||||
import { TranslocoPipe } from '@jsverse/transloco';
|
||||
import { Combobox, ComboboxInput } from '@angular/aria/combobox';
|
||||
import { LucideLoaderCircle } from '@lucide/angular';
|
||||
|
||||
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({
|
||||
selector: 'app-autocomplete',
|
||||
standalone: true,
|
||||
imports: [
|
||||
OverlayModule,
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxPopupContainer,
|
||||
Listbox,
|
||||
Option,
|
||||
TranslocoPipe,
|
||||
LucideLoaderCircle,
|
||||
],
|
||||
imports: [Combobox, ComboboxInput, LucideLoaderCircle, AppAutocompletePopupComponent, AppAutocompleteSelectedTagsComponent],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
@@ -35,6 +28,14 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
|
||||
#origin
|
||||
[class]="boxClass()"
|
||||
(pointerdown)="focusInputOnPointerdown($event, input)">
|
||||
@if (selectedTags().length) {
|
||||
<app-autocomplete-selected-tags
|
||||
[tags]="selectedTags()"
|
||||
[size]="selectedTagSize()"
|
||||
[removable]="!isUnavailable()"
|
||||
[removeTagLabel]="removeTagLabel()"
|
||||
(remove)="clearSelectedTag(input)" />
|
||||
}
|
||||
<input
|
||||
ngComboboxInput
|
||||
#input
|
||||
@@ -44,87 +45,127 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
|
||||
[(value)]="query"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[placeholder]="placeholder()"
|
||||
[placeholder]="placeholderText()"
|
||||
[attr.aria-label]="ariaLabel() || 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-describedby]="resolvedDescribedBy()"
|
||||
[disabled]="disabled()"
|
||||
[required]="required()"
|
||||
[readonly]="readonly()"
|
||||
[readonly]="inputReadonly()"
|
||||
(input)="onType(input.value)"
|
||||
(focus)="onInputFocus()"
|
||||
(keydown.enter)="onEnter($event)"
|
||||
(blur)="onInputBlur()"
|
||||
[class]="innerInputClass" />
|
||||
@if (pending()) {
|
||||
<svg lucideLoaderCircle class="size-4 shrink-0 animate-spin text-text-muted" aria-hidden="true"></svg>
|
||||
}
|
||||
<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>
|
||||
|
||||
<ng-template ngComboboxPopupContainer>
|
||||
<ng-template
|
||||
[cdkConnectedOverlay]="{
|
||||
origin,
|
||||
usePopover: 'inline',
|
||||
matchWidth: true,
|
||||
positions: overlayPositions,
|
||||
viewportMargin: 8,
|
||||
push: true
|
||||
}"
|
||||
[cdkConnectedOverlayOpen]="cb.expanded()"
|
||||
[cdkConnectedOverlayScrollStrategy]="overlayScrollStrategy"
|
||||
(attach)="onOverlayAttach()">
|
||||
<div [class]="surfaceClass">
|
||||
<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>
|
||||
<app-autocomplete-popup
|
||||
[origin]="origin"
|
||||
[open]="cb.expanded()"
|
||||
[disabled]="disabled()"
|
||||
[readonly]="readonly()"
|
||||
[pending]="pending()"
|
||||
[loadingMore]="loadingMore()"
|
||||
[hasMore]="hasMore()"
|
||||
[errored]="errored()"
|
||||
[suggestions]="normalizedSuggestions()"
|
||||
[emptyMessage]="emptyMessage()"
|
||||
[optionTemplate]="optionTemplate()?.template ?? null"
|
||||
(optionSelected)="selectOption($event)"
|
||||
(loadMore)="loadMore.emit()" />
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppAutocompleteComponent extends AppAutocompleteBaseDirective implements FormValueControl<string> {
|
||||
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 {
|
||||
if (this.isUnavailable()) return;
|
||||
if (this.allowCustom() || !text.trim()) this.value.set(text);
|
||||
if (this.isUnavailable() || this.showSelectedTag()) return;
|
||||
if (this.selectedDisplay() !== 'tag' && (this.allowCustom() || !text.trim())) this.value.set(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 {
|
||||
this.touched.set(true);
|
||||
|
||||
if (this.allowCustom()) return;
|
||||
|
||||
queueMicrotask(() => {
|
||||
if (!this.allowCustom()) this.query.set(this.value());
|
||||
if (!this.allowCustom()) this.query.set(this.selectedLabel());
|
||||
});
|
||||
}
|
||||
|
||||
protected onSelect(values: readonly string[]): void {
|
||||
if (this.isUnavailable() || !values.length) return;
|
||||
const picked = values[values.length - 1];
|
||||
this.value.set(picked);
|
||||
this.query.set(picked);
|
||||
protected selectOption(option: AppAutocompleteOption): void {
|
||||
if (this.isUnavailable()) return;
|
||||
this.committedOption.set(option);
|
||||
this.value.set(option.value);
|
||||
this.query.set(this.selectedDisplay() === 'tag' ? '' : option.label);
|
||||
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,
|
||||
model,
|
||||
viewChild,
|
||||
viewChildren,
|
||||
} from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
import { Combobox, ComboboxInput, ComboboxPopupContainer } from '@angular/aria/combobox';
|
||||
import { Listbox, Option } from '@angular/aria/listbox';
|
||||
import { OverlayModule } from '@angular/cdk/overlay';
|
||||
import { TranslocoPipe } from '@jsverse/transloco';
|
||||
import { Combobox, ComboboxInput } from '@angular/aria/combobox';
|
||||
import { LucideLoaderCircle } from '@lucide/angular';
|
||||
|
||||
import { AppTagComponent } from '../tag/app-tag.component';
|
||||
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({
|
||||
selector: 'app-multi-autocomplete',
|
||||
standalone: true,
|
||||
imports: [
|
||||
OverlayModule,
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxPopupContainer,
|
||||
Listbox,
|
||||
Option,
|
||||
AppTagComponent,
|
||||
TranslocoPipe,
|
||||
LucideLoaderCircle,
|
||||
],
|
||||
imports: [Combobox, ComboboxInput, LucideLoaderCircle, AppAutocompletePopupComponent, AppAutocompleteSelectedTagsComponent],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
@@ -46,13 +34,13 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
|
||||
#origin
|
||||
[class]="boxClass()"
|
||||
(pointerdown)="focusInputOnPointerdown($event, input)">
|
||||
@for (tag of value(); track tag) {
|
||||
<app-tag
|
||||
size="sm"
|
||||
@if (selectedTags().length) {
|
||||
<app-autocomplete-selected-tags
|
||||
[tags]="selectedTags()"
|
||||
[size]="selectedTagSize()"
|
||||
[removable]="!isUnavailable()"
|
||||
[label]="tag"
|
||||
[removeLabel]="removeTagLabel() || ('shared.ui.autocomplete.removeTag' | transloco: { tag })"
|
||||
(remove)="removeChip(tag)" />
|
||||
[removeTagLabel]="removeTagLabel()"
|
||||
(remove)="removeChip($event)" />
|
||||
}
|
||||
<input
|
||||
ngComboboxInput
|
||||
@@ -73,49 +61,33 @@ import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive'
|
||||
[required]="required()"
|
||||
[readonly]="readonly()"
|
||||
(input)="onType(input.value)"
|
||||
(focus)="onInputFocus()"
|
||||
(keydown.enter)="onEnter($event)"
|
||||
(keydown.backspace)="onBackspace()"
|
||||
(blur)="touched.set(true)"
|
||||
[class]="innerInputClass" />
|
||||
@if (pending()) {
|
||||
<svg lucideLoaderCircle class="size-4 shrink-0 animate-spin text-text-muted" aria-hidden="true"></svg>
|
||||
}
|
||||
<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>
|
||||
|
||||
<ng-template ngComboboxPopupContainer>
|
||||
<ng-template
|
||||
[cdkConnectedOverlay]="{
|
||||
origin,
|
||||
usePopover: 'inline',
|
||||
matchWidth: true,
|
||||
positions: overlayPositions,
|
||||
viewportMargin: 8,
|
||||
push: true
|
||||
}"
|
||||
[cdkConnectedOverlayOpen]="cb.expanded()"
|
||||
[cdkConnectedOverlayScrollStrategy]="overlayScrollStrategy"
|
||||
(attach)="onOverlayAttach()">
|
||||
<div [class]="surfaceClass">
|
||||
<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>
|
||||
<app-autocomplete-popup
|
||||
[origin]="origin"
|
||||
[open]="cb.expanded()"
|
||||
[disabled]="disabled()"
|
||||
[readonly]="readonly()"
|
||||
[pending]="pending()"
|
||||
[loadingMore]="loadingMore()"
|
||||
[hasMore]="hasMore()"
|
||||
[errored]="errored()"
|
||||
[suggestions]="normalizedSuggestions()"
|
||||
[emptyMessage]="emptyMessage()"
|
||||
[optionTemplate]="optionTemplate()?.template ?? null"
|
||||
(optionSelected)="selectOption($event)"
|
||||
(loadMore)="loadMore.emit()" />
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
@@ -124,14 +96,20 @@ export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective
|
||||
|
||||
readonly removeTagLabel = input('');
|
||||
|
||||
private readonly listbox = viewChild<Listbox<string>>(Listbox);
|
||||
protected readonly optionRefs = viewChildren(Option);
|
||||
private readonly popup = viewChild(AppAutocompletePopupComponent);
|
||||
private readonly chipLabels = new Map<string, string>();
|
||||
|
||||
protected readonly query = linkedSignal<string[], string>({
|
||||
source: this.value,
|
||||
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 onType(text: string): void {
|
||||
@@ -143,12 +121,19 @@ export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective
|
||||
if (this.isUnavailable()) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const active = this.optionRefs().find((option) => option.active());
|
||||
const active = this.popup()?.activeOption();
|
||||
if (active) {
|
||||
this.addChip(String(active.value()), true);
|
||||
this.addChip(active);
|
||||
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 {
|
||||
@@ -159,35 +144,33 @@ export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective
|
||||
this.touched.set(true);
|
||||
}
|
||||
|
||||
protected onSelect(values: readonly string[]): void {
|
||||
if (this.isUnavailable() || !values.length) return;
|
||||
this.addChip(values[values.length - 1], true);
|
||||
protected selectOption(option: AppAutocompleteOption): void {
|
||||
this.addChip(option);
|
||||
}
|
||||
|
||||
protected removeChip(tag: string): void {
|
||||
this.value.set(this.value().filter((existing) => existing !== tag));
|
||||
protected removeChip(value: string): void {
|
||||
this.chipLabels.delete(value);
|
||||
this.value.set(this.value().filter((existing) => existing !== value));
|
||||
this.touched.set(true);
|
||||
}
|
||||
|
||||
private addChip(text: string, fromSuggestion = false): void {
|
||||
private addChip(option: AppAutocompleteOption): void {
|
||||
if (this.isUnavailable()) return;
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) return;
|
||||
if (!fromSuggestion && !this.allowCustom() && !this.suggestions().includes(trimmed)) return;
|
||||
const current = this.value();
|
||||
if (current.includes(trimmed)) {
|
||||
if (current.includes(option.value)) {
|
||||
this.clearTagInput();
|
||||
return;
|
||||
}
|
||||
this.value.set([...current, trimmed]);
|
||||
this.chipLabels.set(option.value, option.label);
|
||||
this.value.set([...current, option.value]);
|
||||
this.clearTagInput();
|
||||
this.touched.set(true);
|
||||
this.complete.emit('');
|
||||
}
|
||||
|
||||
private clearTagInput(): void {
|
||||
this.combobox()?.close();
|
||||
this.listbox()?.values.set([]);
|
||||
this.closePopup();
|
||||
this.popup()?.clearSelection();
|
||||
this.query.set('');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,8 +159,7 @@
|
||||
},
|
||||
"ui": {
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"previousMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
"ui": {
|
||||
"autocomplete": {
|
||||
"noResults": "No results",
|
||||
"removeTag": "Remove {{ tag }}"
|
||||
"loadFailed": "Couldn't load results"
|
||||
},
|
||||
"datePicker": {
|
||||
"previousMonth": "Previous month",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -159,8 +159,7 @@
|
||||
},
|
||||
"ui": {
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"previousMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
@@ -192,8 +192,7 @@
|
||||
"loading": ""
|
||||
},
|
||||
"autocomplete": {
|
||||
"noResults": "",
|
||||
"removeTag": ""
|
||||
"noResults": ""
|
||||
},
|
||||
"datePicker": {
|
||||
"nextMonth": "",
|
||||
|
||||
Reference in New Issue
Block a user