refactor(icon): fix SVG icons loading straight to memory (#56)

* refactor(icon): fix SVG icon loading straight to memory

* refactor(icon): loading with improved error handling

* refactor(icon): add flag for SVG icons loading state

* chore(release): 2.3.0 [skip ci]

## [2.3.0](https://github.com/grimmory-tools/grimmory/compare/v2.2.6...v2.3.0) (2026-03-21)

### Features

* **release:** document develop-based stable release previews ([930e526](https://github.com/grimmory-tools/grimmory/commit/930e5262285540b3b65b9ef4f7be328a05dfb5b4))

### Bug Fixes

* **api:** fix potential memory leaks in file processing ([031e8ae](https://github.com/grimmory-tools/grimmory/commit/031e8ae257c3354cacce2d17c8c6bc35ce80badb))
* **ci:** correct artifact download action pin ([37ca101](https://github.com/grimmory-tools/grimmory/commit/37ca101dd4bd08ccfe6d4d2395ecc71298cc323d))
* **ci:** publish PR test results from workflow_run ([11a76bf](https://github.com/grimmory-tools/grimmory/commit/11a76bffe12f80d0271e3626291cfbd275346727))
* **ci:** repair release preview and test result publishing ([afa5b81](https://github.com/grimmory-tools/grimmory/commit/afa5b818ebe612e66acc819aa398ac0c6184d21b))
* drop telemetry from app ([#52](https://github.com/grimmory-tools/grimmory/issues/52)) ([4d82cb7](https://github.com/grimmory-tools/grimmory/commit/4d82cb718833a2a4e08ee2f18b2ff3ab9b043dd6))
* **ui:** repair frontend compile after rebrand ([fea1ec6](https://github.com/grimmory-tools/grimmory/commit/fea1ec6930ae64445c6d7e7b38bdc4e7925b51c1))

### Refactors

* **build:** rename frontend dist output to grimmory ([ecf388f](https://github.com/grimmory-tools/grimmory/commit/ecf388f7a2086fbd1d8737a972926d70ec3190d4))
* **i18n:** rename booklore translation keys to grimmory ([eb94afa](https://github.com/grimmory-tools/grimmory/commit/eb94afa7ad600eaa2535802583f21937bd1ae2c0))
* **metadata:** move default parser from Amazon to Goodreads ([e252122](https://github.com/grimmory-tools/grimmory/commit/e252122bc5a89c75af85ddbaae66a14d368479f9))
* pull kepubify & ffprobe during build ([#50](https://github.com/grimmory-tools/grimmory/issues/50)) ([1c15629](https://github.com/grimmory-tools/grimmory/commit/1c15629a10ba2e2ad78455f118e8c937b585b157))
* **ui:** rebrand frontend surfaces to grimmory ([d786dd8](https://github.com/grimmory-tools/grimmory/commit/d786dd8ccbebaa360385dce834816bcb6aaf3b2f))

### Chores

* **api:** remove the custom startup banner ([98c9b1a](https://github.com/grimmory-tools/grimmory/commit/98c9b1ae653c2140b7b2ab86b5511be3376bfe43))
* **deps:** bump flatted from 3.4.1 to 3.4.2 in /booklore-ui ([#73](https://github.com/grimmory-tools/grimmory/issues/73)) ([c4bd0c7](https://github.com/grimmory-tools/grimmory/commit/c4bd0c779ae398968dbdea6d566693ed57eab3eb))
* **funding:** point support links at opencollective ([55c0ac0](https://github.com/grimmory-tools/grimmory/commit/55c0ac089966b8586e7d7bdef1fc469049903d08))
* **release:** 2.2.7 [skip ci] ([0b5e24c](https://github.com/grimmory-tools/grimmory/commit/0b5e24c23848c9e97b04f4221303d0b4bf0b2dd7))
* remove old verbose PR template, replace with temporary more low-key one. ([#84](https://github.com/grimmory-tools/grimmory/issues/84)) ([b868526](https://github.com/grimmory-tools/grimmory/commit/b8685268a9a9730416a209201a70c284cee590c5))
* **ui:** drop financial support dialog ([#21](https://github.com/grimmory-tools/grimmory/issues/21)) ([62be6b1](https://github.com/grimmory-tools/grimmory/commit/62be6b152cbd42910620fdeae1f35783ea258b27))

### Documentation

* updated supported file formats in README.md ([#68](https://github.com/grimmory-tools/grimmory/issues/68)) ([f912e80](https://github.com/grimmory-tools/grimmory/commit/f912e802f97263206308817acd5bab84a5321dcf))

### Style

* **i18n:** normalize translation json formatting ([#89](https://github.com/grimmory-tools/grimmory/issues/89)) ([857290d](https://github.com/grimmory-tools/grimmory/commit/857290d215b518e61c9b3a058ae5d40d5e214672))
* **ui:** simplify the topbar logo branding ([0416d48](https://github.com/grimmory-tools/grimmory/commit/0416d48a6c441792b4c9607b3e472159c879d439))

* fix(book-browser): prevent memory leaks by unsubscribing from observables (#80)

* test(icon): remove redundant initialization in IconServiceTest

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Alex Fair <20632147+afairgiant@users.noreply.github.com>
This commit is contained in:
brios
2026-04-22 17:26:35 -04:00
committed by Zach Yale
co-authored by github-actions[bot] Alex Fair
parent 79aa2e04c9
commit c9c255b15d
5 changed files with 48 additions and 82 deletions
@@ -4,7 +4,6 @@ import org.booklore.config.AppProperties;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.request.SvgIconCreateRequest;
import org.booklore.model.dto.response.SvgIconBatchResponse;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
@@ -44,40 +43,6 @@ public class IconService {
private static final String XML_DECLARATION = "<?xml";
private static final String SVG_END_TAG = "</svg>";
@PostConstruct
public void init() {
try {
Path iconsPath = getIconsSvgPath();
if (Files.exists(iconsPath)) {
loadIconsIntoCache();
log.info("Loaded {} SVG icons into cache", svgCache.size());
} else {
Files.createDirectories(iconsPath);
log.info("Created icons directory: {}", iconsPath);
}
} catch (IOException e) {
log.error("Failed to initialize IconService: {}", e.getMessage(), e);
}
}
private void loadIconsIntoCache() throws IOException {
Path iconsPath = getIconsSvgPath();
try (Stream<Path> paths = Files.list(iconsPath)) {
paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(SVG_EXTENSION))
.limit(MAX_CACHE_SIZE)
.forEach(path -> {
try {
String filename = path.getFileName().toString();
String content = Files.readString(path);
svgCache.put(filename, content);
} catch (IOException e) {
log.warn("Failed to load icon: {}", path.getFileName(), e);
}
});
}
}
public void saveSvgIcon(SvgIconCreateRequest request) {
validateSvgData(request.getSvgData());
@@ -90,6 +55,7 @@ public class IconService {
}
try {
Files.createDirectories(filePath.getParent());
Files.writeString(filePath, request.getSvgData(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
@@ -37,7 +37,6 @@ class IconServiceTest {
iconService = new IconService(appProperties);
iconsSvgPath = Paths.get(TEST_DIR, "icons", SVG_DIR);
Files.createDirectories(iconsSvgPath);
iconService.init();
}
@AfterEach
@@ -1,29 +1,12 @@
import {inject, Injectable} from '@angular/core';
import {IconService} from '../../shared/services/icon.service';
import {forkJoin, Observable, of} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PostLoginInitializerService {
private iconService = inject(IconService);
initialize(): Observable<void> {
return forkJoin([
this.preloadIcons(),
]).pipe(
map(() => undefined)
);
}
private preloadIcons(): Observable<void> {
return this.iconService.preloadAllIcons().pipe(
catchError((err) => {
console.error('Failed to preload icons:', err);
return of(void 0);
})
);
return of(undefined);
}
}
@@ -11,6 +11,8 @@ import {IconCategoriesHelper} from '../../helpers/icon-categories.helper';
import {Button} from 'primeng/button';
import {TabsModule} from 'primeng/tabs';
import {UserService} from '../../../features/settings/user-management/user.service';
import {from, of} from 'rxjs';
import {catchError, mergeMap, toArray} from 'rxjs/operators';
interface SvgEntry {
name: string;
@@ -44,6 +46,8 @@ interface SvgIconBatchResponse {
})
export class IconPickerComponent implements OnInit {
private hasLoadedSvgIcons = false;
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 +84,8 @@ export class IconPickerComponent implements OnInit {
set activeTabIndex(value: string) {
this._activeTabIndex = value;
if (value === '1' && this.svgIcons.length === 0) {
this.loadSvgIconsFromCache();
if (value === '1' && !this.hasLoadedSvgIcons && !this.isLoadingSvgIcons) {
this.loadSvgIcons();
}
}
@@ -110,8 +114,8 @@ export class IconPickerComponent implements OnInit {
ngOnInit(): void {
if (this.activeTabIndex === '1') {
this.loadSvgIconsFromCache();
if (this.activeTabIndex === '1' && !this.hasLoadedSvgIcons && !this.isLoadingSvgIcons) {
this.loadSvgIcons();
}
}
@@ -130,8 +134,37 @@ export class IconPickerComponent implements OnInit {
this.ref.close({type: 'PRIME_NG', value: icon});
}
private loadSvgIconsFromCache(): void {
this.svgIcons = this.iconCache.getAllIconNames();
private loadSvgIcons(): void {
this.isLoadingSvgIcons = true;
this.svgIconsError = '';
this.iconService.getIconNames().subscribe({
next: (names) => {
this.hasLoadedSvgIcons = true;
if (names.length === 0) {
this.svgIcons = [];
this.isLoadingSvgIcons = false;
return;
}
from(names).pipe(
mergeMap(name =>
this.iconCache.getCachedSanitized(name)
? of(null)
: this.iconService.getSvgIconContent(name).pipe(catchError(() => of(null))),
5
),
toArray()
).subscribe(() => {
this.svgIcons = names;
this.isLoadingSvgIcons = false;
});
},
error: () => {
this.isLoadingSvgIcons = false;
this.hasLoadedSvgIcons = false;
this.svgIconsError = this.ERROR_MESSAGES.LOAD_ICONS_ERROR;
}
});
}
getSvgContent(iconName: string): SafeHtml | null {
@@ -264,7 +297,8 @@ export class IconPickerComponent implements OnInit {
}
this.clearAllEntries();
this.loadSvgIconsFromCache();
this.hasLoadedSvgIcons = false;
this.loadSvgIcons();
},
error: () => {
this.isSavingBatch = false;
@@ -25,7 +25,6 @@ interface SvgIconBatchResponse {
results: IconSaveResult[];
}
type IconContentMap = Record<string, string>;
@Injectable({
providedIn: 'root'
})
@@ -33,7 +32,6 @@ 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);
@@ -49,24 +47,10 @@ export class IconService {
});
}
preloadAllIcons(): Observable<void> {
if (this.preloadCache$) {
return this.preloadCache$;
}
this.preloadCache$ = this.http.get<IconContentMap>(`${this.baseUrl}/all/content`).pipe(
tap((iconsMap) => {
Object.entries(iconsMap).forEach(([iconName, content]) => {
const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(content));
this.iconCache.cacheIcon(iconName, content, sanitized);
});
}),
map(() => void 0),
shareReplay({ bufferSize: 1, refCount: false }),
finalize(() => this.preloadCache$ = null)
getIconNames(page: number = 0, size: number = 1000): Observable<string[]> {
return this.http.get<{ content: string[] }>(`${this.baseUrl}?page=${page}&size=${size}`).pipe(
map(response => response.content)
);
return this.preloadCache$;
}
getSvgIconContent(iconName: string): Observable<string> {