refactor(frontend): Migrate state to Tanstack Query + signals (#117)

* refactor(frontend): migrate state to TanStack Query and signals

* fix(frontend): keep book cache in sync after patches
This commit is contained in:
Alex
2026-04-22 17:26:31 -04:00
committed by Zach Yale
parent 8fcb14753e
commit ccb80d7421
237 changed files with 6456 additions and 8464 deletions
+90 -4
View File
@@ -23,6 +23,7 @@
"@primeuix/themes": "^2.0.3",
"@stomp/rx-stomp": "^2.3.0",
"@stomp/stompjs": "^7.3.0",
"@tanstack/angular-query-experimental": "5.90.26",
"@tweenjs/tween.js": "^25.0.0",
"chart.js": "^4.5.1",
"chartjs-chart-matrix": "^3.0.0",
@@ -298,6 +299,7 @@
"integrity": "sha512-3zbx2Pu/PyP0cw5EMgpdVMerYwYOtZvV1pFXxoViGZAxFzQ8TGHCuJm4ECg3jcs7iBdt1O9ZejMuwebVCXeD3A==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"tinyglobby": "^0.2.14",
"ts-morph": "^21.0.0"
@@ -348,6 +350,7 @@
"integrity": "sha512-kYFwTNzToG2SJMxj2f41w3QRtdqlrFuF+bpZrtIaHOP078Ktld8EPIp9KqB0Y46Vvs69ifby5Q1/wPD9wA3iaw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@angular-devkit/core": "21.2.0",
"rxjs": "7.8.2"
@@ -395,6 +398,7 @@
"integrity": "sha512-3kn3FI5v7BQ7Zct6raek+WgvyDwOJ8wElbyC903GxMQCDBRGGcevhHvTAIHhknihEsrgplzPhTlWeMbk1JfdFg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@angular-devkit/core": "21.2.0",
"jsonc-parser": "3.3.1",
@@ -492,6 +496,7 @@
"integrity": "sha512-TCb3qYOC/uXKZCo56cJ6N9sHeWdFhyVqrbbYfFjTi09081T6jllgHDZL5Ms7gOMNY8KywWGGbhxwvzeA0RwTgA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@angular-eslint/bundled-angular-compiler": "21.2.0",
"eslint-scope": "^9.0.0"
@@ -506,6 +511,7 @@
"resolved": "https://registry.npmjs.org/@angular/animations/-/animations-21.2.4.tgz",
"integrity": "sha512-hO1P7ks9n7lW3D31bzHohSuoAaj05xJUlK8rZgX8IkH5DLx4qhvfNh0t4bbLuBJLP2r1TaLsQ8KFcemCkFRO2w==",
"license": "MIT",
"peer": true,
"dependencies": {
"tslib": "^2.3.0"
},
@@ -522,6 +528,7 @@
"integrity": "sha512-K0EqiHz2y7TSyD4adWD0+C/P9khKlrsSWavXWxGRvoSJC/H3I3SK5Z6BWwftBibXR1Fis7njwvl5IGAlQrDchA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@ampproject/remapping": "2.3.0",
"@angular-devkit/architect": "0.2102.0",
@@ -634,6 +641,7 @@
"resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-21.2.0.tgz",
"integrity": "sha512-1P0TNL1F51NC7JAaXabaAHY7Y1zBloLSZXfml1POa4a116V+y/QZfPGsxM0LwD1qSSXhSb2LNl7duTtJAP39bA==",
"license": "MIT",
"peer": true,
"dependencies": {
"parse5": "^8.0.0",
"tslib": "^2.3.0"
@@ -651,6 +659,7 @@
"integrity": "sha512-yaGEpckqgOemcHkoWeH92i9eNrcbr9iE/dnxL+Du6s9spTAXJ2jjtYfszhmowuQZkCK5rjecMb8ctNtHlaGCjg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@angular-devkit/architect": "0.2102.0",
"@angular-devkit/core": "21.2.0",
@@ -698,6 +707,7 @@
"resolved": "https://registry.npmjs.org/@angular/common/-/common-21.2.4.tgz",
"integrity": "sha512-NrP6qOuUpo3fqq14UJ1b2bIRtWsfvxh1qLqOyFV4gfBrHhXd0XffU1LUlUw1qp4w1uBSgPJ0/N5bSPUWrAguVg==",
"license": "MIT",
"peer": true,
"dependencies": {
"tslib": "^2.3.0"
},
@@ -714,6 +724,7 @@
"resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-21.2.4.tgz",
"integrity": "sha512-9+ulVK3idIo/Tu4X2ic7/V0+Uj7pqrOAbOuIirYe6Ymm3AjexuFRiGBbfcH0VJhQ5cf8TvIJ1fuh+MI4JiRIxA==",
"license": "MIT",
"peer": true,
"dependencies": {
"tslib": "^2.3.0"
},
@@ -727,6 +738,7 @@
"integrity": "sha512-vGjd7DZo/Ox50pQCm5EycmBu91JclimPtZoyNXu/2hSxz3oAkzwiHCwlHwk2g58eheSSp+lYtYRLmHAqSVZLjg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/core": "7.29.0",
"@jridgewell/sourcemap-codec": "^1.4.14",
@@ -759,6 +771,7 @@
"resolved": "https://registry.npmjs.org/@angular/core/-/core-21.2.4.tgz",
"integrity": "sha512-2+gd67ZuXHpGOqeb2o7XZPueEWEP81eJza2tSHkT5QMV8lnYllDEmaNnkPxnIjSLGP1O3PmiXxo4z8ibHkLZwg==",
"license": "MIT",
"peer": true,
"dependencies": {
"tslib": "^2.3.0"
},
@@ -784,6 +797,7 @@
"resolved": "https://registry.npmjs.org/@angular/forms/-/forms-21.2.4.tgz",
"integrity": "sha512-1fOhctA9ADEBYjI3nPQUR5dHsK2+UWAjup37Ksldk/k0w8UpD5YsN7JVNvsDMZRFMucKYcGykPblU7pABtsqnQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"tslib": "^2.3.0"
@@ -803,6 +817,7 @@
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-21.2.4.tgz",
"integrity": "sha512-1A9e/cQVu+3BkRCktLcO3RZGuw8NOTHw1frUUrpAz+iMyvIT4sDRFbL+U1g8qmOCZqRNC1Pi1HZfZ1kl6kvrcQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"tslib": "^2.3.0"
},
@@ -843,6 +858,7 @@
"resolved": "https://registry.npmjs.org/@angular/router/-/router-21.2.4.tgz",
"integrity": "sha512-OjWze4XT8i2MThcBXMv7ru1k6/5L6QYZbcXuseqimFCHm2avEJ+mXPovY066fMBZJhqbXdjB82OhHAWkIHjglQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"tslib": "^2.3.0"
},
@@ -861,6 +877,7 @@
"resolved": "https://registry.npmjs.org/@angular/service-worker/-/service-worker-21.2.4.tgz",
"integrity": "sha512-YcPMb0co2hEDwzOG5S27b6f8rotXEUDx88nQuhHDl/ztuzXaxKklJ21qVDVZ0R433YBCRQJl2D6ZrpJojsnBFw==",
"license": "MIT",
"peer": true,
"dependencies": {
"tslib": "^2.3.0"
},
@@ -960,6 +977,7 @@
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@babel/generator": "^7.29.0",
@@ -1332,6 +1350,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=20.19.0"
},
@@ -1372,6 +1391,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=20.19.0"
}
@@ -2369,6 +2389,7 @@
"integrity": "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@inquirer/checkbox": "^4.3.2",
"@inquirer/confirm": "^5.1.21",
@@ -4497,7 +4518,49 @@
"version": "7.3.0",
"resolved": "https://registry.npmjs.org/@stomp/stompjs/-/stompjs-7.3.0.tgz",
"integrity": "sha512-nKMLoFfJhrQAqkvvKd1vLq/cVBGCMwPRCD0LqW7UT1fecRx9C3GoKEIR2CYwVuErGeZu8w0kFkl2rlhPlqHVgQ==",
"license": "Apache-2.0"
"license": "Apache-2.0",
"peer": true
},
"node_modules/@tanstack/angular-query-experimental": {
"version": "5.90.26",
"resolved": "https://registry.npmjs.org/@tanstack/angular-query-experimental/-/angular-query-experimental-5.90.26.tgz",
"integrity": "sha512-VsQhC82xNZjEpnAIdDTWy3hbkHVgTLobMOMFii2vtiJV2rx+a61q06OMxAns3JNU+8yw1YGDnD2Vna5PHA9+yg==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.91.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"optionalDependencies": {
"@tanstack/query-devtools": "5.93.0"
},
"peerDependencies": {
"@angular/common": ">=16.0.0",
"@angular/core": ">=16.0.0"
}
},
"node_modules/@tanstack/query-core": {
"version": "5.91.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.91.0.tgz",
"integrity": "sha512-FYXN8Kk9Q5VKuV6AIVaNwMThSi0nvAtR4X7HQoigf6ePOtFcavJYVIzgFhOVdtbBQtCJE3KimDIMMJM2DR1hjw==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/query-devtools": {
"version": "5.93.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.93.0.tgz",
"integrity": "sha512-+kpsx1NQnOFTZsw6HAFCW3HkKg0+2cepGtAWXjiiSOJJ1CtQpt72EE2nyZb+AjAbLRPoeRmPJ8MtQd8r8gsPdg==",
"license": "MIT",
"optional": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@ts-morph/common": {
"version": "0.22.0",
@@ -4540,7 +4603,8 @@
"version": "25.0.0",
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz",
"integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.1",
@@ -4609,6 +4673,7 @@
"integrity": "sha512-RpV6r/ij22zRRdyBPcxDeKAzH43phWVKEjL2iksqo1Vz3CuBUrgmPpPhALKiRfU7OMCmeeO9vECBMsV0hMTG8Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.18.0"
}
@@ -4662,6 +4727,7 @@
"integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.56.1",
"@typescript-eslint/types": "8.56.1",
@@ -4769,6 +4835,7 @@
"integrity": "sha512-dbMkdIUkIkchgGDIv7KLUpa0Mda4IYjo4IAMJUZ+3xNoUXxMsk9YtKpTHSChRS85o+H9ftm51gsK1dZReY9CVw==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
@@ -4811,6 +4878,7 @@
"integrity": "sha512-HPAVNIME3tABJ61siYlHzSWCGtOoeP2RTIaHXFMPqjrQKCGB9OgUVdiNgH7TJS2JNIQ5qQ4RsAUDuGaGme/KOA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.9.1",
"@typescript-eslint/scope-manager": "8.56.1",
@@ -5052,6 +5120,7 @@
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -5473,6 +5542,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -5633,6 +5703,7 @@
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@kurkle/color": "^0.3.0"
},
@@ -6378,6 +6449,7 @@
"integrity": "sha512-VmQ+sifHUbI/IcSopBCF/HO3YiHQx/AVd3UVyYL6weuwW+HvON9VYn5l6Zl1WZzPWXPNZrSQpxwkkZ/VuvJZzg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -6711,6 +6783,7 @@
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.1",
@@ -7193,6 +7266,7 @@
"integrity": "sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=16.9.0"
}
@@ -7631,6 +7705,7 @@
"integrity": "sha512-0+MoQNYyr2rBHqO1xilltfDjV9G7ymYGlAUazgcDLQaUf8JDHbuGwsxN6U9qWaElZ4w1B2r7yEGIL3GdeW3Rug==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@acemir/cssom": "^0.9.31",
"@asamuzakjp/dom-selector": "^6.8.1",
@@ -7792,6 +7867,7 @@
"integrity": "sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"cli-truncate": "^5.0.0",
"colorette": "^2.0.20",
@@ -9158,6 +9234,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -9568,6 +9645,7 @@
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"tslib": "^2.1.0"
}
@@ -10271,7 +10349,8 @@
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
"license": "0BSD",
"peer": true
},
"node_modules/tuf-js": {
"version": "4.1.0",
@@ -10322,6 +10401,7 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -10336,6 +10416,7 @@
"integrity": "sha512-U4lM6pjmBX7J5wk4szltF7I1cGBHXZopnAXCMXb3+fZ3B/0Z3hq3wS/CCUB2NZBNAExK92mCU2tEohWuwVMsDQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/eslint-plugin": "8.56.1",
"@typescript-eslint/parser": "8.56.1",
@@ -10457,6 +10538,7 @@
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"peer": true,
"bin": {
"uuid": "dist/esm/bin/uuid"
}
@@ -10487,6 +10569,7 @@
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.27.0",
"fdir": "^6.5.0",
@@ -10562,6 +10645,7 @@
"integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@vitest/expect": "4.0.18",
"@vitest/mocker": "4.0.18",
@@ -10986,6 +11070,7 @@
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"dev": true,
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
@@ -11004,7 +11089,8 @@
"version": "0.16.1",
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.16.1.tgz",
"integrity": "sha512-dpvY17vxYIW3+bNrP0ClUlaiY0CiIRK3tnoLaGoQsQcY9/I/NpzIWQ7tQNhbV7LacQMpCII6wVzuL3tuWOyfuA==",
"license": "MIT"
"license": "MIT",
"peer": true
}
}
}
+1
View File
@@ -27,6 +27,7 @@
"@primeuix/themes": "^2.0.3",
"@stomp/rx-stomp": "^2.3.0",
"@stomp/stompjs": "^7.3.0",
"@tanstack/angular-query-experimental": "5.90.26",
"@tweenjs/tween.js": "^25.0.0",
"chart.js": "^4.5.1",
"chartjs-chart-matrix": "^3.0.0",
+4 -6
View File
@@ -1,8 +1,9 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {signal} from '@angular/core';
import {AppComponent} from './app.component';
import {AuthInitializationService} from './core/security/auth-initialization-service';
import {BehaviorSubject, of} from 'rxjs';
import {of} from 'rxjs';
import {RxStompService} from './shared/websocket/rx-stomp.service';
import {BookService} from './features/book/service/book.service';
import {NotificationEventService} from './shared/websocket/notification-event.service';
@@ -18,15 +19,12 @@ import {TranslocoTestingModule} from '@jsverse/transloco';
describe('AppComponent offline detection', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
let authInitSubject: BehaviorSubject<boolean>;
beforeEach(() => {
authInitSubject = new BehaviorSubject<boolean>(false);
TestBed.configureTestingModule({
imports: [TranslocoTestingModule.forRoot({langs: {}})],
providers: [
{provide: AuthInitializationService, useValue: {initialized$: authInitSubject.asObservable()}},
{provide: AuthInitializationService, useValue: {initialized: signal(false)}},
{provide: RxStompService, useValue: {watch: vi.fn(() => of())}},
{provide: BookService, useValue: {}},
{provide: NotificationEventService, useValue: {}},
@@ -34,7 +32,7 @@ describe('AppComponent offline detection', () => {
{provide: MetadataProgressService, useValue: {}},
{provide: BookdropFileService, useValue: {}},
{provide: TaskService, useValue: {}},
{provide: LibraryService, useValue: {largeLibraryLoading$: of({isLoading: false, expectedCount: 0})}},
{provide: LibraryService, useValue: {largeLibraryLoading: signal({isLoading: false, expectedCount: 0})}},
{provide: LibraryHealthService, useValue: {initialize: vi.fn()}},
{provide: LibraryLoadingService, useValue: {hide: vi.fn()}},
]
+14 -13
View File
@@ -1,4 +1,4 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Component, effect, inject, OnDestroy, OnInit} from '@angular/core';
import {RxStompService} from './shared/websocket/rx-stomp.service';
import {BookService} from './features/book/service/book.service';
import {NotificationEventService} from './shared/websocket/notification-event.service';
@@ -17,7 +17,7 @@ import {TaskProgressPayload, TaskService} from './features/settings/task-managem
import {LibraryService} from './features/book/service/library.service';
import {LibraryHealthService} from './features/book/service/library-health.service';
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
import {scan, withLatestFrom} from 'rxjs/operators';
import {scan} from 'rxjs/operators';
import {AuthService} from './shared/service/auth.service';
@Component({
@@ -46,19 +46,20 @@ export class AppComponent implements OnInit, OnDestroy {
private libraryHealthService = inject(LibraryHealthService);
private libraryLoadingService = inject(LibraryLoadingService);
private authService = inject(AuthService);
private readonly syncAuthInitializationEffect = effect(() => {
const ready = this.authInit.initialized();
this.loading = !ready;
if (ready && !this.subscriptionsInitialized) {
this.setupWebSocketSubscriptions();
this.libraryHealthService.initialize();
this.subscriptionsInitialized = true;
}
});
ngOnInit(): void {
window.addEventListener('online', this.onOnline);
window.addEventListener('offline', this.onOffline);
this.authInit.initialized$.subscribe(ready => {
this.loading = !ready;
if (ready && !this.subscriptionsInitialized) {
this.setupWebSocketSubscriptions();
this.libraryHealthService.initialize();
this.subscriptionsInitialized = true;
}
});
}
private onOnline = () => {
@@ -84,8 +85,8 @@ export class AppComponent implements OnInit, OnDestroy {
private setupWebSocketSubscriptions(): void {
this.subscriptions.push(
this.rxStompService.watch('/user/queue/book-add').pipe(
withLatestFrom(this.libraryService.largeLibraryLoading$),
scan((acc, [msg, loadingState]) => {
scan((acc, msg) => {
const loadingState = this.libraryService.largeLibraryLoading();
const book = JSON.parse(msg.body);
if (loadingState.isLoading) {
const newCount = acc.count + 1;
@@ -1,12 +1,11 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {Injectable, signal} from '@angular/core';
@Injectable({providedIn: 'root'})
export class AuthInitializationService {
private initialized = new BehaviorSubject<boolean>(false);
initialized$ = this.initialized.asObservable();
private readonly _initialized = signal(false);
readonly initialized = this._initialized.asReadonly();
markAsInitialized() {
this.initialized.next(true);
markAsInitialized(): void {
this._initialized.set(true);
}
}
@@ -1,22 +1,39 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {initializeAuthFactory} from './auth-initializer';
import {AuthInitializationService} from './auth-initialization-service';
import {AuthService} from '../../shared/service/auth.service';
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
import {BehaviorSubject} from 'rxjs';
import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental';
describe('initializeAuthFactory', () => {
let authInitService: AuthInitializationService;
let publicSettingsSubject: BehaviorSubject<PublicAppSettings | null>;
let mockQueryClient: { fetchQuery: ReturnType<typeof vi.fn> };
const defaultPublicSettings: PublicAppSettings = {
oidcEnabled: false,
remoteAuthEnabled: false,
oidcProviderDetails: null!,
oidcForceOnlyMode: false,
};
beforeEach(() => {
publicSettingsSubject = new BehaviorSubject<PublicAppSettings | null>(null);
mockQueryClient = {
fetchQuery: vi.fn().mockResolvedValue(defaultPublicSettings),
};
TestBed.configureTestingModule({
providers: [
{provide: AuthService, useValue: {tokenSubject: {next: vi.fn()}, getInternalAccessToken: vi.fn()}},
{provide: AppSettingsService, useValue: {publicAppSettings$: publicSettingsSubject.asObservable()}},
{provide: AuthService, useValue: {token: signal(null), getInternalAccessToken: vi.fn()}},
{
provide: AppSettingsService,
useValue: {
publicAppSettings: signal(null),
getPublicSettingsQueryOptions: () => queryOptions({queryKey: ['public-settings'], queryFn: async () => defaultPublicSettings}),
},
},
{provide: QueryClient, useValue: mockQueryClient},
AuthInitializationService,
]
});
@@ -32,8 +49,6 @@ describe('initializeAuthFactory', () => {
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
const initPromise = TestBed.runInInjectionContext(() => factory());
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!, oidcForceOnlyMode: false});
await initPromise;
expect(markSpy).toHaveBeenCalled();
@@ -49,8 +64,6 @@ describe('initializeAuthFactory', () => {
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
const initPromise = TestBed.runInInjectionContext(() => factory());
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!, oidcForceOnlyMode: false});
await initPromise;
expect(markSpy).toHaveBeenCalled();
@@ -2,6 +2,7 @@ import {inject} from '@angular/core';
import {AuthService, websocketInitializer} from '../../shared/service/auth.service';
import {AppSettingsService} from '../../shared/service/app-settings.service';
import {AuthInitializationService} from './auth-initialization-service';
import {QueryClient} from '@tanstack/angular-query-experimental';
const SETTINGS_TIMEOUT_MS = 10000;
@@ -10,42 +11,41 @@ export function initializeAuthFactory() {
const appSettingsService = inject(AppSettingsService);
const authService = inject(AuthService);
const authInitService = inject(AuthInitializationService);
const queryClient = inject(QueryClient);
return new Promise<void>((resolve) => {
const settingsPromise = queryClient.fetchQuery(appSettingsService.getPublicSettingsQueryOptions());
const timeoutPromise = new Promise<null>(resolve =>
setTimeout(() => resolve(null), SETTINGS_TIMEOUT_MS)
);
const settingsTimeout = setTimeout(() => {
return Promise.race([settingsPromise, timeoutPromise]).then(publicSettings => {
if (!publicSettings) {
console.warn('[Auth] Public settings fetch timed out, falling back to local auth');
sub.unsubscribe();
authInitService.markAsInitialized();
resolve();
}, SETTINGS_TIMEOUT_MS);
return;
}
const sub = appSettingsService.publicAppSettings$.subscribe(publicSettings => {
if (publicSettings) {
clearTimeout(settingsTimeout);
if (publicSettings.remoteAuthEnabled) {
authService.remoteLogin().subscribe({
next: () => {
authInitService.markAsInitialized();
resolve();
},
error: err => {
console.error('[Remote Login] failed:', err);
authInitService.markAsInitialized();
resolve();
}
});
} else {
if (authService.getInternalAccessToken()) {
websocketInitializer(authService)();
if (publicSettings.remoteAuthEnabled) {
return new Promise<void>(resolve => {
authService.remoteLogin().subscribe({
next: () => {
authInitService.markAsInitialized();
resolve();
},
error: err => {
console.error('[Remote Login] failed:', err);
authInitService.markAsInitialized();
resolve();
}
authInitService.markAsInitialized();
resolve();
}
sub.unsubscribe();
});
});
} else {
if (authService.getInternalAccessToken()) {
websocketInitializer(authService)();
}
});
authInitService.markAsInitialized();
return;
}
});
};
}
@@ -1,20 +1,15 @@
import {inject} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';
import {UserService} from '../../../features/settings/user-management/user.service';
import {map} from 'rxjs/operators';
export const BookdropGuard: CanActivateFn = () => {
const userService = inject(UserService);
const router = inject(Router);
const user = userService.currentUser();
return userService.userState$.pipe(
map(state => {
const user = state.user;
if (user && (user.permissions.admin || user.permissions.canAccessBookdrop)) {
return true;
}
router.navigate(['/dashboard']);
return false;
})
);
if (user && (user.permissions.admin || user.permissions.canAccessBookdrop)) {
return true;
}
router.navigate(['/dashboard']);
return false;
};
@@ -1,20 +1,15 @@
import {inject} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';
import {UserService} from '../../../features/settings/user-management/user.service';
import {map} from 'rxjs/operators';
export const EditMetadataGuard: CanActivateFn = () => {
const userService = inject(UserService);
const router = inject(Router);
const user = userService.currentUser();
return userService.userState$.pipe(
map(state => {
const user = state.user;
if (user && (user.permissions.admin || user.permissions.canEditMetadata)) {
return true;
}
router.navigate(['/dashboard']);
return false;
})
);
if (user && (user.permissions.admin || user.permissions.canEditMetadata)) {
return true;
}
router.navigate(['/dashboard']);
return false;
};
@@ -1,20 +1,15 @@
import {inject} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';
import {UserService} from '../../../features/settings/user-management/user.service';
import {map} from 'rxjs/operators';
export const LibraryStatsGuard: CanActivateFn = () => {
const userService = inject(UserService);
const router = inject(Router);
const user = userService.currentUser();
return userService.userState$.pipe(
map(state => {
const user = state.user;
if (user && (user.permissions.admin || user.permissions.canAccessLibraryStats)) {
return true;
}
router.navigate(['/dashboard']);
return false;
})
);
if (user && (user.permissions.admin || user.permissions.canAccessLibraryStats)) {
return true;
}
router.navigate(['/dashboard']);
return false;
};
@@ -1,20 +1,15 @@
import {inject} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';
import {UserService} from '../../../features/settings/user-management/user.service';
import {map} from 'rxjs/operators';
export const ManageLibraryGuard: CanActivateFn = () => {
const userService = inject(UserService);
const router = inject(Router);
const user = userService.currentUser();
return userService.userState$.pipe(
map(state => {
const user = state.user;
if (user && (user.permissions.admin || user.permissions.canManageLibrary)) {
return true;
}
router.navigate(['/dashboard']);
return false;
})
);
if (user && (user.permissions.admin || user.permissions.canManageLibrary)) {
return true;
}
router.navigate(['/dashboard']);
return false;
};
@@ -1,20 +1,15 @@
import {inject} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';
import {UserService} from '../../../features/settings/user-management/user.service';
import {map} from 'rxjs/operators';
export const UserStatsGuard: CanActivateFn = () => {
const userService = inject(UserService);
const router = inject(Router);
const user = userService.currentUser();
return userService.userState$.pipe(
map(state => {
const user = state.user;
if (user && (user.permissions.admin || user.permissions.canAccessUserStats)) {
return true;
}
router.navigate(['/dashboard']);
return false;
})
);
if (user && (user.permissions.admin || user.permissions.canAccessUserStats)) {
return true;
}
router.navigate(['/dashboard']);
return false;
};
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, effect, inject} from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
import {Button} from 'primeng/button';
@@ -8,9 +8,7 @@ import {ToggleSwitch} from 'primeng/toggleswitch';
import {InputNumber} from 'primeng/inputnumber';
import {MessageService} from 'primeng/api';
import {AppSettingsService} from '../../../shared/service/app-settings.service';
import {Observable} from 'rxjs';
import {AppSettingKey, AppSettings, OidcProviderDetails, OidcTestResult} from '../../../shared/model/app-settings.model';
import {filter, take} from 'rxjs/operators';
import {MultiSelect} from 'primeng/multiselect';
import {Library} from '../../../features/book/model/library.model';
import {LibraryService} from '../../../features/book/service/library.service';
@@ -46,7 +44,7 @@ import {TagComponent} from '../../../shared/components/tag/tag.component';
],
styleUrls: ['./authentication-settings.component.scss']
})
export class AuthenticationSettingsComponent implements OnInit {
export class AuthenticationSettingsComponent {
availablePermissions = [
{label: 'Upload Books', value: 'permissionUpload', selected: false, translationKey: 'perms.uploadBooks'},
{label: 'Download Books', value: 'permissionDownload', selected: false, translationKey: 'perms.downloadBooks'},
@@ -64,7 +62,7 @@ export class AuthenticationSettingsComponent implements OnInit {
allowLocalAccountLinking = true;
selectedPermissions: string[] = [];
oidcEnabled = false;
allLibraries: Library[] = [];
editingLibraryIds: number[] = [];
sessionDurationHours: number | null = null;
backchannelLogoutUri = `${window.location.origin}/api/v1/auth/oidc/backchannel-logout`;
@@ -116,21 +114,14 @@ export class AuthenticationSettingsComponent implements OnInit {
private libraryService = inject(LibraryService);
private groupMappingService = inject(OidcGroupMappingService);
private t = inject(TranslocoService);
get allLibraries() { return this.libraryService.libraries(); }
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
ngOnInit(): void {
this.appSettings$.pipe(
filter((settings): settings is AppSettings => settings != null),
take(1)
).subscribe(settings => this.loadSettings(settings));
this.libraryService.libraryState$
.pipe(
filter(state => !!state?.loaded),
take(1)
).subscribe(state => this.allLibraries = state.libraries ?? []);
}
private readonly loadSettingsEffect = effect(() => {
const settings = this.appSettingsService.appSettings();
if (settings) {
this.loadSettings(settings);
}
});
loadSettings(settings: AppSettings): void {
this.oidcEnabled = settings.oidcEnabled;
@@ -1,5 +1,5 @@
<ng-container *transloco="let t; prefix: 'authorBrowser'">
@if (loading) {
@if (loading()) {
<div class="loading-state">
<p-progressSpinner
[style]="{'width': '60px', 'height': '60px'}"
@@ -10,7 +10,7 @@
</div>
}
@if (!loading) {
@if (!loading()) {
<div class="browse-header">
<h2 class="browse-title">{{ t('browseAllAuthors') }}</h2>
@@ -21,7 +21,7 @@
pInputText
type="text"
[placeholder]="t('searchPlaceholder')"
[ngModel]="searchTerm$ | async"
[ngModel]="searchTerm()"
(ngModelChange)="onSearchChange($event)"
class="search-input"/>
</div>
@@ -29,7 +29,7 @@
<div class="filter-sort-wrapper">
<p-select
[options]="sortOptions"
[ngModel]="sortBy$ | async"
[ngModel]="sortBy()"
(ngModelChange)="onSortChange($event)"
optionLabel="label"
optionValue="value"
@@ -37,12 +37,12 @@
</p-select>
<button class="sort-direction-btn" (click)="toggleSortDirection()">
<i class="pi" [class.pi-arrow-up]="(sortDirection$ | async) === 'asc'" [class.pi-arrow-down]="(sortDirection$ | async) === 'desc'"></i>
<i class="pi" [class.pi-arrow-up]="sortDirection() === 'asc'" [class.pi-arrow-down]="sortDirection() === 'desc'"></i>
</button>
<button class="filter-btn" (click)="filterPopover.toggle($event)">
<i class="pi pi-filter"></i>
@if (activeFilterCount > 0) {
@if (activeFilterCount() > 0) {
<span class="filter-badge"></span>
}
</button>
@@ -55,15 +55,15 @@
<div class="display-settings-content">
<label class="display-settings-label">{{ t('cardSize') }}</label>
<p-slider
[(ngModel)]="authorScaleService.scaleFactor"
[ngModel]="authorScaleService.scaleFactor()"
(ngModelChange)="authorScaleService.setScale($event)"
[min]="0.7"
[max]="1.3"
[step]="0.01"
[style]="{ width: '100%' }"
(onChange)="updateScale()">
[style]="{ width: '100%' }">
</p-slider>
<div class="scale-value-display">
{{ authorScaleService.scaleFactor.toFixed(2) }}x
{{ authorScaleService.scaleFactor().toFixed(2) }}x
</div>
</div>
</p-popover>
@@ -79,7 +79,7 @@
{label: t('filters.matched'), value: 'matched'},
{label: t('filters.unmatched'), value: 'unmatched'}
]"
[ngModel]="(filters$ | async)?.matchStatus"
[ngModel]="filters().matchStatus"
(ngModelChange)="onFilterChange('matchStatus', $event)"
optionLabel="label"
optionValue="value"
@@ -95,7 +95,7 @@
{label: t('filters.hasPhoto'), value: 'has-photo'},
{label: t('filters.noPhoto'), value: 'no-photo'}
]"
[ngModel]="(filters$ | async)?.photoStatus"
[ngModel]="filters().photoStatus"
(ngModelChange)="onFilterChange('photoStatus', $event)"
optionLabel="label"
optionValue="value"
@@ -113,7 +113,7 @@
{label: t('filters.inProgress'), value: 'in-progress'},
{label: t('filters.unread'), value: 'unread'}
]"
[ngModel]="(filters$ | async)?.readStatus"
[ngModel]="filters().readStatus"
(ngModelChange)="onFilterChange('readStatus', $event)"
optionLabel="label"
optionValue="value"
@@ -137,7 +137,7 @@
{label: '21-35', value: '21-35'},
{label: '36+', value: '36+'}
]"
[ngModel]="(filters$ | async)?.bookCount"
[ngModel]="filters().bookCount"
(ngModelChange)="onFilterChange('bookCount', $event)"
optionLabel="label"
optionValue="value"
@@ -148,8 +148,8 @@
<div class="filter-group">
<label class="filter-label">{{ t('filters.library') }}</label>
<p-select
[options]="libraryOptions"
[ngModel]="(filters$ | async)?.library"
[options]="libraryOptions()"
[ngModel]="filters().library"
(ngModelChange)="onFilterChange('library', $event)"
optionLabel="label"
optionValue="value"
@@ -160,8 +160,8 @@
<div class="filter-group">
<label class="filter-label">{{ t('filters.genre') }}</label>
<p-select
[options]="genreOptions"
[ngModel]="(filters$ | async)?.genre"
[options]="genreOptions()"
[ngModel]="filters().genre"
(ngModelChange)="onFilterChange('genre', $event)"
optionLabel="label"
optionValue="value"
@@ -169,7 +169,7 @@
</p-select>
</div>
@if (activeFilterCount > 0) {
@if (activeFilterCount() > 0) {
<p-button
[label]="t('filters.reset')"
icon="pi pi-filter-slash"
@@ -186,7 +186,7 @@
</div>
</div>
@if (filteredAuthors$ | async; as authorList) {
@if (filteredAuthors(); as authorList) {
@if (authorList.length === 0) {
<div class="empty-state">
<i class="pi pi-users empty-icon"></i>
@@ -203,7 +203,7 @@
@for (author of scroll.viewPortItems; track author.id; let i = $index) {
<div class="virtual-scroller-item"
[ngStyle]="{width: cardWidth + 'px', height: cardHeight + 'px'}"
[style.--card-scale]="authorScaleService.scaleFactor">
[style.--card-scale]="authorScaleService.scaleFactor()">
<app-author-card
[author]="author"
[index]="authorList.indexOf(author)"
@@ -226,12 +226,12 @@
}
}
@if (userService.userState$ | async; as userState) {
<div class="author-browser-footer" [class.footer-hidden]="selectedCount === 0">
@if (currentUser(); as user) {
<div class="author-browser-footer" [class.footer-hidden]="selectedCount() === 0">
<div class="footer-content">
<div class="selected-count-badge">
<i class="pi pi-check-circle"></i>
<span class="selected-count">{{ selectedCount }}</span>
<span class="selected-count">{{ selectedCount() }}</span>
<span class="selected-label">{{ t('footer.selected') }}</span>
</div>
@if (canEditMetadata || canDeleteBook) {
@@ -1,8 +1,8 @@
import {Component, HostListener, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {AsyncPipe, NgStyle} from '@angular/common';
import {Component, computed, DestroyRef, effect, HostListener, inject, OnInit, signal, ViewChild} from '@angular/core';
import {NgStyle} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {combineLatest, Observable, BehaviorSubject, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {filter} from 'rxjs/operators';
import {ProgressSpinner} from 'primeng/progressspinner';
import {InputText} from 'primeng/inputtext';
import {Select} from 'primeng/select';
@@ -56,7 +56,6 @@ const DEFAULT_SORT_DIRECTIONS: Record<string, SortDirection> = {
templateUrl: './author-browser.component.html',
styleUrls: ['./author-browser.component.scss'],
imports: [
AsyncPipe,
NgStyle,
FormsModule,
ProgressSpinner,
@@ -72,7 +71,7 @@ const DEFAULT_SORT_DIRECTIONS: Record<string, SortDirection> = {
VirtualScrollerModule
]
})
export class AuthorBrowserComponent implements OnInit, OnDestroy {
export class AuthorBrowserComponent implements OnInit {
private static readonly BASE_WIDTH = 165;
private static readonly BASE_HEIGHT = 290;
@@ -87,6 +86,7 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
private t = inject(TranslocoService);
private router = inject(Router);
private activatedRoute = inject(ActivatedRoute);
private destroyRef = inject(DestroyRef);
protected userService = inject(UserService);
protected authorScaleService = inject(AuthorScalePreferenceService);
protected selectionService = inject(AuthorSelectionService);
@@ -94,15 +94,87 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
@ViewChild('scroll')
virtualScroller: VirtualScrollerComponent | undefined;
private subscriptions: Subscription[] = [];
loading = true;
private authorsLoaded = false;
private booksLoaded = false;
screenWidth = window.innerWidth;
selectedCount = 0;
isCheckboxEnabled = false;
thumbnailCacheBusters = new Map<number, number>();
private selectedAuthors = this.selectionService.selectedAuthors;
private allAuthorsState = signal<AuthorSummary[] | null>(null);
loading = computed(() => this.allAuthorsState() === null || this.bookService.isBooksLoading());
protected currentUser = this.userService.currentUser;
selectedCount = computed(() => this.selectedAuthors().size);
searchTerm = signal('');
sortBy = signal('name');
sortDirection = signal<SortDirection>('asc');
filters = signal<AuthorFilters>({...DEFAULT_AUTHOR_FILTERS});
private enrichedAuthors = computed(() => {
const authors = this.allAuthorsState();
if (!authors) {
return [];
}
return this.enrichAuthors(authors, this.bookService.books());
});
libraryOptions = computed<FilterOption[]>(() => {
const allLabel = this.t.translate('authorBrowser.filters.all');
const librarySet = new Set<string>();
for (const author of this.enrichedAuthors()) {
for (const library of author.libraryNames) {
librarySet.add(library);
}
}
return [
{label: allLabel, value: 'all'},
...[...librarySet].sort().map(library => ({label: library, value: library}))
];
});
genreOptions = computed<FilterOption[]>(() => {
const allLabel = this.t.translate('authorBrowser.filters.all');
const genreSet = new Set<string>();
for (const author of this.enrichedAuthors()) {
for (const category of author.categories) {
genreSet.add(category);
}
}
return [
{label: allLabel, value: 'all'},
...[...genreSet].sort().map(category => ({label: category, value: category}))
];
});
activeFilterCount = computed(() => {
const filters = this.filters();
let count = 0;
if (filters.matchStatus !== 'all') count++;
if (filters.photoStatus !== 'all') count++;
if (filters.readStatus !== 'all') count++;
if (filters.bookCount !== 'all') count++;
if (filters.library !== 'all') count++;
if (filters.genre !== 'all') count++;
return count;
});
filteredAuthors = computed<EnrichedAuthor[]>(() => {
let result = this.enrichedAuthors();
const search = this.searchTerm().trim().toLowerCase();
if (search) {
result = result.filter(author => author.name.toLowerCase().includes(search));
}
result = this.applyFilters(result, this.filters());
return this.applySort(result, this.sortBy(), this.sortDirection());
});
private readonly syncAuthorsEffect = effect(() => {
const authors = this.authorService.allAuthors();
if (authors !== null) {
this.allAuthorsState.set(authors);
}
});
private readonly syncSelectionEffect = effect(() => {
this.selectionService.setCurrentAuthors(this.filteredAuthors());
});
@HostListener('window:resize')
onResize(): void {
@@ -117,39 +189,27 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
const base = this.isMobile
? AuthorBrowserComponent.MOBILE_BASE_WIDTH
: AuthorBrowserComponent.BASE_WIDTH;
return Math.round(base * this.authorScaleService.scaleFactor);
return Math.round(base * this.authorScaleService.scaleFactor());
}
get cardHeight(): number {
const base = this.isMobile
? AuthorBrowserComponent.MOBILE_BASE_HEIGHT
: AuthorBrowserComponent.BASE_HEIGHT;
return Math.round(base * this.authorScaleService.scaleFactor);
return Math.round(base * this.authorScaleService.scaleFactor());
}
get gridColumnMinWidth(): string {
return `${this.cardWidth}px`;
}
searchTerm$ = new BehaviorSubject<string>('');
sortBy$ = new BehaviorSubject<string>('name');
sortDirection$ = new BehaviorSubject<SortDirection>('asc');
allAuthors$ = new BehaviorSubject<AuthorSummary[]>([]);
filters$ = new BehaviorSubject<AuthorFilters>({...DEFAULT_AUTHOR_FILTERS});
sortOptions: SortOption[] = [];
libraryOptions: FilterOption[] = [];
genreOptions: FilterOption[] = [];
activeFilterCount = 0;
private readonly validSortValues = [
'name', 'book-count', 'matched', 'recently-added', 'recently-read',
'reading-progress', 'avg-rating', 'photo', 'series-count'
];
filteredAuthors$!: Observable<EnrichedAuthor[]>;
private enrichedAuthors$ = new BehaviorSubject<EnrichedAuthor[]>([]);
ngOnInit(): void {
this.pageTitle.setPageTitle(this.t.translate('authorBrowser.pageTitle'));
@@ -168,116 +228,51 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
const sortParam = this.activatedRoute.snapshot.queryParamMap.get('sort');
const dirParam = this.activatedRoute.snapshot.queryParamMap.get('dir') as SortDirection | null;
if (sortParam && this.validSortValues.includes(sortParam)) {
this.sortBy$.next(sortParam);
this.sortDirection$.next(dirParam === 'asc' || dirParam === 'desc' ? dirParam : DEFAULT_SORT_DIRECTIONS[sortParam]);
this.sortBy.set(sortParam);
this.sortDirection.set(dirParam === 'asc' || dirParam === 'desc' ? dirParam : DEFAULT_SORT_DIRECTIONS[sortParam]);
}
this.subscriptions.push(
this.authorService.allAuthors$.pipe(
filter((authors): authors is AuthorSummary[] => authors !== null)
).subscribe(authors => {
this.allAuthors$.next(authors);
this.authorsLoaded = true;
this.updateLoading();
})
);
this.subscriptions.push(
combineLatest([
this.allAuthors$,
this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
map(state => state.books || [])
)
]).subscribe(([authors, books]) => {
this.booksLoaded = true;
this.updateLoading();
const enriched = this.enrichAuthors(authors, books);
this.updateDynamicFilterOptions(enriched);
this.enrichedAuthors$.next(enriched);
})
);
this.filteredAuthors$ = combineLatest([
this.enrichedAuthors$,
this.searchTerm$,
this.sortBy$,
this.sortDirection$,
this.filters$
]).pipe(
map(([enriched, search, sortBy, sortDir, filters]) => {
let result = enriched;
if (search.trim()) {
const term = search.trim().toLowerCase();
result = result.filter(a => a.name.toLowerCase().includes(term));
}
result = this.applyFilters(result, filters);
result = this.applySort(result, sortBy, sortDir);
this.selectionService.setCurrentAuthors(result);
return result;
})
);
this.subscriptions.push(
this.selectionService.selectedAuthors$.subscribe(selected => {
this.selectedCount = selected.size;
this.isCheckboxEnabled = selected.size > 0;
})
);
this.setupScrollPositionTracking();
}
ngOnDestroy(): void {
this.subscriptions.forEach(s => s.unsubscribe());
this.selectionService.deselectAll();
this.destroyRef.onDestroy(() => this.selectionService.deselectAll());
}
onSearchChange(value: string): void {
this.searchTerm$.next(value);
this.searchTerm.set(value);
}
onSortChange(value: string): void {
this.sortBy$.next(value);
this.sortDirection$.next(DEFAULT_SORT_DIRECTIONS[value] || 'asc');
this.updateSortQueryParams(value, this.sortDirection$.value);
this.sortBy.set(value);
const nextDirection = DEFAULT_SORT_DIRECTIONS[value] || 'asc';
this.sortDirection.set(nextDirection);
this.updateSortQueryParams(value, nextDirection);
}
toggleSortDirection(): void {
const next: SortDirection = this.sortDirection$.value === 'asc' ? 'desc' : 'asc';
this.sortDirection$.next(next);
this.updateSortQueryParams(this.sortBy$.value, next);
const next: SortDirection = this.sortDirection() === 'asc' ? 'desc' : 'asc';
this.sortDirection.set(next);
this.updateSortQueryParams(this.sortBy(), next);
}
onFilterChange(key: keyof AuthorFilters, value: string): void {
const current = this.filters$.value;
this.filters$.next({...current, [key]: value});
this.updateActiveFilterCount();
this.filters.update(current => ({...current, [key]: value}));
}
resetFilters(): void {
this.filters$.next({...DEFAULT_AUTHOR_FILTERS});
this.activeFilterCount = 0;
}
updateScale(): void {
this.authorScaleService.setScale(this.authorScaleService.scaleFactor);
this.filters.set({...DEFAULT_AUTHOR_FILTERS});
}
get canEditMetadata(): boolean {
const user = this.userService.getCurrentUser();
const user = this.userService.currentUser();
return !!user?.permissions?.admin || !!user?.permissions?.canEditMetadata;
}
get canDeleteBook(): boolean {
const user = this.userService.getCurrentUser();
const user = this.userService.currentUser();
return !!user?.permissions?.admin || !!user?.permissions?.canDeleteBook;
}
isAuthorSelected(authorId: number): boolean {
return this.selectionService.selectedAuthors.has(authorId);
return this.selectedAuthors().has(authorId);
}
onCheckboxClicked(event: AuthorCheckboxClickEvent): void {
@@ -322,9 +317,9 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
onAuthorQuickMatched(updated: AuthorSummary): void {
this.thumbnailCacheBusters.set(updated.id, Date.now());
const current = this.allAuthors$.value;
const updatedList = current.map(a => a.id === updated.id ? updated : a);
this.allAuthors$.next(updatedList);
this.allAuthorsState.update(current =>
(current ?? []).map(author => author.id === updated.id ? updated : author)
);
}
autoMatchSelected(): void {
@@ -333,10 +328,9 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
this.authorService.autoMatchAuthors(ids).subscribe({
next: (matched) => {
this.thumbnailCacheBusters.set(matched.id, Date.now());
const current = this.allAuthors$.value;
this.allAuthors$.next(current.map(a => a.id === matched.id
? {...a, asin: matched.asin, hasPhoto: matched.hasPhoto}
: a
this.allAuthorsState.update(current => (current ?? []).map(author => author.id === matched.id
? {...author, asin: matched.asin, hasPhoto: matched.hasPhoto}
: author
));
},
complete: () => {
@@ -386,43 +380,6 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
});
}
private updateLoading(): void {
this.loading = !this.authorsLoaded || !this.booksLoaded;
}
private updateActiveFilterCount(): void {
const f = this.filters$.value;
let count = 0;
if (f.matchStatus !== 'all') count++;
if (f.photoStatus !== 'all') count++;
if (f.readStatus !== 'all') count++;
if (f.bookCount !== 'all') count++;
if (f.library !== 'all') count++;
if (f.genre !== 'all') count++;
this.activeFilterCount = count;
}
private updateDynamicFilterOptions(authors: EnrichedAuthor[]): void {
const allLabel = this.t.translate('authorBrowser.filters.all');
const librarySet = new Set<string>();
const genreSet = new Set<string>();
for (const a of authors) {
for (const lib of a.libraryNames) librarySet.add(lib);
for (const cat of a.categories) genreSet.add(cat);
}
this.libraryOptions = [
{label: allLabel, value: 'all'},
...[...librarySet].sort().map(lib => ({label: lib, value: lib}))
];
this.genreOptions = [
{label: allLabel, value: 'all'},
...[...genreSet].sort().map(cat => ({label: cat, value: cat}))
];
}
private enrichAuthors(authors: AuthorSummary[], books: Book[]): EnrichedAuthor[] {
const booksByAuthor = new Map<string, Book[]>();
for (const book of books) {
@@ -544,14 +501,13 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
}
private setupScrollPositionTracking(): void {
this.subscriptions.push(
this.router.events.pipe(
filter(event => event instanceof NavigationStart)
).subscribe(() => {
this.dismissBodyMenus();
this.saveScrollPosition();
})
);
this.router.events.pipe(
filter(event => event instanceof NavigationStart),
takeUntilDestroyed(this.destroyRef)
).subscribe(() => {
this.dismissBodyMenus();
this.saveScrollPosition();
});
}
private dismissBodyMenus(): void {
@@ -568,8 +524,7 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
private removeAuthorsFromList(ids: number[]): void {
const idSet = new Set(ids);
const updated = this.allAuthors$.value.filter(a => !idSet.has(a.id));
this.allAuthors$.next(updated);
this.allAuthorsState.update(current => (current ?? []).filter(author => !idSet.has(author.id)));
}
private applySort(authors: EnrichedAuthor[], sortBy: string, direction: SortDirection): EnrichedAuthor[] {
@@ -7,7 +7,7 @@
</div>
}
@if (!loading && author) {
@if (!loading && author(); as author) {
<div class="author-wrapper">
<p-tabs [value]="tab" lazy="true" scrollable>
<p-tablist>
@@ -95,7 +95,7 @@
</div>
</div>
@if (authorBooks$ | async; as books) {
@if (authorBooks(); as books) {
<div class="books-section">
<h3 class="section-title">{{ t('booksBy', {name: author.name}) }} ({{ books.length }})</h3>
@if (books.length === 0) {
@@ -1,8 +1,6 @@
import {AfterViewChecked, Component, ElementRef, inject, OnInit, ViewChild} from '@angular/core';
import {AfterViewChecked, Component, computed, ElementRef, inject, OnInit, signal, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {combineLatest, Observable} from 'rxjs';
import {filter, map} from 'rxjs/operators';
import {NgClass, NgStyle} from '@angular/common';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {ProgressSpinner} from 'primeng/progressspinner';
import {Button} from 'primeng/button';
@@ -14,7 +12,6 @@ import {Tooltip} from 'primeng/tooltip';
import {AuthorService} from '../../service/author.service';
import {AuthorDetails} from '../../model/author.model';
import {BookService} from '../../../book/service/book.service';
import {Book} from '../../../book/model/book.model';
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
@@ -29,7 +26,6 @@ import {PageTitleService} from '../../../../shared/service/page-title.service';
templateUrl: './author-detail.component.html',
styleUrls: ['./author-detail.component.scss'],
imports: [
AsyncPipe,
NgClass,
NgStyle,
Tabs,
@@ -63,7 +59,6 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
author: AuthorDetails | null = null;
loading = true;
tab = 'books';
isExpanded = false;
@@ -71,20 +66,31 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
hasPhoto = true;
photoTimestamp = Date.now();
quickMatching = false;
private authorState = signal<AuthorDetails | null>(null);
author = this.authorState.asReadonly();
authorBooks = computed(() => {
const authorName = this.author()?.name?.toLowerCase();
if (!authorName) {
return [];
}
authorBooks$!: Observable<Book[]>;
return this.bookService.books().filter(book =>
book.metadata?.authors?.some(author => author.toLowerCase() === authorName)
);
});
get currentCardSize() {
return this.coverScalePreferenceService.currentCardSize;
return this.coverScalePreferenceService.currentCardSize();
}
get gridColumnMinWidth(): string {
return this.coverScalePreferenceService.gridColumnMinWidth;
return this.coverScalePreferenceService.gridColumnMinWidth();
}
get photoUrl(): string {
if (!this.author) return '';
return this.authorService.getAuthorPhotoUrl(this.author.id) + '&t=' + this.photoTimestamp;
const author = this.author();
if (!author) return '';
return this.authorService.getAuthorPhotoUrl(author.id) + '&t=' + this.photoTimestamp;
}
get canEditMetadata(): boolean {
@@ -99,18 +105,6 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
this.tab = tabParam;
}
this.loadAuthor(authorId);
this.authorBooks$ = this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
map(state => {
const books = state.books || [];
const authorName = this.author?.name?.toLowerCase();
if (!authorName) return [];
return books.filter(b =>
b.metadata?.authors?.some(a => a.toLowerCase() === authorName)
);
})
);
}
ngAfterViewChecked(): void {
@@ -129,15 +123,21 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
}
onAuthorUpdated(updatedAuthor: AuthorDetails): void {
this.author = updatedAuthor;
this.authorState.set(updatedAuthor);
this.hasPhoto = true;
this.photoTimestamp = Date.now();
this.authorService.patchAuthorInCache(updatedAuthor.id, {
name: updatedAuthor.name,
asin: updatedAuthor.asin,
hasPhoto: true,
});
}
quickMatch(): void {
if (!this.author || this.quickMatching) return;
const author = this.author();
if (!author || this.quickMatching) return;
this.quickMatching = true;
this.authorService.quickMatchAuthor(this.author.id).subscribe({
this.authorService.quickMatchAuthor(author.id).subscribe({
next: (matched) => {
this.onAuthorUpdated(matched);
this.quickMatching = false;
@@ -161,20 +161,9 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
private loadAuthor(authorId: number): void {
this.authorService.getAuthorDetails(authorId).subscribe({
next: (author) => {
this.author = author;
this.authorState.set(author);
this.loading = false;
this.pageTitle.setPageTitle(author.name);
this.authorBooks$ = this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
map(state => {
const books = state.books || [];
const name = author.name.toLowerCase();
return books.filter(b =>
b.metadata?.authors?.some(a => a.toLowerCase() === name)
);
})
);
},
error: () => {
this.loading = false;
@@ -0,0 +1,10 @@
import {QueryClient} from '@tanstack/angular-query-experimental';
import {AuthorSummary} from '../model/author.model';
import {AUTHORS_QUERY_KEY} from './author-query-keys';
export function patchAuthorInCache(queryClient: QueryClient, authorId: number, fields: Partial<AuthorSummary>): void {
queryClient.setQueryData<AuthorSummary[]>(AUTHORS_QUERY_KEY, current =>
(current ?? []).map(author => author.id === authorId ? {...author, ...fields} : author)
);
}
@@ -0,0 +1 @@
export const AUTHORS_QUERY_KEY = ['authors'] as const;
@@ -1,6 +1,4 @@
import {inject, Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {inject, Injectable, signal} from '@angular/core';
import {LocalStorageService} from '../../../shared/service/local-storage.service';
@Injectable({
@@ -13,31 +11,46 @@ export class AuthorScalePreferenceService {
private readonly localStorageService = inject(LocalStorageService);
private readonly scaleChangeSubject = new Subject<number>();
private readonly _scaleFactor = signal(1.0);
readonly scaleFactor = this._scaleFactor.asReadonly();
scaleFactor = 1.0;
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
private lastPersistedScale = 1.0;
constructor() {
this.loadScaleFromStorage();
this.scaleChangeSubject
.pipe(debounceTime(this.DEBOUNCE_MS))
.subscribe(scale => this.saveScalePreference(scale));
const initialScale = this.loadScaleFromStorage();
this._scaleFactor.set(initialScale);
this.lastPersistedScale = initialScale;
}
setScale(scale: number): void {
this.scaleFactor = scale;
this.scaleChangeSubject.next(scale);
this._scaleFactor.set(scale);
if (scale === this.lastPersistedScale) {
return;
}
this.scheduleSave(scale);
}
private scheduleSave(scale: number): void {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(() => {
this.saveScalePreference(scale);
}, this.DEBOUNCE_MS);
}
private saveScalePreference(scale: number): void {
this.localStorageService.set(this.STORAGE_KEY, scale);
this.lastPersistedScale = scale;
}
private loadScaleFromStorage(): void {
private loadScaleFromStorage(): number {
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
if (saved !== null && !isNaN(saved)) {
this.scaleFactor = saved;
return saved;
}
return 1.0;
}
}
@@ -1,5 +1,4 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {computed, Injectable, signal} from '@angular/core';
import {AuthorSummary} from '../model/author.model';
export interface AuthorCheckboxClickEvent {
@@ -11,20 +10,13 @@ export interface AuthorCheckboxClickEvent {
@Injectable({providedIn: 'root'})
export class AuthorSelectionService {
private selectedAuthorsSubject = new BehaviorSubject<Set<number>>(new Set());
private readonly _selectedAuthors = signal<Set<number>>(new Set());
readonly selectedAuthors = this._selectedAuthors.asReadonly();
readonly selectedCount = computed(() => this._selectedAuthors().size);
private currentAuthors: AuthorSummary[] = [];
private lastSelectedIndex: number | null = null;
selectedAuthors$: Observable<Set<number>> = this.selectedAuthorsSubject.asObservable();
get selectedAuthors(): Set<number> {
return this.selectedAuthorsSubject.value;
}
get selectedCount(): number {
return this.selectedAuthorsSubject.value.size;
}
setCurrentAuthors(authors: AuthorSummary[]): void {
this.currentAuthors = authors;
}
@@ -55,31 +47,37 @@ export class AuthorSelectionService {
}
selectAll(): void {
const current = new Set(this.selectedAuthorsSubject.value);
for (const author of this.currentAuthors) {
current.add(author.id);
}
this.selectedAuthorsSubject.next(current);
this._selectedAuthors.update(current => {
const next = new Set(current);
for (const author of this.currentAuthors) {
next.add(author.id);
}
return next;
});
}
deselectAll(): void {
this.selectedAuthorsSubject.next(new Set());
this._selectedAuthors.set(new Set());
this.lastSelectedIndex = null;
}
getSelectedIds(): number[] {
return Array.from(this.selectedAuthorsSubject.value);
return Array.from(this.selectedAuthors());
}
private select(id: number): void {
const current = new Set(this.selectedAuthorsSubject.value);
current.add(id);
this.selectedAuthorsSubject.next(current);
this._selectedAuthors.update(current => {
const next = new Set(current);
next.add(id);
return next;
});
}
private deselect(id: number): void {
const current = new Set(this.selectedAuthorsSubject.value);
current.delete(id);
this.selectedAuthorsSubject.next(current);
this._selectedAuthors.update(current => {
const next = new Set(current);
next.delete(id);
return next;
});
}
}
@@ -1,11 +1,14 @@
import {inject, Injectable} from '@angular/core';
import {computed, effect, inject, Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {lastValueFrom, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {SseClient} from 'ngx-sse-client';
import {API_CONFIG} from '../../../core/config/api-config';
import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model';
import {AuthService} from '../../../shared/service/auth.service';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {AUTHORS_QUERY_KEY} from './author-query-keys';
import {patchAuthorInCache} from './author-query-cache';
@Injectable({
providedIn: 'root'
@@ -15,16 +18,41 @@ export class AuthorService {
private http = inject(HttpClient);
private authService = inject(AuthService);
private sseClient = inject(SseClient);
private queryClient = inject(QueryClient);
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`;
private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`;
private readonly token = this.authService.token;
private allAuthorsSubject = new BehaviorSubject<AuthorSummary[] | null>(null);
allAuthors$ = this.allAuthorsSubject.asObservable();
private authorsQuery = injectQuery(() => ({
...this.getAuthorsQueryOptions(),
enabled: !!this.token(),
}));
getAllAuthors(): Observable<AuthorSummary[]> {
return this.http.get<AuthorSummary[]>(this.baseUrl).pipe(
tap(authors => this.allAuthorsSubject.next(authors))
);
allAuthors = computed(() => this.authorsQuery.data() ?? null);
isAuthorsLoading = computed(() => !!this.token() && this.authorsQuery.isPending());
constructor() {
effect(() => {
const token = this.token();
if (token === null) {
this.queryClient.removeQueries({queryKey: AUTHORS_QUERY_KEY});
}
});
}
private getAuthorsQueryOptions() {
return queryOptions({
queryKey: AUTHORS_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<AuthorSummary[]>(this.baseUrl))
});
}
invalidateAuthors(): void {
void this.queryClient.invalidateQueries({queryKey: AUTHORS_QUERY_KEY, exact: true});
}
patchAuthorInCache(authorId: number, fields: Partial<AuthorSummary>): void {
patchAuthorInCache(this.queryClient, authorId, fields);
}
getAuthorDetails(authorId: number): Observable<AuthorDetails> {
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, computed, effect, inject} from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
@@ -13,8 +13,6 @@ import {BookMetadataService} from '../../service/book-metadata.service';
import {LibraryService} from '../../service/library.service';
import {Library} from '../../model/library.model';
import {CreatePhysicalBookRequest} from '../../model/book.model';
import {filter, take} from 'rxjs/operators';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {TranslocoDirective} from '@jsverse/transloco';
@Component({
@@ -34,15 +32,13 @@ import {TranslocoDirective} from '@jsverse/transloco';
],
styleUrl: './add-physical-book-dialog.component.scss',
})
export class AddPhysicalBookDialogComponent implements OnInit {
export class AddPhysicalBookDialogComponent {
private dynamicDialogRef = inject(DynamicDialogRef);
private dialogConfig = inject(DynamicDialogConfig);
private bookService = inject(BookService);
private bookMetadataService = inject(BookMetadataService);
private libraryService = inject(LibraryService);
private destroyRef = inject(DestroyRef);
libraries: Library[] = [];
selectedLibraryId: number | null = null;
title: string = '';
isbn: string = '';
@@ -54,49 +50,33 @@ export class AddPhysicalBookDialogComponent implements OnInit {
pageCount: number | null = null;
categories: string[] = [];
allAuthors: string[] = [];
allCategories: string[] = [];
private readonly metadata = computed(() => this.bookService.uniqueMetadata());
get allAuthors(): string[] { return this.metadata().authors; }
get allCategories(): string[] { return this.metadata().categories; }
filteredAuthors: string[] = [];
filteredCategories: string[] = [];
coverUrl: string | null = null;
isLoading: boolean = false;
isFetchingMetadata: boolean = false;
private readonly initializeSelectedLibraryEffect = effect(() => {
const libraries = this.libraries;
if (libraries.length === 0) {
return;
}
ngOnInit(): void {
this.libraryService.libraryState$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(state => {
if (state.loaded && state.libraries) {
this.libraries = state.libraries;
if (this.dialogConfig.data?.libraryId) {
this.selectedLibraryId = this.dialogConfig.data.libraryId;
} else if (this.libraries.length > 0 && this.libraries[0].id !== undefined) {
this.selectedLibraryId = this.libraries[0].id;
}
}
});
this.prepareAutoComplete();
}
if (this.dialogConfig.data?.libraryId) {
this.selectedLibraryId = this.dialogConfig.data.libraryId;
return;
}
private prepareAutoComplete(): void {
this.bookService.bookState$
.pipe(
filter((bookState) => bookState.loaded),
take(1)
)
.subscribe((bookState) => {
const authors = new Set<string>();
const categories = new Set<string>();
if (this.selectedLibraryId == null && this.libraries[0].id !== undefined) {
this.selectedLibraryId = this.libraries[0].id;
}
});
(bookState.books ?? []).forEach((book) => {
book.metadata?.authors?.forEach((author) => authors.add(author));
book.metadata?.categories?.forEach((category) => categories.add(category));
});
this.allAuthors = Array.from(authors);
this.allCategories = Array.from(categories);
});
get libraries(): Library[] {
return this.libraryService.libraries();
}
filterAuthors(event: AutoCompleteCompleteEvent): void {
@@ -1,4 +1,4 @@
import {ChangeDetectorRef, Component, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {ChangeDetectorRef, Component, effect, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
@@ -12,7 +12,6 @@ import {BookFileService} from '../../service/book-file.service';
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
import {AdditionalFileType, Book} from '../../model/book.model';
import {MessageService} from 'primeng/api';
import {filter, take} from 'rxjs/operators';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
interface FileTypeOption {
@@ -73,18 +72,12 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
{ label: this.t.translate('book.fileUploader.typeAlternativeFormat'), value: AdditionalFileType.ALTERNATIVE_FORMAT },
{ label: this.t.translate('book.fileUploader.typeSupplementary'), value: AdditionalFileType.SUPPLEMENTARY }
];
this.appSettingsService.appSettings$
.pipe(
filter(settings => settings != null),
take(1)
)
.subscribe(settings => {
if (settings) {
const maxSizeMb = settings.maxFileUploadSizeInMb || 100;
this.maxFileSizeBytes = maxSizeMb * 1024 * 1024;
this.maxFileSizeDisplay = `${maxSizeMb} MB`;
}
});
const settings = this.appSettingsService.appSettings();
if (settings) {
const maxSizeMb = settings.maxFileUploadSizeInMb || 100;
this.maxFileSizeBytes = maxSizeMb * 1024 * 1024;
this.maxFileSizeDisplay = `${maxSizeMb} MB`;
}
}
ngOnDestroy(): void {
@@ -1,16 +1,10 @@
import {Injectable, inject} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Observable, of, combineLatest} from 'rxjs';
import {map, switchMap, take, catchError} from 'rxjs/operators';
import {ParamMap} from '@angular/router';
import {Library} from '../../model/library.model';
import {Shelf} from '../../model/shelf.model';
import {Book} from '../../model/book.model';
import {BookState} from '../../model/state/book-state.model';
import {SortOption} from '../../model/sort.model';
import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service';
import {ShelfService} from '../../service/shelf.service';
import {SortService} from '../../service/sort.service';
import {MagicShelf, MagicShelfService} 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';
@@ -24,79 +18,61 @@ export interface EntityInfo {
@Injectable({providedIn: 'root'})
export class BookBrowserEntityService {
private libraryService = inject(LibraryService);
private bookService = inject(BookService);
private shelfService = inject(ShelfService);
private sortService = inject(SortService);
private magicShelfService = inject(MagicShelfService);
private bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
getEntityInfoFromRoute(activatedRoute: ActivatedRoute): Observable<EntityInfo> {
return activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
const magicShelfId = Number(params.get('magicShelfId') || NaN);
getEntityInfo(paramMap: ParamMap): EntityInfo {
const libraryId = Number(paramMap.get('libraryId') || NaN);
const shelfId = Number(paramMap.get('shelfId') || NaN);
const magicShelfId = Number(paramMap.get('magicShelfId') || NaN);
if (!isNaN(libraryId)) {
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
return {entityId: shelfId, entityType: EntityType.SHELF};
} else if (!isNaN(magicShelfId)) {
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
} else {
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
})
);
if (!Number.isNaN(libraryId)) {
return {entityId: libraryId, entityType: EntityType.LIBRARY};
}
if (!Number.isNaN(shelfId)) {
return {entityId: shelfId, entityType: EntityType.SHELF};
}
if (!Number.isNaN(magicShelfId)) {
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
}
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | MagicShelf | null> {
getEntity(entityId: number, entityType: EntityType): Library | Shelf | MagicShelf | null {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchLibrary(entityId);
return this.libraryService.libraries().find(lib => lib.id === entityId) ?? null;
case EntityType.SHELF:
return this.fetchShelf(entityId);
return this.shelfService.shelves().find(shelf => shelf.id === entityId) ?? null;
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelf(entityId);
return this.magicShelfService.findShelfById(entityId) ?? null;
default:
return of(null);
return null;
}
}
fetchBooksByEntity(
entityId: number,
entityType: EntityType,
sortOption: SortOption
): Observable<BookState> {
getBooksByEntity(books: Book[], entityId: number, entityType: EntityType): Book[] {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchBooks(book => book.libraryId === entityId, sortOption);
return books.filter(book => book.libraryId === entityId);
case EntityType.SHELF:
return this.fetchShelfBooks(entityId, sortOption);
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelfBooks(entityId, sortOption);
return books.filter(book => book.shelves?.some(shelf => shelf.id === entityId) ?? false);
case EntityType.MAGIC_SHELF: {
const magicShelf = this.getEntity(entityId, entityType);
return this.isMagicShelf(magicShelf) ? this.filterByMagicShelf(books, magicShelf) : [];
}
case EntityType.UNSHELVED:
return books.filter(book => !book.shelves || book.shelves.length === 0);
case EntityType.ALL_BOOKS:
default:
return this.fetchAllBooks(sortOption);
return books;
}
}
fetchAllBooks(sortOption: SortOption): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState, sortOption))
);
}
fetchUnshelvedBooks(sortOption: SortOption): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => ({
...bookState,
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
})),
map(bookState => this.processBookState(bookState, sortOption))
);
}
isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
return (entity as Library).paths !== undefined;
}
@@ -105,85 +81,17 @@ export class BookBrowserEntityService {
return !!entity && 'filterJson' in entity;
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
);
}
private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
private fetchMagicShelf(magicShelfId: number): Observable<MagicShelf | null> {
return this.magicShelfService.shelvesState$.pipe(
take(1),
switchMap((state) => {
const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null;
if (cached) {
return of(cached);
}
return this.magicShelfService.getShelf(magicShelfId).pipe(
map(shelf => shelf ?? null),
catchError(() => of(null))
);
})
);
}
private fetchShelfBooks(shelfId: number, sortOption: SortOption): Observable<BookState> {
return this.fetchBooks(book => book.shelves?.some(s => s.id === shelfId) ?? false, sortOption);
}
private fetchMagicShelfBooks(magicShelfId: number, sortOption: SortOption): Observable<BookState> {
return combineLatest([
this.bookService.bookState$,
this.magicShelfService.getShelf(magicShelfId)
]).pipe(
map(([bookState, magicShelf]) => {
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
return bookState;
}
const allBooks = bookState.books ?? [];
const filteredBooks = allBooks.filter(book =>
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule, allBooks)
);
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], sortOption);
return {...bookState, books: sortedBooks};
})
);
}
private fetchBooks(bookFilter: (book: Book) => boolean, sortOption: SortOption): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.loaded && !bookState.error) {
const filteredBooks = bookState.books?.filter(bookFilter) || [];
const sortedBooks = this.sortService.applySort(filteredBooks, sortOption);
return {...bookState, books: sortedBooks};
}
return bookState;
})
);
}
private processBookState(bookState: BookState, sortOption: SortOption): BookState {
if (bookState.loaded && !bookState.error) {
const sortedBooks = this.sortService.applySort(bookState.books || [], sortOption);
return {...bookState, books: sortedBooks};
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
if (!magicShelf.filterJson) {
return [];
}
try {
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
} catch {
console.warn('Invalid filterJson for MagicShelf');
return [];
}
return bookState;
}
}
@@ -4,7 +4,7 @@
<div class="book-browser-header">
<div class="entity-info-wrapper">
@if (entityType$ | async; as entityType) {
@if (entityType(); as entityType) {
<div class="entity-info">
<p class="entity-title">
@if (entityType === EntityType.ALL_BOOKS) {
@@ -18,19 +18,19 @@
} @else if (entityType === EntityType.UNSHELVED) {
{{ (isFilterActive || hasSearchTerm) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
} @else {
{{ entityType }}: {{ (entity$ | async)?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
}
</p>
@if (seriesCollapseFilter.isSeriesCollapsed && (bookState$ | async)?.books; as books) {
@if (seriesCollapseFilter.seriesCollapsed() && books(); as books) {
<p class="series-collapsed-info">
{{ t('labels.seriesCollapsedInfo', { count: books.length, itemWord: books.length === 1 ? t('labels.item') : t('labels.items') }) }}
</p>
}
</div>
@if (userService.userState$ | async; as userState) {
@if (userService.currentUser(); as currentUser) {
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
(userState.user?.permissions?.admin || userState.user?.permissions?.canManageLibrary)) {
(currentUser.permissions.admin || currentUser.permissions.canManageLibrary)) {
<div class="entity-menu-wrapper">
<p-button
icon="pi pi-ellipsis-v"
@@ -39,7 +39,7 @@
severity="info"
(click)="entitymenu.toggle($event)">
</p-button>
<p-menu #entitymenu [model]="entityOptions" [popup]="true" appendTo="body"></p-menu>
<p-menu #entitymenu [model]="entityOptions()" [popup]="true" appendTo="body"></p-menu>
</div>
}
}
@@ -106,7 +106,7 @@
<p-checkbox
inputId="collapse-series-checkbox"
[binary]="true"
[ngModel]="seriesCollapseFilter.isSeriesCollapsed"
[ngModel]="seriesCollapseFilter.seriesCollapsed()"
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
</p-checkbox>
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
@@ -137,15 +137,15 @@
<div class="display-settings-section">
<label class="display-settings-label">{{ t('labels.gridItemSize') }}</label>
<p-slider
[(ngModel)]="coverScalePreferenceService.scaleFactor"
[ngModel]="coverScalePreferenceService.scaleFactor()"
(ngModelChange)="coverScalePreferenceService.setScale($event)"
[min]="0.5"
[max]="1.5"
[step]="0.01"
[style]="{ width: '100%' }"
(onChange)="updateScale()">
[style]="{ width: '100%' }">
</p-slider>
<div class="scale-value-display">
{{ coverScalePreferenceService.scaleFactor.toFixed(2) }}x
{{ coverScalePreferenceService.scaleFactor().toFixed(2) }}x
</div>
</div>
}
@@ -154,7 +154,7 @@
<p-checkbox
inputId="show-book-type-pill-checkbox"
[binary]="true"
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill"
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill()"
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
</p-checkbox>
<label for="show-book-type-pill-checkbox" class="display-settings-label">{{ t('labels.bookTypeOverlay') }}</label>
@@ -253,7 +253,7 @@
<a class="topbar-items topbar-item" (click)="toggleSidebar()">
<i
[ngClass]="showFilter ? 'pi pi-angle-double-right' : 'pi pi-angle-double-left'"
[ngClass]="showFilter() ? 'pi pi-angle-double-right' : 'pi pi-angle-double-left'"
[pTooltip]="t('tooltip.toggleSidebar')"
tooltipPosition="top">
</i>
@@ -261,78 +261,75 @@
</div>
</div>
@if (bookState$ | async; as bookState) {
@if (books(); as books) {
<div>
@if (!bookState?.loaded && !bookState?.error) {
@if (isBooksLoading()) {
<div>
<p-progressSpinner></p-progressSpinner>
</div>
}
<div class="book-state-wrapper">
@if (bookState?.error) {
@if (booksError()) {
<div class="no-books-container">
<p class="no-books-text">
{{ entityType === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
</p>
</div>
}
@if (!bookState?.error && bookState?.loaded && bookState?.books?.length === 0) {
} @else if (!isBooksLoading() && books.length === 0) {
<div class="no-books-container">
<p class="no-books-text">
{{ t('labels.noBooks') }}
</p>
</div>
}
@if (bookState?.books; as books) {
@if (currentViewMode === 'table' && books.length > 0) {
<app-book-table
[books]="books"
[preselectedBookIds]="selectedBooks"
(selectedBooksChange)="onSelectedBooksChange($event)"
[sortOption]="this.bookSorter.selectedSort!"
[visibleColumns]="visibleColumns"
></app-book-table>
}
@if (currentViewMode === 'grid') {
<virtual-scroller class="virtual-scroller" #scroll [items]="books">
<div
class="grid"
#container
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
@for (book of scroll.viewPortItems; let i = $index; track book.id) {
<div
class="virtual-scroller-item"
[ngStyle]="{width: currentCardSize.width + 'px', height: getCardHeight(book) + 'px'}">
<app-book-card
[index]="books.indexOf(book)"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled"
[onBookSelect]="handleBookSelect.bind(this)"
[isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="selectedBooks.has(book.id)"
[useSquareCovers]="isAudiobookOnlyLibrary"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
}
</div>
</virtual-scroller>
}
@if (currentViewMode === 'table' && books.length > 0) {
<app-book-table
[books]="books"
[preselectedBookIds]="selectedBooks()"
(selectedBooksChange)="onSelectedBooksChange($event)"
[sortOption]="this.bookSorter.selectedSort!"
[visibleColumns]="visibleColumns"
></app-book-table>
}
@if (userService.userState$ | async; as userState) {
<div class="book-browser-footer" [class.footer-hidden]="selectedCount === 0">
@if (currentViewMode === 'grid') {
<virtual-scroller class="virtual-scroller" #scroll [items]="books">
<div
class="grid"
#container
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
@for (book of scroll.viewPortItems; let i = $index; track book.id) {
<div
class="virtual-scroller-item"
[ngStyle]="{width: currentCardSize.width + 'px', height: getCardHeight(book) + 'px'}">
<app-book-card
[index]="books.indexOf(book)"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled"
[onBookSelect]="handleBookSelect.bind(this)"
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="selectedBooks().has(book.id)"
[useSquareCovers]="isAudiobookOnlyLibrary"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
}
</div>
</virtual-scroller>
}
@if (userService.currentUser(); as currentUser) {
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
<div class="footer-content">
<div class="footer-left">
<div class="selected-count-badge">
<i class="pi pi-check-circle"></i>
<span class="selected-count">{{ selectedCount }}</span>
<span class="selected-count">{{ selectedCount() }}</span>
<span class="selected-label">{{ t('labels.selected') }}</span>
</div>
</div>
<div class="footer-center">
@if (entityType$ | async; as entityType) {
@if (entityType(); as entityType) {
<div class="action-buttons-group">
@if (hasMetadataMenuItems) {
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
@@ -363,7 +360,7 @@
tooltipPosition="top">
</p-button>
}
@if (userState.user?.permissions?.canBulkLockUnlockMetadata) {
@if (currentUser.permissions.canBulkLockUnlockMetadata) {
<p-button
outlined="true"
icon="pi pi-lock"
@@ -373,7 +370,7 @@
tooltipPosition="top">
</p-button>
}
@if (userState.user?.permissions?.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
@if (currentUser.permissions.canMoveOrganizeFiles && appSettingsService.appSettings()?.diskType === 'LOCAL') {
<p-button
outlined="true"
icon="pi pi-arrows-h"
@@ -383,7 +380,7 @@
tooltipPosition="top">
</p-button>
}
@if (userState.user?.permissions?.canManageLibrary || userState.user?.permissions?.admin) {
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
<p-button
outlined="true"
icon="pi pi-link"
@@ -428,7 +425,7 @@
tooltipPosition="top">
</p-button>
</div>
@if (userState?.user?.permissions?.admin || userState?.user?.permissions?.canDeleteBook) {
@if (currentUser?.permissions?.admin || currentUser?.permissions?.canDeleteBook) {
<p-divider layout="vertical"></p-divider>
<p-button
outlined="true"
@@ -449,17 +446,17 @@
}
</div>
@if (this.showFilter) {
@if (showFilter()) {
<div
class="mobile-filter-mask"
(click)="toggleSidebar()">
</div>
<app-book-filter
[showFilter]="showFilter"
[showFilter]="showFilter()"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter }"
[entity$]="entity$"
[entityType$]="entityType$"
[ngClass]="{ 'active': showFilter() }"
[entity]="entity()"
[entityType]="entityType()"
[resetFilter$]="resetFilterSubject"
(filterSelected)="onFilterSelected($event)"
(filterModeChanged)="onFilterModeChanged($event)">
@@ -1,22 +1,21 @@
import {AfterViewInit, ChangeDetectorRef, Component, HostListener, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {AfterViewInit, Component, HostListener, computed, effect, inject, OnDestroy, OnInit, signal, ViewChild} from '@angular/core';
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
import {PageTitleService} from '../../../../shared/service/page-title.service';
import {BookService} from '../../service/book.service';
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
import {debounceTime, filter, map, switchMap, takeUntil} from 'rxjs/operators';
import {BehaviorSubject, combineLatest, finalize, Observable, of, Subject, Subscription} from 'rxjs';
import {debounceTime, distinctUntilChanged, filter, map, takeUntil} from 'rxjs/operators';
import {combineLatest, finalize, Subject} from 'rxjs';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
import {Shelf} from '../../model/shelf.model';
import {SortDirection, SortOption} from '../../model/sort.model';
import {BookState} from '../../model/state/book-state.model';
import {Book} from '../../model/book.model';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {BookTableComponent} from './book-table/book-table.component';
import {animate, style, transition, trigger} from '@angular/animations';
import {Button} from 'primeng/button';
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {NgClass, NgStyle} from '@angular/common';
import {VirtualScrollerComponent, VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
import {BookCardComponent} from './book-card/book-card.component';
import {ProgressSpinner} from 'primeng/progressspinner';
@@ -27,8 +26,6 @@ import {BookFilterComponent} from './book-filter/book-filter.component';
import {Tooltip} from 'primeng/tooltip';
import {BookFilterMode, DEFAULT_VISIBLE_SORT_FIELDS, EntityViewPreferences, SortCriterion, UserService} from '../../../settings/user-management/user.service';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {SideBarFilter} from './filters/sidebar-filter';
import {HeaderFilter} from './filters/HeaderFilter';
import {CoverScalePreferenceService} from './cover-scale-preference.service';
import {BookSorter} from './sorting/BookSorter';
import {BookDialogHelperService} from './book-dialog-helper.service';
@@ -41,7 +38,6 @@ import {TableColumnPreferenceService} from './table-column-preference.service';
import {TieredMenu} from 'primeng/tieredmenu';
import {BadgeModule} from 'primeng/badge';
import {BookMenuService} from '../../service/book-menu.service';
import {MagicShelf} from '../../../magic-shelf/service/magic-shelf.service';
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service';
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
@@ -57,7 +53,6 @@ import {BookFilterOrchestrationService} from './book-filter-orchestration.servic
import {BookBrowserScrollService} from './book-browser-scroll.service';
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
import {MultiSortPopoverComponent} from './sorting/multi-sort-popover/multi-sort-popover.component';
import {SortService} from '../../service/sort.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
export enum EntityType {
@@ -74,7 +69,7 @@ export enum EntityType {
templateUrl: './book-browser.component.html',
styleUrls: ['./book-browser.component.scss'],
imports: [
Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule,
Button, VirtualScrollerModule, BookCardComponent, ProgressSpinner, Menu, InputText, FormsModule,
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
Checkbox, Slider, Divider, MultiSelect, TieredMenu, BadgeModule, MultiSortPopoverComponent, TranslocoDirective
],
@@ -105,7 +100,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
protected bookSelectionService = inject(BookSelectionService);
protected appSettingsService = inject(AppSettingsService);
private cdr = inject(ChangeDetectorRef);
private activatedRoute = inject(ActivatedRoute);
private router = inject(Router);
private messageService = inject(MessageService);
@@ -124,35 +118,98 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private scrollService = inject(BookBrowserScrollService);
private readonly t = inject(TranslocoService);
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
entityType$: Observable<EntityType> | undefined;
private entityRouteInfo$!: Observable<EntityInfo>;
searchTerm$ = new BehaviorSubject<string>('');
selectedFilter = new BehaviorSubject<Record<string, string[]> | null>(null);
selectedFilterMode = new BehaviorSubject<BookFilterMode>('and');
private readonly defaultSortCriteria: SortOption[] = [{
field: 'addedOn',
direction: SortDirection.DESCENDING,
label: 'Added On'
}];
private readonly routePath = toSignal(
this.activatedRoute.url.pipe(
map(() => this.activatedRoute.snapshot.routeConfig?.path ?? '')
),
{initialValue: this.activatedRoute.snapshot.routeConfig?.path ?? ''}
);
private readonly routeParamMap = toSignal(this.activatedRoute.paramMap, {
initialValue: this.activatedRoute.snapshot.paramMap
});
private readonly queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap
});
private readonly searchTerm = signal('');
private readonly debouncedSearchTerm = toSignal(
toObservable(this.searchTerm).pipe(
debounceTime(500),
distinctUntilChanged()
),
{initialValue: this.searchTerm()}
);
private readonly selectedFilter = signal<Record<string, string[]> | null>(null);
private readonly selectedFilterMode = signal<BookFilterMode>('and');
private readonly sortCriteria = signal<SortOption[]>(this.defaultSortCriteria);
private readonly seriesCollapsed = this.seriesCollapseFilter.seriesCollapsed;
readonly selectedBooks = this.bookSelectionService.selectedBooks;
readonly selectedCount = this.bookSelectionService.selectedCount;
readonly showFilter = this.sidebarFilterTogglePrefService.showFilter;
private readonly currentUser$ = toObservable(this.userService.currentUser).pipe(filter(u => !!u));
readonly entityInfo = computed<EntityInfo>(() => {
const routePath = this.routePath();
if (routePath === 'all-books') {
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
if (routePath === 'unshelved-books') {
return {entityId: NaN, entityType: EntityType.UNSHELVED};
}
return this.entityService.getEntityInfo(this.routeParamMap());
});
readonly entityType = computed(() => this.entityInfo().entityType);
readonly entity = computed(() => {
const {entityId, entityType} = this.entityInfo();
return this.entityService.getEntity(entityId, entityType);
});
readonly entityOptions = computed<MenuItem[]>(() => {
const entity = this.entity();
if (!entity) {
return [];
}
return this.entityService.isLibrary(entity)
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
: this.entityService.isMagicShelf(entity)
? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity);
});
readonly books = computed(() => {
const {entityId, entityType} = this.entityInfo();
const books = this.entityService.getBooksByEntity(this.bookService.books(), entityId, entityType);
return this.filterOrchestrationService.applyFilters(
books,
this.debouncedSearchTerm(),
this.selectedFilter(),
this.selectedFilterMode(),
this.seriesCollapseFilter,
this.seriesCollapsed(),
this.filterOrchestrationService.shouldForceExpandSeries(this.queryParamMap()),
this.sortCriteria()
);
});
readonly isBooksLoading = this.bookService.isBooksLoading;
readonly booksError = this.bookService.booksError;
protected resetFilterSubject = new Subject<void>();
parsedFilters: Record<string, string[]> = {};
entity: Library | Shelf | MagicShelf | null = null;
entityType: EntityType | undefined;
bookTitle = '';
entityOptions: MenuItem[] | undefined;
isDrawerVisible = false;
dynamicDialogRef: DynamicDialogRef | undefined | null;
EntityType = EntityType;
currentFilterLabel: string | null = null;
rawFilterParamFromUrl: string | null = null;
hasSearchTerm = false;
visibleColumns: { field: string; header: string }[] = [];
entityViewPreferences: EntityViewPreferences | undefined;
currentViewMode: string | undefined;
lastAppliedSortCriteria: SortOption[] = [];
visibleSortOptions: SortOption[] = [];
showFilter = false;
screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024;
mobileColumnCount = 3;
selectedCount = 0;
private readonly MOBILE_BREAKPOINT = 768;
private readonly CARD_ASPECT_RATIO = 7 / 5;
@@ -166,15 +223,60 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
protected metadataMenuItems: MenuItem[] | undefined;
protected moreActionsMenuItems: MenuItem[] | undefined;
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
private headerFilter = new HeaderFilter(this.searchTerm$);
protected bookSorter = new BookSorter(
sortCriteria => this.onMultiSortChange(sortCriteria),
this.t
);
private sortService = inject(SortService);
private readonly syncBrowserStateEffect = effect(() => {
const entityType = this.entityType();
const entity = this.entity();
private bookStateSubscription: Subscription | undefined;
if (entityType === EntityType.ALL_BOOKS) {
this.pageTitle.setPageTitle(this.t.translate('book.browser.labels.allBooks'));
this.seriesCollapseFilter.setContext(null, null);
return;
}
if (entityType === EntityType.UNSHELVED) {
this.pageTitle.setPageTitle(this.t.translate('book.browser.labels.unshelvedBooks'));
this.seriesCollapseFilter.setContext(null, null);
return;
}
if (entity) {
this.pageTitle.setPageTitle(entity.name);
}
if (!entity) {
this.seriesCollapseFilter.setContext(null, null);
return;
}
switch (entityType) {
case EntityType.LIBRARY:
this.seriesCollapseFilter.setContext('LIBRARY', entity.id ?? 0);
break;
case EntityType.SHELF:
this.seriesCollapseFilter.setContext('SHELF', entity.id ?? 0);
break;
case EntityType.MAGIC_SHELF:
this.seriesCollapseFilter.setContext('MAGIC_SHELF', entity.id ?? 0);
break;
default:
this.seriesCollapseFilter.setContext(null, null);
}
});
private readonly syncBooksEffect = effect(() => {
const books = this.books();
this.bookSelectionService.setCurrentBooks(books);
this.bookNavigationService.setAvailableBookIds(books.map(book => book.id));
});
private readonly syncMoreActionsMenuEffect = effect(() => {
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(
this.selectedBooks(),
this.userService.currentUser()
);
});
@ViewChild(BookTableComponent)
bookTableComponent!: BookTableComponent;
@@ -202,15 +304,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
return {width: cardWidth, height: cardHeight};
}
get selectedBooks(): Set<number> {
return this.bookSelectionService.selectedBooks;
}
get currentCardSize() {
if (this.isMobile) {
return this.mobileCardSize;
}
const base = this.coverScalePreferenceService.currentCardSize;
const base = this.coverScalePreferenceService.currentCardSize();
if (this.isAudiobookOnlyLibrary) {
const squareSide = Math.round(base.width * 1.1);
return { width: squareSide, height: squareSide + 31 };
@@ -225,7 +323,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (this.isAudiobookOnlyLibrary) {
return `${this.currentCardSize.width}px`;
}
return this.coverScalePreferenceService.gridColumnMinWidth;
return this.coverScalePreferenceService.gridColumnMinWidth();
}
getCardHeight(_book: Book): number {
@@ -243,11 +341,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
get isFilterActive(): boolean {
return !!this.selectedFilter.value && Object.keys(this.selectedFilter.value).length > 0;
const selectedFilter = this.selectedFilter();
return !!selectedFilter && Object.keys(selectedFilter).length > 0;
}
get computedFilterLabel(): string {
const filters = this.selectedFilter.value;
const filters = this.selectedFilter();
if (!filters || Object.keys(filters).length === 0) {
return this.t.translate('book.browser.labels.allBooks');
@@ -277,8 +376,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
get isAudiobookOnlyLibrary(): boolean {
if (!this.entity || this.entityType !== EntityType.LIBRARY) return false;
const library = this.entity as Library;
const entity = this.entity();
if (!entity || this.entityType() !== EntityType.LIBRARY) return false;
const library = entity as Library;
return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK';
}
@@ -287,33 +387,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
get hasMetadataMenuItems(): boolean {
return this.metadataMenuItems!.length > 0;
return (this.metadataMenuItems?.length ?? 0) > 0;
}
get hasMoreActionsItems(): boolean {
return this.moreActionsMenuItems!.length > 0;
return (this.moreActionsMenuItems?.length ?? 0) > 0;
}
ngOnInit(): void {
this.pageTitle.setPageTitle('');
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000), takeUntil(this.destroy$)).subscribe();
this.loadMobileColumnsPreference();
this.initializeEntityRouting();
this.setupRouteChangeHandlers();
this.setupUserStateSubscription();
this.setupQueryParamSubscription();
this.setupFilterToggleSubscription();
this.setupSearchTermSubscription();
this.setupScrollPositionTracking();
this.setupSelectionSubscription();
}
ngAfterViewInit(): void {
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(this.parsedFilters);
this.bookFilterComponent.onFiltersChanged?.();
this.bookFilterComponent.selectedFilterMode = this.selectedFilterMode.getValue();
this.bookFilterComponent.selectedFilterMode = this.selectedFilterMode();
}
}
@@ -344,92 +436,50 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
}
private initializeEntityRouting(): void {
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
const entityType = currentPath === 'all-books' ? EntityType.ALL_BOOKS : EntityType.UNSHELVED;
this.entityType = entityType;
this.entityType$ = of(entityType);
this.entityRouteInfo$ = of({entityId: NaN, entityType});
this.entity$ = of(null);
this.seriesCollapseFilter.setContext(null, null);
this.pageTitle.setPageTitle(currentPath === 'all-books' ? this.t.translate('book.browser.labels.allBooks') : this.t.translate('book.browser.labels.unshelvedBooks'));
} else {
const routeEntityInfo$ = this.entityService.getEntityInfoFromRoute(this.activatedRoute);
this.entityRouteInfo$ = routeEntityInfo$;
this.entityType$ = routeEntityInfo$.pipe(map(info => {
this.entityType = info.entityType;
return info.entityType;
}));
this.entity$ = routeEntityInfo$.pipe(
switchMap(({entityId, entityType}) => this.entityService.fetchEntity(entityId, entityType))
);
this.entity$.pipe(takeUntil(this.destroy$)).subscribe(entity => this.handleEntityLoaded(entity));
}
}
private handleEntityLoaded(entity: Library | Shelf | MagicShelf | null): void {
if (entity) {
this.pageTitle.setPageTitle(entity.name);
}
this.entity = entity ?? null;
this.updateSeriesCollapseContext();
this.entityOptions = entity
? this.entityService.isLibrary(entity)
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
: this.entityService.isMagicShelf(entity)
? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
: [];
}
private setupRouteChangeHandlers(): void {
this.activatedRoute.paramMap.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.searchTerm$.next('');
this.searchTerm.set('');
this.bookTitle = '';
this.bookSelectionService.deselectAll();
this.clearFilter();
});
}
private setupUserStateSubscription(): void {
this.userService.userState$.pipe(
filter(u => !!u?.user && u.loaded),
takeUntil(this.destroy$)
).subscribe(userState => {
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
() => this.autoFetchMetadata(),
() => this.fetchMetadata(),
() => this.bulkEditMetadata(),
() => this.multiBookEditMetadata(),
() => this.regenerateCoversForSelected(),
() => this.generateCustomCoversForSelected(),
userState.user
);
});
private readonly syncMetadataMenuEffect = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
}
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
() => this.autoFetchMetadata(),
() => this.fetchMetadata(),
() => this.bulkEditMetadata(),
() => this.multiBookEditMetadata(),
() => this.regenerateCoversForSelected(),
() => this.generateCustomCoversForSelected(),
user
);
});
private setupQueryParamSubscription(): void {
combineLatest([
this.entityRouteInfo$,
this.activatedRoute.paramMap.pipe(map(() => this.entityInfo())),
this.activatedRoute.queryParamMap,
this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded))
]).pipe(takeUntil(this.destroy$)).subscribe(([entityInfo, queryParamMap, user]) => {
this.currentUser$,
]).pipe(
takeUntil(this.destroy$)
).subscribe(([entityInfo, queryParamMap, currentUser]) => {
const parseResult = this.queryParamsService.parseQueryParams(
queryParamMap,
user.user?.userSettings?.entityViewPreferences,
currentUser.userSettings?.entityViewPreferences,
entityInfo.entityType,
entityInfo.entityId,
this.bookSorter.sortOptions,
user.user?.userSettings?.filterMode ?? 'and'
currentUser.userSettings?.filterMode ?? 'and'
);
if (parseResult.filterMode !== this.selectedFilterMode.getValue()) {
this.selectedFilterMode.next(parseResult.filterMode);
if (parseResult.filterMode !== this.selectedFilterMode()) {
this.selectedFilterMode.set(parseResult.filterMode);
if (this.bookFilterComponent) {
this.bookFilterComponent.selectedFilterMode = parseResult.filterMode;
}
@@ -440,7 +490,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (filterParams) {
this.settingFiltersFromUrl = true;
this.selectedFilter.next(parseResult.filters);
this.selectedFilter.set(parseResult.filters);
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(parseResult.filters);
@@ -461,12 +511,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.parsedFilters = parseResult.filters;
this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences;
this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor);
this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference);
this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences;
this.columnPreferenceService.initPreferences(currentUser.userSettings?.tableColumnPreference);
this.visibleColumns = this.columnPreferenceService.visibleColumns;
const visibleFields = user.user?.userSettings?.visibleSortFields ?? DEFAULT_VISIBLE_SORT_FIELDS;
const visibleFields = currentUser.userSettings?.visibleSortFields ?? DEFAULT_VISIBLE_SORT_FIELDS;
const sortOptionsByField = new Map(this.bookSorter.sortOptions.map(o => [o.field, o]));
this.visibleSortOptions = visibleFields.map(f => sortOptionsByField.get(f)).filter((o): o is SortOption => !!o);
@@ -484,61 +533,42 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.queryParamsService.syncQueryParams(
this.currentViewMode!,
this.selectedFilterMode.getValue(),
this.selectedFilterMode(),
this.parsedFilters
);
});
}
private setupSearchTermSubscription(): void {
this.searchTerm$.pipe(takeUntil(this.destroy$)).subscribe(term => {
this.hasSearchTerm = !!term && term.trim().length > 0;
});
}
private setupFilterToggleSubscription(): void {
this.sidebarFilterTogglePrefService.showFilter$
.pipe(takeUntil(this.destroy$))
.subscribe(value => {
this.showFilter = value;
});
}
private setupSelectionSubscription(): void {
this.bookSelectionService.selectedBooks$
.pipe(takeUntil(this.destroy$))
.subscribe(selectedBooks => {
this.selectedCount = selectedBooks.size;
this.cdr.detectChanges();
});
}
onFilterSelected(filters: Record<string, any> | null): void {
onFilterSelected(filters: Record<string, unknown> | null): void {
if (this.settingFiltersFromUrl) return;
this.selectedFilter.next(filters);
const normalizedFilters = filters
? Object.fromEntries(
Object.entries(filters).map(([key, value]) => [
key,
(Array.isArray(value) ? value : [value]).map(filterValue => String(filterValue))
])
)
: null;
this.selectedFilter.set(normalizedFilters);
this.rawFilterParamFromUrl = null;
const hasSidebarFilters = !!filters && Object.keys(filters).length > 0;
const hasSidebarFilters = !!normalizedFilters && Object.keys(normalizedFilters).length > 0;
this.currentFilterLabel = hasSidebarFilters ? this.computedFilterLabel : this.t.translate('book.browser.labels.allBooks');
this.queryParamsService.updateFilters(filters);
this.queryParamsService.updateFilters(normalizedFilters);
}
onFilterModeChanged(mode: BookFilterMode): void {
if (this.settingFiltersFromUrl || mode === this.selectedFilterMode.getValue()) return;
if (this.settingFiltersFromUrl || mode === this.selectedFilterMode()) return;
this.selectedFilterMode.next(mode);
this.selectedFilterMode.set(mode);
this.queryParamsService.updateFilterMode(mode, this.parsedFilters);
}
toggleSidebar(): void {
this.showFilter = !this.showFilter;
this.sidebarFilterTogglePrefService.selectedShowFilter = this.showFilter;
}
updateScale(): void {
this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor);
this.sidebarFilterTogglePrefService.toggle();
}
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
@@ -550,19 +580,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
onCheckboxClicked(event: CheckboxClickEvent): void {
this.bookSelectionService.handleCheckboxClick(event);
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
}
handleBookSelect(book: Book, selected: boolean): void {
this.bookSelectionService.handleBookSelection(book, selected);
this.isDrawerVisible = this.bookSelectionService.hasSelection();
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
}
onSelectedBooksChange(selectedBookIds: Set<number>): void {
this.bookSelectionService.setSelectedBooks(selectedBookIds);
this.isDrawerVisible = this.bookSelectionService.hasSelection();
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
}
selectAllBooks(): void {
@@ -570,21 +595,19 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (this.bookTableComponent) {
this.bookTableComponent.selectAllBooks();
}
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
}
deselectAllBooks(): void {
this.bookSelectionService.deselectAll();
this.isDrawerVisible = false;
if (this.bookTableComponent) {
this.bookTableComponent.clearSelectedBooks();
}
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
}
confirmDeleteBooks(): void {
const selectedBooks = this.selectedBooks();
this.confirmationService.confirm({
message: this.t.translate('book.browser.confirm.deleteMessage', {count: this.selectedBooks.size}),
message: this.t.translate('book.browser.confirm.deleteMessage', {count: selectedBooks.size}),
header: this.t.translate('book.browser.confirm.deleteHeader'),
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
@@ -594,10 +617,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
acceptButtonStyleClass: 'p-button-danger',
rejectButtonStyleClass: 'p-button-outlined',
accept: () => {
const count = this.selectedBooks.size;
const count = selectedBooks.size;
const loader = this.loadingService.show(this.t.translate('book.browser.loading.deleting', {count}));
this.bookService.deleteBooks(this.selectedBooks)
this.bookService.deleteBooks(selectedBooks)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe(() => {
this.bookSelectionService.deselectAll();
@@ -621,54 +644,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
applySortCriteria(sortCriteria: SortOption[]): void {
// Use first criterion for API call (backend doesn't support multi-sort)
const primarySort = sortCriteria[0] ?? {field: 'addedOn', direction: 'DESCENDING', label: 'Added On'};
if (this.entityType === EntityType.ALL_BOOKS) {
this.bookState$ = this.entityService.fetchAllBooks(primarySort).pipe(
map(bookState => this.applyClientSideMultiSort(bookState, sortCriteria)),
switchMap(bookState => this.applyBookFilters(bookState))
);
} else if (this.entityType === EntityType.UNSHELVED) {
this.bookState$ = this.entityService.fetchUnshelvedBooks(primarySort).pipe(
map(bookState => this.applyClientSideMultiSort(bookState, sortCriteria)),
switchMap(bookState => this.applyBookFilters(bookState))
);
} else {
const routeParam$ = this.entityService.getEntityInfoFromRoute(this.activatedRoute);
this.bookState$ = routeParam$.pipe(
switchMap(({entityId, entityType}) =>
this.entityService.fetchBooksByEntity(entityId, entityType, primarySort)
),
map(bookState => this.applyClientSideMultiSort(bookState, sortCriteria)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
if (this.bookStateSubscription) {
this.bookStateSubscription.unsubscribe();
}
this.bookStateSubscription = this.bookState$
.pipe(
filter(state => state.loaded && !state.error),
takeUntil(this.destroy$),
map(state => state.books || [])
)
.subscribe(books => {
this.bookSelectionService.setCurrentBooks(books);
this.bookNavigationService.setAvailableBookIds(books.map(book => book.id));
});
}
private applyClientSideMultiSort(bookState: BookState, sortCriteria: SortOption[]): BookState {
if (!bookState.books || sortCriteria.length <= 1) {
return bookState;
}
return {
...bookState,
books: this.sortService.applyMultiSort(bookState.books, sortCriteria)
};
this.sortCriteria.set(sortCriteria.length > 0 ? sortCriteria : this.defaultSortCriteria);
}
// Backward compatibility wrapper
@@ -689,18 +665,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
get canSaveSort(): boolean {
return this.entityType === EntityType.LIBRARY ||
this.entityType === EntityType.SHELF ||
this.entityType === EntityType.MAGIC_SHELF ||
this.entityType === EntityType.ALL_BOOKS ||
this.entityType === EntityType.UNSHELVED;
const entityType = this.entityType();
return entityType === EntityType.LIBRARY ||
entityType === EntityType.SHELF ||
entityType === EntityType.MAGIC_SHELF ||
entityType === EntityType.ALL_BOOKS ||
entityType === EntityType.UNSHELVED;
}
get hasSearchTerm(): boolean {
return this.searchTerm().trim().length > 0;
}
onSaveSortConfig(criteria: SortOption[]): void {
if (!this.entityType) return;
const entityType = this.entityType();
if (!entityType) return;
const user = this.userService.getCurrentUser();
if (!user) return;
const entity = this.entity();
const sortCriteria: SortCriterion[] = criteria.map(c => ({
field: c.field,
@@ -711,7 +694,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
user.userSettings.entityViewPreferences ?? {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 1.0, seriesCollapsed: false, overlayBookType: true}, overrides: []}
);
if (this.entityType === EntityType.ALL_BOOKS || this.entityType === EntityType.UNSHELVED) {
if (entityType === EntityType.ALL_BOOKS || entityType === EntityType.UNSHELVED) {
prefs.global = {
...prefs.global,
sortKey: sortCriteria[0]?.field ?? 'title',
@@ -719,11 +702,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
sortCriteria
};
} else {
if (!this.entity) return;
if (!entity) return;
if (!prefs.overrides) prefs.overrides = [];
let overrideEntityType: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF';
switch (this.entityType) {
switch (entityType) {
case EntityType.LIBRARY: overrideEntityType = 'LIBRARY'; break;
case EntityType.SHELF: overrideEntityType = 'SHELF'; break;
case EntityType.MAGIC_SHELF: overrideEntityType = 'MAGIC_SHELF'; break;
@@ -731,7 +714,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
const existingIndex = prefs.overrides.findIndex(
o => o.entityType === overrideEntityType && o.entityId === this.entity!.id
o => o.entityType === overrideEntityType && o.entityId === entity.id
);
if (existingIndex >= 0) {
@@ -744,7 +727,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
} else {
prefs.overrides.push({
entityType: overrideEntityType,
entityId: this.entity!.id!,
entityId: entity.id!,
preferences: {
sortKey: sortCriteria[0]?.field ?? 'title',
sortDir: sortCriteria[0]?.direction ?? 'ASC',
@@ -762,9 +745,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.browser.toast.sortSavedSummary'),
detail: this.entityType === EntityType.ALL_BOOKS || this.entityType === EntityType.UNSHELVED
detail: entityType === EntityType.ALL_BOOKS || entityType === EntityType.UNSHELVED
? this.t.translate('book.browser.toast.sortSavedGlobalDetail')
: this.t.translate('book.browser.toast.sortSavedEntityDetail', {entityType: this.entityType.toLowerCase()})
: this.t.translate('book.browser.toast.sortSavedEntityDetail', {entityType: entityType.toLowerCase()})
});
}
@@ -773,7 +756,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
onSearchTermChange(term: string): void {
this.searchTerm$.next(term);
this.searchTerm.set(term);
}
clearSearch(): void {
@@ -787,8 +770,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
clearFilter(): void {
if (this.selectedFilter.value !== null) {
this.selectedFilter.next(null);
if (this.selectedFilter() !== null) {
this.selectedFilter.set(null);
}
this.clearSearch();
}
@@ -799,11 +782,13 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
unshelfBooks(): void {
if (!this.entity) return;
const count = this.selectedBooks.size;
const entity = this.entity();
if (!entity) return;
const selectedBooks = this.selectedBooks();
const count = selectedBooks.size;
const loader = this.loadingService.show(this.t.translate('book.browser.loading.unshelving', {count}));
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id!]))
this.bookService.updateBookShelves(selectedBooks, new Set(), new Set([entity.id!]))
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
next: () => {
@@ -817,7 +802,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
openShelfAssigner(): void {
this.dynamicDialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks);
this.dynamicDialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(result => {
if (result.assigned) {
@@ -828,7 +813,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
lockUnlockMetadata(): void {
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks);
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(() => {
this.bookSelectionService.deselectAll();
@@ -837,19 +822,20 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
autoFetchMetadata(): void {
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
const selectedBooks = this.selectedBooks();
if (selectedBooks.size === 0) return;
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.BOOKS,
bookIds: Array.from(this.selectedBooks),
bookIds: Array.from(selectedBooks),
}).subscribe();
}
fetchMetadata(): void {
this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks);
this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks());
}
bulkEditMetadata(): void {
this.dynamicDialogRef = this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks);
this.dynamicDialogRef = this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(() => {
this.bookSelectionService.deselectAll();
@@ -858,7 +844,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
multiBookEditMetadata(): void {
this.dynamicDialogRef = this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks);
this.dynamicDialogRef = this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(() => {
this.bookSelectionService.deselectAll();
@@ -867,8 +853,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
regenerateCoversForSelected(): void {
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
const count = this.selectedBooks.size;
const selectedBooks = this.selectedBooks();
if (selectedBooks.size === 0) return;
const count = selectedBooks.size;
this.confirmationService.confirm({
message: this.t.translate('book.browser.confirm.regenCoverMessage', {count}),
header: this.t.translate('book.browser.confirm.regenCoverHeader'),
@@ -884,7 +871,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
severity: 'secondary'
},
accept: () => {
this.bookMetadataManageService.regenerateCoversForBooks(Array.from(this.selectedBooks)).subscribe({
this.bookMetadataManageService.regenerateCoversForBooks(Array.from(selectedBooks)).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
@@ -907,8 +894,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
generateCustomCoversForSelected(): void {
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
const count = this.selectedBooks.size;
const selectedBooks = this.selectedBooks();
if (selectedBooks.size === 0) return;
const count = selectedBooks.size;
this.confirmationService.confirm({
message: this.t.translate('book.browser.confirm.customCoverMessage', {count}),
header: this.t.translate('book.browser.confirm.customCoverHeader'),
@@ -924,7 +912,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
severity: 'secondary'
},
accept: () => {
this.bookMetadataManageService.generateCustomCoversForBooks(Array.from(this.selectedBooks)).subscribe({
this.bookMetadataManageService.generateCustomCoversForBooks(Array.from(selectedBooks)).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
@@ -947,13 +935,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
moveFiles(): void {
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
this.dialogHelperService.openFileMoverDialog(this.selectedBooks());
}
attachFilesToBook(): void {
const currentState = this.bookService.getCurrentBookState();
const selectedBookIds = Array.from(this.selectedBooks);
const sourceBooks = (currentState.books || []).filter(book =>
const selectedBookIds = Array.from(this.selectedBooks());
const sourceBooks = this.bookService.books().filter(book =>
selectedBookIds.includes(book.id)
);
@@ -988,11 +975,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
canAttachFiles(): boolean {
if (this.selectedBooks.size === 0) return false;
const selectedBookIds = Array.from(this.selectedBooks());
if (selectedBookIds.length === 0) return false;
const currentState = this.bookService.getCurrentBookState();
const selectedBookIds = Array.from(this.selectedBooks);
const selectedBooks = (currentState.books || []).filter(book =>
const selectedBooks = this.bookService.books().filter(book =>
selectedBookIds.includes(book.id)
);
@@ -1002,56 +988,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
return libraryIds.size === 1;
}
user() {
return this.userService.getCurrentUser();
}
private updateSeriesCollapseContext(): void {
let type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF' | null = null;
let id: number | null = null;
if (this.entity && this.entityType) {
switch (this.entityType) {
case EntityType.LIBRARY:
type = 'LIBRARY';
id = this.entity.id ?? 0;
break;
case EntityType.SHELF:
type = 'SHELF';
id = this.entity.id ?? 0;
break;
case EntityType.MAGIC_SHELF:
type = 'MAGIC_SHELF';
id = this.entity.id ?? 0;
break;
}
}
this.seriesCollapseFilter.setContext(type, id);
}
private applyBookFilters(bookState: BookState): Observable<BookState> {
const forceExpandSeries = this.filterOrchestrationService.shouldForceExpandSeries(
this.activatedRoute.snapshot.queryParamMap
);
// Use first sort criterion for series collapse filter
const primarySort: SortOption = this.bookSorter.selectedSort ?? {
field: 'addedOn',
direction: SortDirection.DESCENDING,
label: 'Added On'
};
return this.filterOrchestrationService.applyFilters(
bookState,
this.headerFilter,
this.sideBarFilter,
this.seriesCollapseFilter,
forceExpandSeries,
primarySort
);
}
setMobileColumns(columns: number): void {
this.mobileColumnCount = columns;
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
@@ -1,47 +1,32 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, Subject} from 'rxjs';
import {debounceTime, filter, takeUntil} from 'rxjs/operators';
import {effect, inject, Injectable, signal} from '@angular/core';
import {UserService} from '../../../settings/user-management/user.service';
@Injectable({
providedIn: 'root'
})
export class BookCardOverlayPreferenceService {
private static readonly PERSIST_DELAY_MS = 500;
private readonly userService = inject(UserService);
private readonly _showBookTypePill = new BehaviorSubject<boolean>(true);
readonly showBookTypePill$ = this._showBookTypePill.asObservable();
private readonly _showBookTypePill = signal(true);
readonly showBookTypePill = this._showBookTypePill.asReadonly();
private destroy$ = new Subject<void>();
private hasUserToggled = false;
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
constructor() {
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
)
.subscribe(() => {
effect(() => {
const user = this.userService.currentUser();
if (user) {
this.loadPreferencesFromUser();
});
this.showBookTypePill$
.pipe(debounceTime(500))
.subscribe(show => {
if (this.hasUserToggled) {
this.persistPreference(show);
}
});
}
});
}
setShowBookTypePill(show: boolean): void {
this.hasUserToggled = true;
this._showBookTypePill.next(show);
}
get showBookTypePill(): boolean {
return this._showBookTypePill.value;
this._showBookTypePill.set(show);
this.schedulePersist(show);
}
private loadPreferencesFromUser(): void {
@@ -68,12 +53,21 @@ export class BookCardOverlayPreferenceService {
}
}
this.hasUserToggled = false;
if (this._showBookTypePill.value !== show) {
this._showBookTypePill.next(show);
if (this._showBookTypePill() !== show) {
this._showBookTypePill.set(show);
}
}
private schedulePersist(show: boolean): void {
if (this.persistTimeout) {
clearTimeout(this.persistTimeout);
}
this.persistTimeout = setTimeout(() => {
this.persistPreference(show);
}, BookCardOverlayPreferenceService.PERSIST_DELAY_MS);
}
private persistPreference(show: boolean): void {
const user = this.userService.getCurrentUser();
if (!user) return;
@@ -118,9 +112,4 @@ export class BookCardOverlayPreferenceService {
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -14,7 +14,7 @@
(load)="onImageLoad()"/>
<div class="top-left-overlay-stack">
@if (showBookTypePill && getDisplayFormat(); as displayFormat) {
@if ((overlayPreferenceService?.showBookTypePill() ?? true) && getDisplayFormat(); as displayFormat) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + displayFormat.toLowerCase()">
{{ displayFormat }}
</div>
@@ -1,4 +1,4 @@
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
import {TooltipModule} from "primeng/tooltip";
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
import {Button} from 'primeng/button';
@@ -13,13 +13,11 @@ import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-r
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {NgClass} from '@angular/common';
import {User, UserService} from '../../../../settings/user-management/user.service';
import {filter, Subject, Subscription} from 'rxjs';
import {EmailService} from '../../../../settings/email-v2/email.service';
import {TieredMenu} from 'primeng/tieredmenu';
import {Router} from '@angular/router';
import {RouterLink} from '@angular/router';
import {ProgressBar} from 'primeng/progressbar';
import {take, takeUntil} from 'rxjs/operators';
import {readStatusLabels} from '../book-filter/book-filter.config';
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
@@ -29,6 +27,7 @@ import {BookNavigationService} from '../../../service/book-navigation.service';
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {QueryClient} from '@tanstack/angular-query-experimental';
@Component({
selector: 'app-book-card',
@@ -38,7 +37,7 @@ import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
export class BookCardComponent implements OnInit, OnChanges {
@Output() checkboxClick = new EventEmitter<{ index: number; book: Book; selected: boolean; shiftKey: boolean }>();
@Output() menuToggled = new EventEmitter<boolean>();
@@ -78,6 +77,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
private cdr = inject(ChangeDetectorRef);
private appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
private queryClient = inject(QueryClient);
protected _progressPercentage: number | null = null;
protected _koProgressPercentage: number | null = null;
@@ -98,45 +98,24 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
protected _readButtonIcon: string = 'pi pi-book';
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
private destroy$ = new Subject<void>();
protected readStatusHelper = inject(ReadStatusHelper);
private user: User | null = null;
private diskType: string = 'LOCAL';
private menuInitialized = false;
showBookTypePill = true;
private overlayPrefSub?: Subscription;
ngOnInit(): void {
this.computeAllMemoizedValues();
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
take(1),
takeUntil(this.destroy$)
)
.subscribe(userState => {
this.user = userState.user;
this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route';
});
this.appSettingsService.appSettings$
.pipe(
filter(settings => !!settings),
take(1),
takeUntil(this.destroy$)
)
.subscribe(settings => {
this.diskType = settings?.diskType ?? 'LOCAL';
});
if (this.overlayPreferenceService) {
this.overlayPrefSub = this.overlayPreferenceService.showBookTypePill$.subscribe(val => {
this.showBookTypePill = val;
this.cdr.markForCheck();
});
const currentUser = this.userService.currentUser();
if (currentUser) {
this.user = currentUser;
this.metadataCenterViewMode = currentUser.userSettings?.metadataCenterViewMode ?? 'route';
}
const settings = this.appSettingsService.appSettings();
if (settings) {
this.diskType = settings.diskType ?? 'LOCAL';
}
}
ngOnChanges(changes: SimpleChanges): void {
@@ -321,19 +300,25 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) {
this.isSubMenuLoading = true;
this.cdr.markForCheck();
this.bookService.getBookByIdFromAPI(this.book.id, true).subscribe({
next: (book) => {
const requestedBookId = this.book.id;
void this.queryClient.fetchQuery(this.bookService.bookDetailQueryOptions(requestedBookId, true))
.then((book) => {
if (this.book.id !== requestedBookId) {
return;
}
this.book = book;
this.additionalFilesLoaded = true;
this.isSubMenuLoading = false;
this.initMenu();
this.cdr.markForCheck();
},
error: () => {
})
.catch(() => {
if (this.book.id !== requestedBookId) {
return;
}
this.isSubMenuLoading = false;
this.cdr.markForCheck();
}
});
});
}
}
@@ -689,7 +674,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
}
openBookInfo(book: Book): void {
const allBookIds = this.bookNavigationService.getAvailableBookIds();
const allBookIds = this.bookNavigationService.availableBookIds();
if (allBookIds.length > 0) {
this.bookNavigationService.setNavigationContext(allBookIds, book.id);
}
@@ -941,12 +926,4 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
toggleSelection(event: CheckboxChangeEvent): void {
this.toggleCardSelection(event.checked);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
if (this.overlayPrefSub) {
this.overlayPrefSub.unsubscribe();
}
}
}
@@ -1,43 +1,36 @@
import {inject, Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {map, switchMap} from 'rxjs/operators';
import {BookState} from '../../model/state/book-state.model';
import {ParamMap} from '@angular/router';
import {Book} from '../../model/book.model';
import {SortOption} from '../../model/sort.model';
import {SortService} from '../../service/sort.service';
import {HeaderFilter} from './filters/HeaderFilter';
import {SideBarFilter} from './filters/sidebar-filter';
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
import {filterBooksByFilters} from './filters/sidebar-filter';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {ParamMap} from '@angular/router';
import {QUERY_PARAMS} from './book-browser-query-params.service';
import {BookFilterMode} from '../../../settings/user-management/user.service';
@Injectable({providedIn: 'root'})
export class BookFilterOrchestrationService {
private sortService = inject(SortService);
applyFilters(
bookState: BookState,
headerFilter: HeaderFilter,
sideBarFilter: SideBarFilter,
books: Book[],
searchTerm: string,
activeFilters: Record<string, unknown[]> | null,
filterMode: BookFilterMode,
seriesCollapseFilter: SeriesCollapseFilter,
isSeriesCollapsed: boolean,
forceExpandSeries: boolean,
sortOption: SortOption
): Observable<BookState> {
return headerFilter.filter(bookState).pipe(
switchMap(filtered => sideBarFilter.filter(filtered)),
switchMap(filtered => seriesCollapseFilter.filter(filtered, forceExpandSeries)),
map(filtered =>
(filtered.loaded && !filtered.error)
? ({
...filtered,
books: this.sortService.applySort(filtered.books || [], sortOption)
})
: filtered
)
);
sortCriteria: SortOption[]
): Book[] {
const searchedBooks = filterBooksBySearchTerm(books, searchTerm);
const filteredBooks = filterBooksByFilters(searchedBooks, activeFilters, filterMode);
const collapsedBooks = seriesCollapseFilter.collapseBooks(filteredBooks, forceExpandSeries, isSeriesCollapsed);
return this.sortService.applyMultiSort(collapsedBooks, sortCriteria);
}
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
return (!!filterParam && filterParam.split(',').some(pair => pair.trim().startsWith('series:')));
return !!filterParam && filterParam.split(',').some(pair => pair.trim().startsWith('series:'));
}
}
@@ -16,7 +16,7 @@
<div class="filter-content">
<p-accordion [value]="expandedPanels" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
@for (filterType of visibleFilterTypes; track trackByFilterType(i, filterType); let i = $index) {
@if (filterStreams[filterType] | async; as filters) {
@if (filterSignals[filterType](); as filters) {
@if (filters.length > 0) {
<p-accordion-panel [value]="i">
<p-accordion-header>
@@ -1,11 +1,11 @@
import {ChangeDetectionStrategy, Component, EventEmitter, inject, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {BehaviorSubject, Observable, of, Subject, takeUntil} from 'rxjs';
import {ChangeDetectionStrategy, Component, effect, EventEmitter, inject, Input, OnDestroy, OnInit, Output, Signal, signal} from '@angular/core';
import {Subject, takeUntil} from 'rxjs';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {EntityType} from '../book-browser.component';
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
import {CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
import {AsyncPipe, NgClass} from '@angular/common';
import {NgClass} from '@angular/common';
import {Badge} from 'primeng/badge';
import {FormsModule} from '@angular/forms';
import {SelectButton} from 'primeng/selectbutton';
@@ -13,10 +13,12 @@ import {BookFilterMode, DEFAULT_VISIBLE_FILTERS, UserService, VisibleFilterType}
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
import {BookFilterService} from './book-filter.service';
import {filter} from 'rxjs/operators';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
type FilterModeOption = { label: string; value: BookFilterMode };
interface FilterModeOption {
label: string;
value: BookFilterMode;
}
@Component({
selector: 'app-book-filter',
@@ -27,13 +29,17 @@ type FilterModeOption = { label: string; value: BookFilterMode };
imports: [
Accordion, AccordionPanel, AccordionHeader, AccordionContent,
CdkVirtualScrollViewport, CdkFixedSizeVirtualScroll, CdkVirtualForOf,
NgClass, Badge, AsyncPipe, FormsModule, SelectButton,
NgClass, Badge, FormsModule, SelectButton,
TranslocoDirective
]
})
export class BookFilterComponent implements OnInit, OnDestroy {
@Input() entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
@Input() entityType$: Observable<EntityType> | undefined;
@Input() set entity(value: Library | Shelf | MagicShelf | null | undefined) {
this.entitySignal.set(value ?? null);
}
@Input() set entityType(value: EntityType | undefined) {
this.entityTypeSignal.set(value ?? EntityType.ALL_BOOKS);
}
@Input() resetFilter$!: Subject<void>;
@Input() showFilter = false;
@@ -45,12 +51,19 @@ export class BookFilterComponent implements OnInit, OnDestroy {
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
private readonly activeFilters$ = new BehaviorSubject<Record<string, unknown[]> | null>(null);
private readonly filterMode$ = new BehaviorSubject<BookFilterMode>('and');
private readonly entitySignal = signal<Library | Shelf | MagicShelf | null>(null);
private readonly entityTypeSignal = signal<EntityType>(EntityType.ALL_BOOKS);
private readonly activeFiltersSignal = signal<Record<string, unknown[]> | null>(null);
private readonly filterModeSignal = signal<BookFilterMode>('and');
activeFilters: Record<string, unknown[]> = {};
filterStreams: Record<FilterType, Observable<Filter[]>> = {} as Record<FilterType, Observable<Filter[]>>;
filterTypes: FilterType[] = [];
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
this.entitySignal,
this.entityTypeSignal,
this.activeFiltersSignal,
this.filterModeSignal
);
filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
visibleFilterTypes: FilterType[] = [];
expandedPanels: number[] = [0];
truncatedFilters: Record<string, boolean> = {};
@@ -78,14 +91,15 @@ export class BookFilterComponent implements OnInit, OnDestroy {
set selectedFilterMode(mode: BookFilterMode) {
if (mode === this._selectedFilterMode) return;
this._selectedFilterMode = mode;
this.filterMode$.next(mode);
this.filterModeSignal.set(mode);
this.filterModeChanged.emit(mode);
this.emitFilters();
}
ngOnInit(): void {
this.updateVisibleFilterTypes();
this.updateExpandedPanels();
this.subscribeToUserSettings();
this.initializeFilterStreams();
this.subscribeToReset();
}
@@ -95,9 +109,11 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
handleFilterClick(filterType: string, value: unknown): void {
this._selectedFilterMode === 'single'
? this.handleSingleMode(filterType, value)
: this.handleMultiMode(filterType, value);
if (this._selectedFilterMode === 'single') {
this.handleSingleMode(filterType, value);
} else {
this.handleMultiMode(filterType, value);
}
this.emitFilters();
}
@@ -113,7 +129,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
clearActiveFilter(): void {
this.activeFilters = {};
this.expandedPanels = [0];
this.activeFilters$.next(null);
this.activeFiltersSignal.set(null);
this.filterSelected.emit(null);
}
@@ -149,31 +165,14 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
private subscribeToUserSettings(): void {
this.userService.userState$.pipe(
filter(state => !!state?.user && state.loaded),
takeUntil(this.destroy$)
).subscribe(state => {
const settings = state.user!.userSettings;
this._visibleFilters = settings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this._visibleFilters = user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
this.updateVisibleFilterTypes();
});
}
private initializeFilterStreams(): void {
const entity$ = this.entity$ ?? of(null);
const entityType$ = this.entityType$ ?? of(EntityType.ALL_BOOKS);
this.filterStreams = this.filterService.createFilterStreams(
entity$,
entityType$,
this.activeFilters$,
this.filterMode$
);
this.filterTypes = Object.keys(this.filterStreams) as FilterType[];
this.updateVisibleFilterTypes();
this.updateExpandedPanels();
}
private updateVisibleFilterTypes(): void {
this.visibleFilterTypes = this._visibleFilters.filter(
vf => this.filterTypes.includes(vf as FilterType)
@@ -223,7 +222,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
private emitFilters(): void {
const hasFilters = Object.keys(this.activeFilters).length > 0;
const filtersToEmit = hasFilters ? {...this.activeFilters} : null;
this.activeFilters$.next(filtersToEmit);
this.activeFiltersSignal.set(filtersToEmit);
this.filterSelected.emit(filtersToEmit);
}
@@ -1,5 +1,4 @@
import {inject, Injectable} from '@angular/core';
import {combineLatest, map, Observable, of, shareReplay} from 'rxjs';
import {computed, inject, Injectable, Signal} from '@angular/core';
import {Book} from '../../../model/book.model';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
@@ -21,31 +20,57 @@ export class BookFilterService {
private readonly libraryService = inject(LibraryService);
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
createFilterStreams(
entity$: Observable<Library | Shelf | MagicShelf | null>,
entityType$: Observable<EntityType>,
activeFilters$: Observable<Record<string, unknown[]> | null> = of(null),
filterMode$: Observable<BookFilterMode> = of('and')
): Record<FilterType, Observable<Filter[]>> {
const filteredBooks$ = this.createFilteredBooksStream(entity$, entityType$);
createFilterSignals(
entity: Signal<Library | Shelf | MagicShelf | null>,
entityType: Signal<EntityType>,
activeFilters: Signal<Record<string, unknown[]> | null>,
filterMode: Signal<BookFilterMode>
): Record<FilterType, Signal<Filter[]>> {
const filteredBooks = computed(() =>
this.filterBooksByEntity(this.bookService.books(), entity(), entityType())
);
const streams = {} as Record<FilterType, Observable<Filter[]>>;
const signals = {} as Record<FilterType, Signal<Filter[]>>;
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
const filterType = type as Exclude<FilterType, 'library'>;
streams[filterType] = this.createCascadingFilterStream(
filteredBooks$,
activeFilters$,
filterMode$,
filterType,
FILTER_EXTRACTORS[filterType],
config.sortMode
);
signals[filterType] = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
});
}
streams.library = this.createCascadingLibraryFilterStream(filteredBooks$, activeFilters$, filterMode$);
signals.library = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
const libraries = this.libraryService.libraries();
return streams;
const libraryMap = new Map(
libraries
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const filterMap = new Map<number, Filter>();
for (const book of books) {
if (book.libraryId == null) continue;
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
return signals;
}
filterBooksByEntity(
@@ -59,9 +84,10 @@ export class BookFilterService {
case EntityType.LIBRARY:
return books.filter(book => book.libraryId === (entity as Library).id);
case EntityType.SHELF:
case EntityType.SHELF: {
const shelfId = (entity as Shelf).id;
return books.filter(book => book.shelves?.some(s => s.id === shelfId));
}
case EntityType.MAGIC_SHELF:
return this.filterByMagicShelf(books, entity as MagicShelf);
@@ -82,77 +108,6 @@ export class BookFilterService {
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
}
private createFilteredBooksStream(
entity$: Observable<Library | Shelf | MagicShelf | null>,
entityType$: Observable<EntityType>
): Observable<Book[]> {
return combineLatest([
this.bookService.bookState$,
entity$,
entityType$
]).pipe(
map(([state, entity, entityType]) =>
this.filterBooksByEntity(state.books || [], entity, entityType)
),
shareReplay({bufferSize: 1, refCount: true})
);
}
private createCascadingFilterStream(
books$: Observable<Book[]>,
activeFilters$: Observable<Record<string, unknown[]> | null>,
filterMode$: Observable<BookFilterMode>,
filterType: FilterType,
extractor: (book: Book) => FilterValue[],
sortMode: SortMode
): Observable<Filter[]> {
return combineLatest([books$, activeFilters$, filterMode$]).pipe(
map(([books, activeFilters, mode]) => {
const filteredBooks = filterBooksByFilters(books, activeFilters, mode, filterType);
return this.buildAndSortFilters(filteredBooks, extractor, sortMode);
}),
shareReplay({bufferSize: 1, refCount: true})
);
}
private createCascadingLibraryFilterStream(
books$: Observable<Book[]>,
activeFilters$: Observable<Record<string, unknown[]> | null>,
filterMode$: Observable<BookFilterMode>
): Observable<Filter[]> {
return combineLatest([books$, this.libraryService.libraryState$, activeFilters$, filterMode$]).pipe(
map(([books, libraryState, activeFilters, mode]) => {
const filteredBooks = filterBooksByFilters(books, activeFilters, mode, 'library');
const libraryMap = new Map(
(libraryState.libraries || [])
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const filterMap = new Map<number, Filter>();
for (const book of filteredBooks) {
if (book.libraryId == null) continue;
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
}),
shareReplay({bufferSize: 1, refCount: true})
);
}
private buildAndSortFilters(
books: Book[],
extractor: (book: Book) => FilterValue[],
@@ -1,5 +1,4 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {computed, Injectable, signal} from '@angular/core';
import {Book} from '../../model/book.model';
export interface CheckboxClickEvent {
@@ -11,46 +10,39 @@ export interface CheckboxClickEvent {
@Injectable({providedIn: 'root'})
export class BookSelectionService {
private selectedBooksSubject = new BehaviorSubject<Set<number>>(new Set());
private readonly _selectedBooks = signal<Set<number>>(new Set());
readonly selectedBooks = this._selectedBooks.asReadonly();
readonly selectedCount = computed(() => this._selectedBooks().size);
private currentBooks: Book[] = [];
private lastSelectedIndex: number | null = null;
selectedBooks$: Observable<Set<number>> = this.selectedBooksSubject.asObservable();
get selectedBooks(): Set<number> {
return this.selectedBooksSubject.value;
}
get selectedCount(): number {
return this.selectedBooksSubject.value.size;
}
setCurrentBooks(books: Book[]): void {
this.currentBooks = books;
}
getCurrentBooks(): Book[] {
return this.currentBooks;
}
selectBook(book: Book): void {
const current = new Set(this.selectedBooksSubject.value);
if (book.seriesBooks) {
book.seriesBooks.forEach(b => current.add(b.id));
} else {
current.add(book.id);
}
this.selectedBooksSubject.next(current);
this._selectedBooks.update(current => {
const next = new Set(current);
if (book.seriesBooks) {
book.seriesBooks.forEach(seriesBook => next.add(seriesBook.id));
} else {
next.add(book.id);
}
return next;
});
}
deselectBook(book: Book): void {
const current = new Set(this.selectedBooksSubject.value);
if (book.seriesBooks) {
book.seriesBooks.forEach(b => current.delete(b.id));
} else {
current.delete(book.id);
}
this.selectedBooksSubject.next(current);
this._selectedBooks.update(current => {
const next = new Set(current);
if (book.seriesBooks) {
book.seriesBooks.forEach(seriesBook => next.delete(seriesBook.id));
} else {
next.delete(book.id);
}
return next;
});
}
handleCheckboxClick(event: CheckboxClickEvent): void {
@@ -83,23 +75,21 @@ export class BookSelectionService {
selectAll(): void {
if (!this.currentBooks || this.currentBooks.length === 0) return;
const current = new Set(this.selectedBooksSubject.value);
for (const book of this.currentBooks) {
current.add(book.id);
}
this.selectedBooksSubject.next(current);
this._selectedBooks.update(current => {
const next = new Set(current);
for (const book of this.currentBooks) {
next.add(book.id);
}
return next;
});
}
deselectAll(): void {
this.selectedBooksSubject.next(new Set());
this._selectedBooks.set(new Set());
this.lastSelectedIndex = null;
}
setSelectedBooks(bookIds: Set<number>): void {
this.selectedBooksSubject.next(new Set(bookIds));
}
hasSelection(): boolean {
return this.selectedBooksSubject.value.size > 0;
this._selectedBooks.set(new Set(bookIds));
}
}
@@ -12,9 +12,8 @@ import {BookService} from '../../../service/book.service';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {MessageService} from 'primeng/api';
import {RouterLink} from '@angular/router';
import {filter, Subject} from 'rxjs';
import {Subject} from 'rxjs';
import {UserService} from '../../../../settings/user-management/user.service';
import {take, takeUntil} from 'rxjs/operators';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@@ -85,18 +84,13 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
scrollHeight = 'calc(100dvh - 160px)';
ngOnInit(): void {
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
take(1),
takeUntil(this.destroy$)
)
.subscribe(userState => {
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
});
const user = this.userService.currentUser();
if (user) {
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
}
this.selectedBookIds = this.preselectedBookIds;
this.selectedBooks = this.bookService.getBooksByIdsFromState([...this.selectedBookIds]);
this.selectedBooks = this.bookService.getBooksByIds([...this.selectedBookIds]);
this.setScrollHeight();
window.addEventListener('resize', this.setScrollHeight.bind(this));
}
@@ -1,6 +1,4 @@
import {inject, Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {computed, inject, Injectable, signal} from '@angular/core';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
@@ -21,49 +19,53 @@ export class CoverScalePreferenceService {
private readonly t = inject(TranslocoService);
private readonly localStorageService = inject(LocalStorageService);
private readonly scaleChangeSubject = new Subject<number>();
readonly scaleChange$ = this.scaleChangeSubject.asObservable();
private readonly _scaleFactor = signal(1.0);
readonly scaleFactor = this._scaleFactor.asReadonly();
scaleFactor = 1.0;
readonly currentCardSize = computed(() => ({
width: Math.round(this.BASE_WIDTH * this.scaleFactor()),
height: Math.round(this.BASE_HEIGHT * this.scaleFactor()),
}));
readonly gridColumnMinWidth = computed(() => `${this.currentCardSize().width}px`);
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
private lastPersistedScale = 1.0;
constructor() {
this.loadScaleFromStorage();
this.scaleChange$
.pipe(debounceTime(this.DEBOUNCE_MS))
.subscribe(scale => this.saveScalePreference(scale));
}
initScaleValue(scale: number | undefined): void {
this.scaleFactor = scale ?? 1.0;
const initialScale = this.loadScaleFromStorage();
this._scaleFactor.set(initialScale);
this.lastPersistedScale = initialScale;
}
setScale(scale: number): void {
this.scaleFactor = scale;
this.scaleChangeSubject.next(scale);
}
get currentCardSize(): { width: number; height: number } {
return {
width: Math.round(this.BASE_WIDTH * this.scaleFactor),
height: Math.round(this.BASE_HEIGHT * this.scaleFactor),
};
}
get gridColumnMinWidth(): string {
return `${this.currentCardSize.width}px`;
this._scaleFactor.set(scale);
if (scale === this.lastPersistedScale) {
return;
}
this.scheduleSave(scale);
}
getCardHeight(_book: Book): number {
// Use uniform height for all book types to ensure smooth virtual scrolling.
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
// cannot accurately estimate positions when item heights vary.
return this.currentCardSize.height;
return this.currentCardSize().height;
}
private scheduleSave(scale: number): void {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(() => {
this.saveScalePreference(scale);
}, this.DEBOUNCE_MS);
}
private saveScalePreference(scale: number): void {
try {
this.localStorageService.set(this.STORAGE_KEY, scale);
this.lastPersistedScale = scale;
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.coverPref.toast.savedSummary'),
@@ -80,10 +82,11 @@ export class CoverScalePreferenceService {
}
}
private loadScaleFromStorage(): void {
private loadScaleFromStorage(): number {
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
if (saved !== null && !isNaN(saved)) {
this.scaleFactor = saved;
return saved;
}
return 1.0;
}
}
@@ -1,6 +0,0 @@
import {BookState} from '../../../model/state/book-state.model';
import {Observable} from 'rxjs';
export interface BookFilter {
filter(bookState: BookState): Observable<BookState>;
}
@@ -1,61 +1,42 @@
import {BookFilter} from './BookFilter';
import {BookState} from '../../../model/state/book-state.model';
import {Observable, of} from 'rxjs';
import {map, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {Book} from '../../../model/book.model';
export class HeaderFilter implements BookFilter {
constructor(private searchTerm$: Observable<string>) {
}
filter(bookState: BookState): Observable<BookState> {
const normalize = (str: string): string => {
if (!str) return '';
// Normalize Unicode combining characters (e.g., é -> e)
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
s = s.replace(/ø/gi, 'o')
.replace(/ł/gi, 'l')
.replace(/æ/gi, 'ae')
.replace(/œ/gi, 'oe')
.replace(/ß/g, 'ss');
s = s.replace(/[!@$%^&*_=|~`<>?/";']/g, '');
s = s.replace(/\s+/g, ' ').trim();
return s.toLowerCase();
};
return this.searchTerm$.pipe(
distinctUntilChanged(),
switchMap((term: string) => {
const normalizedTerm = normalize(term || '').trim();
if (normalizedTerm.length < 2) {
return of(bookState);
}
return of(normalizedTerm).pipe(
debounceTime(500),
map(nTerm => {
const filteredBooks = bookState.books?.filter(book => {
const title = book.metadata?.title || '';
const series = book.metadata?.seriesName || '';
const authors = book.metadata?.authors || [];
const categories = book.metadata?.categories || [];
const isbn = book.metadata?.isbn10 || '';
const isbn13 = book.metadata?.isbn13 || '';
const fileName = book.primaryFile?.fileName || '';
const matchesTitle = normalize(title).includes(nTerm);
const matchesSeries = normalize(series).includes(nTerm);
const matchesAuthor = authors.some(author => normalize(author).includes(nTerm));
const matchesCategory = categories.some(category => normalize(category).includes(nTerm));
const matchesIsbn = normalize(isbn).includes(nTerm) || normalize(isbn13).includes(nTerm);
const matchesFileName = normalize(fileName).includes(nTerm);
return matchesTitle || matchesSeries || matchesAuthor || matchesCategory || matchesIsbn || matchesFileName;
}) || null;
return {...bookState, books: filteredBooks};
})
);
})
);
}
export function normalizeSearchTerm(str: string): string {
if (!str) return '';
// Normalize Unicode combining characters (e.g., é -> e)
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
s = s.replace(/ø/gi, 'o')
.replace(/ł/gi, 'l')
.replace(/æ/gi, 'ae')
.replace(/œ/gi, 'oe')
.replace(/ß/g, 'ss');
s = s.replace(/[!@$%^&*_=|~`<>?/";']/g, '');
s = s.replace(/\s+/g, ' ').trim();
return s.toLowerCase();
}
export function filterBooksBySearchTerm(books: Book[], term: string): Book[] {
const normalizedTerm = normalizeSearchTerm(term || '').trim();
if (normalizedTerm.length < 2) {
return books;
}
return books.filter(book => {
const title = book.metadata?.title || '';
const series = book.metadata?.seriesName || '';
const authors = book.metadata?.authors || [];
const categories = book.metadata?.categories || [];
const isbn = book.metadata?.isbn10 || '';
const isbn13 = book.metadata?.isbn13 || '';
const fileName = book.primaryFile?.fileName || '';
const matchesTitle = normalizeSearchTerm(title).includes(normalizedTerm);
const matchesSeries = normalizeSearchTerm(series).includes(normalizedTerm);
const matchesAuthor = authors.some(author => normalizeSearchTerm(author).includes(normalizedTerm));
const matchesCategory = categories.some(category => normalizeSearchTerm(category).includes(normalizedTerm));
const matchesIsbn = normalizeSearchTerm(isbn).includes(normalizedTerm) || normalizeSearchTerm(isbn13).includes(normalizedTerm);
const matchesFileName = normalizeSearchTerm(fileName).includes(normalizedTerm);
return matchesTitle || matchesSeries || matchesAuthor || matchesCategory || matchesIsbn || matchesFileName;
});
}
@@ -1,41 +1,27 @@
import {BookFilter} from './BookFilter';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {BookState} from '../../../model/state/book-state.model';
import {debounceTime, filter, map, takeUntil} from 'rxjs/operators';
import {effect, inject, Injectable, signal} from '@angular/core';
import {Book} from '../../../model/book.model';
import {inject, Injectable, OnDestroy} from '@angular/core';
import {MessageService} from 'primeng/api';
import {UserService} from '../../../../settings/user-management/user.service';
@Injectable({providedIn: 'root'})
export class SeriesCollapseFilter implements BookFilter, OnDestroy {
export class SeriesCollapseFilter {
private static readonly PERSIST_DELAY_MS = 500;
private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService);
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
private destroy$ = new Subject<void>();
private hasUserToggled = false;
private readonly _seriesCollapsed = signal(false);
readonly seriesCollapsed = this._seriesCollapsed.asReadonly();
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
constructor() {
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
)
.subscribe(() => {
effect(() => {
const user = this.userService.currentUser();
if (user) {
this.applyPreference();
});
this.seriesCollapse$
.pipe(debounceTime(500))
.subscribe(isCollapsed => {
if (this.hasUserToggled) {
this.persistCollapsePreference(isCollapsed);
}
});
}
});
}
setContext(type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF' | null, id: number | null): void {
@@ -47,13 +33,9 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy {
this.applyPreference();
}
get isSeriesCollapsed(): boolean {
return this.seriesCollapseSubject.value;
}
setCollapsed(value: boolean): void {
this.hasUserToggled = true;
this.seriesCollapseSubject.next(value);
this._seriesCollapsed.set(value);
this.schedulePersist(value);
}
private applyPreference(): void {
@@ -64,70 +46,74 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy {
if (prefs) {
// Backward compatibility: check for old 'seriesCollapse' field
const globalAny = prefs.global as any;
collapsed = prefs.global?.seriesCollapsed ?? globalAny?.seriesCollapse ?? false;
const legacyGlobalSeriesCollapse = (prefs.global as { seriesCollapse?: boolean }).seriesCollapse;
collapsed = prefs.global?.seriesCollapsed ?? legacyGlobalSeriesCollapse ?? false;
if (this.currentContext) {
const override = prefs.overrides?.find(o =>
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
);
if (override) {
const prefAny = override.preferences as any;
const legacyOverrideSeriesCollapse = (override.preferences as { seriesCollapse?: boolean }).seriesCollapse;
if (override.preferences.seriesCollapsed !== undefined) {
collapsed = override.preferences.seriesCollapsed;
} else if (prefAny?.seriesCollapse !== undefined) {
collapsed = prefAny.seriesCollapse;
} else if (legacyOverrideSeriesCollapse !== undefined) {
collapsed = legacyOverrideSeriesCollapse;
}
}
}
}
this.hasUserToggled = false;
if (this.seriesCollapseSubject.value !== collapsed) {
this.seriesCollapseSubject.next(collapsed);
if (this._seriesCollapsed() !== collapsed) {
this._seriesCollapsed.set(collapsed);
}
}
filter(bookState: BookState, forceExpandSeries?: boolean): Observable<BookState> {
return this.seriesCollapse$.pipe(
map(isCollapsed => {
const shouldCollapse = forceExpandSeries ? false : isCollapsed;
if (!shouldCollapse || !bookState.books) return bookState;
collapseBooks(books: Book[], forceExpandSeries?: boolean, isSeriesCollapsed: boolean = this.seriesCollapsed()): Book[] {
const shouldCollapse = forceExpandSeries ? false : isSeriesCollapsed;
if (!shouldCollapse || books.length === 0) return books;
const books = [...bookState.books];
const sourceBooks = [...books];
const seriesMap = new Map<string, Book[]>();
const collapsedBooks: Book[] = [];
const seriesMap = new Map<string, Book[]>();
const collapsedBooks: Book[] = [];
for (const book of books) {
const seriesName = book.metadata?.seriesName?.trim();
if (seriesName) {
if (!seriesMap.has(seriesName)) {
seriesMap.set(seriesName, []);
}
seriesMap.get(seriesName)!.push(book);
} else {
collapsedBooks.push(book);
}
for (const book of sourceBooks) {
const seriesName = book.metadata?.seriesName?.trim();
if (seriesName) {
if (!seriesMap.has(seriesName)) {
seriesMap.set(seriesName, []);
}
seriesMap.get(seriesName)!.push(book);
} else {
collapsedBooks.push(book);
}
}
for (const [seriesName, group] of seriesMap.entries()) {
const sortedGroup = group.slice().sort((a, b) => {
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
return aNum - bNum;
});
const firstBook = sortedGroup[0];
collapsedBooks.push({
...firstBook,
seriesBooks: group,
seriesCount: group.length
});
}
for (const group of seriesMap.values()) {
const sortedGroup = group.slice().sort((a, b) => {
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
return aNum - bNum;
});
const firstBook = sortedGroup[0];
collapsedBooks.push({
...firstBook,
seriesBooks: group,
seriesCount: group.length
});
}
return {...bookState, books: collapsedBooks};
})
);
return collapsedBooks;
}
private schedulePersist(isCollapsed: boolean): void {
if (this.persistTimeout) {
clearTimeout(this.persistTimeout);
}
this.persistTimeout = setTimeout(() => {
this.persistCollapsePreference(isCollapsed);
}, SeriesCollapseFilter.PERSIST_DELAY_MS);
}
private persistCollapsePreference(isCollapsed: boolean): void {
@@ -180,9 +166,4 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy {
life: 1500
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -1,5 +1,4 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {inject, Injectable, signal} from '@angular/core';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
@@ -14,31 +13,26 @@ export class SidebarFilterTogglePrefService {
private readonly t = inject(TranslocoService);
private readonly localStorageService = inject(LocalStorageService);
private readonly showFilterSubject = new BehaviorSubject<boolean>(true);
readonly showFilter$ = this.showFilterSubject.asObservable();
private readonly _showFilter = signal(true);
readonly showFilter = this._showFilter.asReadonly();
constructor() {
const isNarrow = window.innerWidth <= 768;
this.showFilterSubject = new BehaviorSubject<boolean>(!isNarrow);
this.showFilter$ = this.showFilterSubject.asObservable();
this._showFilter.set(!isNarrow);
this.loadFromStorage();
}
get selectedShowFilter(): boolean {
return this.showFilterSubject.value;
toggle(): void {
this.setShowFilter(!this.showFilter());
}
set selectedShowFilter(value: boolean) {
if (this.showFilterSubject.value !== value) {
this.showFilterSubject.next(value);
setShowFilter(value: boolean): void {
if (this._showFilter() !== value) {
this._showFilter.set(value);
this.savePreference(value);
}
}
toggle(): void {
this.selectedShowFilter = !this.selectedShowFilter;
}
private savePreference(value: boolean): void {
try {
this.localStorageService.set(this.STORAGE_KEY, value);
@@ -55,10 +49,10 @@ export class SidebarFilterTogglePrefService {
private loadFromStorage(): void {
const isNarrow = window.innerWidth <= 768;
if (isNarrow) {
this.showFilterSubject.next(false);
this._showFilter.set(false);
} else {
const saved = this.localStorageService.get<boolean>(this.STORAGE_KEY);
this.showFilterSubject.next(saved !== null ? saved : true);
this._showFilter.set(saved !== null ? saved : true);
}
}
}
@@ -1,7 +1,3 @@
import {combineLatest, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {BookFilter} from './BookFilter';
import {BookState} from '../../../model/state/book-state.model';
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
import {Book, ReadStatus} from '../../../model/book.model';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
@@ -95,18 +91,20 @@ export function doesBookMatchFilter(
return effectiveMode === 'or'
? filterValues.some(val => book.shelves?.some(s => s.id == val))
: filterValues.every(val => book.shelves?.some(s => s.id == val));
case 'shelfStatus':
case 'shelfStatus': {
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
return filterValues.includes(shelved);
}
case 'tag':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.tags?.includes(val as string))
: filterValues.every(val => book.metadata?.tags?.includes(val as string));
case 'publishedDate':
case 'publishedDate': {
const bookYear = book.metadata?.publishedDate
? new Date(book.metadata.publishedDate).getFullYear()
: null;
return bookYear ? filterValues.some(val => val == bookYear || val == bookYear.toString()) : false;
}
case 'fileSize':
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range as string | number));
case 'amazonRating':
@@ -118,7 +116,7 @@ export function doesBookMatchFilter(
case 'language':
return filterValues.includes(book.metadata?.language);
case 'pageCount':
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range as string | number));
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount ?? undefined, range as string | number));
case 'mood':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
@@ -194,23 +192,3 @@ export function filterBooksByFilters(
});
}
export class SideBarFilter implements BookFilter {
constructor(private selectedFilter$: Observable<unknown>, private selectedFilterMode$: Observable<BookFilterMode>) {
}
filter(bookState: BookState): Observable<BookState> {
return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe(
map(([activeFilters, mode]) => {
if (bookState.books == null) return bookState;
if (!activeFilters) return bookState;
const filteredBooks = filterBooksByFilters(
bookState.books || [],
activeFilters as Record<string, unknown[]>,
mode
);
return {...bookState, books: filteredBooks};
})
);
}
}
@@ -1,5 +1,4 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {inject, Injectable, signal} from '@angular/core';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
@@ -12,8 +11,8 @@ export class TableColumnPreferenceService {
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readonly preferencesSubject = new BehaviorSubject<TableColumnPreference[]>([]);
readonly preferences$ = this.preferencesSubject.asObservable();
private readonly _preferences = signal<TableColumnPreference[]>([]);
readonly preferences = this._preferences.asReadonly();
private readonly allAvailableFields = [
'readStatus', 'title', 'authors', 'publisher', 'seriesName', 'seriesNumber',
@@ -31,7 +30,7 @@ export class TableColumnPreferenceService {
initPreferences(savedPrefs: TableColumnPreference[] | undefined): void {
const effectivePrefs = savedPrefs?.length ? savedPrefs : this.fallbackPreferences;
this.preferencesSubject.next(this.mergeWithAllColumns(effectivePrefs));
this._preferences.set(this.mergeWithAllColumns(effectivePrefs));
}
get allColumns(): { field: string; header: string }[] {
@@ -42,7 +41,7 @@ export class TableColumnPreferenceService {
}
get visibleColumns(): { field: string; header: string }[] {
return this.preferencesSubject.value
return this.preferences()
.filter(pref => pref.visible)
.sort((a, b) => a.order - b.order)
.map(pref => ({
@@ -51,10 +50,6 @@ export class TableColumnPreferenceService {
}));
}
get preferences(): TableColumnPreference[] {
return this.preferencesSubject.value;
}
saveVisibleColumns(selectedColumns: { field: string }[]): void {
const selectedFieldSet = new Set(selectedColumns.map(c => c.field));
@@ -67,7 +62,7 @@ export class TableColumnPreferenceService {
};
});
this.preferencesSubject.next(updatedPreferences);
this._preferences.set(updatedPreferences);
const currentUser = this.userService.getCurrentUser();
if (!currentUser) return;
@@ -1,13 +1,11 @@
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {Component, computed, inject, Input} from '@angular/core';
import {Book} from '../../model/book.model';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {Button} from 'primeng/button';
import {UserService} from '../../../settings/user-management/user.service';
import {Router} from '@angular/router';
import {filter, Subject} from 'rxjs';
import {NgClass} from '@angular/common';
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
import {takeUntil} from 'rxjs/operators';
import {TooltipModule} from 'primeng/tooltip';
@Component({
@@ -20,7 +18,7 @@ import {TooltipModule} from 'primeng/tooltip';
templateUrl: './book-card-lite-component.html',
styleUrl: './book-card-lite-component.scss'
})
export class BookCardLiteComponent implements OnInit, OnDestroy {
export class BookCardLiteComponent {
@Input() book!: Book;
@Input() isActive: boolean = false;
@Input() showSeriesNumber: boolean = false;
@@ -30,9 +28,9 @@ export class BookCardLiteComponent implements OnInit, OnDestroy {
private userService = inject(UserService);
private bookMetadataHostService = inject(BookMetadataHostService);
private destroy$ = new Subject<void>();
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
private metadataCenterViewMode = computed(() =>
this.userService.currentUser()?.userSettings.metadataCenterViewMode ?? 'route'
);
isHovered: boolean = false;
isAudiobookOnly(): boolean {
@@ -48,19 +46,8 @@ export class BookCardLiteComponent implements OnInit, OnDestroy {
return this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
}
ngOnInit(): void {
this.userService.userState$
.pipe(
filter(userState => !!userState),
takeUntil(this.destroy$)
)
.subscribe((user) => {
this.metadataCenterViewMode = user?.user?.userSettings.metadataCenterViewMode ?? 'route';
});
}
openBookInfo(book: Book): void {
if (this.metadataCenterViewMode === 'route') {
if (this.metadataCenterViewMode() === 'route') {
this.router.navigate(['/book', book.id], {
queryParams: {tab: 'view'}
});
@@ -68,9 +55,4 @@ export class BookCardLiteComponent implements OnInit, OnDestroy {
this.bookMetadataHostService.requestBookSwitch(book.id);
}
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -1,11 +1,10 @@
import { Component, inject, OnInit, OnDestroy } from '@angular/core';
import { Component, computed, inject, OnInit, OnDestroy, Signal, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
import { AutoComplete, AutoCompleteSelectEvent } from 'primeng/autocomplete';
import { Button } from 'primeng/button';
import { Checkbox } from 'primeng/checkbox';
import { Subject, takeUntil } from 'rxjs';
import { filter, take } from 'rxjs/operators';
import { BookService } from '../../service/book.service';
import { BookFileService } from '../../service/book-file.service';
import { Book } from '../../model/book.model';
@@ -37,7 +36,7 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
filteredBooks: Book[] = [];
private destroy$ = new Subject<void>();
private allBooks: Book[] = [];
private allBooks: Signal<Book[]> = signal([]);
private readonly t = inject(TranslocoService);
private readonly appSettingsService = inject(AppSettingsService);
@@ -63,28 +62,22 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
return;
}
this.appSettingsService.appSettings$.pipe(
filter(settings => !!settings),
take(1),
takeUntil(this.destroy$)
).subscribe(settings => {
this.moveFiles = settings!.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
});
const settings = this.appSettingsService.appSettings();
if (settings) {
this.moveFiles = settings.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
}
// Get the library ID from first source book (all should be same library)
const libraryId = this.sourceBooks[0].libraryId;
const sourceBookIds = new Set(this.sourceBooks.map(b => b.id));
// Load all books from state and filter for same library, excluding source books
this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
take(1),
takeUntil(this.destroy$)
).subscribe(state => {
this.allBooks = (state.books || []).filter(book =>
this.allBooks = computed(() =>
this.bookService.books().filter(book =>
book.libraryId === libraryId && !sourceBookIds.has(book.id)
);
});
)
);
this.filteredBooks = this.allBooks().slice(0, 20);
}
ngOnDestroy(): void {
@@ -98,12 +91,13 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
filterBooks(event: { query: string }): void {
const query = event.query.toLowerCase().trim();
const books = this.allBooks();
if (!query) {
this.filteredBooks = this.allBooks.slice(0, 20);
this.filteredBooks = books.slice(0, 20);
return;
}
this.filteredBooks = this.allBooks
this.filteredBooks = books
.filter(book => {
const title = book.metadata?.title?.toLowerCase() || '';
const authors = book.metadata?.authors?.join(' ').toLowerCase() || '';
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';
import {Component, DestroyRef, effect, inject, Input, OnChanges, OnInit, signal, SimpleChanges} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {BookReview, BookReviewService} from './book-review-service';
@@ -36,6 +36,7 @@ export class BookReviewsComponent implements OnInit, OnChanges {
private appSettingsService = inject(AppSettingsService);
private destroyRef = inject(DestroyRef);
private readonly t = inject(TranslocoService);
private bookIdState = signal<number | null>(null);
loading = false;
hasPermission = false;
@@ -45,29 +46,31 @@ export class BookReviewsComponent implements OnInit, OnChanges {
allSpoilersRevealed = false;
reviewDownloadEnabled = true;
constructor() {
effect(() => {
const bookId = this.bookIdState();
if (!bookId) {
this.reviewsLocked = false;
return;
}
const book = this.bookService.findBookById(bookId);
this.reviewsLocked = book?.metadata?.reviewsLocked ?? false;
});
}
ngOnInit(): void {
this.checkUserPermissions();
this.subscribeToBookState();
this.subscribeToAppSettings();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['bookId'] && changes['bookId'].currentValue) {
this.bookIdState.set(changes['bookId'].currentValue);
this.loadReviews();
}
}
private subscribeToBookState(): void {
this.bookService.bookState$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(state => {
if (state.books && this.bookId) {
const book = state.books.find(b => b.id === this.bookId);
this.reviewsLocked = book?.metadata?.reviewsLocked ?? false;
}
});
}
private loadReviews(): void {
if (this.loading || !this.bookId) {
return;
@@ -244,12 +247,9 @@ export class BookReviewsComponent implements OnInit, OnChanges {
}
private checkUserPermissions(): void {
this.userService.userState$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(userState => {
this.hasPermission = userState?.user?.permissions?.admin ||
userState?.user?.permissions?.canEditMetadata || false;
});
const user = this.userService.currentUser();
this.hasPermission = user?.permissions?.admin ||
user?.permissions?.canEditMetadata || false;
}
deleteReview(review: BookReview): void {
@@ -315,11 +315,8 @@ export class BookReviewsComponent implements OnInit, OnChanges {
}
private subscribeToAppSettings(): void {
this.appSettingsService.appSettings$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(settings => {
this.reviewDownloadEnabled = settings?.metadataPublicReviewsSettings?.downloadEnabled ?? true;
});
const settings = this.appSettingsService.appSettings();
this.reviewDownloadEnabled = settings?.metadataPublicReviewsSettings?.downloadEnabled ?? true;
}
getProviderSeverity(provider: string): 'success' | 'warn' {
@@ -1,6 +1,6 @@
import {Component, ElementRef, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
import {BehaviorSubject, of, Subscription} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, switchMap, tap} from 'rxjs/operators';
import {Component, ElementRef, HostListener, computed, inject, signal} from '@angular/core';
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
import {Book} from '../../model/book.model';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
@@ -12,7 +12,7 @@ import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {Router} from '@angular/router';
import {IconField} from 'primeng/iconfield';
import {InputIcon} from 'primeng/inputicon';
import {HeaderFilter} from '../book-browser/filters/HeaderFilter';
import {filterBooksBySearchTerm} from '../book-browser/filters/HeaderFilter';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@Component({
@@ -31,43 +31,41 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
styleUrls: ['./book-searcher.component.scss'],
standalone: true
})
export class BookSearcherComponent implements OnInit, OnDestroy {
searchQuery: string = '';
books: Book[] = [];
isLoading = false;
export class BookSearcherComponent {
searchQuery = '';
activeIndex = -1;
#searchSubject = new BehaviorSubject<string>('');
#subscription!: Subscription;
isSearchFocused = false;
private readonly searchTerm = signal('');
private readonly debouncedSearchTerm = toSignal(
toObservable(this.searchTerm).pipe(
debounceTime(200),
distinctUntilChanged()
),
{initialValue: ''}
);
private readonly filteredBooks = computed(() => {
const term = this.debouncedSearchTerm().trim();
if (term.length < 2) {
return [];
}
return filterBooksBySearchTerm(this.bookService.books(), term).slice(0, 50);
});
private bookService = inject(BookService);
private router = inject(Router);
protected urlHelper = inject(UrlHelperService);
private readonly t = inject(TranslocoService);
private elRef = inject(ElementRef);
private headerFilter = new HeaderFilter(
this.#searchSubject.pipe(debounceTime(200), distinctUntilChanged())
);
ngOnInit(): void {
this.#subscription = this.bookService.bookState$.pipe(
tap(() => {
if (this.searchQuery.trim().length >= 2) {
this.isLoading = true;
}
}),
switchMap(bookState => this.headerFilter.filter(bookState)),
catchError(() => of({books: [], loaded: true, error: null}))
).subscribe({
next: (filteredState) => {
this.isLoading = false;
this.activeIndex = -1;
const term = this.searchQuery.trim();
this.books = term.length >= 2
? (filteredState.books || []).slice(0, 50)
: [];
}
});
get books(): Book[] {
return this.filteredBooks();
}
get isLoading(): boolean {
const rawTerm = this.searchTerm().trim();
return rawTerm.length >= 2 && rawTerm !== this.debouncedSearchTerm().trim();
}
getAuthorNames(authors: string[] | undefined): string {
@@ -89,7 +87,8 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
}
onSearchInputChange(): void {
this.#searchSubject.next(this.searchQuery.trim());
this.searchTerm.set(this.searchQuery.trim());
this.activeIndex = -1;
}
onBookClick(book: Book): void {
@@ -101,8 +100,8 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
clearSearch(): void {
this.searchQuery = '';
this.books = [];
this.isLoading = false;
this.searchTerm.set('');
this.activeIndex = -1;
}
get isDropdownOpen(): boolean {
@@ -140,10 +139,4 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
break;
}
}
ngOnDestroy(): void {
if (this.#subscription) {
this.#subscription.unsubscribe();
}
}
}
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, effect, inject} from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
@@ -11,8 +11,7 @@ import {BookService} from '../../service/book.service';
import {BookMetadataService} from '../../service/book-metadata.service';
import {LibraryService} from '../../service/library.service';
import {Library} from '../../model/library.model';
import {Book, CreatePhysicalBookRequest} from '../../model/book.model';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {BookMetadata, CreatePhysicalBookRequest} from '../../model/book.model';
import {TranslocoDirective} from '@jsverse/transloco';
import {Tabs, TabList, Tab, TabPanels, TabPanel} from 'primeng/tabs';
@@ -58,15 +57,13 @@ type ImportPhase = 'upload' | 'processing' | 'summary';
],
styleUrl: './bulk-isbn-import-dialog.component.scss',
})
export class BulkIsbnImportDialogComponent implements OnInit {
export class BulkIsbnImportDialogComponent {
private dynamicDialogRef = inject(DynamicDialogRef);
private dialogConfig = inject(DynamicDialogConfig);
private bookService = inject(BookService);
private bookMetadataService = inject(BookMetadataService);
private libraryService = inject(LibraryService);
private destroyRef = inject(DestroyRef);
libraries: Library[] = [];
selectedLibraryId: number | null = null;
phase: ImportPhase = 'upload';
@@ -84,20 +81,24 @@ export class BulkIsbnImportDialogComponent implements OnInit {
parseError = '';
readonly maxIsbnCount = MAX_ISBN_COUNT;
private readonly initializeSelectedLibraryEffect = effect(() => {
const libraries = this.libraries;
if (libraries.length === 0) {
return;
}
ngOnInit(): void {
this.libraryService.libraryState$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(state => {
if (state.loaded && state.libraries) {
this.libraries = state.libraries;
if (this.dialogConfig.data?.libraryId) {
this.selectedLibraryId = this.dialogConfig.data.libraryId;
} else if (this.libraries.length > 0 && this.libraries[0].id !== undefined) {
this.selectedLibraryId = this.libraries[0].id;
}
}
});
if (this.dialogConfig.data?.libraryId) {
this.selectedLibraryId = this.dialogConfig.data.libraryId;
return;
}
if (this.selectedLibraryId == null && libraries[0].id !== undefined) {
this.selectedLibraryId = libraries[0].id;
}
});
get libraries(): Library[] {
return this.libraryService.libraries();
}
onFileSelect(event: FileSelectEvent): void {
@@ -177,9 +178,9 @@ export class BulkIsbnImportDialogComponent implements OnInit {
entry.status = 'created-no-metadata';
this.noMetadataCount++;
}
} catch (err: any) {
} catch (err: unknown) {
entry.status = 'failed';
entry.error = err?.message || 'Unknown error';
entry.error = err instanceof Error ? err.message : 'Unknown error';
this.failedCount++;
}
@@ -310,7 +311,7 @@ export class BulkIsbnImportDialogComponent implements OnInit {
const isbns = new Set<string>();
if (!this.selectedLibraryId) return isbns;
const books: Book[] = this.bookService.getCurrentBookState().books ?? [];
const books = this.bookService.books();
for (const book of books) {
if (book.libraryId !== this.selectedLibraryId) continue;
const isbn13 = book.metadata?.isbn13;
@@ -332,8 +333,8 @@ export class BulkIsbnImportDialogComponent implements OnInit {
return false;
}
private lookupIsbn(isbn: string): Promise<any> {
return new Promise((resolve, reject) => {
private lookupIsbn(isbn: string): Promise<BookMetadata | null> {
return new Promise((resolve) => {
this.bookMetadataService.lookupByIsbn(isbn).subscribe({
next: metadata => resolve(metadata),
error: err => {
@@ -8,7 +8,7 @@ import {SelectButton} from 'primeng/selectbutton';
import {ProgressBar} from 'primeng/progressbar';
import {Tag} from 'primeng/tag';
import {Paginator} from 'primeng/paginator';
import {filter, Subject, take, takeUntil} from 'rxjs';
import {Subject, takeUntil} from 'rxjs';
import {BookFileService} from '../../service/book-file.service';
import {BookService} from '../../service/book.service';
import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model';
@@ -81,13 +81,10 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
ngOnInit(): void {
this.libraryId = this.config.data.libraryId;
this.appSettingsService.appSettings$.pipe(
filter(settings => !!settings),
take(1),
takeUntil(this.destroy$)
).subscribe(settings => {
this.moveFiles = settings!.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
});
const settings = this.appSettingsService.appSettings();
if (settings) {
this.moveFiles = settings.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
}
this.presetOptions = [
{label: this.t.translate('book.duplicateMerger.presetStrict'), value: 'strict'},
@@ -1,5 +1,14 @@
<ng-container *transloco="let t; prefix: 'book.seriesPage'">
@if (filteredBooks$ | async; as books) {
@if (isBooksLoading()) {
<div class="loading-state">
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
</p-progressSpinner>
<p style="color: var(--primary-color);">
{{ t('loadingSeriesDetails') }}
</p>
</div>
} @else {
@let books = filteredBooks();
<div class="series-wrapper">
<p-tabs [value]="tab" lazy="true" scrollable>
<p-tablist>
@@ -21,7 +30,7 @@
<!-- HERO: Cover + Identity info -->
<div class="series-hero">
@if (coverBook$ | async; as coverBook) {
@if (coverBook(); as coverBook) {
<div class="hero-cover-section">
<img
[src]="getBookThumbnailUrl(coverBook)"
@@ -33,9 +42,9 @@
}
<div class="hero-info">
<h2 class="series-title">{{ seriesTitle$ | async }}</h2>
<h2 class="series-title">{{ seriesTitle() }}</h2>
@if (allAuthors$ | async; as authors) {
@if (allAuthors(); as authors) {
<p class="series-authors">
@for (author of authors; track $index; let isLast = $last) {
<a class="author-link" (click)="goToAuthorBooks(author)">{{ author }}</a>
@@ -44,7 +53,7 @@
</p>
}
@if (allCategories$ | async; as categories) {
@if (allCategories(); as categories) {
@if (categories.length) {
<div class="categories-scroll">
<div class="categories-list">
@@ -59,7 +68,7 @@
}
<div class="metadata-cards">
@if (allPublishers$ | async; as publishers) {
@if (allPublishers(); as publishers) {
@if (publishers.length) {
<span class="meta-card meta-card--publisher" (click)="goToPublisher(publishers[0])">
<i class="pi pi-building"></i>
@@ -73,13 +82,13 @@
<i class="pi pi-book"></i>
{{ books.length }} {{ books.length === 1 ? t('book') : t('books') }}
</span>
@if (yearsRange$ | async; as years) {
@if (yearsRange(); as years) {
<span class="meta-card meta-card--years">
<i class="pi pi-calendar"></i>
{{ years }}
</span>
}
@if (seriesStats$ | async; as stats) {
@if (seriesStats(); as stats) {
@if (stats.totalPages > 0) {
<span class="meta-card meta-card--pages">
<i class="pi pi-file"></i>
@@ -101,7 +110,7 @@
</span>
}
}
@if (allLanguages$ | async; as languages) {
@if (allLanguages(); as languages) {
@if (languages.length) {
<span class="meta-card meta-card--language">
<i class="pi pi-globe"></i>
@@ -109,7 +118,7 @@
</span>
}
}
@if (seriesCompletion$ | async; as completion) {
@if (seriesCompletion(); as completion) {
<span class="meta-card meta-card--owned">
<i class="pi pi-check-circle"></i>
{{ completion.owned }}/{{ completion.total }} {{ t('stats.owned') }}
@@ -118,7 +127,7 @@
</div>
<!-- Ratings -->
@if (seriesStats$ | async; as stats) {
@if (seriesStats(); as stats) {
@if (stats.avgPersonalRating != null || stats.avgGoodreads != null || stats.avgAmazon != null || stats.avgHardcover != null) {
<div class="ratings-row">
@if (stats.avgPersonalRating != null) {
@@ -155,7 +164,7 @@
<!-- Next Up + Progress (pushed to bottom, aligned with cover) -->
<div class="hero-status">
@if (nextUp$ | async; as nextUp) {
@if (nextUp(); as nextUp) {
<div class="next-up-card" (click)="readBook(nextUp.book.id)">
<img [src]="nextUp.thumbnailUrl"
[alt]="nextUp.book.metadata?.title || ''"
@@ -181,7 +190,7 @@
</div>
}
@if (readStatusBreakdown$ | async; as segments) {
@if (readStatusBreakdown(); as segments) {
@if (segments.length) {
<div class="read-progress-card">
<div class="read-progress-section">
@@ -202,7 +211,7 @@
{{ getStatusLabel(seg.status) }} ({{ seg.count }})
</span>
}
@let readProg = seriesReadProgress$ | async;
@let readProg = seriesReadProgress();
@if (readProg) {
<span class="read-percent-label">
{{ t('readPercent', { progress: readProg }) }}
@@ -227,7 +236,7 @@
<div #descriptionContent [ngClass]="{ 'line-clamp-7': !isExpanded }"
class="description-content">
<div class="description-html"
[innerHTML]="(firstDescription$ | async) || t('noDescription')"></div>
[innerHTML]="firstDescription() || t('noDescription')"></div>
</div>
@if (isExpanded || isOverflowing) {
<button class="expand-toggle" (click)="toggleExpand()">
@@ -356,7 +365,7 @@
</p-tabpanels>
</p-tabs>
@if (selectedBooks.size > 0) {
@if (userService.userState$ | async; as userState) {
@if (currentUser(); as user) {
<div class="book-browser-footer" [@slideInOut]>
<div class="footer-content">
<div class="footer-left">
@@ -387,17 +396,17 @@
[pTooltip]="t('tooltip.assignToShelf')"
tooltipPosition="top">
</p-button>
@if (userState.user!.permissions.canBulkLockUnlockMetadata) {
@if (user.permissions.canBulkLockUnlockMetadata) {
<p-button
outlined="true"
icon="pi pi-lock"
severity="info"
(click)="lockUnlockMetadata()"
[pTooltip]="t('tooltip.lockUnlockMetadata')"
tooltipPosition="top">
(click)="lockUnlockMetadata()"
[pTooltip]="t('tooltip.lockUnlockMetadata')"
tooltipPosition="top">
</p-button>
}
@if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
@if (user.permissions.canMoveOrganizeFiles && appSettings()?.diskType === 'LOCAL') {
<p-button
outlined="true"
icon="pi pi-arrows-h"
@@ -440,7 +449,7 @@
tooltipPosition="top">
</p-button>
</div>
@if (userState.user!.permissions.admin || userState.user!.permissions.canDeleteBook) {
@if (user.permissions.admin || user.permissions.canDeleteBook) {
<p-divider layout="vertical"></p-divider>
<p-button
outlined="true"
@@ -458,14 +467,5 @@
}
}
</div>
} @else {
<div class="loading-state">
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
</p-progressSpinner>
<p style="color: var(--primary-color);">
{{ t('loadingSeriesDetails') }}
</p>
</div>
}
</ng-container>
@@ -1,10 +1,10 @@
import {FormsModule} from "@angular/forms";
import {Button} from "primeng/button";
import {ActivatedRoute, Router} from "@angular/router";
import {AsyncPipe, DecimalPipe, KeyValuePipe, NgClass, NgStyle} from "@angular/common";
import {filter, finalize, map, switchMap, tap} from "rxjs/operators";
import {combineLatest, Observable, Subscription} from "rxjs";
import {Book, BookType, ReadStatus} from "../../model/book.model";
import {toSignal} from '@angular/core/rxjs-interop';
import {DecimalPipe, KeyValuePipe, NgClass, NgStyle} from "@angular/common";
import {finalize, map} from "rxjs/operators";
import {Book, BookType, computeSeriesReadStatus, ReadStatus} from "../../model/book.model";
import {BookService} from "../../service/book.service";
import {BookMetadataManageService} from "../../service/book-metadata-manage.service";
import {BookCardComponent} from "../book-browser/book-card/book-card.component";
@@ -28,9 +28,10 @@ import {Tooltip} from "primeng/tooltip";
import {Divider} from "primeng/divider";
import {TagComponent} from "../../../../shared/components/tag/tag.component";
import {animate, style, transition, trigger} from "@angular/animations";
import {AfterViewChecked, Component, ElementRef, inject, OnDestroy, ViewChild} from '@angular/core';
import {AfterViewChecked, Component, computed, effect, ElementRef, inject, ViewChild} from '@angular/core';
import {BookCardOverlayPreferenceService} from '../book-browser/book-card-overlay-preference.service';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {injectQuery} from '@tanstack/angular-query-experimental';
interface ReadStatusSegment {
status: ReadStatus;
@@ -68,7 +69,6 @@ interface SeriesStats {
templateUrl: "./series-page.component.html",
styleUrls: ["./series-page.component.scss"],
imports: [
AsyncPipe,
DecimalPipe,
KeyValuePipe,
Button,
@@ -103,7 +103,7 @@ interface SeriesStats {
])
]
})
export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
export class SeriesPageComponent implements AfterViewChecked {
private route = inject(ActivatedRoute);
private bookService = inject(BookService);
@@ -128,313 +128,257 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
tab: string = "view";
isExpanded = false;
isOverflowing = false;
protected appSettings = this.appSettingsService.appSettings;
protected currentUser = this.userService.currentUser;
protected isBooksLoading = this.bookService.isBooksLoading;
// Selection state
selectedBooks = new Set<number>();
lastSelectedIndex: number | null = null;
currentBooks: Book[] = [];
private userSub: Subscription;
// Menu items
protected metadataMenuItems: MenuItem[] | undefined;
protected moreActionsMenuItems: MenuItem[] | undefined;
seriesParam$: Observable<string> = this.route.paramMap.pipe(
private seriesParam = toSignal(this.route.paramMap.pipe(
map((params) => params.get("seriesName") || ""),
map((name) => decodeURIComponent(name))
);
), {initialValue: ""});
booksInSeries$: Observable<Book[]> = this.bookService.bookState$.pipe(
filter((state) => state.loaded && !!state.books),
map((state) => state.books || [])
);
filteredBooks = computed(() => {
const seriesName = this.seriesParam().trim().toLowerCase();
const inSeries = this.bookService.books().filter(
(book) => book.metadata?.seriesName?.trim().toLowerCase() === seriesName
);
filteredBooks$: Observable<Book[]> = combineLatest([
this.seriesParam$.pipe(map((n) => n.trim().toLowerCase())),
this.booksInSeries$,
]).pipe(
map(([seriesName, books]) => {
const inSeries = books.filter(
(b) => b.metadata?.seriesName?.trim().toLowerCase() === seriesName
);
return inSeries.sort((a, b) => {
const aNum = a.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
const bNum = b.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
return aNum - bNum;
});
}),
tap(books => this.currentBooks = books)
);
return [...inSeries].sort((a, b) => {
const aNum = a.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
const bNum = b.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
return aNum - bNum;
});
});
coverBook$: Observable<Book | null> = this.filteredBooks$.pipe(
map(books => books[0] ?? null)
);
coverBook = computed(() => this.filteredBooks()[0] ?? null);
private firstBookId = computed(() => this.coverBook()?.id ?? null);
private firstBookDetailQuery = injectQuery(() => ({
...this.bookService.bookDetailQueryOptions(this.firstBookId() ?? -1, true),
enabled: this.firstBookId() != null,
}));
seriesTitle$: Observable<string> = combineLatest([
this.seriesParam$,
this.filteredBooks$,
]).pipe(map(([param, books]) => books[0]?.metadata?.seriesName || param));
seriesTitle = computed(() => this.filteredBooks()[0]?.metadata?.seriesName || this.seriesParam());
yearsRange$: Observable<string | null> = this.filteredBooks$.pipe(
map((books) => {
const years = books
.map((b) => b.metadata?.publishedDate)
.filter((d): d is string => !!d)
.map((d) => {
const match = d.match(/\d{4}/);
return match ? parseInt(match[0], 10) : null;
})
.filter((y): y is number => y !== null);
yearsRange = computed(() => {
const years = this.filteredBooks()
.map((book) => book.metadata?.publishedDate)
.filter((date): date is string => !!date)
.map((date) => {
const match = date.match(/\d{4}/);
return match ? parseInt(match[0], 10) : null;
})
.filter((year): year is number => year !== null);
if (years.length === 0) return null;
const min = Math.min(...years);
const max = Math.max(...years);
return min === max ? String(min) : `${min}-${max}`;
})
);
if (years.length === 0) return null;
const min = Math.min(...years);
const max = Math.max(...years);
return min === max ? String(min) : `${min}-${max}`;
});
firstBookWithDesc$: Observable<Book> = this.filteredBooks$.pipe(
map((books) => books[0]),
filter((b): b is Book => !!b),
switchMap((b) => this.bookService.getBookByIdFromAPI(b.id, true))
);
firstBookWithDesc = computed(() => this.firstBookDetailQuery.data() ?? null);
firstDescription = computed(() => this.firstBookWithDesc()?.metadata?.description || "");
firstDescription$: Observable<string> = this.firstBookWithDesc$.pipe(
map((b) => b.metadata?.description || "")
);
seriesReadStatus = computed(() => computeSeriesReadStatus(this.filteredBooks()));
seriesReadStatus$: Observable<ReadStatus> = this.filteredBooks$.pipe(
map((books) => {
if (!books || books.length === 0) return ReadStatus.UNREAD;
const statuses = books.map((b) => (b.readStatus as ReadStatus) ?? ReadStatus.UNREAD);
seriesReadProgress = computed(() => {
const books = this.filteredBooks();
const readCount = books.filter((book) => book.readStatus === ReadStatus.READ).length;
return `${readCount}/${books.length}`;
});
const hasWontRead = statuses.includes(ReadStatus.WONT_READ);
if (hasWontRead) return ReadStatus.WONT_READ;
allAuthors = computed(() => {
const authors = new Set<string>();
for (const book of this.filteredBooks()) {
book.metadata?.authors?.forEach((author) => authors.add(author));
}
return Array.from(authors);
});
const hasAbandoned = statuses.includes(ReadStatus.ABANDONED);
if (hasAbandoned) return ReadStatus.ABANDONED;
allCategories = computed(() => {
const categories = new Set<string>();
for (const book of this.filteredBooks()) {
book.metadata?.categories?.forEach((category) => categories.add(category));
}
return Array.from(categories);
});
const allRead = statuses.every((s) => s === ReadStatus.READ);
if (allRead) return ReadStatus.READ;
const isAnyReading = statuses.some(
(s) => s === ReadStatus.READING || s === ReadStatus.RE_READING || s === ReadStatus.PAUSED
);
if (isAnyReading) return ReadStatus.READING;
const someRead = statuses.some((s) => s === ReadStatus.READ);
if (someRead) return ReadStatus.PARTIALLY_READ;
const allUnread = statuses.every((s) => s === ReadStatus.UNREAD);
if (allUnread) return ReadStatus.UNREAD;
return ReadStatus.PARTIALLY_READ;
})
);
seriesReadProgress$: Observable<string> = this.filteredBooks$.pipe(
map((books) => {
const total = books?.length ?? 0;
const readCount = (books || []).filter((b) => b.readStatus === ReadStatus.READ).length;
return `${readCount}/${total}`;
})
);
// Aggregated metadata across all books
allAuthors$: Observable<string[]> = this.filteredBooks$.pipe(
map(books => {
const set = new Set<string>();
for (const book of books) {
book.metadata?.authors?.forEach(a => set.add(a));
allPublishers = computed(() => {
const publishers = new Set<string>();
for (const book of this.filteredBooks()) {
if (book.metadata?.publisher) {
publishers.add(book.metadata.publisher);
}
return Array.from(set);
})
);
}
return Array.from(publishers);
});
allCategories$: Observable<string[]> = this.filteredBooks$.pipe(
map(books => {
const set = new Set<string>();
for (const book of books) {
book.metadata?.categories?.forEach(c => set.add(c));
allLanguages = computed(() => {
const languages = new Set<string>();
for (const book of this.filteredBooks()) {
if (book.metadata?.language) {
languages.add(book.metadata.language);
}
return Array.from(set);
})
);
}
return Array.from(languages);
});
allPublishers$: Observable<string[]> = this.filteredBooks$.pipe(
map(books => {
const set = new Set<string>();
for (const book of books) {
if (book.metadata?.publisher) set.add(book.metadata.publisher);
seriesCompletion = computed<SeriesCompletion | null>(() => {
const totals = this.filteredBooks()
.map((book) => book.metadata?.seriesTotal)
.filter((total): total is number => total != null && total > 0);
if (totals.length === 0) return null;
const seriesTotal = Math.max(...totals);
const ownedNumbers = new Set(
this.filteredBooks()
.map((book) => book.metadata?.seriesNumber)
.filter((number): number is number => number != null)
);
const missingNumbers: number[] = [];
for (let i = 1; i <= seriesTotal; i++) {
if (!ownedNumbers.has(i)) missingNumbers.push(i);
}
const owned = ownedNumbers.size;
return {
owned,
total: seriesTotal,
percent: seriesTotal > 0 ? Math.round((owned / seriesTotal) * 100) : 0,
missingNumbers
};
});
readStatusBreakdown = computed(() => {
const books = this.filteredBooks();
if (books.length === 0) return [];
const counts = new Map<ReadStatus, number>();
for (const book of books) {
const status = (book.readStatus as ReadStatus) ?? ReadStatus.UNREAD;
counts.set(status, (counts.get(status) || 0) + 1);
}
const total = books.length;
const segments: ReadStatusSegment[] = [];
for (const [status, count] of counts) {
segments.push({status, count, percent: (count / total) * 100});
}
return segments;
});
nextUp = computed<NextUpBook | null>(() => {
const books = this.filteredBooks();
const reading = books.find(book =>
book.readStatus === ReadStatus.READING ||
book.readStatus === ReadStatus.RE_READING ||
book.readStatus === ReadStatus.PAUSED
);
const target = reading || books.find(book => book.readStatus === ReadStatus.UNREAD || !book.readStatus);
if (!target) return null;
const isAudiobook = target.primaryFile?.bookType === 'AUDIOBOOK';
const thumbnailUrl = isAudiobook
? this.urlHelper.getAudiobookThumbnailUrl(target.id, target.metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getThumbnailUrl(target.id, target.metadata?.coverUpdatedOn);
const isReading = target.readStatus === ReadStatus.READING ||
target.readStatus === ReadStatus.RE_READING ||
target.readStatus === ReadStatus.PAUSED;
let progressPercent: number | null = null;
if (isReading) {
progressPercent = target.epubProgress?.percentage
?? target.pdfProgress?.percentage
?? target.cbxProgress?.percentage
?? target.audiobookProgress?.percentage
?? target.koreaderProgress?.percentage
?? target.koboProgress?.percentage
?? null;
if (progressPercent != null) {
progressPercent = Math.round(progressPercent);
}
return Array.from(set);
})
);
}
allLanguages$: Observable<string[]> = this.filteredBooks$.pipe(
map(books => {
const set = new Set<string>();
for (const book of books) {
if (book.metadata?.language) set.add(book.metadata.language);
}
return Array.from(set);
})
);
return {book: target, thumbnailUrl, isReading, progressPercent};
});
// Series completion tracker
seriesCompletion$: Observable<SeriesCompletion | null> = this.filteredBooks$.pipe(
map(books => {
const totals = books
.map(b => b.metadata?.seriesTotal)
.filter((t): t is number => t != null && t > 0);
if (totals.length === 0) return null;
seriesStats = computed<SeriesStats>(() => {
let totalPages = 0;
const personalRatings: number[] = [];
const goodreadsRatings: number[] = [];
const amazonRatings: number[] = [];
const hardcoverRatings: number[] = [];
const formatCounts = new Map<BookType, number>();
let totalAudioDurationSeconds = 0;
const seriesTotal = Math.max(...totals);
const ownedNumbers = new Set(
books
.map(b => b.metadata?.seriesNumber)
.filter((n): n is number => n != null)
);
for (const book of this.filteredBooks()) {
if (book.metadata?.pageCount) totalPages += book.metadata.pageCount;
if (book.personalRating != null) personalRatings.push(book.personalRating);
if (book.metadata?.goodreadsRating != null) goodreadsRatings.push(book.metadata.goodreadsRating);
if (book.metadata?.amazonRating != null) amazonRatings.push(book.metadata.amazonRating);
if (book.metadata?.hardcoverRating != null) hardcoverRatings.push(book.metadata.hardcoverRating);
const missingNumbers: number[] = [];
for (let i = 1; i <= seriesTotal; i++) {
if (!ownedNumbers.has(i)) missingNumbers.push(i);
const bookType = book.primaryFile?.bookType;
if (bookType) {
formatCounts.set(bookType, (formatCounts.get(bookType) || 0) + 1);
}
const owned = ownedNumbers.size;
return {
owned,
total: seriesTotal,
percent: seriesTotal > 0 ? Math.round((owned / seriesTotal) * 100) : 0,
missingNumbers
};
})
);
// Reading progress breakdown
readStatusBreakdown$: Observable<ReadStatusSegment[]> = this.filteredBooks$.pipe(
map(books => {
if (!books.length) return [];
const counts = new Map<ReadStatus, number>();
for (const book of books) {
const status = (book.readStatus as ReadStatus) ?? ReadStatus.UNREAD;
counts.set(status, (counts.get(status) || 0) + 1);
if (book.metadata?.audiobookMetadata?.durationSeconds) {
totalAudioDurationSeconds += book.metadata.audiobookMetadata.durationSeconds;
}
const total = books.length;
const segments: ReadStatusSegment[] = [];
for (const [status, count] of counts) {
segments.push({status, count, percent: (count / total) * 100});
}
return segments;
})
);
}
// Next up / continue reading
nextUp$: Observable<NextUpBook | null> = this.filteredBooks$.pipe(
map(books => {
const reading = books.find(b =>
b.readStatus === ReadStatus.READING ||
b.readStatus === ReadStatus.RE_READING ||
b.readStatus === ReadStatus.PAUSED
);
const target = reading || books.find(b => b.readStatus === ReadStatus.UNREAD || !b.readStatus);
if (!target) return null;
const avg = (ratings: number[]) => ratings.length > 0
? ratings.reduce((total, rating) => total + rating, 0) / ratings.length
: null;
const isAudiobook = target.primaryFile?.bookType === 'AUDIOBOOK';
const thumbnailUrl = isAudiobook
? this.urlHelper.getAudiobookThumbnailUrl(target.id, target.metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getThumbnailUrl(target.id, target.metadata?.coverUpdatedOn);
const isReading = target.readStatus === ReadStatus.READING ||
target.readStatus === ReadStatus.RE_READING ||
target.readStatus === ReadStatus.PAUSED;
let progressPercent: number | null = null;
if (isReading) {
progressPercent = target.epubProgress?.percentage
?? target.pdfProgress?.percentage
?? target.cbxProgress?.percentage
?? target.audiobookProgress?.percentage
?? target.koreaderProgress?.percentage
?? target.koboProgress?.percentage
?? null;
if (progressPercent != null) {
progressPercent = Math.round(progressPercent);
}
}
return {book: target, thumbnailUrl, isReading, progressPercent};
})
);
// Series statistics
seriesStats$: Observable<SeriesStats> = this.filteredBooks$.pipe(
map(books => {
let totalPages = 0;
const personalRatings: number[] = [];
const goodreadsRatings: number[] = [];
const amazonRatings: number[] = [];
const hardcoverRatings: number[] = [];
const formatCounts = new Map<BookType, number>();
let totalAudioDurationSeconds = 0;
for (const book of books) {
if (book.metadata?.pageCount) totalPages += book.metadata.pageCount;
if (book.personalRating != null) personalRatings.push(book.personalRating);
if (book.metadata?.goodreadsRating != null) goodreadsRatings.push(book.metadata.goodreadsRating);
if (book.metadata?.amazonRating != null) amazonRatings.push(book.metadata.amazonRating);
if (book.metadata?.hardcoverRating != null) hardcoverRatings.push(book.metadata.hardcoverRating);
const bookType = book.primaryFile?.bookType;
if (bookType) {
formatCounts.set(bookType, (formatCounts.get(bookType) || 0) + 1);
}
if (book.metadata?.audiobookMetadata?.durationSeconds) {
totalAudioDurationSeconds += book.metadata.audiobookMetadata.durationSeconds;
}
}
const avg = (arr: number[]) => arr.length > 0 ? arr.reduce((a, b) => a + b, 0) / arr.length : null;
return {
totalPages,
avgPersonalRating: avg(personalRatings),
avgGoodreads: avg(goodreadsRatings),
avgAmazon: avg(amazonRatings),
avgHardcover: avg(hardcoverRatings),
formatCounts,
totalAudioDurationSeconds
};
})
);
return {
totalPages,
avgPersonalRating: avg(personalRatings),
avgGoodreads: avg(goodreadsRatings),
avgAmazon: avg(amazonRatings),
avgHardcover: avg(hardcoverRatings),
formatCounts,
totalAudioDurationSeconds
};
});
constructor() {
this.userSub = this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded))
.subscribe(userState => {
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
() => this.autoFetchMetadata(),
() => this.fetchMetadata(),
() => this.bulkEditMetadata(),
() => this.multiBookEditMetadata(),
() => this.regenerateCoversForSelected(),
() => this.generateCustomCoversForSelected(),
userState.user
);
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
});
}
effect(() => {
const user = this.currentUser();
if (!user) {
return;
}
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
() => this.autoFetchMetadata(),
() => this.fetchMetadata(),
() => this.bulkEditMetadata(),
() => this.multiBookEditMetadata(),
() => this.regenerateCoversForSelected(),
() => this.generateCustomCoversForSelected(),
user
);
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.currentUser());
});
ngOnDestroy(): void {
this.userSub.unsubscribe();
}
get currentCardSize() {
return this.coverScalePreferenceService.currentCardSize;
return this.coverScalePreferenceService.currentCardSize();
}
get gridColumnMinWidth(): string {
return this.coverScalePreferenceService.gridColumnMinWidth;
return this.coverScalePreferenceService.gridColumnMinWidth();
}
goToAuthorBooks(author: string): void {
@@ -607,8 +551,9 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
const start = Math.min(this.lastSelectedIndex, index);
const end = Math.max(this.lastSelectedIndex, index);
const isUnselectingRange = !selected;
const books = this.filteredBooks();
for (let i = start; i <= end; i++) {
const book = this.currentBooks[i];
const book = books[i];
if (!book) continue;
this.handleBookSelection(book, !isUnselectingRange);
}
@@ -622,8 +567,7 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
}
selectAllBooks(): void {
if (!this.currentBooks) return;
for (const book of this.currentBooks) {
for (const book of this.filteredBooks()) {
this.selectedBooks.add(book.id);
}
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
@@ -654,8 +598,6 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
.subscribe(() => {
this.selectedBooks.clear();
});
},
reject: () => {
}
});
}
@@ -795,7 +737,7 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
}
user() {
return this.userService.getCurrentUser();
return this.currentUser();
}
get hasMetadataMenuItems(): boolean {
@@ -25,65 +25,69 @@
</div>
<div class="shelves-container">
@if ((shelfState$ | async)?.shelves && (shelfState$ | async)!.shelves!.length > 0) {
<div class="shelves-list">
<div class="list-header">
<span class="shelf-count">
<i class="pi pi-bookmark"></i>
{{ t('shelvesAvailable', { count: (shelfState$ | async)!.shelves!.length }) }}
</span>
<p-iconfield class="shelf-search">
<p-inputicon class="pi pi-search"/>
<input
type="text"
pInputText
[(ngModel)]="searchQuery"
[placeholder]="t('searchPlaceholder')"
/>
@if (searchQuery) {
<i class="pi pi-times clear-icon" (click)="searchQuery = ''"></i>
}
</p-iconfield>
</div>
@if (shelves(); as shelves) {
@if (shelves.length > 0) {
<div class="shelves-list">
<div class="list-header">
<span class="shelf-count">
<i class="pi pi-bookmark"></i>
{{ t('shelvesAvailable', { count: shelves.length }) }}
</span>
<p-iconfield class="shelf-search">
<p-inputicon class="pi pi-search"/>
<input
type="text"
pInputText
[(ngModel)]="searchQuery"
[placeholder]="t('searchPlaceholder')"
/>
@if (searchQuery) {
<button type="button" class="clear-icon" (click)="searchQuery = ''">
<i class="pi pi-times"></i>
</button>
}
</p-iconfield>
</div>
<div class="shelves-grid">
@for (shelf of filterShelves((shelfState$ | async)!.shelves!); track shelf.id) {
<div class="shelf-item" [class.selected]="isShelfSelected(shelf)">
<div class="shelf-checkbox">
<p-checkbox
[inputId]="'shelf-' + shelf.id"
name="shelves"
[value]="shelf"
[(ngModel)]="selectedShelves"
/>
<div class="shelves-grid">
@for (shelf of filterShelves(shelves); track shelf.id) {
<div class="shelf-item" [class.selected]="isShelfSelected(shelf)">
<div class="shelf-checkbox">
<p-checkbox
[inputId]="'shelf-' + shelf.id"
name="shelves"
[value]="shelf"
[(ngModel)]="selectedShelves"
/>
</div>
<label [for]="'shelf-' + shelf.id" class="shelf-label">
@if (shelf.icon) {
<div class="shelf-icon-wrapper">
<app-icon-display
[icon]="getShelfIcon(shelf)"
size="20px"
iconClass="shelf-icon"
/>
</div>
} @else {
<div class="shelf-icon-wrapper-empty">
</div>
}
<span class="shelf-name">{{ shelf.name }}</span>
</label>
</div>
<label [for]="'shelf-' + shelf.id" class="shelf-label">
@if (shelf.icon) {
<div class="shelf-icon-wrapper">
<app-icon-display
[icon]="getShelfIcon(shelf)"
size="20px"
iconClass="shelf-icon"
/>
</div>
} @else {
<div class="shelf-icon-wrapper-empty">
</div>
}
<span class="shelf-name">{{ shelf.name }}</span>
</label>
</div>
}
}
</div>
</div>
</div>
} @else {
<div class="empty-state">
<div class="empty-icon-wrapper">
<i class="pi pi-bookmark empty-icon"></i>
} @else {
<div class="empty-state">
<div class="empty-icon-wrapper">
<i class="pi pi-bookmark empty-icon"></i>
</div>
<h3 class="empty-title">{{ t('emptyTitle') }}</h3>
<p class="empty-description" [innerHTML]="t('emptyDescription')"></p>
</div>
<h3 class="empty-title">{{ t('emptyTitle') }}</h3>
<p class="empty-description" [innerHTML]="t('emptyDescription')"></p>
</div>
}
}
</div>
@@ -1,15 +1,12 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, computed, effect, inject} from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {Book} from '../../model/book.model';
import {MessageService} from 'primeng/api';
import {ShelfService} from '../../service/shelf.service';
import {combineLatest, finalize, Observable} from 'rxjs';
import {finalize} from 'rxjs';
import {BookService} from '../../service/book.service';
import {map, tap} from 'rxjs/operators';
import {Shelf} from '../../model/shelf.model';
import {ShelfState} from '../../model/state/shelf-state.model';
import {Button} from 'primeng/button';
import {AsyncPipe} from '@angular/common';
import {Checkbox} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
@@ -30,7 +27,6 @@ import {InputIcon} from 'primeng/inputicon';
imports: [
Button,
Checkbox,
AsyncPipe,
FormsModule,
IconDisplayComponent,
TranslocoDirective,
@@ -39,7 +35,7 @@ import {InputIcon} from 'primeng/inputicon';
InputIcon
]
})
export class ShelfAssignerComponent implements OnInit {
export class ShelfAssignerComponent {
private shelfService = inject(ShelfService);
private dynamicDialogConfig = inject(DynamicDialogConfig);
@@ -52,43 +48,40 @@ export class ShelfAssignerComponent implements OnInit {
private readonly t = inject(TranslocoService);
searchQuery = '';
private shelfSortField: 'name' | 'id' = 'name';
private shelfSortOrder: 'asc' | 'desc' = 'asc';
shelfState$: Observable<ShelfState> = combineLatest([
this.shelfService.shelfState$,
this.userService.userState$
]).pipe(
map(([state, userState]) => {
if (userState.user?.userSettings.sidebarShelfSorting) {
this.shelfSortField = this.validateSortField(userState.user.userSettings.sidebarShelfSorting.field);
this.shelfSortOrder = this.validateSortOrder(userState.user.userSettings.sidebarShelfSorting.order);
}
const filtered = state.shelves?.filter(s => s.userId === userState.user?.id) || [];
return {
...state,
shelves: this.sortShelves(filtered)
};
})
);
private currentUser = this.userService.currentUser;
book: Book = this.dynamicDialogConfig.data.book;
selectedShelves: Shelf[] = [];
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
isMultiBooks: boolean = this.dynamicDialogConfig.data.isMultiBooks;
ngOnInit(): void {
if (!this.isMultiBooks && this.book.shelves) {
this.shelfState$.pipe(
map(state => state.shelves || []),
tap(shelves => {
this.selectedShelves = shelves.filter(shelf =>
this.book.shelves?.some(bShelf => bShelf.id === shelf.id)
);
})
).subscribe();
private readonly shelfSortField = computed<'name' | 'id'>(() => {
const sorting = this.currentUser()?.userSettings.sidebarShelfSorting;
return sorting ? this.validateSortField(sorting.field) : 'name';
});
private readonly shelfSortOrder = computed<'asc' | 'desc'>(() => {
const sorting = this.currentUser()?.userSettings.sidebarShelfSorting;
return sorting ? this.validateSortOrder(sorting.order) : 'asc';
});
readonly shelves = computed(() => {
const user = this.currentUser();
const filteredShelves = this.shelfService.shelves().filter(shelf => shelf.userId === user?.id);
return this.sortShelves(filteredShelves);
});
private hasInitializedSelectedShelves = false;
private readonly initializeSelectedShelvesEffect = effect(() => {
if (this.isMultiBooks || this.hasInitializedSelectedShelves || !this.book.shelves?.length) {
return;
}
}
const selectedShelves = this.shelves().filter(shelf =>
this.book.shelves?.some(bookShelf => bookShelf.id === shelf.id)
);
if (selectedShelves.length > 0 || this.shelfService.shelves().length > 0) {
this.selectedShelves = selectedShelves;
this.hasInitializedSelectedShelves = true;
}
});
updateBooksShelves(): void {
const idsToAssign = new Set<number | undefined>(this.selectedShelves.map(shelf => shelf.id));
@@ -125,13 +118,7 @@ export class ShelfAssignerComponent implements OnInit {
}
createShelfDialog(): void {
const dialogRef = this.bookDialogHelper.openShelfCreatorDialog();
dialogRef.onClose.subscribe((created: boolean) => {
if (created) {
this.shelfService.reloadShelves();
}
});
this.bookDialogHelper.openShelfCreatorDialog();
}
closeDialog(): void {
@@ -159,16 +146,18 @@ export class ShelfAssignerComponent implements OnInit {
}
private sortShelves(shelves: Shelf[]): Shelf[] {
const sortField = this.shelfSortField();
const sortOrder = this.shelfSortOrder();
return [...shelves].sort((a, b) => {
const aVal = (a as unknown as Record<string, unknown>)[this.shelfSortField] ?? '';
const bVal = (b as unknown as Record<string, unknown>)[this.shelfSortField] ?? '';
const aVal = (a as unknown as Record<string, unknown>)[sortField] ?? '';
const bVal = (b as unknown as Record<string, unknown>)[sortField] ?? '';
let comparison = 0;
if (typeof aVal === 'string' && typeof bVal === 'string') {
comparison = aVal.localeCompare(bVal);
} else if (typeof aVal === 'number' && typeof bVal === 'number') {
comparison = aVal - bVal;
}
return this.shelfSortOrder === 'asc' ? comparison : -comparison;
return sortOrder === 'asc' ? comparison : -comparison;
});
}
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, effect, inject, Injector, OnInit} from '@angular/core';
import {ShelfService} from '../../service/shelf.service';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {Button} from 'primeng/button';
@@ -37,6 +37,8 @@ export class ShelfEditDialogComponent implements OnInit {
private iconPickerService = inject(IconPickerService);
private userService = inject(UserService);
private readonly t = inject(TranslocoService);
private readonly injector = inject(Injector);
private shelfInitialized = false;
shelfName: string = '';
selectedIcon: IconSelection | null = null;
@@ -46,18 +48,28 @@ export class ShelfEditDialogComponent implements OnInit {
ngOnInit(): void {
const shelfId = this.dynamicDialogConfig?.data.shelfId;
this.shelf = this.shelfService.getShelfById(shelfId);
if (this.shelf) {
this.shelfName = this.shelf.name;
this.isPublic = this.shelf.publicShelf ?? false;
if (this.shelf.iconType && this.shelf.icon) {
if (this.shelf.iconType === 'PRIME_NG') {
this.selectedIcon = {type: 'PRIME_NG', value: `pi pi-${this.shelf.icon}`};
effect(() => {
if (this.shelfInitialized) {
return;
}
const shelf = this.shelfService.shelves().find(currentShelf => currentShelf.id === shelfId);
if (!shelf) {
return;
}
this.shelfInitialized = true;
this.shelf = shelf;
this.shelfName = shelf.name;
this.isPublic = shelf.publicShelf ?? false;
if (shelf.iconType && shelf.icon) {
if (shelf.iconType === 'PRIME_NG') {
this.selectedIcon = {type: 'PRIME_NG', value: `pi pi-${shelf.icon}`};
} else {
this.selectedIcon = {type: 'CUSTOM_SVG', value: this.shelf.icon};
this.selectedIcon = {type: 'CUSTOM_SVG', value: shelf.icon};
}
}
}
}, {injector: this.injector});
}
openIconPicker() {
@@ -402,6 +402,25 @@ export enum ReadStatus {
UNSET = 'UNSET'
}
export function computeSeriesReadStatus(books: Book[]): ReadStatus {
if (!books || books.length === 0) return ReadStatus.UNREAD;
const statuses = books.map(b => (b.readStatus as ReadStatus) ?? ReadStatus.UNREAD);
if (statuses.includes(ReadStatus.WONT_READ)) return ReadStatus.WONT_READ;
if (statuses.includes(ReadStatus.ABANDONED)) return ReadStatus.ABANDONED;
if (statuses.every(s => s === ReadStatus.READ)) return ReadStatus.READ;
const isAnyReading = statuses.some(
s => s === ReadStatus.READING || s === ReadStatus.RE_READING || s === ReadStatus.PAUSED
);
if (isAnyReading) return ReadStatus.READING;
if (statuses.some(s => s === ReadStatus.READ)) return ReadStatus.PARTIALLY_READ;
if (statuses.every(s => s === ReadStatus.UNREAD)) return ReadStatus.UNREAD;
return ReadStatus.PARTIALLY_READ;
}
export interface CreatePhysicalBookRequest {
libraryId: number;
isbn?: string;
@@ -1,7 +0,0 @@
import {Book} from '../book.model';
export interface BookState {
books: Book[] | null;
loaded: boolean;
error: string | null;
}
@@ -1,7 +0,0 @@
import {Library} from '../library.model';
export interface LibraryState {
libraries: Library[] | null;
loaded: boolean;
error: string | null;
}
@@ -1,7 +0,0 @@
import {Shelf} from '../shelf.model';
export interface ShelfState {
shelves: Shelf[] | null;
loaded: boolean;
error: string | null;
}
@@ -6,8 +6,9 @@ import {AdditionalFile, AdditionalFileType, Book, DetachBookFileResponse, Duplic
import {API_CONFIG} from '../../../core/config/api-config';
import {MessageService} from 'primeng/api';
import {FileDownloadService} from '../../../shared/service/file-download.service';
import {BookStateService} from './book-state.service';
import {TranslocoService} from '@jsverse/transloco';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {patchBookInCacheWith, patchBooksInCache, removeBooksFromCache} from './book-query-cache';
@Injectable({
providedIn: 'root',
@@ -19,7 +20,7 @@ export class BookFileService {
private http = inject(HttpClient);
private messageService = inject(MessageService);
private fileDownloadService = inject(FileDownloadService);
private bookStateService = inject(BookStateService);
private queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
@@ -44,26 +45,13 @@ export class BookFileService {
}
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
return this.http.delete<void>(deleteUrl).pipe(
return this.http.delete<void>(`${this.url}/${bookId}/files/${fileId}`).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
return {
...book,
alternativeFormats: book.alternativeFormats?.filter(file => file.id !== fileId),
supplementaryFiles: book.supplementaryFiles?.filter(file => file.id !== fileId)
};
}
return book;
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
patchBookInCacheWith(this.queryClient, bookId, book => ({
...book,
alternativeFormats: book.alternativeFormats?.filter(f => f.id !== fileId),
supplementaryFiles: book.supplementaryFiles?.filter(f => f.id !== fileId),
}));
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.bookService.toast.fileDeletedSummary'),
@@ -82,43 +70,19 @@ export class BookFileService {
}
deleteBookFile(bookId: number, fileId: number, isPrimary: boolean): Observable<void> {
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
return this.http.delete<void>(deleteUrl).pipe(
return this.http.delete<void>(`${this.url}/${bookId}/files/${fileId}`).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
if (isPrimary) {
const remainingAlternatives = book.alternativeFormats?.filter(file => file.id !== fileId) || [];
if (remainingAlternatives.length > 0) {
const [newPrimary, ...restAlternatives] = remainingAlternatives;
return {
...book,
primaryFile: newPrimary,
alternativeFormats: restAlternatives
};
} else {
return {
...book,
primaryFile: undefined,
alternativeFormats: []
};
}
} else {
return {
...book,
alternativeFormats: book.alternativeFormats?.filter(file => file.id !== fileId)
};
}
patchBookInCacheWith(this.queryClient, bookId, book => {
if (isPrimary) {
const remaining = book.alternativeFormats?.filter(f => f.id !== fileId) || [];
const [newPrimary, ...rest] = remaining;
return {...book, primaryFile: newPrimary, alternativeFormats: rest};
}
return book;
return {
...book,
alternativeFormats: book.alternativeFormats?.filter(f => f.id !== fileId),
};
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.bookService.toast.fileDeletedSummary'),
@@ -162,26 +126,13 @@ export class BookFileService {
}
}
return this.http.post<AdditionalFile>(`${this.url}/${bookId}/files`, formData).pipe(
tap((newFile) => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
const updatedBook = {...book};
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
updatedBook.alternativeFormats = [...(book.alternativeFormats || []), newFile];
} else {
updatedBook.supplementaryFiles = [...(book.supplementaryFiles || []), newFile];
}
return updatedBook;
tap(newFile => {
patchBookInCacheWith(this.queryClient, bookId, book => {
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
return {...book, alternativeFormats: [...(book.alternativeFormats || []), newFile]};
}
return book;
return {...book, supplementaryFiles: [...(book.supplementaryFiles || []), newFile]};
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.bookService.toast.fileUploadedSummary'),
@@ -209,19 +160,9 @@ export class BookFileService {
}
detachBookFile(bookId: number, fileId: number, copyMetadata: boolean): Observable<DetachBookFileResponse> {
return this.http.post<DetachBookFileResponse>(`${this.url}/${bookId}/files/${fileId}/detach`, { copyMetadata }).pipe(
return this.http.post<DetachBookFileResponse>(`${this.url}/${bookId}/files/${fileId}/detach`, {copyMetadata}).pipe(
tap(response => {
const currentState = this.bookStateService.getCurrentBookState();
let updatedBooks = (currentState.books || []).map(book =>
book.id === bookId ? response.sourceBook : book
);
updatedBooks = [...updatedBooks, response.newBook];
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
patchBooksInCache(this.queryClient, [response.sourceBook, response.newBook]);
this.messageService.add({
severity: 'success',
summary: this.t.translate('metadata.viewer.toast.detachFileSuccessSummary'),
@@ -249,22 +190,12 @@ export class BookFileService {
moveFiles
}).pipe(
tap(response => {
const currentState = this.bookStateService.getCurrentBookState();
const deletedIdSet = new Set(response.deletedSourceBookIds);
let updatedBooks = (currentState.books || []).map(book =>
book.id === targetBookId ? response.updatedBook : book
).filter(book => !deletedIdSet.has(book.id));
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
const fileCount = sourceBookIds.length;
patchBooksInCache(this.queryClient, [response.updatedBook]);
removeBooksFromCache(this.queryClient, response.deletedSourceBookIds);
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.bookService.toast.filesAttachedSummary'),
detail: this.t.translate('book.bookService.toast.filesAttachedDetail', {count: fileCount})
detail: this.t.translate('book.bookService.toast.filesAttachedDetail', {count: sourceBookIds.length})
});
}),
catchError(error => {
@@ -328,7 +328,7 @@ export class BookMenuService {
rejectLabel: this.t.translate('common.no'),
accept: () => {
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.removingFromShelves', {count}));
const books = this.bookService.getBooksByIdsFromState(Array.from(selectedBooks));
const books = this.bookService.getBooksByIds(Array.from(selectedBooks));
const allShelfIds = new Set<number>();
books.forEach(b => b.shelves?.forEach(s => {
if (s.id) allShelfIds.add(s.id);
@@ -5,10 +5,9 @@ import {catchError, map, tap} from 'rxjs/operators';
import {Book, BookMetadata, BulkMetadataUpdateRequest, MetadataUpdateWrapper} from '../model/book.model';
import {API_CONFIG} from '../../../core/config/api-config';
import {MessageService} from 'primeng/api';
import {BookStateService} from './book-state.service';
import {BookSocketService} from './book-socket.service';
import {TranslocoService} from '@jsverse/transloco';
import {BookService} from './book.service';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {invalidateBookQueries, invalidateBooksQuery, patchBookInCacheWith, patchBookMetadataInCache} from './book-query-cache';
@Injectable({
providedIn: 'root',
@@ -19,23 +18,25 @@ export class BookMetadataManageService {
private http = inject(HttpClient);
private messageService = inject(MessageService);
private bookStateService = inject(BookStateService);
private bookSocketService = inject(BookSocketService);
private bookService = inject(BookService);
private queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean, replaceMode: 'REPLACE_ALL' | 'REPLACE_WHEN_PROVIDED' = 'REPLACE_ALL'): Observable<BookMetadata> {
const params = new HttpParams().set('mergeCategories', mergeCategories.toString()).set('replaceMode', replaceMode);
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
map(updatedMetadata => {
this.bookSocketService.handleBookMetadataUpdate(bookId!, updatedMetadata);
return updatedMetadata;
tap(updatedMetadata => {
if (bookId != null) {
patchBookMetadataInCache(this.queryClient, bookId, updatedMetadata);
}
})
);
}
updateBooksMetadata(request: BulkMetadataUpdateRequest): Observable<void> {
return this.http.put(`${this.url}/bulk-edit-metadata`, request).pipe(
tap(() => {
invalidateBooksQuery(this.queryClient);
}),
map(() => void 0)
);
}
@@ -43,16 +44,15 @@ export class BookMetadataManageService {
toggleAllLock(bookIds: Set<number>, lock: string): Observable<void> {
const requestBody = {
bookIds: Array.from(bookIds),
lock: lock
lock
};
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
tap((updatedMetadataList) => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
tap(updatedMetadataList => {
updatedMetadataList.forEach(metadata => {
if (metadata.bookId != null) {
patchBookMetadataInCache(this.queryClient, metadata.bookId, metadata);
}
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}),
map(() => void 0),
catchError((error) => {
@@ -64,32 +64,24 @@ export class BookMetadataManageService {
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
const requestBody = {
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, {
bookIds: Array.from(bookIdSet),
fieldActions
};
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
}).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (!bookIdSet.has(book.id)) return book;
const updatedMetadata = {...book.metadata};
for (const [field, action] of Object.entries(fieldActions)) {
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
if (lockField in updatedMetadata) {
(updatedMetadata as Record<string, unknown>)[lockField] = action === 'LOCK';
for (const bookId of bookIdSet) {
patchBookInCacheWith(this.queryClient, bookId, book => {
if (!book.metadata) return book;
const updatedMetadata = {...book.metadata} as Record<string, unknown>;
for (const [field, action] of Object.entries(fieldActions)) {
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
if (lockField in updatedMetadata) {
updatedMetadata[lockField] = action === 'LOCK';
}
}
}
return {
...book,
metadata: updatedMetadata
};
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks as Book[]
});
return {...book, metadata: updatedMetadata as BookMetadata};
});
}
}),
catchError(error => {
this.messageService.add({
@@ -103,39 +95,47 @@ export class BookMetadataManageService {
}
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(
return this.http.post(`${this.url}/metadata/manage/consolidate`, {metadataType, targetValues, valuesToMerge}).pipe(
tap(() => {
this.bookService.refreshBooks();
invalidateBooksQuery(this.queryClient);
})
);
}
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(
return this.http.post(`${this.url}/metadata/manage/delete`, {metadataType, valuesToDelete}).pipe(
tap(() => {
this.bookService.refreshBooks();
invalidateBooksQuery(this.queryClient);
})
);
}
/*------------------ Cover Operations ------------------*/
getUploadCoverUrl(bookId: number): string {
return this.url + '/' + bookId + "/metadata/cover/upload"
return this.url + '/' + bookId + '/metadata/cover/upload';
}
uploadCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/cover/from-url`, {url});
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/cover/from-url`, {url}).pipe(
tap(updatedMetadata => {
patchBookMetadataInCache(this.queryClient, bookId, updatedMetadata);
})
);
}
regenerateCovers(missingOnly = false): Observable<void> {
return this.http.post<void>(`${this.url}/regenerate-covers?missingOnly=${missingOnly}`, {});
return this.http.post<void>(`${this.url}/regenerate-covers?missingOnly=${missingOnly}`, {}).pipe(
tap(() => {
invalidateBooksQuery(this.queryClient);
})
);
}
regenerateCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {});
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {}).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, [bookId]);
})
);
}
getFileMetadata(bookId: number): Observable<BookMetadata> {
@@ -143,37 +143,65 @@ export class BookMetadataManageService {
}
generateCustomCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-cover`, {});
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-cover`, {}).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, [bookId]);
})
);
}
generateCustomCoversForBooks(bookIds: number[]): Observable<void> {
return this.http.post<void>(`${this.url}/bulk-generate-custom-covers`, {bookIds});
return this.http.post<void>(`${this.url}/bulk-generate-custom-covers`, {bookIds}).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, bookIds);
})
);
}
regenerateCoversForBooks(bookIds: number[]): Observable<void> {
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, {bookIds});
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, {bookIds}).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, bookIds);
})
);
}
uploadAudiobookCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/audiobook-cover/from-url`, {url});
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/audiobook-cover/from-url`, {url}).pipe(
tap(updatedMetadata => {
patchBookMetadataInCache(this.queryClient, bookId, updatedMetadata);
})
);
}
uploadAudiobookCoverFromFile(bookId: number, file: File): Observable<void> {
const formData = new FormData();
formData.append('file', file);
return this.http.post<void>(`${this.url}/${bookId}/metadata/audiobook-cover/upload`, formData);
return this.http.post<void>(`${this.url}/${bookId}/metadata/audiobook-cover/upload`, formData).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, [bookId]);
})
);
}
getUploadAudiobookCoverUrl(bookId: number): string {
return this.url + '/' + bookId + "/metadata/audiobook-cover/upload";
return this.url + '/' + bookId + '/metadata/audiobook-cover/upload';
}
regenerateAudiobookCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/regenerate-audiobook-cover`, {});
return this.http.post<void>(`${this.url}/${bookId}/regenerate-audiobook-cover`, {}).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, [bookId]);
})
);
}
generateCustomAudiobookCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-audiobook-cover`, {});
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-audiobook-cover`, {}).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, [bookId]);
})
);
}
supportsDualCovers(book: Book): boolean {
@@ -187,6 +215,10 @@ export class BookMetadataManageService {
const formData = new FormData();
formData.append('file', file);
formData.append('bookIds', bookIds.join(','));
return this.http.post<void>(`${this.url}/bulk-upload-cover`, formData);
return this.http.post<void>(`${this.url}/bulk-upload-cover`, formData).pipe(
tap(() => {
invalidateBookQueries(this.queryClient, bookIds);
})
);
}
}
@@ -1,5 +1,4 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {computed, Injectable, signal} from '@angular/core';
export interface BookNavigationState {
bookIds: number[];
@@ -10,77 +9,69 @@ export interface BookNavigationState {
providedIn: 'root'
})
export class BookNavigationService {
private navigationState$ = new BehaviorSubject<BookNavigationState | null>(null);
private availableBookIds: number[] = [];
private readonly _navigationState = signal<BookNavigationState | null>(null);
readonly navigationState = this._navigationState.asReadonly();
private readonly _availableBookIds = signal<number[]>([]);
readonly availableBookIds = this._availableBookIds.asReadonly();
readonly canNavigatePrevious = computed(() => {
const state = this.navigationState();
return state !== null && state.currentIndex > 0;
});
readonly canNavigateNext = computed(() => {
const state = this.navigationState();
return state !== null && state.currentIndex < state.bookIds.length - 1;
});
readonly previousBookId = computed<number | null>(() => {
const state = this.navigationState();
return state && state.currentIndex > 0
? state.bookIds[state.currentIndex - 1]
: null;
});
readonly nextBookId = computed<number | null>(() => {
const state = this.navigationState();
return state && state.currentIndex < state.bookIds.length - 1
? state.bookIds[state.currentIndex + 1]
: null;
});
readonly currentPosition = computed<{ current: number; total: number } | null>(() => {
const state = this.navigationState();
return state
? {
current: state.currentIndex + 1,
total: state.bookIds.length
}
: null;
});
setAvailableBookIds(bookIds: number[]): void {
this.availableBookIds = bookIds;
}
getAvailableBookIds(): number[] {
return this.availableBookIds;
this._availableBookIds.set(bookIds);
}
setNavigationContext(bookIds: number[], currentBookId: number): void {
const currentIndex = bookIds.indexOf(currentBookId);
if (currentIndex !== -1) {
this.navigationState$.next({bookIds, currentIndex});
this._navigationState.set({bookIds, currentIndex});
} else {
this.navigationState$.next(null);
this._navigationState.set(null);
}
}
getNavigationState(): Observable<BookNavigationState | null> {
return this.navigationState$.asObservable();
}
canNavigatePrevious(): boolean {
const state = this.navigationState$.value;
return state !== null && state.currentIndex > 0;
}
canNavigateNext(): boolean {
const state = this.navigationState$.value;
return state !== null && state.currentIndex < state.bookIds.length - 1;
}
getPreviousBookId(): number | null {
const state = this.navigationState$.value;
if (state && state.currentIndex > 0) {
return state.bookIds[state.currentIndex - 1];
}
return null;
}
getNextBookId(): number | null {
const state = this.navigationState$.value;
if (state && state.currentIndex < state.bookIds.length - 1) {
return state.bookIds[state.currentIndex + 1];
}
return null;
}
updateCurrentBook(bookId: number): void {
const state = this.navigationState$.value;
const state = this.navigationState();
if (state) {
const newIndex = state.bookIds.indexOf(bookId);
if (newIndex !== -1) {
this.navigationState$.next({
this._navigationState.set({
...state,
currentIndex: newIndex
});
}
}
}
getCurrentPosition(): { current: number; total: number } | null {
const state = this.navigationState$.value;
if (state) {
return {
current: state.currentIndex + 1,
total: state.bookIds.length
};
}
return null;
}
}
@@ -3,10 +3,32 @@ import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
import {Book, BookFileProgress, ReadStatus} from '../model/book.model';
import {BookStateService} from './book-state.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from '../model/book.model';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {
patchBooksInCache,
patchBookFieldsInCache,
} from './book-query-cache';
function getResetProgressFields(type: ResetProgressType): Partial<Book> {
if (type === ResetProgressTypes.KOREADER) {
return {koreaderProgress: undefined};
}
if (type === ResetProgressTypes.KOBO) {
return {koboProgress: undefined};
}
return {
epubProgress: undefined,
pdfProgress: undefined,
cbxProgress: undefined,
audiobookProgress: undefined,
};
}
@Injectable({
providedIn: 'root',
@@ -15,7 +37,7 @@ export class BookPatchService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private bookStateService = inject(BookStateService);
private queryClient = inject(QueryClient);
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number; bookFileId?: number }>();
@@ -28,7 +50,20 @@ export class BookPatchService {
prev.bookFileId === curr.bookFileId
),
exhaustMap(payload => {
const body: any = {
const body: {
bookId: number;
epubProgress: {
cfi: string;
href: string;
percentage: number;
};
fileProgress?: {
bookFileId: number;
positionData: string;
positionHref: string;
progressPercent: number;
};
} = {
bookId: payload.bookId,
epubProgress: {
cfi: payload.cfi,
@@ -36,7 +71,6 @@ export class BookPatchService {
percentage: payload.percentage
}
};
// Add file-level progress if bookFileId is provided
if (payload.bookFileId) {
body.fileProgress = {
bookFileId: payload.bookFileId,
@@ -62,31 +96,33 @@ export class BookPatchService {
};
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
tap(updatedBooks => {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
updatedBooks.forEach(updatedBook => {
const index = currentBooks.findIndex(b => b.id === updatedBook.id);
if (index !== -1) {
currentBooks[index] = updatedBook;
}
});
this.bookStateService.updateBookState({...currentState, books: [...currentBooks]});
patchBooksInCache(this.queryClient, updatedBooks);
})
);
}
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
const body: any = {
bookId: bookId,
const body: {
bookId: number;
pdfProgress: {
page: page,
percentage: percentage
page: number;
percentage: number;
};
fileProgress?: {
bookFileId: number;
positionData: string;
progressPercent: number;
};
} = {
bookId,
pdfProgress: {
page,
percentage
}
};
// Add file-level progress if bookFileId is provided
if (bookFileId) {
body.fileProgress = {
bookFileId: bookFileId,
bookFileId,
positionData: String(page),
progressPercent: percentage
};
@@ -99,17 +135,27 @@ export class BookPatchService {
}
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
const body: any = {
bookId: bookId,
const body: {
bookId: number;
cbxProgress: {
page: page,
percentage: percentage
page: number;
percentage: number;
};
fileProgress?: {
bookFileId: number;
positionData: string;
progressPercent: number;
};
} = {
bookId,
cbxProgress: {
page,
percentage
}
};
// Add file-level progress if bookFileId is provided
if (bookFileId) {
body.fileProgress = {
bookFileId: bookFileId,
bookFileId,
positionData: String(page),
progressPercent: percentage
};
@@ -117,38 +163,20 @@ export class BookPatchService {
return this.http.post<void>(`${this.url}/progress`, body);
}
/**
* Save file-level progress directly using the new API.
* This is the preferred method for per-file progress tracking.
*/
saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> {
const body = {
bookId: bookId,
fileProgress: fileProgress
};
return this.http.post<void>(`${this.url}/progress`, body);
return this.http.post<void>(`${this.url}/progress`, {
bookId,
fileProgress
});
}
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
const body = {
bookId: bookId,
dateFinished: dateFinished
};
return this.http.post<void>(`${this.url}/progress`, body).pipe(
return this.http.post<void>(`${this.url}/progress`, {
bookId,
dateFinished
}).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
if (currentState.books) {
const updatedBooks = currentState.books.map(book => {
if (book.id === bookId) {
return {...book, dateFinished: dateFinished || undefined};
}
return book;
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
}
patchBookFieldsInCache(this.queryClient, [{bookId, fields: {dateFinished: dateFinished || undefined}}]);
})
);
}
@@ -159,52 +187,31 @@ export class BookPatchService {
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
const progressReset: Partial<Book> =
type === 'KOREADER' ? {koreaderProgress: undefined} :
type === 'KOBO' ? {koboProgress: undefined} :
{epubProgress: undefined, pdfProgress: undefined, cbxProgress: undefined, audiobookProgress: undefined};
return {
...book,
...progressReset,
readStatus: response.readStatus,
readStatusModifiedTime: response.readStatusModifiedTime,
dateFinished: response.dateFinished
};
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
bookId: r.bookId,
fields: {
...getResetProgressFields(type),
readStatus: r.readStatus,
readStatusModifiedTime: r.readStatusModifiedTime,
dateFinished: r.dateFinished
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})));
})
);
}
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
const requestBody = {
bookIds: ids,
status: status
};
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/status`, requestBody).pipe(
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/status`, {
bookIds: ids,
status
}).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
readStatus: response.readStatus,
readStatusModifiedTime: response.readStatusModifiedTime,
dateFinished: response.dateFinished
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
bookId: r.bookId,
fields: {readStatus: r.readStatus, readStatusModifiedTime: r.readStatusModifiedTime, dateFinished: r.dateFinished}
})));
})
);
}
@@ -214,18 +221,10 @@ export class BookPatchService {
return this.http.post<PersonalRatingUpdateResponse[]>(`${this.url}/reset-personal-rating`, ids).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
personalRating: response.personalRating
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
bookId: r.bookId,
fields: {personalRating: r.personalRating}
})));
})
);
}
@@ -235,28 +234,20 @@ export class BookPatchService {
return this.http.put<PersonalRatingUpdateResponse[]>(`${this.url}/personal-rating`, {ids, rating}).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
personalRating: response.personalRating
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
bookId: r.bookId,
fields: {personalRating: r.personalRating}
})));
})
);
}
updateLastReadTime(bookId: number): void {
const timestamp = new Date().toISOString();
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book =>
book.id === bookId ? {...book, lastReadTime: timestamp} : book
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).map(book =>
book.id === bookId ? {...book, lastReadTime: timestamp} : book
)
);
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
}
@@ -0,0 +1,106 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {Book} from '../model/book.model';
import {
addBookToCache,
patchBooksInCache,
removeBookQueries,
removeBooksFromCache
} from './book-query-cache';
import {
BOOKS_QUERY_KEY,
bookDetailQueryKey,
bookDetailQueryPrefix,
bookRecommendationsQueryKey
} from './book-query-keys';
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
return {
id,
libraryId: 1,
libraryName: 'Test Library',
metadata: {
bookId: id,
title: `Book ${id}`
},
...overrides
};
}
describe('book-query-cache', () => {
let queryClient: QueryClient;
beforeEach(() => {
queryClient = new QueryClient();
});
it('adds new books and replaces existing entries by id', () => {
const firstBook = makeBook(1);
const secondBook = makeBook(2);
const updatedSecondBook = makeBook(2, {
libraryName: 'Updated Library',
metadata: {
bookId: 2,
title: 'Updated Book 2'
}
});
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook]);
addBookToCache(queryClient, secondBook);
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, secondBook]);
addBookToCache(queryClient, updatedSecondBook);
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
});
it('patches list entries and invalidates matching detail queries', () => {
const firstBook = makeBook(1);
const secondBook = makeBook(2);
const updatedSecondBook = makeBook(2, {
libraryName: 'Updated Library'
});
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook]);
patchBooksInCache(queryClient, [updatedSecondBook]);
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(1);
});
it('removes detail and recommendation queries for deleted books', () => {
const firstBook = makeBook(1);
const secondBook = makeBook(2);
queryClient.setQueryData(bookDetailQueryKey(1, false), firstBook);
queryClient.setQueryData(bookDetailQueryKey(1, true), firstBook);
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [secondBook]);
queryClient.setQueryData(bookDetailQueryKey(2, false), secondBook);
removeBookQueries(queryClient, [1]);
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
expect(queryClient.getQueryData(bookDetailQueryKey(1, true))).toBeUndefined();
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
expect(queryClient.getQueryData(bookDetailQueryKey(2, false))).toEqual(secondBook);
});
it('removes deleted books from the list cache and associated queries', () => {
const firstBook = makeBook(1);
const secondBook = makeBook(2);
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook]);
queryClient.setQueryData(bookDetailQueryKey(1, false), firstBook);
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [secondBook]);
removeBooksFromCache(queryClient, [1]);
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([secondBook]);
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
});
});
@@ -0,0 +1,85 @@
import {QueryClient} from '@tanstack/angular-query-experimental';
import {Book, BookMetadata} from '../model/book.model';
import {BOOKS_QUERY_KEY, bookDetailQueryPrefix, bookRecommendationsQueryPrefix} from './book-query-keys';
// --- Full invalidation (refetches from server) ---
export function invalidateBooksQuery(queryClient: QueryClient): void {
void queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
}
export function invalidateBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
invalidateBooksQuery(queryClient);
invalidateBookDetailQueries(queryClient, bookIds);
}
export function invalidateBookDetailQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
for (const bookId of new Set(bookIds)) {
void queryClient.invalidateQueries({queryKey: bookDetailQueryPrefix(bookId)});
}
}
export function removeBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
for (const bookId of new Set(bookIds)) {
queryClient.removeQueries({queryKey: bookDetailQueryPrefix(bookId)});
queryClient.removeQueries({queryKey: bookRecommendationsQueryPrefix(bookId)});
}
}
export function removeBooksFromCache(queryClient: QueryClient, bookIds: Iterable<number>): void {
const removedIds = new Set(bookIds);
if (removedIds.size === 0) {
return;
}
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).filter(book => !removedIds.has(book.id))
);
removeBookQueries(queryClient, removedIds);
}
// --- Surgical patches (updates cache directly, no list refetch) ---
export function addBookToCache(queryClient: QueryClient, book: Book): void {
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current => {
const books = current ?? [];
const exists = books.some(b => b.id === book.id);
return exists ? books.map(b => b.id === book.id ? book : b) : [...books, book];
});
}
export function patchBooksInCache(queryClient: QueryClient, updatedBooks: Book[]): void {
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).map(book => updatedMap.get(book.id) ?? book)
);
invalidateBookDetailQueries(queryClient, updatedBooks.map(b => b.id));
}
export function patchBookMetadataInCache(queryClient: QueryClient, bookId: number, metadata: BookMetadata): void {
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).map(book =>
book.id === bookId ? {...book, metadata} : book
)
);
invalidateBookDetailQueries(queryClient, [bookId]);
}
export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, updater: (book: Book) => Book): void {
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).map(book => book.id === bookId ? updater(book) : book)
);
invalidateBookDetailQueries(queryClient, [bookId]);
}
export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookId: number; fields: Partial<Book>}[]): void {
const updateMap = new Map(updates.map(u => [u.bookId, u.fields]));
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).map(book => {
const fields = updateMap.get(book.id);
return fields ? {...book, ...fields} : book;
})
);
invalidateBookDetailQueries(queryClient, updates.map(u => u.bookId));
}
@@ -0,0 +1,13 @@
export const BOOKS_QUERY_KEY = ['books'] as const;
export const bookDetailQueryKey = (bookId: number, withDescription: boolean) =>
['books', 'detail', bookId, withDescription] as const;
export const bookDetailQueryPrefix = (bookId: number) =>
['books', 'detail', bookId] as const;
export const bookRecommendationsQueryKey = (bookId: number, limit: number) =>
['books', 'recommendations', bookId, limit] as const;
export const bookRecommendationsQueryPrefix = (bookId: number) =>
['books', 'recommendations', bookId] as const;
@@ -1,70 +1,54 @@
import {inject, Injectable} from '@angular/core';
import {BookStateService} from './book-state.service';
import {Book, BookMetadata} from '../model/book.model';
import {Book} from '../model/book.model';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {
addBookToCache,
invalidateBookDetailQueries,
invalidateBooksQuery,
patchBooksInCache,
removeBookQueries,
} from './book-query-cache';
@Injectable({
providedIn: 'root',
})
export class BookSocketService {
private bookStateService = inject(BookStateService);
private queryClient = inject(QueryClient);
handleNewlyCreatedBook(book: Book): void {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = currentState.books ? [...currentState.books] : [];
const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id);
if (bookIndex > -1) {
updatedBooks[bookIndex] = book;
} else {
updatedBooks.push(book);
}
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
addBookToCache(this.queryClient, book);
}
handleRemovedBookIds(removedBookIds: number[]): void {
const currentState = this.bookStateService.getCurrentBookState();
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id));
this.bookStateService.updateBookState({...currentState, books: filteredBooks});
invalidateBooksQuery(this.queryClient);
removeBookQueries(this.queryClient, removedBookIds);
}
handleBookUpdate(updatedBook: Book): void {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book =>
book.id === updatedBook.id ? updatedBook : book
);
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
patchBooksInCache(this.queryClient, [updatedBook]);
}
handleMultipleBookUpdates(updatedBooks: Book[]): void {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
const mergedBooks = currentBooks.map(book =>
updatedMap.has(book.id) ? updatedMap.get(book.id)! : book
);
this.bookStateService.updateBookState({...currentState, books: mergedBooks});
patchBooksInCache(this.queryClient, updatedBooks);
}
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata): void {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
return book.id === bookId ? {...book, metadata: updatedMetadata} : book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
handleBookMetadataUpdate(bookId: number): void {
invalidateBooksQuery(this.queryClient);
invalidateBookDetailQueries(this.queryClient, [bookId]);
}
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
if (!patches || patches.length === 0) return;
const currentState = this.bookStateService.getCurrentBookState();
const books = currentState.books || [];
patches.forEach(p => {
const index = books.findIndex(b => b.id === p.id);
if (index !== -1 && books[index].metadata) {
books[index].metadata.coverUpdatedOn = p.coverUpdatedOn;
}
});
this.bookStateService.updateBookState({...currentState, books});
const patchMap = new Map(patches.map(p => [p.id, p.coverUpdatedOn]));
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).map(book => {
const coverUpdatedOn = patchMap.get(book.id);
return coverUpdatedOn && book.metadata
? {...book, metadata: {...book.metadata, coverUpdatedOn}}
: book;
})
);
invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id));
}
}
@@ -1,33 +0,0 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {BookState} from '../model/state/book-state.model';
@Injectable({
providedIn: 'root',
})
export class BookStateService {
private bookStateSubject = new BehaviorSubject<BookState>({
books: null,
loaded: false,
error: null,
});
public readonly bookState$ = this.bookStateSubject.asObservable();
getCurrentBookState(): BookState {
return this.bookStateSubject.value;
}
updateBookState(state: BookState): void {
this.bookStateSubject.next(state);
}
resetBookState(): void {
this.bookStateSubject.next({
books: null,
loaded: true,
error: null,
});
}
}
@@ -1,18 +1,27 @@
import {inject, Injectable} from '@angular/core';
import {first, Observable, of, throwError} from 'rxjs';
import {computed, effect, inject, Injectable} from '@angular/core';
import {first, from, lastValueFrom, Observable, throwError} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, tap} from 'rxjs/operators';
import {catchError, map, tap} from 'rxjs/operators';
import {Book, BookDeletionResponse, BookRecommendation, BookSetting, BookStatusUpdateResponse, BookType, CreatePhysicalBookRequest, PersonalRatingUpdateResponse, ReadStatus} from '../model/book.model';
import {BookState} from '../model/state/book-state.model';
import {API_CONFIG} from '../../../core/config/api-config';
import {MessageService} from 'primeng/api';
import {ResetProgressType} from '../../../shared/constants/reset-progress-type';
import {AuthService} from '../../../shared/service/auth.service';
import {Router} from '@angular/router';
import {BookStateService} from './book-state.service';
import {BookSocketService} from './book-socket.service';
import {BookPatchService} from './book-patch.service';
import {TranslocoService} from '@jsverse/transloco';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {
BOOKS_QUERY_KEY,
bookDetailQueryKey,
bookRecommendationsQueryKey,
} from './book-query-keys';
import {
invalidateBooksQuery,
patchBooksInCache,
removeBookQueries,
} from './book-query-cache';
@Injectable({
providedIn: 'root',
@@ -25,156 +34,139 @@ export class BookService {
private messageService = inject(MessageService);
private authService = inject(AuthService);
private router = inject(Router);
private bookStateService = inject(BookStateService);
private bookSocketService = inject(BookSocketService);
private bookPatchService = inject(BookPatchService);
private queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
private readonly token = this.authService.token;
private loading$: Observable<Book[]> | null = null;
private booksQuery = injectQuery(() => ({
...this.getBooksQueryOptions(),
enabled: !!this.token(),
}));
books = computed(() => this.booksQuery.data() ?? []);
/** Pre-computed unique metadata values for autocomplete across the app. */
readonly uniqueMetadata = computed(() => {
const books = this.books();
const authors = new Set<string>();
const categories = new Set<string>();
const moods = new Set<string>();
const tags = new Set<string>();
const publishers = new Set<string>();
const series = new Set<string>();
for (const book of books) {
const m = book.metadata;
if (!m) continue;
m.authors?.forEach(v => authors.add(v));
m.categories?.forEach(v => categories.add(v));
m.moods?.forEach(v => moods.add(v));
m.tags?.forEach(v => tags.add(v));
if (m.publisher) publishers.add(m.publisher);
if (m.seriesName) series.add(m.seriesName);
}
return {
authors: Array.from(authors),
categories: Array.from(categories),
moods: Array.from(moods),
tags: Array.from(tags),
publishers: Array.from(publishers),
series: Array.from(series),
};
});
booksError = computed<string | null>(() => {
if (!this.token() || !this.booksQuery.isError()) {
return null;
}
const error = this.booksQuery.error();
return error instanceof Error ? error.message : 'Failed to load books';
});
isBooksLoading = computed(() => !!this.token() && this.booksQuery.isPending());
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
effect(() => {
const token = this.token();
if (token === null) {
this.bookStateService.resetBookState();
this.loading$ = null;
} else {
const current = this.bookStateService.getCurrentBookState();
if (current.loaded && !current.books) {
this.bookStateService.updateBookState({
books: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
this.queryClient.removeQueries({queryKey: BOOKS_QUERY_KEY});
}
});
}
/*------------------ State Management ------------------*/
bookState$ = this.bookStateService.bookState$.pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchBooks().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
getCurrentBookState(): BookState {
return this.bookStateService.getCurrentBookState();
private getBooksQueryOptions() {
return queryOptions({
queryKey: BOOKS_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url))
});
}
private fetchBooks(): Observable<Book[]> {
return this.http.get<Book[]>(this.url).pipe(
map(bookList => {
this.bookStateService.updateBookState({
books: bookList,
loaded: true,
error: null,
});
return bookList;
}),
catchError(error => {
const curr = this.bookStateService.getCurrentBookState();
this.bookStateService.updateBookState({
books: curr.books,
loaded: true,
error: error.message,
});
throw error;
})
);
bookDetailQueryOptions(bookId: number, withDescription: boolean) {
return queryOptions({
queryKey: bookDetailQueryKey(bookId, withDescription),
queryFn: () => lastValueFrom(this.http.get<Book>(`${this.url}/${bookId}`, {
params: {
withDescription: withDescription.toString()
}
}))
});
}
refreshBooks(): void {
this.http.get<Book[]>(this.url).pipe(
tap(bookList => {
this.bookStateService.updateBookState({
books: bookList,
loaded: true,
error: null,
});
}),
catchError(error => {
this.bookStateService.updateBookState({
books: null,
loaded: true,
error: error.message,
});
return of(null);
})
).subscribe();
ensureBookDetail(bookId: number, withDescription: boolean): Promise<Book> {
return this.queryClient.ensureQueryData(this.bookDetailQueryOptions(bookId, withDescription));
}
removeBooksByLibraryId(libraryId: number): void {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId);
this.bookStateService.updateBookState({...currentState, books: filteredBooks});
private getBookRecommendationsQueryOptions(bookId: number, limit: number) {
return queryOptions({
queryKey: bookRecommendationsQueryKey(bookId, limit),
queryFn: () => lastValueFrom(this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
params: {limit: limit.toString()}
}))
});
}
removeBooksFromShelf(shelfId: number): void {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
const updatedBooks = currentBooks.map(book => ({
...book,
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}));
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
(current ?? []).map(book => ({
...book,
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}))
);
}
/*------------------ Book Retrieval ------------------*/
getBookByIdFromState(bookId: number): Book | undefined {
const currentState = this.bookStateService.getCurrentBookState();
return currentState.books?.find(book => +book.id === +bookId);
findBookById(bookId: number): Book | undefined {
return this.books().find(book => +book.id === +bookId);
}
getBooksByIdsFromState(bookIds: number[]): Book[] {
const currentState = this.bookStateService.getCurrentBookState();
if (!currentState.books || bookIds.length === 0) return [];
getBooksByIds(bookIds: number[]): Book[] {
if (bookIds.length === 0) return [];
const idSet = new Set(bookIds.map(id => +id));
return currentState.books.filter(book => idSet.has(+book.id));
}
getBookByIdFromAPI(bookId: number, withDescription: boolean): Observable<Book> {
return this.http.get<Book>(`${this.url}/${bookId}`, {
params: {
withDescription: withDescription.toString()
}
});
return this.books().filter(book => idSet.has(+book.id));
}
getBooksInSeries(bookId: number): Observable<Book[]> {
return this.bookStateService.bookState$.pipe(
filter(state => state.loaded),
first(),
map(state => {
const allBooks = state.books || [];
const currentBook = allBooks.find(b => b.id === bookId);
if (!currentBook || !currentBook.metadata?.seriesName) {
return from(this.queryClient.ensureQueryData(this.getBooksQueryOptions())).pipe(
map(books => {
const currentBook = books.find(book => book.id === bookId);
if (!currentBook?.metadata?.seriesName) {
return [];
}
const seriesName = currentBook.metadata.seriesName.toLowerCase();
return allBooks.filter(b => b.metadata?.seriesName?.toLowerCase() === seriesName);
})
return books.filter(book => book.metadata?.seriesName?.toLowerCase() === seriesName);
}),
first()
);
}
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
params: {limit: limit.toString()}
});
return from(this.queryClient.ensureQueryData(this.getBookRecommendationsQueryOptions(bookId, limit)));
}
/*------------------ Book Operations ------------------*/
@@ -185,16 +177,9 @@ export class BookService {
return this.http.delete<BookDeletionResponse>(this.url, {params}).pipe(
tap(response => {
const currentState = this.bookStateService.getCurrentBookState();
const remainingBooks = (currentState.books || []).filter(
book => !ids.has(book.id)
);
this.bookStateService.updateBookState({
books: remainingBooks,
loaded: true,
error: null,
});
const deletedIds = response.deleted.length > 0 ? response.deleted : idList;
invalidateBooksQuery(this.queryClient);
removeBookQueries(this.queryClient, deletedIds);
if (response.failedFileDeletions?.length > 0) {
this.messageService.add({
@@ -222,24 +207,13 @@ export class BookService {
}
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
return this.bookPatchService.updateBookShelves(bookIds, shelvesToAssign, shelvesToUnassign).pipe(
catchError(error => {
const currentState = this.bookStateService.getCurrentBookState();
this.bookStateService.updateBookState({...currentState, error: error.message});
throw error;
})
);
return this.bookPatchService.updateBookShelves(bookIds, shelvesToAssign, shelvesToUnassign);
}
createPhysicalBook(request: CreatePhysicalBookRequest): Observable<Book> {
return this.http.post<Book>(`${this.url}/physical`, request).pipe(
tap(newBook => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = [...(currentState.books || []), newBook];
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
invalidateBooksQuery(this.queryClient);
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.bookService.toast.physicalBookCreatedSummary'),
@@ -260,9 +234,7 @@ export class BookService {
togglePhysicalFlag(bookId: number, physical: boolean): Observable<Book> {
return this.http.patch<Book>(`${this.url}/${bookId}/physical`, null, {params: {physical}}).pipe(
tap(updatedBook => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(b => b.id === bookId ? {...b, isPhysical: physical} : b);
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
patchBooksInCache(this.queryClient, [updatedBook]);
})
);
}
@@ -270,9 +242,7 @@ export class BookService {
/*------------------ Reading & Viewer Settings ------------------*/
readBook(bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
const book = this.bookStateService
.getCurrentBookState()
.books?.find(b => b.id === bookId);
const book = this.findBookById(bookId);
if (!book) {
console.error('Book not found');
@@ -283,7 +253,7 @@ export class BookService {
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;
let baseUrl: string | null = null;
let queryParams: Record<string, any> = {};
const queryParams: Partial<{streaming: true; bookType: BookType}> = {};
switch (bookType) {
case 'PDF':
@@ -389,6 +359,10 @@ export class BookService {
this.bookSocketService.handleMultipleBookUpdates(updatedBooks);
}
handleBookMetadataUpdate(bookId: number): void {
this.bookSocketService.handleBookMetadataUpdate(bookId);
}
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
this.bookSocketService.handleMultipleBookCoverPatches(patches);
}
@@ -1,22 +1,27 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {LibraryHealthService} from './library-health.service';
import {HttpClient} from '@angular/common/http';
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
import {of, Subject} from 'rxjs';
import {IMessage} from '@stomp/rx-stomp';
import {provideTanStackQuery, QueryClient} from '@tanstack/angular-query-experimental';
import {LibraryHealthService} from './library-health.service';
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
describe('LibraryHealthService', () => {
let service: LibraryHealthService;
let queryClient: QueryClient;
let httpGetSpy: ReturnType<typeof vi.fn>;
let wsSubject: Subject<IMessage>;
beforeEach(() => {
httpGetSpy = vi.fn().mockReturnValue(of({}));
wsSubject = new Subject<IMessage>();
queryClient = new QueryClient();
TestBed.configureTestingModule({
providers: [
provideTanStackQuery(queryClient),
LibraryHealthService,
{provide: HttpClient, useValue: {get: httpGetSpy}},
{provide: RxStompService, useValue: {watch: vi.fn(() => wsSubject.asObservable())}},
@@ -26,66 +31,52 @@ describe('LibraryHealthService', () => {
service = TestBed.inject(LibraryHealthService);
});
it('should fetch initial health on initialize', () => {
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
async function initializeService(): Promise<void> {
const fetchQuerySpy = vi.spyOn(queryClient, 'fetchQuery');
service.initialize();
await fetchQuerySpy.mock.results[0]?.value;
}
expect(httpGetSpy).toHaveBeenCalled();
it('fetches initial health on initialize', async () => {
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
await initializeService();
expect(httpGetSpy).toHaveBeenCalledOnce();
expect(service.health()).toEqual({1: true, 2: false});
});
it('should emit unhealthy for a library with false health', () => {
it('reports unhealthy for a library with false health', async () => {
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
service.initialize();
const results: boolean[] = [];
service.isUnhealthy$(2).subscribe(v => results.push(v));
await initializeService();
expect(results).toContain(true);
expect(service.isUnhealthy(2)).toBe(true);
});
it('should emit healthy for a library with true health', () => {
it('reports healthy for a library with true health', async () => {
httpGetSpy.mockReturnValue(of({1: true}));
service.initialize();
const results: boolean[] = [];
service.isUnhealthy$(1).subscribe(v => results.push(v));
await initializeService();
expect(results[results.length - 1]).toBe(false);
expect(service.isUnhealthy(1)).toBe(false);
});
it('should emit false for unknown library', () => {
it('reports false for an unknown library', async () => {
httpGetSpy.mockReturnValue(of({}));
service.initialize();
const results: boolean[] = [];
service.isUnhealthy$(99).subscribe(v => results.push(v));
await initializeService();
expect(results[results.length - 1]).toBe(false);
expect(service.isUnhealthy(99)).toBe(false);
});
it('should update state from websocket messages', () => {
it('updates state from websocket messages', async () => {
httpGetSpy.mockReturnValue(of({1: true}));
service.initialize();
const results: boolean[] = [];
service.isUnhealthy$(1).subscribe(v => results.push(v));
await initializeService();
wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage);
expect(results[results.length - 1]).toBe(true);
});
it('should use distinctUntilChanged to avoid duplicate emissions', () => {
httpGetSpy.mockReturnValue(of({1: true}));
service.initialize();
const results: boolean[] = [];
service.isUnhealthy$(1).subscribe(v => results.push(v));
// Same state again via websocket
wsSubject.next({body: JSON.stringify({libraryHealth: {1: true}})} as IMessage);
wsSubject.next({body: JSON.stringify({libraryHealth: {1: true}})} as IMessage);
expect(results.length).toBe(1);
expect(service.isUnhealthy(1)).toBe(true);
expect(service.health()).toEqual({1: false});
});
});
@@ -1,33 +1,43 @@
import {inject, Injectable} from '@angular/core';
import {computed, inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import {distinctUntilChanged, map} from 'rxjs/operators';
import {lastValueFrom} from 'rxjs';
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
const LIBRARY_HEALTH_QUERY_KEY = ['libraryHealth'] as const;
@Injectable({providedIn: 'root'})
export class LibraryHealthService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`;
private http = inject(HttpClient);
private rxStompService = inject(RxStompService);
private queryClient = inject(QueryClient);
private healthSubject = new BehaviorSubject<Record<number, boolean>>({});
private healthQuery = injectQuery(() => ({
...this.getHealthQueryOptions(),
enabled: false, // manually triggered via initialize()
}));
health = computed(() => this.healthQuery.data() ?? {});
private getHealthQueryOptions() {
return queryOptions({
queryKey: LIBRARY_HEALTH_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<Record<number, boolean>>(this.url))
});
}
initialize(): void {
this.http.get<Record<number, boolean>>(this.url).subscribe(health => {
this.healthSubject.next(health);
});
void this.queryClient.fetchQuery(this.getHealthQueryOptions());
this.rxStompService.watch('/topic/library-health').subscribe(msg => {
const payload = JSON.parse(msg.body);
this.healthSubject.next(payload.libraryHealth);
this.queryClient.setQueryData(LIBRARY_HEALTH_QUERY_KEY, payload.libraryHealth);
});
}
isUnhealthy$(libraryId: number): Observable<boolean> {
return this.healthSubject.pipe(
map(health => health[libraryId] === false),
distinctUntilChanged()
);
isUnhealthy(libraryId: number): boolean {
return this.health()[libraryId] === false;
}
}
@@ -0,0 +1,4 @@
export const LIBRARIES_QUERY_KEY = ['libraries'] as const;
export const libraryFormatCountsQueryKey = (libraryId: number) =>
['libraries', 'format-counts', libraryId] as const;
@@ -1,13 +1,15 @@
import {inject, Injectable} from '@angular/core';
import {computed, effect, inject, Injectable, signal} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, distinctUntilChanged, finalize, map, shareReplay, tap} from 'rxjs/operators';
import {from, lastValueFrom, Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {Library} from '../model/library.model';
import {LibraryState} from '../model/state/library-state.model';
import {BookService} from './book.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {AuthService} from '../../../shared/service/auth.service';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys';
@Injectable({providedIn: 'root'})
export class LibraryService {
@@ -15,72 +17,56 @@ export class LibraryService {
private http = inject(HttpClient);
private bookService = inject(BookService);
private authService = inject(AuthService);
private queryClient = inject(QueryClient);
private readonly token = this.authService.token;
private libraryStateSubject = new BehaviorSubject<LibraryState>({
libraries: null,
loaded: false,
error: null,
});
private largeLibraryLoadingSubject = new BehaviorSubject<{ isLoading: boolean; expectedCount: number }>({
readonly largeLibraryLoading = signal<{ isLoading: boolean; expectedCount: number }>({
isLoading: false,
expectedCount: 0
});
largeLibraryLoading$ = this.largeLibraryLoadingSubject.asObservable();
private librariesQuery = injectQuery(() => ({
...this.getLibrariesQueryOptions(),
enabled: !!this.token(),
}));
private loading$: Observable<Library[]> | null = null;
libraries = computed(() => this.librariesQuery.data() ?? []);
librariesError = computed<string | null>(() => {
if (!this.token() || !this.librariesQuery.isError()) {
return null;
}
const error = this.librariesQuery.error();
return error instanceof Error ? error.message : 'Failed to load libraries';
});
isLibrariesLoading = computed(() => !!this.token() && this.librariesQuery.isPending());
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
effect(() => {
const token = this.token();
if (token === null) {
this.libraryStateSubject.next({
libraries: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.libraryStateSubject.value;
if (current.loaded && !current.libraries) {
this.libraryStateSubject.next({
libraries: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
this.queryClient.removeQueries({queryKey: LIBRARIES_QUERY_KEY});
}
});
}
libraryState$ = this.libraryStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchLibraries().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
private getLibrariesQueryOptions() {
return queryOptions({
queryKey: LIBRARIES_QUERY_KEY,
queryFn: async () => {
const libraries = await lastValueFrom(this.http.get<Library[]>(this.url));
return this.sortLibraries(libraries);
}
})
);
});
}
private fetchLibraries(): Observable<Library[]> {
return this.http.get<Library[]>(this.url).pipe(
tap(libs => this.libraryStateSubject.next({
libraries: this.sortLibraries(libs),
loaded: true,
error: null,
})),
catchError(err => {
const current = this.libraryStateSubject.value;
this.libraryStateSubject.next({libraries: current.libraries, loaded: true, error: err.message});
throw err;
})
);
private getLibraryFormatCountsQueryOptions(libraryId: number) {
return queryOptions({
queryKey: libraryFormatCountsQueryKey(libraryId),
queryFn: () => lastValueFrom(this.http.get<Record<string, number>>(`${this.url}/${libraryId}/format-counts`))
});
}
scanLibraryPaths(lib: Library): Observable<number> {
@@ -89,23 +75,17 @@ export class LibraryService {
createLibrary(lib: Library): Observable<Library> {
return this.http.post<Library>(this.url, lib).pipe(
map(created => {
const curr = this.libraryStateSubject.value;
const updated = curr.libraries ? [...curr.libraries, created] : [created];
this.libraryStateSubject.next({...curr, libraries: this.sortLibraries(updated)});
return created;
tap(() => {
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
})
);
}
updateLibrary(lib: Library, id?: number): Observable<Library> {
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: this.sortLibraries(list)});
this.bookService.refreshBooks();
return updated;
tap(() => {
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
})
);
}
@@ -113,25 +93,17 @@ export class LibraryService {
deleteLibrary(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
this.bookService.removeBooksByLibraryId(id);
const curr = this.libraryStateSubject.value;
const filtered = curr.libraries?.filter(l => l.id !== id) || [];
this.libraryStateSubject.next({...curr, libraries: filtered});
}),
catchError(err => {
const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...curr, error: err.message});
return of();
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
this.queryClient.removeQueries({queryKey: libraryFormatCountsQueryKey(id), exact: true});
})
);
}
refreshLibrary(id: number): Observable<void> {
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
catchError(err => {
const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...curr, error: err.message});
throw err;
tap(() => {
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
})
);
}
@@ -140,42 +112,34 @@ export class LibraryService {
return this.http
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
.pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: this.sortLibraries(list)});
return updated;
tap(() => {
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
})
);
}
doesLibraryExistByName(name: string): boolean {
return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name);
return this.libraries().some(library => library.name === name);
}
findLibraryById(id: number): Library | undefined {
return this.libraryStateSubject.value.libraries?.find(l => l.id === id);
return this.libraries().find(library => library.id === id);
}
getLibrariesFromState(): Library[] {
return this.libraryStateSubject.value.libraries || [];
}
getBookCount(libraryId: number): Observable<number> {
return this.bookService.bookState$.pipe(
map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
);
getBookCountValue(libraryId: number): number {
return this.bookService.books().filter(book => book.libraryId === libraryId).length;
}
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
this.largeLibraryLoadingSubject.next({ isLoading, expectedCount });
this.largeLibraryLoading.set({ isLoading, expectedCount });
}
getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> {
return this.http.get<Record<string, number>>(`${this.url}/${libraryId}/format-counts`);
return from(this.queryClient.ensureQueryData(this.getLibraryFormatCountsQueryOptions(libraryId)));
}
private sortLibraries(libraries: Library[]): Library[] {
return [...libraries].sort((a, b) => a.name.localeCompare(b.name));
}
}
@@ -1,14 +1,17 @@
import {inject, Injectable} from '@angular/core';
import {computed, effect, inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, combineLatest, Observable, of} from 'rxjs';
import {tap, catchError, map, shareReplay, finalize} from 'rxjs/operators';
import {lastValueFrom, Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {Shelf} from '../model/shelf.model';
import {ShelfState} from '../model/state/shelf-state.model';
import {BookService} from './book.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {Book} from '../model/book.model';
import {UserService} from '../../settings/user-management/user.service';
import {AuthService} from '../../../shared/service/auth.service';
const SHELVES_QUERY_KEY = ['shelves'] as const;
@Injectable({providedIn: 'root'})
export class ShelfService {
@@ -16,65 +19,60 @@ export class ShelfService {
private http = inject(HttpClient);
private bookService = inject(BookService);
private userService = inject(UserService);
private authService = inject(AuthService);
private queryClient = inject(QueryClient);
private readonly token = this.authService.token;
private shelfStateSubject = new BehaviorSubject<ShelfState>({
shelves: null,
loaded: false,
error: null,
private shelvesQuery = injectQuery(() => ({
...this.getShelvesQueryOptions(),
enabled: !!this.token(),
}));
shelves = computed(() => this.shelvesQuery.data() ?? []);
shelvesError = computed<string | null>(() => {
if (!this.token() || !this.shelvesQuery.isError()) {
return null;
}
const error = this.shelvesQuery.error();
return error instanceof Error ? error.message : 'Failed to load shelves';
});
private loading$: Observable<Shelf[]> | null = null;
isShelvesLoading = computed(() => !!this.token() && this.shelvesQuery.isPending());
shelfState$ = this.shelfStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchShelves().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private fetchShelves(): Observable<Shelf[]> {
return this.http.get<Shelf[]>(this.url).pipe(
tap(shelves => this.shelfStateSubject.next({shelves, loaded: true, error: null})),
catchError(err => {
const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
throw err;
})
);
}
public reloadShelves(): void {
this.fetchShelves().subscribe({
next: () => {
},
error: () => {
constructor() {
effect(() => {
const token = this.token();
if (token === null) {
this.queryClient.removeQueries({queryKey: SHELVES_QUERY_KEY});
}
});
}
private getShelvesQueryOptions() {
return queryOptions({
queryKey: SHELVES_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<Shelf[]>(this.url))
});
}
reloadShelves(): void {
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
}
createShelf(shelf: Shelf): Observable<Shelf> {
return this.http.post<Shelf>(this.url, shelf).pipe(
map(newShelf => {
const curr = this.shelfStateSubject.value;
const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
this.shelfStateSubject.next({...curr, shelves: updated});
return newShelf;
tap(() => {
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
})
);
}
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
map(updated => {
const curr = this.shelfStateSubject.value;
const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated];
this.shelfStateSubject.next({...curr, shelves: list});
return updated;
tap(() => {
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
})
);
}
@@ -83,56 +81,33 @@ export class ShelfService {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
this.bookService.removeBooksFromShelf(id);
const curr = this.shelfStateSubject.value;
const filtered = curr.shelves?.filter(s => s.id !== id) || [];
this.shelfStateSubject.next({...curr, shelves: filtered});
}),
catchError(err => {
const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({...curr, error: err.message});
return of();
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
})
);
}
getShelfById(id: number): Shelf | undefined {
return this.shelfStateSubject.value.shelves?.find(s => s.id === id);
}
getBookCountValue(shelfId: number): number {
const shelf = this.shelves().find(currentShelf => currentShelf.id === shelfId);
if (!shelf) return 0;
getShelvesFromState(): Shelf[] {
return this.shelfStateSubject.value.shelves ?? [];
}
const currentUserId = this.userService.getCurrentUser()?.id;
const isOwner = currentUserId === shelf.userId;
getBookCount(shelfId: number): Observable<number> {
return combineLatest([
this.shelfState$,
this.userService.userState$,
this.bookService.bookState$
]).pipe(
map(([shelfState, userState, bookState]) => {
const shelf = shelfState.shelves?.find(s => s.id === shelfId);
if (!shelf) return 0;
if (isOwner) {
return this.bookService.books().filter(book =>
book.shelves?.some(currentShelf => currentShelf.id === shelfId)
).length;
}
const isOwner = userState.user?.id === shelf.userId;
if (isOwner) {
return (bookState.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length;
} else {
return shelf.bookCount || 0;
}
})
);
return shelf.bookCount || 0;
}
getBooksOnShelf(shelfId: number): Observable<Book[]> {
return this.http.get<Book[]>(`${this.url}/${shelfId}/books`);
}
getUnshelvedBookCount(): Observable<number> {
return this.bookService.bookState$.pipe(
map(state =>
(state.books || []).filter(b => !b.shelves || b.shelves.length === 0).length
)
);
getUnshelvedBookCountValue(): number {
return this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length;
}
}
@@ -1,7 +1,5 @@
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Component, DestroyRef, effect, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {filter} from 'rxjs/operators';
import {Button} from 'primeng/button';
import {NgClass} from '@angular/common';
import {Tooltip} from 'primeng/tooltip';
@@ -79,18 +77,15 @@ export class BookdropFileMetadataPickerComponent implements OnInit {
metadataFieldsBottom: MetadataFieldConfig[] = getBottomFields();
private readonly syncProviderFieldsEffect = effect(() => {
const settings = this.appSettingsService.appSettings();
if (settings?.metadataProviderSpecificFields) {
this.enabledProviderFields = settings.metadataProviderSpecificFields;
this.metadataFieldsBottom = getBottomFields(this.enabledProviderFields);
}
});
ngOnInit(): void {
this.appSettingsService.appSettings$
.pipe(
filter(settings => !!settings?.metadataProviderSpecificFields),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(settings => {
if (settings?.metadataProviderSpecificFields) {
this.enabledProviderFields = settings.metadataProviderSpecificFields;
this.metadataFieldsBottom = getBottomFields(this.enabledProviderFields);
}
});
}
copyMissing(): void {
@@ -1,6 +1,6 @@
import {Component, DestroyRef, inject, OnInit, QueryList, ViewChildren} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {filter, startWith, take, tap} from 'rxjs/operators';
import {startWith, tap} from 'rxjs/operators';
import {PageTitleService} from "../../../../shared/service/page-title.service";
import {BookdropFile, BookdropFinalizePayload, BookdropFinalizeResult, BookdropService, FileExtractionResult, BulkEditRequest as BackendBulkEditRequest, BulkEditResult as BackendBulkEditResult} from '../../service/bookdrop.service';
@@ -14,10 +14,10 @@ import {Select} from 'primeng/select';
import {Tooltip} from 'primeng/tooltip';
import {Divider} from 'primeng/divider';
import {ConfirmationService, MessageService} from 'primeng/api';
import {Observable, Subscription} from 'rxjs';
import {Subscription} from 'rxjs';
import {InputGroup} from 'primeng/inputgroup';
import {InputGroupAddonModule} from 'primeng/inputgroupaddon';
import {AppSettings} from '../../../../shared/model/app-settings.model';
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
import {BookMetadata} from '../../../book/model/book.model';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
@@ -79,14 +79,12 @@ export class BookdropFileReviewComponent implements OnInit {
@ViewChildren('metadataPicker') metadataPickers!: QueryList<BookdropFileMetadataPickerComponent>;
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
private routerSub!: Subscription;
uploadPattern = '';
_defaultLibraryId: string | null = null;
defaultPathId: string | null = null;
libraries: Library[] = [];
bookdropFileUis: BookdropFileUI[] = [];
fileUiCache: Record<number, BookdropFileUI> = {};
copiedFlags: Record<number, boolean> = {};
@@ -111,16 +109,10 @@ export class BookdropFileReviewComponent implements OnInit {
}))
.subscribe();
this.libraryService.libraryState$
.subscribe(state => {
this.libraries = state.libraries ?? [];
});
this.appSettings$
.pipe(filter(Boolean), take(1))
.subscribe(settings => {
this.uploadPattern = settings?.uploadPattern ?? '';
});
const settings = this.appSettingsService.appSettings();
if (settings) {
this.uploadPattern = settings.uploadPattern ?? '';
}
}
get defaultLibraryId() {
@@ -137,6 +129,10 @@ export class BookdropFileReviewComponent implements OnInit {
}
}
get libraries(): Library[] {
return this.libraryService.libraries();
}
get libraryOptions() {
if (!this.libraries) return [];
return this.libraries.map(lib => ({label: lib.name, value: String(lib.id ?? '')}));
@@ -278,7 +274,7 @@ export class BookdropFileReviewComponent implements OnInit {
}
copyMetadata(): void {
const files = this.getSelectedFiles().map(fileUi => {
this.getSelectedFiles().forEach(fileUi => {
const cachedfUi = this.fileUiCache[fileUi.file.id];
const fetched = cachedfUi.file.fetchedMetadata;
const form = cachedfUi.metadataForm;
@@ -299,7 +295,7 @@ export class BookdropFileReviewComponent implements OnInit {
resetMetadata(): void {
const selectedFiles = this.getSelectedFiles();
const files = selectedFiles.map(fileUi => {
selectedFiles.forEach(fileUi => {
const original = fileUi.file.originalMetadata;
fileUi.metadataForm.patchValue({
title: original?.title || null,
@@ -1,6 +1,6 @@
import {inject, Injectable, OnDestroy} from '@angular/core';
import {effect, inject, Injectable, OnDestroy} from '@angular/core';
import {BehaviorSubject, Subscription} from 'rxjs';
import {map, filter, take} from 'rxjs/operators';
import {map} from 'rxjs/operators';
import {BookdropFileApiService} from './bookdrop-file-api.service';
import {AuthService} from '../../../shared/service/auth.service';
import {UserService} from '../../settings/user-management/user.service';
@@ -30,21 +30,20 @@ export class BookdropFileService implements OnDestroy {
private authService = inject(AuthService);
private subscriptions = new Subscription();
private userService = inject(UserService);
private hasInitialized = false;
constructor() {
this.userService.userState$
.pipe(
filter(state => state.loaded && !!state.user),
take(1)
)
.subscribe(state => {
const user = state.user!;
if (user.permissions.admin || user.permissions.canAccessBookdrop) {
this.authService.token$
.pipe(filter(t => !!t), take(1))
.subscribe(() => this.refresh());
}
});
effect(() => {
const user = this.userService.currentUser();
if (this.hasInitialized || !user) {
return;
}
this.hasInitialized = true;
if ((user.permissions.admin || user.permissions.canAccessBookdrop) && this.authService.token()) {
this.refresh();
}
});
}
handleIncomingFile(summary: BookdropFileNotification): void {
@@ -28,9 +28,10 @@
<div class="scroller-fields">
<div class="scroller-field" [class.expanded]="scroller.type !== 'magicShelf'">
<label>{{ t('type') }}</label>
<label [for]="'dashboard-scroller-type-' + scroller.id">{{ t('type') }}</label>
<p-select
fluid
[inputId]="'dashboard-scroller-type-' + scroller.id"
[options]="availableScrollerTypes"
[(ngModel)]="scroller.type"
(onChange)="onScrollerTypeChange(scroller)"
@@ -41,10 +42,11 @@
@if (scroller.type === 'magicShelf') {
<div class="scroller-field">
<label>{{ t('magicShelf') }}</label>
<label [for]="'dashboard-scroller-magic-shelf-' + scroller.id">{{ t('magicShelf') }}</label>
<p-select
fluid
[options]="(magicShelves$ | async)!"
[inputId]="'dashboard-scroller-magic-shelf-' + scroller.id"
[options]="magicShelves()"
[(ngModel)]="scroller.magicShelfId"
[placeholder]="t('selectMagicShelf')"
appendTo="body">
@@ -52,9 +54,10 @@
</div>
<div class="scroller-field">
<label>{{ t('sortField') }}</label>
<label [for]="'dashboard-scroller-sort-field-' + scroller.id">{{ t('sortField') }}</label>
<p-select
fluid
[inputId]="'dashboard-scroller-sort-field-' + scroller.id"
[options]="sortFieldOptions"
[(ngModel)]="scroller.sortField"
[placeholder]="t('selectField')"
@@ -63,9 +66,10 @@
</div>
<div class="scroller-field">
<label>{{ t('direction') }}</label>
<label [for]="'dashboard-scroller-sort-direction-' + scroller.id">{{ t('direction') }}</label>
<p-select
fluid
[inputId]="'dashboard-scroller-sort-direction-' + scroller.id"
[options]="sortDirectionOptions"
[(ngModel)]="scroller.sortDirection"
[placeholder]="t('selectDirection')"
@@ -76,9 +80,10 @@
</div>
<div class="scroller-field max-items-field">
<label>{{ t('maxItems') }}</label>
<label [for]="'dashboard-scroller-max-items-' + scroller.id">{{ t('maxItems') }}</label>
<p-inputNumber
fluid
[inputId]="'dashboard-scroller-max-items-' + scroller.id"
[(ngModel)]="scroller.maxItems"
[min]="MIN_ITEMS"
[max]="MAX_ITEMS"
@@ -1,5 +1,5 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Component, computed, effect, inject} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@@ -11,7 +11,6 @@ import {InputNumberModule} from 'primeng/inputnumber';
import {DashboardConfig, ScrollerConfig, ScrollerType} from '../../models/dashboard-config.model';
import {DashboardConfigService} from '../../services/dashboard-config.service';
import {MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
import {map} from 'rxjs/operators';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
export const MAX_SCROLLERS = 5;
@@ -36,49 +35,48 @@ export const MAX_ITEMS = 20;
templateUrl: './dashboard-settings.component.html',
styleUrls: ['./dashboard-settings.component.scss']
})
export class DashboardSettingsComponent implements OnInit {
export class DashboardSettingsComponent {
private configService = inject(DashboardConfigService);
private dialogRef = inject(DynamicDialogRef);
private magicShelfService = inject(MagicShelfService);
private translocoService = inject(TranslocoService);
private destroyRef = inject(DestroyRef);
private readonly activeLanguage = toSignal(this.translocoService.langChanges$, {
initialValue: this.translocoService.getActiveLang()
});
config!: DashboardConfig;
config: DashboardConfig = structuredClone(this.configService.config());
availableScrollerTypes: {label: string; value: ScrollerType}[] = [];
sortFieldOptions: {label: string; value: string}[] = [];
sortDirectionOptions: {label: string; value: string}[] = [];
magicShelves$ = this.magicShelfService.shelvesState$.pipe(
map(state => (state.shelves || []).map(shelf => ({
magicShelves = computed(() =>
this.magicShelfService.shelves().map(shelf => ({
label: shelf.name,
value: shelf.id!
})))
}))
);
private magicShelvesMap = new Map<number, string>();
private magicShelvesMap = computed(() => {
const shelfMap = new Map<number, string>();
this.magicShelfService.shelves().forEach(shelf => {
if (shelf.id) {
shelfMap.set(shelf.id, shelf.name);
}
});
return shelfMap;
});
readonly MIN_ITEMS = MIN_ITEMS;
readonly MAX_ITEMS = MAX_ITEMS;
ngOnInit(): void {
this.translocoService.langChanges$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.buildTranslatedOptions());
private readonly syncTranslatedOptionsEffect = effect(() => {
this.activeLanguage();
this.buildTranslatedOptions();
});
this.configService.config$.subscribe(config => {
this.config = JSON.parse(JSON.stringify(config));
});
this.magicShelfService.shelvesState$.subscribe(state => {
this.magicShelvesMap.clear();
(state.shelves || []).forEach(shelf => {
if (shelf.id) {
this.magicShelvesMap.set(shelf.id, shelf.name);
}
});
});
}
private readonly syncConfigEffect = effect(() => {
this.config = structuredClone(this.configService.config());
});
private buildTranslatedOptions(): void {
const t = (key: string) => this.translocoService.translate(`dashboard.settings.${key}`);
@@ -119,7 +117,7 @@ export class DashboardSettingsComponent implements OnInit {
getScrollerTitle(scroller: ScrollerConfig): string {
if (scroller.type === ScrollerType.MAGIC_SHELF && scroller.magicShelfId) {
return this.magicShelvesMap.get(scroller.magicShelfId) || 'dashboard.scroller.magicShelf';
return this.magicShelvesMap().get(scroller.magicShelfId) || 'dashboard.scroller.magicShelf';
}
switch (scroller.type) {
@@ -1,6 +1,6 @@
<ng-container *transloco="let t; prefix: 'dashboard.main'">
<div class="dashboard-container">
@if ((bookState$ | async)?.loaded === false) {
@if (isBooksLoading()) {
<div class="loading-state">
<p-progressSpinner
class="spinner center-spinner"
@@ -10,13 +10,12 @@
animationDuration="1.5s">
</p-progressSpinner>
</div>
}
@if ((bookState$ | async)?.loaded === true) {
} @else {
<div class="dashboard">
<div class="dashboard-inner">
@if (isLibrariesEmpty$ | async) {
@if (isLibrariesEmpty()) {
<div class="dashboard-no-library">
@if ((userService.userState$ | async)?.user?.permissions; as permissions) {
@if (userService.currentUser()?.permissions; as permissions) {
<div>
@if (permissions.admin || permissions.canManageLibrary) {
<div>
@@ -51,7 +50,7 @@
</p-button>
</div>
@if (dashboardConfig$ | async; as config) {
@if (dashboardConfig(); as config) {
@for (scroller of config.scrollers; track scroller.id) {
@if (scroller.enabled) {
<app-dashboard-scroller
@@ -59,7 +58,7 @@
[title]="scroller.title"
[isMagicShelf]="scroller.type === ScrollerType.MAGIC_SHELF"
[useSquareCovers]="scroller.type === ScrollerType.LAST_LISTENED"
[books]="getBooksForScroller(scroller) | async">
[books]="getBooksForScroller(scroller)">
</app-dashboard-scroller>
}
}
@@ -1,13 +1,7 @@
import {Component, inject, OnInit} from '@angular/core';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {LibraryService} from '../../../book/service/library.service';
import {Observable} from 'rxjs';
import {map, shareReplay, switchMap} from 'rxjs/operators';
import {Component, computed, inject, OnInit} from '@angular/core';
import {Button} from 'primeng/button';
import {AsyncPipe} from '@angular/common';
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
import {BookService} from '../../../book/service/book.service';
import {BookState} from '../../../book/model/state/book-state.model';
import {Book, ReadStatus} from '../../../book/model/book.model';
import {UserService} from '../../../settings/user-management/user.service';
import {ProgressSpinner} from 'primeng/progressspinner';
@@ -20,8 +14,9 @@ import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-e
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
import {SortService} from '../../../book/service/sort.service';
import {PageTitleService} from "../../../../shared/service/page-title.service";
import {PageTitleService} from '../../../../shared/service/page-title.service';
import {SortDirection, SortOption} from '../../../book/model/sort.model';
import {LibraryService} from '../../../book/service/library.service';
const DEFAULT_MAX_ITEMS = 20;
@@ -32,7 +27,6 @@ const DEFAULT_MAX_ITEMS = 20;
imports: [
Button,
DashboardScrollerComponent,
AsyncPipe,
ProgressSpinner,
TooltipModule,
TranslocoDirective
@@ -42,6 +36,7 @@ const DEFAULT_MAX_ITEMS = 20;
export class MainDashboardComponent implements OnInit {
private bookService = inject(BookService);
private libraryService = inject(LibraryService);
private dialogLauncher = inject(DialogLauncherService);
protected userService = inject(UserService);
private dashboardConfigService = inject(DashboardConfigService);
@@ -51,174 +46,146 @@ export class MainDashboardComponent implements OnInit {
private pageTitle = inject(PageTitleService);
private readonly t = inject(TranslocoService);
bookState$ = this.bookService.bookState$;
dashboardConfig$ = this.dashboardConfigService.config$;
private scrollerBooksCache = new Map<string, Observable<Book[]>>();
isLibrariesEmpty$: Observable<boolean> = inject(LibraryService).libraryState$.pipe(
map(state => !state.libraries || state.libraries.length === 0)
readonly dashboardConfig = this.dashboardConfigService.config;
readonly isBooksLoading = this.bookService.isBooksLoading;
readonly isLibrariesEmpty = computed(() =>
!this.libraryService.isLibrariesLoading() && this.libraryService.libraries().length === 0
);
readonly scrollerBooks = computed(() => {
const config = this.dashboardConfig();
const books = this.bookService.books();
const scrollerMap = new Map<string, Book[]>();
for (const scroller of config.scrollers) {
scrollerMap.set(scroller.id, this.getBooksForConfig(scroller, books, this.magicShelfService.shelves()));
}
return scrollerMap;
});
ScrollerType = ScrollerType;
ngOnInit(): void {
this.pageTitle.setPageTitle(this.t.translate('dashboard.main.pageTitle'));
this.dashboardConfig$.subscribe(() => {
this.scrollerBooksCache.clear();
});
this.magicShelfService.shelvesState$.subscribe(() => {
this.scrollerBooksCache.clear();
});
}
private getLastReadBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
return this.bookService.bookState$.pipe(
map((state: BookState) => {
let books = (state.books || []).filter(book =>
book.lastReadTime &&
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
this.hasEbookProgress(book)
);
books = books.sort((a, b) => {
const aTime = new Date(a.lastReadTime!).getTime();
const bTime = new Date(b.lastReadTime!).getTime();
return bTime - aTime;
});
return books.slice(0, maxItems);
})
);
getBooksForScroller(config: ScrollerConfig): Book[] {
return this.scrollerBooks().get(config.id) ?? [];
}
private getLastListenedBooks(maxItems: number): Observable<Book[]> {
return this.bookService.bookState$.pipe(
map((state: BookState) => {
let books = (state.books || []).filter(book =>
book.lastReadTime &&
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
book.audiobookProgress
);
books = books.sort((a, b) => {
const aTime = new Date(a.lastReadTime!).getTime();
const bTime = new Date(b.lastReadTime!).getTime();
return bTime - aTime;
});
return books.slice(0, maxItems);
})
private getBooksForConfig(config: ScrollerConfig, books: Book[], magicShelves: {id?: number | null; filterJson: string}[]): Book[] {
switch (config.type) {
case ScrollerType.LAST_READ:
return this.getLastReadBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
case ScrollerType.LAST_LISTENED:
return this.getLastListenedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
case ScrollerType.LATEST_ADDED:
return this.getLatestAddedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
case ScrollerType.RANDOM:
return this.getRandomBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
case ScrollerType.MAGIC_SHELF:
return this.getMagicShelfBooks(config, books, magicShelves);
default:
return [];
}
}
private getLastReadBooks(books: Book[], maxItems: number): Book[] {
const recentBooks = books.filter(book =>
book.lastReadTime &&
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
this.hasEbookProgress(book)
);
return recentBooks.sort((a, b) => {
const aTime = new Date(a.lastReadTime!).getTime();
const bTime = new Date(b.lastReadTime!).getTime();
return bTime - aTime;
}).slice(0, maxItems);
}
private getLastListenedBooks(books: Book[], maxItems: number): Book[] {
const recentBooks = books.filter(book =>
book.lastReadTime &&
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
book.audiobookProgress
);
return recentBooks.sort((a, b) => {
const aTime = new Date(a.lastReadTime!).getTime();
const bTime = new Date(b.lastReadTime!).getTime();
return bTime - aTime;
}).slice(0, maxItems);
}
private hasEbookProgress(book: Book): boolean {
return !!(book.epubProgress || book.pdfProgress || book.cbxProgress || book.koreaderProgress || book.koboProgress);
}
private getLatestAddedBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
return this.bookService.bookState$.pipe(
map((state: BookState) => {
let books = (state.books || []).filter(book => book.addedOn);
private getLatestAddedBooks(books: Book[], maxItems: number): Book[] {
const addedBooks = books.filter(book => book.addedOn);
books = books.sort((a, b) => {
const aTime = new Date(a.addedOn!).getTime();
const bTime = new Date(b.addedOn!).getTime();
return bTime - aTime;
});
return books.slice(0, maxItems);
})
);
return addedBooks.sort((a, b) => {
const aTime = new Date(a.addedOn!).getTime();
const bTime = new Date(b.addedOn!).getTime();
return bTime - aTime;
}).slice(0, maxItems);
}
private getRandomBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
return this.bookService.bookState$.pipe(
map((state: BookState) => {
const excludedStatuses = new Set<ReadStatus>([
ReadStatus.READ,
ReadStatus.PARTIALLY_READ,
ReadStatus.READING,
ReadStatus.PAUSED,
ReadStatus.WONT_READ,
ReadStatus.ABANDONED
]);
private getRandomBooks(books: Book[], maxItems: number): Book[] {
const excludedStatuses = new Set<ReadStatus>([
ReadStatus.READ,
ReadStatus.PARTIALLY_READ,
ReadStatus.READING,
ReadStatus.PAUSED,
ReadStatus.WONT_READ,
ReadStatus.ABANDONED
]);
const candidates = (state.books || []).filter(book =>
!book.readStatus || !excludedStatuses.has(book.readStatus)
);
return this.shuffleBooks(candidates, maxItems);
})
const candidates = books.filter(book =>
!book.readStatus || !excludedStatuses.has(book.readStatus)
);
return this.shuffleBooks(candidates, maxItems);
}
private getMagicShelfBooks(shelfId: number, maxItems?: number, sortBy?: string): Observable<Book[]> {
return this.magicShelfService.getShelf(shelfId).pipe(
switchMap((shelf) => {
if (!shelf) return this.bookService.bookState$.pipe(map(() => []));
let group: GroupRule;
try {
group = JSON.parse(shelf.filterJson);
} catch (e) {
console.error('Invalid filter JSON', e);
return this.bookService.bookState$.pipe(map(() => []));
}
return this.bookService.bookState$.pipe(
map((state: BookState) => {
const allBooks = state.books || [];
const filteredBooks = allBooks.filter((book) =>
this.ruleEvaluatorService.evaluateGroup(book, group, allBooks)
);
return maxItems ? filteredBooks.slice(0, maxItems) : filteredBooks;
})
);
})
);
}
getBooksForScroller(config: ScrollerConfig): Observable<Book[]> {
if (!this.scrollerBooksCache.has(config.id)) {
let books$: Observable<Book[]>;
switch (config.type) {
case ScrollerType.LAST_READ:
books$ = this.getLastReadBooks(config.maxItems || DEFAULT_MAX_ITEMS);
break;
case ScrollerType.LAST_LISTENED:
books$ = this.getLastListenedBooks(config.maxItems || DEFAULT_MAX_ITEMS);
break;
case ScrollerType.LATEST_ADDED:
books$ = this.getLatestAddedBooks(config.maxItems || DEFAULT_MAX_ITEMS);
break;
case ScrollerType.RANDOM:
books$ = this.getRandomBooks(config.maxItems || DEFAULT_MAX_ITEMS);
break;
case ScrollerType.MAGIC_SHELF:
books$ = this.getMagicShelfBooks(config.magicShelfId!, config.maxItems).pipe(
map(books => {
if (config.sortField && config.sortDirection) {
const sortOption = this.createSortOption(config.sortField, config.sortDirection);
return this.sortService.applySort(books, sortOption);
}
return books;
})
);
break;
default:
books$ = this.bookService.bookState$.pipe(map(() => []));
}
this.scrollerBooksCache.set(config.id, books$.pipe(shareReplay(1)));
private getMagicShelfBooks(
config: ScrollerConfig,
books: Book[],
magicShelves: {id?: number | null; filterJson: string}[]
): Book[] {
const shelf = magicShelves.find(currentShelf => currentShelf.id === config.magicShelfId);
if (!shelf) {
return [];
}
return this.scrollerBooksCache.get(config.id)!;
let group: GroupRule;
try {
group = JSON.parse(shelf.filterJson);
} catch (e) {
console.error('Invalid filter JSON', e);
return [];
}
let filteredBooks = books.filter(book =>
this.ruleEvaluatorService.evaluateGroup(book, group, books)
);
if (config.maxItems) {
filteredBooks = filteredBooks.slice(0, config.maxItems);
}
if (config.sortField && config.sortDirection) {
const sortOption = this.createSortOption(config.sortField, config.sortDirection);
return this.sortService.applySort(filteredBooks, sortOption);
}
return filteredBooks;
}
private createSortOption(field: string, direction: string): SortOption {
return {
field: field,
field,
direction: direction === 'asc' ? SortDirection.ASCENDING : SortDirection.DESCENDING,
label: ''
};
@@ -1,65 +1,97 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {effect, inject, Injectable, signal} from '@angular/core';
import {DashboardConfig, DEFAULT_DASHBOARD_CONFIG, ScrollerType} from '../models/dashboard-config.model';
import {UserService} from '../../settings/user-management/user.service';
import {filter, take} from 'rxjs/operators';
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
@Injectable({
providedIn: 'root'
})
export class DashboardConfigService {
private configSubject = new BehaviorSubject<DashboardConfig>(DEFAULT_DASHBOARD_CONFIG);
private readonly userService = inject(UserService);
private readonly magicShelfService = inject(MagicShelfService);
public config$: Observable<DashboardConfig> = this.configSubject.asObservable();
private readonly _config = signal<DashboardConfig>(this.cloneConfig(DEFAULT_DASHBOARD_CONFIG));
readonly config = this._config.asReadonly();
constructor(private userService: UserService, private magicShelfService: MagicShelfService) {
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
take(1)
)
.subscribe(userState => {
const dashboardConfig = userState.user?.userSettings?.dashboardConfig as DashboardConfig;
if (dashboardConfig) {
this.configSubject.next(dashboardConfig);
}
});
constructor() {
effect(() => {
const user = this.userService.currentUser();
if (user) {
const dashboardConfig = user.userSettings?.dashboardConfig as DashboardConfig;
this._config.set(this.normalizeConfig(dashboardConfig));
}
});
this.magicShelfService.shelvesState$.subscribe(state => {
const currentConfig = this.configSubject.value;
let updated = false;
effect(() => {
const shelves = this.magicShelfService.shelves();
const currentConfig = this._config();
const syncedConfig = this.syncMagicShelfTitles(currentConfig, shelves);
currentConfig.scrollers.forEach(scroller => {
if (scroller.type === ScrollerType.MAGIC_SHELF && scroller.magicShelfId) {
const shelf = state.shelves?.find(s => s.id === scroller.magicShelfId);
if (shelf && scroller.title !== shelf.name) {
scroller.title = shelf.name;
updated = true;
}
}
});
if (updated) {
this.configSubject.next({...currentConfig});
if (syncedConfig) {
this._config.set(syncedConfig);
const user = this.userService.getCurrentUser();
if (user) {
this.userService.updateUserSetting(user.id, 'dashboardConfig', currentConfig);
this.userService.updateUserSetting(user.id, 'dashboardConfig', syncedConfig);
}
}
});
}
saveConfig(config: DashboardConfig): void {
this.configSubject.next(config);
const nextConfig = this.normalizeConfig(config);
this._config.set(nextConfig);
const user = this.userService.getCurrentUser();
if (user) {
this.userService.updateUserSetting(user.id, 'dashboardConfig', config);
this.userService.updateUserSetting(user.id, 'dashboardConfig', nextConfig);
}
}
resetToDefault(): void {
this.saveConfig(DEFAULT_DASHBOARD_CONFIG);
}
private normalizeConfig(config: DashboardConfig | null | undefined): DashboardConfig {
if (!config?.scrollers?.length) {
return this.cloneConfig(DEFAULT_DASHBOARD_CONFIG);
}
return this.cloneConfig(config);
}
private cloneConfig(config: DashboardConfig): DashboardConfig {
return {
scrollers: config.scrollers.map(scroller => ({...scroller}))
};
}
private syncMagicShelfTitles(
config: DashboardConfig,
shelves: Array<{ id?: number | null; name: string }>
): DashboardConfig | null {
let updated = false;
const scrollers = config.scrollers.map(scroller => {
if (scroller.type !== ScrollerType.MAGIC_SHELF || !scroller.magicShelfId) {
return scroller;
}
const shelf = shelves.find(currentShelf => currentShelf.id === scroller.magicShelfId);
if (!shelf || scroller.title === shelf.name) {
return scroller;
}
updated = true;
return {
...scroller,
title: shelf.name
};
});
if (!updated) {
return null;
}
return {scrollers};
}
}
@@ -29,7 +29,7 @@
</div>
<div class="icon-picker-section">
<div class="icon-picker-wrapper">
<label>{{ t('form.shelfIcon') }}</label>
<span>{{ t('form.shelfIcon') }}</span>
@if (selectedIcon) {
<div class="selected-icon-display">
<div class="icon-display-container" (click)="openIconPicker()" (keydown.enter)="openIconPicker()" tabindex="0" role="button">
@@ -116,11 +116,11 @@
</div>
</div>
<ng-template #groupTemplate let-group="group">
<ng-template #groupTemplate let-group="group">
<div class="group-container" [formGroup]="group">
<div class="group-header">
<label>{{ t('group.condition') }}</label>
<p-select [options]="conditionOptions" formControlName="join" class="condition-select" appendTo="body" [showClear]="false"/>
<label [for]="getControlId(group.get('join'), 'magic-shelf-group-join')">{{ t('group.condition') }}</label>
<p-select [inputId]="getControlId(group.get('join'), 'magic-shelf-group-join')" [options]="conditionOptions" formControlName="join" class="condition-select" appendTo="body" [showClear]="false"/>
<p-button icon="pi pi-plus" size="small" text (click)="addRule(group)" [label]="t('actions.addRule')" outlined></p-button>
<p-button icon="pi pi-folder-open" size="small" text (click)="addGroup(group)" [label]="t('actions.addGroup')" outlined></p-button>
@if (group.parent) {
@@ -187,11 +187,11 @@
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
<p-multiSelect [options]="fileType" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectFileTypes')"></p-multiSelect>
} @else if (ruleCtrl.get('field')?.value === 'library') {
<p-multiSelect [options]="libraryOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectLibraries')"></p-multiSelect>
<p-multiSelect [options]="libraryOptions()" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectLibraries')"></p-multiSelect>
} @else if (ruleCtrl.get('field')?.value === 'shelf') {
<p-multiSelect [options]="shelfOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectShelves')"></p-multiSelect>
<p-multiSelect [options]="shelfOptions()" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectShelves')"></p-multiSelect>
} @else if (ruleCtrl.get('field')?.value === 'categories') {
<p-multiSelect [options]="categoryOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectGenres')"></p-multiSelect>
<p-multiSelect [options]="categoryOptions()" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectGenres')"></p-multiSelect>
} @else if (ruleCtrl.get('field')?.value === 'contentRating') {
<p-multiSelect [options]="contentRatingOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectContentRatings')"></p-multiSelect>
} @else {
@@ -204,11 +204,11 @@
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
<p-select [options]="fileType" formControlName="value" [placeholder]="t('placeholders.selectFileType')" appendTo="body" class="value-input"></p-select>
} @else if (ruleCtrl.get('field')?.value === 'library') {
<p-select [options]="libraryOptions" formControlName="value" [placeholder]="t('placeholders.selectLibrary')" appendTo="body" class="value-input"></p-select>
<p-select [options]="libraryOptions()" formControlName="value" [placeholder]="t('placeholders.selectLibrary')" appendTo="body" class="value-input"></p-select>
} @else if (ruleCtrl.get('field')?.value === 'shelf') {
<p-select [options]="shelfOptions" formControlName="value" [placeholder]="t('placeholders.selectShelf')" appendTo="body" class="value-input"></p-select>
<p-select [options]="shelfOptions()" formControlName="value" [placeholder]="t('placeholders.selectShelf')" appendTo="body" class="value-input"></p-select>
} @else if (ruleCtrl.get('field')?.value === 'categories') {
<p-select [options]="categoryOptions" formControlName="value" [placeholder]="t('placeholders.selectGenre')" appendTo="body" class="value-input"></p-select>
<p-select [options]="categoryOptions()" formControlName="value" [placeholder]="t('placeholders.selectGenre')" appendTo="body" class="value-input"></p-select>
} @else if (ruleCtrl.get('field')?.value === 'contentRating') {
<p-select [options]="contentRatingOptions" formControlName="value" [placeholder]="t('placeholders.selectContentRating')" appendTo="body" class="value-input"></p-select>
} @else {
@@ -27,7 +27,7 @@ describe('MagicShelfComponent (Part 3)', () => {
providers: [
{provide: TranslocoService, useValue: mockTransloco},
{provide: LibraryService, useValue: {getLibrariesFromState: vi.fn(() => [])}},
{provide: ShelfService, useValue: {getShelvesFromState: vi.fn(() => [])}},
{provide: ShelfService, useValue: {shelves$: of([])}},
{provide: BookService, useValue: {bookState$: of({loaded: false, books: []})}},
{provide: MagicShelfService, useValue: {}},
{provide: MessageService, useValue: {add: vi.fn()}},
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, computed, effect, inject, OnInit} from '@angular/core';
import {AbstractControl, FormArray, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
import {Button} from 'primeng/button';
import {NgTemplateOutlet} from '@angular/common';
@@ -8,8 +8,7 @@ import {DatePicker} from 'primeng/datepicker';
import {InputNumber} from 'primeng/inputnumber';
import {ReadStatus} from '../../book/model/book.model';
import {LibraryService} from '../../book/service/library.service';
import {Library} from '../../book/model/library.model';
import {MagicShelfService} from '../service/magic-shelf.service';
import {MagicShelf, MagicShelfService} from '../service/magic-shelf.service';
import {MessageService} from 'primeng/api';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MultiSelect} from 'primeng/multiselect';
@@ -22,7 +21,6 @@ import {IconDisplayComponent} from '../../../shared/components/icon-display/icon
import {Tooltip} from 'primeng/tooltip';
import {BookService} from '../../book/service/book.service';
import {ShelfService} from '../../book/service/shelf.service';
import {Shelf} from '../../book/model/shelf.model';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {TextareaModule} from 'primeng/textarea';
@@ -250,10 +248,12 @@ const READ_STATUS_KEYS: Record<string, string> = {
export class MagicShelfComponent implements OnInit {
private readonly t = inject(TranslocoService);
private readonly controlIds = new WeakMap<AbstractControl, string>();
private controlIdCounter = 0;
numericFieldConfigMap = new Map<RuleField, FieldConfig>(
Object.entries(FIELD_CONFIGS)
.filter(([_, config]) => config.type)
.filter(([, config]) => config.type)
.map(([key, config]) => [key as RuleField, {type: config.type!, max: config.max}])
);
@@ -438,11 +438,29 @@ export class MagicShelfComponent implements OnInit {
];
}
libraries: Library[] = [];
libraryOptions: { label: string; value: number }[] = [];
shelves: Shelf[] = [];
shelfOptions: { label: string; value: number }[] = [];
categoryOptions: { label: string; value: string }[] = [];
libraryOptions = computed(() =>
this.libraryService.libraries().map(library => ({
label: library.name,
value: library.id!
}))
);
shelfOptions = computed(() =>
this.shelfService.shelves().map(shelf => ({
label: shelf.name,
value: shelf.id!
}))
);
categoryOptions = computed(() => {
const categoriesSet = new Set<string>();
this.bookService.books().forEach(book => {
book.metadata?.categories?.forEach(category => categoriesSet.add(category));
});
return Array.from(categoriesSet).map(category => ({
label: category,
value: category
})).sort((a, b) => a.label.localeCompare(b.label));
});
form = new FormGroup({
name: new FormControl<string | null>(null),
@@ -468,9 +486,25 @@ export class MagicShelfComponent implements OnInit {
private iconPicker = inject(IconPickerService);
selectedIcon: IconSelection | null = null;
private formInitializedFromShelf = false;
trackByFn(ruleCtrl: AbstractControl, index: number): unknown {
return ruleCtrl;
return ruleCtrl ?? index;
}
getControlId(control: AbstractControl | null, prefix: string): string {
if (!control) {
return `${prefix}-missing`;
}
const existingId = this.controlIds.get(control);
if (existingId) {
return existingId;
}
const newId = `${prefix}-${this.controlIdCounter++}`;
this.controlIds.set(control, newId);
return newId;
}
ngOnInit(): void {
@@ -478,62 +512,40 @@ export class MagicShelfComponent implements OnInit {
const id = this.config?.data?.id;
this.editMode = !!this.config?.data?.editMode;
// Load available categories from book metadata
this.bookService.bookState$.subscribe(state => {
if (state.loaded && state.books) {
// Extract unique categories from all books
const categoriesSet = new Set<string>();
state.books.forEach(book => {
if (book.metadata?.categories) {
book.metadata.categories.forEach(cat => categoriesSet.add(cat));
}
});
this.categoryOptions = Array.from(categoriesSet).map(cat => ({
label: cat,
value: cat
})).sort((a, b) => a.label.localeCompare(b.label));
}
});
if (id) {
this.shelfId = id;
this.magicShelfService.getShelf(id).subscribe((data) => {
const iconValue = data?.icon ?? null;
this.form = new FormGroup({
name: new FormControl<string | null>(data?.name ?? null, {nonNullable: true, validators: [Validators.required]}),
icon: new FormControl<string | null>(iconValue),
isPublic: new FormControl<boolean>(data?.isPublic ?? false),
group: data?.filterJson ? this.buildGroupFromData(JSON.parse(data.filterJson)) : this.createGroup()
});
if (iconValue) {
this.selectedIcon = iconValue.startsWith('pi ')
? {type: 'PRIME_NG', value: iconValue}
: {type: 'CUSTOM_SVG', value: iconValue};
effect(() => {
const shelf = this.magicShelfService.findShelfById(id);
if (!shelf || this.formInitializedFromShelf) {
return;
}
this.initializeForm(shelf);
this.formInitializedFromShelf = true;
});
} else {
this.form = new FormGroup({
name: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}),
icon: new FormControl<string | null>(null),
isPublic: new FormControl<boolean>(false),
group: this.createGroup()
});
this.initializeForm();
this.formInitializedFromShelf = true;
}
}
this.libraries = this.libraryService.getLibrariesFromState();
this.libraryOptions = this.libraries.map(lib => ({
label: lib.name,
value: lib.id!
}));
private initializeForm(shelf?: MagicShelf): void {
const iconValue = shelf?.icon ?? null;
this.shelves = this.shelfService.getShelvesFromState();
this.shelfOptions = this.shelves.map(shelf => ({
label: shelf.name,
value: shelf.id!
}));
this.form = new FormGroup({
name: new FormControl<string | null>(shelf?.name ?? null, {nonNullable: true, validators: [Validators.required]}),
icon: new FormControl<string | null>(iconValue),
isPublic: new FormControl<boolean>(shelf?.isPublic ?? false),
group: shelf?.filterJson ? this.buildGroupFromData(JSON.parse(shelf.filterJson)) : this.createGroup()
});
if (iconValue) {
this.selectedIcon = iconValue.startsWith('pi ')
? {type: 'PRIME_NG', value: iconValue}
: {type: 'CUSTOM_SVG', value: iconValue};
} else {
this.selectedIcon = null;
}
}
buildGroupFromData(data: GroupRule): GroupFormGroup {
@@ -1,8 +1,10 @@
import {inject, Injectable} from '@angular/core';
import {API_CONFIG} from '../../../core/config/api-config';
import {computed, effect, inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, distinctUntilChanged, finalize, map, shareReplay, switchMap, tap} from 'rxjs/operators';
import {lastValueFrom, Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {API_CONFIG} from '../../../core/config/api-config';
import {BookService} from '../../book/service/book.service';
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
import {AuthService} from '../../../shared/service/auth.service';
@@ -17,11 +19,7 @@ export interface MagicShelf {
isPublic?: boolean;
}
export interface MagicShelfState {
shelves: MagicShelf[] | null;
loaded: boolean;
error: string | null;
}
const MAGIC_SHELVES_QUERY_KEY = ['magicShelves'] as const;
@Injectable({
providedIn: 'root',
@@ -33,68 +31,51 @@ export class MagicShelfService {
private readonly bookService = inject(BookService);
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
private readonly authService = inject(AuthService);
private readonly queryClient = inject(QueryClient);
private readonly token = this.authService.token;
private readonly shelvesStateSubject = new BehaviorSubject<MagicShelfState>({
shelves: null,
loaded: false,
error: null,
private readonly shelvesQuery = injectQuery(() => ({
...this.getShelvesQueryOptions(),
enabled: !!this.token(),
}));
readonly shelves = computed(() => this.shelvesQuery.data() ?? []);
readonly shelvesError = computed<string | null>(() => {
if (!this.token() || !this.shelvesQuery.isError()) {
return null;
}
const error = this.shelvesQuery.error();
return error instanceof Error ? error.message : 'Failed to load magic shelves';
});
private loading$: Observable<MagicShelf[]> | null = null;
readonly isShelvesLoading = computed(() => !!this.token() && this.shelvesQuery.isPending());
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
effect(() => {
const token = this.token();
if (token === null) {
this.shelvesStateSubject.next({
shelves: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.shelvesStateSubject.value;
if (current.loaded && !current.shelves) {
this.shelvesStateSubject.next({
shelves: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
this.queryClient.removeQueries({queryKey: MAGIC_SHELVES_QUERY_KEY});
}
});
}
public readonly shelvesState$ = this.shelvesStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchMagicShelves().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private get state(): MagicShelfState {
return this.shelvesStateSubject.value;
private getShelvesQueryOptions() {
return queryOptions({
queryKey: MAGIC_SHELVES_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<MagicShelf[]>(this.url))
});
}
private fetchMagicShelves(): Observable<MagicShelf[]> {
return this.http.get<MagicShelf[]>(this.url).pipe(
tap(shelves => this.shelvesStateSubject.next({shelves, loaded: true, error: null})),
catchError(err => {
const curr = this.shelvesStateSubject.value;
this.shelvesStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
throw err;
})
);
}
saveShelf(data: { id?: number; name: string | null; icon: string | null; iconType?: 'PRIME_NG' | 'CUSTOM_SVG'; group: unknown, isPublic?: boolean | null }): Observable<MagicShelf> {
saveShelf(data: {
id?: number;
name: string | null;
icon: string | null;
iconType?: 'PRIME_NG' | 'CUSTOM_SVG';
group: unknown;
isPublic?: boolean | null;
}): Observable<MagicShelf> {
const payload: MagicShelf = {
id: data.id,
name: data.name ?? '',
@@ -105,70 +86,40 @@ export class MagicShelfService {
};
return this.http.post<MagicShelf>(this.url, payload).pipe(
tap((newShelf) => {
const curr = this.state;
const shelves = curr.shelves || [];
const updated = shelves.some((s) => s.id === newShelf.id)
? shelves.map((s) => (s.id === newShelf.id ? newShelf : s))
: [...shelves, newShelf];
this.shelvesStateSubject.next({...curr, shelves: updated});
}),
catchError((error) => {
this.updateError(error.message);
throw error;
tap(() => {
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
})
);
}
getShelf(id: number): Observable<MagicShelf | undefined> {
return this.shelvesState$.pipe(
map(state => (state.shelves || []).find(shelf => shelf.id === id))
);
findShelfById(id: number): MagicShelf | undefined {
return this.shelves().find(shelf => shelf.id === id);
}
getBookCountValue(shelfId: number): number {
const shelf = this.findShelfById(shelfId);
if (!shelf) {
return 0;
}
let group: GroupRule;
try {
group = JSON.parse(shelf.filterJson);
} catch (error) {
console.error('Invalid filter JSON', error);
return 0;
}
const allBooks = this.bookService.books();
return allBooks.filter(book =>
this.ruleEvaluatorService.evaluateGroup(book, group, allBooks)
).length;
}
deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
const curr = this.state;
const updated = (curr.shelves || []).filter((s) => s.id !== id);
this.shelvesStateSubject.next({...curr, shelves: updated});
}),
catchError((error) => {
this.updateError(error.message);
throw error;
})
);
}
private updateError(error: string): void {
this.shelvesStateSubject.next({
...this.state,
error,
loaded: true,
});
}
getBookCount(shelfId: number): Observable<number> {
return this.getShelf(shelfId).pipe(
switchMap((shelf) => {
if (!shelf) return of(0);
let group: GroupRule;
try {
group = JSON.parse(shelf.filterJson);
} catch (e) {
console.error('Invalid filter JSON', e);
return of(0);
}
return this.bookService.bookState$.pipe(
map((state) => {
const allBooks = state.books ?? [];
return allBooks.filter((book) =>
this.ruleEvaluatorService.evaluateGroup(book, group, allBooks)
).length;
})
);
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
})
);
}
@@ -47,25 +47,25 @@
<p-tabpanels class="tabpanels-responsive">
<p-tabpanel value="view">
<app-metadata-viewer
[book$]="book$"
[book]="book()"
[recommendedBooks]="recommendedBooks">
</app-metadata-viewer>
</p-tabpanel>
@if (admin || canEditMetadata) {
<p-tabpanel value="edit">
<app-metadata-editor
[book$]="book$">
[book]="book()">
</app-metadata-editor>
</p-tabpanel>
}
@if (admin || canEditMetadata) {
<p-tabpanel value="match">
<app-metadata-searcher [book$]="book$" [isActiveTab]="tab === 'match'"></app-metadata-searcher>
<app-metadata-searcher [book]="book()" [isActiveTab]="tab === 'match'"></app-metadata-searcher>
</p-tabpanel>
}
@if ((admin || canEditMetadata) && !isPhysical && isLocalStorage) {
<p-tabpanel value="sidecar">
<app-sidecar-viewer [book$]="book$"></app-sidecar-viewer>
<app-sidecar-viewer [book]="book()"></app-sidecar-viewer>
</p-tabpanel>
}
</p-tabpanels>
@@ -1,9 +1,9 @@
import {Component, inject, OnDestroy, OnInit, Optional} from '@angular/core';
import {computed, Component, effect, inject, OnDestroy, OnInit, signal} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {UserService} from '../../../settings/user-management/user.service';
import {Book, BookRecommendation} from '../../../book/model/book.model';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {distinctUntilChanged, filter, map, shareReplay, switchMap, take, takeUntil, tap,} from 'rxjs/operators';
import {Subject} from 'rxjs';
import {distinctUntilChanged, filter, map, takeUntil,} from 'rxjs/operators';
import {BookService} from '../../../book/service/book.service';
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
import {Tab, TabList, TabPanel, TabPanels, Tabs,} from 'primeng/tabs';
@@ -15,6 +15,7 @@ import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.compone
import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
import {SidecarViewerComponent} from './sidecar-viewer/sidecar-viewer.component';
import {injectQuery} from '@tanstack/angular-query-experimental';
@Component({
selector: 'app-book-metadata-center',
@@ -42,18 +43,50 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
private userService = inject(UserService);
private appSettingsService = inject(AppSettingsService);
private metadataHostService = inject(BookMetadataHostService);
readonly config = inject(DynamicDialogConfig, {optional: true});
readonly ref = inject(DynamicDialogRef, {optional: true});
private destroy$ = new Subject<void>();
book$!: Observable<Book>;
private currentBookId = signal<number | null>(this.config?.data?.bookId ?? null);
private bookQuery = injectQuery(() => {
const bookId = this.currentBookId();
if (bookId == null) {
return {
queryKey: ['books', 'detail', -1, true] as const,
queryFn: async (): Promise<Book> => {
throw new Error('No book selected');
},
enabled: false,
};
}
return this.bookService.bookDetailQueryOptions(bookId, true);
});
readonly book = computed(() => this.bookQuery.data() ?? null);
private readonly fetchRecommendations = effect(() => {
const bookId = this.currentBookId();
if (bookId == null) {
this.recommendedBooks = [];
return;
}
this.fetchBookRecommendationsIfNeeded(bookId);
});
recommendedBooks: BookRecommendation[] = [];
private _tab: string = 'view';
canEditMetadata: boolean = false;
admin: boolean = false;
isPhysical: boolean = false;
private readonly syncUserPermissionsEffect = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this.canEditMetadata = user.permissions?.canEditMetadata ?? false;
this.admin = user.permissions?.admin ?? false;
});
get isPhysical(): boolean { return this.book()?.isPhysical ?? false; }
isLocalStorage: boolean = true;
private appSettings$ = this.appSettingsService.appSettings$;
private currentBookId$ = new BehaviorSubject<number | null>(null);
private validTabs = ['view', 'edit', 'match', 'sidecar'];
get tab(): string {
@@ -72,16 +105,10 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
}
}
constructor(
@Optional() public config?: DynamicDialogConfig,
@Optional() public ref?: DynamicDialogRef
) {
}
ngOnInit(): void {
const bookIdFromDialog: number | undefined = this.config?.data?.bookId;
if (bookIdFromDialog != null) {
this.currentBookId$.next(bookIdFromDialog);
this.currentBookId.set(bookIdFromDialog);
} else {
this.route.paramMap
.pipe(
@@ -89,7 +116,7 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
filter(bookId => !isNaN(bookId)),
takeUntil(this.destroy$)
)
.subscribe(bookId => this.currentBookId$.next(bookId));
.subscribe(bookId => this.currentBookId.set(bookId));
}
this.metadataHostService.bookSwitches$
@@ -98,34 +125,7 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
distinctUntilChanged(),
takeUntil(this.destroy$)
)
.subscribe(bookId => {
this.currentBookId$.next(bookId);
});
this.book$ = this.currentBookId$.pipe(
filter((bookId): bookId is number => bookId != null),
distinctUntilChanged(),
switchMap(bookId =>
this.bookService.bookState$.pipe(
map(state => state.books?.find(b => b.id === bookId)),
filter((book): book is Book => !!book && !!book.metadata),
distinctUntilChanged(),
switchMap(book =>
this.bookService.getBookByIdFromAPI(book.id, true)
)
)
),
tap(book => this.isPhysical = book.isPhysical ?? false),
takeUntil(this.destroy$),
shareReplay({bufferSize: 1, refCount: true})
);
this.currentBookId$
.pipe(
filter((id): id is number => id != null),
takeUntil(this.destroy$)
)
.subscribe(bookId => this.fetchBookRecommendationsIfNeeded(bookId));
.subscribe(bookId => this.currentBookId.set(bookId));
this.route.queryParamMap
.pipe(
@@ -137,39 +137,24 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
this._tab = this.validTabs.includes(tabParam) ? tabParam : 'view';
});
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
)
.subscribe(userState => {
this.canEditMetadata = userState.user?.permissions?.canEditMetadata ?? false;
this.admin = userState.user?.permissions?.admin ?? false;
});
this.appSettings$
.pipe(
filter(settings => !!settings),
take(1),
takeUntil(this.destroy$)
)
.subscribe(settings => {
this.isLocalStorage = settings!.diskType === 'LOCAL';
});
const currentSettings = this.appSettingsService.appSettings();
if (currentSettings) {
this.isLocalStorage = currentSettings.diskType === 'LOCAL';
}
}
private fetchBookRecommendationsIfNeeded(bookId: number): void {
this.appSettings$.pipe(
filter(settings => settings != null),
take(1),
filter(settings => settings!.similarBookRecommendation ?? false),
switchMap(() => this.bookService.getBookRecommendations(bookId)),
takeUntil(this.destroy$)
).subscribe(recommendations => {
this.recommendedBooks = recommendations.sort(
(a, b) => (b.similarityScore ?? 0) - (a.similarityScore ?? 0)
);
});
const settings = this.appSettingsService.appSettings();
if (!settings || !(settings.similarBookRecommendation ?? false)) {
return;
}
this.bookService.getBookRecommendations(bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(recommendations => {
this.recommendedBooks = recommendations.sort(
(a, b) => (b.similarityScore ?? 0) - (a.similarityScore ?? 0)
);
});
}
ngOnDestroy(): void {
@@ -1,4 +1,4 @@
@if (book$ | async; as book) {
@if (book; as book) {
<form [formGroup]="metadataForm" class="metadata-form" *transloco="let t; prefix: 'metadata.editor'">
@if (isLoading) {
<div class="loading-overlay"></div>
@@ -952,7 +952,7 @@
</div>
}
@if (navigationState$ | async) {
@if (navigationState()) {
<div class="navigation-center">
<p-button
icon="pi pi-chevron-left"
@@ -965,7 +965,7 @@
tooltipPosition="bottom">
</p-button>
<span class="navigation-position">
{{ getNavigationPosition() }}
{{ navigationPosition() }}
</span>
<p-button
icon="pi pi-chevron-right"
@@ -1023,7 +1023,7 @@
}
<div class="mobile-actions-row">
@if (navigationState$ | async) {
@if (navigationState()) {
<div class="navigation-center">
<p-button
icon="pi pi-chevron-left"
@@ -1036,7 +1036,7 @@
tooltipPosition="bottom">
</p-button>
<span class="navigation-position">
{{ getNavigationPosition() }}
{{ navigationPosition() }}
</span>
<p-button
icon="pi pi-chevron-right"
@@ -1,10 +1,9 @@
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output,} from "@angular/core";
import {Component, computed, DestroyRef, effect, EffectRef, EventEmitter, inject, Input, OnInit, Output,} from "@angular/core";
import {InputText} from "primeng/inputtext";
import {Button} from "primeng/button";
import {Divider} from "primeng/divider";
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule,} from "@angular/forms";
import {Observable, sample} from "rxjs";
import {AsyncPipe} from "@angular/common";
import {MessageService} from "primeng/api";
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper,} from "../../../../book/model/book.model";
import {UrlHelperService} from "../../../../../shared/service/url-helper.service";
@@ -45,7 +44,6 @@ import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/d
Button,
Divider,
FormsModule,
AsyncPipe,
ReactiveFormsModule,
FileUpload,
ProgressSpinner,
@@ -62,7 +60,29 @@ import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/d
],
})
export class MetadataEditorComponent implements OnInit {
@Input() book$!: Observable<Book | null>;
private currentBook: Book | null = null;
@Input()
set book(value: Book | null) {
this.currentBook = value;
const metadata = value?.metadata;
if (!metadata) return;
this.currentBookId = metadata.bookId;
if (this.refreshingBookIds.has(value.id)) {
this.refreshingBookIds.delete(value.id);
this.isAutoFetching = false;
}
this.originalMetadata = structuredClone(metadata);
this.populateFormFromMetadata(metadata);
}
get book(): Book | null {
return this.currentBook;
}
@Output() nextBookClicked = new EventEmitter<void>();
@Output() previousBookClicked = new EventEmitter<void>();
@Output() closeDialogButtonClicked = new EventEmitter<void>();
@@ -84,6 +104,7 @@ export class MetadataEditorComponent implements OnInit {
private destroyRef = inject(DestroyRef);
private appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
metadataForm: FormGroup;
currentBookId!: number;
@@ -100,12 +121,12 @@ export class MetadataEditorComponent implements OnInit {
originalMetadata!: BookMetadata;
allAuthors!: string[];
allCategories!: string[];
allMoods!: string[];
allTags!: string[];
allPublishers!: string[];
allSeries!: string[];
get allAuthors(): string[] { return this.uniqueMetadata().authors; }
get allCategories(): string[] { return this.uniqueMetadata().categories; }
get allMoods(): string[] { return this.uniqueMetadata().moods; }
get allTags(): string[] { return this.uniqueMetadata().tags; }
get allPublishers(): string[] { return this.uniqueMetadata().publishers; }
get allSeries(): string[] { return this.uniqueMetadata().series; }
filteredCategories: string[] = [];
filteredAuthors: string[] = [];
authorInputValue = '';
@@ -150,7 +171,16 @@ export class MetadataEditorComponent implements OnInit {
audibleReviewCount: true,
};
navigationState$ = this.bookNavigationService.getNavigationState();
private syncProviderFieldsEffect!: EffectRef;
readonly navigationState = this.bookNavigationService.navigationState;
readonly canNavigatePrevious = this.bookNavigationService.canNavigatePrevious;
readonly canNavigateNext = this.bookNavigationService.canNavigateNext;
readonly navigationPosition = computed(() => {
const position = this.bookNavigationService.currentPosition();
return position
? this.t.translate('metadata.editor.navigationPosition', {current: position.current, total: position.total})
: '';
});
filterCategories(event: { query: string }) {
const query = event.query.toLowerCase();
@@ -356,78 +386,18 @@ export class MetadataEditorComponent implements OnInit {
}
ngOnInit(): void {
this.book$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((book) => {
const metadata = book?.metadata;
if (!metadata) return;
this.currentBookId = metadata.bookId;
if (this.refreshingBookIds.has(book.id)) {
this.refreshingBookIds.delete(book.id);
this.isAutoFetching = false;
const user = this.userService.currentUser();
if (user) {
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
this.autoSaveEnabled = user.userSettings.autoSaveMetadata ?? false;
}
this.syncProviderFieldsEffect = effect(() => {
const settings = this.appSettingsService.appSettings();
if (settings?.metadataProviderSpecificFields) {
this.providerSpecificFields = settings.metadataProviderSpecificFields;
}
this.originalMetadata = structuredClone(metadata);
this.populateFormFromMetadata(metadata);
});
this.prepareAutoComplete();
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
take(1)
)
.subscribe(userState => {
this.metadataCenterViewMode = userState.user?.userSettings.metadataCenterViewMode ?? 'route';
this.autoSaveEnabled = userState.user?.userSettings.autoSaveMetadata ?? false;
});
this.appSettingsService.appSettings$
.pipe(
filter(settings => !!settings),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(settings => {
if (settings?.metadataProviderSpecificFields) {
this.providerSpecificFields = settings.metadataProviderSpecificFields;
}
});
}
private prepareAutoComplete(): void {
this.bookService.bookState$
.pipe(
filter((bookState) => bookState.loaded),
take(1)
)
.subscribe((bookState) => {
const authors = new Set<string>();
const categories = new Set<string>();
const moods = new Set<string>();
const tags = new Set<string>();
const publishers = new Set<string>();
const series = new Set<string>();
(bookState.books ?? []).forEach((book) => {
book.metadata?.authors?.forEach((author) => authors.add(author));
book.metadata?.categories?.forEach((category) =>
categories.add(category)
);
book.metadata?.moods?.forEach((mood) => moods.add(mood));
book.metadata?.tags?.forEach((tag) => tags.add(tag));
if (book.metadata?.publisher) {
publishers.add(book.metadata.publisher);
}
if (book.metadata?.seriesName) {
series.add(book.metadata.seriesName);
}
});
this.allAuthors = Array.from(authors);
this.allCategories = Array.from(categories);
this.allMoods = Array.from(moods);
this.allTags = Array.from(tags);
this.allPublishers = Array.from(publishers);
this.allSeries = Array.from(series);
});
}
private populateFormFromMetadata(metadata: BookMetadata): void {
@@ -654,7 +624,6 @@ export class MetadataEditorComponent implements OnInit {
summary: this.t.translate('metadata.editor.toast.successSummary'),
detail: this.t.translate('metadata.editor.toast.metadataUpdated'),
});
this.prepareAutoComplete();
this.metadataForm.markAsPristine();
},
error: (err: any) => {
@@ -937,6 +906,7 @@ export class MetadataEditorComponent implements OnInit {
event.originalEvent as HttpResponse<unknown>;
if (response && response.status === 200) {
this.isUploading = false;
this.bookService.handleBookMetadataUpdate(this.currentBookId);
} else {
this.isUploading = false;
this.messageService.add({
@@ -960,11 +930,9 @@ export class MetadataEditorComponent implements OnInit {
regenerateCover(bookId: number) {
this.bookMetadataManageService.regenerateCover(bookId).pipe(
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
next: () => {
this.messageService.add({
severity: "success",
summary: this.t.translate('metadata.editor.toast.successSummary'),
@@ -984,12 +952,10 @@ export class MetadataEditorComponent implements OnInit {
generateCustomCover(bookId: number) {
this.isGeneratingCover = true;
this.bookMetadataManageService.generateCustomCover(bookId).pipe(
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
finalize(() => this.isGeneratingCover = false),
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
next: () => {
this.messageService.add({
severity: "success",
summary: this.t.translate('metadata.editor.toast.successSummary'),
@@ -1008,11 +974,9 @@ export class MetadataEditorComponent implements OnInit {
regenerateAudiobookCover(bookId: number) {
this.bookMetadataManageService.regenerateAudiobookCover(bookId).pipe(
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
next: () => {
this.messageService.add({
severity: "success",
summary: this.t.translate('metadata.editor.toast.successSummary'),
@@ -1032,12 +996,10 @@ export class MetadataEditorComponent implements OnInit {
generateCustomAudiobookCover(bookId: number) {
this.isGeneratingAudiobookCover = true;
this.bookMetadataManageService.generateCustomAudiobookCover(bookId).pipe(
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
finalize(() => this.isGeneratingAudiobookCover = false),
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
next: () => {
this.messageService.add({
severity: "success",
summary: this.t.translate('metadata.editor.toast.successSummary'),
@@ -1130,23 +1092,12 @@ export class MetadataEditorComponent implements OnInit {
ref?.onClose.pipe(
take(1),
filter(result => !!result),
switchMap(() => this.bookService.getBookByIdFromAPI(this.currentBookId, false)),
takeUntilDestroyed(this.destroyRef)
).subscribe(updatedBook => {
this.bookService.handleBookUpdate(updatedBook);
});
}
canNavigatePrevious(): boolean {
return this.bookNavigationService.canNavigatePrevious();
}
canNavigateNext(): boolean {
return this.bookNavigationService.canNavigateNext();
).subscribe();
}
navigatePrevious(): void {
const prevBookId = this.bookNavigationService.getPreviousBookId();
const prevBookId = this.bookNavigationService.previousBookId();
if (prevBookId) {
if (this.autoSaveEnabled && this.metadataForm.dirty) {
this.saveMetadata().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.navigateToBook(prevBookId));
@@ -1157,7 +1108,7 @@ export class MetadataEditorComponent implements OnInit {
}
navigateNext(): void {
const nextBookId = this.bookNavigationService.getNextBookId();
const nextBookId = this.bookNavigationService.nextBookId();
if (nextBookId) {
if (this.autoSaveEnabled && this.metadataForm.dirty) {
this.saveMetadata().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.navigateToBook(nextBookId));
@@ -1178,11 +1129,6 @@ export class MetadataEditorComponent implements OnInit {
}
}
getNavigationPosition(): string {
const position = this.bookNavigationService.getCurrentPosition();
return position ? this.t.translate('metadata.editor.navigationPosition', {current: position.current, total: position.total}) : '';
}
isFieldVisible(field: keyof MetadataProviderSpecificFields): boolean {
return this.providerSpecificFields[field] ?? false;
}
@@ -1236,11 +1182,8 @@ export class MetadataEditorComponent implements OnInit {
ref?.onClose.pipe(
take(1),
filter(result => !!result),
switchMap(() => this.bookService.getBookByIdFromAPI(this.currentBookId, false)),
takeUntilDestroyed(this.destroyRef)
).subscribe(updatedBook => {
this.bookService.handleBookUpdate(updatedBook);
});
).subscribe();
}
onAudiobookCoverUpload(event: FileUploadEvent): void {
@@ -1248,11 +1191,7 @@ export class MetadataEditorComponent implements OnInit {
event.originalEvent as HttpResponse<unknown>;
if (response && response.status === 200) {
this.isUploading = false;
this.bookService.getBookByIdFromAPI(this.currentBookId, false).pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe(updatedBook => {
this.bookService.handleBookUpdate(updatedBook);
});
this.bookService.handleBookMetadataUpdate(this.currentBookId);
} else {
this.isUploading = false;
this.messageService.add({
@@ -1,4 +1,4 @@
@if (book$ | async; as book) {
@if (book; as book) {
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="metadata-picker" *transloco="let t; prefix: 'metadata.picker'">
<div class="dialog-body">
@if (detailLoading) {
@@ -1,19 +1,17 @@
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {Component, computed, DestroyRef, effect, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper} from '../../../../book/model/book.model';
import {MessageService} from 'primeng/api';
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
import {Button} from 'primeng/button';
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
import {AsyncPipe} from '@angular/common';
import {forkJoin, Observable} from 'rxjs';
import {Tooltip} from 'primeng/tooltip';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {BookService} from '../../../../book/service/book.service';
import {BookMetadataManageService} from '../../../../book/service/book-metadata-manage.service';
import {Textarea} from 'primeng/textarea';
import {filter, take} from 'rxjs/operators';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {AutoComplete, AutoCompleteSelectEvent} from 'primeng/autocomplete';
import {Image} from 'primeng/image';
import {Checkbox} from 'primeng/checkbox';
@@ -34,7 +32,6 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
InputText,
ReactiveFormsModule,
Tooltip,
AsyncPipe,
Textarea,
AutoComplete,
Image,
@@ -63,13 +60,36 @@ export class MetadataPickerComponent implements OnInit {
@Input() reviewMode!: boolean;
@Input() fetchedMetadata!: BookMetadata;
@Input() book$!: Observable<Book | null>;
@Input()
set book(value: Book | null) {
this.currentBook = value;
const metadata = value?.metadata;
if (!metadata) return;
if (this.reviewMode) {
this.metadataForm.reset();
this.copiedFields = {};
this.savedFields = {};
this.hoveredFields = {};
}
this.originalMetadata = metadata;
this.originalMetadata.thumbnailUrl = this.urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn);
this.currentBookId = metadata.bookId;
this.patchMetadataToForm(metadata, value);
}
get book(): Book | null {
return this.currentBook;
}
@Input() detailLoading = false;
@Output() goBack = new EventEmitter<boolean>();
currentBook: Book | null = null;
private allItems: Record<string, string[]> = {};
private get allItems(): Record<string, string[]> { return this.uniqueMetadata(); }
filteredItems: Record<string, string[]> = {};
authorInputValue = '';
@@ -90,6 +110,8 @@ export class MetadataPickerComponent implements OnInit {
private formBuilder = inject(MetadataFormBuilder);
private metadataUtils = inject(MetadataUtilsService);
private readonly t = inject(TranslocoService);
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
private enabledProviderFields: MetadataProviderSpecificFields | null = null;
@@ -130,64 +152,16 @@ export class MetadataPickerComponent implements OnInit {
.filter(item => item.toLowerCase().includes(query));
}
private readonly syncProviderFieldsEffect = effect(() => {
const settings = this.appSettingsService.appSettings();
if (settings?.metadataProviderSpecificFields) {
this.enabledProviderFields = settings.metadataProviderSpecificFields;
this.updateProviderFields();
this.updateBottomFields();
}
});
ngOnInit(): void {
this.appSettingsService.appSettings$
.pipe(
filter(settings => !!settings?.metadataProviderSpecificFields),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(settings => {
if (settings?.metadataProviderSpecificFields) {
this.enabledProviderFields = settings.metadataProviderSpecificFields;
this.updateProviderFields();
this.updateBottomFields();
}
});
this.bookService.bookState$
.pipe(
filter(bookState => bookState.loaded),
take(1)
)
.subscribe(bookState => {
const itemSets: Record<string, Set<string>> = {
authors: new Set<string>(),
categories: new Set<string>(),
moods: new Set<string>(),
tags: new Set<string>()
};
(bookState.books ?? []).forEach(book => {
for (const key of Object.keys(itemSets)) {
const values = book.metadata?.[key as keyof BookMetadata] as string[] | undefined;
values?.forEach(v => itemSets[key].add(v));
}
});
for (const key of Object.keys(itemSets)) {
this.allItems[key] = Array.from(itemSets[key]);
}
});
this.book$
.pipe(
filter((book): book is Book => !!book && !!book.metadata),
takeUntilDestroyed(this.destroyRef)
).subscribe((book) => {
if (this.reviewMode) {
this.metadataForm.reset();
this.copiedFields = {};
this.savedFields = {};
this.hoveredFields = {};
}
this.currentBook = book;
const metadata = book.metadata!;
this.originalMetadata = metadata;
this.originalMetadata.thumbnailUrl = this.urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn);
this.currentBookId = metadata.bookId;
this.patchMetadataToForm(metadata, book);
});
}
private patchMetadataToForm(metadata: BookMetadata, book: Book): void {
@@ -1,8 +1,8 @@
@if (selectedFetchedMetadata$ | async; as selectedFetchedMetadata) {
@if (selectedFetchedMetadata(); as selectedFetchedMetadata) {
<div class="metadata-container">
<app-metadata-picker
[fetchedMetadata]="selectedFetchedMetadata"
[book$]="book$"
[book]="book"
[detailLoading]="detailLoading"
(goBack)="onGoBack()">
</app-metadata-picker>
@@ -1,4 +1,4 @@
import {Component, inject, Input, OnChanges, OnDestroy, OnInit, SimpleChanges} from '@angular/core';
import {Component, effect, inject, Input, OnChanges, OnDestroy, OnInit, signal, SimpleChanges} from '@angular/core';
import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
import {InputText} from 'primeng/inputtext';
@@ -9,10 +9,7 @@ import {Book, BookMetadata} from '../../../../book/model/book.model';
import {AppSettings} from '../../../../../shared/model/app-settings.model';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {BehaviorSubject, combineLatest, Observable, Subject, Subscription, takeUntil} from 'rxjs';
import {filter, switchMap} from 'rxjs/operators';
import {ActivatedRoute} from '@angular/router';
import {AsyncPipe} from '@angular/common';
import {Subject, Subscription, takeUntil} from 'rxjs';
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
import {BookMetadataService} from '../../../../book/service/book-metadata.service';
import {Tooltip} from 'primeng/tooltip';
@@ -29,7 +26,6 @@ import {TranslocoDirective} from '@jsverse/transloco';
InputText,
MetadataPickerComponent,
MultiSelect,
AsyncPipe,
Tooltip,
TranslocoDirective
],
@@ -43,21 +39,48 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
loading: boolean = false;
searchTriggered = false;
@Input() book$!: Observable<Book | null>;
private currentBook: Book | null = null;
private currentSettings: AppSettings | null = null;
@Input()
set book(value: Book | null) {
this.currentBook = value;
this.syncFormFromState();
}
get book(): Book | null {
return this.currentBook;
}
@Input() isActiveTab: boolean = false;
selectedFetchedMetadata$ = new BehaviorSubject<BookMetadata | null>(null);
readonly selectedFetchedMetadata = signal<BookMetadata | null>(null);
detailLoading = false;
private formBuilder = inject(FormBuilder);
private bookMetadataService = inject(BookMetadataService);
private appSettingsService = inject(AppSettingsService);
private route = inject(ActivatedRoute);
private subscription: Subscription = new Subscription();
private cancelRequest$ = new Subject<void>();
private syncSettingsEffect = effect(() => {
const settings = this.appSettingsService.appSettings();
if (!settings) return;
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
this.currentSettings = settings;
const providerSettings = settings.metadataProviderSettings ?? {};
this.providers = Object.entries(providerSettings)
.filter(([_, value]) => !!value && typeof value === 'object' && 'enabled' in value && (value as any).enabled)
.map(([key]) => key.charAt(0).toUpperCase() + key.slice(1));
const currentProviders = this.form.get('provider')?.value || [];
const validProviders = currentProviders.filter((p: string) => this.providers.includes(p));
if (validProviders.length !== currentProviders.length) {
this.form.patchValue({provider: validProviders.length > 0 ? validProviders : null});
}
this.syncFormFromState();
});
providerCounts: Map<string, number> = new Map();
providerLoading: Map<string, boolean> = new Map();
@@ -87,64 +110,39 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
}
ngOnInit() {
this.subscription.add(
this.appSettings$
.pipe(filter(settings => !!settings))
.subscribe(settings => {
const providerSettings = settings!.metadataProviderSettings ?? {};
this.providers = Object.entries(providerSettings)
.filter(([_, value]) => !!value && typeof value === 'object' && 'enabled' in value && (value as any).enabled)
.map(([key]) => key.charAt(0).toUpperCase() + key.slice(1));
}
const currentProviders = this.form.get('provider')?.value || [];
const validProviders = currentProviders.filter((p: string) => this.providers.includes(p));
if (validProviders.length !== currentProviders.length) {
this.form.patchValue({provider: validProviders.length > 0 ? validProviders : null});
}
})
);
private syncFormFromState(): void {
if (!this.currentBook || !this.currentSettings) {
return;
}
this.subscription.add(
this.route.paramMap
.pipe(
switchMap(params => {
const bookId = +params.get('id')!;
if (this.bookId !== bookId) {
this.bookId = bookId;
this.cancelRequest$.next();
this.loading = false;
this.allFetchedMetadata = [];
this.filteredMetadata = [];
this.providerCounts.clear();
this.selectedFetchedMetadata$.next(null);
}
return combineLatest([this.book$, this.appSettings$]);
}),
filter(([book, settings]) => !!book && !!settings),
)
.subscribe(([book, settings]) => {
const bookChanged = book!.id !== this.bookId;
if (bookChanged) {
this.resetFormFromBook(book!);
if (settings!.autoBookSearch) {
if (this.isActiveTab) {
this.onSubmit();
} else {
this.pendingAutoSearch = true;
}
}
} else {
this.updateFormFromBook(book!);
}
})
);
const bookChanged = this.currentBook.id !== this.bookId;
if (bookChanged) {
this.resetFormFromBook(this.currentBook);
if (this.currentSettings.autoBookSearch) {
if (this.isActiveTab) {
this.onSubmit();
} else {
this.pendingAutoSearch = true;
}
}
return;
}
this.updateFormFromBook(this.currentBook);
}
private resetFormFromBook(book: Book): void {
this.selectedFetchedMetadata$.next(null);
this.cancelRequest$.next();
this.loading = false;
this.detailLoading = false;
this.selectedFetchedMetadata.set(null);
this.allFetchedMetadata = [];
this.filteredMetadata = [];
this.providerCounts.clear();
this.providerLoading.clear();
this.providerCompletionStatus.clear();
this.metadataByProvider.clear();
this.selectedProviderFilters = new Set(['all']);
this.bookId = book.id;
@@ -175,7 +173,6 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
this.cancelRequest$.next();
this.cancelRequest$.complete();
this.subscription.unsubscribe();
this.selectedFetchedMetadata$.complete();
}
get isSearchEnabled(): boolean {
@@ -374,7 +371,7 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
}
onBookClick(fetchedMetadata: BookMetadata) {
this.selectedFetchedMetadata$.next(fetchedMetadata);
this.selectedFetchedMetadata.set(fetchedMetadata);
const enrichment = this.getDetailEnrichmentInfo(fetchedMetadata);
@@ -384,10 +381,10 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
.pipe(takeUntil(this.cancelRequest$))
.subscribe({
next: (enriched) => {
const current = this.selectedFetchedMetadata$.value;
const current = this.selectedFetchedMetadata();
const currentId = current && this.getProviderItemId(current, enrichment.provider);
if (currentId === enrichment.id) {
this.selectedFetchedMetadata$.next(enriched);
this.selectedFetchedMetadata.set(enriched);
}
this.detailLoading = false;
},
@@ -433,7 +430,7 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
onGoBack() {
this.detailLoading = false;
this.selectedFetchedMetadata$.next(null);
this.selectedFetchedMetadata.set(null);
}
sanitizeHtml(htmlString: string | null | undefined): string {
@@ -1,4 +1,4 @@
@if (book$ | async; as book) {
@if (book; as book) {
<div class="metadata-viewer-container" *transloco="let t; prefix: 'metadata.viewer'">
<div class="metadata-header">
@@ -61,7 +61,7 @@
</div>
</div>
@if (navigationState$ | async) {
@if (navigationState()) {
<div class="navigation-buttons-mobile">
<p-button
icon="pi pi-chevron-left"
@@ -74,7 +74,7 @@
tooltipPosition="bottom">
</p-button>
<span class="navigation-position">
{{ getNavigationPosition() }}
{{ navigationPosition() }}
</span>
<p-button
icon="pi pi-chevron-right"
@@ -620,10 +620,10 @@
}
</div>
@if (userService.userState$ | async; as userState) {
@if (userService.currentUser(); as currentUser) {
<div class="action-buttons-container">
<div class="action-buttons">
@if (navigationState$ | async) {
@if (navigationState()) {
<div class="action-group navigation-group">
<p-button
icon="pi pi-chevron-left"
@@ -635,7 +635,7 @@
tooltipPosition="bottom">
</p-button>
<span class="navigation-position">
{{ getNavigationPosition() }}
{{ navigationPosition() }}
</span>
<p-button
icon="pi pi-chevron-right"
@@ -651,28 +651,22 @@
}
@if (hasDigitalFile(book)) {
<div class="action-group primary-actions">
@if (readMenuItems$ | async; as readItems) {
@if (readItems.length > 0) {
<p-splitbutton [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" [model]="readItems" (onClick)="read(book.id)" severity="primary" class="read-button-responsive"/>
} @else {
<p-button [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" (onClick)="read(book.id)" severity="primary" class="read-button-responsive"/>
}
@if (readMenuItems().length > 0) {
<p-splitbutton [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" [model]="readMenuItems()" (onClick)="read(book.id)" severity="primary" class="read-button-responsive"/>
} @else {
<p-button [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" (onClick)="read(book.id)" severity="primary" class="read-button-responsive"/>
}
</div>
}
<div class="action-group secondary-actions">
@if ((userState.user!.permissions.canDownload || userState.user!.permissions.admin) && hasAnyFiles(book)) {
@if ((currentUser.permissions.canDownload || currentUser.permissions.admin) && hasAnyFiles(book)) {
@if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) {
@if (downloadMenuItems$ | async; as downloadItems) {
<p-splitbutton [label]="(getDisplayFormat(book.primaryFile) ?? 'File') + ' · ' + formatFileSize(book.primaryFile)" icon="pi pi-download" [model]="downloadItems" (onClick)="download(book)" severity="success" outlined class="mobile-icon-only"/>
}
<p-splitbutton [label]="(getDisplayFormat(book.primaryFile) ?? 'File') + ' · ' + formatFileSize(book.primaryFile)" icon="pi pi-download" [model]="downloadMenuItems()" (onClick)="download(book)" severity="success" outlined class="mobile-icon-only"/>
} @else {
<p-button [label]="(getDisplayFormat(book.primaryFile) ?? 'File') + ' · ' + formatFileSize(book.primaryFile)" icon="pi pi-download" severity="success" outlined (onClick)="download(book)" class="mobile-icon-only"></p-button>
}
}
@if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) {
@if (currentUser.permissions.canEditMetadata || currentUser.permissions.admin) {
<p-button
[label]="isAutoFetching ? t('fetchingBtn') : t('fetchMetadataBtn')"
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
@@ -685,11 +679,9 @@
class="mobile-icon-only">
</p-button>
}
@if (otherItems$ | async; as otherItems) {
@if (otherItems.length > 0) {
<p-button icon="pi pi-ellipsis-v" severity="info" outlined (click)="entitymenu.toggle($event)"></p-button>
<p-tieredMenu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-tieredMenu>
}
@if (otherItems().length > 0) {
<p-button icon="pi pi-ellipsis-v" severity="info" outlined (click)="entitymenu.toggle($event)"></p-button>
<p-tieredMenu #entitymenu [model]="otherItems()" [popup]="true" appendTo="body"></p-tieredMenu>
}
</div>
</div>
@@ -1,7 +1,6 @@
import {AfterViewChecked, Component, DestroyRef, ElementRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, Input, OnChanges, OnInit, signal, SimpleChanges, ViewChild} from '@angular/core';
import {Button} from 'primeng/button';
import {AsyncPipe, DecimalPipe, NgClass} from '@angular/common';
import {combineLatest, Observable} from 'rxjs';
import {DecimalPipe, NgClass} from '@angular/common';
import {BookService} from '../../../../book/service/book.service';
import {BookFileService} from '../../../../book/service/book-file.service';
import {Rating, RatingRateEvent} from 'primeng/rating';
@@ -18,7 +17,7 @@ import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {ProgressBar} from 'primeng/progressbar';
import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type.enum';
import {Router} from '@angular/router';
import {filter, map, switchMap, take, tap} from 'rxjs/operators';
import {filter, take, tap} from 'rxjs/operators';
import {Menu} from 'primeng/menu';
import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
import {DatePicker} from 'primeng/datepicker';
@@ -46,10 +45,28 @@ import DOMPurify from 'dompurify';
standalone: true,
templateUrl: './metadata-viewer.component.html',
styleUrl: './metadata-viewer.component.scss',
imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, MetadataTabsComponent, TranslocoDirective, TranslocoPipe, Dialog, Checkbox]
imports: [Button, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, MetadataTabsComponent, TranslocoDirective, TranslocoPipe, Dialog, Checkbox]
})
export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChecked {
@Input() book$!: Observable<Book | null>;
private currentBook = signal<Book | null>(null);
@Input()
set book(value: Book | null) {
this.currentBook.set(value);
if (!value?.metadata) {
return;
}
this.isAutoFetching = false;
this.loadBooksInSeriesAndFilterRecommended(value.metadata.bookId);
this.selectedReadStatus = value.readStatus ?? ReadStatus.UNREAD;
}
get book(): Book | null {
return this.currentBook();
}
@Input() recommendedBooks: BookRecommendation[] = [];
private originalRecommendedBooks: BookRecommendation[] = [];
@@ -64,16 +81,305 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
private authorService = inject(AuthorService);
protected urlHelper = inject(UrlHelperService);
protected userService = inject(UserService);
private appSettingsService = inject(AppSettingsService);
private confirmationService = inject(ConfirmationService);
private router = inject(Router);
private destroyRef = inject(DestroyRef);
private dialogRef?: DynamicDialogRef;
private userState = this.userService.currentUser;
private appSettings = this.appSettingsService.appSettings;
readMenuItems$!: Observable<MenuItem[]>;
refreshMenuItems$!: Observable<MenuItem[]>;
otherItems$!: Observable<MenuItem[]>;
downloadMenuItems$!: Observable<MenuItem[]>;
readonly readMenuItems = computed<MenuItem[]>(() => {
const book = this.currentBook();
if (!book) {
return [];
}
const items: MenuItem[] = [];
const primaryType = book.primaryFile?.bookType;
if (primaryType === 'EPUB') {
items.push({
label: this.t.translate('metadata.viewer.menuStreamingReader'),
icon: 'pi pi-play',
command: () => this.read(book.id, 'epub-streaming')
});
}
const readableAlternatives = book.alternativeFormats?.filter(f =>
f.bookType && ['PDF', 'EPUB', 'FB2', 'MOBI', 'AZW3', 'CBX', 'AUDIOBOOK'].includes(f.bookType)
) ?? [];
const uniqueAltTypes = [...new Set(readableAlternatives.map(f => f.bookType))];
if (uniqueAltTypes.length > 0 && items.length > 0) {
items.push({separator: true});
}
uniqueAltTypes.forEach(formatType => {
if (formatType === 'EPUB') {
items.push({
label: formatType,
icon: this.getFileIcon(formatType),
items: [
{
label: this.t.translate('metadata.viewer.menuStandardReader'),
icon: 'pi pi-book',
command: () => this.read(book.id, undefined, formatType)
},
{
label: this.t.translate('metadata.viewer.menuStreamingReader'),
icon: 'pi pi-play',
command: () => this.read(book.id, 'epub-streaming', formatType)
}
]
});
return;
}
items.push({
label: formatType,
icon: this.getFileIcon(formatType ?? null),
command: () => this.read(book.id, undefined, formatType)
});
});
return items;
});
readonly downloadMenuItems = computed<MenuItem[]>(() => {
const book = this.currentBook();
if (!book || (!book.alternativeFormats?.length && !book.supplementaryFiles?.length)) {
return [];
}
const items: MenuItem[] = [];
if (book.alternativeFormats?.length) {
book.alternativeFormats.forEach(format => {
items.push({
label: `${format.bookType ?? 'File'} · ${this.formatFileSize(format)}`,
icon: this.getFileIcon(format.bookType ?? null),
command: () => this.downloadAdditionalFile(book, format.id)
});
});
}
if (book.alternativeFormats?.length && book.supplementaryFiles?.length) {
items.push({separator: true});
}
if (book.supplementaryFiles?.length) {
book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
items.push({
label: `${this.truncateFileName(file.fileName, 20)} · ${this.formatFileSize(file)}`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'},
command: () => this.downloadAdditionalFile(book, file.id)
});
});
}
return items;
});
readonly otherItems = computed<MenuItem[]>(() => {
const book = this.currentBook();
const user = this.userState();
const appSettings = this.appSettings();
if (!book || !user) {
return [];
}
const permissions = user.permissions;
const items: MenuItem[] = [];
items.push({
label: this.t.translate('metadata.viewer.menuShelf'),
icon: 'pi pi-folder',
command: () => this.assignShelf(book.id)
});
if (permissions?.canManageLibrary || permissions?.admin) {
const isPhysical = book.isPhysical ?? false;
items.push({
label: isPhysical
? this.t.translate('metadata.viewer.menuUnmarkPhysical')
: this.t.translate('metadata.viewer.menuMarkPhysical'),
icon: isPhysical ? 'pi pi-times-circle' : 'pi pi-book',
command: () => {
this.bookService.togglePhysicalFlag(book.id, !isPhysical).subscribe();
}
});
}
if (permissions?.canUpload || permissions?.admin) {
items.push({
label: this.t.translate('metadata.viewer.menuUploadFile'),
icon: 'pi pi-upload',
command: () => {
this.bookDialogHelperService.openAdditionalFileUploaderDialog(book);
},
});
}
const hasFiles = this.hasAnyFiles(book);
if (hasFiles && (permissions?.canManageLibrary || permissions?.admin) && appSettings?.diskType === 'LOCAL') {
items.push({
label: this.t.translate('metadata.viewer.menuOrganizeFiles'),
icon: 'pi pi-arrows-h',
command: () => {
this.openFileMoverDialog(book.id);
},
});
}
if (hasFiles && (permissions?.canEmailBook || permissions?.admin)) {
items.push({
label: this.t.translate('metadata.viewer.menuSendBook'),
icon: 'pi pi-send',
items: [
{
label: this.t.translate('metadata.viewer.menuQuickSend'),
icon: 'pi pi-bolt',
command: () => this.quickSend(book)
},
{
label: this.t.translate('metadata.viewer.menuCustomSend'),
icon: 'pi pi-cog',
command: () => {
this.bookDialogHelperService.openCustomSendDialog(book);
}
}
]
});
}
const isSingleFileBook = hasFiles && !book.alternativeFormats?.length;
const library = this.libraryService.findLibraryById(book.libraryId);
const isMultiFormatLibrary = !library?.allowedFormats?.length || library.allowedFormats.length > 1;
if (isSingleFileBook && isMultiFormatLibrary && (permissions?.canManageLibrary || permissions?.admin)) {
items.push({
label: this.t.translate('metadata.viewer.menuAttachToAnotherBook'),
icon: 'pi pi-link',
command: () => {
this.bookDialogHelperService.openBookFileAttacherDialog(book);
},
});
}
if (permissions?.canDeleteBook || permissions?.admin) {
const deleteFormatItems: MenuItem[] = [];
const hasMultipleFormats = (book.alternativeFormats?.length ?? 0) > 0;
if (book.primaryFile) {
const extension = this.getFileExtension(book.primaryFile.filePath);
const isPrimaryOnly = !hasMultipleFormats;
const truncatedName = this.truncateFileName(book.primaryFile.fileName, 25);
deleteFormatItems.push({
label: `${truncatedName} (${this.formatFileSize(book.primaryFile)}) [Primary]`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: book.primaryFile.fileName, tooltipPosition: 'left'},
command: () => this.deleteBookFile(book, book.primaryFile!.id, book.primaryFile!.fileName || 'file', true, isPrimaryOnly)
});
}
if (book.alternativeFormats?.length) {
book.alternativeFormats.forEach(format => {
const extension = this.getFileExtension(format.filePath);
const truncatedName = this.truncateFileName(format.fileName, 25);
deleteFormatItems.push({
label: `${truncatedName} (${this.formatFileSize(format)})`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: format.fileName, tooltipPosition: 'left'},
command: () => this.deleteBookFile(book, format.id, format.fileName || 'file', false, false)
});
});
}
if (deleteFormatItems.length > 0) {
items.push({
label: this.t.translate('metadata.viewer.menuDeleteFileFormats'),
icon: 'pi pi-file',
items: deleteFormatItems
});
}
if (book.supplementaryFiles?.length) {
const deleteSupplementaryItems: MenuItem[] = [];
book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
const truncatedName = this.truncateFileName(file.fileName, 25);
deleteSupplementaryItems.push({
label: `${truncatedName} (${this.formatFileSize(file)})`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'},
command: () => this.deleteAdditionalFile(book.id, file.id, file.fileName || 'file')
});
});
items.push({
label: this.t.translate('metadata.viewer.menuDeleteSupplementaryFiles'),
icon: 'pi pi-paperclip',
items: deleteSupplementaryItems
});
}
const allFormats: string[] = [];
if (book.primaryFile?.fileName) {
allFormats.push(book.primaryFile.fileName);
}
book.alternativeFormats?.forEach(f => {
if (f.fileName) allFormats.push(f.fileName);
});
book.supplementaryFiles?.forEach(f => {
if (f.fileName) allFormats.push(f.fileName);
});
const isPhysical = !hasFiles;
const fileListMessage = allFormats.length > 0
? `\n\nThe following files will be permanently deleted:\n• ${allFormats.join('\n• ')}`
: '';
const deleteLabel = isPhysical ? this.t.translate('metadata.viewer.menuDeleteBook') : this.t.translate('metadata.viewer.menuDeleteBookAllFiles');
const deleteMessage = isPhysical
? this.t.translate('metadata.viewer.confirm.deleteBookMessage', { title: book.metadata?.title })
: this.t.translate('metadata.viewer.confirm.deleteBookAllFilesMessage', { title: book.metadata?.title, fileList: fileListMessage });
const deleteAcceptLabel = isPhysical ? this.t.translate('common.delete') : this.t.translate('metadata.viewer.confirm.deleteEverythingBtn');
items.push({
label: deleteLabel,
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: deleteMessage,
header: deleteLabel,
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
rejectIcon: 'pi pi-times',
acceptLabel: deleteAcceptLabel,
rejectLabel: this.t.translate('common.cancel'),
acceptButtonStyleClass: 'p-button-danger',
rejectButtonStyleClass: 'p-button-outlined',
accept: () => {
this.bookService.deleteBooks(new Set([book.id])).subscribe({
next: () => {
if (this.metadataCenterViewMode === 'route') {
this.router.navigate(['/dashboard']);
} else {
this.dialogRef?.close();
}
},
error: () => {
}
});
}
});
},
});
}
return items;
});
bookInSeries: Book[] = [];
@ViewChild(Image) private coverImage?: Image;
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
@@ -106,10 +412,16 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
private bookNavigationService = inject(BookNavigationService);
private metadataHostService = inject(BookMetadataHostService);
private appSettingsService = inject(AppSettingsService);
private appSettings$ = this.appSettingsService.appSettings$;
amazonDomain = 'com';
navigationState$ = this.bookNavigationService.getNavigationState();
readonly navigationState = this.bookNavigationService.navigationState;
readonly canNavigatePrevious = this.bookNavigationService.canNavigatePrevious;
readonly canNavigateNext = this.bookNavigationService.canNavigateNext;
readonly navigationPosition = computed(() => {
const position = this.bookNavigationService.currentPosition();
return position
? this.t.translate('metadata.viewer.navigationPosition', { current: position.current, total: position.total })
: '';
});
ngOnInit(): void {
this.destroyRef.onDestroy(() => this.coverImage?.closePreview());
@@ -118,359 +430,24 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
window.addEventListener('popstate', onPopState);
this.destroyRef.onDestroy(() => window.removeEventListener('popstate', onPopState));
this.readMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => {
const items: MenuItem[] = [];
const primaryType = book.primaryFile?.bookType;
if (primaryType === 'EPUB') {
items.push({
label: this.t.translate('metadata.viewer.menuStreamingReader'),
icon: 'pi pi-play',
command: () => this.read(book.id, 'epub-streaming')
});
}
const user = this.userService.currentUser();
if (user) {
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
}
// Get readable alternative formats and group by type
const readableAlternatives = book.alternativeFormats?.filter(f =>
f.bookType && ['PDF', 'EPUB', 'FB2', 'MOBI', 'AZW3', 'CBX', 'AUDIOBOOK'].includes(f.bookType)
) ?? [];
// Get unique format types from alternatives
const uniqueAltTypes = [...new Set(readableAlternatives.map(f => f.bookType))];
if (uniqueAltTypes.length > 0) {
if (items.length > 0) {
items.push({separator: true});
}
uniqueAltTypes.forEach(formatType => {
if (formatType === 'EPUB') {
// For EPUB, offer both standard and streaming readers
items.push({
label: formatType,
icon: this.getFileIcon(formatType),
items: [
{
label: this.t.translate('metadata.viewer.menuStandardReader'),
icon: 'pi pi-book',
command: () => this.read(book.id, undefined, formatType)
},
{
label: this.t.translate('metadata.viewer.menuStreamingReader'),
icon: 'pi pi-play',
command: () => this.read(book.id, 'epub-streaming', formatType)
}
]
});
} else {
// For other formats, just show the type
items.push({
label: formatType,
icon: this.getFileIcon(formatType ?? null),
command: () => this.read(book.id, undefined, formatType)
});
}
});
}
return items;
})
);
this.downloadMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null &&
((book.alternativeFormats !== undefined && book.alternativeFormats.length > 0) ||
(book.supplementaryFiles !== undefined && book.supplementaryFiles.length > 0))),
map((book): MenuItem[] => {
const items: MenuItem[] = [];
// Add alternative formats with type and size
if (book.alternativeFormats && book.alternativeFormats.length > 0) {
book.alternativeFormats.forEach(format => {
items.push({
label: `${format.bookType ?? 'File'} · ${this.formatFileSize(format)}`,
icon: this.getFileIcon(format.bookType ?? null),
command: () => this.downloadAdditionalFile(book, format.id)
});
});
}
// Add separator if both types exist
if (book.alternativeFormats && book.alternativeFormats.length > 0 &&
book.supplementaryFiles && book.supplementaryFiles.length > 0) {
items.push({separator: true});
}
// Add supplementary files
if (book.supplementaryFiles && book.supplementaryFiles.length > 0) {
book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
items.push({
label: `${this.truncateFileName(file.fileName, 20)} · ${this.formatFileSize(file)}`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'},
command: () => this.downloadAdditionalFile(book, file.id)
});
});
}
return items;
})
);
this.otherItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
switchMap(book =>
combineLatest([
this.userService.userState$.pipe(take(1)),
this.appSettingsService.appSettings$.pipe(take(1))
]).pipe(
map(([userState, appSettings]) => {
const items: MenuItem[] = [];
items.push({
label: this.t.translate('metadata.viewer.menuShelf'),
icon: 'pi pi-folder',
command: () => this.assignShelf(book.id)
});
if (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin) {
const isPhysical = book.isPhysical ?? false;
items.push({
label: isPhysical
? this.t.translate('metadata.viewer.menuUnmarkPhysical')
: this.t.translate('metadata.viewer.menuMarkPhysical'),
icon: isPhysical ? 'pi pi-times-circle' : 'pi pi-book',
command: () => {
this.bookService.togglePhysicalFlag(book.id, !isPhysical).subscribe();
}
});
}
// Add allowed submenus based on user permissions
if (userState?.user?.permissions.canUpload || userState?.user?.permissions.admin) {
items.push({
label: this.t.translate('metadata.viewer.menuUploadFile'),
icon: 'pi pi-upload',
command: () => {
this.bookDialogHelperService.openAdditionalFileUploaderDialog(book);
},
});
}
const hasFiles = this.hasAnyFiles(book);
if (hasFiles && (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin) && appSettings?.diskType === 'LOCAL') {
items.push({
label: this.t.translate('metadata.viewer.menuOrganizeFiles'),
icon: 'pi pi-arrows-h',
command: () => {
this.openFileMoverDialog(book.id);
},
});
}
if (hasFiles && (userState?.user?.permissions.canEmailBook || userState?.user?.permissions.admin)) {
items.push({
label: this.t.translate('metadata.viewer.menuSendBook'),
icon: 'pi pi-send',
items: [
{
label: this.t.translate('metadata.viewer.menuQuickSend'),
icon: 'pi pi-bolt',
command: () => this.quickSend(book)
},
{
label: this.t.translate('metadata.viewer.menuCustomSend'),
icon: 'pi pi-cog',
command: () => {
this.bookDialogHelperService.openCustomSendDialog(book);
}
}
]
});
}
// Show "Attach to Another Book" for single-file books (detached books) - not for physical books
// Hide in single-format libraries where attaching provides no cross-format benefit
const isSingleFileBook = hasFiles && !book.alternativeFormats?.length;
const library = this.libraryService.findLibraryById(book.libraryId);
const isMultiFormatLibrary = !library?.allowedFormats?.length || library.allowedFormats.length > 1;
if (isSingleFileBook && isMultiFormatLibrary && (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin)) {
items.push({
label: this.t.translate('metadata.viewer.menuAttachToAnotherBook'),
icon: 'pi pi-link',
command: () => {
this.bookDialogHelperService.openBookFileAttacherDialog(book);
},
});
}
if (userState?.user?.permissions.canDeleteBook || userState?.user?.permissions.admin) {
// Delete File Formats submenu - allows deleting individual book format files
const deleteFormatItems: MenuItem[] = [];
const hasMultipleFormats = (book.alternativeFormats?.length ?? 0) > 0;
// Add primary file if it exists
if (book.primaryFile) {
const extension = this.getFileExtension(book.primaryFile.filePath);
const isPrimaryOnly = !hasMultipleFormats;
const truncatedName = this.truncateFileName(book.primaryFile.fileName, 25);
deleteFormatItems.push({
label: `${truncatedName} (${this.formatFileSize(book.primaryFile)}) [Primary]`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: book.primaryFile.fileName, tooltipPosition: 'left'},
command: () => this.deleteBookFile(book, book.primaryFile!.id, book.primaryFile!.fileName || 'file', true, isPrimaryOnly)
});
}
// Add alternative formats
if (book.alternativeFormats && book.alternativeFormats.length > 0) {
book.alternativeFormats.forEach(format => {
const extension = this.getFileExtension(format.filePath);
const truncatedName = this.truncateFileName(format.fileName, 25);
deleteFormatItems.push({
label: `${truncatedName} (${this.formatFileSize(format)})`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: format.fileName, tooltipPosition: 'left'},
command: () => this.deleteBookFile(book, format.id, format.fileName || 'file', false, false)
});
});
}
if (deleteFormatItems.length > 0) {
items.push({
label: this.t.translate('metadata.viewer.menuDeleteFileFormats'),
icon: 'pi pi-file',
items: deleteFormatItems
});
}
// Delete Supplementary Files submenu - for non-book files
if (book.supplementaryFiles && book.supplementaryFiles.length > 0) {
const deleteSupplementaryItems: MenuItem[] = [];
book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
const truncatedName = this.truncateFileName(file.fileName, 25);
deleteSupplementaryItems.push({
label: `${truncatedName} (${this.formatFileSize(file)})`,
icon: this.getFileIcon(extension),
tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'},
command: () => this.deleteAdditionalFile(book.id, file.id, file.fileName || 'file')
});
});
items.push({
label: this.t.translate('metadata.viewer.menuDeleteSupplementaryFiles'),
icon: 'pi pi-paperclip',
items: deleteSupplementaryItems
});
}
// Delete Book & All Files - deletes the entire book entity
const allFormats: string[] = [];
if (book.primaryFile?.fileName) {
allFormats.push(book.primaryFile.fileName);
}
book.alternativeFormats?.forEach(f => {
if (f.fileName) allFormats.push(f.fileName);
});
book.supplementaryFiles?.forEach(f => {
if (f.fileName) allFormats.push(f.fileName);
});
const isPhysical = !hasFiles;
const fileListMessage = allFormats.length > 0
? `\n\nThe following files will be permanently deleted:\n• ${allFormats.join('\n• ')}`
: '';
const deleteLabel = isPhysical ? this.t.translate('metadata.viewer.menuDeleteBook') : this.t.translate('metadata.viewer.menuDeleteBookAllFiles');
const deleteMessage = isPhysical
? this.t.translate('metadata.viewer.confirm.deleteBookMessage', { title: book.metadata?.title })
: this.t.translate('metadata.viewer.confirm.deleteBookAllFilesMessage', { title: book.metadata?.title, fileList: fileListMessage });
const deleteAcceptLabel = isPhysical ? this.t.translate('common.delete') : this.t.translate('metadata.viewer.confirm.deleteEverythingBtn');
items.push({
label: deleteLabel,
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: deleteMessage,
header: deleteLabel,
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
rejectIcon: 'pi pi-times',
acceptLabel: deleteAcceptLabel,
rejectLabel: this.t.translate('common.cancel'),
acceptButtonStyleClass: 'p-button-danger',
rejectButtonStyleClass: 'p-button-outlined',
accept: () => {
this.bookService.deleteBooks(new Set([book.id])).subscribe({
next: () => {
if (this.metadataCenterViewMode === 'route') {
this.router.navigate(['/dashboard']);
} else {
this.dialogRef?.close();
}
},
error: () => {
}
});
}
});
},
});
}
return items;
})
)
)
);
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
take(1)
)
.subscribe(userState => {
this.metadataCenterViewMode = userState.user?.userSettings.metadataCenterViewMode ?? 'route';
});
this.book$
.pipe(
takeUntilDestroyed(this.destroyRef),
filter((book): book is Book => book != null && book.metadata != null)
)
.subscribe(book => {
this.isAutoFetching = false;
this.loadBooksInSeriesAndFilterRecommended(book.metadata!.bookId);
this.selectedReadStatus = book.readStatus ?? ReadStatus.UNREAD;
});
this.appSettings$
.pipe(
filter(settings => settings != null),
take(1)
)
.subscribe(settings => {
this.amazonDomain = settings?.metadataProviderSettings?.amazon?.domain ?? 'com';
});
const settings = this.appSettingsService.appSettings();
if (settings) {
this.amazonDomain = settings.metadataProviderSettings?.amazon?.domain ?? 'com';
}
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['recommendedBooks']) {
this.originalRecommendedBooks = [...this.recommendedBooks];
this.withCurrentBook(book => this.filterRecommendations(book));
this.filterRecommendations(this.book);
}
}
private withCurrentBook(callback: (book: Book | null) => void): void {
this.book$.pipe(take(1)).subscribe(callback);
}
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
this.bookService.getBooksInSeries(bookId).pipe(
tap(series => {
@@ -478,9 +455,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
this.bookInSeries = series;
this.originalRecommendedBooks = [...this.recommendedBooks];
}),
switchMap(() => this.book$.pipe(take(1))),
takeUntilDestroyed(this.destroyRef)
).subscribe(book => this.filterRecommendations(book));
).subscribe(() => this.filterRecommendations(this.book));
}
private filterRecommendations(book: Book | null): void {
@@ -695,7 +671,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
}
assignShelf(bookId: number) {
this.bookDialogHelperService.openShelfAssignerDialog((this.bookService.getBookByIdFromState(bookId) as Book), null);
this.bookDialogHelperService.openShelfAssignerDialog((this.bookService.findBookById(bookId) as Book), null);
}
updateReadStatus(status: ReadStatus): void {
@@ -703,31 +679,30 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
return;
}
this.book$.pipe(take(1)).subscribe(book => {
if (!book || !book.id) {
return;
}
const book = this.book;
if (!book?.id) {
return;
}
this.bookService.updateBookReadStatus(book.id, status).subscribe({
next: (updatedBooks) => {
this.selectedReadStatus = status;
this.messageService.add({
severity: 'success',
summary: this.t.translate('metadata.viewer.toast.readStatusUpdatedSummary'),
detail: this.t.translate('metadata.viewer.toast.readStatusUpdatedDetail', { status: this.getStatusLabel(status) }),
life: 2000
});
},
error: (err) => {
console.error('Failed to update read status:', err);
this.messageService.add({
severity: 'error',
summary: this.t.translate('metadata.viewer.toast.readStatusFailedSummary'),
detail: this.t.translate('metadata.viewer.toast.readStatusFailedDetail'),
life: 3000
});
}
});
this.bookService.updateBookReadStatus(book.id, status).subscribe({
next: () => {
this.selectedReadStatus = status;
this.messageService.add({
severity: 'success',
summary: this.t.translate('metadata.viewer.toast.readStatusUpdatedSummary'),
detail: this.t.translate('metadata.viewer.toast.readStatusUpdatedDetail', { status: this.getStatusLabel(status) }),
life: 2000
});
},
error: (err) => {
console.error('Failed to update read status:', err);
this.messageService.add({
severity: 'error',
summary: this.t.translate('metadata.viewer.toast.readStatusFailedSummary'),
detail: this.t.translate('metadata.viewer.toast.readStatusFailedDetail'),
life: 3000
});
}
});
}
@@ -1272,23 +1247,15 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
protected readonly ResetProgressTypes = ResetProgressTypes;
protected readonly ReadStatus = ReadStatus;
canNavigatePrevious(): boolean {
return this.bookNavigationService.canNavigatePrevious();
}
canNavigateNext(): boolean {
return this.bookNavigationService.canNavigateNext();
}
navigatePrevious(): void {
const prevBookId = this.bookNavigationService.getPreviousBookId();
const prevBookId = this.bookNavigationService.previousBookId();
if (prevBookId) {
this.navigateToBook(prevBookId);
}
}
navigateNext(): void {
const nextBookId = this.bookNavigationService.getNextBookId();
const nextBookId = this.bookNavigationService.nextBookId();
if (nextBookId) {
this.navigateToBook(nextBookId);
}
@@ -1305,11 +1272,6 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
}
}
getNavigationPosition(): string {
const position = this.bookNavigationService.getCurrentPosition();
return position ? this.t.translate('metadata.viewer.navigationPosition', { current: position.current, total: position.total }) : '';
}
hasDigitalFile(book: Book): boolean {
return !!book?.primaryFile;
}
@@ -1,6 +1,6 @@
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {filter, switchMap, takeUntil} from 'rxjs/operators';
import {Component, inject, Input, OnDestroy} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {Book} from '../../../../book/model/book.model';
import {SidecarMetadata, SidecarService, SidecarSyncStatus} from '../../../service/sidecar.service';
import {MessageService} from 'primeng/api';
@@ -17,8 +17,21 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
styleUrls: ['./sidecar-viewer.component.scss'],
imports: [Button, Tag, Tooltip, JsonPipe, DatePipe, TranslocoDirective]
})
export class SidecarViewerComponent implements OnInit, OnDestroy {
@Input() book$!: Observable<Book>;
export class SidecarViewerComponent implements OnDestroy {
@Input()
set book(value: Book | null) {
if (!value) {
this.currentBookId = null;
this.sidecarContent = null;
this.syncStatus = 'NOT_APPLICABLE';
this.loading = false;
this.error = null;
return;
}
this.currentBookId = value.id;
this.loadSidecarData(value.id);
}
private sidecarService = inject(SidecarService);
private messageService = inject(MessageService);
@@ -33,16 +46,6 @@ export class SidecarViewerComponent implements OnInit, OnDestroy {
currentBookId: number | null = null;
error: string | null = null;
ngOnInit(): void {
this.book$.pipe(
filter((book): book is Book => !!book),
takeUntil(this.destroy$)
).subscribe(book => {
this.currentBookId = book.id;
this.loadSidecarData(book.id);
});
}
loadSidecarData(bookId: number): void {
this.loading = true;
this.error = null;
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, computed, effect, inject, Injector, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
@@ -14,7 +14,6 @@ import {Checkbox} from 'primeng/checkbox';
import {AutoComplete} from 'primeng/autocomplete';
import {AutoCompleteSelectEvent} from 'primeng/autocomplete';
import {ProgressSpinner} from 'primeng/progressspinner';
import {filter, take} from "rxjs/operators";
@Component({
selector: 'app-bulk-metadata-update-component',
@@ -63,13 +62,15 @@ export class BulkMetadataUpdateComponent implements OnInit {
private readonly bookService = inject(BookService);
private readonly bookMetadataManageService = inject(BookMetadataManageService);
private readonly messageService = inject(MessageService);
private readonly injector = inject(Injector);
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
allAuthors!: string[];
allGenres!: string[];
allMoods!: string[];
allTags!: string[];
allPublishers!: string[];
allSeries!: string[];
get allAuthors(): string[] { return this.uniqueMetadata().authors; }
get allGenres(): string[] { return this.uniqueMetadata().categories; }
get allMoods(): string[] { return this.uniqueMetadata().moods; }
get allTags(): string[] { return this.uniqueMetadata().tags; }
get allPublishers(): string[] { return this.uniqueMetadata().publishers; }
get allSeries(): string[] { return this.uniqueMetadata().series; }
filteredGenres: string[] = [];
filteredAuthors: string[] = [];
filteredMoods: string[] = [];
@@ -121,7 +122,7 @@ export class BulkMetadataUpdateComponent implements OnInit {
ngOnInit(): void {
this.bookIds = this.config.data?.bookIds ?? [];
this.books = this.bookService.getBooksByIdsFromState(this.bookIds);
this.books = this.bookService.getBooksByIds(this.bookIds);
this.metadataForm = this.fb.group({
authors: [],
@@ -135,41 +136,9 @@ export class BulkMetadataUpdateComponent implements OnInit {
tags: []
});
this.bookService.bookState$
.pipe(
filter((bookState) => bookState.loaded),
take(1)
)
.subscribe((bookState) => {
const authors = new Set<string>();
const categories = new Set<string>();
const moods = new Set<string>();
const tags = new Set<string>();
const publishers = new Set<string>();
const series = new Set<string>();
(bookState.books ?? []).forEach((book) => {
book.metadata?.authors?.forEach((author) => authors.add(author));
book.metadata?.categories?.forEach((category) =>
categories.add(category)
);
book.metadata?.moods?.forEach((mood) => moods.add(mood));
book.metadata?.tags?.forEach((tag) => tags.add(tag));
if (book.metadata?.publisher) {
publishers.add(book.metadata.publisher);
}
if (book.metadata?.seriesName) {
series.add(book.metadata.seriesName);
}
});
this.allAuthors = Array.from(authors);
this.allGenres = Array.from(categories);
this.allMoods = Array.from(moods);
this.allTags = Array.from(tags);
this.allPublishers = Array.from(publishers);
this.allSeries = Array.from(series);
});
effect(() => {
this.books = this.bookService.books().filter(book => this.bookIds.includes(book.id));
}, {injector: this.injector});
}
onFieldClearToggle(field: keyof typeof this.clearFields): void {
@@ -54,7 +54,7 @@ export class CoverSearchComponent implements OnInit {
ngOnInit() {
this.bookId = this.dynamicDialogConfig.data.bookId;
const book = this.bookService.getBookByIdFromState(this.bookId);
const book = this.bookService.findBookById(this.bookId);
// Use explicitly provided coverType, or auto-detect based on primary file
if (this.dynamicDialogConfig.data.coverType) {
@@ -1,4 +1,4 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Component, effect, inject, OnDestroy, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {TableModule} from 'primeng/table';
@@ -77,6 +77,16 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
private readonly t = inject(TranslocoService);
private routeSub!: Subscription;
private readonly syncMetadataEffect = effect(() => {
const isLoading = this.bookService.isBooksLoading();
this.loading = isLoading;
if (isLoading) {
return;
}
this.extractMetadata(this.bookService.books());
});
authors: MetadataItem[] = [];
categories: MetadataItem[] = [];
@@ -136,7 +146,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
];
ngOnInit() {
this.loadMetadata();
this.routeSub = this.route.queryParams.subscribe(params => {
const tabParam = params['tab'] as MetadataType;
if (this.validTabs.includes(tabParam)) {
@@ -164,16 +173,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
this.routeSub.unsubscribe();
}
loadMetadata() {
this.loading = true;
this.bookService.bookState$.subscribe(state => {
if (state.loaded && state.books) {
this.extractMetadata(state.books);
this.loading = false;
}
});
}
private extractMetadata(books: Book[]) {
const authorsMap = new Map<string, Set<number>>();
const categoriesMap = new Map<string, Set<number>>();
@@ -346,7 +345,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
this.renameTarget = '';
this.mergingInProgress = false;
this.loading = false;
this.loadMetadata();
},
error: (error) => {
this.messageService.add({
@@ -365,7 +363,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
}
confirmMerge() {
const selected = this.getSelectedItems(this.currentMergeType);
if (!this.mergeTarget.trim()) {
this.messageService.add({
severity: 'warn',
@@ -423,7 +420,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
this.clearSelection(this.currentMergeType);
this.mergingInProgress = false;
this.loading = false;
this.loadMetadata();
},
error: (error) => {
this.messageService.add({
@@ -479,7 +475,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
this.clearSelection(this.currentMergeType);
this.deletingInProgress = false;
this.loading = false;
this.loadMetadata();
},
error: (error) => {
this.messageService.add({

Some files were not shown because too many files have changed in this diff Show More