refactor(ui): new component library (#1740)
This commit is contained in:
@@ -44,6 +44,7 @@
|
||||
"chart.js": "^4.5.1",
|
||||
"chartjs-chart-matrix": "3.0.4",
|
||||
"chartjs-plugin-datalabels": "^2.2.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"date-fns": "^4.4.0",
|
||||
"dompurify": "^3.4.7",
|
||||
"markdown-it": "^14.2.0",
|
||||
@@ -54,6 +55,7 @@
|
||||
"primeicons": "^7.0.0",
|
||||
"primeng": "^21.1.8",
|
||||
"rxjs": "^7.8.2",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tslib": "^2.8.1",
|
||||
"uuid": "^14.0.0"
|
||||
},
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('app routes', () => {
|
||||
const shellRoute = routes.find(route => route.path === '' && Array.isArray(route.children));
|
||||
const children = shellRoute?.children ?? [];
|
||||
|
||||
expect(children).toHaveLength(17);
|
||||
expect(children).toHaveLength(21);
|
||||
expect(shellRoute?.canActivateChild).toEqual([AuthChildGuard]);
|
||||
expect(children.find(route => route.path === 'dashboard')?.canActivate).toBeUndefined();
|
||||
expect(children.find(route => route.path === 'all-books')?.canActivate).toBeUndefined();
|
||||
@@ -38,6 +38,10 @@ describe('app routes', () => {
|
||||
expect(typeof children.find(route => route.path === 'shelf/:shelfId/books')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'unshelved-books')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'magic-shelf/:magicShelfId/books')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'design-system')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'design-system/form/library')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'design-system/form/device')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'design-system/form/everything')?.loadComponent).toBe('function');
|
||||
});
|
||||
|
||||
it('defines guarded lazy routes for metadata, stats, and bookdrop', () => {
|
||||
|
||||
@@ -53,6 +53,10 @@ export const routes: Routes = [
|
||||
{path: 'library-stats', loadComponent: () => import('./features/stats/component/library-stats/library-stats.component').then(m => m.LibraryStatsComponent), canActivate: [LibraryStatsGuard]},
|
||||
{path: 'reading-stats', loadComponent: () => import('./features/stats/component/user-stats/user-stats.component').then(m => m.UserStatsComponent), canActivate: [UserStatsGuard]},
|
||||
{path: 'notebook', loadComponent: () => import('./features/notebook/components/notebook/notebook.component').then(m => m.NotebookComponent)},
|
||||
{path: 'design-system', loadComponent: () => import('./features/design-system/design-system.component').then(m => m.DesignSystemComponent)},
|
||||
{path: 'design-system/form/library', loadComponent: () => import('./features/design-system/forms/library-form.component').then(m => m.LibraryFormExampleComponent)},
|
||||
{path: 'design-system/form/device', loadComponent: () => import('./features/design-system/forms/device-form.component').then(m => m.DeviceFormExampleComponent)},
|
||||
{path: 'design-system/form/everything', loadComponent: () => import('./features/design-system/forms/everything-form.component').then(m => m.EverythingFormExampleComponent)},
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+2
-4
@@ -79,11 +79,9 @@
|
||||
@case ('rating') {
|
||||
<span class="rating-wrapper" [title]="cell.rating === null ? '' : cell.display">
|
||||
<app-rating
|
||||
[value]="cell.rating"
|
||||
readonly
|
||||
[value]="cell.rating ?? 0"
|
||||
[ariaLabel]="cell.rating === null ? t('book.table.noRating') : t('book.table.ratingOutOf', {rating: cell.display, max: 5})" />
|
||||
@if (cell.rating !== null) {
|
||||
<span class="rating-value">({{ cell.display }})</span>
|
||||
}
|
||||
</span>
|
||||
}
|
||||
@case ('clickable') {
|
||||
|
||||
-5
@@ -162,11 +162,6 @@
|
||||
min-width: 6.125rem;
|
||||
}
|
||||
|
||||
.rating-value {
|
||||
color: inherit;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.cell-link {
|
||||
overflow: hidden;
|
||||
color: var(--color-primary-text);
|
||||
|
||||
+2
-1
@@ -85,7 +85,8 @@ describe('BookTableRowComponent', () => {
|
||||
expect(links[0]?.textContent?.trim()).toBe('Alpha');
|
||||
expect(links[0]?.getAttribute('href')).toBe('/book/1');
|
||||
expect(links[1]?.textContent?.trim()).toBe('Test Author');
|
||||
expect(rating?.textContent).toContain('(4.2)');
|
||||
expect(rating?.querySelector('app-rating')).toBeTruthy();
|
||||
expect(rating?.getAttribute('title')).toBe('4.2');
|
||||
expect(cells[3]?.textContent?.trim()).toBe('1.5 MB');
|
||||
});
|
||||
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ import {Book, BookMetadata} from '../../../model/book.model';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
|
||||
import {RatingComponent} from '../../../../../shared/components/rating/rating.component';
|
||||
import {AppRatingComponent} from '../../../../../shared/ui/rating/app-rating.component';
|
||||
import {RATING_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
|
||||
|
||||
interface BookTableCellLink {
|
||||
@@ -89,7 +89,7 @@ const CLICKABLE_FILTER_KEYS: Record<string, string> = {
|
||||
CoverPlaceholderComponent,
|
||||
FormsModule,
|
||||
NgClass,
|
||||
RatingComponent,
|
||||
AppRatingComponent,
|
||||
RouterLink,
|
||||
Tooltip,
|
||||
TranslocoDirective,
|
||||
|
||||
@@ -0,0 +1,608 @@
|
||||
<main cdkScrollable class="design-system-page">
|
||||
<header class="page-header flex flex-wrap items-center justify-between gap-3">
|
||||
<h1>Design System</h1>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<app-button variant="soft" size="sm" icon="pi pi-folder" label="Create library" (clicked)="openExample('library')" />
|
||||
<app-button variant="soft" size="sm" icon="pi pi-mobile" label="Device settings" (clicked)="openExample('device')" />
|
||||
<app-button variant="soft" size="sm" icon="pi pi-list" label="Everything" (clicked)="openExample('everything')" />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Buttons</h2>
|
||||
|
||||
<div class="variant-grid">
|
||||
@for (example of buttonExamples; track example.tone + example.variant) {
|
||||
<div class="variant-cell">
|
||||
<span class="variant-label">{{ example.tone }} / {{ example.variant }}</span>
|
||||
<div class="button-row">
|
||||
@for (size of buttonSizes; track size) {
|
||||
<app-button
|
||||
[tone]="example.tone"
|
||||
[variant]="example.variant"
|
||||
[size]="size"
|
||||
icon="pi pi-bolt"
|
||||
[label]="size" />
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="sample-row">
|
||||
<app-button iconOnly icon="pi pi-chevron-left" ariaLabel="Previous" />
|
||||
<app-button iconOnly rounded icon="pi pi-heart" ariaLabel="Favourite" />
|
||||
<app-button label="Loading" icon="pi pi-save" loading />
|
||||
<app-button label="Disabled" disabled />
|
||||
<app-button fluid label="Full width" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Split Buttons</h2>
|
||||
|
||||
<div class="sample-row">
|
||||
<app-split-button
|
||||
tone="primary"
|
||||
label="Open"
|
||||
icon="pi pi-folder-open"
|
||||
[model]="menuItems" />
|
||||
<app-split-button
|
||||
label="Download"
|
||||
icon="pi pi-download"
|
||||
[model]="menuItems" />
|
||||
<app-split-button
|
||||
tone="danger"
|
||||
variant="soft"
|
||||
label="Delete"
|
||||
icon="pi pi-trash"
|
||||
[model]="menuItems" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Inputs</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>Small</span>
|
||||
<app-input size="sm" placeholder="Small input" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Medium</span>
|
||||
<app-input [(value)]="inputValue" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Large</span>
|
||||
<app-input size="lg" placeholder="Large input" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Invalid</span>
|
||||
<app-input invalid value="Needs attention" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Disabled</span>
|
||||
<app-input disabled value="Disabled input" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Password</span>
|
||||
<app-input type="password" value="password" revealToggle />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Trailing Action</span>
|
||||
<app-input value="Search text" trailingIcon="pi pi-times" trailingAriaLabel="Clear text" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Leading Icon</span>
|
||||
<app-input type="search" leadingIcon="pi pi-search" placeholder="Search..." />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Leading + Trailing</span>
|
||||
<app-input
|
||||
type="search"
|
||||
value="Search text"
|
||||
leadingIcon="pi pi-search"
|
||||
trailingIcon="pi pi-times"
|
||||
trailingAriaLabel="Clear search" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Number Inputs</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>Range (8-72)</span>
|
||||
<app-number-input [(value)]="fontSizeValue" [min]="8" [max]="72" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Step 0.5</span>
|
||||
<app-number-input [(value)]="weightValue" [min]="0" [max]="10" [step]="0.5" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>With unit</span>
|
||||
<app-number-input [value]="250" [min]="1" [max]="1000" unit="MB" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Disabled</span>
|
||||
<app-number-input [value]="42" disabled />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Sliders</h2>
|
||||
|
||||
<div class="flex max-w-md flex-col gap-5">
|
||||
<div class="field">
|
||||
<span>Range value ({{ aspectRatioValue.toFixed(1) }})</span>
|
||||
<app-slider [(value)]="aspectRatioValue" [min]="1.5" [max]="3" [step]="0.1" ariaLabel="Range value" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Percentage ({{ compressionValue }}%)</span>
|
||||
<app-slider [(value)]="compressionValue" [min]="1" [max]="100" ariaLabel="Percentage" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Disabled</span>
|
||||
<app-slider [value]="40" disabled ariaLabel="Disabled slider" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Ratings</h2>
|
||||
|
||||
<div class="flex flex-col gap-5">
|
||||
<div class="field">
|
||||
<span>Expandable ({{ personalRating }})</span>
|
||||
<app-rating [(value)]="personalRating" expandable ariaLabel="Expandable rating" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Editable ({{ ratingValue }})</span>
|
||||
<app-rating [(value)]="ratingValue" ariaLabel="Editable rating" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Read-only</span>
|
||||
<app-rating [value]="4.3" readonly showValue />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Sizes</span>
|
||||
<div class="flex items-center gap-4">
|
||||
<app-rating [value]="3.5" readonly size="sm" />
|
||||
<app-rating [value]="3.5" readonly size="md" />
|
||||
<app-rating [value]="3.5" readonly size="lg" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Disabled</span>
|
||||
<app-rating [value]="3" disabled ariaLabel="Disabled rating" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Checkboxes</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>Default</span>
|
||||
<app-checkbox ariaLabel="Default checkbox" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Checked</span>
|
||||
<app-checkbox [(checked)]="checkboxAccepted" ariaLabel="Checked checkbox" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Indeterminate</span>
|
||||
<app-checkbox [indeterminate]="true" ariaLabel="Indeterminate checkbox" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Disabled</span>
|
||||
<app-checkbox disabled [checked]="true" ariaLabel="Disabled checkbox" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Switches</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>Off</span>
|
||||
<app-switch ariaLabel="Off switch" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>On</span>
|
||||
<app-switch [(checked)]="switchEnabled" ariaLabel="On switch" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Disabled</span>
|
||||
<app-switch disabled [checked]="true" ariaLabel="Disabled switch" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Small</span>
|
||||
<app-switch size="sm" [checked]="true" ariaLabel="Small switch" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Large</span>
|
||||
<app-switch size="lg" [checked]="true" ariaLabel="Large switch" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="input-grid">
|
||||
<app-field label="Labeled switch" hint="Inline help text.">
|
||||
<app-switch [(checked)]="switchEnabled" />
|
||||
</app-field>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Radio Groups</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>List</span>
|
||||
<app-radio-group [(value)]="radioViewValue" [options]="radioViewOptions" ariaLabel="Options" />
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<span>Segmented</span>
|
||||
<app-radio-group variant="segmented" [(value)]="radioViewValue" [options]="radioViewOptions" ariaLabel="Segmented options" />
|
||||
</div>
|
||||
|
||||
<app-field label="Radio group" hint="Choose one.">
|
||||
<app-radio-group [formField]="profileForm.viewMode" [options]="radioViewOptions" />
|
||||
</app-field>
|
||||
</div>
|
||||
|
||||
<div class="input-grid">
|
||||
<app-radio-group variant="card" [(value)]="radioDensityValue" [options]="radioDensityOptions" ariaLabel="Card options" />
|
||||
|
||||
<app-field label="Card radio group" hint="Card layout with descriptions.">
|
||||
<app-radio-group variant="card" [(value)]="radioDensityValue" [options]="radioDensityOptions" />
|
||||
</app-field>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Selects</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>Default</span>
|
||||
<app-select
|
||||
[(value)]="selectValue"
|
||||
[options]="selectOptions" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Small</span>
|
||||
<app-select
|
||||
size="sm"
|
||||
[options]="selectOptions"
|
||||
placeholder="Choose option" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Clearable</span>
|
||||
<app-select
|
||||
showClear
|
||||
[options]="selectOptions"
|
||||
placeholder="Choose option" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Filter</span>
|
||||
<app-select
|
||||
filter
|
||||
[options]="selectOptions"
|
||||
placeholder="Search options" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Grouped</span>
|
||||
<app-select
|
||||
[groups]="groupedSelectOptions"
|
||||
placeholder="Choose option" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Swatches</span>
|
||||
<app-select
|
||||
[(value)]="themeValue"
|
||||
[options]="themeSelectOptions">
|
||||
<ng-template appSelectSelected let-option>
|
||||
@if (option) {
|
||||
<span class="select-rich-option">
|
||||
<span class="select-swatch" [style.background]="$any(option).color"></span>
|
||||
<span>{{ $any(option).label }}</span>
|
||||
</span>
|
||||
}
|
||||
</ng-template>
|
||||
<ng-template appSelectOption let-option>
|
||||
<span class="select-rich-option">
|
||||
<span class="select-swatch" [style.background]="$any(option).color"></span>
|
||||
<span>{{ $any(option).label }}</span>
|
||||
</span>
|
||||
</ng-template>
|
||||
</app-select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Invalid</span>
|
||||
<app-select
|
||||
invalid
|
||||
[options]="selectOptions"
|
||||
placeholder="Choose option" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Disabled</span>
|
||||
<app-select
|
||||
disabled
|
||||
value="a"
|
||||
[options]="selectOptions" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Multiple</span>
|
||||
<app-multi-select
|
||||
showClear
|
||||
filter
|
||||
[(value)]="multiSelectValue"
|
||||
[options]="selectOptions"
|
||||
placeholder="Choose options" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Date Pickers</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>Default</span>
|
||||
<app-date-picker [(value)]="dateValue" placeholder="Select a date" ariaLabel="Example date" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Small</span>
|
||||
<app-date-picker size="sm" [(value)]="dateValue" placeholder="Select a date" ariaLabel="Small date" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Bounded (this month)</span>
|
||||
<app-date-picker
|
||||
[(value)]="dateValue"
|
||||
minDate="2026-06-01"
|
||||
maxDate="2026-06-30"
|
||||
placeholder="Within June"
|
||||
ariaLabel="Bounded date" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Range</span>
|
||||
<app-date-range-picker [(value)]="dateRangeValue" placeholder="Select a range" ariaLabel="Date range" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<app-field [field]="profileForm.birthday" label="Birthday">
|
||||
<app-date-picker [formField]="profileForm.birthday" placeholder="Pick a date" />
|
||||
</app-field>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Autocomplete</h2>
|
||||
|
||||
<div class="max-w-md">
|
||||
<app-autocomplete
|
||||
[(value)]="autocompleteValue"
|
||||
[suggestions]="filteredAutocompleteOptions()"
|
||||
(complete)="filterAutocompleteOptions($event)"
|
||||
placeholder="Start typing..."
|
||||
ariaLabel="Autocomplete" />
|
||||
</div>
|
||||
<div class="max-w-md">
|
||||
<app-multi-autocomplete
|
||||
[(value)]="tags"
|
||||
[suggestions]="filteredTags()"
|
||||
(complete)="filterTags($event)"
|
||||
placeholder="Add tags..."
|
||||
ariaLabel="Tags"
|
||||
removeTagLabel="Remove tag" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Textareas</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<div class="field">
|
||||
<span>Default</span>
|
||||
<app-textarea [(value)]="textareaValue" rows="1" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Auto Resize</span>
|
||||
<app-textarea autoResize rows="2" value="Example text" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Invalid</span>
|
||||
<app-textarea invalid rows="1" value="Needs attention" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Form Fields</h2>
|
||||
|
||||
<div class="input-grid">
|
||||
<app-field label="Display name" hint="Required.">
|
||||
<app-input [formField]="profileForm.displayName" placeholder="Display name" />
|
||||
</app-field>
|
||||
|
||||
<app-field label="Email" hint="Valid email address.">
|
||||
<app-input type="email" [formField]="profileForm.email" placeholder="name@example.com" />
|
||||
</app-field>
|
||||
|
||||
<app-field label="Notes" hint="At least 10 characters.">
|
||||
<app-textarea [formField]="profileForm.bio" rows="2" placeholder="Notes" />
|
||||
</app-field>
|
||||
|
||||
<app-field label="Static error" hint="Hint stays visible with errors." [errors]="['Required field.']">
|
||||
<app-input value="Example value" invalid />
|
||||
</app-field>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Messages</h2>
|
||||
|
||||
<div class="flex max-w-md flex-col gap-2">
|
||||
<app-message color="neutral">Neutral message.</app-message>
|
||||
<app-message color="primary">Primary message.</app-message>
|
||||
<app-message color="green">Success message.</app-message>
|
||||
<app-message color="amber">Warning message.</app-message>
|
||||
<app-message color="red">Error message.</app-message>
|
||||
</div>
|
||||
|
||||
<p class="text-sm text-text-muted dark:text-text-secondary">
|
||||
Group validation:
|
||||
</p>
|
||||
<div class="flex max-w-md flex-wrap items-center gap-2">
|
||||
<app-button label="Validate group" (clicked)="validateSyncGroup()" />
|
||||
<app-message inline [field]="syncForm.sync" />
|
||||
</div>
|
||||
|
||||
<p class="text-sm text-text-muted dark:text-text-secondary">
|
||||
Form summary:
|
||||
</p>
|
||||
<div class="flex max-w-md flex-col gap-2">
|
||||
<app-message [field]="profileForm" summary />
|
||||
<app-message [field]="profileForm" summary summaryLayout="inline" />
|
||||
<app-button label="Validate page" (clicked)="validateProfile()" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Accordion</h2>
|
||||
|
||||
<div class="max-w-md">
|
||||
<app-accordion [items]="accordionItems" [(value)]="accordionValue">
|
||||
<ng-template appAccordionHeader let-item>{{ item.title }}</ng-template>
|
||||
<ng-template appAccordionActions>
|
||||
<app-button size="sm" variant="ghost" icon="pi pi-cog" iconOnly ariaLabel="Configure" />
|
||||
</ng-template>
|
||||
<ng-template appAccordionContent let-item>{{ item.body }}</ng-template>
|
||||
</app-accordion>
|
||||
</div>
|
||||
|
||||
<p class="text-sm text-text-muted dark:text-text-secondary">Multiple items open.</p>
|
||||
<div class="max-w-md">
|
||||
<app-accordion multiple [items]="accordionItems" [(value)]="accordionMultiValue">
|
||||
<ng-template appAccordionHeader let-item>
|
||||
<span class="inline-flex items-center gap-2"><i class="pi pi-folder text-text-muted" aria-hidden="true"></i>{{ item.title }}</span>
|
||||
</ng-template>
|
||||
<ng-template appAccordionContent let-item>{{ item.body }}</ng-template>
|
||||
</app-accordion>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Spinners</h2>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-6">
|
||||
<app-spinner size="sm" ariaLabel="Loading" />
|
||||
<app-spinner size="md" ariaLabel="Loading" />
|
||||
<app-spinner size="lg" ariaLabel="Loading" />
|
||||
<app-spinner size="lg" styleClass="text-text-muted" ariaLabel="Loading" />
|
||||
<span class="inline-flex items-center gap-2 text-sm text-text-muted dark:text-text-secondary">
|
||||
<app-spinner size="sm" ariaLabel="Loading" /> Loading...
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Menus</h2>
|
||||
|
||||
<app-button label="Open menu" icon="pi pi-ellipsis-v" (clicked)="debugMenu.toggle($event)" />
|
||||
<app-menu #debugMenu [model]="menuItems" />
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Tooltips</h2>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<app-button label="Top" [appTooltip]="'Defaults to the top'" />
|
||||
<app-button label="Bottom" [appTooltip]="'Below the trigger'" appTooltipPosition="bottom" />
|
||||
<app-button label="Left" [appTooltip]="'To the left'" appTooltipPosition="left" />
|
||||
<app-button label="Right" [appTooltip]="'To the right'" appTooltipPosition="right" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Tags</h2>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<app-tag label="Neutral" />
|
||||
<app-tag color="primary" label="Primary" />
|
||||
<app-tag color="green" label="Green" />
|
||||
<app-tag color="red" label="Red" />
|
||||
<app-tag color="amber" label="Amber" />
|
||||
<app-tag color="sky" label="Sky" />
|
||||
<app-tag color="blue" label="Blue" />
|
||||
<app-tag color="teal" label="Teal" />
|
||||
<app-tag color="indigo" label="Indigo" />
|
||||
<app-tag color="purple" label="Purple" />
|
||||
<app-tag color="pink" label="Pink" />
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<app-tag size="sm" color="green" label="Small" />
|
||||
<app-tag size="md" color="green" label="Medium" />
|
||||
<app-tag color="amber" icon="pi pi-exclamation-triangle" label="With icon" />
|
||||
<app-tag color="sky">Projected content</app-tag>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<app-tag color="blue" clickable label="Clickable" ariaLabel="Clickable tag" />
|
||||
<app-tag color="indigo" removable label="Removable" removeLabel="Remove tag" />
|
||||
<app-tag customColor="#6366f1" label="Custom color" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Tabs</h2>
|
||||
|
||||
<div class="flex min-w-0 flex-col gap-6">
|
||||
<app-tabs
|
||||
[tabs]="settingsTabs"
|
||||
variant="underline"
|
||||
ariaLabel="Underline tabs example"
|
||||
[(selectedTabId)]="underlineTab"
|
||||
/>
|
||||
<app-tabs
|
||||
[tabs]="settingsTabs"
|
||||
variant="segmented"
|
||||
ariaLabel="Segmented tabs example"
|
||||
[(selectedTabId)]="segmentedTab"
|
||||
/>
|
||||
<div class="flex min-w-0 flex-col items-start gap-3">
|
||||
<app-tabs
|
||||
[tabs]="settingsTabs"
|
||||
variant="segmented"
|
||||
size="sm"
|
||||
collapse="never"
|
||||
ariaLabel="Small segmented tabs"
|
||||
[(selectedTabId)]="segmentedTabSm"
|
||||
/>
|
||||
<app-tabs
|
||||
[tabs]="settingsTabs"
|
||||
variant="segmented"
|
||||
size="lg"
|
||||
collapse="never"
|
||||
ariaLabel="Large segmented tabs"
|
||||
[(selectedTabId)]="segmentedTabLg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<app-tabs
|
||||
[tabs]="manyTabs"
|
||||
variant="underline"
|
||||
ariaLabel="Many tabs example"
|
||||
[(selectedTabId)]="manyTab"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</main>
|
||||
@@ -0,0 +1,112 @@
|
||||
:host {
|
||||
display: block;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.design-system-page {
|
||||
box-sizing: border-box;
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
align-content: start;
|
||||
height: 100%;
|
||||
padding: 2rem;
|
||||
overflow-y: auto;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.page-header {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: var(--color-text-strong);
|
||||
font-size: 2rem;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: var(--color-text-strong);
|
||||
font-size: 1.1rem;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.showcase-section {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.showcase-section + .showcase-section {
|
||||
padding-top: 1.5rem;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.variant-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.variant-cell {
|
||||
display: grid;
|
||||
gap: 0.625rem;
|
||||
min-width: 0;
|
||||
padding: 0.875rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.variant-label,
|
||||
.field > span {
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.button-row,
|
||||
.sample-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.input-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
align-items: start;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.select-rich-option {
|
||||
display: inline-flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.select-swatch {
|
||||
width: 0.875rem;
|
||||
height: 0.875rem;
|
||||
flex: 0 0 auto;
|
||||
border-radius: 999px;
|
||||
box-shadow: inset 0 0 0 1px rgb(0 0 0 / 15%);
|
||||
}
|
||||
|
||||
@media (width <= 640px) {
|
||||
.design-system-page {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||
import { CdkScrollable } from '@angular/cdk/scrolling';
|
||||
import { Router } from '@angular/router';
|
||||
import { email, form, FormField, minLength, required, validate } from '@angular/forms/signals';
|
||||
import { MenuItem } from 'primeng/api';
|
||||
import { AppAccordionComponent } from '../../shared/ui/accordion/app-accordion.component';
|
||||
import {
|
||||
AppAccordionActionsDirective,
|
||||
AppAccordionContentDirective,
|
||||
AppAccordionHeaderDirective,
|
||||
} from '../../shared/ui/accordion/app-accordion.directives';
|
||||
import { AppAutocompleteComponent } from '../../shared/ui/autocomplete/app-autocomplete.component';
|
||||
import { AppMultiAutocompleteComponent } from '../../shared/ui/autocomplete/app-multi-autocomplete.component';
|
||||
import { AppButtonComponent } from '../../shared/ui/button/app-button.component';
|
||||
import { type ButtonSize, type ButtonTone, type ButtonVariant } from '../../shared/ui/button/app-button.variants';
|
||||
import { AppCheckboxComponent } from '../../shared/ui/checkbox/app-checkbox.component';
|
||||
import { AppDatePickerComponent } from '../../shared/ui/date-picker/app-date-picker.component';
|
||||
import { AppDateRangePickerComponent, type DatePickerRange } from '../../shared/ui/date-picker/app-date-range-picker.component';
|
||||
import { AppFieldComponent } from '../../shared/ui/field/app-field.component';
|
||||
import { AppInputComponent } from '../../shared/ui/input/app-input.component';
|
||||
import { AppMenuComponent } from '../../shared/ui/menu/app-menu.component';
|
||||
import { AppMessageComponent } from '../../shared/ui/message/app-message.component';
|
||||
import { AppNumberInputComponent } from '../../shared/ui/number-input/app-number-input.component';
|
||||
import { appMenuSection, appMenuSeparator } from '../../shared/ui/menu/app-menu.items';
|
||||
import { AppRadioGroupComponent, type RadioOption } from '../../shared/ui/radio-group/app-radio-group.component';
|
||||
import { AppRatingComponent } from '../../shared/ui/rating/app-rating.component';
|
||||
import { AppMultiSelectComponent } from '../../shared/ui/select/app-multi-select.component';
|
||||
import { AppSelectComponent } from '../../shared/ui/select/app-select.component';
|
||||
import { type SelectOption, type SelectOptionGroup } from '../../shared/ui/select/app-select.options';
|
||||
import { AppSelectOptionTemplateDirective, AppSelectSelectedTemplateDirective } from '../../shared/ui/select/app-select.templates';
|
||||
import { AppSliderComponent } from '../../shared/ui/slider/app-slider.component';
|
||||
import { AppSpinnerComponent } from '../../shared/ui/spinner/app-spinner.component';
|
||||
import { AppSplitButtonComponent } from '../../shared/ui/split-button/app-split-button.component';
|
||||
import { AppSwitchComponent } from '../../shared/ui/switch/app-switch.component';
|
||||
import { AppTabsComponent, type TabItem } from '../../shared/ui/tabs/app-tabs.component';
|
||||
import { AppTagComponent } from '../../shared/ui/tag/app-tag.component';
|
||||
import { AppTextareaComponent } from '../../shared/ui/textarea/app-textarea.component';
|
||||
import { AppTooltipDirective } from '../../shared/ui/tooltip/app-tooltip.directive';
|
||||
|
||||
interface ButtonExample {
|
||||
tone: ButtonTone;
|
||||
variant: ButtonVariant;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-design-system',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CdkScrollable,
|
||||
AppAccordionComponent,
|
||||
AppAccordionHeaderDirective,
|
||||
AppAccordionContentDirective,
|
||||
AppAccordionActionsDirective,
|
||||
AppAutocompleteComponent,
|
||||
AppMultiAutocompleteComponent,
|
||||
AppButtonComponent,
|
||||
AppCheckboxComponent,
|
||||
AppDatePickerComponent,
|
||||
AppDateRangePickerComponent,
|
||||
AppFieldComponent,
|
||||
AppInputComponent,
|
||||
AppMenuComponent,
|
||||
AppMessageComponent,
|
||||
AppNumberInputComponent,
|
||||
AppRadioGroupComponent,
|
||||
AppRatingComponent,
|
||||
AppMultiSelectComponent,
|
||||
AppSelectComponent,
|
||||
AppSelectOptionTemplateDirective,
|
||||
AppSelectSelectedTemplateDirective,
|
||||
AppSliderComponent,
|
||||
AppSpinnerComponent,
|
||||
AppSplitButtonComponent,
|
||||
AppSwitchComponent,
|
||||
AppTabsComponent,
|
||||
AppTagComponent,
|
||||
AppTextareaComponent,
|
||||
AppTooltipDirective,
|
||||
FormField,
|
||||
],
|
||||
templateUrl: './design-system.component.html',
|
||||
styleUrl: './design-system.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class DesignSystemComponent {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
openExample(path: string): void {
|
||||
void this.router.navigate(['/design-system', 'form', path]);
|
||||
}
|
||||
|
||||
readonly buttonExamples: ButtonExample[] = [
|
||||
{ tone: 'neutral', variant: 'soft' },
|
||||
{ tone: 'neutral', variant: 'solid' },
|
||||
{ tone: 'neutral', variant: 'ghost' },
|
||||
{ tone: 'primary', variant: 'soft' },
|
||||
{ tone: 'primary', variant: 'solid' },
|
||||
{ tone: 'primary', variant: 'ghost' },
|
||||
{ tone: 'danger', variant: 'soft' },
|
||||
{ tone: 'danger', variant: 'solid' },
|
||||
{ tone: 'danger', variant: 'ghost' },
|
||||
];
|
||||
readonly buttonSizes: ButtonSize[] = ['sm', 'md', 'lg'];
|
||||
readonly menuItems: MenuItem[] = [
|
||||
appMenuSection('Actions'),
|
||||
{ label: 'Rename' },
|
||||
{ label: 'Duplicate' },
|
||||
appMenuSeparator(),
|
||||
appMenuSection('Danger'),
|
||||
{ label: 'Delete', styleClass: 'app-menu-item-destructive' },
|
||||
];
|
||||
readonly selectOptions: SelectOption<string>[] = [
|
||||
{ label: 'Option A', value: 'a' },
|
||||
{ label: 'Option B', value: 'b' },
|
||||
{ label: 'Option C', value: 'c' },
|
||||
];
|
||||
readonly groupedSelectOptions: SelectOptionGroup<string>[] = [
|
||||
{
|
||||
label: 'Group A',
|
||||
options: [
|
||||
{ label: 'Option A', value: 'a' },
|
||||
{ label: 'Option B', value: 'b' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Group B',
|
||||
options: [
|
||||
{ label: 'Option C', value: 'c' },
|
||||
{ label: 'Option D', value: 'd' },
|
||||
],
|
||||
},
|
||||
];
|
||||
readonly themeSelectOptions = [
|
||||
{ label: 'Green', value: 'green', color: 'var(--color-green-500)' },
|
||||
{ label: 'Blue', value: 'blue', color: 'var(--color-blue-500)' },
|
||||
{ label: 'Rose', value: 'rose', color: 'var(--color-rose-500)' },
|
||||
];
|
||||
|
||||
readonly settingsTabs: TabItem[] = [
|
||||
{ id: 'general', label: 'General', icon: 'pi pi-cog' },
|
||||
{ id: 'metadata', label: 'Metadata', icon: 'pi pi-tag' },
|
||||
{ id: 'formats', label: 'Formats', icon: 'pi pi-file' },
|
||||
];
|
||||
readonly manyTabs: TabItem[] = [
|
||||
{ id: 'general', label: 'General' },
|
||||
{ id: 'metadata', label: 'Metadata' },
|
||||
{ id: 'formats', label: 'Formats' },
|
||||
{ id: 'readers', label: 'Readers' },
|
||||
{ id: 'integrations', label: 'Integrations' },
|
||||
{ id: 'notifications', label: 'Notifications' },
|
||||
{ id: 'security', label: 'Security' },
|
||||
{ id: 'advanced', label: 'Advanced' },
|
||||
];
|
||||
readonly underlineTab = signal<string | undefined>('general');
|
||||
readonly segmentedTab = signal<string | undefined>('general');
|
||||
readonly segmentedTabSm = signal<string | undefined>('general');
|
||||
readonly segmentedTabLg = signal<string | undefined>('general');
|
||||
readonly manyTab = signal<string | undefined>('general');
|
||||
|
||||
readonly radioViewOptions: RadioOption<string>[] = [
|
||||
{ label: 'List', value: 'list' },
|
||||
{ label: 'Grid', value: 'grid' },
|
||||
{ label: 'Cards', value: 'cards' },
|
||||
];
|
||||
readonly radioDensityOptions: RadioOption<string>[] = [
|
||||
{ label: 'Compact', value: 'compact', description: 'Tighter rows.' },
|
||||
{ label: 'Comfortable', value: 'comfortable', description: 'Default spacing.' },
|
||||
{ label: 'Spacious', value: 'spacious', description: 'Larger gaps.' },
|
||||
];
|
||||
|
||||
inputValue = 'Example title';
|
||||
autocompleteValue = '';
|
||||
readonly autocompleteOptions = [
|
||||
'Alpha',
|
||||
'Beta',
|
||||
'Gamma',
|
||||
'Delta',
|
||||
'Epsilon',
|
||||
'Zeta',
|
||||
];
|
||||
readonly filteredAutocompleteOptions = signal<string[]>([]);
|
||||
tags: string[] = ['Tag one'];
|
||||
readonly allTags = ['Tag one', 'Tag two', 'Tag three', 'Tag four', 'Tag five'];
|
||||
readonly filteredTags = signal<string[]>([]);
|
||||
readonly accordionItems = [
|
||||
{ title: 'General', body: 'General content.' },
|
||||
{ title: 'Details', body: 'Details content.' },
|
||||
{ title: 'Settings', body: 'Settings content.' },
|
||||
];
|
||||
accordionValue: number | null = 0;
|
||||
accordionMultiValue: number[] = [0];
|
||||
fontSizeValue: number | null = 16;
|
||||
weightValue: number | null = 5;
|
||||
aspectRatioValue = 2.1;
|
||||
compressionValue = 70;
|
||||
personalRating = 3.5;
|
||||
ratingValue = 4;
|
||||
checkboxAccepted = true;
|
||||
switchEnabled = true;
|
||||
selectValue: string | null = 'a';
|
||||
multiSelectValue: string[] = ['a', 'c'];
|
||||
themeValue: string | null = 'green';
|
||||
textareaValue = 'Example notes';
|
||||
radioViewValue: string | null = 'list';
|
||||
radioDensityValue: string | null = 'comfortable';
|
||||
dateValue = '';
|
||||
dateRangeValue: DatePickerRange = { start: '', end: '' };
|
||||
|
||||
readonly profileModel = signal<{
|
||||
displayName: string;
|
||||
email: string;
|
||||
bio: string;
|
||||
viewMode: string | null;
|
||||
birthday: string;
|
||||
}>({ displayName: '', email: '', bio: '', viewMode: null, birthday: '' });
|
||||
readonly profileForm = form(this.profileModel, (path) => {
|
||||
required(path.displayName, { message: 'Display name is required' });
|
||||
email(path.email, { message: 'Enter a valid email' });
|
||||
minLength(path.bio, 10, { message: 'Use at least 10 characters' });
|
||||
required(path.viewMode, { message: 'Choose an option' });
|
||||
required(path.birthday, { message: 'Pick a date' });
|
||||
});
|
||||
|
||||
readonly syncModel = signal({ sync: { enabled: true, host: '' } });
|
||||
readonly syncForm = form(this.syncModel, (path) => {
|
||||
validate(path.sync, ({ value }) =>
|
||||
value().enabled && !value().host
|
||||
? { kind: 'valueRequired', message: 'Enter a value to continue' }
|
||||
: null,
|
||||
);
|
||||
});
|
||||
|
||||
validateSyncGroup(): void {
|
||||
this.syncForm.sync().markAsTouched();
|
||||
}
|
||||
|
||||
validateProfile(): void {
|
||||
this.profileForm().markAsTouched();
|
||||
}
|
||||
|
||||
filterAutocompleteOptions(query: string): void {
|
||||
const q = query.trim().toLowerCase();
|
||||
this.filteredAutocompleteOptions.set(
|
||||
q ? this.autocompleteOptions.filter((option) => option.toLowerCase().includes(q)) : [],
|
||||
);
|
||||
}
|
||||
|
||||
filterTags(query: string): void {
|
||||
const q = query.trim().toLowerCase();
|
||||
this.filteredTags.set(q ? this.allTags.filter((tag) => tag.toLowerCase().includes(q)) : []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<main cdkScrollable class="h-full overflow-y-auto bg-page p-6 text-text sm:p-8">
|
||||
<div class="mx-auto flex w-full max-w-2xl flex-col gap-6">
|
||||
<header class="flex flex-col gap-3">
|
||||
<app-button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="pi pi-chevron-left"
|
||||
label="Back to design system"
|
||||
styleClass="self-start"
|
||||
(clicked)="back()" />
|
||||
<div class="flex flex-col gap-1">
|
||||
<h1 class="text-2xl font-extrabold text-text-strong">Device settings</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<app-tag [color]="deviceForm().valid() ? 'green' : 'red'" [label]="deviceForm().valid() ? 'valid' : 'invalid'" />
|
||||
<app-tag [color]="deviceForm().dirty() ? 'amber' : 'neutral'" [label]="deviceForm().dirty() ? 'dirty' : 'pristine'" />
|
||||
<app-tag [color]="deviceForm().touched() ? 'sky' : 'neutral'" [label]="deviceForm().touched() ? 'touched' : 'untouched'" />
|
||||
@if (deviceForm().submitting()) {
|
||||
<app-tag color="primary" icon="pi pi-spin pi-spinner" label="submitting" />
|
||||
}
|
||||
</div>
|
||||
|
||||
<form [formRoot]="deviceForm" class="flex flex-col divide-y divide-border">
|
||||
<section class="flex flex-col gap-5 pb-7">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<h2 class="m-0 inline-flex items-center gap-2 text-base font-bold text-text-strong">
|
||||
<i class="pi pi-book text-text-muted" aria-hidden="true"></i> Hardcover
|
||||
</h2>
|
||||
<app-switch [formField]="deviceForm.hardcover.enabled" ariaLabel="Enable Hardcover sync" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (!deviceForm.hardcover.apiKey().hidden()) {
|
||||
<app-field [field]="deviceForm.hardcover.apiKey" label="API key" hint='Starts with "hc_".'>
|
||||
<app-input type="password" revealToggle [formField]="deviceForm.hardcover.apiKey" placeholder="hc_…" />
|
||||
</app-field>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="flex flex-col gap-5 py-7">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<h2 class="m-0 inline-flex items-center gap-2 text-base font-bold text-text-strong">
|
||||
<i class="pi pi-tablet text-text-muted" aria-hidden="true"></i> Kobo
|
||||
</h2>
|
||||
<app-switch [formField]="deviceForm.kobo.enabled" ariaLabel="Enable Kobo sync" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (!deviceForm.kobo.twoWaySync().hidden()) {
|
||||
<app-field [field]="deviceForm.kobo.twoWaySync" label="Two-way progress sync" hint="Requires KEPUB.">
|
||||
<app-switch [formField]="deviceForm.kobo.twoWaySync" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="deviceForm.kobo.convertToKepub" label="Convert to KEPUB" hint="Needed for two-way sync.">
|
||||
<app-switch [formField]="deviceForm.kobo.convertToKepub" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="deviceForm.kobo.markAsReading" label="Mark as reading at {{ model().kobo.markAsReading }}%" hint="1-10%.">
|
||||
<app-slider [formField]="deviceForm.kobo.markAsReading" ariaLabel="Mark as reading threshold" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="deviceForm.kobo.markAsFinished" label="Mark as finished at {{ model().kobo.markAsFinished }}%" hint="90-100%.">
|
||||
<app-slider [formField]="deviceForm.kobo.markAsFinished" ariaLabel="Mark as finished threshold" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="deviceForm.kobo.conversionLimitMb" label="Conversion size limit" hint="1-250 MB.">
|
||||
<app-number-input [formField]="deviceForm.kobo.conversionLimitMb" unit="MB" />
|
||||
</app-field>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="flex flex-col gap-5 py-7">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<h2 class="m-0 inline-flex items-center gap-2 text-base font-bold text-text-strong">
|
||||
<i class="pi pi-mobile text-text-muted" aria-hidden="true"></i> KOReader
|
||||
</h2>
|
||||
<app-switch [formField]="deviceForm.koreader.enabled" ariaLabel="Enable KOReader sync" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (!deviceForm.koreader.username().hidden()) {
|
||||
<app-field [field]="deviceForm.koreader.syncWithWebReader" label="Also sync with the web reader" hint="Shares progress.">
|
||||
<app-switch [formField]="deviceForm.koreader.syncWithWebReader" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="deviceForm.koreader.username" label="Sync username" hint="Required when enabled.">
|
||||
<app-input [formField]="deviceForm.koreader.username" placeholder="reader" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="deviceForm.koreader.password" label="Sync password" hint="At least 6 characters.">
|
||||
<app-input type="password" revealToggle [formField]="deviceForm.koreader.password" placeholder="••••••" />
|
||||
</app-field>
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-3 pt-6">
|
||||
<app-button
|
||||
type="submit"
|
||||
tone="primary"
|
||||
label="Save settings"
|
||||
icon="pi pi-save"
|
||||
[loading]="deviceForm().submitting()"
|
||||
[disabled]="deviceForm().submitting()" />
|
||||
<app-button variant="soft" label="Validate" (clicked)="validateAll()" />
|
||||
<app-button variant="ghost" label="Reset" (clicked)="reset()" />
|
||||
@if (submitState() === 'saved') {
|
||||
<app-message inline color="green" class="ml-auto">Settings saved.</app-message>
|
||||
} @else if (submitAttempted()) {
|
||||
<app-message class="ml-auto" [field]="deviceForm" summary summaryLayout="inline" />
|
||||
}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<details class="border-t border-border pt-4">
|
||||
<summary class="cursor-pointer text-sm font-semibold text-text-strong">Form value</summary>
|
||||
<pre class="mt-3 overflow-x-auto text-xs text-text-muted dark:text-text-secondary">{{ model() | json }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</main>
|
||||
@@ -0,0 +1,139 @@
|
||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||
import { JsonPipe } from '@angular/common';
|
||||
import { CdkScrollable } from '@angular/cdk/scrolling';
|
||||
import { Router } from '@angular/router';
|
||||
import { form, FormField, FormRoot, hidden, max, min, minLength, required, validate } from '@angular/forms/signals';
|
||||
import { AppButtonComponent } from '../../../shared/ui/button/app-button.component';
|
||||
import { AppFieldComponent } from '../../../shared/ui/field/app-field.component';
|
||||
import { AppInputComponent } from '../../../shared/ui/input/app-input.component';
|
||||
import { AppMessageComponent } from '../../../shared/ui/message/app-message.component';
|
||||
import { AppNumberInputComponent } from '../../../shared/ui/number-input/app-number-input.component';
|
||||
import { AppSliderComponent } from '../../../shared/ui/slider/app-slider.component';
|
||||
import { AppSwitchComponent } from '../../../shared/ui/switch/app-switch.component';
|
||||
import { AppTagComponent } from '../../../shared/ui/tag/app-tag.component';
|
||||
|
||||
interface DeviceFormModel {
|
||||
hardcover: { enabled: boolean; apiKey: string };
|
||||
kobo: {
|
||||
enabled: boolean;
|
||||
twoWaySync: boolean;
|
||||
convertToKepub: boolean;
|
||||
markAsReading: number;
|
||||
markAsFinished: number;
|
||||
conversionLimitMb: number | null;
|
||||
};
|
||||
koreader: { enabled: boolean; syncWithWebReader: boolean; username: string; password: string };
|
||||
}
|
||||
|
||||
function createInitialModel(): DeviceFormModel {
|
||||
return {
|
||||
hardcover: { enabled: false, apiKey: '' },
|
||||
kobo: {
|
||||
enabled: true,
|
||||
twoWaySync: false,
|
||||
convertToKepub: true,
|
||||
markAsReading: 3,
|
||||
markAsFinished: 95,
|
||||
conversionLimitMb: 50,
|
||||
},
|
||||
koreader: { enabled: false, syncWithWebReader: false, username: '', password: '' },
|
||||
};
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-device-form-example',
|
||||
standalone: true,
|
||||
host: { class: 'block h-full min-h-0' },
|
||||
imports: [
|
||||
CdkScrollable,
|
||||
JsonPipe,
|
||||
FormField,
|
||||
FormRoot,
|
||||
AppButtonComponent,
|
||||
AppFieldComponent,
|
||||
AppInputComponent,
|
||||
AppMessageComponent,
|
||||
AppNumberInputComponent,
|
||||
AppSliderComponent,
|
||||
AppSwitchComponent,
|
||||
AppTagComponent,
|
||||
],
|
||||
templateUrl: './device-form.component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class DeviceFormExampleComponent {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
readonly model = signal<DeviceFormModel>(createInitialModel());
|
||||
readonly deviceForm = form(this.model, path => {
|
||||
hidden(path.hardcover.apiKey, ({ valueOf }) => !valueOf(path.hardcover.enabled));
|
||||
required(path.hardcover.apiKey, { message: 'Enter your Hardcover API key' });
|
||||
minLength(path.hardcover.apiKey, 20, { message: 'Hardcover keys are at least 20 characters' });
|
||||
|
||||
min(path.kobo.markAsReading, 1);
|
||||
max(path.kobo.markAsReading, 10);
|
||||
min(path.kobo.markAsFinished, 90);
|
||||
max(path.kobo.markAsFinished, 100);
|
||||
min(path.kobo.conversionLimitMb, 1);
|
||||
max(path.kobo.conversionLimitMb, 250);
|
||||
hidden(path.kobo.twoWaySync, ({ valueOf }) => !valueOf(path.kobo.enabled));
|
||||
hidden(path.kobo.convertToKepub, ({ valueOf }) => !valueOf(path.kobo.enabled));
|
||||
hidden(path.kobo.markAsReading, ({ valueOf }) => !valueOf(path.kobo.enabled));
|
||||
hidden(path.kobo.markAsFinished, ({ valueOf }) => !valueOf(path.kobo.enabled));
|
||||
hidden(path.kobo.conversionLimitMb, ({ valueOf }) => !valueOf(path.kobo.enabled));
|
||||
validate(path.kobo.twoWaySync, ({ value, valueOf }) =>
|
||||
value() && !valueOf(path.kobo.convertToKepub)
|
||||
? { kind: 'needsKepub', message: 'Two-way sync needs KEPUB conversion turned on' }
|
||||
: null,
|
||||
);
|
||||
|
||||
hidden(path.koreader.syncWithWebReader, ({ valueOf }) => !valueOf(path.koreader.enabled));
|
||||
hidden(path.koreader.username, ({ valueOf }) => !valueOf(path.koreader.enabled));
|
||||
hidden(path.koreader.password, ({ valueOf }) => !valueOf(path.koreader.enabled));
|
||||
required(path.koreader.username, { message: 'Choose a sync username' });
|
||||
required(path.koreader.password, { message: 'Set a sync password' });
|
||||
minLength(path.koreader.password, 6, { message: 'Use at least 6 characters' });
|
||||
}, {
|
||||
submission: {
|
||||
action: async field => {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(true);
|
||||
await delay(900);
|
||||
const hardcover = this.model().hardcover;
|
||||
if (hardcover.enabled && !hardcover.apiKey.startsWith('hc_')) {
|
||||
return [{ fieldTree: field.hardcover.apiKey, kind: 'server', message: 'Key must start with "hc_"' }];
|
||||
}
|
||||
this.submitState.set('saved');
|
||||
return undefined;
|
||||
},
|
||||
onInvalid: field => {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(true);
|
||||
field().errorSummary()[0]?.fieldTree().focusBoundControl();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
readonly submitState = signal<'idle' | 'saved'>('idle');
|
||||
readonly submitAttempted = signal(false);
|
||||
|
||||
validateAll(): void {
|
||||
this.submitState.set('idle');
|
||||
this.deviceForm().markAsTouched();
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(false);
|
||||
this.model.set(createInitialModel());
|
||||
this.deviceForm().reset();
|
||||
}
|
||||
|
||||
back(): void {
|
||||
void this.router.navigate(['/design-system']);
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<main cdkScrollable class="h-full overflow-y-auto bg-page p-6 text-text sm:p-8">
|
||||
<div class="mx-auto flex w-full max-w-2xl flex-col gap-6">
|
||||
<header class="flex flex-col gap-3">
|
||||
<app-button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="pi pi-chevron-left"
|
||||
label="Back to design system"
|
||||
styleClass="self-start"
|
||||
(clicked)="back()" />
|
||||
<div class="flex flex-col gap-1">
|
||||
<h1 class="text-2xl font-extrabold text-text-strong">Everything</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<app-tag [color]="everythingForm().valid() ? 'green' : 'red'" [label]="everythingForm().valid() ? 'valid' : 'invalid'" />
|
||||
<app-tag [color]="everythingForm().dirty() ? 'amber' : 'neutral'" [label]="everythingForm().dirty() ? 'dirty' : 'pristine'" />
|
||||
<app-tag [color]="everythingForm().touched() ? 'sky' : 'neutral'" [label]="everythingForm().touched() ? 'touched' : 'untouched'" />
|
||||
@if (everythingForm().submitting()) {
|
||||
<app-tag color="primary" icon="pi pi-spin pi-spinner" label="submitting" />
|
||||
}
|
||||
</div>
|
||||
|
||||
<form [formRoot]="everythingForm" class="flex flex-col gap-5">
|
||||
<app-field [field]="everythingForm.text" label="Text input" hint="Required.">
|
||||
<app-input [formField]="everythingForm.text" placeholder="Type something" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.textarea" label="Textarea" hint="Required.">
|
||||
<app-textarea [formField]="everythingForm.textarea" rows="3" placeholder="A longer value" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.number" label="Number" hint="0-100.">
|
||||
<app-number-input [formField]="everythingForm.number" unit="pt" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.select" label="Single select" hint="Pick one.">
|
||||
<app-select [formField]="everythingForm.select" [options]="selectOptions" placeholder="Choose one" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.multiSelect" label="Multi-select" hint="Pick at least one.">
|
||||
<app-multi-select [formField]="everythingForm.multiSelect" [options]="selectOptions" showClear filter placeholder="Choose any" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.autocomplete" label="Autocomplete" hint="Pick or type.">
|
||||
<app-autocomplete
|
||||
[formField]="everythingForm.autocomplete"
|
||||
[suggestions]="autocompleteSuggestions()"
|
||||
(complete)="filterAutocomplete($event)"
|
||||
placeholder="Type to search"
|
||||
ariaLabel="Autocomplete" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.multiAutocomplete" label="Multi-autocomplete (tags)" hint="Add at least one.">
|
||||
<app-multi-autocomplete
|
||||
[formField]="everythingForm.multiAutocomplete"
|
||||
[suggestions]="multiAutocompleteSuggestions()"
|
||||
(complete)="filterMultiAutocomplete($event)"
|
||||
placeholder="Add tags"
|
||||
ariaLabel="Tags"
|
||||
removeTagLabel="Remove tag" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.checkbox" label="Checkbox" hint="Must be checked.">
|
||||
<app-checkbox [formField]="everythingForm.checkbox" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.switch" label="Switch" hint="Optional.">
|
||||
<app-switch [formField]="everythingForm.switch" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.radio" label="Radio group" hint="Choose one.">
|
||||
<app-radio-group [formField]="everythingForm.radio" [options]="radioOptions" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.slider" label="Slider — {{ model().slider }}" hint="0-100.">
|
||||
<app-slider [formField]="everythingForm.slider" ariaLabel="Slider" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.rating" label="Rating" hint="Required.">
|
||||
<app-rating [formField]="everythingForm.rating" ariaLabel="Rating" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.date" label="Date" hint="Required.">
|
||||
<app-date-picker [formField]="everythingForm.date" placeholder="Pick a date" ariaLabel="Date" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="everythingForm.dateRange" label="Date range" hint="Start and end required.">
|
||||
<app-date-range-picker [formField]="everythingForm.dateRange" placeholder="Pick a range" ariaLabel="Date range" />
|
||||
</app-field>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-3 border-t border-border pt-5">
|
||||
<app-button
|
||||
type="submit"
|
||||
tone="primary"
|
||||
label="Save"
|
||||
icon="pi pi-save"
|
||||
[loading]="everythingForm().submitting()"
|
||||
[disabled]="everythingForm().submitting()" />
|
||||
<app-button variant="soft" label="Validate" (clicked)="validateAll()" />
|
||||
<app-button variant="ghost" label="Reset" (clicked)="reset()" />
|
||||
@if (submitState() === 'saved') {
|
||||
<app-message inline color="green" class="ml-auto">Saved.</app-message>
|
||||
} @else if (submitAttempted()) {
|
||||
<app-message class="ml-auto" [field]="everythingForm" summary summaryLayout="inline" />
|
||||
}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<details class="border-t border-border pt-4">
|
||||
<summary class="cursor-pointer text-sm font-semibold text-text-strong">Form value</summary>
|
||||
<pre class="mt-3 overflow-x-auto text-xs text-text-muted dark:text-text-secondary">{{ model() | json }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</main>
|
||||
@@ -0,0 +1,183 @@
|
||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||
import { JsonPipe } from '@angular/common';
|
||||
import { CdkScrollable } from '@angular/cdk/scrolling';
|
||||
import { Router } from '@angular/router';
|
||||
import { form, FormField, FormRoot, max, min, minLength, required, validate } from '@angular/forms/signals';
|
||||
import { AppButtonComponent } from '../../../shared/ui/button/app-button.component';
|
||||
import { AppFieldComponent } from '../../../shared/ui/field/app-field.component';
|
||||
import { AppInputComponent } from '../../../shared/ui/input/app-input.component';
|
||||
import { AppTextareaComponent } from '../../../shared/ui/textarea/app-textarea.component';
|
||||
import { AppNumberInputComponent } from '../../../shared/ui/number-input/app-number-input.component';
|
||||
import { AppSelectComponent } from '../../../shared/ui/select/app-select.component';
|
||||
import { AppMultiSelectComponent } from '../../../shared/ui/select/app-multi-select.component';
|
||||
import { AppAutocompleteComponent } from '../../../shared/ui/autocomplete/app-autocomplete.component';
|
||||
import { AppMultiAutocompleteComponent } from '../../../shared/ui/autocomplete/app-multi-autocomplete.component';
|
||||
import { AppCheckboxComponent } from '../../../shared/ui/checkbox/app-checkbox.component';
|
||||
import { AppSwitchComponent } from '../../../shared/ui/switch/app-switch.component';
|
||||
import { AppRadioGroupComponent, type RadioOption } from '../../../shared/ui/radio-group/app-radio-group.component';
|
||||
import { AppSliderComponent } from '../../../shared/ui/slider/app-slider.component';
|
||||
import { AppRatingComponent } from '../../../shared/ui/rating/app-rating.component';
|
||||
import { AppDatePickerComponent } from '../../../shared/ui/date-picker/app-date-picker.component';
|
||||
import { AppDateRangePickerComponent, type DatePickerRange } from '../../../shared/ui/date-picker/app-date-range-picker.component';
|
||||
import { AppMessageComponent } from '../../../shared/ui/message/app-message.component';
|
||||
import { AppTagComponent } from '../../../shared/ui/tag/app-tag.component';
|
||||
import { type SelectOption } from '../../../shared/ui/select/app-select.options';
|
||||
|
||||
interface EverythingFormModel {
|
||||
text: string;
|
||||
textarea: string;
|
||||
number: number | null;
|
||||
select: string;
|
||||
multiSelect: string[];
|
||||
autocomplete: string;
|
||||
multiAutocomplete: string[];
|
||||
checkbox: boolean;
|
||||
switch: boolean;
|
||||
radio: string;
|
||||
slider: number;
|
||||
rating: number;
|
||||
date: string;
|
||||
dateRange: DatePickerRange;
|
||||
}
|
||||
|
||||
function createInitialModel(): EverythingFormModel {
|
||||
return {
|
||||
text: '',
|
||||
textarea: '',
|
||||
number: null,
|
||||
select: '',
|
||||
multiSelect: [],
|
||||
autocomplete: '',
|
||||
multiAutocomplete: [],
|
||||
checkbox: false,
|
||||
switch: false,
|
||||
radio: '',
|
||||
slider: 50,
|
||||
rating: 0,
|
||||
date: '',
|
||||
dateRange: { start: '', end: '' },
|
||||
};
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-everything-form-example',
|
||||
standalone: true,
|
||||
host: { class: 'block h-full min-h-0' },
|
||||
imports: [
|
||||
CdkScrollable,
|
||||
JsonPipe,
|
||||
FormField,
|
||||
FormRoot,
|
||||
AppButtonComponent,
|
||||
AppFieldComponent,
|
||||
AppInputComponent,
|
||||
AppTextareaComponent,
|
||||
AppNumberInputComponent,
|
||||
AppSelectComponent,
|
||||
AppMultiSelectComponent,
|
||||
AppAutocompleteComponent,
|
||||
AppMultiAutocompleteComponent,
|
||||
AppCheckboxComponent,
|
||||
AppSwitchComponent,
|
||||
AppRadioGroupComponent,
|
||||
AppSliderComponent,
|
||||
AppRatingComponent,
|
||||
AppDatePickerComponent,
|
||||
AppDateRangePickerComponent,
|
||||
AppMessageComponent,
|
||||
AppTagComponent,
|
||||
],
|
||||
templateUrl: './everything-form.component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class EverythingFormExampleComponent {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
readonly model = signal<EverythingFormModel>(createInitialModel());
|
||||
readonly everythingForm = form(this.model, path => {
|
||||
required(path.text, { message: 'Required' });
|
||||
required(path.textarea, { message: 'Required' });
|
||||
required(path.number, { message: 'Enter a number' });
|
||||
min(path.number, 0, { message: '0 or more' });
|
||||
max(path.number, 100, { message: '100 or less' });
|
||||
min(path.slider, 0);
|
||||
max(path.slider, 100);
|
||||
required(path.select, { message: 'Pick an option' });
|
||||
required(path.autocomplete, { message: 'Pick or type a value' });
|
||||
required(path.radio, { message: 'Choose one' });
|
||||
required(path.date, { message: 'Pick a date' });
|
||||
minLength(path.multiSelect, 1, { message: 'Pick at least one' });
|
||||
minLength(path.multiAutocomplete, 1, { message: 'Add at least one tag' });
|
||||
validate(path.checkbox, ({ value }) => (value() ? null : { kind: 'mustAccept', message: 'Please confirm' }));
|
||||
validate(path.rating, ({ value }) => (value() > 0 ? null : { kind: 'rate', message: 'Add a rating' }));
|
||||
validate(path.dateRange, ({ value }) =>
|
||||
value().start && value().end ? null : { kind: 'range', message: 'Pick a start and end date' },
|
||||
);
|
||||
}, {
|
||||
submission: {
|
||||
action: async field => {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(true);
|
||||
await delay(700);
|
||||
if (this.model().text.trim().toLowerCase() === 'taken') {
|
||||
return [{ fieldTree: field.text, kind: 'server', message: '"taken" is not allowed' }];
|
||||
}
|
||||
this.submitState.set('saved');
|
||||
return undefined;
|
||||
},
|
||||
onInvalid: field => {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(true);
|
||||
field().errorSummary()[0]?.fieldTree().focusBoundControl();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
readonly submitState = signal<'idle' | 'saved'>('idle');
|
||||
readonly submitAttempted = signal(false);
|
||||
|
||||
readonly selectOptions: readonly SelectOption<string>[] = [
|
||||
{ label: 'One', value: 'one' },
|
||||
{ label: 'Two', value: 'two' },
|
||||
{ label: 'Three', value: 'three' },
|
||||
];
|
||||
readonly radioOptions: readonly RadioOption<string>[] = [
|
||||
{ label: 'Option A', value: 'a', description: 'First choice.' },
|
||||
{ label: 'Option B', value: 'b', description: 'Second choice.' },
|
||||
];
|
||||
|
||||
private readonly allTags = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta'];
|
||||
readonly autocompleteSuggestions = signal<string[]>([]);
|
||||
readonly multiAutocompleteSuggestions = signal<string[]>([]);
|
||||
|
||||
filterAutocomplete(query: string): void {
|
||||
const q = query.trim().toLowerCase();
|
||||
this.autocompleteSuggestions.set(q ? this.allTags.filter(t => t.includes(q)) : [...this.allTags]);
|
||||
}
|
||||
|
||||
filterMultiAutocomplete(query: string): void {
|
||||
const q = query.trim().toLowerCase();
|
||||
const chosen = this.model().multiAutocomplete;
|
||||
this.multiAutocompleteSuggestions.set(this.allTags.filter(t => t.includes(q) && !chosen.includes(t)));
|
||||
}
|
||||
|
||||
validateAll(): void {
|
||||
this.submitState.set('idle');
|
||||
this.everythingForm().markAsTouched();
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(false);
|
||||
this.model.set(createInitialModel());
|
||||
this.everythingForm().reset();
|
||||
}
|
||||
|
||||
back(): void {
|
||||
void this.router.navigate(['/design-system']);
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<main cdkScrollable class="h-full overflow-y-auto bg-page p-6 text-text sm:p-8">
|
||||
<div class="mx-auto flex w-full max-w-2xl flex-col gap-6">
|
||||
<header class="flex flex-col gap-3">
|
||||
<app-button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="pi pi-chevron-left"
|
||||
label="Back to design system"
|
||||
styleClass="self-start"
|
||||
(clicked)="back()" />
|
||||
<div class="flex flex-col gap-1">
|
||||
<h1 class="text-2xl font-extrabold text-text-strong">Create library</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<app-tag [color]="libraryForm().valid() ? 'green' : 'red'" [label]="libraryForm().valid() ? 'valid' : 'invalid'" />
|
||||
<app-tag [color]="libraryForm().dirty() ? 'amber' : 'neutral'" [label]="libraryForm().dirty() ? 'dirty' : 'pristine'" />
|
||||
<app-tag [color]="libraryForm().touched() ? 'sky' : 'neutral'" [label]="libraryForm().touched() ? 'touched' : 'untouched'" />
|
||||
@if (libraryForm().submitting()) {
|
||||
<app-tag color="primary" icon="pi pi-spin pi-spinner" label="submitting" />
|
||||
}
|
||||
</div>
|
||||
|
||||
<form [formRoot]="libraryForm" class="flex flex-col gap-5">
|
||||
<app-field [field]="libraryForm.name" label="Library name" hint="2+ characters.">
|
||||
<app-input [formField]="libraryForm.name" placeholder="e.g. Science Fiction" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="libraryForm.folders" label="Folders" hint="Press Enter to add.">
|
||||
<app-multi-autocomplete
|
||||
[formField]="libraryForm.folders"
|
||||
[suggestions]="folderSuggestions()"
|
||||
(complete)="filterFolders($event)"
|
||||
placeholder="/books/sci-fi"
|
||||
ariaLabel="Folders"
|
||||
removeTagLabel="Remove folder" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="libraryForm.organizationMode" label="Organization" hint="How files map to books.">
|
||||
<app-radio-group variant="card" [formField]="libraryForm.organizationMode" [options]="organizationOptions" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="libraryForm.metadataSource" label="Metadata source" hint="Default: embedded.">
|
||||
<app-select [formField]="libraryForm.metadataSource" [options]="metadataSourceOptions" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="libraryForm.allowedFormats" label="Allowed formats" hint="At least one required.">
|
||||
<app-multi-select
|
||||
[formField]="libraryForm.allowedFormats"
|
||||
[options]="formatOptions"
|
||||
showClear
|
||||
filter
|
||||
placeholder="Choose formats" />
|
||||
</app-field>
|
||||
|
||||
<app-field [field]="libraryForm.watch" label="Watch folders" hint="Import new files.">
|
||||
<app-switch [formField]="libraryForm.watch" />
|
||||
</app-field>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-3 border-t border-border pt-5">
|
||||
<app-button
|
||||
type="submit"
|
||||
tone="primary"
|
||||
label="Save library"
|
||||
icon="pi pi-save"
|
||||
[loading]="libraryForm().submitting()"
|
||||
[disabled]="libraryForm().submitting()" />
|
||||
<app-button variant="soft" label="Validate" (clicked)="validateAll()" />
|
||||
<app-button variant="ghost" label="Reset" (clicked)="reset()" />
|
||||
@if (submitState() === 'saved') {
|
||||
<app-message inline color="green" class="ml-auto">Library saved.</app-message>
|
||||
} @else if (submitAttempted()) {
|
||||
<app-message class="ml-auto" [field]="libraryForm" summary summaryLayout="inline" />
|
||||
}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<details class="border-t border-border pt-4">
|
||||
<summary class="cursor-pointer text-sm font-semibold text-text-strong">Form value</summary>
|
||||
<pre class="mt-3 overflow-x-auto text-xs text-text-muted dark:text-text-secondary">{{ model() | json }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</main>
|
||||
@@ -0,0 +1,167 @@
|
||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||
import { JsonPipe } from '@angular/common';
|
||||
import { CdkScrollable } from '@angular/cdk/scrolling';
|
||||
import { Router } from '@angular/router';
|
||||
import { form, FormField, FormRoot, minLength, required, validate } from '@angular/forms/signals';
|
||||
import { AppButtonComponent } from '../../../shared/ui/button/app-button.component';
|
||||
import { AppFieldComponent } from '../../../shared/ui/field/app-field.component';
|
||||
import { AppInputComponent } from '../../../shared/ui/input/app-input.component';
|
||||
import { AppMessageComponent } from '../../../shared/ui/message/app-message.component';
|
||||
import { AppMultiAutocompleteComponent } from '../../../shared/ui/autocomplete/app-multi-autocomplete.component';
|
||||
import { AppMultiSelectComponent } from '../../../shared/ui/select/app-multi-select.component';
|
||||
import { AppRadioGroupComponent, type RadioOption } from '../../../shared/ui/radio-group/app-radio-group.component';
|
||||
import { AppSelectComponent } from '../../../shared/ui/select/app-select.component';
|
||||
import { AppSwitchComponent } from '../../../shared/ui/switch/app-switch.component';
|
||||
import { AppTagComponent } from '../../../shared/ui/tag/app-tag.component';
|
||||
import { type SelectOption } from '../../../shared/ui/select/app-select.options';
|
||||
|
||||
type OrganizationMode = 'BOOK_PER_FILE' | 'BOOK_PER_FOLDER';
|
||||
type MetadataSource = 'EMBEDDED' | 'SIDECAR' | 'PREFER_SIDECAR' | 'PREFER_EMBEDDED' | 'NONE';
|
||||
|
||||
interface LibraryFormModel {
|
||||
name: string;
|
||||
folders: string[];
|
||||
organizationMode: OrganizationMode;
|
||||
metadataSource: MetadataSource;
|
||||
allowedFormats: string[];
|
||||
watch: boolean;
|
||||
}
|
||||
|
||||
const TAKEN_NAMES = ['fiction', 'comics'];
|
||||
const RESERVED_NAMES = ['all books', 'unshelved'];
|
||||
const PATH_SEPARATOR = /[\\/]/;
|
||||
|
||||
function createInitialModel(): LibraryFormModel {
|
||||
return {
|
||||
name: '',
|
||||
folders: [],
|
||||
organizationMode: 'BOOK_PER_FILE',
|
||||
metadataSource: 'EMBEDDED',
|
||||
allowedFormats: ['EPUB', 'PDF'],
|
||||
watch: true,
|
||||
};
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-form-example',
|
||||
standalone: true,
|
||||
host: { class: 'block h-full min-h-0' },
|
||||
imports: [
|
||||
CdkScrollable,
|
||||
JsonPipe,
|
||||
FormField,
|
||||
FormRoot,
|
||||
AppButtonComponent,
|
||||
AppFieldComponent,
|
||||
AppInputComponent,
|
||||
AppMessageComponent,
|
||||
AppMultiAutocompleteComponent,
|
||||
AppMultiSelectComponent,
|
||||
AppRadioGroupComponent,
|
||||
AppSelectComponent,
|
||||
AppSwitchComponent,
|
||||
AppTagComponent,
|
||||
],
|
||||
templateUrl: './library-form.component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class LibraryFormExampleComponent {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
readonly submitState = signal<'idle' | 'saved'>('idle');
|
||||
readonly submitAttempted = signal(false);
|
||||
|
||||
readonly model = signal<LibraryFormModel>(createInitialModel());
|
||||
readonly libraryForm = form(
|
||||
this.model,
|
||||
path => {
|
||||
required(path.name, { message: 'Give the library a name' });
|
||||
minLength(path.name, 2, { message: 'Use at least 2 characters' });
|
||||
validate(path.name, ({ value }) => {
|
||||
const name = value().trim();
|
||||
if (PATH_SEPARATOR.test(name)) return { kind: 'nameFormat', message: 'Name cannot contain / or \\' };
|
||||
if (RESERVED_NAMES.includes(name.toLowerCase())) return { kind: 'nameReserved', message: `"${name}" is a reserved name` };
|
||||
return null;
|
||||
});
|
||||
minLength(path.folders, 1, { message: 'Add at least one folder' });
|
||||
minLength(path.allowedFormats, 1, { message: 'Allow at least one format' });
|
||||
validate(path.watch, ({ value, valueOf }) =>
|
||||
value() && valueOf(path.metadataSource) === 'NONE'
|
||||
? { kind: 'watchWithoutMetadata', message: 'Pick a metadata source or turn watching off' }
|
||||
: null,
|
||||
);
|
||||
},
|
||||
{
|
||||
submission: {
|
||||
action: async field => {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(true);
|
||||
await delay(900);
|
||||
const name = this.model().name.trim();
|
||||
if (TAKEN_NAMES.includes(name.toLowerCase())) {
|
||||
return [{ fieldTree: field.name, kind: 'server', message: `A library named "${name}" already exists` }];
|
||||
}
|
||||
this.submitState.set('saved');
|
||||
return undefined;
|
||||
},
|
||||
onInvalid: field => {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(true);
|
||||
field().errorSummary()[0]?.fieldTree().focusBoundControl();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
readonly organizationOptions: readonly RadioOption<OrganizationMode>[] = [
|
||||
{ label: 'One book per file', value: 'BOOK_PER_FILE', description: 'Each file is separate.' },
|
||||
{ label: 'One book per folder', value: 'BOOK_PER_FOLDER', description: 'Group files by folder.' },
|
||||
];
|
||||
readonly metadataSourceOptions: readonly SelectOption<MetadataSource>[] = [
|
||||
{ label: 'Embedded', value: 'EMBEDDED' },
|
||||
{ label: 'Sidecar (.opf)', value: 'SIDECAR' },
|
||||
{ label: 'Prefer sidecar', value: 'PREFER_SIDECAR' },
|
||||
{ label: 'Prefer embedded', value: 'PREFER_EMBEDDED' },
|
||||
{ label: 'No metadata', value: 'NONE' },
|
||||
];
|
||||
readonly formatOptions: readonly SelectOption<string>[] = [
|
||||
{ label: 'EPUB', value: 'EPUB' },
|
||||
{ label: 'PDF', value: 'PDF' },
|
||||
{ label: 'CBX', value: 'CBX' },
|
||||
{ label: 'MOBI', value: 'MOBI' },
|
||||
{ label: 'AZW3', value: 'AZW3' },
|
||||
{ label: 'FB2', value: 'FB2' },
|
||||
{ label: 'Audiobook', value: 'AUDIOBOOK' },
|
||||
];
|
||||
|
||||
private readonly allFolders = ['/books', '/books/sci-fi', '/books/fantasy', '/comics', '/audiobooks', '/imports'];
|
||||
readonly folderSuggestions = signal<string[]>([]);
|
||||
|
||||
filterFolders(query: string): void {
|
||||
const q = query.trim().toLowerCase();
|
||||
const chosen = this.model().folders;
|
||||
this.folderSuggestions.set(
|
||||
q ? this.allFolders.filter(folder => folder.toLowerCase().includes(q) && !chosen.includes(folder)) : [],
|
||||
);
|
||||
}
|
||||
|
||||
validateAll(): void {
|
||||
this.submitState.set('idle');
|
||||
this.libraryForm().markAsTouched();
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.submitState.set('idle');
|
||||
this.submitAttempted.set(false);
|
||||
this.model.set(createInitialModel());
|
||||
this.libraryForm().reset();
|
||||
}
|
||||
|
||||
back(): void {
|
||||
void this.router.navigate(['/design-system']);
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
<span
|
||||
[class]="'app-rating ' + ratingClass()"
|
||||
[style.--app-rating-color]="color()"
|
||||
[style.--app-rating-size]="size()"
|
||||
[attr.aria-label]="ratingAriaLabel()"
|
||||
role="img">
|
||||
@for (fill of starFills(); track $index) {
|
||||
<span class="app-rating-star" [style.--app-rating-star-fill]="fill">
|
||||
<svg class="app-rating-star-empty" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" focusable="false">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.562.562 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z" />
|
||||
</svg>
|
||||
<svg class="app-rating-star-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path fill-rule="evenodd" d="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" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
@@ -1,64 +0,0 @@
|
||||
:host {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
line-height: 1;
|
||||
|
||||
--app-rating-color: var(--p-rating-icon-active-color, var(--p-primary-color));
|
||||
--app-rating-empty-color: var(--p-rating-icon-color, var(--p-text-muted-color));
|
||||
--app-rating-gap: var(--p-rating-gap, 0.2188rem);
|
||||
--app-rating-size: 18px;
|
||||
}
|
||||
|
||||
.app-rating {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--app-rating-gap);
|
||||
line-height: 1;
|
||||
|
||||
&.app-rating-excellent {
|
||||
--app-rating-color: rgb(34 197 94);
|
||||
}
|
||||
|
||||
&.app-rating-good {
|
||||
--app-rating-color: rgb(52 211 153);
|
||||
}
|
||||
|
||||
&.app-rating-mixed {
|
||||
--app-rating-color: rgb(234 179 8);
|
||||
}
|
||||
|
||||
&.app-rating-low {
|
||||
--app-rating-color: rgb(249 115 22);
|
||||
}
|
||||
|
||||
&.app-rating-poor {
|
||||
--app-rating-color: rgb(239 68 68);
|
||||
}
|
||||
}
|
||||
|
||||
.app-rating-star {
|
||||
--app-rating-star-fill: 0%;
|
||||
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
width: var(--app-rating-size);
|
||||
height: var(--app-rating-size);
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
.app-rating-star svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.app-rating-star-empty {
|
||||
color: var(--app-rating-empty-color);
|
||||
}
|
||||
|
||||
.app-rating-star-filled {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
fill: var(--app-rating-color);
|
||||
clip-path: inset(0 calc(100% - var(--app-rating-star-fill)) 0 0);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import {ChangeDetectionStrategy, Component, computed, input} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-rating',
|
||||
standalone: true,
|
||||
templateUrl: './rating.component.html',
|
||||
styleUrls: ['./rating.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class RatingComponent {
|
||||
value = input<number | null>(null);
|
||||
color = input<string | null>(null);
|
||||
max = input(5);
|
||||
size = input('18px');
|
||||
ariaLabel = input<string | null>(null);
|
||||
|
||||
protected readonly ratingClass = computed(() => this.getRatingClass(this.value()));
|
||||
|
||||
protected readonly ratingAriaLabel = computed(() => {
|
||||
const label = this.ariaLabel();
|
||||
if (label) return label;
|
||||
|
||||
const rating = this.value();
|
||||
return rating === null ? null : `${rating.toFixed(1)} / ${this.max()}`;
|
||||
});
|
||||
|
||||
protected readonly starFills = computed(() => {
|
||||
const rating = this.value();
|
||||
return Array.from({length: this.max()}, (_, index) => this.getStarFill(rating, index));
|
||||
});
|
||||
|
||||
private getStarFill(rating: number | null, starIndex: number): string {
|
||||
if (rating === null) return '0%';
|
||||
const fill = Math.max(0, Math.min(1, rating - starIndex));
|
||||
return `${Math.round(fill * 100)}%`;
|
||||
}
|
||||
|
||||
private getRatingClass(rating: number | null): string {
|
||||
if (rating === null) return 'app-rating-unrated';
|
||||
if (rating >= 4.5) return 'app-rating-excellent';
|
||||
if (rating >= 4) return 'app-rating-good';
|
||||
if (rating >= 3.5) return 'app-rating-mixed';
|
||||
if (rating >= 2.5) return 'app-rating-low';
|
||||
return 'app-rating-poor';
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
@if (tabs().length) {
|
||||
<div ngTabs class="app-tabs-root">
|
||||
<div
|
||||
ngTabList
|
||||
class="app-tabs"
|
||||
[class.is-measured]="indicatorVisible()"
|
||||
[class.is-animated]="indicatorAnimated()"
|
||||
[(selectedTab)]="selectedTabId"
|
||||
[attr.aria-label]="ariaLabel()"
|
||||
>
|
||||
<span
|
||||
class="app-tabs-indicator"
|
||||
aria-hidden="true"
|
||||
[style.transform]="'translateX(' + indicatorLeft() + 'px)'"
|
||||
[style.width.px]="indicatorWidth()"
|
||||
></span>
|
||||
@for (tab of tabs(); track tab.id) {
|
||||
<button
|
||||
ngTab
|
||||
type="button"
|
||||
[id]="tab.id"
|
||||
[value]="tab.id"
|
||||
class="app-tab"
|
||||
>
|
||||
@if (tab.icon) {
|
||||
<i [class]="'app-tab-icon ' + tab.icon" aria-hidden="true"></i>
|
||||
}
|
||||
<span class="app-tab-label">{{ tab.label }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
import {
|
||||
afterRenderEffect,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
DestroyRef,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
signal,
|
||||
viewChildren,
|
||||
} from '@angular/core';
|
||||
import {Tab as NgTab, TabList, Tabs} from '@angular/aria/tabs';
|
||||
|
||||
export interface TabItem {
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export type TabsVariant = 'underline' | 'segmented';
|
||||
export type TabsPlacement = 'inline' | 'below';
|
||||
|
||||
@Component({
|
||||
selector: 'app-tabs',
|
||||
standalone: true,
|
||||
imports: [Tabs, TabList, NgTab],
|
||||
templateUrl: './app-tabs.component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: {
|
||||
'[class.variant-underline]': 'variant() === "underline"',
|
||||
'[class.variant-segmented]': 'variant() === "segmented"',
|
||||
'[class.placement-inline]': 'placement() === "inline"',
|
||||
'[class.placement-below]': 'placement() === "below"',
|
||||
},
|
||||
})
|
||||
export class AppTabsComponent {
|
||||
readonly tabs = input.required<TabItem[]>();
|
||||
readonly variant = input<TabsVariant>('underline');
|
||||
readonly placement = input<TabsPlacement>('below');
|
||||
readonly ariaLabel = input.required<string>();
|
||||
readonly selectedTabId = model<string | undefined>(undefined);
|
||||
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly tabDirectives = viewChildren(NgTab);
|
||||
|
||||
protected readonly activeTabId = computed(() => this.selectedTabId() ?? this.tabs()[0]?.id);
|
||||
protected readonly indicatorLeft = signal(0);
|
||||
protected readonly indicatorWidth = signal(0);
|
||||
protected readonly indicatorVisible = signal(false);
|
||||
protected readonly indicatorAnimated = signal(false);
|
||||
|
||||
private pendingAnimationFrame: number | null = null;
|
||||
private initialRevealScheduled = false;
|
||||
|
||||
constructor() {
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
afterRenderEffect(() => {
|
||||
this.tabs();
|
||||
this.variant();
|
||||
this.placement();
|
||||
this.activeTabId();
|
||||
this.scheduleMeasure();
|
||||
|
||||
const tabs = this.tabDirectives();
|
||||
if (tabs.length && typeof ResizeObserver !== 'undefined') {
|
||||
resizeObserver ??= new ResizeObserver(() => this.scheduleMeasure());
|
||||
resizeObserver.disconnect();
|
||||
for (const tab of tabs) {
|
||||
resizeObserver.observe(tab.element);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.destroyRef.onDestroy(() => {
|
||||
resizeObserver?.disconnect();
|
||||
if (this.pendingAnimationFrame !== null) {
|
||||
cancelAnimationFrame(this.pendingAnimationFrame);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private measure(): void {
|
||||
const activeTabId = this.activeTabId();
|
||||
const active = this.tabDirectives().find(tab => tab.value() === activeTabId);
|
||||
if (!active) {
|
||||
this.indicatorVisible.set(false);
|
||||
return;
|
||||
}
|
||||
this.indicatorLeft.set(active.element.offsetLeft);
|
||||
this.indicatorWidth.set(active.element.offsetWidth);
|
||||
if (!this.indicatorVisible()) {
|
||||
this.scheduleInitialReveal();
|
||||
return;
|
||||
}
|
||||
this.indicatorAnimated.set(true);
|
||||
}
|
||||
|
||||
private scheduleMeasure(): void {
|
||||
if (this.pendingAnimationFrame !== null) {
|
||||
cancelAnimationFrame(this.pendingAnimationFrame);
|
||||
}
|
||||
|
||||
this.pendingAnimationFrame = requestAnimationFrame(() => {
|
||||
this.pendingAnimationFrame = null;
|
||||
this.measure();
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleInitialReveal(): void {
|
||||
if (this.initialRevealScheduled) return;
|
||||
this.initialRevealScheduled = true;
|
||||
|
||||
void document.fonts.ready.then(() => {
|
||||
if (this.pendingAnimationFrame !== null) {
|
||||
cancelAnimationFrame(this.pendingAnimationFrame);
|
||||
}
|
||||
this.pendingAnimationFrame = requestAnimationFrame(() => {
|
||||
this.measure();
|
||||
this.indicatorVisible.set(true);
|
||||
this.pendingAnimationFrame = requestAnimationFrame(() => {
|
||||
this.pendingAnimationFrame = null;
|
||||
this.indicatorAnimated.set(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
|
||||
.app-cg-item {
|
||||
transition-property: background-color, color;
|
||||
}
|
||||
|
||||
.app-cg-item:hover,
|
||||
.app-cg-item.app-cg-active,
|
||||
.app-cg-item.app-cg-prominent {
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.app-cg-item:hover {
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.app-cg-item:not(.app-cg-last, :hover, .app-cg-active, .app-cg-prominent),
|
||||
.app-cg-item:not(:hover):has(+ .app-cg-item:is(:hover, .app-cg-active)),
|
||||
.app-cg-item.app-cg-prominent:not(.app-cg-last, :hover, .app-cg-active):has(
|
||||
+ .app-cg-item.app-cg-prominent
|
||||
),
|
||||
.app-cg-group > *:has(+ * > .app-cg-item:is(:hover, .app-cg-active)) > .app-cg-item:not(:hover),
|
||||
.app-cg-group
|
||||
> *:has(+ * > .app-cg-item.app-cg-prominent)
|
||||
> .app-cg-item.app-cg-prominent:not(.app-cg-last, :hover, .app-cg-active) {
|
||||
border-right-color: transparent;
|
||||
}
|
||||
|
||||
.app-cg-item:is(:hover, .app-cg-active) + .app-cg-item:not(:hover, .app-cg-active),
|
||||
.app-cg-item.app-cg-prominent + .app-cg-item:not(:hover, .app-cg-active, .app-cg-prominent) {
|
||||
border-left-color: transparent;
|
||||
}
|
||||
|
||||
.app-cg-group
|
||||
> *:has(> .app-cg-item:is(:hover, .app-cg-active))
|
||||
+ *
|
||||
> .app-cg-item:not(:hover, .app-cg-active),
|
||||
.app-cg-group
|
||||
> *:has(> .app-cg-item.app-cg-prominent)
|
||||
+ *
|
||||
> .app-cg-item:not(:hover, .app-cg-active, .app-cg-prominent) {
|
||||
border-left-color: transparent;
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
app-tabs {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.app-tabs-root {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
.app-tabs {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.app-tabs-indicator {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
pointer-events: none;
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.app-tabs.is-measured .app-tabs-indicator {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.app-tabs.is-animated .app-tabs-indicator {
|
||||
transition:
|
||||
transform 220ms cubic-bezier(0.4, 0, 0.2, 1),
|
||||
width 220ms cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.app-tab {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--control-gap);
|
||||
box-sizing: border-box;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.8203rem;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color var(--transition-fast),
|
||||
background-color var(--transition-fast),
|
||||
transform var(--transition-fast);
|
||||
|
||||
&:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
&[aria-selected="true"]:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
.app-tab-icon {
|
||||
font-size: 0.875em;
|
||||
line-height: 1;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.app-tab-label {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
app-tabs.placement-below {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
height: var(--app-tabs-row-height, 3.0625rem);
|
||||
padding: 0.2188rem 1.75rem 0;
|
||||
|
||||
@media (width <= 767px) {
|
||||
padding: 0.2188rem 0.875rem 0;
|
||||
}
|
||||
}
|
||||
|
||||
app-tabs.variant-underline {
|
||||
--app-tabs-divider: color-mix(in srgb, var(--color-border) 70%, transparent);
|
||||
|
||||
padding: 0;
|
||||
|
||||
.app-tabs {
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
gap: 1.3125rem;
|
||||
padding: 0 1.75rem;
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
right: 1.75rem;
|
||||
bottom: 0;
|
||||
left: 1.75rem;
|
||||
height: 1px;
|
||||
background: var(--app-tabs-divider);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (width <= 767px) {
|
||||
gap: 0.875rem;
|
||||
padding: 0 0.875rem;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
|
||||
&::after {
|
||||
right: 0.875rem;
|
||||
left: 0.875rem;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.app-tab {
|
||||
min-width: 4.375rem;
|
||||
padding: 0 0.875rem;
|
||||
|
||||
@media (width <= 767px) {
|
||||
flex: 1 1 0;
|
||||
min-width: 3.5rem;
|
||||
padding: 0 0.7656rem;
|
||||
}
|
||||
|
||||
&[aria-selected="true"] {
|
||||
color: var(--color-text);
|
||||
|
||||
&::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: 2px;
|
||||
background: var(--color-primary);
|
||||
border-radius: 2px 2px 0 0;
|
||||
z-index: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.app-tabs.is-measured .app-tab[aria-selected="true"]::before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.app-tabs-indicator {
|
||||
bottom: 0;
|
||||
height: 2px;
|
||||
background: var(--color-primary);
|
||||
border-radius: 2px 2px 0 0;
|
||||
z-index: 1;
|
||||
}
|
||||
}
|
||||
|
||||
app-tabs.variant-segmented {
|
||||
.app-tabs {
|
||||
gap: 0.1094rem;
|
||||
padding: var(--space-1);
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--control-bg);
|
||||
|
||||
@media (width <= 767px) {
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.app-tab {
|
||||
height: 1.75rem;
|
||||
padding: 0 0.875rem;
|
||||
border-radius: var(--control-radius);
|
||||
|
||||
&:hover:not([aria-selected="true"]) {
|
||||
background: var(--color-surface-hover);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
&[aria-selected="true"] {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.app-tabs.is-measured .app-tab[aria-selected="true"] {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.app-tabs-indicator {
|
||||
top: var(--space-1);
|
||||
bottom: var(--space-1);
|
||||
box-sizing: border-box;
|
||||
background: var(--control-primary-bg);
|
||||
border-radius: var(--control-radius);
|
||||
box-shadow: 0 0 0 1px var(--control-primary-border);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,30 @@
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@keyframes enter {
|
||||
from {
|
||||
opacity: var(--tw-enter-opacity, 1);
|
||||
transform: translate3d(var(--tw-enter-translate-x, 0), var(--tw-enter-translate-y, 0), 0)
|
||||
scale3d(var(--tw-enter-scale, 1), var(--tw-enter-scale, 1), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@utility animate-in {
|
||||
animation: enter 120ms ease-out;
|
||||
}
|
||||
@utility fade-in-0 {
|
||||
--tw-enter-opacity: 0;
|
||||
}
|
||||
@utility zoom-in-98 {
|
||||
--tw-enter-scale: 0.98;
|
||||
}
|
||||
@utility slide-in-from-top-1 {
|
||||
--tw-enter-translate-y: -0.25rem;
|
||||
}
|
||||
@utility slide-in-from-bottom-1 {
|
||||
--tw-enter-translate-y: 0.25rem;
|
||||
}
|
||||
|
||||
@theme static {
|
||||
--font-sans: -apple-system, "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica", "Arial", sans-serif;
|
||||
|
||||
@@ -61,6 +85,9 @@
|
||||
--color-logo-start: var(--color-primary-400);
|
||||
--color-logo-end: var(--color-primary-600);
|
||||
--color-logo-bookmark: #FF2126;
|
||||
|
||||
--shadow-control: 0 1px 2px -1px rgb(0 0 0 / 6%), 0 2px 4px 0 rgb(0 0 0 / 4%);
|
||||
--shadow-pop: 0 4px 12px -2px rgb(0 0 0 / 12%), 0 2px 6px -2px rgb(0 0 0 / 8%);
|
||||
}
|
||||
|
||||
:root {
|
||||
@@ -113,6 +140,8 @@
|
||||
--color-logo-bookmark: var(--color-white);
|
||||
--color-warning: var(--color-amber-400);
|
||||
--color-info: var(--color-sky-400);
|
||||
--shadow-control: 0 1px 2px -1px rgb(0 0 0 / 50%), 0 2px 4px 0 rgb(0 0 0 / 40%);
|
||||
--shadow-pop: 0 4px 12px -2px rgb(0 0 0 / 55%), 0 2px 6px -2px rgb(0 0 0 / 45%);
|
||||
}
|
||||
|
||||
[data-app-theme="grimmory"] {
|
||||
@@ -481,7 +510,6 @@
|
||||
--color-logo-end: var(--color-gray-300);
|
||||
}
|
||||
|
||||
/* Custom theme: zinc surface, primary palette chosen at runtime via the picker. */
|
||||
[data-app-theme="custom"] {
|
||||
--app-primary-tint: 5%;
|
||||
--color-primary-50: var(--color-orange-50);
|
||||
@@ -516,6 +544,8 @@
|
||||
--color-border: color-mix(in srgb, var(--color-text) 18%, transparent);
|
||||
--color-card-outline: color-mix(in srgb, var(--color-text) 14%, transparent);
|
||||
--color-active-surface: color-mix(in srgb, var(--color-primary) 14%, transparent);
|
||||
--shadow-control: 0 1px 2px -1px rgb(0 0 0 / 60%), 0 2px 4px 0 rgb(0 0 0 / 50%);
|
||||
--shadow-pop: 0 4px 14px -2px rgb(0 0 0 / 70%), 0 2px 8px -2px rgb(0 0 0 / 55%);
|
||||
}
|
||||
|
||||
@source inline("bg-{red,orange,amber,yellow,lime,green,emerald,teal,cyan,sky,blue,indigo,violet,purple,fuchsia,pink,rose}-{50,100,200,300,400,500,600,700,800,900,950}");
|
||||
|
||||
@@ -150,5 +150,60 @@
|
||||
"toast": {
|
||||
"createFailedDefault": "Failed to create admin user. Try again."
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"issueCount": "{{ count }} issues",
|
||||
"issuePosition": "{{ current }} of {{ count }} issues",
|
||||
"previousIssue": "Previous issue",
|
||||
"nextIssue": "Next issue"
|
||||
},
|
||||
"ui": {
|
||||
"autocomplete": {
|
||||
"noResults": "No results",
|
||||
"removeTag": "Remove {{ tag }}"
|
||||
},
|
||||
"datePicker": {
|
||||
"previousMonth": "Previous month",
|
||||
"nextMonth": "Next month"
|
||||
},
|
||||
"input": {
|
||||
"showPassword": "Show password",
|
||||
"hidePassword": "Hide password",
|
||||
"trailingAction": "Input action"
|
||||
},
|
||||
"message": {
|
||||
"issueCount": "{{ count }} issues",
|
||||
"issuePosition": "{{ current }} of {{ count }} issues",
|
||||
"previousIssue": "Previous issue",
|
||||
"nextIssue": "Next issue"
|
||||
},
|
||||
"rating": {
|
||||
"valueText": "{{ rating }} out of {{ max }} stars",
|
||||
"setRatingTo": "Set rating to {{ rating }} out of {{ max }} stars"
|
||||
},
|
||||
"select": {
|
||||
"clearSelection": "Clear selection",
|
||||
"noResults": "No results",
|
||||
"search": "Search",
|
||||
"selectedCount": "{{ count }} selected"
|
||||
},
|
||||
"spinner": {
|
||||
"loading": "Loading"
|
||||
},
|
||||
"tag": {
|
||||
"removeTag": "Remove tag",
|
||||
"removeLabel": "Remove {{ label }}"
|
||||
},
|
||||
"validation": {
|
||||
"default": "Invalid value",
|
||||
"email": "Enter a valid email",
|
||||
"max": "Value is too high",
|
||||
"maxLength": "Use a shorter value",
|
||||
"min": "Value is too low",
|
||||
"minLength": "Use a longer value",
|
||||
"parse": "Enter a valid value",
|
||||
"pattern": "Enter a valid value",
|
||||
"required": "This field is required"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
@include meta.load-css("assets/styles/buttons");
|
||||
@include meta.load-css("assets/styles/text-fields");
|
||||
@include meta.load-css("assets/styles/control-groups");
|
||||
@include meta.load-css("assets/styles/tabs");
|
||||
@include meta.load-css("assets/styles/page");
|
||||
@include meta.load-css("assets/styles/layout");
|
||||
@include meta.load-css("assets/styles/overlays");
|
||||
@include meta.load-css("assets/styles/utilities");
|
||||
@include meta.load-css("assets/styles/connected-group");
|
||||
@include meta.load-css("assets/styles/compat");
|
||||
|
||||
Generated
+18
@@ -79,6 +79,9 @@ importers:
|
||||
chartjs-plugin-datalabels:
|
||||
specifier: ^2.2.0
|
||||
version: 2.2.0(chart.js@4.5.1)
|
||||
class-variance-authority:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1
|
||||
date-fns:
|
||||
specifier: ^4.4.0
|
||||
version: 4.4.0
|
||||
@@ -109,6 +112,9 @@ importers:
|
||||
rxjs:
|
||||
specifier: ^7.8.2
|
||||
version: 7.8.2
|
||||
tailwind-merge:
|
||||
specifier: ^3.6.0
|
||||
version: 3.6.0
|
||||
tslib:
|
||||
specifier: ^2.8.1
|
||||
version: 2.8.1
|
||||
@@ -3142,6 +3148,9 @@ packages:
|
||||
resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
class-variance-authority@0.7.1:
|
||||
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
|
||||
|
||||
clean-stack@2.2.0:
|
||||
resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==}
|
||||
engines: {node: '>=6'}
|
||||
@@ -5418,6 +5427,9 @@ packages:
|
||||
tailwind-merge@3.5.0:
|
||||
resolution: {integrity: sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==}
|
||||
|
||||
tailwind-merge@3.6.0:
|
||||
resolution: {integrity: sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w==}
|
||||
|
||||
tailwindcss-primeui@0.6.1:
|
||||
resolution: {integrity: sha512-T69Rylcrmnt8zy9ik+qZvsLuRIrS9/k6rYJSIgZ1trnbEzGDDQSCIdmfyZknevqiHwpSJHSmQ9XT2C+S/hJY4A==}
|
||||
peerDependencies:
|
||||
@@ -8688,6 +8700,10 @@ snapshots:
|
||||
|
||||
chownr@3.0.0: {}
|
||||
|
||||
class-variance-authority@0.7.1:
|
||||
dependencies:
|
||||
clsx: 2.1.1
|
||||
|
||||
clean-stack@2.2.0: {}
|
||||
|
||||
clean-stack@5.3.0:
|
||||
@@ -11112,6 +11128,8 @@ snapshots:
|
||||
|
||||
tailwind-merge@3.5.0: {}
|
||||
|
||||
tailwind-merge@3.6.0: {}
|
||||
|
||||
tailwindcss-primeui@0.6.1(tailwindcss@4.3.0):
|
||||
dependencies:
|
||||
tailwindcss: 4.3.0
|
||||
|
||||
Reference in New Issue
Block a user