diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/IconController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/IconController.java index bbf2d4a74..1fe4d519a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/IconController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/IconController.java @@ -15,6 +15,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; +import java.util.Map; + @Tag(name = "Icons", description = "Endpoints for managing SVG icons") @AllArgsConstructor @RestController @@ -69,4 +71,12 @@ public class IconController { iconService.deleteSvgIcon(svgName); 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> getAllIconsContent() { + Map iconsMap = iconService.getAllIconsContent(); + return ResponseEntity.ok(iconsMap); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/IconService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/IconService.java index e83dd031c..eed8acc8d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/IconService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/IconService.java @@ -19,7 +19,9 @@ import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -271,4 +273,35 @@ public class IconService { ConcurrentHashMap getSvgCache() { return svgCache; } + + public Map getAllIconsContent() { + Path iconsPath = getIconsSvgPath(); + + if (!Files.exists(iconsPath)) { + return Collections.emptyMap(); + } + + try (Stream paths = Files.list(iconsPath)) { + Map 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()); + } + } } diff --git a/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.html b/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.html index bd954c2b7..4d2228a84 100644 --- a/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.html +++ b/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.html @@ -23,23 +23,23 @@ style="cursor: pointer;"> -
-
- - -
-
- - -
+
+ +

@@ -59,23 +59,23 @@ style="cursor: pointer;"> -

-
- - -
-
- - -
+
+ +

diff --git a/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.scss b/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.scss index 16e080cbf..20cc62f14 100644 --- a/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.scss +++ b/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.scss @@ -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); + } + } } } diff --git a/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.ts b/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.ts index c4fce8a2c..0427132e0 100644 --- a/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.ts +++ b/booklore-ui/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.ts @@ -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', diff --git a/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.html b/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.html index 040379b75..1aeb85192 100644 --- a/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.html +++ b/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.html @@ -28,11 +28,11 @@

+ [(ngModel)]="selectedSort" placeholder="Sort By" class="select-item" appendTo="body"> + placeholder="Direction" class="select-item" appendTo="body"> + placeholder="View Mode" class="select-item" appendTo="body">

@@ -57,35 +57,35 @@

-
- - -
+

- Add custom preferences for specific libraries or shelves. + Add custom preferences for specific libraries or shelves. These will override your default settings.

