Improve the SVG fetching and caching logic (#2011)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2025-12-27 15:26:11 -07:00
committed by GitHub
co-authored by acx10
parent 81757317e5
commit 9e151010e7
14 changed files with 368 additions and 374 deletions
@@ -1,4 +1,4 @@
import {Component, inject, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core';
import {Component, inject, Input, OnInit, OnChanges, SimpleChanges, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {IconSelection} from '../../service/icon-picker.service';
import {NgClass, NgStyle} from '@angular/common';
import {IconCacheService} from '../../services/icon-cache.service';
@@ -41,7 +41,8 @@ import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
height: 100%;
display: block;
}
`]
`],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class IconDisplayComponent implements OnInit, OnChanges {
@Input() icon: IconSelection | null = null;
@@ -53,28 +54,42 @@ export class IconDisplayComponent implements OnInit, OnChanges {
private iconCache = inject(IconCacheService);
private iconService = inject(IconService);
private sanitizer = inject(DomSanitizer);
private cdr = inject(ChangeDetectorRef);
private lastLoadedIconName: string | null = null;
ngOnInit(): void {
this.loadIconIfNeeded();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['icon'] && this.icon?.type === 'CUSTOM_SVG') {
this.loadIconIfNeeded();
if (changes['icon']) {
const currentIcon = changes['icon'].currentValue;
const previousIcon = changes['icon'].previousValue;
if (currentIcon?.type === 'CUSTOM_SVG' &&
currentIcon?.value !== previousIcon?.value) {
this.loadIconIfNeeded();
}
}
}
private loadIconIfNeeded(): void {
if (this.icon?.type === 'CUSTOM_SVG') {
this.iconService.getSanitizedSvgContent(this.icon.value).subscribe({
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.icon?.type === 'CUSTOM_SVG' && this.icon.value !== this.lastLoadedIconName) {
this.lastLoadedIconName = this.icon.value;
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);
this.cdr.markForCheck();
}
}
}
});
});
}
}
}
@@ -50,28 +50,6 @@
}
</div>
@if (totalSvgPages > 1) {
<div class="pagination-controls">
<p-button
(onClick)="loadSvgIcons(currentSvgPage - 1)"
[disabled]="currentSvgPage === 0"
label="Prev"
icon="pi pi-chevron-left"
outlined>
</p-button>
<span class="pagination-info">
Page {{ currentSvgPage + 1 }} of {{ totalSvgPages }}
</span>
<p-button
(onClick)="loadSvgIcons(currentSvgPage + 1)"
[disabled]="currentSvgPage >= totalSvgPages - 1"
label="Next"
icon="pi pi-chevron-right"
iconPos="right"
outlined>
</p-button>
</div>
}
@if (canManageIcons) {
<div style="display: flex; align-items: center; position: fixed; right: 32px; bottom: 32px; z-index: 101;">
@@ -43,7 +43,6 @@ interface SvgIconBatchResponse {
})
export class IconPickerComponent implements OnInit {
private readonly SVG_PAGE_SIZE = 50;
private readonly MAX_ICON_NAME_LENGTH = 255;
private readonly MAX_SVG_SIZE = 1048576; // 1MB
private readonly ICON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
@@ -80,8 +79,8 @@ export class IconPickerComponent implements OnInit {
set activeTabIndex(value: string) {
this._activeTabIndex = value;
if (value === '1' && this.svgIcons.length === 0 && !this.isLoadingSvgIcons) {
this.loadSvgIcons(0);
if (value === '1' && this.svgIcons.length === 0) {
this.loadSvgIconsFromCache();
}
}
@@ -96,8 +95,6 @@ export class IconPickerComponent implements OnInit {
svgIcons: string[] = [];
svgSearchText: string = '';
currentSvgPage: number = 0;
totalSvgPages: number = 0;
isLoadingSvgIcons: boolean = false;
svgIconsError: string = '';
selectedSvgIcon: string | null = null;
@@ -105,9 +102,15 @@ export class IconPickerComponent implements OnInit {
draggedSvgIcon: string | null = null;
isTrashHover: boolean = false;
get canManageIcons(): boolean {
const user = this.userService.getCurrentUser();
return user?.permissions.canManageIcons || user?.permissions.admin || false;
}
ngOnInit(): void {
if (this.activeTabIndex === '1') {
this.loadSvgIcons(0);
this.loadSvgIconsFromCache();
}
}
@@ -126,44 +129,8 @@ export class IconPickerComponent implements OnInit {
this.ref.close({type: 'PRIME_NG', value: icon});
}
loadSvgIcons(page: number): void {
this.isLoadingSvgIcons = true;
this.svgIconsError = '';
this.iconService.getIconNames(page, this.SVG_PAGE_SIZE).subscribe({
next: (response) => {
this.svgIcons = response.content;
this.currentSvgPage = response.number;
this.totalSvgPages = response.totalPages;
this.isLoadingSvgIcons = false;
this.preloadSvgContent(response.content);
},
error: () => {
this.isLoadingSvgIcons = false;
this.svgIconsError = this.ERROR_MESSAGES.LOAD_ICONS_ERROR;
}
});
}
private preloadSvgContent(iconNames: string[]): void {
iconNames.forEach(iconName => {
if (!this.iconCache.isCached(iconName)) {
this.loadSvgContent(iconName);
}
});
}
private loadSvgContent(iconName: string): void {
this.iconService.getSanitizedSvgContent(iconName).subscribe({
next: () => {
},
error: () => {
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(iconName, errorSvg, sanitized);
}
});
private loadSvgIconsFromCache(): void {
this.svgIcons = this.iconCache.getAllIconNames();
}
getSvgContent(iconName: string): SafeHtml | null {
@@ -254,47 +221,78 @@ export class IconPickerComponent implements OnInit {
this.iconService.saveBatchSvgIcons(svgData).subscribe({
next: (response: SvgIconBatchResponse) => {
this.isSavingBatch = false;
this.handleBatchSaveResponse(response);
let successCount = 0;
let failureCount = 0;
response.results.forEach(result => {
if (result.success) {
successCount++;
} else {
failureCount++;
const entry = this.svgEntries.find(e => e.name === result.iconName);
if (entry) {
entry.error = result.errorMessage;
}
}
});
if (successCount > 0 && failureCount === 0) {
this.messageService.add({
severity: 'success',
summary: 'Icons Saved',
detail: `${successCount} SVG icon${successCount > 1 ? 's' : ''} saved successfully.`,
life: 2500
});
} else if (successCount > 0 && failureCount > 0) {
this.messageService.add({
severity: 'warn',
summary: 'Partial Success',
detail: `${successCount} SVG icon${successCount > 1 ? 's' : ''} saved, ${failureCount} failed.`,
life: 3500
});
} else if (failureCount > 0) {
this.messageService.add({
severity: 'error',
summary: 'Save Failed',
detail: `Failed to save ${failureCount} SVG icon${failureCount > 1 ? 's' : ''}.`,
life: 4000
});
}
this.clearAllEntries();
this.loadSvgIconsFromCache();
},
error: (error) => {
error: () => {
this.isSavingBatch = false;
this.batchErrorMessage = error.error?.message || 'Failed to save SVG icons. Please try again.';
this.batchErrorMessage = 'Failed to save SVG icons. Please try again.';
}
});
}
private handleBatchSaveResponse(response: SvgIconBatchResponse): void {
if (response.failureCount === 0) {
this.handleSuccessfulBatchSave();
return;
}
private deleteSvgIcon(iconName: string): void {
this.isLoadingSvgIcons = true;
response.results.forEach(result => {
if (!result.success) {
const entryIndex = this.svgEntries.findIndex(entry => entry.name === result.iconName);
if (entryIndex !== -1) {
this.svgEntries[entryIndex].error = result.errorMessage;
}
this.iconService.deleteSvgIcon(iconName).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Icon Deleted',
detail: 'SVG icon deleted successfully.',
life: 2500
});
this.svgIcons = this.svgIcons.filter(name => name !== iconName);
this.isLoadingSvgIcons = false;
},
error: (error) => {
this.isLoadingSvgIcons = false;
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: error.error?.message || this.ERROR_MESSAGES.DELETE_ERROR,
life: 4000
});
}
});
const successfulNames = response.results
.filter(result => result.success)
.map(result => result.iconName);
this.svgEntries = this.svgEntries.filter(entry => !successfulNames.includes(entry.name));
if (response.successCount > 0) {
this.messageService.add({
severity: 'warn',
summary: 'Partial Success',
detail: `${response.successCount} of ${response.totalRequested} icon(s) saved successfully. ${response.failureCount} failed.`,
life: 5000
});
this.loadSvgIcons(0);
} else {
this.batchErrorMessage = `Failed to save ${response.failureCount} icon(s). Please fix the errors and try again.`;
}
}
private validateSvgInput(): string | null {
@@ -306,44 +304,27 @@ export class IconPickerComponent implements OnInit {
return this.ERROR_MESSAGES.NO_NAME;
}
if (!this.ICON_NAME_PATTERN.test(this.svgName)) {
return this.ERROR_MESSAGES.INVALID_NAME;
}
if (this.svgName.length > this.MAX_ICON_NAME_LENGTH) {
return this.ERROR_MESSAGES.NAME_TOO_LONG;
}
if (!this.svgContent.trim().includes('<svg')) {
return this.ERROR_MESSAGES.INVALID_SVG;
if (!this.ICON_NAME_PATTERN.test(this.svgName)) {
return this.ERROR_MESSAGES.INVALID_NAME;
}
if (this.svgContent.length > this.MAX_SVG_SIZE) {
const svgSize = new Blob([this.svgContent]).size;
if (svgSize > this.MAX_SVG_SIZE) {
return this.ERROR_MESSAGES.SVG_TOO_LARGE;
}
return null;
}
private handleSuccessfulBatchSave(): void {
this.messageService.add({
severity: 'success',
summary: 'Icons Saved',
detail: `${this.svgEntries.length} SVG icon(s) saved successfully.`,
life: 3000
});
this.activeTabIndex = '1';
this.loadSvgIcons(0);
this.clearAllEntries();
this.resetSvgForm();
}
private resetSvgForm(): void {
this.svgSearchText = '';
this.svgContent = '';
this.svgName = '';
this.svgPreview = null;
this.errorMessage = '';
}
onSvgIconDragStart(iconName: string): void {
@@ -352,7 +333,6 @@ export class IconPickerComponent implements OnInit {
onSvgIconDragEnd(): void {
this.draggedSvgIcon = null;
this.isTrashHover = false;
}
onTrashDragOver(event: DragEvent): void {
@@ -369,41 +349,9 @@ export class IconPickerComponent implements OnInit {
event.preventDefault();
this.isTrashHover = false;
if (!this.draggedSvgIcon) {
return;
if (this.draggedSvgIcon) {
this.deleteSvgIcon(this.draggedSvgIcon);
this.draggedSvgIcon = null;
}
this.deleteSvgIcon(this.draggedSvgIcon);
this.draggedSvgIcon = null;
}
private deleteSvgIcon(iconName: string): void {
this.isLoadingSvgIcons = true;
this.iconService.deleteSvgIcon(iconName).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Icon Deleted',
detail: 'SVG icon deleted successfully.',
life: 2500
});
this.loadSvgIcons(this.currentSvgPage);
},
error: (error) => {
this.isLoadingSvgIcons = false;
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: error.error?.message || this.ERROR_MESSAGES.DELETE_ERROR,
life: 4000
});
}
});
}
get canManageIcons(): boolean {
const user = this.userService.getCurrentUser();
return user?.permissions.canManageIcons || user?.permissions.admin || false;
}
}
@@ -1,11 +1,10 @@
import {Injectable} from '@angular/core';
import {SafeHtml} from '@angular/platform-browser';
import {Observable, BehaviorSubject} from 'rxjs';
import {BehaviorSubject} from 'rxjs';
interface CachedIcon {
content: string;
sanitized: SafeHtml;
timestamp: number;
}
@Injectable({
@@ -13,25 +12,9 @@ interface CachedIcon {
})
export class IconCacheService {
private cache = new Map<string, CachedIcon>();
private readonly CACHE_DURATION_MS = 1000 * 60 * 60;
private cacheUpdate$ = new BehaviorSubject<string | null>(null);
getCachedContent(iconName: string): string | null {
const cached = this.cache.get(iconName);
if (!cached) {
return null;
}
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
this.cache.delete(iconName);
return null;
}
return cached.content;
}
getCachedSanitized(iconName: string): SafeHtml | null {
const cached = this.cache.get(iconName);
@@ -39,55 +22,22 @@ export class IconCacheService {
return null;
}
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
this.cache.delete(iconName);
return null;
}
return cached.sanitized;
}
cacheIcon(iconName: string, content: string, sanitized: SafeHtml): void {
this.cache.set(iconName, {
content,
sanitized,
timestamp: Date.now()
sanitized
});
this.cacheUpdate$.next(iconName);
}
isCached(iconName: string): boolean {
const cached = this.cache.get(iconName);
if (!cached) {
return false;
}
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
this.cache.delete(iconName);
return false;
}
return true;
removeIcon(iconName: string): boolean {
return this.cache.delete(iconName);
}
invalidate(iconName: string): void {
this.cache.delete(iconName);
this.cacheUpdate$.next(null);
}
invalidateMultiple(iconNames: string[]): void {
iconNames.forEach(name => this.cache.delete(name));
this.cacheUpdate$.next(null);
}
clearCache(): void {
this.cache.clear();
this.cacheUpdate$.next(null);
}
getCacheUpdates(): Observable<string | null> {
return this.cacheUpdate$.asObservable();
getAllIconNames(): string[] {
return Array.from(this.cache.keys()).sort();
}
}
@@ -1,19 +1,11 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {tap} from 'rxjs/operators';
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';
interface PageResponse<T> {
content: T[];
number: number;
size: number;
totalElements: number;
totalPages: number;
}
interface SvgIconData {
svgName: string;
svgData: string;
@@ -32,44 +24,65 @@ interface SvgIconBatchResponse {
results: IconSaveResult[];
}
interface IconContentMap {
[iconName: string]: string;
}
@Injectable({
providedIn: 'root'
})
export class IconService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/icons`;
private requestCache = new Map<string, Observable<string>>();
private preloadCache$: Observable<void> | null = null;
private http = inject(HttpClient);
private iconCache = inject(IconCacheService);
private sanitizer = inject(DomSanitizer);
saveSvgIcon(svgContent: string, svgName: string): Observable<any> {
return this.http.post(this.baseUrl, {
svgData: svgContent,
svgName: svgName
});
}
preloadAllIcons(): Observable<void> {
if (this.preloadCache$) {
return this.preloadCache$;
}
getIconNames(page: number = 0, size: number = 50): Observable<PageResponse<string>> {
return this.http.get<PageResponse<string>>(this.baseUrl, {
params: {page: page.toString(), size: size.toString()}
});
this.preloadCache$ = this.http.get<IconContentMap>(`${this.baseUrl}/all/content`).pipe(
tap((iconsMap) => {
Object.entries(iconsMap).forEach(([iconName, content]) => {
const sanitized = this.sanitizer.bypassSecurityTrustHtml(content);
this.iconCache.cacheIcon(iconName, content, sanitized);
});
}),
map(() => void 0),
shareReplay({bufferSize: 1, refCount: false}),
finalize(() => this.preloadCache$ = null)
);
return this.preloadCache$;
}
getSvgIconContent(iconName: string): Observable<string> {
const cached = this.iconCache.getCachedContent(iconName);
const cached = this.iconCache.getCachedSanitized(iconName);
if (cached) {
return of(cached);
return of('');
}
return this.http.get(`${this.baseUrl}/${encodeURIComponent(iconName)}/content`, {
responseType: 'text'
}).pipe(
tap(content => {
const sanitized = this.sanitizer.bypassSecurityTrustHtml(content);
this.iconCache.cacheIcon(iconName, content, sanitized);
})
);
if (!this.requestCache.has(iconName)) {
const request$ = this.http.get(`${this.baseUrl}/${encodeURIComponent(iconName)}/content`, {
responseType: 'text'
}).pipe(
tap(content => {
const sanitized = this.sanitizer.bypassSecurityTrustHtml(content);
this.iconCache.cacheIcon(iconName, content, sanitized);
}),
shareReplay({bufferSize: 1, refCount: true}),
finalize(() => this.requestCache.delete(iconName))
);
this.requestCache.set(iconName, request$);
}
return this.requestCache.get(iconName)!;
}
getSanitizedSvgContent(iconName: string): Observable<SafeHtml> {
@@ -95,7 +108,8 @@ export class IconService {
deleteSvgIcon(svgName: string): Observable<any> {
return this.http.delete(`${this.baseUrl}/${encodeURIComponent(svgName)}`).pipe(
tap(() => {
this.iconCache.invalidate(svgName);
this.iconCache.removeIcon(svgName);
this.requestCache.delete(svgName);
})
);
}
@@ -103,11 +117,15 @@ export class IconService {
saveBatchSvgIcons(icons: SvgIconData[]): Observable<SvgIconBatchResponse> {
return this.http.post<SvgIconBatchResponse>(`${this.baseUrl}/batch`, {icons}).pipe(
tap((response) => {
const successfulIcons = response.results
.filter(result => result.success)
.map(result => result.iconName);
this.iconCache.invalidateMultiple(successfulIcons);
response.results.forEach(result => {
if (result.success) {
const iconData = icons.find(icon => icon.svgName === result.iconName);
if (iconData) {
const sanitized = this.sanitizer.bypassSecurityTrustHtml(iconData.svgData);
this.iconCache.cacheIcon(iconData.svgName, iconData.svgData, sanitized);
}
}
});
})
);
}