refactor(ui): new icon library and user migration (#1828)

This commit is contained in:
Alex
2026-06-25 08:57:48 +01:00
committed by GitHub
parent 90fa4d7c42
commit d0d884a06b
66 changed files with 963 additions and 486 deletions
@@ -1,7 +1,6 @@
package org.booklore.model.enums;
public enum IconType {
PRIME_NG,
LUCIDE,
CUSTOM_SVG
}
@@ -4,7 +4,7 @@ import lombok.Getter;
@Getter
public enum ShelfType {
KOBO("Kobo", "pi pi-tablet");
KOBO("Kobo", "tablet");
private final String name;
private final String icon;
@@ -107,7 +107,7 @@ public class KoboSettingsService {
ShelfCreateRequest.builder()
.name(ShelfType.KOBO.getName())
.icon(ShelfType.KOBO.getIcon())
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.build()
);
}
@@ -25,7 +25,7 @@ public class UserDefaultsService {
.user(user)
.name("Favorites")
.icon("heart")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.build();
shelfRepository.save(shelf);
}
@@ -52,4 +52,4 @@ public class UserDefaultsService {
log.error("Error serializing setting {} for user {}", key, user.getUsername(), e);
}
}
}
}
@@ -0,0 +1,344 @@
-- Migrates Prime icons to Lucide. Brand-logo icons without a close Lucide replacement use the default book icon.
CREATE TEMPORARY TABLE prime_to_lucide_icon_map (
prime_icon VARCHAR(64) NOT NULL PRIMARY KEY,
lucide_icon VARCHAR(64) NOT NULL
);
INSERT INTO prime_to_lucide_icon_map (prime_icon, lucide_icon) VALUES
('address-book', 'contact'),
('align-center', 'text-align-center'),
('align-justify', 'text-align-justify'),
('align-left', 'text-align-start'),
('align-right', 'text-align-end'),
('amazon', 'book'),
('android', 'book'),
('angle-double-down', 'chevrons-down'),
('angle-double-left', 'chevrons-left'),
('angle-double-right', 'chevrons-right'),
('angle-double-up', 'chevrons-up'),
('angle-down', 'chevron-down'),
('angle-left', 'chevron-left'),
('angle-right', 'chevron-right'),
('angle-up', 'chevron-up'),
('apple', 'book'),
('arrow-circle-down', 'circle-arrow-down'),
('arrow-circle-left', 'circle-arrow-left'),
('arrow-circle-right', 'circle-arrow-right'),
('arrow-circle-up', 'circle-arrow-up'),
('arrow-down', 'arrow-down'),
('arrow-down-left', 'arrow-down-left'),
('arrow-down-left-and-arrow-up-right-to-center', 'shrink'),
('arrow-down-right', 'arrow-down-right'),
('arrow-left', 'arrow-left'),
('arrow-right', 'arrow-right'),
('arrow-right-arrow-left', 'arrow-right-left'),
('arrow-up', 'arrow-up'),
('arrow-up-left', 'arrow-up-left'),
('arrow-up-right', 'arrow-up-right'),
('arrow-up-right-and-arrow-down-left-from-center', 'expand'),
('arrows-alt', 'move'),
('arrows-h', 'move-horizontal'),
('arrows-v', 'move-vertical'),
('asterisk', 'asterisk'),
('at', 'at-sign'),
('backward', 'rewind'),
('ban', 'ban'),
('barcode', 'barcode'),
('bars', 'menu'),
('bell', 'bell'),
('bell-slash', 'bell-off'),
('bitcoin', 'bitcoin'),
('bolt', 'zap'),
('book', 'book'),
('bookmark', 'bookmark'),
('bookmark-fill', 'bookmark'),
('box', 'box'),
('briefcase', 'briefcase'),
('building', 'building'),
('building-columns', 'building-2'),
('bullseye', 'target'),
('calculator', 'calculator'),
('calendar', 'calendar'),
('calendar-clock', 'calendar-clock'),
('calendar-minus', 'calendar-minus'),
('calendar-plus', 'calendar-plus'),
('calendar-times', 'calendar-x'),
('camera', 'camera'),
('car', 'car'),
('caret-down', 'chevron-down'),
('caret-left', 'chevron-left'),
('caret-right', 'chevron-right'),
('caret-up', 'chevron-up'),
('cart-arrow-down', 'shopping-cart'),
('cart-minus', 'shopping-cart'),
('cart-plus', 'shopping-cart'),
('chart-bar', 'chart-column'),
('chart-line', 'chart-line'),
('chart-pie', 'chart-pie'),
('chart-scatter', 'chart-scatter'),
('check', 'check'),
('check-circle', 'circle-check'),
('check-square', 'square-check'),
('chevron-circle-down', 'circle-chevron-down'),
('chevron-circle-left', 'circle-chevron-left'),
('chevron-circle-right', 'circle-chevron-right'),
('chevron-circle-up', 'circle-chevron-up'),
('chevron-down', 'chevron-down'),
('chevron-left', 'chevron-left'),
('chevron-right', 'chevron-right'),
('chevron-up', 'chevron-up'),
('circle', 'circle'),
('circle-fill', 'circle'),
('circle-off', 'circle-slash'),
('circle-on', 'circle'),
('clipboard', 'clipboard'),
('clock', 'clock'),
('clone', 'copy'),
('cloud', 'cloud'),
('cloud-download', 'cloud-download'),
('cloud-upload', 'cloud-upload'),
('code', 'code'),
('cog', 'settings'),
('comment', 'message-circle'),
('comments', 'messages-square'),
('compass', 'compass'),
('copy', 'copy'),
('credit-card', 'credit-card'),
('crown', 'crown'),
('database', 'database'),
('delete-left', 'delete'),
('desktop', 'monitor'),
('directions', 'navigation'),
('directions-alt', 'navigation-2'),
('discord', 'book'),
('dollar', 'dollar-sign'),
('download', 'download'),
('eject', 'unplug'),
('ellipsis-h', 'ellipsis'),
('ellipsis-v', 'ellipsis-vertical'),
('envelope', 'mail'),
('equals', 'equal'),
('eraser', 'eraser'),
('ethereum', 'book'),
('euro', 'euro'),
('exclamation-circle', 'circle-alert'),
('exclamation-triangle', 'triangle-alert'),
('expand', 'expand'),
('external-link', 'external-link'),
('eye', 'eye'),
('eye-slash', 'eye-off'),
('facebook', 'book'),
('face-smile', 'smile'),
('fast-backward', 'skip-back'),
('fast-forward', 'skip-forward'),
('file', 'file'),
('file-arrow-up', 'file-up'),
('file-check', 'file-check'),
('file-edit', 'file-pen'),
('file-excel', 'file-spreadsheet'),
('file-export', 'file-output'),
('file-import', 'file-input'),
('file-o', 'file'),
('file-pdf', 'file-text'),
('file-plus', 'file-plus'),
('file-word', 'file-text'),
('filter', 'funnel'),
('filter-fill', 'funnel'),
('filter-slash', 'funnel-x'),
('flag', 'flag'),
('flag-fill', 'flag'),
('folder', 'folder'),
('folder-open', 'folder-open'),
('folder-plus', 'folder-plus'),
('forward', 'fast-forward'),
('gauge', 'gauge'),
('gift', 'gift'),
('github', 'book'),
('globe', 'globe'),
('google', 'book'),
('graduation-cap', 'graduation-cap'),
('hammer', 'hammer'),
('hashtag', 'hash'),
('headphones', 'headphones'),
('heart', 'heart'),
('heart-fill', 'heart'),
('history', 'history'),
('home', 'house'),
('hourglass', 'hourglass'),
('id-card', 'id-card'),
('image', 'image'),
('images', 'images'),
('instagram', 'book'),
('inbox', 'inbox'),
('indian-rupee', 'indian-rupee'),
('info', 'info'),
('info-circle', 'info'),
('key', 'key'),
('language', 'languages'),
('lightbulb', 'lightbulb'),
('link', 'link'),
('linkedin', 'book'),
('list', 'list'),
('list-check', 'list-checks'),
('lock', 'lock'),
('lock-open', 'lock-open'),
('map', 'map'),
('map-marker', 'map-pin'),
('mars', 'mars'),
('megaphone', 'megaphone'),
('microchip', 'cpu'),
('microchip-ai', 'brain-circuit'),
('microphone', 'mic'),
('microsoft', 'book'),
('minus', 'minus'),
('minus-circle', 'circle-minus'),
('mobile', 'smartphone'),
('money-bill', 'banknote'),
('moon', 'moon'),
('objects-column', 'columns-3'),
('palette', 'palette'),
('paperclip', 'paperclip'),
('paypal', 'book'),
('pause', 'pause'),
('pause-circle', 'circle-pause'),
('pen-to-square', 'square-pen'),
('pencil', 'pencil'),
('percentage', 'percent'),
('phone', 'phone'),
('pinterest', 'book'),
('play', 'play'),
('play-circle', 'circle-play'),
('plus', 'plus'),
('plus-circle', 'circle-plus'),
('pound', 'pound-sterling'),
('power-off', 'power'),
('prime', 'sparkles'),
('print', 'printer'),
('qrcode', 'qr-code'),
('question', 'circle-question-mark'),
('question-circle', 'circle-question-mark'),
('receipt', 'receipt'),
('reddit', 'book'),
('refresh', 'rotate-cw'),
('replay', 'rotate-ccw'),
('reply', 'reply'),
('save', 'save'),
('search', 'search'),
('search-minus', 'zoom-out'),
('search-plus', 'zoom-in'),
('send', 'send'),
('server', 'server'),
('share-alt', 'share-2'),
('shield', 'shield'),
('shop', 'store'),
('shopping-bag', 'shopping-bag'),
('shopping-cart', 'shopping-cart'),
('sign-in', 'log-in'),
('sign-out', 'log-out'),
('sitemap', 'network'),
('slack', 'book'),
('sliders-h', 'sliders-horizontal'),
('sliders-v', 'sliders-vertical'),
('sort', 'arrow-up-down'),
('sort-alpha-down', 'arrow-down-a-z'),
('sort-alpha-down-alt', 'arrow-down-z-a'),
('sort-alpha-up', 'arrow-up-a-z'),
('sort-alpha-up-alt', 'arrow-up-z-a'),
('sort-alt', 'arrow-up-down'),
('sort-alt-slash', 'arrow-up-down'),
('sort-amount-down', 'arrow-down-wide-narrow'),
('sort-amount-down-alt', 'arrow-down-narrow-wide'),
('sort-amount-up', 'arrow-up-narrow-wide'),
('sort-amount-up-alt', 'arrow-up-wide-narrow'),
('sort-down', 'chevron-down'),
('sort-down-fill', 'chevron-down'),
('sort-numeric-down', 'arrow-down-0-1'),
('sort-numeric-down-alt', 'arrow-down-1-0'),
('sort-numeric-up', 'arrow-up-0-1'),
('sort-numeric-up-alt', 'arrow-up-1-0'),
('sort-up', 'chevron-up'),
('sort-up-fill', 'chevron-up'),
('sparkles', 'sparkles'),
('spinner', 'loader-circle'),
('spinner-dotted', 'loader'),
('star', 'star'),
('star-fill', 'star'),
('star-half', 'star-half'),
('star-half-fill', 'star-half'),
('step-backward', 'skip-back'),
('step-backward-alt', 'skip-back'),
('step-forward', 'skip-forward'),
('step-forward-alt', 'skip-forward'),
('stop', 'square'),
('stop-circle', 'circle-stop'),
('stopwatch', 'timer'),
('sun', 'sun'),
('sync', 'refresh-cw'),
('table', 'table'),
('tablet', 'tablet'),
('tag', 'tag'),
('tags', 'tags'),
('telegram', 'book'),
('th-large', 'layout-grid'),
('thumbs-down', 'thumbs-down'),
('thumbs-down-fill', 'thumbs-down'),
('thumbs-up', 'thumbs-up'),
('thumbs-up-fill', 'thumbs-up'),
('thumbtack', 'pin'),
('ticket', 'ticket'),
('tiktok', 'book'),
('times', 'x'),
('times-circle', 'circle-x'),
('trash', 'trash-2'),
('trophy', 'trophy'),
('truck', 'truck'),
('turkish-lira', 'turkish-lira'),
('twitch', 'book'),
('twitter', 'book'),
('undo', 'undo'),
('unlock', 'lock-open'),
('upload', 'upload'),
('user', 'user'),
('user-edit', 'user-pen'),
('user-minus', 'user-minus'),
('user-plus', 'user-plus'),
('users', 'users'),
('venus', 'venus'),
('verified', 'badge-check'),
('video', 'video'),
('vimeo', 'book'),
('volume-down', 'volume-1'),
('volume-off', 'volume-x'),
('volume-up', 'volume-2'),
('wallet', 'wallet'),
('warehouse', 'warehouse'),
('wave-pulse', 'activity'),
('whatsapp', 'book'),
('wifi', 'wifi'),
('window-maximize', 'maximize'),
('window-minimize', 'minimize'),
('wrench', 'wrench'),
('youtube', 'book');
UPDATE library
LEFT JOIN prime_to_lucide_icon_map
ON REPLACE(REPLACE(library.icon, 'pi pi-', ''), 'pi-', '') = prime_to_lucide_icon_map.prime_icon
SET library.icon = COALESCE(prime_to_lucide_icon_map.lucide_icon, IF(library.icon IS NULL, NULL, 'book')),
library.icon_type = IF(library.icon IS NULL, NULL, 'LUCIDE')
WHERE library.icon_type = 'PRIME_NG';
UPDATE shelf
LEFT JOIN prime_to_lucide_icon_map
ON REPLACE(REPLACE(shelf.icon, 'pi pi-', ''), 'pi-', '') = prime_to_lucide_icon_map.prime_icon
SET shelf.icon = COALESCE(prime_to_lucide_icon_map.lucide_icon, IF(shelf.icon IS NULL, NULL, 'book')),
shelf.icon_type = IF(shelf.icon IS NULL, NULL, 'LUCIDE')
WHERE shelf.icon_type = 'PRIME_NG';
UPDATE magic_shelf
LEFT JOIN prime_to_lucide_icon_map
ON REPLACE(REPLACE(magic_shelf.icon, 'pi pi-', ''), 'pi-', '') = prime_to_lucide_icon_map.prime_icon
SET magic_shelf.icon = COALESCE(prime_to_lucide_icon_map.lucide_icon, IF(magic_shelf.icon IS NULL, NULL, 'book')),
magic_shelf.icon_type = IF(magic_shelf.icon IS NULL, NULL, 'LUCIDE')
WHERE magic_shelf.icon_type = 'PRIME_NG';
DROP TEMPORARY TABLE prime_to_lucide_icon_map;
@@ -77,7 +77,7 @@ class MagicShelfServiceTest {
MagicShelf dto = new MagicShelf();
dto.setName("Favorites");
dto.setIcon("star");
dto.setIconType(IconType.PRIME_NG);
dto.setIconType(IconType.LUCIDE);
dto.setFilterJson("{\"rating\": 5}");
dto.setIsPublic(false);
@@ -93,7 +93,7 @@ class MagicShelfServiceTest {
assertNotNull(result);
assertEquals("star", result.getIcon());
assertEquals(IconType.PRIME_NG, result.getIconType());
assertEquals(IconType.LUCIDE, result.getIconType());
}
@Test
@@ -103,7 +103,7 @@ class MagicShelfServiceTest {
.userId(1L)
.name("Old Shelf")
.icon("star")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.filterJson("{\"status\": \"reading\"}")
.build();
@@ -137,7 +137,7 @@ class MagicShelfServiceTest {
.userId(1L)
.name("Old Shelf")
.icon("star")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.filterJson("{\"status\": \"reading\"}")
.build();
@@ -170,7 +170,7 @@ class MagicShelfServiceTest {
.userId(1L)
.name("Shelf With Icon")
.icon("heart")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.filterJson("{}")
.build();
@@ -84,7 +84,7 @@ class ShelfServiceTest {
ShelfCreateRequest request = ShelfCreateRequest.builder()
.name("My Shelf")
.icon("heart")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
@@ -92,7 +92,7 @@ class ShelfServiceTest {
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
when(shelfRepository.save(any(ShelfEntity.class))).thenAnswer(invocation -> invocation.getArgument(0));
when(shelfMapper.toShelf(any(ShelfEntity.class))).thenReturn(
Shelf.builder().name("My Shelf").icon("heart").iconType(IconType.PRIME_NG).build());
Shelf.builder().name("My Shelf").icon("heart").iconType(IconType.LUCIDE).build());
shelfService.createShelf(request);
@@ -101,7 +101,7 @@ class ShelfServiceTest {
ShelfEntity saved = captor.getValue();
assertEquals("heart", saved.getIcon());
assertEquals(IconType.PRIME_NG, saved.getIconType());
assertEquals(IconType.LUCIDE, saved.getIconType());
}
@Test
@@ -110,7 +110,7 @@ class ShelfServiceTest {
.id(1L)
.name("Old Shelf")
.icon("star")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.user(userEntity)
.build();
@@ -141,7 +141,7 @@ class ShelfServiceTest {
.id(1L)
.name("Old Shelf")
.icon("star")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.user(userEntity)
.build();
@@ -88,7 +88,7 @@ class LibraryServiceIconTest {
.id(1L)
.name("My Library")
.icon("book")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.libraryPaths(new ArrayList<>())
.watch(false)
.build();
@@ -122,7 +122,7 @@ class LibraryServiceIconTest {
.id(1L)
.name("My Library")
.icon("book")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.libraryPaths(new ArrayList<>())
.watch(false)
.build();
@@ -156,7 +156,7 @@ class LibraryServiceIconTest {
.id(1L)
.name("Library With Icon")
.icon("star")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.libraryPaths(new ArrayList<>())
.watch(false)
.build();
@@ -218,7 +218,7 @@ class LibraryServiceIconTest {
CreateLibraryRequest request = CreateLibraryRequest.builder()
.name("Icon Library")
.icon("book")
.iconType(IconType.PRIME_NG)
.iconType(IconType.LUCIDE)
.paths(Collections.emptyList())
.watch(false)
.build();
@@ -231,7 +231,7 @@ class LibraryServiceIconTest {
return entity;
});
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(
Library.builder().name("Icon Library").icon("book").iconType(IconType.PRIME_NG).build());
Library.builder().name("Icon Library").icon("book").iconType(IconType.LUCIDE).build());
libraryService.createLibrary(request);
@@ -240,6 +240,6 @@ class LibraryServiceIconTest {
LibraryEntity saved = captor.getValue();
assertEquals("book", saved.getIcon());
assertEquals(IconType.PRIME_NG, saved.getIconType());
assertEquals(IconType.LUCIDE, saved.getIconType());
}
}
@@ -46,7 +46,7 @@ class UserDefaultsServiceTest {
ShelfEntity saved = captor.getValue();
assertEquals("Favorites", saved.getName());
assertEquals("heart", saved.getIcon());
assertEquals(IconType.PRIME_NG, saved.getIconType());
assertEquals(IconType.LUCIDE, saved.getIconType());
assertEquals(user, saved.getUser());
}
+5
View File
@@ -50,6 +50,11 @@
"glob": "**/*",
"input": "node_modules/@embedpdf/snippet/dist/",
"output": "/assets/embedpdf/"
},
{
"glob": "**/*.svg",
"input": "node_modules/lucide-static/icons",
"output": "/assets/lucide/"
}
],
"styles": [
+2
View File
@@ -35,6 +35,7 @@
"@embedpdf/pdfium": "2.14.4",
"@embedpdf/snippet": "2.14.4",
"@jsverse/transloco": "^8.4.0",
"@lucide/angular": "^1.18.0",
"@primeuix/themes": "^2.0.3",
"@stomp/rx-stomp": "^2.4.0",
"@stomp/stompjs": "^7.3.0",
@@ -47,6 +48,7 @@
"class-variance-authority": "^0.7.1",
"date-fns": "^4.4.0",
"dompurify": "^3.4.10",
"lucide-static": "1.18.0",
"markdown-it": "^14.2.0",
"ng-lazyload-image": "^9.1.3",
"ng2-charts": "^10.0.0",
@@ -196,7 +196,7 @@ describe('ShelfAssignerComponent', () => {
]);
});
it('maps custom svg and PrimeNG shelf icons to icon-display selections', () => {
it('maps custom svg and Lucide shelf icons to icon-display selections', () => {
const {component} = createHarness();
expect(component.getShelfIcon(createShelf({
@@ -207,11 +207,11 @@ describe('ShelfAssignerComponent', () => {
value: 'custom-icons/moon.svg',
});
expect(component.getShelfIcon(createShelf({
iconType: 'PRIME_NG',
iconType: 'LUCIDE',
icon: 'bookmark',
}))).toEqual({
type: 'PRIME_NG',
value: 'pi pi-bookmark',
type: 'LUCIDE',
value: 'bookmark',
});
});
@@ -13,11 +13,11 @@ import {BookDialogHelperService} from '../book-browser/book-dialog-helper.servic
import {LoadingService} from '../../../../core/services/loading.service';
import {UserService} from '../../../settings/user-management/user.service';
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
import {IconSelection} from '../../../../shared/service/icon-picker.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {InputText} from 'primeng/inputtext';
import {IconField} from 'primeng/iconfield';
import {InputIcon} from 'primeng/inputicon';
import {IconSelection, toIconSelection} from '../../../../shared/icons/icon-selection';
@Component({
selector: 'app-shelf-assigner',
@@ -129,12 +129,8 @@ export class ShelfAssignerComponent {
return this.selectedShelves.some(s => s.id === shelf.id);
}
getShelfIcon(shelf: Shelf): IconSelection {
if (shelf.iconType === 'CUSTOM_SVG') {
return {type: 'CUSTOM_SVG', value: shelf.icon ?? ""};
} else {
return {type: 'PRIME_NG', value: `pi pi-${shelf.icon}`};
}
getShelfIcon(shelf: Shelf): IconSelection | null {
return shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : null;
}
filterShelves(shelves: Shelf[]): Shelf[] {
@@ -69,8 +69,8 @@
<div class="icon-info">
<span class="icon-label">{{ t('selectedIcon') }}</span>
<span class="icon-name">
@if (selectedIcon.type === 'PRIME_NG') {
{{ selectedIcon.value }}
@if (selectedIcon.type === 'CUSTOM_SVG') {
{{ t('customSvg') }}
} @else {
{{ selectedIcon.value }}
}
@@ -5,7 +5,8 @@ import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Observable, of, throwError} from 'rxjs';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service';
import {IconPickerService} from '../../../../shared/service/icon-picker.service';
import {IconSelection} from '../../../../shared/icons/icon-selection';
import {UserService} from '../../../settings/user-management/user.service';
import {Shelf} from '../../model/shelf.model';
import {ShelfService} from '../../service/shelf.service';
@@ -67,8 +68,8 @@ describe('ShelfCreatorComponent', () => {
it('picks an icon through the injected icon picker and ignores empty selections', () => {
const pickedIcon: IconSelection = {
type: 'PRIME_NG',
value: 'pi pi-star',
type: 'LUCIDE',
value: 'star',
};
const {component, iconPickerService} = createHarness({
iconPickerResult: pickedIcon,
@@ -114,16 +115,16 @@ describe('ShelfCreatorComponent', () => {
component.shelfName = 'Weekend Reads';
component.isPublic = true;
component.selectedIcon = {
type: 'PRIME_NG',
value: 'pi pi-bookmark',
type: 'LUCIDE',
value: 'bookmark',
};
component.createShelf();
expect(createShelf).toHaveBeenCalledWith({
name: 'Weekend Reads',
icon: 'pi pi-bookmark',
iconType: 'PRIME_NG',
icon: 'bookmark',
iconType: 'LUCIDE',
publicShelf: true,
});
expect(translate).toHaveBeenCalledWith('common.success');
@@ -2,7 +2,8 @@ import {Component, inject} from '@angular/core';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {MessageService} from 'primeng/api';
import {ShelfService} from '../../service/shelf.service';
import {IconPickerService, IconSelection} from '../../../../shared/service/icon-picker.service';
import {IconPickerService} from '../../../../shared/service/icon-picker.service';
import {IconSelection} from '../../../../shared/icons/icon-selection';
import {Shelf} from '../../model/shelf.model';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
@@ -6,7 +6,8 @@ import {Observable, of, throwError} from 'rxjs';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service';
import {IconPickerService} from '../../../../shared/service/icon-picker.service';
import {IconSelection} from '../../../../shared/icons/icon-selection';
import {UserService} from '../../../settings/user-management/user.service';
import {Shelf} from '../../model/shelf.model';
import {ShelfService} from '../../service/shelf.service';
@@ -71,12 +72,12 @@ describe('ShelfEditDialogComponent', () => {
};
}
it('hydrates the dialog from a matching PrimeNG shelf', () => {
it('hydrates the dialog from a matching Lucide shelf', () => {
const shelf = createShelf({
id: 42,
name: 'Queue',
icon: 'bookmark',
iconType: 'PRIME_NG',
iconType: 'LUCIDE',
publicShelf: true,
});
@@ -89,8 +90,8 @@ describe('ShelfEditDialogComponent', () => {
expect(component.shelfName).toBe('Queue');
expect(component.isPublic).toBe(true);
expect(component.selectedIcon).toEqual({
type: 'PRIME_NG',
value: 'pi pi-bookmark',
type: 'LUCIDE',
value: 'bookmark',
});
});
@@ -125,7 +126,7 @@ describe('ShelfEditDialogComponent', () => {
id: 11,
name: 'Should Not Replace',
icon: 'bookmark',
iconType: 'PRIME_NG',
iconType: 'LUCIDE',
publicShelf: true,
}),
]);
@@ -141,8 +142,8 @@ describe('ShelfEditDialogComponent', () => {
it('picks and clears icons through the dialog-local icon selection methods', () => {
const pickedIcon: IconSelection = {
type: 'PRIME_NG',
value: 'pi pi-star',
type: 'LUCIDE',
value: 'star',
};
const {component, iconPickerService} = createHarness({
shelvesData: [createShelf()],
@@ -166,16 +167,16 @@ describe('ShelfEditDialogComponent', () => {
component.shelfName = 'Renamed Shelf';
component.isPublic = true;
component.selectedIcon = {
type: 'PRIME_NG',
value: 'pi pi-heart',
type: 'LUCIDE',
value: 'heart',
};
component.save();
expect(updateShelf).toHaveBeenCalledWith({
name: 'Renamed Shelf',
icon: 'pi pi-heart',
iconType: 'PRIME_NG',
icon: 'heart',
iconType: 'LUCIDE',
publicShelf: true,
}, 7);
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
@@ -7,11 +7,12 @@ import {InputText} from 'primeng/inputtext';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Shelf} from '../../model/shelf.model';
import {MessageService} from 'primeng/api';
import {IconPickerService, IconSelection} from '../../../../shared/service/icon-picker.service';
import {IconPickerService} from '../../../../shared/service/icon-picker.service';
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
import {Checkbox} from 'primeng/checkbox';
import {UserService} from '../../../settings/user-management/user.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {IconSelection, toIconSelection} from '../../../../shared/icons/icon-selection';
@Component({
selector: 'app-shelf-edit-dialog',
@@ -63,11 +64,7 @@ export class ShelfEditDialogComponent implements OnInit {
this.shelfName = shelf.name;
this.isPublic = shelf.publicShelf ?? false;
if (shelf.iconType && shelf.icon) {
if (shelf.iconType === 'PRIME_NG') {
this.selectedIcon = {type: 'PRIME_NG', value: `pi pi-${shelf.icon}`};
} else {
this.selectedIcon = {type: 'CUSTOM_SVG', value: shelf.icon};
}
this.selectedIcon = toIconSelection(shelf.icon, shelf.iconType);
}
}, {injector: this.injector});
}
@@ -1,5 +1,6 @@
import {SortOption} from './sort.model';
import {BookType} from './book.model';
import {IconType} from '../../../shared/icons/icon-selection';
export type MetadataSource = 'EMBEDDED' | 'SIDECAR' | 'PREFER_SIDECAR' | 'PREFER_EMBEDDED' | 'NONE';
@@ -9,7 +10,7 @@ export interface Library {
id?: number;
name: string;
icon?: string | null;
iconType?: 'PRIME_NG' | 'CUSTOM_SVG' | null;
iconType?: IconType | null;
watch: boolean;
fileNamingPattern?: string;
sort?: SortOption;
@@ -1,4 +1,5 @@
import {SortOption} from './sort.model';
import {IconType} from '../../../shared/icons/icon-selection';
export type ShelfSystemKey = 'kobo';
@@ -6,7 +7,7 @@ export interface Shelf {
id?: number;
name: string;
icon?: string | null;
iconType?: 'PRIME_NG' | 'CUSTOM_SVG' | null;
iconType?: IconType | null;
sort?: SortOption;
publicShelf?: boolean;
userId?: number;
@@ -5,7 +5,7 @@
<!-- iOS needs both type="search" and a form with an action attribute. -->
<form ngNoForm action="." class="command-palette-form" (submit)="$event.preventDefault()">
<div class="command-palette-input-row">
<i class="pi pi-search" aria-hidden="true"></i>
<svg lucideSearch class="command-palette-search-icon" aria-hidden="true"></svg>
<input
#paletteInput
type="search"
@@ -27,7 +27,7 @@
[attr.aria-label]="'close' | transloco"
(click)="svc.hide()"
>
<i class="pi pi-times" aria-hidden="true"></i>
<svg lucideX aria-hidden="true"></svg>
</button>
</div>
</form>
@@ -86,14 +86,12 @@
</div>
</ng-container>
} @else {
@if (item.icon) {
<app-icon-display
class="command-palette-item-icon"
[icon]="item.icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
}
<app-icon-display
class="command-palette-item-icon"
[icon]="item.icon ?? null"
size="18px"
[displayEmpty]="true"
></app-icon-display>
<span class="command-palette-item-title">{{ item.title }}</span>
@if (item.subtitle) {
<span class="command-palette-item-subtitle">{{ item.subtitle }}</span>
@@ -36,9 +36,11 @@
gap: var(--space-3);
padding: var(--space-4) var(--space-5);
i {
.command-palette-search-icon {
flex-shrink: 0;
width: 1.125rem;
height: 1.125rem;
color: var(--color-text-secondary);
font-size: var(--app-text-lg);
}
}
@@ -88,8 +90,9 @@
outline-offset: 2px;
}
i {
font-size: 1.0938rem;
svg {
width: 1.0938rem;
height: 1.0938rem;
}
}
@@ -295,12 +298,12 @@
0
calc(0.6563rem + env(safe-area-inset-left));
> .pi-search {
> .command-palette-search-icon {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 2.1875rem;
width: 1.125rem;
}
}
@@ -7,6 +7,7 @@ import { filter, take } from 'rxjs/operators';
import { FormsModule } from '@angular/forms';
import { TranslocoDirective, TranslocoPipe } from '@jsverse/transloco';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { LucideSearch, LucideX } from '@lucide/angular';
import { CoverPlaceholderComponent } from '../../shared/components/cover-generator/cover-generator.component';
import { IconDisplayComponent } from '../../shared/components/icon-display/icon-display.component';
@@ -17,7 +18,7 @@ import { CommandPaletteService } from './command-palette.service';
@Component({
selector: 'app-command-palette',
standalone: true,
imports: [A11yModule, OverlayModule, FormsModule, TranslocoDirective, TranslocoPipe, IconDisplayComponent, CoverPlaceholderComponent],
imports: [A11yModule, OverlayModule, FormsModule, TranslocoDirective, TranslocoPipe, IconDisplayComponent, CoverPlaceholderComponent, LucideSearch, LucideX],
templateUrl: './command-palette.component.html',
styleUrl: './command-palette.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
@@ -1,4 +1,4 @@
import { IconSelection } from '../../shared/service/icon-picker.service';
import { IconSelection } from '../../shared/icons/icon-selection';
export type PaletteItemKind =
| 'action'
@@ -14,7 +14,7 @@ import { ShelfService } from '../book/service/shelf.service';
import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
import { UrlHelperService } from '../../shared/service/url-helper.service';
import { UserService } from '../settings/user-management/user.service';
import { IconService } from '../../shared/services/icon.service';
import { CustomSvgService } from '../../shared/services/custom-svg.service';
import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
import { CommandPaletteService } from './command-palette.service';
@@ -68,7 +68,7 @@ describe('CommandPaletteService', () => {
{ provide: UserService, useValue: { currentUser: signal({ permissions: {} }) } },
{ provide: MessageService, useValue: { add: vi.fn() } },
{ provide: UrlHelperService, useValue: urlHelper },
{ provide: IconService, useValue: { getSvgIconContent: vi.fn(() => of('')) } },
{ provide: CustomSvgService, useValue: { getSvgIconContent: vi.fn(() => of('')) } },
{
provide: DialogLauncherService,
useValue: {
@@ -15,10 +15,10 @@ import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
import { UserService } from '../settings/user-management/user.service';
import { NavItem } from '../../shared/layout/navigation/nav-item.model';
import { buildAllNavPages, buildQuickActionNavItems } from '../../shared/layout/navigation/nav-catalog';
import { IconSelection } from '../../shared/service/icon-picker.service';
import { UrlHelperService } from '../../shared/service/url-helper.service';
import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
import { IconService } from '../../shared/services/icon.service';
import { CustomSvgService } from '../../shared/services/custom-svg.service';
import { toIconSelection } from '../../shared/icons/icon-selection';
import { PaletteGroup, PaletteItem, PaletteItemKind } from './command-palette.model';
@@ -49,7 +49,7 @@ export class CommandPaletteService {
private readonly libraryService = inject(LibraryService);
private readonly dialogLauncherService = inject(DialogLauncherService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
private readonly iconService = inject(IconService);
private readonly customSvgService = inject(CustomSvgService);
private readonly urlHelper = inject(UrlHelperService);
private readonly messageService = inject(MessageService);
@@ -106,7 +106,7 @@ export class CommandPaletteService {
for (const item of items) {
if (item.icon?.type === 'CUSTOM_SVG' && !seen.has(item.icon.value)) {
seen.add(item.icon.value);
this.iconService.getSvgIconContent(item.icon.value).subscribe({ error: () => undefined });
this.customSvgService.getSvgIconContent(item.icon.value).subscribe({ error: () => undefined });
}
}
};
@@ -235,7 +235,7 @@ export class CommandPaletteService {
id: `shelf:${shelf.id}`,
kind: 'shelf' as const,
title: shelf.name,
icon: this.iconSelectionFor(shelf.icon, shelf.iconType, 'pi-bookmark'),
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
searchText: normalizeSearchTerm(shelf.name),
route: [`/shelf/${shelf.id}/books`],
}))
@@ -248,7 +248,7 @@ export class CommandPaletteService {
id: `magic-shelf:${shelf.id}`,
kind: 'magicShelf' as const,
title: shelf.name,
icon: this.iconSelectionFor(shelf.icon, shelf.iconType, 'pi-sparkles'),
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
searchText: normalizeSearchTerm(shelf.name),
route: [`/magic-shelf/${shelf.id}/books`],
}))
@@ -261,7 +261,7 @@ export class CommandPaletteService {
id: `library:${library.id}`,
kind: 'library' as const,
title: library.name,
icon: this.iconSelectionFor(library.icon, library.iconType, 'pi-folder'),
icon: library.icon ? toIconSelection(library.icon, library.iconType) : undefined,
searchText: normalizeSearchTerm(library.name),
route: [`/library/${library.id}/books`],
}))
@@ -271,16 +271,6 @@ export class CommandPaletteService {
this.trimmedQuery().length >= MIN_BOOK_SEARCH_LENGTH ? this.localBookItems() : []
);
private iconSelectionFor(
value: string | null | undefined,
iconType: string | null | undefined,
fallback: string,
): IconSelection {
if (!value) return { type: 'PRIME_NG', value: fallback };
if (iconType === 'CUSTOM_SVG') return { type: 'CUSTOM_SVG', value };
return { type: 'PRIME_NG', value };
}
private toPaletteBookItem(book: Book): PaletteItem {
const metadata = book.metadata;
const title = metadata?.title ?? book.primaryFile?.fileName ?? book.fileName ?? '';
@@ -294,7 +284,7 @@ export class CommandPaletteService {
id: `book:${book.id}`,
kind: 'book',
title,
icon: { type: 'PRIME_NG', value: 'pi-book' },
icon: { type: 'LUCIDE', value: 'book-open' },
searchText: normalizeSearchTerm(haystack),
route: ['/book', book.id],
queryParams: { tab: 'view' },
@@ -316,7 +306,7 @@ export class CommandPaletteService {
id: `${kind}:${item.id}`,
kind,
title: item.label,
icon: item.icon ? { type: 'PRIME_NG', value: item.icon } : undefined,
icon: item.icon ? toIconSelection(item.icon, item.iconType) : undefined,
searchText: normalizeSearchTerm(item.label),
route: item.routerLink,
command: item.action,
@@ -50,27 +50,27 @@
<span>
{{ t('iconLabel') }}
</span>
@if (!selectedIcon()) {
<button class="icon-picker-trigger" (click)="openIconPicker()" type="button">
<i class="pi pi-plus"></i>
<span>{{ t('chooseIcon') }}</span>
</button>
} @else {
@if (selectedIcon(); as icon) {
<div class="icon-selected">
<div class="icon-preview">
<app-icon-display [icon]="selectedIcon()!" size="16px" />
<app-icon-display [icon]="icon" size="16px" />
</div>
<span class="icon-value">
@if (selectedIcon()!.type === 'PRIME_NG') {
{{ selectedIcon()!.value }}
} @else {
@if (icon.type === 'CUSTOM_SVG') {
{{ t('customSvg') }}
} @else {
{{ icon.value }}
}
</span>
<button class="icon-clear" (click)="clearSelectedIcon()" type="button">
<i class="pi pi-times"></i>
</button>
</div>
} @else {
<button class="icon-picker-trigger" (click)="openIconPicker()" type="button">
<i class="pi pi-plus"></i>
<span>{{ t('chooseIcon') }}</span>
</button>
}
</div>
</div>
@@ -10,7 +10,7 @@ import { Library, MetadataSource, OrganizationMode } from '../book/model/library
import { BookType } from '../book/model/book.model';
import { ToggleSwitch } from 'primeng/toggleswitch';
import { Tooltip } from 'primeng/tooltip';
import { IconPickerService, IconSelection } from '../../shared/service/icon-picker.service';
import { IconPickerService } from '../../shared/service/icon-picker.service';
import { Button } from 'primeng/button';
import { IconDisplayComponent } from '../../shared/components/icon-display/icon-display.component';
import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
@@ -20,6 +20,7 @@ import { Checkbox } from 'primeng/checkbox';
import { Select } from 'primeng/select';
import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco';
import { LibraryImportProgressService } from '../../shared/service/library-import-progress.service';
import { IconSelection, toIconSelection } from '../../shared/icons/icon-selection';
interface FormatEntry { type: BookType; label: string }
@@ -139,12 +140,7 @@ export class LibraryCreatorComponent {
this.folders.set(paths.map(p => p.path));
if (icon != null && iconType) {
if (iconType === 'CUSTOM_SVG') {
this.selectedIcon.set({ type: 'CUSTOM_SVG', value: icon });
} else {
const value = icon.slice(0, 6) === 'pi pi-' ? icon : `pi pi-${icon}`;
this.selectedIcon.set({ type: 'PRIME_NG', value });
}
this.selectedIcon.set(toIconSelection(icon, iconType));
}
if (formatPriority && formatPriority.length > 0) {
@@ -14,7 +14,7 @@ import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MultiSelect} from 'primeng/multiselect';
import {AutoComplete} from 'primeng/autocomplete';
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, RELATIVE_DATE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../service/magic-shelf-utils';
import {IconPickerService, IconSelection} from '../../../shared/service/icon-picker.service';
import {IconPickerService} from '../../../shared/service/icon-picker.service';
import {CheckboxChangeEvent, Checkbox} from "primeng/checkbox";
import {UserService} from "../../settings/user-management/user.service";
import {IconDisplayComponent} from '../../../shared/components/icon-display/icon-display.component';
@@ -23,6 +23,7 @@ import {BookService} from '../../book/service/book.service';
import {ShelfService} from '../../book/service/shelf.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Textarea} from 'primeng/textarea';
import {IconSelection, toIconSelection} from '../../../shared/icons/icon-selection';
export type RuleOperator =
| 'equals'
@@ -543,9 +544,7 @@ export class MagicShelfComponent implements OnInit {
});
if (iconValue) {
this.selectedIcon = iconValue.startsWith('pi ')
? {type: 'PRIME_NG', value: iconValue}
: {type: 'CUSTOM_SVG', value: iconValue};
this.selectedIcon = toIconSelection(iconValue, shelf?.iconType);
} else {
this.selectedIcon = null;
}
@@ -14,8 +14,8 @@ function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf {
return {
id: 1,
name: 'Favorites',
icon: 'pi pi-star',
iconType: 'PRIME_NG',
icon: 'star',
iconType: 'LUCIDE',
filterJson: JSON.stringify(buildGroupRule()),
isPublic: false,
...overrides,
@@ -152,8 +152,8 @@ describe('MagicShelfService', () => {
service.saveShelf({
name: 'Magic',
icon: 'pi pi-bolt',
iconType: 'PRIME_NG',
icon: 'zap',
iconType: 'LUCIDE',
group,
isPublic: true,
}).subscribe();
@@ -162,8 +162,8 @@ describe('MagicShelfService', () => {
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual(expect.objectContaining({
name: 'Magic',
icon: 'pi pi-bolt',
iconType: 'PRIME_NG',
icon: 'zap',
iconType: 'LUCIDE',
filterJson: JSON.stringify(group),
isPublic: true,
}));
@@ -9,12 +9,13 @@ import {BookService} from '../../book/service/book.service';
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
import {AuthService} from '../../../shared/service/auth.service';
import {GroupRule} from '../component/magic-shelf-component';
import {IconType} from '../../../shared/icons/icon-selection';
export interface MagicShelf {
id?: number | null;
name: string;
icon?: string | null;
iconType?: 'PRIME_NG' | 'CUSTOM_SVG' | null;
iconType?: IconType | null;
filterJson: string;
isPublic?: boolean;
}
@@ -72,7 +73,7 @@ export class MagicShelfService {
id?: number;
name: string | null;
icon: string | null;
iconType?: 'PRIME_NG' | 'CUSTOM_SVG';
iconType?: IconType | null;
group: unknown;
isPublic?: boolean | null;
}): Observable<MagicShelf> {
@@ -1,35 +1,34 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {SafeHtml} from '@angular/platform-browser';
import {of, throwError} from 'rxjs';
import {Subject, of, throwError} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {IconDisplayComponent} from './icon-display.component';
import {IconCacheService} from '../../services/icon-cache.service';
import {IconService} from '../../services/icon.service';
import {CustomSvgCacheService} from '../../services/custom-svg-cache.service';
import {CustomSvgService} from '../../services/custom-svg.service';
describe('IconDisplayComponent', () => {
let fixture: ComponentFixture<IconDisplayComponent>;
let component: IconDisplayComponent;
let iconCache: {
let customSvgCache: {
getCachedSanitized: ReturnType<typeof vi.fn>;
cacheIcon: ReturnType<typeof vi.fn>;
};
let iconService: {getSanitizedSvgContent: ReturnType<typeof vi.fn>};
let customSvgService: {getSanitizedSvgContent: ReturnType<typeof vi.fn>};
beforeEach(async () => {
iconCache = {
customSvgCache = {
getCachedSanitized: vi.fn(() => null),
cacheIcon: vi.fn(),
};
iconService = {
getSanitizedSvgContent: vi.fn(() => of('<svg>ok</svg>' as SafeHtml)),
customSvgService = {
getSanitizedSvgContent: vi.fn(() => of('<svg>ok</svg>')),
};
await TestBed.configureTestingModule({
imports: [IconDisplayComponent],
providers: [
{provide: IconCacheService, useValue: iconCache},
{provide: IconService, useValue: iconService},
{provide: CustomSvgCacheService, useValue: customSvgCache},
{provide: CustomSvgService, useValue: customSvgService},
],
}).compileComponents();
@@ -42,38 +41,20 @@ describe('IconDisplayComponent', () => {
TestBed.resetTestingModule();
});
it('normalizes PrimeNG icon class names', () => {
expect(component.getPrimeNgIconClass('pi pi-book')).toBe('pi pi-book');
expect(component.getPrimeNgIconClass('pi-book')).toBe('pi pi-book');
expect(component.getPrimeNgIconClass('book')).toBe('pi pi-book');
});
it('builds PrimeNG styles from the configured size and extra icon style', () => {
component.size = '20px';
component.iconStyle = {color: 'tomato'};
expect(component.getPrimeNgStyle()).toEqual({
fontSize: '17px',
width: '20px',
height: '20px',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
color: 'tomato',
});
});
it('loads uncached custom SVG icons on initialization', () => {
component.icon = {type: 'CUSTOM_SVG', value: 'dragon'};
fixture.detectChanges();
expect(iconCache.getCachedSanitized).toHaveBeenCalledWith('dragon');
expect(iconService.getSanitizedSvgContent).toHaveBeenCalledWith('dragon');
expect(customSvgCache.getCachedSanitized).toHaveBeenCalledWith('dragon');
expect(customSvgService.getSanitizedSvgContent).toHaveBeenCalledWith('dragon');
});
it('does not reload the same custom SVG when the value has not changed', () => {
const loadSpy = vi.spyOn(component as never, 'loadIconIfNeeded');
component.icon = {type: 'CUSTOM_SVG', value: 'dragon'};
fixture.detectChanges();
customSvgService.getSanitizedSvgContent.mockClear();
component.ngOnChanges({
icon: {
currentValue: {type: 'CUSTOM_SVG', value: 'dragon'},
@@ -83,12 +64,15 @@ describe('IconDisplayComponent', () => {
},
});
expect(loadSpy).not.toHaveBeenCalled();
expect(customSvgService.getSanitizedSvgContent).not.toHaveBeenCalled();
});
it('reloads when the custom SVG icon value changes', () => {
const loadSpy = vi.spyOn(component as never, 'loadIconIfNeeded');
component.icon = {type: 'CUSTOM_SVG', value: 'phoenix'};
fixture.detectChanges();
customSvgService.getSanitizedSvgContent.mockClear();
component.icon = {type: 'CUSTOM_SVG', value: 'dragon'};
component.ngOnChanges({
icon: {
currentValue: {type: 'CUSTOM_SVG', value: 'dragon'},
@@ -98,14 +82,14 @@ describe('IconDisplayComponent', () => {
},
});
expect(loadSpy).toHaveBeenCalled();
expect(customSvgService.getSanitizedSvgContent).toHaveBeenCalledWith('dragon');
});
it('exposes cached SVG content and empty-icon dimensions', () => {
iconCache.getCachedSanitized.mockReturnValueOnce('<svg>cached</svg>' as SafeHtml);
customSvgCache.getCachedSanitized.mockReturnValueOnce('<svg>cached</svg>');
component.size = '2rem';
expect(component.getSvgContent('cached')).toBe('<svg>cached</svg>' as SafeHtml);
expect(component.getSvgContent('cached')).toBe('<svg>cached</svg>');
expect(component.getEmptyIconStyle()).toEqual({
width: '2rem',
height: '2rem',
@@ -113,15 +97,27 @@ describe('IconDisplayComponent', () => {
});
it('caches an error SVG when loading a custom icon fails', () => {
iconService.getSanitizedSvgContent.mockReturnValueOnce(
customSvgService.getSanitizedSvgContent.mockReturnValueOnce(
throwError(() => new Error('nope'))
);
component.icon = {type: 'CUSTOM_SVG', value: 'broken'};
fixture.detectChanges();
expect(iconCache.cacheIcon).toHaveBeenCalledOnce();
expect(iconCache.cacheIcon.mock.calls[0]?.[0]).toBe('broken');
expect(iconCache.cacheIcon.mock.calls[0]?.[1]).toContain('stroke="red"');
expect(customSvgCache.cacheIcon).toHaveBeenCalledOnce();
expect(customSvgCache.cacheIcon.mock.calls[0]?.[0]).toBe('broken');
expect(customSvgCache.cacheIcon.mock.calls[0]?.[1]).toContain('stroke="red"');
});
it('caches a load failure under the originally requested custom icon name', () => {
const loadResult = new Subject<string>();
customSvgService.getSanitizedSvgContent.mockReturnValueOnce(loadResult.asObservable());
component.icon = {type: 'CUSTOM_SVG', value: 'dragon'};
fixture.detectChanges();
component.icon = {type: 'CUSTOM_SVG', value: 'phoenix'};
loadResult.error(new Error('nope'));
expect(customSvgCache.cacheIcon.mock.calls[0]?.[0]).toBe('dragon');
});
});
@@ -1,25 +1,39 @@
import {Component, inject, Input, OnInit, OnChanges, SimpleChanges, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {IconSelection} from '../../service/icon-picker.service';
import {Component, inject, Input, OnInit, OnChanges, SimpleChanges, ChangeDetectionStrategy, ChangeDetectorRef, DestroyRef} from '@angular/core';
import {IconSelection} from '../../icons/icon-selection';
import {NgClass, NgStyle} from '@angular/common';
import {IconCacheService} from '../../services/icon-cache.service';
import {IconService} from '../../services/icon.service';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
import {CustomSvgCacheService} from '../../services/custom-svg-cache.service';
import {CustomSvgService} from '../../services/custom-svg.service';
import {AppIconDirective} from '../icon/app-icon.directive';
import {SvgContentDirective} from '../icon/svg-content.directive';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
const ERROR_SVG = [
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="red">',
'<circle cx="12" cy="12" r="10"/>',
'<line x1="15" y1="9" x2="9" y2="15"/>',
'<line x1="9" y1="9" x2="15" y2="15"/>',
'</svg>',
].join('');
@Component({
selector: 'app-icon-display',
standalone: true,
imports: [NgClass, NgStyle],
imports: [NgClass, NgStyle, AppIconDirective, SvgContentDirective],
template: `
@if (icon) {
@if (icon.type === 'PRIME_NG') {
<i [class]="getPrimeNgIconClass(icon.value)" [ngClass]="iconClass" [ngStyle]="getPrimeNgStyle()"></i>
} @else {
@if (icon.type === 'CUSTOM_SVG') {
<div
class="svg-icon-inline"
[innerHTML]="getSvgContent(icon.value)"
[appSvgContent]="getSvgContent(icon.value)"
[ngClass]="iconClass"
[ngStyle]="getSvgStyle()"
></div>
} @else {
<svg
[appIcon]="icon.value"
[ngClass]="iconClass"
[ngStyle]="getSvgStyle()"
></svg>
}
} @else if (displayEmpty) {
<div
@@ -68,10 +82,10 @@ export class IconDisplayComponent implements OnInit, OnChanges {
@Input() alt: string = 'Icon';
@Input() displayEmpty: boolean = false;
private iconCache = inject(IconCacheService);
private iconService = inject(IconService);
private sanitizer = inject(DomSanitizer);
private cdr = inject(ChangeDetectorRef);
private readonly customSvgCache = inject(CustomSvgCacheService);
private readonly customSvgService = inject(CustomSvgService);
private readonly cdr = inject(ChangeDetectorRef);
private readonly destroyRef = inject(DestroyRef);
private lastLoadedIconName: string | null = null;
ngOnInit(): void {
@@ -92,36 +106,25 @@ export class IconDisplayComponent implements OnInit, OnChanges {
private loadIconIfNeeded(): void {
if (this.icon?.type === 'CUSTOM_SVG' && this.icon.value !== this.lastLoadedIconName) {
this.lastLoadedIconName = this.icon.value;
const requestedIconName = this.icon.value;
this.lastLoadedIconName = requestedIconName;
if (!this.iconCache.getCachedSanitized(this.icon.value)) {
this.iconService.getSanitizedSvgContent(this.icon.value).subscribe({
next: () => this.cdr.markForCheck(),
error: () => {
if (this.icon?.type === 'CUSTOM_SVG') {
const errorSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="red"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>';
const sanitized = this.sanitizer.bypassSecurityTrustHtml(errorSvg);
this.iconCache.cacheIcon(this.icon.value, errorSvg, sanitized);
if (this.customSvgCache.getCachedSanitized(requestedIconName) === null) {
this.customSvgService.getSanitizedSvgContent(requestedIconName)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: () => this.cdr.markForCheck(),
error: () => {
this.customSvgCache.cacheIcon(requestedIconName, ERROR_SVG, ERROR_SVG);
this.cdr.markForCheck();
}
}
});
});
}
}
}
getSvgContent(iconName: string): SafeHtml | null {
return this.iconCache.getCachedSanitized(iconName) || null;
}
getPrimeNgIconClass(iconValue: string): string {
if (iconValue.startsWith('pi pi-')) {
return iconValue;
}
if (iconValue.startsWith('pi-')) {
return `pi ${iconValue}`;
}
return `pi pi-${iconValue}`;
getSvgContent(iconName: string): string | null {
return this.customSvgCache.getCachedSanitized(iconName);
}
getSvgStyle(): Record<string, string> {
@@ -139,19 +142,4 @@ export class IconDisplayComponent implements OnInit, OnChanges {
};
}
getPrimeNgStyle(): Record<string, string> {
const fontSize = this.size.endsWith('px')
? `${parseInt(this.size) * 0.85}px`
: `calc(${this.size} * 0.85)`;
return {
fontSize: fontSize,
width: this.size,
height: this.size,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
...this.iconStyle
};
}
}
@@ -2,7 +2,7 @@
<header class="dialog-header">
<div class="header-content">
<div class="header-icon">
<i class="pi pi-palette"></i>
<svg lucidePalette aria-hidden="true"></svg>
</div>
<div class="header-text">
<h1>Choose an Icon</h1>
@@ -22,31 +22,30 @@
<p-tabs [(value)]="activeTabIndex">
<p-tablist>
<p-tab value="0">
<i class="pi pi-prime"></i>
<span>Prime Icons</span>
<svg lucideSparkles aria-hidden="true"></svg>
<span>Default</span>
</p-tab>
<p-tab value="1">
<i class="pi pi-images"></i>
<svg lucideImages aria-hidden="true"></svg>
<span>SVG Library</span>
</p-tab>
@if (canManageIcons) {
<p-tab value="2">
<i class="pi pi-plus-circle"></i>
<svg lucideCirclePlus aria-hidden="true"></svg>
<span>Add Custom</span>
</p-tab>
}
</p-tablist>
<p-tabpanels>
<!-- Prime Icons Tab -->
<p-tabpanel value="0">
<div class="tab-content">
<div class="search-container">
<i class="pi pi-search search-icon"></i>
<svg lucideSearch class="search-icon" aria-hidden="true"></svg>
<input
type="text"
pInputText
placeholder="Search Prime icons..."
placeholder="Search icons"
[(ngModel)]="searchText"
class="search-input"
/>
@@ -61,9 +60,11 @@
(click)="selectIcon(icon)"
(keydown.enter)="selectIcon(icon)"
[class.selected]="icon === selectedIcon"
[title]="icon"
[title]="displayIconName(icon)"
>
<i [class]="icon"></i>
@if (getLucideIconData(icon); as iconData) {
<svg [lucideIcon]="iconData" aria-hidden="true"></svg>
}
</div>
}
</div>
@@ -109,7 +110,7 @@
(dragstart)="onSvgIconDragStart(iconName)"
(dragend)="onSvgIconDragEnd()"
>
<div class="svg-icon-inline" [innerHTML]="getSvgContent(iconName)"></div>
<div class="svg-icon-inline" [appSvgContent]="getSvgContent(iconName)"></div>
</div>
}
</div>
@@ -171,7 +172,7 @@
@if (svgContent && svgPreview) {
<div class="preview-card">
<div class="preview-label">Preview</div>
<div class="preview-content" [innerHTML]="svgPreview"></div>
<div class="preview-content" [appSvgContent]="svgPreview"></div>
</div>
}
@@ -221,7 +222,7 @@
<i class="pi pi-times"></i>
</button>
</div>
<div class="queue-item-preview" [innerHTML]="entry.preview"></div>
<div class="queue-item-preview" [appSvgContent]="entry.preview"></div>
@if (entry.error) {
<div class="queue-item-error">{{ entry.error }}</div>
}
@@ -1,23 +1,24 @@
import {Component, inject, OnInit} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {IconService} from '../../services/icon.service';
import {IconCacheService} from '../../services/icon-cache.service';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
import {CustomSvgService} from '../../services/custom-svg.service';
import {CustomSvgCacheService} from '../../services/custom-svg-cache.service';
import DOMPurify from 'dompurify';
import {UrlHelperService} from '../../service/url-helper.service';
import {MessageService} from 'primeng/api';
import {IconCategoriesHelper} from '../../helpers/icon-categories.helper';
import {Button} from 'primeng/button';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {UserService} from '../../../features/settings/user-management/user.service';
import {from, of} from 'rxjs';
import {catchError, mergeMap, toArray} from 'rxjs/operators';
import {LucideCirclePlus, LucideDynamicIcon, LucideImages, LucidePalette, LucideSearch, LucideSparkles, provideLucideConfig, type LucideIconData, type LucideIconNode} from '@lucide/angular';
import iconNodes from 'lucide-static/icon-nodes.json';
import {SvgContentDirective} from '../icon/svg-content.directive';
interface SvgEntry {
name: string;
content: string;
preview: SafeHtml | null;
preview: string | null;
error: string;
}
@@ -34,13 +35,23 @@ interface SvgIconBatchResponse {
results: IconSaveResult[];
}
const lucideIconNodes = iconNodes as unknown as Record<string, LucideIconNode[]>;
@Component({
selector: 'app-icon-picker-component',
imports: [
FormsModule,
Button,
Tabs, TabList, Tab, TabPanels, TabPanel
Tabs, TabList, Tab, TabPanels, TabPanel,
SvgContentDirective,
LucideDynamicIcon,
LucideCirclePlus,
LucideImages,
LucidePalette,
LucideSearch,
LucideSparkles
],
providers: [provideLucideConfig({ size: 16, strokeWidth: 2 })],
templateUrl: './icon-picker-component.html',
styleUrl: './icon-picker-component.scss'
})
@@ -65,16 +76,20 @@ export class IconPickerComponent implements OnInit {
};
ref = inject(DynamicDialogRef);
iconService = inject(IconService);
iconCache = inject(IconCacheService);
sanitizer = inject(DomSanitizer);
customSvgService = inject(CustomSvgService);
customSvgCache = inject(CustomSvgCacheService);
urlHelper = inject(UrlHelperService);
messageService = inject(MessageService);
userService = inject(UserService);
searchText: string = '';
selectedIcon: string | null = null;
icons: string[] = IconCategoriesHelper.createIconList();
readonly lucideIconData = new Map<string, LucideIconData>(
Object.entries(lucideIconNodes)
.sort(([left], [right]) => left.localeCompare(right))
.map(([name, node]): [string, LucideIconData] => [name, {name, size: 24, node}]),
);
icons: string[] = [...this.lucideIconData.keys()];
private _activeTabIndex: string = '0';
@@ -91,7 +106,7 @@ export class IconPickerComponent implements OnInit {
svgContent: string = '';
svgName: string = '';
svgPreview: SafeHtml | null = null;
svgPreview: string | null = null;
errorMessage: string = '';
svgEntries: SvgEntry[] = [];
@@ -131,14 +146,22 @@ export class IconPickerComponent implements OnInit {
selectIcon(icon: string): void {
this.selectedIcon = icon;
this.ref.close({type: 'PRIME_NG', value: icon});
this.ref.close({type: 'LUCIDE', value: icon});
}
displayIconName(icon: string): string {
return icon.trim().replaceAll('-', ' ');
}
getLucideIconData(icon: string): LucideIconData | null {
return this.lucideIconData.get(icon) ?? null;
}
private loadSvgIcons(): void {
this.isLoadingSvgIcons = true;
this.svgIconsError = '';
this.iconService.getIconNames().subscribe({
this.customSvgService.getIconNames().subscribe({
next: (names) => {
this.hasLoadedSvgIcons = true;
if (names.length === 0) {
@@ -148,9 +171,9 @@ export class IconPickerComponent implements OnInit {
}
from(names).pipe(
mergeMap(name =>
this.iconCache.getCachedSanitized(name)
this.customSvgCache.getCachedSanitized(name)
? of(null)
: this.iconService.getSvgIconContent(name).pipe(catchError(() => of(null))),
: this.customSvgService.getSvgIconContent(name).pipe(catchError(() => of(null))),
5
),
toArray()
@@ -167,8 +190,8 @@ export class IconPickerComponent implements OnInit {
});
}
getSvgContent(iconName: string): SafeHtml | null {
return this.iconCache.getCachedSanitized(iconName) || null;
getSvgContent(iconName: string): string | null {
return this.customSvgCache.getCachedSanitized(iconName) || null;
}
selectSvgIcon(iconName: string): void {
@@ -196,7 +219,7 @@ export class IconPickerComponent implements OnInit {
USE_PROFILES: { svg: true },
FORBID_TAGS: ['script', 'style', 'foreignObject']
});
this.svgPreview = this.sanitizer.bypassSecurityTrustHtml(sanitized);
this.svgPreview = sanitized;
} catch {
this.svgPreview = null;
this.errorMessage = this.ERROR_MESSAGES.PARSE_ERROR;
@@ -256,7 +279,7 @@ export class IconPickerComponent implements OnInit {
svgData: entry.content
}));
this.iconService.saveBatchSvgIcons(svgData).subscribe({
this.customSvgService.saveBatchSvgIcons(svgData).subscribe({
next: (response: SvgIconBatchResponse) => {
this.isSavingBatch = false;
let successCount = 0;
@@ -310,7 +333,7 @@ export class IconPickerComponent implements OnInit {
private deleteSvgIcon(iconName: string): void {
this.isLoadingSvgIcons = true;
this.iconService.deleteSvgIcon(iconName).subscribe({
this.customSvgService.deleteSvgIcon(iconName).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
@@ -0,0 +1,90 @@
import {
Directive,
ElementRef,
effect,
inject,
Injectable,
input,
Renderer2,
Signal,
signal,
WritableSignal,
} from '@angular/core';
import DOMPurify from 'dompurify';
@Injectable({providedIn: 'root'})
export class LucideIconService {
private readonly cache = new Map<string, WritableSignal<SVGSVGElement | null>>();
icon(name: string): Signal<SVGSVGElement | null> {
const cached = this.cache.get(name);
if (cached) {
return cached;
}
const result = signal<SVGSVGElement | null>(null);
this.cache.set(name, result);
fetch(`assets/lucide/${encodeURIComponent(name)}.svg`)
.then(response => {
if (!response.ok) {
return '';
}
return response.text();
})
.then(text => result.set(this.parseSvg(text)))
.catch(() => result.set(null));
return result;
}
private parseSvg(svgText: string): SVGSVGElement | null {
if (!svgText) {
return null;
}
const sanitizedSvgText = DOMPurify.sanitize(svgText, {USE_PROFILES: {svg: true}});
const parsed = new DOMParser().parseFromString(sanitizedSvgText, 'image/svg+xml');
if (parsed.querySelector('parsererror')) {
return null;
}
const svg = parsed.querySelector('svg');
return svg instanceof SVGSVGElement ? svg : null;
}
}
@Directive({
selector: 'svg[appIcon]',
standalone: true,
})
export class AppIconDirective {
readonly appIcon = input.required<string>();
private readonly svg = inject<ElementRef<SVGSVGElement>>(ElementRef).nativeElement;
private readonly icons = inject(LucideIconService);
private readonly renderer = inject(Renderer2);
constructor() {
this.renderer.setAttribute(this.svg, 'viewBox', '0 0 24 24');
this.renderer.setAttribute(this.svg, 'width', '1em');
this.renderer.setAttribute(this.svg, 'height', '1em');
this.renderer.setAttribute(this.svg, 'fill', 'none');
this.renderer.setAttribute(this.svg, 'stroke', 'currentColor');
this.renderer.setAttribute(this.svg, 'stroke-width', '2');
this.renderer.setAttribute(this.svg, 'stroke-linecap', 'round');
this.renderer.setAttribute(this.svg, 'stroke-linejoin', 'round');
this.renderer.setAttribute(this.svg, 'aria-hidden', 'true');
effect(() => {
const icon = this.icons.icon(this.appIcon())();
while (this.svg.firstChild) {
this.renderer.removeChild(this.svg, this.svg.firstChild);
}
for (const child of Array.from(icon?.childNodes ?? [])) {
this.renderer.appendChild(this.svg, document.importNode(child, true));
}
});
}
}
@@ -0,0 +1,40 @@
import {Directive, ElementRef, Renderer2, effect, inject, input} from '@angular/core';
@Directive({
selector: '[appSvgContent]',
standalone: true,
})
export class SvgContentDirective {
readonly appSvgContent = input<string | null>(null);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
private readonly renderer = inject(Renderer2);
constructor() {
effect(() => {
this.render(this.appSvgContent());
});
}
private render(svgText: string | null): void {
while (this.host.firstChild) {
this.renderer.removeChild(this.host, this.host.firstChild);
}
if (!svgText) {
return;
}
const parsed = new DOMParser().parseFromString(svgText, 'image/svg+xml');
if (parsed.querySelector('parsererror')) {
return;
}
const svg = parsed.querySelector('svg');
if (!(svg instanceof SVGSVGElement)) {
return;
}
this.renderer.appendChild(this.host, document.importNode(svg, true));
}
}
@@ -1,15 +0,0 @@
import {describe, expect, it} from 'vitest';
import {IconCategoriesHelper} from './icon-categories.helper';
describe('IconCategoriesHelper', () => {
it('creates a prime icon class list from the static categories', () => {
const icons = IconCategoriesHelper.createIconList();
expect(icons[0]).toBe('pi pi-address-book');
expect(icons.at(-1)).toBe('pi pi-youtube');
expect(new Set(icons).size).toBe(icons.length);
expect(icons).toContain('pi pi-book');
expect(icons).toContain('pi pi-shield');
});
});
@@ -1,44 +0,0 @@
export class IconCategoriesHelper {
static readonly CATEGORIES: string[] = [
"address-book", "align-center", "align-justify", "align-left", "align-right", "amazon", "android",
"angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left",
"angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right", "arrow-circle-up",
"arrow-down", "arrow-down-left", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-right", "arrow-left",
"arrow-right", "arrow-right-arrow-left", "arrow-up", "arrow-up-left", "arrow-up-right", "arrow-up-right-and-arrow-down-left-from-center",
"arrows-alt", "arrows-h", "arrows-v", "asterisk", "at", "backward", "ban", "barcode", "bars", "bell", "bell-slash",
"bitcoin", "bolt", "book", "bookmark", "bookmark-fill", "box", "briefcase", "building", "building-columns", "bullseye",
"calculator", "calendar", "calendar-clock", "calendar-minus", "calendar-plus", "calendar-times", "camera", "car",
"caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus", "chart-bar",
"chart-line", "chart-pie", "chart-scatter", "check", "check-circle", "check-square", "chevron-circle-down",
"chevron-circle-left", "chevron-circle-right", "chevron-circle-up", "chevron-down", "chevron-left", "chevron-right",
"chevron-up", "circle", "circle-fill", "circle-off", "circle-on", "clipboard", "clock", "clone", "cloud", "cloud-download",
"cloud-upload", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left",
"desktop", "directions", "directions-alt", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v",
"envelope", "equals", "eraser", "ethereum", "euro", "exclamation-circle", "exclamation-triangle", "expand",
"external-link", "eye", "eye-slash", "face-smile", "facebook", "fast-backward", "fast-forward", "file", "file-arrow-up",
"file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word",
"filter", "filter-fill", "filter-slash", "flag", "flag-fill", "folder", "folder-open", "folder-plus", "forward", "gauge",
"gift", "github", "globe", "google", "graduation-cap", "hammer", "hashtag", "headphones", "heart", "heart-fill", "history",
"home", "hourglass", "id-card", "image", "images", "inbox", "indian-rupee", "info", "info-circle", "instagram", "key",
"language", "lightbulb", "link", "linkedin", "list", "list-check", "lock", "lock-open", "map", "map-marker", "mars", "megaphone",
"microchip", "microchip-ai", "microphone", "microsoft", "minus", "minus-circle", "mobile", "money-bill", "moon", "objects-column",
"palette", "paperclip", "pause", "pause-circle", "paypal", "pen-to-square", "pencil", "percentage", "phone", "pinterest", "play",
"play-circle", "plus", "plus-circle", "pound", "power-off", "prime", "print", "qrcode", "question", "question-circle", "receipt",
"reddit", "refresh", "replay", "reply", "save", "search", "search-minus", "search-plus", "send", "server", "share-alt", "shield",
"shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort",
"sort-alpha-down", "sort-alpha-down-alt", "sort-alpha-up", "sort-alpha-up-alt", "sort-alt", "sort-alt-slash",
"sort-amount-down", "sort-amount-down-alt", "sort-amount-up", "sort-amount-up-alt", "sort-down", "sort-down-fill",
"sort-numeric-down", "sort-numeric-down-alt", "sort-numeric-up", "sort-numeric-up-alt", "sort-up", "sort-up-fill", "sparkles",
"spinner", "spinner-dotted", "star", "star-fill", "star-half", "star-half-fill", "step-backward", "step-backward-alt",
"step-forward", "step-forward-alt", "stop", "stop-circle", "stopwatch", "sun", "sync", "table", "tablet", "tag", "tags",
"telegram", "th-large", "thumbs-down", "thumbs-down-fill", "thumbs-up", "thumbs-up-fill", "thumbtack", "ticket", "tiktok",
"times", "times-circle", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user",
"user-edit", "user-minus", "user-plus", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off",
"volume-up", "wallet", "warehouse", "wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench",
"youtube"
];
static createIconList(): string[] {
return this.CATEGORIES.map(iconName => `pi pi-${iconName}`);
}
}
@@ -0,0 +1,9 @@
export type IconType = 'LUCIDE' | 'CUSTOM_SVG';
export interface IconSelection {
type: IconType;
value: string;
}
export const toIconSelection = (value: string, type: IconType | null | undefined): IconSelection =>
type === 'CUSTOM_SVG' ? {type: 'CUSTOM_SVG', value} : {type: 'LUCIDE', value};
@@ -6,7 +6,7 @@
[attr.aria-label]="t('menu.toggleNavigation')"
(click)="layoutService.onMenuToggle()"
>
<i class="pi pi-bars" aria-hidden="true"></i>
<svg lucideMenu aria-hidden="true"></svg>
</button>
<div class="mobile-topbar-brand">
<svg class="mobile-topbar-brand-icon" viewBox="0 0 100 126" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
@@ -33,7 +33,7 @@
[attr.aria-label]="'common.close' | transloco"
(click)="closeSearch()"
>
<i class="pi pi-times" aria-hidden="true"></i>
<svg lucideX aria-hidden="true"></svg>
</button>
} @else {
<button
@@ -42,7 +42,7 @@
[attr.aria-label]="t('menu.search')"
(click)="openSearch()"
>
<i class="pi pi-search" aria-hidden="true"></i>
<svg lucideSearch aria-hidden="true"></svg>
</button>
}
</header>
@@ -75,8 +75,9 @@
outline-offset: 2px;
}
i {
font-size: 1.0938rem;
svg {
width: 1.0938rem;
height: 1.0938rem;
}
}
@@ -59,23 +59,24 @@ describe('AppMobileTopbarComponent', () => {
expect(commandPaletteService.open).toHaveBeenCalledOnce();
});
it('shows the search icon when the palette is closed', () => {
it('opens the command palette from the topbar button when the palette is closed', () => {
commandPaletteService.isOpen.set(false);
fixture.detectChanges();
const icon = fixture.nativeElement.querySelector('.mobile-topbar button:last-of-type i');
expect(icon?.classList.contains('pi-search')).toBe(true);
const button = fixture.nativeElement.querySelector('.mobile-topbar button:last-of-type') as HTMLButtonElement;
button.click();
expect(layoutService.closeMobileSidebar).toHaveBeenCalledOnce();
expect(commandPaletteService.open).toHaveBeenCalledOnce();
});
it('swaps to a close button that hides the palette when it is open', () => {
it('hides the command palette from the topbar button when the palette is open', () => {
commandPaletteService.isOpen.set(true);
fixture.detectChanges();
const button = fixture.nativeElement.querySelector('.mobile-topbar button:last-of-type') as HTMLButtonElement;
const icon = button.querySelector('i');
expect(icon?.classList.contains('pi-times')).toBe(true);
button.click();
expect(commandPaletteService.hide).toHaveBeenCalledOnce();
});
});
@@ -1,5 +1,6 @@
import { Component, inject } from '@angular/core';
import { TranslocoDirective, TranslocoPipe } from '@jsverse/transloco';
import { LucideMenu, LucideSearch, LucideX } from '@lucide/angular';
import { CommandPaletteService } from '../../../features/command-palette/command-palette.service';
import { LayoutService } from '../layout.service';
@@ -7,7 +8,7 @@ import { LayoutService } from '../layout.service';
selector: 'app-mobile-topbar',
templateUrl: './app.mobile-topbar.component.html',
styleUrl: './app.mobile-topbar.component.scss',
imports: [TranslocoDirective, TranslocoPipe],
imports: [TranslocoDirective, TranslocoPipe, LucideMenu, LucideSearch, LucideX],
})
export class AppMobileTopbarComponent {
readonly layoutService = inject(LayoutService);
@@ -80,7 +80,7 @@
(click)="openContextMenu($event, entitymenu)"
>
<span class="entity-menu-button-content">
<i class="pi pi-ellipsis-v entity-menu-icon" aria-hidden="true"></i>
<svg lucideEllipsisVertical class="entity-menu-icon" aria-hidden="true"></svg>
<span class="entity-menu-count">{{ formatCount(currentItem.bookCount) }}</span>
</span>
</button>
@@ -3,10 +3,11 @@ import { RouterLink } from '@angular/router';
import { Menu } from 'primeng/menu';
import { Tooltip } from 'primeng/tooltip';
import { TranslocoPipe } from '@jsverse/transloco';
import { LucideEllipsisVertical } from '@lucide/angular';
import { IconSelection, toIconSelection } from '../../icons/icon-selection';
import { UserService } from '../../../features/settings/user-management/user.service';
import { IconDisplayComponent } from '../../components/icon-display/icon-display.component';
import { IconSelection } from '../../service/icon-picker.service';
import { LayoutService } from '../layout.service';
import { SidebarLeaf } from '../navigation/nav-item.model';
@@ -22,6 +23,7 @@ import { SidebarLeaf } from '../navigation/nav-item.model';
IconDisplayComponent,
Tooltip,
TranslocoPipe,
LucideEllipsisVertical,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
@@ -70,10 +72,7 @@ export class AppSidebarItemRowComponent {
getIconSelection(): IconSelection | null {
const item = this.item();
if (!item.icon) return null;
return {
type: item.iconType || 'PRIME_NG',
value: item.icon,
};
return toIconSelection(item.icon, item.iconType);
}
hasContextMenu(): boolean {
@@ -12,11 +12,11 @@
<span>{{ currentItem.label }}</span>
</span>
<span class="expand-icon-button" aria-hidden="true">
<i
[ngClass]="{ 'pi': true, 'pi-angle-up': expanded, 'pi-angle-down': !expanded }"
class="expand-icon"
aria-hidden="true"
></i>
@if (expanded) {
<svg lucideChevronUp class="expand-icon" aria-hidden="true"></svg>
} @else {
<svg lucideChevronDown class="expand-icon" aria-hidden="true"></svg>
}
</span>
</button>
<div class="sidebar-section-divider" aria-hidden="true"></div>
@@ -115,7 +115,8 @@
}
.expand-icon {
font-size: var(--app-text-lg);
width: var(--app-text-lg);
height: var(--app-text-lg);
color: var(--color-text-secondary);
}
}
@@ -1,9 +1,9 @@
import { ChangeDetectionStrategy, Component, HostBinding, computed, inject, input } from '@angular/core';
import { NgClass } from '@angular/common';
import { LayoutService } from '../layout.service';
import { AppSidebarItemRowComponent } from './app.sidebar-item-row.component';
import { SidebarLeaf, SidebarSection } from '../navigation/nav-item.model';
import { LucideChevronDown, LucideChevronUp } from '@lucide/angular';
@Component({
// Attribute selector so the section renders into its host <li> inside a <ul>.
@@ -11,7 +11,7 @@ import { SidebarLeaf, SidebarSection } from '../navigation/nav-item.model';
selector: '[appSidebarSection]',
templateUrl: './app.sidebar-section.component.html',
styleUrls: ['./app.sidebar-section.component.scss'],
imports: [NgClass, AppSidebarItemRowComponent],
imports: [LucideChevronDown, LucideChevronUp, AppSidebarItemRowComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppSidebarSectionComponent {
@@ -59,7 +59,7 @@
[attr.aria-expanded]="addMenuOpen() ? 'true' : 'false'"
(click)="toggleAddMenu($event, addMenu)"
>
<i class="pi pi-plus" aria-hidden="true"></i>
<svg lucidePlus aria-hidden="true"></svg>
</button>
<p-menu
@@ -82,7 +82,7 @@
tooltipPosition="bottom"
(click)="openUploadDialog()"
>
<i class="pi pi-upload" aria-hidden="true"></i>
<svg lucideUpload aria-hidden="true"></svg>
</button>
}
@@ -100,7 +100,7 @@
(click)="toggleHeaderNotificationsPopover(notificationsMobileOrigin)"
>
<span class="sidebar-notification-button-content">
<i class="pi pi-bell" aria-hidden="true"></i>
<svg lucideBell aria-hidden="true"></svg>
@if (shouldShowNotificationBadge()) {
<span class="sidebar-notification-badge">{{ completedTaskCount() }}</span>
}
@@ -117,7 +117,7 @@
[tooltipDisabled]="!layoutService.isDesktop()"
tooltipPosition="bottom"
>
<i class="pi pi-cog" aria-hidden="true"></i>
<svg lucideSettings aria-hidden="true"></svg>
</a>
@if (currentUser(); as user) {
@@ -141,7 +141,7 @@
[attr.aria-label]="'layout.closeNavigation' | transloco"
(click)="closeMobileSidebar()"
>
<i class="pi pi-times" aria-hidden="true"></i>
<svg lucideX aria-hidden="true"></svg>
</button>
</div>
@@ -154,7 +154,7 @@
tooltipPosition="right"
(click)="openSearch()"
>
<i class="pi pi-search" aria-hidden="true"></i>
<svg lucideSearch aria-hidden="true"></svg>
<span class="sidebar-action-label">{{ t('search') }}</span>
<kbd class="sidebar-search-shortcut" aria-hidden="true">{{ searchShortcutLabel }}</kbd>
</button>
@@ -181,7 +181,7 @@
[attr.aria-expanded]="addMenuOpen() ? 'true' : 'false'"
(click)="toggleAddMenu($event, addMenu)"
>
<i class="pi pi-plus" aria-hidden="true"></i>
<svg lucidePlus aria-hidden="true"></svg>
<span class="sidebar-footer-action-label">{{ t('add') }}</span>
</button>
@@ -195,7 +195,7 @@
tooltipPosition="top"
(click)="openUploadDialog()"
>
<i class="pi pi-upload" aria-hidden="true"></i>
<svg lucideUpload aria-hidden="true"></svg>
<span class="sidebar-footer-action-label">{{ t('uploadBook') }}</span>
</button>
}
@@ -214,7 +214,7 @@
(click)="toggleFooterNotificationsPopover(notificationsFooterOrigin)"
>
<span class="sidebar-notification-button-content">
<i class="pi pi-bell" aria-hidden="true"></i>
<svg lucideBell aria-hidden="true"></svg>
@if (shouldShowNotificationBadge()) {
<span class="sidebar-notification-badge">{{ completedTaskCount() }}</span>
}
@@ -232,7 +232,7 @@
[tooltipDisabled]="!layoutService.isDesktop()"
tooltipPosition="top"
>
<i class="pi pi-cog" aria-hidden="true"></i>
<svg lucideSettings aria-hidden="true"></svg>
<span class="sidebar-footer-action-label">{{ t('settings') }}</span>
</a>
@@ -271,12 +271,11 @@
tooltipPosition="right"
(click)="layoutService.toggleSidebarCollapsed()"
>
<i
class="pi"
[class.pi-angle-double-left]="!layoutService.sidebarCollapsed()"
[class.pi-angle-double-right]="layoutService.sidebarCollapsed()"
aria-hidden="true"
></i>
@if (layoutService.sidebarCollapsed()) {
<svg lucidePanelLeftOpen aria-hidden="true"></svg>
} @else {
<svg lucidePanelLeftClose aria-hidden="true"></svg>
}
</button>
</div>
} @else {
@@ -291,12 +290,11 @@
tooltipPosition="right"
(click)="layoutService.toggleSidebarCollapsed()"
>
<i
class="pi"
[class.pi-angle-double-left]="!layoutService.sidebarCollapsed()"
[class.pi-angle-double-right]="layoutService.sidebarCollapsed()"
aria-hidden="true"
></i>
@if (layoutService.sidebarCollapsed()) {
<svg lucidePanelLeftOpen aria-hidden="true"></svg>
} @else {
<svg lucidePanelLeftClose aria-hidden="true"></svg>
}
</button>
</div>
}
@@ -367,7 +365,7 @@
[attr.aria-label]="t('documentation')"
(click)="openDocumentation()"
>
<i class="pi pi-question-circle" aria-hidden="true"></i>
<svg lucideCircleQuestionMark aria-hidden="true"></svg>
</button>
</div>
@@ -379,7 +377,7 @@
type="button"
(click)="openChangelogDialog()"
>
<i class="pi pi-arrow-up-right" aria-hidden="true"></i>
<svg lucideArrowUpRight aria-hidden="true"></svg>
<span>{{ t('updateAvailable') }}</span>
</button>
</div>
@@ -389,7 +387,7 @@
<div class="user-account-popover-body">
@if (!user.permissions.demoUser) {
<button type="button" class="menu-item user-account-popover-action" (click)="openAccountSettings()">
<i class="pi pi-user-edit" aria-hidden="true"></i>
<svg lucideUserPen aria-hidden="true"></svg>
<span>{{ 'settingsProfile.title' | transloco }}</span>
</button>
}
@@ -400,7 +398,7 @@
class="menu-item user-account-popover-action"
(click)="openReadingStats()"
>
<i class="pi pi-chart-bar" aria-hidden="true"></i>
<svg lucideChartColumn aria-hidden="true"></svg>
<span>{{ t('readingStats') }}</span>
</button>
}
@@ -413,14 +411,15 @@
[attr.aria-expanded]="appearanceMenuOpen()"
(click)="toggleAppearanceMenu()"
>
<i class="pi pi-palette" aria-hidden="true"></i>
<svg lucidePalette aria-hidden="true"></svg>
<span>{{ 'layout.theme.appearance' | transloco }}</span>
<span class="ml-auto mr-1.5 min-w-0 max-w-[4.75rem] overflow-hidden text-ellipsis whitespace-nowrap text-xs text-text-secondary">{{ selectedAppearanceLabel() }}</span>
<i
class="pi pi-chevron-down size-2.5 shrink-0 text-[0.6875rem] text-text-secondary! transition-transform duration-150"
<svg
lucideChevronDown
class="size-2.5 shrink-0 text-text-secondary! transition-transform duration-150"
[class.rotate-180]="appearanceMenuOpen()"
aria-hidden="true">
</i>
</svg>
</button>
<div
@@ -436,14 +435,14 @@
@for (option of appearanceOptions; track option.value) {
<button
type="button"
class="menu-item user-account-popover-action aria-pressed:bg-active-surface aria-pressed:text-primary! aria-pressed:[&_.pi]:text-primary!"
class="menu-item user-account-popover-action aria-pressed:bg-active-surface aria-pressed:text-primary! aria-pressed:[&_svg]:text-primary!"
[attr.aria-pressed]="selectedAppearancePreference() === option.value"
(click)="updateAppearancePreference(option.value)"
>
<i [class]="option.icon" aria-hidden="true"></i>
<svg [lucideIcon]="option.icon" aria-hidden="true"></svg>
<span>{{ option.labelKey | transloco }}</span>
@if (selectedAppearancePreference() === option.value) {
<i class="pi pi-check ml-auto text-primary!" aria-hidden="true"></i>
<svg lucideCheck class="ml-auto text-primary!" aria-hidden="true"></svg>
}
</button>
}
@@ -455,7 +454,7 @@
<footer class="user-account-popover-footer">
<button type="button" class="menu-item user-account-popover-logout" (click)="logout()">
<i class="pi pi-sign-out" aria-hidden="true"></i>
<svg lucideLogOut aria-hidden="true"></svg>
<span>{{ t('logout') }}</span>
</button>
</footer>
@@ -143,8 +143,9 @@
outline: none;
}
i {
font-size: var(--app-text-base);
svg {
width: var(--app-text-base);
height: var(--app-text-base);
}
}
@@ -240,10 +241,9 @@
}
}
i {
svg {
width: var(--sidebar-row-icon-size);
height: var(--sidebar-row-icon-size);
font-size: var(--app-text-base);
display: inline-flex;
align-items: center;
justify-content: center;
@@ -279,7 +279,7 @@
display: none;
}
i {
svg {
margin: 0;
}
}
@@ -501,8 +501,9 @@
}
}
.sidebar-footer-action i {
font-size: var(--app-text-lg);
.sidebar-footer-action svg {
width: var(--app-text-lg);
height: var(--app-text-lg);
}
.sidebar-collapse-button {
@@ -7,6 +7,25 @@ import { CdkConnectedOverlay, CdkOverlayOrigin, ConnectedPosition } from '@angul
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
import { UnifiedNotificationBoxComponent } from '../../components/unified-notification-popover/unified-notification-popover-component';
import { AppButtonDirective } from '../../components/button/app-button.directive';
import {
LucideArrowUpRight,
LucideBell,
LucideChartColumn,
LucideCheck,
LucideChevronDown,
LucideCircleQuestionMark,
LucideDynamicIcon,
LucideLogOut,
LucidePalette,
LucidePanelLeftClose,
LucidePanelLeftOpen,
LucidePlus,
LucideSearch,
LucideSettings,
LucideUpload,
LucideUserPen,
LucideX,
} from '@lucide/angular';
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';
@@ -109,6 +128,23 @@ function isNewerVersion(latest: string | undefined, current: string | undefined)
imports: [
AppSidebarSectionComponent,
AppButtonDirective,
LucideArrowUpRight,
LucideBell,
LucideChartColumn,
LucideCheck,
LucideChevronDown,
LucideCircleQuestionMark,
LucideDynamicIcon,
LucideLogOut,
LucidePalette,
LucidePanelLeftClose,
LucidePanelLeftOpen,
LucidePlus,
LucideSearch,
LucideSettings,
LucideUpload,
LucideUserPen,
LucideX,
Menu,
UnifiedNotificationBoxComponent,
RouterLink,
@@ -333,11 +369,18 @@ export class AppSidebarComponent {
}
}
// Temporary: PrimeNG p-menu cannot render non-Prime icons here.
private static readonly ADD_MENU_ICONS: Record<string, string> = {
createLibrary: 'pi pi-folder',
createShelf: 'pi pi-bookmark',
createMagicShelf: 'pi pi-sparkles',
};
private toMenuItems(items: readonly (NavItem | null | undefined)[]): MenuItem[] {
return items.flatMap((item): MenuItem[] =>
item ? [{
label: item.label,
icon: item.icon ? `pi ${item.icon}` : undefined,
icon: AppSidebarComponent.ADD_MENU_ICONS[item.id],
routerLink: item.routerLink,
command: item.action,
}] : []
@@ -131,7 +131,7 @@ describe('buildLibrarySection', () => {
});
it('renders each library with route, count, health, and icon metadata', () => {
const libs = [library({ id: 5, name: 'Fiction', icon: 'pi-book', iconType: 'PRIME_NG' })];
const libs = [library({ id: 5, name: 'Fiction', icon: 'book', iconType: 'LUCIDE' })];
const counts = new Map([[5, 42]]);
const [section] = buildLibrarySection(libs, counts, { field: 'name', order: 'asc' }, translate, libraryDeps);
@@ -139,8 +139,8 @@ describe('buildLibrarySection', () => {
id: 'library:5',
label: 'Fiction',
type: 'library',
icon: 'pi-book',
iconType: 'PRIME_NG',
icon: 'book',
iconType: 'LUCIDE',
routerLink: ['/library/5/books'],
bookCount: 42,
unhealthy: false,
@@ -216,7 +216,7 @@ describe('buildMagicShelfSection', () => {
it('renders sorted magic shelves with route, icon, and count', () => {
const shelves = [
magicShelf({ id: 2, name: 'Beta', icon: 'pi-sparkles', iconType: 'PRIME_NG' }),
magicShelf({ id: 2, name: 'Beta', icon: 'sparkles', iconType: 'LUCIDE' }),
magicShelf({ id: 1, name: 'Alpha' }),
];
const counts = new Map([[1, 4], [2, 7]]);
@@ -227,7 +227,7 @@ describe('buildMagicShelfSection', () => {
id: 'magicShelf:1', label: 'Alpha', routerLink: ['/magic-shelf/1/books'], bookCount: 4,
}),
expect.objectContaining({
id: 'magicShelf:2', label: 'Beta', icon: 'pi-sparkles', iconType: 'PRIME_NG',
id: 'magicShelf:2', label: 'Beta', icon: 'sparkles', iconType: 'LUCIDE',
routerLink: ['/magic-shelf/2/books'], bookCount: 7,
}),
]);
@@ -136,8 +136,7 @@ export function buildShelfSection(
id: 'shelfUnshelved',
label: translate('layout.menu.unshelved'),
type: 'shelf',
icon: 'pi pi-inbox',
iconType: 'PRIME_NG',
icon: 'inbox',
routerLink: ['/unshelved-books'],
bookCount: unshelvedCount,
}];
@@ -64,34 +64,34 @@ const HOME_PAGE_DEFINITIONS: readonly PageDefinition[] = [
{
id: 'dashboard',
labelKey: 'layout.menu.dashboard',
icon: 'pi-home',
icon: 'house',
routerLink: ['/dashboard'],
},
{
id: 'allBooks',
labelKey: 'layout.menu.allBooks',
icon: 'pi-book',
icon: 'library-big',
routerLink: ['/all-books'],
type: 'allBooks',
},
{
id: 'series',
labelKey: 'layout.menu.series',
icon: 'pi-objects-column',
icon: 'book-copy',
routerLink: ['/series'],
type: 'series',
},
{
id: 'authors',
labelKey: 'layout.menu.authors',
icon: 'pi-users',
icon: 'users',
routerLink: ['/authors'],
type: 'authors',
},
{
id: 'notebook',
labelKey: 'layout.menu.notebook',
icon: 'pi-pencil',
icon: 'notebook-pen',
routerLink: ['/notebook'],
},
] as const;
@@ -100,34 +100,34 @@ const SECONDARY_PAGE_DEFINITIONS: readonly PageDefinition[] = [
{
id: 'settings',
labelKey: 'layout.menu.settings',
icon: 'pi-cog',
icon: 'settings',
routerLink: ['/settings'],
},
{
id: 'libraryStats',
labelKey: 'layout.menu.libraryStats',
icon: 'pi-chart-line',
icon: 'chart-line',
routerLink: ['/library-stats'],
isVisible: canAccessLibraryStats,
},
{
id: 'readingStats',
labelKey: 'layout.menu.readingStats',
icon: 'pi-chart-bar',
icon: 'chart-column',
routerLink: ['/reading-stats'],
isVisible: canAccessUserStats,
},
{
id: 'metadataManager',
labelKey: 'layout.menu.metadataManager',
icon: 'pi-sparkles',
icon: 'tags',
routerLink: ['/metadata-manager'],
isVisible: canEditMetadata,
},
{
id: 'bookdrop',
labelKey: 'layout.menu.bookdrop',
icon: 'pi-inbox',
icon: 'inbox',
routerLink: ['/bookdrop'],
isVisible: canAccessBookdrop,
},
@@ -137,20 +137,20 @@ const CREATE_ACTION_DEFINITIONS: readonly ActionDefinition[] = [
{
id: 'createLibrary',
labelKey: 'layout.menu.createLibrary',
icon: 'pi-folder',
icon: 'folder',
run: (handlers) => handlers.createLibrary,
isVisible: canManageLibraries,
},
{
id: 'createShelf',
labelKey: 'book.shelfCreator.title',
icon: 'pi-bookmark',
icon: 'bookmark',
run: (handlers) => handlers.createShelf,
},
{
id: 'createMagicShelf',
labelKey: 'layout.menu.createMagicShelf',
icon: 'pi-sparkles',
icon: 'sparkles',
run: (handlers) => handlers.createMagicShelf,
},
] as const;
@@ -160,7 +160,7 @@ const ACTION_DEFINITIONS: readonly ActionDefinition[] = [
{
id: 'uploadBook',
labelKey: 'layout.menu.uploadBook',
icon: 'pi-upload',
icon: 'upload',
run: (handlers) => handlers.uploadBook,
isVisible: canUploadBooks,
},
@@ -1,6 +1,5 @@
import type { MenuItem } from 'primeng/api';
export type NavIconType = 'PRIME_NG' | 'CUSTOM_SVG';
import { IconType } from '../../icons/icon-selection';
export type NavItemType =
| 'library' | 'shelf' | 'magicShelf'
@@ -10,7 +9,7 @@ export interface NavItem {
id: string;
label: string;
icon?: string;
iconType?: NavIconType;
iconType?: IconType;
routerLink?: string[];
type?: NavItemType;
action?: () => void;
@@ -1,13 +1,14 @@
import { LucideMonitor, LucideMoon, LucideSun, type LucideIconData } from '@lucide/angular';
import type {AppearancePreference} from '../../model/app-state.model';
export interface AppearanceOption {
value: AppearancePreference;
labelKey: string;
icon: string;
icon: LucideIconData;
}
export const APPEARANCE_OPTIONS: readonly AppearanceOption[] = [
{value: 'light', labelKey: 'layout.theme.light', icon: 'pi pi-sun'},
{value: 'dark', labelKey: 'layout.theme.dark', icon: 'pi pi-moon'},
{value: 'system', labelKey: 'layout.theme.system', icon: 'pi pi-desktop'},
{value: 'light', labelKey: 'layout.theme.light', icon: LucideSun.icon},
{value: 'dark', labelKey: 'layout.theme.dark', icon: LucideMoon.icon},
{value: 'system', labelKey: 'layout.theme.system', icon: LucideMonitor.icon},
];
@@ -29,12 +29,12 @@ describe('IconPickerService', () => {
it('returns the icon selected by the dialog', async () => {
dialogLauncherService.openIconPickerDialog.mockResolvedValue({
onClose: of({type: 'PRIME_NG', value: 'pi pi-book'}),
onClose: of({type: 'LUCIDE', value: 'book'}),
});
await expect(firstValueFrom(service.open())).resolves.toEqual({
type: 'PRIME_NG',
value: 'pi pi-book',
type: 'LUCIDE',
value: 'book',
});
});
});
@@ -1,11 +1,7 @@
import {inject, Injectable} from '@angular/core';
import {EMPTY, from, Observable, switchMap} from 'rxjs';
import {DialogLauncherService} from '../services/dialog-launcher.service';
export interface IconSelection {
type: 'PRIME_NG' | 'CUSTOM_SVG';
value: string;
}
import {IconSelection} from '../icons/icon-selection';
@Injectable({providedIn: 'root'})
export class IconPickerService {
@@ -1,11 +1,11 @@
import {describe, expect, it} from 'vitest';
import {IconCacheService} from './icon-cache.service';
import {CustomSvgCacheService} from './custom-svg-cache.service';
describe('IconCacheService', () => {
describe('CustomSvgCacheService', () => {
it('stores, retrieves, removes, and sorts cached icon names', () => {
const service = new IconCacheService();
const sanitized = {id: 'sanitized'} as never;
const service = new CustomSvgCacheService();
const sanitized = '<svg>sanitized</svg>';
expect(service.getCachedSanitized('missing')).toBeNull();
@@ -1,21 +1,20 @@
import {Injectable} from '@angular/core';
import {SafeHtml} from '@angular/platform-browser';
import {BehaviorSubject} from 'rxjs';
interface CachedIcon {
content: string;
sanitized: SafeHtml;
sanitized: string;
}
@Injectable({
providedIn: 'root'
})
export class IconCacheService {
private cache = new Map<string, CachedIcon>();
export class CustomSvgCacheService {
private readonly cache = new Map<string, CachedIcon>();
private cacheUpdate$ = new BehaviorSubject<string | null>(null);
private readonly cacheUpdate$ = new BehaviorSubject<string | null>(null);
getCachedSanitized(iconName: string): SafeHtml | null {
getCachedSanitized(iconName: string): string | null {
const cached = this.cache.get(iconName);
if (!cached) {
@@ -25,7 +24,7 @@ export class IconCacheService {
return cached.sanitized;
}
cacheIcon(iconName: string, content: string, sanitized: SafeHtml): void {
cacheIcon(iconName: string, content: string, sanitized: string): void {
this.cache.set(iconName, {
content,
sanitized
@@ -38,6 +37,6 @@ export class IconCacheService {
}
getAllIconNames(): string[] {
return Array.from(this.cache.keys()).sort();
return Array.from(this.cache.keys()).sort((left, right) => left.localeCompare(right));
}
}
@@ -1,47 +1,40 @@
import {provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {IconCacheService} from './icon-cache.service';
import {IconService} from './icon.service';
import {CustomSvgCacheService} from './custom-svg-cache.service';
import {CustomSvgService} from './custom-svg.service';
describe('IconService', () => {
let service: IconService;
describe('CustomSvgService', () => {
let service: CustomSvgService;
let httpTestingController: HttpTestingController;
let iconCache: {
let customSvgCache: {
getCachedSanitized: ReturnType<typeof vi.fn>;
cacheIcon: ReturnType<typeof vi.fn>;
removeIcon: ReturnType<typeof vi.fn>;
};
let bypassSecurityTrustHtml: ReturnType<typeof vi.fn>;
beforeEach(() => {
iconCache = {
customSvgCache = {
getCachedSanitized: vi.fn(() => null),
cacheIcon: vi.fn(),
removeIcon: vi.fn(),
};
bypassSecurityTrustHtml = vi.fn(value => value as SafeHtml);
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
IconService,
CustomSvgService,
{
provide: IconCacheService,
useValue: iconCache,
},
{
provide: DomSanitizer,
useValue: {bypassSecurityTrustHtml},
provide: CustomSvgCacheService,
useValue: customSvgCache,
},
],
});
service = TestBed.inject(IconService);
service = TestBed.inject(CustomSvgService);
httpTestingController = TestBed.inject(HttpTestingController);
});
@@ -65,7 +58,7 @@ describe('IconService', () => {
});
it('short-circuits svg content requests when the sanitized icon is already cached', () => {
iconCache.getCachedSanitized.mockReturnValue('cached-safe-html' as SafeHtml);
customSvgCache.getCachedSanitized.mockReturnValue('cached-svg');
let result: string | undefined;
service.getSvgIconContent('sun').subscribe(value => {
@@ -88,8 +81,7 @@ describe('IconService', () => {
request.flush('<svg><rect /></svg>');
expect(result).toBe('<svg><rect /></svg>');
expect(bypassSecurityTrustHtml).toHaveBeenCalled();
expect(iconCache.cacheIcon).toHaveBeenCalledWith(
expect(customSvgCache.cacheIcon).toHaveBeenCalledWith(
'sun',
'<svg><rect /></svg>',
expect.stringContaining('<svg>')
@@ -97,15 +89,15 @@ describe('IconService', () => {
});
it('returns cached sanitized svg content without issuing a request', () => {
iconCache.getCachedSanitized.mockReturnValue('cached-safe-html' as SafeHtml);
customSvgCache.getCachedSanitized.mockReturnValue('cached-svg');
let result: SafeHtml | undefined;
let result: string | undefined;
service.getSanitizedSvgContent('moon').subscribe(value => {
result = value;
});
httpTestingController.expectNone(req => req.url.includes('/api/v1/icons/moon/content'));
expect(result).toBe('cached-safe-html');
expect(result).toBe('cached-svg');
});
it('removes icons from the cache after deletion', () => {
@@ -115,7 +107,7 @@ describe('IconService', () => {
expect(request.request.method).toBe('DELETE');
request.flush(null);
expect(iconCache.removeIcon).toHaveBeenCalledWith('sun rise');
expect(customSvgCache.removeIcon).toHaveBeenCalledWith('sun rise');
});
it('caches only successfully saved icons from batch saves', () => {
@@ -139,7 +131,7 @@ describe('IconService', () => {
],
});
expect(iconCache.cacheIcon).toHaveBeenCalledTimes(1);
expect(iconCache.cacheIcon).toHaveBeenCalledWith('sun', '<svg>sun</svg>', '<svg>sun</svg>');
expect(customSvgCache.cacheIcon).toHaveBeenCalledTimes(1);
expect(customSvgCache.cacheIcon).toHaveBeenCalledWith('sun', '<svg>sun</svg>', '<svg>sun</svg>');
});
});
@@ -3,8 +3,7 @@ import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { finalize, map, shareReplay, tap } from 'rxjs/operators';
import { API_CONFIG } from '../../core/config/api-config';
import { IconCacheService } from './icon-cache.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { CustomSvgCacheService } from './custom-svg-cache.service';
import DOMPurify from 'dompurify';
interface SvgIconData {
@@ -28,18 +27,14 @@ interface SvgIconBatchResponse {
@Injectable({
providedIn: 'root'
})
export class IconService {
export class CustomSvgService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/icons`;
private requestCache = new Map<string, Observable<string>>();
private readonly requestCache = new Map<string, Observable<string>>();
private http = inject(HttpClient);
private iconCache = inject(IconCacheService);
private sanitizer = inject(DomSanitizer);
private readonly http = inject(HttpClient);
private readonly customSvgCache = inject(CustomSvgCacheService);
/**
* Sanitizes SVG content using DOMPurify.
*/
private sanitizeSvgContent(content: string): string {
return DOMPurify.sanitize(content, {
USE_PROFILES: { svg: true },
@@ -54,8 +49,8 @@ export class IconService {
}
getSvgIconContent(iconName: string): Observable<string> {
const cached = this.iconCache.getCachedSanitized(iconName);
if (cached) {
const cached = this.customSvgCache.getCachedSanitized(iconName);
if (cached !== null) {
return of('');
}
@@ -64,8 +59,8 @@ export class IconService {
responseType: 'text'
}).pipe(
tap(content => {
const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(content));
this.iconCache.cacheIcon(iconName, content, sanitized);
const sanitized = this.sanitizeSvgContent(content);
this.customSvgCache.cacheIcon(iconName, content, sanitized);
}),
shareReplay({ bufferSize: 1, refCount: true }),
finalize(() => this.requestCache.delete(iconName))
@@ -77,17 +72,17 @@ export class IconService {
return this.requestCache.get(iconName)!;
}
getSanitizedSvgContent(iconName: string): Observable<SafeHtml> {
const cached = this.iconCache.getCachedSanitized(iconName);
if (cached) {
getSanitizedSvgContent(iconName: string): Observable<string> {
const cached = this.customSvgCache.getCachedSanitized(iconName);
if (cached !== null) {
return of(cached);
}
return new Observable<SafeHtml>(observer => {
return new Observable<string>(observer => {
this.getSvgIconContent(iconName).subscribe({
next: () => {
const sanitized = this.iconCache.getCachedSanitized(iconName);
if (sanitized) {
const sanitized = this.customSvgCache.getCachedSanitized(iconName);
if (sanitized !== null) {
observer.next(sanitized);
observer.complete();
}
@@ -100,7 +95,7 @@ export class IconService {
deleteSvgIcon(svgName: string): Observable<unknown> {
return this.http.delete(`${this.baseUrl}/${encodeURIComponent(svgName)}`).pipe(
tap(() => {
this.iconCache.removeIcon(svgName);
this.customSvgCache.removeIcon(svgName);
this.requestCache.delete(svgName);
})
);
@@ -113,8 +108,8 @@ export class IconService {
if (result.success) {
const iconData = icons.find(icon => icon.svgName === result.iconName);
if (iconData) {
const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(iconData.svgData));
this.iconCache.cacheIcon(iconData.svgName, iconData.svgData, sanitized);
const sanitized = this.sanitizeSvgContent(iconData.svgData);
this.customSvgCache.cacheIcon(iconData.svgName, iconData.svgData, sanitized);
}
}
});
+1
View File
@@ -634,6 +634,7 @@
"chooseIcon": "Choose an Icon",
"chooseIconSubtitle": "Select from available icons",
"selectedIcon": "Selected Icon",
"customSvg": "Custom SVG",
"removeIconTooltip": "Remove icon",
"visibilityLabel": "Visibility",
"makePublicLabel": "Make this shelf public (read-only for others)",
+2
View File
@@ -21,10 +21,12 @@ import { provideServiceWorker } from '@angular/service-worker';
import { provideTransloco } from '@jsverse/transloco';
import { AVAILABLE_LANGS, TranslocoInlineLoader } from './app/core/config/transloco-loader';
import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental';
import { provideLucideConfig } from '@lucide/angular';
bootstrapApplication(AppComponent, {
providers: [
provideZonelessChangeDetection(),
provideLucideConfig({ size: '1em', strokeWidth: 2 }),
provideTanStackQuery(new QueryClient({
defaultOptions: {
queries: {
+23
View File
@@ -52,6 +52,9 @@ importers:
'@jsverse/transloco':
specifier: ^8.4.0
version: 8.4.0(@angular/core@21.2.17(@angular/compiler@21.2.17)(rxjs@7.8.2))(rxjs@7.8.2)(typescript@5.9.3)
'@lucide/angular':
specifier: ^1.18.0
version: 1.18.0(@angular/common@21.2.17(@angular/core@21.2.17(@angular/compiler@21.2.17)(rxjs@7.8.2))(rxjs@7.8.2))(@angular/core@21.2.17(@angular/compiler@21.2.17)(rxjs@7.8.2))
'@primeuix/themes':
specifier: ^2.0.3
version: 2.0.3
@@ -88,6 +91,9 @@ importers:
dompurify:
specifier: ^3.4.10
version: 3.4.10
lucide-static:
specifier: 1.18.0
version: 1.18.0
markdown-it:
specifier: ^14.2.0
version: 14.2.0
@@ -1558,6 +1564,12 @@ packages:
cpu: [x64]
os: [win32]
'@lucide/angular@1.18.0':
resolution: {integrity: sha512-YNJC1Gnbzg0p1EGD5suehI5tdbjfoi5qFP1MfTD5l8e2YYHO3M83Q4c5AF9/E/xFqAwqVZxiDcB3KJqPA5blIw==}
peerDependencies:
'@angular/common': '>=17.0.0'
'@angular/core': '>=17.0.0'
'@modelcontextprotocol/sdk@1.26.0':
resolution: {integrity: sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==}
engines: {node: '>=18'}
@@ -4161,6 +4173,9 @@ packages:
lru-cache@5.1.1:
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
lucide-static@1.18.0:
resolution: {integrity: sha512-0WRXLQnjbte5SXuzom6yfeGlVSFsEsC9rzxn66DZN0pXows3+N34CQHy3BHI1qA3uH7u/SUzx8LQhjeAnxd8JQ==}
magic-string@0.30.21:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -7141,6 +7156,12 @@ snapshots:
'@lmdb/lmdb-win32-x64@3.5.1':
optional: true
'@lucide/angular@1.18.0(@angular/common@21.2.17(@angular/core@21.2.17(@angular/compiler@21.2.17)(rxjs@7.8.2))(rxjs@7.8.2))(@angular/core@21.2.17(@angular/compiler@21.2.17)(rxjs@7.8.2))':
dependencies:
'@angular/common': 21.2.17(@angular/core@21.2.17(@angular/compiler@21.2.17)(rxjs@7.8.2))(rxjs@7.8.2)
'@angular/core': 21.2.17(@angular/compiler@21.2.17)(rxjs@7.8.2)
tslib: 2.8.1
'@modelcontextprotocol/sdk@1.26.0(zod@4.3.6)':
dependencies:
'@hono/node-server': 1.19.14(hono@4.12.25)
@@ -9698,6 +9719,8 @@ snapshots:
dependencies:
yallist: 3.1.1
lucide-static@1.18.0: {}
magic-string@0.30.21:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5