chore(ui): rebuilt app-menu to angular aria template-based component (#2044)
This commit is contained in:
@@ -41,18 +41,28 @@
|
||||
<h2>Split Buttons</h2>
|
||||
|
||||
<div class="sample-row">
|
||||
<app-split-button
|
||||
tone="primary"
|
||||
label="Open"
|
||||
[model]="menuItems"><svg lucideFolderOpen></svg></app-split-button>
|
||||
<app-split-button
|
||||
label="Download"
|
||||
[model]="menuItems"><svg lucideDownload></svg></app-split-button>
|
||||
<app-split-button
|
||||
tone="danger"
|
||||
variant="soft"
|
||||
label="Delete"
|
||||
[model]="menuItems"><svg lucideTrash2></svg></app-split-button>
|
||||
<app-split-button tone="primary" label="Open" (clicked)="logMenu('Open')">
|
||||
<svg lucideFolderOpen></svg>
|
||||
<app-menu ariaLabel="Open options">
|
||||
<app-menu-item [icon]="iconFolderOpen" (selected)="logMenu('Open in place')">Open</app-menu-item>
|
||||
<app-menu-item [icon]="iconCopy" (selected)="logMenu('Open a copy')">Open a copy</app-menu-item>
|
||||
</app-menu>
|
||||
</app-split-button>
|
||||
<app-split-button label="Download" (clicked)="logMenu('Download')">
|
||||
<svg lucideDownload></svg>
|
||||
<app-menu ariaLabel="Download options">
|
||||
<app-menu-item [icon]="iconDownload" shortcut="⌘S" (selected)="logMenu('Download EPUB')">Download EPUB</app-menu-item>
|
||||
<app-menu-item [icon]="iconDownload" (selected)="logMenu('Download PDF')">Download PDF</app-menu-item>
|
||||
</app-menu>
|
||||
</app-split-button>
|
||||
<app-split-button tone="danger" variant="soft" label="Delete" (clicked)="logMenu('Delete')">
|
||||
<svg lucideTrash2></svg>
|
||||
<app-menu ariaLabel="Delete options">
|
||||
<app-menu-item (selected)="logMenu('Delete this')">Delete this</app-menu-item>
|
||||
<app-menu-separator />
|
||||
<app-menu-item variant="destructive" [icon]="iconTrash" (selected)="logMenu('Delete all')">Delete all…</app-menu-item>
|
||||
</app-menu>
|
||||
</app-split-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -511,8 +521,61 @@
|
||||
<section class="showcase-section">
|
||||
<h2>Menus</h2>
|
||||
|
||||
<app-button label="Open menu" (clicked)="debugMenu.toggle($event)"><svg lucideEllipsisVertical></svg></app-button>
|
||||
<app-menu #debugMenu [model]="menuItems" />
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
[appMenuTriggerFor]="richMenu"
|
||||
class="inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-sm font-medium text-text hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">
|
||||
<svg lucideEllipsisVertical class="size-4" aria-hidden="true"></svg>
|
||||
Actions
|
||||
</button>
|
||||
<span
|
||||
class="flex h-24 w-64 items-center justify-center rounded-md border border-dashed border-border text-sm text-text-muted"
|
||||
[appContextMenuFor]="richMenu">
|
||||
Right-click anywhere here
|
||||
</span>
|
||||
<span class="text-sm text-text-muted">Last action: <span class="font-semibold text-text">{{ lastMenuEvent() }}</span></span>
|
||||
</div>
|
||||
|
||||
<app-menu #richMenu ariaLabel="Item actions">
|
||||
<ng-template appMenuContent>
|
||||
<app-menu-section>Actions</app-menu-section>
|
||||
<app-menu-item [icon]="iconPencil" shortcut="⌘E" (selected)="logMenu('Rename')">Rename</app-menu-item>
|
||||
<app-menu-item [icon]="iconCopy" shortcut="⌘D" (selected)="logMenu('Duplicate')">Duplicate</app-menu-item>
|
||||
<app-menu-item [icon]="iconShare" [submenu]="shareMenu">Share</app-menu-item>
|
||||
|
||||
<app-menu-separator />
|
||||
|
||||
<app-menu-section>View</app-menu-section>
|
||||
<app-menu-checkbox [(checked)]="menuPinned" (selected)="logMenu('Pinned ' + $event)">Pin to top</app-menu-checkbox>
|
||||
<app-menu-checkbox [(checked)]="menuWrap" (selected)="logMenu('Wrap ' + $event)">Wrap long titles</app-menu-checkbox>
|
||||
|
||||
<app-menu-separator />
|
||||
|
||||
<app-menu-section>Density</app-menu-section>
|
||||
<app-menu-radio-group [(value)]="menuDensity" (valueSelected)="logMenu('Density ' + $event)">
|
||||
<app-menu-radio [value]="'compact'">Compact</app-menu-radio>
|
||||
<app-menu-radio [value]="'comfortable'">Comfortable</app-menu-radio>
|
||||
<app-menu-radio [value]="'spacious'">Spacious</app-menu-radio>
|
||||
</app-menu-radio-group>
|
||||
|
||||
<app-menu-separator />
|
||||
|
||||
<div class="flex flex-col gap-0.5 px-2 py-1.5 text-sm">
|
||||
<span class="font-medium text-text-strong">Signed in as Ada</span>
|
||||
<span class="text-xs text-text-muted">ada@example.com</span>
|
||||
</div>
|
||||
|
||||
<app-menu-separator />
|
||||
|
||||
<app-menu-item variant="destructive" [icon]="iconTrash" (selected)="logMenu('Delete')">Delete…</app-menu-item>
|
||||
</ng-template>
|
||||
</app-menu>
|
||||
|
||||
<app-menu #shareMenu="ngMenu" ariaLabel="Share targets">
|
||||
<app-menu-item [icon]="iconShare" (selected)="logMenu('Share link')">Copy link</app-menu-item>
|
||||
<app-menu-item [icon]="iconDownload" (selected)="logMenu('Share email')">Send by email…</app-menu-item>
|
||||
</app-menu>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
|
||||
@@ -2,9 +2,9 @@ import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/cor
|
||||
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 {
|
||||
LucideChevronLeft,
|
||||
LucideCopy,
|
||||
LucideDownload,
|
||||
LucideEllipsisVertical,
|
||||
LucideFile,
|
||||
@@ -12,15 +12,18 @@ import {
|
||||
LucideFolderOpen,
|
||||
LucideHeart,
|
||||
LucideList,
|
||||
LucidePencil,
|
||||
LucideSave,
|
||||
LucideSearch,
|
||||
LucideSettings,
|
||||
LucideShare2,
|
||||
LucideSmartphone,
|
||||
LucideTag,
|
||||
LucideTrash2,
|
||||
LucideTriangleAlert,
|
||||
LucideX,
|
||||
LucideZap,
|
||||
type LucideIconData,
|
||||
} from '@lucide/angular';
|
||||
import { AppAccordionComponent } from '../../shared/ui/accordion/app-accordion.component';
|
||||
import {
|
||||
@@ -38,9 +41,16 @@ import { AppDateRangePickerComponent, type DatePickerRange } from '../../shared/
|
||||
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 { AppMenuContentDirective } from '../../shared/ui/menu/app-menu-content.directive';
|
||||
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 { AppMenuItemComponent } from '../../shared/ui/menu/app-menu-item.component';
|
||||
import { AppMenuCheckboxComponent } from '../../shared/ui/menu/app-menu-checkbox.component';
|
||||
import { AppMenuRadioGroupComponent } from '../../shared/ui/menu/app-menu-radio-group.component';
|
||||
import { AppMenuRadioComponent } from '../../shared/ui/menu/app-menu-radio.component';
|
||||
import { AppMenuSectionComponent } from '../../shared/ui/menu/app-menu-section.component';
|
||||
import { AppMenuSeparatorComponent } from '../../shared/ui/menu/app-menu-separator.component';
|
||||
import { AppContextMenuDirective, AppMenuTriggerDirective } from '../../shared/ui/menu/app-menu-trigger.directive';
|
||||
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';
|
||||
@@ -79,6 +89,15 @@ interface ButtonExample {
|
||||
AppFieldComponent,
|
||||
AppInputComponent,
|
||||
AppMenuComponent,
|
||||
AppMenuContentDirective,
|
||||
AppMenuItemComponent,
|
||||
AppMenuCheckboxComponent,
|
||||
AppMenuRadioGroupComponent,
|
||||
AppMenuRadioComponent,
|
||||
AppMenuSectionComponent,
|
||||
AppMenuSeparatorComponent,
|
||||
AppMenuTriggerDirective,
|
||||
AppContextMenuDirective,
|
||||
AppMessageComponent,
|
||||
AppNumberInputComponent,
|
||||
AppRadioGroupComponent,
|
||||
@@ -135,14 +154,22 @@ export class DesignSystemComponent {
|
||||
{ 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 iconCopy: LucideIconData = LucideCopy.icon;
|
||||
readonly iconPencil: LucideIconData = LucidePencil.icon;
|
||||
readonly iconDownload: LucideIconData = LucideDownload.icon;
|
||||
readonly iconTrash: LucideIconData = LucideTrash2.icon;
|
||||
readonly iconShare: LucideIconData = LucideShare2.icon;
|
||||
readonly iconFolderOpen: LucideIconData = LucideFolderOpen.icon;
|
||||
|
||||
readonly menuPinned = signal(true);
|
||||
readonly menuWrap = signal(false);
|
||||
readonly menuDensity = signal<string | null>('comfortable');
|
||||
readonly lastMenuEvent = signal('nothing yet');
|
||||
|
||||
logMenu(action: string): void {
|
||||
this.lastMenuEvent.set(action);
|
||||
}
|
||||
readonly selectOptions: SelectOption<string>[] = [
|
||||
{ label: 'Option A', value: 'a' },
|
||||
{ label: 'Option B', value: 'b' },
|
||||
|
||||
+18
-10
@@ -4,7 +4,7 @@ import {Router, RouterLink} from '@angular/router';
|
||||
import {TranslocoPipe} from '@jsverse/transloco';
|
||||
import {LucideArrowLeft, LucideEllipsisVertical} from '@lucide/angular';
|
||||
import {AppMenuComponent} from '../../ui/menu/app-menu.component';
|
||||
import {AppMenuItem} from '../../ui/menu/app-menu.items';
|
||||
import {AppMenuItemComponent} from '../../ui/menu/app-menu-item.component';
|
||||
import {AppButtonComponent} from '../../ui/button/app-button.component';
|
||||
import {PageHeaderBreadcrumb} from './page-header.service';
|
||||
|
||||
@@ -16,6 +16,7 @@ const COLLAPSE_AFTER_ITEMS = 4;
|
||||
imports: [
|
||||
AppButtonComponent,
|
||||
AppMenuComponent,
|
||||
AppMenuItemComponent,
|
||||
LucideArrowLeft,
|
||||
LucideEllipsisVertical,
|
||||
NgClass,
|
||||
@@ -58,6 +59,7 @@ const COLLAPSE_AFTER_ITEMS = 4;
|
||||
styleClass="h-7 w-7 pointer-coarse:h-7 pointer-coarse:w-7"
|
||||
[ariaLabel]="'layout.pageHeader.moreBreadcrumbs' | transloco"
|
||||
ariaHasPopup="menu"
|
||||
[ariaExpanded]="hiddenBreadcrumbMenu()?.isOpen() ? 'true' : 'false'"
|
||||
(clicked)="toggleHiddenBreadcrumbs($event)">
|
||||
<svg lucideEllipsisVertical></svg>
|
||||
</app-button>
|
||||
@@ -75,7 +77,13 @@ const COLLAPSE_AFTER_ITEMS = 4;
|
||||
</ol>
|
||||
</nav>
|
||||
@if (hiddenBreadcrumbs().length) {
|
||||
<app-menu #hiddenBreadcrumbMenu [model]="hiddenBreadcrumbMenuItems()" />
|
||||
<app-menu #hiddenBreadcrumbMenu [ariaLabel]="'layout.pageHeader.moreBreadcrumbs' | transloco">
|
||||
@for (breadcrumb of hiddenBreadcrumbs(); track breadcrumbKey(breadcrumb)) {
|
||||
<app-menu-item [disabled]="!breadcrumb.commands?.length" (selected)="navigate(breadcrumb)">
|
||||
{{ breadcrumb.label }}
|
||||
</app-menu-item>
|
||||
}
|
||||
</app-menu>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,13 +131,6 @@ export class AppPageHeaderBreadcrumbsComponent {
|
||||
readonly leadingBreadcrumb = computed(() => (this.shouldCollapse() ? this.trail()[0] : null));
|
||||
readonly hiddenBreadcrumbs = computed(() => (this.shouldCollapse() ? this.trail().slice(1, -2) : []));
|
||||
readonly trailingBreadcrumbs = computed(() => (this.shouldCollapse() ? this.trail().slice(-2) : this.trail()));
|
||||
readonly hiddenBreadcrumbMenuItems = computed<AppMenuItem[]>(() =>
|
||||
this.hiddenBreadcrumbs().map(breadcrumb => ({
|
||||
label: breadcrumb.label,
|
||||
disabled: !breadcrumb.commands?.length,
|
||||
command: () => this.navigate(breadcrumb),
|
||||
})),
|
||||
);
|
||||
|
||||
navigate(breadcrumb: PageHeaderBreadcrumb): void {
|
||||
if (breadcrumb.commands?.length) {
|
||||
@@ -142,7 +143,14 @@ export class AppPageHeaderBreadcrumbsComponent {
|
||||
}
|
||||
|
||||
toggleHiddenBreadcrumbs(event: MouseEvent): void {
|
||||
this.hiddenBreadcrumbMenu()?.toggle(event);
|
||||
const menu = this.hiddenBreadcrumbMenu();
|
||||
if (!menu) return;
|
||||
const origin = event.currentTarget as HTMLElement;
|
||||
if (menu.openerElement() === origin) {
|
||||
menu.close();
|
||||
} else {
|
||||
menu.open(origin);
|
||||
}
|
||||
}
|
||||
|
||||
breadcrumbKey(breadcrumb: PageHeaderBreadcrumb): string {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { cn } from '../cn';
|
||||
|
||||
export const checkIndicatorBaseClass =
|
||||
'flex size-3.5 shrink-0 items-center justify-center rounded border-[1.5px] pointer-coarse:size-4.5';
|
||||
export const checkIndicatorUncheckedClass = 'border-text-muted/50';
|
||||
export const checkIndicatorCheckedClass = 'border-transparent bg-primary text-primary-contrast';
|
||||
export const checkIndicatorIconClass = 'size-2.5 shrink-0 pointer-coarse:size-3';
|
||||
|
||||
export function checkIndicatorClass(checked: boolean): string {
|
||||
return cn(
|
||||
checkIndicatorBaseClass,
|
||||
checked ? checkIndicatorCheckedClass : checkIndicatorUncheckedClass,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
} from '@angular/core';
|
||||
import { LucideCheck, LucideMinus } from '@lucide/angular';
|
||||
|
||||
import { AppMenuComponent } from './app-menu.component';
|
||||
import { AppMenuAriaItemDirective } from './menu-aria-item.directive';
|
||||
import { setupMenuItem } from './menu-item-setup';
|
||||
import {
|
||||
checkIndicatorClass,
|
||||
checkIndicatorIconClass,
|
||||
} from '../checkbox/check-indicator.styles';
|
||||
import {
|
||||
appMenuItemRowClass,
|
||||
appMenuLabelClass,
|
||||
appMenuLeadingSlotClass,
|
||||
appMenuShortcutClass,
|
||||
} from './menu.styles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu-checkbox',
|
||||
standalone: true,
|
||||
imports: [LucideCheck, LucideMinus],
|
||||
hostDirectives: [{ directive: AppMenuAriaItemDirective, inputs: ['disabled'] }],
|
||||
host: {
|
||||
'[class]': 'rowClass',
|
||||
'[attr.role]': "'menuitemcheckbox'",
|
||||
'[attr.aria-checked]': "mixed() ? 'mixed' : checked()",
|
||||
'(click)': 'onEvent($event)',
|
||||
'(keydown)': 'onEvent($event)',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<span [class]="leadingSlotClass">
|
||||
<span [class]="boxClass()" aria-hidden="true">
|
||||
@if (mixed()) {
|
||||
<svg lucideMinus [class]="checkClass" aria-hidden="true"></svg>
|
||||
} @else if (checked()) {
|
||||
<svg lucideCheck [class]="checkClass" aria-hidden="true"></svg>
|
||||
}
|
||||
</span>
|
||||
</span>
|
||||
<span [class]="labelClass" data-menu-label><ng-content /></span>
|
||||
@if (shortcut()) {
|
||||
<span [class]="shortcutClass" aria-hidden="true">{{ shortcut() }}</span>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppMenuCheckboxComponent {
|
||||
readonly checked = model(false);
|
||||
readonly mixed = model(false);
|
||||
readonly shortcut = input('');
|
||||
readonly closeOnSelect = input(false, { transform: booleanAttribute });
|
||||
readonly searchLabel = input('');
|
||||
|
||||
readonly selected = output<boolean>();
|
||||
|
||||
private readonly menuItem = inject(AppMenuAriaItemDirective);
|
||||
private readonly owner = inject(AppMenuComponent);
|
||||
|
||||
protected readonly rowClass = appMenuItemRowClass('default');
|
||||
protected readonly leadingSlotClass = appMenuLeadingSlotClass;
|
||||
protected readonly checkClass = checkIndicatorIconClass;
|
||||
protected readonly labelClass = appMenuLabelClass;
|
||||
protected readonly shortcutClass = appMenuShortcutClass;
|
||||
protected readonly boxClass = computed(() => checkIndicatorClass(this.checked() || this.mixed()));
|
||||
|
||||
constructor() {
|
||||
setupMenuItem(this.searchLabel);
|
||||
}
|
||||
|
||||
protected onEvent(event: Event): void {
|
||||
if (event instanceof KeyboardEvent && (event.repeat || (event.key !== 'Enter' && event.key !== ' '))) return;
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
if (this.menuItem.disabled()) return;
|
||||
this.toggle();
|
||||
}
|
||||
|
||||
private toggle(): void {
|
||||
const next = this.mixed() || !this.checked();
|
||||
this.mixed.set(false);
|
||||
this.checked.set(next);
|
||||
this.selected.emit(next);
|
||||
if (this.closeOnSelect()) this.owner.closeChain();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Directive, inject, TemplateRef, ViewContainerRef } from '@angular/core';
|
||||
|
||||
@Directive({
|
||||
selector: 'ng-template[appMenuContent]',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppMenuContentDirective {
|
||||
private readonly template = inject(TemplateRef);
|
||||
private readonly viewContainer = inject(ViewContainerRef);
|
||||
private rendered = false;
|
||||
|
||||
render(): void {
|
||||
if (this.rendered) return;
|
||||
this.viewContainer.createEmbeddedView(this.template);
|
||||
this.rendered = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
DestroyRef,
|
||||
ElementRef,
|
||||
inject,
|
||||
input,
|
||||
output,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { LucideChevronRight, LucideDynamicIcon, LucideLoaderCircle, type LucideIconData } from '@lucide/angular';
|
||||
|
||||
import { AppMenuComponent } from './app-menu.component';
|
||||
import { AppMenuAriaItemDirective } from './menu-aria-item.directive';
|
||||
import { setupMenuItem } from './menu-item-setup';
|
||||
import {
|
||||
appMenuBadgeSlotClass,
|
||||
appMenuIconClass,
|
||||
appMenuItemRowClass,
|
||||
appMenuLabelClass,
|
||||
appMenuLeadingSlotClass,
|
||||
appMenuShortcutClass,
|
||||
appMenuSpinnerClass,
|
||||
appMenuSubmenuIconClass,
|
||||
appMenuTrailingIconClass,
|
||||
type AppMenuItemVariant,
|
||||
} from './menu.styles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu-item',
|
||||
standalone: true,
|
||||
imports: [NgTemplateOutlet, RouterLink, LucideDynamicIcon, LucideChevronRight, LucideLoaderCircle],
|
||||
hostDirectives: [{ directive: AppMenuAriaItemDirective, inputs: ['disabled', 'submenu'] }],
|
||||
host: {
|
||||
'[class]': 'rowClass()',
|
||||
'[attr.aria-disabled]': 'inert()',
|
||||
'(click)': 'onClick($event)',
|
||||
'(keydown)': 'onKeydown($event)',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
@if (link() !== null) {
|
||||
<a
|
||||
#anchor
|
||||
[routerLink]="link()"
|
||||
[queryParams]="queryParams()"
|
||||
tabindex="-1"
|
||||
class="flex min-h-full w-full items-center gap-2 no-underline text-inherit outline-none">
|
||||
<ng-container [ngTemplateOutlet]="body" />
|
||||
</a>
|
||||
} @else {
|
||||
<ng-container [ngTemplateOutlet]="body" />
|
||||
}
|
||||
|
||||
<ng-template #body>
|
||||
@if (loading()) {
|
||||
<span [class]="leadingSlotClass">
|
||||
<svg lucideLoaderCircle [class]="spinnerClass" aria-hidden="true"></svg>
|
||||
</span>
|
||||
} @else if (icon(); as iconData) {
|
||||
<span [class]="leadingSlotClass">
|
||||
<svg [lucideIcon]="iconData" [class]="iconClass" aria-hidden="true"></svg>
|
||||
</span>
|
||||
} @else if (badge()) {
|
||||
<span [class]="badgeSlotClass">{{ badge() }}</span>
|
||||
} @else if (inset()) {
|
||||
<span [class]="leadingSlotClass" aria-hidden="true"></span>
|
||||
}
|
||||
|
||||
<span [class]="labelClass" data-menu-label><ng-content /></span>
|
||||
|
||||
@if (trailingIcon(); as iconData) {
|
||||
<svg [lucideIcon]="iconData" [class]="trailingIconClass" aria-hidden="true"></svg>
|
||||
}
|
||||
@if (shortcut()) {
|
||||
<span [class]="shortcutClass" aria-hidden="true">{{ shortcut() }}</span>
|
||||
}
|
||||
@if (menuItem.hasPopup()) {
|
||||
<svg lucideChevronRight [class]="submenuIconClass" aria-hidden="true"></svg>
|
||||
}
|
||||
</ng-template>
|
||||
`,
|
||||
})
|
||||
export class AppMenuItemComponent {
|
||||
readonly icon = input<LucideIconData | undefined>(undefined);
|
||||
readonly trailingIcon = input<LucideIconData | undefined>(undefined);
|
||||
readonly badge = input('');
|
||||
readonly loading = input(false, { transform: booleanAttribute });
|
||||
readonly inset = input(false, { transform: booleanAttribute });
|
||||
readonly shortcut = input('');
|
||||
readonly variant = input<AppMenuItemVariant>('default');
|
||||
readonly closeOnSelect = input(true, { transform: booleanAttribute });
|
||||
readonly link = input<string | readonly unknown[] | null>(null);
|
||||
readonly queryParams = input<Record<string, unknown> | null>(null);
|
||||
readonly searchLabel = input('');
|
||||
|
||||
readonly selected = output<void>();
|
||||
|
||||
protected readonly menuItem = inject(AppMenuAriaItemDirective);
|
||||
private readonly owner = inject(AppMenuComponent);
|
||||
private readonly anchor = viewChild<ElementRef<HTMLAnchorElement>>('anchor');
|
||||
private suppressClick = false;
|
||||
|
||||
protected readonly leadingSlotClass = appMenuLeadingSlotClass;
|
||||
protected readonly badgeSlotClass = appMenuBadgeSlotClass;
|
||||
protected readonly iconClass = appMenuIconClass;
|
||||
protected readonly spinnerClass = `${appMenuSpinnerClass} animate-spin`;
|
||||
protected readonly labelClass = appMenuLabelClass;
|
||||
protected readonly trailingIconClass = appMenuTrailingIconClass;
|
||||
protected readonly shortcutClass = appMenuShortcutClass;
|
||||
protected readonly submenuIconClass = appMenuSubmenuIconClass;
|
||||
protected readonly rowClass = computed(() => appMenuItemRowClass(this.variant()));
|
||||
protected readonly inert = computed(() => this.loading() || this.menuItem.disabled());
|
||||
|
||||
constructor() {
|
||||
setupMenuItem(this.searchLabel);
|
||||
|
||||
const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
|
||||
const blockInertActivation = (event: Event) => {
|
||||
if (!this.inert()) return;
|
||||
const isActivation =
|
||||
event.type === 'click' ||
|
||||
(event instanceof KeyboardEvent && (event.key === 'Enter' || event.key === ' ' || event.key === 'ArrowRight'));
|
||||
if (isActivation) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
};
|
||||
host.addEventListener('keydown', blockInertActivation, true);
|
||||
host.addEventListener('click', blockInertActivation, true);
|
||||
|
||||
inject(DestroyRef).onDestroy(() => {
|
||||
host.removeEventListener('keydown', blockInertActivation, true);
|
||||
host.removeEventListener('click', blockInertActivation, true);
|
||||
const submenu = this.menuItem.submenu();
|
||||
if (submenu && submenu.parent() === this.menuItem) {
|
||||
submenu.parent.set(undefined);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected onClick(event: MouseEvent): void {
|
||||
if (this.menuItem.hasPopup()) return;
|
||||
event.stopPropagation();
|
||||
if (this.suppressClick) {
|
||||
this.suppressClick = false;
|
||||
return;
|
||||
}
|
||||
if (this.inert()) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
this.activate();
|
||||
}
|
||||
|
||||
protected onKeydown(event: KeyboardEvent): void {
|
||||
if (event.repeat || (event.key !== 'Enter' && event.key !== ' ')) return;
|
||||
if (this.menuItem.hasPopup()) return;
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
if (this.inert()) return;
|
||||
if (this.link() !== null) {
|
||||
this.suppressClick = true;
|
||||
this.anchor()?.nativeElement.click();
|
||||
}
|
||||
this.activate();
|
||||
}
|
||||
|
||||
private activate(): void {
|
||||
this.selected.emit();
|
||||
if (this.closeOnSelect()) this.owner.closeChain();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { ChangeDetectionStrategy, Component, input, model, output } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu-radio-group',
|
||||
standalone: true,
|
||||
host: { role: 'group', class: 'contents', '[attr.aria-label]': 'ariaLabel() || null' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `<ng-content />`,
|
||||
})
|
||||
export class AppMenuRadioGroupComponent<T> {
|
||||
readonly value = model<T | null>(null);
|
||||
readonly ariaLabel = input('');
|
||||
|
||||
readonly valueSelected = output<T>();
|
||||
|
||||
isSelected(candidate: T): boolean {
|
||||
return Object.is(this.value(), candidate);
|
||||
}
|
||||
|
||||
select(candidate: T): void {
|
||||
this.value.set(candidate);
|
||||
this.valueSelected.emit(candidate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
output,
|
||||
} from '@angular/core';
|
||||
import { LucideCheck } from '@lucide/angular';
|
||||
|
||||
import { AppMenuComponent } from './app-menu.component';
|
||||
import { AppMenuAriaItemDirective } from './menu-aria-item.directive';
|
||||
import { setupMenuItem } from './menu-item-setup';
|
||||
import { AppMenuRadioGroupComponent } from './app-menu-radio-group.component';
|
||||
import {
|
||||
appMenuCheckIconClass,
|
||||
appMenuItemRowClass,
|
||||
appMenuLabelClass,
|
||||
appMenuLeadingSlotClass,
|
||||
appMenuShortcutClass,
|
||||
} from './menu.styles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu-radio',
|
||||
standalone: true,
|
||||
imports: [LucideCheck],
|
||||
hostDirectives: [{ directive: AppMenuAriaItemDirective, inputs: ['disabled'] }],
|
||||
host: {
|
||||
'[class]': 'rowClass',
|
||||
'[attr.role]': "'menuitemradio'",
|
||||
'[attr.aria-checked]': 'checked()',
|
||||
'(click)': 'onEvent($event)',
|
||||
'(keydown)': 'onEvent($event)',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<span [class]="leadingSlotClass">
|
||||
@if (checked()) {
|
||||
<svg lucideCheck [class]="checkClass" aria-hidden="true"></svg>
|
||||
}
|
||||
</span>
|
||||
<span [class]="labelClass" data-menu-label><ng-content /></span>
|
||||
@if (shortcut()) {
|
||||
<span [class]="shortcutClass" aria-hidden="true">{{ shortcut() }}</span>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppMenuRadioComponent<T> {
|
||||
readonly value = input.required<T>();
|
||||
readonly shortcut = input('');
|
||||
readonly closeOnSelect = input(true, { transform: booleanAttribute });
|
||||
readonly searchLabel = input('');
|
||||
|
||||
readonly selected = output<T>();
|
||||
|
||||
private readonly group = inject<AppMenuRadioGroupComponent<T>>(AppMenuRadioGroupComponent);
|
||||
private readonly menuItem = inject(AppMenuAriaItemDirective);
|
||||
private readonly owner = inject(AppMenuComponent);
|
||||
|
||||
protected readonly checked = computed(() => this.group.isSelected(this.value()));
|
||||
protected readonly rowClass = appMenuItemRowClass('default');
|
||||
protected readonly leadingSlotClass = appMenuLeadingSlotClass;
|
||||
protected readonly checkClass = appMenuCheckIconClass;
|
||||
protected readonly labelClass = appMenuLabelClass;
|
||||
protected readonly shortcutClass = appMenuShortcutClass;
|
||||
|
||||
constructor() {
|
||||
setupMenuItem(this.searchLabel);
|
||||
}
|
||||
|
||||
protected onEvent(event: Event): void {
|
||||
if (event instanceof KeyboardEvent && (event.repeat || (event.key !== 'Enter' && event.key !== ' '))) return;
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
if (this.menuItem.disabled()) return;
|
||||
this.choose();
|
||||
}
|
||||
|
||||
private choose(): void {
|
||||
this.group.select(this.value());
|
||||
this.selected.emit(this.value());
|
||||
if (this.closeOnSelect()) this.owner.closeChain();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ChangeDetectionStrategy, Component } from '@angular/core';
|
||||
|
||||
import { appMenuSectionClass } from './menu.styles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu-section',
|
||||
standalone: true,
|
||||
host: { role: 'presentation', '[class]': 'sectionClass' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `<ng-content />`,
|
||||
})
|
||||
export class AppMenuSectionComponent {
|
||||
protected readonly sectionClass = appMenuSectionClass;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ChangeDetectionStrategy, Component } from '@angular/core';
|
||||
|
||||
import { appMenuSeparatorClass } from './menu.styles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu-separator',
|
||||
standalone: true,
|
||||
host: { role: 'separator', '[class]': 'separatorClass' },
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: '',
|
||||
})
|
||||
export class AppMenuSeparatorComponent {
|
||||
protected readonly separatorClass = appMenuSeparatorClass;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { computed, Directive, ElementRef, inject, input } from '@angular/core';
|
||||
|
||||
import { AppMenuComponent } from './app-menu.component';
|
||||
|
||||
@Directive({
|
||||
selector: '[appMenuTriggerFor]',
|
||||
standalone: true,
|
||||
host: {
|
||||
'[attr.aria-haspopup]': "'menu'",
|
||||
'[attr.aria-expanded]': 'expanded()',
|
||||
'[attr.aria-controls]': 'controls()',
|
||||
'(click)': 'toggle($event)',
|
||||
'(keydown)': 'onKeydown($event)',
|
||||
},
|
||||
})
|
||||
export class AppMenuTriggerDirective {
|
||||
readonly menu = input.required<AppMenuComponent>({ alias: 'appMenuTriggerFor' });
|
||||
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
|
||||
protected readonly expanded = computed(() =>
|
||||
this.menu().openerElement() === this.host.nativeElement ? 'true' : 'false',
|
||||
);
|
||||
protected readonly controls = computed(() =>
|
||||
this.expanded() === 'true' ? this.menu().menu.id() : null,
|
||||
);
|
||||
|
||||
protected toggle(event: Event): void {
|
||||
event.stopPropagation();
|
||||
const menu = this.menu();
|
||||
if (menu.openerElement() === this.host.nativeElement) {
|
||||
menu.close();
|
||||
} else {
|
||||
menu.open(this.host.nativeElement);
|
||||
}
|
||||
}
|
||||
|
||||
protected onKeydown(event: KeyboardEvent): void {
|
||||
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp' && event.key !== 'Enter' && event.key !== ' ') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.menu().open(this.host.nativeElement, event.key === 'ArrowUp' ? 'last' : 'first');
|
||||
}
|
||||
}
|
||||
|
||||
@Directive({
|
||||
selector: '[appContextMenuFor]',
|
||||
standalone: true,
|
||||
host: { '(contextmenu)': 'onContextMenu($event)' },
|
||||
})
|
||||
export class AppContextMenuDirective {
|
||||
readonly menu = input.required<AppMenuComponent>({ alias: 'appContextMenuFor' });
|
||||
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
|
||||
protected onContextMenu(event: MouseEvent): void {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
let x = event.clientX;
|
||||
let y = event.clientY;
|
||||
const fromPointer = !(x === 0 && y === 0);
|
||||
if (!fromPointer) {
|
||||
const target = event.target instanceof Element ? event.target : this.host.nativeElement;
|
||||
const rect = target.getBoundingClientRect();
|
||||
x = rect.left + rect.width / 2;
|
||||
y = rect.top + rect.height / 2;
|
||||
}
|
||||
this.menu().openAt(x, y, this.host.nativeElement, fromPointer);
|
||||
}
|
||||
}
|
||||
@@ -1,105 +1,528 @@
|
||||
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';
|
||||
import {
|
||||
afterNextRender,
|
||||
afterRenderEffect,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
contentChild,
|
||||
contentChildren,
|
||||
DestroyRef,
|
||||
effect,
|
||||
ElementRef,
|
||||
inject,
|
||||
Injector,
|
||||
input,
|
||||
output,
|
||||
signal,
|
||||
untracked,
|
||||
} from '@angular/core';
|
||||
import {
|
||||
type ConnectedPosition,
|
||||
type FlexibleConnectedPositionStrategy,
|
||||
type FlexibleConnectedPositionStrategyOrigin,
|
||||
Overlay,
|
||||
type OverlayRef,
|
||||
} from '@angular/cdk/overlay';
|
||||
import { DomPortal } from '@angular/cdk/portal';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { NavigationStart, Router } from '@angular/router';
|
||||
import { Menu, MenuItem } from '@angular/aria/menu';
|
||||
import { LucideChevronLeft } from '@lucide/angular';
|
||||
import { filter, type Subscription } from 'rxjs';
|
||||
|
||||
const isAppMenuSectionItem = (item: MenuItem): item is AppMenuSectionItem =>
|
||||
'appMenuSection' in item && item['appMenuSection'] === true;
|
||||
import { cn } from '../cn';
|
||||
import {
|
||||
connectedOverlayPanelClass,
|
||||
connectedOverlayPositions,
|
||||
connectedOverlayScrollStrategy,
|
||||
} from '../connected-overlay';
|
||||
import { scrollLockStrategy } from '../scroll-lock';
|
||||
import { LayoutService } from '../../layout/layout.service';
|
||||
import {
|
||||
appMenuBackHeaderClass,
|
||||
appMenuBackLabelClass,
|
||||
appMenuBackRowClass,
|
||||
appMenuIconClass,
|
||||
appMenuPanelClass,
|
||||
appMenuScrollRegionClass,
|
||||
appMenuSeparatorClass,
|
||||
appMenuSheetPanelClass,
|
||||
appMenuSheetPaneClass,
|
||||
} from './menu.styles';
|
||||
import { AppMenuAriaItemDirective } from './menu-aria-item.directive';
|
||||
import { AppMenuContentDirective } from './app-menu-content.directive';
|
||||
|
||||
const isSectionLabel = (item: MenuItem): boolean =>
|
||||
isAppMenuSectionItem(item) || hasMenuStyleClass(item.styleClass, APP_MENU_SECTION_CLASS);
|
||||
const menuByElement = new WeakMap<Element, AppMenuComponent>();
|
||||
|
||||
const withStyleClass = (existing: string | undefined, styleClass: string): string => {
|
||||
if (!existing) return styleClass;
|
||||
return hasMenuStyleClass(existing, styleClass) ? existing : `${existing} ${styleClass}`;
|
||||
};
|
||||
type MenuPresentation = 'popup' | 'sheet' | 'push';
|
||||
|
||||
const withoutIconFields = (item: MenuItem): MenuItem => {
|
||||
const { icon, iconClass, iconStyle, ...rest } = item;
|
||||
void icon;
|
||||
void iconClass;
|
||||
void iconStyle;
|
||||
return rest;
|
||||
};
|
||||
const SUBMENU_GAP = 4;
|
||||
|
||||
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));
|
||||
const submenuOverlayPositions: ConnectedPosition[] = [
|
||||
{ originX: 'end', originY: 'top', overlayX: 'start', overlayY: 'top', offsetX: SUBMENU_GAP },
|
||||
{ originX: 'start', originY: 'top', overlayX: 'end', overlayY: 'top', offsetX: -SUBMENU_GAP },
|
||||
{ originX: 'end', originY: 'bottom', overlayX: 'start', overlayY: 'bottom', offsetX: SUBMENU_GAP },
|
||||
{ originX: 'start', originY: 'bottom', overlayX: 'end', overlayY: 'bottom', offsetX: -SUBMENU_GAP },
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu',
|
||||
standalone: true,
|
||||
imports: [TieredMenu, ContextMenu],
|
||||
imports: [LucideChevronLeft],
|
||||
hostDirectives: [{ directive: Menu, inputs: ['wrap', 'typeaheadDelay', 'expansionDelay'] }],
|
||||
host: {
|
||||
'[class]': 'panelClass()',
|
||||
'[class.hidden]': 'concealed()',
|
||||
'[attr.aria-label]': 'ariaLabel()',
|
||||
'(keydown.escape)': 'onEscape($event)',
|
||||
'(focusout)': 'onFocusOut($event)',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: {class: 'contents [&>p-contextmenu]:contents [&>p-tieredmenu]:contents'},
|
||||
template: `
|
||||
@if (contextTarget(); as target) {
|
||||
<p-contextMenu
|
||||
[unstyled]="true"
|
||||
[target]="target"
|
||||
[model]="primeModel()"
|
||||
[appendTo]="appendTo()"
|
||||
[styleClass]="panelClass"
|
||||
[pt]="pt"
|
||||
[ptOptions]="ptOptions" />
|
||||
} @else {
|
||||
<p-tieredMenu
|
||||
#menu
|
||||
[unstyled]="true"
|
||||
[popup]="true"
|
||||
[model]="primeModel()"
|
||||
[appendTo]="appendTo()"
|
||||
[styleClass]="panelClass"
|
||||
[pt]="pt"
|
||||
[ptOptions]="ptOptions" />
|
||||
@if (presentation() === 'push') {
|
||||
<div [class]="backHeaderClass">
|
||||
<button type="button" [class]="backRowClass" (click)="popPush($event)" (keydown)="onBackKeydown($event)">
|
||||
<svg lucideChevronLeft [class]="backIconClass" aria-hidden="true"></svg>
|
||||
<span [class]="backLabelClass">{{ parentLabel() }}</span>
|
||||
</button>
|
||||
<div role="separator" [class]="backSeparatorClass"></div>
|
||||
</div>
|
||||
}
|
||||
<div [class]="scrollRegionClass"><ng-content /></div>
|
||||
`,
|
||||
})
|
||||
export class AppMenuComponent {
|
||||
readonly model = input<readonly MenuItem[]>([]);
|
||||
readonly contextTarget = input<HTMLElement | string | undefined>(undefined);
|
||||
readonly appendTo = input<'body' | 'self' | HTMLElement>('body');
|
||||
readonly showItemIcons = input(false, { transform: booleanAttribute });
|
||||
readonly ariaLabel = input.required<string>();
|
||||
readonly menuClass = input('');
|
||||
|
||||
private readonly menu = viewChild(TieredMenu);
|
||||
readonly opened = output<void>();
|
||||
readonly closed = output<void>();
|
||||
|
||||
protected readonly pt = menuPassThrough;
|
||||
protected readonly ptOptions = { mergeProps: ptViewMerge };
|
||||
protected readonly panelClass = menuPanelClass;
|
||||
protected readonly primeModel = computed(() => normalizeItems(this.model(), this.showItemIcons()));
|
||||
readonly menu = inject(Menu);
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly overlay = inject(Overlay);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly layout = inject(LayoutService);
|
||||
private readonly lazyContent = contentChild(AppMenuContentDirective);
|
||||
private readonly items = contentChildren(AppMenuAriaItemDirective, { descendants: true });
|
||||
|
||||
toggle(event: Event): void {
|
||||
this.menu()?.toggle(event);
|
||||
readonly opensUpward = signal(false);
|
||||
readonly hasItems = computed(() => this.lazyContent() !== undefined || this.ownItems().length > 0);
|
||||
|
||||
private readonly openState = signal(false);
|
||||
private readonly opener = signal<HTMLElement | null>(null);
|
||||
private readonly pushedChild = signal<AppMenuComponent | null>(null);
|
||||
private anchor: FlexibleConnectedPositionStrategyOrigin | null = null;
|
||||
private contextZone: HTMLElement | null = null;
|
||||
private focusReturn: HTMLElement | null = null;
|
||||
private pendingFocus: 'first' | 'last' = 'first';
|
||||
private pendingContextGestureRelease = false;
|
||||
private closingHadFocus = false;
|
||||
|
||||
private overlayRef: OverlayRef | null = null;
|
||||
private overlayIsSheet = false;
|
||||
private attachedAsPush = false;
|
||||
private pushOwner: AppMenuComponent | null = null;
|
||||
private pushReturnParent: Node | null = null;
|
||||
private pushReturnNext: Node | null = null;
|
||||
private portal: DomPortal | null = null;
|
||||
private outsideSub: Subscription | null = null;
|
||||
private positionSub: Subscription | null = null;
|
||||
|
||||
private readonly isSubmenu = computed(() => this.menu.parent() instanceof MenuItem);
|
||||
protected readonly rendered = computed(() =>
|
||||
this.isSubmenu()
|
||||
? this.menu.visible() && (this.parentPanel()?.isOpen() ?? false)
|
||||
: this.openState(),
|
||||
);
|
||||
|
||||
private readonly isMobileShell = computed(() => !this.layout.isDesktop());
|
||||
protected readonly presentation = computed<MenuPresentation>(() => {
|
||||
if (!this.isMobileShell()) return 'popup';
|
||||
return this.isSubmenu() ? 'push' : 'sheet';
|
||||
});
|
||||
|
||||
protected readonly concealed = computed(() => !this.rendered() || this.pushedChild() !== null);
|
||||
|
||||
protected readonly panelClass = computed(() =>
|
||||
cn(appMenuPanelClass, this.menuClass(), this.presentation() !== 'popup' && appMenuSheetPanelClass),
|
||||
);
|
||||
|
||||
protected readonly parentLabel = computed(() => {
|
||||
const parent = this.menu.parent();
|
||||
return parent instanceof MenuItem ? parent.searchTerm() : '';
|
||||
});
|
||||
|
||||
protected readonly backHeaderClass = appMenuBackHeaderClass;
|
||||
protected readonly backRowClass = appMenuBackRowClass;
|
||||
protected readonly backIconClass = appMenuIconClass;
|
||||
protected readonly backLabelClass = appMenuBackLabelClass;
|
||||
protected readonly backSeparatorClass = appMenuSeparatorClass;
|
||||
protected readonly scrollRegionClass = appMenuScrollRegionClass;
|
||||
|
||||
constructor() {
|
||||
menuByElement.set(this.host.nativeElement, this);
|
||||
|
||||
inject(Router).events.pipe(
|
||||
filter((event): event is NavigationStart => event instanceof NavigationStart),
|
||||
takeUntilDestroyed(),
|
||||
).subscribe(() => {
|
||||
if (!this.isSubmenu() && this.openState()) this.close();
|
||||
});
|
||||
|
||||
this.installHostGuards();
|
||||
|
||||
let wasOpen = false;
|
||||
effect(() => {
|
||||
const open = this.rendered();
|
||||
if (open === wasOpen) return;
|
||||
wasOpen = open;
|
||||
untracked(() => (open ? this.attachOverlay() : this.detachOverlay()));
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const wantsSheet = this.presentation() === 'sheet';
|
||||
if (this.openState() && this.overlayRef?.hasAttached() && wantsSheet !== this.overlayIsSheet) {
|
||||
untracked(() => this.close());
|
||||
}
|
||||
});
|
||||
|
||||
afterRenderEffect({
|
||||
mixedReadWrite: () => {
|
||||
this.items();
|
||||
if (this.rendered() && this.overlayRef?.hasAttached()) {
|
||||
this.overlayRef.updatePosition();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.outsideSub?.unsubscribe();
|
||||
this.positionSub?.unsubscribe();
|
||||
this.pushOwner?.pushedChild.set(null);
|
||||
this.overlayRef?.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
open(origin: HTMLElement, focus: 'first' | 'last' = 'first'): void {
|
||||
this.pendingFocus = focus;
|
||||
this.focusReturn = null;
|
||||
this.opener.set(origin);
|
||||
this.anchor = origin;
|
||||
this.contextZone = null;
|
||||
this.show();
|
||||
}
|
||||
|
||||
openAt(x: number, y: number, contextZone?: HTMLElement, fromPointer = true): void {
|
||||
this.pendingFocus = 'first';
|
||||
if (!this.openState()) {
|
||||
this.focusReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
}
|
||||
this.opener.set(null);
|
||||
this.anchor = { x, y };
|
||||
this.contextZone = contextZone ?? null;
|
||||
this.pendingContextGestureRelease = fromPointer;
|
||||
this.show();
|
||||
}
|
||||
|
||||
private show(): void {
|
||||
this.collapseChildren();
|
||||
this.openState.set(true);
|
||||
this.moveToAnchor();
|
||||
}
|
||||
|
||||
private moveToAnchor(): void {
|
||||
const ref = this.overlayRef;
|
||||
if (!ref?.hasAttached() || !this.anchor || this.isSubmenu()) return;
|
||||
if (this.overlayIsSheet) return;
|
||||
(ref.getConfig().positionStrategy as FlexibleConnectedPositionStrategy).setOrigin(this.anchor);
|
||||
ref.updatePosition();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.isSubmenu()) {
|
||||
this.menu.parent()?.close?.();
|
||||
return;
|
||||
}
|
||||
this.closingHadFocus = this.chainHasFocus();
|
||||
this.collapseChildren();
|
||||
this.openState.set(false);
|
||||
if (!this.overlayRef?.hasAttached()) this.clearLogicalState();
|
||||
}
|
||||
|
||||
isOpen(): boolean {
|
||||
return this.rendered();
|
||||
}
|
||||
|
||||
openerElement(): HTMLElement | null {
|
||||
return this.opener();
|
||||
}
|
||||
|
||||
protected onEscape(event: Event): void {
|
||||
if (!this.isSubmenu() && this.openState()) {
|
||||
event.stopPropagation();
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected onFocusOut(event: FocusEvent): void {
|
||||
const next = event.relatedTarget;
|
||||
if (!(next instanceof Element) || !this.rendered()) return;
|
||||
if (this.host.nativeElement.contains(next)) return;
|
||||
if (this.opener()?.contains(next)) return;
|
||||
const menuEl = next.closest('app-menu');
|
||||
if (menuEl) {
|
||||
const other = menuByElement.get(menuEl);
|
||||
if (other && (this.containsMenu(other) || other.containsMenu(this))) return;
|
||||
}
|
||||
this.closeChain();
|
||||
}
|
||||
|
||||
closeChain(): void {
|
||||
const parent = this.parentPanel();
|
||||
if (parent) {
|
||||
parent.closeChain();
|
||||
} else {
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected popPush(event: Event): void {
|
||||
event.stopPropagation();
|
||||
this.close();
|
||||
}
|
||||
|
||||
protected onBackKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
|
||||
}
|
||||
|
||||
private parentPanel(): AppMenuComponent | undefined {
|
||||
const parentItem: unknown = this.menu.parent();
|
||||
return parentItem instanceof AppMenuAriaItemDirective ? parentItem.owner : undefined;
|
||||
}
|
||||
|
||||
private rootPanel(): AppMenuComponent {
|
||||
const parent = this.parentPanel();
|
||||
return parent ? parent.rootPanel() : this;
|
||||
}
|
||||
|
||||
private sheetPane(): HTMLElement | null {
|
||||
return this.overlayIsSheet && this.overlayRef?.hasAttached() ? this.overlayRef.overlayElement : null;
|
||||
}
|
||||
|
||||
private ownItems(): readonly AppMenuAriaItemDirective[] {
|
||||
return this.items().filter((item) => item.parent === this.menu);
|
||||
}
|
||||
|
||||
private collapseChildren(): void {
|
||||
for (const item of this.ownItems()) {
|
||||
if (item.expanded()) item.close();
|
||||
}
|
||||
}
|
||||
|
||||
private attachOverlay(): void {
|
||||
this.lazyContent()?.render();
|
||||
const origin = this.isSubmenu() ? (this.menu.parent() as MenuItem<unknown>).element : this.anchor;
|
||||
if (!origin) return;
|
||||
|
||||
if (this.presentation() === 'push') {
|
||||
this.attachToSheetPane();
|
||||
return;
|
||||
}
|
||||
|
||||
const sheet = this.presentation() === 'sheet';
|
||||
if (this.overlayRef && this.overlayIsSheet !== sheet) {
|
||||
this.positionSub?.unsubscribe();
|
||||
this.positionSub = null;
|
||||
this.overlayRef.dispose();
|
||||
this.overlayRef = null;
|
||||
}
|
||||
this.overlayIsSheet = sheet;
|
||||
this.overlayRef ??= sheet ? this.createSheetOverlay() : this.createPopupOverlay(origin);
|
||||
|
||||
if (sheet) {
|
||||
this.opensUpward.set(true);
|
||||
} else {
|
||||
const strategy = this.overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy;
|
||||
strategy.setOrigin(origin);
|
||||
this.positionSub ??= strategy.positionChanges.subscribe(change => {
|
||||
this.opensUpward.set(change.connectionPair.overlayY === 'bottom');
|
||||
});
|
||||
}
|
||||
|
||||
this.portal ??= new DomPortal(this.host);
|
||||
if (!this.overlayRef.hasAttached()) this.overlayRef.attach(this.portal);
|
||||
this.overlayRef.updatePosition();
|
||||
|
||||
if (!this.isSubmenu()) {
|
||||
this.outsideSub = sheet
|
||||
? this.overlayRef.backdropClick().subscribe((event) => this.onOutsidePointer(event))
|
||||
: this.overlayRef.outsidePointerEvents().subscribe((event) => this.onOutsidePointer(event));
|
||||
afterNextRender(() => this.focusActiveItem(), { injector: this.injector });
|
||||
}
|
||||
this.opened.emit();
|
||||
}
|
||||
|
||||
private attachToSheetPane(): void {
|
||||
const pane = this.rootPanel().sheetPane();
|
||||
if (!pane) return;
|
||||
const el = this.host.nativeElement;
|
||||
this.pushReturnParent = el.parentNode;
|
||||
this.pushReturnNext = el.nextSibling;
|
||||
pane.appendChild(el);
|
||||
this.pushOwner = this.parentPanel() ?? null;
|
||||
this.pushOwner?.pushedChild.set(this);
|
||||
this.attachedAsPush = true;
|
||||
this.opensUpward.set(true);
|
||||
afterNextRender(() => this.focusActiveItem(), { injector: this.injector });
|
||||
this.opened.emit();
|
||||
}
|
||||
|
||||
private restorePushHost(): void {
|
||||
const parent = this.pushReturnParent;
|
||||
const next = this.pushReturnNext;
|
||||
this.pushReturnParent = null;
|
||||
this.pushReturnNext = null;
|
||||
if (!parent) return;
|
||||
if (next && next.parentNode === parent) {
|
||||
parent.insertBefore(this.host.nativeElement, next);
|
||||
} else {
|
||||
parent.appendChild(this.host.nativeElement);
|
||||
}
|
||||
}
|
||||
|
||||
private createSheetOverlay(): OverlayRef {
|
||||
return this.overlay.create({
|
||||
scrollStrategy: scrollLockStrategy(),
|
||||
hasBackdrop: true,
|
||||
backdropClass: 'app-menu-sheet-backdrop',
|
||||
width: '100%',
|
||||
panelClass: appMenuSheetPaneClass.split(' '),
|
||||
positionStrategy: this.overlay.position().global().bottom('0'),
|
||||
});
|
||||
}
|
||||
|
||||
private createPopupOverlay(origin: FlexibleConnectedPositionStrategyOrigin): OverlayRef {
|
||||
return this.overlay.create({
|
||||
scrollStrategy: connectedOverlayScrollStrategy(this.overlay),
|
||||
panelClass: connectedOverlayPanelClass.split(' '),
|
||||
usePopover: this.isSubmenu(),
|
||||
positionStrategy: this.overlay
|
||||
.position()
|
||||
.flexibleConnectedTo(origin)
|
||||
.withFlexibleDimensions(false)
|
||||
.withPopoverLocation(this.isSubmenu() ? 'inline' : 'global')
|
||||
.withPositions(this.isSubmenu() ? submenuOverlayPositions : connectedOverlayPositions),
|
||||
});
|
||||
}
|
||||
|
||||
private clearLogicalState(): void {
|
||||
this.opener.set(null);
|
||||
this.contextZone = null;
|
||||
this.pendingContextGestureRelease = false;
|
||||
this.focusReturn = null;
|
||||
}
|
||||
|
||||
private chainHasFocus(): boolean {
|
||||
const active = document.activeElement;
|
||||
if (!(active instanceof Element)) return false;
|
||||
if (this.host.nativeElement.contains(active)) return true;
|
||||
const menuEl = active.closest('app-menu');
|
||||
const other = menuEl ? menuByElement.get(menuEl) : undefined;
|
||||
return !!other && this.containsMenu(other);
|
||||
}
|
||||
|
||||
private detachOverlay(): void {
|
||||
this.outsideSub?.unsubscribe();
|
||||
this.outsideSub = null;
|
||||
|
||||
const hadFocus = this.chainHasFocus();
|
||||
this.overlayRef?.detach();
|
||||
|
||||
if (this.attachedAsPush) {
|
||||
this.attachedAsPush = false;
|
||||
this.restorePushHost();
|
||||
this.pushOwner?.pushedChild.set(null);
|
||||
this.pushOwner = null;
|
||||
const parent = this.menu.parent();
|
||||
if (hadFocus && parent instanceof MenuItem) {
|
||||
const parentEl = parent.element;
|
||||
afterNextRender(() => {
|
||||
if (parentEl.getBoundingClientRect().height > 0) parentEl.focus();
|
||||
}, { injector: this.injector });
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.isSubmenu()) {
|
||||
const opener = this.opener();
|
||||
const focusReturn = this.focusReturn;
|
||||
const restoreFocus = this.closingHadFocus;
|
||||
this.clearLogicalState();
|
||||
if (restoreFocus && opener) {
|
||||
(opener.querySelector<HTMLElement>('button') ?? opener).focus();
|
||||
} else if (restoreFocus) {
|
||||
focusReturn?.focus();
|
||||
}
|
||||
}
|
||||
this.closed.emit();
|
||||
}
|
||||
|
||||
private onOutsidePointer(event: MouseEvent): void {
|
||||
const target = event.target;
|
||||
if (!(target instanceof Element)) return;
|
||||
if (this.opener()?.contains(target)) return;
|
||||
const isContextGestureEvent =
|
||||
event.type === 'auxclick' ||
|
||||
event.type === 'contextmenu' ||
|
||||
(event.type === 'click' && event.ctrlKey);
|
||||
if (isContextGestureEvent && this.pendingContextGestureRelease) {
|
||||
this.pendingContextGestureRelease = false;
|
||||
return;
|
||||
}
|
||||
if (isContextGestureEvent && this.contextZone?.contains(target)) {
|
||||
return;
|
||||
}
|
||||
const menuEl = target.closest('app-menu');
|
||||
if (menuEl) {
|
||||
const inChain = menuByElement.get(menuEl);
|
||||
if (inChain && this.containsMenu(inChain)) return;
|
||||
}
|
||||
this.close();
|
||||
}
|
||||
|
||||
private containsMenu(other: AppMenuComponent): boolean {
|
||||
let current: AppMenuComponent | undefined = other;
|
||||
while (current) {
|
||||
if (current === this) return true;
|
||||
current = current.parentPanel();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private focusActiveItem(): void {
|
||||
const active = this.host.nativeElement.querySelector<HTMLElement>('[tabindex="0"]');
|
||||
(active ?? this.host.nativeElement).focus({ preventScroll: true });
|
||||
const key = this.pendingFocus === 'last' ? 'End' : 'Home';
|
||||
this.host.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true }));
|
||||
this.pendingFocus = 'first';
|
||||
}
|
||||
|
||||
private installHostGuards(): void {
|
||||
const el = this.host.nativeElement;
|
||||
const keydownGuard = (event: KeyboardEvent) => {
|
||||
if ((event.key === 'Enter' || event.key === ' ') && event.target === el) event.stopPropagation();
|
||||
};
|
||||
const hoverGuard = (event: Event) => {
|
||||
if (this.isMobileShell()) event.stopPropagation();
|
||||
};
|
||||
el.addEventListener('keydown', keydownGuard, true);
|
||||
el.addEventListener('mouseover', hoverGuard, true);
|
||||
el.addEventListener('mouseout', hoverGuard, true);
|
||||
this.destroyRef.onDestroy(() => {
|
||||
el.removeEventListener('keydown', keydownGuard, true);
|
||||
el.removeEventListener('mouseover', hoverGuard, true);
|
||||
el.removeEventListener('mouseout', hoverGuard, true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { type MenuItem } from 'primeng/api';
|
||||
|
||||
export type AppMenuItem = MenuItem;
|
||||
|
||||
export interface AppMenuSectionItem extends MenuItem {
|
||||
appMenuSection: true;
|
||||
}
|
||||
|
||||
export const appMenuSection = (label: string): AppMenuSectionItem => ({
|
||||
label,
|
||||
appMenuSection: true,
|
||||
});
|
||||
|
||||
export const appMenuSeparator = (): MenuItem => ({
|
||||
separator: true,
|
||||
});
|
||||
@@ -0,0 +1,464 @@
|
||||
import { Component, signal, viewChild } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { LayoutService } from '../../layout/layout.service';
|
||||
import { AppMenuComponent } from './app-menu.component';
|
||||
import { AppMenuContentDirective } from './app-menu-content.directive';
|
||||
import { AppMenuItemComponent } from './app-menu-item.component';
|
||||
import { AppMenuCheckboxComponent } from './app-menu-checkbox.component';
|
||||
import { AppMenuRadioComponent } from './app-menu-radio.component';
|
||||
import { AppMenuRadioGroupComponent } from './app-menu-radio-group.component';
|
||||
import { AppContextMenuDirective, AppMenuTriggerDirective } from './app-menu-trigger.directive';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
imports: [
|
||||
AppMenuComponent,
|
||||
AppMenuItemComponent,
|
||||
AppMenuCheckboxComponent,
|
||||
AppMenuRadioGroupComponent,
|
||||
AppMenuRadioComponent,
|
||||
AppMenuContentDirective,
|
||||
AppMenuTriggerDirective,
|
||||
AppContextMenuDirective,
|
||||
],
|
||||
template: `
|
||||
<button #trigger [appMenuTriggerFor]="menu">Open</button>
|
||||
<button class="second" (click)="openSecondFrom($event)">Second opener</button>
|
||||
<div class="zone" [appContextMenuFor]="menu">right-click</div>
|
||||
|
||||
<app-menu #menu ariaLabel="Actions">
|
||||
<app-menu-item (selected)="onDownload()">Download</app-menu-item>
|
||||
<app-menu-item [disabled]="true" (selected)="onDisabled()">Disabled</app-menu-item>
|
||||
<app-menu-checkbox [(checked)]="fav" [(mixed)]="favMixed" (selected)="onFav($event)">Favourite</app-menu-checkbox>
|
||||
<app-menu-radio-group [(value)]="status">
|
||||
<app-menu-radio [value]="'read'">Read</app-menu-radio>
|
||||
<app-menu-radio [value]="'reading'">Reading</app-menu-radio>
|
||||
</app-menu-radio-group>
|
||||
<app-menu-item [submenu]="sub" (selected)="onSend()">Send</app-menu-item>
|
||||
<app-menu-item [loading]="busy()" (selected)="onBusy()">Working</app-menu-item>
|
||||
<app-menu-item [closeOnSelect]="false" (selected)="onKeepOpen()">{{ keepOpenLabel() }}</app-menu-item>
|
||||
<app-menu-item [link]="'/books'" (selected)="onLink()">Go to books</app-menu-item>
|
||||
</app-menu>
|
||||
|
||||
<app-menu #sub="ngMenu" ariaLabel="Send options">
|
||||
<ng-template appMenuContent>
|
||||
<app-menu-item (selected)="onQuick()">Quick send</app-menu-item>
|
||||
</ng-template>
|
||||
</app-menu>
|
||||
|
||||
<button class="lazy-trigger" [appMenuTriggerFor]="lazyMenu">Open lazy menu</button>
|
||||
<app-menu #lazyMenu ariaLabel="Lazy actions">
|
||||
<ng-template appMenuContent>
|
||||
<app-menu-item>Lazy first</app-menu-item>
|
||||
<app-menu-item>Lazy last</app-menu-item>
|
||||
</ng-template>
|
||||
</app-menu>
|
||||
`,
|
||||
})
|
||||
class HostComponent {
|
||||
readonly menuRef = viewChild.required(AppMenuComponent);
|
||||
readonly lazyMenuRef = viewChild.required<AppMenuComponent>('lazyMenu');
|
||||
|
||||
openSecondFrom(event: MouseEvent): void {
|
||||
this.menuRef().open(event.currentTarget as HTMLElement);
|
||||
}
|
||||
readonly fav = signal(false);
|
||||
readonly favMixed = signal(false);
|
||||
readonly busy = signal(true);
|
||||
readonly keepOpenLabel = signal('Keep open');
|
||||
readonly status = signal<string | null>(null);
|
||||
readonly onDownload = vi.fn();
|
||||
readonly onDisabled = vi.fn();
|
||||
readonly onFav = vi.fn();
|
||||
readonly onSend = vi.fn();
|
||||
readonly onQuick = vi.fn();
|
||||
readonly onBusy = vi.fn();
|
||||
readonly onKeepOpen = vi.fn();
|
||||
readonly onLink = vi.fn();
|
||||
}
|
||||
|
||||
function setup(isDesktop = signal(true)) {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideRouter([{ path: 'books', children: [] }]),
|
||||
{ provide: LayoutService, useValue: { isDesktop } },
|
||||
],
|
||||
});
|
||||
const fixture = TestBed.createComponent(HostComponent);
|
||||
fixture.detectChanges();
|
||||
const host = fixture.nativeElement as HTMLElement;
|
||||
return { fixture, host };
|
||||
}
|
||||
|
||||
function openMenu(isDesktop = signal(true)) {
|
||||
const { fixture, host } = setup(isDesktop);
|
||||
(host.querySelector('button') as HTMLButtonElement).click();
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
function rootMenuEl(): HTMLElement {
|
||||
return document.querySelector('app-menu[aria-label="Actions"]') as HTMLElement;
|
||||
}
|
||||
function subMenuEl(): HTMLElement {
|
||||
return document.querySelector('app-menu[aria-label="Send options"]') as HTMLElement;
|
||||
}
|
||||
function isOpen(menu: HTMLElement): boolean {
|
||||
return !menu.classList.contains('hidden');
|
||||
}
|
||||
function itemByText(text: string): HTMLElement {
|
||||
const items = Array.from(document.querySelectorAll('app-menu-item'));
|
||||
return items.find((item) => item.textContent?.includes(text)) as HTMLElement;
|
||||
}
|
||||
|
||||
describe('AppMenu', () => {
|
||||
it('creates opt-in lazy content on first open and keeps it for later opens', async () => {
|
||||
const { fixture, host } = setup();
|
||||
const trigger = host.querySelector('.lazy-trigger') as HTMLButtonElement;
|
||||
|
||||
expect(fixture.componentInstance.lazyMenuRef().hasItems()).toBe(true);
|
||||
expect(document.querySelector('app-menu[aria-label="Lazy actions"] app-menu-item')).toBeNull();
|
||||
|
||||
trigger.click();
|
||||
await fixture.whenStable();
|
||||
expect(itemByText('Lazy first')).not.toBeNull();
|
||||
|
||||
trigger.click();
|
||||
await fixture.whenStable();
|
||||
expect(itemByText('Lazy first')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('focuses the requested lazy item after rendering', async () => {
|
||||
const { fixture, host } = setup();
|
||||
const trigger = host.querySelector('.lazy-trigger') as HTMLButtonElement;
|
||||
|
||||
trigger.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true }));
|
||||
await fixture.whenStable();
|
||||
|
||||
expect(itemByText('Lazy last').getAttribute('data-active')).toBe('true');
|
||||
expect(document.activeElement).toBe(itemByText('Lazy last'));
|
||||
});
|
||||
|
||||
it('opens and closes via the trigger', () => {
|
||||
const { fixture, host } = setup();
|
||||
const trigger = host.querySelector('button') as HTMLButtonElement;
|
||||
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
expect(trigger.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(trigger.getAttribute('aria-haspopup')).toBe('menu');
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
expect(trigger.getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
|
||||
it('emits selected once and closes on a regular item (click)', () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
|
||||
itemByText('Download').click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(cmp.onDownload).toHaveBeenCalledTimes(1);
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps disabled and loading items inert', () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
|
||||
const disabled = itemByText('Disabled');
|
||||
expect(disabled.getAttribute('aria-disabled')).toBe('true');
|
||||
disabled.click();
|
||||
itemByText('Working').click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(cmp.onDisabled).not.toHaveBeenCalled();
|
||||
expect(cmp.onBusy).not.toHaveBeenCalled();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the menu open for a closeOnSelect=false item', () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
|
||||
itemByText('Keep open').click();
|
||||
fixture.detectChanges();
|
||||
expect(cmp.onKeepOpen).toHaveBeenCalledTimes(1);
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
});
|
||||
|
||||
it('renders a link item as a routerLink anchor and emits once on keyboard', async () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
|
||||
const linkItem = itemByText('Go to books');
|
||||
const anchor = linkItem.querySelector('a') as HTMLAnchorElement;
|
||||
expect(anchor.getAttribute('href')).toBe('/books');
|
||||
|
||||
linkItem.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(cmp.onLink).toHaveBeenCalledTimes(1);
|
||||
expect(TestBed.inject(Router).url).toBe('/books');
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('toggles a checkbox, keeps aria-checked and the menu open', () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
|
||||
const checkbox = document.querySelector('app-menu-checkbox') as HTMLElement;
|
||||
expect(checkbox.getAttribute('role')).toBe('menuitemcheckbox');
|
||||
expect(checkbox.getAttribute('aria-checked')).toBe('false');
|
||||
checkbox.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(cmp.fav()).toBe(true);
|
||||
expect(cmp.onFav).toHaveBeenCalledWith(true);
|
||||
expect(checkbox.getAttribute('aria-checked')).toBe('true');
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
});
|
||||
|
||||
it('clears the mixed state and becomes checked when activated', () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
cmp.favMixed.set(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
const checkbox = document.querySelector('app-menu-checkbox') as HTMLElement;
|
||||
expect(checkbox.getAttribute('aria-checked')).toBe('mixed');
|
||||
checkbox.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(cmp.favMixed()).toBe(false);
|
||||
expect(cmp.fav()).toBe(true);
|
||||
expect(checkbox.getAttribute('aria-checked')).toBe('true');
|
||||
});
|
||||
|
||||
it('selects a radio, single-select, and closes', () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
cmp.status.set('read');
|
||||
fixture.detectChanges();
|
||||
|
||||
const radios = document.querySelectorAll('app-menu-radio');
|
||||
expect(radios[0].getAttribute('role')).toBe('menuitemradio');
|
||||
expect(radios[0].getAttribute('aria-checked')).toBe('true');
|
||||
(radios[1] as HTMLElement).click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(cmp.status()).toBe('reading');
|
||||
expect(radios[1].getAttribute('aria-checked')).toBe('true');
|
||||
expect(radios[0].getAttribute('aria-checked')).toBe('false');
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('opens a submenu from its parent item and does not close the chain', () => {
|
||||
const fixture = openMenu();
|
||||
const cmp = fixture.componentInstance;
|
||||
|
||||
const sendItem = itemByText('Send');
|
||||
expect(subMenuEl().querySelector('app-menu-item')).toBeNull();
|
||||
expect(sendItem.getAttribute('aria-haspopup')).toBe('true');
|
||||
sendItem.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(itemByText('Quick send')).not.toBeUndefined();
|
||||
expect(isOpen(subMenuEl())).toBe(true);
|
||||
expect(cmp.onSend).not.toHaveBeenCalled();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
});
|
||||
|
||||
it('closes the submenu chain and restores focus after keyboard selection', () => {
|
||||
const { fixture, host } = setup();
|
||||
const cmp = fixture.componentInstance;
|
||||
const trigger = host.querySelector('button') as HTMLButtonElement;
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
itemByText('Send').click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const leaf = itemByText('Quick send');
|
||||
leaf.focus();
|
||||
leaf.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(cmp.onQuick).toHaveBeenCalledTimes(1);
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
expect(isOpen(subMenuEl())).toBe(false);
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
});
|
||||
|
||||
it('opens a submenu via keyboard ArrowRight', () => {
|
||||
const fixture = openMenu();
|
||||
const menuEl = rootMenuEl();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
menuEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
expect(itemByText('Send').getAttribute('data-active')).toBe('true');
|
||||
menuEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(subMenuEl())).toBe(true);
|
||||
});
|
||||
|
||||
it('updates typeahead when projected label text changes', async () => {
|
||||
const fixture = openMenu();
|
||||
fixture.componentInstance.keepOpenLabel.set('Archive');
|
||||
await fixture.whenStable();
|
||||
|
||||
rootMenuEl().dispatchEvent(new KeyboardEvent('keydown', { key: 'a', bubbles: true }));
|
||||
await fixture.whenStable();
|
||||
|
||||
expect(itemByText('Archive').getAttribute('data-active')).toBe('true');
|
||||
});
|
||||
|
||||
it('opens at coordinates and survives the auxclick fired when the right button releases', () => {
|
||||
const { fixture, host } = setup();
|
||||
const zone = host.querySelector('.zone') as HTMLElement;
|
||||
zone.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 10, clientY: 20 }));
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
|
||||
zone.dispatchEvent(new MouseEvent('auxclick', { bubbles: true, button: 2 }));
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
|
||||
zone.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('moves to a second opener clicked while already open', () => {
|
||||
const { fixture, host } = setup();
|
||||
const trigger = host.querySelector('button') as HTMLButtonElement;
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
|
||||
const second = host.querySelector('.second') as HTMLButtonElement;
|
||||
second.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
expect(fixture.componentInstance.menuRef().openerElement()).toBe(second);
|
||||
});
|
||||
|
||||
it('closes when focus moves outside the menu', () => {
|
||||
const fixture = openMenu();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
|
||||
const outside = document.querySelector('.second') as HTMLButtonElement;
|
||||
rootMenuEl().dispatchEvent(new FocusEvent('focusout', { bubbles: true, relatedTarget: outside }));
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('closes on a trigger click even after focus moves back to the trigger', () => {
|
||||
const { fixture, host } = setup();
|
||||
const trigger = host.querySelector('button') as HTMLButtonElement;
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
|
||||
rootMenuEl().dispatchEvent(new FocusEvent('focusout', { bubbles: true, relatedTarget: trigger }));
|
||||
fixture.detectChanges();
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('closes when a router navigation starts', async () => {
|
||||
const fixture = openMenu();
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
|
||||
await TestBed.inject(Router).navigateByUrl('/books');
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
describe('sheet presentation (mobile shell)', () => {
|
||||
it('presents as a full-width bottom sheet with a scrim, dismissed by scrim tap', () => {
|
||||
const fixture = openMenu(signal(false));
|
||||
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
expect(rootMenuEl().classList.contains('w-full')).toBe(true);
|
||||
const backdrop = document.querySelector('.app-menu-sheet-backdrop') as HTMLElement;
|
||||
expect(backdrop).not.toBeNull();
|
||||
|
||||
backdrop.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('pushes a submenu over its parent and returns through the back row', () => {
|
||||
const fixture = openMenu(signal(false));
|
||||
|
||||
itemByText('Send').click();
|
||||
fixture.detectChanges();
|
||||
fixture.detectChanges();
|
||||
|
||||
const sub = subMenuEl();
|
||||
const root = rootMenuEl();
|
||||
expect(isOpen(sub)).toBe(true);
|
||||
expect(sub.parentElement).toBe(root.parentElement);
|
||||
expect(root.classList.contains('hidden')).toBe(true);
|
||||
const back = sub.querySelector('button') as HTMLButtonElement;
|
||||
expect(back.textContent).toContain('Send');
|
||||
|
||||
back.click();
|
||||
fixture.detectChanges();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(isOpen(subMenuEl())).toBe(false);
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
expect(rootMenuEl().classList.contains('hidden')).toBe(false);
|
||||
});
|
||||
|
||||
it('selecting a pushed submenu leaf closes the whole sheet chain', () => {
|
||||
const fixture = openMenu(signal(false));
|
||||
const cmp = fixture.componentInstance;
|
||||
itemByText('Send').click();
|
||||
fixture.detectChanges();
|
||||
|
||||
itemByText('Quick send').click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(cmp.onQuick).toHaveBeenCalledTimes(1);
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
expect(isOpen(subMenuEl())).toBe(false);
|
||||
});
|
||||
|
||||
it('closes when the viewport crosses the mobile-shell breakpoint while open', () => {
|
||||
const isDesktop = signal(false);
|
||||
const fixture = openMenu(isDesktop);
|
||||
expect(isOpen(rootMenuEl())).toBe(true);
|
||||
|
||||
isDesktop.set(true);
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(rootMenuEl())).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('restores focus to the trigger when closed from within', () => {
|
||||
const { fixture, host } = setup();
|
||||
const trigger = host.querySelector('button') as HTMLButtonElement;
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const menuEl = rootMenuEl();
|
||||
itemByText('Download').focus();
|
||||
menuEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
expect(isOpen(menuEl)).toBe(false);
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Directive, forwardRef, input } from '@angular/core';
|
||||
import { MenuItem } from '@angular/aria/menu';
|
||||
|
||||
import type { AppMenuComponent } from './app-menu.component';
|
||||
|
||||
@Directive({
|
||||
selector: '[appMenuAriaItem]',
|
||||
standalone: true,
|
||||
providers: [{ provide: MenuItem, useExisting: forwardRef(() => AppMenuAriaItemDirective) }],
|
||||
})
|
||||
export class AppMenuAriaItemDirective extends MenuItem<unknown> {
|
||||
override readonly value = input<unknown>('app-menu-item');
|
||||
override readonly disabled = input(false);
|
||||
|
||||
owner: AppMenuComponent | undefined;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { afterEveryRender, ElementRef, inject, type Signal } from '@angular/core';
|
||||
|
||||
import { AppMenuComponent } from './app-menu.component';
|
||||
import { AppMenuAriaItemDirective } from './menu-aria-item.directive';
|
||||
|
||||
export function setupMenuItem(searchLabel: Signal<string>): void {
|
||||
const menuItem = inject(AppMenuAriaItemDirective);
|
||||
const host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
menuItem.owner = inject(AppMenuComponent);
|
||||
|
||||
afterEveryRender(() => {
|
||||
const label = host.nativeElement.querySelector('[data-menu-label]') ?? host.nativeElement;
|
||||
const text = searchLabel().trim() || (label.textContent ?? '').trim();
|
||||
menuItem.searchTerm.set(text);
|
||||
});
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
import { cn } from '../cn';
|
||||
import {
|
||||
overlayListActiveItemStateClass,
|
||||
overlayListItemContentClass,
|
||||
overlayListItemRowClass,
|
||||
overlayListRootClass,
|
||||
overlayListSectionLabelClass,
|
||||
overlayListSeparatorClass,
|
||||
overlayListShortcutClass,
|
||||
overlayListSurfaceClass,
|
||||
} from '../overlay-list.styles';
|
||||
|
||||
const ptClass = (className: string) => ({ class: className });
|
||||
export const APP_MENU_SECTION_CLASS = 'app-menu-section-label';
|
||||
|
||||
type AppMenuItemVariant = 'destructive';
|
||||
|
||||
interface MenuPtOptions {
|
||||
context?: MenuPtContext;
|
||||
}
|
||||
|
||||
interface MenuPtContext {
|
||||
item?: {
|
||||
styleClass?: string;
|
||||
appMenuSection?: boolean;
|
||||
appMenuVariant?: AppMenuItemVariant;
|
||||
};
|
||||
active?: boolean;
|
||||
focused?: boolean;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const destructiveItemStateClass =
|
||||
'text-danger hover:bg-danger/10 hover:text-danger dark:hover:bg-danger/20';
|
||||
const destructiveActiveItemStateClass = 'bg-danger/10 text-danger dark:bg-danger/20';
|
||||
const menuSurfaceClass = cn('min-w-[8rem]', overlayListSurfaceClass);
|
||||
const menuItemLinkClass = cn(overlayListItemRowClass, 'cursor-pointer');
|
||||
|
||||
export const hasMenuStyleClass = (styleClass: string | undefined, className: string): boolean =>
|
||||
(styleClass ?? '').split(/\s+/).includes(className);
|
||||
|
||||
const hasItemClass = (context: MenuPtContext | undefined, className: string): boolean =>
|
||||
hasMenuStyleClass(context?.item?.styleClass, className);
|
||||
|
||||
const isDestructiveItem = (context: MenuPtContext | undefined): boolean =>
|
||||
context?.item?.appMenuVariant === 'destructive' ||
|
||||
hasItemClass(context, 'destructive') ||
|
||||
hasItemClass(context, 'app-menu-item-destructive');
|
||||
|
||||
const isSectionLabel = (context: MenuPtContext | undefined): boolean =>
|
||||
context?.item?.appMenuSection === true || hasItemClass(context, APP_MENU_SECTION_CLASS);
|
||||
|
||||
const isActiveItem = (context: MenuPtContext | undefined): boolean =>
|
||||
context?.active === true || context?.focused === true;
|
||||
|
||||
export const menuPanelClass = menuSurfaceClass;
|
||||
|
||||
export const menuPassThrough = {
|
||||
rootList: ptClass(overlayListRootClass),
|
||||
item: ({ context }: MenuPtOptions) =>
|
||||
ptClass(cn(
|
||||
'relative',
|
||||
context?.disabled && 'pointer-events-none',
|
||||
context?.disabled && !isSectionLabel(context) && 'opacity-50',
|
||||
)),
|
||||
itemContent: ({ context }: MenuPtOptions) => {
|
||||
if (isSectionLabel(context)) {
|
||||
return ptClass('text-text-muted');
|
||||
}
|
||||
|
||||
const destructive = isDestructiveItem(context);
|
||||
return ptClass(cn(
|
||||
overlayListItemContentClass,
|
||||
destructive && destructiveItemStateClass,
|
||||
isActiveItem(context) && (destructive ? destructiveActiveItemStateClass : overlayListActiveItemStateClass),
|
||||
));
|
||||
},
|
||||
itemLink: ({ context }: MenuPtOptions) =>
|
||||
ptClass(isSectionLabel(context) ? overlayListSectionLabelClass : menuItemLinkClass),
|
||||
itemIcon: ({ context }: MenuPtOptions) =>
|
||||
ptClass(cn(
|
||||
'flex size-4 shrink-0 items-center justify-center text-base text-text-muted',
|
||||
isDestructiveItem(context) && 'text-danger',
|
||||
)),
|
||||
itemLabel: ptClass('truncate leading-5'),
|
||||
itemBadge: ptClass(cn(overlayListShortcutClass, 'leading-5')),
|
||||
submenu: ptClass(cn('absolute z-50 m-0 list-none flex-col', menuSurfaceClass)),
|
||||
submenuIcon: ptClass('ml-auto size-4 shrink-0 text-text-muted'),
|
||||
separator: ptClass(overlayListSeparatorClass),
|
||||
} as const;
|
||||
@@ -0,0 +1,64 @@
|
||||
import { cn } from '../cn';
|
||||
import {
|
||||
overlayListItemRowClass,
|
||||
overlayListSectionLabelClass,
|
||||
overlayListSeparatorClass,
|
||||
overlayListShortcutClass,
|
||||
overlayListSurfaceClass,
|
||||
} from '../overlay-list.styles';
|
||||
|
||||
export type AppMenuItemVariant = 'default' | 'destructive';
|
||||
|
||||
export const appMenuPanelClass = cn(
|
||||
'm-0 box-border flex max-h-[calc(100vh-1rem)] min-w-[8rem] flex-col p-1',
|
||||
overlayListSurfaceClass,
|
||||
);
|
||||
|
||||
export const appMenuSheetPanelClass =
|
||||
'w-full max-w-full max-h-[80dvh] ' +
|
||||
'rounded-t-xl rounded-b-none border-x-0 border-b-0 ' +
|
||||
'pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]';
|
||||
|
||||
export const appMenuScrollRegionClass = 'flex min-h-0 flex-col overflow-y-auto overscroll-contain';
|
||||
|
||||
export const appMenuSheetPaneClass = 'will-change-transform animate-in-sheet slide-in-from-bottom-full';
|
||||
|
||||
export const appMenuBackHeaderClass = 'flex-none pb-1';
|
||||
|
||||
export const appMenuBackRowClass = cn(
|
||||
overlayListItemRowClass,
|
||||
'mb-2.5 cursor-pointer rounded-sm font-medium text-text-muted hover:bg-surface-hover hover:text-text-strong',
|
||||
);
|
||||
|
||||
export const appMenuBackLabelClass = 'min-w-0 flex-1 truncate text-left';
|
||||
|
||||
const menuItemStateClass =
|
||||
'data-[active=true]:bg-surface-hover data-[active=true]:text-text-strong ' +
|
||||
'hover:bg-surface-hover hover:text-text-strong ' +
|
||||
'aria-disabled:pointer-events-none aria-disabled:opacity-50';
|
||||
|
||||
const menuItemDestructiveStateClass =
|
||||
'text-danger ' +
|
||||
'data-[active=true]:bg-danger/10 data-[active=true]:text-danger dark:data-[active=true]:bg-danger/20 ' +
|
||||
'hover:bg-danger/10 hover:text-danger dark:hover:bg-danger/20 ' +
|
||||
'aria-disabled:pointer-events-none aria-disabled:opacity-50';
|
||||
|
||||
export function appMenuItemRowClass(variant: AppMenuItemVariant): string {
|
||||
return cn(
|
||||
overlayListItemRowClass,
|
||||
'cursor-pointer rounded-sm text-text no-underline',
|
||||
variant === 'destructive' ? menuItemDestructiveStateClass : menuItemStateClass,
|
||||
);
|
||||
}
|
||||
|
||||
export const appMenuLeadingSlotClass = 'flex size-4 shrink-0 items-center justify-center text-text-muted';
|
||||
export const appMenuBadgeSlotClass = cn(appMenuLeadingSlotClass, 'text-xs font-medium tabular-nums');
|
||||
export const appMenuIconClass = 'size-4 shrink-0';
|
||||
export const appMenuSpinnerClass = 'size-4 shrink-0 border-2';
|
||||
export const appMenuLabelClass = 'min-w-0 flex-1 truncate leading-5';
|
||||
export const appMenuShortcutClass = overlayListShortcutClass;
|
||||
export const appMenuTrailingIconClass = 'size-4 shrink-0';
|
||||
export const appMenuSubmenuIconClass = 'ml-auto size-4 shrink-0 text-text-muted';
|
||||
export const appMenuCheckIconClass = 'size-4 shrink-0 text-primary';
|
||||
export const appMenuSectionClass = cn(overlayListSectionLabelClass, 'text-text-muted');
|
||||
export const appMenuSeparatorClass = overlayListSeparatorClass;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { type ScrollStrategy } from '@angular/cdk/overlay';
|
||||
|
||||
let lockCount = 0;
|
||||
let previousOverflow = '';
|
||||
let previousPaddingRight = '';
|
||||
|
||||
function lockRoot(): void {
|
||||
if (++lockCount > 1) return;
|
||||
const root = document.documentElement;
|
||||
previousOverflow = root.style.overflow;
|
||||
previousPaddingRight = root.style.paddingRight;
|
||||
const scrollbarWidth = window.innerWidth - root.clientWidth;
|
||||
if (scrollbarWidth > 0) {
|
||||
const currentPaddingRight = Number.parseFloat(getComputedStyle(root).paddingRight) || 0;
|
||||
root.style.paddingRight = `${currentPaddingRight + scrollbarWidth}px`;
|
||||
}
|
||||
root.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function unlockRoot(): void {
|
||||
if (--lockCount > 0) return;
|
||||
const root = document.documentElement;
|
||||
root.style.overflow = previousOverflow;
|
||||
root.style.paddingRight = previousPaddingRight;
|
||||
}
|
||||
|
||||
export function scrollLockStrategy(): ScrollStrategy {
|
||||
let enabled = false;
|
||||
return {
|
||||
attach: () => undefined,
|
||||
enable: () => {
|
||||
if (enabled) return;
|
||||
enabled = true;
|
||||
lockRoot();
|
||||
},
|
||||
disable: () => {
|
||||
if (!enabled) return;
|
||||
enabled = false;
|
||||
unlockRoot();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
import { booleanAttribute, ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
||||
import { type MenuItem } from 'primeng/api';
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
contentChild,
|
||||
ElementRef,
|
||||
input,
|
||||
output,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { LucideChevronDown } from '@lucide/angular';
|
||||
import { cn } from '../cn';
|
||||
import { connectedGroupClass, connectedItemClass } from '../connected-group';
|
||||
@@ -10,7 +19,7 @@ import { AppMenuComponent } from '../menu/app-menu.component';
|
||||
@Component({
|
||||
selector: 'app-split-button',
|
||||
standalone: true,
|
||||
imports: [AppButtonComponent, AppMenuComponent, LucideChevronDown],
|
||||
imports: [AppButtonComponent, LucideChevronDown],
|
||||
host: {
|
||||
class: 'inline-block align-middle',
|
||||
'[class.w-full]': 'fluid()',
|
||||
@@ -42,6 +51,7 @@ import { AppMenuComponent } from '../menu/app-menu.component';
|
||||
<ng-content />
|
||||
</app-button>
|
||||
<app-button
|
||||
#menuButton
|
||||
[buttonId]="menuButtonId()"
|
||||
type="button"
|
||||
iconOnly
|
||||
@@ -51,12 +61,13 @@ import { AppMenuComponent } from '../menu/app-menu.component';
|
||||
[styleClass]="menuButtonClass()"
|
||||
[disabled]="isMenuDisabled()"
|
||||
[form]="form()"
|
||||
[ariaHasPopup]="'menu'"
|
||||
ariaHasPopup="menu"
|
||||
[ariaExpanded]="menuExpanded()"
|
||||
[ariaLabel]="menuAriaLabel() || ariaLabel() || label()"
|
||||
(clicked)="menu.toggle($event)">
|
||||
(clicked)="toggleMenu()">
|
||||
<svg lucideChevronDown aria-hidden="true"></svg>
|
||||
</app-button>
|
||||
<app-menu #menu [model]="model()" [appendTo]="appendTo()" />
|
||||
<ng-content select="app-menu" />
|
||||
</span>
|
||||
`,
|
||||
})
|
||||
@@ -79,15 +90,19 @@ export class AppSplitButtonComponent {
|
||||
readonly ariaLabel = input('');
|
||||
readonly menuAriaLabel = input('');
|
||||
readonly iconPos = input<'left' | 'right'>('left');
|
||||
readonly model = input<readonly MenuItem[]>([]);
|
||||
readonly appendTo = input<'body' | 'self' | HTMLElement>('body');
|
||||
readonly loading = input(false, { transform: booleanAttribute });
|
||||
readonly disabled = input(false, { transform: booleanAttribute });
|
||||
readonly type = input<'button' | 'submit' | 'reset'>('button');
|
||||
|
||||
readonly clicked = output<MouseEvent>();
|
||||
|
||||
protected readonly isMenuDisabled = computed(() => this.disabled() || this.loading() || this.model().length === 0);
|
||||
private readonly menu = contentChild(AppMenuComponent);
|
||||
private readonly menuButton = viewChild<unknown, ElementRef<HTMLElement>>('menuButton', { read: ElementRef });
|
||||
|
||||
protected readonly isMenuDisabled = computed(() => this.disabled() || this.loading() || !this.menu()?.hasItems());
|
||||
protected readonly menuExpanded = computed(() =>
|
||||
this.menu()?.openerElement() === this.menuButton()?.nativeElement ? 'true' : 'false',
|
||||
);
|
||||
protected readonly rootClass = computed(() => cn(connectedGroupClass, this.fluid() && 'w-full', this.styleClass()));
|
||||
protected readonly mainButtonClass = computed(() =>
|
||||
cn(
|
||||
@@ -103,4 +118,15 @@ export class AppSplitButtonComponent {
|
||||
this.menuButtonStyleClass(),
|
||||
),
|
||||
);
|
||||
|
||||
protected toggleMenu(): void {
|
||||
const menu = this.menu();
|
||||
const origin = this.menuButton()?.nativeElement;
|
||||
if (!menu || !origin) return;
|
||||
if (menu.openerElement() === origin) {
|
||||
menu.close();
|
||||
} else {
|
||||
menu.open(origin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
background: rgb(0 0 0 / 56%);
|
||||
}
|
||||
|
||||
.cdk-overlay-backdrop.app-menu-sheet-backdrop {
|
||||
background: rgb(0 0 0 / 40%);
|
||||
}
|
||||
|
||||
.cdk-overlay-pane.command-palette-panel {
|
||||
display: flex;
|
||||
pointer-events: auto;
|
||||
|
||||
@@ -28,6 +28,12 @@
|
||||
@utility slide-in-from-bottom-1 {
|
||||
--tw-enter-translate-y: 0.25rem;
|
||||
}
|
||||
@utility slide-in-from-bottom-full {
|
||||
--tw-enter-translate-y: 100%;
|
||||
}
|
||||
@utility animate-in-sheet {
|
||||
animation: enter 250ms cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Inter";
|
||||
|
||||
Reference in New Issue
Block a user