+
+ +
@if (overrides.length > 0) {
- + - Type - Name - Sort By - Sort Dir - View - + Type + Name + Sort By + Direction + View Mode + Actions + [style]="{'width': '100%'}" appendTo="body"> @if (override.entityType) { @@ -93,24 +93,24 @@ [options]="getAvailableEntities(rowIndex, override.entityType)" [(ngModel)]="override.library" optionLabel="label" optionValue="value" - class="w-full" appendTo="body"> + [style]="{'width': '100%'}" appendTo="body"> } + [(ngModel)]="override.sort" [style]="{'width': '100%'}" appendTo="body"> + [style]="{'width': '100%'}" appendTo="body"> + [style]="{'width': '100%'}" appendTo="body"> - + + (onClick)="removeOverride(rowIndex)" [pTooltip]="'Remove override'" tooltipPosition="left"> @@ -121,7 +121,7 @@
- +
diff --git a/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.scss b/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.scss index 0d02ef6fc..2883e1b91 100644 --- a/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.scss +++ b/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.scss @@ -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; + } } } } diff --git a/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.ts b/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.ts index d20106cd8..043494672 100644 --- a/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.ts +++ b/booklore-ui/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.ts @@ -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' diff --git a/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts b/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts index 0e339c531..a2d9d5473 100644 --- a/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts +++ b/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts @@ -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 = ''; - 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 = ''; + const sanitized = this.sanitizer.bypassSecurityTrustHtml(errorSvg); + this.iconCache.cacheIcon(this.icon.value, errorSvg, sanitized); + this.cdr.markForCheck(); + } } - } - }); + }); + } } } diff --git a/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.html b/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.html index a14fe63e8..f898bc601 100644 --- a/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.html +++ b/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.html @@ -50,28 +50,6 @@ } - @if (totalSvgPages > 1) { -
- - - - Page {{ currentSvgPage + 1 }} of {{ totalSvgPages }} - - - -
- } @if (canManageIcons) {
diff --git a/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.ts b/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.ts index 56b5e3c26..9aa7e12d2 100644 --- a/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.ts +++ b/booklore-ui/src/app/shared/components/icon-picker/icon-picker-component.ts @@ -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 = ''; - 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(' 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; } } diff --git a/booklore-ui/src/app/shared/services/icon-cache.service.ts b/booklore-ui/src/app/shared/services/icon-cache.service.ts index f021081cd..af8684c7b 100644 --- a/booklore-ui/src/app/shared/services/icon-cache.service.ts +++ b/booklore-ui/src/app/shared/services/icon-cache.service.ts @@ -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(); - private readonly CACHE_DURATION_MS = 1000 * 60 * 60; private cacheUpdate$ = new BehaviorSubject(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 { - return this.cacheUpdate$.asObservable(); + getAllIconNames(): string[] { + return Array.from(this.cache.keys()).sort(); } } - diff --git a/booklore-ui/src/app/shared/services/icon.service.ts b/booklore-ui/src/app/shared/services/icon.service.ts index f78d6ced8..789f02cd0 100644 --- a/booklore-ui/src/app/shared/services/icon.service.ts +++ b/booklore-ui/src/app/shared/services/icon.service.ts @@ -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 { - 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>(); + private preloadCache$: Observable | null = null; private http = inject(HttpClient); private iconCache = inject(IconCacheService); private sanitizer = inject(DomSanitizer); - saveSvgIcon(svgContent: string, svgName: string): Observable { - return this.http.post(this.baseUrl, { - svgData: svgContent, - svgName: svgName - }); - } + preloadAllIcons(): Observable { + if (this.preloadCache$) { + return this.preloadCache$; + } - getIconNames(page: number = 0, size: number = 50): Observable> { - return this.http.get>(this.baseUrl, { - params: {page: page.toString(), size: size.toString()} - }); + this.preloadCache$ = this.http.get(`${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 { - 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 { @@ -95,7 +108,8 @@ export class IconService { deleteSvgIcon(svgName: string): Observable { 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 { return this.http.post(`${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); + } + } + }); }) ); } diff --git a/booklore-ui/src/main.ts b/booklore-ui/src/main.ts index 0058560a5..cefe2c07c 100644 --- a/booklore-ui/src/main.ts +++ b/booklore-ui/src/main.ts @@ -14,35 +14,36 @@ import {routes} from './app/app.routes'; import {AuthInterceptorService} from './app/core/security/auth-interceptor.service'; import {AuthService, websocketInitializer} from './app/shared/service/auth.service'; 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 {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 { return localStorage; } -import {StartupService} from './app/shared/service/startup.service'; -import {provideCharts, withDefaultRegisterables} from 'ng2-charts'; -import ChartDataLabels from 'chartjs-plugin-datalabels'; - bootstrapApplication(AppComponent, { providers: [ - provideZoneChangeDetection(),provideCharts(withDefaultRegisterables(), ChartDataLabels), - { - provide: APP_INITIALIZER, - useFactory: websocketInitializer, - deps: [AuthService], - multi: true - }, - { - provide: APP_INITIALIZER, - useFactory: (startup: StartupService) => () => startup.load(), - deps: [StartupService], - multi: true - }, + provideZoneChangeDetection(), + provideCharts(withDefaultRegisterables(), ChartDataLabels), + provideAppInitializer(() => { + const authService = inject(AuthService); + return websocketInitializer(authService)(); + }), + provideAppInitializer(() => { + const startup = inject(StartupService); + return startup.load(); + }), + provideAppInitializer(() => { + const iconService = inject(IconService); + return firstValueFrom(iconService.preloadAllIcons()); + }), provideHttpClient(withInterceptors([AuthInterceptorService])), provideOAuthClient(), - // Configure OAuth to use localStorage instead of sessionStorage { provide: OAuthStorage, useFactory: storageFactory