feat(ui): app-menu based shelf assignment component (#2058)
This commit is contained in:
+178
@@ -0,0 +1,178 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {ShelfMembershipMenuComponent, type ShelfMembershipItem} from './shelf-membership-menu.component';
|
||||
|
||||
function shelves(count: number): ShelfMembershipItem[] {
|
||||
return Array.from({length: count}, (_, i) => ({id: i + 1, name: `Shelf ${i + 1}`, checked: false}));
|
||||
}
|
||||
|
||||
describe('ShelfMembershipMenuComponent', () => {
|
||||
let fixture: ComponentFixture<ShelfMembershipMenuComponent>;
|
||||
let host: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ShelfMembershipMenuComponent, getTranslocoModule()],
|
||||
});
|
||||
fixture = TestBed.createComponent(ShelfMembershipMenuComponent);
|
||||
host = fixture.nativeElement as HTMLElement;
|
||||
});
|
||||
|
||||
async function render(items: ShelfMembershipItem[]): Promise<void> {
|
||||
fixture.componentRef.setInput('shelves', items);
|
||||
await fixture.whenStable();
|
||||
if (!fixture.componentInstance.menu().isOpen()) {
|
||||
fixture.componentInstance.menu().open(host);
|
||||
await fixture.whenStable();
|
||||
}
|
||||
}
|
||||
|
||||
async function setQuery(value: string): Promise<void> {
|
||||
const input = menuElement().querySelector('input') as HTMLInputElement;
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event('input', {bubbles: true}));
|
||||
await fixture.whenStable();
|
||||
}
|
||||
|
||||
function menuElement(): HTMLElement {
|
||||
return document.querySelector('app-menu[aria-label="Add to shelf"]') as HTMLElement;
|
||||
}
|
||||
|
||||
function rowLabels(): string[] {
|
||||
return Array.from(menuElement().querySelectorAll('app-menu-checkbox')).map(el => el.textContent?.trim() ?? '');
|
||||
}
|
||||
|
||||
it('does not render shelf rows until the menu first opens', async () => {
|
||||
fixture.componentRef.setInput('shelves', shelves(3));
|
||||
await fixture.whenStable();
|
||||
|
||||
expect(host.querySelector('app-menu-checkbox')).toBeNull();
|
||||
|
||||
fixture.componentInstance.menu().open(host);
|
||||
await fixture.whenStable();
|
||||
|
||||
expect(rowLabels()).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('renders translated menu labels', async () => {
|
||||
await render(shelves(3));
|
||||
expect(menuElement().getAttribute('aria-label')).toBe('Add to shelf');
|
||||
expect(menuElement().querySelector('app-menu-item')?.textContent?.trim()).toBe('New shelf…');
|
||||
});
|
||||
|
||||
it('hides the filter input for a short, scannable list', async () => {
|
||||
await render(shelves(8));
|
||||
expect(menuElement().querySelector('input')).toBeNull();
|
||||
expect(rowLabels().length).toBe(8);
|
||||
});
|
||||
|
||||
it('shows the filter input past the threshold and filters rows by name', async () => {
|
||||
await render(shelves(12));
|
||||
expect(menuElement().querySelector('input')).not.toBeNull();
|
||||
|
||||
await setQuery('Shelf 1');
|
||||
expect(rowLabels()).toEqual(['Shelf 1', 'Shelf 10', 'Shelf 11', 'Shelf 12']);
|
||||
});
|
||||
|
||||
it('focuses the filter when a long menu opens', async () => {
|
||||
await render(shelves(12));
|
||||
expect(document.activeElement).toBe(menuElement().querySelector('input'));
|
||||
});
|
||||
|
||||
it('shows a polite no-matches status instead of an empty gap', async () => {
|
||||
await render(shelves(12));
|
||||
await setQuery('zzz');
|
||||
expect(rowLabels()).toEqual([]);
|
||||
expect(menuElement().querySelector('[role="status"]')?.textContent).toContain('No results');
|
||||
});
|
||||
|
||||
it('keeps typing away from the menu typeahead but hands Escape through', async () => {
|
||||
await render(shelves(12));
|
||||
const input = menuElement().querySelector('input') as HTMLInputElement;
|
||||
const reachedMenu = vi.fn();
|
||||
menuElement().addEventListener('keydown', reachedMenu);
|
||||
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', {key: 'a', bubbles: true, cancelable: true}));
|
||||
expect(reachedMenu).not.toHaveBeenCalled();
|
||||
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape', bubbles: true, cancelable: true}));
|
||||
expect(reachedMenu).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('moves from the filter to the first or last item without skipping a shelf', async () => {
|
||||
await render(shelves(12));
|
||||
const input = menuElement().querySelector('input') as HTMLInputElement;
|
||||
const rows = menuElement().querySelectorAll('app-menu-checkbox');
|
||||
const newShelf = menuElement().querySelector('app-menu-item') as HTMLElement;
|
||||
|
||||
input.focus();
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', {key: 'ArrowDown', bubbles: true, cancelable: true}));
|
||||
expect(document.activeElement).toBe(rows[0]);
|
||||
|
||||
input.focus();
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', {key: 'ArrowUp', bubbles: true, cancelable: true}));
|
||||
expect(document.activeElement).toBe(newShelf);
|
||||
});
|
||||
|
||||
it('emits toggleShelf with the shelf id and next state', async () => {
|
||||
await render(shelves(3));
|
||||
const spy = vi.fn();
|
||||
fixture.componentInstance.toggleShelf.subscribe(spy);
|
||||
const row = menuElement().querySelectorAll('app-menu-checkbox')[1] as HTMLElement;
|
||||
row.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
|
||||
expect(spy).toHaveBeenCalledWith({shelfId: 2, checked: true});
|
||||
});
|
||||
|
||||
it('clears a retained filter when the list shrinks below the threshold', async () => {
|
||||
await render(shelves(12));
|
||||
await setQuery('zzz');
|
||||
expect(rowLabels()).toEqual([]);
|
||||
|
||||
fixture.componentRef.setInput('shelves', shelves(8));
|
||||
await fixture.whenStable();
|
||||
|
||||
const retainedInput = menuElement().querySelector('input') as HTMLInputElement;
|
||||
expect(retainedInput.value).toBe('');
|
||||
expect(rowLabels().length).toBe(8);
|
||||
expect(fixture.componentInstance.menu().isOpen()).toBe(true);
|
||||
expect(document.activeElement).toBe(retainedInput);
|
||||
|
||||
retainedInput.dispatchEvent(new KeyboardEvent('keydown', {key: 'ArrowDown', bubbles: true, cancelable: true}));
|
||||
await fixture.whenStable();
|
||||
|
||||
expect(menuElement().querySelector('input')).toBe(retainedInput);
|
||||
expect(document.activeElement).toBe(menuElement().querySelector('app-menu-checkbox'));
|
||||
|
||||
await render(shelves(12));
|
||||
expect((menuElement().querySelector('input') as HTMLInputElement).value).toBe('');
|
||||
expect(rowLabels().length).toBe(12);
|
||||
|
||||
fixture.componentRef.setInput('shelves', shelves(8));
|
||||
fixture.componentInstance.menu().close();
|
||||
await fixture.whenStable();
|
||||
fixture.componentInstance.menu().open(host);
|
||||
await fixture.whenStable();
|
||||
expect(menuElement().querySelector('input')).toBeNull();
|
||||
});
|
||||
|
||||
it('emits createShelf when the New shelf item is chosen', async () => {
|
||||
await render(shelves(3));
|
||||
const spy = vi.fn();
|
||||
fixture.componentInstance.createShelf.subscribe(spy);
|
||||
const newShelf = menuElement().querySelector('app-menu-item') as HTMLElement;
|
||||
newShelf.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('renders the filter, rows and New shelf in logical order', async () => {
|
||||
await render(shelves(12));
|
||||
const order = Array.from(menuElement().querySelectorAll('input, app-menu-checkbox, app-menu-item')).map(el => {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
return tag === 'input' ? 'filter' : tag === 'app-menu-item' ? 'newShelf' : 'row';
|
||||
});
|
||||
expect(order[0]).toBe('filter');
|
||||
expect(order.at(-1)).toBe('newShelf');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import {ChangeDetectionStrategy, Component, computed, ElementRef, input, linkedSignal, output, viewChild} from '@angular/core';
|
||||
import {Menu} from '@angular/aria/menu';
|
||||
import {TranslocoPipe} from '@jsverse/transloco';
|
||||
|
||||
import {LucideSearch} from '@lucide/angular';
|
||||
|
||||
import {AppMenuComponent} from '../../ui/menu/app-menu.component';
|
||||
import {AppMenuCheckboxComponent} from '../../ui/menu/app-menu-checkbox.component';
|
||||
import {AppMenuContentDirective} from '../../ui/menu/app-menu-content.directive';
|
||||
import {AppMenuItemComponent} from '../../ui/menu/app-menu-item.component';
|
||||
import {AppMenuSeparatorComponent} from '../../ui/menu/app-menu-separator.component';
|
||||
|
||||
export interface ShelfMembershipItem {
|
||||
id: number;
|
||||
name: string;
|
||||
checked: boolean;
|
||||
mixed?: boolean;
|
||||
}
|
||||
|
||||
const FILTER_THRESHOLD = 8;
|
||||
|
||||
@Component({
|
||||
selector: 'app-shelf-membership-menu',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: {class: 'contents'},
|
||||
imports: [
|
||||
TranslocoPipe,
|
||||
LucideSearch,
|
||||
AppMenuComponent,
|
||||
AppMenuCheckboxComponent,
|
||||
AppMenuContentDirective,
|
||||
AppMenuItemComponent,
|
||||
AppMenuSeparatorComponent,
|
||||
],
|
||||
template: `
|
||||
<app-menu
|
||||
[ariaLabel]="'shared.ui.shelfMenu.addToShelf' | transloco"
|
||||
(opened)="onOpened()"
|
||||
(closed)="onClosed()"
|
||||
>
|
||||
<ng-template appMenuContent>
|
||||
@if (filterVisible()) {
|
||||
<div class="flex items-center gap-2 rounded-sm px-2 pb-2 pt-1.5 focus-within:bg-surface-hover focus-within:text-text-strong">
|
||||
<svg lucideSearch class="size-3.5 shrink-0 text-text-muted" aria-hidden="true"></svg>
|
||||
<input
|
||||
#filterInput
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
class="w-full min-w-0 bg-transparent text-sm text-text outline-none placeholder:text-text-muted"
|
||||
[value]="query()"
|
||||
[placeholder]="'shared.ui.select.search' | transloco"
|
||||
[attr.aria-label]="'shared.ui.select.search' | transloco"
|
||||
(input)="query.set(filterInput.value)"
|
||||
(keydown)="onFilterKeydown($event)"
|
||||
/>
|
||||
</div>
|
||||
<app-menu-separator />
|
||||
}
|
||||
<div class="max-h-80 overflow-y-auto overscroll-contain">
|
||||
@for (shelf of filteredShelves(); track shelf.id) {
|
||||
<app-menu-checkbox
|
||||
[checked]="shelf.checked"
|
||||
[mixed]="shelf.mixed ?? false"
|
||||
(selected)="toggleShelf.emit({shelfId: shelf.id, checked: $event})">{{ shelf.name }}</app-menu-checkbox>
|
||||
} @empty {
|
||||
@if (shelves().length > 0) {
|
||||
<p role="status" class="m-0 flex min-h-7 items-center px-2 py-1 text-sm leading-5 text-text-muted pointer-coarse:min-h-11 pointer-coarse:px-3">{{ 'shared.ui.select.noResults' | transloco }}</p>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@if (shelves().length > 0) {
|
||||
<app-menu-separator />
|
||||
}
|
||||
<app-menu-item (selected)="createShelf.emit()">{{ 'shared.ui.shelfMenu.newShelf' | transloco }}</app-menu-item>
|
||||
</ng-template>
|
||||
</app-menu>
|
||||
`,
|
||||
})
|
||||
export class ShelfMembershipMenuComponent {
|
||||
readonly shelves = input.required<ShelfMembershipItem[]>();
|
||||
|
||||
readonly toggleShelf = output<{shelfId: number; checked: boolean}>();
|
||||
readonly createShelf = output<void>();
|
||||
|
||||
readonly menu = viewChild.required(AppMenuComponent);
|
||||
readonly ariaMenu = viewChild.required(AppMenuComponent, {read: Menu});
|
||||
|
||||
private readonly filterInput = viewChild<ElementRef<HTMLInputElement>>('filterInput');
|
||||
|
||||
private readonly filterRequired = computed(() => this.shelves().length > FILTER_THRESHOLD);
|
||||
protected readonly filterVisible = linkedSignal<boolean, boolean>({
|
||||
source: this.filterRequired,
|
||||
computation: (required, previous) => required || (previous?.value ?? false),
|
||||
});
|
||||
protected readonly query = linkedSignal<boolean, string>({
|
||||
source: this.filterRequired,
|
||||
computation: (required, previous) => required ? (previous?.value ?? '') : '',
|
||||
});
|
||||
protected readonly filteredShelves = computed(() => {
|
||||
if (!this.filterVisible()) {
|
||||
return this.shelves();
|
||||
}
|
||||
const needle = this.query().trim().toLowerCase();
|
||||
if (!needle) {
|
||||
return this.shelves();
|
||||
}
|
||||
return this.shelves().filter(shelf => shelf.name.toLowerCase().includes(needle));
|
||||
});
|
||||
|
||||
protected onOpened(): void {
|
||||
this.filterVisible.set(this.filterRequired());
|
||||
queueMicrotask(() => this.filterInput()?.nativeElement.focus({preventScroll: true}));
|
||||
}
|
||||
|
||||
protected onClosed(): void {
|
||||
this.query.set('');
|
||||
this.filterVisible.set(false);
|
||||
}
|
||||
|
||||
protected onFilterKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const key = event.key === 'ArrowDown' ? 'Home' : 'End';
|
||||
this.ariaMenu().element.dispatchEvent(new KeyboardEvent('keydown', {key, bubbles: true, cancelable: true}));
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Escape' || event.key === 'Tab') {
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
event.stopPropagation();
|
||||
}
|
||||
}
|
||||
@@ -187,6 +187,10 @@
|
||||
"search": "Search",
|
||||
"selectedCount": "{{ count }} selected"
|
||||
},
|
||||
"shelfMenu": {
|
||||
"addToShelf": "Add to shelf",
|
||||
"newShelf": "New shelf…"
|
||||
},
|
||||
"spinner": {
|
||||
"loading": "Loading"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user