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
@@ -23,23 +23,23 @@
style="cursor: pointer;">
</i>
</label>
<div class="radio-group">
<div class="radio-option">
<p-radioButton name="viewMode"
[value]="'route'"
[(ngModel)]="viewMode"
inputId="viewModeRoute"
(onClick)="onViewModeChange('route')"></p-radioButton>
<label for="viewModeRoute">Open in Page</label>
</div>
<div class="radio-option">
<p-radioButton name="viewMode"
[value]="'dialog'"
[(ngModel)]="viewMode"
inputId="viewModeDialog"
(onClick)="onViewModeChange('dialog')"></p-radioButton>
<label for="viewModeDialog">Open in Popup</label>
</div>
<div class="button-group">
<button
type="button"
class="option-button"
[class.selected]="viewMode === 'route'"
(click)="onViewModeChange('route')">
<i class="pi pi-window-maximize"></i>
<span class="option-text">Open in Page</span>
</button>
<button
type="button"
class="option-button"
[class.selected]="viewMode === 'dialog'"
(click)="onViewModeChange('dialog')">
<i class="pi pi-external-link"></i>
<span class="option-text">Open in Dialog</span>
</button>
</div>
</div>
<p class="setting-description">
@@ -59,23 +59,23 @@
style="cursor: pointer;">
</i>
</label>
<div class="radio-group">
<div class="radio-option">
<p-radioButton name="seriesViewMode"
[value]="true"
[(ngModel)]="seriesViewMode"
inputId="seriesViewModeTrue"
(onClick)="onSeriesViewModeChange(true)"></p-radioButton>
<label for="seriesViewModeTrue">Enabled</label>
</div>
<div class="radio-option">
<p-radioButton name="seriesViewMode"
[value]="false"
[(ngModel)]="seriesViewMode"
inputId="seriesViewModeFalse"
(onClick)="onSeriesViewModeChange(false)"></p-radioButton>
<label for="seriesViewModeFalse">Disabled</label>
</div>
<div class="button-group">
<button
type="button"
class="option-button"
[class.selected]="seriesViewMode === true"
(click)="onSeriesViewModeChange(true)">
<i class="pi pi-check-circle"></i>
<span class="option-text">Enabled</span>
</button>
<button
type="button"
class="option-button"
[class.selected]="seriesViewMode === false"
(click)="onSeriesViewModeChange(false)">
<i class="pi pi-times-circle"></i>
<span class="option-text">Disabled</span>
</button>
</div>
</div>
<p class="setting-description">
@@ -64,6 +64,11 @@
gap: 2rem;
padding: 0.25rem 0;
&:last-child {
border-bottom: none;
padding-bottom: 0;
}
@media (max-width: 768px) {
flex-direction: column;
gap: 1rem;
@@ -96,16 +101,6 @@
flex-shrink: 0;
min-width: 150px;
}
.radio-group {
display: flex;
gap: 1.5rem;
@media (max-width: 768px) {
flex-direction: column;
gap: 0.75rem;
}
}
}
.setting-description {
@@ -129,24 +124,50 @@
}
}
.radio-group {
.button-group {
display: flex;
gap: 1.5rem;
@media (max-width: 768px) {
flex-direction: column;
gap: 0.75rem;
}
}
.radio-option {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
label {
font-size: 0.875rem;
color: var(--p-text-color);
.option-button {
display: flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
padding: 0.5rem 0.75rem;
border-radius: 0.375rem;
border: 1.5px solid color-mix(in srgb, var(--text-color) 20%, transparent);
background: color-mix(in srgb, var(--text-color) 5%, transparent);
color: var(--text-color);
cursor: pointer;
transition: all 0.2s ease;
font-size: 0.8125rem;
font-weight: 500;
min-width: 4.5rem;
i {
font-size: 0.875rem;
}
.option-text {
white-space: nowrap;
}
&:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
border-color: color-mix(in srgb, var(--primary-color) 40%, transparent);
}
&.selected {
border-color: var(--primary-color);
background: color-mix(in srgb, var(--primary-color) 10%, transparent);
color: var(--primary-color);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 15%, transparent);
&:hover {
transform: translateY(-2px);
}
}
}
}
@@ -1,6 +1,5 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Tooltip} from 'primeng/tooltip';
import {RadioButton} from 'primeng/radiobutton';
import {FormsModule} from '@angular/forms';
import {UserService} from '../../user-management/user.service';
import {MessageService} from 'primeng/api';
@@ -11,7 +10,6 @@ import {Subject} from 'rxjs';
selector: 'app-meta-center-view-mode-component',
imports: [
Tooltip,
RadioButton,
FormsModule
],
templateUrl: './meta-center-view-mode-component.html',
@@ -28,11 +28,11 @@
<label class="setting-label">Default Preferences</label>
<div class="select-group">
<p-select size="small" [options]="sortOptions" optionLabel="label" optionValue="field"
[(ngModel)]="selectedSort" placeholder="Sort" class="select-item"></p-select>
[(ngModel)]="selectedSort" placeholder="Sort By" class="select-item" appendTo="body"></p-select>
<p-select size="small" [options]="sortDirectionOptions" [(ngModel)]="selectedSortDir"
placeholder="Direction" class="select-item"></p-select>
placeholder="Direction" class="select-item" appendTo="body"></p-select>
<p-select size="small" [options]="viewModeOptions" [(ngModel)]="selectedView"
placeholder="View" class="select-item"></p-select>
placeholder="View Mode" class="select-item" appendTo="body"></p-select>
</div>
</div>
<p class="setting-description">
@@ -57,35 +57,35 @@
<div class="settings-card">
<div class="setting-item no-border">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Override Management</label>
<p-button label="Add New Override" outlined size="small" (onClick)="addOverride()"
severity="info" icon="pi pi-plus" [disabled]="availableLibraries.length === 0"></p-button>
</div>
<label class="setting-label">Override Management</label>
<p class="setting-description">
Add custom preferences for specific libraries or shelves.
Add custom preferences for specific libraries or shelves. These will override your default settings.
</p>
</div>
<div class="setting-control">
<p-button label="Add Override" outlined size="small" (onClick)="addOverride()"
severity="success" icon="pi pi-plus" [disabled]="availableLibraries.length === 0"></p-button>
</div>
</div>
@if (overrides.length > 0) {
<div class="overrides-table">
<p-table [value]="overrides">
<p-table [value]="overrides" [tableStyle]="{'width': '100%'}">
<ng-template pTemplate="header">
<tr>
<th class="min-w-[150px] max-w-[220px]">Type</th>
<th class="min-w-[220px] max-w-[280px]">Name</th>
<th class="min-w-[190px] max-w-[250px]">Sort By</th>
<th class="min-w-[125px]">Sort Dir</th>
<th class="min-w-[125px]">View</th>
<th class="w-[75px] text-center"></th>
<th style="min-width: 150px; max-width: 220px;">Type</th>
<th style="min-width: 220px; max-width: 280px;">Name</th>
<th style="min-width: 190px; max-width: 250px;">Sort By</th>
<th style="min-width: 125px;">Direction</th>
<th style="min-width: 125px;">View Mode</th>
<th style="width: 75px; text-align: center;">Actions</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-override let-rowIndex="rowIndex">
<tr>
<td>
<p-select size="small" [options]="entityTypeOptions" [(ngModel)]="override.entityType"
class="w-full" appendTo="body"></p-select>
[style]="{'width': '100%'}" appendTo="body"></p-select>
</td>
<td>
@if (override.entityType) {
@@ -93,24 +93,24 @@
[options]="getAvailableEntities(rowIndex, override.entityType)"
[(ngModel)]="override.library"
optionLabel="label" optionValue="value"
class="w-full" appendTo="body"></p-select>
[style]="{'width': '100%'}" appendTo="body"></p-select>
}
</td>
<td>
<p-select size="small" [options]="sortOptions" optionLabel="label" optionValue="field"
[(ngModel)]="override.sort" class="w-full" appendTo="body"></p-select>
[(ngModel)]="override.sort" [style]="{'width': '100%'}" appendTo="body"></p-select>
</td>
<td>
<p-select size="small" [options]="sortDirectionOptions" [(ngModel)]="override.sortDir"
class="w-full" appendTo="body"></p-select>
[style]="{'width': '100%'}" appendTo="body"></p-select>
</td>
<td>
<p-select size="small" [options]="viewModeOptions" [(ngModel)]="override.view"
class="w-full" appendTo="body"></p-select>
[style]="{'width': '100%'}" appendTo="body"></p-select>
</td>
<td class="text-center">
<td style="text-align: center;">
<p-button icon="pi pi-trash" severity="danger" size="small" [outlined]="true"
(onClick)="removeOverride(rowIndex)"></p-button>
(onClick)="removeOverride(rowIndex)" [pTooltip]="'Remove override'" tooltipPosition="left"></p-button>
</td>
</tr>
</ng-template>
@@ -121,7 +121,7 @@
</div>
<div class="save-section">
<p-button label="Save Settings" icon="pi pi-save" severity="success" outlined (onClick)="saveSettings()"></p-button>
<p-button label="Save Settings" icon="pi pi-save" severity="success" (onClick)="saveSettings()"></p-button>
</div>
</div>
</div>
@@ -1,6 +1,7 @@
.main-container {
width: 100%;
padding: 1rem;
overflow-y: auto;
}
.enclosing-container {
@@ -88,7 +89,7 @@
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
gap: 1rem;
}
.setting-item {
@@ -139,17 +140,17 @@
.select-group {
display: flex;
gap: 1rem;
gap: 0.5rem;
flex-wrap: wrap;
@media (max-width: 768px) {
flex-direction: column;
gap: 0.75rem;
gap: 0.5rem;
width: 100%;
}
.select-item {
min-width: 150px;
min-width: 140px;
@media (max-width: 768px) {
min-width: 100%;
@@ -181,17 +182,17 @@
.select-group {
display: flex;
gap: 1rem;
gap: 0.5rem;
flex-wrap: wrap;
@media (max-width: 768px) {
flex-direction: column;
gap: 0.75rem;
gap: 0.5rem;
width: 100%;
}
.select-item {
min-width: 200px;
min-width: 140px;
@media (max-width: 768px) {
min-width: 100%;
@@ -201,16 +202,35 @@
.overrides-table {
width: 100%;
margin-top: 1rem;
::ng-deep {
.p-datatable {
border: 1px solid var(--p-content-border-color);
border-radius: 6px;
overflow: hidden;
.p-datatable-thead > tr > th {
font-weight: 600;
padding: 0.75rem;
background: color-mix(in srgb, var(--text-color) 3%, transparent);
border-bottom: 1px solid var(--p-content-border-color);
font-size: 0.875rem;
}
.p-datatable-tbody > tr > td {
padding: 0.5rem;
.p-datatable-tbody > tr {
&:hover {
background: color-mix(in srgb, var(--text-color) 3%, transparent);
}
> td {
padding: 0.75rem;
border-bottom: 1px solid color-mix(in srgb, var(--p-content-border-color) 50%, transparent);
}
&:last-child > td {
border-bottom: none;
}
}
}
}
@@ -10,6 +10,7 @@ import {ShelfService} from '../../../book/service/shelf.service';
import {combineLatest, Subject} from 'rxjs';
import {FormsModule} from '@angular/forms';
import {ToastModule} from 'primeng/toast';
import {Tooltip} from 'primeng/tooltip';
import {filter, take, takeUntil} from 'rxjs/operators';
@Component({
@@ -20,7 +21,8 @@ import {filter, take, takeUntil} from 'rxjs/operators';
FormsModule,
Button,
TableModule,
ToastModule
ToastModule,
Tooltip
],
templateUrl: './view-preferences.component.html',
styleUrl: './view-preferences.component.scss'
@@ -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);
}
}
});
})
);
}