Introduced additional library charts to surface meaningful insights (#2390)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -15,7 +15,6 @@ import {CbxReaderComponent} from './features/readers/cbx-reader/cbx-reader.compo
|
||||
import {MainDashboardComponent} from './features/dashboard/components/main-dashboard/main-dashboard.component';
|
||||
import {SeriesPageComponent} from './features/book/components/series-page/series-page.component';
|
||||
import {MetadataManagerComponent} from './features/metadata/component/metadata-manager/metadata-manager.component';
|
||||
import {StatsComponent} from './features/stats/component/stats-component';
|
||||
import {PdfReaderComponent} from './features/readers/pdf-reader/pdf-reader.component';
|
||||
import {BookdropFileReviewComponent} from './features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component';
|
||||
import {LoginGuard} from './shared/components/setup/login.guard';
|
||||
@@ -24,7 +23,8 @@ import {BookdropGuard} from './core/security/guards/bookdrop.guard';
|
||||
import {LibraryStatsGuard} from './core/security/guards/library-stats.guard';
|
||||
import {UserStatsGuard} from './core/security/guards/user-stats.guard';
|
||||
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
|
||||
import {EbookReaderComponent} from './features/readers/ebook-reader/ebook-reader.component';
|
||||
import {EbookReaderComponent} from './features/readers/ebook-reader';
|
||||
import {LibraryStatsComponent} from './features/stats/component/library-stats/library-stats.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
@@ -54,7 +54,7 @@ export const routes: Routes = [
|
||||
{path: 'book/:bookId', component: BookMetadataCenterComponent, canActivate: [AuthGuard]},
|
||||
{path: 'bookdrop', component: BookdropFileReviewComponent, canActivate: [BookdropGuard]},
|
||||
{path: 'metadata-manager', component: MetadataManagerComponent, canActivate: [EditMetadataGuard]},
|
||||
{path: 'library-stats', component: StatsComponent, canActivate: [LibraryStatsGuard]},
|
||||
{path: 'library-stats', component: LibraryStatsComponent, canActivate: [LibraryStatsGuard]},
|
||||
{path: 'reading-stats', component: UserStatsComponent, canActivate: [UserStatsGuard]},
|
||||
]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// Shared chart styles for consistency across all chart components
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
|
||||
.badge-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 0.75rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 0.9rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
.badge-value {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
<div class="author-universe-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-globe author-title-icon"></i>
|
||||
Author Universe
|
||||
</h3>
|
||||
<p class="chart-description">Explore your authors by books, ratings, and reading progress</p>
|
||||
</div>
|
||||
@if (totalAuthors > 0) {
|
||||
<div class="author-count-badge">
|
||||
{{ totalAuthors }} authors
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalAuthors > 0) {
|
||||
<div class="chart-legend-info">
|
||||
<span class="legend-note">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
Bubble size = total pages • Position = books vs rating • Color = completion %
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (insights.length > 0) {
|
||||
<div class="insights-section">
|
||||
<div class="insights-grid">
|
||||
@for (insight of insights; track insight) {
|
||||
<div class="insight-card">
|
||||
<i class="pi pi-star-fill insight-icon"></i>
|
||||
<span class="insight-text">{{ insight }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@if (totalAuthors === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No author data available. Authors need at least 2 books to appear.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.author-universe-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.author-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #8b5cf6;
|
||||
}
|
||||
|
||||
.author-count-badge {
|
||||
background: linear-gradient(135deg, rgba(139, 92, 246, 0.2), rgba(139, 92, 246, 0.1));
|
||||
border: 1px solid rgba(139, 92, 246, 0.3);
|
||||
border-radius: 20px;
|
||||
padding: 0.4rem 1rem;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
color: #a78bfa;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chart-legend-info {
|
||||
margin-bottom: 1rem;
|
||||
|
||||
.legend-note {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-secondary-color);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 6px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
|
||||
i {
|
||||
color: #8b5cf6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 350px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.insights-section {
|
||||
margin-top: 1.25rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
background: linear-gradient(135deg, rgba(139, 92, 246, 0.1), rgba(139, 92, 246, 0.05));
|
||||
border: 1px solid rgba(139, 92, 246, 0.2);
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem 0.85rem;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: linear-gradient(135deg, rgba(139, 92, 246, 0.15), rgba(139, 92, 246, 0.08));
|
||||
border-color: rgba(139, 92, 246, 0.35);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.insight-icon {
|
||||
color: #f59e0b;
|
||||
font-size: 0.85rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.insight-text {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-color, #ffffff);
|
||||
line-height: 1.3;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.chart-legend-info {
|
||||
.legend-note {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 260px;
|
||||
}
|
||||
|
||||
.author-count-badge {
|
||||
font-size: 0.8rem;
|
||||
padding: 0.3rem 0.75rem;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
padding: 0.5rem 0.7rem;
|
||||
|
||||
.insight-text {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+561
@@ -0,0 +1,561 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, TooltipItem} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.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';
|
||||
|
||||
interface AuthorStats {
|
||||
name: string;
|
||||
bookCount: number;
|
||||
totalPages: number;
|
||||
avgRating: number;
|
||||
readCount: number;
|
||||
completionRate: number;
|
||||
categories: string[];
|
||||
ratingSum: number;
|
||||
ratingCount: number;
|
||||
}
|
||||
|
||||
interface BubbleDataPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
r: number;
|
||||
authorStats: AuthorStats;
|
||||
}
|
||||
|
||||
type AuthorUniverseChartData = ChartData<'bubble', BubbleDataPoint[], string>;
|
||||
|
||||
const COMPLETION_COLORS = {
|
||||
high: '#22c55e', // 75-100% read - green
|
||||
medium: '#f59e0b', // 50-74% read - amber
|
||||
low: '#3b82f6', // 25-49% read - blue
|
||||
minimal: '#8b5cf6', // 1-24% read - purple
|
||||
unread: '#6b7280' // 0% read - gray
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-author-universe-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './author-universe-chart.component.html',
|
||||
styleUrls: ['./author-universe-chart.component.scss']
|
||||
})
|
||||
export class AuthorUniverseChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'bubble' as const;
|
||||
public chartOptions: ChartConfiguration<'bubble'>['options'];
|
||||
public totalAuthors = 0;
|
||||
public topAuthors: AuthorStats[] = [];
|
||||
public insights: string[] = [];
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<AuthorUniverseChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<AuthorUniverseChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing author universe data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private initChartOptions(): void {
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 20, right: 20, bottom: 20, left: 20}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Books in Library',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
precision: 0,
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.08)'
|
||||
},
|
||||
border: {display: false},
|
||||
min: 0
|
||||
},
|
||||
y: {
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Average Rating',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
callback: (value) => value.toLocaleString()
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.08)'
|
||||
},
|
||||
border: {display: false},
|
||||
min: 0,
|
||||
max: 5.5,
|
||||
beginAtZero: true
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
color: 'rgba(255, 255, 255, 0.9)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
padding: 15,
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle'
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#8b5cf6',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 16,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context: TooltipItem<'bubble'>[]) => {
|
||||
const raw = context[0].raw as BubbleDataPoint;
|
||||
return raw.authorStats.name;
|
||||
},
|
||||
label: (context: TooltipItem<'bubble'>) => {
|
||||
const raw = context.raw as BubbleDataPoint;
|
||||
const stats = raw.authorStats;
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`Books: ${stats.bookCount}`);
|
||||
lines.push(`Total Pages: ${stats.totalPages.toLocaleString()}`);
|
||||
|
||||
if (stats.avgRating > 0) {
|
||||
lines.push(`Avg Rating: ${stats.avgRating.toFixed(2)} ★`);
|
||||
} else {
|
||||
lines.push(`Avg Rating: No ratings`);
|
||||
}
|
||||
|
||||
lines.push(`Read: ${stats.readCount}/${stats.bookCount} (${Math.round(stats.completionRate)}%)`);
|
||||
|
||||
if (stats.categories.length > 0) {
|
||||
const topCategories = stats.categories.slice(0, 3).join(', ');
|
||||
lines.push(`Genres: ${topCategories}`);
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: true,
|
||||
mode: 'nearest'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.totalAuthors = 0;
|
||||
this.topAuthors = [];
|
||||
this.insights = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
const authorStats = this.calculateAuthorStats(filteredBooks);
|
||||
|
||||
this.totalAuthors = authorStats.length;
|
||||
this.topAuthors = authorStats.slice(0, 10);
|
||||
this.insights = this.generateInsights(authorStats);
|
||||
this.updateChartData(authorStats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculateAuthorStats(books: Book[]): AuthorStats[] {
|
||||
// Single-pass aggregation - O(n) where n = books * avg_authors_per_book
|
||||
const authorMap = new Map<string, AuthorStats>();
|
||||
const categorySet = new Map<string, Set<string>>(); // Track unique categories per author
|
||||
|
||||
for (const book of books) {
|
||||
const authors = book.metadata?.authors;
|
||||
if (!authors || authors.length === 0) continue;
|
||||
|
||||
// Get book's rating once
|
||||
const bookRating = book.personalRating ||
|
||||
book.metadata?.goodreadsRating ||
|
||||
book.metadata?.amazonRating ||
|
||||
book.metadata?.hardcoverRating || 0;
|
||||
|
||||
const isRead = book.readStatus === ReadStatus.READ;
|
||||
const pageCount = book.metadata?.pageCount || 0;
|
||||
const bookCategories = book.metadata?.categories;
|
||||
|
||||
for (const authorName of authors) {
|
||||
const normalizedName = authorName.trim();
|
||||
if (!normalizedName) continue;
|
||||
|
||||
let stats = authorMap.get(normalizedName);
|
||||
if (!stats) {
|
||||
stats = {
|
||||
name: normalizedName,
|
||||
bookCount: 0,
|
||||
totalPages: 0,
|
||||
avgRating: 0,
|
||||
readCount: 0,
|
||||
completionRate: 0,
|
||||
categories: [],
|
||||
ratingSum: 0,
|
||||
ratingCount: 0
|
||||
};
|
||||
authorMap.set(normalizedName, stats);
|
||||
categorySet.set(normalizedName, new Set());
|
||||
}
|
||||
|
||||
// Aggregate in single pass
|
||||
stats.bookCount++;
|
||||
stats.totalPages += pageCount;
|
||||
|
||||
if (isRead) {
|
||||
stats.readCount++;
|
||||
}
|
||||
|
||||
if (bookRating > 0) {
|
||||
stats.ratingSum += bookRating;
|
||||
stats.ratingCount++;
|
||||
}
|
||||
|
||||
// Track unique categories using Set (O(1) lookup)
|
||||
if (bookCategories) {
|
||||
const catSet = categorySet.get(normalizedName)!;
|
||||
for (const cat of bookCategories) {
|
||||
catSet.add(cat);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finalize calculations and filter - only process authors with 2+ books
|
||||
const results: AuthorStats[] = [];
|
||||
|
||||
for (const [name, stats] of authorMap) {
|
||||
if (stats.bookCount < 2) continue; // Skip single-book authors early
|
||||
|
||||
stats.completionRate = (stats.readCount / stats.bookCount) * 100;
|
||||
stats.avgRating = stats.ratingCount > 0 ? stats.ratingSum / stats.ratingCount : 0;
|
||||
stats.categories = Array.from(categorySet.get(name) || []).slice(0, 5); // Limit to 5 categories
|
||||
|
||||
results.push(stats);
|
||||
}
|
||||
|
||||
// Sort and limit to top 50 for rendering performance
|
||||
results.sort((a, b) => b.bookCount - a.bookCount);
|
||||
return results.slice(0, 50);
|
||||
}
|
||||
|
||||
private updateChartData(authorStats: AuthorStats[]): void {
|
||||
if (authorStats.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
return;
|
||||
}
|
||||
|
||||
// Group authors by completion rate for different colored datasets
|
||||
const highCompletion: BubbleDataPoint[] = [];
|
||||
const mediumCompletion: BubbleDataPoint[] = [];
|
||||
const lowCompletion: BubbleDataPoint[] = [];
|
||||
const minimalCompletion: BubbleDataPoint[] = [];
|
||||
const unread: BubbleDataPoint[] = [];
|
||||
|
||||
const maxPages = Math.max(...authorStats.map(s => s.totalPages));
|
||||
|
||||
for (const stats of authorStats) {
|
||||
// Scale bubble radius based on total pages (min 5, max 25)
|
||||
const normalizedPages = stats.totalPages / maxPages;
|
||||
const radius = 5 + (normalizedPages * 20);
|
||||
|
||||
const point: BubbleDataPoint = {
|
||||
x: stats.bookCount,
|
||||
y: stats.avgRating || 2.5, // Default to 2.5 if no rating
|
||||
r: Math.max(5, Math.min(25, radius)),
|
||||
authorStats: stats
|
||||
};
|
||||
|
||||
if (stats.completionRate >= 75) {
|
||||
highCompletion.push(point);
|
||||
} else if (stats.completionRate >= 50) {
|
||||
mediumCompletion.push(point);
|
||||
} else if (stats.completionRate >= 25) {
|
||||
lowCompletion.push(point);
|
||||
} else if (stats.completionRate > 0) {
|
||||
minimalCompletion.push(point);
|
||||
} else {
|
||||
unread.push(point);
|
||||
}
|
||||
}
|
||||
|
||||
const datasets: AuthorUniverseChartData['datasets'] = [];
|
||||
|
||||
if (highCompletion.length > 0) {
|
||||
datasets.push({
|
||||
label: '75-100% Read',
|
||||
data: highCompletion,
|
||||
backgroundColor: this.hexToRgba(COMPLETION_COLORS.high, 0.6),
|
||||
borderColor: COMPLETION_COLORS.high,
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
});
|
||||
}
|
||||
|
||||
if (mediumCompletion.length > 0) {
|
||||
datasets.push({
|
||||
label: '50-74% Read',
|
||||
data: mediumCompletion,
|
||||
backgroundColor: this.hexToRgba(COMPLETION_COLORS.medium, 0.6),
|
||||
borderColor: COMPLETION_COLORS.medium,
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
});
|
||||
}
|
||||
|
||||
if (lowCompletion.length > 0) {
|
||||
datasets.push({
|
||||
label: '25-49% Read',
|
||||
data: lowCompletion,
|
||||
backgroundColor: this.hexToRgba(COMPLETION_COLORS.low, 0.6),
|
||||
borderColor: COMPLETION_COLORS.low,
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
});
|
||||
}
|
||||
|
||||
if (minimalCompletion.length > 0) {
|
||||
datasets.push({
|
||||
label: '1-24% Read',
|
||||
data: minimalCompletion,
|
||||
backgroundColor: this.hexToRgba(COMPLETION_COLORS.minimal, 0.6),
|
||||
borderColor: COMPLETION_COLORS.minimal,
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
});
|
||||
}
|
||||
|
||||
if (unread.length > 0) {
|
||||
datasets.push({
|
||||
label: 'Unread',
|
||||
data: unread,
|
||||
backgroundColor: this.hexToRgba(COMPLETION_COLORS.unread, 0.6),
|
||||
borderColor: COMPLETION_COLORS.unread,
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
});
|
||||
}
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels: [],
|
||||
datasets
|
||||
});
|
||||
}
|
||||
|
||||
private generateInsights(authorStats: AuthorStats[]): string[] {
|
||||
const insights: string[] = [];
|
||||
|
||||
if (authorStats.length === 0) return insights;
|
||||
|
||||
// Most prolific author
|
||||
const mostProlific = authorStats[0];
|
||||
if (mostProlific) {
|
||||
insights.push(`Most collected: ${mostProlific.name} with ${mostProlific.bookCount} books`);
|
||||
}
|
||||
|
||||
// Highest rated author (with at least 2 books)
|
||||
const ratedAuthors = authorStats.filter(a => a.avgRating > 0);
|
||||
if (ratedAuthors.length > 0) {
|
||||
const highestRated = ratedAuthors.reduce((a, b) => a.avgRating > b.avgRating ? a : b);
|
||||
insights.push(`Highest rated: ${highestRated.name} (${highestRated.avgRating.toFixed(1)}★)`);
|
||||
}
|
||||
|
||||
// Most pages by author
|
||||
const mostPages = authorStats.reduce((a, b) => a.totalPages > b.totalPages ? a : b);
|
||||
if (mostPages.totalPages > 0) {
|
||||
insights.push(`Most pages: ${mostPages.name} (${mostPages.totalPages.toLocaleString()} pages)`);
|
||||
}
|
||||
|
||||
// Best completion rate (with at least 3 books)
|
||||
const completionCandidates = authorStats.filter(a => a.bookCount >= 3);
|
||||
if (completionCandidates.length > 0) {
|
||||
const bestCompletion = completionCandidates.reduce((a, b) =>
|
||||
a.completionRate > b.completionRate ? a : b
|
||||
);
|
||||
if (bestCompletion.completionRate > 0) {
|
||||
insights.push(`Most read: ${bestCompletion.name} (${Math.round(bestCompletion.completionRate)}% complete)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Hidden gem - high rated but fewer books (quality over quantity)
|
||||
const hiddenGems = ratedAuthors.filter(a => a.bookCount <= 3 && a.avgRating >= 4.0);
|
||||
if (hiddenGems.length > 0) {
|
||||
const gem = hiddenGems.reduce((a, b) => a.avgRating > b.avgRating ? a : b);
|
||||
insights.push(`Hidden gem: ${gem.name} (${gem.avgRating.toFixed(1)}★ across ${gem.bookCount} books)`);
|
||||
}
|
||||
|
||||
// Biggest backlog - author with most unread books
|
||||
const authorsWithBacklog = authorStats.filter(a => a.bookCount - a.readCount > 0);
|
||||
if (authorsWithBacklog.length > 0) {
|
||||
const biggestBacklog = authorsWithBacklog.reduce((a, b) =>
|
||||
(a.bookCount - a.readCount) > (b.bookCount - b.readCount) ? a : b
|
||||
);
|
||||
const unreadCount = biggestBacklog.bookCount - biggestBacklog.readCount;
|
||||
if (unreadCount >= 2) {
|
||||
insights.push(`Biggest backlog: ${biggestBacklog.name} (${unreadCount} unread books)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Author concentration - what % of total books come from top 3 authors
|
||||
if (authorStats.length >= 3) {
|
||||
const totalBooks = authorStats.reduce((sum, a) => sum + a.bookCount, 0);
|
||||
const top3Books = authorStats.slice(0, 3).reduce((sum, a) => sum + a.bookCount, 0);
|
||||
const concentration = Math.round((top3Books / totalBooks) * 100);
|
||||
if (concentration >= 25) {
|
||||
insights.push(`Top 3 concentration: ${concentration}% of your collection`);
|
||||
}
|
||||
}
|
||||
|
||||
// Longest reads - author with highest avg pages per book
|
||||
const authorsWithPages = authorStats.filter(a => a.totalPages > 0);
|
||||
if (authorsWithPages.length > 0) {
|
||||
const longestReads = authorsWithPages.reduce((a, b) =>
|
||||
(a.totalPages / a.bookCount) > (b.totalPages / b.bookCount) ? a : b
|
||||
);
|
||||
const avgPages = Math.round(longestReads.totalPages / longestReads.bookCount);
|
||||
if (avgPages >= 300) {
|
||||
insights.push(`Longest reads: ${longestReads.name} (avg ${avgPages} pages/book)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Most versatile - author appearing in most genres
|
||||
const versatileAuthors = authorStats.filter(a => a.categories.length >= 3);
|
||||
if (versatileAuthors.length > 0) {
|
||||
const mostVersatile = versatileAuthors.reduce((a, b) =>
|
||||
a.categories.length > b.categories.length ? a : b
|
||||
);
|
||||
insights.push(`Most versatile: ${mostVersatile.name} (${mostVersatile.categories.length} genres)`);
|
||||
}
|
||||
|
||||
// Completely unread - authors with 0% completion but multiple books
|
||||
const completelyUnread = authorStats.filter(a => a.completionRate === 0 && a.bookCount >= 2);
|
||||
if (completelyUnread.length > 0) {
|
||||
const topUnread = completelyUnread.reduce((a, b) => a.bookCount > b.bookCount ? a : b);
|
||||
insights.push(`Untouched author: ${topUnread.name} (${topUnread.bookCount} unread books)`);
|
||||
}
|
||||
|
||||
// Total reading commitment
|
||||
const totalPages = authorStats.reduce((sum, a) => sum + a.totalPages, 0);
|
||||
const totalRead = authorStats.reduce((sum, a) => sum + (a.totalPages * a.completionRate / 100), 0);
|
||||
if (totalPages > 0) {
|
||||
const overallProgress = Math.round((totalRead / totalPages) * 100);
|
||||
insights.push(`Overall progress: ${overallProgress}% pages read across all authors`);
|
||||
}
|
||||
|
||||
return insights;
|
||||
}
|
||||
|
||||
private hexToRgba(hex: string, alpha: number): string {
|
||||
const r = parseInt(hex.slice(1, 3), 16);
|
||||
const g = parseInt(hex.slice(3, 5), 16);
|
||||
const b = parseInt(hex.slice(5, 7), 16);
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<div class="book-formats-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-file formats-title-icon"></i>
|
||||
Book Formats
|
||||
</h3>
|
||||
<p class="chart-description">Distribution of file types in your library</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalBooks > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No books available.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.book-formats-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.formats-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #E11D48;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 220px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 180px;
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface FormatStats {
|
||||
format: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
type FormatChartData = ChartData<'pie', number[], string>;
|
||||
|
||||
const FORMAT_COLORS: Record<string, string> = {
|
||||
'PDF': '#E11D48', // Rose
|
||||
'EPUB': '#0D9488', // Teal
|
||||
'CBX': '#7C3AED', // Violet
|
||||
'FB2': '#F59E0B', // Amber
|
||||
'MOBI': '#2563EB', // Blue
|
||||
'AZW3': '#16A34A' // Green
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-formats-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './book-formats-chart.component.html',
|
||||
styleUrls: ['./book-formats-chart.component.scss']
|
||||
})
|
||||
export class BookFormatsChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'pie' as const;
|
||||
public formatStats: FormatStats[] = [];
|
||||
public totalBooks = 0;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'pie'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'right',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle',
|
||||
padding: 15
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#E11D48',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const value = context.parsed;
|
||||
const total = context.dataset.data.reduce((a: number, b: number) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
return `${context.label}: ${value} books (${percentage}%)`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<FormatChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<FormatChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing book formats data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.formatStats = [];
|
||||
this.totalBooks = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
this.totalBooks = filteredBooks.length;
|
||||
|
||||
if (filteredBooks.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.formatStats = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = this.calculateFormatStats(filteredBooks);
|
||||
this.formatStats = stats;
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculateFormatStats(books: Book[]): FormatStats[] {
|
||||
const formatCounts = new Map<string, number>();
|
||||
|
||||
books.forEach(book => {
|
||||
const format = book.bookType || 'Unknown';
|
||||
formatCounts.set(format, (formatCounts.get(format) || 0) + 1);
|
||||
});
|
||||
|
||||
const total = books.length;
|
||||
return Array.from(formatCounts.entries())
|
||||
.map(([format, count]) => ({
|
||||
format,
|
||||
count,
|
||||
percentage: (count / total) * 100
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
private updateChartData(stats: FormatStats[]): void {
|
||||
const labels = stats.map(s => s.format);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => FORMAT_COLORS[s.format] || '#6B7280');
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 2,
|
||||
hoverBorderColor: '#ffffff',
|
||||
hoverBorderWidth: 3
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<div class="language-chart-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-globe language-title-icon"></i>
|
||||
Languages
|
||||
</h3>
|
||||
<p class="chart-description">Languages represented in your collection</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (booksWithLanguage > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (booksWithLanguage === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No language data available.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.language-chart-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.language-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #2563EB;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 220px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 180px;
|
||||
}
|
||||
}
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface LanguageStats {
|
||||
language: string;
|
||||
displayName: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
type LanguageChartData = ChartData<'pie', number[], string>;
|
||||
|
||||
// Professional color palette for languages
|
||||
const LANGUAGE_COLORS = [
|
||||
'#2563EB', // Blue
|
||||
'#0D9488', // Teal
|
||||
'#7C3AED', // Violet
|
||||
'#DC2626', // Red
|
||||
'#F59E0B', // Amber
|
||||
'#16A34A', // Green
|
||||
'#EC4899', // Pink
|
||||
'#8B5CF6', // Purple
|
||||
'#06B6D4', // Cyan
|
||||
'#EA580C', // Orange
|
||||
'#6366F1', // Indigo
|
||||
'#14B8A6', // Teal-500
|
||||
'#F43F5E', // Rose
|
||||
'#84CC16', // Lime
|
||||
'#A855F7' // Purple-500
|
||||
] as const;
|
||||
|
||||
// Common language code to display name mapping
|
||||
const LANGUAGE_NAMES: Record<string, string> = {
|
||||
'en': 'English',
|
||||
'eng': 'English',
|
||||
'english': 'English',
|
||||
'es': 'Spanish',
|
||||
'spa': 'Spanish',
|
||||
'spanish': 'Spanish',
|
||||
'fr': 'French',
|
||||
'fra': 'French',
|
||||
'french': 'French',
|
||||
'de': 'German',
|
||||
'deu': 'German',
|
||||
'german': 'German',
|
||||
'it': 'Italian',
|
||||
'ita': 'Italian',
|
||||
'italian': 'Italian',
|
||||
'pt': 'Portuguese',
|
||||
'por': 'Portuguese',
|
||||
'portuguese': 'Portuguese',
|
||||
'ru': 'Russian',
|
||||
'rus': 'Russian',
|
||||
'russian': 'Russian',
|
||||
'zh': 'Chinese',
|
||||
'zho': 'Chinese',
|
||||
'chinese': 'Chinese',
|
||||
'ja': 'Japanese',
|
||||
'jpn': 'Japanese',
|
||||
'japanese': 'Japanese',
|
||||
'ko': 'Korean',
|
||||
'kor': 'Korean',
|
||||
'korean': 'Korean',
|
||||
'pl': 'Polish',
|
||||
'pol': 'Polish',
|
||||
'polish': 'Polish',
|
||||
'nl': 'Dutch',
|
||||
'nld': 'Dutch',
|
||||
'dutch': 'Dutch',
|
||||
'sv': 'Swedish',
|
||||
'swe': 'Swedish',
|
||||
'swedish': 'Swedish',
|
||||
'ar': 'Arabic',
|
||||
'ara': 'Arabic',
|
||||
'arabic': 'Arabic',
|
||||
'hi': 'Hindi',
|
||||
'hin': 'Hindi',
|
||||
'hindi': 'Hindi',
|
||||
'tr': 'Turkish',
|
||||
'tur': 'Turkish',
|
||||
'turkish': 'Turkish',
|
||||
'cs': 'Czech',
|
||||
'ces': 'Czech',
|
||||
'czech': 'Czech',
|
||||
'da': 'Danish',
|
||||
'dan': 'Danish',
|
||||
'danish': 'Danish',
|
||||
'fi': 'Finnish',
|
||||
'fin': 'Finnish',
|
||||
'finnish': 'Finnish',
|
||||
'no': 'Norwegian',
|
||||
'nor': 'Norwegian',
|
||||
'norwegian': 'Norwegian',
|
||||
'uk': 'Ukrainian',
|
||||
'ukr': 'Ukrainian',
|
||||
'ukrainian': 'Ukrainian',
|
||||
'he': 'Hebrew',
|
||||
'heb': 'Hebrew',
|
||||
'hebrew': 'Hebrew',
|
||||
'el': 'Greek',
|
||||
'ell': 'Greek',
|
||||
'greek': 'Greek',
|
||||
'hu': 'Hungarian',
|
||||
'hun': 'Hungarian',
|
||||
'hungarian': 'Hungarian',
|
||||
'ro': 'Romanian',
|
||||
'ron': 'Romanian',
|
||||
'romanian': 'Romanian',
|
||||
'th': 'Thai',
|
||||
'tha': 'Thai',
|
||||
'thai': 'Thai',
|
||||
'vi': 'Vietnamese',
|
||||
'vie': 'Vietnamese',
|
||||
'vietnamese': 'Vietnamese',
|
||||
'id': 'Indonesian',
|
||||
'ind': 'Indonesian',
|
||||
'indonesian': 'Indonesian',
|
||||
'ms': 'Malay',
|
||||
'msa': 'Malay',
|
||||
'malay': 'Malay'
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-language-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './language-chart.component.html',
|
||||
styleUrls: ['./language-chart.component.scss']
|
||||
})
|
||||
export class LanguageChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'pie' as const;
|
||||
public languageStats: LanguageStats[] = [];
|
||||
public totalBooks = 0;
|
||||
public booksWithLanguage = 0;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'pie'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'right',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle',
|
||||
padding: 15
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#2563EB',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const value = context.parsed;
|
||||
const total = context.dataset.data.reduce((a: number, b: number) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
return `${context.label}: ${value} books (${percentage}%)`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<LanguageChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<LanguageChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing language data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.languageStats = [];
|
||||
this.totalBooks = 0;
|
||||
this.booksWithLanguage = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
this.totalBooks = filteredBooks.length;
|
||||
|
||||
if (filteredBooks.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.languageStats = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = this.calculateLanguageStats(filteredBooks);
|
||||
this.languageStats = stats;
|
||||
this.booksWithLanguage = stats.reduce((sum, s) => sum + s.count, 0);
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculateLanguageStats(books: Book[]): LanguageStats[] {
|
||||
const languageCounts = new Map<string, number>();
|
||||
|
||||
books.forEach(book => {
|
||||
const language = book.metadata?.language?.trim().toLowerCase();
|
||||
if (language) {
|
||||
// Normalize the language to a display name
|
||||
const normalizedKey = this.normalizeLanguage(language);
|
||||
languageCounts.set(normalizedKey, (languageCounts.get(normalizedKey) || 0) + 1);
|
||||
}
|
||||
});
|
||||
|
||||
const total = Array.from(languageCounts.values()).reduce((a, b) => a + b, 0);
|
||||
|
||||
return Array.from(languageCounts.entries())
|
||||
.map(([language, count]) => ({
|
||||
language,
|
||||
displayName: this.getDisplayName(language),
|
||||
count,
|
||||
percentage: (count / total) * 100
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 15); // Show top 15 languages
|
||||
}
|
||||
|
||||
private normalizeLanguage(language: string): string {
|
||||
const lower = language.toLowerCase().trim();
|
||||
// Check if it maps to a known language
|
||||
if (LANGUAGE_NAMES[lower]) {
|
||||
return lower;
|
||||
}
|
||||
return lower;
|
||||
}
|
||||
|
||||
private getDisplayName(language: string): string {
|
||||
const lower = language.toLowerCase();
|
||||
if (LANGUAGE_NAMES[lower]) {
|
||||
return LANGUAGE_NAMES[lower];
|
||||
}
|
||||
// Capitalize first letter if no mapping found
|
||||
return language.charAt(0).toUpperCase() + language.slice(1);
|
||||
}
|
||||
|
||||
private updateChartData(stats: LanguageStats[]): void {
|
||||
const labels = stats.map(s => s.displayName);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map((_, index) => LANGUAGE_COLORS[index % LANGUAGE_COLORS.length]);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 2,
|
||||
hoverBorderColor: '#ffffff',
|
||||
hoverBorderWidth: 3
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<div class="metadata-score-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-check-circle score-title-icon"></i>
|
||||
Metadata Score
|
||||
</h3>
|
||||
<p class="chart-description">Quality of book metadata in your library</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalBooks > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No metadata score data available.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.metadata-score-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.score-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #16A34A;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 220px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 180px;
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface ScoreRange {
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface ScoreStats {
|
||||
range: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
type ScoreChartData = ChartData<'doughnut', number[], string>;
|
||||
|
||||
const SCORE_RANGES: ScoreRange[] = [
|
||||
{label: 'Excellent (90-100%)', min: 90, max: 100, color: '#16A34A'},
|
||||
{label: 'Good (70-89%)', min: 70, max: 89, color: '#22C55E'},
|
||||
{label: 'Fair (50-69%)', min: 50, max: 69, color: '#F59E0B'},
|
||||
{label: 'Poor (25-49%)', min: 25, max: 49, color: '#F97316'},
|
||||
{label: 'Very Poor (0-24%)', min: 0, max: 24, color: '#DC2626'}
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-score-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './metadata-score-chart.component.html',
|
||||
styleUrls: ['./metadata-score-chart.component.scss']
|
||||
})
|
||||
export class MetadataScoreChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'doughnut' as const;
|
||||
public scoreStats: ScoreStats[] = [];
|
||||
public totalBooks = 0;
|
||||
public averageScore = 0;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'doughnut'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
cutout: '60%',
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'right',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle',
|
||||
padding: 12,
|
||||
boxWidth: 8
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#16A34A',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const value = context.parsed;
|
||||
const total = context.dataset.data.reduce((a: number, b: number) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
return `${value} books (${percentage}%)`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<ScoreChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<ScoreChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing metadata score data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.scoreStats = [];
|
||||
this.totalBooks = 0;
|
||||
this.averageScore = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
const booksWithScore = filteredBooks.filter(b => b.metadataMatchScore != null && b.metadataMatchScore >= 0);
|
||||
|
||||
this.totalBooks = booksWithScore.length;
|
||||
|
||||
if (booksWithScore.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.scoreStats = [];
|
||||
this.averageScore = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = this.calculateScoreStats(booksWithScore);
|
||||
this.scoreStats = stats;
|
||||
this.averageScore = this.calculateAverageScore(booksWithScore);
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculateScoreStats(books: Book[]): ScoreStats[] {
|
||||
const rangeCounts = new Map<string, { count: number, color: string }>();
|
||||
|
||||
SCORE_RANGES.forEach(range => {
|
||||
rangeCounts.set(range.label, {count: 0, color: range.color});
|
||||
});
|
||||
|
||||
books.forEach(book => {
|
||||
const score = book.metadataMatchScore!;
|
||||
for (const range of SCORE_RANGES) {
|
||||
if (score >= range.min && score <= range.max) {
|
||||
const data = rangeCounts.get(range.label)!;
|
||||
data.count++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const total = books.length;
|
||||
return SCORE_RANGES
|
||||
.map(range => {
|
||||
const data = rangeCounts.get(range.label)!;
|
||||
return {
|
||||
range: range.label,
|
||||
count: data.count,
|
||||
percentage: (data.count / total) * 100,
|
||||
color: data.color
|
||||
};
|
||||
})
|
||||
.filter(stat => stat.count > 0);
|
||||
}
|
||||
|
||||
private calculateAverageScore(books: Book[]): number {
|
||||
const total = books.reduce((sum, book) => sum + (book.metadataMatchScore || 0), 0);
|
||||
return Math.round(total / books.length);
|
||||
}
|
||||
|
||||
private updateChartData(stats: ScoreStats[]): void {
|
||||
const labels = stats.map(s => s.range);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => s.color);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 2,
|
||||
hoverBorderColor: '#ffffff',
|
||||
hoverBorderWidth: 3
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<div class="page-count-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-book page-title-icon"></i>
|
||||
Page Count Distribution
|
||||
</h3>
|
||||
<p class="chart-description">Distribution of book lengths in your library</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalBooks > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No page count data available.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.page-count-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.page-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #8B5CF6;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 220px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 180px;
|
||||
}
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface PageRange {
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface PageStats {
|
||||
range: string;
|
||||
count: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
type PageChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
const PAGE_RANGES: PageRange[] = [
|
||||
{label: '0-100', min: 0, max: 100, color: '#06B6D4'},
|
||||
{label: '101-200', min: 101, max: 200, color: '#0EA5E9'},
|
||||
{label: '201-300', min: 201, max: 300, color: '#3B82F6'},
|
||||
{label: '301-500', min: 301, max: 500, color: '#6366F1'},
|
||||
{label: '501-750', min: 501, max: 750, color: '#8B5CF6'},
|
||||
{label: '751-1000', min: 751, max: 1000, color: '#A855F7'},
|
||||
{label: '1000+', min: 1001, max: Infinity, color: '#D946EF'}
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-page-count-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './page-count-chart.component.html',
|
||||
styleUrls: ['./page-count-chart.component.scss']
|
||||
})
|
||||
export class PageCountChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public totalBooks = 0;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'bar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#8B5CF6',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
title: (context) => `${context[0].label} pages`,
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
return `${value} book${value === 1 ? '' : 's'}`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Page Count',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
}
|
||||
},
|
||||
grid: {display: false},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
},
|
||||
stepSize: 1,
|
||||
maxTicksLimit: 6
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<PageChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<PageChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing page count data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.totalBooks = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
const booksWithPageCount = filteredBooks.filter(b => b.metadata?.pageCount != null && b.metadata.pageCount > 0);
|
||||
|
||||
this.totalBooks = booksWithPageCount.length;
|
||||
|
||||
if (booksWithPageCount.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = this.calculatePageStats(booksWithPageCount);
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculatePageStats(books: Book[]): PageStats[] {
|
||||
const rangeCounts = new Map<string, { count: number, color: string }>();
|
||||
|
||||
PAGE_RANGES.forEach(range => {
|
||||
rangeCounts.set(range.label, {count: 0, color: range.color});
|
||||
});
|
||||
|
||||
books.forEach(book => {
|
||||
const pageCount = book.metadata!.pageCount!;
|
||||
for (const range of PAGE_RANGES) {
|
||||
if (pageCount >= range.min && pageCount <= range.max) {
|
||||
const data = rangeCounts.get(range.label)!;
|
||||
data.count++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return PAGE_RANGES.map(range => {
|
||||
const data = rangeCounts.get(range.label)!;
|
||||
return {
|
||||
range: range.label,
|
||||
count: data.count,
|
||||
color: data.color
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private updateChartData(stats: PageStats[]): void {
|
||||
const labels = stats.map(s => s.range);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => s.color);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.7
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<div class="publication-timeline-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar timeline-title-icon"></i>
|
||||
Publication Timeline
|
||||
</h3>
|
||||
<p class="chart-description">When were your books originally published?</p>
|
||||
</div>
|
||||
@if (totalBooks > 0) {
|
||||
<div class="books-count-badge">
|
||||
{{ totalBooks }} books with dates
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalBooks > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (insights) {
|
||||
<div class="insights-section">
|
||||
<div class="insights-row">
|
||||
@if (insights.oldestBook) {
|
||||
<div class="insight-item oldest">
|
||||
<span class="insight-label">Oldest</span>
|
||||
<span class="insight-value">{{ insights.oldestBook.year }}</span>
|
||||
<span class="insight-detail" [title]="insights.oldestBook.title">{{ insights.oldestBook.title }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="insight-item average">
|
||||
<span class="insight-label">Average Year</span>
|
||||
<span class="insight-value">{{ insights.averageYear }}</span>
|
||||
<span class="insight-detail">Median: {{ insights.medianYear }}</span>
|
||||
</div>
|
||||
|
||||
@if (insights.newestBook) {
|
||||
<div class="insight-item newest">
|
||||
<span class="insight-label">Newest</span>
|
||||
<span class="insight-value">{{ insights.newestBook.year }}</span>
|
||||
<span class="insight-detail" [title]="insights.newestBook.title">{{ insights.newestBook.title }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="insights-row secondary">
|
||||
<div class="insight-item timespan">
|
||||
<span class="insight-label">Time Span</span>
|
||||
<span class="insight-value">{{ insights.timeSpan }}</span>
|
||||
<span class="insight-detail">years of literature</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item peak">
|
||||
<span class="insight-label">Peak Decade</span>
|
||||
<span class="insight-value">{{ insights.peakDecade }}</span>
|
||||
<span class="insight-detail">{{ insights.peakDecadeCount }} books</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item decades">
|
||||
<span class="insight-label">Decades Covered</span>
|
||||
<span class="insight-value">{{ insights.decadesCovered }}</span>
|
||||
<span class="insight-detail">different eras</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@if (totalBooks === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No publication date data available.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.publication-timeline-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.timeline-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #a78bfa;
|
||||
}
|
||||
|
||||
.books-count-badge {
|
||||
background: linear-gradient(135deg, rgba(167, 139, 250, 0.2), rgba(167, 139, 250, 0.1));
|
||||
border: 1px solid rgba(167, 139, 250, 0.3);
|
||||
border-radius: 20px;
|
||||
padding: 0.4rem 1rem;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
color: #c4b5fd;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 380px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.insights-section {
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
flex: 1;
|
||||
min-width: 120px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
padding: 0.75rem;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
color: var(--text-secondary-color);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.insight-detail {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
margin-top: 0.25rem;
|
||||
max-width: 150px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&.oldest {
|
||||
.insight-value {
|
||||
color: #f59e0b;
|
||||
}
|
||||
}
|
||||
|
||||
&.average {
|
||||
.insight-value {
|
||||
color: #a78bfa;
|
||||
}
|
||||
}
|
||||
|
||||
&.newest {
|
||||
.insight-value {
|
||||
color: #22d3ee;
|
||||
}
|
||||
}
|
||||
|
||||
&.timespan {
|
||||
.insight-value {
|
||||
color: #f472b6;
|
||||
}
|
||||
}
|
||||
|
||||
&.peak {
|
||||
.insight-value {
|
||||
color: #4ade80;
|
||||
}
|
||||
}
|
||||
|
||||
&.decades {
|
||||
.insight-value {
|
||||
color: #fb923c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.insights-row.secondary {
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 320px;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
padding: 0.6rem;
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.insight-detail {
|
||||
max-width: 100px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 280px;
|
||||
}
|
||||
|
||||
.books-count-badge {
|
||||
font-size: 0.8rem;
|
||||
padding: 0.3rem 0.75rem;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
min-width: 90px;
|
||||
padding: 0.5rem;
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface DecadeStats {
|
||||
decade: string;
|
||||
label: string;
|
||||
count: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface TimelineInsights {
|
||||
oldestBook: { title: string; year: number } | null;
|
||||
newestBook: { title: string; year: number } | null;
|
||||
averageYear: number;
|
||||
medianYear: number;
|
||||
totalWithDate: number;
|
||||
timeSpan: number;
|
||||
peakDecade: string;
|
||||
peakDecadeCount: number;
|
||||
centuryBreakdown: { c21: number; c20: number; older: number };
|
||||
decadesCovered: number;
|
||||
}
|
||||
|
||||
type TimelineChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
// Color gradient from warm (old) to cool (new)
|
||||
const DECADE_COLORS: Record<string, string> = {
|
||||
'pre1900': '#92400e',
|
||||
'1900s': '#b45309',
|
||||
'1910s': '#c2410c',
|
||||
'1920s': '#d97706',
|
||||
'1930s': '#e5932d',
|
||||
'1940s': '#eab308',
|
||||
'1950s': '#a3e635',
|
||||
'1960s': '#4ade80',
|
||||
'1970s': '#22d3ee',
|
||||
'1980s': '#38bdf8',
|
||||
'1990s': '#60a5fa',
|
||||
'2000s': '#818cf8',
|
||||
'2010s': '#a78bfa',
|
||||
'2020s': '#c084fc'
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-publication-timeline-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './publication-timeline-chart.component.html',
|
||||
styleUrls: ['./publication-timeline-chart.component.scss']
|
||||
})
|
||||
export class PublicationTimelineChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public chartOptions: ChartConfiguration<'bar'>['options'];
|
||||
public insights: TimelineInsights | null = null;
|
||||
public totalBooks = 0;
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<TimelineChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<TimelineChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing publication timeline data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private initChartOptions(): void {
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
indexAxis: 'y',
|
||||
layout: {
|
||||
padding: {top: 10, right: 20, bottom: 10, left: 10}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
precision: 0,
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.08)'
|
||||
},
|
||||
border: {display: false},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.9)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
display: false
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#a78bfa',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const value = context.parsed.x;
|
||||
const bookText = value === 1 ? 'book' : 'books';
|
||||
return `${value} ${bookText}`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.insights = null;
|
||||
this.totalBooks = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
const booksWithDate = filteredBooks.filter(b => b.metadata?.publishedDate);
|
||||
|
||||
this.totalBooks = booksWithDate.length;
|
||||
|
||||
if (booksWithDate.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.insights = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const decadeStats = this.calculateDecadeStats(booksWithDate);
|
||||
this.insights = this.calculateInsights(booksWithDate);
|
||||
this.updateChartData(decadeStats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculateDecadeStats(books: Book[]): DecadeStats[] {
|
||||
const decadeCounts = new Map<string, number>();
|
||||
|
||||
for (const book of books) {
|
||||
const year = this.extractYear(book.metadata?.publishedDate);
|
||||
if (!year) continue;
|
||||
|
||||
const decadeKey = this.getDecadeKey(year);
|
||||
decadeCounts.set(decadeKey, (decadeCounts.get(decadeKey) || 0) + 1);
|
||||
}
|
||||
|
||||
// Define decade order
|
||||
const decadeOrder = [
|
||||
'pre1900', '1900s', '1910s', '1920s', '1930s', '1940s',
|
||||
'1950s', '1960s', '1970s', '1980s', '1990s', '2000s', '2010s', '2020s'
|
||||
];
|
||||
|
||||
const decadeLabels: Record<string, string> = {
|
||||
'pre1900': 'Pre-1900',
|
||||
'1900s': '1900s',
|
||||
'1910s': '1910s',
|
||||
'1920s': '1920s',
|
||||
'1930s': '1930s',
|
||||
'1940s': '1940s',
|
||||
'1950s': '1950s',
|
||||
'1960s': '1960s',
|
||||
'1970s': '1970s',
|
||||
'1980s': '1980s',
|
||||
'1990s': '1990s',
|
||||
'2000s': '2000s',
|
||||
'2010s': '2010s',
|
||||
'2020s': '2020s'
|
||||
};
|
||||
|
||||
return decadeOrder
|
||||
.filter(decade => decadeCounts.has(decade))
|
||||
.map(decade => ({
|
||||
decade,
|
||||
label: decadeLabels[decade],
|
||||
count: decadeCounts.get(decade) || 0,
|
||||
color: DECADE_COLORS[decade]
|
||||
}));
|
||||
}
|
||||
|
||||
private extractYear(dateStr: string | undefined): number | null {
|
||||
if (!dateStr) return null;
|
||||
|
||||
// Try parsing as full date or just year
|
||||
const yearMatch = dateStr.match(/\d{4}/);
|
||||
if (yearMatch) {
|
||||
const year = parseInt(yearMatch[0], 10);
|
||||
if (year >= 1000 && year <= new Date().getFullYear() + 1) {
|
||||
return year;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private getDecadeKey(year: number): string {
|
||||
if (year < 1900) return 'pre1900';
|
||||
if (year >= 2020) return '2020s';
|
||||
const decade = Math.floor(year / 10) * 10;
|
||||
return `${decade}s`;
|
||||
}
|
||||
|
||||
private calculateInsights(books: Book[]): TimelineInsights {
|
||||
const years: number[] = [];
|
||||
const decadeCounts = new Map<string, number>();
|
||||
let oldest: { title: string; year: number } | null = null;
|
||||
let newest: { title: string; year: number } | null = null;
|
||||
let c21 = 0, c20 = 0, older = 0;
|
||||
|
||||
for (const book of books) {
|
||||
const year = this.extractYear(book.metadata?.publishedDate);
|
||||
if (!year) continue;
|
||||
|
||||
years.push(year);
|
||||
const title = book.metadata?.title || 'Unknown';
|
||||
|
||||
if (!oldest || year < oldest.year) {
|
||||
oldest = {title, year};
|
||||
}
|
||||
if (!newest || year > newest.year) {
|
||||
newest = {title, year};
|
||||
}
|
||||
|
||||
// Count by century
|
||||
if (year >= 2000) c21++;
|
||||
else if (year >= 1900) c20++;
|
||||
else older++;
|
||||
|
||||
// Count by decade for peak decade
|
||||
const decadeKey = this.getDecadeKey(year);
|
||||
decadeCounts.set(decadeKey, (decadeCounts.get(decadeKey) || 0) + 1);
|
||||
}
|
||||
|
||||
years.sort((a, b) => a - b);
|
||||
const averageYear = years.length > 0
|
||||
? Math.round(years.reduce((a, b) => a + b, 0) / years.length)
|
||||
: 0;
|
||||
const medianYear = years.length > 0
|
||||
? years[Math.floor(years.length / 2)]
|
||||
: 0;
|
||||
|
||||
// Find peak decade
|
||||
let peakDecade = '';
|
||||
let peakDecadeCount = 0;
|
||||
for (const [decade, count] of decadeCounts) {
|
||||
if (count > peakDecadeCount) {
|
||||
peakDecade = decade === 'pre1900' ? 'Pre-1900' : decade.toUpperCase();
|
||||
peakDecadeCount = count;
|
||||
}
|
||||
}
|
||||
|
||||
const timeSpan = oldest && newest ? newest.year - oldest.year : 0;
|
||||
|
||||
return {
|
||||
oldestBook: oldest,
|
||||
newestBook: newest,
|
||||
averageYear,
|
||||
medianYear,
|
||||
totalWithDate: years.length,
|
||||
timeSpan,
|
||||
peakDecade,
|
||||
peakDecadeCount,
|
||||
centuryBreakdown: {c21, c20, older},
|
||||
decadesCovered: decadeCounts.size
|
||||
};
|
||||
}
|
||||
|
||||
private updateChartData(stats: DecadeStats[]): void {
|
||||
const labels = stats.map(s => s.label);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => s.color);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors,
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.85
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<div class="publication-trend-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-line trend-title-icon"></i>
|
||||
Publication Trend
|
||||
</h3>
|
||||
<p class="chart-description">Books by publication year showing collection trends</p>
|
||||
</div>
|
||||
@if (totalBooks > 0 && yearRange) {
|
||||
<div class="year-range-badge">
|
||||
{{ yearRange }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalBooks > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (insights) {
|
||||
<div class="insights-section">
|
||||
<div class="insights-row">
|
||||
<div class="insight-item peak">
|
||||
<span class="insight-label">Peak Year</span>
|
||||
<span class="insight-value">{{ insights.peakYear }}</span>
|
||||
<span class="insight-detail">{{ insights.peakYearCount }} books</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item recent">
|
||||
<span class="insight-label">Last 10 Years</span>
|
||||
<span class="insight-value">{{ insights.booksLast10YearsPercent }}%</span>
|
||||
<span class="insight-detail">{{ insights.booksLast10Years }} books</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item average">
|
||||
<span class="insight-label">Avg per Year</span>
|
||||
<span class="insight-value">{{ insights.averageBooksPerYear }}</span>
|
||||
<span class="insight-detail">books/year</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item productive">
|
||||
<span class="insight-label">Best 5-Year Span</span>
|
||||
<span class="insight-value">{{ insights.mostProductiveSpan }}</span>
|
||||
<span class="insight-detail">most books published</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item timespan">
|
||||
<span class="insight-label">Time Span</span>
|
||||
<span class="insight-value">{{ insights.timeSpan }}</span>
|
||||
<span class="insight-detail">years covered</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item century21">
|
||||
<span class="insight-label">21st Century</span>
|
||||
<span class="insight-value">{{ insights.century21Percent }}%</span>
|
||||
<span class="insight-detail">{{ insights.century21Books }} books</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item classics">
|
||||
<span class="insight-label">Classics</span>
|
||||
<span class="insight-value">{{ insights.classicBooksPercent }}%</span>
|
||||
<span class="insight-detail">{{ insights.classicBooks }} pre-1970</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item unique">
|
||||
<span class="insight-label">Unique Years</span>
|
||||
<span class="insight-value">{{ insights.uniqueYears }}</span>
|
||||
<span class="insight-detail">{{ insights.oldestDecade }} - {{ insights.newestDecade }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@if (totalBooks === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No publication date data available.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.publication-trend-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.trend-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #06b6d4;
|
||||
}
|
||||
|
||||
.year-range-badge {
|
||||
background: linear-gradient(135deg, rgba(6, 182, 212, 0.2), rgba(6, 182, 212, 0.1));
|
||||
border: 1px solid rgba(6, 182, 212, 0.3);
|
||||
border-radius: 20px;
|
||||
padding: 0.4rem 1rem;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
color: #22d3ee;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 380px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.insights-section {
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
flex: 1;
|
||||
min-width: 120px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
padding: 0.75rem;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
color: var(--text-secondary-color);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.insight-detail {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
&.peak {
|
||||
.insight-value {
|
||||
color: #f59e0b;
|
||||
}
|
||||
}
|
||||
|
||||
&.recent {
|
||||
.insight-value {
|
||||
color: #06b6d4;
|
||||
}
|
||||
}
|
||||
|
||||
&.average {
|
||||
.insight-value {
|
||||
color: #a78bfa;
|
||||
}
|
||||
}
|
||||
|
||||
&.productive {
|
||||
.insight-value {
|
||||
color: #4ade80;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
&.timespan {
|
||||
.insight-value {
|
||||
color: #f472b6;
|
||||
}
|
||||
}
|
||||
|
||||
&.century21 {
|
||||
.insight-value {
|
||||
color: #38bdf8;
|
||||
}
|
||||
}
|
||||
|
||||
&.classics {
|
||||
.insight-value {
|
||||
color: #fbbf24;
|
||||
}
|
||||
}
|
||||
|
||||
&.unique {
|
||||
.insight-value {
|
||||
color: #c084fc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 320px;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
padding: 0.6rem;
|
||||
min-width: 100px;
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
&.productive .insight-value {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 280px;
|
||||
}
|
||||
|
||||
.year-range-badge {
|
||||
font-size: 0.8rem;
|
||||
padding: 0.3rem 0.75rem;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
min-width: unset;
|
||||
padding: 0.5rem;
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
|
||||
&.productive .insight-value {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface TrendInsights {
|
||||
peakYear: number;
|
||||
peakYearCount: number;
|
||||
booksLast10Years: number;
|
||||
booksLast10YearsPercent: number;
|
||||
averageBooksPerYear: number;
|
||||
mostProductiveSpan: string;
|
||||
// Additional insights
|
||||
timeSpan: number;
|
||||
classicBooks: number;
|
||||
classicBooksPercent: number;
|
||||
century21Books: number;
|
||||
century21Percent: number;
|
||||
uniqueYears: number;
|
||||
oldestDecade: string;
|
||||
newestDecade: string;
|
||||
}
|
||||
|
||||
type TrendChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-publication-trend-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './publication-trend-chart.component.html',
|
||||
styleUrls: ['./publication-trend-chart.component.scss']
|
||||
})
|
||||
export class PublicationTrendChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'line' as const;
|
||||
public chartOptions: ChartConfiguration<'line'>['options'];
|
||||
public insights: TrendInsights | null = null;
|
||||
public totalBooks = 0;
|
||||
public yearRange = '';
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<TrendChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<TrendChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing publication trend data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private initChartOptions(): void {
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 20, right: 20, bottom: 10, left: 10}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
},
|
||||
maxRotation: 45,
|
||||
minRotation: 45,
|
||||
autoSkip: true,
|
||||
maxTicksLimit: 20
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.05)'
|
||||
},
|
||||
border: {display: false},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Publication Year',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
precision: 0,
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.08)'
|
||||
},
|
||||
border: {display: false},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#06b6d4',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
title: (context) => `Year ${context[0].label}`,
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
const bookText = value === 1 ? 'book' : 'books';
|
||||
return `${value} ${bookText} published`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
},
|
||||
elements: {
|
||||
line: {
|
||||
tension: 0.3,
|
||||
borderWidth: 3
|
||||
},
|
||||
point: {
|
||||
radius: 4,
|
||||
hoverRadius: 7,
|
||||
borderWidth: 2,
|
||||
backgroundColor: '#0e1117'
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'index'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.insights = null;
|
||||
this.totalBooks = 0;
|
||||
this.yearRange = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
const booksWithDate = filteredBooks.filter(b => b.metadata?.publishedDate);
|
||||
|
||||
this.totalBooks = booksWithDate.length;
|
||||
|
||||
if (booksWithDate.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.insights = null;
|
||||
this.yearRange = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const yearCounts = this.calculateYearCounts(booksWithDate);
|
||||
this.insights = this.calculateInsights(yearCounts, booksWithDate.length);
|
||||
this.updateChartData(yearCounts);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculateYearCounts(books: Book[]): Map<number, number> {
|
||||
const yearCounts = new Map<number, number>();
|
||||
|
||||
for (const book of books) {
|
||||
const year = this.extractYear(book.metadata?.publishedDate);
|
||||
if (!year) continue;
|
||||
yearCounts.set(year, (yearCounts.get(year) || 0) + 1);
|
||||
}
|
||||
|
||||
return yearCounts;
|
||||
}
|
||||
|
||||
private extractYear(dateStr: string | undefined): number | null {
|
||||
if (!dateStr) return null;
|
||||
|
||||
const yearMatch = dateStr.match(/\d{4}/);
|
||||
if (yearMatch) {
|
||||
const year = parseInt(yearMatch[0], 10);
|
||||
if (year >= 1000 && year <= new Date().getFullYear() + 1) {
|
||||
return year;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private calculateInsights(yearCounts: Map<number, number>, totalBooks: number): TrendInsights {
|
||||
const currentYear = new Date().getFullYear();
|
||||
const years = Array.from(yearCounts.keys()).sort((a, b) => a - b);
|
||||
|
||||
// Peak year
|
||||
let peakYear = 0;
|
||||
let peakYearCount = 0;
|
||||
for (const [year, count] of yearCounts) {
|
||||
if (count > peakYearCount) {
|
||||
peakYear = year;
|
||||
peakYearCount = count;
|
||||
}
|
||||
}
|
||||
|
||||
// Books in last 10 years
|
||||
let booksLast10Years = 0;
|
||||
let classicBooks = 0; // Pre-1970
|
||||
let century21Books = 0; // 2000+
|
||||
|
||||
for (const [year, count] of yearCounts) {
|
||||
if (year >= currentYear - 10) {
|
||||
booksLast10Years += count;
|
||||
}
|
||||
if (year < 1970) {
|
||||
classicBooks += count;
|
||||
}
|
||||
if (year >= 2000) {
|
||||
century21Books += count;
|
||||
}
|
||||
}
|
||||
|
||||
const booksLast10YearsPercent = totalBooks > 0 ? Math.round((booksLast10Years / totalBooks) * 100) : 0;
|
||||
const classicBooksPercent = totalBooks > 0 ? Math.round((classicBooks / totalBooks) * 100) : 0;
|
||||
const century21Percent = totalBooks > 0 ? Math.round((century21Books / totalBooks) * 100) : 0;
|
||||
|
||||
// Average books per year (only counting years with books)
|
||||
const activeYears = years.length;
|
||||
const averageBooksPerYear = activeYears > 0 ? +(totalBooks / activeYears).toFixed(1) : 0;
|
||||
|
||||
// Most productive 5-year span
|
||||
const mostProductiveSpan = this.findMostProductiveSpan(yearCounts, years);
|
||||
|
||||
// Time span
|
||||
const timeSpan = years.length > 1 ? years[years.length - 1] - years[0] : 0;
|
||||
|
||||
// Oldest and newest decades
|
||||
const oldestYear = years[0] || currentYear;
|
||||
const newestYear = years[years.length - 1] || currentYear;
|
||||
const oldestDecade = oldestYear < 1900 ? 'Pre-1900' : `${Math.floor(oldestYear / 10) * 10}s`;
|
||||
const newestDecade = `${Math.floor(newestYear / 10) * 10}s`;
|
||||
|
||||
return {
|
||||
peakYear,
|
||||
peakYearCount,
|
||||
booksLast10Years,
|
||||
booksLast10YearsPercent,
|
||||
averageBooksPerYear,
|
||||
mostProductiveSpan,
|
||||
timeSpan,
|
||||
classicBooks,
|
||||
classicBooksPercent,
|
||||
century21Books,
|
||||
century21Percent,
|
||||
uniqueYears: activeYears,
|
||||
oldestDecade,
|
||||
newestDecade
|
||||
};
|
||||
}
|
||||
|
||||
private findMostProductiveSpan(yearCounts: Map<number, number>, years: number[]): string {
|
||||
if (years.length === 0) return 'N/A';
|
||||
|
||||
let maxCount = 0;
|
||||
let bestStartYear = years[0];
|
||||
|
||||
for (const startYear of years) {
|
||||
let count = 0;
|
||||
for (let y = startYear; y < startYear + 5; y++) {
|
||||
count += yearCounts.get(y) || 0;
|
||||
}
|
||||
if (count > maxCount) {
|
||||
maxCount = count;
|
||||
bestStartYear = startYear;
|
||||
}
|
||||
}
|
||||
|
||||
return `${bestStartYear}-${bestStartYear + 4}`;
|
||||
}
|
||||
|
||||
private updateChartData(yearCounts: Map<number, number>): void {
|
||||
const years = Array.from(yearCounts.keys()).sort((a, b) => a - b);
|
||||
|
||||
if (years.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.yearRange = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill in gaps for continuous line
|
||||
const minYear = years[0];
|
||||
const maxYear = years[years.length - 1];
|
||||
this.yearRange = `${minYear} - ${maxYear}`;
|
||||
|
||||
const labels: string[] = [];
|
||||
const data: number[] = [];
|
||||
|
||||
for (let year = minYear; year <= maxYear; year++) {
|
||||
labels.push(year.toString());
|
||||
data.push(yearCounts.get(year) || 0);
|
||||
}
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
borderColor: '#06b6d4',
|
||||
backgroundColor: 'rgba(6, 182, 212, 0.1)',
|
||||
pointBackgroundColor: '#06b6d4',
|
||||
pointBorderColor: '#ffffff',
|
||||
fill: true
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<div class="reading-journey-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-directions journey-title-icon"></i>
|
||||
Reading Journey
|
||||
</h3>
|
||||
<p class="chart-description">Books added vs finished over time - the gap is your backlog</p>
|
||||
</div>
|
||||
@if (dateRange) {
|
||||
<div class="date-range-badge">
|
||||
{{ dateRange }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalBooks > 0 && insights) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
<div class="insights-section">
|
||||
<div class="insights-row">
|
||||
<div class="insight-item backlog">
|
||||
<span class="insight-label">Current Backlog</span>
|
||||
<span class="insight-value">{{ insights.currentBacklog }}</span>
|
||||
<span class="insight-detail">{{ insights.backlogPercent }}% unread</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item time-to-read">
|
||||
<span class="insight-label">Avg Time to Finish</span>
|
||||
<span class="insight-value">{{ insights.avgTimeToFinishDays }}</span>
|
||||
<span class="insight-detail">days after adding</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item productive">
|
||||
<span class="insight-label">Best Reading Month</span>
|
||||
<span class="insight-value">{{ insights.mostProductiveCount }}</span>
|
||||
<span class="insight-detail">{{ insights.mostProductiveMonth }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item acquisition">
|
||||
<span class="insight-label">Peak Acquisition</span>
|
||||
<span class="insight-value">{{ insights.busiestAcquisitionCount }}</span>
|
||||
<span class="insight-detail">{{ insights.busiestAcquisitionMonth }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item finish-rate">
|
||||
<span class="insight-label">Finish Rate</span>
|
||||
<span class="insight-value">{{ insights.finishRate }}</span>
|
||||
<span class="insight-detail">books/month avg</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item streak">
|
||||
<span class="insight-label">Longest Streak</span>
|
||||
<span class="insight-value">{{ insights.longestStreak }}</span>
|
||||
<span class="insight-detail">consecutive months</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item recent">
|
||||
<span class="insight-label">Last 3 Months</span>
|
||||
<span class="insight-value">{{ insights.recentActivity }}</span>
|
||||
<span class="insight-detail">recently finished</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item total">
|
||||
<span class="insight-label">Completion</span>
|
||||
<span class="insight-value">{{ insights.totalFinished }}/{{ insights.totalAdded }}</span>
|
||||
<span class="insight-detail">books finished</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks === 0 || !insights) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No reading journey data available.</p>
|
||||
<small>Books need addedOn or dateFinished dates to appear here.</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.reading-journey-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.journey-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #10b981;
|
||||
}
|
||||
|
||||
.date-range-badge {
|
||||
background: linear-gradient(135deg, rgba(16, 185, 129, 0.2), rgba(16, 185, 129, 0.1));
|
||||
border: 1px solid rgba(16, 185, 129, 0.3);
|
||||
border-radius: 20px;
|
||||
padding: 0.4rem 1rem;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
color: #34d399;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 380px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.insights-section {
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
padding: 0.75rem;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
color: var(--text-secondary-color);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.4rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.insight-detail {
|
||||
font-size: 0.7rem;
|
||||
color: var(--text-secondary-color);
|
||||
margin-top: 0.25rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
&.backlog {
|
||||
.insight-value {
|
||||
color: #f59e0b;
|
||||
}
|
||||
}
|
||||
|
||||
&.time-to-read {
|
||||
.insight-value {
|
||||
color: #8b5cf6;
|
||||
}
|
||||
}
|
||||
|
||||
&.productive {
|
||||
.insight-value {
|
||||
color: #10b981;
|
||||
}
|
||||
}
|
||||
|
||||
&.acquisition {
|
||||
.insight-value {
|
||||
color: #3b82f6;
|
||||
}
|
||||
}
|
||||
|
||||
&.finish-rate {
|
||||
.insight-value {
|
||||
color: #06b6d4;
|
||||
}
|
||||
}
|
||||
|
||||
&.streak {
|
||||
.insight-value {
|
||||
color: #f472b6;
|
||||
}
|
||||
}
|
||||
|
||||
&.recent {
|
||||
.insight-value {
|
||||
color: #a78bfa;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
|
||||
&.total {
|
||||
.insight-value {
|
||||
color: #22d3ee;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.insight-item {
|
||||
padding: 0.6rem;
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
&.recent .insight-value,
|
||||
&.total .insight-value {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 320px;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
padding: 0.5rem;
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.6rem;
|
||||
}
|
||||
|
||||
.insight-detail {
|
||||
font-size: 0.6rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 280px;
|
||||
}
|
||||
|
||||
.date-range-badge {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.3rem 0.75rem;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
.insight-value {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+484
@@ -0,0 +1,484 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.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';
|
||||
|
||||
interface MonthlyData {
|
||||
month: string;
|
||||
label: string;
|
||||
added: number;
|
||||
finished: number;
|
||||
cumulativeAdded: number;
|
||||
cumulativeFinished: number;
|
||||
}
|
||||
|
||||
interface JourneyInsights {
|
||||
totalAdded: number;
|
||||
totalFinished: number;
|
||||
currentBacklog: number;
|
||||
backlogPercent: number;
|
||||
avgTimeToFinishDays: number;
|
||||
mostProductiveMonth: string;
|
||||
mostProductiveCount: number;
|
||||
busiestAcquisitionMonth: string;
|
||||
busiestAcquisitionCount: number;
|
||||
finishRate: number;
|
||||
recentActivity: string;
|
||||
longestStreak: number;
|
||||
}
|
||||
|
||||
type JourneyChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-journey-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './reading-journey-chart.component.html',
|
||||
styleUrls: ['./reading-journey-chart.component.scss']
|
||||
})
|
||||
export class ReadingJourneyChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'line' as const;
|
||||
public chartOptions: ChartConfiguration<'line'>['options'];
|
||||
public insights: JourneyInsights | null = null;
|
||||
public totalBooks = 0;
|
||||
public dateRange = '';
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<JourneyChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<JourneyChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing reading journey data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private initChartOptions(): void {
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 20, right: 20, bottom: 10, left: 10}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
},
|
||||
maxRotation: 45,
|
||||
minRotation: 45,
|
||||
autoSkip: true,
|
||||
maxTicksLimit: 24
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.05)'
|
||||
},
|
||||
border: {display: false},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Month',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
precision: 0
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.08)'
|
||||
},
|
||||
border: {display: false},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Cumulative Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: 'rgba(255, 255, 255, 0.9)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
padding: 20,
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle'
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#10b981',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
title: (context) => context[0].label,
|
||||
afterBody: (context) => {
|
||||
const dataIndex = context[0].dataIndex;
|
||||
const addedValue = context[0].chart.data.datasets[0].data[dataIndex] as number;
|
||||
const finishedValue = context[0].chart.data.datasets[1].data[dataIndex] as number;
|
||||
const backlog = addedValue - finishedValue;
|
||||
return [`\nBacklog: ${backlog} books`];
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
},
|
||||
elements: {
|
||||
line: {
|
||||
tension: 0.3,
|
||||
borderWidth: 3
|
||||
},
|
||||
point: {
|
||||
radius: 3,
|
||||
hoverRadius: 6,
|
||||
borderWidth: 2
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'index'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.insights = null;
|
||||
this.totalBooks = 0;
|
||||
this.dateRange = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
this.totalBooks = filteredBooks.length;
|
||||
|
||||
if (filteredBooks.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.insights = null;
|
||||
this.dateRange = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const monthlyData = this.calculateMonthlyData(filteredBooks);
|
||||
this.insights = this.calculateInsights(filteredBooks, monthlyData);
|
||||
this.updateChartData(monthlyData);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private calculateMonthlyData(books: Book[]): MonthlyData[] {
|
||||
const monthlyAdded = new Map<string, number>();
|
||||
const monthlyFinished = new Map<string, number>();
|
||||
|
||||
for (const book of books) {
|
||||
// Track added dates
|
||||
if (book.addedOn) {
|
||||
const monthKey = this.getMonthKey(book.addedOn);
|
||||
if (monthKey) {
|
||||
monthlyAdded.set(monthKey, (monthlyAdded.get(monthKey) || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Track finished dates
|
||||
if (book.dateFinished && book.readStatus === ReadStatus.READ) {
|
||||
const monthKey = this.getMonthKey(book.dateFinished);
|
||||
if (monthKey) {
|
||||
monthlyFinished.set(monthKey, (monthlyFinished.get(monthKey) || 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get all unique months and sort them
|
||||
const allMonths = new Set([...monthlyAdded.keys(), ...monthlyFinished.keys()]);
|
||||
const sortedMonths = Array.from(allMonths).sort();
|
||||
|
||||
if (sortedMonths.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Fill in gaps and calculate cumulative values
|
||||
const firstMonth = sortedMonths[0];
|
||||
const lastMonth = sortedMonths[sortedMonths.length - 1];
|
||||
const allMonthsRange = this.getMonthRange(firstMonth, lastMonth);
|
||||
|
||||
this.dateRange = `${this.formatMonthLabel(firstMonth)} - ${this.formatMonthLabel(lastMonth)}`;
|
||||
|
||||
let cumulativeAdded = 0;
|
||||
let cumulativeFinished = 0;
|
||||
|
||||
return allMonthsRange.map(month => {
|
||||
const added = monthlyAdded.get(month) || 0;
|
||||
const finished = monthlyFinished.get(month) || 0;
|
||||
cumulativeAdded += added;
|
||||
cumulativeFinished += finished;
|
||||
|
||||
return {
|
||||
month,
|
||||
label: this.formatMonthLabel(month),
|
||||
added,
|
||||
finished,
|
||||
cumulativeAdded,
|
||||
cumulativeFinished
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private getMonthKey(dateStr: string): string | null {
|
||||
if (!dateStr) return null;
|
||||
try {
|
||||
const date = new Date(dateStr);
|
||||
if (isNaN(date.getTime())) return null;
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
return `${year}-${month}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private getMonthRange(start: string, end: string): string[] {
|
||||
const months: string[] = [];
|
||||
const [startYear, startMonth] = start.split('-').map(Number);
|
||||
const [endYear, endMonth] = end.split('-').map(Number);
|
||||
|
||||
let year = startYear;
|
||||
let month = startMonth;
|
||||
|
||||
while (year < endYear || (year === endYear && month <= endMonth)) {
|
||||
months.push(`${year}-${String(month).padStart(2, '0')}`);
|
||||
month++;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year++;
|
||||
}
|
||||
}
|
||||
|
||||
return months;
|
||||
}
|
||||
|
||||
private formatMonthLabel(monthKey: string): string {
|
||||
const [year, month] = monthKey.split('-');
|
||||
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
return `${monthNames[parseInt(month, 10) - 1]} ${year}`;
|
||||
}
|
||||
|
||||
private calculateInsights(books: Book[], monthlyData: MonthlyData[]): JourneyInsights {
|
||||
const booksWithAddedDate = books.filter(b => b.addedOn);
|
||||
const booksFinished = books.filter(b => b.dateFinished && b.readStatus === ReadStatus.READ);
|
||||
|
||||
const totalAdded = booksWithAddedDate.length;
|
||||
const totalFinished = booksFinished.length;
|
||||
const currentBacklog = totalAdded - totalFinished;
|
||||
const backlogPercent = totalAdded > 0 ? Math.round((currentBacklog / totalAdded) * 100) : 0;
|
||||
|
||||
// Calculate average time to finish
|
||||
let totalDaysToFinish = 0;
|
||||
let finishedWithBothDates = 0;
|
||||
|
||||
for (const book of booksFinished) {
|
||||
if (book.addedOn && book.dateFinished) {
|
||||
const addedDate = new Date(book.addedOn);
|
||||
const finishedDate = new Date(book.dateFinished);
|
||||
if (!isNaN(addedDate.getTime()) && !isNaN(finishedDate.getTime())) {
|
||||
const days = Math.floor((finishedDate.getTime() - addedDate.getTime()) / (1000 * 60 * 60 * 24));
|
||||
if (days >= 0) {
|
||||
totalDaysToFinish += days;
|
||||
finishedWithBothDates++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const avgTimeToFinishDays = finishedWithBothDates > 0
|
||||
? Math.round(totalDaysToFinish / finishedWithBothDates)
|
||||
: 0;
|
||||
|
||||
// Find most productive reading month
|
||||
let mostProductiveMonth = 'N/A';
|
||||
let mostProductiveCount = 0;
|
||||
let busiestAcquisitionMonth = 'N/A';
|
||||
let busiestAcquisitionCount = 0;
|
||||
|
||||
for (const data of monthlyData) {
|
||||
if (data.finished > mostProductiveCount) {
|
||||
mostProductiveCount = data.finished;
|
||||
mostProductiveMonth = data.label;
|
||||
}
|
||||
if (data.added > busiestAcquisitionCount) {
|
||||
busiestAcquisitionCount = data.added;
|
||||
busiestAcquisitionMonth = data.label;
|
||||
}
|
||||
}
|
||||
|
||||
// Finish rate (books finished per month on average)
|
||||
const finishRate = monthlyData.length > 0
|
||||
? +(totalFinished / monthlyData.length).toFixed(1)
|
||||
: 0;
|
||||
|
||||
// Recent activity
|
||||
const now = new Date();
|
||||
const threeMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 3, 1);
|
||||
let recentFinished = 0;
|
||||
for (const book of booksFinished) {
|
||||
if (book.dateFinished) {
|
||||
const finishDate = new Date(book.dateFinished);
|
||||
if (finishDate >= threeMonthsAgo) {
|
||||
recentFinished++;
|
||||
}
|
||||
}
|
||||
}
|
||||
const recentActivity = recentFinished > 0 ? `${recentFinished} books` : 'No activity';
|
||||
|
||||
// Longest reading streak (consecutive months with finished books)
|
||||
let longestStreak = 0;
|
||||
let currentStreak = 0;
|
||||
for (const data of monthlyData) {
|
||||
if (data.finished > 0) {
|
||||
currentStreak++;
|
||||
longestStreak = Math.max(longestStreak, currentStreak);
|
||||
} else {
|
||||
currentStreak = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
totalAdded,
|
||||
totalFinished,
|
||||
currentBacklog,
|
||||
backlogPercent,
|
||||
avgTimeToFinishDays,
|
||||
mostProductiveMonth,
|
||||
mostProductiveCount,
|
||||
busiestAcquisitionMonth,
|
||||
busiestAcquisitionCount,
|
||||
finishRate,
|
||||
recentActivity,
|
||||
longestStreak
|
||||
};
|
||||
}
|
||||
|
||||
private updateChartData(monthlyData: MonthlyData[]): void {
|
||||
if (monthlyData.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
return;
|
||||
}
|
||||
|
||||
const labels = monthlyData.map(d => d.label);
|
||||
const addedData = monthlyData.map(d => d.cumulativeAdded);
|
||||
const finishedData = monthlyData.map(d => d.cumulativeFinished);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Books Added',
|
||||
data: addedData,
|
||||
borderColor: '#3b82f6',
|
||||
backgroundColor: 'rgba(59, 130, 246, 0.1)',
|
||||
pointBackgroundColor: '#3b82f6',
|
||||
pointBorderColor: '#ffffff',
|
||||
fill: true,
|
||||
order: 2
|
||||
},
|
||||
{
|
||||
label: 'Books Finished',
|
||||
data: finishedData,
|
||||
borderColor: '#10b981',
|
||||
backgroundColor: 'rgba(16, 185, 129, 0.2)',
|
||||
pointBackgroundColor: '#10b981',
|
||||
pointBorderColor: '#ffffff',
|
||||
fill: true,
|
||||
order: 1
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
<div class="top-items-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi" [ngClass]="selectedDataType.icon" [style.color]="selectedDataType.color"></i>
|
||||
Top 15 {{ selectedDataType.label }}
|
||||
</h3>
|
||||
<p class="chart-description">Most represented {{ selectedDataType.label.toLowerCase() }} in your library</p>
|
||||
</div>
|
||||
<div class="header-controls">
|
||||
<p-select
|
||||
[options]="dataTypeOptions"
|
||||
[(ngModel)]="selectedDataType"
|
||||
optionLabel="label"
|
||||
(onChange)="onDataTypeChange()"
|
||||
[style]="{'min-width': '140px'}"
|
||||
size="small"
|
||||
appendTo="body">
|
||||
<ng-template pTemplate="selectedItem">
|
||||
@if (selectedDataType) {
|
||||
<div class="select-item">
|
||||
<i class="pi" [ngClass]="selectedDataType.icon"></i>
|
||||
<span>{{ selectedDataType.label }}</span>
|
||||
</div>
|
||||
}
|
||||
</ng-template>
|
||||
<ng-template pTemplate="item" let-option>
|
||||
<div class="select-item">
|
||||
<i class="pi" [ngClass]="option.icon" [style.color]="option.color"></i>
|
||||
<span>{{ option.label }}</span>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-select>
|
||||
@if (totalItems > 0) {
|
||||
<div class="stats-badge">
|
||||
<span class="badge-value">{{ totalItems }}</span>
|
||||
<span class="badge-label">shown</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalItems > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (insights.length > 0) {
|
||||
<div class="insights-grid">
|
||||
@for (insight of insights; track insight.label) {
|
||||
<div class="insight-card">
|
||||
<i class="pi" [ngClass]="insight.icon" [style.color]="selectedDataType.color"></i>
|
||||
<div class="insight-content">
|
||||
<span class="insight-label">{{ insight.label }}</span>
|
||||
<span class="insight-value">{{ insight.value }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@if (totalItems === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No {{ selectedDataType.label.toLowerCase() }} data available.</p>
|
||||
<small>Make sure your books have {{ selectedDataType.label.toLowerCase() }} metadata.</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
@import '../../../_chart-shared';
|
||||
|
||||
.top-items-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
i {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.header-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.select-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
i {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
.badge-value {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.badge-label {
|
||||
font-size: 0.7rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 450px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
|
||||
.insight-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
> i {
|
||||
font-size: 1.1rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.insight-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
min-width: 0;
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.insight-value {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
.header-controls {
|
||||
justify-content: space-between;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 400px;
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.5rem;
|
||||
|
||||
.insight-card {
|
||||
padding: 0.6rem 0.75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-wrapper {
|
||||
height: 380px;
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
+457
@@ -0,0 +1,457 @@
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData, TooltipItem} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {Select} from 'primeng/select';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
|
||||
interface ItemStats {
|
||||
name: string;
|
||||
count: number;
|
||||
statusBreakdown: Record<ReadStatus, number>;
|
||||
}
|
||||
|
||||
interface DataTypeOption {
|
||||
label: string;
|
||||
value: DataType;
|
||||
icon: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
type DataType = 'authors' | 'categories' | 'publishers' | 'tags' | 'moods' | 'series';
|
||||
type ItemChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
const DATA_TYPE_OPTIONS: DataTypeOption[] = [
|
||||
{label: 'Authors', value: 'authors', icon: 'pi-th-large', color: '#2563EB'},
|
||||
{label: 'Categories', value: 'categories', icon: 'pi-user', color: '#0D9488'},
|
||||
{label: 'Series', value: 'series', icon: 'pi-tag', color: '#DB2777'},
|
||||
{label: 'Publishers', value: 'publishers', icon: 'pi-building', color: '#7C3AED'},
|
||||
{label: 'Tags', value: 'tags', icon: 'pi-bookmark', color: '#EAB308'},
|
||||
{label: 'Moods', value: 'moods', icon: 'pi-heart', color: '#EA580C'}
|
||||
];
|
||||
|
||||
const READ_STATUS_CONFIG: Record<ReadStatus, { label: string; color: string }> = {
|
||||
[ReadStatus.READ]: {label: 'Read', color: '#22c55e'},
|
||||
[ReadStatus.READING]: {label: 'Reading', color: '#3b82f6'},
|
||||
[ReadStatus.RE_READING]: {label: 'Re-reading', color: '#8b5cf6'},
|
||||
[ReadStatus.UNREAD]: {label: 'Unread', color: '#6b7280'},
|
||||
[ReadStatus.PARTIALLY_READ]: {label: 'Partially Read', color: '#f59e0b'},
|
||||
[ReadStatus.PAUSED]: {label: 'Paused', color: '#eab308'},
|
||||
[ReadStatus.WONT_READ]: {label: "Won't Read", color: '#ef4444'},
|
||||
[ReadStatus.ABANDONED]: {label: 'Abandoned', color: '#dc2626'},
|
||||
[ReadStatus.UNSET]: {label: 'Not Set', color: '#9ca3af'}
|
||||
};
|
||||
|
||||
const READ_STATUS_ORDER: ReadStatus[] = [
|
||||
ReadStatus.READ,
|
||||
ReadStatus.READING,
|
||||
ReadStatus.RE_READING,
|
||||
ReadStatus.PARTIALLY_READ,
|
||||
ReadStatus.PAUSED,
|
||||
ReadStatus.UNREAD,
|
||||
ReadStatus.WONT_READ,
|
||||
ReadStatus.ABANDONED,
|
||||
ReadStatus.UNSET
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-top-items-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, BaseChartDirective, Select],
|
||||
templateUrl: './top-items-chart.component.html',
|
||||
styleUrls: ['./top-items-chart.component.scss']
|
||||
})
|
||||
export class TopItemsChartComponent implements OnInit, OnDestroy {
|
||||
@Input() initialDataType: DataType | null = null;
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public readonly chartData$: Observable<ItemChartData>;
|
||||
public chartOptions: ChartConfiguration<'bar'>['options'];
|
||||
public dataTypeOptions = DATA_TYPE_OPTIONS;
|
||||
public selectedDataType: DataTypeOption = DATA_TYPE_OPTIONS[0];
|
||||
|
||||
public totalItems = 0;
|
||||
public totalBooks = 0;
|
||||
public insights: { icon: string; label: string; value: string }[] = [];
|
||||
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<ItemChartData>;
|
||||
private lastCalculatedStats: ItemStats[] = [];
|
||||
private allBooks: Book[] = [];
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<ItemChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
if (this.initialDataType) {
|
||||
const initialOption = DATA_TYPE_OPTIONS.find(opt => opt.value === this.initialDataType);
|
||||
if (initialOption) {
|
||||
this.selectedDataType = initialOption;
|
||||
this.initChartOptions();
|
||||
}
|
||||
}
|
||||
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing top items stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.loadAndProcessData();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
onDataTypeChange(): void {
|
||||
this.initChartOptions();
|
||||
this.processData();
|
||||
}
|
||||
|
||||
private initChartOptions(): void {
|
||||
const currentColor = this.selectedDataType.color;
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
indexAxis: 'y',
|
||||
layout: {
|
||||
padding: {top: 10, right: 20, bottom: 10, left: 10}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
stacked: true,
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
precision: 0,
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.08)'
|
||||
},
|
||||
border: {display: false},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
stacked: true,
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.9)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
maxTicksLimit: 25
|
||||
},
|
||||
grid: {
|
||||
display: false
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
color: 'rgba(255, 255, 255, 0.9)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
padding: 15,
|
||||
usePointStyle: true,
|
||||
pointStyle: 'rectRounded'
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: currentColor,
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const dataIndex = context[0].dataIndex;
|
||||
return this.lastCalculatedStats[dataIndex]?.name || 'Unknown';
|
||||
},
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: true,
|
||||
mode: 'nearest',
|
||||
axis: 'y'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private loadAndProcessData(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.allBooks = [];
|
||||
this.updateChartData([]);
|
||||
return;
|
||||
}
|
||||
|
||||
this.allBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
this.processData();
|
||||
}
|
||||
|
||||
private processData(): void {
|
||||
const stats = this.calculateStats(this.allBooks);
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private updateChartData(stats: ItemStats[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
this.totalItems = stats.length;
|
||||
this.totalBooks = stats.reduce((sum, s) => sum + s.count, 0);
|
||||
|
||||
const labels = stats.map(s => this.truncateTitle(s.name, 30));
|
||||
|
||||
const datasets = READ_STATUS_ORDER
|
||||
.filter(status => stats.some(s => s.statusBreakdown[status] > 0))
|
||||
.map(status => {
|
||||
const config = READ_STATUS_CONFIG[status];
|
||||
return {
|
||||
label: config.label,
|
||||
data: stats.map(s => s.statusBreakdown[status]),
|
||||
backgroundColor: config.color,
|
||||
borderColor: config.color,
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.85,
|
||||
categoryPercentage: 0.8,
|
||||
hoverBorderWidth: 2,
|
||||
hoverBorderColor: '#ffffff'
|
||||
};
|
||||
});
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets
|
||||
});
|
||||
|
||||
this.generateInsights(stats);
|
||||
} catch (error) {
|
||||
console.error('Error updating items chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private generateInsights(stats: ItemStats[]): void {
|
||||
this.insights = [];
|
||||
if (stats.length === 0) return;
|
||||
|
||||
const typeName = this.selectedDataType.label.toLowerCase().slice(0, -1); // Remove 's' for singular
|
||||
const typeNamePlural = this.selectedDataType.label.toLowerCase();
|
||||
|
||||
// 1. Top item
|
||||
const top = stats[0];
|
||||
this.insights.push({
|
||||
icon: 'pi-trophy',
|
||||
label: `Top ${typeName}`,
|
||||
value: `${top.name} (${top.count} books)`
|
||||
});
|
||||
|
||||
// 2. Most completed - highest read percentage
|
||||
const withReads = stats.filter(s => s.count >= 2);
|
||||
if (withReads.length > 0) {
|
||||
const mostRead = withReads.reduce((best, curr) => {
|
||||
const bestPct = best.statusBreakdown[ReadStatus.READ] / best.count;
|
||||
const currPct = curr.statusBreakdown[ReadStatus.READ] / curr.count;
|
||||
return currPct > bestPct ? curr : best;
|
||||
});
|
||||
const readPct = Math.round((mostRead.statusBreakdown[ReadStatus.READ] / mostRead.count) * 100);
|
||||
if (readPct > 0) {
|
||||
this.insights.push({
|
||||
icon: 'pi-check-circle',
|
||||
label: 'Most completed',
|
||||
value: `${mostRead.name} (${readPct}% read)`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Top 5 concentration
|
||||
if (stats.length >= 5) {
|
||||
const top5Books = stats.slice(0, 5).reduce((sum, s) => sum + s.count, 0);
|
||||
const totalAllBooks = this.allBooks.length;
|
||||
if (totalAllBooks > 0) {
|
||||
const concentration = Math.round((top5Books / totalAllBooks) * 100);
|
||||
this.insights.push({
|
||||
icon: 'pi-chart-pie',
|
||||
label: 'Top 5 coverage',
|
||||
value: `${concentration}% of library`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Average books per item
|
||||
if (stats.length > 0) {
|
||||
const avgBooks = (this.totalBooks / stats.length).toFixed(1);
|
||||
this.insights.push({
|
||||
icon: 'pi-book',
|
||||
label: `Avg per ${typeName}`,
|
||||
value: `${avgBooks} books`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private calculateStats(books: Book[]): ItemStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const itemMap = new Map<string, { count: number; statusBreakdown: Record<ReadStatus, number> }>();
|
||||
const dataType = this.selectedDataType.value;
|
||||
|
||||
for (const book of books) {
|
||||
const items = this.getItemsFromBook(book, dataType);
|
||||
const bookStatus = book.readStatus || ReadStatus.UNSET;
|
||||
|
||||
for (const item of items) {
|
||||
if (item && item.trim()) {
|
||||
const normalizedName = item.trim();
|
||||
let entry = itemMap.get(normalizedName);
|
||||
|
||||
if (!entry) {
|
||||
entry = {
|
||||
count: 0,
|
||||
statusBreakdown: this.createEmptyStatusBreakdown()
|
||||
};
|
||||
itemMap.set(normalizedName, entry);
|
||||
}
|
||||
|
||||
entry.count++;
|
||||
entry.statusBreakdown[bookStatus]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(itemMap.entries())
|
||||
.map(([name, data]) => ({name, count: data.count, statusBreakdown: data.statusBreakdown}))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 15);
|
||||
}
|
||||
|
||||
private createEmptyStatusBreakdown(): Record<ReadStatus, number> {
|
||||
return {
|
||||
[ReadStatus.READ]: 0,
|
||||
[ReadStatus.READING]: 0,
|
||||
[ReadStatus.RE_READING]: 0,
|
||||
[ReadStatus.UNREAD]: 0,
|
||||
[ReadStatus.PARTIALLY_READ]: 0,
|
||||
[ReadStatus.PAUSED]: 0,
|
||||
[ReadStatus.WONT_READ]: 0,
|
||||
[ReadStatus.ABANDONED]: 0,
|
||||
[ReadStatus.UNSET]: 0
|
||||
};
|
||||
}
|
||||
|
||||
private getItemsFromBook(book: Book, dataType: DataType): string[] {
|
||||
const metadata = book.metadata;
|
||||
if (!metadata) return [];
|
||||
|
||||
switch (dataType) {
|
||||
case 'authors':
|
||||
return metadata.authors || [];
|
||||
case 'categories':
|
||||
return metadata.categories || [];
|
||||
case 'publishers':
|
||||
return metadata.publisher ? [metadata.publisher] : [];
|
||||
case 'tags':
|
||||
return metadata.tags || [];
|
||||
case 'moods':
|
||||
return metadata.moods || [];
|
||||
case 'series':
|
||||
return metadata.seriesName ? [metadata.seriesName] : [];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<'bar'>): string {
|
||||
const value = context.parsed.x;
|
||||
if (value === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const statusLabel = context.dataset.label || 'Books';
|
||||
const bookText = value === 1 ? 'book' : 'books';
|
||||
|
||||
return `${statusLabel}: ${value} ${bookText}`;
|
||||
}
|
||||
|
||||
private truncateTitle(title: string, maxLength: number): string {
|
||||
return title.length > maxLength ? title.substring(0, maxLength) + '...' : title;
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
<div class="library-stats-container">
|
||||
<div class="header-card">
|
||||
<div class="filter-section">
|
||||
<div class="library-filter">
|
||||
<div class="select-row">
|
||||
<label for="library-dropdown">Library Statistics</label>
|
||||
<div class="flex w-full gap-2 align-items-center">
|
||||
<p-select
|
||||
fluid
|
||||
id="library-dropdown"
|
||||
[options]="libraryOptions"
|
||||
[(ngModel)]="selectedLibrary"
|
||||
optionLabel="name"
|
||||
size="small"
|
||||
placeholder="Select a library"
|
||||
(onChange)="onLibraryChange()"
|
||||
appendTo="body"
|
||||
[style]="{'min-width': '200px'}"
|
||||
class="library-dropdown">
|
||||
</p-select>
|
||||
|
||||
<p-button
|
||||
outlined
|
||||
size="small"
|
||||
(onClick)="toggleConfigPanel()"
|
||||
icon="pi pi-cog">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="library-totals" role="status" aria-live="polite">
|
||||
<div class="total-item total-books" title="Total books">
|
||||
<i class="pi pi-book"></i>
|
||||
<span class="total-label">Books</span>
|
||||
<span class="total-value">{{ totalBooks$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-authors" title="Total authors">
|
||||
<i class="pi pi-users"></i>
|
||||
<span class="total-label">Authors</span>
|
||||
<span class="total-value">{{ totalAuthors$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-series" title="Total series">
|
||||
<i class="pi pi-bookmark"></i>
|
||||
<span class="total-label">Series</span>
|
||||
<span class="total-value">{{ totalSeries$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-publishers" title="Total publishers">
|
||||
<i class="pi pi-building"></i>
|
||||
<span class="total-label">Publishers</span>
|
||||
<span class="total-value">{{ totalPublishers$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-size" title="Total size">
|
||||
<i class="pi pi-file"></i>
|
||||
<span class="total-label">Library Size</span>
|
||||
<span class="total-value">{{ totalSize$ | async }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (showConfigPanel) {
|
||||
<div class="config-modal-overlay" (click)="closeConfigPanel()">
|
||||
<div class="config-modal" (click)="$event.stopPropagation()">
|
||||
<div class="config-modal-header">
|
||||
<h3><i class="pi pi-cog"></i> Chart Configuration</h3>
|
||||
<button type="button" class="close-btn" (click)="closeConfigPanel()" title="Close">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="config-modal-actions">
|
||||
<button type="button" class="config-action-btn enable-all" (click)="enableAllCharts()">
|
||||
<i class="pi pi-check"></i> Enable All
|
||||
</button>
|
||||
<button type="button" class="config-action-btn disable-all" (click)="disableAllCharts()">
|
||||
<i class="pi pi-times"></i> Disable All
|
||||
</button>
|
||||
<button type="button" class="config-action-btn reset-order" (click)="resetChartOrder()">
|
||||
<i class="pi pi-refresh"></i> Reset Order
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="config-modal-content">
|
||||
<div class="config-categories">
|
||||
<div class="config-category">
|
||||
<h4>Small Charts</h4>
|
||||
<div class="chart-toggles">
|
||||
@for (chart of getChartsByCategory('small'); track chart.id) {
|
||||
<div class="chart-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
[id]="'chart-' + chart.id"
|
||||
[checked]="chart.enabled"
|
||||
(change)="toggleChart(chart.id)">
|
||||
<label [for]="'chart-' + chart.id">{{ chart.name }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="config-category">
|
||||
<h4>Large Charts</h4>
|
||||
<div class="chart-toggles">
|
||||
@for (chart of getChartsByCategory('large'); track chart.id) {
|
||||
<div class="chart-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
[id]="'chart-' + chart.id"
|
||||
[checked]="chart.enabled"
|
||||
(change)="toggleChart(chart.id)">
|
||||
<label [for]="'chart-' + chart.id">{{ chart.name }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="config-category">
|
||||
<h4>Extra Large Charts</h4>
|
||||
<div class="chart-toggles">
|
||||
@for (chart of getChartsByCategory('xlarge'); track chart.id) {
|
||||
<div class="chart-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
[id]="'chart-' + chart.id"
|
||||
[checked]="chart.enabled"
|
||||
(change)="toggleChart(chart.id)">
|
||||
<label [for]="'chart-' + chart.id">{{ chart.name }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!isLoading && hasData) {
|
||||
<div class="charts-grid"
|
||||
cdkDropList
|
||||
(cdkDropListDropped)="onChartReorder($event)"
|
||||
[cdkDropListData]="getEnabledChartsSorted()">
|
||||
|
||||
@for (chartConfig of getEnabledChartsSorted(); track chartConfig.id) {
|
||||
<div class="chart-container"
|
||||
cdkDrag
|
||||
[cdkDragData]="chartConfig"
|
||||
[class]="'chart-section ' + chartConfig.category">
|
||||
|
||||
<div class="drag-handle" cdkDragHandle title="Drag to reorder">
|
||||
<i class="pi pi-bars"></i>
|
||||
</div>
|
||||
|
||||
@switch (chartConfig.id) {
|
||||
@case ('bookFormats') {
|
||||
<app-book-formats-chart></app-book-formats-chart>
|
||||
}
|
||||
@case ('languageDistribution') {
|
||||
<app-language-chart></app-language-chart>
|
||||
}
|
||||
@case ('metadataScore') {
|
||||
<app-metadata-score-chart></app-metadata-score-chart>
|
||||
}
|
||||
@case ('pageCountDistribution') {
|
||||
<app-page-count-chart></app-page-count-chart>
|
||||
}
|
||||
@case ('publicationTimeline') {
|
||||
<app-publication-timeline-chart></app-publication-timeline-chart>
|
||||
}
|
||||
@case ('publicationTrend') {
|
||||
<app-publication-trend-chart></app-publication-trend-chart>
|
||||
}
|
||||
@case ('readingJourney') {
|
||||
<app-reading-journey-chart></app-reading-journey-chart>
|
||||
}
|
||||
@case ('topItems') {
|
||||
<app-top-items-chart></app-top-items-chart>
|
||||
}
|
||||
@case ('authorUniverse') {
|
||||
<app-author-universe-chart></app-author-universe-chart>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (isLoading) {
|
||||
<div class="loading-message">
|
||||
Loading statistics...
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!isLoading && !hasData) {
|
||||
<div class="no-data-message">
|
||||
No data available.
|
||||
<small>Make sure your library contains books with metadata.</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+14
-447
@@ -1,9 +1,10 @@
|
||||
.stats-container {
|
||||
.library-stats-container {
|
||||
max-width: 2500px;
|
||||
margin: 0 auto;
|
||||
background: transparent;
|
||||
height: calc(100dvh - 6.25rem);
|
||||
overflow-y: auto;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.header-card {
|
||||
@@ -82,32 +83,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.chart-config-btn {
|
||||
background: var(--primary-color, #80bdff);
|
||||
border: 1px solid var(--primary-color, #80bdff);
|
||||
color: #ffffff;
|
||||
padding: 10px 16px;
|
||||
border-radius: 6px;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-color-darker, #6ba3e0);
|
||||
border-color: var(--primary-color-darker, #6ba3e0);
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 8px rgba(128, 189, 255, 0.3);
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
@@ -244,17 +219,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
&.reset-positions {
|
||||
background: rgba(168, 85, 247, 0.2);
|
||||
border-color: rgba(168, 85, 247, 0.4);
|
||||
color: #a855f7;
|
||||
|
||||
&:hover {
|
||||
background: rgba(168, 85, 247, 0.3);
|
||||
border-color: rgba(168, 85, 247, 0.6);
|
||||
}
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
@@ -449,96 +413,14 @@
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
&.xlarge {
|
||||
grid-column: 1 / -1;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
&.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
margin: 0 0 15px 0;
|
||||
font-weight: 500;
|
||||
font-size: 1.1rem;
|
||||
|
||||
.small & {
|
||||
font-size: 1rem;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.large & {
|
||||
font-size: 1.2rem;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 15px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
|
||||
canvas {
|
||||
width: 100% !important;
|
||||
height: auto !important;
|
||||
}
|
||||
|
||||
&.status-chart,
|
||||
&.book-type-chart,
|
||||
&.language-chart,
|
||||
&.series-chart {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
&.progress-chart,
|
||||
&.rating-chart,
|
||||
&.page-count-chart,
|
||||
&.reading-speed-chart,
|
||||
&.quality-chart,
|
||||
&.velocity-chart {
|
||||
height: 320px;
|
||||
}
|
||||
|
||||
&.categories-chart,
|
||||
&.author-chart,
|
||||
&.completion-chart,
|
||||
&.publisher-chart,
|
||||
&.author-rating-chart,
|
||||
&.book-size-chart {
|
||||
height: 400px;
|
||||
}
|
||||
|
||||
&.year-chart,
|
||||
&.books-added-chart,
|
||||
&.monthly-chart,
|
||||
&.series-completion-chart,
|
||||
&.velocity-timeline-chart,
|
||||
&.monthly-patterns-chart,
|
||||
&.finished-books-timeline-chart {
|
||||
height: 350px;
|
||||
}
|
||||
|
||||
&.series-length-chart,
|
||||
&.author-series-chart,
|
||||
&.top-series-chart {
|
||||
height: 400px;
|
||||
}
|
||||
|
||||
&.reading-heatmap-chart {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
&.reading-profile-radar-chart,
|
||||
&.reading-dna-chart,
|
||||
&.reading-habits-chart {
|
||||
height: 450px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.loading-message,
|
||||
@@ -555,192 +437,11 @@
|
||||
|
||||
.no-data-message {
|
||||
color: var(--text-color-secondary, #999999);
|
||||
}
|
||||
|
||||
.dna-insights {
|
||||
margin-top: 20px;
|
||||
padding-top: 15px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
.insights-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border-color: rgba(255, 255, 255, 0.15);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.insight-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.trait-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.trait-name {
|
||||
color: #ffffff;
|
||||
font-weight: 500;
|
||||
font-size: 0.95rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.trait-score {
|
||||
color: #ffffff;
|
||||
font-weight: 800;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-bar {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.insight-fill {
|
||||
height: 100%;
|
||||
border-radius: 2px;
|
||||
transition: width 0.8s ease;
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.4;
|
||||
margin: 0;
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.intelligence-insights {
|
||||
margin-top: 20px;
|
||||
padding-top: 15px;
|
||||
border-top: 1px solid rgba(0, 212, 170, 0.2);
|
||||
|
||||
.insights-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
background: rgba(0, 212, 170, 0.05);
|
||||
border: 1px solid rgba(0, 212, 170, 0.15);
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 212, 170, 0.08);
|
||||
border-color: rgba(0, 212, 170, 0.25);
|
||||
box-shadow: 0 4px 12px rgba(0, 212, 170, 0.1);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.insight-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.trait-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.trait-name {
|
||||
color: #ffffff;
|
||||
font-weight: 500;
|
||||
font-size: 0.95rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.trait-score {
|
||||
color: #00d4aa;
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-bar {
|
||||
background: rgba(0, 212, 170, 0.15);
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.insight-fill {
|
||||
height: 100%;
|
||||
border-radius: 2px;
|
||||
transition: width 0.8s ease;
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.4;
|
||||
margin: 0;
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
.year-nav-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 4px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.current-year {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
min-width: 4rem;
|
||||
text-align: center;
|
||||
small {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -775,6 +476,7 @@
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.chart-section.xlarge,
|
||||
.chart-section.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
@@ -782,7 +484,7 @@
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.stats-container {
|
||||
.library-stats-container {
|
||||
padding: 15px;
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -814,11 +516,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.chart-config-btn {
|
||||
justify-content: center;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.config-modal {
|
||||
max-width: 95%;
|
||||
max-height: 85vh;
|
||||
@@ -860,6 +557,7 @@
|
||||
&.small,
|
||||
&.medium,
|
||||
&.large,
|
||||
&.xlarge,
|
||||
&.full-width {
|
||||
grid-column: 1;
|
||||
}
|
||||
@@ -882,84 +580,6 @@
|
||||
.chart-section {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
&.status-chart,
|
||||
&.book-type-chart,
|
||||
&.language-chart,
|
||||
&.series-chart {
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
&.progress-chart,
|
||||
&.rating-chart,
|
||||
&.page-count-chart,
|
||||
&.reading-speed-chart,
|
||||
&.quality-chart,
|
||||
&.velocity-chart {
|
||||
height: 280px;
|
||||
}
|
||||
|
||||
&.categories-chart,
|
||||
&.author-chart,
|
||||
&.completion-chart,
|
||||
&.publisher-chart,
|
||||
&.author-rating-chart,
|
||||
&.book-size-chart {
|
||||
height: 100px;
|
||||
}
|
||||
|
||||
&.year-chart,
|
||||
&.books-added-chart,
|
||||
&.monthly-chart,
|
||||
&.series-completion-chart,
|
||||
&.velocity-timeline-chart,
|
||||
&.monthly-patterns-chart,
|
||||
&.finished-books-timeline-chart {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
&.series-length-chart,
|
||||
&.author-series-chart,
|
||||
&.top-series-chart {
|
||||
height: 280px;
|
||||
}
|
||||
|
||||
&.reading-heatmap-chart {
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
.reading-profile-radar-chart,
|
||||
&.reading-dna-chart,
|
||||
&.reading-habits-chart {
|
||||
height: 350px;
|
||||
}
|
||||
}
|
||||
|
||||
.dna-insights,
|
||||
.intelligence-insights {
|
||||
.insights-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
padding: 10px;
|
||||
|
||||
.insight-header {
|
||||
.trait-name {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.trait-score {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
@@ -971,59 +591,6 @@
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
&.status-chart,
|
||||
&.book-type-chart,
|
||||
&.language-chart,
|
||||
&.series-chart {
|
||||
height: 220px;
|
||||
}
|
||||
|
||||
&.progress-chart,
|
||||
&.rating-chart,
|
||||
&.page-count-chart,
|
||||
&.reading-speed-chart,
|
||||
&.quality-chart,
|
||||
&.velocity-chart {
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
&.categories-chart,
|
||||
&.author-chart,
|
||||
&.completion-chart,
|
||||
&.publisher-chart,
|
||||
&.author-rating-chart,
|
||||
&.book-size-chart {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
&.year-chart,
|
||||
&.books-added-chart,
|
||||
&.monthly-chart,
|
||||
&.series-completion-chart,
|
||||
&.velocity-timeline-chart,
|
||||
&.monthly-patterns-chart,
|
||||
&.finished-books-timeline-chart {
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
&.series-length-chart,
|
||||
&.author-series-chart,
|
||||
&.top-series-chart {
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
&.reading-heatmap-chart {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
.reading-profile-radar-chart,
|
||||
&.reading-dna-chart,
|
||||
&.reading-habits-chart {
|
||||
height: 300px;
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-overlay {
|
||||
padding: 10px;
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {of, Subject} from 'rxjs';
|
||||
import {catchError, map, startWith, takeUntil} from 'rxjs/operators';
|
||||
import {CdkDragDrop, DragDropModule, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Button} from 'primeng/button';
|
||||
import {LanguageChartComponent} from './charts/language-chart/language-chart.component';
|
||||
import {BookFormatsChartComponent} from './charts/book-formats-chart/book-formats-chart.component';
|
||||
import {MetadataScoreChartComponent} from './charts/metadata-score-chart/metadata-score-chart.component';
|
||||
import {PageCountChartComponent} from './charts/page-count-chart/page-count-chart.component';
|
||||
import {TopItemsChartComponent} from './charts/top-items-chart/top-items-chart.component';
|
||||
import {AuthorUniverseChartComponent} from './charts/author-universe-chart/author-universe-chart.component';
|
||||
import {PublicationTimelineChartComponent} from './charts/publication-timeline-chart/publication-timeline-chart.component';
|
||||
import {PublicationTrendChartComponent} from './charts/publication-trend-chart/publication-trend-chart.component';
|
||||
import {ReadingJourneyChartComponent} from './charts/reading-journey-chart/reading-journey-chart.component';
|
||||
import {LibrariesSummaryService} from './service/libraries-summary.service';
|
||||
import {LibraryFilterService, LibraryOption} from './service/library-filter.service';
|
||||
|
||||
interface ChartConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
category: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-stats',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
Select,
|
||||
DragDropModule,
|
||||
Button,
|
||||
BookFormatsChartComponent,
|
||||
LanguageChartComponent,
|
||||
MetadataScoreChartComponent,
|
||||
PageCountChartComponent,
|
||||
TopItemsChartComponent,
|
||||
AuthorUniverseChartComponent,
|
||||
PublicationTimelineChartComponent,
|
||||
PublicationTrendChartComponent,
|
||||
ReadingJourneyChartComponent
|
||||
],
|
||||
templateUrl: './library-stats.component.html',
|
||||
styleUrls: ['./library-stats.component.scss']
|
||||
})
|
||||
export class LibraryStatsComponent implements OnInit, OnDestroy {
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly librariesSummaryService = inject(LibrariesSummaryService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public isLoading = true;
|
||||
public hasData = false;
|
||||
public hasError = false;
|
||||
public libraryOptions: LibraryOption[] = [];
|
||||
public selectedLibrary: LibraryOption | null = null;
|
||||
public showConfigPanel = false;
|
||||
|
||||
public chartsConfig: ChartConfig[] = [
|
||||
{id: 'bookFormats', name: 'Book Formats', enabled: true, category: 'small'},
|
||||
{id: 'languageDistribution', name: 'Languages', enabled: true, category: 'small'},
|
||||
{id: 'metadataScore', name: 'Metadata Score', enabled: true, category: 'small'},
|
||||
{id: 'pageCountDistribution', name: 'Page Count', enabled: true, category: 'small'},
|
||||
{id: 'publicationTimeline', name: 'Publication Timeline', enabled: true, category: 'large'},
|
||||
{id: 'readingJourney', name: 'Reading Journey', enabled: true, category: 'large'},
|
||||
{id: 'topItems', name: 'Top Items (Authors/Categories/etc.)', enabled: true, category: 'large'},
|
||||
{id: 'authorUniverse', name: 'Author Universe', enabled: true, category: 'large'},
|
||||
{id: 'publicationTrend', name: 'Publication Trend', enabled: true, category: 'xlarge'}
|
||||
];
|
||||
|
||||
booksSummary$ = this.librariesSummaryService.getBooksSummary().pipe(
|
||||
catchError(error => {
|
||||
console.error('Error loading books summary:', error);
|
||||
this.hasError = true;
|
||||
return of({totalBooks: 0, totalSizeKb: 0, totalAuthors: 0, totalSeries: 0, totalPublishers: 0});
|
||||
})
|
||||
);
|
||||
|
||||
public readonly totalBooks$ = this.booksSummary$.pipe(map(summary => summary.totalBooks));
|
||||
public readonly totalAuthors$ = this.booksSummary$.pipe(map(summary => summary.totalAuthors));
|
||||
public readonly totalSeries$ = this.booksSummary$.pipe(map(summary => summary.totalSeries));
|
||||
public readonly totalPublishers$ = this.booksSummary$.pipe(map(summary => summary.totalPublishers));
|
||||
public readonly totalSize$ = this.librariesSummaryService.getFormattedSize().pipe(catchError(() => of('0 KB')));
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadLibraryOptions();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
onLibraryChange(): void {
|
||||
if (!this.selectedLibrary) {
|
||||
return;
|
||||
}
|
||||
const libraryId = this.selectedLibrary.id;
|
||||
this.libraryFilterService.setSelectedLibrary(libraryId);
|
||||
}
|
||||
|
||||
private loadLibraryOptions(): void {
|
||||
this.libraryFilterService.getLibraryOptions()
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
startWith([]),
|
||||
catchError(error => {
|
||||
console.error('Error loading library options:', error);
|
||||
this.hasError = true;
|
||||
this.isLoading = false;
|
||||
return of([]);
|
||||
})
|
||||
)
|
||||
.subscribe({
|
||||
next: (options) => {
|
||||
this.libraryOptions = options;
|
||||
this.initializeSelectedLibrary(options);
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Subscription error:', error);
|
||||
this.hasError = true;
|
||||
this.isLoading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private initializeSelectedLibrary(options: LibraryOption[]): void {
|
||||
if (options.length === 0) {
|
||||
this.hasData = false;
|
||||
this.isLoading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.selectedLibrary) {
|
||||
this.hasData = true;
|
||||
this.isLoading = false;
|
||||
this.selectedLibrary = options[0];
|
||||
this.libraryFilterService.setSelectedLibrary(this.selectedLibrary.id);
|
||||
}
|
||||
}
|
||||
|
||||
public toggleConfigPanel(): void {
|
||||
this.showConfigPanel = !this.showConfigPanel;
|
||||
}
|
||||
|
||||
public closeConfigPanel(): void {
|
||||
this.showConfigPanel = false;
|
||||
}
|
||||
|
||||
public toggleChart(chartId: string): void {
|
||||
const chart = this.chartsConfig.find(c => c.id === chartId);
|
||||
if (chart) {
|
||||
chart.enabled = !chart.enabled;
|
||||
}
|
||||
}
|
||||
|
||||
public isChartEnabled(chartId: string): boolean {
|
||||
return this.chartsConfig.find(c => c.id === chartId)?.enabled ?? false;
|
||||
}
|
||||
|
||||
public enableAllCharts(): void {
|
||||
this.chartsConfig.forEach(chart => chart.enabled = true);
|
||||
}
|
||||
|
||||
public disableAllCharts(): void {
|
||||
this.chartsConfig.forEach(chart => chart.enabled = false);
|
||||
}
|
||||
|
||||
public getChartsByCategory(category: string): ChartConfig[] {
|
||||
return this.chartsConfig.filter(chart => chart.category === category);
|
||||
}
|
||||
|
||||
public getEnabledChartsSorted(): ChartConfig[] {
|
||||
return this.chartsConfig.filter(chart => chart.enabled);
|
||||
}
|
||||
|
||||
public onChartReorder(event: CdkDragDrop<ChartConfig[]>): void {
|
||||
if (event.previousIndex !== event.currentIndex) {
|
||||
moveItemInArray(this.chartsConfig, event.previousIndex, event.currentIndex);
|
||||
}
|
||||
}
|
||||
|
||||
public resetChartOrder(): void {
|
||||
this.chartsConfig = [
|
||||
{id: 'bookFormats', name: 'Book Formats', enabled: true, category: 'small'},
|
||||
{id: 'languageDistribution', name: 'Languages', enabled: true, category: 'small'},
|
||||
{id: 'metadataScore', name: 'Metadata Score', enabled: true, category: 'small'},
|
||||
{id: 'pageCountDistribution', name: 'Page Count', enabled: true, category: 'small'},
|
||||
{id: 'publicationTimeline', name: 'Publication Timeline', enabled: true, category: 'large'},
|
||||
{id: 'readingJourney', name: 'Reading Journey', enabled: true, category: 'large'},
|
||||
{id: 'topItems', name: 'Top Items (Authors/Categories/etc.)', enabled: true, category: 'large'},
|
||||
{id: 'authorUniverse', name: 'Author Universe', enabled: true, category: 'large'},
|
||||
{id: 'publicationTrend', name: 'Publication Trend', enabled: true, category: 'xlarge'}
|
||||
];
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {combineLatest, map, Observable} from 'rxjs';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, combineLatest, map, Observable} from 'rxjs';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {LibraryService} from '../../book/service/library.service';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
import {LibraryService} from '../../../../book/service/library.service';
|
||||
|
||||
export interface LibraryOption {
|
||||
id: number | null;
|
||||
@@ -1,319 +0,0 @@
|
||||
<div class="stats-container">
|
||||
<div class="header-card">
|
||||
<div class="filter-section">
|
||||
<div class="library-filter">
|
||||
<div class="select-row">
|
||||
<label for="library-dropdown">Library Statistics</label>
|
||||
<div class="flex w-full gap-2 align-items-center">
|
||||
<p-select
|
||||
fluid
|
||||
id="library-dropdown"
|
||||
[options]="libraryOptions"
|
||||
[(ngModel)]="selectedLibrary"
|
||||
optionLabel="name"
|
||||
size="small"
|
||||
placeholder="Select a library"
|
||||
(onChange)="onLibraryChange()"
|
||||
appendTo="body"
|
||||
[style]="{'min-width': '200px'}"
|
||||
class="library-dropdown">
|
||||
</p-select>
|
||||
|
||||
<p-button
|
||||
outlined
|
||||
size="small"
|
||||
(onClick)="toggleConfigPanel()"
|
||||
icon="pi pi-cog">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="library-totals" role="status" aria-live="polite">
|
||||
<div class="total-item total-books" title="Total books">
|
||||
<i class="pi pi-book"></i>
|
||||
<span class="total-label">Books</span>
|
||||
<span class="total-value">{{ totalBooks$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-authors" title="Total authors">
|
||||
<i class="pi pi-users"></i>
|
||||
<span class="total-label">Authors</span>
|
||||
<span class="total-value">{{ totalAuthors$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-series" title="Total series">
|
||||
<i class="pi pi-bookmark"></i>
|
||||
<span class="total-label">Series</span>
|
||||
<span class="total-value">{{ totalSeries$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-publishers" title="Total publishers">
|
||||
<i class="pi pi-building"></i>
|
||||
<span class="total-label">Publishers</span>
|
||||
<span class="total-value">{{ totalPublishers$ | async }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-size" title="Total size">
|
||||
<i class="pi pi-file"></i>
|
||||
<span class="total-label">Library Size</span>
|
||||
<span class="total-value">{{ totalSize$ | async }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chart Configuration Modal Overlay -->
|
||||
@if (showConfigPanel) {
|
||||
<div class="config-modal-overlay" (click)="closeConfigPanel()">
|
||||
<div class="config-modal" (click)="$event.stopPropagation()">
|
||||
<div class="config-modal-header">
|
||||
<h3><i class="pi pi-cog"></i> Chart Configuration</h3>
|
||||
<button type="button" class="close-btn" (click)="closeConfigPanel()" title="Close">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="config-modal-actions">
|
||||
<button type="button" class="config-action-btn enable-all" (click)="enableAllCharts()">
|
||||
<i class="pi pi-check"></i> Enable All
|
||||
</button>
|
||||
<button type="button" class="config-action-btn disable-all" (click)="disableAllCharts()">
|
||||
<i class="pi pi-times"></i> Disable All
|
||||
</button>
|
||||
<button type="button" class="config-action-btn reset-order" (click)="resetChartOrder()">
|
||||
<i class="pi pi-refresh"></i> Reset Order
|
||||
</button>
|
||||
<button type="button" class="config-action-btn reset-positions" (click)="resetChartPositions()">
|
||||
<i class="pi pi-map"></i> Reset Positions
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="config-modal-content">
|
||||
<div class="config-categories">
|
||||
<div class="config-category">
|
||||
<h4>Small Charts</h4>
|
||||
<div class="chart-toggles">
|
||||
@for (chart of getChartsByCategory('small'); track chart.id) {
|
||||
<div class="chart-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
[id]="'chart-' + chart.id"
|
||||
[checked]="chart.enabled"
|
||||
(change)="toggleChart(chart.id)">
|
||||
<label [for]="'chart-' + chart.id">{{ chart.name }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="config-category">
|
||||
<h4>Medium Charts</h4>
|
||||
<div class="chart-toggles">
|
||||
@for (chart of getChartsByCategory('medium'); track chart.id) {
|
||||
<div class="chart-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
[id]="'chart-' + chart.id"
|
||||
[checked]="chart.enabled"
|
||||
(change)="toggleChart(chart.id)">
|
||||
<label [for]="'chart-' + chart.id">{{ chart.name }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="config-category">
|
||||
<h4>Large Charts</h4>
|
||||
<div class="chart-toggles">
|
||||
@for (chart of getChartsByCategory('large'); track chart.id) {
|
||||
<div class="chart-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
[id]="'chart-' + chart.id"
|
||||
[checked]="chart.enabled"
|
||||
(change)="toggleChart(chart.id)">
|
||||
<label [for]="'chart-' + chart.id">{{ chart.name }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="config-category">
|
||||
<h4>Full Width Charts</h4>
|
||||
<div class="chart-toggles">
|
||||
@for (chart of getChartsByCategory('full-width'); track chart.id) {
|
||||
<div class="chart-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
[id]="'chart-' + chart.id"
|
||||
[checked]="chart.enabled"
|
||||
(change)="toggleChart(chart.id)">
|
||||
<label [for]="'chart-' + chart.id">{{ chart.name }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!isLoading && hasData) {
|
||||
<div class="charts-grid"
|
||||
cdkDropList
|
||||
(cdkDropListDropped)="onChartReorder($event)"
|
||||
[cdkDropListData]="getEnabledChartsSorted()">
|
||||
|
||||
@for (chartConfig of getEnabledChartsSorted(); track chartConfig.id) {
|
||||
<div class="chart-container"
|
||||
cdkDrag
|
||||
[cdkDragData]="chartConfig"
|
||||
[class]="'chart-section ' + chartConfig.category">
|
||||
|
||||
<div class="drag-handle" cdkDragHandle title="Drag to reorder">
|
||||
<i class="pi pi-bars"></i>
|
||||
</div>
|
||||
|
||||
@switch (chartConfig.id) {
|
||||
@case ('bookFormats') {
|
||||
<h3>Book Formats</h3>
|
||||
<div class="chart-wrapper book-type-chart">
|
||||
<canvas baseChart
|
||||
[data]="(bookTypeChartService.bookTypeChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="bookTypeChartService.bookTypeChartOptions"
|
||||
[type]="bookTypeChartService.bookTypeChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('languageDistribution') {
|
||||
<h3>Language Distribution</h3>
|
||||
<div class="chart-wrapper language-chart">
|
||||
<canvas baseChart
|
||||
[data]="(languageDistributionChartService.languageChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="languageDistributionChartService.languageChartOptions"
|
||||
[type]="languageDistributionChartService.languageChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('bookMetadataScore') {
|
||||
<h3>Book Metadata Score</h3>
|
||||
<div class="chart-wrapper quality-chart">
|
||||
<canvas baseChart
|
||||
[data]="(bookQualityScoreChartService.qualityChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="bookQualityScoreChartService.qualityChartOptions"
|
||||
[type]="bookQualityScoreChartService.qualityChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('topAuthors') {
|
||||
<h3>Top 25 Authors (with Reading Breakdown)</h3>
|
||||
<div class="chart-wrapper author-chart">
|
||||
<canvas baseChart
|
||||
[data]="(authorPopularityChartService.authorChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="authorPopularityChartService.authorChartOptions"
|
||||
[type]="authorPopularityChartService.authorChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('topCategories') {
|
||||
<h3>Top 25 Categories (with Reading Breakdown)</h3>
|
||||
<div class="chart-wrapper completion-chart">
|
||||
<canvas baseChart
|
||||
[data]="(readingCompletionChartService.completionChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="readingCompletionChartService.completionChartOptions"
|
||||
[type]="readingCompletionChartService.completionChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('topBooksBySize') {
|
||||
<h3>Top 20 Largest Books by File Size</h3>
|
||||
<div class="chart-wrapper book-size-chart">
|
||||
<canvas baseChart
|
||||
[data]="(bookSizeChartService.bookSizeChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="bookSizeChartService.bookSizeChartOptions"
|
||||
[type]="bookSizeChartService.bookSizeChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('monthlyReadingPatterns') {
|
||||
<h3>Monthly Reading Patterns</h3>
|
||||
<div class="chart-wrapper monthly-patterns-chart">
|
||||
<canvas baseChart
|
||||
[data]="(monthlyReadingPatternsChartService.monthlyPatternsChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="monthlyReadingPatternsChartService.monthlyPatternsChartOptions"
|
||||
[type]="monthlyReadingPatternsChartService.monthlyPatternsChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('externalRating') {
|
||||
<h3>External Rating Distribution</h3>
|
||||
<div class="chart-wrapper rating-chart">
|
||||
<canvas baseChart
|
||||
[data]="(bookRatingChartService.ratingChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="bookRatingChartService.ratingChartOptions"
|
||||
[type]="bookRatingChartService.ratingChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('pageCount') {
|
||||
<h3>Page Count Distribution</h3>
|
||||
<div class="chart-wrapper page-count-chart">
|
||||
<canvas baseChart
|
||||
[data]="(pageCountChartService.pageCountChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="pageCountChartService.pageCountChartOptions"
|
||||
[type]="pageCountChartService.pageCountChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('readingVelocityTimeline') {
|
||||
<h3>Reading Velocity Timeline</h3>
|
||||
<div class="chart-wrapper velocity-timeline-chart">
|
||||
<canvas baseChart
|
||||
[data]="(readingVelocityTimelineChartService.velocityTimelineChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="readingVelocityTimelineChartService.velocityTimelineChartOptions"
|
||||
[type]="readingVelocityTimelineChartService.velocityTimelineChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('topSeries') {
|
||||
<h3>Top 20 Series by Book Count</h3>
|
||||
<div class="chart-wrapper top-series-chart">
|
||||
<canvas baseChart
|
||||
[data]="(topSeriesChartService.seriesChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="topSeriesChartService.seriesChartOptions"
|
||||
[type]="topSeriesChartService.seriesChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
@case ('publicationYear') {
|
||||
<h3>Publication Year Timeline</h3>
|
||||
<div class="chart-wrapper year-chart">
|
||||
<canvas baseChart
|
||||
[data]="(publicationYearChartService.yearChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="publicationYearChartService.yearChartOptions"
|
||||
[type]="publicationYearChartService.yearChartType"
|
||||
[plugins]="[ChartDataLabels]">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (isLoading) {
|
||||
<div class="loading-message">
|
||||
Loading statistics...
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!isLoading && !hasData) {
|
||||
<div class="no-data-message">
|
||||
No data available.
|
||||
<small>Make sure your library contains books with metadata.</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@@ -1,208 +0,0 @@
|
||||
import {Component, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Chart, registerables, Tooltip} from 'chart.js';
|
||||
import 'chartjs-chart-matrix';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {catchError, map, of, startWith, Subject, takeUntil} from 'rxjs';
|
||||
import {CdkDragDrop, DragDropModule} from '@angular/cdk/drag-drop';
|
||||
import {Select} from 'primeng/select';
|
||||
import ChartDataLabels from 'chartjs-plugin-datalabels';
|
||||
import {Button} from 'primeng/button';
|
||||
import {MatrixController, MatrixElement} from 'chartjs-chart-matrix';
|
||||
import {PageTitleService} from "../../../shared/service/page-title.service";
|
||||
import {LibraryFilterService, LibraryOption} from '../service/library-filter.service';
|
||||
import {LibrariesSummaryService} from '../service/libraries-summary.service';
|
||||
import {BookTypeChartService} from '../service/book-type-chart.service';
|
||||
import {PageCountChartService} from '../service/page-count-chart.service';
|
||||
import {BookRatingChartService} from '../service/book-rating-chart.service';
|
||||
import {PublicationYearChartService} from '../service/publication-year-chart-service';
|
||||
import {AuthorPopularityChartService} from '../service/author-popularity-chart.service';
|
||||
import {ReadingCompletionChartService} from '../service/reading-completion-chart.service';
|
||||
import {LanguageDistributionChartService} from '../service/language-distribution-chart.service';
|
||||
import {BookQualityScoreChartService} from '../service/book-quality-score-chart.service';
|
||||
import {BookSizeChartService} from '../service/book-size-chart.service';
|
||||
import {ReadingVelocityTimelineChartService} from '../service/reading-velocity-timeline-chart.service';
|
||||
import {MonthlyReadingPatternsChartService} from '../service/monthly-reading-patterns-chart.service';
|
||||
import {TopSeriesChartService} from '../service/top-series-chart.service';
|
||||
import {ChartConfig, ChartConfigService} from '../service/chart-config.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-stats-component',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
BaseChartDirective,
|
||||
Select,
|
||||
DragDropModule,
|
||||
Button
|
||||
],
|
||||
templateUrl: './stats-component.html',
|
||||
styleUrls: ['./stats-component.scss']
|
||||
})
|
||||
export class StatsComponent implements OnInit, OnDestroy {
|
||||
|
||||
@ViewChild(BaseChartDirective) chart: BaseChartDirective | undefined;
|
||||
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly librariesSummaryService = inject(LibrariesSummaryService);
|
||||
protected readonly bookTypeChartService = inject(BookTypeChartService);
|
||||
protected readonly pageCountChartService = inject(PageCountChartService);
|
||||
protected readonly bookRatingChartService = inject(BookRatingChartService);
|
||||
protected readonly publicationYearChartService = inject(PublicationYearChartService);
|
||||
protected readonly authorPopularityChartService = inject(AuthorPopularityChartService);
|
||||
protected readonly readingCompletionChartService = inject(ReadingCompletionChartService);
|
||||
protected readonly languageDistributionChartService = inject(LanguageDistributionChartService);
|
||||
protected readonly bookQualityScoreChartService = inject(BookQualityScoreChartService);
|
||||
protected readonly bookSizeChartService = inject(BookSizeChartService);
|
||||
protected readonly readingVelocityTimelineChartService = inject(ReadingVelocityTimelineChartService);
|
||||
protected readonly monthlyReadingPatternsChartService = inject(MonthlyReadingPatternsChartService);
|
||||
protected readonly topSeriesChartService = inject(TopSeriesChartService);
|
||||
protected readonly chartConfigService = inject(ChartConfigService);
|
||||
private readonly pageTitle = inject(PageTitleService);
|
||||
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public isLoading = true;
|
||||
public hasData = false;
|
||||
public hasError = false;
|
||||
public libraryOptions: LibraryOption[] = [];
|
||||
public selectedLibrary: LibraryOption | null = null;
|
||||
public showConfigPanel = false;
|
||||
public chartsConfig: ChartConfig[] = [];
|
||||
|
||||
booksSummary$ = this.librariesSummaryService.getBooksSummary().pipe(
|
||||
catchError(error => {
|
||||
console.error('Error loading books summary:', error);
|
||||
this.hasError = true;
|
||||
return of({totalBooks: 0, totalSizeKb: 0, totalAuthors: 0, totalSeries: 0, totalPublishers: 0});
|
||||
})
|
||||
);
|
||||
|
||||
public readonly totalBooks$ = this.booksSummary$.pipe(map(summary => summary.totalBooks));
|
||||
public readonly totalAuthors$ = this.booksSummary$.pipe(map(summary => summary.totalAuthors));
|
||||
public readonly totalSeries$ = this.booksSummary$.pipe(map(summary => summary.totalSeries));
|
||||
public readonly totalPublishers$ = this.booksSummary$.pipe(map(summary => summary.totalPublishers));
|
||||
public readonly totalSize$ = this.librariesSummaryService.getFormattedSize().pipe(catchError(() => of('0 KB')));
|
||||
|
||||
ngOnInit(): void {
|
||||
Chart.register(...registerables, Tooltip, ChartDataLabels, MatrixController, MatrixElement);
|
||||
Chart.defaults.plugins.legend.labels.font = {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5,
|
||||
};
|
||||
this.pageTitle.setPageTitle('Statistics');
|
||||
this.loadLibraryOptions();
|
||||
this.loadChartConfig();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
onLibraryChange(): void {
|
||||
if (!this.selectedLibrary) {
|
||||
return;
|
||||
}
|
||||
const libraryId = this.selectedLibrary.id;
|
||||
this.libraryFilterService.setSelectedLibrary(libraryId);
|
||||
}
|
||||
|
||||
private loadLibraryOptions(): void {
|
||||
this.libraryFilterService.getLibraryOptions()
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
startWith([]),
|
||||
catchError(error => {
|
||||
console.error('Error loading library options:', error);
|
||||
this.hasError = true;
|
||||
this.isLoading = false;
|
||||
return of([]);
|
||||
})
|
||||
)
|
||||
.subscribe({
|
||||
next: (options) => {
|
||||
this.libraryOptions = options;
|
||||
this.initializeSelectedLibrary(options);
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Subscription error:', error);
|
||||
this.hasError = true;
|
||||
this.isLoading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private initializeSelectedLibrary(options: LibraryOption[]): void {
|
||||
if (options.length === 0) {
|
||||
this.hasData = false;
|
||||
this.isLoading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.selectedLibrary) {
|
||||
this.hasData = true;
|
||||
this.isLoading = false;
|
||||
this.selectedLibrary = options[0];
|
||||
this.libraryFilterService.setSelectedLibrary(this.selectedLibrary.id);
|
||||
}
|
||||
}
|
||||
|
||||
private loadChartConfig(): void {
|
||||
this.chartConfigService.chartsConfig$
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(config => {
|
||||
this.chartsConfig = config;
|
||||
});
|
||||
}
|
||||
|
||||
public toggleConfigPanel(): void {
|
||||
this.showConfigPanel = !this.showConfigPanel;
|
||||
}
|
||||
|
||||
public closeConfigPanel(): void {
|
||||
this.showConfigPanel = false;
|
||||
}
|
||||
|
||||
public toggleChart(chartId: string): void {
|
||||
this.chartConfigService.toggleChart(chartId);
|
||||
}
|
||||
|
||||
public isChartEnabled(chartId: string): boolean {
|
||||
return this.chartConfigService.isChartEnabled(chartId);
|
||||
}
|
||||
|
||||
public enableAllCharts(): void {
|
||||
this.chartConfigService.enableAllCharts();
|
||||
}
|
||||
|
||||
public disableAllCharts(): void {
|
||||
this.chartConfigService.disableAllCharts();
|
||||
}
|
||||
|
||||
public getChartsByCategory(category: string): ChartConfig[] {
|
||||
return this.chartsConfig.filter(chart => chart.category === category);
|
||||
}
|
||||
|
||||
public getEnabledChartsSorted(): ChartConfig[] {
|
||||
return this.chartConfigService.getEnabledChartsSorted();
|
||||
}
|
||||
|
||||
public onChartReorder(event: CdkDragDrop<ChartConfig[]>): void {
|
||||
if (event.previousIndex !== event.currentIndex) {
|
||||
this.chartConfigService.reorderCharts(event.previousIndex, event.currentIndex);
|
||||
}
|
||||
}
|
||||
|
||||
public resetChartOrder(): void {
|
||||
this.chartConfigService.resetOrder();
|
||||
}
|
||||
|
||||
public resetChartPositions(): void {
|
||||
this.chartConfigService.resetPositions();
|
||||
}
|
||||
|
||||
protected readonly ChartDataLabels = ChartDataLabels;
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {CompletionTimelineResponse, UserStatsService} from '../../../settings/user-management/user-stats.service';
|
||||
import {CompletionTimelineResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
type CompletionChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
+1
-1
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {FavoriteDaysResponse, UserStatsService} from '../../../settings/user-management/user-stats.service';
|
||||
import {Select} from 'primeng/select';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {FavoriteDaysResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
type FavoriteDaysChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {GenreStatsResponse, UserStatsService} from '../../../settings/user-management/user-stats.service';
|
||||
import {GenreStatsResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
type GenreChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
+16
-16
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {PeakHoursResponse, UserStatsService} from '../../../settings/user-management/user-stats.service';
|
||||
import {Select} from 'primeng/select';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {PeakHoursResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
type PeakHoursChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@@ -30,19 +30,19 @@ export class PeakHoursChartComponent implements OnInit, OnDestroy {
|
||||
public selectedMonth: number | null = null;
|
||||
public yearOptions: { label: string; value: number | null }[] = [];
|
||||
public monthOptions: { label: string; value: number | null }[] = [
|
||||
{ label: 'All Months', value: null },
|
||||
{ label: 'January', value: 1 },
|
||||
{ label: 'February', value: 2 },
|
||||
{ label: 'March', value: 3 },
|
||||
{ label: 'April', value: 4 },
|
||||
{ label: 'May', value: 5 },
|
||||
{ label: 'June', value: 6 },
|
||||
{ label: 'July', value: 7 },
|
||||
{ label: 'August', value: 8 },
|
||||
{ label: 'September', value: 9 },
|
||||
{ label: 'October', value: 10 },
|
||||
{ label: 'November', value: 11 },
|
||||
{ label: 'December', value: 12 }
|
||||
{label: 'All Months', value: null},
|
||||
{label: 'January', value: 1},
|
||||
{label: 'February', value: 2},
|
||||
{label: 'March', value: 3},
|
||||
{label: 'April', value: 4},
|
||||
{label: 'May', value: 5},
|
||||
{label: 'June', value: 6},
|
||||
{label: 'July', value: 7},
|
||||
{label: 'August', value: 8},
|
||||
{label: 'September', value: 9},
|
||||
{label: 'October', value: 10},
|
||||
{label: 'November', value: 11},
|
||||
{label: 'December', value: 12}
|
||||
];
|
||||
|
||||
constructor() {
|
||||
@@ -184,9 +184,9 @@ export class PeakHoursChartComponent implements OnInit, OnDestroy {
|
||||
|
||||
private initializeYearOptions(): void {
|
||||
const currentYear = new Date().getFullYear();
|
||||
this.yearOptions = [{ label: 'All Years', value: null }];
|
||||
this.yearOptions = [{label: 'All Years', value: null}];
|
||||
for (let year = currentYear; year >= currentYear - 10; year--) {
|
||||
this.yearOptions.push({ label: year.toString(), value: year });
|
||||
this.yearOptions.push({label: year.toString(), value: year});
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface RatingStats {
|
||||
ratingRange: string;
|
||||
+3
-3
@@ -63,7 +63,7 @@
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 400px;
|
||||
height: 500px;
|
||||
width: 100%;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
@@ -267,7 +267,7 @@
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 350px;
|
||||
height: 420px;
|
||||
|
||||
.quadrant-labels {
|
||||
.quadrant-label {
|
||||
@@ -324,7 +324,7 @@
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
height: 350px;
|
||||
}
|
||||
|
||||
.taste-insights {
|
||||
+9
-9
@@ -4,10 +4,10 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, ScatterDataPoint} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface TasteQuadrant {
|
||||
name: string;
|
||||
@@ -220,10 +220,10 @@ export class RatingTasteChartComponent implements OnInit, OnDestroy {
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -302,7 +302,7 @@ export class RatingTasteChartComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private updateChartData(dataPoints: Map<string, BookDataPoint[]>): void {
|
||||
const quadrantColors: Record<string, {bg: string, border: string}> = {
|
||||
const quadrantColors: Record<string, { bg: string, border: string }> = {
|
||||
'Popular Favorites': {bg: 'rgba(76, 175, 80, 0.7)', border: '#4caf50'},
|
||||
'Hidden Gems': {bg: 'rgba(156, 39, 176, 0.7)', border: '#9c27b0'},
|
||||
'Overrated': {bg: 'rgba(255, 152, 0, 0.7)', border: '#ff9800'},
|
||||
@@ -325,7 +325,7 @@ export class RatingTasteChartComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private calculateStatistics(dataPoints: Map<string, BookDataPoint[]>): void {
|
||||
const quadrantInfo: Record<string, {description: string, icon: string, color: string}> = {
|
||||
const quadrantInfo: Record<string, { description: string, icon: string, color: string }> = {
|
||||
'Popular Favorites': {
|
||||
description: 'Books you and the public both love',
|
||||
icon: '⭐',
|
||||
+3
-3
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, Chart, TooltipItem} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
|
||||
interface ReadingStatusStats {
|
||||
status: string;
|
||||
+7
-7
@@ -4,10 +4,10 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
|
||||
interface BacklogBucket {
|
||||
label: string;
|
||||
@@ -221,10 +221,10 @@ export class ReadingBacklogChartComponent implements OnInit, OnDestroy {
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
+6
-6
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
|
||||
interface ReadingDNAProfile {
|
||||
adventurous: number;
|
||||
@@ -244,10 +244,10 @@ export class ReadingDNAChartComponent implements OnInit, OnDestroy {
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
+6
-7
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
|
||||
interface ReadingHabitsProfile {
|
||||
consistency: number;
|
||||
@@ -244,10 +244,10 @@ export class ReadingHabitsChartComponent implements OnInit, OnDestroy {
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -269,7 +269,6 @@ export class ReadingHabitsChartComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private calculateConsistencyScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const booksWithDates = books.filter(book => book.dateFinished || book.addedOn);
|
||||
if (booksWithDates.length === 0) return 30;
|
||||
|
||||
+3
-3
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface MatrixDataPoint {
|
||||
x: number; // month (0-11)
|
||||
+6
-6
@@ -4,9 +4,9 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface ReadingProgressStats {
|
||||
progressRange: string;
|
||||
@@ -201,10 +201,10 @@ export class ReadingProgressChartComponent implements OnInit, OnDestroy {
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import {Chart, ChartConfiguration, ChartData, registerables} from 'chart.js';
|
||||
import {MatrixController, MatrixElement} from 'chartjs-chart-matrix';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {ReadingSessionHeatmapResponse, UserStatsService} from '../../../settings/user-management/user-stats.service';
|
||||
import {ReadingSessionHeatmapResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
const DAY_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
+3
-3
@@ -1,8 +1,5 @@
|
||||
import {Component, inject, Input, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {ReadingSessionTimelineResponse, UserStatsService} from '../../../settings/user-management/user-stats.service';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {BookType} from '../../../book/model/book.model';
|
||||
import {catchError} from 'rxjs/operators';
|
||||
import {of} from 'rxjs';
|
||||
import {Select} from 'primeng/select';
|
||||
@@ -18,6 +15,9 @@ import {
|
||||
setISOWeekYear,
|
||||
startOfISOWeek
|
||||
} from 'date-fns';
|
||||
import {BookType} from '../../../../../book/model/book.model';
|
||||
import {ReadingSessionTimelineResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {UrlHelperService} from '../../../../../../shared/service/url-helper.service';
|
||||
|
||||
interface ReadingSession {
|
||||
startTime: Date;
|
||||
+4
-4
@@ -4,10 +4,10 @@ import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {LibraryFilterService} from '../../service/library-filter.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 {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
|
||||
interface SeriesInfo {
|
||||
name: string;
|
||||
+15
-15
@@ -1,20 +1,20 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {ReadingSessionHeatmapComponent} from '../component/reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {ReadingSessionTimelineComponent} from '../component/reading-session-timeline/reading-session-timeline.component';
|
||||
import {GenreStatsChartComponent} from '../component/genre-stats-chart/genre-stats-chart.component';
|
||||
import {CompletionTimelineChartComponent} from '../component/completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {FavoriteDaysChartComponent} from '../component/favorite-days-chart/favorite-days-chart.component';
|
||||
import {PeakHoursChartComponent} from '../component/peak-hours-chart/peak-hours-chart.component';
|
||||
import {ReadingDNAChartComponent} from '../component/reading-dna-chart/reading-dna-chart.component';
|
||||
import {ReadingHabitsChartComponent} from '../component/reading-habits-chart/reading-habits-chart.component';
|
||||
import {ReadingHeatmapChartComponent} from '../component/reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {PersonalRatingChartComponent} from '../component/personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingProgressChartComponent} from '../component/reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from '../component/read-status-chart/read-status-chart.component';
|
||||
import {RatingTasteChartComponent} from '../component/rating-taste-chart/rating-taste-chart.component';
|
||||
import {ReadingBacklogChartComponent} from '../component/reading-backlog-chart/reading-backlog-chart.component';
|
||||
import {SeriesProgressChartComponent} from '../component/series-progress-chart/series-progress-chart.component';
|
||||
import {ReadingSessionHeatmapComponent} from '../charts/reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {FavoriteDaysChartComponent} from '../charts/favorite-days-chart/favorite-days-chart.component';
|
||||
import {PeakHoursChartComponent} from '../charts/peak-hours-chart/peak-hours-chart.component';
|
||||
import {ReadingSessionTimelineComponent} from '../charts/reading-session-timeline/reading-session-timeline.component';
|
||||
import {ReadingHeatmapChartComponent} from '../charts/reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {PersonalRatingChartComponent} from '../charts/personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingProgressChartComponent} from '../charts/reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from '../charts/read-status-chart/read-status-chart.component';
|
||||
import {GenreStatsChartComponent} from '../charts/genre-stats-chart/genre-stats-chart.component';
|
||||
import {CompletionTimelineChartComponent} from '../charts/completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {RatingTasteChartComponent} from '../charts/rating-taste-chart/rating-taste-chart.component';
|
||||
import {SeriesProgressChartComponent} from '../charts/series-progress-chart/series-progress-chart.component';
|
||||
import {ReadingDNAChartComponent} from '../charts/reading-dna-chart/reading-dna-chart.component';
|
||||
import {ReadingHabitsChartComponent} from '../charts/reading-habits-chart/reading-habits-chart.component';
|
||||
import {ReadingBacklogChartComponent} from '../charts/reading-backlog-chart/reading-backlog-chart.component';
|
||||
|
||||
export interface UserChartConfig {
|
||||
id: string;
|
||||
@@ -4,24 +4,24 @@ import {Subject} from 'rxjs';
|
||||
import {CdkDragDrop, DragDropModule} from '@angular/cdk/drag-drop';
|
||||
import {DialogModule} from 'primeng/dialog';
|
||||
import {ButtonModule} from 'primeng/button';
|
||||
import {ReadingSessionHeatmapComponent} from '../reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {ReadingSessionTimelineComponent} from '../reading-session-timeline/reading-session-timeline.component';
|
||||
import {GenreStatsChartComponent} from '../genre-stats-chart/genre-stats-chart.component';
|
||||
import {CompletionTimelineChartComponent} from '../completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {takeUntil} from 'rxjs/operators';
|
||||
import {FavoriteDaysChartComponent} from '../favorite-days-chart/favorite-days-chart.component';
|
||||
import {PeakHoursChartComponent} from '../peak-hours-chart/peak-hours-chart.component';
|
||||
import {ReadingDNAChartComponent} from '../reading-dna-chart/reading-dna-chart.component';
|
||||
import {ReadingHabitsChartComponent} from '../reading-habits-chart/reading-habits-chart.component';
|
||||
import {UserChartConfig, UserChartConfigService} from '../../service/user-chart-config.service';
|
||||
import {ReadingHeatmapChartComponent} from '../reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {PersonalRatingChartComponent} from '../personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingProgressChartComponent} from '../reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from '../read-status-chart/read-status-chart.component';
|
||||
import {RatingTasteChartComponent} from '../rating-taste-chart/rating-taste-chart.component';
|
||||
import {ReadingBacklogChartComponent} from '../reading-backlog-chart/reading-backlog-chart.component';
|
||||
import {SeriesProgressChartComponent} from '../series-progress-chart/series-progress-chart.component';
|
||||
import {PeakHoursChartComponent} from './charts/peak-hours-chart/peak-hours-chart.component';
|
||||
import {FavoriteDaysChartComponent} from './charts/favorite-days-chart/favorite-days-chart.component';
|
||||
import {ReadingDNAChartComponent} from './charts/reading-dna-chart/reading-dna-chart.component';
|
||||
import {CompletionTimelineChartComponent} from './charts/completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {ReadingHabitsChartComponent} from './charts/reading-habits-chart/reading-habits-chart.component';
|
||||
import {GenreStatsChartComponent} from './charts/genre-stats-chart/genre-stats-chart.component';
|
||||
import {ReadingHeatmapChartComponent} from './charts/reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {ReadingSessionTimelineComponent} from './charts/reading-session-timeline/reading-session-timeline.component';
|
||||
import {PersonalRatingChartComponent} from './charts/personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingSessionHeatmapComponent} from './charts/reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {ReadingProgressChartComponent} from './charts/reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from './charts/read-status-chart/read-status-chart.component';
|
||||
import {RatingTasteChartComponent} from './charts/rating-taste-chart/rating-taste-chart.component';
|
||||
import {SeriesProgressChartComponent} from './charts/series-progress-chart/series-progress-chart.component';
|
||||
import {ReadingBacklogChartComponent} from './charts/reading-backlog-chart/reading-backlog-chart.component';
|
||||
import {UserChartConfig, UserChartConfigService} from './service/user-chart-config.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-stats',
|
||||
|
||||
@@ -1,331 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
import {ChartConfiguration, ChartData, ChartType, TooltipItem} from 'chart.js';
|
||||
|
||||
interface AuthorStats {
|
||||
author: string;
|
||||
bookCount: number;
|
||||
averageRating: number;
|
||||
totalPages: number;
|
||||
readStatusCounts: Record<ReadStatus, number>;
|
||||
}
|
||||
|
||||
const READ_STATUS_COLORS: Record<ReadStatus, string> = {
|
||||
[ReadStatus.READ]: '#2ecc71',
|
||||
[ReadStatus.READING]: '#f39c12',
|
||||
[ReadStatus.RE_READING]: '#9b59b6',
|
||||
[ReadStatus.PARTIALLY_READ]: '#e67e22',
|
||||
[ReadStatus.PAUSED]: '#34495e',
|
||||
[ReadStatus.UNREAD]: '#4169e1',
|
||||
[ReadStatus.WONT_READ]: '#95a5a6',
|
||||
[ReadStatus.ABANDONED]: '#e74c3c',
|
||||
[ReadStatus.UNSET]: '#3498db'
|
||||
};
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
hoverBorderWidth: 1,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type AuthorChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthorPopularityChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly authorChartType = 'bar' as const;
|
||||
|
||||
public readonly authorChartOptions: ChartConfiguration<'bar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
x: {
|
||||
stacked: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {size: 10},
|
||||
maxRotation: 45,
|
||||
minRotation: 0
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Authors',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
}
|
||||
},
|
||||
y: {
|
||||
stacked: true,
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
stepSize: 1,
|
||||
maxTicksLimit: 25
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.05)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
},
|
||||
padding: 15,
|
||||
boxWidth: 12
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const dataIndex = context[0].dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
return stats[dataIndex]?.author || 'Unknown Author';
|
||||
},
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'index'
|
||||
}
|
||||
};
|
||||
|
||||
private readonly authorChartDataSubject = new BehaviorSubject<AuthorChartData>({
|
||||
labels: [],
|
||||
datasets: Object.values(ReadStatus).map(status => ({
|
||||
label: this.formatReadStatusLabel(status),
|
||||
data: [],
|
||||
backgroundColor: READ_STATUS_COLORS[status],
|
||||
...CHART_DEFAULTS
|
||||
}))
|
||||
});
|
||||
|
||||
public readonly authorChartData$: Observable<AuthorChartData> =
|
||||
this.authorChartDataSubject.asObservable();
|
||||
|
||||
private lastCalculatedStats: AuthorStats[] = [];
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing author stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateAuthorStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: AuthorStats[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
const topAuthors = stats
|
||||
.sort((a, b) => b.bookCount - a.bookCount)
|
||||
.slice(0, 25);
|
||||
|
||||
const labels = topAuthors.map(s => {
|
||||
return s.author.length > 20
|
||||
? s.author.substring(0, 15) + '..'
|
||||
: s.author;
|
||||
});
|
||||
|
||||
const datasets = Object.values(ReadStatus).map(status => ({
|
||||
label: this.formatReadStatusLabel(status),
|
||||
data: topAuthors.map(s => s.readStatusCounts[status] || 0),
|
||||
backgroundColor: READ_STATUS_COLORS[status],
|
||||
...CHART_DEFAULTS
|
||||
}));
|
||||
|
||||
this.authorChartDataSubject.next({
|
||||
labels,
|
||||
datasets
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating author chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateAuthorStats(): AuthorStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
return this.processAuthorStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processAuthorStats(books: Book[]): AuthorStats[] {
|
||||
const authorMap = new Map<string, {
|
||||
bookCount: number;
|
||||
totalRating: number;
|
||||
ratingCount: number;
|
||||
totalPages: number;
|
||||
readStatusCounts: Record<ReadStatus, number>;
|
||||
}>();
|
||||
|
||||
books.forEach(book => {
|
||||
const authors = book.metadata?.authors || ['Unknown Author'];
|
||||
|
||||
authors.forEach(author => {
|
||||
if (!authorMap.has(author)) {
|
||||
authorMap.set(author, {
|
||||
bookCount: 0,
|
||||
totalRating: 0,
|
||||
ratingCount: 0,
|
||||
totalPages: 0,
|
||||
readStatusCounts: Object.values(ReadStatus).reduce((acc, status) => {
|
||||
acc[status] = 0;
|
||||
return acc;
|
||||
}, {} as Record<ReadStatus, number>)
|
||||
});
|
||||
}
|
||||
|
||||
const stats = authorMap.get(author)!;
|
||||
stats.bookCount++;
|
||||
|
||||
if (book.metadata?.pageCount) {
|
||||
stats.totalPages += book.metadata.pageCount;
|
||||
}
|
||||
|
||||
const rawStatus = book.readStatus;
|
||||
const readStatus: ReadStatus = Object.values(ReadStatus).includes(rawStatus as ReadStatus)
|
||||
? (rawStatus as ReadStatus)
|
||||
: ReadStatus.UNSET;
|
||||
stats.readStatusCounts[readStatus]++;
|
||||
|
||||
const ratings = [];
|
||||
if (book.metadata?.goodreadsRating) ratings.push(book.metadata.goodreadsRating);
|
||||
if (book.metadata?.amazonRating) ratings.push(book.metadata.amazonRating);
|
||||
if (book.metadata?.hardcoverRating) ratings.push(book.metadata.hardcoverRating);
|
||||
if (book.metadata?.ranobedbRating) ratings.push(book.metadata.ranobedbRating);
|
||||
if (book.personalRating) ratings.push(book.personalRating);
|
||||
|
||||
if (ratings.length > 0) {
|
||||
const avgRating = ratings.reduce((sum, rating) => sum + rating, 0) / ratings.length;
|
||||
stats.totalRating += avgRating;
|
||||
stats.ratingCount++;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return Array.from(authorMap.entries()).map(([author, stats]) => ({
|
||||
author,
|
||||
bookCount: stats.bookCount,
|
||||
averageRating: stats.ratingCount > 0 ? stats.totalRating / stats.ratingCount : 0,
|
||||
totalPages: stats.totalPages,
|
||||
readStatusCounts: stats.readStatusCounts
|
||||
})).filter(stat => stat.bookCount > 0);
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
|
||||
if (!stats || dataIndex >= stats.length) {
|
||||
return `${context.parsed.y} books`;
|
||||
}
|
||||
|
||||
const author = stats[dataIndex];
|
||||
const value = context.parsed.y;
|
||||
const datasetLabel = context.dataset.label;
|
||||
|
||||
if (context.dataset.label === 'Read' && author.averageRating > 0) {
|
||||
return `${datasetLabel}: ${value} | Avg Rating: ${author.averageRating.toFixed(1)}`;
|
||||
} else {
|
||||
return `${datasetLabel}: ${value}`;
|
||||
}
|
||||
}
|
||||
|
||||
private formatReadStatusLabel(status: ReadStatus): string {
|
||||
return status.split('_').map(word =>
|
||||
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
|
||||
).join(' ');
|
||||
}
|
||||
|
||||
private getLastCalculatedStats(): AuthorStats[] {
|
||||
return this.lastCalculatedStats;
|
||||
}
|
||||
}
|
||||
@@ -1,301 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, Chart, TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface QualityScoreStats {
|
||||
category: string;
|
||||
count: number;
|
||||
averageScore: number;
|
||||
scoreRange: string;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#e74c3c', '#e67e22', '#f39c12', '#f1c40f', '#2ecc71',
|
||||
'#27ae60', '#3498db', '#9b59b6', '#8e44ad', '#34495e'
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
const QUALITY_COLORS = {
|
||||
'Excellent (9+)': '#2ecc71', // Green
|
||||
'Very Good (8-9)': '#27ae60', // Dark Green
|
||||
'Good (6-8)': '#3498db', // Blue
|
||||
'Average (4-6)': '#f39c12', // Orange
|
||||
'Poor (2-4)': '#e67e22', // Dark Orange
|
||||
'Very Poor (0-2)': '#e74c3c' // Red
|
||||
} as const;
|
||||
|
||||
type QualityChartData = ChartData<'doughnut', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookQualityScoreChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly qualityChartType = 'doughnut' as const;
|
||||
|
||||
public readonly qualityChartOptions: ChartConfiguration<'doughnut'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
padding: 12,
|
||||
usePointStyle: true,
|
||||
generateLabels: this.generateLegendLabels.bind(this)
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
position: 'nearest',
|
||||
callbacks: {
|
||||
title: (context) => context[0]?.label || '',
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
},
|
||||
cutout: '45%'
|
||||
};
|
||||
|
||||
private readonly qualityChartDataSubject = new BehaviorSubject<QualityChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly qualityChartData$: Observable<QualityChartData> = this.qualityChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing quality score stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateQualityScoreStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: QualityScoreStats[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
const labels = stats.map(s => s.category);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
const colors = this.getColorsForQualityData(stats);
|
||||
|
||||
this.qualityChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data: dataValues,
|
||||
backgroundColor: colors,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating quality chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private getColorsForQualityData(stats: QualityScoreStats[]): string[] {
|
||||
return stats.map(stat => QUALITY_COLORS[stat.category as keyof typeof QUALITY_COLORS] || '#34495e');
|
||||
}
|
||||
|
||||
private calculateQualityScoreStats(): QualityScoreStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId));
|
||||
return this.processQualityScoreStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
|
||||
return selectedLibraryId && selectedLibraryId !== 'null'
|
||||
? books.filter(book => String(book.libraryId) === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processQualityScoreStats(books: Book[]): QualityScoreStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const qualityCategories = this.categorizeByQualityScore(books);
|
||||
return this.convertToQualityStats(qualityCategories);
|
||||
}
|
||||
|
||||
private categorizeByQualityScore(books: Book[]): Map<string, { books: Book[], scores: number[] }> {
|
||||
const categories = new Map<string, { books: Book[], scores: number[] }>();
|
||||
|
||||
// Initialize 6 categories
|
||||
categories.set('Excellent (9+)', {books: [], scores: []});
|
||||
categories.set('Very Good (8-9)', {books: [], scores: []});
|
||||
categories.set('Good (6-8)', {books: [], scores: []});
|
||||
categories.set('Average (4-6)', {books: [], scores: []});
|
||||
categories.set('Poor (2-4)', {books: [], scores: []});
|
||||
categories.set('Very Poor (0-2)', {books: [], scores: []});
|
||||
|
||||
for (const book of books) {
|
||||
const qualityScore = this.calculateQualityScore(book);
|
||||
const category = this.getQualityCategory(qualityScore);
|
||||
|
||||
categories.get(category)!.books.push(book);
|
||||
categories.get(category)!.scores.push(qualityScore);
|
||||
}
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
private calculateQualityScore(book: Book): number {
|
||||
// Use metadataMatchScore directly, scale from 0-100 to 0-10
|
||||
if (book.metadataMatchScore !== null && book.metadataMatchScore !== undefined) {
|
||||
return Math.min(10, Math.max(0, book.metadataMatchScore / 10));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private getQualityCategory(score: number): string {
|
||||
if (score >= 9) return 'Excellent (9+)';
|
||||
if (score >= 8) return 'Very Good (8-9)';
|
||||
if (score >= 6) return 'Good (6-8)';
|
||||
if (score >= 4) return 'Average (4-6)';
|
||||
if (score >= 2) return 'Poor (2-4)';
|
||||
return 'Very Poor (0-2)';
|
||||
}
|
||||
|
||||
private convertToQualityStats(categoriesMap: Map<string, { books: Book[], scores: number[] }>): QualityScoreStats[] {
|
||||
const scoreRanges: Record<string, string> = {
|
||||
'Excellent (9+)': '90-100%',
|
||||
'Very Good (8-9)': '80-89%',
|
||||
'Good (6-8)': '60-79%',
|
||||
'Average (4-6)': '40-59%',
|
||||
'Poor (2-4)': '20-39%',
|
||||
'Very Poor (0-2)': '0-19%'
|
||||
};
|
||||
|
||||
return Array.from(categoriesMap.entries())
|
||||
.filter(([_, data]) => data.books.length > 0)
|
||||
.map(([category, data]) => {
|
||||
const averageScore = data.scores.reduce((sum, score) => sum + score, 0) / data.scores.length;
|
||||
|
||||
return {
|
||||
category,
|
||||
count: data.books.length,
|
||||
averageScore: Number(averageScore.toFixed(1)),
|
||||
scoreRange: scoreRanges[category] || 'Unknown'
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.averageScore - a.averageScore);
|
||||
}
|
||||
|
||||
private generateLegendLabels(chart: Chart) {
|
||||
const data = chart.data;
|
||||
if (!data.labels?.length || !data.datasets?.[0]?.data?.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dataset = data.datasets[0];
|
||||
|
||||
return data.labels.map((label: unknown, index: number) => {
|
||||
const isVisible = typeof chart.getDataVisibility === 'function'
|
||||
? chart.getDataVisibility(index)
|
||||
: !((chart.getDatasetMeta && (chart.getDatasetMeta(0)?.data?.[index] as any)?.hidden) || false);
|
||||
|
||||
return {
|
||||
text: String(label),
|
||||
fillStyle: (dataset.backgroundColor as string[])[index],
|
||||
strokeStyle: '#ffffff',
|
||||
lineWidth: 1,
|
||||
hidden: !isVisible,
|
||||
index,
|
||||
fontColor: '#ffffff'
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const qualityStats = this.getLastCalculatedStats();
|
||||
|
||||
if (!qualityStats || dataIndex >= qualityStats.length) {
|
||||
return `${context.parsed} books`;
|
||||
}
|
||||
|
||||
const stats = qualityStats[dataIndex];
|
||||
// Defensive: filter to numbers only, avoid division by zero
|
||||
const dataArr = (context.chart.data.datasets[0].data as (number | null | undefined)[]).filter((v): v is number => typeof v === 'number');
|
||||
const total = dataArr.reduce((a, b) => a + b, 0);
|
||||
const percentage = total > 0 ? ((stats.count / total) * 100).toFixed(1) : '0.0';
|
||||
|
||||
return `${stats.count} books (${percentage}%) | Average Score: ${stats.averageScore}/10 (${stats.scoreRange})`;
|
||||
}
|
||||
|
||||
private lastCalculatedStats: QualityScoreStats[] = [];
|
||||
|
||||
private getLastCalculatedStats(): QualityScoreStats[] {
|
||||
return this.lastCalculatedStats;
|
||||
}
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
import {ChartConfiguration, ChartData, ChartType} from 'chart.js';
|
||||
|
||||
interface RatingStats {
|
||||
ratingRange: string;
|
||||
count: number;
|
||||
averageRating: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#DC2626', // Red (1.0-1.9)
|
||||
'#EA580C', // Red-orange (2.0-2.9)
|
||||
'#F59E0B', // Orange (3.0-3.9)
|
||||
'#16A34A', // Green (4.0-4.5)
|
||||
'#2563EB' // Blue (4.6-5.0)
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
hoverBorderWidth: 2,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
const RATING_RANGES = [
|
||||
{range: '1.0-1.9', min: 1.0, max: 1.9},
|
||||
{range: '2.0-2.9', min: 2.0, max: 2.9},
|
||||
{range: '3.0-3.9', min: 3.0, max: 3.9},
|
||||
{range: '4.0-4.5', min: 4.0, max: 4.5},
|
||||
{range: '4.6-5.0', min: 4.6, max: 5.0},
|
||||
{range: 'No Rating', min: 0, max: 0}
|
||||
] as const;
|
||||
|
||||
type RatingChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookRatingChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly ratingChartType: ChartType = 'bar';
|
||||
|
||||
public readonly ratingChartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false,
|
||||
labels: {
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.8)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#666666',
|
||||
borderWidth: 1,
|
||||
callbacks: {
|
||||
title: (context) => `External Rating Range: ${context[0].label}`,
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
return `${value} book${value === 1 ? '' : 's'}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'External Rating Range',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.05)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly ratingChartDataSubject = new BehaviorSubject<RatingChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books by External Rating',
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly ratingChartData$: Observable<RatingChartData> =
|
||||
this.ratingChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing rating stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateRatingStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: RatingStats[]): void {
|
||||
try {
|
||||
const labels = stats.map(s => s.ratingRange);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
|
||||
this.ratingChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'Books by External Rating',
|
||||
data: dataValues,
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateRatingStats(): RatingStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
return this.processRatingStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processRatingStats(books: Book[]): RatingStats[] {
|
||||
const rangeCounts = new Map<string, { count: number, totalRating: number }>();
|
||||
RATING_RANGES.forEach(range => rangeCounts.set(range.range, {count: 0, totalRating: 0}));
|
||||
|
||||
books.forEach(book => {
|
||||
const rating = this.getBookRating(book);
|
||||
|
||||
if (rating === 0) {
|
||||
const noRatingData = rangeCounts.get('No Rating')!;
|
||||
noRatingData.count++;
|
||||
} else {
|
||||
for (const range of RATING_RANGES) {
|
||||
if (range.range !== 'No Rating' && rating >= range.min && rating <= range.max) {
|
||||
const rangeData = rangeCounts.get(range.range)!;
|
||||
rangeData.count++;
|
||||
rangeData.totalRating += rating;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return RATING_RANGES.map(range => {
|
||||
const data = rangeCounts.get(range.range)!;
|
||||
return {
|
||||
ratingRange: range.range,
|
||||
count: data.count,
|
||||
averageRating: data.count > 0 ? data.totalRating / data.count : 0
|
||||
};
|
||||
}).filter(stat => stat.ratingRange !== 'No Rating');
|
||||
}
|
||||
|
||||
private getBookRating(book: Book): number {
|
||||
const ratings = [];
|
||||
|
||||
if (book.metadata?.goodreadsRating) ratings.push(book.metadata.goodreadsRating);
|
||||
if (book.metadata?.amazonRating) ratings.push(book.metadata.amazonRating);
|
||||
if (book.metadata?.hardcoverRating) ratings.push(book.metadata.hardcoverRating);
|
||||
if (book.metadata?.ranobedbRating) ratings.push(book.metadata.ranobedbRating);
|
||||
|
||||
if (ratings.length > 0) {
|
||||
return ratings.reduce((sum, rating) => sum + rating, 0) / ratings.length;
|
||||
}
|
||||
|
||||
if (book.metadata?.rating) return book.metadata.rating;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface BookSizeStats {
|
||||
title: string;
|
||||
sizeMB: number;
|
||||
bookType: string;
|
||||
pageCount?: number;
|
||||
}
|
||||
|
||||
function getBookTypeColor(bookType: string): string {
|
||||
const cssVarName = `--book-type-${bookType.toLowerCase()}-color`;
|
||||
const color = getComputedStyle(document.documentElement).getPropertyValue(cssVarName).trim();
|
||||
return color || '#95a5a6'; // fallback gray
|
||||
}
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderWidth: 1,
|
||||
hoverBorderWidth: 2,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type BookSizeChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookSizeChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly bookSizeChartType = 'bar' as const;
|
||||
|
||||
public readonly bookSizeChartOptions: ChartConfiguration<'bar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
indexAxis: 'y',
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
callback: function (value) {
|
||||
return value + ' MB';
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'File Size (MB)',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
maxTicksLimit: 25
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.05)'
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
datalabels: {
|
||||
display: true,
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
size: 10,
|
||||
family: "'Inter', sans-serif",
|
||||
weight: 'bold'
|
||||
},
|
||||
align: 'center',
|
||||
offset: 8,
|
||||
formatter: (value: number) => `${Math.round(value)} MB`
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const dataIndex = context[0].dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
return stats[dataIndex]?.title || 'Unknown';
|
||||
},
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
}
|
||||
};
|
||||
|
||||
private readonly bookSizeChartDataSubject = new BehaviorSubject<BookSizeChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly bookSizeChartData$: Observable<BookSizeChartData> = this.bookSizeChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing book size stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateBookSizeStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: BookSizeStats[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
const labels = stats.map(s => this.truncateTitle(s.title, 30));
|
||||
const dataValues = stats.map(s => s.sizeMB);
|
||||
const colors = stats.map(s => getBookTypeColor(s.bookType));
|
||||
|
||||
this.bookSizeChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'File Size',
|
||||
data: dataValues,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating book size chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateBookSizeStats(): BookSizeStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId));
|
||||
return this.processBookSizeStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
|
||||
return selectedLibraryId && selectedLibraryId !== 'null'
|
||||
? books.filter(book => String(book.libraryId) === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processBookSizeStats(books: Book[]): BookSizeStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const booksWithSize = books
|
||||
.filter(book => book.fileSizeKb && book.fileSizeKb > 0)
|
||||
.map(book => ({
|
||||
title: book.metadata?.title || book.fileName || 'Unknown Title',
|
||||
sizeMB: Number((book.fileSizeKb! / 1024).toFixed(2)),
|
||||
bookType: book.bookType,
|
||||
pageCount: book.metadata?.pageCount || undefined
|
||||
}))
|
||||
.sort((a, b) => b.sizeMB - a.sizeMB)
|
||||
.slice(0, 20);
|
||||
|
||||
return booksWithSize;
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
|
||||
if (!stats || dataIndex >= stats.length) {
|
||||
return `${context.parsed.x} MB`;
|
||||
}
|
||||
|
||||
const book = stats[dataIndex];
|
||||
const sizeInfo = `${book.sizeMB} MB`;
|
||||
const typeInfo = `Format: ${book.bookType}`;
|
||||
const pageInfo = book.pageCount ? `Pages: ${book.pageCount}` : 'Pages: Unknown';
|
||||
|
||||
return `${sizeInfo} | ${typeInfo} | ${pageInfo}`;
|
||||
}
|
||||
|
||||
private lastCalculatedStats: BookSizeStats[] = [];
|
||||
|
||||
private getLastCalculatedStats(): BookSizeStats[] {
|
||||
return this.lastCalculatedStats;
|
||||
}
|
||||
|
||||
private truncateTitle(title: string, maxLength: number): string {
|
||||
return title.length > maxLength ? title.substring(0, maxLength) + '...' : title;
|
||||
}
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, ChartType, Chart, TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface BookTypeStats {
|
||||
bookType: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFA726', '#AB47BC'] as const;
|
||||
const CHART_DEFAULTS = {
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
borderColor: '#ffffff',
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type BookTypeChartData = ChartData<'pie', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookTypeChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly bookTypeChartType: ChartType = 'pie';
|
||||
|
||||
public readonly bookTypeChartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
padding: 12,
|
||||
usePointStyle: true,
|
||||
generateLabels: this.generateLegendLabels.bind(this)
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
position: 'nearest',
|
||||
callbacks: {
|
||||
title: (context) => context[0]?.label || '',
|
||||
label: this.formatTooltipLabel
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
}
|
||||
};
|
||||
|
||||
private readonly bookTypeChartDataSubject = new BehaviorSubject<BookTypeChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly bookTypeChartData$: Observable<BookTypeChartData> =
|
||||
this.bookTypeChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing book type stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateBookTypeStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: BookTypeStats[]): void {
|
||||
try {
|
||||
const labels = stats.map(s => s.bookType);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
const colors = this.getColorsForData(stats.length);
|
||||
|
||||
this.bookTypeChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data: dataValues,
|
||||
backgroundColor: colors,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private getColorsForData(dataLength: number): string[] {
|
||||
// Repeat colors if we have more data points than colors
|
||||
const colors = [...CHART_COLORS];
|
||||
while (colors.length < dataLength) {
|
||||
colors.push(...CHART_COLORS);
|
||||
}
|
||||
return colors.slice(0, dataLength);
|
||||
}
|
||||
|
||||
private calculateBookTypeStats(): BookTypeStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId));
|
||||
return this.processBookTypeStats(filteredBooks);
|
||||
}
|
||||
|
||||
public updateFromStats(stats: BookTypeStats[]): void {
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
|
||||
return selectedLibraryId && selectedLibraryId !== 'null'
|
||||
? books.filter(book => String(book.libraryId) === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processBookTypeStats(books: Book[]): BookTypeStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const typeMap = this.buildTypeMap(books);
|
||||
return this.convertMapToStats(typeMap, books.length);
|
||||
}
|
||||
|
||||
private buildTypeMap(books: Book[]): Map<string, number> {
|
||||
const typeMap = new Map<string, number>();
|
||||
|
||||
for (const book of books) {
|
||||
const type = book.bookType || 'Unknown';
|
||||
typeMap.set(type, (typeMap.get(type) || 0) + 1);
|
||||
}
|
||||
|
||||
return typeMap;
|
||||
}
|
||||
|
||||
private convertMapToStats(typeMap: Map<string, number>, totalBooks: number): BookTypeStats[] {
|
||||
return Array.from(typeMap.entries())
|
||||
.map(([bookType, count]) => ({
|
||||
bookType: this.formatBookType(bookType),
|
||||
count,
|
||||
percentage: Number(((count / totalBooks) * 100).toFixed(1))
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
private formatBookType(type: string): string {
|
||||
const TYPE_MAPPING: Record<string, string> = {
|
||||
PDF: 'PDF',
|
||||
EPUB: 'EPUB',
|
||||
CBX: 'Comic Books',
|
||||
Unknown: 'Unknown Format'
|
||||
} as const;
|
||||
|
||||
return TYPE_MAPPING[type] || type;
|
||||
}
|
||||
|
||||
private generateLegendLabels(chart: Chart) {
|
||||
const data = chart.data;
|
||||
if (!data.labels?.length || !data.datasets?.[0]?.data?.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dataset = data.datasets[0];
|
||||
const dataValues = dataset.data as number[];
|
||||
|
||||
return data.labels.map((label: unknown, index: number) => ({
|
||||
text: `${String(label)} (${dataValues[index]})`,
|
||||
fillStyle: (dataset.backgroundColor as string[])[index],
|
||||
strokeStyle: '#ffffff',
|
||||
lineWidth: 1,
|
||||
hidden: false,
|
||||
fontColor: '#ffffff',
|
||||
index
|
||||
}));
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const dataset = context.dataset;
|
||||
const value = dataset.data[dataIndex] as number;
|
||||
const label = context.chart.data.labels?.[dataIndex] || 'Unknown';
|
||||
const total = (dataset.data as number[]).reduce((a: number, b: number) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
return `${label}: ${value} books (${percentage}%)`;
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
|
||||
export interface ChartConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
category: 'small' | 'medium' | 'large' | 'full-width';
|
||||
order: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ChartConfigService {
|
||||
private readonly STORAGE_KEY = 'booklore-chart-config';
|
||||
|
||||
private readonly defaultCharts: ChartConfig[] = [
|
||||
{id: 'bookFormats', name: 'Book Formats', enabled: true, category: 'small', order: 0},
|
||||
{id: 'bookMetadataScore', name: 'Book Metadata Score', enabled: true, category: 'small', order: 1},
|
||||
{id: 'languageDistribution', name: 'Language Distribution', enabled: true, category: 'small', order: 2},
|
||||
{id: 'pageCount', name: 'Page Count Distribution', enabled: true, category: 'medium', order: 3},
|
||||
{id: 'topAuthors', name: 'Top 25 Authors', enabled: true, category: 'large', order: 4},
|
||||
{id: 'topCategories', name: 'Top 25 Categories', enabled: true, category: 'large', order: 5},
|
||||
{id: 'monthlyReadingPatterns', name: 'Monthly Reading Patterns', enabled: true, category: 'large', order: 6},
|
||||
{id: 'readingVelocityTimeline', name: 'Reading Velocity Timeline', enabled: true, category: 'large', order: 7},
|
||||
{id: 'topBooksBySize', name: 'Top 20 Largest Books', enabled: true, category: 'large', order: 8},
|
||||
{id: 'topSeries', name: 'Top 20 Series', enabled: true, category: 'large', order: 9},
|
||||
{id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 10},
|
||||
{id: 'externalRating', name: 'External Rating Distribution', enabled: true, category: 'medium', order: 11},
|
||||
];
|
||||
|
||||
private chartsConfigSubject = new BehaviorSubject<ChartConfig[]>(this.loadConfig());
|
||||
public chartsConfig$ = this.chartsConfigSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.initializeConfig();
|
||||
}
|
||||
|
||||
private initializeConfig(): void {
|
||||
const savedConfig = this.loadConfig();
|
||||
this.chartsConfigSubject.next(savedConfig);
|
||||
}
|
||||
|
||||
private loadConfig(): ChartConfig[] {
|
||||
try {
|
||||
const saved = localStorage.getItem(this.STORAGE_KEY);
|
||||
if (saved) {
|
||||
const savedConfig = JSON.parse(saved) as ChartConfig[];
|
||||
return this.mergeWithDefaults(savedConfig);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading chart config from localStorage:', error);
|
||||
}
|
||||
return [...this.defaultCharts];
|
||||
}
|
||||
|
||||
private mergeWithDefaults(savedConfig: ChartConfig[]): ChartConfig[] {
|
||||
const merged = [...this.defaultCharts];
|
||||
|
||||
savedConfig.forEach(saved => {
|
||||
const index = merged.findIndex(chart => chart.id === saved.id);
|
||||
if (index !== -1) {
|
||||
merged[index] = {
|
||||
...merged[index],
|
||||
enabled: saved.enabled,
|
||||
order: saved.order !== undefined ? saved.order : merged[index].order
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return merged.sort((a, b) => a.order - b.order);
|
||||
}
|
||||
|
||||
private saveConfig(config: ChartConfig[]): void {
|
||||
try {
|
||||
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(config));
|
||||
} catch (error) {
|
||||
console.error('Error saving chart config to localStorage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
public toggleChart(chartId: string): void {
|
||||
const currentConfig = this.chartsConfigSubject.value;
|
||||
const updatedConfig = currentConfig.map(chart =>
|
||||
chart.id === chartId ? {...chart, enabled: !chart.enabled} : chart
|
||||
);
|
||||
|
||||
this.chartsConfigSubject.next(updatedConfig);
|
||||
this.saveConfig(updatedConfig);
|
||||
}
|
||||
|
||||
public isChartEnabled(chartId: string): boolean {
|
||||
const config = this.chartsConfigSubject.value;
|
||||
const chart = config.find(c => c.id === chartId);
|
||||
return chart?.enabled ?? false;
|
||||
}
|
||||
|
||||
public enableAllCharts(): void {
|
||||
const updatedConfig = this.chartsConfigSubject.value.map(chart => ({...chart, enabled: true}));
|
||||
this.chartsConfigSubject.next(updatedConfig);
|
||||
this.saveConfig(updatedConfig);
|
||||
}
|
||||
|
||||
public disableAllCharts(): void {
|
||||
const updatedConfig = this.chartsConfigSubject.value.map(chart => ({...chart, enabled: false}));
|
||||
this.chartsConfigSubject.next(updatedConfig);
|
||||
this.saveConfig(updatedConfig);
|
||||
}
|
||||
|
||||
public getEnabledChartsSorted(): ChartConfig[] {
|
||||
return this.chartsConfigSubject.value
|
||||
.filter(chart => chart.enabled)
|
||||
.sort((a, b) => a.order - b.order);
|
||||
}
|
||||
|
||||
public reorderCharts(fromIndex: number, toIndex: number): void {
|
||||
const currentConfig = [...this.chartsConfigSubject.value];
|
||||
const enabledCharts = currentConfig.filter(chart => chart.enabled).sort((a, b) => a.order - b.order);
|
||||
|
||||
if (fromIndex >= enabledCharts.length || toIndex >= enabledCharts.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [movedChart] = enabledCharts.splice(fromIndex, 1);
|
||||
enabledCharts.splice(toIndex, 0, movedChart);
|
||||
|
||||
enabledCharts.forEach((chart, index) => {
|
||||
const configIndex = currentConfig.findIndex(c => c.id === chart.id);
|
||||
if (configIndex !== -1) {
|
||||
currentConfig[configIndex] = {...currentConfig[configIndex], order: index};
|
||||
}
|
||||
});
|
||||
|
||||
this.chartsConfigSubject.next(currentConfig);
|
||||
this.saveConfig(currentConfig);
|
||||
}
|
||||
|
||||
public resetOrder(): void {
|
||||
const currentConfig = this.chartsConfigSubject.value.map((chart, index) => ({
|
||||
...chart,
|
||||
order: this.defaultCharts.find(d => d.id === chart.id)?.order ?? index
|
||||
}));
|
||||
|
||||
this.chartsConfigSubject.next(currentConfig);
|
||||
this.saveConfig(currentConfig);
|
||||
}
|
||||
|
||||
public resetPositions(): void {
|
||||
const resetConfig = this.defaultCharts.map(defaultChart => {
|
||||
const currentChart = this.chartsConfigSubject.value.find(c => c.id === defaultChart.id);
|
||||
return {
|
||||
...defaultChart,
|
||||
enabled: currentChart?.enabled ?? defaultChart.enabled
|
||||
};
|
||||
});
|
||||
|
||||
this.chartsConfigSubject.next(resetConfig);
|
||||
this.saveConfig(resetConfig);
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, Chart, TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface LanguageStats {
|
||||
language: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#4e79a7', '#f28e2c', '#e15759', '#76b7b2', '#59a14f',
|
||||
'#edc949', '#af7aa1', '#ff9da7', '#9c755f', '#bab0ab',
|
||||
'#17becf', '#bcbd22', '#1f77b4', '#ff7f0e', '#2ca02c'
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type LanguageChartData = ChartData<'doughnut', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class LanguageDistributionChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly languageChartType = 'doughnut' as const;
|
||||
|
||||
public readonly languageChartOptions: ChartConfiguration<'doughnut'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
padding: 12,
|
||||
usePointStyle: true,
|
||||
generateLabels: this.generateLegendLabels.bind(this)
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
position: 'nearest',
|
||||
callbacks: {
|
||||
title: (context) => context[0]?.label || '',
|
||||
label: this.formatTooltipLabel
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
},
|
||||
cutout: '45%'
|
||||
};
|
||||
|
||||
private readonly languageChartDataSubject = new BehaviorSubject<LanguageChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly languageChartData$: Observable<LanguageChartData> = this.languageChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing language stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateLanguageStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: LanguageStats[]): void {
|
||||
try {
|
||||
const topLanguages = stats.slice(0, 12); // Show top 12 languages
|
||||
const labels = topLanguages.map(s => s.language);
|
||||
const dataValues = topLanguages.map(s => s.count);
|
||||
const colors = this.getColorsForData(topLanguages.length);
|
||||
|
||||
this.languageChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data: dataValues,
|
||||
backgroundColor: colors,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating language chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private getColorsForData(dataLength: number): string[] {
|
||||
const colors = [...CHART_COLORS];
|
||||
while (colors.length < dataLength) {
|
||||
colors.push(...CHART_COLORS);
|
||||
}
|
||||
return colors.slice(0, dataLength);
|
||||
}
|
||||
|
||||
private calculateLanguageStats(): LanguageStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId));
|
||||
return this.processLanguageStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
|
||||
return selectedLibraryId && selectedLibraryId !== 'null'
|
||||
? books.filter(book => String(book.libraryId) === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processLanguageStats(books: Book[]): LanguageStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const languageMap = this.buildLanguageMap(books);
|
||||
return this.convertMapToStats(languageMap, books.length);
|
||||
}
|
||||
|
||||
private buildLanguageMap(books: Book[]): Map<string, number> {
|
||||
const languageMap = new Map<string, number>();
|
||||
|
||||
for (const book of books) {
|
||||
const language = book.metadata?.language;
|
||||
if (language && language.trim()) {
|
||||
const normalizedLanguage = this.normalizeLanguage(language.trim());
|
||||
languageMap.set(normalizedLanguage, (languageMap.get(normalizedLanguage) || 0) + 1);
|
||||
} else {
|
||||
languageMap.set('Unknown', (languageMap.get('Unknown') || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return languageMap;
|
||||
}
|
||||
|
||||
private normalizeLanguage(language: string): string {
|
||||
const languageMap: Record<string, string> = {
|
||||
'en': 'English',
|
||||
'eng': 'English',
|
||||
'english': 'English',
|
||||
'es': 'Spanish',
|
||||
'spa': 'Spanish',
|
||||
'spanish': 'Spanish',
|
||||
'fr': 'French',
|
||||
'fre': 'French',
|
||||
'fra': 'French',
|
||||
'french': 'French',
|
||||
'de': 'German',
|
||||
'ger': 'German',
|
||||
'deu': 'German',
|
||||
'german': 'German',
|
||||
'it': 'Italian',
|
||||
'ita': 'Italian',
|
||||
'italian': 'Italian',
|
||||
'pt': 'Portuguese',
|
||||
'por': 'Portuguese',
|
||||
'portuguese': 'Portuguese',
|
||||
'ru': 'Russian',
|
||||
'rus': 'Russian',
|
||||
'russian': 'Russian',
|
||||
'ja': 'Japanese',
|
||||
'jpn': 'Japanese',
|
||||
'japanese': 'Japanese',
|
||||
'zh': 'Chinese',
|
||||
'chi': 'Chinese',
|
||||
'chinese': 'Chinese',
|
||||
'ko': 'Korean',
|
||||
'kor': 'Korean',
|
||||
'korean': 'Korean',
|
||||
'ar': 'Arabic',
|
||||
'ara': 'Arabic',
|
||||
'arabic': 'Arabic'
|
||||
};
|
||||
|
||||
const normalized = language.toLowerCase();
|
||||
return languageMap[normalized] || this.capitalizeFirst(language);
|
||||
}
|
||||
|
||||
private capitalizeFirst(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
|
||||
}
|
||||
|
||||
private convertMapToStats(languageMap: Map<string, number>, totalBooks: number): LanguageStats[] {
|
||||
return Array.from(languageMap.entries())
|
||||
.map(([language, count]) => ({
|
||||
language,
|
||||
count,
|
||||
percentage: Number(((count / totalBooks) * 100).toFixed(1))
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
private generateLegendLabels(chart: Chart) {
|
||||
const data = chart.data;
|
||||
if (!data.labels?.length || !data.datasets?.[0]?.data?.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dataset = data.datasets[0];
|
||||
const dataValues = dataset.data as number[];
|
||||
|
||||
return data.labels.map((label: unknown, index: number) => {
|
||||
const isVisible = typeof chart.getDataVisibility === 'function'
|
||||
? chart.getDataVisibility(index)
|
||||
: !((chart.getDatasetMeta && (chart.getDatasetMeta(0)?.data?.[index] as any)?.hidden) || false);
|
||||
|
||||
return {
|
||||
text: `${String(label)} (${dataValues[index]})`,
|
||||
fillStyle: (dataset.backgroundColor as string[])[index],
|
||||
strokeStyle: '#ffffff',
|
||||
lineWidth: 1,
|
||||
hidden: !isVisible,
|
||||
index,
|
||||
fontColor: '#ffffff'
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const dataset = context.dataset;
|
||||
const value = dataset.data[dataIndex] as number;
|
||||
const label = context.chart.data.labels?.[dataIndex] || 'Unknown';
|
||||
const total = (dataset.data as number[]).reduce((a: number, b: number) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
return `${label}: ${value} books (${percentage}%)`;
|
||||
}
|
||||
}
|
||||
@@ -1,502 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface MonthlyPattern {
|
||||
month: string;
|
||||
booksStarted: number;
|
||||
booksFinished: number;
|
||||
booksAdded: number;
|
||||
averageProgress: number;
|
||||
totalReadingTime: number;
|
||||
genreDiversity: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = {
|
||||
booksStarted: '#3498db',
|
||||
booksFinished: '#2ecc71',
|
||||
booksAdded: '#f39c12',
|
||||
averageProgress: '#e74c3c',
|
||||
genreDiversity: '#9b59b6'
|
||||
} as const;
|
||||
|
||||
type MonthlyPatternsChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class MonthlyReadingPatternsChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly monthlyPatternsChartType = 'line' as const;
|
||||
|
||||
public readonly monthlyPatternsChartOptions: ChartConfiguration<'line'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
x: {
|
||||
type: 'category',
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Month',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'left',
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Book Count',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y1: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'right',
|
||||
beginAtZero: true,
|
||||
max: 100,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
callback: function(value) {
|
||||
return value + '%';
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
drawOnChartArea: false
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Progress %',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
padding: 12,
|
||||
usePointStyle: true
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => context[0]?.label || '',
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'index'
|
||||
},
|
||||
elements: {
|
||||
point: {
|
||||
radius: 4,
|
||||
hoverRadius: 6
|
||||
},
|
||||
line: {
|
||||
tension: 0.3,
|
||||
borderWidth: 2
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly monthlyPatternsChartDataSubject = new BehaviorSubject<MonthlyPatternsChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly monthlyPatternsChartData$: Observable<MonthlyPatternsChartData> = this.monthlyPatternsChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing monthly patterns stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateMonthlyPatternsStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: MonthlyPattern[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
const labels = stats.map(s => s.month);
|
||||
|
||||
const datasets = [
|
||||
{
|
||||
label: 'Books Started',
|
||||
data: stats.map(s => s.booksStarted),
|
||||
borderColor: CHART_COLORS.booksStarted,
|
||||
backgroundColor: CHART_COLORS.booksStarted + '20',
|
||||
yAxisID: 'y',
|
||||
tension: 0.3,
|
||||
fill: false,
|
||||
pointStyle: 'circle'
|
||||
},
|
||||
{
|
||||
label: 'Books Finished',
|
||||
data: stats.map(s => s.booksFinished),
|
||||
borderColor: CHART_COLORS.booksFinished,
|
||||
backgroundColor: CHART_COLORS.booksFinished + '20',
|
||||
yAxisID: 'y',
|
||||
tension: 0.3,
|
||||
fill: false,
|
||||
pointStyle: 'triangle'
|
||||
},
|
||||
{
|
||||
label: 'Books Added',
|
||||
data: stats.map(s => s.booksAdded),
|
||||
borderColor: CHART_COLORS.booksAdded,
|
||||
backgroundColor: CHART_COLORS.booksAdded + '20',
|
||||
yAxisID: 'y',
|
||||
tension: 0.3,
|
||||
fill: false,
|
||||
pointStyle: 'rect',
|
||||
borderDash: [3, 3]
|
||||
},
|
||||
{
|
||||
label: 'Avg Progress %',
|
||||
data: stats.map(s => s.averageProgress),
|
||||
borderColor: CHART_COLORS.averageProgress,
|
||||
backgroundColor: CHART_COLORS.averageProgress + '20',
|
||||
yAxisID: 'y1',
|
||||
tension: 0.3,
|
||||
fill: true,
|
||||
fillOpacity: 0.1,
|
||||
pointStyle: 'star'
|
||||
},
|
||||
{
|
||||
label: 'Genre Diversity',
|
||||
data: stats.map(s => s.genreDiversity),
|
||||
borderColor: CHART_COLORS.genreDiversity,
|
||||
backgroundColor: CHART_COLORS.genreDiversity + '20',
|
||||
yAxisID: 'y',
|
||||
tension: 0.3,
|
||||
fill: false,
|
||||
pointStyle: 'cross',
|
||||
borderDash: [5, 2, 2, 2]
|
||||
}
|
||||
];
|
||||
|
||||
this.monthlyPatternsChartDataSubject.next({
|
||||
labels,
|
||||
datasets
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating monthly patterns chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateMonthlyPatternsStats(): MonthlyPattern[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId));
|
||||
return this.processMonthlyPatternsStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
|
||||
return selectedLibraryId && selectedLibraryId !== 'null'
|
||||
? books.filter(book => String(book.libraryId) === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processMonthlyPatternsStats(books: Book[]): MonthlyPattern[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Generate last 12 months
|
||||
const monthlyPatterns: MonthlyPattern[] = [];
|
||||
const currentDate = new Date();
|
||||
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const monthDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
|
||||
const monthKey = this.formatMonthYear(monthDate);
|
||||
const displayMonth = this.formatDisplayMonth(monthKey);
|
||||
|
||||
const pattern = this.calculateMonthlyPattern(books, monthDate, displayMonth);
|
||||
monthlyPatterns.push(pattern);
|
||||
}
|
||||
|
||||
return monthlyPatterns;
|
||||
}
|
||||
|
||||
private calculateMonthlyPattern(books: Book[], monthDate: Date, displayMonth: string): MonthlyPattern {
|
||||
const year = monthDate.getFullYear();
|
||||
const month = monthDate.getMonth();
|
||||
const startOfMonth = new Date(year, month, 1);
|
||||
const endOfMonth = new Date(year, month + 1, 0, 23, 59, 59);
|
||||
|
||||
// Books started this month (estimated by reading status changes)
|
||||
const booksStarted = this.getBooksStartedInMonth(books, startOfMonth, endOfMonth);
|
||||
|
||||
// Books finished this month
|
||||
const booksFinished = books.filter(book => {
|
||||
if (!book.dateFinished) return false;
|
||||
const finishDate = new Date(book.dateFinished);
|
||||
return finishDate >= startOfMonth && finishDate <= endOfMonth;
|
||||
}).length;
|
||||
|
||||
// Books added this month
|
||||
const booksAdded = books.filter(book => {
|
||||
if (!book.addedOn) return false;
|
||||
const addedDate = new Date(book.addedOn);
|
||||
return addedDate >= startOfMonth && addedDate <= endOfMonth;
|
||||
}).length;
|
||||
|
||||
// Average progress of books being read
|
||||
const averageProgress = this.calculateAverageProgress(books, endOfMonth);
|
||||
|
||||
// Estimated total reading time (placeholder calculation)
|
||||
const totalReadingTime = this.estimateMonthlyReadingTime(books, startOfMonth, endOfMonth);
|
||||
|
||||
// Genre diversity (unique categories being read)
|
||||
const genreDiversity = this.calculateGenreDiversity(books, startOfMonth, endOfMonth);
|
||||
|
||||
return {
|
||||
month: displayMonth,
|
||||
booksStarted,
|
||||
booksFinished,
|
||||
booksAdded,
|
||||
averageProgress,
|
||||
totalReadingTime,
|
||||
genreDiversity
|
||||
};
|
||||
}
|
||||
|
||||
private getBooksStartedInMonth(books: Book[], startOfMonth: Date, endOfMonth: Date): number {
|
||||
// Estimate books started by looking at currently reading books and their last read time
|
||||
return books.filter(book => {
|
||||
if (book.readStatus !== ReadStatus.READING && book.readStatus !== ReadStatus.PARTIALLY_READ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (book.lastReadTime) {
|
||||
const lastReadDate = new Date(book.lastReadTime);
|
||||
return lastReadDate >= startOfMonth && lastReadDate <= endOfMonth;
|
||||
}
|
||||
|
||||
// Fallback: if added this month and currently reading, assume started this month
|
||||
if (book.addedOn) {
|
||||
const addedDate = new Date(book.addedOn);
|
||||
return addedDate >= startOfMonth && addedDate <= endOfMonth;
|
||||
}
|
||||
|
||||
return false;
|
||||
}).length;
|
||||
}
|
||||
|
||||
private calculateAverageProgress(books: Book[], asOfDate: Date): number {
|
||||
const booksInProgress = books.filter(book =>
|
||||
book.readStatus === ReadStatus.READING ||
|
||||
book.readStatus === ReadStatus.PARTIALLY_READ
|
||||
);
|
||||
|
||||
if (booksInProgress.length === 0) return 0;
|
||||
|
||||
const totalProgress = booksInProgress.reduce((sum, book) => {
|
||||
const progress = this.getBookProgress(book);
|
||||
return sum + progress;
|
||||
}, 0);
|
||||
|
||||
return Math.round(totalProgress / booksInProgress.length);
|
||||
}
|
||||
|
||||
private getBookProgress(book: Book): number {
|
||||
const epubProgress = book.epubProgress?.percentage || 0;
|
||||
const pdfProgress = book.pdfProgress?.percentage || 0;
|
||||
const cbxProgress = book.cbxProgress?.percentage || 0;
|
||||
const koreaderProgress = book.koreaderProgress?.percentage || 0;
|
||||
|
||||
return Math.max(epubProgress, pdfProgress, cbxProgress, koreaderProgress);
|
||||
}
|
||||
|
||||
private estimateMonthlyReadingTime(books: Book[], startOfMonth: Date, endOfMonth: Date): number {
|
||||
// Simplified estimation based on completed books and their page counts
|
||||
const booksFinishedThisMonth = books.filter(book => {
|
||||
if (!book.dateFinished) return false;
|
||||
const finishDate = new Date(book.dateFinished);
|
||||
return finishDate >= startOfMonth && finishDate <= endOfMonth;
|
||||
});
|
||||
|
||||
const totalPages = booksFinishedThisMonth.reduce((sum, book) =>
|
||||
sum + (book.metadata?.pageCount || 0), 0
|
||||
);
|
||||
|
||||
// Assume 1 page per minute reading speed
|
||||
return Math.round(totalPages);
|
||||
}
|
||||
|
||||
private calculateGenreDiversity(books: Book[], startOfMonth: Date, endOfMonth: Date): number {
|
||||
const relevantBooks = books.filter(book => {
|
||||
// Books finished, started, or being read during this month
|
||||
const wasFinished = book.dateFinished &&
|
||||
new Date(book.dateFinished) >= startOfMonth &&
|
||||
new Date(book.dateFinished) <= endOfMonth;
|
||||
|
||||
const isReading = book.readStatus === ReadStatus.READING ||
|
||||
book.readStatus === ReadStatus.PARTIALLY_READ;
|
||||
|
||||
return wasFinished || isReading;
|
||||
});
|
||||
|
||||
const uniqueGenres = new Set<string>();
|
||||
|
||||
relevantBooks.forEach(book => {
|
||||
if (book.metadata?.categories) {
|
||||
book.metadata.categories.forEach(category => {
|
||||
uniqueGenres.add(category.toLowerCase());
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return uniqueGenres.size;
|
||||
}
|
||||
|
||||
private formatMonthYear(date: Date): string {
|
||||
return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0');
|
||||
}
|
||||
|
||||
private formatDisplayMonth(monthKey: string): string {
|
||||
const [year, month] = monthKey.split('-');
|
||||
const monthNames = [
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
|
||||
];
|
||||
return `${monthNames[parseInt(month) - 1]} ${year}`;
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const datasetLabel = context.dataset.label;
|
||||
const value = context.parsed.y;
|
||||
const dataIndex = context.dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
|
||||
if (!stats || dataIndex >= stats.length) {
|
||||
return `${datasetLabel}: ${value}`;
|
||||
}
|
||||
|
||||
const monthStats = stats[dataIndex];
|
||||
|
||||
switch (datasetLabel) {
|
||||
case 'Books Started':
|
||||
return `${value} books started | ${monthStats.genreDiversity} genres explored`;
|
||||
case 'Books Finished':
|
||||
return `${value} books completed | ${monthStats.totalReadingTime} est. minutes read`;
|
||||
case 'Books Added':
|
||||
return `${value} books added to library`;
|
||||
case 'Avg Progress %':
|
||||
return `${value}% average progress on current reads`;
|
||||
case 'Genre Diversity':
|
||||
return `${value} unique genres being read`;
|
||||
default:
|
||||
return `${datasetLabel}: ${value}`;
|
||||
}
|
||||
}
|
||||
|
||||
private lastCalculatedStats: MonthlyPattern[] = [];
|
||||
|
||||
private getLastCalculatedStats(): MonthlyPattern[] {
|
||||
return this.lastCalculatedStats;
|
||||
}
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, ChartType} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface PageCountStats {
|
||||
category: string;
|
||||
count: number;
|
||||
avgPages: number;
|
||||
minPages: number;
|
||||
maxPages: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#81C784', '#4FC3F7', '#FFB74D', '#F06292', '#BA68C8'
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
hoverBorderWidth: 2,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type PageCountChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class PageCountChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly pageCountChartType: ChartType = 'bar';
|
||||
|
||||
public readonly pageCountChartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => context[0].label,
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
return `${value} book${value === 1 ? '' : 's'}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
maxRotation: 45
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Page Count Category',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.05)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly pageCountChartDataSubject = new BehaviorSubject<PageCountChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books by Page Count',
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly pageCountChartData$: Observable<PageCountChartData> =
|
||||
this.pageCountChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing page count stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculatePageCountStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: PageCountStats[]): void {
|
||||
try {
|
||||
const labels = stats.map(s => s.category);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
|
||||
this.pageCountChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'Books by Page Count',
|
||||
data: dataValues,
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculatePageCountStats(): PageCountStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
return this.processPageCountStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processPageCountStats(books: Book[]): PageCountStats[] {
|
||||
const categories = [
|
||||
{name: 'Short (< 200)', min: 0, max: 199},
|
||||
{name: 'Medium (200-400)', min: 200, max: 400},
|
||||
{name: 'Long (401-600)', min: 401, max: 600},
|
||||
{name: 'Very Long (601-800)', min: 601, max: 800},
|
||||
{name: 'Epic (> 800)', min: 801, max: 9999}
|
||||
];
|
||||
|
||||
return categories.map(category => {
|
||||
const booksInCategory = books.filter(book => {
|
||||
const pageCount = book.metadata?.pageCount;
|
||||
return pageCount && pageCount >= category.min && pageCount <= category.max;
|
||||
});
|
||||
|
||||
const pageCounts = booksInCategory
|
||||
.map(book => book.metadata?.pageCount || 0)
|
||||
.filter(count => count > 0);
|
||||
|
||||
return {
|
||||
category: category.name,
|
||||
count: booksInCategory.length,
|
||||
avgPages: pageCounts.length > 0 ? Math.round(pageCounts.reduce((a, b) => a + b, 0) / pageCounts.length) : 0,
|
||||
minPages: pageCounts.length > 0 ? Math.min(...pageCounts) : 0,
|
||||
maxPages: pageCounts.length > 0 ? Math.max(...pageCounts) : 0
|
||||
};
|
||||
}).filter(stat => stat.count > 0);
|
||||
}
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, ChartType, TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface PublicationYearStats {
|
||||
year: string;
|
||||
count: number;
|
||||
decade: string;
|
||||
}
|
||||
|
||||
const CHART_COLORS = {
|
||||
primary: '#4ECDC4',
|
||||
primaryBackground: 'rgba(78, 205, 196, 0.1)',
|
||||
border: '#ffffff'
|
||||
} as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: CHART_COLORS.primary,
|
||||
backgroundColor: CHART_COLORS.primaryBackground,
|
||||
borderWidth: 2,
|
||||
pointBackgroundColor: CHART_COLORS.primary,
|
||||
pointBorderColor: CHART_COLORS.border,
|
||||
pointBorderWidth: 2,
|
||||
pointRadius: 4,
|
||||
pointHoverRadius: 6,
|
||||
fill: true,
|
||||
tension: 0.4
|
||||
} as const;
|
||||
|
||||
type YearChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class PublicationYearChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly yearChartType = 'line' as const;
|
||||
|
||||
public readonly yearChartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
position: 'nearest',
|
||||
callbacks: {
|
||||
title: (context) => `Year ${context[0].label}`,
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: true,
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
size: 10,
|
||||
weight: 'bold'
|
||||
},
|
||||
align: 'top',
|
||||
offset: 8,
|
||||
formatter: (value: number) => value.toString()
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
maxRotation: 45,
|
||||
callback: function (value, index, values) {
|
||||
// Show every 5th year to avoid crowding
|
||||
return index % 5 === 0 ? this.getLabelForValue(value as number) : '';
|
||||
}
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Publication Year',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.05)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly yearChartDataSubject = new BehaviorSubject<YearChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books Published',
|
||||
data: [],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly yearChartData$: Observable<YearChartData> =
|
||||
this.yearChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing publication year stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculatePublicationYearStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: PublicationYearStats[]): void {
|
||||
try {
|
||||
const labels = stats.map(s => s.year);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
|
||||
this.yearChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'Books Published',
|
||||
data: dataValues,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculatePublicationYearStats(): PublicationYearStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
return this.processPublicationYearStats(filteredBooks);
|
||||
}
|
||||
|
||||
public updateFromStats(stats: PublicationYearStats[]): void {
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processPublicationYearStats(books: Book[]): PublicationYearStats[] {
|
||||
const yearMap = new Map<string, number>();
|
||||
|
||||
books.forEach(book => {
|
||||
if (book.metadata?.publishedDate) {
|
||||
const year = this.extractYear(book.metadata.publishedDate);
|
||||
if (year && year >= 1800 && year <= new Date().getFullYear()) {
|
||||
const yearStr = year.toString();
|
||||
yearMap.set(yearStr, (yearMap.get(yearStr) || 0) + 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Only return years that have books (no 0 entries)
|
||||
return Array.from(yearMap.entries())
|
||||
.filter(([year, count]) => count > 0)
|
||||
.map(([year, count]) => ({
|
||||
year,
|
||||
count,
|
||||
decade: `${Math.floor(parseInt(year) / 10) * 10}s`
|
||||
}))
|
||||
.sort((a, b) => parseInt(a.year) - parseInt(b.year));
|
||||
}
|
||||
|
||||
private extractYear(dateString: string): number | null {
|
||||
const yearMatch = dateString.match(/(\d{4})/);
|
||||
return yearMatch ? parseInt(yearMatch[1]) : null;
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const value = context.parsed.y;
|
||||
return `${value} book${value === 1 ? '' : 's'} published`;
|
||||
}
|
||||
}
|
||||
@@ -1,299 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, map, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
import {ChartConfiguration, ChartData, TooltipItem} from 'chart.js';
|
||||
|
||||
interface CompletionStats {
|
||||
category: string;
|
||||
readStatusCounts: Record<ReadStatus, number>;
|
||||
total: number;
|
||||
}
|
||||
|
||||
const READ_STATUS_COLORS: Record<ReadStatus, string> = {
|
||||
[ReadStatus.READ]: '#2ecc71',
|
||||
[ReadStatus.READING]: '#f39c12',
|
||||
[ReadStatus.RE_READING]: '#9b59b6',
|
||||
[ReadStatus.PARTIALLY_READ]: '#e67e22',
|
||||
[ReadStatus.PAUSED]: '#34495e',
|
||||
[ReadStatus.UNREAD]: '#4169e1',
|
||||
[ReadStatus.WONT_READ]: '#95a5a6',
|
||||
[ReadStatus.ABANDONED]: '#e74c3c',
|
||||
[ReadStatus.UNSET]: '#3498db'
|
||||
};
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
hoverBorderWidth: 1,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type CompletionChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReadingCompletionChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly completionChartType = 'bar' as const;
|
||||
|
||||
public readonly completionChartOptions: ChartConfiguration<'bar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
x: {
|
||||
stacked: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {size: 10},
|
||||
maxRotation: 45,
|
||||
minRotation: 0
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Categories',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
}
|
||||
},
|
||||
y: {
|
||||
stacked: true,
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
stepSize: 1,
|
||||
maxTicksLimit: 25
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.05)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
},
|
||||
padding: 15,
|
||||
boxWidth: 12
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const dataIndex = context[0].dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
return stats[dataIndex]?.category || 'Unknown Category';
|
||||
},
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'index'
|
||||
}
|
||||
};
|
||||
|
||||
private readonly completionChartDataSubject = new BehaviorSubject<CompletionChartData>({
|
||||
labels: [],
|
||||
datasets: Object.values(ReadStatus).map(status => ({
|
||||
label: this.formatReadStatusLabel(status),
|
||||
data: [],
|
||||
backgroundColor: READ_STATUS_COLORS[status],
|
||||
...CHART_DEFAULTS
|
||||
}))
|
||||
});
|
||||
|
||||
public readonly completionChartData$: Observable<CompletionChartData> =
|
||||
this.completionChartDataSubject.asObservable();
|
||||
|
||||
private lastCalculatedStats: CompletionStats[] = [];
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing completion stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateCompletionStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: CompletionStats[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
const topCategories = stats
|
||||
.sort((a, b) => b.total - a.total)
|
||||
.slice(0, 25);
|
||||
|
||||
const labels = topCategories.map(s => {
|
||||
return s.category.length > 20
|
||||
? s.category.substring(0, 15) + '..'
|
||||
: s.category;
|
||||
});
|
||||
|
||||
const datasets = Object.values(ReadStatus).map(status => ({
|
||||
label: this.formatReadStatusLabel(status),
|
||||
data: topCategories.map(s => s.readStatusCounts[status] || 0),
|
||||
backgroundColor: READ_STATUS_COLORS[status],
|
||||
...CHART_DEFAULTS
|
||||
}));
|
||||
|
||||
this.completionChartDataSubject.next({
|
||||
labels,
|
||||
datasets
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating completion chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateCompletionStats(): CompletionStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
return this.processCompletionStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processCompletionStats(books: Book[]): CompletionStats[] {
|
||||
const categoryMap = new Map<string, {
|
||||
readStatusCounts: Record<ReadStatus, number>;
|
||||
}>();
|
||||
|
||||
books.forEach(book => {
|
||||
const categories = book.metadata?.categories || ['Uncategorized'];
|
||||
|
||||
categories.forEach(category => {
|
||||
if (!categoryMap.has(category)) {
|
||||
categoryMap.set(category, {
|
||||
readStatusCounts: Object.values(ReadStatus).reduce((acc, status) => {
|
||||
acc[status] = 0;
|
||||
return acc;
|
||||
}, {} as Record<ReadStatus, number>)
|
||||
});
|
||||
}
|
||||
|
||||
const stats = categoryMap.get(category)!;
|
||||
const rawStatus = book.readStatus;
|
||||
const readStatus: ReadStatus = Object.values(ReadStatus).includes(rawStatus as ReadStatus)
|
||||
? (rawStatus as ReadStatus)
|
||||
: ReadStatus.UNSET;
|
||||
stats.readStatusCounts[readStatus]++;
|
||||
});
|
||||
});
|
||||
|
||||
return Array.from(categoryMap.entries()).map(([category, stats]) => {
|
||||
const total = Object.values(stats.readStatusCounts).reduce((sum, count) => sum + count, 0);
|
||||
return {
|
||||
category,
|
||||
readStatusCounts: stats.readStatusCounts,
|
||||
total
|
||||
};
|
||||
}).filter(stat => stat.total > 0);
|
||||
}
|
||||
|
||||
private formatReadStatusLabel(status: ReadStatus): string {
|
||||
return status.split('_').map(word =>
|
||||
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
|
||||
).join(' ');
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<'bar'>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
|
||||
if (!stats || dataIndex >= stats.length) {
|
||||
return `${context.parsed.y} books`;
|
||||
}
|
||||
|
||||
const category = stats[dataIndex];
|
||||
const value = context.parsed.y;
|
||||
const datasetLabel = context.dataset.label;
|
||||
|
||||
return `${datasetLabel}: ${value}`;
|
||||
}
|
||||
|
||||
private getLastCalculatedStats(): CompletionStats[] {
|
||||
return this.lastCalculatedStats;
|
||||
}
|
||||
}
|
||||
-397
@@ -1,397 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface VelocityTimelineData {
|
||||
month: string;
|
||||
booksCompleted: number;
|
||||
totalPages: number;
|
||||
averagePages: number;
|
||||
averageRating: number;
|
||||
avgPagesPerDay: number;
|
||||
readingVelocity: number; // Books per month
|
||||
}
|
||||
|
||||
const CHART_COLORS = {
|
||||
booksCompleted: '#3498db',
|
||||
avgPagesPerDay: '#e74c3c',
|
||||
averageRating: '#f39c12',
|
||||
readingVelocity: '#2ecc71'
|
||||
} as const;
|
||||
|
||||
type VelocityTimelineChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReadingVelocityTimelineChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly velocityTimelineChartType = 'line' as const;
|
||||
|
||||
public readonly velocityTimelineChartOptions: ChartConfiguration<'line'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
x: {
|
||||
type: 'category',
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
maxRotation: 45
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Month',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'left',
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Books Completed',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y1: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'right',
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
drawOnChartArea: false
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Pages per Day',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
padding: 15,
|
||||
usePointStyle: true
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: { size: 14, weight: 'bold' },
|
||||
bodyFont: { size: 12 },
|
||||
callbacks: {
|
||||
title: (context) => context[0]?.label || '',
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'index'
|
||||
},
|
||||
elements: {
|
||||
point: {
|
||||
radius: 4,
|
||||
hoverRadius: 6
|
||||
},
|
||||
line: {
|
||||
tension: 0.2,
|
||||
borderWidth: 2
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly velocityTimelineChartDataSubject = new BehaviorSubject<VelocityTimelineChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly velocityTimelineChartData$: Observable<VelocityTimelineChartData> = this.velocityTimelineChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing velocity timeline stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateVelocityTimelineStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: VelocityTimelineData[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
const labels = stats.map(s => s.month);
|
||||
|
||||
const datasets = [
|
||||
{
|
||||
label: 'Books Completed',
|
||||
data: stats.map(s => s.booksCompleted),
|
||||
borderColor: CHART_COLORS.booksCompleted,
|
||||
backgroundColor: CHART_COLORS.booksCompleted + '20',
|
||||
yAxisID: 'y',
|
||||
tension: 0.2,
|
||||
fill: false
|
||||
},
|
||||
{
|
||||
label: 'Avg Pages/Day',
|
||||
data: stats.map(s => s.avgPagesPerDay),
|
||||
borderColor: CHART_COLORS.avgPagesPerDay,
|
||||
backgroundColor: CHART_COLORS.avgPagesPerDay + '20',
|
||||
yAxisID: 'y1',
|
||||
tension: 0.2,
|
||||
fill: false
|
||||
},
|
||||
{
|
||||
label: 'Avg Rating (×2)',
|
||||
data: stats.map(s => s.averageRating * 2), // Scale for visibility
|
||||
borderColor: CHART_COLORS.averageRating,
|
||||
backgroundColor: CHART_COLORS.averageRating + '20',
|
||||
yAxisID: 'y',
|
||||
tension: 0.2,
|
||||
fill: false,
|
||||
borderDash: [5, 5]
|
||||
},
|
||||
{
|
||||
label: 'Reading Velocity',
|
||||
data: stats.map(s => s.readingVelocity),
|
||||
borderColor: CHART_COLORS.readingVelocity,
|
||||
backgroundColor: CHART_COLORS.readingVelocity + '20',
|
||||
yAxisID: 'y',
|
||||
tension: 0.2,
|
||||
fill: true,
|
||||
fillOpacity: 0.1
|
||||
}
|
||||
];
|
||||
|
||||
this.velocityTimelineChartDataSubject.next({
|
||||
labels,
|
||||
datasets
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating velocity timeline chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateVelocityTimelineStats(): VelocityTimelineData[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId));
|
||||
return this.processVelocityTimelineStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
|
||||
return selectedLibraryId && selectedLibraryId !== 'null'
|
||||
? books.filter(book => String(book.libraryId) === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processVelocityTimelineStats(books: Book[]): VelocityTimelineData[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Filter completed books with finish dates
|
||||
const completedBooks = books.filter(book =>
|
||||
book.readStatus === ReadStatus.READ &&
|
||||
book.dateFinished
|
||||
);
|
||||
|
||||
if (completedBooks.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Group books by month-year
|
||||
const monthlyData = new Map<string, Book[]>();
|
||||
|
||||
for (const book of completedBooks) {
|
||||
const finishDate = new Date(book.dateFinished!);
|
||||
if (isNaN(finishDate.getTime())) continue;
|
||||
|
||||
const monthKey = this.formatMonthYear(finishDate);
|
||||
if (!monthlyData.has(monthKey)) {
|
||||
monthlyData.set(monthKey, []);
|
||||
}
|
||||
monthlyData.get(monthKey)!.push(book);
|
||||
}
|
||||
|
||||
// Convert to timeline data and sort chronologically
|
||||
const timelineData = Array.from(monthlyData.entries())
|
||||
.map(([monthKey, monthBooks]) => this.calculateMonthlyMetrics(monthKey, monthBooks))
|
||||
.sort((a, b) => new Date(a.month + '-01').getTime() - new Date(b.month + '-01').getTime())
|
||||
.slice(-24); // Last 24 months
|
||||
|
||||
return timelineData;
|
||||
}
|
||||
|
||||
private formatMonthYear(date: Date): string {
|
||||
return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0');
|
||||
}
|
||||
|
||||
private calculateMonthlyMetrics(monthKey: string, books: Book[]): VelocityTimelineData {
|
||||
const totalPages = books.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0);
|
||||
const averagePages = books.length > 0 ? Math.round(totalPages / books.length) : 0;
|
||||
|
||||
// Calculate average rating
|
||||
const ratedBooks = books.filter(book => book.personalRating || book.metadata?.goodreadsRating);
|
||||
const totalRating = ratedBooks.reduce((sum, book) => {
|
||||
const rating = book.personalRating || book.metadata?.goodreadsRating || 0;
|
||||
return sum + rating;
|
||||
}, 0);
|
||||
const averageRating = ratedBooks.length > 0 ? Number((totalRating / ratedBooks.length).toFixed(1)) : 0;
|
||||
|
||||
// Calculate days in month for pages per day calculation
|
||||
const [year, month] = monthKey.split('-').map(Number);
|
||||
const daysInMonth = new Date(year, month, 0).getDate();
|
||||
const avgPagesPerDay = Math.round(totalPages / daysInMonth);
|
||||
|
||||
// Reading velocity is books per month
|
||||
const readingVelocity = books.length;
|
||||
|
||||
return {
|
||||
month: this.formatDisplayMonth(monthKey),
|
||||
booksCompleted: books.length,
|
||||
totalPages,
|
||||
averagePages,
|
||||
averageRating,
|
||||
avgPagesPerDay,
|
||||
readingVelocity
|
||||
};
|
||||
}
|
||||
|
||||
private formatDisplayMonth(monthKey: string): string {
|
||||
const [year, month] = monthKey.split('-');
|
||||
const monthNames = [
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
|
||||
];
|
||||
return `${monthNames[parseInt(month) - 1]} ${year}`;
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<'line'>): string {
|
||||
const datasetLabel = context.dataset.label;
|
||||
const value = context.parsed.y;
|
||||
const dataIndex = context.dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
|
||||
if (!stats || dataIndex >= stats.length) {
|
||||
return `${datasetLabel}: ${value}`;
|
||||
}
|
||||
|
||||
const monthStats = stats[dataIndex];
|
||||
|
||||
switch (datasetLabel) {
|
||||
case 'Books Completed':
|
||||
return `${value} books completed | ${monthStats.totalPages} total pages`;
|
||||
case 'Avg Pages/Day':
|
||||
return `${value} pages/day | ${monthStats.averagePages} avg pages/book`;
|
||||
case 'Avg Rating (×2)':
|
||||
const actualRating = (value ?? 0) / 2;
|
||||
return `${actualRating.toFixed(1)}/5 avg rating | ${monthStats.booksCompleted} books rated`;
|
||||
case 'Reading Velocity':
|
||||
return `${value} books/month | ${monthStats.avgPagesPerDay} pages/day velocity`;
|
||||
default:
|
||||
return `${datasetLabel}: ${value}`;
|
||||
}
|
||||
}
|
||||
|
||||
private lastCalculatedStats: VelocityTimelineData[] = [];
|
||||
|
||||
private getLastCalculatedStats(): VelocityTimelineData[] {
|
||||
return this.lastCalculatedStats;
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, ChartType} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface CategoryStats {
|
||||
category: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57',
|
||||
'#FF9FF3', '#54A0FF', '#5F27CD', '#00D2D3', '#FF9F43',
|
||||
'#FF6348', '#2ED573', '#3742FA', '#F368E0', '#FF3838',
|
||||
'#FF4757', '#5352ED', '#70A1FF', '#7F8FA6', '#40407A',
|
||||
'#2C2C54', '#40407A', '#706FD3', '#F97F51', '#F8B500'
|
||||
] as const;
|
||||
|
||||
const HOVER_COLORS = [
|
||||
'#FF5252', '#26A69A', '#2196F3', '#66BB6A', '#FFB74D',
|
||||
'#E91E63', '#3F51B5', '#9C27B0', '#00BCD4', '#FF9800',
|
||||
'#F44336', '#4CAF50', '#2196F3', '#E91E63', '#FF5722',
|
||||
'#FF4081', '#3F51B5', '#5C6BC0', '#607D8B', '#303F9F',
|
||||
'#1A237E', '#303F9F', '#5E35B1', '#FF6F00', '#E65100'
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
hoverBorderColor: '#ffffff',
|
||||
hoverBorderWidth: 2
|
||||
} as const;
|
||||
|
||||
type CategoriesChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class TopCategoriesChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly categoriesChartType: ChartType = 'bar';
|
||||
|
||||
public readonly categoriesChartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
indexAxis: 'y',
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.8)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#666666',
|
||||
borderWidth: 1,
|
||||
callbacks: {
|
||||
title: () => '',
|
||||
label: (context) => {
|
||||
const label = context.label || '';
|
||||
const value = context.parsed.x;
|
||||
return `${label}: ${value} books`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
size: 12
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
size: 14,
|
||||
weight: 'bold'
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
size: 11
|
||||
},
|
||||
maxRotation: 0,
|
||||
callback: function (value, index) {
|
||||
const label = this.getLabelForValue(value as number);
|
||||
return label.length > 25 ? label.substring(0, 25) + '...' : label;
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.05)'
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly categoriesChartDataSubject = new BehaviorSubject<CategoriesChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books',
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
hoverBackgroundColor: [...HOVER_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly categoriesChartData$: Observable<CategoriesChartData> =
|
||||
this.categoriesChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.initializeChartDataSubscription();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private initializeChartDataSubscription(): void {
|
||||
this.getCategoryStats()
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error processing category stats:', error);
|
||||
return [];
|
||||
})
|
||||
)
|
||||
.subscribe((stats) => this.updateChartData(stats));
|
||||
}
|
||||
|
||||
private updateChartData(stats: CategoryStats[]): void {
|
||||
try {
|
||||
const reversedStats = [...stats].reverse();
|
||||
const labels = reversedStats.map(s => s.category);
|
||||
const dataValues = reversedStats.map(s => s.count);
|
||||
|
||||
this.categoriesChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'Books',
|
||||
data: dataValues,
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
hoverBackgroundColor: [...HOVER_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
public getCategoryStats(): Observable<CategoryStats[]> {
|
||||
return combineLatest([
|
||||
this.bookService.bookState$,
|
||||
this.libraryFilterService.selectedLibrary$
|
||||
]).pipe(
|
||||
map(([state, selectedLibraryId]) => {
|
||||
if (!this.isValidBookState(state)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(state.books!, selectedLibraryId);
|
||||
return this.processCategoryStats(filteredBooks);
|
||||
}),
|
||||
catchError((error) => {
|
||||
console.error('Error getting category stats:', error);
|
||||
return [];
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public updateFromStats(stats: CategoryStats[]): void {
|
||||
this.updateChartData(stats);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processCategoryStats(books: Book[]): CategoryStats[] {
|
||||
const categoryMap = new Map<string, number>();
|
||||
|
||||
books.forEach(book => {
|
||||
if (book.metadata?.categories && Array.isArray(book.metadata.categories)) {
|
||||
book.metadata.categories.forEach(category => {
|
||||
if (category) {
|
||||
categoryMap.set(category, (categoryMap.get(category) || 0) + 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(categoryMap.entries())
|
||||
.map(([category, count]) => ({category, count}))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 15);
|
||||
}
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, TooltipItem} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {BookState} from '../../book/model/state/book-state.model';
|
||||
|
||||
interface SeriesStats {
|
||||
seriesName: string;
|
||||
bookCount: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#4e79a7', '#f28e2c', '#e15759', '#76b7b2',
|
||||
'#59a14f', '#edc949', '#af7aa1', '#ff9da7',
|
||||
'#9c755f', '#bab0ab', '#5778a4', '#e69138',
|
||||
'#d62728', '#6aa7b8', '#54a24b', '#fdd247',
|
||||
'#b07aa1', '#ff9d9a', '#9e6762', '#c9b2d6'
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderWidth: 1,
|
||||
hoverBorderWidth: 2,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type SeriesChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class TopSeriesChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly seriesChartType = 'bar' as const;
|
||||
|
||||
public readonly seriesChartOptions: ChartConfiguration<'bar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
indexAxis: 'y',
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
precision: 0
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
maxTicksLimit: 20
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.05)'
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const dataIndex = context[0].dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
return stats[dataIndex]?.seriesName || 'Unknown Series';
|
||||
},
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: true,
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
size: 10,
|
||||
family: "'Inter', sans-serif",
|
||||
weight: 'bold'
|
||||
},
|
||||
align: 'center',
|
||||
offset: 8,
|
||||
formatter: (value: number) => value.toString()
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
}
|
||||
};
|
||||
|
||||
private readonly seriesChartDataSubject = new BehaviorSubject<SeriesChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly seriesChartData$: Observable<SeriesChartData> = this.seriesChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing top series stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateTopSeriesStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: SeriesStats[]): void {
|
||||
try {
|
||||
this.lastCalculatedStats = stats;
|
||||
const labels = stats.map(s => this.truncateTitle(s.seriesName, 30));
|
||||
const dataValues = stats.map(s => s.bookCount);
|
||||
const colors = this.getColorsForData(stats.length);
|
||||
|
||||
this.seriesChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'Books',
|
||||
data: dataValues,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating series chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateTopSeriesStats(): SeriesStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId));
|
||||
return this.processTopSeriesStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
|
||||
return selectedLibraryId && selectedLibraryId !== 'null'
|
||||
? books.filter(book => String(book.libraryId) === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processTopSeriesStats(books: Book[]): SeriesStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const seriesMap = this.buildSeriesMap(books);
|
||||
return this.convertMapToStats(seriesMap);
|
||||
}
|
||||
|
||||
private buildSeriesMap(books: Book[]): Map<string, number> {
|
||||
const seriesMap = new Map<string, number>();
|
||||
|
||||
for (const book of books) {
|
||||
const seriesName = book.metadata?.seriesName;
|
||||
if (seriesName && seriesName.trim()) {
|
||||
const normalizedName = seriesName.trim();
|
||||
seriesMap.set(normalizedName, (seriesMap.get(normalizedName) || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return seriesMap;
|
||||
}
|
||||
|
||||
private convertMapToStats(seriesMap: Map<string, number>): SeriesStats[] {
|
||||
return Array.from(seriesMap.entries())
|
||||
.map(([seriesName, bookCount]) => ({
|
||||
seriesName,
|
||||
bookCount
|
||||
}))
|
||||
.sort((a, b) => b.bookCount - a.bookCount)
|
||||
.slice(0, 20);
|
||||
}
|
||||
|
||||
private getColorsForData(dataLength: number): string[] {
|
||||
const colors = [...CHART_COLORS];
|
||||
while (colors.length < dataLength) {
|
||||
colors.push(...CHART_COLORS);
|
||||
}
|
||||
return colors.slice(0, dataLength);
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<'bar'>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const stats = this.getLastCalculatedStats();
|
||||
|
||||
if (!stats || dataIndex >= stats.length) {
|
||||
return `${context.parsed.x} books`;
|
||||
}
|
||||
|
||||
const series = stats[dataIndex];
|
||||
const bookCount = series.bookCount;
|
||||
const bookText = bookCount === 1 ? 'book' : 'books';
|
||||
|
||||
return `${bookCount} ${bookText}`;
|
||||
}
|
||||
|
||||
private lastCalculatedStats: SeriesStats[] = [];
|
||||
|
||||
private getLastCalculatedStats(): SeriesStats[] {
|
||||
return this.lastCalculatedStats;
|
||||
}
|
||||
|
||||
private truncateTitle(title: string, maxLength: number): string {
|
||||
return title.length > maxLength ? title.substring(0, maxLength) + '...' : title;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user