refactor(types): replace most usages of 'any' with 'unknown' and improve type safety across services and components (#2050)

* refactor(types): replace most usages of 'any' with 'unknown' and improve type safety across services and components

- Update method signatures, variables, and interfaces to use 'unknown' instead of 'any'
- Refine event and observable typings for better type inference
- Add or adjust explicit types for function parameters and return values
- Update Chart.js tooltip and context typings for chart services
- Improve type safety in Book, BookState, and related models
- Adjust template bindings and method calls to match stricter typings
- Add SecureSrcDirective for secure image loading with fallback and error handling

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* chore(angular): remove proxy configuration from development build settings

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(book-browser): streamline entity and book state management with reactive streams

- Refactor entity type and entity fetching logic to use observables and combine route params
- Simplify book state handling by consolidating filtering and fetching into a single reactive pipeline
- Remove redundant applySortOption logic and related subscriptions
- Fix book card index binding in template for improved rendering performance
- Ensure proper cleanup of epub rendition in epub-reader component

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(book-browser, book-uploader): improve permission checks and enhance file upload handling

- Use optional chaining for user permission checks in book-browser.component.html to prevent runtime errors when user data is undefined
- Refactor book-uploader.component.ts to pass destination and IDs explicitly to uploadBatch, reconstruct files for strict type handling, and ensure proper upload flow and UI feedback

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(charts, services): improve type safety for book state validation and update form field checks

- Refactor isValidBookState methods across chart components and services to use type predicates and stricter type checks for BookState
- Update metadata-picker.component to simplify array field checks for authors, categories, moods, and tags
- Adjust magic-shelf-utils to remove unnecessary fallback in object spread
- Update notification-event.service to use correct timeout type for highlightTimeout

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(theme): ensure safe merging of theme properties and improve type definition for themesMap

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(epub-reader): streamline book and rendition initialization logic

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-02 18:22:54 -07:00
committed by GitHub
parent 998b07d243
commit ab96eee5bc
86 changed files with 853 additions and 638 deletions
@@ -90,7 +90,7 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
return this.files.length > 0;
}
choose(_event: any, chooseCallback: () => void): void {
choose(_event: unknown, chooseCallback: () => void): void {
chooseCallback();
}
@@ -111,7 +111,7 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
}
}
onRemoveTemplatingFile(_event: any, _file: File, removeFileCallback: (event: any, index: number) => void, index: number): void {
onRemoveTemplatingFile(_event: unknown, _file: File, removeFileCallback: (event: unknown, index: number) => void, index: number): void {
removeFileCallback(_event, index);
}
@@ -21,7 +21,7 @@ export class BookDialogHelperService {
private dialogLauncherService = inject(DialogLauncherService);
private openDialog(component: any, options: {}): DynamicDialogRef | null {
private openDialog(component: unknown, options: {}): DynamicDialogRef | null {
return this.dialogLauncherService.openDialog(component, options);
}
@@ -35,10 +35,10 @@
<div
class="filter-row"
[ngClass]="{
'active': activeFilters[filterType]?.includes(filter.value?.id || filter.value)
'active': activeFilters[filterType]?.includes(getFilterValueId(filter))
}"
(click)="handleFilterClick(filterType, filter.value?.id || filter.value)">
{{ filter.value.name || filter.value }}
(click)="handleFilterClick(filterType, getFilterValueId(filter))">
{{ getFilterValueDisplay(filter) }}
<p-badge class="filter-value-badge" [value]="filter.bookCount"></p-badge>
</div>
}
@@ -16,7 +16,36 @@ import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
type Filter<T> = { value: T; bookCount: number };
export interface FilterValue {
id?: string | number;
name?: string;
sortIndex?: number;
}
export interface Filter<T extends FilterValue = FilterValue> {
value: T;
bookCount: number;
}
export type FilterType =
| 'author'
| 'category'
| 'series'
| 'publisher'
| 'readStatus'
| 'personalRating'
| 'publishedDate'
| 'matchScore'
| 'mood'
| 'tag'
| 'language'
| 'bookType'
| 'shelfStatus'
| 'fileSize'
| 'pageCount'
| 'amazonRating'
| 'goodreadsRating'
| 'hardcoverRating';
export const ratingRanges = [
{id: '0to1', label: '0 to 1', min: 0, max: 1, sortIndex: 0},
@@ -153,9 +182,9 @@ function getReadStatusName(status?: ReadStatus | null): string {
]
})
export class BookFilterComponent implements OnInit, OnDestroy {
private filterChangeSubject = new Subject<Record<string, any> | null>();
private filterChangeSubject = new Subject<Record<string, unknown> | null>();
@Output() filterSelected = new EventEmitter<Record<string, any> | null>();
@Output() filterSelected = new EventEmitter<Record<string, unknown> | null>();
@Output() filterModeChanged = new EventEmitter<BookFilterMode>();
@Input() entity$!: Observable<Library | Shelf | MagicShelf | null> | undefined;
@@ -163,10 +192,10 @@ export class BookFilterComponent implements OnInit, OnDestroy {
@Input() resetFilter$!: Subject<void>;
@Input() showFilter: boolean = false;
activeFilters: Record<string, any> = {};
filterStreams: Record<string, Observable<Filter<any>[]>> = {};
activeFilters: Record<string, unknown[]> = {};
filterStreams: Record<FilterType, Observable<Filter[]>> = {} as Record<FilterType, Observable<Filter[]>>;
truncatedFilters: Record<string, boolean> = {};
filterTypes: string[] = [];
filterTypes: FilterType[] = [];
filterModeOptions = [
{label: 'AND', value: 'and'},
{label: 'OR', value: 'or'},
@@ -174,7 +203,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
];
private _selectedFilterMode: BookFilterMode = 'and';
expandedPanels: number[] = [0];
readonly filterLabels: Record<string, string> = {
readonly filterLabels: Record<FilterType, string> = {
author: 'Author',
category: 'Genre',
series: 'Series',
@@ -183,6 +212,8 @@ export class BookFilterComponent implements OnInit, OnDestroy {
personalRating: 'Personal Rating',
publishedDate: 'Published Year',
matchScore: 'Metadata Match Score',
mood: 'Mood',
tag: 'Tag',
language: 'Language',
bookType: 'Book Type',
shelfStatus: 'Shelf Status',
@@ -260,7 +291,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
hardcoverRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.hardcoverRating!), 'id', 'name', 'sortIndex'),
};
this.filterTypes = Object.keys(this.filterStreams);
this.filterTypes = Object.keys(this.filterStreams) as FilterType[];
this.setExpandedPanels();
});
@@ -273,12 +304,12 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
}
private getFilterStream<T>(
private getFilterStream<T extends FilterValue>(
extractor: (book: Book) => T[] | undefined,
idKey: keyof T,
nameKey: keyof T,
sortMode: FilterSortingMode | 'sortIndex' = this.filterSortingMode
): Observable<Filter<T[keyof T]>[]> {
): Observable<Filter<T>[]> {
return combineLatest([
this.bookService.bookState$,
this.entity$ ?? of(null),
@@ -286,7 +317,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
]).pipe(
map(([state, entity, entityType]) => {
const filteredBooks = this.filterBooksByEntityType(state.books || [], entity, entityType);
const filterMap = new Map<any, Filter<any>>();
const filterMap = new Map<unknown, Filter<T>>();
filteredBooks.forEach((book) => {
(extractor(book) || []).forEach((item) => {
@@ -302,11 +333,17 @@ export class BookFilterComponent implements OnInit, OnDestroy {
const sorted = result.sort((a, b) => {
if (sortMode === 'sortIndex') {
return (a.value.sortIndex ?? 999) - (b.value.sortIndex ?? 999);
const aValue = a.value as { sortIndex?: number };
const bValue = b.value as { sortIndex?: number };
return (aValue.sortIndex ?? 999) - (bValue.sortIndex ?? 999);
} else if (sortMode === 'count' && b.bookCount !== a.bookCount) {
return b.bookCount - a.bookCount;
}
return a.value[nameKey].toString().localeCompare(b.value[nameKey].toString());
const aValue = a.value as Record<string, unknown>;
const bValue = b.value as Record<string, unknown>;
const aKey = String(aValue[String(nameKey)] ?? '');
const bKey = String(bValue[String(nameKey)] ?? '');
return aKey.localeCompare(bKey);
});
const isTruncated = sorted.length > 500;
@@ -317,13 +354,13 @@ export class BookFilterComponent implements OnInit, OnDestroy {
map(({items, isTruncated}) => {
setTimeout(() => {
const filterType = Object.keys(this.filterStreams).find(key =>
this.filterStreams[key] === this.getFilterStream(extractor, idKey, nameKey)
this.filterStreams[key as FilterType] === this.getFilterStream(extractor, idKey, nameKey)
);
if (filterType) {
this.truncatedFilters[filterType] = isTruncated;
}
});
return items;
return items as Filter<T>[];
}),
shareReplay({bufferSize: 1, refCount: true})
);
@@ -343,18 +380,21 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
}
private filterBooksByEntityType(books: Book[], entity: any, entityType: EntityType): Book[] {
if (entityType === EntityType.LIBRARY && entity && 'id' in entity) {
return books.filter((book) => book.libraryId === entity.id);
private filterBooksByEntityType(books: Book[], entity: unknown, entityType: EntityType): Book[] {
if (entityType === EntityType.LIBRARY && entity !== null && typeof entity === 'object' && 'id' in entity) {
const libraryEntity = entity as { id: number };
return books.filter((book) => book.libraryId === libraryEntity.id);
}
if (entityType === EntityType.SHELF && entity && 'id' in entity) {
return books.filter((book) => book.shelves?.some((shelf) => shelf.id === entity.id));
if (entityType === EntityType.SHELF && entity !== null && typeof entity === 'object' && 'id' in entity) {
const shelfEntity = entity as { id: number };
return books.filter((book) => book.shelves?.some((shelf) => shelf.id === shelfEntity.id));
}
if (entityType === EntityType.MAGIC_SHELF && entity && 'filterJson' in entity) {
if (entityType === EntityType.MAGIC_SHELF && entity !== null && typeof entity === 'object' && 'filterJson' in entity) {
try {
const groupRule = JSON.parse(entity.filterJson) as GroupRule;
const magicShelfEntity = entity as { filterJson: string };
const groupRule = JSON.parse(magicShelfEntity.filterJson) as GroupRule;
return books.filter((book) => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule));
} catch (e) {
console.warn('Invalid filterJson for MagicShelf:', e);
@@ -365,18 +405,19 @@ export class BookFilterComponent implements OnInit, OnDestroy {
return books;
}
handleFilterClick(filterType: string, value: any): void {
handleFilterClick(filterType: string, value: unknown): void {
if (!this.activeFilters[filterType]) {
this.activeFilters[filterType] = [];
}
const index = this.activeFilters[filterType].indexOf(value);
const filterArray = this.activeFilters[filterType];
const index = filterArray.indexOf(value);
if (index > -1) {
if (this._selectedFilterMode == 'single') {
this.activeFilters = {};
} else {
this.activeFilters[filterType].splice(index, 1);
if (this.activeFilters[filterType].length === 0) {
filterArray.splice(index, 1);
if (filterArray.length === 0) {
delete this.activeFilters[filterType];
}
}
@@ -389,7 +430,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
this.filterChangeSubject.next(Object.keys(this.activeFilters).length ? {...this.activeFilters} : null);
}
setFilters(filters: Record<string, any>) {
setFilters(filters: Record<string, unknown>) {
this.activeFilters = {};
for (const [key, value] of Object.entries(filters)) {
@@ -422,12 +463,26 @@ export class BookFilterComponent implements OnInit, OnDestroy {
this.setExpandedPanels();
}
trackByFilterType(_: number, type: string): string {
trackByFilterType(_: number, type: FilterType): string {
return type;
}
trackByFilter(_: number, filter: Filter<any>): any {
return filter.value.id ?? filter.value;
trackByFilter(_: number, filter: Filter<FilterValue>): unknown {
const value = filter.value as { id?: unknown } | unknown;
return (typeof value === 'object' && value !== null && 'id' in value) ? (value as any).id : filter.value;
}
getFilterValueId(filter: Filter<FilterValue>): unknown {
const value = filter.value as { id?: unknown } | unknown;
return (typeof value === 'object' && value !== null && 'id' in value) ? (value as any).id : filter.value;
}
getFilterValueDisplay(filter: Filter<FilterValue>): string {
const value = filter.value as { name?: string } | string | unknown;
if (typeof value === 'object' && value !== null && 'name' in value) {
return String((value as any).name ?? '');
}
return String(value ?? '');
}
ngOnDestroy(): void {
@@ -39,7 +39,7 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
@Output() selectedBooksChange = new EventEmitter<Set<number>>();
@Input() books: Book[] = [];
@Input() sortOption: SortOption | null = null;
@Input() visibleColumns: any[] = [];
@Input() visibleColumns: { field: string; header: string }[] = [];
@Input() preselectedBookIds = new Set<number>();
protected urlHelper = inject(UrlHelperService);
@@ -120,17 +120,21 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
this.selectedBooksChange.emit(this.selectedBookIds);
}
onRowSelect(event: any): void {
this.selectedBookIds.add(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
onRowSelect(event: { data?: Book | Book[] }): void {
if (event.data && !Array.isArray(event.data)) {
this.selectedBookIds.add(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
}
}
onRowUnselect(event: any): void {
this.selectedBookIds.delete(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
onRowUnselect(event: { data?: Book | Book[] }): void {
if (event.data && !Array.isArray(event.data)) {
this.selectedBookIds.delete(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
}
}
onHeaderCheckboxToggle(event: any): void {
onHeaderCheckboxToggle(event: { checked: boolean }): void {
if (event.checked) {
this.selectedBooks = [...this.books];
this.selectedBookIds = new Set(this.books.map(book => book.id));
@@ -204,7 +208,7 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
'isbn': 'isbn'
} as const;
let data: string[] = [metadata[field]];
let data: string[] = [metadata[field] as string];
switch (field) {
case 'title':
@@ -5,7 +5,7 @@ import {map, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators
export class HeaderFilter implements BookFilter {
constructor(private searchTerm$: Observable<any>) {
constructor(private searchTerm$: Observable<string>) {
}
filter(bookState: BookState): Observable<BookState> {
@@ -25,7 +25,7 @@ export class HeaderFilter implements BookFilter {
return this.searchTerm$.pipe(
distinctUntilChanged(),
switchMap(term => {
switchMap((term: string) => {
const normalizedTerm = normalize(term || '').trim();
if (normalizedTerm.length < 2) {
return of(bookState);
@@ -47,7 +47,7 @@ export function doesBookMatchReadStatus(book: Book, selected: string[]): boolean
export class SideBarFilter implements BookFilter {
constructor(private selectedFilter$: Observable<any>, private selectedFilterMode$: Observable<BookFilterMode>) {
constructor(private selectedFilter$: Observable<unknown>, private selectedFilterMode$: Observable<BookFilterMode>) {
}
filter(bookState: BookState): Observable<BookState> {
@@ -33,8 +33,8 @@ export class BookSenderComponent implements OnInit {
emailProviders: { label: string, value: EmailProvider }[] = [];
emailRecipients: { label: string, value: EmailRecipient }[] = [];
selectedProvider?: any;
selectedRecipient?: any;
selectedProvider?: { label: string; value: EmailProvider };
selectedRecipient?: { label: string; value: EmailRecipient };
ngOnInit(): void {
this.emailProviderService.getEmailProviders().subscribe({
@@ -48,6 +48,7 @@ export interface Book extends FileInfo {
libraryPath?: { id: number };
alternativeFormats?: AdditionalFile[];
supplementaryFiles?: AdditionalFile[];
[key: string]: unknown;
}
export interface EpubProgress {
@@ -145,7 +146,7 @@ export interface BookMetadata {
tagsLocked?: boolean;
coverLocked?: boolean;
reviewsLocked?: boolean;
[key: string]: any;
[key: string]: unknown;
}
export interface MetadataClearFlags {
@@ -215,7 +216,7 @@ export interface BookSetting {
epubSettings?: EpubViewerSetting;
cbxSettings?: CbxViewerSetting;
newPdfSettings?: NewPdfReaderSetting;
[key: string]: any;
[key: string]: unknown;
}
export interface BookRecommendation {
@@ -484,7 +484,7 @@ export class BookService {
for (const [field, action] of Object.entries(fieldActions)) {
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
if (lockField in updatedMetadata) {
(updatedMetadata as any)[lockField] = action === 'LOCK';
(updatedMetadata as Record<string, unknown>)[lockField] = action === 'LOCK';
}
}
return {
@@ -508,7 +508,7 @@ export class BookService {
);
}
consolidateMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', targetValues: string[], valuesToMerge: string[]): Observable<any> {
consolidateMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', targetValues: string[], valuesToMerge: string[]): Observable<unknown> {
const payload = {metadataType, targetValues, valuesToMerge};
return this.http.post(`${this.url}/metadata/manage/consolidate`, payload).pipe(
tap(() => {
@@ -517,7 +517,7 @@ export class BookService {
);
}
deleteMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', valuesToDelete: string[]): Observable<any> {
deleteMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', valuesToDelete: string[]): Observable<unknown> {
const payload = {metadataType, valuesToDelete};
return this.http.post(`${this.url}/metadata/manage/delete`, payload).pipe(
tap(() => {
@@ -135,7 +135,7 @@ export class LibraryShelfMenuService {
];
}
initializeShelfMenuItems(entity: any): MenuItem[] {
initializeShelfMenuItems(entity: Shelf | null): MenuItem[] {
return [
{
label: 'Options',
@@ -183,7 +183,7 @@ export class LibraryShelfMenuService {
];
}
initializeMagicShelfMenuItems(entity: any): MenuItem[] {
initializeMagicShelfMenuItems(entity: MagicShelf | null): MenuItem[] {
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const isPublicShelf = entity?.isPublic ?? false;
const disableOptions = isPublicShelf && !isAdmin;