refactor(ui): new component library (#1740)
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
contentChild,
|
||||
input,
|
||||
model,
|
||||
numberAttribute,
|
||||
} from '@angular/core';
|
||||
import { AccordionContent, AccordionGroup, AccordionPanel, AccordionTrigger } from '@angular/aria/accordion';
|
||||
|
||||
import {
|
||||
AppAccordionActionsDirective,
|
||||
AppAccordionContentDirective,
|
||||
AppAccordionHeaderDirective,
|
||||
} from './app-accordion.directives';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-accordion',
|
||||
standalone: true,
|
||||
imports: [NgTemplateOutlet, AccordionGroup, AccordionPanel, AccordionTrigger, AccordionContent],
|
||||
host: { class: 'block' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<div ngAccordionGroup [multiExpandable]="multiple()" [disabled]="disabled()" [class]="rootClass">
|
||||
@for (item of items(); track $index; let i = $index) {
|
||||
<div>
|
||||
<div [class]="headerRowClass">
|
||||
<div role="heading" [attr.aria-level]="headingLevel()" class="min-w-0 flex-1">
|
||||
<button
|
||||
type="button"
|
||||
ngAccordionTrigger
|
||||
#trigger="ngAccordionTrigger"
|
||||
[panel]="panelRef"
|
||||
[expanded]="isOpen(i)"
|
||||
(expandedChange)="onToggle(i, $event)"
|
||||
[class]="triggerClass">
|
||||
<span [class]="actionsTemplate() ? labelWithActionsClass : labelClass">
|
||||
@if (headerTemplate(); as tpl) {
|
||||
<ng-container
|
||||
[ngTemplateOutlet]="tpl.template"
|
||||
[ngTemplateOutletContext]="{ $implicit: item, index: i, expanded: trigger.expanded() }" />
|
||||
} @else {
|
||||
{{ item }}
|
||||
}
|
||||
</span>
|
||||
<i [class]="chevronClass" [class.rotate-180]="trigger.expanded()" aria-hidden="true"></i>
|
||||
</button>
|
||||
</div>
|
||||
@if (actionsTemplate(); as tpl) {
|
||||
<div [class]="actionsOverlayClass">
|
||||
<div [class]="actionsClass" tabindex="-1" (keydown)="$event.stopPropagation()">
|
||||
<ng-container
|
||||
[ngTemplateOutlet]="tpl.template"
|
||||
[ngTemplateOutletContext]="{ $implicit: item, index: i, expanded: trigger.expanded() }" />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div
|
||||
ngAccordionPanel
|
||||
#panelRef="ngAccordionPanel"
|
||||
[preserveContent]="preserveContent()"
|
||||
class="grid transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none"
|
||||
[style.grid-template-rows]="trigger.expanded() ? '1fr' : '0fr'">
|
||||
<div class="overflow-hidden">
|
||||
<ng-template ngAccordionContent>
|
||||
<div [class]="contentClass">
|
||||
@if (contentTemplate(); as tpl) {
|
||||
<ng-container [ngTemplateOutlet]="tpl.template" [ngTemplateOutletContext]="{ $implicit: item, index: i }" />
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppAccordionComponent {
|
||||
readonly items = input<readonly unknown[]>([]);
|
||||
readonly multiple = input(false, { transform: booleanAttribute });
|
||||
readonly disabled = input(false, { transform: booleanAttribute });
|
||||
readonly preserveContent = input(true, { transform: booleanAttribute });
|
||||
readonly headingLevel = input(3, { transform: numberAttribute });
|
||||
readonly value = model<number | number[] | null>(null);
|
||||
|
||||
protected readonly headerTemplate = contentChild(AppAccordionHeaderDirective);
|
||||
protected readonly contentTemplate = contentChild(AppAccordionContentDirective);
|
||||
protected readonly actionsTemplate = contentChild(AppAccordionActionsDirective);
|
||||
|
||||
protected readonly rootClass =
|
||||
'divide-y divide-border overflow-hidden rounded-md border ' +
|
||||
`${neutralControlBorderClass} bg-card shadow-control`;
|
||||
protected readonly headerRowClass = 'relative flex items-stretch';
|
||||
protected readonly triggerClass =
|
||||
'relative flex h-full w-full cursor-pointer select-none items-center px-3 py-2.5 text-sm font-medium text-text-strong outline-hidden ' +
|
||||
'transition-colors hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary ' +
|
||||
'aria-disabled:cursor-default aria-disabled:opacity-50';
|
||||
protected readonly labelClass = 'min-w-0 flex-1 pr-7 text-left';
|
||||
protected readonly labelWithActionsClass = 'min-w-0 flex-1 pr-24 text-left';
|
||||
protected readonly chevronClass =
|
||||
'pi pi-chevron-down pointer-events-none absolute right-3 top-1/2 shrink-0 -translate-y-1/2 text-xs text-text-muted transition-transform duration-200';
|
||||
protected readonly actionsOverlayClass = 'pointer-events-none absolute inset-y-0 right-8 flex items-center';
|
||||
protected readonly actionsClass = 'pointer-events-auto flex shrink-0 items-center gap-1';
|
||||
protected readonly contentClass = 'surface-page border-t border-border px-3 py-3 text-sm text-text';
|
||||
|
||||
protected isOpen(index: number): boolean {
|
||||
const value = this.value();
|
||||
return this.multiple() ? Array.isArray(value) && value.includes(index) : value === index;
|
||||
}
|
||||
|
||||
protected onToggle(index: number, expanded: boolean): void {
|
||||
if (this.multiple()) {
|
||||
const value = this.value();
|
||||
const current = Array.isArray(value) ? value : [];
|
||||
this.value.set(expanded ? [...current, index] : current.filter((open) => open !== index));
|
||||
return;
|
||||
}
|
||||
if (expanded) {
|
||||
this.value.set(index);
|
||||
} else if (this.value() === index) {
|
||||
this.value.set(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Directive, inject, TemplateRef } from '@angular/core';
|
||||
|
||||
@Directive({ selector: 'ng-template[appAccordionHeader]', standalone: true })
|
||||
export class AppAccordionHeaderDirective {
|
||||
readonly template = inject(TemplateRef);
|
||||
}
|
||||
|
||||
@Directive({ selector: 'ng-template[appAccordionContent]', standalone: true })
|
||||
export class AppAccordionContentDirective {
|
||||
readonly template = inject(TemplateRef);
|
||||
}
|
||||
|
||||
@Directive({ selector: 'ng-template[appAccordionActions]', standalone: true })
|
||||
export class AppAccordionActionsDirective {
|
||||
readonly template = inject(TemplateRef);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
computed,
|
||||
Directive,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
type ElementRef,
|
||||
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 {
|
||||
overlayListEmptyItemClass,
|
||||
overlayListOptionClass,
|
||||
overlayListRootClass,
|
||||
overlayListSurfaceClass,
|
||||
} from '../overlay-list.styles';
|
||||
import { autocompleteBoxVariants } from './app-autocomplete.variants';
|
||||
|
||||
@Directive()
|
||||
export abstract class AppAutocompleteBaseDirective {
|
||||
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 = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly allowCustom = input(true, { transform: booleanAttribute });
|
||||
readonly suggestions = input<readonly string[]>([]);
|
||||
readonly size = input<AppInputSize>('md');
|
||||
readonly placeholder = input('');
|
||||
readonly emptyMessage = input('');
|
||||
readonly inputId = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
|
||||
readonly complete = output<string>();
|
||||
|
||||
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 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 overlayPositions = connectedOverlayPositions;
|
||||
protected readonly overlayScrollStrategy = connectedOverlayScrollStrategy(this.overlayService);
|
||||
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 p-1');
|
||||
protected readonly optionClass = overlayListOptionClass;
|
||||
protected readonly emptyClass = overlayListEmptyItemClass;
|
||||
|
||||
protected readonly boxClass = computed(() =>
|
||||
autocompleteBoxVariants({ size: this.size(), disabled: this.disabled(), invalid: this.showInvalid() }),
|
||||
);
|
||||
|
||||
protected focusInputOnPointerdown(event: PointerEvent, input: HTMLInputElement): void {
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
if (target?.closest('button')) return;
|
||||
input.focus();
|
||||
}
|
||||
|
||||
protected onOverlayAttach(): void {
|
||||
refreshConnectedOverlayPosition(this.overlay());
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.input()?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { ChangeDetectionStrategy, Component, linkedSignal, model } 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 { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive';
|
||||
|
||||
@Component({
|
||||
selector: 'app-autocomplete',
|
||||
standalone: true,
|
||||
imports: [
|
||||
OverlayModule,
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxPopupContainer,
|
||||
Listbox,
|
||||
Option,
|
||||
TranslocoPipe,
|
||||
],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<div
|
||||
ngCombobox
|
||||
#cb="ngCombobox"
|
||||
filterMode="manual"
|
||||
[readonly]="readonly()"
|
||||
[disabled]="disabled()"
|
||||
class="relative block w-full">
|
||||
<div
|
||||
#origin
|
||||
[class]="boxClass()"
|
||||
(pointerdown)="focusInputOnPointerdown($event, input)">
|
||||
<input
|
||||
ngComboboxInput
|
||||
#input
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
[(value)]="query"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[placeholder]="placeholder()"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[disabled]="disabled()"
|
||||
[required]="required()"
|
||||
[readonly]="readonly()"
|
||||
(input)="onType(input.value)"
|
||||
(blur)="onInputBlur()"
|
||||
[class]="innerInputClass" />
|
||||
@if (pending()) {
|
||||
<i class="pi pi-spinner pi-spin shrink-0 text-xs text-text-muted" aria-hidden="true"></i>
|
||||
}
|
||||
</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>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppAutocompleteComponent extends AppAutocompleteBaseDirective implements FormValueControl<string> {
|
||||
readonly value = model('');
|
||||
|
||||
protected readonly query = linkedSignal(() => this.value());
|
||||
|
||||
protected onType(text: string): void {
|
||||
if (this.isUnavailable()) return;
|
||||
if (this.allowCustom() || !text.trim()) this.value.set(text);
|
||||
this.complete.emit(text);
|
||||
}
|
||||
|
||||
protected onInputBlur(): void {
|
||||
this.touched.set(true);
|
||||
|
||||
if (this.allowCustom()) return;
|
||||
|
||||
queueMicrotask(() => {
|
||||
if (!this.allowCustom()) this.query.set(this.value());
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
this.touched.set(true);
|
||||
this.combobox()?.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export const autocompleteBoxVariants = cva(
|
||||
`flex w-full flex-wrap items-center gap-1.5 rounded-md border ${neutralControlBorderClass} bg-card text-text-strong shadow-control outline-hidden ` +
|
||||
'transition-[background-color,border-color,color] duration-150 ' +
|
||||
'focus-within:border-primary/60 focus-within:outline-1 focus-within:outline-offset-0 focus-within:outline-primary/60',
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'min-h-8 px-3 py-1 text-xs',
|
||||
md: 'min-h-9 px-3 py-1 text-sm',
|
||||
lg: 'min-h-10 px-4 py-1.5 text-sm',
|
||||
},
|
||||
disabled: { true: 'pointer-events-none opacity-50', false: '' },
|
||||
invalid: {
|
||||
true: 'border-danger focus-within:border-danger focus-within:outline-danger',
|
||||
false: '',
|
||||
},
|
||||
},
|
||||
defaultVariants: { size: 'md', disabled: false, invalid: false },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,191 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
input,
|
||||
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 { AppTagComponent } from '../tag/app-tag.component';
|
||||
import { AppAutocompleteBaseDirective } from './app-autocomplete-base.directive';
|
||||
|
||||
@Component({
|
||||
selector: 'app-multi-autocomplete',
|
||||
standalone: true,
|
||||
imports: [
|
||||
OverlayModule,
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxPopupContainer,
|
||||
Listbox,
|
||||
Option,
|
||||
AppTagComponent,
|
||||
TranslocoPipe,
|
||||
],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<div
|
||||
ngCombobox
|
||||
#cb="ngCombobox"
|
||||
filterMode="manual"
|
||||
[readonly]="readonly()"
|
||||
[disabled]="disabled()"
|
||||
class="relative block w-full">
|
||||
<div
|
||||
#origin
|
||||
[class]="boxClass()"
|
||||
(pointerdown)="focusInputOnPointerdown($event, input)">
|
||||
@for (tag of value(); track tag) {
|
||||
<app-tag
|
||||
size="sm"
|
||||
[removable]="!isUnavailable()"
|
||||
[label]="tag"
|
||||
[removeLabel]="removeTagLabel() || ('shared.ui.autocomplete.removeTag' | transloco: { tag })"
|
||||
(remove)="removeChip(tag)" />
|
||||
}
|
||||
<input
|
||||
ngComboboxInput
|
||||
#input
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
[(value)]="query"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[placeholder]="placeholderText()"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[disabled]="disabled()"
|
||||
[required]="required()"
|
||||
[readonly]="readonly()"
|
||||
(input)="onType(input.value)"
|
||||
(keydown.enter)="onEnter($event)"
|
||||
(keydown.backspace)="onBackspace()"
|
||||
(blur)="touched.set(true)"
|
||||
[class]="innerInputClass" />
|
||||
@if (pending()) {
|
||||
<i class="pi pi-spinner pi-spin shrink-0 text-xs text-text-muted" aria-hidden="true"></i>
|
||||
}
|
||||
</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>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective implements FormValueControl<string[]> {
|
||||
readonly value = model<string[]>([]);
|
||||
|
||||
readonly removeTagLabel = input('');
|
||||
|
||||
private readonly listbox = viewChild<Listbox<string>>(Listbox);
|
||||
protected readonly optionRefs = viewChildren(Option);
|
||||
|
||||
protected readonly query = linkedSignal<string[], string>({
|
||||
source: this.value,
|
||||
computation: () => '',
|
||||
});
|
||||
|
||||
protected readonly placeholderText = computed(() => (this.value().length ? '' : this.placeholder()));
|
||||
|
||||
protected onType(text: string): void {
|
||||
if (this.isUnavailable()) return;
|
||||
this.complete.emit(text);
|
||||
}
|
||||
|
||||
protected onEnter(event: Event): void {
|
||||
if (this.isUnavailable()) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const active = this.optionRefs().find((option) => option.active());
|
||||
if (active) {
|
||||
this.addChip(String(active.value()), true);
|
||||
return;
|
||||
}
|
||||
this.addChip(this.query());
|
||||
}
|
||||
|
||||
protected onBackspace(): void {
|
||||
if (this.isUnavailable() || this.query()) return;
|
||||
const current = this.value();
|
||||
if (!current.length) return;
|
||||
this.value.set(current.slice(0, -1));
|
||||
this.touched.set(true);
|
||||
}
|
||||
|
||||
protected onSelect(values: readonly string[]): void {
|
||||
if (this.isUnavailable() || !values.length) return;
|
||||
this.addChip(values[values.length - 1], true);
|
||||
}
|
||||
|
||||
protected removeChip(tag: string): void {
|
||||
this.value.set(this.value().filter((existing) => existing !== tag));
|
||||
this.touched.set(true);
|
||||
}
|
||||
|
||||
private addChip(text: string, fromSuggestion = false): 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)) {
|
||||
this.clearTagInput();
|
||||
return;
|
||||
}
|
||||
this.value.set([...current, trimmed]);
|
||||
this.clearTagInput();
|
||||
this.touched.set(true);
|
||||
this.complete.emit('');
|
||||
}
|
||||
|
||||
private clearTagInput(): void {
|
||||
this.combobox()?.close();
|
||||
this.listbox()?.values.set([]);
|
||||
this.query.set('');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { booleanAttribute, ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
||||
import { cn } from '../cn';
|
||||
import { SPINNER_RING } from '../spinner/app-spinner.variants';
|
||||
import { buttonVariants, type ButtonSize, type ButtonTone, type ButtonVariant } from './app-button.variants';
|
||||
|
||||
@Component({
|
||||
selector: 'app-button',
|
||||
standalone: true,
|
||||
host: {
|
||||
class: 'inline-block align-middle',
|
||||
'[class.w-full]': 'fluid()',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<button
|
||||
[attr.id]="buttonId() || null"
|
||||
[class]="buttonClass()"
|
||||
[disabled]="disabled() || loading()"
|
||||
[type]="type()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.value]="value() ?? null"
|
||||
[attr.form]="form() || null"
|
||||
[attr.title]="title() || null"
|
||||
[attr.tabindex]="tabIndex()"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-busy]="loading() ? 'true' : null"
|
||||
[attr.aria-controls]="ariaControls() || null"
|
||||
[attr.aria-expanded]="ariaExpanded()"
|
||||
[attr.aria-haspopup]="ariaHasPopup()"
|
||||
[attr.aria-pressed]="ariaPressed()"
|
||||
(click)="clicked.emit($event)">
|
||||
@if (loading()) {
|
||||
<span [class]="loadingRingClass" aria-hidden="true"></span>
|
||||
} @else if (icon() && iconPos() === 'left') {
|
||||
<i [class]="iconClass()" aria-hidden="true"></i>
|
||||
}
|
||||
@if (label()) {
|
||||
<span class="leading-none">{{ label() }}</span>
|
||||
}
|
||||
<ng-content />
|
||||
@if (!loading() && icon() && iconPos() === 'right') {
|
||||
<i [class]="iconClass()" aria-hidden="true"></i>
|
||||
}
|
||||
</button>
|
||||
`,
|
||||
})
|
||||
export class AppButtonComponent {
|
||||
readonly tone = input<ButtonTone>('neutral');
|
||||
readonly variant = input<ButtonVariant>('soft');
|
||||
readonly size = input<ButtonSize>('md');
|
||||
readonly iconOnly = input(false, { transform: booleanAttribute });
|
||||
readonly rounded = input(false, { transform: booleanAttribute });
|
||||
readonly fluid = input(false, { transform: booleanAttribute });
|
||||
readonly styleClass = input('');
|
||||
readonly buttonId = input('');
|
||||
readonly name = input('');
|
||||
readonly value = input<string | number | null>(null);
|
||||
readonly form = input('');
|
||||
readonly title = input('');
|
||||
readonly tabIndex = input<number | null>(null);
|
||||
readonly label = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaControls = input('');
|
||||
readonly ariaExpanded = input<boolean | string | null>(null);
|
||||
readonly ariaHasPopup = input<boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog' | null>(null);
|
||||
readonly ariaPressed = input<boolean | 'false' | 'true' | 'mixed' | null>(null);
|
||||
readonly icon = input('');
|
||||
readonly iconPos = input<'left' | 'right'>('left');
|
||||
readonly loading = input(false, { transform: booleanAttribute });
|
||||
readonly disabled = input(false, { transform: booleanAttribute });
|
||||
readonly type = input<'button' | 'submit' | 'reset'>('button');
|
||||
|
||||
readonly clicked = output<MouseEvent>();
|
||||
|
||||
protected readonly buttonClass = computed(() =>
|
||||
cn(
|
||||
buttonVariants({
|
||||
tone: this.tone(),
|
||||
variant: this.variant(),
|
||||
size: this.size(),
|
||||
iconOnly: this.iconOnly(),
|
||||
rounded: this.rounded(),
|
||||
fluid: this.fluid(),
|
||||
}),
|
||||
this.styleClass(),
|
||||
),
|
||||
);
|
||||
protected readonly iconClass = computed(() => cn(this.icon(), 'shrink-0 m-0 leading-none'));
|
||||
protected readonly loadingRingClass = cn(SPINNER_RING, 'size-[1em] border-2 shrink-0');
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass, neutralSurfaceHoverClass } from '../control.styles';
|
||||
|
||||
export type ButtonTone = 'neutral' | 'primary' | 'danger';
|
||||
export type ButtonVariant = 'soft' | 'solid' | 'ghost';
|
||||
export type ButtonSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
export const buttonVariants = cva(
|
||||
'inline-flex shrink-0 cursor-pointer select-none items-center justify-center ' +
|
||||
'rounded-md border leading-none whitespace-nowrap font-medium ' +
|
||||
'transition-[background-color,border-color,color] duration-150 active:translate-y-px ' +
|
||||
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary ' +
|
||||
'disabled:pointer-events-none disabled:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
tone: { neutral: '', primary: '', danger: '' },
|
||||
variant: { soft: '', solid: '', ghost: '' },
|
||||
size: {
|
||||
sm: 'h-8 px-3 gap-1.5 text-xs',
|
||||
md: 'h-9 px-3 gap-2 text-sm',
|
||||
lg: 'h-10 px-4 gap-2 text-sm',
|
||||
},
|
||||
iconOnly: { true: '', false: '' },
|
||||
rounded: { true: 'rounded-full', false: '' },
|
||||
fluid: { true: 'w-full', false: '' },
|
||||
},
|
||||
compoundVariants: [
|
||||
{
|
||||
tone: 'neutral',
|
||||
variant: ['soft', 'solid'],
|
||||
class: `bg-card text-text-strong ${neutralControlBorderClass} shadow-control ${neutralSurfaceHoverClass} hover:border-text/15`,
|
||||
},
|
||||
{
|
||||
tone: 'primary',
|
||||
variant: 'soft',
|
||||
class:
|
||||
'bg-primary/10 text-primary-text border-primary/15 shadow-control hover:bg-primary/20 dark:hover:bg-primary/15 hover:border-primary/30 dark:border-primary/30 dark:hover:border-primary/45',
|
||||
},
|
||||
{
|
||||
tone: 'primary',
|
||||
variant: 'solid',
|
||||
class: 'bg-primary text-primary-contrast border-transparent font-semibold shadow-control hover:bg-primary-hover',
|
||||
},
|
||||
{
|
||||
tone: 'danger',
|
||||
variant: 'soft',
|
||||
class:
|
||||
'bg-danger/10 text-danger border-danger/15 shadow-control hover:bg-danger/20 dark:hover:bg-danger/15 hover:border-danger/30 dark:border-danger/30 dark:hover:border-danger/45',
|
||||
},
|
||||
{
|
||||
tone: 'danger',
|
||||
variant: 'solid',
|
||||
class: 'bg-danger text-white border-transparent font-semibold shadow-control hover:bg-danger-hover',
|
||||
},
|
||||
{
|
||||
tone: 'neutral',
|
||||
variant: 'ghost',
|
||||
class: `bg-transparent border-transparent text-text-secondary ${neutralSurfaceHoverClass} hover:text-text-strong`,
|
||||
},
|
||||
{ tone: 'primary', variant: 'ghost', class: 'bg-transparent border-transparent text-primary hover:bg-primary/10' },
|
||||
{ tone: 'danger', variant: 'ghost', class: 'bg-transparent border-transparent text-danger hover:bg-danger/10' },
|
||||
{ iconOnly: true, size: 'sm', class: 'w-8 px-0 gap-0' },
|
||||
{ iconOnly: true, size: 'md', class: 'w-9 px-0 gap-0' },
|
||||
{ iconOnly: true, size: 'lg', class: 'w-10 px-0 gap-0' },
|
||||
],
|
||||
defaultVariants: { tone: 'neutral', variant: 'soft', size: 'md', iconOnly: false, rounded: false, fluid: false },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,123 @@
|
||||
import {
|
||||
afterRenderEffect,
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
type ElementRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { type FormCheckboxControl } from '@angular/forms/signals';
|
||||
import { cn } from '../cn';
|
||||
import { invisibleControlInputClass } from '../control.styles';
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
import {
|
||||
appCheckboxBoxVariants,
|
||||
appCheckboxIndicatorVariants,
|
||||
appCheckboxRootVariants,
|
||||
type AppCheckboxSize,
|
||||
} from './app-checkbox.variants';
|
||||
|
||||
@Component({
|
||||
selector: 'app-checkbox',
|
||||
standalone: true,
|
||||
host: { class: 'inline-block align-middle' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<span [class]="rootClass()">
|
||||
<input
|
||||
#checkbox
|
||||
type="checkbox"
|
||||
[class]="inputClass"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-labelledby]="ariaLabelledBy() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[checked]="checked()"
|
||||
[disabled]="isUnavailable()"
|
||||
[required]="required()"
|
||||
(change)="onInputChange(checkbox.checked)"
|
||||
(blur)="touched.set(true)" />
|
||||
<span [class]="boxClass()" aria-hidden="true"></span>
|
||||
<svg [class]="checkIndicatorClass()" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path
|
||||
d="M12.5 4.75L6.75 10.5L3.5 7.25"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round" />
|
||||
</svg>
|
||||
<svg [class]="indeterminateIndicatorClass()" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path d="M4 8H12" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
|
||||
</svg>
|
||||
</span>
|
||||
`,
|
||||
})
|
||||
export class AppCheckboxComponent implements FormCheckboxControl {
|
||||
readonly checked = model(false);
|
||||
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 = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly indeterminate = model(false);
|
||||
readonly size = input<AppCheckboxSize>('md');
|
||||
readonly inputId = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaLabelledBy = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
readonly styleClass = input('');
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
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 rootClass = computed(() => cn(appCheckboxRootVariants({ size: this.size() }), this.styleClass()));
|
||||
protected readonly inputClass = invisibleControlInputClass;
|
||||
protected readonly boxClass = computed(() =>
|
||||
appCheckboxBoxVariants({ disabled: this.isUnavailable(), invalid: this.showInvalid() }),
|
||||
);
|
||||
protected readonly checkIndicatorClass = computed(() =>
|
||||
cn(
|
||||
appCheckboxIndicatorVariants({ size: this.size() }),
|
||||
this.checked() && !this.indeterminate() ? 'opacity-100' : 'opacity-0',
|
||||
),
|
||||
);
|
||||
protected readonly indeterminateIndicatorClass = computed(() =>
|
||||
cn(appCheckboxIndicatorVariants({ size: this.size() }), this.indeterminate() ? 'opacity-100' : 'opacity-0'),
|
||||
);
|
||||
|
||||
private readonly checkbox = viewChild<ElementRef<HTMLInputElement>>('checkbox');
|
||||
|
||||
constructor() {
|
||||
afterRenderEffect({
|
||||
write: () => {
|
||||
const checkbox = this.checkbox()?.nativeElement;
|
||||
if (checkbox) checkbox.indeterminate = this.indeterminate();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected onInputChange(checked: boolean): void {
|
||||
this.checked.set(checked);
|
||||
this.indeterminate.set(false);
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.checkbox()?.nativeElement?.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export type AppCheckboxSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
export const appCheckboxRootVariants = cva('relative inline-grid shrink-0 place-items-center align-middle', {
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'size-4',
|
||||
md: 'size-5',
|
||||
lg: 'size-6',
|
||||
},
|
||||
},
|
||||
defaultVariants: { size: 'md' },
|
||||
});
|
||||
|
||||
export const appCheckboxBoxVariants = cva(
|
||||
`size-full rounded border ${neutralControlBorderClass} bg-card dark:bg-app shadow-control ` +
|
||||
'transition-[background-color,border-color,opacity] duration-150 ' +
|
||||
'peer-hover:border-primary/50 peer-checked:border-transparent peer-checked:bg-primary dark:peer-checked:bg-primary ' +
|
||||
'peer-checked:hover:bg-primary-hover peer-checked:active:bg-primary-active ' +
|
||||
'peer-indeterminate:border-transparent peer-indeterminate:bg-primary dark:peer-indeterminate:bg-primary ' +
|
||||
'peer-indeterminate:hover:bg-primary-hover peer-indeterminate:active:bg-primary-active ' +
|
||||
'peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-primary',
|
||||
{
|
||||
variants: {
|
||||
disabled: {
|
||||
true: 'opacity-50',
|
||||
false: '',
|
||||
},
|
||||
invalid: {
|
||||
true: 'border-danger',
|
||||
false: '',
|
||||
},
|
||||
},
|
||||
defaultVariants: { disabled: false, invalid: false },
|
||||
},
|
||||
);
|
||||
|
||||
export const appCheckboxIndicatorVariants = cva(
|
||||
'pointer-events-none absolute inset-0 m-auto text-primary-contrast opacity-0 transition-opacity duration-150',
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'size-3',
|
||||
md: 'size-3.5',
|
||||
lg: 'size-4',
|
||||
},
|
||||
},
|
||||
defaultVariants: { size: 'md' },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,14 @@
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...classes: (string | false | null | undefined)[]): string {
|
||||
return twMerge(classes.filter(Boolean).join(' '));
|
||||
}
|
||||
|
||||
type PtAttrs = Record<string, unknown> & { class?: string };
|
||||
|
||||
export function ptViewMerge(global: unknown, self: unknown, datasets?: unknown): Record<string, unknown> {
|
||||
const { class: globalClass, ...globalRest } = (global ?? {}) as PtAttrs;
|
||||
const { class: selfClass, ...selfRest } = (self ?? {}) as PtAttrs;
|
||||
const { class: datasetClass, ...datasetRest } = (datasets ?? {}) as PtAttrs;
|
||||
return { ...globalRest, ...selfRest, ...datasetRest, class: twMerge(globalClass, selfClass, datasetClass) };
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { cn } from './cn';
|
||||
|
||||
export const connectedGroupClass = 'app-cg-group isolate inline-flex';
|
||||
|
||||
interface ConnectedItemState {
|
||||
first: boolean;
|
||||
last: boolean;
|
||||
prominent?: boolean;
|
||||
}
|
||||
|
||||
export function connectedItemClass(state: ConnectedItemState): string {
|
||||
return cn(
|
||||
'app-cg-item relative',
|
||||
state.prominent && 'app-cg-prominent',
|
||||
state.first ? 'rounded-l-md' : 'rounded-l-none',
|
||||
state.last ? 'app-cg-last rounded-r-md' : 'rounded-r-none',
|
||||
!state.first && '-ml-px',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
type CdkConnectedOverlay,
|
||||
type ConnectedPosition,
|
||||
type Overlay,
|
||||
type OverlayRef,
|
||||
type ScrollStrategy,
|
||||
} from '@angular/cdk/overlay';
|
||||
|
||||
const CONNECTED_OVERLAY_GAP = 4;
|
||||
|
||||
const OVERLAY_ABOVE_CLASS = 'app-overlay-above';
|
||||
|
||||
export const connectedOverlayPanelClass =
|
||||
'origin-top will-change-transform animate-in fade-in-0 zoom-in-98 slide-in-from-top-1 ' +
|
||||
'[.app-overlay-above_&]:origin-bottom [.app-overlay-above_&]:slide-in-from-bottom-1';
|
||||
|
||||
export const connectedOverlayPositions: ConnectedPosition[] = [
|
||||
{ originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', offsetY: CONNECTED_OVERLAY_GAP },
|
||||
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: -CONNECTED_OVERLAY_GAP, panelClass: OVERLAY_ABOVE_CLASS },
|
||||
{ originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', offsetY: CONNECTED_OVERLAY_GAP },
|
||||
{ originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', offsetY: -CONNECTED_OVERLAY_GAP, panelClass: OVERLAY_ABOVE_CLASS },
|
||||
];
|
||||
|
||||
export function connectedOverlayScrollStrategy(overlay: Overlay): ScrollStrategy {
|
||||
return overlay.scrollStrategies.reposition({ scrollThrottle: 0 });
|
||||
}
|
||||
|
||||
export function refreshConnectedOverlayPosition(overlay: CdkConnectedOverlay | undefined): void {
|
||||
refreshOverlayRefPosition(overlay?.overlayRef);
|
||||
}
|
||||
|
||||
export function refreshOverlayRefPosition(overlayRef: OverlayRef | null | undefined): void {
|
||||
if (!overlayRef) return;
|
||||
|
||||
if (overlayRef.hasAttached()) overlayRef.updatePosition();
|
||||
queueMicrotask(() => {
|
||||
if (overlayRef.hasAttached()) overlayRef.updatePosition();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export const neutralControlBorderClass =
|
||||
'border-[color-mix(in_srgb,var(--color-text)_4%,var(--color-border))] dark:border-border';
|
||||
export const neutralSurfaceHoverClass =
|
||||
'hover:bg-[color-mix(in_srgb,var(--color-text)_6%,var(--color-card))] ' +
|
||||
'dark:hover:bg-[color-mix(in_srgb,var(--color-text)_9%,var(--color-card))]';
|
||||
export const invisibleControlInputClass =
|
||||
'peer absolute inset-0 z-10 m-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed';
|
||||
@@ -0,0 +1,480 @@
|
||||
import {
|
||||
afterRenderEffect,
|
||||
booleanAttribute,
|
||||
computed,
|
||||
Directive,
|
||||
inject,
|
||||
input,
|
||||
LOCALE_ID,
|
||||
model,
|
||||
signal,
|
||||
type ElementRef,
|
||||
type Signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
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 { overlayListSurfaceClass } from '../overlay-list.styles';
|
||||
import { appInputVariants } from '../input/app-input.variants';
|
||||
import {
|
||||
appDatePickerDayBase,
|
||||
appDatePickerDaySelected,
|
||||
appDatePickerDayToday,
|
||||
type AppDatePickerSize,
|
||||
} from './app-date-picker.variants';
|
||||
|
||||
type WeekInfoLocale = Intl.Locale & { getWeekInfo?: () => { firstDay: number }; weekInfo?: { firstDay: number } };
|
||||
|
||||
interface YearMonth {
|
||||
readonly y: number;
|
||||
readonly m: number;
|
||||
}
|
||||
|
||||
export interface DaySelectionFlags {
|
||||
readonly point: boolean;
|
||||
readonly spanStart: boolean;
|
||||
readonly spanEnd: boolean;
|
||||
readonly spanMiddle: boolean;
|
||||
}
|
||||
|
||||
export interface DayCell extends DaySelectionFlags {
|
||||
readonly iso: string;
|
||||
readonly day: number;
|
||||
readonly today: boolean;
|
||||
readonly disabled: boolean;
|
||||
readonly gridSelected: boolean;
|
||||
readonly ariaLabel: string;
|
||||
}
|
||||
|
||||
interface WeekRow {
|
||||
readonly key: string;
|
||||
readonly days: readonly DayCell[];
|
||||
}
|
||||
|
||||
function pad2(value: number): string {
|
||||
return value < 10 ? `0${value}` : `${value}`;
|
||||
}
|
||||
|
||||
function toIso(year: number, month: number, day: number): string {
|
||||
return `${year}-${pad2(month)}-${pad2(day)}`;
|
||||
}
|
||||
|
||||
export function parseIso(value: string): YearMonth & { d: number } | null {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
||||
if (!match) return null;
|
||||
const y = Number(match[1]);
|
||||
const m = Number(match[2]);
|
||||
const d = Number(match[3]);
|
||||
const probe = new Date(y, m - 1, d);
|
||||
if (probe.getFullYear() !== y || probe.getMonth() !== m - 1 || probe.getDate() !== d) return null;
|
||||
return { y, m, d };
|
||||
}
|
||||
|
||||
function localeFirstDay(locale: string): number {
|
||||
try {
|
||||
const info = new Intl.Locale(locale) as WeekInfoLocale;
|
||||
const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay;
|
||||
return typeof firstDay === 'number' ? firstDay : 1;
|
||||
} catch {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
function currentYearMonth(): YearMonth {
|
||||
const now = new Date();
|
||||
return { y: now.getFullYear(), m: now.getMonth() + 1 };
|
||||
}
|
||||
|
||||
export const DATE_PICKER_TEMPLATE = `
|
||||
<div #origin class="relative block w-full">
|
||||
<input
|
||||
#trigger
|
||||
readonly
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
[class]="triggerClass()"
|
||||
[value]="displayValue()"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.placeholder]="placeholder() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
aria-haspopup="dialog"
|
||||
[attr.aria-expanded]="open()"
|
||||
[disabled]="disabled()"
|
||||
[required]="required()"
|
||||
(click)="toggle()"
|
||||
(keydown)="onTriggerKeydown($event)"
|
||||
(blur)="onTriggerBlur($event)" />
|
||||
|
||||
<span
|
||||
class="pointer-events-none absolute inset-y-0 right-0 inline-flex w-10 items-center justify-center text-text-muted">
|
||||
@if (pending()) {
|
||||
<i class="pi pi-spinner pi-spin text-xs" aria-hidden="true"></i>
|
||||
} @else {
|
||||
<i class="pi pi-calendar text-sm" aria-hidden="true"></i>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<ng-template
|
||||
[cdkConnectedOverlay]="{
|
||||
origin,
|
||||
usePopover: 'inline',
|
||||
positions: overlayPositions,
|
||||
viewportMargin: 8,
|
||||
push: true
|
||||
}"
|
||||
[cdkConnectedOverlayOpen]="open()"
|
||||
[cdkConnectedOverlayScrollStrategy]="overlayScrollStrategy"
|
||||
(attach)="onOverlayAttach()"
|
||||
(overlayKeydown)="onOverlayKeydown($event)"
|
||||
(overlayOutsideClick)="onOutsideClick($event)"
|
||||
(detach)="close()">
|
||||
<div
|
||||
role="dialog"
|
||||
[attr.aria-label]="monthYearLabel()"
|
||||
[class]="popupClass"
|
||||
(focusout)="onPopupFocusOut($event)">
|
||||
<div class="mb-2 flex items-center justify-between gap-1">
|
||||
<button type="button" [class]="navButtonClass" [attr.aria-label]="'shared.ui.datePicker.previousMonth' | transloco" (click)="shiftMonth(-1)">
|
||||
<i class="pi pi-chevron-left text-xs" aria-hidden="true"></i>
|
||||
</button>
|
||||
<span aria-live="polite" class="text-sm font-semibold text-text-strong">{{ monthYearLabel() }}</span>
|
||||
<button type="button" [class]="navButtonClass" [attr.aria-label]="'shared.ui.datePicker.nextMonth' | transloco" (click)="shiftMonth(1)">
|
||||
<i class="pi pi-chevron-right text-xs" aria-hidden="true"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<table
|
||||
ngGrid
|
||||
colWrap="continuous"
|
||||
rowWrap="nowrap"
|
||||
[enableSelection]="true"
|
||||
[softDisabled]="false"
|
||||
[multi]="isRange"
|
||||
selectionMode="explicit"
|
||||
class="border-collapse"
|
||||
[attr.aria-label]="monthYearLabel()">
|
||||
<thead>
|
||||
<tr>
|
||||
@for (weekday of weekdays(); track weekday.key) {
|
||||
<th scope="col" class="p-0">
|
||||
<span class="flex size-9 items-center justify-center text-xs font-medium text-text-muted">
|
||||
<span class="sr-only">{{ weekday.long }}</span>
|
||||
<span aria-hidden="true">{{ weekday.narrow }}</span>
|
||||
</span>
|
||||
</th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody (mouseleave)="clearPreview()">
|
||||
@for (week of weeks(); track week.key) {
|
||||
<tr ngGridRow>
|
||||
@for (day of week.days; track day.iso) {
|
||||
<td
|
||||
ngGridCell
|
||||
class="p-0"
|
||||
[disabled]="day.disabled"
|
||||
[selected]="day.gridSelected"
|
||||
(selectedChange)="onCellSelected(day, $event)">
|
||||
<button
|
||||
ngGridCellWidget
|
||||
type="button"
|
||||
[disabled]="day.disabled"
|
||||
[class]="dayClass(day)"
|
||||
[attr.aria-label]="day.ariaLabel"
|
||||
[attr.data-day]="day.day"
|
||||
[attr.data-selected]="day.gridSelected ? '' : null"
|
||||
[attr.data-today]="day.today ? '' : null"
|
||||
(mouseenter)="onDayHover(day)">
|
||||
{{ day.day }}
|
||||
</button>
|
||||
</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</ng-template>
|
||||
`;
|
||||
|
||||
@Directive()
|
||||
export abstract class AppDatePickerBaseDirective {
|
||||
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 = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly size = input<AppDatePickerSize>('md');
|
||||
readonly placeholder = input('');
|
||||
readonly inputId = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
readonly styleClass = input('');
|
||||
readonly minDate = input('');
|
||||
readonly maxDate = input('');
|
||||
readonly locale = input('');
|
||||
readonly firstDayOfWeek = input<number | null>(null);
|
||||
|
||||
protected abstract readonly isRange: boolean;
|
||||
protected abstract readonly displayValue: Signal<string>;
|
||||
protected abstract dayFlags(iso: string, outside: boolean): DaySelectionFlags;
|
||||
protected abstract pickDay(day: DayCell): void;
|
||||
protected abstract anchorIso(): string;
|
||||
protected abstract pickingEnd(): boolean;
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
private readonly localeId = inject(LOCALE_ID);
|
||||
private readonly overlayService = inject(Overlay);
|
||||
private readonly originRef = viewChild<ElementRef<HTMLElement>>('origin');
|
||||
private readonly triggerRef = viewChild<ElementRef<HTMLInputElement>>('trigger');
|
||||
private readonly overlay = viewChild(CdkConnectedOverlay);
|
||||
|
||||
private readonly initialView = currentYearMonth();
|
||||
protected readonly open = signal(false);
|
||||
protected readonly viewYear = signal(this.initialView.y);
|
||||
protected readonly viewMonth = signal(this.initialView.m);
|
||||
protected readonly previewEnd = signal('');
|
||||
|
||||
private readonly todayIso = (() => {
|
||||
const today = new Date();
|
||||
return toIso(today.getFullYear(), today.getMonth() + 1, today.getDate());
|
||||
})();
|
||||
|
||||
protected readonly overlayPositions = connectedOverlayPositions;
|
||||
protected readonly overlayScrollStrategy = connectedOverlayScrollStrategy(this.overlayService);
|
||||
protected readonly popupClass = cn(overlayListSurfaceClass, connectedOverlayPanelClass, 'w-auto p-3');
|
||||
protected readonly navButtonClass =
|
||||
'flex size-7 items-center justify-center rounded-md border-0 bg-transparent text-text-muted outline-hidden ' +
|
||||
'transition-colors hover:bg-surface-hover hover:text-text-strong ' +
|
||||
'focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-primary';
|
||||
|
||||
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 triggerClass = computed(() =>
|
||||
cn(
|
||||
appInputVariants({ size: this.size() }),
|
||||
this.readonly() ? 'cursor-default select-text' : 'cursor-pointer select-none',
|
||||
'pr-10',
|
||||
this.styleClass(),
|
||||
),
|
||||
);
|
||||
|
||||
protected readonly resolvedLocale = computed(() => this.locale() || this.localeId || 'en');
|
||||
private readonly resolvedFirstDay = computed(() => this.firstDayOfWeek() ?? localeFirstDay(this.resolvedLocale()));
|
||||
|
||||
protected readonly weekdays = computed(() => {
|
||||
const locale = this.resolvedLocale();
|
||||
const jsFirst = this.resolvedFirstDay() % 7;
|
||||
const longFmt = new Intl.DateTimeFormat(locale, { weekday: 'long' });
|
||||
const narrowFmt = new Intl.DateTimeFormat(locale, { weekday: 'narrow' });
|
||||
return Array.from({ length: 7 }, (_, index) => {
|
||||
const ref = new Date(2021, 7, 1 + ((jsFirst + index) % 7));
|
||||
return { key: index, long: longFmt.format(ref), narrow: narrowFmt.format(ref) };
|
||||
});
|
||||
});
|
||||
|
||||
protected readonly monthYearLabel = computed(() =>
|
||||
new Intl.DateTimeFormat(this.resolvedLocale(), { month: 'long', year: 'numeric' }).format(
|
||||
new Date(this.viewYear(), this.viewMonth() - 1, 1),
|
||||
),
|
||||
);
|
||||
|
||||
protected readonly weeks = computed<WeekRow[]>(() => {
|
||||
const year = this.viewYear();
|
||||
const month = this.viewMonth();
|
||||
const jsFirst = this.resolvedFirstDay() % 7;
|
||||
const min = this.minDate();
|
||||
const max = this.maxDate();
|
||||
const fullFmt = new Intl.DateTimeFormat(this.resolvedLocale(), { dateStyle: 'full' });
|
||||
|
||||
const firstWeekday = new Date(year, month - 1, 1).getDay();
|
||||
const leading = (firstWeekday - jsFirst + 7) % 7;
|
||||
const cursor = new Date(year, month - 1, 1 - leading);
|
||||
|
||||
const rows: WeekRow[] = [];
|
||||
for (let week = 0; week < 6; week++) {
|
||||
const days: DayCell[] = [];
|
||||
for (let column = 0; column < 7; column++) {
|
||||
const cy = cursor.getFullYear();
|
||||
const cm = cursor.getMonth() + 1;
|
||||
const cd = cursor.getDate();
|
||||
const iso = toIso(cy, cm, cd);
|
||||
const outside = cm !== month;
|
||||
const outOfRange = (min !== '' && iso < min) || (max !== '' && iso > max);
|
||||
const disabled = outside || outOfRange;
|
||||
const flags = this.dayFlags(iso, outside);
|
||||
|
||||
days.push({
|
||||
iso,
|
||||
day: cd,
|
||||
today: !outside && iso === this.todayIso,
|
||||
disabled,
|
||||
...flags,
|
||||
gridSelected: !disabled && (flags.point || flags.spanStart || flags.spanEnd || flags.spanMiddle),
|
||||
ariaLabel: fullFmt.format(cursor),
|
||||
});
|
||||
cursor.setDate(cd + 1);
|
||||
}
|
||||
rows.push({ key: days[0].iso, days });
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
|
||||
constructor() {
|
||||
afterRenderEffect({
|
||||
mixedReadWrite: () => {
|
||||
if (this.open()) this.focusInitialDay();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected dayClass(day: DayCell): string {
|
||||
const inSelection = day.point || day.spanStart || day.spanEnd || day.spanMiddle;
|
||||
return cn(
|
||||
appDatePickerDayBase,
|
||||
day.disabled && 'text-text-muted opacity-40',
|
||||
inSelection && appDatePickerDaySelected,
|
||||
(day.spanStart || day.spanEnd || day.spanMiddle) && 'rounded-none',
|
||||
!inSelection && day.today && appDatePickerDayToday,
|
||||
);
|
||||
}
|
||||
|
||||
protected toggle(): void {
|
||||
if (this.isUnavailable()) return;
|
||||
if (this.open()) {
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
this.openPopup();
|
||||
}
|
||||
|
||||
protected onCellSelected(day: DayCell, selected: boolean): void {
|
||||
if (this.isUnavailable() || day.disabled) return;
|
||||
if (!this.isRange && !selected) return;
|
||||
this.pickDay(day);
|
||||
}
|
||||
|
||||
protected onDayHover(day: DayCell): void {
|
||||
if (day.disabled || !this.pickingEnd()) return;
|
||||
this.previewEnd.set(day.iso);
|
||||
}
|
||||
|
||||
protected clearPreview(): void {
|
||||
this.previewEnd.set('');
|
||||
}
|
||||
|
||||
protected onTriggerKeydown(event: KeyboardEvent): void {
|
||||
if (this.isUnavailable()) return;
|
||||
if (this.open()) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.close(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.key === 'ArrowDown' || event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
this.openPopup();
|
||||
}
|
||||
}
|
||||
|
||||
protected onTriggerBlur(event: FocusEvent): void {
|
||||
if (this.disabled()) return;
|
||||
if (this.relatedTargetInPopup(event.relatedTarget)) return;
|
||||
this.touched.set(true);
|
||||
}
|
||||
|
||||
protected onOverlayKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.close(true);
|
||||
}
|
||||
}
|
||||
|
||||
protected onOutsideClick(event: MouseEvent): void {
|
||||
const target = event.target;
|
||||
if (target instanceof Node && this.originRef()?.nativeElement.contains(target)) return;
|
||||
this.close();
|
||||
}
|
||||
|
||||
protected onPopupFocusOut(event: FocusEvent): void {
|
||||
const next = event.relatedTarget;
|
||||
if (next === null) return;
|
||||
if (next instanceof Node && this.originRef()?.nativeElement.contains(next)) return;
|
||||
if (this.relatedTargetInPopup(next)) return;
|
||||
this.close();
|
||||
}
|
||||
|
||||
protected onOverlayAttach(): void {
|
||||
refreshConnectedOverlayPosition(this.overlay());
|
||||
}
|
||||
|
||||
protected close(refocusTrigger = false): void {
|
||||
this.clearPreview();
|
||||
this.open.set(false);
|
||||
if (refocusTrigger) queueMicrotask(() => this.focus());
|
||||
}
|
||||
|
||||
private openPopup(): void {
|
||||
const base = parseIso(this.anchorIso()) ?? currentYearMonth();
|
||||
this.viewYear.set(base.y);
|
||||
this.viewMonth.set(base.m);
|
||||
this.open.set(true);
|
||||
}
|
||||
|
||||
protected shiftMonth(delta: number): void {
|
||||
const base = new Date(this.viewYear(), this.viewMonth() - 1 + delta, 1);
|
||||
this.viewYear.set(base.getFullYear());
|
||||
this.viewMonth.set(base.getMonth() + 1);
|
||||
}
|
||||
|
||||
protected formatDate(iso: string): string {
|
||||
const parsed = parseIso(iso);
|
||||
if (!parsed) return '';
|
||||
return new Intl.DateTimeFormat(this.resolvedLocale(), { dateStyle: 'medium' }).format(
|
||||
new Date(parsed.y, parsed.m - 1, parsed.d),
|
||||
);
|
||||
}
|
||||
|
||||
private relatedTargetInPopup(target: EventTarget | null): boolean {
|
||||
const overlayElement = this.overlay()?.overlayRef?.overlayElement;
|
||||
return target instanceof Node && overlayElement?.contains(target) === true;
|
||||
}
|
||||
|
||||
private focusInitialDay(): void {
|
||||
const overlayElement = this.overlay()?.overlayRef?.overlayElement;
|
||||
if (!overlayElement) return;
|
||||
const target =
|
||||
overlayElement.querySelector<HTMLElement>('button[data-selected]') ??
|
||||
overlayElement.querySelector<HTMLElement>('button[data-today]:not([disabled])') ??
|
||||
overlayElement.querySelector<HTMLElement>('button[data-day]:not([disabled])');
|
||||
target?.focus();
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.triggerRef()?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, model } from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
import { Grid, GridCell, GridCellWidget, GridRow } from '@angular/aria/grid';
|
||||
import { OverlayModule } from '@angular/cdk/overlay';
|
||||
import { TranslocoPipe } from '@jsverse/transloco';
|
||||
|
||||
import {
|
||||
AppDatePickerBaseDirective,
|
||||
DATE_PICKER_TEMPLATE,
|
||||
type DayCell,
|
||||
type DaySelectionFlags,
|
||||
} from './app-date-picker-base.directive';
|
||||
|
||||
const NO_SELECTION: DaySelectionFlags = { point: false, spanStart: false, spanEnd: false, spanMiddle: false };
|
||||
|
||||
@Component({
|
||||
selector: 'app-date-picker',
|
||||
standalone: true,
|
||||
imports: [OverlayModule, Grid, GridRow, GridCell, GridCellWidget, TranslocoPipe],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: DATE_PICKER_TEMPLATE,
|
||||
})
|
||||
export class AppDatePickerComponent extends AppDatePickerBaseDirective implements FormValueControl<string> {
|
||||
readonly value = model('');
|
||||
|
||||
protected override readonly isRange = false;
|
||||
|
||||
protected override readonly displayValue = computed(() => this.formatDate(this.value()));
|
||||
|
||||
protected override dayFlags(iso: string, outside: boolean): DaySelectionFlags {
|
||||
const value = this.value();
|
||||
if (outside || value === '' || iso !== value) return NO_SELECTION;
|
||||
return { ...NO_SELECTION, point: true };
|
||||
}
|
||||
|
||||
protected override pickDay(day: DayCell): void {
|
||||
this.value.set(day.iso);
|
||||
this.touched.set(true);
|
||||
this.close(true);
|
||||
}
|
||||
|
||||
protected override anchorIso(): string {
|
||||
return this.value();
|
||||
}
|
||||
|
||||
protected override pickingEnd(): boolean {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export type AppDatePickerSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
export const appDatePickerDayBase =
|
||||
'relative flex size-9 items-center justify-center rounded-md border-0 bg-transparent text-sm font-normal text-text outline-hidden ' +
|
||||
'hover:bg-surface-hover hover:text-text-strong ' +
|
||||
'focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-primary ' +
|
||||
'disabled:pointer-events-none';
|
||||
|
||||
export const appDatePickerDaySelected = 'bg-primary/15 text-text-strong hover:bg-primary/25';
|
||||
|
||||
export const appDatePickerDayToday = 'font-semibold text-primary';
|
||||
@@ -0,0 +1,82 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, model } from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
import { Grid, GridCell, GridCellWidget, GridRow } from '@angular/aria/grid';
|
||||
import { OverlayModule } from '@angular/cdk/overlay';
|
||||
import { TranslocoPipe } from '@jsverse/transloco';
|
||||
|
||||
import {
|
||||
AppDatePickerBaseDirective,
|
||||
DATE_PICKER_TEMPLATE,
|
||||
type DayCell,
|
||||
type DaySelectionFlags,
|
||||
} from './app-date-picker-base.directive';
|
||||
|
||||
export interface DatePickerRange {
|
||||
readonly start: string;
|
||||
readonly end: string;
|
||||
}
|
||||
|
||||
const EMPTY_RANGE: DatePickerRange = { start: '', end: '' };
|
||||
const NO_SELECTION: DaySelectionFlags = { point: false, spanStart: false, spanEnd: false, spanMiddle: false };
|
||||
|
||||
@Component({
|
||||
selector: 'app-date-range-picker',
|
||||
standalone: true,
|
||||
imports: [OverlayModule, Grid, GridRow, GridCell, GridCellWidget, TranslocoPipe],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: DATE_PICKER_TEMPLATE,
|
||||
})
|
||||
export class AppDateRangePickerComponent extends AppDatePickerBaseDirective implements FormValueControl<DatePickerRange> {
|
||||
readonly value = model<DatePickerRange>(EMPTY_RANGE);
|
||||
|
||||
protected override readonly isRange = true;
|
||||
|
||||
private readonly span = computed(() => {
|
||||
const range = this.value();
|
||||
const effStart = range.start;
|
||||
const effEnd = range.end || (this.pickingEnd() ? this.previewEnd() : '');
|
||||
const hasSpan = effStart !== '' && effEnd !== '' && effStart !== effEnd;
|
||||
const lo = hasSpan && effStart > effEnd ? effEnd : effStart;
|
||||
const hi = hasSpan && effStart > effEnd ? effStart : effEnd;
|
||||
return { hasSpan, lo, hi, effStart };
|
||||
});
|
||||
|
||||
protected override readonly displayValue = computed(() => {
|
||||
const range = this.value();
|
||||
const start = this.formatDate(range.start);
|
||||
const end = this.formatDate(range.end);
|
||||
if (!start && !end) return '';
|
||||
return `${start || '…'} – ${end || '…'}`;
|
||||
});
|
||||
|
||||
protected override dayFlags(iso: string): DaySelectionFlags {
|
||||
const { hasSpan, lo, hi, effStart } = this.span();
|
||||
if (hasSpan) {
|
||||
return { point: false, spanStart: iso === lo, spanEnd: iso === hi, spanMiddle: iso > lo && iso < hi };
|
||||
}
|
||||
if (effStart !== '' && iso === effStart) return { ...NO_SELECTION, point: true };
|
||||
return NO_SELECTION;
|
||||
}
|
||||
|
||||
protected override pickDay(day: DayCell): void {
|
||||
const range = this.value();
|
||||
this.touched.set(true);
|
||||
this.clearPreview();
|
||||
if (!range.start || range.end || day.iso < range.start) {
|
||||
this.value.set({ start: day.iso, end: '' });
|
||||
return;
|
||||
}
|
||||
this.value.set({ start: range.start, end: day.iso });
|
||||
this.close(true);
|
||||
}
|
||||
|
||||
protected override anchorIso(): string {
|
||||
return this.value().start;
|
||||
}
|
||||
|
||||
protected override pickingEnd(): boolean {
|
||||
const range = this.value();
|
||||
return range.start !== '' && range.end === '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
contentChild,
|
||||
forwardRef,
|
||||
inject,
|
||||
input,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { FormField as SignalFormField, type FieldState } from '@angular/forms/signals';
|
||||
import { TranslocoService } from '@jsverse/transloco';
|
||||
import { cn } from '../cn';
|
||||
import {
|
||||
APP_FIELD,
|
||||
APP_FIELD_DEFAULT_ERROR_KEY,
|
||||
appFieldErrorKey,
|
||||
appFieldErrorMessage,
|
||||
type AppFieldContext,
|
||||
type AppFieldLike,
|
||||
} from './app-field.context';
|
||||
|
||||
let nextFieldId = 0;
|
||||
|
||||
@Component({
|
||||
selector: 'app-field',
|
||||
standalone: true,
|
||||
host: {
|
||||
'[class]': 'rootClass()',
|
||||
'[class.hidden]': 'hidden()',
|
||||
'(input)': 'editing.set(true)',
|
||||
'(change)': 'editing.set(true)',
|
||||
'(focusout)': 'editing.set(false)',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
providers: [{ provide: APP_FIELD, useExisting: forwardRef(() => AppFieldComponent) }],
|
||||
template: `
|
||||
@if (label()) {
|
||||
<label
|
||||
class="inline-flex items-center text-sm font-medium text-text-strong"
|
||||
[attr.id]="labelId()"
|
||||
[attr.for]="controlId()">
|
||||
<span>{{ label() }}</span>
|
||||
@if (showRequiredMark()) {
|
||||
<span class="ml-0.5 text-danger" aria-hidden="true">*</span>
|
||||
}
|
||||
</label>
|
||||
}
|
||||
|
||||
<ng-content />
|
||||
|
||||
@if (showHint()) {
|
||||
<p [id]="hintId()" class="m-0 text-xs text-text-muted dark:text-text-secondary">{{ hint() }}</p>
|
||||
}
|
||||
@if (displayErrors().length) {
|
||||
<div [id]="errorId()" aria-live="polite" class="flex flex-col gap-0.5">
|
||||
@for (message of displayErrors(); track message) {
|
||||
<p class="m-0 text-xs text-danger">{{ message }}</p>
|
||||
}
|
||||
</div>
|
||||
} @else if (disabledReasonMessages().length) {
|
||||
<div [id]="disabledId()" role="status" class="flex flex-col gap-0.5">
|
||||
@for (message of disabledReasonMessages(); track message) {
|
||||
<p class="m-0 text-xs text-text-muted dark:text-text-secondary">{{ message }}</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppFieldComponent implements AppFieldContext {
|
||||
readonly field = input<AppFieldLike | undefined>(undefined);
|
||||
readonly label = input('');
|
||||
readonly hint = input('');
|
||||
readonly errors = input<string | readonly string[]>([]);
|
||||
readonly required = input(false, { transform: booleanAttribute });
|
||||
readonly fieldId = input('');
|
||||
readonly styleClass = input('');
|
||||
|
||||
private readonly transloco = inject(TranslocoService);
|
||||
private readonly activeLang = toSignal(this.transloco.langChanges$, { initialValue: this.transloco.getActiveLang() });
|
||||
private readonly generatedId = `app-field-${++nextFieldId}`;
|
||||
protected readonly editing = signal(false);
|
||||
private readonly projectedFormField = contentChild(SignalFormField, { descendants: true });
|
||||
private readonly fieldState = computed<FieldState<unknown> | null>(
|
||||
() => this.field()?.() ?? this.projectedFormField()?.state() ?? null,
|
||||
);
|
||||
|
||||
readonly controlId = computed(() => this.fieldId() || this.generatedId);
|
||||
readonly labelId = computed(() => (this.label() ? `${this.controlId()}-label` : null));
|
||||
|
||||
protected readonly displayErrors = computed<readonly string[]>(() => {
|
||||
this.activeLang();
|
||||
const state = this.fieldState();
|
||||
if (state) {
|
||||
if (!state.touched() || this.editing()) return [];
|
||||
return state.errors().map(error => appFieldErrorMessage(error, this.translateFallbackError));
|
||||
}
|
||||
|
||||
const errors = this.errors();
|
||||
if (Array.isArray(errors)) return errors;
|
||||
return errors ? [errors] : [];
|
||||
});
|
||||
protected readonly disabledReasonMessages = computed<readonly string[]>(() =>
|
||||
(this.fieldState()?.disabledReasons() ?? [])
|
||||
.map(reason => reason.message)
|
||||
.filter((message): message is string => typeof message === 'string' && message.length > 0),
|
||||
);
|
||||
|
||||
protected readonly showHint = computed(() => !!this.hint() && !this.disabledReasonMessages().length);
|
||||
protected readonly hintId = computed(() => `${this.controlId()}-hint`);
|
||||
protected readonly errorId = computed(() => `${this.controlId()}-error`);
|
||||
protected readonly disabledId = computed(() => `${this.controlId()}-disabled`);
|
||||
readonly describedById = computed(() => {
|
||||
const ids: string[] = [];
|
||||
if (this.showHint()) ids.push(this.hintId());
|
||||
if (this.displayErrors().length) ids.push(this.errorId());
|
||||
else if (this.disabledReasonMessages().length) ids.push(this.disabledId());
|
||||
return ids.length ? ids.join(' ') : null;
|
||||
});
|
||||
readonly validationVisible = computed(() => this.displayErrors().length > 0);
|
||||
|
||||
protected readonly showRequiredMark = computed(() => this.fieldState()?.required() ?? this.required());
|
||||
protected readonly hidden = computed(() => this.fieldState()?.hidden() ?? false);
|
||||
protected readonly rootClass = computed(() => cn('flex flex-col gap-1.5', this.styleClass()));
|
||||
|
||||
private readonly translateFallbackError = (kind: string): string => {
|
||||
const key = appFieldErrorKey(kind);
|
||||
const translated = this.transloco.translate(key);
|
||||
return translated === key ? this.transloco.translate(APP_FIELD_DEFAULT_ERROR_KEY) : translated;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { InjectionToken, type Signal } from '@angular/core';
|
||||
import { type FieldState, type ValidationError } from '@angular/forms/signals';
|
||||
|
||||
export type AppFieldLike = () => FieldState<unknown>;
|
||||
|
||||
export interface AppFieldContext {
|
||||
readonly controlId: Signal<string>;
|
||||
readonly labelId: Signal<string | null>;
|
||||
readonly describedById: Signal<string | null>;
|
||||
readonly validationVisible: Signal<boolean>;
|
||||
}
|
||||
|
||||
export const APP_FIELD = new InjectionToken<AppFieldContext>('APP_FIELD');
|
||||
export const APP_FIELD_DEFAULT_ERROR_KEY = 'shared.ui.validation.default';
|
||||
|
||||
export function appFieldErrorKey(kind: string): string {
|
||||
return `shared.ui.validation.${kind}`;
|
||||
}
|
||||
|
||||
export function appFieldErrorMessage(error: ValidationError, fallback?: (kind: string) => string): string {
|
||||
if (typeof error.message === 'string' && error.message.length > 0) return error.message;
|
||||
return fallback ? fallback(error.kind) : error.kind;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
signal,
|
||||
type ElementRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
import { translateSignal } from '@jsverse/transloco';
|
||||
import { cn } from '../cn';
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
import { appInputVariants, type AppInputSize, type AppInputVariant } from './app-input.variants';
|
||||
|
||||
type AppInputType = 'text' | 'email' | 'password' | 'search' | 'tel' | 'url';
|
||||
|
||||
const TRAILING_ACTION_BUTTON_CLASS =
|
||||
'absolute inset-y-0 right-0 inline-flex w-10 items-center justify-center rounded-r-md text-text-muted ' +
|
||||
'transition-colors hover:text-text-strong ' +
|
||||
'focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-primary ' +
|
||||
'disabled:pointer-events-none disabled:opacity-50';
|
||||
|
||||
@Component({
|
||||
selector: 'app-input',
|
||||
standalone: true,
|
||||
host: { class: 'relative block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
@if (leadingIcon()) {
|
||||
<span class="pointer-events-none absolute inset-y-0 left-0 inline-flex w-10 items-center justify-center text-text-muted">
|
||||
<i [class]="leadingIcon()" aria-hidden="true"></i>
|
||||
</span>
|
||||
}
|
||||
<input
|
||||
#input
|
||||
[class]="inputClass()"
|
||||
[type]="resolvedType()"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.placeholder]="placeholder() || null"
|
||||
[attr.autocomplete]="autocomplete() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.maxlength]="maxLength()"
|
||||
[attr.minlength]="minLength()"
|
||||
[attr.pattern]="patternAttr()"
|
||||
[value]="value()"
|
||||
[disabled]="disabled()"
|
||||
[readonly]="readonly()"
|
||||
[required]="required()"
|
||||
(input)="onInput(input)"
|
||||
(blur)="touched.set(true)"
|
||||
(keydown)="keyedDown.emit($event)"
|
||||
(keyup.enter)="onEnterKeyup($event)" />
|
||||
@if (pending()) {
|
||||
<span
|
||||
class="pointer-events-none absolute inset-y-0 inline-flex w-10 items-center justify-center text-text-muted"
|
||||
[class.right-10]="showTrailingAction()"
|
||||
[class.right-0]="!showTrailingAction()">
|
||||
<i class="pi pi-spinner pi-spin text-xs" aria-hidden="true"></i>
|
||||
</span>
|
||||
}
|
||||
@if (showTrailingAction()) {
|
||||
<button
|
||||
type="button"
|
||||
[class]="trailingActionButtonClass"
|
||||
[disabled]="disabled()"
|
||||
[attr.aria-label]="trailingActionAriaLabel()"
|
||||
[attr.aria-pressed]="trailingActionPressed()"
|
||||
(click)="onTrailingActionClick($event)">
|
||||
<i [class]="trailingActionIcon()" aria-hidden="true"></i>
|
||||
</button>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppInputComponent implements FormValueControl<string> {
|
||||
readonly value = model('');
|
||||
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 touched = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly size = input<AppInputSize>('md');
|
||||
readonly variant = input<AppInputVariant>('outlined');
|
||||
readonly type = input<AppInputType>('text');
|
||||
readonly inputId = input('');
|
||||
readonly placeholder = input('');
|
||||
readonly autocomplete = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
readonly styleClass = input('');
|
||||
readonly readonly = input(false, { transform: booleanAttribute });
|
||||
readonly maxLength = input<number | undefined>(undefined);
|
||||
readonly minLength = input<number | undefined>(undefined);
|
||||
readonly pattern = input<readonly RegExp[]>([]);
|
||||
readonly revealToggle = input(false, { transform: booleanAttribute });
|
||||
readonly leadingIcon = input('');
|
||||
readonly trailingIcon = input('');
|
||||
readonly trailingAriaLabel = input('');
|
||||
readonly trailingPressed = input<boolean | 'false' | 'true' | 'mixed' | null>(null);
|
||||
|
||||
readonly keyedDown = output<KeyboardEvent>();
|
||||
readonly enterPressed = output<KeyboardEvent>();
|
||||
readonly trailingClicked = output<MouseEvent>();
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
protected readonly trailingActionButtonClass = TRAILING_ACTION_BUTTON_CLASS;
|
||||
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 patternAttr = computed(() => this.pattern()[0]?.source ?? null);
|
||||
|
||||
protected readonly passwordVisible = signal(false);
|
||||
protected readonly showRevealToggle = computed(() => this.type() === 'password' && this.revealToggle());
|
||||
protected readonly showTrailingAction = computed(() => this.showRevealToggle() || this.trailingIcon() !== '');
|
||||
private readonly showPasswordLabel = translateSignal('shared.ui.input.showPassword');
|
||||
private readonly hidePasswordLabel = translateSignal('shared.ui.input.hidePassword');
|
||||
private readonly trailingActionDefaultLabel = translateSignal('shared.ui.input.trailingAction');
|
||||
protected readonly resolvedType = computed(() =>
|
||||
this.showRevealToggle() && this.passwordVisible() ? 'text' : this.type(),
|
||||
);
|
||||
protected readonly trailingActionIcon = computed(() => {
|
||||
if (this.showRevealToggle()) {
|
||||
return this.passwordVisible() ? 'pi pi-eye-slash' : 'pi pi-eye';
|
||||
}
|
||||
|
||||
return this.trailingIcon();
|
||||
});
|
||||
protected readonly trailingActionAriaLabel = computed(() => {
|
||||
if (this.showRevealToggle()) {
|
||||
return this.passwordVisible() ? this.hidePasswordLabel() : this.showPasswordLabel();
|
||||
}
|
||||
|
||||
return this.trailingAriaLabel() || this.trailingActionDefaultLabel();
|
||||
});
|
||||
protected readonly trailingActionPressed = computed(() => {
|
||||
if (this.showRevealToggle()) {
|
||||
return this.passwordVisible();
|
||||
}
|
||||
|
||||
return this.trailingPressed();
|
||||
});
|
||||
protected readonly trailingPaddingClass = computed(() => {
|
||||
const hasTrailingAction = this.showTrailingAction();
|
||||
const pending = this.pending();
|
||||
|
||||
if (hasTrailingAction && pending) return 'pr-20';
|
||||
if (hasTrailingAction || pending) return 'pr-10';
|
||||
return '';
|
||||
});
|
||||
protected readonly inputClass = computed(() =>
|
||||
cn(
|
||||
appInputVariants({ size: this.size(), variant: this.variant() }),
|
||||
this.leadingIcon() && 'pl-10',
|
||||
this.trailingPaddingClass(),
|
||||
this.styleClass(),
|
||||
),
|
||||
);
|
||||
|
||||
private readonly input = viewChild<ElementRef<HTMLInputElement>>('input');
|
||||
|
||||
protected onInput(input: HTMLInputElement): void {
|
||||
if (this.disabled() || this.readonly()) {
|
||||
input.value = this.value();
|
||||
return;
|
||||
}
|
||||
this.value.set(input.value);
|
||||
}
|
||||
|
||||
protected onEnterKeyup(event: Event): void {
|
||||
this.enterPressed.emit(event as KeyboardEvent);
|
||||
}
|
||||
|
||||
protected onTrailingActionClick(event: MouseEvent): void {
|
||||
if (this.showRevealToggle()) {
|
||||
this.passwordVisible.update(visible => !visible);
|
||||
return;
|
||||
}
|
||||
|
||||
this.trailingClicked.emit(event);
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.input()?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export type AppInputSize = 'sm' | 'md' | 'lg';
|
||||
export type AppInputVariant = 'outlined' | 'bare';
|
||||
|
||||
export const appInputVariants = cva(
|
||||
`block w-full text-text-strong outline-hidden ` +
|
||||
'placeholder:text-text-muted transition-[background-color,border-color,color] duration-150 ' +
|
||||
'[&::-webkit-search-cancel-button]:hidden [&::-webkit-search-decoration]:hidden ' +
|
||||
'disabled:pointer-events-none disabled:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'text-xs',
|
||||
md: 'text-sm',
|
||||
lg: 'text-sm',
|
||||
},
|
||||
variant: {
|
||||
outlined:
|
||||
`rounded-md border ${neutralControlBorderClass} bg-card shadow-control ` +
|
||||
'focus:border-primary/60 focus:outline-1 focus:outline-offset-0 focus:outline-primary/60 ' +
|
||||
'aria-invalid:border-danger aria-invalid:focus:border-danger aria-invalid:focus:outline-danger',
|
||||
bare: 'rounded-none border-0 bg-transparent shadow-none aria-invalid:text-danger',
|
||||
},
|
||||
},
|
||||
compoundVariants: [
|
||||
{ variant: 'outlined', size: 'sm', class: 'h-8 px-3 leading-8' },
|
||||
{ variant: 'outlined', size: 'md', class: 'h-9 px-3 leading-9' },
|
||||
{ variant: 'outlined', size: 'lg', class: 'h-10 px-4 leading-10' },
|
||||
{ variant: 'bare', size: 'sm', class: 'h-full min-h-8 px-3' },
|
||||
{ variant: 'bare', size: 'md', class: 'h-full min-h-9 px-4' },
|
||||
{ variant: 'bare', size: 'lg', class: 'h-full min-h-10 px-4' },
|
||||
],
|
||||
defaultVariants: { size: 'md', variant: 'outlined' },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,104 @@
|
||||
import { booleanAttribute, ChangeDetectionStrategy, Component, computed, input, viewChild } from '@angular/core';
|
||||
import { type MenuItem } from 'primeng/api';
|
||||
import { ContextMenu } from 'primeng/contextmenu';
|
||||
import { TieredMenu } from 'primeng/tieredmenu';
|
||||
import { ptViewMerge } from '../cn';
|
||||
import { type AppMenuSectionItem } from './app-menu.items';
|
||||
import { APP_MENU_SECTION_CLASS, hasMenuStyleClass, menuPanelClass, menuPassThrough } from './menu.pt';
|
||||
|
||||
const isAppMenuSectionItem = (item: MenuItem): item is AppMenuSectionItem =>
|
||||
'appMenuSection' in item && item['appMenuSection'] === true;
|
||||
|
||||
const isSectionLabel = (item: MenuItem): boolean =>
|
||||
isAppMenuSectionItem(item) || hasMenuStyleClass(item.styleClass, APP_MENU_SECTION_CLASS);
|
||||
|
||||
const withStyleClass = (existing: string | undefined, styleClass: string): string => {
|
||||
if (!existing) return styleClass;
|
||||
return hasMenuStyleClass(existing, styleClass) ? existing : `${existing} ${styleClass}`;
|
||||
};
|
||||
|
||||
const withoutIconFields = (item: MenuItem): MenuItem => {
|
||||
const { icon, iconClass, iconStyle, ...rest } = item;
|
||||
void icon;
|
||||
void iconClass;
|
||||
void iconStyle;
|
||||
return rest;
|
||||
};
|
||||
|
||||
const withoutActionFields = (item: MenuItem): MenuItem => {
|
||||
const { command, routerLink, url, ...rest } = item;
|
||||
void command;
|
||||
void routerLink;
|
||||
void url;
|
||||
return rest;
|
||||
};
|
||||
|
||||
const normalizeItem = (item: MenuItem, showItemIcons: boolean): MenuItem => {
|
||||
const itemWithChildren: MenuItem = {
|
||||
...item,
|
||||
...(item.items ? { items: normalizeItems(item.items, showItemIcons) } : {}),
|
||||
};
|
||||
const normalizedItem = showItemIcons ? itemWithChildren : withoutIconFields(itemWithChildren);
|
||||
|
||||
if (isSectionLabel(normalizedItem)) {
|
||||
const sectionItem = withoutActionFields(normalizedItem);
|
||||
|
||||
return {
|
||||
...sectionItem,
|
||||
appMenuSection: true,
|
||||
disabled: true,
|
||||
styleClass: withStyleClass(sectionItem.styleClass, APP_MENU_SECTION_CLASS),
|
||||
};
|
||||
}
|
||||
|
||||
return normalizedItem;
|
||||
};
|
||||
|
||||
const normalizeItems = (items: readonly MenuItem[], showItemIcons: boolean): MenuItem[] =>
|
||||
items.map((item) => normalizeItem(item, showItemIcons));
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu',
|
||||
standalone: true,
|
||||
imports: [TieredMenu, ContextMenu],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
@if (contextTarget(); as target) {
|
||||
<p-contextMenu
|
||||
[unstyled]="true"
|
||||
[target]="target"
|
||||
[model]="primeModel()"
|
||||
[appendTo]="appendTo()"
|
||||
[styleClass]="panelClass"
|
||||
[pt]="pt"
|
||||
[ptOptions]="ptOptions" />
|
||||
} @else {
|
||||
<p-tieredMenu
|
||||
#menu
|
||||
[unstyled]="true"
|
||||
[popup]="true"
|
||||
[model]="primeModel()"
|
||||
[appendTo]="appendTo()"
|
||||
[styleClass]="panelClass"
|
||||
[pt]="pt"
|
||||
[ptOptions]="ptOptions" />
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppMenuComponent {
|
||||
readonly model = input<readonly MenuItem[]>([]);
|
||||
readonly contextTarget = input<HTMLElement | string | undefined>(undefined);
|
||||
readonly appendTo = input<'body' | 'self' | HTMLElement>('body');
|
||||
readonly showItemIcons = input(false, { transform: booleanAttribute });
|
||||
|
||||
private readonly menu = viewChild(TieredMenu);
|
||||
|
||||
protected readonly pt = menuPassThrough;
|
||||
protected readonly ptOptions = { mergeProps: ptViewMerge };
|
||||
protected readonly panelClass = menuPanelClass;
|
||||
protected readonly primeModel = computed(() => normalizeItems(this.model(), this.showItemIcons()));
|
||||
|
||||
toggle(event: Event): void {
|
||||
this.menu()?.toggle(event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { type MenuItem } from 'primeng/api';
|
||||
|
||||
export interface AppMenuSectionItem extends MenuItem {
|
||||
appMenuSection: true;
|
||||
}
|
||||
|
||||
export const appMenuSection = (label: string): AppMenuSectionItem => ({
|
||||
label,
|
||||
appMenuSection: true,
|
||||
});
|
||||
|
||||
export const appMenuSeparator = (): MenuItem => ({
|
||||
separator: true,
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { cn } from '../cn';
|
||||
import {
|
||||
overlayListActiveItemStateClass,
|
||||
overlayListItemContentClass,
|
||||
overlayListItemRowClass,
|
||||
overlayListRootClass,
|
||||
overlayListSectionLabelClass,
|
||||
overlayListSeparatorClass,
|
||||
overlayListShortcutClass,
|
||||
overlayListSurfaceClass,
|
||||
} from '../overlay-list.styles';
|
||||
|
||||
const ptClass = (className: string) => ({ class: className });
|
||||
export const APP_MENU_SECTION_CLASS = 'app-menu-section-label';
|
||||
|
||||
type AppMenuItemVariant = 'destructive';
|
||||
|
||||
interface MenuPtOptions {
|
||||
context?: MenuPtContext;
|
||||
}
|
||||
|
||||
interface MenuPtContext {
|
||||
item?: {
|
||||
styleClass?: string;
|
||||
appMenuSection?: boolean;
|
||||
appMenuVariant?: AppMenuItemVariant;
|
||||
};
|
||||
active?: boolean;
|
||||
focused?: boolean;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const destructiveItemStateClass =
|
||||
'text-danger hover:bg-danger/10 hover:text-danger dark:hover:bg-danger/20';
|
||||
const destructiveActiveItemStateClass = 'bg-danger/10 text-danger dark:bg-danger/20';
|
||||
const menuSurfaceClass = cn('min-w-[8rem]', overlayListSurfaceClass);
|
||||
const menuItemLinkClass = cn(overlayListItemRowClass, 'cursor-pointer');
|
||||
|
||||
export const hasMenuStyleClass = (styleClass: string | undefined, className: string): boolean =>
|
||||
(styleClass ?? '').split(/\s+/).includes(className);
|
||||
|
||||
const hasItemClass = (context: MenuPtContext | undefined, className: string): boolean =>
|
||||
hasMenuStyleClass(context?.item?.styleClass, className);
|
||||
|
||||
const isDestructiveItem = (context: MenuPtContext | undefined): boolean =>
|
||||
context?.item?.appMenuVariant === 'destructive' ||
|
||||
hasItemClass(context, 'destructive') ||
|
||||
hasItemClass(context, 'app-menu-item-destructive');
|
||||
|
||||
const isSectionLabel = (context: MenuPtContext | undefined): boolean =>
|
||||
context?.item?.appMenuSection === true || hasItemClass(context, APP_MENU_SECTION_CLASS);
|
||||
|
||||
const isActiveItem = (context: MenuPtContext | undefined): boolean =>
|
||||
context?.active === true || context?.focused === true;
|
||||
|
||||
export const menuPanelClass = menuSurfaceClass;
|
||||
|
||||
export const menuPassThrough = {
|
||||
rootList: ptClass(overlayListRootClass),
|
||||
item: ({ context }: MenuPtOptions) =>
|
||||
ptClass(cn(
|
||||
'relative',
|
||||
context?.disabled && 'pointer-events-none',
|
||||
context?.disabled && !isSectionLabel(context) && 'opacity-50',
|
||||
)),
|
||||
itemContent: ({ context }: MenuPtOptions) => {
|
||||
if (isSectionLabel(context)) {
|
||||
return ptClass('text-text-muted');
|
||||
}
|
||||
|
||||
const destructive = isDestructiveItem(context);
|
||||
return ptClass(cn(
|
||||
overlayListItemContentClass,
|
||||
destructive && destructiveItemStateClass,
|
||||
isActiveItem(context) && (destructive ? destructiveActiveItemStateClass : overlayListActiveItemStateClass),
|
||||
));
|
||||
},
|
||||
itemLink: ({ context }: MenuPtOptions) =>
|
||||
ptClass(isSectionLabel(context) ? overlayListSectionLabelClass : menuItemLinkClass),
|
||||
itemIcon: ({ context }: MenuPtOptions) =>
|
||||
ptClass(cn(
|
||||
'flex size-4 shrink-0 items-center justify-center text-base text-text-muted',
|
||||
isDestructiveItem(context) && 'text-danger',
|
||||
)),
|
||||
itemLabel: ptClass('truncate leading-5'),
|
||||
itemBadge: ptClass(cn(overlayListShortcutClass, 'leading-5')),
|
||||
submenu: ptClass(cn('absolute z-50 m-0 list-none flex-col', menuSurfaceClass)),
|
||||
submenuIcon: ptClass('ml-auto size-4 shrink-0 text-text-muted'),
|
||||
separator: ptClass(overlayListSeparatorClass),
|
||||
} as const;
|
||||
@@ -0,0 +1,198 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { booleanAttribute, ChangeDetectionStrategy, Component, computed, inject, input, signal } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { type FieldState, type ValidationError } from '@angular/forms/signals';
|
||||
import { TranslocoPipe, TranslocoService } from '@jsverse/transloco';
|
||||
import { AppButtonComponent } from '../button/app-button.component';
|
||||
import { cn } from '../cn';
|
||||
import {
|
||||
APP_FIELD_DEFAULT_ERROR_KEY,
|
||||
appFieldErrorKey,
|
||||
appFieldErrorMessage,
|
||||
type AppFieldLike,
|
||||
} from '../field/app-field.context';
|
||||
import { MESSAGE_ICONS, messageVariants, type MessageColor } from './app-message.variants';
|
||||
|
||||
type SummaryLayout = 'list' | 'inline';
|
||||
|
||||
@Component({
|
||||
selector: 'app-message',
|
||||
standalone: true,
|
||||
imports: [AppButtonComponent, TranslocoPipe],
|
||||
host: {
|
||||
'[class.block]': '!inline()',
|
||||
'[class.inline-block]': 'inline()',
|
||||
'[class.align-middle]': 'inline()',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
@if (visible()) {
|
||||
<div [class]="rootClass()" [attr.role]="role()">
|
||||
<i [class]="iconClass()" aria-hidden="true"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
@if (field() && summary()) {
|
||||
@if (summaryLayout() === 'inline') {
|
||||
@if (hasMultipleSummaryIssues()) {
|
||||
<div class="relative flex min-w-0 items-center gap-2 pr-20 text-current">
|
||||
<span class="min-w-0 flex-1 truncate font-medium text-current">
|
||||
{{ activeIssueMessage() }}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs text-current/80">
|
||||
{{ 'shared.ui.message.issuePosition' | transloco: { current: activeSummaryIndex() + 1, count: summaryCount() } }}
|
||||
</span>
|
||||
<div class="absolute right-0 top-1/2 flex -translate-y-1/2 items-center gap-1">
|
||||
<app-button
|
||||
tone="danger"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
iconOnly
|
||||
icon="pi pi-chevron-up"
|
||||
[ariaLabel]="'shared.ui.message.previousIssue' | transloco"
|
||||
(clicked)="focusAdjacentSummaryIssue(-1)" />
|
||||
<app-button
|
||||
tone="danger"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
iconOnly
|
||||
icon="pi pi-chevron-down"
|
||||
[ariaLabel]="'shared.ui.message.nextIssue' | transloco"
|
||||
(clicked)="focusAdjacentSummaryIssue(1)" />
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
class="block w-full truncate text-left font-medium text-current underline-offset-2 hover:underline focus-visible:rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current"
|
||||
(click)="focusAdjacentSummaryIssue(1)">
|
||||
{{ activeIssueMessage() }}
|
||||
</button>
|
||||
}
|
||||
} @else {
|
||||
<p class="font-medium text-current">
|
||||
{{ 'shared.ui.message.issueCount' | transloco: { count: summaryCount() } }}
|
||||
</p>
|
||||
<ul class="mt-1 flex flex-col gap-0.5">
|
||||
@for (issue of summaryIssues(); track issue) {
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm text-left text-current underline underline-offset-2 hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current"
|
||||
(click)="focusIssue(issue)">
|
||||
{{ issueLabel(issue) }}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
} @else if (field()) {
|
||||
{{ fieldText() }}
|
||||
} @else {
|
||||
<ng-content />
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppMessageComponent {
|
||||
readonly color = input<MessageColor>('neutral');
|
||||
readonly field = input<AppFieldLike | undefined>(undefined);
|
||||
readonly summary = input(false, { transform: booleanAttribute });
|
||||
readonly summaryLayout = input<SummaryLayout>('list');
|
||||
readonly inline = input(false, { transform: booleanAttribute });
|
||||
readonly styleClass = input('');
|
||||
|
||||
private readonly transloco = inject(TranslocoService);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly activeLang = toSignal(this.transloco.langChanges$, { initialValue: this.transloco.getActiveLang() });
|
||||
private readonly summaryIssueIndex = signal(0);
|
||||
|
||||
private readonly fieldState = computed<FieldState<unknown> | null>(() => this.field()?.() ?? null);
|
||||
|
||||
protected readonly fieldMessages = computed<readonly string[]>(() => {
|
||||
this.activeLang();
|
||||
const state = this.fieldState();
|
||||
if (!state || !state.touched()) return [];
|
||||
return state.errors().map(error => appFieldErrorMessage(error, this.translateFallbackError));
|
||||
});
|
||||
protected readonly fieldText = computed(() => this.fieldMessages().join(' '));
|
||||
|
||||
protected readonly summaryIssues = computed<readonly ValidationError.WithFieldTree[]>(() => {
|
||||
const state = this.fieldState();
|
||||
if (!state || !state.touched()) return [];
|
||||
return state.errorSummary();
|
||||
});
|
||||
protected readonly summaryCount = computed(() => this.summaryIssues().length);
|
||||
protected readonly activeSummaryIndex = computed(() => {
|
||||
const count = this.summaryCount();
|
||||
if (count === 0) return 0;
|
||||
return Math.min(this.summaryIssueIndex(), count - 1);
|
||||
});
|
||||
protected readonly hasMultipleSummaryIssues = computed(() => this.summaryCount() > 1);
|
||||
protected readonly activeIssueMessage = computed(() => {
|
||||
this.activeLang();
|
||||
const issue = this.summaryIssues()[this.activeSummaryIndex()];
|
||||
return issue ? appFieldErrorMessage(issue, this.translateFallbackError) : '';
|
||||
});
|
||||
|
||||
protected readonly visible = computed(() => {
|
||||
if (!this.field()) return true;
|
||||
return this.summary() ? this.summaryCount() > 0 : this.fieldMessages().length > 0;
|
||||
});
|
||||
protected readonly resolvedColor = computed<MessageColor>(() => (this.field() ? 'red' : this.color()));
|
||||
protected readonly role = computed(() => (this.resolvedColor() === 'red' ? 'alert' : 'status'));
|
||||
protected readonly iconClass = computed(() =>
|
||||
cn(MESSAGE_ICONS[this.resolvedColor()], 'mt-0.5 shrink-0 text-[1.05em] leading-none'),
|
||||
);
|
||||
protected readonly rootClass = computed(() =>
|
||||
cn(messageVariants({ color: this.resolvedColor() }), this.inline() && 'inline-flex align-middle', this.styleClass()),
|
||||
);
|
||||
|
||||
protected issueLabel(issue: ValidationError): string {
|
||||
this.activeLang();
|
||||
return appFieldErrorMessage(issue, this.translateFallbackError);
|
||||
}
|
||||
|
||||
protected focusIssue(issue: ValidationError.WithFieldTree): void {
|
||||
this.focusAndReveal(issue);
|
||||
}
|
||||
|
||||
protected focusAdjacentSummaryIssue(direction: 1 | -1): void {
|
||||
const count = this.summaryCount();
|
||||
if (count === 0) return;
|
||||
|
||||
const nextIndex = (this.activeSummaryIndex() + direction + count) % count;
|
||||
this.summaryIssueIndex.set(nextIndex);
|
||||
const issue = this.summaryIssues()[nextIndex];
|
||||
if (issue) this.focusAndReveal(issue);
|
||||
}
|
||||
|
||||
private focusAndReveal(issue: ValidationError.WithFieldTree): void {
|
||||
issue.fieldTree().focusBoundControl();
|
||||
const field = (this.document.activeElement as HTMLElement | null)?.closest<HTMLElement>('app-field') ?? null;
|
||||
if (!field) return;
|
||||
|
||||
field.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
|
||||
const highlightColor = 'color-mix(in srgb, var(--color-danger) 12%, transparent)';
|
||||
const highlightShadow = `0 0 0 6px ${highlightColor}`;
|
||||
field.animate?.(
|
||||
[
|
||||
{ borderRadius: '0.25rem', backgroundColor: highlightColor, boxShadow: highlightShadow },
|
||||
{
|
||||
borderRadius: '0.25rem',
|
||||
backgroundColor: highlightColor,
|
||||
boxShadow: highlightShadow,
|
||||
offset: 0.45,
|
||||
},
|
||||
{ borderRadius: '0.25rem', backgroundColor: 'transparent', boxShadow: '0 0 0 6px transparent' },
|
||||
],
|
||||
{ duration: 1400, easing: 'ease-out' },
|
||||
);
|
||||
}
|
||||
|
||||
private readonly translateFallbackError = (kind: string): string => {
|
||||
const key = appFieldErrorKey(kind);
|
||||
const translated = this.transloco.translate(key);
|
||||
return translated === key ? this.transloco.translate(APP_FIELD_DEFAULT_ERROR_KEY) : translated;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export type MessageColor = 'neutral' | 'primary' | 'green' | 'amber' | 'red';
|
||||
|
||||
export const messageVariants = cva('flex min-h-9 items-center gap-2 rounded-md border px-3 py-1.5 text-sm', {
|
||||
variants: {
|
||||
color: {
|
||||
neutral: `bg-card text-text-strong ${neutralControlBorderClass}`,
|
||||
primary: 'bg-primary/10 text-primary-text border-primary/15 dark:border-primary/30',
|
||||
green: 'bg-green-500/10 text-green-600 border-green-600/15 dark:text-green-400 dark:border-green-500/30',
|
||||
amber: 'bg-amber-500/10 text-amber-600 border-amber-600/15 dark:text-amber-400 dark:border-amber-500/30',
|
||||
red: 'bg-red-500/10 text-red-600 border-red-500/15 dark:text-red-400 dark:border-red-500/30',
|
||||
},
|
||||
},
|
||||
defaultVariants: { color: 'neutral' },
|
||||
});
|
||||
|
||||
export const MESSAGE_ICONS: Record<MessageColor, string> = {
|
||||
neutral: 'pi pi-info-circle',
|
||||
primary: 'pi pi-info-circle',
|
||||
green: 'pi pi-check-circle',
|
||||
amber: 'pi pi-exclamation-triangle',
|
||||
red: 'pi pi-exclamation-circle',
|
||||
};
|
||||
@@ -0,0 +1,187 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
numberAttribute,
|
||||
type ElementRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { transformedValue, type FormValueControl, type ParseResult } from '@angular/forms/signals';
|
||||
|
||||
import { cn } from '../cn';
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
import { appInputVariants, type AppInputSize } from '../input/app-input.variants';
|
||||
|
||||
@Component({
|
||||
selector: 'app-number-input',
|
||||
standalone: true,
|
||||
host: { class: 'relative block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<input
|
||||
#input
|
||||
[class]="inputClass()"
|
||||
type="number"
|
||||
inputmode="decimal"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.placeholder]="placeholder() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.min]="min()"
|
||||
[attr.max]="max()"
|
||||
[attr.step]="normalizedStep()"
|
||||
[value]="rawValue()"
|
||||
[disabled]="disabled()"
|
||||
[readonly]="readonly()"
|
||||
[required]="required()"
|
||||
(input)="onInput(input)"
|
||||
(blur)="touched.set(true)" />
|
||||
|
||||
@if (unit() || !readonly()) {
|
||||
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-stretch">
|
||||
@if (unit()) {
|
||||
<span class="flex select-none items-center pr-3 text-xs text-text-muted">{{ unit() }}</span>
|
||||
}
|
||||
@if (!readonly()) {
|
||||
<span
|
||||
class="pointer-events-auto my-px mr-px flex w-8 flex-col overflow-hidden rounded-r-[0.3rem] border-l border-border">
|
||||
<button
|
||||
type="button"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
[class]="stepButtonClass"
|
||||
[disabled]="disabled() || atMax()"
|
||||
(click)="nudge(1)">
|
||||
<i class="pi pi-chevron-up text-xs leading-none" aria-hidden="true"></i>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
[class]="stepButtonClass + ' border-t border-border'"
|
||||
[disabled]="disabled() || atMin()"
|
||||
(click)="nudge(-1)">
|
||||
<i class="pi pi-chevron-down text-xs leading-none" aria-hidden="true"></i>
|
||||
</button>
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppNumberInputComponent implements FormValueControl<number | null> {
|
||||
readonly value = model<number | null>(null);
|
||||
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 touched = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly size = input<AppInputSize>('md');
|
||||
readonly min = input<number | undefined>(undefined);
|
||||
readonly max = input<number | undefined>(undefined);
|
||||
readonly step = input(1, { transform: numberAttribute });
|
||||
readonly unit = input('');
|
||||
readonly inputId = input('');
|
||||
readonly placeholder = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
readonly styleClass = input('');
|
||||
readonly readonly = input(false, { transform: booleanAttribute });
|
||||
|
||||
protected readonly rawValue = transformedValue(this.value, {
|
||||
parse: parseNumberInput,
|
||||
format: value => value?.toString() ?? '',
|
||||
});
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
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 normalizedStep = computed(() => {
|
||||
const step = this.step();
|
||||
return Number.isFinite(step) && step > 0 ? step : 1;
|
||||
});
|
||||
|
||||
protected readonly atMax = computed(() => {
|
||||
const max = this.max();
|
||||
const value = this.value();
|
||||
return max != null && value != null && value >= max;
|
||||
});
|
||||
protected readonly atMin = computed(() => {
|
||||
const min = this.min();
|
||||
const value = this.value();
|
||||
return min != null && value != null && value <= min;
|
||||
});
|
||||
|
||||
protected readonly stepButtonClass =
|
||||
'flex flex-1 items-center justify-center text-text-muted transition-colors ' +
|
||||
'hover:bg-surface-hover hover:text-text-strong ' +
|
||||
'active:bg-[color-mix(in_srgb,var(--color-text)_14%,transparent)] active:text-text-strong ' +
|
||||
'disabled:pointer-events-none disabled:opacity-40';
|
||||
|
||||
protected readonly inputPaddingClass = computed(() => {
|
||||
if (this.unit()) return 'pr-16';
|
||||
return this.readonly() ? '' : 'pr-9';
|
||||
});
|
||||
protected readonly inputClass = computed(() =>
|
||||
cn(
|
||||
appInputVariants({ size: this.size() }),
|
||||
'[appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none',
|
||||
this.inputPaddingClass(),
|
||||
this.styleClass(),
|
||||
),
|
||||
);
|
||||
|
||||
private readonly input = viewChild<ElementRef<HTMLInputElement>>('input');
|
||||
|
||||
protected onInput(input: HTMLInputElement): void {
|
||||
if (this.disabled() || this.readonly()) {
|
||||
input.value = this.rawValue();
|
||||
return;
|
||||
}
|
||||
this.rawValue.set(input.value);
|
||||
}
|
||||
|
||||
protected nudge(direction: 1 | -1): void {
|
||||
const base = this.value() ?? this.min() ?? 0;
|
||||
this.value.set(this.roundToStep(this.clamp(base + direction * this.normalizedStep())));
|
||||
}
|
||||
|
||||
private clamp(n: number): number {
|
||||
const min = this.min();
|
||||
const max = this.max();
|
||||
if (min != null && n < min) return min;
|
||||
if (max != null && n > max) return max;
|
||||
return n;
|
||||
}
|
||||
|
||||
private roundToStep(n: number): number {
|
||||
const decimals = (String(this.normalizedStep()).split('.')[1] ?? '').length;
|
||||
return decimals ? Number(n.toFixed(decimals)) : n;
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.input()?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
|
||||
function parseNumberInput(raw: string): ParseResult<number | null> {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed === '') return { value: null };
|
||||
|
||||
const parsed = Number(trimmed);
|
||||
if (!Number.isFinite(parsed)) return { error: { kind: 'parse' } };
|
||||
|
||||
return { value: parsed };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { cn } from './cn';
|
||||
|
||||
export const overlayListSurfaceClass =
|
||||
'z-50 overflow-visible rounded-md border border-border bg-card p-1 text-text shadow-pop';
|
||||
export const overlayListRootClass = 'm-0 flex list-none flex-col p-0 outline-none';
|
||||
|
||||
const overlayListItemStateClass = 'hover:bg-surface-hover hover:text-text-strong';
|
||||
export const overlayListActiveItemStateClass = 'bg-surface-hover text-text-strong';
|
||||
export const overlayListItemRowClass =
|
||||
'flex h-7 w-full select-none items-center gap-2 px-2 py-0 text-sm leading-5 text-inherit no-underline outline-hidden';
|
||||
export const overlayListItemContentClass = cn(
|
||||
'rounded-sm text-text',
|
||||
overlayListItemStateClass,
|
||||
);
|
||||
export const overlayListOptionClass = cn(
|
||||
overlayListItemRowClass,
|
||||
'cursor-pointer rounded-sm text-text',
|
||||
overlayListItemStateClass,
|
||||
'aria-disabled:pointer-events-none aria-disabled:opacity-50',
|
||||
);
|
||||
export const overlayListEmptyItemClass = 'flex h-7 items-center px-2 text-sm leading-5 text-text-muted';
|
||||
|
||||
export const overlayListSectionLabelClass =
|
||||
'flex h-5 w-full cursor-default select-none items-center px-2 py-0 text-xs font-semibold leading-5 text-inherit no-underline outline-hidden';
|
||||
|
||||
export const overlayListSeparatorClass = '-mx-1 my-0.5 h-px bg-border';
|
||||
export const overlayListShortcutClass = 'ml-auto text-xs tracking-widest text-text-muted';
|
||||
@@ -0,0 +1,155 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
type ElementRef,
|
||||
viewChildren,
|
||||
} from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
import { cn } from '../cn';
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
import {
|
||||
appRadioGroupDotVariants,
|
||||
appRadioGroupOptionVariants,
|
||||
appRadioGroupRootVariants,
|
||||
appRadioGroupSegmentClass,
|
||||
type AppRadioGroupSize,
|
||||
type AppRadioGroupVariant,
|
||||
} from './app-radio-group.variants';
|
||||
|
||||
export interface RadioOption<T> {
|
||||
readonly value: T;
|
||||
readonly label: string;
|
||||
readonly description?: string;
|
||||
readonly disabled?: boolean;
|
||||
}
|
||||
|
||||
const defaultCompareWith = <T>(optionValue: T, selectedValue: T): boolean => Object.is(optionValue, selectedValue);
|
||||
let nextGroupId = 0;
|
||||
|
||||
@Component({
|
||||
selector: 'app-radio-group',
|
||||
standalone: true,
|
||||
host: { class: 'block' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<div
|
||||
role="radiogroup"
|
||||
[class]="rootClass()"
|
||||
[attr.id]="resolvedGroupId()"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-labelledby]="resolvedLabelledBy()"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null">
|
||||
@for (option of options(); track option.value; let i = $index) {
|
||||
<label [class]="variant() === 'segmented' ? segmentClass(i) : optionClass()">
|
||||
<input
|
||||
#radio
|
||||
type="radio"
|
||||
class="peer sr-only"
|
||||
[name]="groupName()"
|
||||
[checked]="isSelected(option)"
|
||||
[disabled]="isUnavailable() || option.disabled === true"
|
||||
[required]="required()"
|
||||
(change)="onSelect(option)"
|
||||
(blur)="touched.set(true)" />
|
||||
@if (variant() === 'segmented') {
|
||||
<span class="truncate leading-none">{{ option.label }}</span>
|
||||
} @else {
|
||||
<span [class]="dotClass()" aria-hidden="true"></span>
|
||||
<span [class]="textBlockClass()">
|
||||
<span class="font-medium leading-5">{{ option.label }}</span>
|
||||
@if (option.description) {
|
||||
<span class="text-xs text-text-muted dark:text-text-secondary">{{ option.description }}</span>
|
||||
}
|
||||
</span>
|
||||
}
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppRadioGroupComponent<T> implements FormValueControl<T | null> {
|
||||
readonly value = model<T | null>(null);
|
||||
readonly disabled = input(false, { transform: booleanAttribute });
|
||||
readonly invalid = input(false, { transform: booleanAttribute });
|
||||
readonly pending = input(false, { transform: booleanAttribute });
|
||||
readonly required = input(false, { transform: booleanAttribute });
|
||||
readonly readonly = input(false, { transform: booleanAttribute });
|
||||
readonly touched = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly options = input<readonly RadioOption<T>[]>([]);
|
||||
readonly variant = input<AppRadioGroupVariant>('list');
|
||||
readonly size = input<AppRadioGroupSize>('md');
|
||||
readonly groupId = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaLabelledBy = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
readonly styleClass = input('');
|
||||
readonly compareWith = input<(optionValue: T, selectedValue: T) => boolean>(defaultCompareWith);
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
private readonly autoName = `app-radio-group-${++nextGroupId}`;
|
||||
private readonly radios = viewChildren<ElementRef<HTMLInputElement>>('radio');
|
||||
|
||||
protected readonly groupName = computed(() => this.name() || this.autoName);
|
||||
protected readonly resolvedGroupId = computed(() => this.groupId() || this.fieldContext?.controlId() || null);
|
||||
protected readonly resolvedLabelledBy = computed(
|
||||
() => this.ariaLabelledBy() || this.fieldContext?.labelId() || 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 rootClass = computed(() =>
|
||||
cn(appRadioGroupRootVariants({ variant: this.variant() }), this.styleClass()),
|
||||
);
|
||||
protected readonly optionClass = computed(() =>
|
||||
appRadioGroupOptionVariants({ variant: this.variant(), size: this.size() }),
|
||||
);
|
||||
protected readonly dotClass = computed(() =>
|
||||
appRadioGroupDotVariants({ size: this.size(), variant: this.variant() }),
|
||||
);
|
||||
protected readonly textBlockClass = computed(() =>
|
||||
cn(
|
||||
'flex min-w-0 flex-col gap-0.5 text-text-strong',
|
||||
this.variant() === 'card' && 'peer-checked:text-primary-text',
|
||||
),
|
||||
);
|
||||
|
||||
protected isSelected(option: RadioOption<T>): boolean {
|
||||
const value = this.value();
|
||||
return value != null && this.compareWith()(option.value, value);
|
||||
}
|
||||
|
||||
protected segmentClass(index: number): string {
|
||||
const options = this.options();
|
||||
const value = this.value();
|
||||
const option = options[index];
|
||||
return appRadioGroupSegmentClass({
|
||||
size: this.size(),
|
||||
selected: value != null && option != null && this.compareWith()(option.value, value),
|
||||
first: index === 0,
|
||||
last: index === options.length - 1,
|
||||
});
|
||||
}
|
||||
|
||||
protected onSelect(option: RadioOption<T>): void {
|
||||
this.value.set(option.value);
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
const optionIndex = this.options().findIndex(option => this.isSelected(option) && !option.disabled);
|
||||
const fallbackIndex = this.options().findIndex(option => !option.disabled);
|
||||
this.radios()[optionIndex >= 0 ? optionIndex : fallbackIndex]?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { buttonVariants } from '../button/app-button.variants';
|
||||
import { cn } from '../cn';
|
||||
import { connectedGroupClass, connectedItemClass } from '../connected-group';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export type AppRadioGroupVariant = 'list' | 'card' | 'segmented';
|
||||
export type AppRadioGroupSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
export const appRadioGroupRootVariants = cva('', {
|
||||
variants: {
|
||||
variant: {
|
||||
list: 'flex flex-col gap-2',
|
||||
card: 'flex flex-col gap-2',
|
||||
segmented: cn(connectedGroupClass, 'items-stretch'),
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'list' },
|
||||
});
|
||||
|
||||
const cardOption =
|
||||
'flex-row-reverse items-center justify-between gap-3 rounded-lg border ' +
|
||||
`${neutralControlBorderClass} ` +
|
||||
'bg-card px-4 py-3 shadow-control outline-hidden transition-[background-color,border-color] duration-150 ' +
|
||||
'has-[input:checked]:border-primary/15 has-[input:checked]:bg-primary/10 dark:has-[input:checked]:border-primary/30 ' +
|
||||
'has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-primary';
|
||||
|
||||
interface AppRadioGroupSegmentState {
|
||||
size: AppRadioGroupSize;
|
||||
selected: boolean;
|
||||
first: boolean;
|
||||
last: boolean;
|
||||
}
|
||||
|
||||
export function appRadioGroupSegmentClass(state: AppRadioGroupSegmentState): string {
|
||||
return cn(
|
||||
buttonVariants({ tone: state.selected ? 'primary' : 'neutral', variant: 'soft', size: state.size }),
|
||||
connectedItemClass({ first: state.first, last: state.last }),
|
||||
state.selected && 'app-cg-active',
|
||||
'outline-hidden',
|
||||
'has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50',
|
||||
'has-[input:focus-visible]:z-10 has-[input:focus-visible]:outline-2',
|
||||
'has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-primary',
|
||||
);
|
||||
}
|
||||
|
||||
export const appRadioGroupOptionVariants = cva(
|
||||
'relative flex cursor-pointer has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
list: 'items-start gap-2.5',
|
||||
card: cardOption,
|
||||
segmented: '',
|
||||
},
|
||||
size: {
|
||||
sm: 'text-xs',
|
||||
md: 'text-sm',
|
||||
lg: 'text-sm',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'list', size: 'md' },
|
||||
},
|
||||
);
|
||||
|
||||
const dotBase =
|
||||
'relative flex shrink-0 items-center justify-center rounded-full border bg-card shadow-control ' +
|
||||
`${neutralControlBorderClass} ` +
|
||||
'transition-[background-color,border-color] duration-150 ' +
|
||||
'peer-checked:border-transparent peer-checked:bg-primary ' +
|
||||
"before:content-[''] before:rounded-full before:bg-primary-contrast before:opacity-0 before:transition-opacity before:duration-150 " +
|
||||
'peer-checked:before:opacity-100';
|
||||
|
||||
export const appRadioGroupDotVariants = cva(dotBase, {
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'size-3.5 before:size-1',
|
||||
md: 'size-4 before:size-1.5',
|
||||
lg: 'size-5 before:size-2',
|
||||
},
|
||||
variant: {
|
||||
list:
|
||||
'peer-focus-visible:border-primary/60 peer-focus-visible:outline-1 ' +
|
||||
'peer-focus-visible:outline-offset-0 peer-focus-visible:outline-primary/60',
|
||||
card: '',
|
||||
segmented: '',
|
||||
},
|
||||
},
|
||||
compoundVariants: [
|
||||
{ variant: 'list', size: 'sm', class: 'mt-px' },
|
||||
{ variant: 'list', size: ['md', 'lg'], class: 'mt-0.5' },
|
||||
],
|
||||
defaultVariants: { size: 'md', variant: 'list' },
|
||||
});
|
||||
@@ -0,0 +1,320 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
numberAttribute,
|
||||
signal,
|
||||
type ElementRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
import { TranslocoPipe, translateSignal } from '@jsverse/transloco';
|
||||
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
|
||||
const STAR_PATH =
|
||||
'M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005Z';
|
||||
|
||||
const STAR_SIZES: Record<'sm' | 'md' | 'lg', string> = { sm: '14px', md: '18px', lg: '22px' };
|
||||
|
||||
interface Star {
|
||||
readonly value: number;
|
||||
readonly fill: number;
|
||||
readonly hidden: boolean;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-rating',
|
||||
standalone: true,
|
||||
imports: [TranslocoPipe],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: { class: 'inline-flex' },
|
||||
template: `
|
||||
@if (readonly()) {
|
||||
<span
|
||||
#readonlyRoot
|
||||
class="rating"
|
||||
role="img"
|
||||
tabindex="-1"
|
||||
[attr.aria-label]="readonlyLabel()"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[class.opacity-50]="disabled()"
|
||||
[style.--star-size]="starSize()">
|
||||
@for (star of starList(); track $index) {
|
||||
<span class="star" [style.--fill]="star.fill + '%'">
|
||||
<svg class="star-base" viewBox="0 0 24 24" aria-hidden="true"><path [attr.d]="path" /></svg>
|
||||
<svg class="star-fill fill-amber-400 dark:fill-yellow-400" viewBox="0 0 24 24" aria-hidden="true"><path [attr.d]="path" /></svg>
|
||||
</span>
|
||||
}
|
||||
@if (showValue() && value() > 0) {
|
||||
<span class="rating-label">{{ valueLabel() }}</span>
|
||||
}
|
||||
@if (pending()) {
|
||||
<i class="pi pi-spinner pi-spin ml-1 text-xs text-text-muted" aria-hidden="true"></i>
|
||||
}
|
||||
</span>
|
||||
} @else {
|
||||
<div
|
||||
class="rating editable"
|
||||
[class.expandable]="expandable()"
|
||||
[class.expanded]="isExpanded()"
|
||||
[class.opacity-50]="disabled()"
|
||||
[style.--star-size]="starSize()"
|
||||
(mouseenter)="onEnter()"
|
||||
(mouseleave)="onLeave()">
|
||||
<input
|
||||
#input
|
||||
type="range"
|
||||
class="range"
|
||||
min="0"
|
||||
[max]="stars()"
|
||||
[step]="step()"
|
||||
[value]="value()"
|
||||
[disabled]="disabled()"
|
||||
[required]="required()"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.aria-valuetext]="valueText()"
|
||||
(input)="onRange(input.value)"
|
||||
(change)="touched.set(true)" />
|
||||
@for (star of starList(); track $index) {
|
||||
<button
|
||||
type="button"
|
||||
class="star"
|
||||
tabindex="-1"
|
||||
[attr.aria-label]="'shared.ui.rating.setRatingTo' | transloco: { rating: formatRating(star.value), max: stars() }"
|
||||
[class.hidden-star]="star.hidden"
|
||||
[style.--fill]="star.fill + '%'"
|
||||
[disabled]="disabled()"
|
||||
(mouseenter)="onStarHover(star.value)"
|
||||
(click)="onStarClick(star.value)">
|
||||
<svg class="star-base" viewBox="0 0 24 24" aria-hidden="true"><path [attr.d]="path" /></svg>
|
||||
<svg class="star-fill fill-amber-400 dark:fill-yellow-400" viewBox="0 0 24 24" aria-hidden="true"><path [attr.d]="path" /></svg>
|
||||
</button>
|
||||
}
|
||||
@if (expandable()) {
|
||||
<span class="rating-label">{{ expandableLabel() }}</span>
|
||||
} @else if (showValue() && value() > 0) {
|
||||
<span class="rating-label">{{ valueLabel() }}</span>
|
||||
}
|
||||
@if (pending()) {
|
||||
<i class="pi pi-spinner pi-spin ml-1 text-xs text-text-muted" aria-hidden="true"></i>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
.rating {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
line-height: 0;
|
||||
}
|
||||
.editable:has(.range:focus-visible) {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 3px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.star {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
width: var(--star-size);
|
||||
height: var(--star-size);
|
||||
line-height: 0;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
button.star {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
}
|
||||
.editable .star:not(.hidden-star):not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
.star svg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
}
|
||||
.star-base {
|
||||
fill: var(--color-surface-hover);
|
||||
}
|
||||
.star-fill {
|
||||
clip-path: inset(0 calc(100% - var(--fill, 0%)) 0 0);
|
||||
}
|
||||
.expandable .star {
|
||||
overflow: hidden;
|
||||
transition: width 0.2s ease, margin-left 0.2s ease, opacity 0.2s ease;
|
||||
}
|
||||
.expandable .star svg {
|
||||
width: var(--star-size);
|
||||
}
|
||||
.hidden-star {
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.range {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.rating-label {
|
||||
margin-left: 6px;
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--color-text-muted);
|
||||
white-space: nowrap;
|
||||
line-height: 1;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppRatingComponent implements FormValueControl<number> {
|
||||
readonly value = model(0);
|
||||
readonly stars = input(5, { transform: numberAttribute });
|
||||
readonly readonly = input(false, { transform: booleanAttribute });
|
||||
readonly expandable = input(false, { transform: booleanAttribute });
|
||||
readonly showValue = input(false, { transform: booleanAttribute });
|
||||
readonly size = input<'sm' | 'md' | 'lg'>('md');
|
||||
|
||||
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 touched = model(false);
|
||||
readonly name = input('');
|
||||
readonly inputId = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
|
||||
protected readonly path = STAR_PATH;
|
||||
protected readonly formatRating = formatRating;
|
||||
protected readonly starSize = computed(() => STAR_SIZES[this.size()]);
|
||||
protected readonly step = computed(() => (this.expandable() ? 0.5 : 1));
|
||||
|
||||
private readonly expanded = signal(false);
|
||||
private readonly hoverValue = signal<number | null>(null);
|
||||
protected readonly isExpanded = computed(() => this.expandable() && this.expanded());
|
||||
protected readonly preview = computed(() => this.hoverValue() ?? this.value());
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
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));
|
||||
|
||||
private readonly input = viewChild<ElementRef<HTMLInputElement>>('input');
|
||||
private readonly readonlyRoot = viewChild<ElementRef<HTMLElement>>('readonlyRoot');
|
||||
|
||||
protected readonly starList = computed<Star[]>(() => {
|
||||
const count = this.stars();
|
||||
const preview = this.preview();
|
||||
|
||||
if (this.expandable()) {
|
||||
const expanded = this.isExpanded();
|
||||
return Array.from({ length: count * 2 }, (_, i): Star => {
|
||||
const pos = i + 1;
|
||||
if (expanded) {
|
||||
return { value: pos / 2, fill: preview * 2 >= pos ? 100 : 0, hidden: false };
|
||||
}
|
||||
if (pos > count) return { value: pos / 2, fill: 0, hidden: true };
|
||||
return { value: pos, fill: clampFill(preview - (pos - 1)), hidden: false };
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from({ length: count }, (_, i): Star => {
|
||||
const pos = i + 1;
|
||||
const fill = this.readonly() ? clampFill(preview - i) : preview >= pos ? 100 : 0;
|
||||
return { value: pos, fill, hidden: false };
|
||||
});
|
||||
});
|
||||
|
||||
protected readonly valueLabel = computed(() => `${formatRating(this.value())} / ${this.stars()}`);
|
||||
private readonly valueTextParams = computed(() => ({ rating: formatRating(this.value()), max: this.stars() }));
|
||||
protected readonly valueText = translateSignal('shared.ui.rating.valueText', this.valueTextParams);
|
||||
|
||||
protected readonly readonlyLabel = computed(() => this.ariaLabel() || this.valueText());
|
||||
|
||||
protected readonly expandableLabel = computed(() => {
|
||||
const preview = this.preview();
|
||||
if (this.isExpanded()) return `(${preview * 2} / ${this.stars() * 2})`;
|
||||
return preview > 0 ? `(${formatRating(preview)} / ${this.stars()})` : '';
|
||||
});
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
(this.input()?.nativeElement ?? this.readonlyRoot()?.nativeElement)?.focus(options);
|
||||
}
|
||||
|
||||
protected onRange(raw: string): void {
|
||||
if (raw.trim() === '') return;
|
||||
|
||||
const nextValue = Number(raw);
|
||||
if (!Number.isFinite(nextValue)) return;
|
||||
|
||||
this.value.set(Math.max(0, Math.min(this.stars(), nextValue)));
|
||||
}
|
||||
|
||||
protected onEnter(): void {
|
||||
if (this.expandable() && !this.disabled()) this.expanded.set(true);
|
||||
}
|
||||
|
||||
protected onLeave(): void {
|
||||
if (!this.expandable()) return;
|
||||
this.expanded.set(false);
|
||||
this.hoverValue.set(null);
|
||||
}
|
||||
|
||||
protected onStarHover(value: number): void {
|
||||
if (this.disabled()) return;
|
||||
if (this.expandable() && !this.isExpanded()) return;
|
||||
this.hoverValue.set(value);
|
||||
}
|
||||
|
||||
protected onStarClick(value: number): void {
|
||||
if (this.disabled()) return;
|
||||
this.touched.set(true);
|
||||
|
||||
if (this.expandable() && !this.isExpanded()) {
|
||||
this.expanded.set(true);
|
||||
return;
|
||||
}
|
||||
|
||||
this.value.set(this.value() === value ? 0 : value);
|
||||
|
||||
if (this.expandable()) {
|
||||
this.expanded.set(false);
|
||||
this.hoverValue.set(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function clampFill(units: number): number {
|
||||
return Math.round(Math.max(0, Math.min(1, units)) * 100);
|
||||
}
|
||||
|
||||
function formatRating(value: number): string {
|
||||
return Number.isInteger(value) ? `${value}` : value.toFixed(1);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
model,
|
||||
} 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, translateSignal } from '@jsverse/transloco';
|
||||
|
||||
import { cn } from '../cn';
|
||||
import { AppSelectBaseDirective } from './app-select-base.directive';
|
||||
import { type SelectOption } from './app-select.options';
|
||||
|
||||
@Component({
|
||||
selector: 'app-multi-select',
|
||||
standalone: true,
|
||||
imports: [
|
||||
NgTemplateOutlet,
|
||||
OverlayModule,
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxPopupContainer,
|
||||
Listbox,
|
||||
Option,
|
||||
TranslocoPipe,
|
||||
],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<div ngCombobox #cb="ngCombobox" [readonly]="true" [disabled]="disabled()" class="relative block h-full w-full">
|
||||
<div
|
||||
#origin
|
||||
[class]="triggerClass()"
|
||||
[attr.data-expanded]="cb.expanded() ? 'true' : null">
|
||||
<input
|
||||
ngComboboxInput
|
||||
#input
|
||||
readonly
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
[value]="triggerLabel()"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-labelledby]="ariaLabelledBy() || null"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[disabled]="disabled()"
|
||||
[required]="required()"
|
||||
(keydown)="onTriggerKeydown($event)"
|
||||
(blur)="onTriggerBlur($event)"
|
||||
class="absolute inset-0 z-10 h-full w-full cursor-pointer rounded-md border-0 bg-transparent p-0 text-transparent caret-transparent outline-hidden disabled:cursor-default" />
|
||||
|
||||
<span aria-hidden="true" [class]="labelClass()" [class.text-text-muted]="!hasSelection()">
|
||||
{{ triggerLabel() }}
|
||||
</span>
|
||||
|
||||
@if (showClear() && hasSelection() && !isUnavailable()) {
|
||||
<button
|
||||
type="button"
|
||||
[attr.aria-label]="'shared.ui.select.clearSelection' | transloco"
|
||||
class="relative z-20 flex h-full shrink-0 items-center justify-center border-0 bg-transparent p-0 text-text-muted transition-colors hover:text-text-strong"
|
||||
[class.w-9]="variant() !== 'bare'"
|
||||
[class.w-7]="variant() === 'bare'"
|
||||
(click)="clear($event)">
|
||||
<i class="pi pi-times text-xs" aria-hidden="true"></i>
|
||||
</button>
|
||||
}
|
||||
|
||||
<span
|
||||
class="flex h-full shrink-0 items-center justify-center text-text-muted"
|
||||
[class.w-9]="variant() !== 'bare'"
|
||||
[class.w-7]="variant() === 'bare'">
|
||||
@if (pending()) {
|
||||
<i class="pi pi-spinner pi-spin text-xs" aria-hidden="true"></i>
|
||||
} @else {
|
||||
<i class="pi pi-chevron-down text-xs transition-transform" [class.rotate-180]="cb.expanded()" aria-hidden="true"></i>
|
||||
}
|
||||
</span>
|
||||
</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">
|
||||
@if (filter()) {
|
||||
<div class="flex h-9 items-center border-b border-border pl-3 pr-2 text-text-muted">
|
||||
<input
|
||||
#filterInput
|
||||
type="text"
|
||||
[value]="filterText()"
|
||||
(input)="filterText.set(filterInput.value)"
|
||||
(keydown)="onFilterKeydown($event)"
|
||||
[placeholder]="filterPlaceholder() || ('shared.ui.select.search' | transloco)"
|
||||
[readonly]="readonly()"
|
||||
class="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" />
|
||||
<i class="pi pi-search shrink-0 text-xs" aria-hidden="true"></i>
|
||||
</div>
|
||||
}
|
||||
|
||||
<ul
|
||||
ngListbox
|
||||
tabindex="-1"
|
||||
focusMode="activedescendant"
|
||||
selectionMode="explicit"
|
||||
[multi]="true"
|
||||
[values]="listboxValues()"
|
||||
[readonly]="readonly()"
|
||||
[disabled]="disabled()"
|
||||
(valuesChange)="onValuesChange($event)"
|
||||
[class]="listClass()">
|
||||
@for (grp of renderedGroups(); track grp.trackKey; let first = $first) {
|
||||
@if (grouped()) {
|
||||
@if (!first) {
|
||||
<li role="separator" [class]="separatorClass"></li>
|
||||
}
|
||||
<li role="presentation" [class]="sectionClass">{{ grp.label }}</li>
|
||||
}
|
||||
@for (option of grp.options; track option) {
|
||||
<li
|
||||
ngOption
|
||||
tabindex="-1"
|
||||
[value]="option.value"
|
||||
[label]="option.label"
|
||||
[disabled]="option.disabled === true"
|
||||
[class]="optionClass">
|
||||
<span [class]="checkboxClass(isSelected(option))">
|
||||
@if (isSelected(option)) { <i class="pi pi-check text-[0.625rem] text-white" aria-hidden="true"></i> }
|
||||
</span>
|
||||
@if (optionTemplate(); as tpl) {
|
||||
<ng-container [ngTemplateOutlet]="tpl.template" [ngTemplateOutletContext]="{ $implicit: option }" />
|
||||
} @else {
|
||||
<span class="truncate leading-5">{{ option.label }}</span>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
} @empty {
|
||||
<li [class]="emptyClass">{{ emptyMessage() || ('shared.ui.select.noResults' | transloco) }}</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ng-template>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppMultiSelectComponent<T> extends AppSelectBaseDirective<T> implements FormValueControl<T[]> {
|
||||
readonly value = model<T[]>([]);
|
||||
|
||||
private readonly selectedCount = computed(() => this.value().length);
|
||||
private readonly selectedCountParam = computed(() => String(this.selectedCount()));
|
||||
private readonly selectedCountLabel = translateSignal('shared.ui.select.selectedCount', {
|
||||
count: this.selectedCountParam,
|
||||
});
|
||||
|
||||
protected override readonly hasSelection = computed(() => this.selectedCount() > 0);
|
||||
|
||||
protected override readonly triggerLabel = computed(() =>
|
||||
this.selectedCount() ? this.selectedCountLabel() : this.placeholder(),
|
||||
);
|
||||
|
||||
protected override readonly listboxValues = computed<T[]>(() => {
|
||||
return this.visibleOptionValuesForSelected(this.value());
|
||||
});
|
||||
|
||||
protected override onValuesChange(values: readonly T[]): void {
|
||||
if (this.isUnavailable()) return;
|
||||
this.touched.set(true);
|
||||
const hiddenSelections = this.value().filter((selectedValue) => !this.isVisibleValue(selectedValue));
|
||||
this.value.set([...hiddenSelections, ...values]);
|
||||
}
|
||||
|
||||
protected override clearValue(): void {
|
||||
this.value.set([]);
|
||||
}
|
||||
|
||||
protected override isSelected(option: SelectOption<T>): boolean {
|
||||
return this.value().some((selectedValue) => this.valuesMatch(option.value, selectedValue));
|
||||
}
|
||||
|
||||
protected checkboxClass(selected: boolean): string {
|
||||
return cn(
|
||||
'mr-2 flex size-4 shrink-0 items-center justify-center rounded-sm border transition-colors',
|
||||
selected ? 'border-primary bg-primary' : 'border-border bg-card',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
computed,
|
||||
contentChild,
|
||||
Directive,
|
||||
inject,
|
||||
input,
|
||||
linkedSignal,
|
||||
model,
|
||||
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 FILTER_TEXT_EDITING_KEYS = new Set([' ', 'Spacebar', 'Backspace', 'Delete', 'Home', 'End']);
|
||||
const defaultCompareWith = <T>(optionValue: T, selectedValue: T): boolean => Object.is(optionValue, selectedValue);
|
||||
const UNGROUPED_GROUP_TRACK_KEY = Symbol('app-select-ungrouped');
|
||||
|
||||
interface RenderedSelectOptionGroup<T> extends SelectOptionGroup<T> {
|
||||
readonly trackKey: unknown;
|
||||
}
|
||||
|
||||
@Directive()
|
||||
export abstract class AppSelectBaseDirective<T> {
|
||||
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 = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly size = input<AppSelectSize>('md');
|
||||
readonly variant = input<AppSelectVariant>('outlined');
|
||||
readonly options = input<readonly SelectOption<T>[]>([]);
|
||||
readonly groups = input<readonly SelectOptionGroup<T>[]>([]);
|
||||
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<SelectCompareWith<T>>(defaultCompareWith);
|
||||
|
||||
readonly cleared = output<void>();
|
||||
|
||||
protected abstract readonly hasSelection: Signal<boolean>;
|
||||
protected abstract readonly triggerLabel: Signal<string>;
|
||||
protected abstract readonly listboxValues: Signal<T[]>;
|
||||
protected abstract onValuesChange(values: readonly T[]): void;
|
||||
protected abstract clearValue(): void;
|
||||
protected abstract isSelected(option: SelectOption<T>): 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 input = viewChild<ElementRef<HTMLInputElement>>('input');
|
||||
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',
|
||||
);
|
||||
protected readonly overlayPositions = connectedOverlayPositions;
|
||||
protected readonly overlayScrollStrategy = connectedOverlayScrollStrategy(this.overlayService);
|
||||
protected readonly listClass = computed(() =>
|
||||
cn(
|
||||
overlayListRootClass,
|
||||
this.filter() ? 'max-h-[12.75rem] overflow-y-auto p-1' : 'max-h-60 overflow-y-auto p-1',
|
||||
),
|
||||
);
|
||||
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<readonly RenderedSelectOptionGroup<T>[]>(() => {
|
||||
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<T>[] = [];
|
||||
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<readonly SelectOption<T>[]>(() =>
|
||||
this.grouped() ? this.groups().flatMap((group) => group.options) : this.options(),
|
||||
);
|
||||
|
||||
protected readonly filterText = linkedSignal<boolean, string>({
|
||||
source: () => this.combobox()?.expanded() ?? false,
|
||||
computation: (expanded, previous) => (expanded ? (previous?.value ?? '') : ''),
|
||||
});
|
||||
|
||||
protected onTriggerKeydown(event: KeyboardEvent): void {
|
||||
const combobox = this.combobox();
|
||||
if (this.isUnavailable() || !combobox || combobox.expanded()) return;
|
||||
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp' && event.key !== 'Enter' && event.key !== ' ') return;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
combobox.open();
|
||||
}
|
||||
|
||||
protected onFilterKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'Escape' || event.key === 'Enter' || event.key === 'Tab' || event.key.startsWith('Arrow')) return;
|
||||
|
||||
if (event.key.length === 1 || event.ctrlKey || event.metaKey || FILTER_TEXT_EDITING_KEYS.has(event.key)) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
}
|
||||
|
||||
protected onTriggerBlur(event: FocusEvent): void {
|
||||
if (this.isUnavailable()) return;
|
||||
const relatedTarget = event.relatedTarget;
|
||||
const overlayElement = this.overlay()?.overlayRef?.overlayElement;
|
||||
if (relatedTarget instanceof Node && overlayElement?.contains(relatedTarget)) return;
|
||||
this.touched.set(true);
|
||||
}
|
||||
|
||||
protected clear(event: MouseEvent): void {
|
||||
event.stopPropagation();
|
||||
if (this.isUnavailable()) return;
|
||||
this.clearValue();
|
||||
this.touched.set(true);
|
||||
this.cleared.emit();
|
||||
}
|
||||
|
||||
private matchesFilter(option: SelectOption<T>): boolean {
|
||||
if (!this.filter()) return true;
|
||||
const query = this.filterText().trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return option.label.toLowerCase().includes(query);
|
||||
}
|
||||
|
||||
protected valuesMatch(optionValue: T, selectedValue: T): boolean {
|
||||
return this.compareWith()(optionValue, selectedValue);
|
||||
}
|
||||
|
||||
protected findOptionForValue(value: T): SelectOption<T> | null {
|
||||
return this.flatOptions().find((option) => this.valuesMatch(option.value, value)) ?? null;
|
||||
}
|
||||
|
||||
protected findVisibleOptionForValue(value: T): SelectOption<T> | 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.input()?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
contentChild,
|
||||
model,
|
||||
} 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 { AppSelectBaseDirective } from './app-select-base.directive';
|
||||
import { AppSelectSelectedTemplateDirective } from './app-select.templates';
|
||||
import { type SelectOption } from './app-select.options';
|
||||
|
||||
@Component({
|
||||
selector: 'app-select',
|
||||
standalone: true,
|
||||
imports: [
|
||||
NgTemplateOutlet,
|
||||
OverlayModule,
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxPopupContainer,
|
||||
Listbox,
|
||||
Option,
|
||||
TranslocoPipe,
|
||||
],
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<div ngCombobox #cb="ngCombobox" [readonly]="true" [disabled]="disabled()" class="relative block h-full w-full">
|
||||
<div
|
||||
#origin
|
||||
[class]="triggerClass()"
|
||||
[attr.data-expanded]="cb.expanded() ? 'true' : null">
|
||||
<input
|
||||
ngComboboxInput
|
||||
#input
|
||||
readonly
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
[value]="triggerLabel()"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-labelledby]="ariaLabelledBy() || null"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[disabled]="disabled()"
|
||||
[required]="required()"
|
||||
(keydown)="onTriggerKeydown($event)"
|
||||
(blur)="onTriggerBlur($event)"
|
||||
class="absolute inset-0 z-10 h-full w-full cursor-pointer rounded-md border-0 bg-transparent p-0 text-transparent caret-transparent outline-hidden disabled:cursor-default" />
|
||||
|
||||
<span aria-hidden="true" [class]="labelClass()" [class.text-text-muted]="!hasSelection()">
|
||||
@if (selectedTemplate(); as tpl) {
|
||||
@if (selectedOption(); as opt) {
|
||||
<ng-container [ngTemplateOutlet]="tpl.template" [ngTemplateOutletContext]="{ $implicit: opt }" />
|
||||
} @else {
|
||||
{{ placeholder() }}
|
||||
}
|
||||
} @else {
|
||||
{{ triggerLabel() }}
|
||||
}
|
||||
</span>
|
||||
|
||||
@if (showClear() && hasSelection() && !isUnavailable()) {
|
||||
<button
|
||||
type="button"
|
||||
[attr.aria-label]="'shared.ui.select.clearSelection' | transloco"
|
||||
class="relative z-20 flex h-full shrink-0 items-center justify-center border-0 bg-transparent p-0 text-text-muted transition-colors hover:text-text-strong"
|
||||
[class.w-9]="variant() !== 'bare'"
|
||||
[class.w-7]="variant() === 'bare'"
|
||||
(click)="clear($event)">
|
||||
<i class="pi pi-times text-xs" aria-hidden="true"></i>
|
||||
</button>
|
||||
}
|
||||
|
||||
<span
|
||||
class="flex h-full shrink-0 items-center justify-center text-text-muted"
|
||||
[class.w-9]="variant() !== 'bare'"
|
||||
[class.w-7]="variant() === 'bare'">
|
||||
@if (pending()) {
|
||||
<i class="pi pi-spinner pi-spin text-xs" aria-hidden="true"></i>
|
||||
} @else {
|
||||
<i class="pi pi-chevron-down text-xs transition-transform" [class.rotate-180]="cb.expanded()" aria-hidden="true"></i>
|
||||
}
|
||||
</span>
|
||||
</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">
|
||||
@if (filter()) {
|
||||
<div class="flex h-9 items-center border-b border-border pl-3 pr-2 text-text-muted">
|
||||
<input
|
||||
#filterInput
|
||||
type="text"
|
||||
[value]="filterText()"
|
||||
(input)="filterText.set(filterInput.value)"
|
||||
(keydown)="onFilterKeydown($event)"
|
||||
[placeholder]="filterPlaceholder() || ('shared.ui.select.search' | transloco)"
|
||||
[readonly]="readonly()"
|
||||
class="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" />
|
||||
<i class="pi pi-search shrink-0 text-xs" aria-hidden="true"></i>
|
||||
</div>
|
||||
}
|
||||
|
||||
<ul
|
||||
ngListbox
|
||||
tabindex="-1"
|
||||
focusMode="activedescendant"
|
||||
selectionMode="explicit"
|
||||
[values]="listboxValues()"
|
||||
[readonly]="readonly()"
|
||||
[disabled]="disabled()"
|
||||
(valuesChange)="onValuesChange($event)"
|
||||
[class]="listClass()">
|
||||
@for (grp of renderedGroups(); track grp.trackKey; let first = $first) {
|
||||
@if (grouped()) {
|
||||
@if (!first) {
|
||||
<li role="separator" [class]="separatorClass"></li>
|
||||
}
|
||||
<li role="presentation" [class]="sectionClass">{{ grp.label }}</li>
|
||||
}
|
||||
@for (option of grp.options; track option) {
|
||||
<li
|
||||
ngOption
|
||||
tabindex="-1"
|
||||
[value]="option.value"
|
||||
[label]="option.label"
|
||||
[disabled]="option.disabled === true"
|
||||
[class]="optionClass">
|
||||
@if (optionTemplate(); as tpl) {
|
||||
<ng-container [ngTemplateOutlet]="tpl.template" [ngTemplateOutletContext]="{ $implicit: option }" />
|
||||
} @else {
|
||||
<span class="truncate leading-5">{{ option.label }}</span>
|
||||
}
|
||||
@if (isSelected(option)) {
|
||||
<i class="pi pi-check order-last ml-auto size-4 shrink-0 text-primary" aria-hidden="true"></i>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
} @empty {
|
||||
<li [class]="emptyClass">{{ emptyMessage() || ('shared.ui.select.noResults' | transloco) }}</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ng-template>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppSelectComponent<T> extends AppSelectBaseDirective<T> implements FormValueControl<T | null> {
|
||||
readonly value = model<T | null>(null);
|
||||
|
||||
protected readonly selectedTemplate = contentChild(AppSelectSelectedTemplateDirective);
|
||||
|
||||
protected readonly selectedOption = computed<SelectOption<T> | null>(() => {
|
||||
const value = this.value();
|
||||
if (value == null) return null;
|
||||
return this.findOptionForValue(value);
|
||||
});
|
||||
|
||||
protected override readonly hasSelection = computed(() => this.value() != null);
|
||||
|
||||
protected override readonly triggerLabel = computed(() => this.selectedOption()?.label ?? this.placeholder());
|
||||
|
||||
protected override readonly listboxValues = computed<T[]>(() => {
|
||||
const value = this.value();
|
||||
const option = value == null ? null : this.findVisibleOptionForValue(value);
|
||||
return option ? [option.value] : [];
|
||||
});
|
||||
|
||||
protected override onValuesChange(values: readonly T[]): void {
|
||||
if (this.isUnavailable()) return;
|
||||
this.touched.set(true);
|
||||
|
||||
if (values.length) {
|
||||
this.value.set(values[values.length - 1]);
|
||||
return;
|
||||
}
|
||||
|
||||
const current = this.value();
|
||||
if (current != null && !this.isVisibleValue(current)) return;
|
||||
this.value.set(null);
|
||||
}
|
||||
|
||||
protected override clearValue(): void {
|
||||
this.value.set(null);
|
||||
}
|
||||
|
||||
protected override isSelected(option: SelectOption<T>): boolean {
|
||||
const value = this.value();
|
||||
return value != null && this.valuesMatch(option.value, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export interface SelectOption<T> {
|
||||
readonly label: string;
|
||||
readonly value: T;
|
||||
readonly disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface SelectOptionGroup<T> {
|
||||
readonly label: string;
|
||||
readonly options: readonly SelectOption<T>[];
|
||||
}
|
||||
|
||||
export type SelectCompareWith<T> = (optionValue: T, selectedValue: T) => boolean;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Directive, TemplateRef, inject } from '@angular/core';
|
||||
|
||||
interface AppSelectOptionTemplateContext<T = unknown> {
|
||||
$implicit: T;
|
||||
}
|
||||
|
||||
@Directive({
|
||||
selector: 'ng-template[appSelectOption]',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppSelectOptionTemplateDirective<T = unknown> {
|
||||
readonly template = inject<TemplateRef<AppSelectOptionTemplateContext<T>>>(TemplateRef);
|
||||
}
|
||||
|
||||
@Directive({
|
||||
selector: 'ng-template[appSelectSelected]',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppSelectSelectedTemplateDirective<T = unknown> {
|
||||
readonly template = inject<TemplateRef<AppSelectOptionTemplateContext<T>>>(TemplateRef);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export type AppSelectSize = 'sm' | 'md' | 'lg';
|
||||
export type AppSelectVariant = 'outlined' | 'bare';
|
||||
|
||||
export const appSelectTriggerVariants = cva(
|
||||
'relative inline-flex w-full cursor-pointer select-none items-center p-0 text-left font-normal ' +
|
||||
'outline-hidden transition-[background-color,border-color,color] duration-150',
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'text-xs',
|
||||
md: 'text-sm',
|
||||
lg: 'text-sm',
|
||||
},
|
||||
variant: {
|
||||
outlined:
|
||||
`rounded-md border ${neutralControlBorderClass} bg-card shadow-control ` +
|
||||
'focus-within:border-primary/60 focus-within:outline-1 focus-within:outline-offset-0 focus-within:outline-primary/60 ' +
|
||||
'data-[expanded=true]:border-primary/60',
|
||||
bare: 'rounded-none border-0 bg-transparent shadow-none',
|
||||
},
|
||||
invalid: {
|
||||
true: 'border-danger focus-within:border-danger focus-within:outline-danger data-[expanded=true]:border-danger',
|
||||
false: '',
|
||||
},
|
||||
disabled: {
|
||||
true: 'pointer-events-none opacity-50',
|
||||
false: '',
|
||||
},
|
||||
},
|
||||
compoundVariants: [
|
||||
{ variant: 'outlined', size: 'sm', class: 'h-8' },
|
||||
{ variant: 'outlined', size: 'md', class: 'h-9' },
|
||||
{ variant: 'outlined', size: 'lg', class: 'h-10' },
|
||||
{ variant: 'bare', size: 'sm', class: 'h-full min-h-8' },
|
||||
{ variant: 'bare', size: 'md', class: 'h-full min-h-9' },
|
||||
{ variant: 'bare', size: 'lg', class: 'h-full min-h-10' },
|
||||
],
|
||||
defaultVariants: { size: 'md', variant: 'outlined', invalid: false, disabled: false },
|
||||
},
|
||||
);
|
||||
|
||||
export const appSelectLabelVariants = cva(
|
||||
'block min-w-0 flex-auto truncate bg-transparent text-text-strong',
|
||||
{
|
||||
variants: {
|
||||
size: { sm: '', md: '', lg: '' },
|
||||
variant: { outlined: '', bare: '' },
|
||||
},
|
||||
compoundVariants: [
|
||||
{ variant: 'outlined', size: 'sm', class: 'px-3 leading-8' },
|
||||
{ variant: 'outlined', size: 'md', class: 'px-3 leading-9' },
|
||||
{ variant: 'outlined', size: 'lg', class: 'px-4 leading-10' },
|
||||
{ variant: 'bare', size: 'sm', class: 'px-3' },
|
||||
{ variant: 'bare', size: 'md', class: 'px-4' },
|
||||
{ variant: 'bare', size: 'lg', class: 'px-4' },
|
||||
],
|
||||
defaultVariants: { size: 'md', variant: 'outlined' },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,103 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
numberAttribute,
|
||||
type ElementRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
import { invisibleControlInputClass, neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-slider',
|
||||
standalone: true,
|
||||
host: { class: 'block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<div
|
||||
class="relative flex h-5 w-full touch-none select-none items-center"
|
||||
[class.opacity-50]="isUnavailable()"
|
||||
[style.--pct]="fraction()">
|
||||
<input
|
||||
#input
|
||||
type="range"
|
||||
[class]="inputClass"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[min]="min() ?? 0"
|
||||
[max]="max() ?? 100"
|
||||
[step]="step()"
|
||||
[value]="value()"
|
||||
[disabled]="isUnavailable()"
|
||||
[required]="required()"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
(input)="onInput(input.value)"
|
||||
(change)="touched.set(true)" />
|
||||
|
||||
<div class="pointer-events-none absolute inset-x-0 h-1.5 rounded-full bg-border"></div>
|
||||
<div class="pointer-events-none absolute left-0 h-1.5 rounded-full bg-primary" [style.width]="thumbPosition"></div>
|
||||
<div
|
||||
[class]="thumbClass"
|
||||
[style.left]="thumbPosition"></div>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AppSliderComponent implements FormValueControl<number> {
|
||||
readonly value = model(0);
|
||||
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 = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly min = input<number | undefined>(undefined);
|
||||
readonly max = input<number | undefined>(undefined);
|
||||
readonly step = input(1, { transform: numberAttribute });
|
||||
readonly inputId = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
|
||||
protected readonly inputClass = invisibleControlInputClass;
|
||||
protected readonly thumbPosition = 'calc(0.5rem + var(--pct) * (100% - 1rem))';
|
||||
protected readonly thumbClass =
|
||||
`pointer-events-none absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border ${neutralControlBorderClass} ` +
|
||||
'bg-white shadow-control transition-shadow peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-primary';
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
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 fraction = computed(() => {
|
||||
const min = this.min() ?? 0;
|
||||
const span = (this.max() ?? 100) - min;
|
||||
if (span <= 0) return 0;
|
||||
return Math.min(1, Math.max(0, (this.value() - min) / span));
|
||||
});
|
||||
|
||||
private readonly input = viewChild<ElementRef<HTMLInputElement>>('input');
|
||||
|
||||
protected onInput(raw: string): void {
|
||||
this.value.set(Number(raw));
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.input()?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
|
||||
import { translateSignal } from '@jsverse/transloco';
|
||||
import { cn } from '../cn';
|
||||
import { spinnerVariants, type SpinnerSize } from './app-spinner.variants';
|
||||
|
||||
@Component({
|
||||
selector: 'app-spinner',
|
||||
standalone: true,
|
||||
host: {
|
||||
class: 'inline-flex text-primary',
|
||||
role: 'status',
|
||||
'[attr.aria-label]': 'ariaLabel() || defaultAriaLabel()',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `<span [class]="ringClass()"></span>`,
|
||||
})
|
||||
export class AppSpinnerComponent {
|
||||
readonly size = input<SpinnerSize>('md');
|
||||
readonly ariaLabel = input('');
|
||||
readonly styleClass = input('');
|
||||
|
||||
protected readonly defaultAriaLabel = translateSignal('shared.ui.spinner.loading');
|
||||
protected readonly ringClass = computed(() => cn(spinnerVariants({ size: this.size() }), this.styleClass()));
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
|
||||
export type SpinnerSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
export const SPINNER_RING = 'inline-block animate-spin rounded-full border-current border-t-transparent [animation-duration:0.85s]';
|
||||
|
||||
export const spinnerVariants = cva(SPINNER_RING, {
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'size-4 border-2',
|
||||
md: 'size-6 border-2',
|
||||
lg: 'size-10 border-[3px]',
|
||||
},
|
||||
},
|
||||
defaultVariants: { size: 'md' },
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { booleanAttribute, ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
||||
import { type MenuItem } from 'primeng/api';
|
||||
import { cn } from '../cn';
|
||||
import { connectedGroupClass, connectedItemClass } from '../connected-group';
|
||||
import { AppButtonComponent } from '../button/app-button.component';
|
||||
import { type ButtonSize, type ButtonTone, type ButtonVariant } from '../button/app-button.variants';
|
||||
import { AppMenuComponent } from '../menu/app-menu.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-split-button',
|
||||
standalone: true,
|
||||
imports: [AppButtonComponent, AppMenuComponent],
|
||||
host: {
|
||||
class: 'inline-block align-middle',
|
||||
'[class.w-full]': 'fluid()',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<span [class]="rootClass()">
|
||||
<app-button
|
||||
[class.min-w-0]="fluid()"
|
||||
[class.flex-1]="fluid()"
|
||||
[buttonId]="buttonId()"
|
||||
[tone]="tone()"
|
||||
[variant]="variant()"
|
||||
[size]="size()"
|
||||
[fluid]="fluid()"
|
||||
[styleClass]="mainButtonClass()"
|
||||
[disabled]="disabled()"
|
||||
[loading]="loading()"
|
||||
[type]="type()"
|
||||
[name]="name()"
|
||||
[value]="value()"
|
||||
[form]="form()"
|
||||
[title]="title()"
|
||||
[tabIndex]="tabIndex()"
|
||||
[label]="label()"
|
||||
[ariaLabel]="ariaLabel()"
|
||||
[icon]="icon()"
|
||||
[iconPos]="iconPos()"
|
||||
(clicked)="clicked.emit($event)">
|
||||
<ng-content />
|
||||
</app-button>
|
||||
<app-button
|
||||
[buttonId]="menuButtonId()"
|
||||
type="button"
|
||||
iconOnly
|
||||
icon="pi pi-chevron-down"
|
||||
[tone]="tone()"
|
||||
[variant]="variant()"
|
||||
[size]="size()"
|
||||
[styleClass]="menuButtonClass()"
|
||||
[disabled]="isMenuDisabled()"
|
||||
[form]="form()"
|
||||
[ariaHasPopup]="'menu'"
|
||||
[ariaLabel]="menuAriaLabel() || ariaLabel() || label()"
|
||||
(clicked)="menu.toggle($event)" />
|
||||
<app-menu #menu [model]="model()" [appendTo]="appendTo()" />
|
||||
</span>
|
||||
`,
|
||||
})
|
||||
export class AppSplitButtonComponent {
|
||||
readonly tone = input<ButtonTone>('neutral');
|
||||
readonly variant = input<ButtonVariant>('soft');
|
||||
readonly size = input<ButtonSize>('md');
|
||||
readonly fluid = input(false, { transform: booleanAttribute });
|
||||
readonly styleClass = input('');
|
||||
readonly mainStyleClass = input('');
|
||||
readonly menuButtonStyleClass = input('');
|
||||
readonly buttonId = input('');
|
||||
readonly menuButtonId = input('');
|
||||
readonly name = input('');
|
||||
readonly value = input<string | number | null>(null);
|
||||
readonly form = input('');
|
||||
readonly title = input('');
|
||||
readonly tabIndex = input<number | null>(null);
|
||||
readonly label = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly menuAriaLabel = input('');
|
||||
readonly icon = input('');
|
||||
readonly iconPos = input<'left' | 'right'>('left');
|
||||
readonly model = input<readonly MenuItem[]>([]);
|
||||
readonly appendTo = input<'body' | 'self' | HTMLElement>('body');
|
||||
readonly loading = input(false, { transform: booleanAttribute });
|
||||
readonly disabled = input(false, { transform: booleanAttribute });
|
||||
readonly type = input<'button' | 'submit' | 'reset'>('button');
|
||||
|
||||
readonly clicked = output<MouseEvent>();
|
||||
|
||||
protected readonly isMenuDisabled = computed(() => this.disabled() || this.loading() || this.model().length === 0);
|
||||
protected readonly rootClass = computed(() => cn(connectedGroupClass, this.fluid() && 'w-full', this.styleClass()));
|
||||
protected readonly mainButtonClass = computed(() =>
|
||||
cn(
|
||||
connectedItemClass({ first: true, last: false, prominent: this.tone() !== 'neutral' }),
|
||||
'relative focus-visible:z-10',
|
||||
this.mainStyleClass(),
|
||||
),
|
||||
);
|
||||
protected readonly menuButtonClass = computed(() =>
|
||||
cn(
|
||||
connectedItemClass({ first: false, last: true, prominent: this.tone() !== 'neutral' }),
|
||||
'relative shrink-0 focus-visible:z-10',
|
||||
this.menuButtonStyleClass(),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
type ElementRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { type FormCheckboxControl } from '@angular/forms/signals';
|
||||
import { cn } from '../cn';
|
||||
import { invisibleControlInputClass } from '../control.styles';
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
import {
|
||||
appSwitchRootVariants,
|
||||
appSwitchThumbVariants,
|
||||
appSwitchTrackVariants,
|
||||
type AppSwitchSize,
|
||||
} from './app-switch.variants';
|
||||
|
||||
@Component({
|
||||
selector: 'app-switch',
|
||||
standalone: true,
|
||||
host: { class: 'inline-flex align-middle' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<span [class]="rootClass()">
|
||||
<input
|
||||
#control
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
[class]="inputClass"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-labelledby]="ariaLabelledBy() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-readonly]="readonly() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[checked]="checked()"
|
||||
[disabled]="isUnavailable()"
|
||||
[required]="required()"
|
||||
(change)="onInputChange(control.checked)"
|
||||
(blur)="touched.set(true)" />
|
||||
<span [class]="trackClass()" aria-hidden="true"></span>
|
||||
<span [class]="thumbClass()" aria-hidden="true"></span>
|
||||
</span>
|
||||
`,
|
||||
})
|
||||
export class AppSwitchComponent implements FormCheckboxControl {
|
||||
readonly checked = model(false);
|
||||
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 = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly size = input<AppSwitchSize>('md');
|
||||
readonly inputId = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaLabelledBy = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
readonly styleClass = input('');
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
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 rootClass = computed(() => cn(appSwitchRootVariants({ size: this.size() }), this.styleClass()));
|
||||
protected readonly inputClass = invisibleControlInputClass;
|
||||
protected readonly trackClass = computed(() =>
|
||||
appSwitchTrackVariants({ disabled: this.isUnavailable(), invalid: this.showInvalid() }),
|
||||
);
|
||||
protected readonly thumbClass = computed(() =>
|
||||
appSwitchThumbVariants({ size: this.size(), disabled: this.isUnavailable() }),
|
||||
);
|
||||
|
||||
private readonly control = viewChild<ElementRef<HTMLInputElement>>('control');
|
||||
|
||||
protected onInputChange(checked: boolean): void {
|
||||
this.checked.set(checked);
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.control()?.nativeElement.focus(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export type AppSwitchSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
export const appSwitchRootVariants = cva('relative inline-flex shrink-0 align-middle', {
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'h-4 w-8',
|
||||
md: 'h-5 w-10',
|
||||
lg: 'h-6 w-12',
|
||||
},
|
||||
},
|
||||
defaultVariants: { size: 'md' },
|
||||
});
|
||||
|
||||
export const appSwitchTrackVariants = cva(
|
||||
`absolute inset-0 rounded-full border ${neutralControlBorderClass} bg-text-muted/30 shadow-control ` +
|
||||
'transition-[background-color,border-color,opacity] duration-150 ' +
|
||||
'peer-checked:border-transparent peer-checked:bg-primary ' +
|
||||
'peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-primary',
|
||||
{
|
||||
variants: {
|
||||
disabled: {
|
||||
true: 'opacity-50',
|
||||
false: '',
|
||||
},
|
||||
invalid: {
|
||||
true: 'border-danger',
|
||||
false: '',
|
||||
},
|
||||
},
|
||||
defaultVariants: { disabled: false, invalid: false },
|
||||
},
|
||||
);
|
||||
|
||||
export const appSwitchThumbVariants = cva(
|
||||
'pointer-events-none absolute left-0.5 top-1/2 -translate-y-1/2 translate-x-0 rounded-full bg-white shadow-sm ' +
|
||||
'transition-[opacity,translate,transform] duration-150',
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
sm: 'size-3 peer-checked:translate-x-4',
|
||||
md: 'size-4 peer-checked:translate-x-5',
|
||||
lg: 'size-5 peer-checked:translate-x-6',
|
||||
},
|
||||
disabled: {
|
||||
true: 'opacity-50',
|
||||
false: '',
|
||||
},
|
||||
},
|
||||
defaultVariants: { size: 'md', disabled: false },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,191 @@
|
||||
import {
|
||||
afterRenderEffect,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
DestroyRef,
|
||||
ElementRef,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
signal,
|
||||
untracked,
|
||||
viewChild,
|
||||
viewChildren,
|
||||
} from '@angular/core';
|
||||
import { Tab as NgTab, TabList, Tabs } from '@angular/aria/tabs';
|
||||
import { AppSelectComponent } from '../select/app-select.component';
|
||||
import { type SelectOption } from '../select/app-select.options';
|
||||
import { cn } from '../cn';
|
||||
import {
|
||||
appTabsListVariants,
|
||||
appTabsRootVariants,
|
||||
appTabVariants,
|
||||
type TabsCollapse,
|
||||
type TabsPlacement,
|
||||
type TabsSize,
|
||||
type TabsVariant,
|
||||
} from './app-tabs.variants';
|
||||
|
||||
export interface TabItem {
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
const COLLAPSE_HYSTERESIS = 8;
|
||||
|
||||
@Component({
|
||||
selector: 'app-tabs',
|
||||
standalone: true,
|
||||
imports: [Tabs, TabList, NgTab, AppSelectComponent],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: { class: 'relative block min-w-0' },
|
||||
template: `
|
||||
@if (tabs().length) {
|
||||
@if (collapsed()) {
|
||||
<app-select
|
||||
class="block w-full"
|
||||
[options]="collapsedOptions()"
|
||||
[value]="activeTabId() ?? null"
|
||||
(valueChange)="selectTab($event)"
|
||||
[ariaLabel]="ariaLabel()" />
|
||||
}
|
||||
<div
|
||||
data-tabs-row
|
||||
[class]="rowClass()"
|
||||
[attr.aria-hidden]="collapsed() ? 'true' : null"
|
||||
[attr.inert]="collapsed() ? '' : null">
|
||||
<div ngTabs [class]="rootClass()">
|
||||
<div
|
||||
#tabList
|
||||
ngTabList
|
||||
[class]="listClass()"
|
||||
[selectedTab]="activeTabId()"
|
||||
(selectedTabChange)="selectTab($event)"
|
||||
[attr.aria-label]="ariaLabel()">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
[class]="indicatorClass()"
|
||||
[style.transform]="'translateX(' + indicatorLeft() + 'px)'"
|
||||
[style.width.px]="indicatorWidth()"></span>
|
||||
@for (tab of tabs(); track tab.id) {
|
||||
<button ngTab type="button" [value]="tab.id" [class]="tabClass()">
|
||||
@if (tab.icon) {
|
||||
<i [class]="tab.icon + ' shrink-0 text-[0.875em] leading-none'" aria-hidden="true"></i>
|
||||
}
|
||||
<span class="leading-none">{{ tab.label }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppTabsComponent {
|
||||
readonly tabs = input.required<readonly TabItem[]>();
|
||||
readonly variant = input<TabsVariant>('underline');
|
||||
readonly size = input<TabsSize>('md');
|
||||
readonly placement = input<TabsPlacement>('inline');
|
||||
readonly collapse = input<TabsCollapse>('auto');
|
||||
readonly ariaLabel = input.required<string>();
|
||||
readonly selectedTabId = model<string | undefined>(undefined);
|
||||
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly tabDirectives = viewChildren(NgTab);
|
||||
private readonly tabListRef = viewChild<unknown, ElementRef<HTMLElement>>('tabList', { read: ElementRef });
|
||||
|
||||
protected readonly activeTabId = computed(() => this.resolveTabId(this.selectedTabId()));
|
||||
protected readonly collapsedOptions = computed<SelectOption<string>[]>(() =>
|
||||
this.tabs().map((tab) => ({ label: tab.label, value: tab.id })),
|
||||
);
|
||||
protected readonly collapsed = signal(false);
|
||||
protected readonly indicatorLeft = signal(0);
|
||||
protected readonly indicatorWidth = signal(0);
|
||||
private readonly indicatorReady = signal(false);
|
||||
|
||||
protected readonly rowClass = computed(() =>
|
||||
this.collapsed() ? 'pointer-events-none invisible absolute left-0 top-0 w-max max-w-full overflow-hidden' : 'block',
|
||||
);
|
||||
protected readonly rootClass = computed(() => appTabsRootVariants({ placement: this.placement() }));
|
||||
protected readonly listClass = computed(() => appTabsListVariants({ variant: this.variant() }));
|
||||
protected readonly tabClass = computed(() => appTabVariants({ variant: this.variant(), size: this.size() }));
|
||||
protected readonly indicatorClass = computed(() => {
|
||||
const animated = this.indicatorReady() && 'transition-[transform,width] duration-200 ease-out';
|
||||
return this.variant() === 'segmented'
|
||||
? cn(
|
||||
'pointer-events-none absolute inset-y-1 left-0 z-0 rounded-md border border-primary/15 ' +
|
||||
'bg-primary/10 shadow-control dark:border-primary/30',
|
||||
animated,
|
||||
)
|
||||
: cn('pointer-events-none absolute bottom-0 left-0 h-0.5 rounded-t-[2px] bg-primary', animated);
|
||||
});
|
||||
|
||||
constructor() {
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
afterRenderEffect(() => {
|
||||
this.tabs();
|
||||
this.variant();
|
||||
this.size();
|
||||
this.placement();
|
||||
this.collapse();
|
||||
this.activeTabId();
|
||||
this.measureLayout();
|
||||
|
||||
if (typeof ResizeObserver === 'undefined') return;
|
||||
resizeObserver ??= new ResizeObserver(() => this.measureLayout());
|
||||
resizeObserver.disconnect();
|
||||
resizeObserver.observe(this.host.nativeElement);
|
||||
for (const tab of this.tabDirectives()) {
|
||||
resizeObserver.observe(tab.element);
|
||||
}
|
||||
});
|
||||
|
||||
this.destroyRef.onDestroy(() => resizeObserver?.disconnect());
|
||||
}
|
||||
|
||||
protected selectTab(value: string | null | undefined): void {
|
||||
this.selectedTabId.set(this.resolveTabId(value ?? undefined));
|
||||
}
|
||||
|
||||
private measureLayout(): void {
|
||||
this.measure();
|
||||
this.measureFit();
|
||||
}
|
||||
|
||||
private measureFit(): void {
|
||||
const mode = this.collapse();
|
||||
if (mode !== 'auto') {
|
||||
this.collapsed.set(mode === 'always');
|
||||
return;
|
||||
}
|
||||
const list = this.tabListRef()?.nativeElement;
|
||||
if (!list) return;
|
||||
const available = this.host.nativeElement.clientWidth;
|
||||
const content = list.scrollWidth;
|
||||
const collapsed = untracked(this.collapsed);
|
||||
if (!collapsed) {
|
||||
if (content > available + 1) this.collapsed.set(true);
|
||||
} else if (content <= available - COLLAPSE_HYSTERESIS) {
|
||||
this.collapsed.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
private measure(): void {
|
||||
const active = this.tabDirectives().find((tab) => tab.value() === this.activeTabId());
|
||||
if (!active) return;
|
||||
this.indicatorLeft.set(active.element.offsetLeft);
|
||||
this.indicatorWidth.set(active.element.offsetWidth);
|
||||
if (!this.indicatorReady() && typeof requestAnimationFrame !== 'undefined') {
|
||||
requestAnimationFrame(() => this.indicatorReady.set(true));
|
||||
}
|
||||
}
|
||||
|
||||
private resolveTabId(value: string | undefined): string | undefined {
|
||||
const tabs = this.tabs();
|
||||
return tabs.some((tab) => tab.id === value) ? value : tabs[0]?.id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
|
||||
export type TabsVariant = 'underline' | 'segmented';
|
||||
export type TabsPlacement = 'inline' | 'below';
|
||||
export type TabsSize = 'sm' | 'md' | 'lg';
|
||||
export type TabsCollapse = 'auto' | 'always' | 'never';
|
||||
|
||||
export const appTabsRootVariants = cva('relative', {
|
||||
variants: {
|
||||
placement: {
|
||||
inline: '',
|
||||
below: 'flex min-h-[3rem] items-end',
|
||||
},
|
||||
},
|
||||
defaultVariants: { placement: 'inline' },
|
||||
});
|
||||
|
||||
export const appTabsListVariants = cva('relative flex min-w-0', {
|
||||
variants: {
|
||||
variant: {
|
||||
underline: 'items-stretch gap-5 border-b border-border/70',
|
||||
segmented: 'items-center gap-1 rounded-[10px] bg-text/[0.04] p-1 dark:bg-text/[0.04]',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'underline' },
|
||||
});
|
||||
|
||||
export const appTabVariants = cva(
|
||||
'relative z-10 inline-flex cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap font-medium ' +
|
||||
'leading-none transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary ' +
|
||||
'aria-selected:focus-visible:outline-none',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
underline: 'text-text-secondary hover:text-text aria-selected:text-text-strong',
|
||||
segmented: 'text-text-secondary hover:text-text-strong aria-selected:text-primary-text',
|
||||
},
|
||||
size: { sm: '', md: '', lg: '' },
|
||||
},
|
||||
compoundVariants: [
|
||||
{ variant: 'underline', size: 'sm', class: 'px-3 py-2 text-xs' },
|
||||
{ variant: 'underline', size: 'md', class: 'px-3.5 py-2.5 text-sm' },
|
||||
{ variant: 'underline', size: 'lg', class: 'px-4 py-3 text-sm' },
|
||||
{ variant: 'segmented', size: 'sm', class: 'h-8 px-3 text-xs' },
|
||||
{ variant: 'segmented', size: 'md', class: 'h-9 px-3 text-sm' },
|
||||
{ variant: 'segmented', size: 'lg', class: 'h-10 px-4 text-sm' },
|
||||
],
|
||||
defaultVariants: { variant: 'underline', size: 'md' },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,98 @@
|
||||
import { booleanAttribute, ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
||||
import { translateSignal } from '@jsverse/transloco';
|
||||
import { cn } from '../cn';
|
||||
import { tagRemoveVariants, tagVariants, type TagColor, type TagSize } from './app-tag.variants';
|
||||
|
||||
@Component({
|
||||
selector: 'app-tag',
|
||||
standalone: true,
|
||||
host: { class: 'inline-flex align-middle' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
@if (clickable()) {
|
||||
<button
|
||||
type="button"
|
||||
[class]="tagClass()"
|
||||
[style.background-color]="customBg()"
|
||||
[style.color]="customTextColor()"
|
||||
[style.border-color]="customBorder()"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
(click)="clicked.emit($event)">
|
||||
@if (icon()) {
|
||||
<i [class]="icon()" aria-hidden="true"></i>
|
||||
}
|
||||
@if (label()) {
|
||||
<span>{{ label() }}</span>
|
||||
}
|
||||
<ng-content />
|
||||
</button>
|
||||
} @else {
|
||||
<span
|
||||
[class]="tagClass()"
|
||||
[style.background-color]="customBg()"
|
||||
[style.color]="customTextColor()"
|
||||
[style.border-color]="customBorder()">
|
||||
@if (icon()) {
|
||||
<i [class]="icon()" aria-hidden="true"></i>
|
||||
}
|
||||
@if (label()) {
|
||||
<span>{{ label() }}</span>
|
||||
}
|
||||
<ng-content />
|
||||
@if (removable()) {
|
||||
<button
|
||||
type="button"
|
||||
[class]="removeClass()"
|
||||
[attr.aria-label]="resolvedRemoveLabel()"
|
||||
(click)="$event.stopPropagation(); remove.emit($event)">
|
||||
<i class="pi pi-times text-[0.7em]" aria-hidden="true"></i>
|
||||
</button>
|
||||
}
|
||||
</span>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppTagComponent {
|
||||
readonly color = input<TagColor>('neutral');
|
||||
readonly size = input<TagSize>('md');
|
||||
readonly label = input('');
|
||||
readonly icon = input('');
|
||||
readonly styleClass = input('');
|
||||
readonly customColor = input('');
|
||||
readonly clickable = input(false, { transform: booleanAttribute });
|
||||
readonly removable = input(false, { transform: booleanAttribute });
|
||||
readonly ariaLabel = input('');
|
||||
readonly removeLabel = input('');
|
||||
|
||||
readonly clicked = output<MouseEvent>();
|
||||
readonly remove = output<MouseEvent>();
|
||||
|
||||
protected readonly tagClass = computed(() =>
|
||||
cn(
|
||||
tagVariants({
|
||||
color: this.customTextColor() ? 'custom' : this.color(),
|
||||
size: this.size(),
|
||||
clickable: this.clickable(),
|
||||
}),
|
||||
this.styleClass(),
|
||||
),
|
||||
);
|
||||
|
||||
protected readonly removeClass = computed(() => tagRemoveVariants({ size: this.size() }));
|
||||
private readonly removeLabelParams = computed(() => ({ label: this.label() }));
|
||||
private readonly removeTagLabel = translateSignal('shared.ui.tag.removeTag');
|
||||
private readonly removeLabelWithValue = translateSignal('shared.ui.tag.removeLabel', this.removeLabelParams);
|
||||
protected readonly resolvedRemoveLabel = computed(
|
||||
() => this.removeLabel() || (this.label() ? this.removeLabelWithValue() : this.removeTagLabel()),
|
||||
);
|
||||
protected readonly customTextColor = computed(() => this.customColor() || null);
|
||||
|
||||
protected readonly customBg = computed(() => {
|
||||
const color = this.customTextColor();
|
||||
return color ? `color-mix(in srgb, ${color}, transparent 90%)` : null;
|
||||
});
|
||||
protected readonly customBorder = computed(() => {
|
||||
const color = this.customTextColor();
|
||||
return color ? `color-mix(in srgb, ${color}, transparent 85%)` : null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
|
||||
export type TagColor =
|
||||
| 'neutral'
|
||||
| 'primary'
|
||||
| 'red'
|
||||
| 'amber'
|
||||
| 'green'
|
||||
| 'teal'
|
||||
| 'sky'
|
||||
| 'blue'
|
||||
| 'indigo'
|
||||
| 'purple'
|
||||
| 'pink';
|
||||
export type TagSize = 'sm' | 'md';
|
||||
|
||||
export const tagVariants = cva(
|
||||
'inline-flex items-center gap-1 rounded-full border font-medium leading-none whitespace-nowrap',
|
||||
{
|
||||
variants: {
|
||||
color: {
|
||||
neutral: 'bg-text/5 text-text-secondary border-text/10 dark:bg-text/10',
|
||||
primary: 'bg-primary/10 text-primary-text border-primary/15 dark:border-primary/30',
|
||||
red: 'bg-red-500/10 text-red-700 border-red-500/15 dark:text-red-300 dark:border-red-400/20',
|
||||
amber: 'bg-amber-500/10 text-amber-700 border-amber-500/15 dark:text-amber-300 dark:border-amber-400/20',
|
||||
green: 'bg-green-500/10 text-green-700 border-green-500/15 dark:text-green-300 dark:border-green-400/20',
|
||||
teal: 'bg-teal-500/10 text-teal-700 border-teal-500/15 dark:text-teal-300 dark:border-teal-400/20',
|
||||
sky: 'bg-sky-500/10 text-sky-700 border-sky-500/15 dark:text-sky-300 dark:border-sky-400/20',
|
||||
blue: 'bg-blue-500/10 text-blue-700 border-blue-500/15 dark:text-blue-300 dark:border-blue-400/20',
|
||||
indigo: 'bg-indigo-500/10 text-indigo-700 border-indigo-500/15 dark:text-indigo-300 dark:border-indigo-400/20',
|
||||
purple: 'bg-purple-500/10 text-purple-700 border-purple-500/15 dark:text-purple-300 dark:border-purple-400/20',
|
||||
pink: 'bg-pink-500/10 text-pink-700 border-pink-500/15 dark:text-pink-300 dark:border-pink-400/20',
|
||||
custom: '',
|
||||
},
|
||||
size: {
|
||||
sm: 'px-1.5 py-0.5 text-xs',
|
||||
md: 'px-2 py-0.5 text-sm',
|
||||
},
|
||||
clickable: {
|
||||
true:
|
||||
'cursor-pointer transition-[background-color,border-color] duration-150 ' +
|
||||
'hover:border-current/40 active:translate-y-px ' +
|
||||
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary',
|
||||
false: '',
|
||||
},
|
||||
},
|
||||
defaultVariants: { color: 'neutral', size: 'md', clickable: false },
|
||||
},
|
||||
);
|
||||
|
||||
export const tagRemoveVariants = cva(
|
||||
'-my-0.5 inline-flex shrink-0 cursor-pointer items-center justify-center self-stretch rounded-r-full ' +
|
||||
'transition-colors hover:bg-current/15 ' +
|
||||
'focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-current',
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
sm: '-mr-1.5 pl-1 pr-1.5',
|
||||
md: '-mr-2 pl-1.5 pr-2',
|
||||
},
|
||||
},
|
||||
defaultVariants: { size: 'md' },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
afterRenderEffect,
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
type ElementRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { type FormValueControl } from '@angular/forms/signals';
|
||||
import { cn } from '../cn';
|
||||
import { APP_FIELD } from '../field/app-field.context';
|
||||
import { appTextareaVariants } from './app-textarea.variants';
|
||||
|
||||
@Component({
|
||||
selector: 'app-textarea',
|
||||
standalone: true,
|
||||
host: { class: 'relative block w-full' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<textarea
|
||||
#textarea
|
||||
[class]="textareaClass()"
|
||||
[attr.id]="resolvedInputId()"
|
||||
[attr.name]="name() || null"
|
||||
[attr.placeholder]="placeholder() || null"
|
||||
[attr.aria-label]="ariaLabel() || null"
|
||||
[attr.aria-describedby]="resolvedDescribedBy()"
|
||||
[attr.aria-invalid]="showInvalid() ? 'true' : null"
|
||||
[attr.aria-busy]="pending() ? 'true' : null"
|
||||
[attr.maxlength]="maxLength()"
|
||||
[attr.minlength]="minLength()"
|
||||
[attr.rows]="rows()"
|
||||
[style.height]="initialHeight()"
|
||||
[style.min-height]="minHeight()"
|
||||
[value]="value()"
|
||||
[disabled]="disabled()"
|
||||
[readonly]="readonly()"
|
||||
[required]="required()"
|
||||
(input)="onInput(textarea)"
|
||||
(blur)="touched.set(true)"></textarea>
|
||||
@if (pending()) {
|
||||
<span class="pointer-events-none absolute right-3 top-2.5 inline-flex text-text-muted">
|
||||
<i class="pi pi-spinner pi-spin text-xs" aria-hidden="true"></i>
|
||||
</span>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppTextareaComponent implements FormValueControl<string> {
|
||||
readonly value = model('');
|
||||
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 touched = model(false);
|
||||
readonly name = input('');
|
||||
|
||||
readonly inputId = input('');
|
||||
readonly placeholder = input('');
|
||||
readonly ariaLabel = input('');
|
||||
readonly ariaDescribedBy = input('');
|
||||
readonly styleClass = input('');
|
||||
readonly readonly = input(false, { transform: booleanAttribute });
|
||||
readonly rows = input<string | number | null>(4);
|
||||
readonly maxLength = input<number | undefined>(undefined);
|
||||
readonly minLength = input<number | undefined>(undefined);
|
||||
readonly autoResize = input(false, { transform: booleanAttribute });
|
||||
|
||||
private readonly fieldContext = inject(APP_FIELD, { optional: true });
|
||||
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 textareaClass = computed(() =>
|
||||
cn(appTextareaVariants({ autoResize: this.autoResize() }), this.pending() && 'pr-10', this.styleClass()),
|
||||
);
|
||||
protected readonly minHeight = computed(() => {
|
||||
const rowCount = Number(this.rows());
|
||||
const rows = Number.isFinite(rowCount) && rowCount > 0 ? rowCount : 4;
|
||||
|
||||
return `calc(${rows} * 1.25rem + 1rem)`;
|
||||
});
|
||||
protected readonly initialHeight = computed(() => (this.autoResize() ? null : this.minHeight()));
|
||||
|
||||
private readonly textarea = viewChild<ElementRef<HTMLTextAreaElement>>('textarea');
|
||||
|
||||
constructor() {
|
||||
afterRenderEffect({
|
||||
mixedReadWrite: () => {
|
||||
this.value();
|
||||
this.autoResize();
|
||||
this.resize();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected onInput(textarea: HTMLTextAreaElement): void {
|
||||
if (this.disabled() || this.readonly()) {
|
||||
textarea.value = this.value();
|
||||
return;
|
||||
}
|
||||
this.value.set(textarea.value);
|
||||
this.resize();
|
||||
}
|
||||
|
||||
focus(options?: FocusOptions): void {
|
||||
this.textarea()?.nativeElement.focus(options);
|
||||
}
|
||||
|
||||
private resize(): void {
|
||||
if (!this.autoResize()) return;
|
||||
|
||||
const textarea = this.textarea()?.nativeElement;
|
||||
if (!textarea) return;
|
||||
|
||||
textarea.style.height = 'auto';
|
||||
textarea.style.height = `${textarea.scrollHeight}px`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { cva } from 'class-variance-authority';
|
||||
import { neutralControlBorderClass } from '../control.styles';
|
||||
|
||||
export const appTextareaVariants = cva(
|
||||
`block w-full rounded-md border ${neutralControlBorderClass} bg-card text-text-strong shadow-control outline-hidden ` +
|
||||
'px-3 py-[0.4375rem] text-sm leading-5 ' +
|
||||
'placeholder:text-text-muted transition-[background-color,border-color,color] duration-150 ' +
|
||||
'focus:border-primary/60 focus:outline-1 focus:outline-offset-0 focus:outline-primary/60 ' +
|
||||
'disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-danger aria-invalid:focus:border-danger aria-invalid:focus:outline-danger',
|
||||
{
|
||||
variants: {
|
||||
autoResize: {
|
||||
true: 'resize-none overflow-hidden',
|
||||
false: 'resize-y',
|
||||
},
|
||||
},
|
||||
defaultVariants: { autoResize: false },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
|
||||
|
||||
const CHIP_CLASS =
|
||||
'pointer-events-none w-fit max-w-xs select-none break-words rounded-md bg-surface-900 ' +
|
||||
'px-2 py-1 text-xs font-medium leading-snug text-surface-50 shadow-pop dark:bg-surface-700';
|
||||
|
||||
@Component({
|
||||
selector: 'app-tooltip',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `<div role="tooltip" [id]="id()" [class]="chipClass">{{ text() }}</div>`,
|
||||
})
|
||||
export class AppTooltipContainerComponent {
|
||||
readonly id = input('');
|
||||
readonly text = input('');
|
||||
|
||||
protected readonly chipClass = CHIP_CLASS;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { FocusMonitor } from '@angular/cdk/a11y';
|
||||
import { Overlay, type OverlayRef } from '@angular/cdk/overlay';
|
||||
import { ComponentPortal } from '@angular/cdk/portal';
|
||||
import {
|
||||
booleanAttribute,
|
||||
DestroyRef,
|
||||
Directive,
|
||||
effect,
|
||||
ElementRef,
|
||||
inject,
|
||||
input,
|
||||
numberAttribute,
|
||||
type ComponentRef,
|
||||
ViewContainerRef,
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { connectedOverlayScrollStrategy, refreshOverlayRefPosition } from '../connected-overlay';
|
||||
import { AppTooltipContainerComponent } from './app-tooltip.container';
|
||||
import { type AppTooltipSide, tooltipPositions } from './app-tooltip.positions';
|
||||
|
||||
let nextId = 0;
|
||||
|
||||
@Directive({
|
||||
selector: '[appTooltip]',
|
||||
standalone: true,
|
||||
host: {
|
||||
'(mouseenter)': 'show()',
|
||||
'(mouseleave)': 'hide()',
|
||||
'(keydown.escape)': 'hide()',
|
||||
},
|
||||
})
|
||||
export class AppTooltipDirective {
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly overlay = inject(Overlay);
|
||||
private readonly vcr = inject(ViewContainerRef);
|
||||
private readonly focusMonitor = inject(FocusMonitor);
|
||||
|
||||
readonly text = input('', { alias: 'appTooltip' });
|
||||
readonly position = input<AppTooltipSide>('top', { alias: 'appTooltipPosition' });
|
||||
readonly disabled = input(false, { alias: 'appTooltipDisabled', transform: booleanAttribute });
|
||||
readonly showDelay = input(0, { alias: 'appTooltipShowDelay', transform: numberAttribute });
|
||||
readonly hideDelay = input(0, { alias: 'appTooltipHideDelay', transform: numberAttribute });
|
||||
|
||||
private readonly id = `app-tooltip-${nextId++}`;
|
||||
private readonly portal = new ComponentPortal(AppTooltipContainerComponent, this.vcr);
|
||||
|
||||
private overlayRef: OverlayRef | null = null;
|
||||
private containerRef: ComponentRef<AppTooltipContainerComponent> | null = null;
|
||||
private previousDescribedBy: string | null = null;
|
||||
private showTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private hideTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.focusMonitor
|
||||
.monitor(this.host)
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe((origin) => {
|
||||
if (origin === 'keyboard' || origin === 'program') this.show();
|
||||
else if (!origin) this.hide();
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const text = this.text();
|
||||
if (this.disabled() || !text.trim()) {
|
||||
this.hide();
|
||||
return;
|
||||
}
|
||||
this.containerRef?.setInput('text', text);
|
||||
});
|
||||
|
||||
inject(DestroyRef).onDestroy(() => {
|
||||
this.clearShowTimer();
|
||||
this.clearHideTimer();
|
||||
this.focusMonitor.stopMonitoring(this.host);
|
||||
this.detach();
|
||||
});
|
||||
}
|
||||
|
||||
protected show(): void {
|
||||
if (this.disabled() || !this.text().trim()) return;
|
||||
this.clearHideTimer();
|
||||
if (this.containerRef || this.showTimer) return;
|
||||
const delay = this.showDelay();
|
||||
if (delay <= 0) {
|
||||
this.attach();
|
||||
return;
|
||||
}
|
||||
this.showTimer = setTimeout(() => {
|
||||
this.showTimer = null;
|
||||
this.attach();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
protected hide(): void {
|
||||
this.clearShowTimer();
|
||||
if (!this.containerRef || this.hideTimer) return;
|
||||
const delay = this.hideDelay();
|
||||
if (delay <= 0) {
|
||||
this.detach();
|
||||
return;
|
||||
}
|
||||
this.hideTimer = setTimeout(() => {
|
||||
this.hideTimer = null;
|
||||
this.detach();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private attach(): void {
|
||||
const overlayRef = this.ensureOverlay();
|
||||
const container = overlayRef.attach(this.portal);
|
||||
this.containerRef = container;
|
||||
container.setInput('id', this.id);
|
||||
container.setInput('text', this.text());
|
||||
this.previousDescribedBy = this.host.nativeElement.getAttribute('aria-describedby');
|
||||
this.host.nativeElement.setAttribute('aria-describedby', this.describedByWithTooltip());
|
||||
|
||||
container.changeDetectorRef.detectChanges();
|
||||
refreshOverlayRefPosition(overlayRef);
|
||||
}
|
||||
|
||||
private ensureOverlay(): OverlayRef {
|
||||
if (this.overlayRef) return this.overlayRef;
|
||||
|
||||
const positionStrategy = this.overlay
|
||||
.position()
|
||||
.flexibleConnectedTo(this.host)
|
||||
.withPositions(tooltipPositions(this.position()))
|
||||
.withPush(true)
|
||||
.withFlexibleDimensions(false)
|
||||
.withViewportMargin(8);
|
||||
|
||||
this.overlayRef = this.overlay.create({
|
||||
positionStrategy,
|
||||
scrollStrategy: connectedOverlayScrollStrategy(this.overlay),
|
||||
panelClass: 'app-tooltip-overlay',
|
||||
});
|
||||
return this.overlayRef;
|
||||
}
|
||||
|
||||
private detach(): void {
|
||||
if (this.containerRef) {
|
||||
this.containerRef = null;
|
||||
this.removeTooltipDescription();
|
||||
this.previousDescribedBy = null;
|
||||
}
|
||||
|
||||
this.overlayRef?.dispose();
|
||||
this.overlayRef = null;
|
||||
}
|
||||
|
||||
private describedByWithTooltip(): string {
|
||||
const ids = new Set((this.previousDescribedBy ?? '').split(/\s+/).filter(Boolean));
|
||||
ids.add(this.id);
|
||||
return Array.from(ids).join(' ');
|
||||
}
|
||||
|
||||
private removeTooltipDescription(): void {
|
||||
const ids = (this.host.nativeElement.getAttribute('aria-describedby') ?? '')
|
||||
.split(/\s+/)
|
||||
.filter((id) => id && id !== this.id);
|
||||
|
||||
if (ids.length) {
|
||||
this.host.nativeElement.setAttribute('aria-describedby', ids.join(' '));
|
||||
return;
|
||||
}
|
||||
|
||||
this.host.nativeElement.removeAttribute('aria-describedby');
|
||||
}
|
||||
|
||||
private clearShowTimer(): void {
|
||||
if (!this.showTimer) return;
|
||||
clearTimeout(this.showTimer);
|
||||
this.showTimer = null;
|
||||
}
|
||||
|
||||
private clearHideTimer(): void {
|
||||
if (!this.hideTimer) return;
|
||||
clearTimeout(this.hideTimer);
|
||||
this.hideTimer = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { type ConnectedPosition } from '@angular/cdk/overlay';
|
||||
|
||||
export type AppTooltipSide = 'top' | 'bottom' | 'left' | 'right';
|
||||
|
||||
const GAP = 8;
|
||||
|
||||
const SIDE_POSITION: Record<AppTooltipSide, ConnectedPosition> = {
|
||||
top: { originX: 'center', originY: 'top', overlayX: 'center', overlayY: 'bottom', offsetY: -GAP },
|
||||
bottom: { originX: 'center', originY: 'bottom', overlayX: 'center', overlayY: 'top', offsetY: GAP },
|
||||
left: { originX: 'start', originY: 'center', overlayX: 'end', overlayY: 'center', offsetX: -GAP },
|
||||
right: { originX: 'end', originY: 'center', overlayX: 'start', overlayY: 'center', offsetX: GAP },
|
||||
};
|
||||
|
||||
const FALLBACKS: Record<AppTooltipSide, AppTooltipSide[]> = {
|
||||
top: ['top', 'bottom', 'right', 'left'],
|
||||
bottom: ['bottom', 'top', 'right', 'left'],
|
||||
left: ['left', 'right', 'top', 'bottom'],
|
||||
right: ['right', 'left', 'bottom', 'top'],
|
||||
};
|
||||
|
||||
export function tooltipPositions(preferred: AppTooltipSide): ConnectedPosition[] {
|
||||
return FALLBACKS[preferred].map((side) => SIDE_POSITION[side]);
|
||||
}
|
||||
Reference in New Issue
Block a user