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
@@ -15,6 +15,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Map;
@Tag(name = "Icons", description = "Endpoints for managing SVG icons") @Tag(name = "Icons", description = "Endpoints for managing SVG icons")
@AllArgsConstructor @AllArgsConstructor
@RestController @RestController
@@ -69,4 +71,12 @@ public class IconController {
iconService.deleteSvgIcon(svgName); iconService.deleteSvgIcon(svgName);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@Operation(summary = "Get all icon contents", description = "Retrieve all SVG icons as a map of icon names to their content.")
@ApiResponse(responseCode = "200", description = "All icon contents retrieved successfully")
@GetMapping("/all/content")
public ResponseEntity<Map<String, String>> getAllIconsContent() {
Map<String, String> iconsMap = iconService.getAllIconsContent();
return ResponseEntity.ok(iconsMap);
}
} }
@@ -19,7 +19,9 @@ import java.nio.file.Paths;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -271,4 +273,35 @@ public class IconService {
ConcurrentHashMap<String, String> getSvgCache() { ConcurrentHashMap<String, String> getSvgCache() {
return svgCache; return svgCache;
} }
public Map<String, String> getAllIconsContent() {
Path iconsPath = getIconsSvgPath();
if (!Files.exists(iconsPath)) {
return Collections.emptyMap();
}
try (Stream<Path> paths = Files.list(iconsPath)) {
Map<String, String> iconMap = new HashMap<>();
paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(SVG_EXTENSION))
.forEach(path -> {
try {
String filename = path.getFileName().toString();
String iconName = filename.replace(SVG_EXTENSION, "");
String content = svgCache.getOrDefault(filename, Files.readString(path));
iconMap.put(iconName, content);
} catch (IOException e) {
log.warn("Failed to read icon: {}", path.getFileName(), e);
}
});
log.info("Retrieved {} icons for bulk content request", iconMap.size());
return iconMap;
} catch (IOException e) {
log.error("Failed to read icons directory: {}", e.getMessage(), e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read icons: " + e.getMessage());
}
}
} }
@@ -23,23 +23,23 @@
style="cursor: pointer;"> style="cursor: pointer;">
</i> </i>
</label> </label>
<div class="radio-group"> <div class="button-group">
<div class="radio-option"> <button
<p-radioButton name="viewMode" type="button"
[value]="'route'" class="option-button"
[(ngModel)]="viewMode" [class.selected]="viewMode === 'route'"
inputId="viewModeRoute" (click)="onViewModeChange('route')">
(onClick)="onViewModeChange('route')"></p-radioButton> <i class="pi pi-window-maximize"></i>
<label for="viewModeRoute">Open in Page</label> <span class="option-text">Open in Page</span>
</div> </button>
<div class="radio-option"> <button
<p-radioButton name="viewMode" type="button"
[value]="'dialog'" class="option-button"
[(ngModel)]="viewMode" [class.selected]="viewMode === 'dialog'"
inputId="viewModeDialog" (click)="onViewModeChange('dialog')">
(onClick)="onViewModeChange('dialog')"></p-radioButton> <i class="pi pi-external-link"></i>
<label for="viewModeDialog">Open in Popup</label> <span class="option-text">Open in Dialog</span>
</div> </button>
</div> </div>
</div> </div>
<p class="setting-description"> <p class="setting-description">
@@ -59,23 +59,23 @@
style="cursor: pointer;"> style="cursor: pointer;">
</i> </i>
</label> </label>
<div class="radio-group"> <div class="button-group">
<div class="radio-option"> <button
<p-radioButton name="seriesViewMode" type="button"
[value]="true" class="option-button"
[(ngModel)]="seriesViewMode" [class.selected]="seriesViewMode === true"
inputId="seriesViewModeTrue" (click)="onSeriesViewModeChange(true)">
(onClick)="onSeriesViewModeChange(true)"></p-radioButton> <i class="pi pi-check-circle"></i>
<label for="seriesViewModeTrue">Enabled</label> <span class="option-text">Enabled</span>
</div> </button>
<div class="radio-option"> <button
<p-radioButton name="seriesViewMode" type="button"
[value]="false" class="option-button"
[(ngModel)]="seriesViewMode" [class.selected]="seriesViewMode === false"
inputId="seriesViewModeFalse" (click)="onSeriesViewModeChange(false)">
(onClick)="onSeriesViewModeChange(false)"></p-radioButton> <i class="pi pi-times-circle"></i>
<label for="seriesViewModeFalse">Disabled</label> <span class="option-text">Disabled</span>
</div> </button>
</div> </div>
</div> </div>
<p class="setting-description"> <p class="setting-description">
@@ -64,6 +64,11 @@
gap: 2rem; gap: 2rem;
padding: 0.25rem 0; padding: 0.25rem 0;
&:last-child {
border-bottom: none;
padding-bottom: 0;
}
@media (max-width: 768px) { @media (max-width: 768px) {
flex-direction: column; flex-direction: column;
gap: 1rem; gap: 1rem;
@@ -96,16 +101,6 @@
flex-shrink: 0; flex-shrink: 0;
min-width: 150px; min-width: 150px;
} }
.radio-group {
display: flex;
gap: 1.5rem;
@media (max-width: 768px) {
flex-direction: column;
gap: 0.75rem;
}
}
} }
.setting-description { .setting-description {
@@ -129,24 +124,50 @@
} }
} }
.radio-group { .button-group {
display: flex; 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; gap: 0.5rem;
flex-wrap: wrap;
label { .option-button {
font-size: 0.875rem; display: flex;
color: var(--p-text-color); 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; 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 {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {RadioButton} from 'primeng/radiobutton';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {UserService} from '../../user-management/user.service'; import {UserService} from '../../user-management/user.service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
@@ -11,7 +10,6 @@ import {Subject} from 'rxjs';
selector: 'app-meta-center-view-mode-component', selector: 'app-meta-center-view-mode-component',
imports: [ imports: [
Tooltip, Tooltip,
RadioButton,
FormsModule FormsModule
], ],
templateUrl: './meta-center-view-mode-component.html', templateUrl: './meta-center-view-mode-component.html',
@@ -28,11 +28,11 @@
<label class="setting-label">Default Preferences</label> <label class="setting-label">Default Preferences</label>
<div class="select-group"> <div class="select-group">
<p-select size="small" [options]="sortOptions" optionLabel="label" optionValue="field" <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" <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" <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>
</div> </div>
<p class="setting-description"> <p class="setting-description">
@@ -57,35 +57,35 @@
<div class="settings-card"> <div class="settings-card">
<div class="setting-item no-border"> <div class="setting-item no-border">
<div class="setting-info"> <div class="setting-info">
<div class="setting-label-row"> <label class="setting-label">Override Management</label>
<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>
<p class="setting-description"> <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> </p>
</div> </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> </div>
@if (overrides.length > 0) { @if (overrides.length > 0) {
<div class="overrides-table"> <div class="overrides-table">
<p-table [value]="overrides"> <p-table [value]="overrides" [tableStyle]="{'width': '100%'}">
<ng-template pTemplate="header"> <ng-template pTemplate="header">
<tr> <tr>
<th class="min-w-[150px] max-w-[220px]">Type</th> <th style="min-width: 150px; max-width: 220px;">Type</th>
<th class="min-w-[220px] max-w-[280px]">Name</th> <th style="min-width: 220px; max-width: 280px;">Name</th>
<th class="min-w-[190px] max-w-[250px]">Sort By</th> <th style="min-width: 190px; max-width: 250px;">Sort By</th>
<th class="min-w-[125px]">Sort Dir</th> <th style="min-width: 125px;">Direction</th>
<th class="min-w-[125px]">View</th> <th style="min-width: 125px;">View Mode</th>
<th class="w-[75px] text-center"></th> <th style="width: 75px; text-align: center;">Actions</th>
</tr> </tr>
</ng-template> </ng-template>
<ng-template pTemplate="body" let-override let-rowIndex="rowIndex"> <ng-template pTemplate="body" let-override let-rowIndex="rowIndex">
<tr> <tr>
<td> <td>
<p-select size="small" [options]="entityTypeOptions" [(ngModel)]="override.entityType" <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>
<td> <td>
@if (override.entityType) { @if (override.entityType) {
@@ -93,24 +93,24 @@
[options]="getAvailableEntities(rowIndex, override.entityType)" [options]="getAvailableEntities(rowIndex, override.entityType)"
[(ngModel)]="override.library" [(ngModel)]="override.library"
optionLabel="label" optionValue="value" optionLabel="label" optionValue="value"
class="w-full" appendTo="body"></p-select> [style]="{'width': '100%'}" appendTo="body"></p-select>
} }
</td> </td>
<td> <td>
<p-select size="small" [options]="sortOptions" optionLabel="label" optionValue="field" <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>
<td> <td>
<p-select size="small" [options]="sortDirectionOptions" [(ngModel)]="override.sortDir" <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>
<td> <td>
<p-select size="small" [options]="viewModeOptions" [(ngModel)]="override.view" <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>
<td class="text-center"> <td style="text-align: center;">
<p-button icon="pi pi-trash" severity="danger" size="small" [outlined]="true" <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> </td>
</tr> </tr>
</ng-template> </ng-template>
@@ -121,7 +121,7 @@
</div> </div>
<div class="save-section"> <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> </div>
</div> </div>
@@ -1,6 +1,7 @@
.main-container { .main-container {
width: 100%; width: 100%;
padding: 1rem; padding: 1rem;
overflow-y: auto;
} }
.enclosing-container { .enclosing-container {
@@ -88,7 +89,7 @@
padding: 1.5rem; padding: 1.5rem;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.5rem; gap: 1rem;
} }
.setting-item { .setting-item {
@@ -139,17 +140,17 @@
.select-group { .select-group {
display: flex; display: flex;
gap: 1rem; gap: 0.5rem;
flex-wrap: wrap; flex-wrap: wrap;
@media (max-width: 768px) { @media (max-width: 768px) {
flex-direction: column; flex-direction: column;
gap: 0.75rem; gap: 0.5rem;
width: 100%; width: 100%;
} }
.select-item { .select-item {
min-width: 150px; min-width: 140px;
@media (max-width: 768px) { @media (max-width: 768px) {
min-width: 100%; min-width: 100%;
@@ -181,17 +182,17 @@
.select-group { .select-group {
display: flex; display: flex;
gap: 1rem; gap: 0.5rem;
flex-wrap: wrap; flex-wrap: wrap;
@media (max-width: 768px) { @media (max-width: 768px) {
flex-direction: column; flex-direction: column;
gap: 0.75rem; gap: 0.5rem;
width: 100%; width: 100%;
} }
.select-item { .select-item {
min-width: 200px; min-width: 140px;
@media (max-width: 768px) { @media (max-width: 768px) {
min-width: 100%; min-width: 100%;
@@ -201,16 +202,35 @@
.overrides-table { .overrides-table {
width: 100%; width: 100%;
margin-top: 1rem;
::ng-deep { ::ng-deep {
.p-datatable { .p-datatable {
border: 1px solid var(--p-content-border-color);
border-radius: 6px;
overflow: hidden;
.p-datatable-thead > tr > th { .p-datatable-thead > tr > th {
font-weight: 600; font-weight: 600;
padding: 0.75rem; 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 { .p-datatable-tbody > tr {
padding: 0.5rem; &: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 {combineLatest, Subject} from 'rxjs';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {ToastModule} from 'primeng/toast'; import {ToastModule} from 'primeng/toast';
import {Tooltip} from 'primeng/tooltip';
import {filter, take, takeUntil} from 'rxjs/operators'; import {filter, take, takeUntil} from 'rxjs/operators';
@Component({ @Component({
@@ -20,7 +21,8 @@ import {filter, take, takeUntil} from 'rxjs/operators';
FormsModule, FormsModule,
Button, Button,
TableModule, TableModule,
ToastModule ToastModule,
Tooltip
], ],
templateUrl: './view-preferences.component.html', templateUrl: './view-preferences.component.html',
styleUrl: './view-preferences.component.scss' 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 {IconSelection} from '../../service/icon-picker.service';
import {NgClass, NgStyle} from '@angular/common'; import {NgClass, NgStyle} from '@angular/common';
import {IconCacheService} from '../../services/icon-cache.service'; import {IconCacheService} from '../../services/icon-cache.service';
@@ -41,7 +41,8 @@ import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
height: 100%; height: 100%;
display: block; display: block;
} }
`] `],
changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class IconDisplayComponent implements OnInit, OnChanges { export class IconDisplayComponent implements OnInit, OnChanges {
@Input() icon: IconSelection | null = null; @Input() icon: IconSelection | null = null;
@@ -53,28 +54,42 @@ export class IconDisplayComponent implements OnInit, OnChanges {
private iconCache = inject(IconCacheService); private iconCache = inject(IconCacheService);
private iconService = inject(IconService); private iconService = inject(IconService);
private sanitizer = inject(DomSanitizer); private sanitizer = inject(DomSanitizer);
private cdr = inject(ChangeDetectorRef);
private lastLoadedIconName: string | null = null;
ngOnInit(): void { ngOnInit(): void {
this.loadIconIfNeeded(); this.loadIconIfNeeded();
} }
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
if (changes['icon'] && this.icon?.type === 'CUSTOM_SVG') { if (changes['icon']) {
this.loadIconIfNeeded(); const currentIcon = changes['icon'].currentValue;
const previousIcon = changes['icon'].previousValue;
if (currentIcon?.type === 'CUSTOM_SVG' &&
currentIcon?.value !== previousIcon?.value) {
this.loadIconIfNeeded();
}
} }
} }
private loadIconIfNeeded(): void { private loadIconIfNeeded(): void {
if (this.icon?.type === 'CUSTOM_SVG') { if (this.icon?.type === 'CUSTOM_SVG' && this.icon.value !== this.lastLoadedIconName) {
this.iconService.getSanitizedSvgContent(this.icon.value).subscribe({ this.lastLoadedIconName = this.icon.value;
error: () => {
if (this.icon?.type === 'CUSTOM_SVG') { if (!this.iconCache.getCachedSanitized(this.icon.value)) {
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>'; this.iconService.getSanitizedSvgContent(this.icon.value).subscribe({
const sanitized = this.sanitizer.bypassSecurityTrustHtml(errorSvg); next: () => this.cdr.markForCheck(),
this.iconCache.cacheIcon(this.icon.value, errorSvg, sanitized); 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> </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) { @if (canManageIcons) {
<div style="display: flex; align-items: center; position: fixed; right: 32px; bottom: 32px; z-index: 101;"> <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 { export class IconPickerComponent implements OnInit {
private readonly SVG_PAGE_SIZE = 50;
private readonly MAX_ICON_NAME_LENGTH = 255; private readonly MAX_ICON_NAME_LENGTH = 255;
private readonly MAX_SVG_SIZE = 1048576; // 1MB private readonly MAX_SVG_SIZE = 1048576; // 1MB
private readonly ICON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/; private readonly ICON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
@@ -80,8 +79,8 @@ export class IconPickerComponent implements OnInit {
set activeTabIndex(value: string) { set activeTabIndex(value: string) {
this._activeTabIndex = value; this._activeTabIndex = value;
if (value === '1' && this.svgIcons.length === 0 && !this.isLoadingSvgIcons) { if (value === '1' && this.svgIcons.length === 0) {
this.loadSvgIcons(0); this.loadSvgIconsFromCache();
} }
} }
@@ -96,8 +95,6 @@ export class IconPickerComponent implements OnInit {
svgIcons: string[] = []; svgIcons: string[] = [];
svgSearchText: string = ''; svgSearchText: string = '';
currentSvgPage: number = 0;
totalSvgPages: number = 0;
isLoadingSvgIcons: boolean = false; isLoadingSvgIcons: boolean = false;
svgIconsError: string = ''; svgIconsError: string = '';
selectedSvgIcon: string | null = null; selectedSvgIcon: string | null = null;
@@ -105,9 +102,15 @@ export class IconPickerComponent implements OnInit {
draggedSvgIcon: string | null = null; draggedSvgIcon: string | null = null;
isTrashHover: boolean = false; isTrashHover: boolean = false;
get canManageIcons(): boolean {
const user = this.userService.getCurrentUser();
return user?.permissions.canManageIcons || user?.permissions.admin || false;
}
ngOnInit(): void { ngOnInit(): void {
if (this.activeTabIndex === '1') { 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}); this.ref.close({type: 'PRIME_NG', value: icon});
} }
loadSvgIcons(page: number): void { private loadSvgIconsFromCache(): void {
this.isLoadingSvgIcons = true; this.svgIcons = this.iconCache.getAllIconNames();
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);
}
});
} }
getSvgContent(iconName: string): SafeHtml | null { getSvgContent(iconName: string): SafeHtml | null {
@@ -254,47 +221,78 @@ export class IconPickerComponent implements OnInit {
this.iconService.saveBatchSvgIcons(svgData).subscribe({ this.iconService.saveBatchSvgIcons(svgData).subscribe({
next: (response: SvgIconBatchResponse) => { next: (response: SvgIconBatchResponse) => {
this.isSavingBatch = false; 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.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 { private deleteSvgIcon(iconName: string): void {
if (response.failureCount === 0) { this.isLoadingSvgIcons = true;
this.handleSuccessfulBatchSave();
return;
}
response.results.forEach(result => { this.iconService.deleteSvgIcon(iconName).subscribe({
if (!result.success) { next: () => {
const entryIndex = this.svgEntries.findIndex(entry => entry.name === result.iconName); this.messageService.add({
if (entryIndex !== -1) { severity: 'success',
this.svgEntries[entryIndex].error = result.errorMessage; 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 { private validateSvgInput(): string | null {
@@ -306,44 +304,27 @@ export class IconPickerComponent implements OnInit {
return this.ERROR_MESSAGES.NO_NAME; 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) { if (this.svgName.length > this.MAX_ICON_NAME_LENGTH) {
return this.ERROR_MESSAGES.NAME_TOO_LONG; return this.ERROR_MESSAGES.NAME_TOO_LONG;
} }
if (!this.svgContent.trim().includes('<svg')) { if (!this.ICON_NAME_PATTERN.test(this.svgName)) {
return this.ERROR_MESSAGES.INVALID_SVG; 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 this.ERROR_MESSAGES.SVG_TOO_LARGE;
} }
return null; 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 { private resetSvgForm(): void {
this.svgSearchText = '';
this.svgContent = ''; this.svgContent = '';
this.svgName = ''; this.svgName = '';
this.svgPreview = null; this.svgPreview = null;
this.errorMessage = '';
} }
onSvgIconDragStart(iconName: string): void { onSvgIconDragStart(iconName: string): void {
@@ -352,7 +333,6 @@ export class IconPickerComponent implements OnInit {
onSvgIconDragEnd(): void { onSvgIconDragEnd(): void {
this.draggedSvgIcon = null; this.draggedSvgIcon = null;
this.isTrashHover = false;
} }
onTrashDragOver(event: DragEvent): void { onTrashDragOver(event: DragEvent): void {
@@ -369,41 +349,9 @@ export class IconPickerComponent implements OnInit {
event.preventDefault(); event.preventDefault();
this.isTrashHover = false; this.isTrashHover = false;
if (!this.draggedSvgIcon) { if (this.draggedSvgIcon) {
return; 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 {Injectable} from '@angular/core';
import {SafeHtml} from '@angular/platform-browser'; import {SafeHtml} from '@angular/platform-browser';
import {Observable, BehaviorSubject} from 'rxjs'; import {BehaviorSubject} from 'rxjs';
interface CachedIcon { interface CachedIcon {
content: string; content: string;
sanitized: SafeHtml; sanitized: SafeHtml;
timestamp: number;
} }
@Injectable({ @Injectable({
@@ -13,25 +12,9 @@ interface CachedIcon {
}) })
export class IconCacheService { export class IconCacheService {
private cache = new Map<string, CachedIcon>(); private cache = new Map<string, CachedIcon>();
private readonly CACHE_DURATION_MS = 1000 * 60 * 60;
private cacheUpdate$ = new BehaviorSubject<string | null>(null); 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 { getCachedSanitized(iconName: string): SafeHtml | null {
const cached = this.cache.get(iconName); const cached = this.cache.get(iconName);
@@ -39,55 +22,22 @@ export class IconCacheService {
return null; return null;
} }
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
this.cache.delete(iconName);
return null;
}
return cached.sanitized; return cached.sanitized;
} }
cacheIcon(iconName: string, content: string, sanitized: SafeHtml): void { cacheIcon(iconName: string, content: string, sanitized: SafeHtml): void {
this.cache.set(iconName, { this.cache.set(iconName, {
content, content,
sanitized, sanitized
timestamp: Date.now()
}); });
this.cacheUpdate$.next(iconName); this.cacheUpdate$.next(iconName);
} }
isCached(iconName: string): boolean { removeIcon(iconName: string): boolean {
const cached = this.cache.get(iconName); return this.cache.delete(iconName);
if (!cached) {
return false;
}
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
this.cache.delete(iconName);
return false;
}
return true;
} }
invalidate(iconName: string): void { getAllIconNames(): string[] {
this.cache.delete(iconName); return Array.from(this.cache.keys()).sort();
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();
} }
} }
@@ -1,19 +1,11 @@
import {inject, Injectable} from '@angular/core'; import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {Observable, of} from 'rxjs'; 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 {API_CONFIG} from '../../core/config/api-config';
import {IconCacheService} from './icon-cache.service'; import {IconCacheService} from './icon-cache.service';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser'; import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
interface PageResponse<T> {
content: T[];
number: number;
size: number;
totalElements: number;
totalPages: number;
}
interface SvgIconData { interface SvgIconData {
svgName: string; svgName: string;
svgData: string; svgData: string;
@@ -32,44 +24,65 @@ interface SvgIconBatchResponse {
results: IconSaveResult[]; results: IconSaveResult[];
} }
interface IconContentMap {
[iconName: string]: string;
}
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class IconService { export class IconService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/icons`; 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 http = inject(HttpClient);
private iconCache = inject(IconCacheService); private iconCache = inject(IconCacheService);
private sanitizer = inject(DomSanitizer); private sanitizer = inject(DomSanitizer);
saveSvgIcon(svgContent: string, svgName: string): Observable<any> { preloadAllIcons(): Observable<void> {
return this.http.post(this.baseUrl, { if (this.preloadCache$) {
svgData: svgContent, return this.preloadCache$;
svgName: svgName }
});
}
getIconNames(page: number = 0, size: number = 50): Observable<PageResponse<string>> { this.preloadCache$ = this.http.get<IconContentMap>(`${this.baseUrl}/all/content`).pipe(
return this.http.get<PageResponse<string>>(this.baseUrl, { tap((iconsMap) => {
params: {page: page.toString(), size: size.toString()} 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> { getSvgIconContent(iconName: string): Observable<string> {
const cached = this.iconCache.getCachedContent(iconName); const cached = this.iconCache.getCachedSanitized(iconName);
if (cached) { if (cached) {
return of(cached); return of('');
} }
return this.http.get(`${this.baseUrl}/${encodeURIComponent(iconName)}/content`, { if (!this.requestCache.has(iconName)) {
responseType: 'text' const request$ = this.http.get(`${this.baseUrl}/${encodeURIComponent(iconName)}/content`, {
}).pipe( responseType: 'text'
tap(content => { }).pipe(
const sanitized = this.sanitizer.bypassSecurityTrustHtml(content); tap(content => {
this.iconCache.cacheIcon(iconName, content, sanitized); 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> { getSanitizedSvgContent(iconName: string): Observable<SafeHtml> {
@@ -95,7 +108,8 @@ export class IconService {
deleteSvgIcon(svgName: string): Observable<any> { deleteSvgIcon(svgName: string): Observable<any> {
return this.http.delete(`${this.baseUrl}/${encodeURIComponent(svgName)}`).pipe( return this.http.delete(`${this.baseUrl}/${encodeURIComponent(svgName)}`).pipe(
tap(() => { 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> { saveBatchSvgIcons(icons: SvgIconData[]): Observable<SvgIconBatchResponse> {
return this.http.post<SvgIconBatchResponse>(`${this.baseUrl}/batch`, {icons}).pipe( return this.http.post<SvgIconBatchResponse>(`${this.baseUrl}/batch`, {icons}).pipe(
tap((response) => { tap((response) => {
const successfulIcons = response.results response.results.forEach(result => {
.filter(result => result.success) if (result.success) {
.map(result => result.iconName); const iconData = icons.find(icon => icon.svgName === result.iconName);
if (iconData) {
this.iconCache.invalidateMultiple(successfulIcons); const sanitized = this.sanitizer.bypassSecurityTrustHtml(iconData.svgData);
this.iconCache.cacheIcon(iconData.svgName, iconData.svgData, sanitized);
}
}
});
}) })
); );
} }
+20 -19
View File
@@ -14,35 +14,36 @@ import {routes} from './app/app.routes';
import {AuthInterceptorService} from './app/core/security/auth-interceptor.service'; import {AuthInterceptorService} from './app/core/security/auth-interceptor.service';
import {AuthService, websocketInitializer} from './app/shared/service/auth.service'; import {AuthService, websocketInitializer} from './app/shared/service/auth.service';
import {OAuthStorage, provideOAuthClient} from 'angular-oauth2-oidc'; import {OAuthStorage, provideOAuthClient} from 'angular-oauth2-oidc';
import {APP_INITIALIZER, provideAppInitializer, provideZoneChangeDetection} from '@angular/core'; import {inject, provideAppInitializer, provideZoneChangeDetection} from '@angular/core';
import {initializeAuthFactory} from './app/core/security/auth-initializer'; import {initializeAuthFactory} from './app/core/security/auth-initializer';
import {StartupService} from './app/shared/service/startup.service';
import {provideCharts, withDefaultRegisterables} from 'ng2-charts';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import {IconService} from './app/shared/services/icon.service';
import {firstValueFrom} from 'rxjs';
export function storageFactory(): OAuthStorage { export function storageFactory(): OAuthStorage {
return localStorage; return localStorage;
} }
import {StartupService} from './app/shared/service/startup.service';
import {provideCharts, withDefaultRegisterables} from 'ng2-charts';
import ChartDataLabels from 'chartjs-plugin-datalabels';
bootstrapApplication(AppComponent, { bootstrapApplication(AppComponent, {
providers: [ providers: [
provideZoneChangeDetection(),provideCharts(withDefaultRegisterables(), ChartDataLabels), provideZoneChangeDetection(),
{ provideCharts(withDefaultRegisterables(), ChartDataLabels),
provide: APP_INITIALIZER, provideAppInitializer(() => {
useFactory: websocketInitializer, const authService = inject(AuthService);
deps: [AuthService], return websocketInitializer(authService)();
multi: true }),
}, provideAppInitializer(() => {
{ const startup = inject(StartupService);
provide: APP_INITIALIZER, return startup.load();
useFactory: (startup: StartupService) => () => startup.load(), }),
deps: [StartupService], provideAppInitializer(() => {
multi: true const iconService = inject(IconService);
}, return firstValueFrom(iconService.preloadAllIcons());
}),
provideHttpClient(withInterceptors([AuthInterceptorService])), provideHttpClient(withInterceptors([AuthInterceptorService])),
provideOAuthClient(), provideOAuthClient(),
// Configure OAuth to use localStorage instead of sessionStorage
{ {
provide: OAuthStorage, provide: OAuthStorage,
useFactory: storageFactory useFactory: storageFactory