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:
Generated
+90
-4
@@ -23,6 +23,7 @@
|
|||||||
"@primeuix/themes": "^2.0.3",
|
"@primeuix/themes": "^2.0.3",
|
||||||
"@stomp/rx-stomp": "^2.3.0",
|
"@stomp/rx-stomp": "^2.3.0",
|
||||||
"@stomp/stompjs": "^7.3.0",
|
"@stomp/stompjs": "^7.3.0",
|
||||||
|
"@tanstack/angular-query-experimental": "5.90.26",
|
||||||
"@tweenjs/tween.js": "^25.0.0",
|
"@tweenjs/tween.js": "^25.0.0",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
"chartjs-chart-matrix": "^3.0.0",
|
"chartjs-chart-matrix": "^3.0.0",
|
||||||
@@ -298,6 +299,7 @@
|
|||||||
"integrity": "sha512-3zbx2Pu/PyP0cw5EMgpdVMerYwYOtZvV1pFXxoViGZAxFzQ8TGHCuJm4ECg3jcs7iBdt1O9ZejMuwebVCXeD3A==",
|
"integrity": "sha512-3zbx2Pu/PyP0cw5EMgpdVMerYwYOtZvV1pFXxoViGZAxFzQ8TGHCuJm4ECg3jcs7iBdt1O9ZejMuwebVCXeD3A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tinyglobby": "^0.2.14",
|
"tinyglobby": "^0.2.14",
|
||||||
"ts-morph": "^21.0.0"
|
"ts-morph": "^21.0.0"
|
||||||
@@ -348,6 +350,7 @@
|
|||||||
"integrity": "sha512-kYFwTNzToG2SJMxj2f41w3QRtdqlrFuF+bpZrtIaHOP078Ktld8EPIp9KqB0Y46Vvs69ifby5Q1/wPD9wA3iaw==",
|
"integrity": "sha512-kYFwTNzToG2SJMxj2f41w3QRtdqlrFuF+bpZrtIaHOP078Ktld8EPIp9KqB0Y46Vvs69ifby5Q1/wPD9wA3iaw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular-devkit/core": "21.2.0",
|
"@angular-devkit/core": "21.2.0",
|
||||||
"rxjs": "7.8.2"
|
"rxjs": "7.8.2"
|
||||||
@@ -395,6 +398,7 @@
|
|||||||
"integrity": "sha512-3kn3FI5v7BQ7Zct6raek+WgvyDwOJ8wElbyC903GxMQCDBRGGcevhHvTAIHhknihEsrgplzPhTlWeMbk1JfdFg==",
|
"integrity": "sha512-3kn3FI5v7BQ7Zct6raek+WgvyDwOJ8wElbyC903GxMQCDBRGGcevhHvTAIHhknihEsrgplzPhTlWeMbk1JfdFg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular-devkit/core": "21.2.0",
|
"@angular-devkit/core": "21.2.0",
|
||||||
"jsonc-parser": "3.3.1",
|
"jsonc-parser": "3.3.1",
|
||||||
@@ -492,6 +496,7 @@
|
|||||||
"integrity": "sha512-TCb3qYOC/uXKZCo56cJ6N9sHeWdFhyVqrbbYfFjTi09081T6jllgHDZL5Ms7gOMNY8KywWGGbhxwvzeA0RwTgA==",
|
"integrity": "sha512-TCb3qYOC/uXKZCo56cJ6N9sHeWdFhyVqrbbYfFjTi09081T6jllgHDZL5Ms7gOMNY8KywWGGbhxwvzeA0RwTgA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular-eslint/bundled-angular-compiler": "21.2.0",
|
"@angular-eslint/bundled-angular-compiler": "21.2.0",
|
||||||
"eslint-scope": "^9.0.0"
|
"eslint-scope": "^9.0.0"
|
||||||
@@ -506,6 +511,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/animations/-/animations-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/animations/-/animations-21.2.4.tgz",
|
||||||
"integrity": "sha512-hO1P7ks9n7lW3D31bzHohSuoAaj05xJUlK8rZgX8IkH5DLx4qhvfNh0t4bbLuBJLP2r1TaLsQ8KFcemCkFRO2w==",
|
"integrity": "sha512-hO1P7ks9n7lW3D31bzHohSuoAaj05xJUlK8rZgX8IkH5DLx4qhvfNh0t4bbLuBJLP2r1TaLsQ8KFcemCkFRO2w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
},
|
},
|
||||||
@@ -522,6 +528,7 @@
|
|||||||
"integrity": "sha512-K0EqiHz2y7TSyD4adWD0+C/P9khKlrsSWavXWxGRvoSJC/H3I3SK5Z6BWwftBibXR1Fis7njwvl5IGAlQrDchA==",
|
"integrity": "sha512-K0EqiHz2y7TSyD4adWD0+C/P9khKlrsSWavXWxGRvoSJC/H3I3SK5Z6BWwftBibXR1Fis7njwvl5IGAlQrDchA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ampproject/remapping": "2.3.0",
|
"@ampproject/remapping": "2.3.0",
|
||||||
"@angular-devkit/architect": "0.2102.0",
|
"@angular-devkit/architect": "0.2102.0",
|
||||||
@@ -634,6 +641,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-21.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-21.2.0.tgz",
|
||||||
"integrity": "sha512-1P0TNL1F51NC7JAaXabaAHY7Y1zBloLSZXfml1POa4a116V+y/QZfPGsxM0LwD1qSSXhSb2LNl7duTtJAP39bA==",
|
"integrity": "sha512-1P0TNL1F51NC7JAaXabaAHY7Y1zBloLSZXfml1POa4a116V+y/QZfPGsxM0LwD1qSSXhSb2LNl7duTtJAP39bA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"parse5": "^8.0.0",
|
"parse5": "^8.0.0",
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
@@ -651,6 +659,7 @@
|
|||||||
"integrity": "sha512-yaGEpckqgOemcHkoWeH92i9eNrcbr9iE/dnxL+Du6s9spTAXJ2jjtYfszhmowuQZkCK5rjecMb8ctNtHlaGCjg==",
|
"integrity": "sha512-yaGEpckqgOemcHkoWeH92i9eNrcbr9iE/dnxL+Du6s9spTAXJ2jjtYfszhmowuQZkCK5rjecMb8ctNtHlaGCjg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular-devkit/architect": "0.2102.0",
|
"@angular-devkit/architect": "0.2102.0",
|
||||||
"@angular-devkit/core": "21.2.0",
|
"@angular-devkit/core": "21.2.0",
|
||||||
@@ -698,6 +707,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/common/-/common-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/common/-/common-21.2.4.tgz",
|
||||||
"integrity": "sha512-NrP6qOuUpo3fqq14UJ1b2bIRtWsfvxh1qLqOyFV4gfBrHhXd0XffU1LUlUw1qp4w1uBSgPJ0/N5bSPUWrAguVg==",
|
"integrity": "sha512-NrP6qOuUpo3fqq14UJ1b2bIRtWsfvxh1qLqOyFV4gfBrHhXd0XffU1LUlUw1qp4w1uBSgPJ0/N5bSPUWrAguVg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
},
|
},
|
||||||
@@ -714,6 +724,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-21.2.4.tgz",
|
||||||
"integrity": "sha512-9+ulVK3idIo/Tu4X2ic7/V0+Uj7pqrOAbOuIirYe6Ymm3AjexuFRiGBbfcH0VJhQ5cf8TvIJ1fuh+MI4JiRIxA==",
|
"integrity": "sha512-9+ulVK3idIo/Tu4X2ic7/V0+Uj7pqrOAbOuIirYe6Ymm3AjexuFRiGBbfcH0VJhQ5cf8TvIJ1fuh+MI4JiRIxA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
},
|
},
|
||||||
@@ -727,6 +738,7 @@
|
|||||||
"integrity": "sha512-vGjd7DZo/Ox50pQCm5EycmBu91JclimPtZoyNXu/2hSxz3oAkzwiHCwlHwk2g58eheSSp+lYtYRLmHAqSVZLjg==",
|
"integrity": "sha512-vGjd7DZo/Ox50pQCm5EycmBu91JclimPtZoyNXu/2hSxz3oAkzwiHCwlHwk2g58eheSSp+lYtYRLmHAqSVZLjg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/core": "7.29.0",
|
"@babel/core": "7.29.0",
|
||||||
"@jridgewell/sourcemap-codec": "^1.4.14",
|
"@jridgewell/sourcemap-codec": "^1.4.14",
|
||||||
@@ -759,6 +771,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/core/-/core-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/core/-/core-21.2.4.tgz",
|
||||||
"integrity": "sha512-2+gd67ZuXHpGOqeb2o7XZPueEWEP81eJza2tSHkT5QMV8lnYllDEmaNnkPxnIjSLGP1O3PmiXxo4z8ibHkLZwg==",
|
"integrity": "sha512-2+gd67ZuXHpGOqeb2o7XZPueEWEP81eJza2tSHkT5QMV8lnYllDEmaNnkPxnIjSLGP1O3PmiXxo4z8ibHkLZwg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
},
|
},
|
||||||
@@ -784,6 +797,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/forms/-/forms-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/forms/-/forms-21.2.4.tgz",
|
||||||
"integrity": "sha512-1fOhctA9ADEBYjI3nPQUR5dHsK2+UWAjup37Ksldk/k0w8UpD5YsN7JVNvsDMZRFMucKYcGykPblU7pABtsqnQ==",
|
"integrity": "sha512-1fOhctA9ADEBYjI3nPQUR5dHsK2+UWAjup37Ksldk/k0w8UpD5YsN7JVNvsDMZRFMucKYcGykPblU7pABtsqnQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@standard-schema/spec": "^1.0.0",
|
"@standard-schema/spec": "^1.0.0",
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
@@ -803,6 +817,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-21.2.4.tgz",
|
||||||
"integrity": "sha512-1A9e/cQVu+3BkRCktLcO3RZGuw8NOTHw1frUUrpAz+iMyvIT4sDRFbL+U1g8qmOCZqRNC1Pi1HZfZ1kl6kvrcQ==",
|
"integrity": "sha512-1A9e/cQVu+3BkRCktLcO3RZGuw8NOTHw1frUUrpAz+iMyvIT4sDRFbL+U1g8qmOCZqRNC1Pi1HZfZ1kl6kvrcQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
},
|
},
|
||||||
@@ -843,6 +858,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/router/-/router-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/router/-/router-21.2.4.tgz",
|
||||||
"integrity": "sha512-OjWze4XT8i2MThcBXMv7ru1k6/5L6QYZbcXuseqimFCHm2avEJ+mXPovY066fMBZJhqbXdjB82OhHAWkIHjglQ==",
|
"integrity": "sha512-OjWze4XT8i2MThcBXMv7ru1k6/5L6QYZbcXuseqimFCHm2avEJ+mXPovY066fMBZJhqbXdjB82OhHAWkIHjglQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
},
|
},
|
||||||
@@ -861,6 +877,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@angular/service-worker/-/service-worker-21.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@angular/service-worker/-/service-worker-21.2.4.tgz",
|
||||||
"integrity": "sha512-YcPMb0co2hEDwzOG5S27b6f8rotXEUDx88nQuhHDl/ztuzXaxKklJ21qVDVZ0R433YBCRQJl2D6ZrpJojsnBFw==",
|
"integrity": "sha512-YcPMb0co2hEDwzOG5S27b6f8rotXEUDx88nQuhHDl/ztuzXaxKklJ21qVDVZ0R433YBCRQJl2D6ZrpJojsnBFw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0"
|
||||||
},
|
},
|
||||||
@@ -960,6 +977,7 @@
|
|||||||
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
|
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/code-frame": "^7.29.0",
|
"@babel/code-frame": "^7.29.0",
|
||||||
"@babel/generator": "^7.29.0",
|
"@babel/generator": "^7.29.0",
|
||||||
@@ -1332,6 +1350,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.19.0"
|
"node": ">=20.19.0"
|
||||||
},
|
},
|
||||||
@@ -1372,6 +1391,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.19.0"
|
"node": ">=20.19.0"
|
||||||
}
|
}
|
||||||
@@ -2369,6 +2389,7 @@
|
|||||||
"integrity": "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==",
|
"integrity": "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@inquirer/checkbox": "^4.3.2",
|
"@inquirer/checkbox": "^4.3.2",
|
||||||
"@inquirer/confirm": "^5.1.21",
|
"@inquirer/confirm": "^5.1.21",
|
||||||
@@ -4497,7 +4518,49 @@
|
|||||||
"version": "7.3.0",
|
"version": "7.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/@stomp/stompjs/-/stompjs-7.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@stomp/stompjs/-/stompjs-7.3.0.tgz",
|
||||||
"integrity": "sha512-nKMLoFfJhrQAqkvvKd1vLq/cVBGCMwPRCD0LqW7UT1fecRx9C3GoKEIR2CYwVuErGeZu8w0kFkl2rlhPlqHVgQ==",
|
"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": {
|
"node_modules/@ts-morph/common": {
|
||||||
"version": "0.22.0",
|
"version": "0.22.0",
|
||||||
@@ -4540,7 +4603,8 @@
|
|||||||
"version": "25.0.0",
|
"version": "25.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz",
|
||||||
"integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==",
|
"integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==",
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/@tybys/wasm-util": {
|
"node_modules/@tybys/wasm-util": {
|
||||||
"version": "0.10.1",
|
"version": "0.10.1",
|
||||||
@@ -4609,6 +4673,7 @@
|
|||||||
"integrity": "sha512-RpV6r/ij22zRRdyBPcxDeKAzH43phWVKEjL2iksqo1Vz3CuBUrgmPpPhALKiRfU7OMCmeeO9vECBMsV0hMTG8Q==",
|
"integrity": "sha512-RpV6r/ij22zRRdyBPcxDeKAzH43phWVKEjL2iksqo1Vz3CuBUrgmPpPhALKiRfU7OMCmeeO9vECBMsV0hMTG8Q==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~7.18.0"
|
"undici-types": "~7.18.0"
|
||||||
}
|
}
|
||||||
@@ -4662,6 +4727,7 @@
|
|||||||
"integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==",
|
"integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/scope-manager": "8.56.1",
|
"@typescript-eslint/scope-manager": "8.56.1",
|
||||||
"@typescript-eslint/types": "8.56.1",
|
"@typescript-eslint/types": "8.56.1",
|
||||||
@@ -4769,6 +4835,7 @@
|
|||||||
"integrity": "sha512-dbMkdIUkIkchgGDIv7KLUpa0Mda4IYjo4IAMJUZ+3xNoUXxMsk9YtKpTHSChRS85o+H9ftm51gsK1dZReY9CVw==",
|
"integrity": "sha512-dbMkdIUkIkchgGDIv7KLUpa0Mda4IYjo4IAMJUZ+3xNoUXxMsk9YtKpTHSChRS85o+H9ftm51gsK1dZReY9CVw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
},
|
},
|
||||||
@@ -4811,6 +4878,7 @@
|
|||||||
"integrity": "sha512-HPAVNIME3tABJ61siYlHzSWCGtOoeP2RTIaHXFMPqjrQKCGB9OgUVdiNgH7TJS2JNIQ5qQ4RsAUDuGaGme/KOA==",
|
"integrity": "sha512-HPAVNIME3tABJ61siYlHzSWCGtOoeP2RTIaHXFMPqjrQKCGB9OgUVdiNgH7TJS2JNIQ5qQ4RsAUDuGaGme/KOA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/eslint-utils": "^4.9.1",
|
"@eslint-community/eslint-utils": "^4.9.1",
|
||||||
"@typescript-eslint/scope-manager": "8.56.1",
|
"@typescript-eslint/scope-manager": "8.56.1",
|
||||||
@@ -5052,6 +5120,7 @@
|
|||||||
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
|
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"bin": {
|
"bin": {
|
||||||
"acorn": "bin/acorn"
|
"acorn": "bin/acorn"
|
||||||
},
|
},
|
||||||
@@ -5473,6 +5542,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"baseline-browser-mapping": "^2.9.0",
|
"baseline-browser-mapping": "^2.9.0",
|
||||||
"caniuse-lite": "^1.0.30001759",
|
"caniuse-lite": "^1.0.30001759",
|
||||||
@@ -5633,6 +5703,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
|
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
|
||||||
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
|
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@kurkle/color": "^0.3.0"
|
"@kurkle/color": "^0.3.0"
|
||||||
},
|
},
|
||||||
@@ -6378,6 +6449,7 @@
|
|||||||
"integrity": "sha512-VmQ+sifHUbI/IcSopBCF/HO3YiHQx/AVd3UVyYL6weuwW+HvON9VYn5l6Zl1WZzPWXPNZrSQpxwkkZ/VuvJZzg==",
|
"integrity": "sha512-VmQ+sifHUbI/IcSopBCF/HO3YiHQx/AVd3UVyYL6weuwW+HvON9VYn5l6Zl1WZzPWXPNZrSQpxwkkZ/VuvJZzg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/eslint-utils": "^4.8.0",
|
"@eslint-community/eslint-utils": "^4.8.0",
|
||||||
"@eslint-community/regexpp": "^4.12.1",
|
"@eslint-community/regexpp": "^4.12.1",
|
||||||
@@ -6711,6 +6783,7 @@
|
|||||||
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
|
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"accepts": "^2.0.0",
|
"accepts": "^2.0.0",
|
||||||
"body-parser": "^2.2.1",
|
"body-parser": "^2.2.1",
|
||||||
@@ -7193,6 +7266,7 @@
|
|||||||
"integrity": "sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==",
|
"integrity": "sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.9.0"
|
"node": ">=16.9.0"
|
||||||
}
|
}
|
||||||
@@ -7631,6 +7705,7 @@
|
|||||||
"integrity": "sha512-0+MoQNYyr2rBHqO1xilltfDjV9G7ymYGlAUazgcDLQaUf8JDHbuGwsxN6U9qWaElZ4w1B2r7yEGIL3GdeW3Rug==",
|
"integrity": "sha512-0+MoQNYyr2rBHqO1xilltfDjV9G7ymYGlAUazgcDLQaUf8JDHbuGwsxN6U9qWaElZ4w1B2r7yEGIL3GdeW3Rug==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@acemir/cssom": "^0.9.31",
|
"@acemir/cssom": "^0.9.31",
|
||||||
"@asamuzakjp/dom-selector": "^6.8.1",
|
"@asamuzakjp/dom-selector": "^6.8.1",
|
||||||
@@ -7792,6 +7867,7 @@
|
|||||||
"integrity": "sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==",
|
"integrity": "sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"cli-truncate": "^5.0.0",
|
"cli-truncate": "^5.0.0",
|
||||||
"colorette": "^2.0.20",
|
"colorette": "^2.0.20",
|
||||||
@@ -9158,6 +9234,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.11",
|
"nanoid": "^3.3.11",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
@@ -9568,6 +9645,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
|
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
|
||||||
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
|
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.1.0"
|
"tslib": "^2.1.0"
|
||||||
}
|
}
|
||||||
@@ -10271,7 +10349,8 @@
|
|||||||
"version": "2.8.1",
|
"version": "2.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
"license": "0BSD"
|
"license": "0BSD",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/tuf-js": {
|
"node_modules/tuf-js": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
@@ -10322,6 +10401,7 @@
|
|||||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
|
"peer": true,
|
||||||
"bin": {
|
"bin": {
|
||||||
"tsc": "bin/tsc",
|
"tsc": "bin/tsc",
|
||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
@@ -10336,6 +10416,7 @@
|
|||||||
"integrity": "sha512-U4lM6pjmBX7J5wk4szltF7I1cGBHXZopnAXCMXb3+fZ3B/0Z3hq3wS/CCUB2NZBNAExK92mCU2tEohWuwVMsDQ==",
|
"integrity": "sha512-U4lM6pjmBX7J5wk4szltF7I1cGBHXZopnAXCMXb3+fZ3B/0Z3hq3wS/CCUB2NZBNAExK92mCU2tEohWuwVMsDQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/eslint-plugin": "8.56.1",
|
"@typescript-eslint/eslint-plugin": "8.56.1",
|
||||||
"@typescript-eslint/parser": "8.56.1",
|
"@typescript-eslint/parser": "8.56.1",
|
||||||
@@ -10457,6 +10538,7 @@
|
|||||||
"https://github.com/sponsors/ctavan"
|
"https://github.com/sponsors/ctavan"
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"bin": {
|
"bin": {
|
||||||
"uuid": "dist/esm/bin/uuid"
|
"uuid": "dist/esm/bin/uuid"
|
||||||
}
|
}
|
||||||
@@ -10487,6 +10569,7 @@
|
|||||||
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
|
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.27.0",
|
"esbuild": "^0.27.0",
|
||||||
"fdir": "^6.5.0",
|
"fdir": "^6.5.0",
|
||||||
@@ -10562,6 +10645,7 @@
|
|||||||
"integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==",
|
"integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitest/expect": "4.0.18",
|
"@vitest/expect": "4.0.18",
|
||||||
"@vitest/mocker": "4.0.18",
|
"@vitest/mocker": "4.0.18",
|
||||||
@@ -10986,6 +11070,7 @@
|
|||||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/colinhacks"
|
"url": "https://github.com/sponsors/colinhacks"
|
||||||
}
|
}
|
||||||
@@ -11004,7 +11089,8 @@
|
|||||||
"version": "0.16.1",
|
"version": "0.16.1",
|
||||||
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.16.1.tgz",
|
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.16.1.tgz",
|
||||||
"integrity": "sha512-dpvY17vxYIW3+bNrP0ClUlaiY0CiIRK3tnoLaGoQsQcY9/I/NpzIWQ7tQNhbV7LacQMpCII6wVzuL3tuWOyfuA==",
|
"integrity": "sha512-dpvY17vxYIW3+bNrP0ClUlaiY0CiIRK3tnoLaGoQsQcY9/I/NpzIWQ7tQNhbV7LacQMpCII6wVzuL3tuWOyfuA==",
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@
|
|||||||
"@primeuix/themes": "^2.0.3",
|
"@primeuix/themes": "^2.0.3",
|
||||||
"@stomp/rx-stomp": "^2.3.0",
|
"@stomp/rx-stomp": "^2.3.0",
|
||||||
"@stomp/stompjs": "^7.3.0",
|
"@stomp/stompjs": "^7.3.0",
|
||||||
|
"@tanstack/angular-query-experimental": "5.90.26",
|
||||||
"@tweenjs/tween.js": "^25.0.0",
|
"@tweenjs/tween.js": "^25.0.0",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
"chartjs-chart-matrix": "^3.0.0",
|
"chartjs-chart-matrix": "^3.0.0",
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||||
|
import {signal} from '@angular/core';
|
||||||
import {AppComponent} from './app.component';
|
import {AppComponent} from './app.component';
|
||||||
import {AuthInitializationService} from './core/security/auth-initialization-service';
|
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 {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||||
import {BookService} from './features/book/service/book.service';
|
import {BookService} from './features/book/service/book.service';
|
||||||
import {NotificationEventService} from './shared/websocket/notification-event.service';
|
import {NotificationEventService} from './shared/websocket/notification-event.service';
|
||||||
@@ -18,15 +19,12 @@ import {TranslocoTestingModule} from '@jsverse/transloco';
|
|||||||
describe('AppComponent offline detection', () => {
|
describe('AppComponent offline detection', () => {
|
||||||
let fixture: ComponentFixture<AppComponent>;
|
let fixture: ComponentFixture<AppComponent>;
|
||||||
let component: AppComponent;
|
let component: AppComponent;
|
||||||
let authInitSubject: BehaviorSubject<boolean>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
authInitSubject = new BehaviorSubject<boolean>(false);
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [TranslocoTestingModule.forRoot({langs: {}})],
|
imports: [TranslocoTestingModule.forRoot({langs: {}})],
|
||||||
providers: [
|
providers: [
|
||||||
{provide: AuthInitializationService, useValue: {initialized$: authInitSubject.asObservable()}},
|
{provide: AuthInitializationService, useValue: {initialized: signal(false)}},
|
||||||
{provide: RxStompService, useValue: {watch: vi.fn(() => of())}},
|
{provide: RxStompService, useValue: {watch: vi.fn(() => of())}},
|
||||||
{provide: BookService, useValue: {}},
|
{provide: BookService, useValue: {}},
|
||||||
{provide: NotificationEventService, useValue: {}},
|
{provide: NotificationEventService, useValue: {}},
|
||||||
@@ -34,7 +32,7 @@ describe('AppComponent offline detection', () => {
|
|||||||
{provide: MetadataProgressService, useValue: {}},
|
{provide: MetadataProgressService, useValue: {}},
|
||||||
{provide: BookdropFileService, useValue: {}},
|
{provide: BookdropFileService, useValue: {}},
|
||||||
{provide: TaskService, 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: LibraryHealthService, useValue: {initialize: vi.fn()}},
|
||||||
{provide: LibraryLoadingService, useValue: {hide: vi.fn()}},
|
{provide: LibraryLoadingService, useValue: {hide: vi.fn()}},
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -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 {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||||
import {BookService} from './features/book/service/book.service';
|
import {BookService} from './features/book/service/book.service';
|
||||||
import {NotificationEventService} from './shared/websocket/notification-event.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 {LibraryService} from './features/book/service/library.service';
|
||||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||||
import {LibraryLoadingService} from './features/library-creator/library-loading.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';
|
import {AuthService} from './shared/service/auth.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -46,19 +46,20 @@ export class AppComponent implements OnInit, OnDestroy {
|
|||||||
private libraryHealthService = inject(LibraryHealthService);
|
private libraryHealthService = inject(LibraryHealthService);
|
||||||
private libraryLoadingService = inject(LibraryLoadingService);
|
private libraryLoadingService = inject(LibraryLoadingService);
|
||||||
private authService = inject(AuthService);
|
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 {
|
ngOnInit(): void {
|
||||||
window.addEventListener('online', this.onOnline);
|
window.addEventListener('online', this.onOnline);
|
||||||
window.addEventListener('offline', this.onOffline);
|
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 = () => {
|
private onOnline = () => {
|
||||||
@@ -84,8 +85,8 @@ export class AppComponent implements OnInit, OnDestroy {
|
|||||||
private setupWebSocketSubscriptions(): void {
|
private setupWebSocketSubscriptions(): void {
|
||||||
this.subscriptions.push(
|
this.subscriptions.push(
|
||||||
this.rxStompService.watch('/user/queue/book-add').pipe(
|
this.rxStompService.watch('/user/queue/book-add').pipe(
|
||||||
withLatestFrom(this.libraryService.largeLibraryLoading$),
|
scan((acc, msg) => {
|
||||||
scan((acc, [msg, loadingState]) => {
|
const loadingState = this.libraryService.largeLibraryLoading();
|
||||||
const book = JSON.parse(msg.body);
|
const book = JSON.parse(msg.body);
|
||||||
if (loadingState.isLoading) {
|
if (loadingState.isLoading) {
|
||||||
const newCount = acc.count + 1;
|
const newCount = acc.count + 1;
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import {Injectable} from '@angular/core';
|
import {Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject} from 'rxjs';
|
|
||||||
|
|
||||||
@Injectable({providedIn: 'root'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class AuthInitializationService {
|
export class AuthInitializationService {
|
||||||
private initialized = new BehaviorSubject<boolean>(false);
|
private readonly _initialized = signal(false);
|
||||||
initialized$ = this.initialized.asObservable();
|
readonly initialized = this._initialized.asReadonly();
|
||||||
|
|
||||||
markAsInitialized() {
|
markAsInitialized(): void {
|
||||||
this.initialized.next(true);
|
this._initialized.set(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,39 @@
|
|||||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {signal} from '@angular/core';
|
||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {initializeAuthFactory} from './auth-initializer';
|
import {initializeAuthFactory} from './auth-initializer';
|
||||||
import {AuthInitializationService} from './auth-initialization-service';
|
import {AuthInitializationService} from './auth-initialization-service';
|
||||||
import {AuthService} from '../../shared/service/auth.service';
|
import {AuthService} from '../../shared/service/auth.service';
|
||||||
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
|
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
|
||||||
import {BehaviorSubject} from 'rxjs';
|
import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
describe('initializeAuthFactory', () => {
|
describe('initializeAuthFactory', () => {
|
||||||
let authInitService: AuthInitializationService;
|
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(() => {
|
beforeEach(() => {
|
||||||
publicSettingsSubject = new BehaviorSubject<PublicAppSettings | null>(null);
|
mockQueryClient = {
|
||||||
|
fetchQuery: vi.fn().mockResolvedValue(defaultPublicSettings),
|
||||||
|
};
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
{provide: AuthService, useValue: {tokenSubject: {next: vi.fn()}, getInternalAccessToken: vi.fn()}},
|
{provide: AuthService, useValue: {token: signal(null), getInternalAccessToken: vi.fn()}},
|
||||||
{provide: AppSettingsService, useValue: {publicAppSettings$: publicSettingsSubject.asObservable()}},
|
{
|
||||||
|
provide: AppSettingsService,
|
||||||
|
useValue: {
|
||||||
|
publicAppSettings: signal(null),
|
||||||
|
getPublicSettingsQueryOptions: () => queryOptions({queryKey: ['public-settings'], queryFn: async () => defaultPublicSettings}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{provide: QueryClient, useValue: mockQueryClient},
|
||||||
AuthInitializationService,
|
AuthInitializationService,
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
@@ -32,8 +49,6 @@ describe('initializeAuthFactory', () => {
|
|||||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||||
|
|
||||||
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!, oidcForceOnlyMode: false});
|
|
||||||
|
|
||||||
await initPromise;
|
await initPromise;
|
||||||
|
|
||||||
expect(markSpy).toHaveBeenCalled();
|
expect(markSpy).toHaveBeenCalled();
|
||||||
@@ -49,8 +64,6 @@ describe('initializeAuthFactory', () => {
|
|||||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||||
|
|
||||||
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!, oidcForceOnlyMode: false});
|
|
||||||
|
|
||||||
await initPromise;
|
await initPromise;
|
||||||
|
|
||||||
expect(markSpy).toHaveBeenCalled();
|
expect(markSpy).toHaveBeenCalled();
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {inject} from '@angular/core';
|
|||||||
import {AuthService, websocketInitializer} from '../../shared/service/auth.service';
|
import {AuthService, websocketInitializer} from '../../shared/service/auth.service';
|
||||||
import {AppSettingsService} from '../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../shared/service/app-settings.service';
|
||||||
import {AuthInitializationService} from './auth-initialization-service';
|
import {AuthInitializationService} from './auth-initialization-service';
|
||||||
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
const SETTINGS_TIMEOUT_MS = 10000;
|
const SETTINGS_TIMEOUT_MS = 10000;
|
||||||
|
|
||||||
@@ -10,42 +11,41 @@ export function initializeAuthFactory() {
|
|||||||
const appSettingsService = inject(AppSettingsService);
|
const appSettingsService = inject(AppSettingsService);
|
||||||
const authService = inject(AuthService);
|
const authService = inject(AuthService);
|
||||||
const authInitService = inject(AuthInitializationService);
|
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');
|
console.warn('[Auth] Public settings fetch timed out, falling back to local auth');
|
||||||
sub.unsubscribe();
|
|
||||||
authInitService.markAsInitialized();
|
authInitService.markAsInitialized();
|
||||||
resolve();
|
return;
|
||||||
}, SETTINGS_TIMEOUT_MS);
|
}
|
||||||
|
|
||||||
const sub = appSettingsService.publicAppSettings$.subscribe(publicSettings => {
|
if (publicSettings.remoteAuthEnabled) {
|
||||||
if (publicSettings) {
|
return new Promise<void>(resolve => {
|
||||||
clearTimeout(settingsTimeout);
|
authService.remoteLogin().subscribe({
|
||||||
|
next: () => {
|
||||||
if (publicSettings.remoteAuthEnabled) {
|
authInitService.markAsInitialized();
|
||||||
authService.remoteLogin().subscribe({
|
resolve();
|
||||||
next: () => {
|
},
|
||||||
authInitService.markAsInitialized();
|
error: err => {
|
||||||
resolve();
|
console.error('[Remote Login] failed:', err);
|
||||||
},
|
authInitService.markAsInitialized();
|
||||||
error: err => {
|
resolve();
|
||||||
console.error('[Remote Login] failed:', err);
|
|
||||||
authInitService.markAsInitialized();
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
if (authService.getInternalAccessToken()) {
|
|
||||||
websocketInitializer(authService)();
|
|
||||||
}
|
}
|
||||||
authInitService.markAsInitialized();
|
});
|
||||||
resolve();
|
});
|
||||||
}
|
} else {
|
||||||
sub.unsubscribe();
|
if (authService.getInternalAccessToken()) {
|
||||||
|
websocketInitializer(authService)();
|
||||||
}
|
}
|
||||||
});
|
authInitService.markAsInitialized();
|
||||||
|
return;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,15 @@
|
|||||||
import {inject} from '@angular/core';
|
import {inject} from '@angular/core';
|
||||||
import {CanActivateFn, Router} from '@angular/router';
|
import {CanActivateFn, Router} from '@angular/router';
|
||||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||||
import {map} from 'rxjs/operators';
|
|
||||||
|
|
||||||
export const BookdropGuard: CanActivateFn = () => {
|
export const BookdropGuard: CanActivateFn = () => {
|
||||||
const userService = inject(UserService);
|
const userService = inject(UserService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
|
const user = userService.currentUser();
|
||||||
|
|
||||||
return userService.userState$.pipe(
|
if (user && (user.permissions.admin || user.permissions.canAccessBookdrop)) {
|
||||||
map(state => {
|
return true;
|
||||||
const user = state.user;
|
}
|
||||||
if (user && (user.permissions.admin || user.permissions.canAccessBookdrop)) {
|
router.navigate(['/dashboard']);
|
||||||
return true;
|
return false;
|
||||||
}
|
|
||||||
router.navigate(['/dashboard']);
|
|
||||||
return false;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,20 +1,15 @@
|
|||||||
import {inject} from '@angular/core';
|
import {inject} from '@angular/core';
|
||||||
import {CanActivateFn, Router} from '@angular/router';
|
import {CanActivateFn, Router} from '@angular/router';
|
||||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||||
import {map} from 'rxjs/operators';
|
|
||||||
|
|
||||||
export const EditMetadataGuard: CanActivateFn = () => {
|
export const EditMetadataGuard: CanActivateFn = () => {
|
||||||
const userService = inject(UserService);
|
const userService = inject(UserService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
|
const user = userService.currentUser();
|
||||||
|
|
||||||
return userService.userState$.pipe(
|
if (user && (user.permissions.admin || user.permissions.canEditMetadata)) {
|
||||||
map(state => {
|
return true;
|
||||||
const user = state.user;
|
}
|
||||||
if (user && (user.permissions.admin || user.permissions.canEditMetadata)) {
|
router.navigate(['/dashboard']);
|
||||||
return true;
|
return false;
|
||||||
}
|
|
||||||
router.navigate(['/dashboard']);
|
|
||||||
return false;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,20 +1,15 @@
|
|||||||
import {inject} from '@angular/core';
|
import {inject} from '@angular/core';
|
||||||
import {CanActivateFn, Router} from '@angular/router';
|
import {CanActivateFn, Router} from '@angular/router';
|
||||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||||
import {map} from 'rxjs/operators';
|
|
||||||
|
|
||||||
export const LibraryStatsGuard: CanActivateFn = () => {
|
export const LibraryStatsGuard: CanActivateFn = () => {
|
||||||
const userService = inject(UserService);
|
const userService = inject(UserService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
|
const user = userService.currentUser();
|
||||||
|
|
||||||
return userService.userState$.pipe(
|
if (user && (user.permissions.admin || user.permissions.canAccessLibraryStats)) {
|
||||||
map(state => {
|
return true;
|
||||||
const user = state.user;
|
}
|
||||||
if (user && (user.permissions.admin || user.permissions.canAccessLibraryStats)) {
|
router.navigate(['/dashboard']);
|
||||||
return true;
|
return false;
|
||||||
}
|
|
||||||
router.navigate(['/dashboard']);
|
|
||||||
return false;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,20 +1,15 @@
|
|||||||
import {inject} from '@angular/core';
|
import {inject} from '@angular/core';
|
||||||
import {CanActivateFn, Router} from '@angular/router';
|
import {CanActivateFn, Router} from '@angular/router';
|
||||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||||
import {map} from 'rxjs/operators';
|
|
||||||
|
|
||||||
export const ManageLibraryGuard: CanActivateFn = () => {
|
export const ManageLibraryGuard: CanActivateFn = () => {
|
||||||
const userService = inject(UserService);
|
const userService = inject(UserService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
|
const user = userService.currentUser();
|
||||||
|
|
||||||
return userService.userState$.pipe(
|
if (user && (user.permissions.admin || user.permissions.canManageLibrary)) {
|
||||||
map(state => {
|
return true;
|
||||||
const user = state.user;
|
}
|
||||||
if (user && (user.permissions.admin || user.permissions.canManageLibrary)) {
|
router.navigate(['/dashboard']);
|
||||||
return true;
|
return false;
|
||||||
}
|
|
||||||
router.navigate(['/dashboard']);
|
|
||||||
return false;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,20 +1,15 @@
|
|||||||
import {inject} from '@angular/core';
|
import {inject} from '@angular/core';
|
||||||
import {CanActivateFn, Router} from '@angular/router';
|
import {CanActivateFn, Router} from '@angular/router';
|
||||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||||
import {map} from 'rxjs/operators';
|
|
||||||
|
|
||||||
export const UserStatsGuard: CanActivateFn = () => {
|
export const UserStatsGuard: CanActivateFn = () => {
|
||||||
const userService = inject(UserService);
|
const userService = inject(UserService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
|
const user = userService.currentUser();
|
||||||
|
|
||||||
return userService.userState$.pipe(
|
if (user && (user.permissions.admin || user.permissions.canAccessUserStats)) {
|
||||||
map(state => {
|
return true;
|
||||||
const user = state.user;
|
}
|
||||||
if (user && (user.permissions.admin || user.permissions.canAccessUserStats)) {
|
router.navigate(['/dashboard']);
|
||||||
return true;
|
return false;
|
||||||
}
|
|
||||||
router.navigate(['/dashboard']);
|
|
||||||
return false;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
+10
-19
@@ -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 {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||||
import {InputText} from 'primeng/inputtext';
|
import {InputText} from 'primeng/inputtext';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
@@ -8,9 +8,7 @@ import {ToggleSwitch} from 'primeng/toggleswitch';
|
|||||||
import {InputNumber} from 'primeng/inputnumber';
|
import {InputNumber} from 'primeng/inputnumber';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
||||||
import {Observable} from 'rxjs';
|
|
||||||
import {AppSettingKey, AppSettings, OidcProviderDetails, OidcTestResult} from '../../../shared/model/app-settings.model';
|
import {AppSettingKey, AppSettings, OidcProviderDetails, OidcTestResult} from '../../../shared/model/app-settings.model';
|
||||||
import {filter, take} from 'rxjs/operators';
|
|
||||||
import {MultiSelect} from 'primeng/multiselect';
|
import {MultiSelect} from 'primeng/multiselect';
|
||||||
import {Library} from '../../../features/book/model/library.model';
|
import {Library} from '../../../features/book/model/library.model';
|
||||||
import {LibraryService} from '../../../features/book/service/library.service';
|
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']
|
styleUrls: ['./authentication-settings.component.scss']
|
||||||
})
|
})
|
||||||
export class AuthenticationSettingsComponent implements OnInit {
|
export class AuthenticationSettingsComponent {
|
||||||
availablePermissions = [
|
availablePermissions = [
|
||||||
{label: 'Upload Books', value: 'permissionUpload', selected: false, translationKey: 'perms.uploadBooks'},
|
{label: 'Upload Books', value: 'permissionUpload', selected: false, translationKey: 'perms.uploadBooks'},
|
||||||
{label: 'Download Books', value: 'permissionDownload', selected: false, translationKey: 'perms.downloadBooks'},
|
{label: 'Download Books', value: 'permissionDownload', selected: false, translationKey: 'perms.downloadBooks'},
|
||||||
@@ -64,7 +62,7 @@ export class AuthenticationSettingsComponent implements OnInit {
|
|||||||
allowLocalAccountLinking = true;
|
allowLocalAccountLinking = true;
|
||||||
selectedPermissions: string[] = [];
|
selectedPermissions: string[] = [];
|
||||||
oidcEnabled = false;
|
oidcEnabled = false;
|
||||||
allLibraries: Library[] = [];
|
|
||||||
editingLibraryIds: number[] = [];
|
editingLibraryIds: number[] = [];
|
||||||
sessionDurationHours: number | null = null;
|
sessionDurationHours: number | null = null;
|
||||||
backchannelLogoutUri = `${window.location.origin}/api/v1/auth/oidc/backchannel-logout`;
|
backchannelLogoutUri = `${window.location.origin}/api/v1/auth/oidc/backchannel-logout`;
|
||||||
@@ -116,21 +114,14 @@ export class AuthenticationSettingsComponent implements OnInit {
|
|||||||
private libraryService = inject(LibraryService);
|
private libraryService = inject(LibraryService);
|
||||||
private groupMappingService = inject(OidcGroupMappingService);
|
private groupMappingService = inject(OidcGroupMappingService);
|
||||||
private t = inject(TranslocoService);
|
private t = inject(TranslocoService);
|
||||||
|
get allLibraries() { return this.libraryService.libraries(); }
|
||||||
|
|
||||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
private readonly loadSettingsEffect = effect(() => {
|
||||||
|
const settings = this.appSettingsService.appSettings();
|
||||||
ngOnInit(): void {
|
if (settings) {
|
||||||
this.appSettings$.pipe(
|
this.loadSettings(settings);
|
||||||
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 ?? []);
|
|
||||||
}
|
|
||||||
|
|
||||||
loadSettings(settings: AppSettings): void {
|
loadSettings(settings: AppSettings): void {
|
||||||
this.oidcEnabled = settings.oidcEnabled;
|
this.oidcEnabled = settings.oidcEnabled;
|
||||||
|
|||||||
+24
-24
@@ -1,5 +1,5 @@
|
|||||||
<ng-container *transloco="let t; prefix: 'authorBrowser'">
|
<ng-container *transloco="let t; prefix: 'authorBrowser'">
|
||||||
@if (loading) {
|
@if (loading()) {
|
||||||
<div class="loading-state">
|
<div class="loading-state">
|
||||||
<p-progressSpinner
|
<p-progressSpinner
|
||||||
[style]="{'width': '60px', 'height': '60px'}"
|
[style]="{'width': '60px', 'height': '60px'}"
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (!loading) {
|
@if (!loading()) {
|
||||||
<div class="browse-header">
|
<div class="browse-header">
|
||||||
<h2 class="browse-title">{{ t('browseAllAuthors') }}</h2>
|
<h2 class="browse-title">{{ t('browseAllAuthors') }}</h2>
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
pInputText
|
pInputText
|
||||||
type="text"
|
type="text"
|
||||||
[placeholder]="t('searchPlaceholder')"
|
[placeholder]="t('searchPlaceholder')"
|
||||||
[ngModel]="searchTerm$ | async"
|
[ngModel]="searchTerm()"
|
||||||
(ngModelChange)="onSearchChange($event)"
|
(ngModelChange)="onSearchChange($event)"
|
||||||
class="search-input"/>
|
class="search-input"/>
|
||||||
</div>
|
</div>
|
||||||
@@ -29,7 +29,7 @@
|
|||||||
<div class="filter-sort-wrapper">
|
<div class="filter-sort-wrapper">
|
||||||
<p-select
|
<p-select
|
||||||
[options]="sortOptions"
|
[options]="sortOptions"
|
||||||
[ngModel]="sortBy$ | async"
|
[ngModel]="sortBy()"
|
||||||
(ngModelChange)="onSortChange($event)"
|
(ngModelChange)="onSortChange($event)"
|
||||||
optionLabel="label"
|
optionLabel="label"
|
||||||
optionValue="value"
|
optionValue="value"
|
||||||
@@ -37,12 +37,12 @@
|
|||||||
</p-select>
|
</p-select>
|
||||||
|
|
||||||
<button class="sort-direction-btn" (click)="toggleSortDirection()">
|
<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>
|
||||||
|
|
||||||
<button class="filter-btn" (click)="filterPopover.toggle($event)">
|
<button class="filter-btn" (click)="filterPopover.toggle($event)">
|
||||||
<i class="pi pi-filter"></i>
|
<i class="pi pi-filter"></i>
|
||||||
@if (activeFilterCount > 0) {
|
@if (activeFilterCount() > 0) {
|
||||||
<span class="filter-badge"></span>
|
<span class="filter-badge"></span>
|
||||||
}
|
}
|
||||||
</button>
|
</button>
|
||||||
@@ -55,15 +55,15 @@
|
|||||||
<div class="display-settings-content">
|
<div class="display-settings-content">
|
||||||
<label class="display-settings-label">{{ t('cardSize') }}</label>
|
<label class="display-settings-label">{{ t('cardSize') }}</label>
|
||||||
<p-slider
|
<p-slider
|
||||||
[(ngModel)]="authorScaleService.scaleFactor"
|
[ngModel]="authorScaleService.scaleFactor()"
|
||||||
|
(ngModelChange)="authorScaleService.setScale($event)"
|
||||||
[min]="0.7"
|
[min]="0.7"
|
||||||
[max]="1.3"
|
[max]="1.3"
|
||||||
[step]="0.01"
|
[step]="0.01"
|
||||||
[style]="{ width: '100%' }"
|
[style]="{ width: '100%' }">
|
||||||
(onChange)="updateScale()">
|
|
||||||
</p-slider>
|
</p-slider>
|
||||||
<div class="scale-value-display">
|
<div class="scale-value-display">
|
||||||
{{ authorScaleService.scaleFactor.toFixed(2) }}x
|
{{ authorScaleService.scaleFactor().toFixed(2) }}x
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</p-popover>
|
</p-popover>
|
||||||
@@ -79,7 +79,7 @@
|
|||||||
{label: t('filters.matched'), value: 'matched'},
|
{label: t('filters.matched'), value: 'matched'},
|
||||||
{label: t('filters.unmatched'), value: 'unmatched'}
|
{label: t('filters.unmatched'), value: 'unmatched'}
|
||||||
]"
|
]"
|
||||||
[ngModel]="(filters$ | async)?.matchStatus"
|
[ngModel]="filters().matchStatus"
|
||||||
(ngModelChange)="onFilterChange('matchStatus', $event)"
|
(ngModelChange)="onFilterChange('matchStatus', $event)"
|
||||||
optionLabel="label"
|
optionLabel="label"
|
||||||
optionValue="value"
|
optionValue="value"
|
||||||
@@ -95,7 +95,7 @@
|
|||||||
{label: t('filters.hasPhoto'), value: 'has-photo'},
|
{label: t('filters.hasPhoto'), value: 'has-photo'},
|
||||||
{label: t('filters.noPhoto'), value: 'no-photo'}
|
{label: t('filters.noPhoto'), value: 'no-photo'}
|
||||||
]"
|
]"
|
||||||
[ngModel]="(filters$ | async)?.photoStatus"
|
[ngModel]="filters().photoStatus"
|
||||||
(ngModelChange)="onFilterChange('photoStatus', $event)"
|
(ngModelChange)="onFilterChange('photoStatus', $event)"
|
||||||
optionLabel="label"
|
optionLabel="label"
|
||||||
optionValue="value"
|
optionValue="value"
|
||||||
@@ -113,7 +113,7 @@
|
|||||||
{label: t('filters.inProgress'), value: 'in-progress'},
|
{label: t('filters.inProgress'), value: 'in-progress'},
|
||||||
{label: t('filters.unread'), value: 'unread'}
|
{label: t('filters.unread'), value: 'unread'}
|
||||||
]"
|
]"
|
||||||
[ngModel]="(filters$ | async)?.readStatus"
|
[ngModel]="filters().readStatus"
|
||||||
(ngModelChange)="onFilterChange('readStatus', $event)"
|
(ngModelChange)="onFilterChange('readStatus', $event)"
|
||||||
optionLabel="label"
|
optionLabel="label"
|
||||||
optionValue="value"
|
optionValue="value"
|
||||||
@@ -137,7 +137,7 @@
|
|||||||
{label: '21-35', value: '21-35'},
|
{label: '21-35', value: '21-35'},
|
||||||
{label: '36+', value: '36+'}
|
{label: '36+', value: '36+'}
|
||||||
]"
|
]"
|
||||||
[ngModel]="(filters$ | async)?.bookCount"
|
[ngModel]="filters().bookCount"
|
||||||
(ngModelChange)="onFilterChange('bookCount', $event)"
|
(ngModelChange)="onFilterChange('bookCount', $event)"
|
||||||
optionLabel="label"
|
optionLabel="label"
|
||||||
optionValue="value"
|
optionValue="value"
|
||||||
@@ -148,8 +148,8 @@
|
|||||||
<div class="filter-group">
|
<div class="filter-group">
|
||||||
<label class="filter-label">{{ t('filters.library') }}</label>
|
<label class="filter-label">{{ t('filters.library') }}</label>
|
||||||
<p-select
|
<p-select
|
||||||
[options]="libraryOptions"
|
[options]="libraryOptions()"
|
||||||
[ngModel]="(filters$ | async)?.library"
|
[ngModel]="filters().library"
|
||||||
(ngModelChange)="onFilterChange('library', $event)"
|
(ngModelChange)="onFilterChange('library', $event)"
|
||||||
optionLabel="label"
|
optionLabel="label"
|
||||||
optionValue="value"
|
optionValue="value"
|
||||||
@@ -160,8 +160,8 @@
|
|||||||
<div class="filter-group">
|
<div class="filter-group">
|
||||||
<label class="filter-label">{{ t('filters.genre') }}</label>
|
<label class="filter-label">{{ t('filters.genre') }}</label>
|
||||||
<p-select
|
<p-select
|
||||||
[options]="genreOptions"
|
[options]="genreOptions()"
|
||||||
[ngModel]="(filters$ | async)?.genre"
|
[ngModel]="filters().genre"
|
||||||
(ngModelChange)="onFilterChange('genre', $event)"
|
(ngModelChange)="onFilterChange('genre', $event)"
|
||||||
optionLabel="label"
|
optionLabel="label"
|
||||||
optionValue="value"
|
optionValue="value"
|
||||||
@@ -169,7 +169,7 @@
|
|||||||
</p-select>
|
</p-select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (activeFilterCount > 0) {
|
@if (activeFilterCount() > 0) {
|
||||||
<p-button
|
<p-button
|
||||||
[label]="t('filters.reset')"
|
[label]="t('filters.reset')"
|
||||||
icon="pi pi-filter-slash"
|
icon="pi pi-filter-slash"
|
||||||
@@ -186,7 +186,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (filteredAuthors$ | async; as authorList) {
|
@if (filteredAuthors(); as authorList) {
|
||||||
@if (authorList.length === 0) {
|
@if (authorList.length === 0) {
|
||||||
<div class="empty-state">
|
<div class="empty-state">
|
||||||
<i class="pi pi-users empty-icon"></i>
|
<i class="pi pi-users empty-icon"></i>
|
||||||
@@ -203,7 +203,7 @@
|
|||||||
@for (author of scroll.viewPortItems; track author.id; let i = $index) {
|
@for (author of scroll.viewPortItems; track author.id; let i = $index) {
|
||||||
<div class="virtual-scroller-item"
|
<div class="virtual-scroller-item"
|
||||||
[ngStyle]="{width: cardWidth + 'px', height: cardHeight + 'px'}"
|
[ngStyle]="{width: cardWidth + 'px', height: cardHeight + 'px'}"
|
||||||
[style.--card-scale]="authorScaleService.scaleFactor">
|
[style.--card-scale]="authorScaleService.scaleFactor()">
|
||||||
<app-author-card
|
<app-author-card
|
||||||
[author]="author"
|
[author]="author"
|
||||||
[index]="authorList.indexOf(author)"
|
[index]="authorList.indexOf(author)"
|
||||||
@@ -226,12 +226,12 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (userService.userState$ | async; as userState) {
|
@if (currentUser(); as user) {
|
||||||
<div class="author-browser-footer" [class.footer-hidden]="selectedCount === 0">
|
<div class="author-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
||||||
<div class="footer-content">
|
<div class="footer-content">
|
||||||
<div class="selected-count-badge">
|
<div class="selected-count-badge">
|
||||||
<i class="pi pi-check-circle"></i>
|
<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>
|
<span class="selected-label">{{ t('footer.selected') }}</span>
|
||||||
</div>
|
</div>
|
||||||
@if (canEditMetadata || canDeleteBook) {
|
@if (canEditMetadata || canDeleteBook) {
|
||||||
|
|||||||
+117
-162
@@ -1,8 +1,8 @@
|
|||||||
import {Component, HostListener, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
import {Component, computed, DestroyRef, effect, HostListener, inject, OnInit, signal, ViewChild} from '@angular/core';
|
||||||
import {AsyncPipe, NgStyle} from '@angular/common';
|
import {NgStyle} from '@angular/common';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {combineLatest, Observable, BehaviorSubject, Subscription} from 'rxjs';
|
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {filter, map} from 'rxjs/operators';
|
import {filter} from 'rxjs/operators';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {InputText} from 'primeng/inputtext';
|
import {InputText} from 'primeng/inputtext';
|
||||||
import {Select} from 'primeng/select';
|
import {Select} from 'primeng/select';
|
||||||
@@ -56,7 +56,6 @@ const DEFAULT_SORT_DIRECTIONS: Record<string, SortDirection> = {
|
|||||||
templateUrl: './author-browser.component.html',
|
templateUrl: './author-browser.component.html',
|
||||||
styleUrls: ['./author-browser.component.scss'],
|
styleUrls: ['./author-browser.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
AsyncPipe,
|
|
||||||
NgStyle,
|
NgStyle,
|
||||||
FormsModule,
|
FormsModule,
|
||||||
ProgressSpinner,
|
ProgressSpinner,
|
||||||
@@ -72,7 +71,7 @@ const DEFAULT_SORT_DIRECTIONS: Record<string, SortDirection> = {
|
|||||||
VirtualScrollerModule
|
VirtualScrollerModule
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
export class AuthorBrowserComponent implements OnInit {
|
||||||
|
|
||||||
private static readonly BASE_WIDTH = 165;
|
private static readonly BASE_WIDTH = 165;
|
||||||
private static readonly BASE_HEIGHT = 290;
|
private static readonly BASE_HEIGHT = 290;
|
||||||
@@ -87,6 +86,7 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
|||||||
private t = inject(TranslocoService);
|
private t = inject(TranslocoService);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private activatedRoute = inject(ActivatedRoute);
|
private activatedRoute = inject(ActivatedRoute);
|
||||||
|
private destroyRef = inject(DestroyRef);
|
||||||
protected userService = inject(UserService);
|
protected userService = inject(UserService);
|
||||||
protected authorScaleService = inject(AuthorScalePreferenceService);
|
protected authorScaleService = inject(AuthorScalePreferenceService);
|
||||||
protected selectionService = inject(AuthorSelectionService);
|
protected selectionService = inject(AuthorSelectionService);
|
||||||
@@ -94,15 +94,87 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
|||||||
@ViewChild('scroll')
|
@ViewChild('scroll')
|
||||||
virtualScroller: VirtualScrollerComponent | undefined;
|
virtualScroller: VirtualScrollerComponent | undefined;
|
||||||
|
|
||||||
private subscriptions: Subscription[] = [];
|
|
||||||
|
|
||||||
loading = true;
|
|
||||||
private authorsLoaded = false;
|
|
||||||
private booksLoaded = false;
|
|
||||||
screenWidth = window.innerWidth;
|
screenWidth = window.innerWidth;
|
||||||
selectedCount = 0;
|
|
||||||
isCheckboxEnabled = false;
|
|
||||||
thumbnailCacheBusters = new Map<number, number>();
|
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')
|
@HostListener('window:resize')
|
||||||
onResize(): void {
|
onResize(): void {
|
||||||
@@ -117,39 +189,27 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
|||||||
const base = this.isMobile
|
const base = this.isMobile
|
||||||
? AuthorBrowserComponent.MOBILE_BASE_WIDTH
|
? AuthorBrowserComponent.MOBILE_BASE_WIDTH
|
||||||
: AuthorBrowserComponent.BASE_WIDTH;
|
: AuthorBrowserComponent.BASE_WIDTH;
|
||||||
return Math.round(base * this.authorScaleService.scaleFactor);
|
return Math.round(base * this.authorScaleService.scaleFactor());
|
||||||
}
|
}
|
||||||
|
|
||||||
get cardHeight(): number {
|
get cardHeight(): number {
|
||||||
const base = this.isMobile
|
const base = this.isMobile
|
||||||
? AuthorBrowserComponent.MOBILE_BASE_HEIGHT
|
? AuthorBrowserComponent.MOBILE_BASE_HEIGHT
|
||||||
: AuthorBrowserComponent.BASE_HEIGHT;
|
: AuthorBrowserComponent.BASE_HEIGHT;
|
||||||
return Math.round(base * this.authorScaleService.scaleFactor);
|
return Math.round(base * this.authorScaleService.scaleFactor());
|
||||||
}
|
}
|
||||||
|
|
||||||
get gridColumnMinWidth(): string {
|
get gridColumnMinWidth(): string {
|
||||||
return `${this.cardWidth}px`;
|
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[] = [];
|
sortOptions: SortOption[] = [];
|
||||||
libraryOptions: FilterOption[] = [];
|
|
||||||
genreOptions: FilterOption[] = [];
|
|
||||||
activeFilterCount = 0;
|
|
||||||
|
|
||||||
private readonly validSortValues = [
|
private readonly validSortValues = [
|
||||||
'name', 'book-count', 'matched', 'recently-added', 'recently-read',
|
'name', 'book-count', 'matched', 'recently-added', 'recently-read',
|
||||||
'reading-progress', 'avg-rating', 'photo', 'series-count'
|
'reading-progress', 'avg-rating', 'photo', 'series-count'
|
||||||
];
|
];
|
||||||
|
|
||||||
filteredAuthors$!: Observable<EnrichedAuthor[]>;
|
|
||||||
private enrichedAuthors$ = new BehaviorSubject<EnrichedAuthor[]>([]);
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.pageTitle.setPageTitle(this.t.translate('authorBrowser.pageTitle'));
|
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 sortParam = this.activatedRoute.snapshot.queryParamMap.get('sort');
|
||||||
const dirParam = this.activatedRoute.snapshot.queryParamMap.get('dir') as SortDirection | null;
|
const dirParam = this.activatedRoute.snapshot.queryParamMap.get('dir') as SortDirection | null;
|
||||||
if (sortParam && this.validSortValues.includes(sortParam)) {
|
if (sortParam && this.validSortValues.includes(sortParam)) {
|
||||||
this.sortBy$.next(sortParam);
|
this.sortBy.set(sortParam);
|
||||||
this.sortDirection$.next(dirParam === 'asc' || dirParam === 'desc' ? dirParam : DEFAULT_SORT_DIRECTIONS[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();
|
this.setupScrollPositionTracking();
|
||||||
}
|
this.destroyRef.onDestroy(() => this.selectionService.deselectAll());
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.subscriptions.forEach(s => s.unsubscribe());
|
|
||||||
this.selectionService.deselectAll();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onSearchChange(value: string): void {
|
onSearchChange(value: string): void {
|
||||||
this.searchTerm$.next(value);
|
this.searchTerm.set(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
onSortChange(value: string): void {
|
onSortChange(value: string): void {
|
||||||
this.sortBy$.next(value);
|
this.sortBy.set(value);
|
||||||
this.sortDirection$.next(DEFAULT_SORT_DIRECTIONS[value] || 'asc');
|
const nextDirection = DEFAULT_SORT_DIRECTIONS[value] || 'asc';
|
||||||
this.updateSortQueryParams(value, this.sortDirection$.value);
|
this.sortDirection.set(nextDirection);
|
||||||
|
this.updateSortQueryParams(value, nextDirection);
|
||||||
}
|
}
|
||||||
|
|
||||||
toggleSortDirection(): void {
|
toggleSortDirection(): void {
|
||||||
const next: SortDirection = this.sortDirection$.value === 'asc' ? 'desc' : 'asc';
|
const next: SortDirection = this.sortDirection() === 'asc' ? 'desc' : 'asc';
|
||||||
this.sortDirection$.next(next);
|
this.sortDirection.set(next);
|
||||||
this.updateSortQueryParams(this.sortBy$.value, next);
|
this.updateSortQueryParams(this.sortBy(), next);
|
||||||
}
|
}
|
||||||
|
|
||||||
onFilterChange(key: keyof AuthorFilters, value: string): void {
|
onFilterChange(key: keyof AuthorFilters, value: string): void {
|
||||||
const current = this.filters$.value;
|
this.filters.update(current => ({...current, [key]: value}));
|
||||||
this.filters$.next({...current, [key]: value});
|
|
||||||
this.updateActiveFilterCount();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
resetFilters(): void {
|
resetFilters(): void {
|
||||||
this.filters$.next({...DEFAULT_AUTHOR_FILTERS});
|
this.filters.set({...DEFAULT_AUTHOR_FILTERS});
|
||||||
this.activeFilterCount = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateScale(): void {
|
|
||||||
this.authorScaleService.setScale(this.authorScaleService.scaleFactor);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get canEditMetadata(): boolean {
|
get canEditMetadata(): boolean {
|
||||||
const user = this.userService.getCurrentUser();
|
const user = this.userService.currentUser();
|
||||||
return !!user?.permissions?.admin || !!user?.permissions?.canEditMetadata;
|
return !!user?.permissions?.admin || !!user?.permissions?.canEditMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
get canDeleteBook(): boolean {
|
get canDeleteBook(): boolean {
|
||||||
const user = this.userService.getCurrentUser();
|
const user = this.userService.currentUser();
|
||||||
return !!user?.permissions?.admin || !!user?.permissions?.canDeleteBook;
|
return !!user?.permissions?.admin || !!user?.permissions?.canDeleteBook;
|
||||||
}
|
}
|
||||||
|
|
||||||
isAuthorSelected(authorId: number): boolean {
|
isAuthorSelected(authorId: number): boolean {
|
||||||
return this.selectionService.selectedAuthors.has(authorId);
|
return this.selectedAuthors().has(authorId);
|
||||||
}
|
}
|
||||||
|
|
||||||
onCheckboxClicked(event: AuthorCheckboxClickEvent): void {
|
onCheckboxClicked(event: AuthorCheckboxClickEvent): void {
|
||||||
@@ -322,9 +317,9 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
onAuthorQuickMatched(updated: AuthorSummary): void {
|
onAuthorQuickMatched(updated: AuthorSummary): void {
|
||||||
this.thumbnailCacheBusters.set(updated.id, Date.now());
|
this.thumbnailCacheBusters.set(updated.id, Date.now());
|
||||||
const current = this.allAuthors$.value;
|
this.allAuthorsState.update(current =>
|
||||||
const updatedList = current.map(a => a.id === updated.id ? updated : a);
|
(current ?? []).map(author => author.id === updated.id ? updated : author)
|
||||||
this.allAuthors$.next(updatedList);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
autoMatchSelected(): void {
|
autoMatchSelected(): void {
|
||||||
@@ -333,10 +328,9 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
|||||||
this.authorService.autoMatchAuthors(ids).subscribe({
|
this.authorService.autoMatchAuthors(ids).subscribe({
|
||||||
next: (matched) => {
|
next: (matched) => {
|
||||||
this.thumbnailCacheBusters.set(matched.id, Date.now());
|
this.thumbnailCacheBusters.set(matched.id, Date.now());
|
||||||
const current = this.allAuthors$.value;
|
this.allAuthorsState.update(current => (current ?? []).map(author => author.id === matched.id
|
||||||
this.allAuthors$.next(current.map(a => a.id === matched.id
|
? {...author, asin: matched.asin, hasPhoto: matched.hasPhoto}
|
||||||
? {...a, asin: matched.asin, hasPhoto: matched.hasPhoto}
|
: author
|
||||||
: a
|
|
||||||
));
|
));
|
||||||
},
|
},
|
||||||
complete: () => {
|
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[] {
|
private enrichAuthors(authors: AuthorSummary[], books: Book[]): EnrichedAuthor[] {
|
||||||
const booksByAuthor = new Map<string, Book[]>();
|
const booksByAuthor = new Map<string, Book[]>();
|
||||||
for (const book of books) {
|
for (const book of books) {
|
||||||
@@ -544,14 +501,13 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private setupScrollPositionTracking(): void {
|
private setupScrollPositionTracking(): void {
|
||||||
this.subscriptions.push(
|
this.router.events.pipe(
|
||||||
this.router.events.pipe(
|
filter(event => event instanceof NavigationStart),
|
||||||
filter(event => event instanceof NavigationStart)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe(() => {
|
).subscribe(() => {
|
||||||
this.dismissBodyMenus();
|
this.dismissBodyMenus();
|
||||||
this.saveScrollPosition();
|
this.saveScrollPosition();
|
||||||
})
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private dismissBodyMenus(): void {
|
private dismissBodyMenus(): void {
|
||||||
@@ -568,8 +524,7 @@ export class AuthorBrowserComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
private removeAuthorsFromList(ids: number[]): void {
|
private removeAuthorsFromList(ids: number[]): void {
|
||||||
const idSet = new Set(ids);
|
const idSet = new Set(ids);
|
||||||
const updated = this.allAuthors$.value.filter(a => !idSet.has(a.id));
|
this.allAuthorsState.update(current => (current ?? []).filter(author => !idSet.has(author.id)));
|
||||||
this.allAuthors$.next(updated);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private applySort(authors: EnrichedAuthor[], sortBy: string, direction: SortDirection): EnrichedAuthor[] {
|
private applySort(authors: EnrichedAuthor[], sortBy: string, direction: SortDirection): EnrichedAuthor[] {
|
||||||
|
|||||||
+2
-2
@@ -7,7 +7,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (!loading && author) {
|
@if (!loading && author(); as author) {
|
||||||
<div class="author-wrapper">
|
<div class="author-wrapper">
|
||||||
<p-tabs [value]="tab" lazy="true" scrollable>
|
<p-tabs [value]="tab" lazy="true" scrollable>
|
||||||
<p-tablist>
|
<p-tablist>
|
||||||
@@ -95,7 +95,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (authorBooks$ | async; as books) {
|
@if (authorBooks(); as books) {
|
||||||
<div class="books-section">
|
<div class="books-section">
|
||||||
<h3 class="section-title">{{ t('booksBy', {name: author.name}) }} ({{ books.length }})</h3>
|
<h3 class="section-title">{{ t('booksBy', {name: author.name}) }} ({{ books.length }})</h3>
|
||||||
@if (books.length === 0) {
|
@if (books.length === 0) {
|
||||||
|
|||||||
+28
-39
@@ -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 {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
|
import {NgClass, NgStyle} from '@angular/common';
|
||||||
import {combineLatest, Observable} from 'rxjs';
|
|
||||||
import {filter, map} from 'rxjs/operators';
|
|
||||||
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
@@ -14,7 +12,6 @@ import {Tooltip} from 'primeng/tooltip';
|
|||||||
import {AuthorService} from '../../service/author.service';
|
import {AuthorService} from '../../service/author.service';
|
||||||
import {AuthorDetails} from '../../model/author.model';
|
import {AuthorDetails} from '../../model/author.model';
|
||||||
import {BookService} from '../../../book/service/book.service';
|
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 {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
|
||||||
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
|
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
|
||||||
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-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',
|
templateUrl: './author-detail.component.html',
|
||||||
styleUrls: ['./author-detail.component.scss'],
|
styleUrls: ['./author-detail.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
AsyncPipe,
|
|
||||||
NgClass,
|
NgClass,
|
||||||
NgStyle,
|
NgStyle,
|
||||||
Tabs,
|
Tabs,
|
||||||
@@ -63,7 +59,6 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
|
|
||||||
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
||||||
|
|
||||||
author: AuthorDetails | null = null;
|
|
||||||
loading = true;
|
loading = true;
|
||||||
tab = 'books';
|
tab = 'books';
|
||||||
isExpanded = false;
|
isExpanded = false;
|
||||||
@@ -71,20 +66,31 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
hasPhoto = true;
|
hasPhoto = true;
|
||||||
photoTimestamp = Date.now();
|
photoTimestamp = Date.now();
|
||||||
quickMatching = false;
|
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() {
|
get currentCardSize() {
|
||||||
return this.coverScalePreferenceService.currentCardSize;
|
return this.coverScalePreferenceService.currentCardSize();
|
||||||
}
|
}
|
||||||
|
|
||||||
get gridColumnMinWidth(): string {
|
get gridColumnMinWidth(): string {
|
||||||
return this.coverScalePreferenceService.gridColumnMinWidth;
|
return this.coverScalePreferenceService.gridColumnMinWidth();
|
||||||
}
|
}
|
||||||
|
|
||||||
get photoUrl(): string {
|
get photoUrl(): string {
|
||||||
if (!this.author) return '';
|
const author = this.author();
|
||||||
return this.authorService.getAuthorPhotoUrl(this.author.id) + '&t=' + this.photoTimestamp;
|
if (!author) return '';
|
||||||
|
return this.authorService.getAuthorPhotoUrl(author.id) + '&t=' + this.photoTimestamp;
|
||||||
}
|
}
|
||||||
|
|
||||||
get canEditMetadata(): boolean {
|
get canEditMetadata(): boolean {
|
||||||
@@ -99,18 +105,6 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
this.tab = tabParam;
|
this.tab = tabParam;
|
||||||
}
|
}
|
||||||
this.loadAuthor(authorId);
|
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 {
|
ngAfterViewChecked(): void {
|
||||||
@@ -129,15 +123,21 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onAuthorUpdated(updatedAuthor: AuthorDetails): void {
|
onAuthorUpdated(updatedAuthor: AuthorDetails): void {
|
||||||
this.author = updatedAuthor;
|
this.authorState.set(updatedAuthor);
|
||||||
this.hasPhoto = true;
|
this.hasPhoto = true;
|
||||||
this.photoTimestamp = Date.now();
|
this.photoTimestamp = Date.now();
|
||||||
|
this.authorService.patchAuthorInCache(updatedAuthor.id, {
|
||||||
|
name: updatedAuthor.name,
|
||||||
|
asin: updatedAuthor.asin,
|
||||||
|
hasPhoto: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
quickMatch(): void {
|
quickMatch(): void {
|
||||||
if (!this.author || this.quickMatching) return;
|
const author = this.author();
|
||||||
|
if (!author || this.quickMatching) return;
|
||||||
this.quickMatching = true;
|
this.quickMatching = true;
|
||||||
this.authorService.quickMatchAuthor(this.author.id).subscribe({
|
this.authorService.quickMatchAuthor(author.id).subscribe({
|
||||||
next: (matched) => {
|
next: (matched) => {
|
||||||
this.onAuthorUpdated(matched);
|
this.onAuthorUpdated(matched);
|
||||||
this.quickMatching = false;
|
this.quickMatching = false;
|
||||||
@@ -161,20 +161,9 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
private loadAuthor(authorId: number): void {
|
private loadAuthor(authorId: number): void {
|
||||||
this.authorService.getAuthorDetails(authorId).subscribe({
|
this.authorService.getAuthorDetails(authorId).subscribe({
|
||||||
next: (author) => {
|
next: (author) => {
|
||||||
this.author = author;
|
this.authorState.set(author);
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
this.pageTitle.setPageTitle(author.name);
|
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: () => {
|
error: () => {
|
||||||
this.loading = false;
|
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;
|
||||||
+27
-14
@@ -1,6 +1,4 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable, signal} from '@angular/core';
|
||||||
import {Subject} from 'rxjs';
|
|
||||||
import {debounceTime} from 'rxjs/operators';
|
|
||||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
@@ -13,31 +11,46 @@ export class AuthorScalePreferenceService {
|
|||||||
|
|
||||||
private readonly localStorageService = inject(LocalStorageService);
|
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() {
|
constructor() {
|
||||||
this.loadScaleFromStorage();
|
const initialScale = this.loadScaleFromStorage();
|
||||||
|
this._scaleFactor.set(initialScale);
|
||||||
this.scaleChangeSubject
|
this.lastPersistedScale = initialScale;
|
||||||
.pipe(debounceTime(this.DEBOUNCE_MS))
|
|
||||||
.subscribe(scale => this.saveScalePreference(scale));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setScale(scale: number): void {
|
setScale(scale: number): void {
|
||||||
this.scaleFactor = scale;
|
this._scaleFactor.set(scale);
|
||||||
this.scaleChangeSubject.next(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 {
|
private saveScalePreference(scale: number): void {
|
||||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
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);
|
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
||||||
if (saved !== null && !isNaN(saved)) {
|
if (saved !== null && !isNaN(saved)) {
|
||||||
this.scaleFactor = saved;
|
return saved;
|
||||||
}
|
}
|
||||||
|
return 1.0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import {Injectable} from '@angular/core';
|
import {computed, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, Observable} from 'rxjs';
|
|
||||||
import {AuthorSummary} from '../model/author.model';
|
import {AuthorSummary} from '../model/author.model';
|
||||||
|
|
||||||
export interface AuthorCheckboxClickEvent {
|
export interface AuthorCheckboxClickEvent {
|
||||||
@@ -11,20 +10,13 @@ export interface AuthorCheckboxClickEvent {
|
|||||||
|
|
||||||
@Injectable({providedIn: 'root'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class AuthorSelectionService {
|
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 currentAuthors: AuthorSummary[] = [];
|
||||||
private lastSelectedIndex: number | null = null;
|
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 {
|
setCurrentAuthors(authors: AuthorSummary[]): void {
|
||||||
this.currentAuthors = authors;
|
this.currentAuthors = authors;
|
||||||
}
|
}
|
||||||
@@ -55,31 +47,37 @@ export class AuthorSelectionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
selectAll(): void {
|
selectAll(): void {
|
||||||
const current = new Set(this.selectedAuthorsSubject.value);
|
this._selectedAuthors.update(current => {
|
||||||
for (const author of this.currentAuthors) {
|
const next = new Set(current);
|
||||||
current.add(author.id);
|
for (const author of this.currentAuthors) {
|
||||||
}
|
next.add(author.id);
|
||||||
this.selectedAuthorsSubject.next(current);
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
deselectAll(): void {
|
deselectAll(): void {
|
||||||
this.selectedAuthorsSubject.next(new Set());
|
this._selectedAuthors.set(new Set());
|
||||||
this.lastSelectedIndex = null;
|
this.lastSelectedIndex = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
getSelectedIds(): number[] {
|
getSelectedIds(): number[] {
|
||||||
return Array.from(this.selectedAuthorsSubject.value);
|
return Array.from(this.selectedAuthors());
|
||||||
}
|
}
|
||||||
|
|
||||||
private select(id: number): void {
|
private select(id: number): void {
|
||||||
const current = new Set(this.selectedAuthorsSubject.value);
|
this._selectedAuthors.update(current => {
|
||||||
current.add(id);
|
const next = new Set(current);
|
||||||
this.selectedAuthorsSubject.next(current);
|
next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private deselect(id: number): void {
|
private deselect(id: number): void {
|
||||||
const current = new Set(this.selectedAuthorsSubject.value);
|
this._selectedAuthors.update(current => {
|
||||||
current.delete(id);
|
const next = new Set(current);
|
||||||
this.selectedAuthorsSubject.next(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 {HttpClient, HttpHeaders} from '@angular/common/http';
|
||||||
import {BehaviorSubject, Observable} from 'rxjs';
|
import {lastValueFrom, Observable} from 'rxjs';
|
||||||
import {map, tap} from 'rxjs/operators';
|
import {map} from 'rxjs/operators';
|
||||||
import {SseClient} from 'ngx-sse-client';
|
import {SseClient} from 'ngx-sse-client';
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model';
|
import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model';
|
||||||
import {AuthService} from '../../../shared/service/auth.service';
|
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({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
@@ -15,16 +18,41 @@ export class AuthorService {
|
|||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private authService = inject(AuthService);
|
private authService = inject(AuthService);
|
||||||
private sseClient = inject(SseClient);
|
private sseClient = inject(SseClient);
|
||||||
|
private queryClient = inject(QueryClient);
|
||||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`;
|
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`;
|
||||||
private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`;
|
private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`;
|
||||||
|
private readonly token = this.authService.token;
|
||||||
|
|
||||||
private allAuthorsSubject = new BehaviorSubject<AuthorSummary[] | null>(null);
|
private authorsQuery = injectQuery(() => ({
|
||||||
allAuthors$ = this.allAuthorsSubject.asObservable();
|
...this.getAuthorsQueryOptions(),
|
||||||
|
enabled: !!this.token(),
|
||||||
|
}));
|
||||||
|
|
||||||
getAllAuthors(): Observable<AuthorSummary[]> {
|
allAuthors = computed(() => this.authorsQuery.data() ?? null);
|
||||||
return this.http.get<AuthorSummary[]>(this.baseUrl).pipe(
|
isAuthorsLoading = computed(() => !!this.token() && this.authorsQuery.isPending());
|
||||||
tap(authors => this.allAuthorsSubject.next(authors))
|
|
||||||
);
|
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> {
|
getAuthorDetails(authorId: number): Observable<AuthorDetails> {
|
||||||
|
|||||||
+20
-40
@@ -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 {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
@@ -13,8 +13,6 @@ import {BookMetadataService} from '../../service/book-metadata.service';
|
|||||||
import {LibraryService} from '../../service/library.service';
|
import {LibraryService} from '../../service/library.service';
|
||||||
import {Library} from '../../model/library.model';
|
import {Library} from '../../model/library.model';
|
||||||
import {CreatePhysicalBookRequest} from '../../model/book.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';
|
import {TranslocoDirective} from '@jsverse/transloco';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -34,15 +32,13 @@ import {TranslocoDirective} from '@jsverse/transloco';
|
|||||||
],
|
],
|
||||||
styleUrl: './add-physical-book-dialog.component.scss',
|
styleUrl: './add-physical-book-dialog.component.scss',
|
||||||
})
|
})
|
||||||
export class AddPhysicalBookDialogComponent implements OnInit {
|
export class AddPhysicalBookDialogComponent {
|
||||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||||
private dialogConfig = inject(DynamicDialogConfig);
|
private dialogConfig = inject(DynamicDialogConfig);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private bookMetadataService = inject(BookMetadataService);
|
private bookMetadataService = inject(BookMetadataService);
|
||||||
private libraryService = inject(LibraryService);
|
private libraryService = inject(LibraryService);
|
||||||
private destroyRef = inject(DestroyRef);
|
|
||||||
|
|
||||||
libraries: Library[] = [];
|
|
||||||
selectedLibraryId: number | null = null;
|
selectedLibraryId: number | null = null;
|
||||||
title: string = '';
|
title: string = '';
|
||||||
isbn: string = '';
|
isbn: string = '';
|
||||||
@@ -54,49 +50,33 @@ export class AddPhysicalBookDialogComponent implements OnInit {
|
|||||||
pageCount: number | null = null;
|
pageCount: number | null = null;
|
||||||
categories: string[] = [];
|
categories: string[] = [];
|
||||||
|
|
||||||
allAuthors: string[] = [];
|
private readonly metadata = computed(() => this.bookService.uniqueMetadata());
|
||||||
allCategories: string[] = [];
|
get allAuthors(): string[] { return this.metadata().authors; }
|
||||||
|
get allCategories(): string[] { return this.metadata().categories; }
|
||||||
filteredAuthors: string[] = [];
|
filteredAuthors: string[] = [];
|
||||||
filteredCategories: string[] = [];
|
filteredCategories: string[] = [];
|
||||||
|
|
||||||
coverUrl: string | null = null;
|
coverUrl: string | null = null;
|
||||||
isLoading: boolean = false;
|
isLoading: boolean = false;
|
||||||
isFetchingMetadata: boolean = false;
|
isFetchingMetadata: boolean = false;
|
||||||
|
private readonly initializeSelectedLibraryEffect = effect(() => {
|
||||||
|
const libraries = this.libraries;
|
||||||
|
if (libraries.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
if (this.dialogConfig.data?.libraryId) {
|
||||||
this.libraryService.libraryState$
|
this.selectedLibraryId = this.dialogConfig.data.libraryId;
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
return;
|
||||||
.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();
|
|
||||||
}
|
|
||||||
|
|
||||||
private prepareAutoComplete(): void {
|
if (this.selectedLibraryId == null && this.libraries[0].id !== undefined) {
|
||||||
this.bookService.bookState$
|
this.selectedLibraryId = this.libraries[0].id;
|
||||||
.pipe(
|
}
|
||||||
filter((bookState) => bookState.loaded),
|
});
|
||||||
take(1)
|
|
||||||
)
|
|
||||||
.subscribe((bookState) => {
|
|
||||||
const authors = new Set<string>();
|
|
||||||
const categories = new Set<string>();
|
|
||||||
|
|
||||||
(bookState.books ?? []).forEach((book) => {
|
get libraries(): Library[] {
|
||||||
book.metadata?.authors?.forEach((author) => authors.add(author));
|
return this.libraryService.libraries();
|
||||||
book.metadata?.categories?.forEach((category) => categories.add(category));
|
|
||||||
});
|
|
||||||
|
|
||||||
this.allAuthors = Array.from(authors);
|
|
||||||
this.allCategories = Array.from(categories);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
filterAuthors(event: AutoCompleteCompleteEvent): void {
|
filterAuthors(event: AutoCompleteCompleteEvent): void {
|
||||||
|
|||||||
+7
-14
@@ -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 {FormsModule} from '@angular/forms';
|
||||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
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 {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||||
import {AdditionalFileType, Book} from '../../model/book.model';
|
import {AdditionalFileType, Book} from '../../model/book.model';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {filter, take} from 'rxjs/operators';
|
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
|
|
||||||
interface FileTypeOption {
|
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.typeAlternativeFormat'), value: AdditionalFileType.ALTERNATIVE_FORMAT },
|
||||||
{ label: this.t.translate('book.fileUploader.typeSupplementary'), value: AdditionalFileType.SUPPLEMENTARY }
|
{ label: this.t.translate('book.fileUploader.typeSupplementary'), value: AdditionalFileType.SUPPLEMENTARY }
|
||||||
];
|
];
|
||||||
this.appSettingsService.appSettings$
|
const settings = this.appSettingsService.appSettings();
|
||||||
.pipe(
|
if (settings) {
|
||||||
filter(settings => settings != null),
|
const maxSizeMb = settings.maxFileUploadSizeInMb || 100;
|
||||||
take(1)
|
this.maxFileSizeBytes = maxSizeMb * 1024 * 1024;
|
||||||
)
|
this.maxFileSizeDisplay = `${maxSizeMb} MB`;
|
||||||
.subscribe(settings => {
|
}
|
||||||
if (settings) {
|
|
||||||
const maxSizeMb = settings.maxFileUploadSizeInMb || 100;
|
|
||||||
this.maxFileSizeBytes = maxSizeMb * 1024 * 1024;
|
|
||||||
this.maxFileSizeDisplay = `${maxSizeMb} MB`;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
ngOnDestroy(): void {
|
||||||
|
|||||||
+44
-136
@@ -1,16 +1,10 @@
|
|||||||
import {Injectable, inject} from '@angular/core';
|
import {Injectable, inject} from '@angular/core';
|
||||||
import {ActivatedRoute} from '@angular/router';
|
import {ParamMap} from '@angular/router';
|
||||||
import {Observable, of, combineLatest} from 'rxjs';
|
|
||||||
import {map, switchMap, take, catchError} from 'rxjs/operators';
|
|
||||||
import {Library} from '../../model/library.model';
|
import {Library} from '../../model/library.model';
|
||||||
import {Shelf} from '../../model/shelf.model';
|
import {Shelf} from '../../model/shelf.model';
|
||||||
import {Book} from '../../model/book.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 {LibraryService} from '../../service/library.service';
|
||||||
import {BookService} from '../../service/book.service';
|
|
||||||
import {ShelfService} from '../../service/shelf.service';
|
import {ShelfService} from '../../service/shelf.service';
|
||||||
import {SortService} from '../../service/sort.service';
|
|
||||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
||||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||||
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
||||||
@@ -24,79 +18,61 @@ export interface EntityInfo {
|
|||||||
@Injectable({providedIn: 'root'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class BookBrowserEntityService {
|
export class BookBrowserEntityService {
|
||||||
private libraryService = inject(LibraryService);
|
private libraryService = inject(LibraryService);
|
||||||
private bookService = inject(BookService);
|
|
||||||
private shelfService = inject(ShelfService);
|
private shelfService = inject(ShelfService);
|
||||||
private sortService = inject(SortService);
|
|
||||||
private magicShelfService = inject(MagicShelfService);
|
private magicShelfService = inject(MagicShelfService);
|
||||||
private bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
private bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||||
|
|
||||||
getEntityInfoFromRoute(activatedRoute: ActivatedRoute): Observable<EntityInfo> {
|
getEntityInfo(paramMap: ParamMap): EntityInfo {
|
||||||
return activatedRoute.paramMap.pipe(
|
const libraryId = Number(paramMap.get('libraryId') || NaN);
|
||||||
map(params => {
|
const shelfId = Number(paramMap.get('shelfId') || NaN);
|
||||||
const libraryId = Number(params.get('libraryId') || NaN);
|
const magicShelfId = Number(paramMap.get('magicShelfId') || NaN);
|
||||||
const shelfId = Number(params.get('shelfId') || NaN);
|
|
||||||
const magicShelfId = Number(params.get('magicShelfId') || NaN);
|
|
||||||
|
|
||||||
if (!isNaN(libraryId)) {
|
if (!Number.isNaN(libraryId)) {
|
||||||
return {entityId: libraryId, entityType: EntityType.LIBRARY};
|
return {entityId: libraryId, entityType: EntityType.LIBRARY};
|
||||||
} else if (!isNaN(shelfId)) {
|
}
|
||||||
return {entityId: shelfId, entityType: EntityType.SHELF};
|
|
||||||
} else if (!isNaN(magicShelfId)) {
|
if (!Number.isNaN(shelfId)) {
|
||||||
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
|
return {entityId: shelfId, entityType: EntityType.SHELF};
|
||||||
} else {
|
}
|
||||||
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
|
|
||||||
}
|
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) {
|
switch (entityType) {
|
||||||
case EntityType.LIBRARY:
|
case EntityType.LIBRARY:
|
||||||
return this.fetchLibrary(entityId);
|
return this.libraryService.libraries().find(lib => lib.id === entityId) ?? null;
|
||||||
case EntityType.SHELF:
|
case EntityType.SHELF:
|
||||||
return this.fetchShelf(entityId);
|
return this.shelfService.shelves().find(shelf => shelf.id === entityId) ?? null;
|
||||||
case EntityType.MAGIC_SHELF:
|
case EntityType.MAGIC_SHELF:
|
||||||
return this.fetchMagicShelf(entityId);
|
return this.magicShelfService.findShelfById(entityId) ?? null;
|
||||||
default:
|
default:
|
||||||
return of(null);
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fetchBooksByEntity(
|
getBooksByEntity(books: Book[], entityId: number, entityType: EntityType): Book[] {
|
||||||
entityId: number,
|
|
||||||
entityType: EntityType,
|
|
||||||
sortOption: SortOption
|
|
||||||
): Observable<BookState> {
|
|
||||||
switch (entityType) {
|
switch (entityType) {
|
||||||
case EntityType.LIBRARY:
|
case EntityType.LIBRARY:
|
||||||
return this.fetchBooks(book => book.libraryId === entityId, sortOption);
|
return books.filter(book => book.libraryId === entityId);
|
||||||
case EntityType.SHELF:
|
case EntityType.SHELF:
|
||||||
return this.fetchShelfBooks(entityId, sortOption);
|
return books.filter(book => book.shelves?.some(shelf => shelf.id === entityId) ?? false);
|
||||||
case EntityType.MAGIC_SHELF:
|
case EntityType.MAGIC_SHELF: {
|
||||||
return this.fetchMagicShelfBooks(entityId, sortOption);
|
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:
|
case EntityType.ALL_BOOKS:
|
||||||
default:
|
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 {
|
isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
|
||||||
return (entity as Library).paths !== undefined;
|
return (entity as Library).paths !== undefined;
|
||||||
}
|
}
|
||||||
@@ -105,85 +81,17 @@ export class BookBrowserEntityService {
|
|||||||
return !!entity && 'filterJson' in entity;
|
return !!entity && 'filterJson' in entity;
|
||||||
}
|
}
|
||||||
|
|
||||||
private fetchLibrary(libraryId: number): Observable<Library | null> {
|
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
|
||||||
return this.libraryService.libraryState$.pipe(
|
if (!magicShelf.filterJson) {
|
||||||
map(libraryState => {
|
return [];
|
||||||
if (libraryState.libraries) {
|
}
|
||||||
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
|
|
||||||
}
|
try {
|
||||||
return null;
|
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 [];
|
||||||
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};
|
|
||||||
}
|
}
|
||||||
return bookState;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+66
-69
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
<div class="book-browser-header">
|
<div class="book-browser-header">
|
||||||
<div class="entity-info-wrapper">
|
<div class="entity-info-wrapper">
|
||||||
@if (entityType$ | async; as entityType) {
|
@if (entityType(); as entityType) {
|
||||||
<div class="entity-info">
|
<div class="entity-info">
|
||||||
<p class="entity-title">
|
<p class="entity-title">
|
||||||
@if (entityType === EntityType.ALL_BOOKS) {
|
@if (entityType === EntityType.ALL_BOOKS) {
|
||||||
@@ -18,19 +18,19 @@
|
|||||||
} @else if (entityType === EntityType.UNSHELVED) {
|
} @else if (entityType === EntityType.UNSHELVED) {
|
||||||
{{ (isFilterActive || hasSearchTerm) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
|
{{ (isFilterActive || hasSearchTerm) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
|
||||||
} @else {
|
} @else {
|
||||||
{{ entityType }}: {{ (entity$ | async)?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
|
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
|
||||||
}
|
}
|
||||||
</p>
|
</p>
|
||||||
@if (seriesCollapseFilter.isSeriesCollapsed && (bookState$ | async)?.books; as books) {
|
@if (seriesCollapseFilter.seriesCollapsed() && books(); as books) {
|
||||||
<p class="series-collapsed-info">
|
<p class="series-collapsed-info">
|
||||||
{{ t('labels.seriesCollapsedInfo', { count: books.length, itemWord: books.length === 1 ? t('labels.item') : t('labels.items') }) }}
|
{{ t('labels.seriesCollapsedInfo', { count: books.length, itemWord: books.length === 1 ? t('labels.item') : t('labels.items') }) }}
|
||||||
</p>
|
</p>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (userService.userState$ | async; as userState) {
|
@if (userService.currentUser(); as currentUser) {
|
||||||
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
|
@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">
|
<div class="entity-menu-wrapper">
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-ellipsis-v"
|
icon="pi pi-ellipsis-v"
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
severity="info"
|
severity="info"
|
||||||
(click)="entitymenu.toggle($event)">
|
(click)="entitymenu.toggle($event)">
|
||||||
</p-button>
|
</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>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -106,7 +106,7 @@
|
|||||||
<p-checkbox
|
<p-checkbox
|
||||||
inputId="collapse-series-checkbox"
|
inputId="collapse-series-checkbox"
|
||||||
[binary]="true"
|
[binary]="true"
|
||||||
[ngModel]="seriesCollapseFilter.isSeriesCollapsed"
|
[ngModel]="seriesCollapseFilter.seriesCollapsed()"
|
||||||
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
|
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
|
||||||
</p-checkbox>
|
</p-checkbox>
|
||||||
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
|
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
|
||||||
@@ -137,15 +137,15 @@
|
|||||||
<div class="display-settings-section">
|
<div class="display-settings-section">
|
||||||
<label class="display-settings-label">{{ t('labels.gridItemSize') }}</label>
|
<label class="display-settings-label">{{ t('labels.gridItemSize') }}</label>
|
||||||
<p-slider
|
<p-slider
|
||||||
[(ngModel)]="coverScalePreferenceService.scaleFactor"
|
[ngModel]="coverScalePreferenceService.scaleFactor()"
|
||||||
|
(ngModelChange)="coverScalePreferenceService.setScale($event)"
|
||||||
[min]="0.5"
|
[min]="0.5"
|
||||||
[max]="1.5"
|
[max]="1.5"
|
||||||
[step]="0.01"
|
[step]="0.01"
|
||||||
[style]="{ width: '100%' }"
|
[style]="{ width: '100%' }">
|
||||||
(onChange)="updateScale()">
|
|
||||||
</p-slider>
|
</p-slider>
|
||||||
<div class="scale-value-display">
|
<div class="scale-value-display">
|
||||||
{{ coverScalePreferenceService.scaleFactor.toFixed(2) }}x
|
{{ coverScalePreferenceService.scaleFactor().toFixed(2) }}x
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,7 @@
|
|||||||
<p-checkbox
|
<p-checkbox
|
||||||
inputId="show-book-type-pill-checkbox"
|
inputId="show-book-type-pill-checkbox"
|
||||||
[binary]="true"
|
[binary]="true"
|
||||||
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill"
|
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill()"
|
||||||
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
|
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
|
||||||
</p-checkbox>
|
</p-checkbox>
|
||||||
<label for="show-book-type-pill-checkbox" class="display-settings-label">{{ t('labels.bookTypeOverlay') }}</label>
|
<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()">
|
<a class="topbar-items topbar-item" (click)="toggleSidebar()">
|
||||||
<i
|
<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')"
|
[pTooltip]="t('tooltip.toggleSidebar')"
|
||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</i>
|
</i>
|
||||||
@@ -261,78 +261,75 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (bookState$ | async; as bookState) {
|
@if (books(); as books) {
|
||||||
<div>
|
<div>
|
||||||
@if (!bookState?.loaded && !bookState?.error) {
|
@if (isBooksLoading()) {
|
||||||
<div>
|
<div>
|
||||||
<p-progressSpinner></p-progressSpinner>
|
<p-progressSpinner></p-progressSpinner>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="book-state-wrapper">
|
<div class="book-state-wrapper">
|
||||||
@if (bookState?.error) {
|
@if (booksError()) {
|
||||||
<div class="no-books-container">
|
<div class="no-books-container">
|
||||||
<p class="no-books-text">
|
<p class="no-books-text">
|
||||||
{{ entityType === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
|
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
}
|
} @else if (!isBooksLoading() && books.length === 0) {
|
||||||
@if (!bookState?.error && bookState?.loaded && bookState?.books?.length === 0) {
|
|
||||||
<div class="no-books-container">
|
<div class="no-books-container">
|
||||||
<p class="no-books-text">
|
<p class="no-books-text">
|
||||||
{{ t('labels.noBooks') }}
|
{{ t('labels.noBooks') }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (bookState?.books; as books) {
|
@if (currentViewMode === 'table' && books.length > 0) {
|
||||||
@if (currentViewMode === 'table' && books.length > 0) {
|
<app-book-table
|
||||||
<app-book-table
|
[books]="books"
|
||||||
[books]="books"
|
[preselectedBookIds]="selectedBooks()"
|
||||||
[preselectedBookIds]="selectedBooks"
|
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
[sortOption]="this.bookSorter.selectedSort!"
|
||||||
[sortOption]="this.bookSorter.selectedSort!"
|
[visibleColumns]="visibleColumns"
|
||||||
[visibleColumns]="visibleColumns"
|
></app-book-table>
|
||||||
></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 (userService.userState$ | async; as userState) {
|
@if (currentViewMode === 'grid') {
|
||||||
<div class="book-browser-footer" [class.footer-hidden]="selectedCount === 0">
|
<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-content">
|
||||||
<div class="footer-left">
|
<div class="footer-left">
|
||||||
<div class="selected-count-badge">
|
<div class="selected-count-badge">
|
||||||
<i class="pi pi-check-circle"></i>
|
<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>
|
<span class="selected-label">{{ t('labels.selected') }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="footer-center">
|
<div class="footer-center">
|
||||||
@if (entityType$ | async; as entityType) {
|
@if (entityType(); as entityType) {
|
||||||
<div class="action-buttons-group">
|
<div class="action-buttons-group">
|
||||||
@if (hasMetadataMenuItems) {
|
@if (hasMetadataMenuItems) {
|
||||||
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
||||||
@@ -363,7 +360,7 @@
|
|||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
}
|
}
|
||||||
@if (userState.user?.permissions?.canBulkLockUnlockMetadata) {
|
@if (currentUser.permissions.canBulkLockUnlockMetadata) {
|
||||||
<p-button
|
<p-button
|
||||||
outlined="true"
|
outlined="true"
|
||||||
icon="pi pi-lock"
|
icon="pi pi-lock"
|
||||||
@@ -373,7 +370,7 @@
|
|||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
}
|
}
|
||||||
@if (userState.user?.permissions?.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
|
@if (currentUser.permissions.canMoveOrganizeFiles && appSettingsService.appSettings()?.diskType === 'LOCAL') {
|
||||||
<p-button
|
<p-button
|
||||||
outlined="true"
|
outlined="true"
|
||||||
icon="pi pi-arrows-h"
|
icon="pi pi-arrows-h"
|
||||||
@@ -383,7 +380,7 @@
|
|||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
}
|
}
|
||||||
@if (userState.user?.permissions?.canManageLibrary || userState.user?.permissions?.admin) {
|
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
|
||||||
<p-button
|
<p-button
|
||||||
outlined="true"
|
outlined="true"
|
||||||
icon="pi pi-link"
|
icon="pi pi-link"
|
||||||
@@ -428,7 +425,7 @@
|
|||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
</div>
|
</div>
|
||||||
@if (userState?.user?.permissions?.admin || userState?.user?.permissions?.canDeleteBook) {
|
@if (currentUser?.permissions?.admin || currentUser?.permissions?.canDeleteBook) {
|
||||||
<p-divider layout="vertical"></p-divider>
|
<p-divider layout="vertical"></p-divider>
|
||||||
<p-button
|
<p-button
|
||||||
outlined="true"
|
outlined="true"
|
||||||
@@ -449,17 +446,17 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (this.showFilter) {
|
@if (showFilter()) {
|
||||||
<div
|
<div
|
||||||
class="mobile-filter-mask"
|
class="mobile-filter-mask"
|
||||||
(click)="toggleSidebar()">
|
(click)="toggleSidebar()">
|
||||||
</div>
|
</div>
|
||||||
<app-book-filter
|
<app-book-filter
|
||||||
[showFilter]="showFilter"
|
[showFilter]="showFilter()"
|
||||||
class="filter-overlay-container"
|
class="filter-overlay-container"
|
||||||
[ngClass]="{ 'active': showFilter }"
|
[ngClass]="{ 'active': showFilter() }"
|
||||||
[entity$]="entity$"
|
[entity]="entity()"
|
||||||
[entityType$]="entityType$"
|
[entityType]="entityType()"
|
||||||
[resetFilter$]="resetFilterSubject"
|
[resetFilter$]="resetFilterSubject"
|
||||||
(filterSelected)="onFilterSelected($event)"
|
(filterSelected)="onFilterSelected($event)"
|
||||||
(filterModeChanged)="onFilterModeChanged($event)">
|
(filterModeChanged)="onFilterModeChanged($event)">
|
||||||
|
|||||||
+242
-306
@@ -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 {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
||||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||||
import {BookService} from '../../service/book.service';
|
import {BookService} from '../../service/book.service';
|
||||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||||
import {debounceTime, filter, map, switchMap, takeUntil} from 'rxjs/operators';
|
import {debounceTime, distinctUntilChanged, filter, map, takeUntil} from 'rxjs/operators';
|
||||||
import {BehaviorSubject, combineLatest, finalize, Observable, of, Subject, Subscription} from 'rxjs';
|
import {combineLatest, finalize, Subject} from 'rxjs';
|
||||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {Library} from '../../model/library.model';
|
import {Library} from '../../model/library.model';
|
||||||
import {Shelf} from '../../model/shelf.model';
|
|
||||||
import {SortDirection, SortOption} from '../../model/sort.model';
|
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||||
import {BookState} from '../../model/state/book-state.model';
|
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
|
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
|
||||||
import {BookTableComponent} from './book-table/book-table.component';
|
import {BookTableComponent} from './book-table/book-table.component';
|
||||||
import {animate, style, transition, trigger} from '@angular/animations';
|
import {animate, style, transition, trigger} from '@angular/animations';
|
||||||
import {Button} from 'primeng/button';
|
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 {VirtualScrollerComponent, VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
|
||||||
import {BookCardComponent} from './book-card/book-card.component';
|
import {BookCardComponent} from './book-card/book-card.component';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
@@ -27,8 +26,6 @@ import {BookFilterComponent} from './book-filter/book-filter.component';
|
|||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {BookFilterMode, DEFAULT_VISIBLE_SORT_FIELDS, EntityViewPreferences, SortCriterion, UserService} from '../../../settings/user-management/user.service';
|
import {BookFilterMode, DEFAULT_VISIBLE_SORT_FIELDS, EntityViewPreferences, SortCriterion, UserService} from '../../../settings/user-management/user.service';
|
||||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||||
import {SideBarFilter} from './filters/sidebar-filter';
|
|
||||||
import {HeaderFilter} from './filters/HeaderFilter';
|
|
||||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||||
import {BookSorter} from './sorting/BookSorter';
|
import {BookSorter} from './sorting/BookSorter';
|
||||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||||
@@ -41,7 +38,6 @@ import {TableColumnPreferenceService} from './table-column-preference.service';
|
|||||||
import {TieredMenu} from 'primeng/tieredmenu';
|
import {TieredMenu} from 'primeng/tieredmenu';
|
||||||
import {BadgeModule} from 'primeng/badge';
|
import {BadgeModule} from 'primeng/badge';
|
||||||
import {BookMenuService} from '../../service/book-menu.service';
|
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 {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service';
|
||||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||||
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
|
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 {BookBrowserScrollService} from './book-browser-scroll.service';
|
||||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||||
import {MultiSortPopoverComponent} from './sorting/multi-sort-popover/multi-sort-popover.component';
|
import {MultiSortPopoverComponent} from './sorting/multi-sort-popover/multi-sort-popover.component';
|
||||||
import {SortService} from '../../service/sort.service';
|
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
|
|
||||||
export enum EntityType {
|
export enum EntityType {
|
||||||
@@ -74,7 +69,7 @@ export enum EntityType {
|
|||||||
templateUrl: './book-browser.component.html',
|
templateUrl: './book-browser.component.html',
|
||||||
styleUrls: ['./book-browser.component.scss'],
|
styleUrls: ['./book-browser.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule,
|
Button, VirtualScrollerModule, BookCardComponent, ProgressSpinner, Menu, InputText, FormsModule,
|
||||||
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
|
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
|
||||||
Checkbox, Slider, Divider, MultiSelect, TieredMenu, BadgeModule, MultiSortPopoverComponent, TranslocoDirective
|
Checkbox, Slider, Divider, MultiSelect, TieredMenu, BadgeModule, MultiSortPopoverComponent, TranslocoDirective
|
||||||
],
|
],
|
||||||
@@ -105,7 +100,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
protected bookSelectionService = inject(BookSelectionService);
|
protected bookSelectionService = inject(BookSelectionService);
|
||||||
protected appSettingsService = inject(AppSettingsService);
|
protected appSettingsService = inject(AppSettingsService);
|
||||||
|
|
||||||
private cdr = inject(ChangeDetectorRef);
|
|
||||||
private activatedRoute = inject(ActivatedRoute);
|
private activatedRoute = inject(ActivatedRoute);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
@@ -124,35 +118,98 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
private scrollService = inject(BookBrowserScrollService);
|
private scrollService = inject(BookBrowserScrollService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
bookState$: Observable<BookState> | undefined;
|
private readonly defaultSortCriteria: SortOption[] = [{
|
||||||
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
|
field: 'addedOn',
|
||||||
entityType$: Observable<EntityType> | undefined;
|
direction: SortDirection.DESCENDING,
|
||||||
private entityRouteInfo$!: Observable<EntityInfo>;
|
label: 'Added On'
|
||||||
searchTerm$ = new BehaviorSubject<string>('');
|
}];
|
||||||
selectedFilter = new BehaviorSubject<Record<string, string[]> | null>(null);
|
private readonly routePath = toSignal(
|
||||||
selectedFilterMode = new BehaviorSubject<BookFilterMode>('and');
|
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>();
|
protected resetFilterSubject = new Subject<void>();
|
||||||
|
|
||||||
parsedFilters: Record<string, string[]> = {};
|
parsedFilters: Record<string, string[]> = {};
|
||||||
entity: Library | Shelf | MagicShelf | null = null;
|
|
||||||
entityType: EntityType | undefined;
|
|
||||||
bookTitle = '';
|
bookTitle = '';
|
||||||
entityOptions: MenuItem[] | undefined;
|
|
||||||
isDrawerVisible = false;
|
|
||||||
dynamicDialogRef: DynamicDialogRef | undefined | null;
|
dynamicDialogRef: DynamicDialogRef | undefined | null;
|
||||||
EntityType = EntityType;
|
EntityType = EntityType;
|
||||||
currentFilterLabel: string | null = null;
|
currentFilterLabel: string | null = null;
|
||||||
rawFilterParamFromUrl: string | null = null;
|
rawFilterParamFromUrl: string | null = null;
|
||||||
hasSearchTerm = false;
|
|
||||||
visibleColumns: { field: string; header: string }[] = [];
|
visibleColumns: { field: string; header: string }[] = [];
|
||||||
entityViewPreferences: EntityViewPreferences | undefined;
|
entityViewPreferences: EntityViewPreferences | undefined;
|
||||||
currentViewMode: string | undefined;
|
currentViewMode: string | undefined;
|
||||||
lastAppliedSortCriteria: SortOption[] = [];
|
lastAppliedSortCriteria: SortOption[] = [];
|
||||||
visibleSortOptions: SortOption[] = [];
|
visibleSortOptions: SortOption[] = [];
|
||||||
showFilter = false;
|
|
||||||
screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024;
|
screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024;
|
||||||
mobileColumnCount = 3;
|
mobileColumnCount = 3;
|
||||||
selectedCount = 0;
|
|
||||||
|
|
||||||
private readonly MOBILE_BREAKPOINT = 768;
|
private readonly MOBILE_BREAKPOINT = 768;
|
||||||
private readonly CARD_ASPECT_RATIO = 7 / 5;
|
private readonly CARD_ASPECT_RATIO = 7 / 5;
|
||||||
@@ -166,15 +223,60 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
protected metadataMenuItems: MenuItem[] | undefined;
|
protected metadataMenuItems: MenuItem[] | undefined;
|
||||||
protected moreActionsMenuItems: MenuItem[] | undefined;
|
protected moreActionsMenuItems: MenuItem[] | undefined;
|
||||||
|
|
||||||
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
|
|
||||||
private headerFilter = new HeaderFilter(this.searchTerm$);
|
|
||||||
protected bookSorter = new BookSorter(
|
protected bookSorter = new BookSorter(
|
||||||
sortCriteria => this.onMultiSortChange(sortCriteria),
|
sortCriteria => this.onMultiSortChange(sortCriteria),
|
||||||
this.t
|
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)
|
@ViewChild(BookTableComponent)
|
||||||
bookTableComponent!: BookTableComponent;
|
bookTableComponent!: BookTableComponent;
|
||||||
@@ -202,15 +304,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
return {width: cardWidth, height: cardHeight};
|
return {width: cardWidth, height: cardHeight};
|
||||||
}
|
}
|
||||||
|
|
||||||
get selectedBooks(): Set<number> {
|
|
||||||
return this.bookSelectionService.selectedBooks;
|
|
||||||
}
|
|
||||||
|
|
||||||
get currentCardSize() {
|
get currentCardSize() {
|
||||||
if (this.isMobile) {
|
if (this.isMobile) {
|
||||||
return this.mobileCardSize;
|
return this.mobileCardSize;
|
||||||
}
|
}
|
||||||
const base = this.coverScalePreferenceService.currentCardSize;
|
const base = this.coverScalePreferenceService.currentCardSize();
|
||||||
if (this.isAudiobookOnlyLibrary) {
|
if (this.isAudiobookOnlyLibrary) {
|
||||||
const squareSide = Math.round(base.width * 1.1);
|
const squareSide = Math.round(base.width * 1.1);
|
||||||
return { width: squareSide, height: squareSide + 31 };
|
return { width: squareSide, height: squareSide + 31 };
|
||||||
@@ -225,7 +323,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
if (this.isAudiobookOnlyLibrary) {
|
if (this.isAudiobookOnlyLibrary) {
|
||||||
return `${this.currentCardSize.width}px`;
|
return `${this.currentCardSize.width}px`;
|
||||||
}
|
}
|
||||||
return this.coverScalePreferenceService.gridColumnMinWidth;
|
return this.coverScalePreferenceService.gridColumnMinWidth();
|
||||||
}
|
}
|
||||||
|
|
||||||
getCardHeight(_book: Book): number {
|
getCardHeight(_book: Book): number {
|
||||||
@@ -243,11 +341,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get isFilterActive(): boolean {
|
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 {
|
get computedFilterLabel(): string {
|
||||||
const filters = this.selectedFilter.value;
|
const filters = this.selectedFilter();
|
||||||
|
|
||||||
if (!filters || Object.keys(filters).length === 0) {
|
if (!filters || Object.keys(filters).length === 0) {
|
||||||
return this.t.translate('book.browser.labels.allBooks');
|
return this.t.translate('book.browser.labels.allBooks');
|
||||||
@@ -277,8 +376,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get isAudiobookOnlyLibrary(): boolean {
|
get isAudiobookOnlyLibrary(): boolean {
|
||||||
if (!this.entity || this.entityType !== EntityType.LIBRARY) return false;
|
const entity = this.entity();
|
||||||
const library = this.entity as Library;
|
if (!entity || this.entityType() !== EntityType.LIBRARY) return false;
|
||||||
|
const library = entity as Library;
|
||||||
return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK';
|
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 {
|
get hasMetadataMenuItems(): boolean {
|
||||||
return this.metadataMenuItems!.length > 0;
|
return (this.metadataMenuItems?.length ?? 0) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
get hasMoreActionsItems(): boolean {
|
get hasMoreActionsItems(): boolean {
|
||||||
return this.moreActionsMenuItems!.length > 0;
|
return (this.moreActionsMenuItems?.length ?? 0) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.pageTitle.setPageTitle('');
|
|
||||||
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000), takeUntil(this.destroy$)).subscribe();
|
|
||||||
this.loadMobileColumnsPreference();
|
this.loadMobileColumnsPreference();
|
||||||
|
|
||||||
this.initializeEntityRouting();
|
|
||||||
this.setupRouteChangeHandlers();
|
this.setupRouteChangeHandlers();
|
||||||
this.setupUserStateSubscription();
|
|
||||||
this.setupQueryParamSubscription();
|
this.setupQueryParamSubscription();
|
||||||
this.setupFilterToggleSubscription();
|
|
||||||
this.setupSearchTermSubscription();
|
|
||||||
this.setupScrollPositionTracking();
|
this.setupScrollPositionTracking();
|
||||||
this.setupSelectionSubscription();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ngAfterViewInit(): void {
|
ngAfterViewInit(): void {
|
||||||
if (this.bookFilterComponent) {
|
if (this.bookFilterComponent) {
|
||||||
this.bookFilterComponent.setFilters?.(this.parsedFilters);
|
this.bookFilterComponent.setFilters?.(this.parsedFilters);
|
||||||
this.bookFilterComponent.onFiltersChanged?.();
|
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 {
|
private setupRouteChangeHandlers(): void {
|
||||||
this.activatedRoute.paramMap.pipe(takeUntil(this.destroy$)).subscribe(() => {
|
this.activatedRoute.paramMap.pipe(takeUntil(this.destroy$)).subscribe(() => {
|
||||||
this.searchTerm$.next('');
|
this.searchTerm.set('');
|
||||||
this.bookTitle = '';
|
this.bookTitle = '';
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
this.clearFilter();
|
this.clearFilter();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupUserStateSubscription(): void {
|
private readonly syncMetadataMenuEffect = effect(() => {
|
||||||
this.userService.userState$.pipe(
|
const user = this.userService.currentUser();
|
||||||
filter(u => !!u?.user && u.loaded),
|
if (!user) return;
|
||||||
takeUntil(this.destroy$)
|
|
||||||
).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());
|
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
|
||||||
}
|
() => this.autoFetchMetadata(),
|
||||||
|
() => this.fetchMetadata(),
|
||||||
|
() => this.bulkEditMetadata(),
|
||||||
|
() => this.multiBookEditMetadata(),
|
||||||
|
() => this.regenerateCoversForSelected(),
|
||||||
|
() => this.generateCustomCoversForSelected(),
|
||||||
|
user
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
private setupQueryParamSubscription(): void {
|
private setupQueryParamSubscription(): void {
|
||||||
combineLatest([
|
combineLatest([
|
||||||
this.entityRouteInfo$,
|
this.activatedRoute.paramMap.pipe(map(() => this.entityInfo())),
|
||||||
this.activatedRoute.queryParamMap,
|
this.activatedRoute.queryParamMap,
|
||||||
this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded))
|
this.currentUser$,
|
||||||
]).pipe(takeUntil(this.destroy$)).subscribe(([entityInfo, queryParamMap, user]) => {
|
]).pipe(
|
||||||
|
takeUntil(this.destroy$)
|
||||||
|
).subscribe(([entityInfo, queryParamMap, currentUser]) => {
|
||||||
const parseResult = this.queryParamsService.parseQueryParams(
|
const parseResult = this.queryParamsService.parseQueryParams(
|
||||||
queryParamMap,
|
queryParamMap,
|
||||||
user.user?.userSettings?.entityViewPreferences,
|
currentUser.userSettings?.entityViewPreferences,
|
||||||
entityInfo.entityType,
|
entityInfo.entityType,
|
||||||
entityInfo.entityId,
|
entityInfo.entityId,
|
||||||
this.bookSorter.sortOptions,
|
this.bookSorter.sortOptions,
|
||||||
user.user?.userSettings?.filterMode ?? 'and'
|
currentUser.userSettings?.filterMode ?? 'and'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
if (parseResult.filterMode !== this.selectedFilterMode.getValue()) {
|
if (parseResult.filterMode !== this.selectedFilterMode()) {
|
||||||
this.selectedFilterMode.next(parseResult.filterMode);
|
this.selectedFilterMode.set(parseResult.filterMode);
|
||||||
if (this.bookFilterComponent) {
|
if (this.bookFilterComponent) {
|
||||||
this.bookFilterComponent.selectedFilterMode = parseResult.filterMode;
|
this.bookFilterComponent.selectedFilterMode = parseResult.filterMode;
|
||||||
}
|
}
|
||||||
@@ -440,7 +490,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
|
|
||||||
if (filterParams) {
|
if (filterParams) {
|
||||||
this.settingFiltersFromUrl = true;
|
this.settingFiltersFromUrl = true;
|
||||||
this.selectedFilter.next(parseResult.filters);
|
this.selectedFilter.set(parseResult.filters);
|
||||||
|
|
||||||
if (this.bookFilterComponent) {
|
if (this.bookFilterComponent) {
|
||||||
this.bookFilterComponent.setFilters?.(parseResult.filters);
|
this.bookFilterComponent.setFilters?.(parseResult.filters);
|
||||||
@@ -461,12 +511,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
this.parsedFilters = parseResult.filters;
|
this.parsedFilters = parseResult.filters;
|
||||||
|
|
||||||
|
|
||||||
this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences;
|
this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences;
|
||||||
this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor);
|
this.columnPreferenceService.initPreferences(currentUser.userSettings?.tableColumnPreference);
|
||||||
this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference);
|
|
||||||
this.visibleColumns = this.columnPreferenceService.visibleColumns;
|
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]));
|
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);
|
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.queryParamsService.syncQueryParams(
|
||||||
this.currentViewMode!,
|
this.currentViewMode!,
|
||||||
this.selectedFilterMode.getValue(),
|
this.selectedFilterMode(),
|
||||||
this.parsedFilters
|
this.parsedFilters
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupSearchTermSubscription(): void {
|
onFilterSelected(filters: Record<string, unknown> | null): 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 {
|
|
||||||
if (this.settingFiltersFromUrl) return;
|
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;
|
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.currentFilterLabel = hasSidebarFilters ? this.computedFilterLabel : this.t.translate('book.browser.labels.allBooks');
|
||||||
|
|
||||||
this.queryParamsService.updateFilters(filters);
|
this.queryParamsService.updateFilters(normalizedFilters);
|
||||||
}
|
}
|
||||||
|
|
||||||
onFilterModeChanged(mode: BookFilterMode): void {
|
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);
|
this.queryParamsService.updateFilterMode(mode, this.parsedFilters);
|
||||||
}
|
}
|
||||||
|
|
||||||
toggleSidebar(): void {
|
toggleSidebar(): void {
|
||||||
this.showFilter = !this.showFilter;
|
this.sidebarFilterTogglePrefService.toggle();
|
||||||
this.sidebarFilterTogglePrefService.selectedShowFilter = this.showFilter;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateScale(): void {
|
|
||||||
this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
|
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
|
||||||
@@ -550,19 +580,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
|
|
||||||
onCheckboxClicked(event: CheckboxClickEvent): void {
|
onCheckboxClicked(event: CheckboxClickEvent): void {
|
||||||
this.bookSelectionService.handleCheckboxClick(event);
|
this.bookSelectionService.handleCheckboxClick(event);
|
||||||
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleBookSelect(book: Book, selected: boolean): void {
|
handleBookSelect(book: Book, selected: boolean): void {
|
||||||
this.bookSelectionService.handleBookSelection(book, selected);
|
this.bookSelectionService.handleBookSelection(book, selected);
|
||||||
this.isDrawerVisible = this.bookSelectionService.hasSelection();
|
|
||||||
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onSelectedBooksChange(selectedBookIds: Set<number>): void {
|
onSelectedBooksChange(selectedBookIds: Set<number>): void {
|
||||||
this.bookSelectionService.setSelectedBooks(selectedBookIds);
|
this.bookSelectionService.setSelectedBooks(selectedBookIds);
|
||||||
this.isDrawerVisible = this.bookSelectionService.hasSelection();
|
|
||||||
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
selectAllBooks(): void {
|
selectAllBooks(): void {
|
||||||
@@ -570,21 +595,19 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
if (this.bookTableComponent) {
|
if (this.bookTableComponent) {
|
||||||
this.bookTableComponent.selectAllBooks();
|
this.bookTableComponent.selectAllBooks();
|
||||||
}
|
}
|
||||||
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
deselectAllBooks(): void {
|
deselectAllBooks(): void {
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
this.isDrawerVisible = false;
|
|
||||||
if (this.bookTableComponent) {
|
if (this.bookTableComponent) {
|
||||||
this.bookTableComponent.clearSelectedBooks();
|
this.bookTableComponent.clearSelectedBooks();
|
||||||
}
|
}
|
||||||
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
confirmDeleteBooks(): void {
|
confirmDeleteBooks(): void {
|
||||||
|
const selectedBooks = this.selectedBooks();
|
||||||
this.confirmationService.confirm({
|
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'),
|
header: this.t.translate('book.browser.confirm.deleteHeader'),
|
||||||
icon: 'pi pi-exclamation-triangle',
|
icon: 'pi pi-exclamation-triangle',
|
||||||
acceptIcon: 'pi pi-trash',
|
acceptIcon: 'pi pi-trash',
|
||||||
@@ -594,10 +617,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
acceptButtonStyleClass: 'p-button-danger',
|
acceptButtonStyleClass: 'p-button-danger',
|
||||||
rejectButtonStyleClass: 'p-button-outlined',
|
rejectButtonStyleClass: 'p-button-outlined',
|
||||||
accept: () => {
|
accept: () => {
|
||||||
const count = this.selectedBooks.size;
|
const count = selectedBooks.size;
|
||||||
const loader = this.loadingService.show(this.t.translate('book.browser.loading.deleting', {count}));
|
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)))
|
.pipe(finalize(() => this.loadingService.hide(loader)))
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
@@ -621,54 +644,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
applySortCriteria(sortCriteria: SortOption[]): void {
|
applySortCriteria(sortCriteria: SortOption[]): void {
|
||||||
// Use first criterion for API call (backend doesn't support multi-sort)
|
this.sortCriteria.set(sortCriteria.length > 0 ? sortCriteria : this.defaultSortCriteria);
|
||||||
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)
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Backward compatibility wrapper
|
// Backward compatibility wrapper
|
||||||
@@ -689,18 +665,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get canSaveSort(): boolean {
|
get canSaveSort(): boolean {
|
||||||
return this.entityType === EntityType.LIBRARY ||
|
const entityType = this.entityType();
|
||||||
this.entityType === EntityType.SHELF ||
|
return entityType === EntityType.LIBRARY ||
|
||||||
this.entityType === EntityType.MAGIC_SHELF ||
|
entityType === EntityType.SHELF ||
|
||||||
this.entityType === EntityType.ALL_BOOKS ||
|
entityType === EntityType.MAGIC_SHELF ||
|
||||||
this.entityType === EntityType.UNSHELVED;
|
entityType === EntityType.ALL_BOOKS ||
|
||||||
|
entityType === EntityType.UNSHELVED;
|
||||||
|
}
|
||||||
|
|
||||||
|
get hasSearchTerm(): boolean {
|
||||||
|
return this.searchTerm().trim().length > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
onSaveSortConfig(criteria: SortOption[]): void {
|
onSaveSortConfig(criteria: SortOption[]): void {
|
||||||
if (!this.entityType) return;
|
const entityType = this.entityType();
|
||||||
|
if (!entityType) return;
|
||||||
|
|
||||||
const user = this.userService.getCurrentUser();
|
const user = this.userService.getCurrentUser();
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
|
const entity = this.entity();
|
||||||
|
|
||||||
const sortCriteria: SortCriterion[] = criteria.map(c => ({
|
const sortCriteria: SortCriterion[] = criteria.map(c => ({
|
||||||
field: c.field,
|
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: []}
|
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 = {
|
||||||
...prefs.global,
|
...prefs.global,
|
||||||
sortKey: sortCriteria[0]?.field ?? 'title',
|
sortKey: sortCriteria[0]?.field ?? 'title',
|
||||||
@@ -719,11 +702,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
sortCriteria
|
sortCriteria
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
if (!this.entity) return;
|
if (!entity) return;
|
||||||
if (!prefs.overrides) prefs.overrides = [];
|
if (!prefs.overrides) prefs.overrides = [];
|
||||||
|
|
||||||
let overrideEntityType: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF';
|
let overrideEntityType: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF';
|
||||||
switch (this.entityType) {
|
switch (entityType) {
|
||||||
case EntityType.LIBRARY: overrideEntityType = 'LIBRARY'; break;
|
case EntityType.LIBRARY: overrideEntityType = 'LIBRARY'; break;
|
||||||
case EntityType.SHELF: overrideEntityType = 'SHELF'; break;
|
case EntityType.SHELF: overrideEntityType = 'SHELF'; break;
|
||||||
case EntityType.MAGIC_SHELF: overrideEntityType = 'MAGIC_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(
|
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) {
|
if (existingIndex >= 0) {
|
||||||
@@ -744,7 +727,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
} else {
|
} else {
|
||||||
prefs.overrides.push({
|
prefs.overrides.push({
|
||||||
entityType: overrideEntityType,
|
entityType: overrideEntityType,
|
||||||
entityId: this.entity!.id!,
|
entityId: entity.id!,
|
||||||
preferences: {
|
preferences: {
|
||||||
sortKey: sortCriteria[0]?.field ?? 'title',
|
sortKey: sortCriteria[0]?.field ?? 'title',
|
||||||
sortDir: sortCriteria[0]?.direction ?? 'ASC',
|
sortDir: sortCriteria[0]?.direction ?? 'ASC',
|
||||||
@@ -762,9 +745,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('book.browser.toast.sortSavedSummary'),
|
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.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 {
|
onSearchTermChange(term: string): void {
|
||||||
this.searchTerm$.next(term);
|
this.searchTerm.set(term);
|
||||||
}
|
}
|
||||||
|
|
||||||
clearSearch(): void {
|
clearSearch(): void {
|
||||||
@@ -787,8 +770,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
clearFilter(): void {
|
clearFilter(): void {
|
||||||
if (this.selectedFilter.value !== null) {
|
if (this.selectedFilter() !== null) {
|
||||||
this.selectedFilter.next(null);
|
this.selectedFilter.set(null);
|
||||||
}
|
}
|
||||||
this.clearSearch();
|
this.clearSearch();
|
||||||
}
|
}
|
||||||
@@ -799,11 +782,13 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
unshelfBooks(): void {
|
unshelfBooks(): void {
|
||||||
if (!this.entity) return;
|
const entity = this.entity();
|
||||||
const count = this.selectedBooks.size;
|
if (!entity) return;
|
||||||
|
const selectedBooks = this.selectedBooks();
|
||||||
|
const count = selectedBooks.size;
|
||||||
const loader = this.loadingService.show(this.t.translate('book.browser.loading.unshelving', {count}));
|
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)))
|
.pipe(finalize(() => this.loadingService.hide(loader)))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: () => {
|
next: () => {
|
||||||
@@ -817,7 +802,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
openShelfAssigner(): void {
|
openShelfAssigner(): void {
|
||||||
this.dynamicDialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks);
|
this.dynamicDialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks());
|
||||||
if (this.dynamicDialogRef) {
|
if (this.dynamicDialogRef) {
|
||||||
this.dynamicDialogRef.onClose.subscribe(result => {
|
this.dynamicDialogRef.onClose.subscribe(result => {
|
||||||
if (result.assigned) {
|
if (result.assigned) {
|
||||||
@@ -828,7 +813,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
lockUnlockMetadata(): void {
|
lockUnlockMetadata(): void {
|
||||||
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks);
|
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks());
|
||||||
if (this.dynamicDialogRef) {
|
if (this.dynamicDialogRef) {
|
||||||
this.dynamicDialogRef.onClose.subscribe(() => {
|
this.dynamicDialogRef.onClose.subscribe(() => {
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
@@ -837,19 +822,20 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
autoFetchMetadata(): void {
|
autoFetchMetadata(): void {
|
||||||
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
|
const selectedBooks = this.selectedBooks();
|
||||||
|
if (selectedBooks.size === 0) return;
|
||||||
this.taskHelperService.refreshMetadataTask({
|
this.taskHelperService.refreshMetadataTask({
|
||||||
refreshType: MetadataRefreshType.BOOKS,
|
refreshType: MetadataRefreshType.BOOKS,
|
||||||
bookIds: Array.from(this.selectedBooks),
|
bookIds: Array.from(selectedBooks),
|
||||||
}).subscribe();
|
}).subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
fetchMetadata(): void {
|
fetchMetadata(): void {
|
||||||
this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks);
|
this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks());
|
||||||
}
|
}
|
||||||
|
|
||||||
bulkEditMetadata(): void {
|
bulkEditMetadata(): void {
|
||||||
this.dynamicDialogRef = this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks);
|
this.dynamicDialogRef = this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks());
|
||||||
if (this.dynamicDialogRef) {
|
if (this.dynamicDialogRef) {
|
||||||
this.dynamicDialogRef.onClose.subscribe(() => {
|
this.dynamicDialogRef.onClose.subscribe(() => {
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
@@ -858,7 +844,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
multiBookEditMetadata(): void {
|
multiBookEditMetadata(): void {
|
||||||
this.dynamicDialogRef = this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks);
|
this.dynamicDialogRef = this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks());
|
||||||
if (this.dynamicDialogRef) {
|
if (this.dynamicDialogRef) {
|
||||||
this.dynamicDialogRef.onClose.subscribe(() => {
|
this.dynamicDialogRef.onClose.subscribe(() => {
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
@@ -867,8 +853,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
regenerateCoversForSelected(): void {
|
regenerateCoversForSelected(): void {
|
||||||
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
|
const selectedBooks = this.selectedBooks();
|
||||||
const count = this.selectedBooks.size;
|
if (selectedBooks.size === 0) return;
|
||||||
|
const count = selectedBooks.size;
|
||||||
this.confirmationService.confirm({
|
this.confirmationService.confirm({
|
||||||
message: this.t.translate('book.browser.confirm.regenCoverMessage', {count}),
|
message: this.t.translate('book.browser.confirm.regenCoverMessage', {count}),
|
||||||
header: this.t.translate('book.browser.confirm.regenCoverHeader'),
|
header: this.t.translate('book.browser.confirm.regenCoverHeader'),
|
||||||
@@ -884,7 +871,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
severity: 'secondary'
|
severity: 'secondary'
|
||||||
},
|
},
|
||||||
accept: () => {
|
accept: () => {
|
||||||
this.bookMetadataManageService.regenerateCoversForBooks(Array.from(this.selectedBooks)).subscribe({
|
this.bookMetadataManageService.regenerateCoversForBooks(Array.from(selectedBooks)).subscribe({
|
||||||
next: () => {
|
next: () => {
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
@@ -907,8 +894,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
generateCustomCoversForSelected(): void {
|
generateCustomCoversForSelected(): void {
|
||||||
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
|
const selectedBooks = this.selectedBooks();
|
||||||
const count = this.selectedBooks.size;
|
if (selectedBooks.size === 0) return;
|
||||||
|
const count = selectedBooks.size;
|
||||||
this.confirmationService.confirm({
|
this.confirmationService.confirm({
|
||||||
message: this.t.translate('book.browser.confirm.customCoverMessage', {count}),
|
message: this.t.translate('book.browser.confirm.customCoverMessage', {count}),
|
||||||
header: this.t.translate('book.browser.confirm.customCoverHeader'),
|
header: this.t.translate('book.browser.confirm.customCoverHeader'),
|
||||||
@@ -924,7 +912,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
severity: 'secondary'
|
severity: 'secondary'
|
||||||
},
|
},
|
||||||
accept: () => {
|
accept: () => {
|
||||||
this.bookMetadataManageService.generateCustomCoversForBooks(Array.from(this.selectedBooks)).subscribe({
|
this.bookMetadataManageService.generateCustomCoversForBooks(Array.from(selectedBooks)).subscribe({
|
||||||
next: () => {
|
next: () => {
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
@@ -947,13 +935,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
moveFiles(): void {
|
moveFiles(): void {
|
||||||
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
|
this.dialogHelperService.openFileMoverDialog(this.selectedBooks());
|
||||||
}
|
}
|
||||||
|
|
||||||
attachFilesToBook(): void {
|
attachFilesToBook(): void {
|
||||||
const currentState = this.bookService.getCurrentBookState();
|
const selectedBookIds = Array.from(this.selectedBooks());
|
||||||
const selectedBookIds = Array.from(this.selectedBooks);
|
const sourceBooks = this.bookService.books().filter(book =>
|
||||||
const sourceBooks = (currentState.books || []).filter(book =>
|
|
||||||
selectedBookIds.includes(book.id)
|
selectedBookIds.includes(book.id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -988,11 +975,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
canAttachFiles(): boolean {
|
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 selectedBooks = this.bookService.books().filter(book =>
|
||||||
const selectedBookIds = Array.from(this.selectedBooks);
|
|
||||||
const selectedBooks = (currentState.books || []).filter(book =>
|
|
||||||
selectedBookIds.includes(book.id)
|
selectedBookIds.includes(book.id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1002,56 +988,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
return libraryIds.size === 1;
|
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 {
|
setMobileColumns(columns: number): void {
|
||||||
this.mobileColumnCount = columns;
|
this.mobileColumnCount = columns;
|
||||||
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
|
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
|
||||||
|
|||||||
+25
-36
@@ -1,47 +1,32 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {effect, inject, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, Subject} from 'rxjs';
|
|
||||||
import {debounceTime, filter, takeUntil} from 'rxjs/operators';
|
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class BookCardOverlayPreferenceService {
|
export class BookCardOverlayPreferenceService {
|
||||||
|
private static readonly PERSIST_DELAY_MS = 500;
|
||||||
|
|
||||||
private readonly userService = inject(UserService);
|
private readonly userService = inject(UserService);
|
||||||
|
|
||||||
private readonly _showBookTypePill = new BehaviorSubject<boolean>(true);
|
private readonly _showBookTypePill = signal(true);
|
||||||
readonly showBookTypePill$ = this._showBookTypePill.asObservable();
|
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 currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
|
||||||
|
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.userService.userState$
|
effect(() => {
|
||||||
.pipe(
|
const user = this.userService.currentUser();
|
||||||
filter(userState => !!userState?.user && userState.loaded),
|
if (user) {
|
||||||
takeUntil(this.destroy$)
|
|
||||||
)
|
|
||||||
.subscribe(() => {
|
|
||||||
this.loadPreferencesFromUser();
|
this.loadPreferencesFromUser();
|
||||||
});
|
}
|
||||||
|
});
|
||||||
this.showBookTypePill$
|
|
||||||
.pipe(debounceTime(500))
|
|
||||||
.subscribe(show => {
|
|
||||||
if (this.hasUserToggled) {
|
|
||||||
this.persistPreference(show);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setShowBookTypePill(show: boolean): void {
|
setShowBookTypePill(show: boolean): void {
|
||||||
this.hasUserToggled = true;
|
this._showBookTypePill.set(show);
|
||||||
this._showBookTypePill.next(show);
|
this.schedulePersist(show);
|
||||||
}
|
|
||||||
|
|
||||||
get showBookTypePill(): boolean {
|
|
||||||
return this._showBookTypePill.value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadPreferencesFromUser(): void {
|
private loadPreferencesFromUser(): void {
|
||||||
@@ -68,12 +53,21 @@ export class BookCardOverlayPreferenceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.hasUserToggled = false;
|
if (this._showBookTypePill() !== show) {
|
||||||
if (this._showBookTypePill.value !== show) {
|
this._showBookTypePill.set(show);
|
||||||
this._showBookTypePill.next(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 {
|
private persistPreference(show: boolean): void {
|
||||||
const user = this.userService.getCurrentUser();
|
const user = this.userService.getCurrentUser();
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
@@ -118,9 +112,4 @@ export class BookCardOverlayPreferenceService {
|
|||||||
|
|
||||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.destroy$.next();
|
|
||||||
this.destroy$.complete();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@
|
|||||||
(load)="onImageLoad()"/>
|
(load)="onImageLoad()"/>
|
||||||
|
|
||||||
<div class="top-left-overlay-stack">
|
<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()">
|
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + displayFormat.toLowerCase()">
|
||||||
{{ displayFormat }}
|
{{ displayFormat }}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+27
-50
@@ -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 {TooltipModule} from "primeng/tooltip";
|
||||||
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
|
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
|
||||||
import {Button} from 'primeng/button';
|
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 {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||||
import {NgClass} from '@angular/common';
|
import {NgClass} from '@angular/common';
|
||||||
import {User, UserService} from '../../../../settings/user-management/user.service';
|
import {User, UserService} from '../../../../settings/user-management/user.service';
|
||||||
import {filter, Subject, Subscription} from 'rxjs';
|
|
||||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||||
import {TieredMenu} from 'primeng/tieredmenu';
|
import {TieredMenu} from 'primeng/tieredmenu';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {RouterLink} from '@angular/router';
|
import {RouterLink} from '@angular/router';
|
||||||
import {ProgressBar} from 'primeng/progressbar';
|
import {ProgressBar} from 'primeng/progressbar';
|
||||||
import {take, takeUntil} from 'rxjs/operators';
|
|
||||||
import {readStatusLabels} from '../book-filter/book-filter.config';
|
import {readStatusLabels} from '../book-filter/book-filter.config';
|
||||||
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
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 {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
|
||||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||||
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||||
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-book-card',
|
selector: 'app-book-card',
|
||||||
@@ -38,7 +37,7 @@ import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
|||||||
standalone: true,
|
standalone: true,
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
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() checkboxClick = new EventEmitter<{ index: number; book: Book; selected: boolean; shiftKey: boolean }>();
|
||||||
@Output() menuToggled = new EventEmitter<boolean>();
|
@Output() menuToggled = new EventEmitter<boolean>();
|
||||||
@@ -78,6 +77,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
|||||||
private cdr = inject(ChangeDetectorRef);
|
private cdr = inject(ChangeDetectorRef);
|
||||||
private appSettingsService = inject(AppSettingsService);
|
private appSettingsService = inject(AppSettingsService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
private queryClient = inject(QueryClient);
|
||||||
|
|
||||||
protected _progressPercentage: number | null = null;
|
protected _progressPercentage: number | null = null;
|
||||||
protected _koProgressPercentage: 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';
|
protected _readButtonIcon: string = 'pi pi-book';
|
||||||
|
|
||||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||||
private destroy$ = new Subject<void>();
|
|
||||||
protected readStatusHelper = inject(ReadStatusHelper);
|
protected readStatusHelper = inject(ReadStatusHelper);
|
||||||
private user: User | null = null;
|
private user: User | null = null;
|
||||||
private diskType: string = 'LOCAL';
|
private diskType: string = 'LOCAL';
|
||||||
private menuInitialized = false;
|
private menuInitialized = false;
|
||||||
|
|
||||||
showBookTypePill = true;
|
|
||||||
|
|
||||||
private overlayPrefSub?: Subscription;
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.computeAllMemoizedValues();
|
this.computeAllMemoizedValues();
|
||||||
this.userService.userState$
|
const currentUser = this.userService.currentUser();
|
||||||
.pipe(
|
if (currentUser) {
|
||||||
filter(userState => !!userState?.user && userState.loaded),
|
this.user = currentUser;
|
||||||
take(1),
|
this.metadataCenterViewMode = currentUser.userSettings?.metadataCenterViewMode ?? 'route';
|
||||||
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 settings = this.appSettingsService.appSettings();
|
||||||
|
if (settings) {
|
||||||
|
this.diskType = settings.diskType ?? 'LOCAL';
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges): void {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
@@ -321,19 +300,25 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
|||||||
if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) {
|
if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) {
|
||||||
this.isSubMenuLoading = true;
|
this.isSubMenuLoading = true;
|
||||||
this.cdr.markForCheck();
|
this.cdr.markForCheck();
|
||||||
this.bookService.getBookByIdFromAPI(this.book.id, true).subscribe({
|
const requestedBookId = this.book.id;
|
||||||
next: (book) => {
|
void this.queryClient.fetchQuery(this.bookService.bookDetailQueryOptions(requestedBookId, true))
|
||||||
|
.then((book) => {
|
||||||
|
if (this.book.id !== requestedBookId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.book = book;
|
this.book = book;
|
||||||
this.additionalFilesLoaded = true;
|
this.additionalFilesLoaded = true;
|
||||||
this.isSubMenuLoading = false;
|
this.isSubMenuLoading = false;
|
||||||
this.initMenu();
|
this.initMenu();
|
||||||
this.cdr.markForCheck();
|
this.cdr.markForCheck();
|
||||||
},
|
})
|
||||||
error: () => {
|
.catch(() => {
|
||||||
|
if (this.book.id !== requestedBookId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.isSubMenuLoading = false;
|
this.isSubMenuLoading = false;
|
||||||
this.cdr.markForCheck();
|
this.cdr.markForCheck();
|
||||||
}
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -689,7 +674,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
openBookInfo(book: Book): void {
|
openBookInfo(book: Book): void {
|
||||||
const allBookIds = this.bookNavigationService.getAvailableBookIds();
|
const allBookIds = this.bookNavigationService.availableBookIds();
|
||||||
if (allBookIds.length > 0) {
|
if (allBookIds.length > 0) {
|
||||||
this.bookNavigationService.setNavigationContext(allBookIds, book.id);
|
this.bookNavigationService.setNavigationContext(allBookIds, book.id);
|
||||||
}
|
}
|
||||||
@@ -941,12 +926,4 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
|||||||
toggleSelection(event: CheckboxChangeEvent): void {
|
toggleSelection(event: CheckboxChangeEvent): void {
|
||||||
this.toggleCardSelection(event.checked);
|
this.toggleCardSelection(event.checked);
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.destroy$.next();
|
|
||||||
this.destroy$.complete();
|
|
||||||
if (this.overlayPrefSub) {
|
|
||||||
this.overlayPrefSub.unsubscribe();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-24
@@ -1,43 +1,36 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable} from '@angular/core';
|
||||||
import {Observable} from 'rxjs';
|
import {ParamMap} from '@angular/router';
|
||||||
import {map, switchMap} from 'rxjs/operators';
|
import {Book} from '../../model/book.model';
|
||||||
import {BookState} from '../../model/state/book-state.model';
|
|
||||||
import {SortOption} from '../../model/sort.model';
|
import {SortOption} from '../../model/sort.model';
|
||||||
import {SortService} from '../../service/sort.service';
|
import {SortService} from '../../service/sort.service';
|
||||||
import {HeaderFilter} from './filters/HeaderFilter';
|
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
|
||||||
import {SideBarFilter} from './filters/sidebar-filter';
|
import {filterBooksByFilters} from './filters/sidebar-filter';
|
||||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||||
import {ParamMap} from '@angular/router';
|
|
||||||
import {QUERY_PARAMS} from './book-browser-query-params.service';
|
import {QUERY_PARAMS} from './book-browser-query-params.service';
|
||||||
|
import {BookFilterMode} from '../../../settings/user-management/user.service';
|
||||||
|
|
||||||
@Injectable({providedIn: 'root'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class BookFilterOrchestrationService {
|
export class BookFilterOrchestrationService {
|
||||||
private sortService = inject(SortService);
|
private sortService = inject(SortService);
|
||||||
|
|
||||||
applyFilters(
|
applyFilters(
|
||||||
bookState: BookState,
|
books: Book[],
|
||||||
headerFilter: HeaderFilter,
|
searchTerm: string,
|
||||||
sideBarFilter: SideBarFilter,
|
activeFilters: Record<string, unknown[]> | null,
|
||||||
|
filterMode: BookFilterMode,
|
||||||
seriesCollapseFilter: SeriesCollapseFilter,
|
seriesCollapseFilter: SeriesCollapseFilter,
|
||||||
|
isSeriesCollapsed: boolean,
|
||||||
forceExpandSeries: boolean,
|
forceExpandSeries: boolean,
|
||||||
sortOption: SortOption
|
sortCriteria: SortOption[]
|
||||||
): Observable<BookState> {
|
): Book[] {
|
||||||
return headerFilter.filter(bookState).pipe(
|
const searchedBooks = filterBooksBySearchTerm(books, searchTerm);
|
||||||
switchMap(filtered => sideBarFilter.filter(filtered)),
|
const filteredBooks = filterBooksByFilters(searchedBooks, activeFilters, filterMode);
|
||||||
switchMap(filtered => seriesCollapseFilter.filter(filtered, forceExpandSeries)),
|
const collapsedBooks = seriesCollapseFilter.collapseBooks(filteredBooks, forceExpandSeries, isSeriesCollapsed);
|
||||||
map(filtered =>
|
return this.sortService.applyMultiSort(collapsedBooks, sortCriteria);
|
||||||
(filtered.loaded && !filtered.error)
|
|
||||||
? ({
|
|
||||||
...filtered,
|
|
||||||
books: this.sortService.applySort(filtered.books || [], sortOption)
|
|
||||||
})
|
|
||||||
: filtered
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
|
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
|
||||||
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
|
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:'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -16,7 +16,7 @@
|
|||||||
<div class="filter-content">
|
<div class="filter-content">
|
||||||
<p-accordion [value]="expandedPanels" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
|
<p-accordion [value]="expandedPanels" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
|
||||||
@for (filterType of visibleFilterTypes; track trackByFilterType(i, filterType); let i = $index) {
|
@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) {
|
@if (filters.length > 0) {
|
||||||
<p-accordion-panel [value]="i">
|
<p-accordion-panel [value]="i">
|
||||||
<p-accordion-header>
|
<p-accordion-header>
|
||||||
|
|||||||
+39
-40
@@ -1,11 +1,11 @@
|
|||||||
import {ChangeDetectionStrategy, Component, EventEmitter, inject, Input, OnDestroy, OnInit, Output} from '@angular/core';
|
import {ChangeDetectionStrategy, Component, effect, EventEmitter, inject, Input, OnDestroy, OnInit, Output, Signal, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, Observable, of, Subject, takeUntil} from 'rxjs';
|
import {Subject, takeUntil} from 'rxjs';
|
||||||
import {Library} from '../../../model/library.model';
|
import {Library} from '../../../model/library.model';
|
||||||
import {Shelf} from '../../../model/shelf.model';
|
import {Shelf} from '../../../model/shelf.model';
|
||||||
import {EntityType} from '../book-browser.component';
|
import {EntityType} from '../book-browser.component';
|
||||||
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
|
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
|
||||||
import {CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
|
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 {Badge} from 'primeng/badge';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {SelectButton} from 'primeng/selectbutton';
|
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 {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
|
||||||
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
|
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
|
||||||
import {BookFilterService} from './book-filter.service';
|
import {BookFilterService} from './book-filter.service';
|
||||||
import {filter} from 'rxjs/operators';
|
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
|
|
||||||
type FilterModeOption = { label: string; value: BookFilterMode };
|
interface FilterModeOption {
|
||||||
|
label: string;
|
||||||
|
value: BookFilterMode;
|
||||||
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-book-filter',
|
selector: 'app-book-filter',
|
||||||
@@ -27,13 +29,17 @@ type FilterModeOption = { label: string; value: BookFilterMode };
|
|||||||
imports: [
|
imports: [
|
||||||
Accordion, AccordionPanel, AccordionHeader, AccordionContent,
|
Accordion, AccordionPanel, AccordionHeader, AccordionContent,
|
||||||
CdkVirtualScrollViewport, CdkFixedSizeVirtualScroll, CdkVirtualForOf,
|
CdkVirtualScrollViewport, CdkFixedSizeVirtualScroll, CdkVirtualForOf,
|
||||||
NgClass, Badge, AsyncPipe, FormsModule, SelectButton,
|
NgClass, Badge, FormsModule, SelectButton,
|
||||||
TranslocoDirective
|
TranslocoDirective
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
export class BookFilterComponent implements OnInit, OnDestroy {
|
export class BookFilterComponent implements OnInit, OnDestroy {
|
||||||
@Input() entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
|
@Input() set entity(value: Library | Shelf | MagicShelf | null | undefined) {
|
||||||
@Input() entityType$: Observable<EntityType> | undefined;
|
this.entitySignal.set(value ?? null);
|
||||||
|
}
|
||||||
|
@Input() set entityType(value: EntityType | undefined) {
|
||||||
|
this.entityTypeSignal.set(value ?? EntityType.ALL_BOOKS);
|
||||||
|
}
|
||||||
@Input() resetFilter$!: Subject<void>;
|
@Input() resetFilter$!: Subject<void>;
|
||||||
@Input() showFilter = false;
|
@Input() showFilter = false;
|
||||||
|
|
||||||
@@ -45,12 +51,19 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
|||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly destroy$ = new Subject<void>();
|
private readonly destroy$ = new Subject<void>();
|
||||||
|
|
||||||
private readonly activeFilters$ = new BehaviorSubject<Record<string, unknown[]> | null>(null);
|
private readonly entitySignal = signal<Library | Shelf | MagicShelf | null>(null);
|
||||||
private readonly filterMode$ = new BehaviorSubject<BookFilterMode>('and');
|
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[]> = {};
|
activeFilters: Record<string, unknown[]> = {};
|
||||||
filterStreams: Record<FilterType, Observable<Filter[]>> = {} as Record<FilterType, Observable<Filter[]>>;
|
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
|
||||||
filterTypes: FilterType[] = [];
|
this.entitySignal,
|
||||||
|
this.entityTypeSignal,
|
||||||
|
this.activeFiltersSignal,
|
||||||
|
this.filterModeSignal
|
||||||
|
);
|
||||||
|
filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
|
||||||
visibleFilterTypes: FilterType[] = [];
|
visibleFilterTypes: FilterType[] = [];
|
||||||
expandedPanels: number[] = [0];
|
expandedPanels: number[] = [0];
|
||||||
truncatedFilters: Record<string, boolean> = {};
|
truncatedFilters: Record<string, boolean> = {};
|
||||||
@@ -78,14 +91,15 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
|||||||
set selectedFilterMode(mode: BookFilterMode) {
|
set selectedFilterMode(mode: BookFilterMode) {
|
||||||
if (mode === this._selectedFilterMode) return;
|
if (mode === this._selectedFilterMode) return;
|
||||||
this._selectedFilterMode = mode;
|
this._selectedFilterMode = mode;
|
||||||
this.filterMode$.next(mode);
|
this.filterModeSignal.set(mode);
|
||||||
this.filterModeChanged.emit(mode);
|
this.filterModeChanged.emit(mode);
|
||||||
this.emitFilters();
|
this.emitFilters();
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.updateVisibleFilterTypes();
|
||||||
|
this.updateExpandedPanels();
|
||||||
this.subscribeToUserSettings();
|
this.subscribeToUserSettings();
|
||||||
this.initializeFilterStreams();
|
|
||||||
this.subscribeToReset();
|
this.subscribeToReset();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,9 +109,11 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleFilterClick(filterType: string, value: unknown): void {
|
handleFilterClick(filterType: string, value: unknown): void {
|
||||||
this._selectedFilterMode === 'single'
|
if (this._selectedFilterMode === 'single') {
|
||||||
? this.handleSingleMode(filterType, value)
|
this.handleSingleMode(filterType, value);
|
||||||
: this.handleMultiMode(filterType, value);
|
} else {
|
||||||
|
this.handleMultiMode(filterType, value);
|
||||||
|
}
|
||||||
this.emitFilters();
|
this.emitFilters();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +129,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
|||||||
clearActiveFilter(): void {
|
clearActiveFilter(): void {
|
||||||
this.activeFilters = {};
|
this.activeFilters = {};
|
||||||
this.expandedPanels = [0];
|
this.expandedPanels = [0];
|
||||||
this.activeFilters$.next(null);
|
this.activeFiltersSignal.set(null);
|
||||||
this.filterSelected.emit(null);
|
this.filterSelected.emit(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,31 +165,14 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private subscribeToUserSettings(): void {
|
private subscribeToUserSettings(): void {
|
||||||
this.userService.userState$.pipe(
|
effect(() => {
|
||||||
filter(state => !!state?.user && state.loaded),
|
const user = this.userService.currentUser();
|
||||||
takeUntil(this.destroy$)
|
if (!user) return;
|
||||||
).subscribe(state => {
|
this._visibleFilters = user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
|
||||||
const settings = state.user!.userSettings;
|
|
||||||
this._visibleFilters = settings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
|
|
||||||
this.updateVisibleFilterTypes();
|
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 {
|
private updateVisibleFilterTypes(): void {
|
||||||
this.visibleFilterTypes = this._visibleFilters.filter(
|
this.visibleFilterTypes = this._visibleFilters.filter(
|
||||||
vf => this.filterTypes.includes(vf as FilterType)
|
vf => this.filterTypes.includes(vf as FilterType)
|
||||||
@@ -223,7 +222,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
|||||||
private emitFilters(): void {
|
private emitFilters(): void {
|
||||||
const hasFilters = Object.keys(this.activeFilters).length > 0;
|
const hasFilters = Object.keys(this.activeFilters).length > 0;
|
||||||
const filtersToEmit = hasFilters ? {...this.activeFilters} : null;
|
const filtersToEmit = hasFilters ? {...this.activeFilters} : null;
|
||||||
this.activeFilters$.next(filtersToEmit);
|
this.activeFiltersSignal.set(filtersToEmit);
|
||||||
this.filterSelected.emit(filtersToEmit);
|
this.filterSelected.emit(filtersToEmit);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+47
-92
@@ -1,5 +1,4 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {computed, inject, Injectable, Signal} from '@angular/core';
|
||||||
import {combineLatest, map, Observable, of, shareReplay} from 'rxjs';
|
|
||||||
import {Book} from '../../../model/book.model';
|
import {Book} from '../../../model/book.model';
|
||||||
import {Library} from '../../../model/library.model';
|
import {Library} from '../../../model/library.model';
|
||||||
import {Shelf} from '../../../model/shelf.model';
|
import {Shelf} from '../../../model/shelf.model';
|
||||||
@@ -21,31 +20,57 @@ export class BookFilterService {
|
|||||||
private readonly libraryService = inject(LibraryService);
|
private readonly libraryService = inject(LibraryService);
|
||||||
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||||
|
|
||||||
createFilterStreams(
|
createFilterSignals(
|
||||||
entity$: Observable<Library | Shelf | MagicShelf | null>,
|
entity: Signal<Library | Shelf | MagicShelf | null>,
|
||||||
entityType$: Observable<EntityType>,
|
entityType: Signal<EntityType>,
|
||||||
activeFilters$: Observable<Record<string, unknown[]> | null> = of(null),
|
activeFilters: Signal<Record<string, unknown[]> | null>,
|
||||||
filterMode$: Observable<BookFilterMode> = of('and')
|
filterMode: Signal<BookFilterMode>
|
||||||
): Record<FilterType, Observable<Filter[]>> {
|
): Record<FilterType, Signal<Filter[]>> {
|
||||||
const filteredBooks$ = this.createFilteredBooksStream(entity$, entityType$);
|
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)) {
|
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
|
||||||
const filterType = type as Exclude<FilterType, 'library'>;
|
const filterType = type as Exclude<FilterType, 'library'>;
|
||||||
streams[filterType] = this.createCascadingFilterStream(
|
signals[filterType] = computed(() => {
|
||||||
filteredBooks$,
|
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
|
||||||
activeFilters$,
|
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
|
||||||
filterMode$,
|
});
|
||||||
filterType,
|
|
||||||
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(
|
filterBooksByEntity(
|
||||||
@@ -59,9 +84,10 @@ export class BookFilterService {
|
|||||||
case EntityType.LIBRARY:
|
case EntityType.LIBRARY:
|
||||||
return books.filter(book => book.libraryId === (entity as Library).id);
|
return books.filter(book => book.libraryId === (entity as Library).id);
|
||||||
|
|
||||||
case EntityType.SHELF:
|
case EntityType.SHELF: {
|
||||||
const shelfId = (entity as Shelf).id;
|
const shelfId = (entity as Shelf).id;
|
||||||
return books.filter(book => book.shelves?.some(s => s.id === shelfId));
|
return books.filter(book => book.shelves?.some(s => s.id === shelfId));
|
||||||
|
}
|
||||||
|
|
||||||
case EntityType.MAGIC_SHELF:
|
case EntityType.MAGIC_SHELF:
|
||||||
return this.filterByMagicShelf(books, entity as MagicShelf);
|
return this.filterByMagicShelf(books, entity as MagicShelf);
|
||||||
@@ -82,77 +108,6 @@ export class BookFilterService {
|
|||||||
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
|
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(
|
private buildAndSortFilters(
|
||||||
books: Book[],
|
books: Book[],
|
||||||
extractor: (book: Book) => FilterValue[],
|
extractor: (book: Book) => FilterValue[],
|
||||||
|
|||||||
+32
-42
@@ -1,5 +1,4 @@
|
|||||||
import {Injectable} from '@angular/core';
|
import {computed, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, Observable} from 'rxjs';
|
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
|
|
||||||
export interface CheckboxClickEvent {
|
export interface CheckboxClickEvent {
|
||||||
@@ -11,46 +10,39 @@ export interface CheckboxClickEvent {
|
|||||||
|
|
||||||
@Injectable({providedIn: 'root'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class BookSelectionService {
|
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 currentBooks: Book[] = [];
|
||||||
private lastSelectedIndex: number | null = null;
|
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 {
|
setCurrentBooks(books: Book[]): void {
|
||||||
this.currentBooks = books;
|
this.currentBooks = books;
|
||||||
}
|
}
|
||||||
|
|
||||||
getCurrentBooks(): Book[] {
|
|
||||||
return this.currentBooks;
|
|
||||||
}
|
|
||||||
|
|
||||||
selectBook(book: Book): void {
|
selectBook(book: Book): void {
|
||||||
const current = new Set(this.selectedBooksSubject.value);
|
this._selectedBooks.update(current => {
|
||||||
if (book.seriesBooks) {
|
const next = new Set(current);
|
||||||
book.seriesBooks.forEach(b => current.add(b.id));
|
if (book.seriesBooks) {
|
||||||
} else {
|
book.seriesBooks.forEach(seriesBook => next.add(seriesBook.id));
|
||||||
current.add(book.id);
|
} else {
|
||||||
}
|
next.add(book.id);
|
||||||
this.selectedBooksSubject.next(current);
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
deselectBook(book: Book): void {
|
deselectBook(book: Book): void {
|
||||||
const current = new Set(this.selectedBooksSubject.value);
|
this._selectedBooks.update(current => {
|
||||||
if (book.seriesBooks) {
|
const next = new Set(current);
|
||||||
book.seriesBooks.forEach(b => current.delete(b.id));
|
if (book.seriesBooks) {
|
||||||
} else {
|
book.seriesBooks.forEach(seriesBook => next.delete(seriesBook.id));
|
||||||
current.delete(book.id);
|
} else {
|
||||||
}
|
next.delete(book.id);
|
||||||
this.selectedBooksSubject.next(current);
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
handleCheckboxClick(event: CheckboxClickEvent): void {
|
handleCheckboxClick(event: CheckboxClickEvent): void {
|
||||||
@@ -83,23 +75,21 @@ export class BookSelectionService {
|
|||||||
selectAll(): void {
|
selectAll(): void {
|
||||||
if (!this.currentBooks || this.currentBooks.length === 0) return;
|
if (!this.currentBooks || this.currentBooks.length === 0) return;
|
||||||
|
|
||||||
const current = new Set(this.selectedBooksSubject.value);
|
this._selectedBooks.update(current => {
|
||||||
for (const book of this.currentBooks) {
|
const next = new Set(current);
|
||||||
current.add(book.id);
|
for (const book of this.currentBooks) {
|
||||||
}
|
next.add(book.id);
|
||||||
this.selectedBooksSubject.next(current);
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
deselectAll(): void {
|
deselectAll(): void {
|
||||||
this.selectedBooksSubject.next(new Set());
|
this._selectedBooks.set(new Set());
|
||||||
this.lastSelectedIndex = null;
|
this.lastSelectedIndex = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
setSelectedBooks(bookIds: Set<number>): void {
|
setSelectedBooks(bookIds: Set<number>): void {
|
||||||
this.selectedBooksSubject.next(new Set(bookIds));
|
this._selectedBooks.set(new Set(bookIds));
|
||||||
}
|
|
||||||
|
|
||||||
hasSelection(): boolean {
|
|
||||||
return this.selectedBooksSubject.value.size > 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-12
@@ -12,9 +12,8 @@ import {BookService} from '../../../service/book.service';
|
|||||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {RouterLink} from '@angular/router';
|
import {RouterLink} from '@angular/router';
|
||||||
import {filter, Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {UserService} from '../../../../settings/user-management/user.service';
|
import {UserService} from '../../../../settings/user-management/user.service';
|
||||||
import {take, takeUntil} from 'rxjs/operators';
|
|
||||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
|
|
||||||
@@ -85,18 +84,13 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
scrollHeight = 'calc(100dvh - 160px)';
|
scrollHeight = 'calc(100dvh - 160px)';
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.userService.userState$
|
const user = this.userService.currentUser();
|
||||||
.pipe(
|
if (user) {
|
||||||
filter(userState => !!userState?.user && userState.loaded),
|
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
|
||||||
take(1),
|
}
|
||||||
takeUntil(this.destroy$)
|
|
||||||
)
|
|
||||||
.subscribe(userState => {
|
|
||||||
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
|
|
||||||
});
|
|
||||||
|
|
||||||
this.selectedBookIds = this.preselectedBookIds;
|
this.selectedBookIds = this.preselectedBookIds;
|
||||||
this.selectedBooks = this.bookService.getBooksByIdsFromState([...this.selectedBookIds]);
|
this.selectedBooks = this.bookService.getBooksByIds([...this.selectedBookIds]);
|
||||||
this.setScrollHeight();
|
this.setScrollHeight();
|
||||||
window.addEventListener('resize', this.setScrollHeight.bind(this));
|
window.addEventListener('resize', this.setScrollHeight.bind(this));
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-31
@@ -1,6 +1,4 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {computed, inject, Injectable, signal} from '@angular/core';
|
||||||
import {Subject} from 'rxjs';
|
|
||||||
import {debounceTime} from 'rxjs/operators';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||||
@@ -21,49 +19,53 @@ export class CoverScalePreferenceService {
|
|||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly localStorageService = inject(LocalStorageService);
|
private readonly localStorageService = inject(LocalStorageService);
|
||||||
|
|
||||||
private readonly scaleChangeSubject = new Subject<number>();
|
private readonly _scaleFactor = signal(1.0);
|
||||||
readonly scaleChange$ = this.scaleChangeSubject.asObservable();
|
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() {
|
constructor() {
|
||||||
this.loadScaleFromStorage();
|
const initialScale = this.loadScaleFromStorage();
|
||||||
|
this._scaleFactor.set(initialScale);
|
||||||
this.scaleChange$
|
this.lastPersistedScale = initialScale;
|
||||||
.pipe(debounceTime(this.DEBOUNCE_MS))
|
|
||||||
.subscribe(scale => this.saveScalePreference(scale));
|
|
||||||
}
|
|
||||||
|
|
||||||
initScaleValue(scale: number | undefined): void {
|
|
||||||
this.scaleFactor = scale ?? 1.0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setScale(scale: number): void {
|
setScale(scale: number): void {
|
||||||
this.scaleFactor = scale;
|
this._scaleFactor.set(scale);
|
||||||
this.scaleChangeSubject.next(scale);
|
if (scale === this.lastPersistedScale) {
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
get currentCardSize(): { width: number; height: number } {
|
this.scheduleSave(scale);
|
||||||
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`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getCardHeight(_book: Book): number {
|
getCardHeight(_book: Book): number {
|
||||||
// Use uniform height for all book types to ensure smooth virtual scrolling.
|
// Use uniform height for all book types to ensure smooth virtual scrolling.
|
||||||
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
|
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
|
||||||
// cannot accurately estimate positions when item heights vary.
|
// 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 {
|
private saveScalePreference(scale: number): void {
|
||||||
try {
|
try {
|
||||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
this.localStorageService.set(this.STORAGE_KEY, scale);
|
||||||
|
this.lastPersistedScale = scale;
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('book.coverPref.toast.savedSummary'),
|
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);
|
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
||||||
if (saved !== null && !isNaN(saved)) {
|
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 {Book} from '../../../model/book.model';
|
||||||
import {BookState} from '../../../model/state/book-state.model';
|
|
||||||
import {Observable, of} from 'rxjs';
|
|
||||||
import {map, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
|
|
||||||
|
|
||||||
export class HeaderFilter implements BookFilter {
|
export function normalizeSearchTerm(str: string): string {
|
||||||
|
if (!str) return '';
|
||||||
constructor(private searchTerm$: Observable<string>) {
|
// Normalize Unicode combining characters (e.g., é -> e)
|
||||||
}
|
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
||||||
|
s = s.replace(/ø/gi, 'o')
|
||||||
filter(bookState: BookState): Observable<BookState> {
|
.replace(/ł/gi, 'l')
|
||||||
const normalize = (str: string): string => {
|
.replace(/æ/gi, 'ae')
|
||||||
if (!str) return '';
|
.replace(/œ/gi, 'oe')
|
||||||
// Normalize Unicode combining characters (e.g., é -> e)
|
.replace(/ß/g, 'ss');
|
||||||
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
s = s.replace(/[!@$%^&*_=|~`<>?/";']/g, '');
|
||||||
s = s.replace(/ø/gi, 'o')
|
s = s.replace(/\s+/g, ' ').trim();
|
||||||
.replace(/ł/gi, 'l')
|
return s.toLowerCase();
|
||||||
.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 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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
+61
-80
@@ -1,41 +1,27 @@
|
|||||||
import {BookFilter} from './BookFilter';
|
import {effect, inject, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, Observable, Subject} from 'rxjs';
|
|
||||||
import {BookState} from '../../../model/state/book-state.model';
|
|
||||||
import {debounceTime, filter, map, takeUntil} from 'rxjs/operators';
|
|
||||||
import {Book} from '../../../model/book.model';
|
import {Book} from '../../../model/book.model';
|
||||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {UserService} from '../../../../settings/user-management/user.service';
|
import {UserService} from '../../../../settings/user-management/user.service';
|
||||||
|
|
||||||
@Injectable({providedIn: 'root'})
|
@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 userService = inject(UserService);
|
||||||
private readonly messageService = inject(MessageService);
|
private readonly messageService = inject(MessageService);
|
||||||
|
|
||||||
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
|
private readonly _seriesCollapsed = signal(false);
|
||||||
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
|
readonly seriesCollapsed = this._seriesCollapsed.asReadonly();
|
||||||
private destroy$ = new Subject<void>();
|
|
||||||
|
|
||||||
private hasUserToggled = false;
|
|
||||||
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
|
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
|
||||||
|
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.userService.userState$
|
effect(() => {
|
||||||
.pipe(
|
const user = this.userService.currentUser();
|
||||||
filter(userState => !!userState?.user && userState.loaded),
|
if (user) {
|
||||||
takeUntil(this.destroy$)
|
|
||||||
)
|
|
||||||
.subscribe(() => {
|
|
||||||
this.applyPreference();
|
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 {
|
setContext(type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF' | null, id: number | null): void {
|
||||||
@@ -47,13 +33,9 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy {
|
|||||||
this.applyPreference();
|
this.applyPreference();
|
||||||
}
|
}
|
||||||
|
|
||||||
get isSeriesCollapsed(): boolean {
|
|
||||||
return this.seriesCollapseSubject.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
setCollapsed(value: boolean): void {
|
setCollapsed(value: boolean): void {
|
||||||
this.hasUserToggled = true;
|
this._seriesCollapsed.set(value);
|
||||||
this.seriesCollapseSubject.next(value);
|
this.schedulePersist(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
private applyPreference(): void {
|
private applyPreference(): void {
|
||||||
@@ -64,70 +46,74 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy {
|
|||||||
|
|
||||||
if (prefs) {
|
if (prefs) {
|
||||||
// Backward compatibility: check for old 'seriesCollapse' field
|
// Backward compatibility: check for old 'seriesCollapse' field
|
||||||
const globalAny = prefs.global as any;
|
const legacyGlobalSeriesCollapse = (prefs.global as { seriesCollapse?: boolean }).seriesCollapse;
|
||||||
collapsed = prefs.global?.seriesCollapsed ?? globalAny?.seriesCollapse ?? false;
|
collapsed = prefs.global?.seriesCollapsed ?? legacyGlobalSeriesCollapse ?? false;
|
||||||
|
|
||||||
if (this.currentContext) {
|
if (this.currentContext) {
|
||||||
const override = prefs.overrides?.find(o =>
|
const override = prefs.overrides?.find(o =>
|
||||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||||
);
|
);
|
||||||
if (override) {
|
if (override) {
|
||||||
const prefAny = override.preferences as any;
|
const legacyOverrideSeriesCollapse = (override.preferences as { seriesCollapse?: boolean }).seriesCollapse;
|
||||||
if (override.preferences.seriesCollapsed !== undefined) {
|
if (override.preferences.seriesCollapsed !== undefined) {
|
||||||
collapsed = override.preferences.seriesCollapsed;
|
collapsed = override.preferences.seriesCollapsed;
|
||||||
} else if (prefAny?.seriesCollapse !== undefined) {
|
} else if (legacyOverrideSeriesCollapse !== undefined) {
|
||||||
collapsed = prefAny.seriesCollapse;
|
collapsed = legacyOverrideSeriesCollapse;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.hasUserToggled = false;
|
if (this._seriesCollapsed() !== collapsed) {
|
||||||
if (this.seriesCollapseSubject.value !== collapsed) {
|
this._seriesCollapsed.set(collapsed);
|
||||||
this.seriesCollapseSubject.next(collapsed);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
filter(bookState: BookState, forceExpandSeries?: boolean): Observable<BookState> {
|
collapseBooks(books: Book[], forceExpandSeries?: boolean, isSeriesCollapsed: boolean = this.seriesCollapsed()): Book[] {
|
||||||
return this.seriesCollapse$.pipe(
|
const shouldCollapse = forceExpandSeries ? false : isSeriesCollapsed;
|
||||||
map(isCollapsed => {
|
if (!shouldCollapse || books.length === 0) return books;
|
||||||
const shouldCollapse = forceExpandSeries ? false : isCollapsed;
|
|
||||||
if (!shouldCollapse || !bookState.books) return bookState;
|
|
||||||
|
|
||||||
const books = [...bookState.books];
|
const sourceBooks = [...books];
|
||||||
|
const seriesMap = new Map<string, Book[]>();
|
||||||
|
const collapsedBooks: Book[] = [];
|
||||||
|
|
||||||
const seriesMap = new Map<string, Book[]>();
|
for (const book of sourceBooks) {
|
||||||
const collapsedBooks: Book[] = [];
|
const seriesName = book.metadata?.seriesName?.trim();
|
||||||
|
if (seriesName) {
|
||||||
for (const book of books) {
|
if (!seriesMap.has(seriesName)) {
|
||||||
const seriesName = book.metadata?.seriesName?.trim();
|
seriesMap.set(seriesName, []);
|
||||||
if (seriesName) {
|
|
||||||
if (!seriesMap.has(seriesName)) {
|
|
||||||
seriesMap.set(seriesName, []);
|
|
||||||
}
|
|
||||||
seriesMap.get(seriesName)!.push(book);
|
|
||||||
} else {
|
|
||||||
collapsedBooks.push(book);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
seriesMap.get(seriesName)!.push(book);
|
||||||
|
} else {
|
||||||
|
collapsedBooks.push(book);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (const [seriesName, group] of seriesMap.entries()) {
|
for (const group of seriesMap.values()) {
|
||||||
const sortedGroup = group.slice().sort((a, b) => {
|
const sortedGroup = group.slice().sort((a, b) => {
|
||||||
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||||
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||||
return aNum - bNum;
|
return aNum - bNum;
|
||||||
});
|
});
|
||||||
const firstBook = sortedGroup[0];
|
const firstBook = sortedGroup[0];
|
||||||
collapsedBooks.push({
|
collapsedBooks.push({
|
||||||
...firstBook,
|
...firstBook,
|
||||||
seriesBooks: group,
|
seriesBooks: group,
|
||||||
seriesCount: group.length
|
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 {
|
private persistCollapsePreference(isCollapsed: boolean): void {
|
||||||
@@ -180,9 +166,4 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy {
|
|||||||
life: 1500
|
life: 1500
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.destroy$.next();
|
|
||||||
this.destroy$.complete();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-17
@@ -1,5 +1,4 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject} from 'rxjs';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
||||||
@@ -14,31 +13,26 @@ export class SidebarFilterTogglePrefService {
|
|||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly localStorageService = inject(LocalStorageService);
|
private readonly localStorageService = inject(LocalStorageService);
|
||||||
|
|
||||||
private readonly showFilterSubject = new BehaviorSubject<boolean>(true);
|
private readonly _showFilter = signal(true);
|
||||||
readonly showFilter$ = this.showFilterSubject.asObservable();
|
readonly showFilter = this._showFilter.asReadonly();
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
const isNarrow = window.innerWidth <= 768;
|
const isNarrow = window.innerWidth <= 768;
|
||||||
this.showFilterSubject = new BehaviorSubject<boolean>(!isNarrow);
|
this._showFilter.set(!isNarrow);
|
||||||
this.showFilter$ = this.showFilterSubject.asObservable();
|
|
||||||
this.loadFromStorage();
|
this.loadFromStorage();
|
||||||
}
|
}
|
||||||
|
|
||||||
get selectedShowFilter(): boolean {
|
toggle(): void {
|
||||||
return this.showFilterSubject.value;
|
this.setShowFilter(!this.showFilter());
|
||||||
}
|
}
|
||||||
|
|
||||||
set selectedShowFilter(value: boolean) {
|
setShowFilter(value: boolean): void {
|
||||||
if (this.showFilterSubject.value !== value) {
|
if (this._showFilter() !== value) {
|
||||||
this.showFilterSubject.next(value);
|
this._showFilter.set(value);
|
||||||
this.savePreference(value);
|
this.savePreference(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
toggle(): void {
|
|
||||||
this.selectedShowFilter = !this.selectedShowFilter;
|
|
||||||
}
|
|
||||||
|
|
||||||
private savePreference(value: boolean): void {
|
private savePreference(value: boolean): void {
|
||||||
try {
|
try {
|
||||||
this.localStorageService.set(this.STORAGE_KEY, value);
|
this.localStorageService.set(this.STORAGE_KEY, value);
|
||||||
@@ -55,10 +49,10 @@ export class SidebarFilterTogglePrefService {
|
|||||||
private loadFromStorage(): void {
|
private loadFromStorage(): void {
|
||||||
const isNarrow = window.innerWidth <= 768;
|
const isNarrow = window.innerWidth <= 768;
|
||||||
if (isNarrow) {
|
if (isNarrow) {
|
||||||
this.showFilterSubject.next(false);
|
this._showFilter.set(false);
|
||||||
} else {
|
} else {
|
||||||
const saved = this.localStorageService.get<boolean>(this.STORAGE_KEY);
|
const saved = this.localStorageService.get<boolean>(this.STORAGE_KEY);
|
||||||
this.showFilterSubject.next(saved !== null ? saved : true);
|
this._showFilter.set(saved !== null ? saved : true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-27
@@ -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 {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
|
||||||
import {Book, ReadStatus} from '../../../model/book.model';
|
import {Book, ReadStatus} from '../../../model/book.model';
|
||||||
import {BookFilterMode} from '../../../../settings/user-management/user.service';
|
import {BookFilterMode} from '../../../../settings/user-management/user.service';
|
||||||
@@ -95,18 +91,20 @@ export function doesBookMatchFilter(
|
|||||||
return effectiveMode === 'or'
|
return effectiveMode === 'or'
|
||||||
? filterValues.some(val => book.shelves?.some(s => s.id == val))
|
? filterValues.some(val => book.shelves?.some(s => s.id == val))
|
||||||
: filterValues.every(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';
|
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
|
||||||
return filterValues.includes(shelved);
|
return filterValues.includes(shelved);
|
||||||
|
}
|
||||||
case 'tag':
|
case 'tag':
|
||||||
return effectiveMode === 'or'
|
return effectiveMode === 'or'
|
||||||
? filterValues.some(val => book.metadata?.tags?.includes(val as string))
|
? filterValues.some(val => book.metadata?.tags?.includes(val as string))
|
||||||
: filterValues.every(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
|
const bookYear = book.metadata?.publishedDate
|
||||||
? new Date(book.metadata.publishedDate).getFullYear()
|
? new Date(book.metadata.publishedDate).getFullYear()
|
||||||
: null;
|
: null;
|
||||||
return bookYear ? filterValues.some(val => val == bookYear || val == bookYear.toString()) : false;
|
return bookYear ? filterValues.some(val => val == bookYear || val == bookYear.toString()) : false;
|
||||||
|
}
|
||||||
case 'fileSize':
|
case 'fileSize':
|
||||||
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range as string | number));
|
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range as string | number));
|
||||||
case 'amazonRating':
|
case 'amazonRating':
|
||||||
@@ -118,7 +116,7 @@ export function doesBookMatchFilter(
|
|||||||
case 'language':
|
case 'language':
|
||||||
return filterValues.includes(book.metadata?.language);
|
return filterValues.includes(book.metadata?.language);
|
||||||
case 'pageCount':
|
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':
|
case 'mood':
|
||||||
return effectiveMode === 'or'
|
return effectiveMode === 'or'
|
||||||
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
|
? 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};
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+6
-11
@@ -1,5 +1,4 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject} from 'rxjs';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||||
@@ -12,8 +11,8 @@ export class TableColumnPreferenceService {
|
|||||||
private readonly messageService = inject(MessageService);
|
private readonly messageService = inject(MessageService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
private readonly preferencesSubject = new BehaviorSubject<TableColumnPreference[]>([]);
|
private readonly _preferences = signal<TableColumnPreference[]>([]);
|
||||||
readonly preferences$ = this.preferencesSubject.asObservable();
|
readonly preferences = this._preferences.asReadonly();
|
||||||
|
|
||||||
private readonly allAvailableFields = [
|
private readonly allAvailableFields = [
|
||||||
'readStatus', 'title', 'authors', 'publisher', 'seriesName', 'seriesNumber',
|
'readStatus', 'title', 'authors', 'publisher', 'seriesName', 'seriesNumber',
|
||||||
@@ -31,7 +30,7 @@ export class TableColumnPreferenceService {
|
|||||||
|
|
||||||
initPreferences(savedPrefs: TableColumnPreference[] | undefined): void {
|
initPreferences(savedPrefs: TableColumnPreference[] | undefined): void {
|
||||||
const effectivePrefs = savedPrefs?.length ? savedPrefs : this.fallbackPreferences;
|
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 }[] {
|
get allColumns(): { field: string; header: string }[] {
|
||||||
@@ -42,7 +41,7 @@ export class TableColumnPreferenceService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get visibleColumns(): { field: string; header: string }[] {
|
get visibleColumns(): { field: string; header: string }[] {
|
||||||
return this.preferencesSubject.value
|
return this.preferences()
|
||||||
.filter(pref => pref.visible)
|
.filter(pref => pref.visible)
|
||||||
.sort((a, b) => a.order - b.order)
|
.sort((a, b) => a.order - b.order)
|
||||||
.map(pref => ({
|
.map(pref => ({
|
||||||
@@ -51,10 +50,6 @@ export class TableColumnPreferenceService {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
get preferences(): TableColumnPreference[] {
|
|
||||||
return this.preferencesSubject.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
saveVisibleColumns(selectedColumns: { field: string }[]): void {
|
saveVisibleColumns(selectedColumns: { field: string }[]): void {
|
||||||
const selectedFieldSet = new Set(selectedColumns.map(c => c.field));
|
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();
|
const currentUser = this.userService.getCurrentUser();
|
||||||
if (!currentUser) return;
|
if (!currentUser) return;
|
||||||
|
|||||||
+6
-24
@@ -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 {Book} from '../../model/book.model';
|
||||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {filter, Subject} from 'rxjs';
|
|
||||||
import {NgClass} from '@angular/common';
|
import {NgClass} from '@angular/common';
|
||||||
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
|
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
|
||||||
import {takeUntil} from 'rxjs/operators';
|
|
||||||
import {TooltipModule} from 'primeng/tooltip';
|
import {TooltipModule} from 'primeng/tooltip';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -20,7 +18,7 @@ import {TooltipModule} from 'primeng/tooltip';
|
|||||||
templateUrl: './book-card-lite-component.html',
|
templateUrl: './book-card-lite-component.html',
|
||||||
styleUrl: './book-card-lite-component.scss'
|
styleUrl: './book-card-lite-component.scss'
|
||||||
})
|
})
|
||||||
export class BookCardLiteComponent implements OnInit, OnDestroy {
|
export class BookCardLiteComponent {
|
||||||
@Input() book!: Book;
|
@Input() book!: Book;
|
||||||
@Input() isActive: boolean = false;
|
@Input() isActive: boolean = false;
|
||||||
@Input() showSeriesNumber: boolean = false;
|
@Input() showSeriesNumber: boolean = false;
|
||||||
@@ -30,9 +28,9 @@ export class BookCardLiteComponent implements OnInit, OnDestroy {
|
|||||||
private userService = inject(UserService);
|
private userService = inject(UserService);
|
||||||
private bookMetadataHostService = inject(BookMetadataHostService);
|
private bookMetadataHostService = inject(BookMetadataHostService);
|
||||||
|
|
||||||
private destroy$ = new Subject<void>();
|
private metadataCenterViewMode = computed(() =>
|
||||||
|
this.userService.currentUser()?.userSettings.metadataCenterViewMode ?? 'route'
|
||||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
);
|
||||||
isHovered: boolean = false;
|
isHovered: boolean = false;
|
||||||
|
|
||||||
isAudiobookOnly(): boolean {
|
isAudiobookOnly(): boolean {
|
||||||
@@ -48,19 +46,8 @@ export class BookCardLiteComponent implements OnInit, OnDestroy {
|
|||||||
return this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
|
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 {
|
openBookInfo(book: Book): void {
|
||||||
if (this.metadataCenterViewMode === 'route') {
|
if (this.metadataCenterViewMode() === 'route') {
|
||||||
this.router.navigate(['/book', book.id], {
|
this.router.navigate(['/book', book.id], {
|
||||||
queryParams: {tab: 'view'}
|
queryParams: {tab: 'view'}
|
||||||
});
|
});
|
||||||
@@ -68,9 +55,4 @@ export class BookCardLiteComponent implements OnInit, OnDestroy {
|
|||||||
this.bookMetadataHostService.requestBookSwitch(book.id);
|
this.bookMetadataHostService.requestBookSwitch(book.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.destroy$.next();
|
|
||||||
this.destroy$.complete();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-21
@@ -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 { FormsModule } from '@angular/forms';
|
||||||
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
|
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
|
||||||
import { AutoComplete, AutoCompleteSelectEvent } from 'primeng/autocomplete';
|
import { AutoComplete, AutoCompleteSelectEvent } from 'primeng/autocomplete';
|
||||||
import { Button } from 'primeng/button';
|
import { Button } from 'primeng/button';
|
||||||
import { Checkbox } from 'primeng/checkbox';
|
import { Checkbox } from 'primeng/checkbox';
|
||||||
import { Subject, takeUntil } from 'rxjs';
|
import { Subject, takeUntil } from 'rxjs';
|
||||||
import { filter, take } from 'rxjs/operators';
|
|
||||||
import { BookService } from '../../service/book.service';
|
import { BookService } from '../../service/book.service';
|
||||||
import { BookFileService } from '../../service/book-file.service';
|
import { BookFileService } from '../../service/book-file.service';
|
||||||
import { Book } from '../../model/book.model';
|
import { Book } from '../../model/book.model';
|
||||||
@@ -37,7 +36,7 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
|||||||
filteredBooks: Book[] = [];
|
filteredBooks: Book[] = [];
|
||||||
|
|
||||||
private destroy$ = new Subject<void>();
|
private destroy$ = new Subject<void>();
|
||||||
private allBooks: Book[] = [];
|
private allBooks: Signal<Book[]> = signal([]);
|
||||||
|
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly appSettingsService = inject(AppSettingsService);
|
private readonly appSettingsService = inject(AppSettingsService);
|
||||||
@@ -63,28 +62,22 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.appSettingsService.appSettings$.pipe(
|
const settings = this.appSettingsService.appSettings();
|
||||||
filter(settings => !!settings),
|
if (settings) {
|
||||||
take(1),
|
this.moveFiles = settings.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
|
||||||
takeUntil(this.destroy$)
|
}
|
||||||
).subscribe(settings => {
|
|
||||||
this.moveFiles = settings!.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get the library ID from first source book (all should be same library)
|
// Get the library ID from first source book (all should be same library)
|
||||||
const libraryId = this.sourceBooks[0].libraryId;
|
const libraryId = this.sourceBooks[0].libraryId;
|
||||||
const sourceBookIds = new Set(this.sourceBooks.map(b => b.id));
|
const sourceBookIds = new Set(this.sourceBooks.map(b => b.id));
|
||||||
|
|
||||||
// Load all books from state and filter for same library, excluding source books
|
this.allBooks = computed(() =>
|
||||||
this.bookService.bookState$.pipe(
|
this.bookService.books().filter(book =>
|
||||||
filter(state => state.loaded && !!state.books),
|
|
||||||
take(1),
|
|
||||||
takeUntil(this.destroy$)
|
|
||||||
).subscribe(state => {
|
|
||||||
this.allBooks = (state.books || []).filter(book =>
|
|
||||||
book.libraryId === libraryId && !sourceBookIds.has(book.id)
|
book.libraryId === libraryId && !sourceBookIds.has(book.id)
|
||||||
);
|
)
|
||||||
});
|
);
|
||||||
|
|
||||||
|
this.filteredBooks = this.allBooks().slice(0, 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
ngOnDestroy(): void {
|
||||||
@@ -98,12 +91,13 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
filterBooks(event: { query: string }): void {
|
filterBooks(event: { query: string }): void {
|
||||||
const query = event.query.toLowerCase().trim();
|
const query = event.query.toLowerCase().trim();
|
||||||
|
const books = this.allBooks();
|
||||||
if (!query) {
|
if (!query) {
|
||||||
this.filteredBooks = this.allBooks.slice(0, 20);
|
this.filteredBooks = books.slice(0, 20);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.filteredBooks = this.allBooks
|
this.filteredBooks = books
|
||||||
.filter(book => {
|
.filter(book => {
|
||||||
const title = book.metadata?.title?.toLowerCase() || '';
|
const title = book.metadata?.title?.toLowerCase() || '';
|
||||||
const authors = book.metadata?.authors?.join(' ').toLowerCase() || '';
|
const authors = book.metadata?.authors?.join(' ').toLowerCase() || '';
|
||||||
|
|||||||
+21
-24
@@ -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 {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {BookReview, BookReviewService} from './book-review-service';
|
import {BookReview, BookReviewService} from './book-review-service';
|
||||||
@@ -36,6 +36,7 @@ export class BookReviewsComponent implements OnInit, OnChanges {
|
|||||||
private appSettingsService = inject(AppSettingsService);
|
private appSettingsService = inject(AppSettingsService);
|
||||||
private destroyRef = inject(DestroyRef);
|
private destroyRef = inject(DestroyRef);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
private bookIdState = signal<number | null>(null);
|
||||||
|
|
||||||
loading = false;
|
loading = false;
|
||||||
hasPermission = false;
|
hasPermission = false;
|
||||||
@@ -45,29 +46,31 @@ export class BookReviewsComponent implements OnInit, OnChanges {
|
|||||||
allSpoilersRevealed = false;
|
allSpoilersRevealed = false;
|
||||||
reviewDownloadEnabled = true;
|
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 {
|
ngOnInit(): void {
|
||||||
this.checkUserPermissions();
|
this.checkUserPermissions();
|
||||||
this.subscribeToBookState();
|
|
||||||
this.subscribeToAppSettings();
|
this.subscribeToAppSettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges): void {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
if (changes['bookId'] && changes['bookId'].currentValue) {
|
if (changes['bookId'] && changes['bookId'].currentValue) {
|
||||||
|
this.bookIdState.set(changes['bookId'].currentValue);
|
||||||
this.loadReviews();
|
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 {
|
private loadReviews(): void {
|
||||||
if (this.loading || !this.bookId) {
|
if (this.loading || !this.bookId) {
|
||||||
return;
|
return;
|
||||||
@@ -244,12 +247,9 @@ export class BookReviewsComponent implements OnInit, OnChanges {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private checkUserPermissions(): void {
|
private checkUserPermissions(): void {
|
||||||
this.userService.userState$
|
const user = this.userService.currentUser();
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
this.hasPermission = user?.permissions?.admin ||
|
||||||
.subscribe(userState => {
|
user?.permissions?.canEditMetadata || false;
|
||||||
this.hasPermission = userState?.user?.permissions?.admin ||
|
|
||||||
userState?.user?.permissions?.canEditMetadata || false;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteReview(review: BookReview): void {
|
deleteReview(review: BookReview): void {
|
||||||
@@ -315,11 +315,8 @@ export class BookReviewsComponent implements OnInit, OnChanges {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private subscribeToAppSettings(): void {
|
private subscribeToAppSettings(): void {
|
||||||
this.appSettingsService.appSettings$
|
const settings = this.appSettingsService.appSettings();
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
this.reviewDownloadEnabled = settings?.metadataPublicReviewsSettings?.downloadEnabled ?? true;
|
||||||
.subscribe(settings => {
|
|
||||||
this.reviewDownloadEnabled = settings?.metadataPublicReviewsSettings?.downloadEnabled ?? true;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getProviderSeverity(provider: string): 'success' | 'warn' {
|
getProviderSeverity(provider: string): 'success' | 'warn' {
|
||||||
|
|||||||
+34
-41
@@ -1,6 +1,6 @@
|
|||||||
import {Component, ElementRef, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
|
import {Component, ElementRef, HostListener, computed, inject, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, of, Subscription} from 'rxjs';
|
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||||
import {catchError, debounceTime, distinctUntilChanged, switchMap, tap} from 'rxjs/operators';
|
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {InputTextModule} from 'primeng/inputtext';
|
import {InputTextModule} from 'primeng/inputtext';
|
||||||
@@ -12,7 +12,7 @@ import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
|||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {IconField} from 'primeng/iconfield';
|
import {IconField} from 'primeng/iconfield';
|
||||||
import {InputIcon} from 'primeng/inputicon';
|
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';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -31,43 +31,41 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
|||||||
styleUrls: ['./book-searcher.component.scss'],
|
styleUrls: ['./book-searcher.component.scss'],
|
||||||
standalone: true
|
standalone: true
|
||||||
})
|
})
|
||||||
export class BookSearcherComponent implements OnInit, OnDestroy {
|
export class BookSearcherComponent {
|
||||||
searchQuery: string = '';
|
searchQuery = '';
|
||||||
books: Book[] = [];
|
|
||||||
isLoading = false;
|
|
||||||
activeIndex = -1;
|
activeIndex = -1;
|
||||||
#searchSubject = new BehaviorSubject<string>('');
|
|
||||||
#subscription!: Subscription;
|
|
||||||
isSearchFocused = false;
|
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 bookService = inject(BookService);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
protected urlHelper = inject(UrlHelperService);
|
protected urlHelper = inject(UrlHelperService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private elRef = inject(ElementRef);
|
private elRef = inject(ElementRef);
|
||||||
private headerFilter = new HeaderFilter(
|
|
||||||
this.#searchSubject.pipe(debounceTime(200), distinctUntilChanged())
|
|
||||||
);
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
get books(): Book[] {
|
||||||
this.#subscription = this.bookService.bookState$.pipe(
|
return this.filteredBooks();
|
||||||
tap(() => {
|
}
|
||||||
if (this.searchQuery.trim().length >= 2) {
|
|
||||||
this.isLoading = true;
|
get isLoading(): boolean {
|
||||||
}
|
const rawTerm = this.searchTerm().trim();
|
||||||
}),
|
return rawTerm.length >= 2 && rawTerm !== this.debouncedSearchTerm().trim();
|
||||||
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)
|
|
||||||
: [];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getAuthorNames(authors: string[] | undefined): string {
|
getAuthorNames(authors: string[] | undefined): string {
|
||||||
@@ -89,7 +87,8 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onSearchInputChange(): void {
|
onSearchInputChange(): void {
|
||||||
this.#searchSubject.next(this.searchQuery.trim());
|
this.searchTerm.set(this.searchQuery.trim());
|
||||||
|
this.activeIndex = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
onBookClick(book: Book): void {
|
onBookClick(book: Book): void {
|
||||||
@@ -101,8 +100,8 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
clearSearch(): void {
|
clearSearch(): void {
|
||||||
this.searchQuery = '';
|
this.searchQuery = '';
|
||||||
this.books = [];
|
this.searchTerm.set('');
|
||||||
this.isLoading = false;
|
this.activeIndex = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
get isDropdownOpen(): boolean {
|
get isDropdownOpen(): boolean {
|
||||||
@@ -140,10 +139,4 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
if (this.#subscription) {
|
|
||||||
this.#subscription.unsubscribe();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-24
@@ -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 {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
@@ -11,8 +11,7 @@ import {BookService} from '../../service/book.service';
|
|||||||
import {BookMetadataService} from '../../service/book-metadata.service';
|
import {BookMetadataService} from '../../service/book-metadata.service';
|
||||||
import {LibraryService} from '../../service/library.service';
|
import {LibraryService} from '../../service/library.service';
|
||||||
import {Library} from '../../model/library.model';
|
import {Library} from '../../model/library.model';
|
||||||
import {Book, CreatePhysicalBookRequest} from '../../model/book.model';
|
import {BookMetadata, CreatePhysicalBookRequest} from '../../model/book.model';
|
||||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
|
||||||
import {TranslocoDirective} from '@jsverse/transloco';
|
import {TranslocoDirective} from '@jsverse/transloco';
|
||||||
import {Tabs, TabList, Tab, TabPanels, TabPanel} from 'primeng/tabs';
|
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',
|
styleUrl: './bulk-isbn-import-dialog.component.scss',
|
||||||
})
|
})
|
||||||
export class BulkIsbnImportDialogComponent implements OnInit {
|
export class BulkIsbnImportDialogComponent {
|
||||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||||
private dialogConfig = inject(DynamicDialogConfig);
|
private dialogConfig = inject(DynamicDialogConfig);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private bookMetadataService = inject(BookMetadataService);
|
private bookMetadataService = inject(BookMetadataService);
|
||||||
private libraryService = inject(LibraryService);
|
private libraryService = inject(LibraryService);
|
||||||
private destroyRef = inject(DestroyRef);
|
|
||||||
|
|
||||||
libraries: Library[] = [];
|
|
||||||
selectedLibraryId: number | null = null;
|
selectedLibraryId: number | null = null;
|
||||||
|
|
||||||
phase: ImportPhase = 'upload';
|
phase: ImportPhase = 'upload';
|
||||||
@@ -84,20 +81,24 @@ export class BulkIsbnImportDialogComponent implements OnInit {
|
|||||||
|
|
||||||
parseError = '';
|
parseError = '';
|
||||||
readonly maxIsbnCount = MAX_ISBN_COUNT;
|
readonly maxIsbnCount = MAX_ISBN_COUNT;
|
||||||
|
private readonly initializeSelectedLibraryEffect = effect(() => {
|
||||||
|
const libraries = this.libraries;
|
||||||
|
if (libraries.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
if (this.dialogConfig.data?.libraryId) {
|
||||||
this.libraryService.libraryState$
|
this.selectedLibraryId = this.dialogConfig.data.libraryId;
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
return;
|
||||||
.subscribe(state => {
|
}
|
||||||
if (state.loaded && state.libraries) {
|
|
||||||
this.libraries = state.libraries;
|
if (this.selectedLibraryId == null && libraries[0].id !== undefined) {
|
||||||
if (this.dialogConfig.data?.libraryId) {
|
this.selectedLibraryId = libraries[0].id;
|
||||||
this.selectedLibraryId = this.dialogConfig.data.libraryId;
|
}
|
||||||
} else if (this.libraries.length > 0 && this.libraries[0].id !== undefined) {
|
});
|
||||||
this.selectedLibraryId = this.libraries[0].id;
|
|
||||||
}
|
get libraries(): Library[] {
|
||||||
}
|
return this.libraryService.libraries();
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onFileSelect(event: FileSelectEvent): void {
|
onFileSelect(event: FileSelectEvent): void {
|
||||||
@@ -177,9 +178,9 @@ export class BulkIsbnImportDialogComponent implements OnInit {
|
|||||||
entry.status = 'created-no-metadata';
|
entry.status = 'created-no-metadata';
|
||||||
this.noMetadataCount++;
|
this.noMetadataCount++;
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
entry.status = 'failed';
|
entry.status = 'failed';
|
||||||
entry.error = err?.message || 'Unknown error';
|
entry.error = err instanceof Error ? err.message : 'Unknown error';
|
||||||
this.failedCount++;
|
this.failedCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,7 +311,7 @@ export class BulkIsbnImportDialogComponent implements OnInit {
|
|||||||
const isbns = new Set<string>();
|
const isbns = new Set<string>();
|
||||||
if (!this.selectedLibraryId) return isbns;
|
if (!this.selectedLibraryId) return isbns;
|
||||||
|
|
||||||
const books: Book[] = this.bookService.getCurrentBookState().books ?? [];
|
const books = this.bookService.books();
|
||||||
for (const book of books) {
|
for (const book of books) {
|
||||||
if (book.libraryId !== this.selectedLibraryId) continue;
|
if (book.libraryId !== this.selectedLibraryId) continue;
|
||||||
const isbn13 = book.metadata?.isbn13;
|
const isbn13 = book.metadata?.isbn13;
|
||||||
@@ -332,8 +333,8 @@ export class BulkIsbnImportDialogComponent implements OnInit {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private lookupIsbn(isbn: string): Promise<any> {
|
private lookupIsbn(isbn: string): Promise<BookMetadata | null> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve) => {
|
||||||
this.bookMetadataService.lookupByIsbn(isbn).subscribe({
|
this.bookMetadataService.lookupByIsbn(isbn).subscribe({
|
||||||
next: metadata => resolve(metadata),
|
next: metadata => resolve(metadata),
|
||||||
error: err => {
|
error: err => {
|
||||||
|
|||||||
+5
-8
@@ -8,7 +8,7 @@ import {SelectButton} from 'primeng/selectbutton';
|
|||||||
import {ProgressBar} from 'primeng/progressbar';
|
import {ProgressBar} from 'primeng/progressbar';
|
||||||
import {Tag} from 'primeng/tag';
|
import {Tag} from 'primeng/tag';
|
||||||
import {Paginator} from 'primeng/paginator';
|
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 {BookFileService} from '../../service/book-file.service';
|
||||||
import {BookService} from '../../service/book.service';
|
import {BookService} from '../../service/book.service';
|
||||||
import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model';
|
import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model';
|
||||||
@@ -81,13 +81,10 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
|||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.libraryId = this.config.data.libraryId;
|
this.libraryId = this.config.data.libraryId;
|
||||||
|
|
||||||
this.appSettingsService.appSettings$.pipe(
|
const settings = this.appSettingsService.appSettings();
|
||||||
filter(settings => !!settings),
|
if (settings) {
|
||||||
take(1),
|
this.moveFiles = settings.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
|
||||||
takeUntil(this.destroy$)
|
}
|
||||||
).subscribe(settings => {
|
|
||||||
this.moveFiles = settings!.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
|
|
||||||
});
|
|
||||||
|
|
||||||
this.presetOptions = [
|
this.presetOptions = [
|
||||||
{label: this.t.translate('book.duplicateMerger.presetStrict'), value: 'strict'},
|
{label: this.t.translate('book.duplicateMerger.presetStrict'), value: 'strict'},
|
||||||
|
|||||||
+31
-31
@@ -1,5 +1,14 @@
|
|||||||
<ng-container *transloco="let t; prefix: 'book.seriesPage'">
|
<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">
|
<div class="series-wrapper">
|
||||||
<p-tabs [value]="tab" lazy="true" scrollable>
|
<p-tabs [value]="tab" lazy="true" scrollable>
|
||||||
<p-tablist>
|
<p-tablist>
|
||||||
@@ -21,7 +30,7 @@
|
|||||||
|
|
||||||
<!-- HERO: Cover + Identity info -->
|
<!-- HERO: Cover + Identity info -->
|
||||||
<div class="series-hero">
|
<div class="series-hero">
|
||||||
@if (coverBook$ | async; as coverBook) {
|
@if (coverBook(); as coverBook) {
|
||||||
<div class="hero-cover-section">
|
<div class="hero-cover-section">
|
||||||
<img
|
<img
|
||||||
[src]="getBookThumbnailUrl(coverBook)"
|
[src]="getBookThumbnailUrl(coverBook)"
|
||||||
@@ -33,9 +42,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
<div class="hero-info">
|
<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">
|
<p class="series-authors">
|
||||||
@for (author of authors; track $index; let isLast = $last) {
|
@for (author of authors; track $index; let isLast = $last) {
|
||||||
<a class="author-link" (click)="goToAuthorBooks(author)">{{ author }}</a>
|
<a class="author-link" (click)="goToAuthorBooks(author)">{{ author }}</a>
|
||||||
@@ -44,7 +53,7 @@
|
|||||||
</p>
|
</p>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (allCategories$ | async; as categories) {
|
@if (allCategories(); as categories) {
|
||||||
@if (categories.length) {
|
@if (categories.length) {
|
||||||
<div class="categories-scroll">
|
<div class="categories-scroll">
|
||||||
<div class="categories-list">
|
<div class="categories-list">
|
||||||
@@ -59,7 +68,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
<div class="metadata-cards">
|
<div class="metadata-cards">
|
||||||
@if (allPublishers$ | async; as publishers) {
|
@if (allPublishers(); as publishers) {
|
||||||
@if (publishers.length) {
|
@if (publishers.length) {
|
||||||
<span class="meta-card meta-card--publisher" (click)="goToPublisher(publishers[0])">
|
<span class="meta-card meta-card--publisher" (click)="goToPublisher(publishers[0])">
|
||||||
<i class="pi pi-building"></i>
|
<i class="pi pi-building"></i>
|
||||||
@@ -73,13 +82,13 @@
|
|||||||
<i class="pi pi-book"></i>
|
<i class="pi pi-book"></i>
|
||||||
{{ books.length }} {{ books.length === 1 ? t('book') : t('books') }}
|
{{ books.length }} {{ books.length === 1 ? t('book') : t('books') }}
|
||||||
</span>
|
</span>
|
||||||
@if (yearsRange$ | async; as years) {
|
@if (yearsRange(); as years) {
|
||||||
<span class="meta-card meta-card--years">
|
<span class="meta-card meta-card--years">
|
||||||
<i class="pi pi-calendar"></i>
|
<i class="pi pi-calendar"></i>
|
||||||
{{ years }}
|
{{ years }}
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
@if (seriesStats$ | async; as stats) {
|
@if (seriesStats(); as stats) {
|
||||||
@if (stats.totalPages > 0) {
|
@if (stats.totalPages > 0) {
|
||||||
<span class="meta-card meta-card--pages">
|
<span class="meta-card meta-card--pages">
|
||||||
<i class="pi pi-file"></i>
|
<i class="pi pi-file"></i>
|
||||||
@@ -101,7 +110,7 @@
|
|||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@if (allLanguages$ | async; as languages) {
|
@if (allLanguages(); as languages) {
|
||||||
@if (languages.length) {
|
@if (languages.length) {
|
||||||
<span class="meta-card meta-card--language">
|
<span class="meta-card meta-card--language">
|
||||||
<i class="pi pi-globe"></i>
|
<i class="pi pi-globe"></i>
|
||||||
@@ -109,7 +118,7 @@
|
|||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@if (seriesCompletion$ | async; as completion) {
|
@if (seriesCompletion(); as completion) {
|
||||||
<span class="meta-card meta-card--owned">
|
<span class="meta-card meta-card--owned">
|
||||||
<i class="pi pi-check-circle"></i>
|
<i class="pi pi-check-circle"></i>
|
||||||
{{ completion.owned }}/{{ completion.total }} {{ t('stats.owned') }}
|
{{ completion.owned }}/{{ completion.total }} {{ t('stats.owned') }}
|
||||||
@@ -118,7 +127,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Ratings -->
|
<!-- Ratings -->
|
||||||
@if (seriesStats$ | async; as stats) {
|
@if (seriesStats(); as stats) {
|
||||||
@if (stats.avgPersonalRating != null || stats.avgGoodreads != null || stats.avgAmazon != null || stats.avgHardcover != null) {
|
@if (stats.avgPersonalRating != null || stats.avgGoodreads != null || stats.avgAmazon != null || stats.avgHardcover != null) {
|
||||||
<div class="ratings-row">
|
<div class="ratings-row">
|
||||||
@if (stats.avgPersonalRating != null) {
|
@if (stats.avgPersonalRating != null) {
|
||||||
@@ -155,7 +164,7 @@
|
|||||||
|
|
||||||
<!-- Next Up + Progress (pushed to bottom, aligned with cover) -->
|
<!-- Next Up + Progress (pushed to bottom, aligned with cover) -->
|
||||||
<div class="hero-status">
|
<div class="hero-status">
|
||||||
@if (nextUp$ | async; as nextUp) {
|
@if (nextUp(); as nextUp) {
|
||||||
<div class="next-up-card" (click)="readBook(nextUp.book.id)">
|
<div class="next-up-card" (click)="readBook(nextUp.book.id)">
|
||||||
<img [src]="nextUp.thumbnailUrl"
|
<img [src]="nextUp.thumbnailUrl"
|
||||||
[alt]="nextUp.book.metadata?.title || ''"
|
[alt]="nextUp.book.metadata?.title || ''"
|
||||||
@@ -181,7 +190,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (readStatusBreakdown$ | async; as segments) {
|
@if (readStatusBreakdown(); as segments) {
|
||||||
@if (segments.length) {
|
@if (segments.length) {
|
||||||
<div class="read-progress-card">
|
<div class="read-progress-card">
|
||||||
<div class="read-progress-section">
|
<div class="read-progress-section">
|
||||||
@@ -202,7 +211,7 @@
|
|||||||
{{ getStatusLabel(seg.status) }} ({{ seg.count }})
|
{{ getStatusLabel(seg.status) }} ({{ seg.count }})
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
@let readProg = seriesReadProgress$ | async;
|
@let readProg = seriesReadProgress();
|
||||||
@if (readProg) {
|
@if (readProg) {
|
||||||
<span class="read-percent-label">
|
<span class="read-percent-label">
|
||||||
{{ t('readPercent', { progress: readProg }) }}
|
{{ t('readPercent', { progress: readProg }) }}
|
||||||
@@ -227,7 +236,7 @@
|
|||||||
<div #descriptionContent [ngClass]="{ 'line-clamp-7': !isExpanded }"
|
<div #descriptionContent [ngClass]="{ 'line-clamp-7': !isExpanded }"
|
||||||
class="description-content">
|
class="description-content">
|
||||||
<div class="description-html"
|
<div class="description-html"
|
||||||
[innerHTML]="(firstDescription$ | async) || t('noDescription')"></div>
|
[innerHTML]="firstDescription() || t('noDescription')"></div>
|
||||||
</div>
|
</div>
|
||||||
@if (isExpanded || isOverflowing) {
|
@if (isExpanded || isOverflowing) {
|
||||||
<button class="expand-toggle" (click)="toggleExpand()">
|
<button class="expand-toggle" (click)="toggleExpand()">
|
||||||
@@ -356,7 +365,7 @@
|
|||||||
</p-tabpanels>
|
</p-tabpanels>
|
||||||
</p-tabs>
|
</p-tabs>
|
||||||
@if (selectedBooks.size > 0) {
|
@if (selectedBooks.size > 0) {
|
||||||
@if (userService.userState$ | async; as userState) {
|
@if (currentUser(); as user) {
|
||||||
<div class="book-browser-footer" [@slideInOut]>
|
<div class="book-browser-footer" [@slideInOut]>
|
||||||
<div class="footer-content">
|
<div class="footer-content">
|
||||||
<div class="footer-left">
|
<div class="footer-left">
|
||||||
@@ -387,17 +396,17 @@
|
|||||||
[pTooltip]="t('tooltip.assignToShelf')"
|
[pTooltip]="t('tooltip.assignToShelf')"
|
||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
@if (userState.user!.permissions.canBulkLockUnlockMetadata) {
|
@if (user.permissions.canBulkLockUnlockMetadata) {
|
||||||
<p-button
|
<p-button
|
||||||
outlined="true"
|
outlined="true"
|
||||||
icon="pi pi-lock"
|
icon="pi pi-lock"
|
||||||
severity="info"
|
severity="info"
|
||||||
(click)="lockUnlockMetadata()"
|
(click)="lockUnlockMetadata()"
|
||||||
[pTooltip]="t('tooltip.lockUnlockMetadata')"
|
[pTooltip]="t('tooltip.lockUnlockMetadata')"
|
||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
}
|
}
|
||||||
@if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
|
@if (user.permissions.canMoveOrganizeFiles && appSettings()?.diskType === 'LOCAL') {
|
||||||
<p-button
|
<p-button
|
||||||
outlined="true"
|
outlined="true"
|
||||||
icon="pi pi-arrows-h"
|
icon="pi pi-arrows-h"
|
||||||
@@ -440,7 +449,7 @@
|
|||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
</div>
|
</div>
|
||||||
@if (userState.user!.permissions.admin || userState.user!.permissions.canDeleteBook) {
|
@if (user.permissions.admin || user.permissions.canDeleteBook) {
|
||||||
<p-divider layout="vertical"></p-divider>
|
<p-divider layout="vertical"></p-divider>
|
||||||
<p-button
|
<p-button
|
||||||
outlined="true"
|
outlined="true"
|
||||||
@@ -458,14 +467,5 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
</div>
|
</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>
|
</ng-container>
|
||||||
|
|||||||
+216
-274
@@ -1,10 +1,10 @@
|
|||||||
import {FormsModule} from "@angular/forms";
|
import {FormsModule} from "@angular/forms";
|
||||||
import {Button} from "primeng/button";
|
import {Button} from "primeng/button";
|
||||||
import {ActivatedRoute, Router} from "@angular/router";
|
import {ActivatedRoute, Router} from "@angular/router";
|
||||||
import {AsyncPipe, DecimalPipe, KeyValuePipe, NgClass, NgStyle} from "@angular/common";
|
import {toSignal} from '@angular/core/rxjs-interop';
|
||||||
import {filter, finalize, map, switchMap, tap} from "rxjs/operators";
|
import {DecimalPipe, KeyValuePipe, NgClass, NgStyle} from "@angular/common";
|
||||||
import {combineLatest, Observable, Subscription} from "rxjs";
|
import {finalize, map} from "rxjs/operators";
|
||||||
import {Book, BookType, ReadStatus} from "../../model/book.model";
|
import {Book, BookType, computeSeriesReadStatus, ReadStatus} from "../../model/book.model";
|
||||||
import {BookService} from "../../service/book.service";
|
import {BookService} from "../../service/book.service";
|
||||||
import {BookMetadataManageService} from "../../service/book-metadata-manage.service";
|
import {BookMetadataManageService} from "../../service/book-metadata-manage.service";
|
||||||
import {BookCardComponent} from "../book-browser/book-card/book-card.component";
|
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 {Divider} from "primeng/divider";
|
||||||
import {TagComponent} from "../../../../shared/components/tag/tag.component";
|
import {TagComponent} from "../../../../shared/components/tag/tag.component";
|
||||||
import {animate, style, transition, trigger} from "@angular/animations";
|
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 {BookCardOverlayPreferenceService} from '../book-browser/book-card-overlay-preference.service';
|
||||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||||
|
import {injectQuery} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
interface ReadStatusSegment {
|
interface ReadStatusSegment {
|
||||||
status: ReadStatus;
|
status: ReadStatus;
|
||||||
@@ -68,7 +69,6 @@ interface SeriesStats {
|
|||||||
templateUrl: "./series-page.component.html",
|
templateUrl: "./series-page.component.html",
|
||||||
styleUrls: ["./series-page.component.scss"],
|
styleUrls: ["./series-page.component.scss"],
|
||||||
imports: [
|
imports: [
|
||||||
AsyncPipe,
|
|
||||||
DecimalPipe,
|
DecimalPipe,
|
||||||
KeyValuePipe,
|
KeyValuePipe,
|
||||||
Button,
|
Button,
|
||||||
@@ -103,7 +103,7 @@ interface SeriesStats {
|
|||||||
])
|
])
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
|
export class SeriesPageComponent implements AfterViewChecked {
|
||||||
|
|
||||||
private route = inject(ActivatedRoute);
|
private route = inject(ActivatedRoute);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
@@ -128,313 +128,257 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
|
|||||||
tab: string = "view";
|
tab: string = "view";
|
||||||
isExpanded = false;
|
isExpanded = false;
|
||||||
isOverflowing = false;
|
isOverflowing = false;
|
||||||
|
protected appSettings = this.appSettingsService.appSettings;
|
||||||
|
protected currentUser = this.userService.currentUser;
|
||||||
|
protected isBooksLoading = this.bookService.isBooksLoading;
|
||||||
|
|
||||||
// Selection state
|
// Selection state
|
||||||
selectedBooks = new Set<number>();
|
selectedBooks = new Set<number>();
|
||||||
lastSelectedIndex: number | null = null;
|
lastSelectedIndex: number | null = null;
|
||||||
currentBooks: Book[] = [];
|
|
||||||
private userSub: Subscription;
|
|
||||||
|
|
||||||
// Menu items
|
// Menu items
|
||||||
protected metadataMenuItems: MenuItem[] | undefined;
|
protected metadataMenuItems: MenuItem[] | undefined;
|
||||||
protected moreActionsMenuItems: 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((params) => params.get("seriesName") || ""),
|
||||||
map((name) => decodeURIComponent(name))
|
map((name) => decodeURIComponent(name))
|
||||||
);
|
), {initialValue: ""});
|
||||||
|
|
||||||
booksInSeries$: Observable<Book[]> = this.bookService.bookState$.pipe(
|
filteredBooks = computed(() => {
|
||||||
filter((state) => state.loaded && !!state.books),
|
const seriesName = this.seriesParam().trim().toLowerCase();
|
||||||
map((state) => state.books || [])
|
const inSeries = this.bookService.books().filter(
|
||||||
);
|
(book) => book.metadata?.seriesName?.trim().toLowerCase() === seriesName
|
||||||
|
);
|
||||||
|
|
||||||
filteredBooks$: Observable<Book[]> = combineLatest([
|
return [...inSeries].sort((a, b) => {
|
||||||
this.seriesParam$.pipe(map((n) => n.trim().toLowerCase())),
|
const aNum = a.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
|
||||||
this.booksInSeries$,
|
const bNum = b.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
|
||||||
]).pipe(
|
return aNum - bNum;
|
||||||
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)
|
|
||||||
);
|
|
||||||
|
|
||||||
coverBook$: Observable<Book | null> = this.filteredBooks$.pipe(
|
coverBook = computed(() => this.filteredBooks()[0] ?? null);
|
||||||
map(books => books[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([
|
seriesTitle = computed(() => this.filteredBooks()[0]?.metadata?.seriesName || this.seriesParam());
|
||||||
this.seriesParam$,
|
|
||||||
this.filteredBooks$,
|
|
||||||
]).pipe(map(([param, books]) => books[0]?.metadata?.seriesName || param));
|
|
||||||
|
|
||||||
yearsRange$: Observable<string | null> = this.filteredBooks$.pipe(
|
yearsRange = computed(() => {
|
||||||
map((books) => {
|
const years = this.filteredBooks()
|
||||||
const years = books
|
.map((book) => book.metadata?.publishedDate)
|
||||||
.map((b) => b.metadata?.publishedDate)
|
.filter((date): date is string => !!date)
|
||||||
.filter((d): d is string => !!d)
|
.map((date) => {
|
||||||
.map((d) => {
|
const match = date.match(/\d{4}/);
|
||||||
const match = d.match(/\d{4}/);
|
return match ? parseInt(match[0], 10) : null;
|
||||||
return match ? parseInt(match[0], 10) : null;
|
})
|
||||||
})
|
.filter((year): year is number => year !== null);
|
||||||
.filter((y): y is number => y !== null);
|
|
||||||
|
|
||||||
if (years.length === 0) return null;
|
if (years.length === 0) return null;
|
||||||
const min = Math.min(...years);
|
const min = Math.min(...years);
|
||||||
const max = Math.max(...years);
|
const max = Math.max(...years);
|
||||||
return min === max ? String(min) : `${min}-${max}`;
|
return min === max ? String(min) : `${min}-${max}`;
|
||||||
})
|
});
|
||||||
);
|
|
||||||
|
|
||||||
firstBookWithDesc$: Observable<Book> = this.filteredBooks$.pipe(
|
firstBookWithDesc = computed(() => this.firstBookDetailQuery.data() ?? null);
|
||||||
map((books) => books[0]),
|
firstDescription = computed(() => this.firstBookWithDesc()?.metadata?.description || "");
|
||||||
filter((b): b is Book => !!b),
|
|
||||||
switchMap((b) => this.bookService.getBookByIdFromAPI(b.id, true))
|
|
||||||
);
|
|
||||||
|
|
||||||
firstDescription$: Observable<string> = this.firstBookWithDesc$.pipe(
|
seriesReadStatus = computed(() => computeSeriesReadStatus(this.filteredBooks()));
|
||||||
map((b) => b.metadata?.description || "")
|
|
||||||
);
|
|
||||||
|
|
||||||
seriesReadStatus$: Observable<ReadStatus> = this.filteredBooks$.pipe(
|
seriesReadProgress = computed(() => {
|
||||||
map((books) => {
|
const books = this.filteredBooks();
|
||||||
if (!books || books.length === 0) return ReadStatus.UNREAD;
|
const readCount = books.filter((book) => book.readStatus === ReadStatus.READ).length;
|
||||||
const statuses = books.map((b) => (b.readStatus as ReadStatus) ?? ReadStatus.UNREAD);
|
return `${readCount}/${books.length}`;
|
||||||
|
});
|
||||||
|
|
||||||
const hasWontRead = statuses.includes(ReadStatus.WONT_READ);
|
allAuthors = computed(() => {
|
||||||
if (hasWontRead) return ReadStatus.WONT_READ;
|
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);
|
allCategories = computed(() => {
|
||||||
if (hasAbandoned) return ReadStatus.ABANDONED;
|
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);
|
allPublishers = computed(() => {
|
||||||
if (allRead) return ReadStatus.READ;
|
const publishers = new Set<string>();
|
||||||
|
for (const book of this.filteredBooks()) {
|
||||||
const isAnyReading = statuses.some(
|
if (book.metadata?.publisher) {
|
||||||
(s) => s === ReadStatus.READING || s === ReadStatus.RE_READING || s === ReadStatus.PAUSED
|
publishers.add(book.metadata.publisher);
|
||||||
);
|
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
return Array.from(set);
|
}
|
||||||
})
|
return Array.from(publishers);
|
||||||
);
|
});
|
||||||
|
|
||||||
allCategories$: Observable<string[]> = this.filteredBooks$.pipe(
|
allLanguages = computed(() => {
|
||||||
map(books => {
|
const languages = new Set<string>();
|
||||||
const set = new Set<string>();
|
for (const book of this.filteredBooks()) {
|
||||||
for (const book of books) {
|
if (book.metadata?.language) {
|
||||||
book.metadata?.categories?.forEach(c => set.add(c));
|
languages.add(book.metadata.language);
|
||||||
}
|
}
|
||||||
return Array.from(set);
|
}
|
||||||
})
|
return Array.from(languages);
|
||||||
);
|
});
|
||||||
|
|
||||||
allPublishers$: Observable<string[]> = this.filteredBooks$.pipe(
|
seriesCompletion = computed<SeriesCompletion | null>(() => {
|
||||||
map(books => {
|
const totals = this.filteredBooks()
|
||||||
const set = new Set<string>();
|
.map((book) => book.metadata?.seriesTotal)
|
||||||
for (const book of books) {
|
.filter((total): total is number => total != null && total > 0);
|
||||||
if (book.metadata?.publisher) set.add(book.metadata.publisher);
|
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(
|
return {book: target, thumbnailUrl, isReading, progressPercent};
|
||||||
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);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
// Series completion tracker
|
seriesStats = computed<SeriesStats>(() => {
|
||||||
seriesCompletion$: Observable<SeriesCompletion | null> = this.filteredBooks$.pipe(
|
let totalPages = 0;
|
||||||
map(books => {
|
const personalRatings: number[] = [];
|
||||||
const totals = books
|
const goodreadsRatings: number[] = [];
|
||||||
.map(b => b.metadata?.seriesTotal)
|
const amazonRatings: number[] = [];
|
||||||
.filter((t): t is number => t != null && t > 0);
|
const hardcoverRatings: number[] = [];
|
||||||
if (totals.length === 0) return null;
|
const formatCounts = new Map<BookType, number>();
|
||||||
|
let totalAudioDurationSeconds = 0;
|
||||||
|
|
||||||
const seriesTotal = Math.max(...totals);
|
for (const book of this.filteredBooks()) {
|
||||||
const ownedNumbers = new Set(
|
if (book.metadata?.pageCount) totalPages += book.metadata.pageCount;
|
||||||
books
|
if (book.personalRating != null) personalRatings.push(book.personalRating);
|
||||||
.map(b => b.metadata?.seriesNumber)
|
if (book.metadata?.goodreadsRating != null) goodreadsRatings.push(book.metadata.goodreadsRating);
|
||||||
.filter((n): n is number => n != null)
|
if (book.metadata?.amazonRating != null) amazonRatings.push(book.metadata.amazonRating);
|
||||||
);
|
if (book.metadata?.hardcoverRating != null) hardcoverRatings.push(book.metadata.hardcoverRating);
|
||||||
|
|
||||||
const missingNumbers: number[] = [];
|
const bookType = book.primaryFile?.bookType;
|
||||||
for (let i = 1; i <= seriesTotal; i++) {
|
if (bookType) {
|
||||||
if (!ownedNumbers.has(i)) missingNumbers.push(i);
|
formatCounts.set(bookType, (formatCounts.get(bookType) || 0) + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const owned = ownedNumbers.size;
|
if (book.metadata?.audiobookMetadata?.durationSeconds) {
|
||||||
return {
|
totalAudioDurationSeconds += book.metadata.audiobookMetadata.durationSeconds;
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
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
|
const avg = (ratings: number[]) => ratings.length > 0
|
||||||
nextUp$: Observable<NextUpBook | null> = this.filteredBooks$.pipe(
|
? ratings.reduce((total, rating) => total + rating, 0) / ratings.length
|
||||||
map(books => {
|
: null;
|
||||||
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 isAudiobook = target.primaryFile?.bookType === 'AUDIOBOOK';
|
return {
|
||||||
const thumbnailUrl = isAudiobook
|
totalPages,
|
||||||
? this.urlHelper.getAudiobookThumbnailUrl(target.id, target.metadata?.audiobookCoverUpdatedOn)
|
avgPersonalRating: avg(personalRatings),
|
||||||
: this.urlHelper.getThumbnailUrl(target.id, target.metadata?.coverUpdatedOn);
|
avgGoodreads: avg(goodreadsRatings),
|
||||||
|
avgAmazon: avg(amazonRatings),
|
||||||
const isReading = target.readStatus === ReadStatus.READING ||
|
avgHardcover: avg(hardcoverRatings),
|
||||||
target.readStatus === ReadStatus.RE_READING ||
|
formatCounts,
|
||||||
target.readStatus === ReadStatus.PAUSED;
|
totalAudioDurationSeconds
|
||||||
|
};
|
||||||
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
|
|
||||||
};
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.userSub = this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded))
|
effect(() => {
|
||||||
.subscribe(userState => {
|
const user = this.currentUser();
|
||||||
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
|
if (!user) {
|
||||||
() => this.autoFetchMetadata(),
|
return;
|
||||||
() => this.fetchMetadata(),
|
}
|
||||||
() => this.bulkEditMetadata(),
|
|
||||||
() => this.multiBookEditMetadata(),
|
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
|
||||||
() => this.regenerateCoversForSelected(),
|
() => this.autoFetchMetadata(),
|
||||||
() => this.generateCustomCoversForSelected(),
|
() => this.fetchMetadata(),
|
||||||
userState.user
|
() => this.bulkEditMetadata(),
|
||||||
);
|
() => this.multiBookEditMetadata(),
|
||||||
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
() => this.regenerateCoversForSelected(),
|
||||||
});
|
() => this.generateCustomCoversForSelected(),
|
||||||
}
|
user
|
||||||
|
);
|
||||||
|
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.currentUser());
|
||||||
|
});
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.userSub.unsubscribe();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get currentCardSize() {
|
get currentCardSize() {
|
||||||
return this.coverScalePreferenceService.currentCardSize;
|
return this.coverScalePreferenceService.currentCardSize();
|
||||||
}
|
}
|
||||||
|
|
||||||
get gridColumnMinWidth(): string {
|
get gridColumnMinWidth(): string {
|
||||||
return this.coverScalePreferenceService.gridColumnMinWidth;
|
return this.coverScalePreferenceService.gridColumnMinWidth();
|
||||||
}
|
}
|
||||||
|
|
||||||
goToAuthorBooks(author: string): void {
|
goToAuthorBooks(author: string): void {
|
||||||
@@ -607,8 +551,9 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
|
|||||||
const start = Math.min(this.lastSelectedIndex, index);
|
const start = Math.min(this.lastSelectedIndex, index);
|
||||||
const end = Math.max(this.lastSelectedIndex, index);
|
const end = Math.max(this.lastSelectedIndex, index);
|
||||||
const isUnselectingRange = !selected;
|
const isUnselectingRange = !selected;
|
||||||
|
const books = this.filteredBooks();
|
||||||
for (let i = start; i <= end; i++) {
|
for (let i = start; i <= end; i++) {
|
||||||
const book = this.currentBooks[i];
|
const book = books[i];
|
||||||
if (!book) continue;
|
if (!book) continue;
|
||||||
this.handleBookSelection(book, !isUnselectingRange);
|
this.handleBookSelection(book, !isUnselectingRange);
|
||||||
}
|
}
|
||||||
@@ -622,8 +567,7 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
|
|||||||
}
|
}
|
||||||
|
|
||||||
selectAllBooks(): void {
|
selectAllBooks(): void {
|
||||||
if (!this.currentBooks) return;
|
for (const book of this.filteredBooks()) {
|
||||||
for (const book of this.currentBooks) {
|
|
||||||
this.selectedBooks.add(book.id);
|
this.selectedBooks.add(book.id);
|
||||||
}
|
}
|
||||||
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
this.moreActionsMenuItems = this.bookMenuService.getMoreActionsMenu(this.selectedBooks, this.user());
|
||||||
@@ -654,8 +598,6 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
|
|||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
this.selectedBooks.clear();
|
this.selectedBooks.clear();
|
||||||
});
|
});
|
||||||
},
|
|
||||||
reject: () => {
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -795,7 +737,7 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
|
|||||||
}
|
}
|
||||||
|
|
||||||
user() {
|
user() {
|
||||||
return this.userService.getCurrentUser();
|
return this.currentUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
get hasMetadataMenuItems(): boolean {
|
get hasMetadataMenuItems(): boolean {
|
||||||
|
|||||||
+59
-55
@@ -25,65 +25,69 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="shelves-container">
|
<div class="shelves-container">
|
||||||
@if ((shelfState$ | async)?.shelves && (shelfState$ | async)!.shelves!.length > 0) {
|
@if (shelves(); as shelves) {
|
||||||
<div class="shelves-list">
|
@if (shelves.length > 0) {
|
||||||
<div class="list-header">
|
<div class="shelves-list">
|
||||||
<span class="shelf-count">
|
<div class="list-header">
|
||||||
<i class="pi pi-bookmark"></i>
|
<span class="shelf-count">
|
||||||
{{ t('shelvesAvailable', { count: (shelfState$ | async)!.shelves!.length }) }}
|
<i class="pi pi-bookmark"></i>
|
||||||
</span>
|
{{ t('shelvesAvailable', { count: shelves.length }) }}
|
||||||
<p-iconfield class="shelf-search">
|
</span>
|
||||||
<p-inputicon class="pi pi-search"/>
|
<p-iconfield class="shelf-search">
|
||||||
<input
|
<p-inputicon class="pi pi-search"/>
|
||||||
type="text"
|
<input
|
||||||
pInputText
|
type="text"
|
||||||
[(ngModel)]="searchQuery"
|
pInputText
|
||||||
[placeholder]="t('searchPlaceholder')"
|
[(ngModel)]="searchQuery"
|
||||||
/>
|
[placeholder]="t('searchPlaceholder')"
|
||||||
@if (searchQuery) {
|
/>
|
||||||
<i class="pi pi-times clear-icon" (click)="searchQuery = ''"></i>
|
@if (searchQuery) {
|
||||||
}
|
<button type="button" class="clear-icon" (click)="searchQuery = ''">
|
||||||
</p-iconfield>
|
<i class="pi pi-times"></i>
|
||||||
</div>
|
</button>
|
||||||
|
}
|
||||||
|
</p-iconfield>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="shelves-grid">
|
<div class="shelves-grid">
|
||||||
@for (shelf of filterShelves((shelfState$ | async)!.shelves!); track shelf.id) {
|
@for (shelf of filterShelves(shelves); track shelf.id) {
|
||||||
<div class="shelf-item" [class.selected]="isShelfSelected(shelf)">
|
<div class="shelf-item" [class.selected]="isShelfSelected(shelf)">
|
||||||
<div class="shelf-checkbox">
|
<div class="shelf-checkbox">
|
||||||
<p-checkbox
|
<p-checkbox
|
||||||
[inputId]="'shelf-' + shelf.id"
|
[inputId]="'shelf-' + shelf.id"
|
||||||
name="shelves"
|
name="shelves"
|
||||||
[value]="shelf"
|
[value]="shelf"
|
||||||
[(ngModel)]="selectedShelves"
|
[(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>
|
</div>
|
||||||
<label [for]="'shelf-' + shelf.id" class="shelf-label">
|
}
|
||||||
@if (shelf.icon) {
|
</div>
|
||||||
<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 {
|
||||||
} @else {
|
<div class="empty-state">
|
||||||
<div class="empty-state">
|
<div class="empty-icon-wrapper">
|
||||||
<div class="empty-icon-wrapper">
|
<i class="pi pi-bookmark empty-icon"></i>
|
||||||
<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>
|
</div>
|
||||||
<h3 class="empty-title">{{ t('emptyTitle') }}</h3>
|
}
|
||||||
<p class="empty-description" [innerHTML]="t('emptyDescription')"></p>
|
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+37
-48
@@ -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 {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {ShelfService} from '../../service/shelf.service';
|
import {ShelfService} from '../../service/shelf.service';
|
||||||
import {combineLatest, finalize, Observable} from 'rxjs';
|
import {finalize} from 'rxjs';
|
||||||
import {BookService} from '../../service/book.service';
|
import {BookService} from '../../service/book.service';
|
||||||
import {map, tap} from 'rxjs/operators';
|
|
||||||
import {Shelf} from '../../model/shelf.model';
|
import {Shelf} from '../../model/shelf.model';
|
||||||
import {ShelfState} from '../../model/state/shelf-state.model';
|
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {AsyncPipe} from '@angular/common';
|
|
||||||
import {Checkbox} from 'primeng/checkbox';
|
import {Checkbox} from 'primeng/checkbox';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||||
@@ -30,7 +27,6 @@ import {InputIcon} from 'primeng/inputicon';
|
|||||||
imports: [
|
imports: [
|
||||||
Button,
|
Button,
|
||||||
Checkbox,
|
Checkbox,
|
||||||
AsyncPipe,
|
|
||||||
FormsModule,
|
FormsModule,
|
||||||
IconDisplayComponent,
|
IconDisplayComponent,
|
||||||
TranslocoDirective,
|
TranslocoDirective,
|
||||||
@@ -39,7 +35,7 @@ import {InputIcon} from 'primeng/inputicon';
|
|||||||
InputIcon
|
InputIcon
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
export class ShelfAssignerComponent implements OnInit {
|
export class ShelfAssignerComponent {
|
||||||
|
|
||||||
private shelfService = inject(ShelfService);
|
private shelfService = inject(ShelfService);
|
||||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||||
@@ -52,43 +48,40 @@ export class ShelfAssignerComponent implements OnInit {
|
|||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
searchQuery = '';
|
searchQuery = '';
|
||||||
private shelfSortField: 'name' | 'id' = 'name';
|
private currentUser = this.userService.currentUser;
|
||||||
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)
|
|
||||||
};
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
book: Book = this.dynamicDialogConfig.data.book;
|
book: Book = this.dynamicDialogConfig.data.book;
|
||||||
selectedShelves: Shelf[] = [];
|
selectedShelves: Shelf[] = [];
|
||||||
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
|
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
|
||||||
isMultiBooks: boolean = this.dynamicDialogConfig.data.isMultiBooks;
|
isMultiBooks: boolean = this.dynamicDialogConfig.data.isMultiBooks;
|
||||||
|
private readonly shelfSortField = computed<'name' | 'id'>(() => {
|
||||||
ngOnInit(): void {
|
const sorting = this.currentUser()?.userSettings.sidebarShelfSorting;
|
||||||
if (!this.isMultiBooks && this.book.shelves) {
|
return sorting ? this.validateSortField(sorting.field) : 'name';
|
||||||
this.shelfState$.pipe(
|
});
|
||||||
map(state => state.shelves || []),
|
private readonly shelfSortOrder = computed<'asc' | 'desc'>(() => {
|
||||||
tap(shelves => {
|
const sorting = this.currentUser()?.userSettings.sidebarShelfSorting;
|
||||||
this.selectedShelves = shelves.filter(shelf =>
|
return sorting ? this.validateSortOrder(sorting.order) : 'asc';
|
||||||
this.book.shelves?.some(bShelf => bShelf.id === shelf.id)
|
});
|
||||||
);
|
readonly shelves = computed(() => {
|
||||||
})
|
const user = this.currentUser();
|
||||||
).subscribe();
|
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 {
|
updateBooksShelves(): void {
|
||||||
const idsToAssign = new Set<number | undefined>(this.selectedShelves.map(shelf => shelf.id));
|
const idsToAssign = new Set<number | undefined>(this.selectedShelves.map(shelf => shelf.id));
|
||||||
@@ -125,13 +118,7 @@ export class ShelfAssignerComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createShelfDialog(): void {
|
createShelfDialog(): void {
|
||||||
const dialogRef = this.bookDialogHelper.openShelfCreatorDialog();
|
this.bookDialogHelper.openShelfCreatorDialog();
|
||||||
|
|
||||||
dialogRef.onClose.subscribe((created: boolean) => {
|
|
||||||
if (created) {
|
|
||||||
this.shelfService.reloadShelves();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
closeDialog(): void {
|
closeDialog(): void {
|
||||||
@@ -159,16 +146,18 @@ export class ShelfAssignerComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private sortShelves(shelves: Shelf[]): Shelf[] {
|
private sortShelves(shelves: Shelf[]): Shelf[] {
|
||||||
|
const sortField = this.shelfSortField();
|
||||||
|
const sortOrder = this.shelfSortOrder();
|
||||||
return [...shelves].sort((a, b) => {
|
return [...shelves].sort((a, b) => {
|
||||||
const aVal = (a 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>)[this.shelfSortField] ?? '';
|
const bVal = (b as unknown as Record<string, unknown>)[sortField] ?? '';
|
||||||
let comparison = 0;
|
let comparison = 0;
|
||||||
if (typeof aVal === 'string' && typeof bVal === 'string') {
|
if (typeof aVal === 'string' && typeof bVal === 'string') {
|
||||||
comparison = aVal.localeCompare(bVal);
|
comparison = aVal.localeCompare(bVal);
|
||||||
} else if (typeof aVal === 'number' && typeof bVal === 'number') {
|
} else if (typeof aVal === 'number' && typeof bVal === 'number') {
|
||||||
comparison = aVal - bVal;
|
comparison = aVal - bVal;
|
||||||
}
|
}
|
||||||
return this.shelfSortOrder === 'asc' ? comparison : -comparison;
|
return sortOrder === 'asc' ? comparison : -comparison;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+22
-10
@@ -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 {ShelfService} from '../../service/shelf.service';
|
||||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
@@ -37,6 +37,8 @@ export class ShelfEditDialogComponent implements OnInit {
|
|||||||
private iconPickerService = inject(IconPickerService);
|
private iconPickerService = inject(IconPickerService);
|
||||||
private userService = inject(UserService);
|
private userService = inject(UserService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
private readonly injector = inject(Injector);
|
||||||
|
private shelfInitialized = false;
|
||||||
|
|
||||||
shelfName: string = '';
|
shelfName: string = '';
|
||||||
selectedIcon: IconSelection | null = null;
|
selectedIcon: IconSelection | null = null;
|
||||||
@@ -46,18 +48,28 @@ export class ShelfEditDialogComponent implements OnInit {
|
|||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
const shelfId = this.dynamicDialogConfig?.data.shelfId;
|
const shelfId = this.dynamicDialogConfig?.data.shelfId;
|
||||||
this.shelf = this.shelfService.getShelfById(shelfId);
|
effect(() => {
|
||||||
if (this.shelf) {
|
if (this.shelfInitialized) {
|
||||||
this.shelfName = this.shelf.name;
|
return;
|
||||||
this.isPublic = this.shelf.publicShelf ?? false;
|
}
|
||||||
if (this.shelf.iconType && this.shelf.icon) {
|
|
||||||
if (this.shelf.iconType === 'PRIME_NG') {
|
const shelf = this.shelfService.shelves().find(currentShelf => currentShelf.id === shelfId);
|
||||||
this.selectedIcon = {type: 'PRIME_NG', value: `pi pi-${this.shelf.icon}`};
|
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 {
|
} else {
|
||||||
this.selectedIcon = {type: 'CUSTOM_SVG', value: this.shelf.icon};
|
this.selectedIcon = {type: 'CUSTOM_SVG', value: shelf.icon};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}, {injector: this.injector});
|
||||||
}
|
}
|
||||||
|
|
||||||
openIconPicker() {
|
openIconPicker() {
|
||||||
|
|||||||
@@ -402,6 +402,25 @@ export enum ReadStatus {
|
|||||||
UNSET = 'UNSET'
|
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 {
|
export interface CreatePhysicalBookRequest {
|
||||||
libraryId: number;
|
libraryId: number;
|
||||||
isbn?: string;
|
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 {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||||
import {BookStateService} from './book-state.service';
|
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
import {patchBookInCacheWith, patchBooksInCache, removeBooksFromCache} from './book-query-cache';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -19,7 +20,7 @@ export class BookFileService {
|
|||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private fileDownloadService = inject(FileDownloadService);
|
private fileDownloadService = inject(FileDownloadService);
|
||||||
private bookStateService = inject(BookStateService);
|
private queryClient = inject(QueryClient);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
|
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
|
||||||
@@ -44,26 +45,13 @@ export class BookFileService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
|
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
|
||||||
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
|
return this.http.delete<void>(`${this.url}/${bookId}/files/${fileId}`).pipe(
|
||||||
return this.http.delete<void>(deleteUrl).pipe(
|
|
||||||
tap(() => {
|
tap(() => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookInCacheWith(this.queryClient, bookId, book => ({
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
...book,
|
||||||
if (book.id === bookId) {
|
alternativeFormats: book.alternativeFormats?.filter(f => f.id !== fileId),
|
||||||
return {
|
supplementaryFiles: book.supplementaryFiles?.filter(f => f.id !== fileId),
|
||||||
...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
|
|
||||||
});
|
|
||||||
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('book.bookService.toast.fileDeletedSummary'),
|
summary: this.t.translate('book.bookService.toast.fileDeletedSummary'),
|
||||||
@@ -82,43 +70,19 @@ export class BookFileService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
deleteBookFile(bookId: number, fileId: number, isPrimary: boolean): Observable<void> {
|
deleteBookFile(bookId: number, fileId: number, isPrimary: boolean): Observable<void> {
|
||||||
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
|
return this.http.delete<void>(`${this.url}/${bookId}/files/${fileId}`).pipe(
|
||||||
return this.http.delete<void>(deleteUrl).pipe(
|
|
||||||
tap(() => {
|
tap(() => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookInCacheWith(this.queryClient, bookId, book => {
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
if (isPrimary) {
|
||||||
if (book.id === bookId) {
|
const remaining = book.alternativeFormats?.filter(f => f.id !== fileId) || [];
|
||||||
if (isPrimary) {
|
const [newPrimary, ...rest] = remaining;
|
||||||
const remainingAlternatives = book.alternativeFormats?.filter(file => file.id !== fileId) || [];
|
return {...book, primaryFile: newPrimary, alternativeFormats: rest};
|
||||||
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)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return book;
|
return {
|
||||||
|
...book,
|
||||||
|
alternativeFormats: book.alternativeFormats?.filter(f => f.id !== fileId),
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
this.bookStateService.updateBookState({
|
|
||||||
...currentState,
|
|
||||||
books: updatedBooks
|
|
||||||
});
|
|
||||||
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('book.bookService.toast.fileDeletedSummary'),
|
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(
|
return this.http.post<AdditionalFile>(`${this.url}/${bookId}/files`, formData).pipe(
|
||||||
tap((newFile) => {
|
tap(newFile => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookInCacheWith(this.queryClient, bookId, book => {
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
|
||||||
if (book.id === bookId) {
|
return {...book, alternativeFormats: [...(book.alternativeFormats || []), newFile]};
|
||||||
const updatedBook = {...book};
|
|
||||||
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
|
|
||||||
updatedBook.alternativeFormats = [...(book.alternativeFormats || []), newFile];
|
|
||||||
} else {
|
|
||||||
updatedBook.supplementaryFiles = [...(book.supplementaryFiles || []), newFile];
|
|
||||||
}
|
|
||||||
return updatedBook;
|
|
||||||
}
|
}
|
||||||
return book;
|
return {...book, supplementaryFiles: [...(book.supplementaryFiles || []), newFile]};
|
||||||
});
|
});
|
||||||
|
|
||||||
this.bookStateService.updateBookState({
|
|
||||||
...currentState,
|
|
||||||
books: updatedBooks
|
|
||||||
});
|
|
||||||
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('book.bookService.toast.fileUploadedSummary'),
|
summary: this.t.translate('book.bookService.toast.fileUploadedSummary'),
|
||||||
@@ -209,19 +160,9 @@ export class BookFileService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
detachBookFile(bookId: number, fileId: number, copyMetadata: boolean): Observable<DetachBookFileResponse> {
|
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 => {
|
tap(response => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBooksInCache(this.queryClient, [response.sourceBook, response.newBook]);
|
||||||
let updatedBooks = (currentState.books || []).map(book =>
|
|
||||||
book.id === bookId ? response.sourceBook : book
|
|
||||||
);
|
|
||||||
updatedBooks = [...updatedBooks, response.newBook];
|
|
||||||
|
|
||||||
this.bookStateService.updateBookState({
|
|
||||||
...currentState,
|
|
||||||
books: updatedBooks
|
|
||||||
});
|
|
||||||
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('metadata.viewer.toast.detachFileSuccessSummary'),
|
summary: this.t.translate('metadata.viewer.toast.detachFileSuccessSummary'),
|
||||||
@@ -249,22 +190,12 @@ export class BookFileService {
|
|||||||
moveFiles
|
moveFiles
|
||||||
}).pipe(
|
}).pipe(
|
||||||
tap(response => {
|
tap(response => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBooksInCache(this.queryClient, [response.updatedBook]);
|
||||||
const deletedIdSet = new Set(response.deletedSourceBookIds);
|
removeBooksFromCache(this.queryClient, 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;
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('book.bookService.toast.filesAttachedSummary'),
|
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 => {
|
catchError(error => {
|
||||||
|
|||||||
@@ -328,7 +328,7 @@ export class BookMenuService {
|
|||||||
rejectLabel: this.t.translate('common.no'),
|
rejectLabel: this.t.translate('common.no'),
|
||||||
accept: () => {
|
accept: () => {
|
||||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.removingFromShelves', {count}));
|
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>();
|
const allShelfIds = new Set<number>();
|
||||||
books.forEach(b => b.shelves?.forEach(s => {
|
books.forEach(b => b.shelves?.forEach(s => {
|
||||||
if (s.id) allShelfIds.add(s.id);
|
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 {Book, BookMetadata, BulkMetadataUpdateRequest, MetadataUpdateWrapper} from '../model/book.model';
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {BookStateService} from './book-state.service';
|
|
||||||
import {BookSocketService} from './book-socket.service';
|
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
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({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -19,23 +18,25 @@ export class BookMetadataManageService {
|
|||||||
|
|
||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private bookStateService = inject(BookStateService);
|
private queryClient = inject(QueryClient);
|
||||||
private bookSocketService = inject(BookSocketService);
|
|
||||||
private bookService = inject(BookService);
|
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean, replaceMode: 'REPLACE_ALL' | 'REPLACE_WHEN_PROVIDED' = 'REPLACE_ALL'): Observable<BookMetadata> {
|
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);
|
const params = new HttpParams().set('mergeCategories', mergeCategories.toString()).set('replaceMode', replaceMode);
|
||||||
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
|
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
|
||||||
map(updatedMetadata => {
|
tap(updatedMetadata => {
|
||||||
this.bookSocketService.handleBookMetadataUpdate(bookId!, updatedMetadata);
|
if (bookId != null) {
|
||||||
return updatedMetadata;
|
patchBookMetadataInCache(this.queryClient, bookId, updatedMetadata);
|
||||||
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateBooksMetadata(request: BulkMetadataUpdateRequest): Observable<void> {
|
updateBooksMetadata(request: BulkMetadataUpdateRequest): Observable<void> {
|
||||||
return this.http.put(`${this.url}/bulk-edit-metadata`, request).pipe(
|
return this.http.put(`${this.url}/bulk-edit-metadata`, request).pipe(
|
||||||
|
tap(() => {
|
||||||
|
invalidateBooksQuery(this.queryClient);
|
||||||
|
}),
|
||||||
map(() => void 0)
|
map(() => void 0)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -43,16 +44,15 @@ export class BookMetadataManageService {
|
|||||||
toggleAllLock(bookIds: Set<number>, lock: string): Observable<void> {
|
toggleAllLock(bookIds: Set<number>, lock: string): Observable<void> {
|
||||||
const requestBody = {
|
const requestBody = {
|
||||||
bookIds: Array.from(bookIds),
|
bookIds: Array.from(bookIds),
|
||||||
lock: lock
|
lock
|
||||||
};
|
};
|
||||||
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
|
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
|
||||||
tap((updatedMetadataList) => {
|
tap(updatedMetadataList => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
updatedMetadataList.forEach(metadata => {
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
if (metadata.bookId != null) {
|
||||||
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
|
patchBookMetadataInCache(this.queryClient, metadata.bookId, metadata);
|
||||||
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
|
}
|
||||||
});
|
});
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
}),
|
}),
|
||||||
map(() => void 0),
|
map(() => void 0),
|
||||||
catchError((error) => {
|
catchError((error) => {
|
||||||
@@ -64,32 +64,24 @@ export class BookMetadataManageService {
|
|||||||
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
|
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
|
||||||
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
|
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),
|
bookIds: Array.from(bookIdSet),
|
||||||
fieldActions
|
fieldActions
|
||||||
};
|
}).pipe(
|
||||||
|
|
||||||
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
|
|
||||||
tap(() => {
|
tap(() => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
for (const bookId of bookIdSet) {
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
patchBookInCacheWith(this.queryClient, bookId, book => {
|
||||||
if (!bookIdSet.has(book.id)) return book;
|
if (!book.metadata) return book;
|
||||||
const updatedMetadata = {...book.metadata};
|
const updatedMetadata = {...book.metadata} as Record<string, unknown>;
|
||||||
for (const [field, action] of Object.entries(fieldActions)) {
|
for (const [field, action] of Object.entries(fieldActions)) {
|
||||||
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
|
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
|
||||||
if (lockField in updatedMetadata) {
|
if (lockField in updatedMetadata) {
|
||||||
(updatedMetadata as Record<string, unknown>)[lockField] = action === 'LOCK';
|
updatedMetadata[lockField] = action === 'LOCK';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return {...book, metadata: updatedMetadata as BookMetadata};
|
||||||
return {
|
});
|
||||||
...book,
|
}
|
||||||
metadata: updatedMetadata
|
|
||||||
};
|
|
||||||
});
|
|
||||||
this.bookStateService.updateBookState({
|
|
||||||
...currentState,
|
|
||||||
books: updatedBooks as Book[]
|
|
||||||
});
|
|
||||||
}),
|
}),
|
||||||
catchError(error => {
|
catchError(error => {
|
||||||
this.messageService.add({
|
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> {
|
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`, {metadataType, targetValues, valuesToMerge}).pipe(
|
||||||
return this.http.post(`${this.url}/metadata/manage/consolidate`, payload).pipe(
|
|
||||||
tap(() => {
|
tap(() => {
|
||||||
this.bookService.refreshBooks();
|
invalidateBooksQuery(this.queryClient);
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', valuesToDelete: string[]): Observable<unknown> {
|
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`, {metadataType, valuesToDelete}).pipe(
|
||||||
return this.http.post(`${this.url}/metadata/manage/delete`, payload).pipe(
|
|
||||||
tap(() => {
|
tap(() => {
|
||||||
this.bookService.refreshBooks();
|
invalidateBooksQuery(this.queryClient);
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*------------------ Cover Operations ------------------*/
|
|
||||||
|
|
||||||
getUploadCoverUrl(bookId: number): string {
|
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> {
|
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> {
|
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> {
|
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> {
|
getFileMetadata(bookId: number): Observable<BookMetadata> {
|
||||||
@@ -143,37 +143,65 @@ export class BookMetadataManageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
generateCustomCover(bookId: number): Observable<void> {
|
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> {
|
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> {
|
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> {
|
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> {
|
uploadAudiobookCoverFromFile(bookId: number, file: File): Observable<void> {
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
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 {
|
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> {
|
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> {
|
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 {
|
supportsDualCovers(book: Book): boolean {
|
||||||
@@ -187,6 +215,10 @@ export class BookMetadataManageService {
|
|||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
formData.append('bookIds', bookIds.join(','));
|
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 {computed, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, Observable} from 'rxjs';
|
|
||||||
|
|
||||||
export interface BookNavigationState {
|
export interface BookNavigationState {
|
||||||
bookIds: number[];
|
bookIds: number[];
|
||||||
@@ -10,77 +9,69 @@ export interface BookNavigationState {
|
|||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class BookNavigationService {
|
export class BookNavigationService {
|
||||||
private navigationState$ = new BehaviorSubject<BookNavigationState | null>(null);
|
private readonly _navigationState = signal<BookNavigationState | null>(null);
|
||||||
private availableBookIds: number[] = [];
|
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 {
|
setAvailableBookIds(bookIds: number[]): void {
|
||||||
this.availableBookIds = bookIds;
|
this._availableBookIds.set(bookIds);
|
||||||
}
|
|
||||||
|
|
||||||
getAvailableBookIds(): number[] {
|
|
||||||
return this.availableBookIds;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setNavigationContext(bookIds: number[], currentBookId: number): void {
|
setNavigationContext(bookIds: number[], currentBookId: number): void {
|
||||||
const currentIndex = bookIds.indexOf(currentBookId);
|
const currentIndex = bookIds.indexOf(currentBookId);
|
||||||
if (currentIndex !== -1) {
|
if (currentIndex !== -1) {
|
||||||
this.navigationState$.next({bookIds, currentIndex});
|
this._navigationState.set({bookIds, currentIndex});
|
||||||
} else {
|
} 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 {
|
updateCurrentBook(bookId: number): void {
|
||||||
const state = this.navigationState$.value;
|
const state = this.navigationState();
|
||||||
if (state) {
|
if (state) {
|
||||||
const newIndex = state.bookIds.indexOf(bookId);
|
const newIndex = state.bookIds.indexOf(bookId);
|
||||||
if (newIndex !== -1) {
|
if (newIndex !== -1) {
|
||||||
this.navigationState$.next({
|
this._navigationState.set({
|
||||||
...state,
|
...state,
|
||||||
currentIndex: newIndex
|
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 {Observable, Subject} from 'rxjs';
|
||||||
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
|
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
|
||||||
import {Book, BookFileProgress, ReadStatus} from '../model/book.model';
|
import {Book, BookFileProgress, ReadStatus} from '../model/book.model';
|
||||||
import {BookStateService} from './book-state.service';
|
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||||
import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from '../model/book.model';
|
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({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -15,7 +37,7 @@ export class BookPatchService {
|
|||||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||||
|
|
||||||
private http = inject(HttpClient);
|
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 }>();
|
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
|
prev.bookFileId === curr.bookFileId
|
||||||
),
|
),
|
||||||
exhaustMap(payload => {
|
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,
|
bookId: payload.bookId,
|
||||||
epubProgress: {
|
epubProgress: {
|
||||||
cfi: payload.cfi,
|
cfi: payload.cfi,
|
||||||
@@ -36,7 +71,6 @@ export class BookPatchService {
|
|||||||
percentage: payload.percentage
|
percentage: payload.percentage
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Add file-level progress if bookFileId is provided
|
|
||||||
if (payload.bookFileId) {
|
if (payload.bookFileId) {
|
||||||
body.fileProgress = {
|
body.fileProgress = {
|
||||||
bookFileId: payload.bookFileId,
|
bookFileId: payload.bookFileId,
|
||||||
@@ -62,31 +96,33 @@ export class BookPatchService {
|
|||||||
};
|
};
|
||||||
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
|
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
|
||||||
tap(updatedBooks => {
|
tap(updatedBooks => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBooksInCache(this.queryClient, updatedBooks);
|
||||||
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]});
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||||
const body: any = {
|
const body: {
|
||||||
bookId: bookId,
|
bookId: number;
|
||||||
pdfProgress: {
|
pdfProgress: {
|
||||||
page: page,
|
page: number;
|
||||||
percentage: percentage
|
percentage: number;
|
||||||
|
};
|
||||||
|
fileProgress?: {
|
||||||
|
bookFileId: number;
|
||||||
|
positionData: string;
|
||||||
|
progressPercent: number;
|
||||||
|
};
|
||||||
|
} = {
|
||||||
|
bookId,
|
||||||
|
pdfProgress: {
|
||||||
|
page,
|
||||||
|
percentage
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Add file-level progress if bookFileId is provided
|
|
||||||
if (bookFileId) {
|
if (bookFileId) {
|
||||||
body.fileProgress = {
|
body.fileProgress = {
|
||||||
bookFileId: bookFileId,
|
bookFileId,
|
||||||
positionData: String(page),
|
positionData: String(page),
|
||||||
progressPercent: percentage
|
progressPercent: percentage
|
||||||
};
|
};
|
||||||
@@ -99,17 +135,27 @@ export class BookPatchService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||||
const body: any = {
|
const body: {
|
||||||
bookId: bookId,
|
bookId: number;
|
||||||
cbxProgress: {
|
cbxProgress: {
|
||||||
page: page,
|
page: number;
|
||||||
percentage: percentage
|
percentage: number;
|
||||||
|
};
|
||||||
|
fileProgress?: {
|
||||||
|
bookFileId: number;
|
||||||
|
positionData: string;
|
||||||
|
progressPercent: number;
|
||||||
|
};
|
||||||
|
} = {
|
||||||
|
bookId,
|
||||||
|
cbxProgress: {
|
||||||
|
page,
|
||||||
|
percentage
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Add file-level progress if bookFileId is provided
|
|
||||||
if (bookFileId) {
|
if (bookFileId) {
|
||||||
body.fileProgress = {
|
body.fileProgress = {
|
||||||
bookFileId: bookFileId,
|
bookFileId,
|
||||||
positionData: String(page),
|
positionData: String(page),
|
||||||
progressPercent: percentage
|
progressPercent: percentage
|
||||||
};
|
};
|
||||||
@@ -117,38 +163,20 @@ export class BookPatchService {
|
|||||||
return this.http.post<void>(`${this.url}/progress`, body);
|
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> {
|
saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> {
|
||||||
const body = {
|
return this.http.post<void>(`${this.url}/progress`, {
|
||||||
bookId: bookId,
|
bookId,
|
||||||
fileProgress: fileProgress
|
fileProgress
|
||||||
};
|
});
|
||||||
return this.http.post<void>(`${this.url}/progress`, body);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
|
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
|
||||||
const body = {
|
return this.http.post<void>(`${this.url}/progress`, {
|
||||||
bookId: bookId,
|
bookId,
|
||||||
dateFinished: dateFinished
|
dateFinished
|
||||||
};
|
}).pipe(
|
||||||
return this.http.post<void>(`${this.url}/progress`, body).pipe(
|
|
||||||
tap(() => {
|
tap(() => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookFieldsInCache(this.queryClient, [{bookId, fields: {dateFinished: dateFinished || undefined}}]);
|
||||||
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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -159,52 +187,31 @@ export class BookPatchService {
|
|||||||
|
|
||||||
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
|
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
|
||||||
tap(responses => {
|
tap(responses => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
bookId: r.bookId,
|
||||||
const response = responses.find(r => r.bookId === book.id);
|
fields: {
|
||||||
if (response) {
|
...getResetProgressFields(type),
|
||||||
const progressReset: Partial<Book> =
|
readStatus: r.readStatus,
|
||||||
type === 'KOREADER' ? {koreaderProgress: undefined} :
|
readStatusModifiedTime: r.readStatusModifiedTime,
|
||||||
type === 'KOBO' ? {koboProgress: undefined} :
|
dateFinished: r.dateFinished
|
||||||
{epubProgress: undefined, pdfProgress: undefined, cbxProgress: undefined, audiobookProgress: undefined};
|
|
||||||
return {
|
|
||||||
...book,
|
|
||||||
...progressReset,
|
|
||||||
readStatus: response.readStatus,
|
|
||||||
readStatusModifiedTime: response.readStatusModifiedTime,
|
|
||||||
dateFinished: response.dateFinished
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
return book;
|
})));
|
||||||
});
|
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
|
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
|
||||||
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
|
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 => {
|
tap(responses => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
bookId: r.bookId,
|
||||||
const response = responses.find(r => r.bookId === book.id);
|
fields: {readStatus: r.readStatus, readStatusModifiedTime: r.readStatusModifiedTime, dateFinished: r.dateFinished}
|
||||||
if (response) {
|
})));
|
||||||
return {
|
|
||||||
...book,
|
|
||||||
readStatus: response.readStatus,
|
|
||||||
readStatusModifiedTime: response.readStatusModifiedTime,
|
|
||||||
dateFinished: response.dateFinished
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return book;
|
|
||||||
});
|
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -214,18 +221,10 @@ export class BookPatchService {
|
|||||||
|
|
||||||
return this.http.post<PersonalRatingUpdateResponse[]>(`${this.url}/reset-personal-rating`, ids).pipe(
|
return this.http.post<PersonalRatingUpdateResponse[]>(`${this.url}/reset-personal-rating`, ids).pipe(
|
||||||
tap(responses => {
|
tap(responses => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
bookId: r.bookId,
|
||||||
const response = responses.find(r => r.bookId === book.id);
|
fields: {personalRating: r.personalRating}
|
||||||
if (response) {
|
})));
|
||||||
return {
|
|
||||||
...book,
|
|
||||||
personalRating: response.personalRating
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return book;
|
|
||||||
});
|
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -235,28 +234,20 @@ export class BookPatchService {
|
|||||||
|
|
||||||
return this.http.put<PersonalRatingUpdateResponse[]>(`${this.url}/personal-rating`, {ids, rating}).pipe(
|
return this.http.put<PersonalRatingUpdateResponse[]>(`${this.url}/personal-rating`, {ids, rating}).pipe(
|
||||||
tap(responses => {
|
tap(responses => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
bookId: r.bookId,
|
||||||
const response = responses.find(r => r.bookId === book.id);
|
fields: {personalRating: r.personalRating}
|
||||||
if (response) {
|
})));
|
||||||
return {
|
|
||||||
...book,
|
|
||||||
personalRating: response.personalRating
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return book;
|
|
||||||
});
|
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateLastReadTime(bookId: number): void {
|
updateLastReadTime(bookId: number): void {
|
||||||
const timestamp = new Date().toISOString();
|
const timestamp = new Date().toISOString();
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||||
const updatedBooks = (currentState.books || []).map(book =>
|
(current ?? []).map(book =>
|
||||||
book.id === bookId ? {...book, lastReadTime: timestamp} : 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 {inject, Injectable} from '@angular/core';
|
||||||
import {BookStateService} from './book-state.service';
|
import {Book} from '../model/book.model';
|
||||||
import {Book, BookMetadata} 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({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class BookSocketService {
|
export class BookSocketService {
|
||||||
private bookStateService = inject(BookStateService);
|
private queryClient = inject(QueryClient);
|
||||||
|
|
||||||
handleNewlyCreatedBook(book: Book): void {
|
handleNewlyCreatedBook(book: Book): void {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
addBookToCache(this.queryClient, book);
|
||||||
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});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleRemovedBookIds(removedBookIds: number[]): void {
|
handleRemovedBookIds(removedBookIds: number[]): void {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
invalidateBooksQuery(this.queryClient);
|
||||||
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id));
|
removeBookQueries(this.queryClient, removedBookIds);
|
||||||
this.bookStateService.updateBookState({...currentState, books: filteredBooks});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleBookUpdate(updatedBook: Book): void {
|
handleBookUpdate(updatedBook: Book): void {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBooksInCache(this.queryClient, [updatedBook]);
|
||||||
const updatedBooks = (currentState.books || []).map(book =>
|
|
||||||
book.id === updatedBook.id ? updatedBook : book
|
|
||||||
);
|
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMultipleBookUpdates(updatedBooks: Book[]): void {
|
handleMultipleBookUpdates(updatedBooks: Book[]): void {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBooksInCache(this.queryClient, updatedBooks);
|
||||||
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});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata): void {
|
handleBookMetadataUpdate(bookId: number): void {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
invalidateBooksQuery(this.queryClient);
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
invalidateBookDetailQueries(this.queryClient, [bookId]);
|
||||||
return book.id === bookId ? {...book, metadata: updatedMetadata} : book;
|
|
||||||
});
|
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
||||||
if (!patches || patches.length === 0) return;
|
if (!patches || patches.length === 0) return;
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
const patchMap = new Map(patches.map(p => [p.id, p.coverUpdatedOn]));
|
||||||
const books = currentState.books || [];
|
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||||
patches.forEach(p => {
|
(current ?? []).map(book => {
|
||||||
const index = books.findIndex(b => b.id === p.id);
|
const coverUpdatedOn = patchMap.get(book.id);
|
||||||
if (index !== -1 && books[index].metadata) {
|
return coverUpdatedOn && book.metadata
|
||||||
books[index].metadata.coverUpdatedOn = p.coverUpdatedOn;
|
? {...book, metadata: {...book.metadata, coverUpdatedOn}}
|
||||||
}
|
: book;
|
||||||
});
|
})
|
||||||
this.bookStateService.updateBookState({...currentState, books});
|
);
|
||||||
|
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 {computed, effect, inject, Injectable} from '@angular/core';
|
||||||
import {first, Observable, of, throwError} from 'rxjs';
|
import {first, from, lastValueFrom, Observable, throwError} from 'rxjs';
|
||||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
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 {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 {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {ResetProgressType} from '../../../shared/constants/reset-progress-type';
|
import {ResetProgressType} from '../../../shared/constants/reset-progress-type';
|
||||||
import {AuthService} from '../../../shared/service/auth.service';
|
import {AuthService} from '../../../shared/service/auth.service';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {BookStateService} from './book-state.service';
|
|
||||||
import {BookSocketService} from './book-socket.service';
|
import {BookSocketService} from './book-socket.service';
|
||||||
import {BookPatchService} from './book-patch.service';
|
import {BookPatchService} from './book-patch.service';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
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({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -25,156 +34,139 @@ export class BookService {
|
|||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private authService = inject(AuthService);
|
private authService = inject(AuthService);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private bookStateService = inject(BookStateService);
|
|
||||||
private bookSocketService = inject(BookSocketService);
|
private bookSocketService = inject(BookSocketService);
|
||||||
private bookPatchService = inject(BookPatchService);
|
private bookPatchService = inject(BookPatchService);
|
||||||
|
private queryClient = inject(QueryClient);
|
||||||
private readonly t = inject(TranslocoService);
|
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() {
|
constructor() {
|
||||||
this.authService.token$.pipe(
|
effect(() => {
|
||||||
distinctUntilChanged()
|
const token = this.token();
|
||||||
).subscribe(token => {
|
|
||||||
if (token === null) {
|
if (token === null) {
|
||||||
this.bookStateService.resetBookState();
|
this.queryClient.removeQueries({queryKey: BOOKS_QUERY_KEY});
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/*------------------ State Management ------------------*/
|
private getBooksQueryOptions() {
|
||||||
|
return queryOptions({
|
||||||
bookState$ = this.bookStateService.bookState$.pipe(
|
queryKey: BOOKS_QUERY_KEY,
|
||||||
tap(state => {
|
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url))
|
||||||
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 fetchBooks(): Observable<Book[]> {
|
bookDetailQueryOptions(bookId: number, withDescription: boolean) {
|
||||||
return this.http.get<Book[]>(this.url).pipe(
|
return queryOptions({
|
||||||
map(bookList => {
|
queryKey: bookDetailQueryKey(bookId, withDescription),
|
||||||
this.bookStateService.updateBookState({
|
queryFn: () => lastValueFrom(this.http.get<Book>(`${this.url}/${bookId}`, {
|
||||||
books: bookList,
|
params: {
|
||||||
loaded: true,
|
withDescription: withDescription.toString()
|
||||||
error: null,
|
}
|
||||||
});
|
}))
|
||||||
return bookList;
|
});
|
||||||
}),
|
|
||||||
catchError(error => {
|
|
||||||
const curr = this.bookStateService.getCurrentBookState();
|
|
||||||
this.bookStateService.updateBookState({
|
|
||||||
books: curr.books,
|
|
||||||
loaded: true,
|
|
||||||
error: error.message,
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshBooks(): void {
|
ensureBookDetail(bookId: number, withDescription: boolean): Promise<Book> {
|
||||||
this.http.get<Book[]>(this.url).pipe(
|
return this.queryClient.ensureQueryData(this.bookDetailQueryOptions(bookId, withDescription));
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
removeBooksByLibraryId(libraryId: number): void {
|
private getBookRecommendationsQueryOptions(bookId: number, limit: number) {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
return queryOptions({
|
||||||
const currentBooks = currentState.books || [];
|
queryKey: bookRecommendationsQueryKey(bookId, limit),
|
||||||
const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId);
|
queryFn: () => lastValueFrom(this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
|
||||||
this.bookStateService.updateBookState({...currentState, books: filteredBooks});
|
params: {limit: limit.toString()}
|
||||||
|
}))
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
removeBooksFromShelf(shelfId: number): void {
|
removeBooksFromShelf(shelfId: number): void {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||||
const currentBooks = currentState.books || [];
|
(current ?? []).map(book => ({
|
||||||
const updatedBooks = currentBooks.map(book => ({
|
...book,
|
||||||
...book,
|
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
|
||||||
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
|
}))
|
||||||
}));
|
);
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*------------------ Book Retrieval ------------------*/
|
/*------------------ Book Retrieval ------------------*/
|
||||||
|
|
||||||
getBookByIdFromState(bookId: number): Book | undefined {
|
findBookById(bookId: number): Book | undefined {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
return this.books().find(book => +book.id === +bookId);
|
||||||
return currentState.books?.find(book => +book.id === +bookId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getBooksByIdsFromState(bookIds: number[]): Book[] {
|
getBooksByIds(bookIds: number[]): Book[] {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
if (bookIds.length === 0) return [];
|
||||||
if (!currentState.books || bookIds.length === 0) return [];
|
|
||||||
|
|
||||||
const idSet = new Set(bookIds.map(id => +id));
|
const idSet = new Set(bookIds.map(id => +id));
|
||||||
return currentState.books.filter(book => idSet.has(+book.id));
|
return this.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()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getBooksInSeries(bookId: number): Observable<Book[]> {
|
getBooksInSeries(bookId: number): Observable<Book[]> {
|
||||||
return this.bookStateService.bookState$.pipe(
|
return from(this.queryClient.ensureQueryData(this.getBooksQueryOptions())).pipe(
|
||||||
filter(state => state.loaded),
|
map(books => {
|
||||||
first(),
|
const currentBook = books.find(book => book.id === bookId);
|
||||||
map(state => {
|
if (!currentBook?.metadata?.seriesName) {
|
||||||
const allBooks = state.books || [];
|
|
||||||
const currentBook = allBooks.find(b => b.id === bookId);
|
|
||||||
|
|
||||||
if (!currentBook || !currentBook.metadata?.seriesName) {
|
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const seriesName = currentBook.metadata.seriesName.toLowerCase();
|
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[]> {
|
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
|
||||||
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
|
return from(this.queryClient.ensureQueryData(this.getBookRecommendationsQueryOptions(bookId, limit)));
|
||||||
params: {limit: limit.toString()}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*------------------ Book Operations ------------------*/
|
/*------------------ Book Operations ------------------*/
|
||||||
@@ -185,16 +177,9 @@ export class BookService {
|
|||||||
|
|
||||||
return this.http.delete<BookDeletionResponse>(this.url, {params}).pipe(
|
return this.http.delete<BookDeletionResponse>(this.url, {params}).pipe(
|
||||||
tap(response => {
|
tap(response => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
const deletedIds = response.deleted.length > 0 ? response.deleted : idList;
|
||||||
const remainingBooks = (currentState.books || []).filter(
|
invalidateBooksQuery(this.queryClient);
|
||||||
book => !ids.has(book.id)
|
removeBookQueries(this.queryClient, deletedIds);
|
||||||
);
|
|
||||||
|
|
||||||
this.bookStateService.updateBookState({
|
|
||||||
books: remainingBooks,
|
|
||||||
loaded: true,
|
|
||||||
error: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.failedFileDeletions?.length > 0) {
|
if (response.failedFileDeletions?.length > 0) {
|
||||||
this.messageService.add({
|
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[]> {
|
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(
|
return this.bookPatchService.updateBookShelves(bookIds, shelvesToAssign, shelvesToUnassign);
|
||||||
catchError(error => {
|
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
|
||||||
this.bookStateService.updateBookState({...currentState, error: error.message});
|
|
||||||
throw error;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
createPhysicalBook(request: CreatePhysicalBookRequest): Observable<Book> {
|
createPhysicalBook(request: CreatePhysicalBookRequest): Observable<Book> {
|
||||||
return this.http.post<Book>(`${this.url}/physical`, request).pipe(
|
return this.http.post<Book>(`${this.url}/physical`, request).pipe(
|
||||||
tap(newBook => {
|
tap(newBook => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
invalidateBooksQuery(this.queryClient);
|
||||||
const updatedBooks = [...(currentState.books || []), newBook];
|
|
||||||
this.bookStateService.updateBookState({
|
|
||||||
...currentState,
|
|
||||||
books: updatedBooks
|
|
||||||
});
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('book.bookService.toast.physicalBookCreatedSummary'),
|
summary: this.t.translate('book.bookService.toast.physicalBookCreatedSummary'),
|
||||||
@@ -260,9 +234,7 @@ export class BookService {
|
|||||||
togglePhysicalFlag(bookId: number, physical: boolean): Observable<Book> {
|
togglePhysicalFlag(bookId: number, physical: boolean): Observable<Book> {
|
||||||
return this.http.patch<Book>(`${this.url}/${bookId}/physical`, null, {params: {physical}}).pipe(
|
return this.http.patch<Book>(`${this.url}/${bookId}/physical`, null, {params: {physical}}).pipe(
|
||||||
tap(updatedBook => {
|
tap(updatedBook => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
patchBooksInCache(this.queryClient, [updatedBook]);
|
||||||
const updatedBooks = (currentState.books || []).map(b => b.id === bookId ? {...b, isPhysical: physical} : b);
|
|
||||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -270,9 +242,7 @@ export class BookService {
|
|||||||
/*------------------ Reading & Viewer Settings ------------------*/
|
/*------------------ Reading & Viewer Settings ------------------*/
|
||||||
|
|
||||||
readBook(bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
|
readBook(bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
|
||||||
const book = this.bookStateService
|
const book = this.findBookById(bookId);
|
||||||
.getCurrentBookState()
|
|
||||||
.books?.find(b => b.id === bookId);
|
|
||||||
|
|
||||||
if (!book) {
|
if (!book) {
|
||||||
console.error('Book not found');
|
console.error('Book not found');
|
||||||
@@ -283,7 +253,7 @@ export class BookService {
|
|||||||
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;
|
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;
|
||||||
|
|
||||||
let baseUrl: string | null = null;
|
let baseUrl: string | null = null;
|
||||||
let queryParams: Record<string, any> = {};
|
const queryParams: Partial<{streaming: true; bookType: BookType}> = {};
|
||||||
|
|
||||||
switch (bookType) {
|
switch (bookType) {
|
||||||
case 'PDF':
|
case 'PDF':
|
||||||
@@ -389,6 +359,10 @@ export class BookService {
|
|||||||
this.bookSocketService.handleMultipleBookUpdates(updatedBooks);
|
this.bookSocketService.handleMultipleBookUpdates(updatedBooks);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
handleBookMetadataUpdate(bookId: number): void {
|
||||||
|
this.bookSocketService.handleBookMetadataUpdate(bookId);
|
||||||
|
}
|
||||||
|
|
||||||
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
||||||
this.bookSocketService.handleMultipleBookCoverPatches(patches);
|
this.bookSocketService.handleMultipleBookCoverPatches(patches);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,27 @@
|
|||||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {LibraryHealthService} from './library-health.service';
|
|
||||||
import {HttpClient} from '@angular/common/http';
|
import {HttpClient} from '@angular/common/http';
|
||||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
|
||||||
import {of, Subject} from 'rxjs';
|
import {of, Subject} from 'rxjs';
|
||||||
import {IMessage} from '@stomp/rx-stomp';
|
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', () => {
|
describe('LibraryHealthService', () => {
|
||||||
let service: LibraryHealthService;
|
let service: LibraryHealthService;
|
||||||
|
let queryClient: QueryClient;
|
||||||
let httpGetSpy: ReturnType<typeof vi.fn>;
|
let httpGetSpy: ReturnType<typeof vi.fn>;
|
||||||
let wsSubject: Subject<IMessage>;
|
let wsSubject: Subject<IMessage>;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
httpGetSpy = vi.fn().mockReturnValue(of({}));
|
httpGetSpy = vi.fn().mockReturnValue(of({}));
|
||||||
wsSubject = new Subject<IMessage>();
|
wsSubject = new Subject<IMessage>();
|
||||||
|
queryClient = new QueryClient();
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
|
provideTanStackQuery(queryClient),
|
||||||
LibraryHealthService,
|
LibraryHealthService,
|
||||||
{provide: HttpClient, useValue: {get: httpGetSpy}},
|
{provide: HttpClient, useValue: {get: httpGetSpy}},
|
||||||
{provide: RxStompService, useValue: {watch: vi.fn(() => wsSubject.asObservable())}},
|
{provide: RxStompService, useValue: {watch: vi.fn(() => wsSubject.asObservable())}},
|
||||||
@@ -26,66 +31,52 @@ describe('LibraryHealthService', () => {
|
|||||||
service = TestBed.inject(LibraryHealthService);
|
service = TestBed.inject(LibraryHealthService);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch initial health on initialize', () => {
|
async function initializeService(): Promise<void> {
|
||||||
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
const fetchQuerySpy = vi.spyOn(queryClient, 'fetchQuery');
|
||||||
service.initialize();
|
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}));
|
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
||||||
service.initialize();
|
|
||||||
|
|
||||||
const results: boolean[] = [];
|
await initializeService();
|
||||||
service.isUnhealthy$(2).subscribe(v => results.push(v));
|
|
||||||
|
|
||||||
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}));
|
httpGetSpy.mockReturnValue(of({1: true}));
|
||||||
service.initialize();
|
|
||||||
|
|
||||||
const results: boolean[] = [];
|
await initializeService();
|
||||||
service.isUnhealthy$(1).subscribe(v => results.push(v));
|
|
||||||
|
|
||||||
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({}));
|
httpGetSpy.mockReturnValue(of({}));
|
||||||
service.initialize();
|
|
||||||
|
|
||||||
const results: boolean[] = [];
|
await initializeService();
|
||||||
service.isUnhealthy$(99).subscribe(v => results.push(v));
|
|
||||||
|
|
||||||
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}));
|
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);
|
wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage);
|
||||||
|
|
||||||
expect(results[results.length - 1]).toBe(true);
|
expect(service.isUnhealthy(1)).toBe(true);
|
||||||
});
|
expect(service.health()).toEqual({1: false});
|
||||||
|
|
||||||
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);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,33 +1,43 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {computed, inject, Injectable} from '@angular/core';
|
||||||
import {HttpClient} from '@angular/common/http';
|
import {HttpClient} from '@angular/common/http';
|
||||||
import {BehaviorSubject, Observable} from 'rxjs';
|
import {lastValueFrom} from 'rxjs';
|
||||||
import {distinctUntilChanged, map} from 'rxjs/operators';
|
|
||||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
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'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class LibraryHealthService {
|
export class LibraryHealthService {
|
||||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`;
|
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`;
|
||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private rxStompService = inject(RxStompService);
|
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 {
|
initialize(): void {
|
||||||
this.http.get<Record<number, boolean>>(this.url).subscribe(health => {
|
void this.queryClient.fetchQuery(this.getHealthQueryOptions());
|
||||||
this.healthSubject.next(health);
|
|
||||||
});
|
|
||||||
|
|
||||||
this.rxStompService.watch('/topic/library-health').subscribe(msg => {
|
this.rxStompService.watch('/topic/library-health').subscribe(msg => {
|
||||||
const payload = JSON.parse(msg.body);
|
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> {
|
isUnhealthy(libraryId: number): boolean {
|
||||||
return this.healthSubject.pipe(
|
return this.health()[libraryId] === false;
|
||||||
map(health => health[libraryId] === false),
|
|
||||||
distinctUntilChanged()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {HttpClient} from '@angular/common/http';
|
||||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
import {from, lastValueFrom, Observable} from 'rxjs';
|
||||||
import {catchError, distinctUntilChanged, finalize, map, shareReplay, tap} from 'rxjs/operators';
|
import {tap} from 'rxjs/operators';
|
||||||
|
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
import {Library} from '../model/library.model';
|
import {Library} from '../model/library.model';
|
||||||
import {LibraryState} from '../model/state/library-state.model';
|
|
||||||
import {BookService} from './book.service';
|
import {BookService} from './book.service';
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {AuthService} from '../../../shared/service/auth.service';
|
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'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class LibraryService {
|
export class LibraryService {
|
||||||
@@ -15,72 +17,56 @@ export class LibraryService {
|
|||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private authService = inject(AuthService);
|
private authService = inject(AuthService);
|
||||||
|
private queryClient = inject(QueryClient);
|
||||||
|
private readonly token = this.authService.token;
|
||||||
|
|
||||||
private libraryStateSubject = new BehaviorSubject<LibraryState>({
|
readonly largeLibraryLoading = signal<{ isLoading: boolean; expectedCount: number }>({
|
||||||
libraries: null,
|
|
||||||
loaded: false,
|
|
||||||
error: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
private largeLibraryLoadingSubject = new BehaviorSubject<{ isLoading: boolean; expectedCount: number }>({
|
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
expectedCount: 0
|
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() {
|
constructor() {
|
||||||
this.authService.token$.pipe(
|
effect(() => {
|
||||||
distinctUntilChanged()
|
const token = this.token();
|
||||||
).subscribe(token => {
|
|
||||||
if (token === null) {
|
if (token === null) {
|
||||||
this.libraryStateSubject.next({
|
this.queryClient.removeQueries({queryKey: LIBRARIES_QUERY_KEY});
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
libraryState$ = this.libraryStateSubject.asObservable().pipe(
|
private getLibrariesQueryOptions() {
|
||||||
tap(state => {
|
return queryOptions({
|
||||||
if (!state.loaded && !state.error && !this.loading$) {
|
queryKey: LIBRARIES_QUERY_KEY,
|
||||||
this.loading$ = this.fetchLibraries().pipe(
|
queryFn: async () => {
|
||||||
shareReplay(1),
|
const libraries = await lastValueFrom(this.http.get<Library[]>(this.url));
|
||||||
finalize(() => (this.loading$ = null))
|
return this.sortLibraries(libraries);
|
||||||
);
|
|
||||||
this.loading$.subscribe();
|
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
);
|
}
|
||||||
|
|
||||||
private fetchLibraries(): Observable<Library[]> {
|
private getLibraryFormatCountsQueryOptions(libraryId: number) {
|
||||||
return this.http.get<Library[]>(this.url).pipe(
|
return queryOptions({
|
||||||
tap(libs => this.libraryStateSubject.next({
|
queryKey: libraryFormatCountsQueryKey(libraryId),
|
||||||
libraries: this.sortLibraries(libs),
|
queryFn: () => lastValueFrom(this.http.get<Record<string, number>>(`${this.url}/${libraryId}/format-counts`))
|
||||||
loaded: true,
|
});
|
||||||
error: null,
|
|
||||||
})),
|
|
||||||
catchError(err => {
|
|
||||||
const current = this.libraryStateSubject.value;
|
|
||||||
this.libraryStateSubject.next({libraries: current.libraries, loaded: true, error: err.message});
|
|
||||||
throw err;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
scanLibraryPaths(lib: Library): Observable<number> {
|
scanLibraryPaths(lib: Library): Observable<number> {
|
||||||
@@ -89,23 +75,17 @@ export class LibraryService {
|
|||||||
|
|
||||||
createLibrary(lib: Library): Observable<Library> {
|
createLibrary(lib: Library): Observable<Library> {
|
||||||
return this.http.post<Library>(this.url, lib).pipe(
|
return this.http.post<Library>(this.url, lib).pipe(
|
||||||
map(created => {
|
tap(() => {
|
||||||
const curr = this.libraryStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||||
const updated = curr.libraries ? [...curr.libraries, created] : [created];
|
|
||||||
this.libraryStateSubject.next({...curr, libraries: this.sortLibraries(updated)});
|
|
||||||
return created;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateLibrary(lib: Library, id?: number): Observable<Library> {
|
updateLibrary(lib: Library, id?: number): Observable<Library> {
|
||||||
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
|
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
|
||||||
map(updated => {
|
tap(() => {
|
||||||
const curr = this.libraryStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||||
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
|
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||||
this.libraryStateSubject.next({...curr, libraries: this.sortLibraries(list)});
|
|
||||||
this.bookService.refreshBooks();
|
|
||||||
return updated;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -113,25 +93,17 @@ export class LibraryService {
|
|||||||
deleteLibrary(id: number): Observable<void> {
|
deleteLibrary(id: number): Observable<void> {
|
||||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||||
tap(() => {
|
tap(() => {
|
||||||
this.bookService.removeBooksByLibraryId(id);
|
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||||
const curr = this.libraryStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||||
const filtered = curr.libraries?.filter(l => l.id !== id) || [];
|
this.queryClient.removeQueries({queryKey: libraryFormatCountsQueryKey(id), exact: true});
|
||||||
this.libraryStateSubject.next({...curr, libraries: filtered});
|
|
||||||
}),
|
|
||||||
catchError(err => {
|
|
||||||
const curr = this.libraryStateSubject.value;
|
|
||||||
this.libraryStateSubject.next({...curr, error: err.message});
|
|
||||||
return of();
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshLibrary(id: number): Observable<void> {
|
refreshLibrary(id: number): Observable<void> {
|
||||||
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
|
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
|
||||||
catchError(err => {
|
tap(() => {
|
||||||
const curr = this.libraryStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||||
this.libraryStateSubject.next({...curr, error: err.message});
|
|
||||||
throw err;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -140,42 +112,34 @@ export class LibraryService {
|
|||||||
return this.http
|
return this.http
|
||||||
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
|
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
|
||||||
.pipe(
|
.pipe(
|
||||||
map(updated => {
|
tap(() => {
|
||||||
const curr = this.libraryStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||||
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
|
|
||||||
this.libraryStateSubject.next({...curr, libraries: this.sortLibraries(list)});
|
|
||||||
return updated;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
doesLibraryExistByName(name: string): boolean {
|
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 {
|
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[] {
|
getBookCountValue(libraryId: number): number {
|
||||||
return this.libraryStateSubject.value.libraries || [];
|
return this.bookService.books().filter(book => book.libraryId === libraryId).length;
|
||||||
}
|
|
||||||
|
|
||||||
getBookCount(libraryId: number): Observable<number> {
|
|
||||||
return this.bookService.bookState$.pipe(
|
|
||||||
map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
|
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
|
||||||
this.largeLibraryLoadingSubject.next({ isLoading, expectedCount });
|
this.largeLibraryLoading.set({ isLoading, expectedCount });
|
||||||
}
|
}
|
||||||
|
|
||||||
getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> {
|
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[] {
|
private sortLibraries(libraries: Library[]): Library[] {
|
||||||
return [...libraries].sort((a, b) => a.name.localeCompare(b.name));
|
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 {HttpClient} from '@angular/common/http';
|
||||||
import {BehaviorSubject, combineLatest, Observable, of} from 'rxjs';
|
import {lastValueFrom, Observable} from 'rxjs';
|
||||||
import {tap, catchError, map, shareReplay, finalize} from 'rxjs/operators';
|
import {tap} from 'rxjs/operators';
|
||||||
|
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
import {Shelf} from '../model/shelf.model';
|
import {Shelf} from '../model/shelf.model';
|
||||||
import {ShelfState} from '../model/state/shelf-state.model';
|
|
||||||
import {BookService} from './book.service';
|
import {BookService} from './book.service';
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {Book} from '../model/book.model';
|
import {Book} from '../model/book.model';
|
||||||
import {UserService} from '../../settings/user-management/user.service';
|
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'})
|
@Injectable({providedIn: 'root'})
|
||||||
export class ShelfService {
|
export class ShelfService {
|
||||||
@@ -16,65 +19,60 @@ export class ShelfService {
|
|||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private userService = inject(UserService);
|
private userService = inject(UserService);
|
||||||
|
private authService = inject(AuthService);
|
||||||
|
private queryClient = inject(QueryClient);
|
||||||
|
private readonly token = this.authService.token;
|
||||||
|
|
||||||
private shelfStateSubject = new BehaviorSubject<ShelfState>({
|
private shelvesQuery = injectQuery(() => ({
|
||||||
shelves: null,
|
...this.getShelvesQueryOptions(),
|
||||||
loaded: false,
|
enabled: !!this.token(),
|
||||||
error: null,
|
}));
|
||||||
|
|
||||||
|
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(
|
constructor() {
|
||||||
tap(state => {
|
effect(() => {
|
||||||
if (!state.loaded && !state.error && !this.loading$) {
|
const token = this.token();
|
||||||
this.loading$ = this.fetchShelves().pipe(
|
if (token === null) {
|
||||||
shareReplay(1),
|
this.queryClient.removeQueries({queryKey: SHELVES_QUERY_KEY});
|
||||||
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: () => {
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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> {
|
createShelf(shelf: Shelf): Observable<Shelf> {
|
||||||
return this.http.post<Shelf>(this.url, shelf).pipe(
|
return this.http.post<Shelf>(this.url, shelf).pipe(
|
||||||
map(newShelf => {
|
tap(() => {
|
||||||
const curr = this.shelfStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
|
||||||
const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
|
|
||||||
this.shelfStateSubject.next({...curr, shelves: updated});
|
|
||||||
return newShelf;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
|
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
|
||||||
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
|
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
|
||||||
map(updated => {
|
tap(() => {
|
||||||
const curr = this.shelfStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
|
||||||
const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated];
|
|
||||||
this.shelfStateSubject.next({...curr, shelves: list});
|
|
||||||
return updated;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -83,56 +81,33 @@ export class ShelfService {
|
|||||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||||
tap(() => {
|
tap(() => {
|
||||||
this.bookService.removeBooksFromShelf(id);
|
this.bookService.removeBooksFromShelf(id);
|
||||||
const curr = this.shelfStateSubject.value;
|
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
|
||||||
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();
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getShelfById(id: number): Shelf | undefined {
|
getBookCountValue(shelfId: number): number {
|
||||||
return this.shelfStateSubject.value.shelves?.find(s => s.id === id);
|
const shelf = this.shelves().find(currentShelf => currentShelf.id === shelfId);
|
||||||
}
|
if (!shelf) return 0;
|
||||||
|
|
||||||
getShelvesFromState(): Shelf[] {
|
const currentUserId = this.userService.getCurrentUser()?.id;
|
||||||
return this.shelfStateSubject.value.shelves ?? [];
|
const isOwner = currentUserId === shelf.userId;
|
||||||
}
|
|
||||||
|
|
||||||
getBookCount(shelfId: number): Observable<number> {
|
if (isOwner) {
|
||||||
return combineLatest([
|
return this.bookService.books().filter(book =>
|
||||||
this.shelfState$,
|
book.shelves?.some(currentShelf => currentShelf.id === shelfId)
|
||||||
this.userService.userState$,
|
).length;
|
||||||
this.bookService.bookState$
|
}
|
||||||
]).pipe(
|
|
||||||
map(([shelfState, userState, bookState]) => {
|
|
||||||
const shelf = shelfState.shelves?.find(s => s.id === shelfId);
|
|
||||||
if (!shelf) return 0;
|
|
||||||
|
|
||||||
const isOwner = userState.user?.id === shelf.userId;
|
return shelf.bookCount || 0;
|
||||||
|
|
||||||
if (isOwner) {
|
|
||||||
return (bookState.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length;
|
|
||||||
} else {
|
|
||||||
return shelf.bookCount || 0;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getBooksOnShelf(shelfId: number): Observable<Book[]> {
|
getBooksOnShelf(shelfId: number): Observable<Book[]> {
|
||||||
return this.http.get<Book[]>(`${this.url}/${shelfId}/books`);
|
return this.http.get<Book[]>(`${this.url}/${shelfId}/books`);
|
||||||
}
|
}
|
||||||
|
|
||||||
getUnshelvedBookCount(): Observable<number> {
|
getUnshelvedBookCountValue(): number {
|
||||||
return this.bookService.bookState$.pipe(
|
return this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length;
|
||||||
map(state =>
|
|
||||||
(state.books || []).filter(b => !b.shelves || b.shelves.length === 0).length
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-14
@@ -1,7 +1,5 @@
|
|||||||
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
|
import {Component, DestroyRef, effect, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
|
||||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
|
||||||
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||||
import {filter} from 'rxjs/operators';
|
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {NgClass} from '@angular/common';
|
import {NgClass} from '@angular/common';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
@@ -79,18 +77,15 @@ export class BookdropFileMetadataPickerComponent implements OnInit {
|
|||||||
|
|
||||||
metadataFieldsBottom: MetadataFieldConfig[] = getBottomFields();
|
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 {
|
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 {
|
copyMissing(): void {
|
||||||
|
|||||||
+13
-17
@@ -1,6 +1,6 @@
|
|||||||
import {Component, DestroyRef, inject, OnInit, QueryList, ViewChildren} from '@angular/core';
|
import {Component, DestroyRef, inject, OnInit, QueryList, ViewChildren} from '@angular/core';
|
||||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
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 {PageTitleService} from "../../../../shared/service/page-title.service";
|
||||||
|
|
||||||
import {BookdropFile, BookdropFinalizePayload, BookdropFinalizeResult, BookdropService, FileExtractionResult, BulkEditRequest as BackendBulkEditRequest, BulkEditResult as BackendBulkEditResult} from '../../service/bookdrop.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 {Tooltip} from 'primeng/tooltip';
|
||||||
import {Divider} from 'primeng/divider';
|
import {Divider} from 'primeng/divider';
|
||||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||||
import {Observable, Subscription} from 'rxjs';
|
import {Subscription} from 'rxjs';
|
||||||
import {InputGroup} from 'primeng/inputgroup';
|
import {InputGroup} from 'primeng/inputgroup';
|
||||||
import {InputGroupAddonModule} from 'primeng/inputgroupaddon';
|
import {InputGroupAddonModule} from 'primeng/inputgroupaddon';
|
||||||
import {AppSettings} from '../../../../shared/model/app-settings.model';
|
|
||||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||||
import {BookMetadata} from '../../../book/model/book.model';
|
import {BookMetadata} from '../../../book/model/book.model';
|
||||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||||
@@ -79,14 +79,12 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
|
|
||||||
@ViewChildren('metadataPicker') metadataPickers!: QueryList<BookdropFileMetadataPickerComponent>;
|
@ViewChildren('metadataPicker') metadataPickers!: QueryList<BookdropFileMetadataPickerComponent>;
|
||||||
|
|
||||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
|
||||||
private routerSub!: Subscription;
|
private routerSub!: Subscription;
|
||||||
|
|
||||||
uploadPattern = '';
|
uploadPattern = '';
|
||||||
_defaultLibraryId: string | null = null;
|
_defaultLibraryId: string | null = null;
|
||||||
|
|
||||||
defaultPathId: string | null = null;
|
defaultPathId: string | null = null;
|
||||||
libraries: Library[] = [];
|
|
||||||
bookdropFileUis: BookdropFileUI[] = [];
|
bookdropFileUis: BookdropFileUI[] = [];
|
||||||
fileUiCache: Record<number, BookdropFileUI> = {};
|
fileUiCache: Record<number, BookdropFileUI> = {};
|
||||||
copiedFlags: Record<number, boolean> = {};
|
copiedFlags: Record<number, boolean> = {};
|
||||||
@@ -111,16 +109,10 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
}))
|
}))
|
||||||
.subscribe();
|
.subscribe();
|
||||||
|
|
||||||
this.libraryService.libraryState$
|
const settings = this.appSettingsService.appSettings();
|
||||||
.subscribe(state => {
|
if (settings) {
|
||||||
this.libraries = state.libraries ?? [];
|
this.uploadPattern = settings.uploadPattern ?? '';
|
||||||
});
|
}
|
||||||
|
|
||||||
this.appSettings$
|
|
||||||
.pipe(filter(Boolean), take(1))
|
|
||||||
.subscribe(settings => {
|
|
||||||
this.uploadPattern = settings?.uploadPattern ?? '';
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get defaultLibraryId() {
|
get defaultLibraryId() {
|
||||||
@@ -137,6 +129,10 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get libraries(): Library[] {
|
||||||
|
return this.libraryService.libraries();
|
||||||
|
}
|
||||||
|
|
||||||
get libraryOptions() {
|
get libraryOptions() {
|
||||||
if (!this.libraries) return [];
|
if (!this.libraries) return [];
|
||||||
return this.libraries.map(lib => ({label: lib.name, value: String(lib.id ?? '')}));
|
return this.libraries.map(lib => ({label: lib.name, value: String(lib.id ?? '')}));
|
||||||
@@ -278,7 +274,7 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
copyMetadata(): void {
|
copyMetadata(): void {
|
||||||
const files = this.getSelectedFiles().map(fileUi => {
|
this.getSelectedFiles().forEach(fileUi => {
|
||||||
const cachedfUi = this.fileUiCache[fileUi.file.id];
|
const cachedfUi = this.fileUiCache[fileUi.file.id];
|
||||||
const fetched = cachedfUi.file.fetchedMetadata;
|
const fetched = cachedfUi.file.fetchedMetadata;
|
||||||
const form = cachedfUi.metadataForm;
|
const form = cachedfUi.metadataForm;
|
||||||
@@ -299,7 +295,7 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
resetMetadata(): void {
|
resetMetadata(): void {
|
||||||
const selectedFiles = this.getSelectedFiles();
|
const selectedFiles = this.getSelectedFiles();
|
||||||
|
|
||||||
const files = selectedFiles.map(fileUi => {
|
selectedFiles.forEach(fileUi => {
|
||||||
const original = fileUi.file.originalMetadata;
|
const original = fileUi.file.originalMetadata;
|
||||||
fileUi.metadataForm.patchValue({
|
fileUi.metadataForm.patchValue({
|
||||||
title: original?.title || null,
|
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 {BehaviorSubject, Subscription} from 'rxjs';
|
||||||
import {map, filter, take} from 'rxjs/operators';
|
import {map} from 'rxjs/operators';
|
||||||
import {BookdropFileApiService} from './bookdrop-file-api.service';
|
import {BookdropFileApiService} from './bookdrop-file-api.service';
|
||||||
import {AuthService} from '../../../shared/service/auth.service';
|
import {AuthService} from '../../../shared/service/auth.service';
|
||||||
import {UserService} from '../../settings/user-management/user.service';
|
import {UserService} from '../../settings/user-management/user.service';
|
||||||
@@ -30,21 +30,20 @@ export class BookdropFileService implements OnDestroy {
|
|||||||
private authService = inject(AuthService);
|
private authService = inject(AuthService);
|
||||||
private subscriptions = new Subscription();
|
private subscriptions = new Subscription();
|
||||||
private userService = inject(UserService);
|
private userService = inject(UserService);
|
||||||
|
private hasInitialized = false;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.userService.userState$
|
effect(() => {
|
||||||
.pipe(
|
const user = this.userService.currentUser();
|
||||||
filter(state => state.loaded && !!state.user),
|
if (this.hasInitialized || !user) {
|
||||||
take(1)
|
return;
|
||||||
)
|
}
|
||||||
.subscribe(state => {
|
this.hasInitialized = true;
|
||||||
const user = state.user!;
|
|
||||||
if (user.permissions.admin || user.permissions.canAccessBookdrop) {
|
if ((user.permissions.admin || user.permissions.canAccessBookdrop) && this.authService.token()) {
|
||||||
this.authService.token$
|
this.refresh();
|
||||||
.pipe(filter(t => !!t), take(1))
|
}
|
||||||
.subscribe(() => this.refresh());
|
});
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleIncomingFile(summary: BookdropFileNotification): void {
|
handleIncomingFile(summary: BookdropFileNotification): void {
|
||||||
|
|||||||
+11
-6
@@ -28,9 +28,10 @@
|
|||||||
|
|
||||||
<div class="scroller-fields">
|
<div class="scroller-fields">
|
||||||
<div class="scroller-field" [class.expanded]="scroller.type !== 'magicShelf'">
|
<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
|
<p-select
|
||||||
fluid
|
fluid
|
||||||
|
[inputId]="'dashboard-scroller-type-' + scroller.id"
|
||||||
[options]="availableScrollerTypes"
|
[options]="availableScrollerTypes"
|
||||||
[(ngModel)]="scroller.type"
|
[(ngModel)]="scroller.type"
|
||||||
(onChange)="onScrollerTypeChange(scroller)"
|
(onChange)="onScrollerTypeChange(scroller)"
|
||||||
@@ -41,10 +42,11 @@
|
|||||||
|
|
||||||
@if (scroller.type === 'magicShelf') {
|
@if (scroller.type === 'magicShelf') {
|
||||||
<div class="scroller-field">
|
<div class="scroller-field">
|
||||||
<label>{{ t('magicShelf') }}</label>
|
<label [for]="'dashboard-scroller-magic-shelf-' + scroller.id">{{ t('magicShelf') }}</label>
|
||||||
<p-select
|
<p-select
|
||||||
fluid
|
fluid
|
||||||
[options]="(magicShelves$ | async)!"
|
[inputId]="'dashboard-scroller-magic-shelf-' + scroller.id"
|
||||||
|
[options]="magicShelves()"
|
||||||
[(ngModel)]="scroller.magicShelfId"
|
[(ngModel)]="scroller.magicShelfId"
|
||||||
[placeholder]="t('selectMagicShelf')"
|
[placeholder]="t('selectMagicShelf')"
|
||||||
appendTo="body">
|
appendTo="body">
|
||||||
@@ -52,9 +54,10 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="scroller-field">
|
<div class="scroller-field">
|
||||||
<label>{{ t('sortField') }}</label>
|
<label [for]="'dashboard-scroller-sort-field-' + scroller.id">{{ t('sortField') }}</label>
|
||||||
<p-select
|
<p-select
|
||||||
fluid
|
fluid
|
||||||
|
[inputId]="'dashboard-scroller-sort-field-' + scroller.id"
|
||||||
[options]="sortFieldOptions"
|
[options]="sortFieldOptions"
|
||||||
[(ngModel)]="scroller.sortField"
|
[(ngModel)]="scroller.sortField"
|
||||||
[placeholder]="t('selectField')"
|
[placeholder]="t('selectField')"
|
||||||
@@ -63,9 +66,10 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="scroller-field">
|
<div class="scroller-field">
|
||||||
<label>{{ t('direction') }}</label>
|
<label [for]="'dashboard-scroller-sort-direction-' + scroller.id">{{ t('direction') }}</label>
|
||||||
<p-select
|
<p-select
|
||||||
fluid
|
fluid
|
||||||
|
[inputId]="'dashboard-scroller-sort-direction-' + scroller.id"
|
||||||
[options]="sortDirectionOptions"
|
[options]="sortDirectionOptions"
|
||||||
[(ngModel)]="scroller.sortDirection"
|
[(ngModel)]="scroller.sortDirection"
|
||||||
[placeholder]="t('selectDirection')"
|
[placeholder]="t('selectDirection')"
|
||||||
@@ -76,9 +80,10 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="scroller-field max-items-field">
|
<div class="scroller-field max-items-field">
|
||||||
<label>{{ t('maxItems') }}</label>
|
<label [for]="'dashboard-scroller-max-items-' + scroller.id">{{ t('maxItems') }}</label>
|
||||||
<p-inputNumber
|
<p-inputNumber
|
||||||
fluid
|
fluid
|
||||||
|
[inputId]="'dashboard-scroller-max-items-' + scroller.id"
|
||||||
[(ngModel)]="scroller.maxItems"
|
[(ngModel)]="scroller.maxItems"
|
||||||
[min]="MIN_ITEMS"
|
[min]="MIN_ITEMS"
|
||||||
[max]="MAX_ITEMS"
|
[max]="MAX_ITEMS"
|
||||||
|
|||||||
+27
-29
@@ -1,5 +1,5 @@
|
|||||||
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
|
import {Component, computed, effect, inject} from '@angular/core';
|
||||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
import {toSignal} from '@angular/core/rxjs-interop';
|
||||||
import {CommonModule} from '@angular/common';
|
import {CommonModule} from '@angular/common';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
@@ -11,7 +11,6 @@ import {InputNumberModule} from 'primeng/inputnumber';
|
|||||||
import {DashboardConfig, ScrollerConfig, ScrollerType} from '../../models/dashboard-config.model';
|
import {DashboardConfig, ScrollerConfig, ScrollerType} from '../../models/dashboard-config.model';
|
||||||
import {DashboardConfigService} from '../../services/dashboard-config.service';
|
import {DashboardConfigService} from '../../services/dashboard-config.service';
|
||||||
import {MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
import {MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
||||||
import {map} from 'rxjs/operators';
|
|
||||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||||
|
|
||||||
export const MAX_SCROLLERS = 5;
|
export const MAX_SCROLLERS = 5;
|
||||||
@@ -36,49 +35,48 @@ export const MAX_ITEMS = 20;
|
|||||||
templateUrl: './dashboard-settings.component.html',
|
templateUrl: './dashboard-settings.component.html',
|
||||||
styleUrls: ['./dashboard-settings.component.scss']
|
styleUrls: ['./dashboard-settings.component.scss']
|
||||||
})
|
})
|
||||||
export class DashboardSettingsComponent implements OnInit {
|
export class DashboardSettingsComponent {
|
||||||
private configService = inject(DashboardConfigService);
|
private configService = inject(DashboardConfigService);
|
||||||
private dialogRef = inject(DynamicDialogRef);
|
private dialogRef = inject(DynamicDialogRef);
|
||||||
private magicShelfService = inject(MagicShelfService);
|
private magicShelfService = inject(MagicShelfService);
|
||||||
private translocoService = inject(TranslocoService);
|
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}[] = [];
|
availableScrollerTypes: {label: string; value: ScrollerType}[] = [];
|
||||||
sortFieldOptions: {label: string; value: string}[] = [];
|
sortFieldOptions: {label: string; value: string}[] = [];
|
||||||
sortDirectionOptions: {label: string; value: string}[] = [];
|
sortDirectionOptions: {label: string; value: string}[] = [];
|
||||||
|
|
||||||
magicShelves$ = this.magicShelfService.shelvesState$.pipe(
|
magicShelves = computed(() =>
|
||||||
map(state => (state.shelves || []).map(shelf => ({
|
this.magicShelfService.shelves().map(shelf => ({
|
||||||
label: shelf.name,
|
label: shelf.name,
|
||||||
value: shelf.id!
|
value: shelf.id!
|
||||||
})))
|
}))
|
||||||
);
|
);
|
||||||
|
private magicShelvesMap = computed(() => {
|
||||||
private magicShelvesMap = new Map<number, string>();
|
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 MIN_ITEMS = MIN_ITEMS;
|
||||||
readonly MAX_ITEMS = MAX_ITEMS;
|
readonly MAX_ITEMS = MAX_ITEMS;
|
||||||
|
|
||||||
ngOnInit(): void {
|
private readonly syncTranslatedOptionsEffect = effect(() => {
|
||||||
this.translocoService.langChanges$
|
this.activeLanguage();
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
this.buildTranslatedOptions();
|
||||||
.subscribe(() => this.buildTranslatedOptions());
|
});
|
||||||
|
|
||||||
this.configService.config$.subscribe(config => {
|
private readonly syncConfigEffect = effect(() => {
|
||||||
this.config = JSON.parse(JSON.stringify(config));
|
this.config = structuredClone(this.configService.config());
|
||||||
});
|
});
|
||||||
|
|
||||||
this.magicShelfService.shelvesState$.subscribe(state => {
|
|
||||||
this.magicShelvesMap.clear();
|
|
||||||
(state.shelves || []).forEach(shelf => {
|
|
||||||
if (shelf.id) {
|
|
||||||
this.magicShelvesMap.set(shelf.id, shelf.name);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private buildTranslatedOptions(): void {
|
private buildTranslatedOptions(): void {
|
||||||
const t = (key: string) => this.translocoService.translate(`dashboard.settings.${key}`);
|
const t = (key: string) => this.translocoService.translate(`dashboard.settings.${key}`);
|
||||||
@@ -119,7 +117,7 @@ export class DashboardSettingsComponent implements OnInit {
|
|||||||
|
|
||||||
getScrollerTitle(scroller: ScrollerConfig): string {
|
getScrollerTitle(scroller: ScrollerConfig): string {
|
||||||
if (scroller.type === ScrollerType.MAGIC_SHELF && scroller.magicShelfId) {
|
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) {
|
switch (scroller.type) {
|
||||||
|
|||||||
+6
-7
@@ -1,6 +1,6 @@
|
|||||||
<ng-container *transloco="let t; prefix: 'dashboard.main'">
|
<ng-container *transloco="let t; prefix: 'dashboard.main'">
|
||||||
<div class="dashboard-container">
|
<div class="dashboard-container">
|
||||||
@if ((bookState$ | async)?.loaded === false) {
|
@if (isBooksLoading()) {
|
||||||
<div class="loading-state">
|
<div class="loading-state">
|
||||||
<p-progressSpinner
|
<p-progressSpinner
|
||||||
class="spinner center-spinner"
|
class="spinner center-spinner"
|
||||||
@@ -10,13 +10,12 @@
|
|||||||
animationDuration="1.5s">
|
animationDuration="1.5s">
|
||||||
</p-progressSpinner>
|
</p-progressSpinner>
|
||||||
</div>
|
</div>
|
||||||
}
|
} @else {
|
||||||
@if ((bookState$ | async)?.loaded === true) {
|
|
||||||
<div class="dashboard">
|
<div class="dashboard">
|
||||||
<div class="dashboard-inner">
|
<div class="dashboard-inner">
|
||||||
@if (isLibrariesEmpty$ | async) {
|
@if (isLibrariesEmpty()) {
|
||||||
<div class="dashboard-no-library">
|
<div class="dashboard-no-library">
|
||||||
@if ((userService.userState$ | async)?.user?.permissions; as permissions) {
|
@if (userService.currentUser()?.permissions; as permissions) {
|
||||||
<div>
|
<div>
|
||||||
@if (permissions.admin || permissions.canManageLibrary) {
|
@if (permissions.admin || permissions.canManageLibrary) {
|
||||||
<div>
|
<div>
|
||||||
@@ -51,7 +50,7 @@
|
|||||||
</p-button>
|
</p-button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (dashboardConfig$ | async; as config) {
|
@if (dashboardConfig(); as config) {
|
||||||
@for (scroller of config.scrollers; track scroller.id) {
|
@for (scroller of config.scrollers; track scroller.id) {
|
||||||
@if (scroller.enabled) {
|
@if (scroller.enabled) {
|
||||||
<app-dashboard-scroller
|
<app-dashboard-scroller
|
||||||
@@ -59,7 +58,7 @@
|
|||||||
[title]="scroller.title"
|
[title]="scroller.title"
|
||||||
[isMagicShelf]="scroller.type === ScrollerType.MAGIC_SHELF"
|
[isMagicShelf]="scroller.type === ScrollerType.MAGIC_SHELF"
|
||||||
[useSquareCovers]="scroller.type === ScrollerType.LAST_LISTENED"
|
[useSquareCovers]="scroller.type === ScrollerType.LAST_LISTENED"
|
||||||
[books]="getBooksForScroller(scroller) | async">
|
[books]="getBooksForScroller(scroller)">
|
||||||
</app-dashboard-scroller>
|
</app-dashboard-scroller>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+114
-147
@@ -1,13 +1,7 @@
|
|||||||
import {Component, inject, OnInit} from '@angular/core';
|
import {Component, computed, 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 {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {AsyncPipe} from '@angular/common';
|
|
||||||
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
||||||
import {BookService} from '../../../book/service/book.service';
|
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 {Book, ReadStatus} from '../../../book/model/book.model';
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
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 {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
||||||
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
||||||
import {SortService} from '../../../book/service/sort.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 {SortDirection, SortOption} from '../../../book/model/sort.model';
|
||||||
|
import {LibraryService} from '../../../book/service/library.service';
|
||||||
|
|
||||||
const DEFAULT_MAX_ITEMS = 20;
|
const DEFAULT_MAX_ITEMS = 20;
|
||||||
|
|
||||||
@@ -32,7 +27,6 @@ const DEFAULT_MAX_ITEMS = 20;
|
|||||||
imports: [
|
imports: [
|
||||||
Button,
|
Button,
|
||||||
DashboardScrollerComponent,
|
DashboardScrollerComponent,
|
||||||
AsyncPipe,
|
|
||||||
ProgressSpinner,
|
ProgressSpinner,
|
||||||
TooltipModule,
|
TooltipModule,
|
||||||
TranslocoDirective
|
TranslocoDirective
|
||||||
@@ -42,6 +36,7 @@ const DEFAULT_MAX_ITEMS = 20;
|
|||||||
export class MainDashboardComponent implements OnInit {
|
export class MainDashboardComponent implements OnInit {
|
||||||
|
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
|
private libraryService = inject(LibraryService);
|
||||||
private dialogLauncher = inject(DialogLauncherService);
|
private dialogLauncher = inject(DialogLauncherService);
|
||||||
protected userService = inject(UserService);
|
protected userService = inject(UserService);
|
||||||
private dashboardConfigService = inject(DashboardConfigService);
|
private dashboardConfigService = inject(DashboardConfigService);
|
||||||
@@ -51,174 +46,146 @@ export class MainDashboardComponent implements OnInit {
|
|||||||
private pageTitle = inject(PageTitleService);
|
private pageTitle = inject(PageTitleService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
bookState$ = this.bookService.bookState$;
|
readonly dashboardConfig = this.dashboardConfigService.config;
|
||||||
dashboardConfig$ = this.dashboardConfigService.config$;
|
readonly isBooksLoading = this.bookService.isBooksLoading;
|
||||||
|
readonly isLibrariesEmpty = computed(() =>
|
||||||
private scrollerBooksCache = new Map<string, Observable<Book[]>>();
|
!this.libraryService.isLibrariesLoading() && this.libraryService.libraries().length === 0
|
||||||
|
|
||||||
isLibrariesEmpty$: Observable<boolean> = inject(LibraryService).libraryState$.pipe(
|
|
||||||
map(state => !state.libraries || state.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;
|
ScrollerType = ScrollerType;
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.pageTitle.setPageTitle(this.t.translate('dashboard.main.pageTitle'));
|
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[]> {
|
getBooksForScroller(config: ScrollerConfig): Book[] {
|
||||||
return this.bookService.bookState$.pipe(
|
return this.scrollerBooks().get(config.id) ?? [];
|
||||||
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);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private getLastListenedBooks(maxItems: number): Observable<Book[]> {
|
private getBooksForConfig(config: ScrollerConfig, books: Book[], magicShelves: {id?: number | null; filterJson: string}[]): Book[] {
|
||||||
return this.bookService.bookState$.pipe(
|
switch (config.type) {
|
||||||
map((state: BookState) => {
|
case ScrollerType.LAST_READ:
|
||||||
let books = (state.books || []).filter(book =>
|
return this.getLastReadBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
book.lastReadTime &&
|
case ScrollerType.LAST_LISTENED:
|
||||||
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
|
return this.getLastListenedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
book.audiobookProgress
|
case ScrollerType.LATEST_ADDED:
|
||||||
);
|
return this.getLatestAddedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
books = books.sort((a, b) => {
|
case ScrollerType.RANDOM:
|
||||||
const aTime = new Date(a.lastReadTime!).getTime();
|
return this.getRandomBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
const bTime = new Date(b.lastReadTime!).getTime();
|
case ScrollerType.MAGIC_SHELF:
|
||||||
return bTime - aTime;
|
return this.getMagicShelfBooks(config, books, magicShelves);
|
||||||
});
|
default:
|
||||||
return books.slice(0, maxItems);
|
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 {
|
private hasEbookProgress(book: Book): boolean {
|
||||||
return !!(book.epubProgress || book.pdfProgress || book.cbxProgress || book.koreaderProgress || book.koboProgress);
|
return !!(book.epubProgress || book.pdfProgress || book.cbxProgress || book.koreaderProgress || book.koboProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
private getLatestAddedBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
|
private getLatestAddedBooks(books: Book[], maxItems: number): Book[] {
|
||||||
return this.bookService.bookState$.pipe(
|
const addedBooks = books.filter(book => book.addedOn);
|
||||||
map((state: BookState) => {
|
|
||||||
let books = (state.books || []).filter(book => book.addedOn);
|
|
||||||
|
|
||||||
books = books.sort((a, b) => {
|
return addedBooks.sort((a, b) => {
|
||||||
const aTime = new Date(a.addedOn!).getTime();
|
const aTime = new Date(a.addedOn!).getTime();
|
||||||
const bTime = new Date(b.addedOn!).getTime();
|
const bTime = new Date(b.addedOn!).getTime();
|
||||||
return bTime - aTime;
|
return bTime - aTime;
|
||||||
});
|
}).slice(0, maxItems);
|
||||||
|
|
||||||
return books.slice(0, maxItems);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private getRandomBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
|
private getRandomBooks(books: Book[], maxItems: number): Book[] {
|
||||||
return this.bookService.bookState$.pipe(
|
const excludedStatuses = new Set<ReadStatus>([
|
||||||
map((state: BookState) => {
|
ReadStatus.READ,
|
||||||
const excludedStatuses = new Set<ReadStatus>([
|
ReadStatus.PARTIALLY_READ,
|
||||||
ReadStatus.READ,
|
ReadStatus.READING,
|
||||||
ReadStatus.PARTIALLY_READ,
|
ReadStatus.PAUSED,
|
||||||
ReadStatus.READING,
|
ReadStatus.WONT_READ,
|
||||||
ReadStatus.PAUSED,
|
ReadStatus.ABANDONED
|
||||||
ReadStatus.WONT_READ,
|
]);
|
||||||
ReadStatus.ABANDONED
|
|
||||||
]);
|
|
||||||
|
|
||||||
const candidates = (state.books || []).filter(book =>
|
const candidates = books.filter(book =>
|
||||||
!book.readStatus || !excludedStatuses.has(book.readStatus)
|
!book.readStatus || !excludedStatuses.has(book.readStatus)
|
||||||
);
|
|
||||||
|
|
||||||
return this.shuffleBooks(candidates, maxItems);
|
|
||||||
})
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return this.shuffleBooks(candidates, maxItems);
|
||||||
}
|
}
|
||||||
|
|
||||||
private getMagicShelfBooks(shelfId: number, maxItems?: number, sortBy?: string): Observable<Book[]> {
|
private getMagicShelfBooks(
|
||||||
return this.magicShelfService.getShelf(shelfId).pipe(
|
config: ScrollerConfig,
|
||||||
switchMap((shelf) => {
|
books: Book[],
|
||||||
if (!shelf) return this.bookService.bookState$.pipe(map(() => []));
|
magicShelves: {id?: number | null; filterJson: string}[]
|
||||||
|
): Book[] {
|
||||||
let group: GroupRule;
|
const shelf = magicShelves.find(currentShelf => currentShelf.id === config.magicShelfId);
|
||||||
try {
|
if (!shelf) {
|
||||||
group = JSON.parse(shelf.filterJson);
|
return [];
|
||||||
} 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)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
private createSortOption(field: string, direction: string): SortOption {
|
||||||
return {
|
return {
|
||||||
field: field,
|
field,
|
||||||
direction: direction === 'asc' ? SortDirection.ASCENDING : SortDirection.DESCENDING,
|
direction: direction === 'asc' ? SortDirection.ASCENDING : SortDirection.DESCENDING,
|
||||||
label: ''
|
label: ''
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,65 +1,97 @@
|
|||||||
import {Injectable} from '@angular/core';
|
import {effect, inject, Injectable, signal} from '@angular/core';
|
||||||
import {BehaviorSubject, Observable} from 'rxjs';
|
|
||||||
import {DashboardConfig, DEFAULT_DASHBOARD_CONFIG, ScrollerType} from '../models/dashboard-config.model';
|
import {DashboardConfig, DEFAULT_DASHBOARD_CONFIG, ScrollerType} from '../models/dashboard-config.model';
|
||||||
import {UserService} from '../../settings/user-management/user.service';
|
import {UserService} from '../../settings/user-management/user.service';
|
||||||
import {filter, take} from 'rxjs/operators';
|
|
||||||
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class DashboardConfigService {
|
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) {
|
constructor() {
|
||||||
this.userService.userState$
|
effect(() => {
|
||||||
.pipe(
|
const user = this.userService.currentUser();
|
||||||
filter(userState => !!userState?.user && userState.loaded),
|
if (user) {
|
||||||
take(1)
|
const dashboardConfig = user.userSettings?.dashboardConfig as DashboardConfig;
|
||||||
)
|
this._config.set(this.normalizeConfig(dashboardConfig));
|
||||||
.subscribe(userState => {
|
}
|
||||||
const dashboardConfig = userState.user?.userSettings?.dashboardConfig as DashboardConfig;
|
});
|
||||||
if (dashboardConfig) {
|
|
||||||
this.configSubject.next(dashboardConfig);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.magicShelfService.shelvesState$.subscribe(state => {
|
effect(() => {
|
||||||
const currentConfig = this.configSubject.value;
|
const shelves = this.magicShelfService.shelves();
|
||||||
let updated = false;
|
const currentConfig = this._config();
|
||||||
|
const syncedConfig = this.syncMagicShelfTitles(currentConfig, shelves);
|
||||||
|
|
||||||
currentConfig.scrollers.forEach(scroller => {
|
if (syncedConfig) {
|
||||||
if (scroller.type === ScrollerType.MAGIC_SHELF && scroller.magicShelfId) {
|
this._config.set(syncedConfig);
|
||||||
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});
|
|
||||||
const user = this.userService.getCurrentUser();
|
const user = this.userService.getCurrentUser();
|
||||||
if (user) {
|
if (user) {
|
||||||
this.userService.updateUserSetting(user.id, 'dashboardConfig', currentConfig);
|
this.userService.updateUserSetting(user.id, 'dashboardConfig', syncedConfig);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
saveConfig(config: DashboardConfig): void {
|
saveConfig(config: DashboardConfig): void {
|
||||||
this.configSubject.next(config);
|
const nextConfig = this.normalizeConfig(config);
|
||||||
|
this._config.set(nextConfig);
|
||||||
|
|
||||||
const user = this.userService.getCurrentUser();
|
const user = this.userService.getCurrentUser();
|
||||||
if (user) {
|
if (user) {
|
||||||
this.userService.updateUserSetting(user.id, 'dashboardConfig', config);
|
this.userService.updateUserSetting(user.id, 'dashboardConfig', nextConfig);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
resetToDefault(): void {
|
resetToDefault(): void {
|
||||||
this.saveConfig(DEFAULT_DASHBOARD_CONFIG);
|
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>
|
||||||
<div class="icon-picker-section">
|
<div class="icon-picker-section">
|
||||||
<div class="icon-picker-wrapper">
|
<div class="icon-picker-wrapper">
|
||||||
<label>{{ t('form.shelfIcon') }}</label>
|
<span>{{ t('form.shelfIcon') }}</span>
|
||||||
@if (selectedIcon) {
|
@if (selectedIcon) {
|
||||||
<div class="selected-icon-display">
|
<div class="selected-icon-display">
|
||||||
<div class="icon-display-container" (click)="openIconPicker()" (keydown.enter)="openIconPicker()" tabindex="0" role="button">
|
<div class="icon-display-container" (click)="openIconPicker()" (keydown.enter)="openIconPicker()" tabindex="0" role="button">
|
||||||
@@ -116,11 +116,11 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ng-template #groupTemplate let-group="group">
|
<ng-template #groupTemplate let-group="group">
|
||||||
<div class="group-container" [formGroup]="group">
|
<div class="group-container" [formGroup]="group">
|
||||||
<div class="group-header">
|
<div class="group-header">
|
||||||
<label>{{ t('group.condition') }}</label>
|
<label [for]="getControlId(group.get('join'), 'magic-shelf-group-join')">{{ t('group.condition') }}</label>
|
||||||
<p-select [options]="conditionOptions" formControlName="join" class="condition-select" appendTo="body" [showClear]="false"/>
|
<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-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>
|
<p-button icon="pi pi-folder-open" size="small" text (click)="addGroup(group)" [label]="t('actions.addGroup')" outlined></p-button>
|
||||||
@if (group.parent) {
|
@if (group.parent) {
|
||||||
@@ -187,11 +187,11 @@
|
|||||||
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
|
} @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>
|
<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') {
|
} @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') {
|
} @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') {
|
} @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') {
|
} @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>
|
<p-multiSelect [options]="contentRatingOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectContentRatings')"></p-multiSelect>
|
||||||
} @else {
|
} @else {
|
||||||
@@ -204,11 +204,11 @@
|
|||||||
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
|
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
|
||||||
<p-select [options]="fileType" formControlName="value" [placeholder]="t('placeholders.selectFileType')" appendTo="body" class="value-input"></p-select>
|
<p-select [options]="fileType" formControlName="value" [placeholder]="t('placeholders.selectFileType')" appendTo="body" class="value-input"></p-select>
|
||||||
} @else if (ruleCtrl.get('field')?.value === 'library') {
|
} @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') {
|
} @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') {
|
} @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') {
|
} @else if (ruleCtrl.get('field')?.value === 'contentRating') {
|
||||||
<p-select [options]="contentRatingOptions" formControlName="value" [placeholder]="t('placeholders.selectContentRating')" appendTo="body" class="value-input"></p-select>
|
<p-select [options]="contentRatingOptions" formControlName="value" [placeholder]="t('placeholders.selectContentRating')" appendTo="body" class="value-input"></p-select>
|
||||||
} @else {
|
} @else {
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ describe('MagicShelfComponent (Part 3)', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{provide: TranslocoService, useValue: mockTransloco},
|
{provide: TranslocoService, useValue: mockTransloco},
|
||||||
{provide: LibraryService, useValue: {getLibrariesFromState: vi.fn(() => [])}},
|
{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: BookService, useValue: {bookState$: of({loaded: false, books: []})}},
|
||||||
{provide: MagicShelfService, useValue: {}},
|
{provide: MagicShelfService, useValue: {}},
|
||||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
{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 {AbstractControl, FormArray, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {NgTemplateOutlet} from '@angular/common';
|
import {NgTemplateOutlet} from '@angular/common';
|
||||||
@@ -8,8 +8,7 @@ import {DatePicker} from 'primeng/datepicker';
|
|||||||
import {InputNumber} from 'primeng/inputnumber';
|
import {InputNumber} from 'primeng/inputnumber';
|
||||||
import {ReadStatus} from '../../book/model/book.model';
|
import {ReadStatus} from '../../book/model/book.model';
|
||||||
import {LibraryService} from '../../book/service/library.service';
|
import {LibraryService} from '../../book/service/library.service';
|
||||||
import {Library} from '../../book/model/library.model';
|
import {MagicShelf, MagicShelfService} from '../service/magic-shelf.service';
|
||||||
import {MagicShelfService} from '../service/magic-shelf.service';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {MultiSelect} from 'primeng/multiselect';
|
import {MultiSelect} from 'primeng/multiselect';
|
||||||
@@ -22,7 +21,6 @@ import {IconDisplayComponent} from '../../../shared/components/icon-display/icon
|
|||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {BookService} from '../../book/service/book.service';
|
import {BookService} from '../../book/service/book.service';
|
||||||
import {ShelfService} from '../../book/service/shelf.service';
|
import {ShelfService} from '../../book/service/shelf.service';
|
||||||
import {Shelf} from '../../book/model/shelf.model';
|
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
import {TextareaModule} from 'primeng/textarea';
|
import {TextareaModule} from 'primeng/textarea';
|
||||||
|
|
||||||
@@ -250,10 +248,12 @@ const READ_STATUS_KEYS: Record<string, string> = {
|
|||||||
export class MagicShelfComponent implements OnInit {
|
export class MagicShelfComponent implements OnInit {
|
||||||
|
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
private readonly controlIds = new WeakMap<AbstractControl, string>();
|
||||||
|
private controlIdCounter = 0;
|
||||||
|
|
||||||
numericFieldConfigMap = new Map<RuleField, FieldConfig>(
|
numericFieldConfigMap = new Map<RuleField, FieldConfig>(
|
||||||
Object.entries(FIELD_CONFIGS)
|
Object.entries(FIELD_CONFIGS)
|
||||||
.filter(([_, config]) => config.type)
|
.filter(([, config]) => config.type)
|
||||||
.map(([key, config]) => [key as RuleField, {type: config.type!, max: config.max}])
|
.map(([key, config]) => [key as RuleField, {type: config.type!, max: config.max}])
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -438,11 +438,29 @@ export class MagicShelfComponent implements OnInit {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
libraries: Library[] = [];
|
libraryOptions = computed(() =>
|
||||||
libraryOptions: { label: string; value: number }[] = [];
|
this.libraryService.libraries().map(library => ({
|
||||||
shelves: Shelf[] = [];
|
label: library.name,
|
||||||
shelfOptions: { label: string; value: number }[] = [];
|
value: library.id!
|
||||||
categoryOptions: { label: string; value: string }[] = [];
|
}))
|
||||||
|
);
|
||||||
|
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({
|
form = new FormGroup({
|
||||||
name: new FormControl<string | null>(null),
|
name: new FormControl<string | null>(null),
|
||||||
@@ -468,9 +486,25 @@ export class MagicShelfComponent implements OnInit {
|
|||||||
private iconPicker = inject(IconPickerService);
|
private iconPicker = inject(IconPickerService);
|
||||||
|
|
||||||
selectedIcon: IconSelection | null = null;
|
selectedIcon: IconSelection | null = null;
|
||||||
|
private formInitializedFromShelf = false;
|
||||||
|
|
||||||
trackByFn(ruleCtrl: AbstractControl, index: number): unknown {
|
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 {
|
ngOnInit(): void {
|
||||||
@@ -478,62 +512,40 @@ export class MagicShelfComponent implements OnInit {
|
|||||||
const id = this.config?.data?.id;
|
const id = this.config?.data?.id;
|
||||||
this.editMode = !!this.config?.data?.editMode;
|
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) {
|
if (id) {
|
||||||
this.shelfId = id;
|
this.shelfId = id;
|
||||||
this.magicShelfService.getShelf(id).subscribe((data) => {
|
effect(() => {
|
||||||
const iconValue = data?.icon ?? null;
|
const shelf = this.magicShelfService.findShelfById(id);
|
||||||
|
if (!shelf || this.formInitializedFromShelf) {
|
||||||
this.form = new FormGroup({
|
return;
|
||||||
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};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.initializeForm(shelf);
|
||||||
|
this.formInitializedFromShelf = true;
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
this.form = new FormGroup({
|
this.initializeForm();
|
||||||
name: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}),
|
this.formInitializedFromShelf = true;
|
||||||
icon: new FormControl<string | null>(null),
|
|
||||||
isPublic: new FormControl<boolean>(false),
|
|
||||||
group: this.createGroup()
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.libraries = this.libraryService.getLibrariesFromState();
|
private initializeForm(shelf?: MagicShelf): void {
|
||||||
this.libraryOptions = this.libraries.map(lib => ({
|
const iconValue = shelf?.icon ?? null;
|
||||||
label: lib.name,
|
|
||||||
value: lib.id!
|
|
||||||
}));
|
|
||||||
|
|
||||||
this.shelves = this.shelfService.getShelvesFromState();
|
this.form = new FormGroup({
|
||||||
this.shelfOptions = this.shelves.map(shelf => ({
|
name: new FormControl<string | null>(shelf?.name ?? null, {nonNullable: true, validators: [Validators.required]}),
|
||||||
label: shelf.name,
|
icon: new FormControl<string | null>(iconValue),
|
||||||
value: shelf.id!
|
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 {
|
buildGroupFromData(data: GroupRule): GroupFormGroup {
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
|
||||||
import {HttpClient} from '@angular/common/http';
|
import {HttpClient} from '@angular/common/http';
|
||||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
import {lastValueFrom, Observable} from 'rxjs';
|
||||||
import {catchError, distinctUntilChanged, finalize, map, shareReplay, switchMap, tap} from 'rxjs/operators';
|
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 {BookService} from '../../book/service/book.service';
|
||||||
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
|
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
|
||||||
import {AuthService} from '../../../shared/service/auth.service';
|
import {AuthService} from '../../../shared/service/auth.service';
|
||||||
@@ -17,11 +19,7 @@ export interface MagicShelf {
|
|||||||
isPublic?: boolean;
|
isPublic?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MagicShelfState {
|
const MAGIC_SHELVES_QUERY_KEY = ['magicShelves'] as const;
|
||||||
shelves: MagicShelf[] | null;
|
|
||||||
loaded: boolean;
|
|
||||||
error: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -33,68 +31,51 @@ export class MagicShelfService {
|
|||||||
private readonly bookService = inject(BookService);
|
private readonly bookService = inject(BookService);
|
||||||
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
|
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
|
private readonly queryClient = inject(QueryClient);
|
||||||
|
private readonly token = this.authService.token;
|
||||||
|
|
||||||
private readonly shelvesStateSubject = new BehaviorSubject<MagicShelfState>({
|
private readonly shelvesQuery = injectQuery(() => ({
|
||||||
shelves: null,
|
...this.getShelvesQueryOptions(),
|
||||||
loaded: false,
|
enabled: !!this.token(),
|
||||||
error: null,
|
}));
|
||||||
|
|
||||||
|
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() {
|
constructor() {
|
||||||
this.authService.token$.pipe(
|
effect(() => {
|
||||||
distinctUntilChanged()
|
const token = this.token();
|
||||||
).subscribe(token => {
|
|
||||||
if (token === null) {
|
if (token === null) {
|
||||||
this.shelvesStateSubject.next({
|
this.queryClient.removeQueries({queryKey: MAGIC_SHELVES_QUERY_KEY});
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public readonly shelvesState$ = this.shelvesStateSubject.asObservable().pipe(
|
private getShelvesQueryOptions() {
|
||||||
tap(state => {
|
return queryOptions({
|
||||||
if (!state.loaded && !state.error && !this.loading$) {
|
queryKey: MAGIC_SHELVES_QUERY_KEY,
|
||||||
this.loading$ = this.fetchMagicShelves().pipe(
|
queryFn: () => lastValueFrom(this.http.get<MagicShelf[]>(this.url))
|
||||||
shareReplay(1),
|
});
|
||||||
finalize(() => (this.loading$ = null))
|
|
||||||
);
|
|
||||||
this.loading$.subscribe();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
private get state(): MagicShelfState {
|
|
||||||
return this.shelvesStateSubject.value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fetchMagicShelves(): Observable<MagicShelf[]> {
|
saveShelf(data: {
|
||||||
return this.http.get<MagicShelf[]>(this.url).pipe(
|
id?: number;
|
||||||
tap(shelves => this.shelvesStateSubject.next({shelves, loaded: true, error: null})),
|
name: string | null;
|
||||||
catchError(err => {
|
icon: string | null;
|
||||||
const curr = this.shelvesStateSubject.value;
|
iconType?: 'PRIME_NG' | 'CUSTOM_SVG';
|
||||||
this.shelvesStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
|
group: unknown;
|
||||||
throw err;
|
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 = {
|
const payload: MagicShelf = {
|
||||||
id: data.id,
|
id: data.id,
|
||||||
name: data.name ?? '',
|
name: data.name ?? '',
|
||||||
@@ -105,70 +86,40 @@ export class MagicShelfService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return this.http.post<MagicShelf>(this.url, payload).pipe(
|
return this.http.post<MagicShelf>(this.url, payload).pipe(
|
||||||
tap((newShelf) => {
|
tap(() => {
|
||||||
const curr = this.state;
|
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
|
||||||
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;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getShelf(id: number): Observable<MagicShelf | undefined> {
|
findShelfById(id: number): MagicShelf | undefined {
|
||||||
return this.shelvesState$.pipe(
|
return this.shelves().find(shelf => shelf.id === id);
|
||||||
map(state => (state.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> {
|
deleteShelf(id: number): Observable<void> {
|
||||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||||
tap(() => {
|
tap(() => {
|
||||||
const curr = this.state;
|
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
|
||||||
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;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -47,25 +47,25 @@
|
|||||||
<p-tabpanels class="tabpanels-responsive">
|
<p-tabpanels class="tabpanels-responsive">
|
||||||
<p-tabpanel value="view">
|
<p-tabpanel value="view">
|
||||||
<app-metadata-viewer
|
<app-metadata-viewer
|
||||||
[book$]="book$"
|
[book]="book()"
|
||||||
[recommendedBooks]="recommendedBooks">
|
[recommendedBooks]="recommendedBooks">
|
||||||
</app-metadata-viewer>
|
</app-metadata-viewer>
|
||||||
</p-tabpanel>
|
</p-tabpanel>
|
||||||
@if (admin || canEditMetadata) {
|
@if (admin || canEditMetadata) {
|
||||||
<p-tabpanel value="edit">
|
<p-tabpanel value="edit">
|
||||||
<app-metadata-editor
|
<app-metadata-editor
|
||||||
[book$]="book$">
|
[book]="book()">
|
||||||
</app-metadata-editor>
|
</app-metadata-editor>
|
||||||
</p-tabpanel>
|
</p-tabpanel>
|
||||||
}
|
}
|
||||||
@if (admin || canEditMetadata) {
|
@if (admin || canEditMetadata) {
|
||||||
<p-tabpanel value="match">
|
<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>
|
</p-tabpanel>
|
||||||
}
|
}
|
||||||
@if ((admin || canEditMetadata) && !isPhysical && isLocalStorage) {
|
@if ((admin || canEditMetadata) && !isPhysical && isLocalStorage) {
|
||||||
<p-tabpanel value="sidecar">
|
<p-tabpanel value="sidecar">
|
||||||
<app-sidecar-viewer [book$]="book$"></app-sidecar-viewer>
|
<app-sidecar-viewer [book]="book()"></app-sidecar-viewer>
|
||||||
</p-tabpanel>
|
</p-tabpanel>
|
||||||
}
|
}
|
||||||
</p-tabpanels>
|
</p-tabpanels>
|
||||||
|
|||||||
+58
-73
@@ -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 {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {Book, BookRecommendation} from '../../../book/model/book.model';
|
import {Book, BookRecommendation} from '../../../book/model/book.model';
|
||||||
import {BehaviorSubject, Observable, Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {distinctUntilChanged, filter, map, shareReplay, switchMap, take, takeUntil, tap,} from 'rxjs/operators';
|
import {distinctUntilChanged, filter, map, takeUntil,} from 'rxjs/operators';
|
||||||
import {BookService} from '../../../book/service/book.service';
|
import {BookService} from '../../../book/service/book.service';
|
||||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||||
import {Tab, TabList, TabPanel, TabPanels, Tabs,} from 'primeng/tabs';
|
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 {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
|
||||||
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
|
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
|
||||||
import {SidecarViewerComponent} from './sidecar-viewer/sidecar-viewer.component';
|
import {SidecarViewerComponent} from './sidecar-viewer/sidecar-viewer.component';
|
||||||
|
import {injectQuery} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-book-metadata-center',
|
selector: 'app-book-metadata-center',
|
||||||
@@ -42,18 +43,50 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
|||||||
private userService = inject(UserService);
|
private userService = inject(UserService);
|
||||||
private appSettingsService = inject(AppSettingsService);
|
private appSettingsService = inject(AppSettingsService);
|
||||||
private metadataHostService = inject(BookMetadataHostService);
|
private metadataHostService = inject(BookMetadataHostService);
|
||||||
|
readonly config = inject(DynamicDialogConfig, {optional: true});
|
||||||
|
readonly ref = inject(DynamicDialogRef, {optional: true});
|
||||||
private destroy$ = new Subject<void>();
|
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[] = [];
|
recommendedBooks: BookRecommendation[] = [];
|
||||||
private _tab: string = 'view';
|
private _tab: string = 'view';
|
||||||
canEditMetadata: boolean = false;
|
canEditMetadata: boolean = false;
|
||||||
admin: 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;
|
isLocalStorage: boolean = true;
|
||||||
|
|
||||||
private appSettings$ = this.appSettingsService.appSettings$;
|
|
||||||
private currentBookId$ = new BehaviorSubject<number | null>(null);
|
|
||||||
private validTabs = ['view', 'edit', 'match', 'sidecar'];
|
private validTabs = ['view', 'edit', 'match', 'sidecar'];
|
||||||
|
|
||||||
get tab(): string {
|
get tab(): string {
|
||||||
@@ -72,16 +105,10 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(
|
|
||||||
@Optional() public config?: DynamicDialogConfig,
|
|
||||||
@Optional() public ref?: DynamicDialogRef
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
const bookIdFromDialog: number | undefined = this.config?.data?.bookId;
|
const bookIdFromDialog: number | undefined = this.config?.data?.bookId;
|
||||||
if (bookIdFromDialog != null) {
|
if (bookIdFromDialog != null) {
|
||||||
this.currentBookId$.next(bookIdFromDialog);
|
this.currentBookId.set(bookIdFromDialog);
|
||||||
} else {
|
} else {
|
||||||
this.route.paramMap
|
this.route.paramMap
|
||||||
.pipe(
|
.pipe(
|
||||||
@@ -89,7 +116,7 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
|||||||
filter(bookId => !isNaN(bookId)),
|
filter(bookId => !isNaN(bookId)),
|
||||||
takeUntil(this.destroy$)
|
takeUntil(this.destroy$)
|
||||||
)
|
)
|
||||||
.subscribe(bookId => this.currentBookId$.next(bookId));
|
.subscribe(bookId => this.currentBookId.set(bookId));
|
||||||
}
|
}
|
||||||
|
|
||||||
this.metadataHostService.bookSwitches$
|
this.metadataHostService.bookSwitches$
|
||||||
@@ -98,34 +125,7 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
|||||||
distinctUntilChanged(),
|
distinctUntilChanged(),
|
||||||
takeUntil(this.destroy$)
|
takeUntil(this.destroy$)
|
||||||
)
|
)
|
||||||
.subscribe(bookId => {
|
.subscribe(bookId => this.currentBookId.set(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));
|
|
||||||
|
|
||||||
this.route.queryParamMap
|
this.route.queryParamMap
|
||||||
.pipe(
|
.pipe(
|
||||||
@@ -137,39 +137,24 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
|||||||
this._tab = this.validTabs.includes(tabParam) ? tabParam : 'view';
|
this._tab = this.validTabs.includes(tabParam) ? tabParam : 'view';
|
||||||
});
|
});
|
||||||
|
|
||||||
this.userService.userState$
|
const currentSettings = this.appSettingsService.appSettings();
|
||||||
.pipe(
|
if (currentSettings) {
|
||||||
filter(userState => !!userState?.user && userState.loaded),
|
this.isLocalStorage = currentSettings.diskType === 'LOCAL';
|
||||||
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';
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fetchBookRecommendationsIfNeeded(bookId: number): void {
|
private fetchBookRecommendationsIfNeeded(bookId: number): void {
|
||||||
this.appSettings$.pipe(
|
const settings = this.appSettingsService.appSettings();
|
||||||
filter(settings => settings != null),
|
if (!settings || !(settings.similarBookRecommendation ?? false)) {
|
||||||
take(1),
|
return;
|
||||||
filter(settings => settings!.similarBookRecommendation ?? false),
|
}
|
||||||
switchMap(() => this.bookService.getBookRecommendations(bookId)),
|
this.bookService.getBookRecommendations(bookId)
|
||||||
takeUntil(this.destroy$)
|
.pipe(takeUntil(this.destroy$))
|
||||||
).subscribe(recommendations => {
|
.subscribe(recommendations => {
|
||||||
this.recommendedBooks = recommendations.sort(
|
this.recommendedBooks = recommendations.sort(
|
||||||
(a, b) => (b.similarityScore ?? 0) - (a.similarityScore ?? 0)
|
(a, b) => (b.similarityScore ?? 0) - (a.similarityScore ?? 0)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
ngOnDestroy(): void {
|
||||||
|
|||||||
+5
-5
@@ -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'">
|
<form [formGroup]="metadataForm" class="metadata-form" *transloco="let t; prefix: 'metadata.editor'">
|
||||||
@if (isLoading) {
|
@if (isLoading) {
|
||||||
<div class="loading-overlay"></div>
|
<div class="loading-overlay"></div>
|
||||||
@@ -952,7 +952,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (navigationState$ | async) {
|
@if (navigationState()) {
|
||||||
<div class="navigation-center">
|
<div class="navigation-center">
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-left"
|
icon="pi pi-chevron-left"
|
||||||
@@ -965,7 +965,7 @@
|
|||||||
tooltipPosition="bottom">
|
tooltipPosition="bottom">
|
||||||
</p-button>
|
</p-button>
|
||||||
<span class="navigation-position">
|
<span class="navigation-position">
|
||||||
{{ getNavigationPosition() }}
|
{{ navigationPosition() }}
|
||||||
</span>
|
</span>
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-right"
|
icon="pi pi-chevron-right"
|
||||||
@@ -1023,7 +1023,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
<div class="mobile-actions-row">
|
<div class="mobile-actions-row">
|
||||||
@if (navigationState$ | async) {
|
@if (navigationState()) {
|
||||||
<div class="navigation-center">
|
<div class="navigation-center">
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-left"
|
icon="pi pi-chevron-left"
|
||||||
@@ -1036,7 +1036,7 @@
|
|||||||
tooltipPosition="bottom">
|
tooltipPosition="bottom">
|
||||||
</p-button>
|
</p-button>
|
||||||
<span class="navigation-position">
|
<span class="navigation-position">
|
||||||
{{ getNavigationPosition() }}
|
{{ navigationPosition() }}
|
||||||
</span>
|
</span>
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-right"
|
icon="pi pi-chevron-right"
|
||||||
|
|||||||
+61
-122
@@ -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 {InputText} from "primeng/inputtext";
|
||||||
import {Button} from "primeng/button";
|
import {Button} from "primeng/button";
|
||||||
import {Divider} from "primeng/divider";
|
import {Divider} from "primeng/divider";
|
||||||
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule,} from "@angular/forms";
|
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule,} from "@angular/forms";
|
||||||
import {Observable, sample} from "rxjs";
|
import {Observable, sample} from "rxjs";
|
||||||
import {AsyncPipe} from "@angular/common";
|
|
||||||
import {MessageService} from "primeng/api";
|
import {MessageService} from "primeng/api";
|
||||||
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper,} from "../../../../book/model/book.model";
|
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper,} from "../../../../book/model/book.model";
|
||||||
import {UrlHelperService} from "../../../../../shared/service/url-helper.service";
|
import {UrlHelperService} from "../../../../../shared/service/url-helper.service";
|
||||||
@@ -45,7 +44,6 @@ import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/d
|
|||||||
Button,
|
Button,
|
||||||
Divider,
|
Divider,
|
||||||
FormsModule,
|
FormsModule,
|
||||||
AsyncPipe,
|
|
||||||
ReactiveFormsModule,
|
ReactiveFormsModule,
|
||||||
FileUpload,
|
FileUpload,
|
||||||
ProgressSpinner,
|
ProgressSpinner,
|
||||||
@@ -62,7 +60,29 @@ import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/d
|
|||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class MetadataEditorComponent implements OnInit {
|
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() nextBookClicked = new EventEmitter<void>();
|
||||||
@Output() previousBookClicked = new EventEmitter<void>();
|
@Output() previousBookClicked = new EventEmitter<void>();
|
||||||
@Output() closeDialogButtonClicked = new EventEmitter<void>();
|
@Output() closeDialogButtonClicked = new EventEmitter<void>();
|
||||||
@@ -84,6 +104,7 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
private destroyRef = inject(DestroyRef);
|
private destroyRef = inject(DestroyRef);
|
||||||
private appSettingsService = inject(AppSettingsService);
|
private appSettingsService = inject(AppSettingsService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
|
||||||
|
|
||||||
metadataForm: FormGroup;
|
metadataForm: FormGroup;
|
||||||
currentBookId!: number;
|
currentBookId!: number;
|
||||||
@@ -100,12 +121,12 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
|
|
||||||
originalMetadata!: BookMetadata;
|
originalMetadata!: BookMetadata;
|
||||||
|
|
||||||
allAuthors!: string[];
|
get allAuthors(): string[] { return this.uniqueMetadata().authors; }
|
||||||
allCategories!: string[];
|
get allCategories(): string[] { return this.uniqueMetadata().categories; }
|
||||||
allMoods!: string[];
|
get allMoods(): string[] { return this.uniqueMetadata().moods; }
|
||||||
allTags!: string[];
|
get allTags(): string[] { return this.uniqueMetadata().tags; }
|
||||||
allPublishers!: string[];
|
get allPublishers(): string[] { return this.uniqueMetadata().publishers; }
|
||||||
allSeries!: string[];
|
get allSeries(): string[] { return this.uniqueMetadata().series; }
|
||||||
filteredCategories: string[] = [];
|
filteredCategories: string[] = [];
|
||||||
filteredAuthors: string[] = [];
|
filteredAuthors: string[] = [];
|
||||||
authorInputValue = '';
|
authorInputValue = '';
|
||||||
@@ -150,7 +171,16 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
audibleReviewCount: true,
|
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 }) {
|
filterCategories(event: { query: string }) {
|
||||||
const query = event.query.toLowerCase();
|
const query = event.query.toLowerCase();
|
||||||
@@ -356,78 +386,18 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.book$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((book) => {
|
const user = this.userService.currentUser();
|
||||||
const metadata = book?.metadata;
|
if (user) {
|
||||||
if (!metadata) return;
|
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
|
||||||
this.currentBookId = metadata.bookId;
|
this.autoSaveEnabled = user.userSettings.autoSaveMetadata ?? false;
|
||||||
if (this.refreshingBookIds.has(book.id)) {
|
}
|
||||||
this.refreshingBookIds.delete(book.id);
|
|
||||||
this.isAutoFetching = 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 {
|
private populateFormFromMetadata(metadata: BookMetadata): void {
|
||||||
@@ -654,7 +624,6 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
||||||
detail: this.t.translate('metadata.editor.toast.metadataUpdated'),
|
detail: this.t.translate('metadata.editor.toast.metadataUpdated'),
|
||||||
});
|
});
|
||||||
this.prepareAutoComplete();
|
|
||||||
this.metadataForm.markAsPristine();
|
this.metadataForm.markAsPristine();
|
||||||
},
|
},
|
||||||
error: (err: any) => {
|
error: (err: any) => {
|
||||||
@@ -937,6 +906,7 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
event.originalEvent as HttpResponse<unknown>;
|
event.originalEvent as HttpResponse<unknown>;
|
||||||
if (response && response.status === 200) {
|
if (response && response.status === 200) {
|
||||||
this.isUploading = false;
|
this.isUploading = false;
|
||||||
|
this.bookService.handleBookMetadataUpdate(this.currentBookId);
|
||||||
} else {
|
} else {
|
||||||
this.isUploading = false;
|
this.isUploading = false;
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
@@ -960,11 +930,9 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
|
|
||||||
regenerateCover(bookId: number) {
|
regenerateCover(bookId: number) {
|
||||||
this.bookMetadataManageService.regenerateCover(bookId).pipe(
|
this.bookMetadataManageService.regenerateCover(bookId).pipe(
|
||||||
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
|
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe({
|
).subscribe({
|
||||||
next: (updatedBook) => {
|
next: () => {
|
||||||
this.bookService.handleBookUpdate(updatedBook);
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: "success",
|
severity: "success",
|
||||||
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
||||||
@@ -984,12 +952,10 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
generateCustomCover(bookId: number) {
|
generateCustomCover(bookId: number) {
|
||||||
this.isGeneratingCover = true;
|
this.isGeneratingCover = true;
|
||||||
this.bookMetadataManageService.generateCustomCover(bookId).pipe(
|
this.bookMetadataManageService.generateCustomCover(bookId).pipe(
|
||||||
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
|
|
||||||
finalize(() => this.isGeneratingCover = false),
|
finalize(() => this.isGeneratingCover = false),
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe({
|
).subscribe({
|
||||||
next: (updatedBook) => {
|
next: () => {
|
||||||
this.bookService.handleBookUpdate(updatedBook);
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: "success",
|
severity: "success",
|
||||||
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
||||||
@@ -1008,11 +974,9 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
|
|
||||||
regenerateAudiobookCover(bookId: number) {
|
regenerateAudiobookCover(bookId: number) {
|
||||||
this.bookMetadataManageService.regenerateAudiobookCover(bookId).pipe(
|
this.bookMetadataManageService.regenerateAudiobookCover(bookId).pipe(
|
||||||
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
|
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe({
|
).subscribe({
|
||||||
next: (updatedBook) => {
|
next: () => {
|
||||||
this.bookService.handleBookUpdate(updatedBook);
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: "success",
|
severity: "success",
|
||||||
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
||||||
@@ -1032,12 +996,10 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
generateCustomAudiobookCover(bookId: number) {
|
generateCustomAudiobookCover(bookId: number) {
|
||||||
this.isGeneratingAudiobookCover = true;
|
this.isGeneratingAudiobookCover = true;
|
||||||
this.bookMetadataManageService.generateCustomAudiobookCover(bookId).pipe(
|
this.bookMetadataManageService.generateCustomAudiobookCover(bookId).pipe(
|
||||||
switchMap(() => this.bookService.getBookByIdFromAPI(bookId, false)),
|
|
||||||
finalize(() => this.isGeneratingAudiobookCover = false),
|
finalize(() => this.isGeneratingAudiobookCover = false),
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe({
|
).subscribe({
|
||||||
next: (updatedBook) => {
|
next: () => {
|
||||||
this.bookService.handleBookUpdate(updatedBook);
|
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: "success",
|
severity: "success",
|
||||||
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
||||||
@@ -1130,23 +1092,12 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
ref?.onClose.pipe(
|
ref?.onClose.pipe(
|
||||||
take(1),
|
take(1),
|
||||||
filter(result => !!result),
|
filter(result => !!result),
|
||||||
switchMap(() => this.bookService.getBookByIdFromAPI(this.currentBookId, false)),
|
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe(updatedBook => {
|
).subscribe();
|
||||||
this.bookService.handleBookUpdate(updatedBook);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
canNavigatePrevious(): boolean {
|
|
||||||
return this.bookNavigationService.canNavigatePrevious();
|
|
||||||
}
|
|
||||||
|
|
||||||
canNavigateNext(): boolean {
|
|
||||||
return this.bookNavigationService.canNavigateNext();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
navigatePrevious(): void {
|
navigatePrevious(): void {
|
||||||
const prevBookId = this.bookNavigationService.getPreviousBookId();
|
const prevBookId = this.bookNavigationService.previousBookId();
|
||||||
if (prevBookId) {
|
if (prevBookId) {
|
||||||
if (this.autoSaveEnabled && this.metadataForm.dirty) {
|
if (this.autoSaveEnabled && this.metadataForm.dirty) {
|
||||||
this.saveMetadata().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.navigateToBook(prevBookId));
|
this.saveMetadata().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.navigateToBook(prevBookId));
|
||||||
@@ -1157,7 +1108,7 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
navigateNext(): void {
|
navigateNext(): void {
|
||||||
const nextBookId = this.bookNavigationService.getNextBookId();
|
const nextBookId = this.bookNavigationService.nextBookId();
|
||||||
if (nextBookId) {
|
if (nextBookId) {
|
||||||
if (this.autoSaveEnabled && this.metadataForm.dirty) {
|
if (this.autoSaveEnabled && this.metadataForm.dirty) {
|
||||||
this.saveMetadata().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.navigateToBook(nextBookId));
|
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 {
|
isFieldVisible(field: keyof MetadataProviderSpecificFields): boolean {
|
||||||
return this.providerSpecificFields[field] ?? false;
|
return this.providerSpecificFields[field] ?? false;
|
||||||
}
|
}
|
||||||
@@ -1236,11 +1182,8 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
ref?.onClose.pipe(
|
ref?.onClose.pipe(
|
||||||
take(1),
|
take(1),
|
||||||
filter(result => !!result),
|
filter(result => !!result),
|
||||||
switchMap(() => this.bookService.getBookByIdFromAPI(this.currentBookId, false)),
|
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe(updatedBook => {
|
).subscribe();
|
||||||
this.bookService.handleBookUpdate(updatedBook);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onAudiobookCoverUpload(event: FileUploadEvent): void {
|
onAudiobookCoverUpload(event: FileUploadEvent): void {
|
||||||
@@ -1248,11 +1191,7 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
event.originalEvent as HttpResponse<unknown>;
|
event.originalEvent as HttpResponse<unknown>;
|
||||||
if (response && response.status === 200) {
|
if (response && response.status === 200) {
|
||||||
this.isUploading = false;
|
this.isUploading = false;
|
||||||
this.bookService.getBookByIdFromAPI(this.currentBookId, false).pipe(
|
this.bookService.handleBookMetadataUpdate(this.currentBookId);
|
||||||
takeUntilDestroyed(this.destroyRef)
|
|
||||||
).subscribe(updatedBook => {
|
|
||||||
this.bookService.handleBookUpdate(updatedBook);
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
this.isUploading = false;
|
this.isUploading = false;
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
|
|||||||
+1
-1
@@ -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'">
|
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="metadata-picker" *transloco="let t; prefix: 'metadata.picker'">
|
||||||
<div class="dialog-body">
|
<div class="dialog-body">
|
||||||
@if (detailLoading) {
|
@if (detailLoading) {
|
||||||
|
|||||||
+38
-64
@@ -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 {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper} from '../../../../book/model/book.model';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
|
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||||
import {InputText} from 'primeng/inputtext';
|
import {InputText} from 'primeng/inputtext';
|
||||||
import {AsyncPipe} from '@angular/common';
|
|
||||||
import {forkJoin, Observable} from 'rxjs';
|
import {forkJoin, Observable} from 'rxjs';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||||
import {BookService} from '../../../../book/service/book.service';
|
import {BookService} from '../../../../book/service/book.service';
|
||||||
import {BookMetadataManageService} from '../../../../book/service/book-metadata-manage.service';
|
import {BookMetadataManageService} from '../../../../book/service/book-metadata-manage.service';
|
||||||
import {Textarea} from 'primeng/textarea';
|
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 {AutoComplete, AutoCompleteSelectEvent} from 'primeng/autocomplete';
|
||||||
import {Image} from 'primeng/image';
|
import {Image} from 'primeng/image';
|
||||||
import {Checkbox} from 'primeng/checkbox';
|
import {Checkbox} from 'primeng/checkbox';
|
||||||
@@ -34,7 +32,6 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
|||||||
InputText,
|
InputText,
|
||||||
ReactiveFormsModule,
|
ReactiveFormsModule,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
AsyncPipe,
|
|
||||||
Textarea,
|
Textarea,
|
||||||
AutoComplete,
|
AutoComplete,
|
||||||
Image,
|
Image,
|
||||||
@@ -63,13 +60,36 @@ export class MetadataPickerComponent implements OnInit {
|
|||||||
|
|
||||||
@Input() reviewMode!: boolean;
|
@Input() reviewMode!: boolean;
|
||||||
@Input() fetchedMetadata!: BookMetadata;
|
@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;
|
@Input() detailLoading = false;
|
||||||
@Output() goBack = new EventEmitter<boolean>();
|
@Output() goBack = new EventEmitter<boolean>();
|
||||||
|
|
||||||
currentBook: Book | null = null;
|
currentBook: Book | null = null;
|
||||||
|
|
||||||
private allItems: Record<string, string[]> = {};
|
private get allItems(): Record<string, string[]> { return this.uniqueMetadata(); }
|
||||||
filteredItems: Record<string, string[]> = {};
|
filteredItems: Record<string, string[]> = {};
|
||||||
authorInputValue = '';
|
authorInputValue = '';
|
||||||
|
|
||||||
@@ -90,6 +110,8 @@ export class MetadataPickerComponent implements OnInit {
|
|||||||
private formBuilder = inject(MetadataFormBuilder);
|
private formBuilder = inject(MetadataFormBuilder);
|
||||||
private metadataUtils = inject(MetadataUtilsService);
|
private metadataUtils = inject(MetadataUtilsService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
|
||||||
|
|
||||||
|
|
||||||
private enabledProviderFields: MetadataProviderSpecificFields | null = null;
|
private enabledProviderFields: MetadataProviderSpecificFields | null = null;
|
||||||
|
|
||||||
@@ -130,64 +152,16 @@ export class MetadataPickerComponent implements OnInit {
|
|||||||
.filter(item => item.toLowerCase().includes(query));
|
.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 {
|
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 {
|
private patchMetadataToForm(metadata: BookMetadata, book: Book): void {
|
||||||
|
|||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
@if (selectedFetchedMetadata$ | async; as selectedFetchedMetadata) {
|
@if (selectedFetchedMetadata(); as selectedFetchedMetadata) {
|
||||||
<div class="metadata-container">
|
<div class="metadata-container">
|
||||||
<app-metadata-picker
|
<app-metadata-picker
|
||||||
[fetchedMetadata]="selectedFetchedMetadata"
|
[fetchedMetadata]="selectedFetchedMetadata"
|
||||||
[book$]="book$"
|
[book]="book"
|
||||||
[detailLoading]="detailLoading"
|
[detailLoading]="detailLoading"
|
||||||
(goBack)="onGoBack()">
|
(goBack)="onGoBack()">
|
||||||
</app-metadata-picker>
|
</app-metadata-picker>
|
||||||
|
|||||||
+62
-65
@@ -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 {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {InputText} from 'primeng/inputtext';
|
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 {AppSettings} from '../../../../../shared/model/app-settings.model';
|
||||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||||
|
|
||||||
import {BehaviorSubject, combineLatest, Observable, Subject, Subscription, takeUntil} from 'rxjs';
|
import {Subject, Subscription, takeUntil} from 'rxjs';
|
||||||
import {filter, switchMap} from 'rxjs/operators';
|
|
||||||
import {ActivatedRoute} from '@angular/router';
|
|
||||||
import {AsyncPipe} from '@angular/common';
|
|
||||||
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
|
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
|
||||||
import {BookMetadataService} from '../../../../book/service/book-metadata.service';
|
import {BookMetadataService} from '../../../../book/service/book-metadata.service';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
@@ -29,7 +26,6 @@ import {TranslocoDirective} from '@jsverse/transloco';
|
|||||||
InputText,
|
InputText,
|
||||||
MetadataPickerComponent,
|
MetadataPickerComponent,
|
||||||
MultiSelect,
|
MultiSelect,
|
||||||
AsyncPipe,
|
|
||||||
Tooltip,
|
Tooltip,
|
||||||
TranslocoDirective
|
TranslocoDirective
|
||||||
],
|
],
|
||||||
@@ -43,21 +39,48 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
loading: boolean = false;
|
loading: boolean = false;
|
||||||
searchTriggered = 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;
|
@Input() isActiveTab: boolean = false;
|
||||||
|
|
||||||
selectedFetchedMetadata$ = new BehaviorSubject<BookMetadata | null>(null);
|
readonly selectedFetchedMetadata = signal<BookMetadata | null>(null);
|
||||||
detailLoading = false;
|
detailLoading = false;
|
||||||
|
|
||||||
private formBuilder = inject(FormBuilder);
|
private formBuilder = inject(FormBuilder);
|
||||||
private bookMetadataService = inject(BookMetadataService);
|
private bookMetadataService = inject(BookMetadataService);
|
||||||
private appSettingsService = inject(AppSettingsService);
|
private appSettingsService = inject(AppSettingsService);
|
||||||
private route = inject(ActivatedRoute);
|
|
||||||
|
|
||||||
private subscription: Subscription = new Subscription();
|
private subscription: Subscription = new Subscription();
|
||||||
private cancelRequest$ = new Subject<void>();
|
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();
|
providerCounts: Map<string, number> = new Map();
|
||||||
providerLoading: Map<string, boolean> = new Map();
|
providerLoading: Map<string, boolean> = new Map();
|
||||||
@@ -87,64 +110,39 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit() {
|
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 || [];
|
private syncFormFromState(): void {
|
||||||
const validProviders = currentProviders.filter((p: string) => this.providers.includes(p));
|
if (!this.currentBook || !this.currentSettings) {
|
||||||
if (validProviders.length !== currentProviders.length) {
|
return;
|
||||||
this.form.patchValue({provider: validProviders.length > 0 ? validProviders : null});
|
}
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
this.subscription.add(
|
const bookChanged = this.currentBook.id !== this.bookId;
|
||||||
this.route.paramMap
|
if (bookChanged) {
|
||||||
.pipe(
|
this.resetFormFromBook(this.currentBook);
|
||||||
switchMap(params => {
|
if (this.currentSettings.autoBookSearch) {
|
||||||
const bookId = +params.get('id')!;
|
if (this.isActiveTab) {
|
||||||
if (this.bookId !== bookId) {
|
this.onSubmit();
|
||||||
this.bookId = bookId;
|
} else {
|
||||||
this.cancelRequest$.next();
|
this.pendingAutoSearch = true;
|
||||||
this.loading = false;
|
}
|
||||||
this.allFetchedMetadata = [];
|
}
|
||||||
this.filteredMetadata = [];
|
return;
|
||||||
this.providerCounts.clear();
|
}
|
||||||
this.selectedFetchedMetadata$.next(null);
|
|
||||||
}
|
this.updateFormFromBook(this.currentBook);
|
||||||
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!);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private resetFormFromBook(book: Book): void {
|
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.allFetchedMetadata = [];
|
||||||
this.filteredMetadata = [];
|
this.filteredMetadata = [];
|
||||||
this.providerCounts.clear();
|
this.providerCounts.clear();
|
||||||
|
this.providerLoading.clear();
|
||||||
|
this.providerCompletionStatus.clear();
|
||||||
this.metadataByProvider.clear();
|
this.metadataByProvider.clear();
|
||||||
this.selectedProviderFilters = new Set(['all']);
|
this.selectedProviderFilters = new Set(['all']);
|
||||||
this.bookId = book.id;
|
this.bookId = book.id;
|
||||||
@@ -175,7 +173,6 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
this.cancelRequest$.next();
|
this.cancelRequest$.next();
|
||||||
this.cancelRequest$.complete();
|
this.cancelRequest$.complete();
|
||||||
this.subscription.unsubscribe();
|
this.subscription.unsubscribe();
|
||||||
this.selectedFetchedMetadata$.complete();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get isSearchEnabled(): boolean {
|
get isSearchEnabled(): boolean {
|
||||||
@@ -374,7 +371,7 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onBookClick(fetchedMetadata: BookMetadata) {
|
onBookClick(fetchedMetadata: BookMetadata) {
|
||||||
this.selectedFetchedMetadata$.next(fetchedMetadata);
|
this.selectedFetchedMetadata.set(fetchedMetadata);
|
||||||
|
|
||||||
const enrichment = this.getDetailEnrichmentInfo(fetchedMetadata);
|
const enrichment = this.getDetailEnrichmentInfo(fetchedMetadata);
|
||||||
|
|
||||||
@@ -384,10 +381,10 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
.pipe(takeUntil(this.cancelRequest$))
|
.pipe(takeUntil(this.cancelRequest$))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (enriched) => {
|
next: (enriched) => {
|
||||||
const current = this.selectedFetchedMetadata$.value;
|
const current = this.selectedFetchedMetadata();
|
||||||
const currentId = current && this.getProviderItemId(current, enrichment.provider);
|
const currentId = current && this.getProviderItemId(current, enrichment.provider);
|
||||||
if (currentId === enrichment.id) {
|
if (currentId === enrichment.id) {
|
||||||
this.selectedFetchedMetadata$.next(enriched);
|
this.selectedFetchedMetadata.set(enriched);
|
||||||
}
|
}
|
||||||
this.detailLoading = false;
|
this.detailLoading = false;
|
||||||
},
|
},
|
||||||
@@ -433,7 +430,7 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
|
|
||||||
onGoBack() {
|
onGoBack() {
|
||||||
this.detailLoading = false;
|
this.detailLoading = false;
|
||||||
this.selectedFetchedMetadata$.next(null);
|
this.selectedFetchedMetadata.set(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
sanitizeHtml(htmlString: string | null | undefined): string {
|
sanitizeHtml(htmlString: string | null | undefined): string {
|
||||||
|
|||||||
+14
-22
@@ -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-viewer-container" *transloco="let t; prefix: 'metadata.viewer'">
|
||||||
<div class="metadata-header">
|
<div class="metadata-header">
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (navigationState$ | async) {
|
@if (navigationState()) {
|
||||||
<div class="navigation-buttons-mobile">
|
<div class="navigation-buttons-mobile">
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-left"
|
icon="pi pi-chevron-left"
|
||||||
@@ -74,7 +74,7 @@
|
|||||||
tooltipPosition="bottom">
|
tooltipPosition="bottom">
|
||||||
</p-button>
|
</p-button>
|
||||||
<span class="navigation-position">
|
<span class="navigation-position">
|
||||||
{{ getNavigationPosition() }}
|
{{ navigationPosition() }}
|
||||||
</span>
|
</span>
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-right"
|
icon="pi pi-chevron-right"
|
||||||
@@ -620,10 +620,10 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (userService.userState$ | async; as userState) {
|
@if (userService.currentUser(); as currentUser) {
|
||||||
<div class="action-buttons-container">
|
<div class="action-buttons-container">
|
||||||
<div class="action-buttons">
|
<div class="action-buttons">
|
||||||
@if (navigationState$ | async) {
|
@if (navigationState()) {
|
||||||
<div class="action-group navigation-group">
|
<div class="action-group navigation-group">
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-left"
|
icon="pi pi-chevron-left"
|
||||||
@@ -635,7 +635,7 @@
|
|||||||
tooltipPosition="bottom">
|
tooltipPosition="bottom">
|
||||||
</p-button>
|
</p-button>
|
||||||
<span class="navigation-position">
|
<span class="navigation-position">
|
||||||
{{ getNavigationPosition() }}
|
{{ navigationPosition() }}
|
||||||
</span>
|
</span>
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-chevron-right"
|
icon="pi pi-chevron-right"
|
||||||
@@ -651,28 +651,22 @@
|
|||||||
}
|
}
|
||||||
@if (hasDigitalFile(book)) {
|
@if (hasDigitalFile(book)) {
|
||||||
<div class="action-group primary-actions">
|
<div class="action-group primary-actions">
|
||||||
@if (readMenuItems$ | async; as readItems) {
|
@if (readMenuItems().length > 0) {
|
||||||
@if (readItems.length > 0) {
|
<p-splitbutton [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" [model]="readMenuItems()" (onClick)="read(book.id)" severity="primary" class="read-button-responsive"/>
|
||||||
<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"/>
|
|
||||||
}
|
|
||||||
} @else {
|
} @else {
|
||||||
<p-button [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" (onClick)="read(book.id)" severity="primary" class="read-button-responsive"/>
|
<p-button [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" (onClick)="read(book.id)" severity="primary" class="read-button-responsive"/>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="action-group secondary-actions">
|
<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 ((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]="downloadMenuItems()" (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]="downloadItems" (onClick)="download(book)" severity="success" outlined class="mobile-icon-only"/>
|
|
||||||
}
|
|
||||||
} @else {
|
} @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>
|
<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
|
<p-button
|
||||||
[label]="isAutoFetching ? t('fetchingBtn') : t('fetchMetadataBtn')"
|
[label]="isAutoFetching ? t('fetchingBtn') : t('fetchMetadataBtn')"
|
||||||
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
|
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
|
||||||
@@ -685,11 +679,9 @@
|
|||||||
class="mobile-icon-only">
|
class="mobile-icon-only">
|
||||||
</p-button>
|
</p-button>
|
||||||
}
|
}
|
||||||
@if (otherItems$ | async; as otherItems) {
|
@if (otherItems().length > 0) {
|
||||||
@if (otherItems.length > 0) {
|
<p-button icon="pi pi-ellipsis-v" severity="info" outlined (click)="entitymenu.toggle($event)"></p-button>
|
||||||
<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>
|
||||||
<p-tieredMenu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-tieredMenu>
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+361
-399
@@ -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 {Button} from 'primeng/button';
|
||||||
import {AsyncPipe, DecimalPipe, NgClass} from '@angular/common';
|
import {DecimalPipe, NgClass} from '@angular/common';
|
||||||
import {combineLatest, Observable} from 'rxjs';
|
|
||||||
import {BookService} from '../../../../book/service/book.service';
|
import {BookService} from '../../../../book/service/book.service';
|
||||||
import {BookFileService} from '../../../../book/service/book-file.service';
|
import {BookFileService} from '../../../../book/service/book-file.service';
|
||||||
import {Rating, RatingRateEvent} from 'primeng/rating';
|
import {Rating, RatingRateEvent} from 'primeng/rating';
|
||||||
@@ -18,7 +17,7 @@ import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
|||||||
import {ProgressBar} from 'primeng/progressbar';
|
import {ProgressBar} from 'primeng/progressbar';
|
||||||
import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type.enum';
|
import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type.enum';
|
||||||
import {Router} from '@angular/router';
|
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 {Menu} from 'primeng/menu';
|
||||||
import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||||
import {DatePicker} from 'primeng/datepicker';
|
import {DatePicker} from 'primeng/datepicker';
|
||||||
@@ -46,10 +45,28 @@ import DOMPurify from 'dompurify';
|
|||||||
standalone: true,
|
standalone: true,
|
||||||
templateUrl: './metadata-viewer.component.html',
|
templateUrl: './metadata-viewer.component.html',
|
||||||
styleUrl: './metadata-viewer.component.scss',
|
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 {
|
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[] = [];
|
@Input() recommendedBooks: BookRecommendation[] = [];
|
||||||
private originalRecommendedBooks: BookRecommendation[] = [];
|
private originalRecommendedBooks: BookRecommendation[] = [];
|
||||||
|
|
||||||
@@ -64,16 +81,305 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
|||||||
private authorService = inject(AuthorService);
|
private authorService = inject(AuthorService);
|
||||||
protected urlHelper = inject(UrlHelperService);
|
protected urlHelper = inject(UrlHelperService);
|
||||||
protected userService = inject(UserService);
|
protected userService = inject(UserService);
|
||||||
|
private appSettingsService = inject(AppSettingsService);
|
||||||
private confirmationService = inject(ConfirmationService);
|
private confirmationService = inject(ConfirmationService);
|
||||||
|
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private destroyRef = inject(DestroyRef);
|
private destroyRef = inject(DestroyRef);
|
||||||
private dialogRef?: DynamicDialogRef;
|
private dialogRef?: DynamicDialogRef;
|
||||||
|
private userState = this.userService.currentUser;
|
||||||
|
private appSettings = this.appSettingsService.appSettings;
|
||||||
|
|
||||||
readMenuItems$!: Observable<MenuItem[]>;
|
readonly readMenuItems = computed<MenuItem[]>(() => {
|
||||||
refreshMenuItems$!: Observable<MenuItem[]>;
|
const book = this.currentBook();
|
||||||
otherItems$!: Observable<MenuItem[]>;
|
if (!book) {
|
||||||
downloadMenuItems$!: Observable<MenuItem[]>;
|
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[] = [];
|
bookInSeries: Book[] = [];
|
||||||
@ViewChild(Image) private coverImage?: Image;
|
@ViewChild(Image) private coverImage?: Image;
|
||||||
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
||||||
@@ -106,10 +412,16 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
|||||||
|
|
||||||
private bookNavigationService = inject(BookNavigationService);
|
private bookNavigationService = inject(BookNavigationService);
|
||||||
private metadataHostService = inject(BookMetadataHostService);
|
private metadataHostService = inject(BookMetadataHostService);
|
||||||
private appSettingsService = inject(AppSettingsService);
|
|
||||||
private appSettings$ = this.appSettingsService.appSettings$;
|
|
||||||
amazonDomain = 'com';
|
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 {
|
ngOnInit(): void {
|
||||||
this.destroyRef.onDestroy(() => this.coverImage?.closePreview());
|
this.destroyRef.onDestroy(() => this.coverImage?.closePreview());
|
||||||
@@ -118,359 +430,24 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
|||||||
window.addEventListener('popstate', onPopState);
|
window.addEventListener('popstate', onPopState);
|
||||||
this.destroyRef.onDestroy(() => window.removeEventListener('popstate', onPopState));
|
this.destroyRef.onDestroy(() => window.removeEventListener('popstate', onPopState));
|
||||||
|
|
||||||
this.readMenuItems$ = this.book$.pipe(
|
const user = this.userService.currentUser();
|
||||||
filter((book): book is Book => book !== null),
|
if (user) {
|
||||||
map((book): MenuItem[] => {
|
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
|
||||||
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')
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get readable alternative formats and group by type
|
const settings = this.appSettingsService.appSettings();
|
||||||
const readableAlternatives = book.alternativeFormats?.filter(f =>
|
if (settings) {
|
||||||
f.bookType && ['PDF', 'EPUB', 'FB2', 'MOBI', 'AZW3', 'CBX', 'AUDIOBOOK'].includes(f.bookType)
|
this.amazonDomain = settings.metadataProviderSettings?.amazon?.domain ?? 'com';
|
||||||
) ?? [];
|
}
|
||||||
|
|
||||||
// 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';
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges): void {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
if (changes['recommendedBooks']) {
|
if (changes['recommendedBooks']) {
|
||||||
this.originalRecommendedBooks = [...this.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 {
|
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
|
||||||
this.bookService.getBooksInSeries(bookId).pipe(
|
this.bookService.getBooksInSeries(bookId).pipe(
|
||||||
tap(series => {
|
tap(series => {
|
||||||
@@ -478,9 +455,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
|||||||
this.bookInSeries = series;
|
this.bookInSeries = series;
|
||||||
this.originalRecommendedBooks = [...this.recommendedBooks];
|
this.originalRecommendedBooks = [...this.recommendedBooks];
|
||||||
}),
|
}),
|
||||||
switchMap(() => this.book$.pipe(take(1))),
|
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe(book => this.filterRecommendations(book));
|
).subscribe(() => this.filterRecommendations(this.book));
|
||||||
}
|
}
|
||||||
|
|
||||||
private filterRecommendations(book: Book | null): void {
|
private filterRecommendations(book: Book | null): void {
|
||||||
@@ -695,7 +671,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
|||||||
}
|
}
|
||||||
|
|
||||||
assignShelf(bookId: number) {
|
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 {
|
updateReadStatus(status: ReadStatus): void {
|
||||||
@@ -703,31 +679,30 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.book$.pipe(take(1)).subscribe(book => {
|
const book = this.book;
|
||||||
if (!book || !book.id) {
|
if (!book?.id) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.bookService.updateBookReadStatus(book.id, status).subscribe({
|
this.bookService.updateBookReadStatus(book.id, status).subscribe({
|
||||||
next: (updatedBooks) => {
|
next: () => {
|
||||||
this.selectedReadStatus = status;
|
this.selectedReadStatus = status;
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
summary: this.t.translate('metadata.viewer.toast.readStatusUpdatedSummary'),
|
summary: this.t.translate('metadata.viewer.toast.readStatusUpdatedSummary'),
|
||||||
detail: this.t.translate('metadata.viewer.toast.readStatusUpdatedDetail', { status: this.getStatusLabel(status) }),
|
detail: this.t.translate('metadata.viewer.toast.readStatusUpdatedDetail', { status: this.getStatusLabel(status) }),
|
||||||
life: 2000
|
life: 2000
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
error: (err) => {
|
error: (err) => {
|
||||||
console.error('Failed to update read status:', err);
|
console.error('Failed to update read status:', err);
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'error',
|
severity: 'error',
|
||||||
summary: this.t.translate('metadata.viewer.toast.readStatusFailedSummary'),
|
summary: this.t.translate('metadata.viewer.toast.readStatusFailedSummary'),
|
||||||
detail: this.t.translate('metadata.viewer.toast.readStatusFailedDetail'),
|
detail: this.t.translate('metadata.viewer.toast.readStatusFailedDetail'),
|
||||||
life: 3000
|
life: 3000
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1272,23 +1247,15 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
|||||||
protected readonly ResetProgressTypes = ResetProgressTypes;
|
protected readonly ResetProgressTypes = ResetProgressTypes;
|
||||||
protected readonly ReadStatus = ReadStatus;
|
protected readonly ReadStatus = ReadStatus;
|
||||||
|
|
||||||
canNavigatePrevious(): boolean {
|
|
||||||
return this.bookNavigationService.canNavigatePrevious();
|
|
||||||
}
|
|
||||||
|
|
||||||
canNavigateNext(): boolean {
|
|
||||||
return this.bookNavigationService.canNavigateNext();
|
|
||||||
}
|
|
||||||
|
|
||||||
navigatePrevious(): void {
|
navigatePrevious(): void {
|
||||||
const prevBookId = this.bookNavigationService.getPreviousBookId();
|
const prevBookId = this.bookNavigationService.previousBookId();
|
||||||
if (prevBookId) {
|
if (prevBookId) {
|
||||||
this.navigateToBook(prevBookId);
|
this.navigateToBook(prevBookId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
navigateNext(): void {
|
navigateNext(): void {
|
||||||
const nextBookId = this.bookNavigationService.getNextBookId();
|
const nextBookId = this.bookNavigationService.nextBookId();
|
||||||
if (nextBookId) {
|
if (nextBookId) {
|
||||||
this.navigateToBook(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 {
|
hasDigitalFile(book: Book): boolean {
|
||||||
return !!book?.primaryFile;
|
return !!book?.primaryFile;
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-15
@@ -1,6 +1,6 @@
|
|||||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
import {Component, inject, Input, OnDestroy} from '@angular/core';
|
||||||
import {Observable, Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {filter, switchMap, takeUntil} from 'rxjs/operators';
|
import {takeUntil} from 'rxjs/operators';
|
||||||
import {Book} from '../../../../book/model/book.model';
|
import {Book} from '../../../../book/model/book.model';
|
||||||
import {SidecarMetadata, SidecarService, SidecarSyncStatus} from '../../../service/sidecar.service';
|
import {SidecarMetadata, SidecarService, SidecarSyncStatus} from '../../../service/sidecar.service';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
@@ -17,8 +17,21 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
|||||||
styleUrls: ['./sidecar-viewer.component.scss'],
|
styleUrls: ['./sidecar-viewer.component.scss'],
|
||||||
imports: [Button, Tag, Tooltip, JsonPipe, DatePipe, TranslocoDirective]
|
imports: [Button, Tag, Tooltip, JsonPipe, DatePipe, TranslocoDirective]
|
||||||
})
|
})
|
||||||
export class SidecarViewerComponent implements OnInit, OnDestroy {
|
export class SidecarViewerComponent implements OnDestroy {
|
||||||
@Input() book$!: Observable<Book>;
|
@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 sidecarService = inject(SidecarService);
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
@@ -33,16 +46,6 @@ export class SidecarViewerComponent implements OnInit, OnDestroy {
|
|||||||
currentBookId: number | null = null;
|
currentBookId: number | null = null;
|
||||||
error: string | 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 {
|
loadSidecarData(bookId: number): void {
|
||||||
this.loading = true;
|
this.loading = true;
|
||||||
this.error = null;
|
this.error = null;
|
||||||
|
|||||||
+13
-44
@@ -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 {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||||
|
|
||||||
import {InputText} from 'primeng/inputtext';
|
import {InputText} from 'primeng/inputtext';
|
||||||
@@ -14,7 +14,6 @@ import {Checkbox} from 'primeng/checkbox';
|
|||||||
import {AutoComplete} from 'primeng/autocomplete';
|
import {AutoComplete} from 'primeng/autocomplete';
|
||||||
import {AutoCompleteSelectEvent} from 'primeng/autocomplete';
|
import {AutoCompleteSelectEvent} from 'primeng/autocomplete';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {filter, take} from "rxjs/operators";
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-bulk-metadata-update-component',
|
selector: 'app-bulk-metadata-update-component',
|
||||||
@@ -63,13 +62,15 @@ export class BulkMetadataUpdateComponent implements OnInit {
|
|||||||
private readonly bookService = inject(BookService);
|
private readonly bookService = inject(BookService);
|
||||||
private readonly bookMetadataManageService = inject(BookMetadataManageService);
|
private readonly bookMetadataManageService = inject(BookMetadataManageService);
|
||||||
private readonly messageService = inject(MessageService);
|
private readonly messageService = inject(MessageService);
|
||||||
|
private readonly injector = inject(Injector);
|
||||||
|
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
|
||||||
|
|
||||||
allAuthors!: string[];
|
get allAuthors(): string[] { return this.uniqueMetadata().authors; }
|
||||||
allGenres!: string[];
|
get allGenres(): string[] { return this.uniqueMetadata().categories; }
|
||||||
allMoods!: string[];
|
get allMoods(): string[] { return this.uniqueMetadata().moods; }
|
||||||
allTags!: string[];
|
get allTags(): string[] { return this.uniqueMetadata().tags; }
|
||||||
allPublishers!: string[];
|
get allPublishers(): string[] { return this.uniqueMetadata().publishers; }
|
||||||
allSeries!: string[];
|
get allSeries(): string[] { return this.uniqueMetadata().series; }
|
||||||
filteredGenres: string[] = [];
|
filteredGenres: string[] = [];
|
||||||
filteredAuthors: string[] = [];
|
filteredAuthors: string[] = [];
|
||||||
filteredMoods: string[] = [];
|
filteredMoods: string[] = [];
|
||||||
@@ -121,7 +122,7 @@ export class BulkMetadataUpdateComponent implements OnInit {
|
|||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.bookIds = this.config.data?.bookIds ?? [];
|
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({
|
this.metadataForm = this.fb.group({
|
||||||
authors: [],
|
authors: [],
|
||||||
@@ -135,41 +136,9 @@ export class BulkMetadataUpdateComponent implements OnInit {
|
|||||||
tags: []
|
tags: []
|
||||||
});
|
});
|
||||||
|
|
||||||
this.bookService.bookState$
|
effect(() => {
|
||||||
.pipe(
|
this.books = this.bookService.books().filter(book => this.bookIds.includes(book.id));
|
||||||
filter((bookState) => bookState.loaded),
|
}, {injector: this.injector});
|
||||||
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);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onFieldClearToggle(field: keyof typeof this.clearFields): void {
|
onFieldClearToggle(field: keyof typeof this.clearFields): void {
|
||||||
|
|||||||
+1
-1
@@ -54,7 +54,7 @@ export class CoverSearchComponent implements OnInit {
|
|||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.bookId = this.dynamicDialogConfig.data.bookId;
|
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
|
// Use explicitly provided coverType, or auto-detect based on primary file
|
||||||
if (this.dynamicDialogConfig.data.coverType) {
|
if (this.dynamicDialogConfig.data.coverType) {
|
||||||
|
|||||||
+11
-16
@@ -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 {CommonModule} from '@angular/common';
|
||||||
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||||
import {TableModule} from 'primeng/table';
|
import {TableModule} from 'primeng/table';
|
||||||
@@ -77,6 +77,16 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
|
|||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
private routeSub!: Subscription;
|
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[] = [];
|
authors: MetadataItem[] = [];
|
||||||
categories: MetadataItem[] = [];
|
categories: MetadataItem[] = [];
|
||||||
@@ -136,7 +146,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
|
|||||||
];
|
];
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.loadMetadata();
|
|
||||||
this.routeSub = this.route.queryParams.subscribe(params => {
|
this.routeSub = this.route.queryParams.subscribe(params => {
|
||||||
const tabParam = params['tab'] as MetadataType;
|
const tabParam = params['tab'] as MetadataType;
|
||||||
if (this.validTabs.includes(tabParam)) {
|
if (this.validTabs.includes(tabParam)) {
|
||||||
@@ -164,16 +173,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
|
|||||||
this.routeSub.unsubscribe();
|
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[]) {
|
private extractMetadata(books: Book[]) {
|
||||||
const authorsMap = new Map<string, Set<number>>();
|
const authorsMap = new Map<string, Set<number>>();
|
||||||
const categoriesMap = 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.renameTarget = '';
|
||||||
this.mergingInProgress = false;
|
this.mergingInProgress = false;
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
this.loadMetadata();
|
|
||||||
},
|
},
|
||||||
error: (error) => {
|
error: (error) => {
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
@@ -365,7 +363,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
confirmMerge() {
|
confirmMerge() {
|
||||||
const selected = this.getSelectedItems(this.currentMergeType);
|
|
||||||
if (!this.mergeTarget.trim()) {
|
if (!this.mergeTarget.trim()) {
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'warn',
|
severity: 'warn',
|
||||||
@@ -423,7 +420,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
|
|||||||
this.clearSelection(this.currentMergeType);
|
this.clearSelection(this.currentMergeType);
|
||||||
this.mergingInProgress = false;
|
this.mergingInProgress = false;
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
this.loadMetadata();
|
|
||||||
},
|
},
|
||||||
error: (error) => {
|
error: (error) => {
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
@@ -479,7 +475,6 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
|
|||||||
this.clearSelection(this.currentMergeType);
|
this.clearSelection(this.currentMergeType);
|
||||||
this.deletingInProgress = false;
|
this.deletingInProgress = false;
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
this.loadMetadata();
|
|
||||||
},
|
},
|
||||||
error: (error) => {
|
error: (error) => {
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user