From 3e5d85bfc1359f844d84320e2d1258fd7489d255 Mon Sep 17 00:00:00 2001 From: Alex <25013571+alexhb1@users.noreply.github.com> Date: Sun, 14 Jun 2026 21:53:12 +0200 Subject: [PATCH] refactor(ui): new component library (#1740) --- frontend/package.json | 2 + frontend/src/app/app.routes.spec.ts | 6 +- frontend/src/app/app.routes.ts | 4 + .../book-table/book-table-row.component.html | 6 +- .../book-table/book-table-row.component.scss | 5 - .../book-table-row.component.spec.ts | 3 +- .../book-table/book-table-row.component.ts | 4 +- .../design-system.component.html | 608 ++++++++++++++++++ .../design-system.component.scss | 112 ++++ .../design-system/design-system.component.ts | 252 ++++++++ .../forms/device-form.component.html | 124 ++++ .../forms/device-form.component.ts | 139 ++++ .../forms/everything-form.component.html | 116 ++++ .../forms/everything-form.component.ts | 183 ++++++ .../forms/library-form.component.html | 84 +++ .../forms/library-form.component.ts | 167 +++++ .../components/rating/rating.component.html | 17 - .../components/rating/rating.component.scss | 64 -- .../components/rating/rating.component.ts | 46 -- .../components/tabs/app-tabs.component.html | 33 - .../components/tabs/app-tabs.component.ts | 129 ---- .../ui/accordion/app-accordion.component.ts | 130 ++++ .../ui/accordion/app-accordion.directives.ts | 16 + .../app-autocomplete-base.directive.ts | 92 +++ .../app-autocomplete.component.ts | 128 ++++ .../autocomplete/app-autocomplete.variants.ts | 23 + .../app-multi-autocomplete.component.ts | 191 ++++++ .../shared/ui/button/app-button.component.ts | 90 +++ .../shared/ui/button/app-button.variants.ts | 68 ++ .../ui/checkbox/app-checkbox.component.ts | 123 ++++ .../ui/checkbox/app-checkbox.variants.ts | 52 ++ frontend/src/app/shared/ui/cn.ts | 14 + frontend/src/app/shared/ui/connected-group.ts | 19 + .../src/app/shared/ui/connected-overlay.ts | 39 ++ frontend/src/app/shared/ui/control.styles.ts | 7 + .../app-date-picker-base.directive.ts | 480 ++++++++++++++ .../date-picker/app-date-picker.component.ts | 50 ++ .../date-picker/app-date-picker.variants.ts | 11 + .../app-date-range-picker.component.ts | 82 +++ .../shared/ui/field/app-field.component.ts | 133 ++++ .../app/shared/ui/field/app-field.context.ts | 23 + .../shared/ui/input/app-input.component.ts | 197 ++++++ .../app/shared/ui/input/app-input.variants.ts | 37 ++ .../app/shared/ui/menu/app-menu.component.ts | 104 +++ .../src/app/shared/ui/menu/app-menu.items.ts | 14 + frontend/src/app/shared/ui/menu/menu.pt.ts | 90 +++ .../ui/message/app-message.component.ts | 198 ++++++ .../shared/ui/message/app-message.variants.ts | 25 + .../app-number-input.component.ts | 187 ++++++ .../src/app/shared/ui/overlay-list.styles.ts | 27 + .../radio-group/app-radio-group.component.ts | 155 +++++ .../radio-group/app-radio-group.variants.ts | 94 +++ .../shared/ui/rating/app-rating.component.ts | 320 +++++++++ .../ui/select/app-multi-select.component.ts | 204 ++++++ .../ui/select/app-select-base.directive.ts | 231 +++++++ .../shared/ui/select/app-select.component.ts | 215 +++++++ .../shared/ui/select/app-select.options.ts | 12 + .../shared/ui/select/app-select.templates.ts | 21 + .../shared/ui/select/app-select.variants.ts | 62 ++ .../shared/ui/slider/app-slider.component.ts | 103 +++ .../ui/spinner/app-spinner.component.ts | 24 + .../shared/ui/spinner/app-spinner.variants.ts | 16 + .../app-split-button.component.ts | 106 +++ .../shared/ui/switch/app-switch.component.ts | 96 +++ .../shared/ui/switch/app-switch.variants.ts | 54 ++ .../app/shared/ui/tabs/app-tabs.component.ts | 191 ++++++ .../app/shared/ui/tabs/app-tabs.variants.ts | 50 ++ .../app/shared/ui/tag/app-tag.component.ts | 98 +++ .../src/app/shared/ui/tag/app-tag.variants.ts | 64 ++ .../ui/textarea/app-textarea.component.ts | 124 ++++ .../ui/textarea/app-textarea.variants.ts | 19 + .../ui/tooltip/app-tooltip.container.ts | 18 + .../ui/tooltip/app-tooltip.directive.ts | 182 ++++++ .../ui/tooltip/app-tooltip.positions.ts | 23 + .../src/assets/styles/connected-group.scss | 42 ++ frontend/src/assets/styles/tabs.scss | 218 ------- frontend/src/assets/styles/tailwind.css | 32 +- frontend/src/i18n/en/shared.json | 55 ++ frontend/src/styles.scss | 2 +- pnpm-lock.yaml | 18 + 80 files changed, 7081 insertions(+), 522 deletions(-) create mode 100644 frontend/src/app/features/design-system/design-system.component.html create mode 100644 frontend/src/app/features/design-system/design-system.component.scss create mode 100644 frontend/src/app/features/design-system/design-system.component.ts create mode 100644 frontend/src/app/features/design-system/forms/device-form.component.html create mode 100644 frontend/src/app/features/design-system/forms/device-form.component.ts create mode 100644 frontend/src/app/features/design-system/forms/everything-form.component.html create mode 100644 frontend/src/app/features/design-system/forms/everything-form.component.ts create mode 100644 frontend/src/app/features/design-system/forms/library-form.component.html create mode 100644 frontend/src/app/features/design-system/forms/library-form.component.ts delete mode 100644 frontend/src/app/shared/components/rating/rating.component.html delete mode 100644 frontend/src/app/shared/components/rating/rating.component.scss delete mode 100644 frontend/src/app/shared/components/rating/rating.component.ts delete mode 100644 frontend/src/app/shared/components/tabs/app-tabs.component.html delete mode 100644 frontend/src/app/shared/components/tabs/app-tabs.component.ts create mode 100644 frontend/src/app/shared/ui/accordion/app-accordion.component.ts create mode 100644 frontend/src/app/shared/ui/accordion/app-accordion.directives.ts create mode 100644 frontend/src/app/shared/ui/autocomplete/app-autocomplete-base.directive.ts create mode 100644 frontend/src/app/shared/ui/autocomplete/app-autocomplete.component.ts create mode 100644 frontend/src/app/shared/ui/autocomplete/app-autocomplete.variants.ts create mode 100644 frontend/src/app/shared/ui/autocomplete/app-multi-autocomplete.component.ts create mode 100644 frontend/src/app/shared/ui/button/app-button.component.ts create mode 100644 frontend/src/app/shared/ui/button/app-button.variants.ts create mode 100644 frontend/src/app/shared/ui/checkbox/app-checkbox.component.ts create mode 100644 frontend/src/app/shared/ui/checkbox/app-checkbox.variants.ts create mode 100644 frontend/src/app/shared/ui/cn.ts create mode 100644 frontend/src/app/shared/ui/connected-group.ts create mode 100644 frontend/src/app/shared/ui/connected-overlay.ts create mode 100644 frontend/src/app/shared/ui/control.styles.ts create mode 100644 frontend/src/app/shared/ui/date-picker/app-date-picker-base.directive.ts create mode 100644 frontend/src/app/shared/ui/date-picker/app-date-picker.component.ts create mode 100644 frontend/src/app/shared/ui/date-picker/app-date-picker.variants.ts create mode 100644 frontend/src/app/shared/ui/date-picker/app-date-range-picker.component.ts create mode 100644 frontend/src/app/shared/ui/field/app-field.component.ts create mode 100644 frontend/src/app/shared/ui/field/app-field.context.ts create mode 100644 frontend/src/app/shared/ui/input/app-input.component.ts create mode 100644 frontend/src/app/shared/ui/input/app-input.variants.ts create mode 100644 frontend/src/app/shared/ui/menu/app-menu.component.ts create mode 100644 frontend/src/app/shared/ui/menu/app-menu.items.ts create mode 100644 frontend/src/app/shared/ui/menu/menu.pt.ts create mode 100644 frontend/src/app/shared/ui/message/app-message.component.ts create mode 100644 frontend/src/app/shared/ui/message/app-message.variants.ts create mode 100644 frontend/src/app/shared/ui/number-input/app-number-input.component.ts create mode 100644 frontend/src/app/shared/ui/overlay-list.styles.ts create mode 100644 frontend/src/app/shared/ui/radio-group/app-radio-group.component.ts create mode 100644 frontend/src/app/shared/ui/radio-group/app-radio-group.variants.ts create mode 100644 frontend/src/app/shared/ui/rating/app-rating.component.ts create mode 100644 frontend/src/app/shared/ui/select/app-multi-select.component.ts create mode 100644 frontend/src/app/shared/ui/select/app-select-base.directive.ts create mode 100644 frontend/src/app/shared/ui/select/app-select.component.ts create mode 100644 frontend/src/app/shared/ui/select/app-select.options.ts create mode 100644 frontend/src/app/shared/ui/select/app-select.templates.ts create mode 100644 frontend/src/app/shared/ui/select/app-select.variants.ts create mode 100644 frontend/src/app/shared/ui/slider/app-slider.component.ts create mode 100644 frontend/src/app/shared/ui/spinner/app-spinner.component.ts create mode 100644 frontend/src/app/shared/ui/spinner/app-spinner.variants.ts create mode 100644 frontend/src/app/shared/ui/split-button/app-split-button.component.ts create mode 100644 frontend/src/app/shared/ui/switch/app-switch.component.ts create mode 100644 frontend/src/app/shared/ui/switch/app-switch.variants.ts create mode 100644 frontend/src/app/shared/ui/tabs/app-tabs.component.ts create mode 100644 frontend/src/app/shared/ui/tabs/app-tabs.variants.ts create mode 100644 frontend/src/app/shared/ui/tag/app-tag.component.ts create mode 100644 frontend/src/app/shared/ui/tag/app-tag.variants.ts create mode 100644 frontend/src/app/shared/ui/textarea/app-textarea.component.ts create mode 100644 frontend/src/app/shared/ui/textarea/app-textarea.variants.ts create mode 100644 frontend/src/app/shared/ui/tooltip/app-tooltip.container.ts create mode 100644 frontend/src/app/shared/ui/tooltip/app-tooltip.directive.ts create mode 100644 frontend/src/app/shared/ui/tooltip/app-tooltip.positions.ts create mode 100644 frontend/src/assets/styles/connected-group.scss delete mode 100644 frontend/src/assets/styles/tabs.scss diff --git a/frontend/package.json b/frontend/package.json index ab6d77d61..4f2c37827 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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" }, diff --git a/frontend/src/app/app.routes.spec.ts b/frontend/src/app/app.routes.spec.ts index 99534ba42..9443a8a30 100644 --- a/frontend/src/app/app.routes.spec.ts +++ b/frontend/src/app/app.routes.spec.ts @@ -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', () => { diff --git a/frontend/src/app/app.routes.ts b/frontend/src/app/app.routes.ts index db97f4a1e..3377db276 100644 --- a/frontend/src/app/app.routes.ts +++ b/frontend/src/app/app.routes.ts @@ -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)}, ] }, { diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html index d301fd710..f9ad87f44 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html @@ -79,11 +79,9 @@ @case ('rating') { - @if (cell.rating !== null) { - ({{ cell.display }}) - } } @case ('clickable') { diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss index d7038584c..c60e8cee9 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss @@ -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); diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts index 4856fe388..e12ff08e2 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts @@ -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'); }); diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts index 94f753748..811a21727 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts @@ -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 = { CoverPlaceholderComponent, FormsModule, NgClass, - RatingComponent, + AppRatingComponent, RouterLink, Tooltip, TranslocoDirective, diff --git a/frontend/src/app/features/design-system/design-system.component.html b/frontend/src/app/features/design-system/design-system.component.html new file mode 100644 index 000000000..59bc6070b --- /dev/null +++ b/frontend/src/app/features/design-system/design-system.component.html @@ -0,0 +1,608 @@ +
+ + +
+

Buttons

+ +
+ @for (example of buttonExamples; track example.tone + example.variant) { +
+ {{ example.tone }} / {{ example.variant }} +
+ @for (size of buttonSizes; track size) { + + } +
+
+ } +
+ +
+ + + + + +
+
+ +
+

Split Buttons

+ +
+ + + +
+
+ +
+

Inputs

+ +
+
+ Small + +
+
+ Medium + +
+
+ Large + +
+
+ Invalid + +
+
+ Disabled + +
+
+ Password + +
+
+ Trailing Action + +
+
+ Leading Icon + +
+
+ Leading + Trailing + +
+
+
+ +
+

Number Inputs

+ +
+
+ Range (8-72) + +
+
+ Step 0.5 + +
+
+ With unit + +
+
+ Disabled + +
+
+
+ +
+

Sliders

+ +
+
+ Range value ({{ aspectRatioValue.toFixed(1) }}) + +
+
+ Percentage ({{ compressionValue }}%) + +
+
+ Disabled + +
+
+
+ +
+

Ratings

+ +
+
+ Expandable ({{ personalRating }}) + +
+
+ Editable ({{ ratingValue }}) + +
+
+ Read-only + +
+
+ Sizes +
+ + + +
+
+
+ Disabled + +
+
+
+ +
+

Checkboxes

+ +
+
+ Default + +
+
+ Checked + +
+
+ Indeterminate + +
+
+ Disabled + +
+
+
+ +
+

Switches

+ +
+
+ Off + +
+
+ On + +
+
+ Disabled + +
+
+ Small + +
+
+ Large + +
+
+ +
+ + + +
+
+ +
+

Radio Groups

+ +
+
+ List + +
+ +
+ Segmented + +
+ + + + +
+ +
+ + + + + +
+
+ +
+

Selects

+ +
+
+ Default + +
+
+ Small + +
+
+ Clearable + +
+
+ Filter + +
+
+ Grouped + +
+
+ Swatches + + + @if (option) { + + + {{ $any(option).label }} + + } + + + + + {{ $any(option).label }} + + + +
+
+ Invalid + +
+
+ Disabled + +
+
+ Multiple + +
+
+
+ +
+

Date Pickers

+ +
+
+ Default + +
+
+ Small + +
+
+ Bounded (this month) + +
+
+ Range + +
+
+ + + +
+
+
+ +
+

Autocomplete

+ +
+ +
+
+ +
+
+ +
+

Textareas

+ +
+
+ Default + +
+
+ Auto Resize + +
+
+ Invalid + +
+
+
+ +
+

Form Fields

+ +
+ + + + + + + + + + + + + + + +
+
+ +
+

Messages

+ +
+ Neutral message. + Primary message. + Success message. + Warning message. + Error message. +
+ +

+ Group validation: +

+
+ + +
+ +

+ Form summary: +

+
+ + + +
+
+ +
+

Accordion

+ +
+ + {{ item.title }} + + + + {{ item.body }} + +
+ +

Multiple items open.

+
+ + + {{ item.title }} + + {{ item.body }} + +
+
+ +
+

Spinners

+ +
+ + + + + + Loading... + +
+
+ +
+

Menus

+ + + +
+ +
+

Tooltips

+ +
+ + + + +
+
+ +
+

Tags

+ +
+ + + + + + + + + + + +
+ +
+ + + + Projected content +
+ +
+ + + +
+
+ +
+

Tabs

+ +
+ + +
+ + +
+ + +
+
+ +
diff --git a/frontend/src/app/features/design-system/design-system.component.scss b/frontend/src/app/features/design-system/design-system.component.scss new file mode 100644 index 000000000..8b6c9206e --- /dev/null +++ b/frontend/src/app/features/design-system/design-system.component.scss @@ -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; + } +} diff --git a/frontend/src/app/features/design-system/design-system.component.ts b/frontend/src/app/features/design-system/design-system.component.ts new file mode 100644 index 000000000..43eedf117 --- /dev/null +++ b/frontend/src/app/features/design-system/design-system.component.ts @@ -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[] = [ + { label: 'Option A', value: 'a' }, + { label: 'Option B', value: 'b' }, + { label: 'Option C', value: 'c' }, + ]; + readonly groupedSelectOptions: SelectOptionGroup[] = [ + { + 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('general'); + readonly segmentedTab = signal('general'); + readonly segmentedTabSm = signal('general'); + readonly segmentedTabLg = signal('general'); + readonly manyTab = signal('general'); + + readonly radioViewOptions: RadioOption[] = [ + { label: 'List', value: 'list' }, + { label: 'Grid', value: 'grid' }, + { label: 'Cards', value: 'cards' }, + ]; + readonly radioDensityOptions: RadioOption[] = [ + { 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([]); + tags: string[] = ['Tag one']; + readonly allTags = ['Tag one', 'Tag two', 'Tag three', 'Tag four', 'Tag five']; + readonly filteredTags = signal([]); + 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)) : []); + } +} diff --git a/frontend/src/app/features/design-system/forms/device-form.component.html b/frontend/src/app/features/design-system/forms/device-form.component.html new file mode 100644 index 000000000..183010e37 --- /dev/null +++ b/frontend/src/app/features/design-system/forms/device-form.component.html @@ -0,0 +1,124 @@ +
+
+
+ +
+

