import { booleanAttribute, computed, contentChild, Directive, inject, input, linkedSignal, output, type ElementRef, type Signal, 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 { overlayListEmptyItemClass, overlayListOptionClass, overlayListRootClass, overlayListSectionLabelClass, overlayListSeparatorClass, overlayListSurfaceClass, } from '../overlay-list.styles'; import { appSelectLabelVariants, appSelectTriggerVariants, type AppSelectSize, type AppSelectVariant, } from './app-select.variants'; import { AppSelectOptionTemplateDirective } from './app-select.templates'; import { type SelectCompareWith, type SelectOption, type SelectOptionGroup } from './app-select.options'; const defaultCompareWith = (optionValue: T, selectedValue: T): boolean => Object.is(optionValue, selectedValue); const UNGROUPED_GROUP_TRACK_KEY = Symbol('app-select-ungrouped'); interface RenderedSelectOptionGroup extends SelectOptionGroup { readonly trackKey: unknown; } @Directive() export abstract class AppSelectBaseDirective { readonly disabled = input(false, { transform: booleanAttribute }); readonly required = input(false, { transform: booleanAttribute }); readonly invalid = input(false, { transform: booleanAttribute }); readonly pending = input(false, { transform: booleanAttribute }); readonly readonly = input(false, { transform: booleanAttribute }); readonly touched = input(false, { transform: booleanAttribute }); readonly touch = output(); readonly name = input(''); readonly size = input('md'); readonly variant = input('outlined'); readonly options = input[]>([]); readonly groups = input[]>([]); readonly filter = input(false, { transform: booleanAttribute }); readonly filterPlaceholder = input(''); readonly showClear = input(false, { transform: booleanAttribute }); readonly placeholder = input(''); readonly emptyMessage = input(''); readonly inputId = input(''); readonly ariaLabel = input(''); readonly ariaLabelledBy = input(''); readonly ariaDescribedBy = input(''); readonly styleClass = input(''); readonly compareWith = input>(defaultCompareWith); readonly cleared = output(); protected abstract readonly hasSelection: Signal; protected abstract readonly triggerLabel: Signal; protected abstract readonly listboxValues: Signal; protected abstract onValuesChange(values: readonly T[]): void; protected abstract clearValue(): void; protected abstract isSelected(option: SelectOption): boolean; private readonly fieldContext = inject(APP_FIELD, { optional: true }); private readonly overlayService = inject(Overlay); private readonly combobox = viewChild(Combobox); private readonly overlay = viewChild(CdkConnectedOverlay); private readonly controlRoot = viewChild>('controlRoot'); protected readonly optionTemplate = contentChild(AppSelectOptionTemplateDirective); protected readonly resolvedInputId = computed(() => this.inputId() || this.fieldContext?.controlId() || null); protected readonly resolvedDescribedBy = computed( () => this.ariaDescribedBy() || this.fieldContext?.describedById() || null, ); protected readonly showInvalid = computed(() => this.invalid() && (this.fieldContext?.validationVisible() ?? true)); protected readonly isUnavailable = computed(() => this.disabled() || this.readonly()); protected readonly surfaceClass = cn( overlayListSurfaceClass, connectedOverlayPanelClass, 'box-border flex w-full flex-col overflow-hidden p-0', ); private readonly triggerZoneWidthClass = computed(() => this.variant() !== 'bare' ? 'w-9 pointer-coarse:w-11' : 'w-7 pointer-coarse:w-10', ); protected readonly filterRowClass = 'flex h-9 items-center border-b border-border pl-3 pr-2 text-text-muted pointer-coarse:h-11'; protected readonly filterInputClass = 'h-full min-w-0 flex-1 border-0 bg-transparent px-0 pr-2 text-sm text-text-strong outline-hidden ' + 'placeholder:text-text-muted focus:outline-hidden pointer-coarse:text-base'; protected readonly clearButtonClass = computed(() => cn( 'relative z-20 flex h-full shrink-0 items-center justify-center border-0 bg-transparent p-0 text-text-muted', 'touch-manipulation transition-colors hover:text-text-strong', this.triggerZoneWidthClass(), ), ); protected readonly indicatorClass = computed(() => cn('flex h-full shrink-0 items-center justify-center text-text-muted', this.triggerZoneWidthClass()), ); protected readonly overlayPositions = connectedOverlayPositions; protected readonly overlayScrollStrategy = connectedOverlayScrollStrategy(this.overlayService); protected readonly listClass = computed(() => cn( overlayListRootClass, 'overflow-y-auto overscroll-contain p-1', this.filter() ? 'max-h-[12.75rem]' : 'max-h-60', ), ); protected readonly sectionClass = cn(overlayListSectionLabelClass, 'text-text-muted'); protected readonly separatorClass = overlayListSeparatorClass; protected readonly optionClass = overlayListOptionClass; protected readonly emptyClass = overlayListEmptyItemClass; protected readonly triggerClass = computed(() => cn( appSelectTriggerVariants({ size: this.size(), variant: this.variant(), invalid: this.showInvalid(), disabled: this.disabled(), }), this.styleClass(), ), ); protected readonly labelClass = computed(() => appSelectLabelVariants({ size: this.size(), variant: this.variant() })); protected readonly grouped = computed(() => this.groups().length > 0); protected readonly renderedGroups = computed[]>(() => { if (!this.grouped()) { const options = this.options().filter((option) => this.matchesFilter(option)); return options.length ? [{ label: '', options, trackKey: UNGROUPED_GROUP_TRACK_KEY }] : []; } const out: RenderedSelectOptionGroup[] = []; for (const group of this.groups()) { const options = group.options.filter((option) => this.matchesFilter(option)); if (options.length) out.push({ label: group.label, options, trackKey: group }); } return out; }); protected readonly flatOptions = computed[]>(() => this.grouped() ? this.groups().flatMap((group) => group.options) : this.options(), ); protected readonly filterText = linkedSignal({ source: () => this.combobox()?.expanded() ?? false, computation: (expanded, previous) => (expanded ? (previous?.value ?? '') : ''), }); protected closePopup(): void { this.combobox()?.expanded.set(false); } protected onExpandedChange(expanded: boolean): void { if (!expanded) this.filterText.set(''); } protected markTouchedWhenFocusLeavesControl(event: FocusEvent): void { if (this.isUnavailable() || this.focusRemainsInControl(event.relatedTarget)) return; this.touch.emit(); } protected clear(event: MouseEvent): void { event.stopPropagation(); if (this.isUnavailable()) return; this.clearValue(); this.cleared.emit(); } private matchesFilter(option: SelectOption): boolean { if (!this.filter()) return true; const query = this.filterText().trim().toLowerCase(); if (!query) return true; return option.label.toLowerCase().includes(query); } private focusRemainsInControl(target: EventTarget | null): boolean { if (!(target instanceof Node)) return false; const controlRoot = this.controlRoot()?.nativeElement; const overlayElement = this.overlay()?.overlayRef?.overlayElement; return controlRoot?.contains(target) === true || overlayElement?.contains(target) === true; } protected valuesMatch(optionValue: T, selectedValue: T): boolean { return this.compareWith()(optionValue, selectedValue); } protected findOptionForValue(value: T): SelectOption | null { return this.flatOptions().find((option) => this.valuesMatch(option.value, value)) ?? null; } protected findVisibleOptionForValue(value: T): SelectOption | null { for (const group of this.renderedGroups()) { const option = group.options.find((candidate) => this.valuesMatch(candidate.value, value)); if (option) return option; } return null; } protected isVisibleValue(value: T): boolean { return this.findVisibleOptionForValue(value) != null; } protected visibleOptionValuesForSelected(values: readonly T[]): T[] { return this.renderedGroups() .flatMap((group) => group.options) .filter((option) => values.some((value) => this.valuesMatch(option.value, value))) .map((option) => option.value); } protected onOverlayAttach(): void { refreshConnectedOverlayPosition(this.overlay()); } focus(options?: FocusOptions): void { this.combobox()?.element.focus(options); } }