refactor(frontend): decouple app shell from PrimeNG layout system (#307)

* refactor(layout): decouple shell from PrimeNG

* fix(frontend): review fixes for layout decoupling

- Rewrite layout service spec to match new API surface
- Remove dead ToastModule import from AppLayoutComponent
- Add missing type="button" to profile and logout buttons
- Add missing i18n keys to all non-English locales

* chore(frontend): Layout shell consistency

* chore(frontend): shell and routing improvements

* chore(frontend): remove stray shimmer effect

* chore(frontend): code cleanup

* chore(ui): Fix navitem types consistency

* chore(frontend): simplify layout structure + imports

* chore(frontend): remove empty files

* chore(frontend): Menu component cleanup

* chore(frontend): remove nav translation layer

* chore(frontend): revert stray artwork change

* chore(frontend): revert author animation tweak

* chore(frontend): review fixes

* fix(frontend): restore topbar template after rebase conflict
This commit is contained in:
Alex
2026-04-22 17:26:57 -04:00
committed by Zach Yale
parent 61b9b53a60
commit 55a6343f65
110 changed files with 1688 additions and 1518 deletions
@@ -0,0 +1,88 @@
<ng-container *transloco="let t; prefix: 'layout.menu'">
<div class="menu-container">
<div>
<div class="home-menu-section">
<ul class="layout-menu">
@if (homeMenu(); as homeMenu) {
@for (item of homeMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="home"></li>
}
}
</ul>
<button
type="button"
class="sidebar-width-btn pi pi-objects-column"
[attr.aria-label]="t('adjustSidebarWidth')"
(click)="widthPanel.toggle($event)"
></button>
<p-popover #widthPanel appendTo="body">
<div class="sidebar-width-popover">
<span class="sidebar-width-popover-label">{{ sidebarWidth }}px</span>
<p-slider
[(ngModel)]="sidebarWidth"
[min]="175"
[max]="400"
[step]="1"
(onChange)="onSidebarWidthChange()"
(onSlideEnd)="saveSidebarWidth()">
</p-slider>
</div>
</p-popover>
</div>
<ul class="layout-menu">
@if (libraryMenu(); as libraryMenu) {
@for (item of libraryMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="library"></li>
}
}
</ul>
<ul class="layout-menu">
@if (shelfMenu(); as shelfMenu) {
@for (item of shelfMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="shelf"></li>
}
}
</ul>
<ul class="layout-menu">
@if (magicShelfMenu(); as magicShelfMenu) {
@for (item of magicShelfMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="magicShelf"></li>
}
}
</ul>
</div>
@if (versionInfo(); as versionInfo) {
<div class="version-info" style="margin-top: auto;">
<div class="version-text">
@if (isSemanticVersion(versionInfo.current)) {
<a
[href]="getVersionUrl(versionInfo.current)"
target="_blank"
rel="noopener noreferrer"
class="version-link"
>
{{ versionInfo.current }}
</a>
} @else {
<span class="version-label">{{ versionInfo.current }}</span>
}
</div>
@if (isSemanticVersion(versionInfo.current) && versionInfo.latest && versionInfo.latest !== versionInfo.current) {
<div>
<button
type="button"
class="update-link"
(click)="openChangelogDialog()"
>
{{ t('update') }}
</button>
</div>
}
</div>
}
</div>
</ng-container>
@@ -0,0 +1,89 @@
.menu-container {
display: flex;
flex-direction: column;
height: 100%;
}
.home-menu-section {
position: relative;
.sidebar-width-btn {
position: absolute;
top: 0.125rem;
right: 0.5rem;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
background: none;
font-size: 0.8rem;
color: var(--surface-500);
cursor: pointer;
transition: color 0.2s ease;
&:hover {
color: var(--primary-color);
}
}
}
.sidebar-width-popover {
display: flex;
align-items: center;
gap: 0.75rem;
min-width: 200px;
padding: 0.25rem;
.sidebar-width-popover-label {
font-size: 0.8rem;
color: var(--text-muted-color);
white-space: nowrap;
min-width: 38px;
text-align: right;
}
p-slider {
flex: 1;
}
}
.version-info {
padding: 1rem;
text-align: center;
width: 100%;
font-size: 0.875rem;
}
.version-text {
color: var(--text-color-secondary);
}
.version-link {
font-size: 0.875rem;
&:hover {
text-decoration: underline;
color: var(--high-contrast-text-color);
}
}
.version-label {
font-size: 0.875rem;
}
.update-link {
padding: 0;
border: 0;
background: none;
cursor: pointer;
color: var(--primary-text-color);
font-family: inherit;
font-size: 0.75rem;
line-height: inherit;
&:hover {
text-decoration: underline;
color: var(--primary-hover-color);
}
}
@@ -0,0 +1,17 @@
import {describe, it} from 'vitest';
// NOTE(frontend-seam): Real menu coverage needs coordinated signals for libraries, shelves,
// magic shelves, authors, books, user permissions, translation changes, and version/dialog
// behavior. The component is a large computed-menu assembler, and a low-value shallow spec would
// not honestly verify the menu trees that matter.
describe.skip('AppMenuComponent', () => {
it('needs a menu-data seam to verify computed home/library/shelf/magic-shelf menu trees', () => {
// TODO(seam): Cover computed menu composition once the dependent signals/services can be
// driven through a stable test harness rather than an all-up runtime mock graph.
});
it('needs a version-dialog and local-storage seam to verify side effects around dialogs and sidebar sizing', () => {
// TODO(seam): Cover version dialog and sidebar width behavior after those side effects are
// exposed behind a narrower facade.
});
});
@@ -0,0 +1,364 @@
import { Component, computed, effect, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { AppMenuitemComponent } from './app.menuitem.component';
import { LibraryService } from '../../../features/book/service/library.service';
import { LibraryHealthService } from '../../../features/book/service/library-health.service';
import { ShelfService } from '../../../features/book/service/shelf.service';
import { BookService } from '../../../features/book/service/book.service';
import { LibraryShelfMenuService } from '../../../features/book/service/library-shelf-menu.service';
import { VersionService } from '../../service/version.service';
import { UserService } from '../../../features/settings/user-management/user.service';
import { MagicShelfService } from '../../../features/magic-shelf/service/magic-shelf.service';
import { SeriesDataService } from '../../../features/series-browser/service/series-data.service';
import { AuthorService } from '../../../features/author-browser/service/author.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { TranslocoDirective, TranslocoService } from '@jsverse/transloco';
import { Slider } from 'primeng/slider';
import { FormsModule } from '@angular/forms';
import { Popover } from 'primeng/popover';
import { LocalStorageService } from '../../service/local-storage.service';
import type { MenuItem } from 'primeng/api';
export type NavIconType = 'PRIME_NG' | 'CUSTOM_SVG';
export type NavItemType =
| 'library' | 'shelf' | 'magicShelf'
| 'allBooks' | 'series' | 'authors';
export interface NavItem {
label: string;
icon?: string;
iconType?: NavIconType;
routerLink?: string[];
type?: NavItemType;
group?: boolean;
bookCount?: number;
unhealthy?: boolean;
items?: NavItem[];
hasDropDown?: boolean;
hasCreate?: boolean;
contextMenuItems?: MenuItem[];
}
@Component({
selector: 'app-menu',
imports: [AppMenuitemComponent, TranslocoDirective, Slider, FormsModule, Popover],
templateUrl: './app.menu.component.html',
styleUrl: './app.menu.component.scss',
})
export class AppMenuComponent {
private readonly libraryService = inject(LibraryService);
private readonly libraryHealthService = inject(LibraryHealthService);
private readonly shelfService = inject(ShelfService);
private readonly bookService = inject(BookService);
private readonly versionService = inject(VersionService);
private readonly libraryShelfMenuService = inject(LibraryShelfMenuService);
private readonly dialogLauncherService = inject(DialogLauncherService);
private readonly userService = inject(UserService);
private readonly magicShelfService = inject(MagicShelfService);
private readonly seriesDataService = inject(SeriesDataService);
private readonly authorService = inject(AuthorService);
private readonly t = inject(TranslocoService);
private readonly localStorageService = inject(LocalStorageService);
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
private readonly currentUser = this.userService.currentUser;
private readonly allAuthors = this.authorService.allAuthors;
readonly versionInfo = toSignal(this.versionService.getVersion(), { initialValue: null });
librarySortField = signal<'name' | 'id'>('name');
librarySortOrder = signal<'asc' | 'desc'>('desc');
shelfSortField = signal<'name' | 'id'>('name');
shelfSortOrder = signal<'asc' | 'desc'>('asc');
magicShelfSortField = signal<'name' | 'id'>('name');
magicShelfSortOrder = signal<'asc' | 'desc'>('asc');
sidebarWidth = this.localStorageService.get<number>('sidebarWidth') ?? 225;
private readonly libraryBookCounts = computed(() => {
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
if (book.libraryId != null) {
counts.set(book.libraryId, (counts.get(book.libraryId) ?? 0) + 1);
}
}
return counts;
});
private readonly shelfBookCounts = computed(() => {
const currentUserId = this.currentUser()?.id;
const counts = new Map<number, number>();
let unshelvedCount = 0;
for (const book of this.bookService.books()) {
if (!book.shelves || book.shelves.length === 0) {
unshelvedCount++;
} else {
for (const shelf of book.shelves) {
if (shelf.id != null) {
counts.set(shelf.id, (counts.get(shelf.id) ?? 0) + 1);
}
}
}
}
// For shelves not owned by the current user, fall back to the shelf's bookCount field
for (const shelf of this.shelfService.shelves()) {
if (shelf.userId !== currentUserId && shelf.id != null) {
counts.set(shelf.id, shelf.bookCount || 0);
}
}
counts.set(-1, unshelvedCount); // sentinel key for unshelved count
return counts;
});
private readonly magicShelfBookCounts = computed(() => {
const counts = new Map<number, number>();
const shelves = this.magicShelfService.shelves();
if (shelves.length === 0) return counts;
for (const shelf of shelves) {
if (shelf.id != null) {
counts.set(shelf.id, this.magicShelfService.getBookCountValue(shelf.id));
}
}
return counts;
});
readonly homeMenu = computed<NavItem[]>(() => {
this.activeLang();
return [
{
label: this.t.translate('layout.menu.home'),
items: [
{
label: this.t.translate('layout.menu.dashboard'),
icon: 'pi pi-fw pi-home',
routerLink: ['/dashboard'],
},
{
label: this.t.translate('layout.menu.allBooks'),
type: 'allBooks',
icon: 'pi pi-fw pi-book',
routerLink: ['/all-books'],
bookCount: this.bookService.books().length,
},
{
label: this.t.translate('layout.menu.series'),
type: 'series',
icon: 'pi pi-fw pi-objects-column',
routerLink: ['/series'],
bookCount: this.seriesDataService.allSeries().length,
},
{
label: this.t.translate('layout.menu.authors'),
type: 'authors',
icon: 'pi pi-fw pi-users',
routerLink: ['/authors'],
bookCount: this.allAuthors()?.length ?? 0,
},
{
label: this.t.translate('layout.menu.notebook'),
icon: 'pi pi-fw pi-pencil',
routerLink: ['/notebook'],
}
],
},
];
});
readonly libraryMenu = computed<NavItem[]>(() => {
this.activeLang();
const libCounts = this.libraryBookCounts();
const sortedLibraries = this.sortArray(
this.libraryService.libraries(),
this.librarySortField(),
this.librarySortOrder()
);
return [
{
label: this.t.translate('layout.menu.libraries'),
type: 'library',
group: true,
hasDropDown: true,
hasCreate: true,
items: sortedLibraries.map((library) => ({
contextMenuItems: this.libraryShelfMenuService.initializeLibraryMenuItems(library),
label: library.name,
type: 'library',
icon: library.icon || undefined,
iconType: this.toNavIconType(library.iconType),
routerLink: [`/library/${library.id}/books`],
bookCount: libCounts.get(library.id ?? 0) ?? 0,
unhealthy: this.libraryHealthService.isUnhealthy(library.id ?? 0),
})),
},
];
});
readonly magicShelfMenu = computed<NavItem[]>(() => {
this.activeLang();
const sortedShelves = this.sortArray(
this.magicShelfService.shelves(),
this.magicShelfSortField(),
this.magicShelfSortOrder()
);
return [
{
label: this.t.translate('layout.menu.magicShelves'),
type: 'magicShelf',
group: true,
hasDropDown: true,
hasCreate: true,
items: sortedShelves.map((shelf) => ({
label: shelf.name,
type: 'magicShelf',
icon: shelf.icon || undefined,
iconType: this.toNavIconType(shelf.iconType),
contextMenuItems: this.libraryShelfMenuService.initializeMagicShelfMenuItems(shelf),
routerLink: [`/magic-shelf/${shelf.id}/books`],
bookCount: this.magicShelfBookCounts().get(shelf.id ?? 0) ?? 0,
})),
},
];
});
readonly shelfMenu = computed<NavItem[]>(() => {
this.activeLang();
const shelfCounts = this.shelfBookCounts();
const sortedShelves = this.sortArray(
this.shelfService.shelves(),
this.shelfSortField(),
this.shelfSortOrder()
);
const shelves = [...sortedShelves];
const koboShelfIndex = shelves.findIndex(shelf => shelf.name === 'Kobo');
let koboShelf = null;
if (koboShelfIndex !== -1) {
koboShelf = shelves.splice(koboShelfIndex, 1)[0];
}
const shelfItems = shelves.map((shelf) => ({
contextMenuItems: this.libraryShelfMenuService.initializeShelfMenuItems(shelf),
label: shelf.name,
type: 'shelf' as const,
icon: shelf.icon || undefined,
iconType: this.toNavIconType(shelf.iconType),
routerLink: [`/shelf/${shelf.id}/books`],
bookCount: shelfCounts.get(shelf.id ?? 0) ?? 0,
}));
const items: NavItem[] = [{
label: this.t.translate('layout.menu.unshelved'),
type: 'shelf',
icon: 'pi pi-inbox',
iconType: 'PRIME_NG',
routerLink: ['/unshelved-books'],
bookCount: shelfCounts.get(-1) ?? 0,
}];
if (koboShelf) {
items.push({
label: koboShelf.name,
type: 'shelf',
icon: koboShelf.icon || undefined,
iconType: this.toNavIconType(koboShelf.iconType),
routerLink: [`/shelf/${koboShelf.id}/books`],
bookCount: shelfCounts.get(koboShelf.id ?? 0) ?? 0,
});
}
items.push(...shelfItems);
return [
{
type: 'shelf',
group: true,
label: this.t.translate('layout.menu.shelves'),
hasDropDown: true,
hasCreate: true,
items,
},
];
});
private readonly syncSortPreferencesEffect = effect(() => {
const user = this.currentUser();
if (!user) {
return;
}
if (user.userSettings.sidebarLibrarySorting) {
this.librarySortField.set(this.validateSortField(user.userSettings.sidebarLibrarySorting.field));
this.librarySortOrder.set(this.validateSortOrder(user.userSettings.sidebarLibrarySorting.order));
}
if (user.userSettings.sidebarShelfSorting) {
this.shelfSortField.set(this.validateSortField(user.userSettings.sidebarShelfSorting.field));
this.shelfSortOrder.set(this.validateSortOrder(user.userSettings.sidebarShelfSorting.order));
}
if (user.userSettings.sidebarMagicShelfSorting) {
this.magicShelfSortField.set(this.validateSortField(user.userSettings.sidebarMagicShelfSorting.field));
this.magicShelfSortOrder.set(this.validateSortOrder(user.userSettings.sidebarMagicShelfSorting.order));
}
});
onSidebarWidthChange(): void {
document.documentElement.style.setProperty('--sidebar-width', this.sidebarWidth + 'px');
}
saveSidebarWidth(): void {
this.localStorageService.set('sidebarWidth', this.sidebarWidth);
}
openChangelogDialog() {
this.dialogLauncherService.openVersionChangelogDialog();
}
getVersionUrl(version: string | undefined): string {
if (!version) return '#';
return version.startsWith('v')
? `https://github.com/grimmory-tools/grimmory/releases/tag/${version}`
: `https://github.com/grimmory-tools/grimmory/commit/${version}`;
}
isSemanticVersion(version: string | undefined): boolean {
if (!version) return false;
const semanticVersionPattern = /^v\d+\.\d+\.\d+$/;
return semanticVersionPattern.test(version);
}
private sortArray<T extends { name?: string | null; id?: number | null }>(
items: T[],
field: 'name' | 'id',
order: 'asc' | 'desc'
): T[] {
const sorted = [...items].sort((a, b) => {
if (field === 'id') {
return (a.id ?? 0) - (b.id ?? 0);
}
return (a.name ?? '').localeCompare(b.name ?? '');
});
return order === 'desc' ? sorted.reverse() : sorted;
}
private validateSortField(field: string): 'name' | 'id' {
return field === 'id' ? 'id' : 'name';
}
private validateSortOrder(order: string): 'asc' | 'desc' {
return order === 'desc' ? 'desc' : 'asc';
}
private toNavIconType(iconType: string | null | undefined): NavIconType | undefined {
return iconType === 'PRIME_NG' || iconType === 'CUSTOM_SVG' ? iconType : undefined;
}
}
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import { TestBed } from '@angular/core/testing';
import { Router, NavigationEnd } from '@angular/router';
import { Subject } from 'rxjs';
import { MenuService } from './app.menu.service';
describe('MenuService', () => {
it('exposes the current path from the router URL', () => {
const routerEvents = new Subject<unknown>();
TestBed.configureTestingModule({
providers: [
MenuService,
{
provide: Router,
useValue: {
url: '/dashboard?tab=recent',
events: routerEvents.asObservable(),
},
},
],
});
const service = TestBed.inject(MenuService);
expect(service.currentPath()).toBe('/dashboard');
});
it('updates currentPath on NavigationEnd', () => {
const routerEvents = new Subject<unknown>();
TestBed.configureTestingModule({
providers: [
MenuService,
{
provide: Router,
useValue: {
url: '/',
events: routerEvents.asObservable(),
},
},
],
});
const service = TestBed.inject(MenuService);
routerEvents.next(new NavigationEnd(1, '/library/1/books', '/library/1/books'));
expect(service.currentPath()).toBe('/library/1/books');
});
});
@@ -0,0 +1,25 @@
import { inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class MenuService {
private readonly router = inject(Router);
/** Current URL path (without query string), updated once per navigation. */
readonly currentPath = signal(this.router.url.split('?')[0]);
constructor() {
this.router.events
.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
takeUntilDestroyed()
)
.subscribe((event) => {
this.currentPath.set(event.urlAfterRedirects.split('?')[0]);
});
}
}
@@ -0,0 +1,107 @@
<ng-container>
@if (root) {
@if (item.hasDropDown) {
<div class="layout-menuitem-root-text root-item-with-dropdown">
<div class="root-item-label-container">
<div>{{ item.label }}</div>
@if (item.hasCreate) {
<button
type="button"
class="plus-icon-button"
[attr.aria-label]="item.label"
(click)="openDialog(item)"
>
<i class="pi pi-plus plus-icon" aria-hidden="true"></i>
</button>
}
</div>
<button
type="button"
class="expand-icon-button"
[attr.aria-label]="item.label"
[attr.aria-expanded]="expanded"
(click)="toggleExpand()"
>
<i
[ngClass]="{
'pi': true,
'pi-angle-up': expanded,
'pi-angle-down': !expanded
}"
class="expand-icon"
aria-hidden="true"
></i>
</button>
</div>
} @else {
<div class="layout-menuitem-root-text root-item">
<div>{{ item.label }}</div>
</div>
}
}
<div>
<div
class="menu-item-container"
[class.active-route-container]="isRouteActive()"
[class.menu-open]="menuOpen"
>
@if (item.routerLink && !item.items) {
<a
class="menu-item-link"
[class.active-route]="isRouteActive()"
[routerLink]="item.routerLink"
tabindex="0"
>
@if (item.unhealthy) {
<span
class="library-health-dot"
[pTooltip]="'common.libraryPathInaccessible' | transloco"
tooltipPosition="right"
></span>
}
<app-icon-display
[icon]="getIconSelection()"
iconClass="layout-menuitem-icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
<span class="layout-menuitem-text menu-item-text">
{{ item.label }}
</span>
</a>
}
<span class="menu-item-end-content">
@if (shouldShowContextMenuButton()) {
<button
type="button"
class="entity-menu-button"
[attr.aria-label]="item.label"
(click)="entitymenu.toggle($event); menuOpen = !menuOpen; $event.stopPropagation()"
>
<span class="entity-menu-button-content">
<i class="pi pi-ellipsis-v entity-menu-icon" aria-hidden="true"></i>
<span class="entity-menu-count">{{ item.bookCount?.toString() || '' }}</span>
</span>
</button>
<p-menu #entitymenu [model]="item.contextMenuItems" [popup]="true" appendTo="body" (onHide)="menuOpen = false"></p-menu>
} @else if (item.bookCount !== undefined) {
<p class="book-count">
{{ formatCount(item.bookCount) }}
</p>
}
</span>
</div>
<div [@children]="expanded ? 'expanded' : 'collapsed'" class="submenu-container">
@if (item.items) {
<ul>
@for (child of item.items; track child.routerLink?.join('/') ?? child.label; let i = $index) {
<li app-menuitem [item]="child" [index]="i" [parentKey]="key"></li>
}
</ul>
}
</div>
</div>
</ng-container>
@@ -0,0 +1,180 @@
.plus-icon-button,
.expand-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
background: none;
cursor: pointer;
}
.plus-icon {
color: var(--primary-color);
transition: color 0.2s ease;
font-size: 0.8rem;
cursor: pointer;
&:hover {
color: var(--primary-hover-color);
}
}
.root-item-with-dropdown {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
padding-top: 1rem;
}
.root-item-label-container {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
cursor: pointer;
}
.expand-icon {
color: var(--surface-500);
&:hover {
color: var(--surface-200);
}
}
.expand-icon-button {
padding-right: 0.75rem;
}
.root-item {
display: flex;
align-items: center;
justify-content: space-between;
}
.menu-item-container {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
border-radius: 8px;
cursor: pointer;
&:hover {
background-color: var(--surface-hover);
}
}
.menu-item-container.active-route-container {
background-color: color-mix(in srgb, var(--primary-color) 8%, transparent);
}
.menu-item-link {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
background-color: transparent;
&:hover,
&:focus {
background-color: transparent;
}
}
.menu-item-text {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-left: 0.35rem;
font-size: 0.985rem;
}
.menu-item-end-content {
display: flex;
align-items: center;
flex-shrink: 0;
}
.entity-menu-button {
display: flex;
align-items: center;
justify-content: center;
min-width: 2rem;
height: 30px;
padding: 0 0.55rem;
border: 0;
border-radius: 999px;
background: transparent;
color: var(--primary-color);
cursor: pointer;
font: inherit;
transition: color 0.2s ease;
}
.entity-menu-button:hover {
background-color: transparent;
color: var(--primary-hover-color);
}
.entity-menu-button-content {
display: flex;
align-items: center;
justify-content: center;
}
.entity-menu-icon {
display: none;
}
.menu-item-container:hover .entity-menu-icon,
.menu-item-container.menu-open .entity-menu-icon {
display: inline;
}
.menu-item-container:hover .entity-menu-count,
.menu-item-container.menu-open .entity-menu-count {
display: none;
}
.book-count {
color: var(--primary-color);
padding-right: 0.75rem;
transition: color 0.2s ease;
}
.menu-item-container:hover .book-count,
.menu-item-container:hover .entity-menu-button {
color: var(--primary-hover-color);
}
.submenu-container {
overflow: hidden;
}
.library-health-dot {
display: inline-block;
flex-shrink: 0;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ef4444;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
box-shadow: 0 0 0 0 rgb(239 68 68 / 70%);
}
50% {
opacity: 0.85;
box-shadow: 0 0 0 5px rgb(239 68 68 / 0%);
}
}
@@ -0,0 +1,132 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppMenuitemComponent } from './app.menuitem.component';
import { MenuService } from './app.menu.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
import { UserService } from '../../../features/settings/user-management/user.service';
describe('AppMenuitemComponent', () => {
let fixture: ComponentFixture<AppMenuitemComponent>;
let component: AppMenuitemComponent;
const menuService = {
currentPath: signal('/'),
};
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [AppMenuitemComponent],
providers: [
{ provide: MenuService, useValue: menuService },
{
provide: DialogLauncherService,
useValue: {
openLibraryCreateDialog: vi.fn(),
openMagicShelfCreateDialog: vi.fn(),
},
},
{
provide: BookDialogHelperService,
useValue: {
openShelfCreatorDialog: vi.fn(),
},
},
{
provide: UserService,
useValue: {
currentUser: signal({
permissions: {
canManageLibrary: true,
admin: true,
},
}),
},
},
],
});
TestBed.overrideComponent(AppMenuitemComponent, {
set: {
template: '',
},
});
fixture = TestBed.createComponent(AppMenuitemComponent);
component = fixture.componentInstance;
component.index = 0;
});
it('passes context menu items through to the template', () => {
const editCommand = vi.fn();
const nestedCommand = vi.fn();
component.item = {
label: 'Shelf A',
type: 'shelf',
contextMenuItems: [
{ label: 'Edit', command: editCommand },
{
label: 'More',
items: [{ label: 'Delete', command: nestedCommand }],
},
],
};
fixture.detectChanges();
const items = component.item.contextMenuItems!;
expect(items[0].label).toBe('Edit');
items[0].command?.({} as never);
expect(editCommand).toHaveBeenCalled();
expect(items[1].items?.[0].label).toBe('Delete');
items[1].items?.[0].command?.({} as never);
expect(nestedCommand).toHaveBeenCalled();
});
it('hides the context menu button for items without context menu actions', () => {
component.item = {
label: 'Unshelved',
type: 'shelf',
};
fixture.detectChanges();
expect(component.shouldShowContextMenuButton()).toBe(false);
});
it('exposes admin and canManipulateLibrary as computed signals from UserService', () => {
component.item = { label: 'Test' };
fixture.detectChanges();
expect(component.admin()).toBe(true);
expect(component.canManipulateLibrary()).toBe(true);
});
it('reports route as active when currentPath matches item routerLink', () => {
component.item = {
label: 'Dashboard',
routerLink: ['/dashboard'],
};
menuService.currentPath.set('/dashboard');
fixture.detectChanges();
expect(component.isRouteActive()).toBe(true);
});
it('reports route as inactive when currentPath does not match', () => {
component.item = {
label: 'Dashboard',
routerLink: ['/dashboard'],
};
menuService.currentPath.set('/library/1/books');
fixture.detectChanges();
expect(component.isRouteActive()).toBe(false);
});
});
@@ -0,0 +1,117 @@
import { ChangeDetectionStrategy, Component, computed, HostBinding, inject, Input, OnInit } from '@angular/core';
import { RouterLink } from '@angular/router';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { MenuService } from './app.menu.service';
import { NgClass } from '@angular/common';
import { Menu } from 'primeng/menu';
import { UserService } from '../../../features/settings/user-management/user.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
import { IconDisplayComponent } from '../../components/icon-display/icon-display.component';
import { Tooltip } from 'primeng/tooltip';
import { IconSelection } from '../../service/icon-picker.service';
import { TranslocoPipe } from '@jsverse/transloco';
import { NavItem } from './app.menu.component';
@Component({
// Keep this attribute selector so recursive menu items remain valid <li> children.
// eslint-disable-next-line @angular-eslint/component-selector
selector: '[app-menuitem]',
templateUrl: './app.menuitem.component.html',
styleUrls: ['./app.menuitem.component.scss'],
imports: [
RouterLink,
NgClass,
Menu,
IconDisplayComponent,
Tooltip,
TranslocoPipe
],
animations: [
trigger('children', [
state('collapsed', style({
height: '0'
})),
state('expanded', style({
height: '*'
})),
transition('collapsed <=> expanded', animate('400ms cubic-bezier(0.86, 0, 0.07, 1)'))
])
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppMenuitemComponent implements OnInit {
@Input() item!: NavItem;
@Input() index!: number;
@Input() @HostBinding('class.layout-root-menuitem') root!: boolean;
@Input() parentKey!: string;
@Input() menuKey!: string;
menuOpen = false;
key: string = '';
expanded = true;
private readonly menuService = inject(MenuService);
private readonly userService = inject(UserService);
private readonly dialogLauncher = inject(DialogLauncherService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
readonly isRouteActive = computed(() => {
const route = this.item?.routerLink?.[0];
if (!route) return false;
return this.menuService.currentPath() === route;
});
readonly canManipulateLibrary = computed(() =>
this.userService.currentUser()?.permissions.canManageLibrary ?? false
);
readonly admin = computed(() =>
this.userService.currentUser()?.permissions.admin ?? false
);
ngOnInit() {
const rootKey = this.menuKey ? this.menuKey + '-' : '';
this.key = this.parentKey ? this.parentKey + '-' + this.index : rootKey + String(this.index);
}
toggleExpand() {
this.expanded = !this.expanded;
}
openDialog(item: NavItem) {
if (item.type === 'library' && this.canManipulateLibrary()) {
this.dialogLauncher.openLibraryCreateDialog();
}
if (item.type === 'magicShelf') {
this.dialogLauncher.openMagicShelfCreateDialog();
}
if (item.type === 'shelf') {
this.bookDialogHelperService.openShelfCreatorDialog();
}
}
formatCount(count: number | null | undefined): string {
if (count == null) return '0';
if (count >= 1000) return Math.floor(count / 1000) + 'K';
return count.toString();
}
getIconSelection(): IconSelection | null {
if (!this.item.icon) return null;
return {
type: this.item.iconType || 'PRIME_NG',
value: this.item.icon
};
}
hasContextMenu(): boolean {
return (this.item.contextMenuItems?.length ?? 0) > 0;
}
shouldShowContextMenuButton(): boolean {
return this.hasContextMenu()
&& (this.item.type !== 'library' || (this.admin() || this.canManipulateLibrary()));
}
}
@@ -0,0 +1,50 @@
<ng-container *transloco="let t; prefix: 'layout.changelog'">
<div class="changelog-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-sparkles header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">{{ t('title') }}</h2>
<p class="panel-description">{{ t('description') }}</p>
</div>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(click)="dialogRef.close()"
class="close-button">
</p-button>
</div>
<div class="dialog-content">
@if (loading) {
<div class="loading-state">
{{ t('loading') }}
</div>
}
@if (!loading && changelog.length === 0) {
<div class="empty-state">
{{ t('empty') }}
</div>
}
@if (!loading && changelog.length > 0) {
<div class="changelog-list">
@for (release of changelog; track release) {
<div class="release-item">
<p class="release-title">
<a [href]="release.url" target="_blank" rel="noopener noreferrer" class="release-link">
{{ release.name }} ({{ release.publishedAt | date: 'mediumDate' }})
</a>
</p>
<div [innerHTML]="markdownToHtml(release.changelog)" class="release-content"></div>
</div>
}
</div>
}
</div>
</div>
</ng-container>
@@ -0,0 +1,139 @@
@use '../../../../shared/styles/panel-shared' as panel;
.changelog-container {
display: flex;
flex-direction: column;
max-height: 90dvh;
}
.panel-header {
@include panel.panel-header;
}
.dialog-content {
padding: 1.5rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
border-radius: 0 0 10px 10px;
box-shadow: 0 2px 6px rgb(0 0 0 / 8%);
overflow-y: auto;
flex: 1;
}
.loading-state,
.empty-state {
padding: 1rem;
text-align: center;
color: var(--text-secondary-color);
}
.changelog-list {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.release-item {
padding-bottom: 1rem;
border-bottom: 1px solid var(--border-color);
&:last-child {
border-bottom: none;
}
}
.release-title {
font-weight: 700;
font-size: 1.25rem;
padding-bottom: 0.5rem;
margin: 0;
}
.release-link {
color: var(--primary-color);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.release-content {
width: 100%;
max-width: 100%;
line-height: 1.75;
color: var(--text-color);
:host ::ng-deep & {
h1, h2, h3, h4, h5, h6 {
margin-top: 1.5rem;
margin-bottom: 0.75rem;
font-weight: 600;
line-height: 1.25;
color: var(--text-color);
&:first-child {
margin-top: 0;
}
}
h3 {
margin-top: 0;
font-size: 1.125rem;
}
p {
margin-top: 0.75rem;
margin-bottom: 0.75rem;
}
ul, ol {
margin-top: 0.75rem;
margin-bottom: 0.75rem;
padding-left: 1.5rem;
}
li {
margin-top: 0.25rem;
margin-bottom: 0.25rem;
}
code {
font-size: 0.875em;
background: var(--ground-background);
padding: 0.125rem 0.375rem;
border-radius: 0.25rem;
}
pre {
margin-top: 1rem;
margin-bottom: 1rem;
padding: 1rem;
background: var(--ground-background);
border-radius: 0.5rem;
overflow-x: auto;
code {
background: transparent;
padding: 0;
}
}
a {
color: var(--primary-color);
text-decoration: underline;
&:hover {
text-decoration: none;
}
}
blockquote {
margin: 1rem 0;
padding-left: 1rem;
border-left: 3px solid var(--border-color);
color: var(--text-secondary-color);
}
}
}
@@ -0,0 +1,72 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {of, throwError} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
import {VersionService} from '../../../service/version.service';
import {VersionChangelogDialogComponent} from './version-changelog-dialog.component';
describe('VersionChangelogDialogComponent', () => {
let fixture: ComponentFixture<VersionChangelogDialogComponent>;
let component: VersionChangelogDialogComponent;
let versionService: {getChangelog: ReturnType<typeof vi.fn>};
beforeEach(async () => {
versionService = {
getChangelog: vi.fn(() => of([
{
version: '1.2.3',
name: 'Stable',
changelog: '## Added\n- New feature',
url: 'https://example.com/releases/1.2.3',
publishedAt: '2026-03-26T00:00:00Z',
},
])),
};
await TestBed.configureTestingModule({
imports: [VersionChangelogDialogComponent, getTranslocoModule()],
providers: [
{provide: VersionService, useValue: versionService},
{provide: DynamicDialogRef, useValue: {close: vi.fn()}},
],
}).compileComponents();
fixture = TestBed.createComponent(VersionChangelogDialogComponent);
component = fixture.componentInstance;
});
afterEach(() => {
vi.restoreAllMocks();
TestBed.resetTestingModule();
});
it('loads the changelog on init and clears the loading state', () => {
component.ngOnInit();
expect(versionService.getChangelog).toHaveBeenCalled();
expect(component.changelog).toHaveLength(1);
expect(component.loading).toBe(false);
});
it('clears the loading state when the changelog request fails', () => {
versionService.getChangelog.mockReturnValueOnce(
throwError(() => new Error('failed'))
);
component.ngOnInit();
expect(component.changelog).toEqual([]);
expect(component.loading).toBe(false);
});
it('converts markdown to sanitized HTML and normalizes headings to h3', () => {
const html = component.markdownToHtml('## Heading\n\n<script>alert(1)</script><b>Safe</b>');
expect(html).toContain('<h3');
expect(html).not.toContain('<h2');
expect(html).not.toContain('<script>');
expect(html).toContain('<b>Safe</b>');
});
});
@@ -0,0 +1,49 @@
import { Component, inject, OnInit } from '@angular/core';
import { ReleaseNote, VersionService } from '../../../service/version.service';
import showdown from 'showdown';
import DOMPurify from 'dompurify';
import {DatePipe} from '@angular/common';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Button} from 'primeng/button';
import {TranslocoDirective} from '@jsverse/transloco';
@Component({
selector: 'app-version-changelog-dialog',
standalone: true,
imports: [
DatePipe,
Button,
TranslocoDirective
],
templateUrl: './version-changelog-dialog.component.html',
styleUrl: './version-changelog-dialog.component.scss'
})
export class VersionChangelogDialogComponent implements OnInit {
private versionService = inject(VersionService);
dialogRef = inject(DynamicDialogRef);
changelog: ReleaseNote[] = [];
loading = true;
private converter = new showdown.Converter({ tables: true, emoji: true });
ngOnInit(): void {
this.versionService.getChangelog().subscribe({
next: (data) => {
this.changelog = data;
this.loading = false;
},
error: () => {
this.loading = false;
}
});
}
markdownToHtml(markdown: string): string {
let html = this.converter.makeHtml(markdown);
html = html.replace(/<h2\b([^>]*)>/g, '<h3$1>').replace(/<\/h2>/g, '</h3>');
return DOMPurify.sanitize(html);
}
}