Device settings

+
+
+ +
+ + + + @if (deviceForm().submitting()) { + + } +
+ +
+
+
+
+

+ Hardcover +

+ +
+
+ + @if (!deviceForm.hardcover.apiKey().hidden()) { + + + + } +
+ +
+
+
+

+ Kobo +

+ +
+
+ + @if (!deviceForm.kobo.twoWaySync().hidden()) { + + + + + + + + + + + + + + + + + + + + } +
+ +
+
+
+

+ KOReader +

+ +
+
+ + @if (!deviceForm.koreader.username().hidden()) { + + + + + + + + + + + + } +
+ +
+ + + + @if (submitState() === 'saved') { + Settings saved. + } @else if (submitAttempted()) { + + } +
+
+ +
+ Form value +
{{ model() | json }}
+
+
+
diff --git a/frontend/src/app/features/design-system/forms/device-form.component.ts b/frontend/src/app/features/design-system/forms/device-form.component.ts new file mode 100644 index 000000000..56866c7dd --- /dev/null +++ b/frontend/src/app/features/design-system/forms/device-form.component.ts @@ -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(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 { + return new Promise(resolve => setTimeout(resolve, ms)); +} diff --git a/frontend/src/app/features/design-system/forms/everything-form.component.html b/frontend/src/app/features/design-system/forms/everything-form.component.html new file mode 100644 index 000000000..84cbcb904 --- /dev/null +++ b/frontend/src/app/features/design-system/forms/everything-form.component.html @@ -0,0 +1,116 @@ +
+
+
+ +
+

Everything

+
+
+ +
+ + + + @if (everythingForm().submitting()) { + + } +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + @if (submitState() === 'saved') { + Saved. + } @else if (submitAttempted()) { + + } +
+
+ +
+ Form value +
{{ model() | json }}
+
+
+
diff --git a/frontend/src/app/features/design-system/forms/everything-form.component.ts b/frontend/src/app/features/design-system/forms/everything-form.component.ts new file mode 100644 index 000000000..eecdc0c73 --- /dev/null +++ b/frontend/src/app/features/design-system/forms/everything-form.component.ts @@ -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(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[] = [ + { label: 'One', value: 'one' }, + { label: 'Two', value: 'two' }, + { label: 'Three', value: 'three' }, + ]; + readonly radioOptions: readonly RadioOption[] = [ + { 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([]); + readonly multiAutocompleteSuggestions = signal([]); + + 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 { + return new Promise(resolve => setTimeout(resolve, ms)); +} diff --git a/frontend/src/app/features/design-system/forms/library-form.component.html b/frontend/src/app/features/design-system/forms/library-form.component.html new file mode 100644 index 000000000..1bf2183be --- /dev/null +++ b/frontend/src/app/features/design-system/forms/library-form.component.html @@ -0,0 +1,84 @@ +
+
+
+ +
+

Create library

+
+
+ +
+ + + + @if (libraryForm().submitting()) { + + } +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + @if (submitState() === 'saved') { + Library saved. + } @else if (submitAttempted()) { + + } +
+
+ +
+ Form value +
{{ model() | json }}
+
+
+
diff --git a/frontend/src/app/features/design-system/forms/library-form.component.ts b/frontend/src/app/features/design-system/forms/library-form.component.ts new file mode 100644 index 000000000..859e183d7 --- /dev/null +++ b/frontend/src/app/features/design-system/forms/library-form.component.ts @@ -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(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[] = [ + { 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[] = [ + { 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[] = [ + { 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([]); + + 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 { + return new Promise(resolve => setTimeout(resolve, ms)); +} diff --git a/frontend/src/app/shared/components/rating/rating.component.html b/frontend/src/app/shared/components/rating/rating.component.html deleted file mode 100644 index 3a2151a83..000000000 --- a/frontend/src/app/shared/components/rating/rating.component.html +++ /dev/null @@ -1,17 +0,0 @@ - - @for (fill of starFills(); track $index) { - - - - - } - diff --git a/frontend/src/app/shared/components/rating/rating.component.scss b/frontend/src/app/shared/components/rating/rating.component.scss deleted file mode 100644 index e426e6893..000000000 --- a/frontend/src/app/shared/components/rating/rating.component.scss +++ /dev/null @@ -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); -} diff --git a/frontend/src/app/shared/components/rating/rating.component.ts b/frontend/src/app/shared/components/rating/rating.component.ts deleted file mode 100644 index 60d07135f..000000000 --- a/frontend/src/app/shared/components/rating/rating.component.ts +++ /dev/null @@ -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(null); - color = input(null); - max = input(5); - size = input('18px'); - ariaLabel = input(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'; - } -} diff --git a/frontend/src/app/shared/components/tabs/app-tabs.component.html b/frontend/src/app/shared/components/tabs/app-tabs.component.html deleted file mode 100644 index 2febc09b5..000000000 --- a/frontend/src/app/shared/components/tabs/app-tabs.component.html +++ /dev/null @@ -1,33 +0,0 @@ -@if (tabs().length) { -
-
- - @for (tab of tabs(); track tab.id) { - - } -
-
-} diff --git a/frontend/src/app/shared/components/tabs/app-tabs.component.ts b/frontend/src/app/shared/components/tabs/app-tabs.component.ts deleted file mode 100644 index 75009e16f..000000000 --- a/frontend/src/app/shared/components/tabs/app-tabs.component.ts +++ /dev/null @@ -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(); - readonly variant = input('underline'); - readonly placement = input('below'); - readonly ariaLabel = input.required(); - readonly selectedTabId = model(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); - }); - }); - }); - } -} diff --git a/frontend/src/app/shared/ui/accordion/app-accordion.component.ts b/frontend/src/app/shared/ui/accordion/app-accordion.component.ts new file mode 100644 index 000000000..48f4c532a --- /dev/null +++ b/frontend/src/app/shared/ui/accordion/app-accordion.component.ts @@ -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: ` +
+ @for (item of items(); track $index; let i = $index) { +
+
+
+ +
+ @if (actionsTemplate(); as tpl) { +
+
+ +
+
+ } +
+ +
+
+ +
+ @if (contentTemplate(); as tpl) { + + } +
+
+
+
+
+ } +
+ `, +}) +export class AppAccordionComponent { + readonly items = input([]); + 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(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); + } + } +} diff --git a/frontend/src/app/shared/ui/accordion/app-accordion.directives.ts b/frontend/src/app/shared/ui/accordion/app-accordion.directives.ts new file mode 100644 index 000000000..1345115ce --- /dev/null +++ b/frontend/src/app/shared/ui/accordion/app-accordion.directives.ts @@ -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); +} diff --git a/frontend/src/app/shared/ui/autocomplete/app-autocomplete-base.directive.ts b/frontend/src/app/shared/ui/autocomplete/app-autocomplete-base.directive.ts new file mode 100644 index 000000000..4fac330dc --- /dev/null +++ b/frontend/src/app/shared/ui/autocomplete/app-autocomplete-base.directive.ts @@ -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 size = input('md'); + readonly placeholder = input(''); + readonly emptyMessage = input(''); + readonly inputId = input(''); + readonly ariaLabel = input(''); + readonly ariaDescribedBy = input(''); + + readonly complete = output(); + + 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>('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); + } +} diff --git a/frontend/src/app/shared/ui/autocomplete/app-autocomplete.component.ts b/frontend/src/app/shared/ui/autocomplete/app-autocomplete.component.ts new file mode 100644 index 000000000..8b5995f1e --- /dev/null +++ b/frontend/src/app/shared/ui/autocomplete/app-autocomplete.component.ts @@ -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: ` +
+
+ + @if (pending()) { + + } +
+ + + +
+
    + @for (option of suggestions(); track option) { +
  • + {{ option }} +
  • + } @empty { +
  • {{ emptyMessage() || ('shared.ui.autocomplete.noResults' | transloco) }}
  • + } +
+
+
+
+
+ `, +}) +export class AppAutocompleteComponent extends AppAutocompleteBaseDirective implements FormValueControl { + 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(); + } +} diff --git a/frontend/src/app/shared/ui/autocomplete/app-autocomplete.variants.ts b/frontend/src/app/shared/ui/autocomplete/app-autocomplete.variants.ts new file mode 100644 index 000000000..1e48e367f --- /dev/null +++ b/frontend/src/app/shared/ui/autocomplete/app-autocomplete.variants.ts @@ -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 }, + }, +); diff --git a/frontend/src/app/shared/ui/autocomplete/app-multi-autocomplete.component.ts b/frontend/src/app/shared/ui/autocomplete/app-multi-autocomplete.component.ts new file mode 100644 index 000000000..f912de16e --- /dev/null +++ b/frontend/src/app/shared/ui/autocomplete/app-multi-autocomplete.component.ts @@ -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: ` +
+
+ @for (tag of value(); track tag) { + + } + + @if (pending()) { + + } +
+ + + +
+
    + @for (option of suggestions(); track option) { +
  • + {{ option }} +
  • + } @empty { +
  • {{ emptyMessage() || ('shared.ui.autocomplete.noResults' | transloco) }}
  • + } +
+
+
+
+
+ `, +}) +export class AppMultiAutocompleteComponent extends AppAutocompleteBaseDirective implements FormValueControl { + readonly value = model([]); + + readonly removeTagLabel = input(''); + + private readonly listbox = viewChild>(Listbox); + protected readonly optionRefs = viewChildren(Option); + + protected readonly query = linkedSignal({ + 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(''); + } +} diff --git a/frontend/src/app/shared/ui/button/app-button.component.ts b/frontend/src/app/shared/ui/button/app-button.component.ts new file mode 100644 index 000000000..1e0d9d4f3 --- /dev/null +++ b/frontend/src/app/shared/ui/button/app-button.component.ts @@ -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: ` + + `, +}) +export class AppButtonComponent { + readonly tone = input('neutral'); + readonly variant = input('soft'); + readonly size = input('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(null); + readonly form = input(''); + readonly title = input(''); + readonly tabIndex = input(null); + readonly label = input(''); + readonly ariaLabel = input(''); + readonly ariaControls = input(''); + readonly ariaExpanded = input(null); + readonly ariaHasPopup = input(null); + readonly ariaPressed = input(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(); + + 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'); +} diff --git a/frontend/src/app/shared/ui/button/app-button.variants.ts b/frontend/src/app/shared/ui/button/app-button.variants.ts new file mode 100644 index 000000000..52fa439dc --- /dev/null +++ b/frontend/src/app/shared/ui/button/app-button.variants.ts @@ -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 }, + }, +); diff --git a/frontend/src/app/shared/ui/checkbox/app-checkbox.component.ts b/frontend/src/app/shared/ui/checkbox/app-checkbox.component.ts new file mode 100644 index 000000000..cd7e7ac51 --- /dev/null +++ b/frontend/src/app/shared/ui/checkbox/app-checkbox.component.ts @@ -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: ` + + + + + + + `, +}) +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('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>('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); + } +} diff --git a/frontend/src/app/shared/ui/checkbox/app-checkbox.variants.ts b/frontend/src/app/shared/ui/checkbox/app-checkbox.variants.ts new file mode 100644 index 000000000..9f85d47e5 --- /dev/null +++ b/frontend/src/app/shared/ui/checkbox/app-checkbox.variants.ts @@ -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' }, + }, +); diff --git a/frontend/src/app/shared/ui/cn.ts b/frontend/src/app/shared/ui/cn.ts new file mode 100644 index 000000000..5a04b73ef --- /dev/null +++ b/frontend/src/app/shared/ui/cn.ts @@ -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 & { class?: string }; + +export function ptViewMerge(global: unknown, self: unknown, datasets?: unknown): Record { + 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) }; +} diff --git a/frontend/src/app/shared/ui/connected-group.ts b/frontend/src/app/shared/ui/connected-group.ts new file mode 100644 index 000000000..f154773eb --- /dev/null +++ b/frontend/src/app/shared/ui/connected-group.ts @@ -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', + ); +} diff --git a/frontend/src/app/shared/ui/connected-overlay.ts b/frontend/src/app/shared/ui/connected-overlay.ts new file mode 100644 index 000000000..a53f8946c --- /dev/null +++ b/frontend/src/app/shared/ui/connected-overlay.ts @@ -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(); + }); +} diff --git a/frontend/src/app/shared/ui/control.styles.ts b/frontend/src/app/shared/ui/control.styles.ts new file mode 100644 index 000000000..faf9a0804 --- /dev/null +++ b/frontend/src/app/shared/ui/control.styles.ts @@ -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'; diff --git a/frontend/src/app/shared/ui/date-picker/app-date-picker-base.directive.ts b/frontend/src/app/shared/ui/date-picker/app-date-picker-base.directive.ts new file mode 100644 index 000000000..eac721744 --- /dev/null +++ b/frontend/src/app/shared/ui/date-picker/app-date-picker-base.directive.ts @@ -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 = ` +
+ + + + @if (pending()) { + + } @else { + + } + +
+ + +
+
+ + {{ monthYearLabel() }} + +
+ + + + + @for (weekday of weekdays(); track weekday.key) { + + } + + + + @for (week of weeks(); track week.key) { + + @for (day of week.days; track day.iso) { + + } + + } + +
+ + {{ weekday.long }} + + +
+ +
+
+
+ `; + +@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('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(null); + + protected abstract readonly isRange: boolean; + protected abstract readonly displayValue: Signal; + 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>('origin'); + private readonly triggerRef = viewChild>('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(() => { + 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('button[data-selected]') ?? + overlayElement.querySelector('button[data-today]:not([disabled])') ?? + overlayElement.querySelector('button[data-day]:not([disabled])'); + target?.focus(); + } + + focus(options?: FocusOptions): void { + this.triggerRef()?.nativeElement.focus(options); + } +} diff --git a/frontend/src/app/shared/ui/date-picker/app-date-picker.component.ts b/frontend/src/app/shared/ui/date-picker/app-date-picker.component.ts new file mode 100644 index 000000000..1f5afd071 --- /dev/null +++ b/frontend/src/app/shared/ui/date-picker/app-date-picker.component.ts @@ -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 { + 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; + } +} diff --git a/frontend/src/app/shared/ui/date-picker/app-date-picker.variants.ts b/frontend/src/app/shared/ui/date-picker/app-date-picker.variants.ts new file mode 100644 index 000000000..f1ea501df --- /dev/null +++ b/frontend/src/app/shared/ui/date-picker/app-date-picker.variants.ts @@ -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'; diff --git a/frontend/src/app/shared/ui/date-picker/app-date-range-picker.component.ts b/frontend/src/app/shared/ui/date-picker/app-date-range-picker.component.ts new file mode 100644 index 000000000..7470a16ad --- /dev/null +++ b/frontend/src/app/shared/ui/date-picker/app-date-range-picker.component.ts @@ -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 { + readonly value = model(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 === ''; + } +} diff --git a/frontend/src/app/shared/ui/field/app-field.component.ts b/frontend/src/app/shared/ui/field/app-field.component.ts new file mode 100644 index 000000000..a4ca0e019 --- /dev/null +++ b/frontend/src/app/shared/ui/field/app-field.component.ts @@ -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()) { + + } + + + + @if (showHint()) { +

{{ hint() }}

+ } + @if (displayErrors().length) { +
+ @for (message of displayErrors(); track message) { +

{{ message }}

+ } +
+ } @else if (disabledReasonMessages().length) { +
+ @for (message of disabledReasonMessages(); track message) { +

{{ message }}

+ } +
+ } + `, +}) +export class AppFieldComponent implements AppFieldContext { + readonly field = input(undefined); + readonly label = input(''); + readonly hint = input(''); + readonly errors = input([]); + 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 | 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(() => { + 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(() => + (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; + }; +} diff --git a/frontend/src/app/shared/ui/field/app-field.context.ts b/frontend/src/app/shared/ui/field/app-field.context.ts new file mode 100644 index 000000000..7904515f7 --- /dev/null +++ b/frontend/src/app/shared/ui/field/app-field.context.ts @@ -0,0 +1,23 @@ +import { InjectionToken, type Signal } from '@angular/core'; +import { type FieldState, type ValidationError } from '@angular/forms/signals'; + +export type AppFieldLike = () => FieldState; + +export interface AppFieldContext { + readonly controlId: Signal; + readonly labelId: Signal; + readonly describedById: Signal; + readonly validationVisible: Signal; +} + +export const APP_FIELD = new InjectionToken('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; +} diff --git a/frontend/src/app/shared/ui/input/app-input.component.ts b/frontend/src/app/shared/ui/input/app-input.component.ts new file mode 100644 index 000000000..b1c7b5496 --- /dev/null +++ b/frontend/src/app/shared/ui/input/app-input.component.ts @@ -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()) { + + + + } + + @if (pending()) { + + + + } + @if (showTrailingAction()) { + + } + `, +}) +export class AppInputComponent implements FormValueControl { + 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('md'); + readonly variant = input('outlined'); + readonly type = input('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(undefined); + readonly minLength = input(undefined); + readonly pattern = input([]); + readonly revealToggle = input(false, { transform: booleanAttribute }); + readonly leadingIcon = input(''); + readonly trailingIcon = input(''); + readonly trailingAriaLabel = input(''); + readonly trailingPressed = input(null); + + readonly keyedDown = output(); + readonly enterPressed = output(); + readonly trailingClicked = output(); + + 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>('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); + } +} diff --git a/frontend/src/app/shared/ui/input/app-input.variants.ts b/frontend/src/app/shared/ui/input/app-input.variants.ts new file mode 100644 index 000000000..43230488f --- /dev/null +++ b/frontend/src/app/shared/ui/input/app-input.variants.ts @@ -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' }, + }, +); diff --git a/frontend/src/app/shared/ui/menu/app-menu.component.ts b/frontend/src/app/shared/ui/menu/app-menu.component.ts new file mode 100644 index 000000000..0ea82f67b --- /dev/null +++ b/frontend/src/app/shared/ui/menu/app-menu.component.ts @@ -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) { + + } @else { + + } + `, +}) +export class AppMenuComponent { + readonly model = input([]); + readonly contextTarget = input(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); + } +} diff --git a/frontend/src/app/shared/ui/menu/app-menu.items.ts b/frontend/src/app/shared/ui/menu/app-menu.items.ts new file mode 100644 index 000000000..d58d09023 --- /dev/null +++ b/frontend/src/app/shared/ui/menu/app-menu.items.ts @@ -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, +}); diff --git a/frontend/src/app/shared/ui/menu/menu.pt.ts b/frontend/src/app/shared/ui/menu/menu.pt.ts new file mode 100644 index 000000000..1af2a9750 --- /dev/null +++ b/frontend/src/app/shared/ui/menu/menu.pt.ts @@ -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; diff --git a/frontend/src/app/shared/ui/message/app-message.component.ts b/frontend/src/app/shared/ui/message/app-message.component.ts new file mode 100644 index 000000000..58fce5cf8 --- /dev/null +++ b/frontend/src/app/shared/ui/message/app-message.component.ts @@ -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()) { +
+ +
+ @if (field() && summary()) { + @if (summaryLayout() === 'inline') { + @if (hasMultipleSummaryIssues()) { +
+ + {{ activeIssueMessage() }} + + + {{ 'shared.ui.message.issuePosition' | transloco: { current: activeSummaryIndex() + 1, count: summaryCount() } }} + +
+ + +
+
+ } @else { + + } + } @else { +

+ {{ 'shared.ui.message.issueCount' | transloco: { count: summaryCount() } }} +

+
    + @for (issue of summaryIssues(); track issue) { +
  • + +
  • + } +
+ } + } @else if (field()) { + {{ fieldText() }} + } @else { + + } +
+
+ } + `, +}) +export class AppMessageComponent { + readonly color = input('neutral'); + readonly field = input(undefined); + readonly summary = input(false, { transform: booleanAttribute }); + readonly summaryLayout = input('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 | null>(() => this.field()?.() ?? null); + + protected readonly fieldMessages = computed(() => { + 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(() => { + 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(() => (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('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; + }; +} diff --git a/frontend/src/app/shared/ui/message/app-message.variants.ts b/frontend/src/app/shared/ui/message/app-message.variants.ts new file mode 100644 index 000000000..0429eb00c --- /dev/null +++ b/frontend/src/app/shared/ui/message/app-message.variants.ts @@ -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 = { + 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', +}; diff --git a/frontend/src/app/shared/ui/number-input/app-number-input.component.ts b/frontend/src/app/shared/ui/number-input/app-number-input.component.ts new file mode 100644 index 000000000..2113680c4 --- /dev/null +++ b/frontend/src/app/shared/ui/number-input/app-number-input.component.ts @@ -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: ` + + + @if (unit() || !readonly()) { +
+ @if (unit()) { + {{ unit() }} + } + @if (!readonly()) { + + + + + } +
+ } + `, +}) +export class AppNumberInputComponent implements FormValueControl { + readonly value = model(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('md'); + readonly min = input(undefined); + readonly max = input(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>('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 { + const trimmed = raw.trim(); + if (trimmed === '') return { value: null }; + + const parsed = Number(trimmed); + if (!Number.isFinite(parsed)) return { error: { kind: 'parse' } }; + + return { value: parsed }; +} diff --git a/frontend/src/app/shared/ui/overlay-list.styles.ts b/frontend/src/app/shared/ui/overlay-list.styles.ts new file mode 100644 index 000000000..aee1c50e9 --- /dev/null +++ b/frontend/src/app/shared/ui/overlay-list.styles.ts @@ -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'; diff --git a/frontend/src/app/shared/ui/radio-group/app-radio-group.component.ts b/frontend/src/app/shared/ui/radio-group/app-radio-group.component.ts new file mode 100644 index 000000000..224969f97 --- /dev/null +++ b/frontend/src/app/shared/ui/radio-group/app-radio-group.component.ts @@ -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 { + readonly value: T; + readonly label: string; + readonly description?: string; + readonly disabled?: boolean; +} + +const defaultCompareWith = (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: ` +
+ @for (option of options(); track option.value; let i = $index) { + + } +
+ `, +}) +export class AppRadioGroupComponent implements FormValueControl { + readonly value = model(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 variant = input('list'); + readonly size = input('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>('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): 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): 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); + } +} diff --git a/frontend/src/app/shared/ui/radio-group/app-radio-group.variants.ts b/frontend/src/app/shared/ui/radio-group/app-radio-group.variants.ts new file mode 100644 index 000000000..049b8d69b --- /dev/null +++ b/frontend/src/app/shared/ui/radio-group/app-radio-group.variants.ts @@ -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' }, +}); diff --git a/frontend/src/app/shared/ui/rating/app-rating.component.ts b/frontend/src/app/shared/ui/rating/app-rating.component.ts new file mode 100644 index 000000000..db0029e2f --- /dev/null +++ b/frontend/src/app/shared/ui/rating/app-rating.component.ts @@ -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()) { + + @for (star of starList(); track $index) { + + + + + } + @if (showValue() && value() > 0) { + {{ valueLabel() }} + } + @if (pending()) { + + } + + } @else { +
+ + @for (star of starList(); track $index) { + + } + @if (expandable()) { + {{ expandableLabel() }} + } @else if (showValue() && value() > 0) { + {{ valueLabel() }} + } + @if (pending()) { + + } +
+ } + `, + 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 { + 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(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>('input'); + private readonly readonlyRoot = viewChild>('readonlyRoot'); + + protected readonly starList = computed(() => { + 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); +} diff --git a/frontend/src/app/shared/ui/select/app-multi-select.component.ts b/frontend/src/app/shared/ui/select/app-multi-select.component.ts new file mode 100644 index 000000000..94adfa877 --- /dev/null +++ b/frontend/src/app/shared/ui/select/app-multi-select.component.ts @@ -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: ` +
+
+ + + + + @if (showClear() && hasSelection() && !isUnavailable()) { + + } + + + @if (pending()) { + + } @else { + + } + +
+ + + +
+ @if (filter()) { +
+ + +
+ } + +
    + @for (grp of renderedGroups(); track grp.trackKey; let first = $first) { + @if (grouped()) { + @if (!first) { +
  • + } +
  • {{ grp.label }}
  • + } + @for (option of grp.options; track option) { +
  • + + @if (isSelected(option)) { } + + @if (optionTemplate(); as tpl) { + + } @else { + {{ option.label }} + } +
  • + } + } @empty { +
  • {{ emptyMessage() || ('shared.ui.select.noResults' | transloco) }}
  • + } +
+
+
+
+
+ `, +}) +export class AppMultiSelectComponent extends AppSelectBaseDirective implements FormValueControl { + readonly value = model([]); + + 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(() => { + 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): 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', + ); + } +} diff --git a/frontend/src/app/shared/ui/select/app-select-base.directive.ts b/frontend/src/app/shared/ui/select/app-select-base.directive.ts new file mode 100644 index 000000000..7086ebb1d --- /dev/null +++ b/frontend/src/app/shared/ui/select/app-select-base.directive.ts @@ -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 = (optionValue: T, selectedValue: T): boolean => Object.is(optionValue, selectedValue); +const UNGROUPED_GROUP_TRACK_KEY = Symbol('app-select-ungrouped'); + +interface RenderedSelectOptionGroup extends SelectOptionGroup { + readonly trackKey: unknown; +} + +@Directive() +export abstract class AppSelectBaseDirective { + readonly disabled = input(false, { transform: booleanAttribute }); + readonly required = input(false, { transform: booleanAttribute }); + readonly invalid = input(false, { transform: booleanAttribute }); + readonly pending = input(false, { transform: booleanAttribute }); + readonly readonly = input(false, { transform: booleanAttribute }); + readonly touched = model(false); + readonly name = input(''); + + readonly size = input('md'); + readonly variant = input('outlined'); + readonly options = input[]>([]); + readonly groups = input[]>([]); + readonly filter = input(false, { transform: booleanAttribute }); + readonly filterPlaceholder = input(''); + readonly showClear = input(false, { transform: booleanAttribute }); + readonly placeholder = input(''); + readonly emptyMessage = input(''); + readonly inputId = input(''); + readonly ariaLabel = input(''); + readonly ariaLabelledBy = input(''); + readonly ariaDescribedBy = input(''); + readonly styleClass = input(''); + readonly compareWith = input>(defaultCompareWith); + + readonly cleared = output(); + + protected abstract readonly hasSelection: Signal; + protected abstract readonly triggerLabel: Signal; + protected abstract readonly listboxValues: Signal; + protected abstract onValuesChange(values: readonly T[]): void; + protected abstract clearValue(): void; + protected abstract isSelected(option: SelectOption): boolean; + + private readonly fieldContext = inject(APP_FIELD, { optional: true }); + private readonly overlayService = inject(Overlay); + private readonly combobox = viewChild(Combobox); + private readonly overlay = viewChild(CdkConnectedOverlay); + private readonly input = viewChild>('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[]>(() => { + if (!this.grouped()) { + const options = this.options().filter((option) => this.matchesFilter(option)); + return options.length ? [{ label: '', options, trackKey: UNGROUPED_GROUP_TRACK_KEY }] : []; + } + + const out: RenderedSelectOptionGroup[] = []; + for (const group of this.groups()) { + const options = group.options.filter((option) => this.matchesFilter(option)); + if (options.length) out.push({ label: group.label, options, trackKey: group }); + } + return out; + }); + + protected readonly flatOptions = computed[]>(() => + this.grouped() ? this.groups().flatMap((group) => group.options) : this.options(), + ); + + protected readonly filterText = linkedSignal({ + source: () => this.combobox()?.expanded() ?? false, + computation: (expanded, previous) => (expanded ? (previous?.value ?? '') : ''), + }); + + protected 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): 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 | null { + return this.flatOptions().find((option) => this.valuesMatch(option.value, value)) ?? null; + } + + protected findVisibleOptionForValue(value: T): SelectOption | null { + for (const group of this.renderedGroups()) { + const option = group.options.find((candidate) => this.valuesMatch(candidate.value, value)); + if (option) return option; + } + return null; + } + + protected isVisibleValue(value: T): boolean { + return this.findVisibleOptionForValue(value) != null; + } + + protected visibleOptionValuesForSelected(values: readonly T[]): T[] { + return this.renderedGroups() + .flatMap((group) => group.options) + .filter((option) => values.some((value) => this.valuesMatch(option.value, value))) + .map((option) => option.value); + } + + protected onOverlayAttach(): void { + refreshConnectedOverlayPosition(this.overlay()); + } + + focus(options?: FocusOptions): void { + this.input()?.nativeElement.focus(options); + } +} diff --git a/frontend/src/app/shared/ui/select/app-select.component.ts b/frontend/src/app/shared/ui/select/app-select.component.ts new file mode 100644 index 000000000..a044f231a --- /dev/null +++ b/frontend/src/app/shared/ui/select/app-select.component.ts @@ -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: ` +
+
+ + + + + @if (showClear() && hasSelection() && !isUnavailable()) { + + } + + + @if (pending()) { + + } @else { + + } + +
+ + + +
+ @if (filter()) { +
+ + +
+ } + +
    + @for (grp of renderedGroups(); track grp.trackKey; let first = $first) { + @if (grouped()) { + @if (!first) { +
  • + } +
  • {{ grp.label }}
  • + } + @for (option of grp.options; track option) { +
  • + @if (optionTemplate(); as tpl) { + + } @else { + {{ option.label }} + } + @if (isSelected(option)) { + + } +
  • + } + } @empty { +
  • {{ emptyMessage() || ('shared.ui.select.noResults' | transloco) }}
  • + } +
+
+
+
+
+ `, +}) +export class AppSelectComponent extends AppSelectBaseDirective implements FormValueControl { + readonly value = model(null); + + protected readonly selectedTemplate = contentChild(AppSelectSelectedTemplateDirective); + + protected readonly selectedOption = computed | 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(() => { + 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): boolean { + const value = this.value(); + return value != null && this.valuesMatch(option.value, value); + } +} diff --git a/frontend/src/app/shared/ui/select/app-select.options.ts b/frontend/src/app/shared/ui/select/app-select.options.ts new file mode 100644 index 000000000..c5f705507 --- /dev/null +++ b/frontend/src/app/shared/ui/select/app-select.options.ts @@ -0,0 +1,12 @@ +export interface SelectOption { + readonly label: string; + readonly value: T; + readonly disabled?: boolean; +} + +export interface SelectOptionGroup { + readonly label: string; + readonly options: readonly SelectOption[]; +} + +export type SelectCompareWith = (optionValue: T, selectedValue: T) => boolean; diff --git a/frontend/src/app/shared/ui/select/app-select.templates.ts b/frontend/src/app/shared/ui/select/app-select.templates.ts new file mode 100644 index 000000000..e27f2b917 --- /dev/null +++ b/frontend/src/app/shared/ui/select/app-select.templates.ts @@ -0,0 +1,21 @@ +import { Directive, TemplateRef, inject } from '@angular/core'; + +interface AppSelectOptionTemplateContext { + $implicit: T; +} + +@Directive({ + selector: 'ng-template[appSelectOption]', + standalone: true, +}) +export class AppSelectOptionTemplateDirective { + readonly template = inject>>(TemplateRef); +} + +@Directive({ + selector: 'ng-template[appSelectSelected]', + standalone: true, +}) +export class AppSelectSelectedTemplateDirective { + readonly template = inject>>(TemplateRef); +} diff --git a/frontend/src/app/shared/ui/select/app-select.variants.ts b/frontend/src/app/shared/ui/select/app-select.variants.ts new file mode 100644 index 000000000..50c786a48 --- /dev/null +++ b/frontend/src/app/shared/ui/select/app-select.variants.ts @@ -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' }, + }, +); diff --git a/frontend/src/app/shared/ui/slider/app-slider.component.ts b/frontend/src/app/shared/ui/slider/app-slider.component.ts new file mode 100644 index 000000000..92af74ea4 --- /dev/null +++ b/frontend/src/app/shared/ui/slider/app-slider.component.ts @@ -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: ` +
+ + +
+
+
+
+ `, +}) +export class AppSliderComponent implements FormValueControl { + 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(undefined); + readonly max = input(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>('input'); + + protected onInput(raw: string): void { + this.value.set(Number(raw)); + } + + focus(options?: FocusOptions): void { + this.input()?.nativeElement.focus(options); + } +} diff --git a/frontend/src/app/shared/ui/spinner/app-spinner.component.ts b/frontend/src/app/shared/ui/spinner/app-spinner.component.ts new file mode 100644 index 000000000..ea22b3674 --- /dev/null +++ b/frontend/src/app/shared/ui/spinner/app-spinner.component.ts @@ -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: ``, +}) +export class AppSpinnerComponent { + readonly size = input('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())); +} diff --git a/frontend/src/app/shared/ui/spinner/app-spinner.variants.ts b/frontend/src/app/shared/ui/spinner/app-spinner.variants.ts new file mode 100644 index 000000000..8d9411b93 --- /dev/null +++ b/frontend/src/app/shared/ui/spinner/app-spinner.variants.ts @@ -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' }, +}); diff --git a/frontend/src/app/shared/ui/split-button/app-split-button.component.ts b/frontend/src/app/shared/ui/split-button/app-split-button.component.ts new file mode 100644 index 000000000..0cdac305e --- /dev/null +++ b/frontend/src/app/shared/ui/split-button/app-split-button.component.ts @@ -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: ` + + + + + + + + `, +}) +export class AppSplitButtonComponent { + readonly tone = input('neutral'); + readonly variant = input('soft'); + readonly size = input('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(null); + readonly form = input(''); + readonly title = input(''); + readonly tabIndex = input(null); + readonly label = input(''); + readonly ariaLabel = input(''); + readonly menuAriaLabel = input(''); + readonly icon = input(''); + readonly iconPos = input<'left' | 'right'>('left'); + readonly model = input([]); + 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(); + + 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(), + ), + ); +} diff --git a/frontend/src/app/shared/ui/switch/app-switch.component.ts b/frontend/src/app/shared/ui/switch/app-switch.component.ts new file mode 100644 index 000000000..5f974d444 --- /dev/null +++ b/frontend/src/app/shared/ui/switch/app-switch.component.ts @@ -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: ` + + + + + + `, +}) +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('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>('control'); + + protected onInputChange(checked: boolean): void { + this.checked.set(checked); + } + + focus(options?: FocusOptions): void { + this.control()?.nativeElement.focus(options); + } +} diff --git a/frontend/src/app/shared/ui/switch/app-switch.variants.ts b/frontend/src/app/shared/ui/switch/app-switch.variants.ts new file mode 100644 index 000000000..0c0100937 --- /dev/null +++ b/frontend/src/app/shared/ui/switch/app-switch.variants.ts @@ -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 }, + }, +); diff --git a/frontend/src/app/shared/ui/tabs/app-tabs.component.ts b/frontend/src/app/shared/ui/tabs/app-tabs.component.ts new file mode 100644 index 000000000..50024bc83 --- /dev/null +++ b/frontend/src/app/shared/ui/tabs/app-tabs.component.ts @@ -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()) { + + } +
+
+
+ + @for (tab of tabs(); track tab.id) { + + } +
+
+
+ } + `, +}) +export class AppTabsComponent { + readonly tabs = input.required(); + readonly variant = input('underline'); + readonly size = input('md'); + readonly placement = input('inline'); + readonly collapse = input('auto'); + readonly ariaLabel = input.required(); + readonly selectedTabId = model(undefined); + + private readonly host = inject>(ElementRef); + private readonly destroyRef = inject(DestroyRef); + private readonly tabDirectives = viewChildren(NgTab); + private readonly tabListRef = viewChild>('tabList', { read: ElementRef }); + + protected readonly activeTabId = computed(() => this.resolveTabId(this.selectedTabId())); + protected readonly collapsedOptions = computed[]>(() => + 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; + } +} diff --git a/frontend/src/app/shared/ui/tabs/app-tabs.variants.ts b/frontend/src/app/shared/ui/tabs/app-tabs.variants.ts new file mode 100644 index 000000000..b7f8d7143 --- /dev/null +++ b/frontend/src/app/shared/ui/tabs/app-tabs.variants.ts @@ -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' }, + }, +); diff --git a/frontend/src/app/shared/ui/tag/app-tag.component.ts b/frontend/src/app/shared/ui/tag/app-tag.component.ts new file mode 100644 index 000000000..3a039b473 --- /dev/null +++ b/frontend/src/app/shared/ui/tag/app-tag.component.ts @@ -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()) { + + } @else { + + @if (icon()) { + + } + @if (label()) { + {{ label() }} + } + + @if (removable()) { + + } + + } + `, +}) +export class AppTagComponent { + readonly color = input('neutral'); + readonly size = input('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(); + readonly remove = output(); + + 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; + }); +} diff --git a/frontend/src/app/shared/ui/tag/app-tag.variants.ts b/frontend/src/app/shared/ui/tag/app-tag.variants.ts new file mode 100644 index 000000000..e4b7f4b43 --- /dev/null +++ b/frontend/src/app/shared/ui/tag/app-tag.variants.ts @@ -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' }, + }, +); diff --git a/frontend/src/app/shared/ui/textarea/app-textarea.component.ts b/frontend/src/app/shared/ui/textarea/app-textarea.component.ts new file mode 100644 index 000000000..abae14bc7 --- /dev/null +++ b/frontend/src/app/shared/ui/textarea/app-textarea.component.ts @@ -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: ` + + @if (pending()) { + + + + } + `, +}) +export class AppTextareaComponent implements FormValueControl { + 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(4); + readonly maxLength = input(undefined); + readonly minLength = input(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>('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`; + } +} diff --git a/frontend/src/app/shared/ui/textarea/app-textarea.variants.ts b/frontend/src/app/shared/ui/textarea/app-textarea.variants.ts new file mode 100644 index 000000000..0ad2cf5ff --- /dev/null +++ b/frontend/src/app/shared/ui/textarea/app-textarea.variants.ts @@ -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 }, + }, +); diff --git a/frontend/src/app/shared/ui/tooltip/app-tooltip.container.ts b/frontend/src/app/shared/ui/tooltip/app-tooltip.container.ts new file mode 100644 index 000000000..23fb5939b --- /dev/null +++ b/frontend/src/app/shared/ui/tooltip/app-tooltip.container.ts @@ -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: `
{{ text() }}
`, +}) +export class AppTooltipContainerComponent { + readonly id = input(''); + readonly text = input(''); + + protected readonly chipClass = CHIP_CLASS; +} diff --git a/frontend/src/app/shared/ui/tooltip/app-tooltip.directive.ts b/frontend/src/app/shared/ui/tooltip/app-tooltip.directive.ts new file mode 100644 index 000000000..08509ae89 --- /dev/null +++ b/frontend/src/app/shared/ui/tooltip/app-tooltip.directive.ts @@ -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); + private readonly overlay = inject(Overlay); + private readonly vcr = inject(ViewContainerRef); + private readonly focusMonitor = inject(FocusMonitor); + + readonly text = input('', { alias: 'appTooltip' }); + readonly position = input('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 | null = null; + private previousDescribedBy: string | null = null; + private showTimer: ReturnType | null = null; + private hideTimer: ReturnType | 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; + } +} diff --git a/frontend/src/app/shared/ui/tooltip/app-tooltip.positions.ts b/frontend/src/app/shared/ui/tooltip/app-tooltip.positions.ts new file mode 100644 index 000000000..7db52bd87 --- /dev/null +++ b/frontend/src/app/shared/ui/tooltip/app-tooltip.positions.ts @@ -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 = { + 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 = { + 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]); +} diff --git a/frontend/src/assets/styles/connected-group.scss b/frontend/src/assets/styles/connected-group.scss new file mode 100644 index 000000000..a53ad0db8 --- /dev/null +++ b/frontend/src/assets/styles/connected-group.scss @@ -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; +} diff --git a/frontend/src/assets/styles/tabs.scss b/frontend/src/assets/styles/tabs.scss deleted file mode 100644 index f52f16ed5..000000000 --- a/frontend/src/assets/styles/tabs.scss +++ /dev/null @@ -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); - } -} diff --git a/frontend/src/assets/styles/tailwind.css b/frontend/src/assets/styles/tailwind.css index e3e9a58a4..819802264 100644 --- a/frontend/src/assets/styles/tailwind.css +++ b/frontend/src/assets/styles/tailwind.css @@ -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}"); diff --git a/frontend/src/i18n/en/shared.json b/frontend/src/i18n/en/shared.json index b1684b352..7b256b021 100644 --- a/frontend/src/i18n/en/shared.json +++ b/frontend/src/i18n/en/shared.json @@ -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" + } } } diff --git a/frontend/src/styles.scss b/frontend/src/styles.scss index b6514191e..f04396789 100644 --- a/frontend/src/styles.scss +++ b/frontend/src/styles.scss @@ -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"); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9262f5578..10ec02a8e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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