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,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));
}
}