Introduced additional library charts to surface meaningful insights (#2390)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+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>
|
||||
+627
@@ -0,0 +1,627 @@
|
||||
.library-stats-container {
|
||||
max-width: 2500px;
|
||||
margin: 0 auto;
|
||||
background: transparent;
|
||||
height: calc(100dvh - 6.25rem);
|
||||
overflow-y: auto;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.header-card {
|
||||
background: var(--card-background);
|
||||
border-radius: 8px;
|
||||
padding: 25px;
|
||||
margin-bottom: 30px;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.filter-section {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
|
||||
.library-filter {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
|
||||
.select-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
label {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
.library-totals {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
margin-top: 8px;
|
||||
font-size: 0.95rem;
|
||||
color: var(--text-secondary-color);
|
||||
flex-wrap: wrap;
|
||||
|
||||
.total-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
padding: 6px 10px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 1.35rem;
|
||||
color: var(--primary-color, #80bdff);
|
||||
}
|
||||
|
||||
.total-label {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.total-value {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 600;
|
||||
margin-left: 4px;
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
backdrop-filter: blur(4px);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.config-modal {
|
||||
background: var(--surface-card, rgba(30, 30, 30, 0.95));
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
width: 100%;
|
||||
max-width: 800px;
|
||||
max-height: 80vh;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.config-modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 20px 25px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
background: var(--surface-ground, rgba(40, 40, 40, 0.8));
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
font-size: 1.2rem;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
|
||||
.pi {
|
||||
color: var(--primary-color, #80bdff);
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: transparent;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
color: var(--text-color, #ffffff);
|
||||
padding: 8px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 20px 25px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
background: var(--surface-ground, rgba(35, 35, 35, 0.6));
|
||||
|
||||
.config-action-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
color: var(--text-color, #ffffff);
|
||||
padding: 10px 16px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
font-weight: 500;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&.enable-all {
|
||||
background: rgba(34, 197, 94, 0.2);
|
||||
border-color: rgba(34, 197, 94, 0.4);
|
||||
color: #22c55e;
|
||||
|
||||
&:hover {
|
||||
background: rgba(34, 197, 94, 0.3);
|
||||
border-color: rgba(34, 197, 94, 0.6);
|
||||
}
|
||||
}
|
||||
|
||||
&.disable-all {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
border-color: rgba(239, 68, 68, 0.4);
|
||||
color: #ef4444;
|
||||
|
||||
&:hover {
|
||||
background: rgba(239, 68, 68, 0.3);
|
||||
border-color: rgba(239, 68, 68, 0.6);
|
||||
}
|
||||
}
|
||||
|
||||
&.reset-order {
|
||||
background: rgba(251, 191, 36, 0.2);
|
||||
border-color: rgba(251, 191, 36, 0.4);
|
||||
color: #fbbf24;
|
||||
|
||||
&:hover {
|
||||
background: rgba(251, 191, 36, 0.3);
|
||||
border-color: rgba(251, 191, 36, 0.6);
|
||||
}
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px 25px;
|
||||
|
||||
.config-categories {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 25px;
|
||||
|
||||
.config-category {
|
||||
h4 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0 0 15px 0;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 2px solid var(--primary-color, #80bdff);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.chart-toggles {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.chart-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px;
|
||||
border-radius: 6px;
|
||||
transition: background-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
input[type="checkbox"] {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
accent-color: var(--primary-color, #80bdff);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
label {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition: color 0.2s ease;
|
||||
flex: 1;
|
||||
|
||||
&:hover {
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
}
|
||||
|
||||
input[type="checkbox"]:checked + label {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.charts-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 20px;
|
||||
margin-bottom: 30px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.chart-container {
|
||||
position: relative;
|
||||
|
||||
&.cdk-drag {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
&.cdk-drag-animating {
|
||||
transition: transform 300ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
&.cdk-drag-disabled {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
&.cdk-drag-preview {
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
||||
backdrop-filter: blur(15px);
|
||||
border: 2px solid var(--primary-color, #80bdff);
|
||||
border-radius: 8px;
|
||||
transform: rotate(2deg);
|
||||
}
|
||||
|
||||
&.cdk-drag-placeholder {
|
||||
opacity: 0.3;
|
||||
border: 2px dashed var(--primary-color, #80bdff);
|
||||
background: transparent !important;
|
||||
}
|
||||
}
|
||||
|
||||
.cdk-drop-list-dragging .chart-container:not(.cdk-drag-placeholder) {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.drag-handle {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
z-index: 10;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 4px;
|
||||
padding: 6px;
|
||||
cursor: default;
|
||||
opacity: 0;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
border-color: var(--primary-color, #80bdff);
|
||||
}
|
||||
|
||||
&:active {
|
||||
background: rgba(0, 0, 0, 0.9);
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
.pi {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 0.8rem;
|
||||
cursor: grab;
|
||||
|
||||
&:hover {
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-container:hover .drag-handle {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.chart-section {
|
||||
background: var(--card-background);
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
&.small {
|
||||
grid-column: span 1;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
&.medium {
|
||||
grid-column: span 1;
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
&.large {
|
||||
grid-column: span 2;
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
&.xlarge {
|
||||
grid-column: 1 / -1;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
&.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
|
||||
.loading-message,
|
||||
.no-data-message {
|
||||
text-align: center;
|
||||
padding: 50px;
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.loading-message {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
color: var(--text-color-secondary, #999999);
|
||||
|
||||
small {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1600px) {
|
||||
.charts-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
|
||||
.chart-section.small {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.chart-section.medium {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.chart-section.large {
|
||||
grid-column: span 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.charts-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
|
||||
.chart-section.small,
|
||||
.chart-section.medium {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.chart-section.large {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.chart-section.xlarge,
|
||||
.chart-section.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.library-stats-container {
|
||||
padding: 15px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.header-card {
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.filter-section {
|
||||
.library-filter {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
|
||||
.select-row {
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
label {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.library-totals {
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal {
|
||||
max-width: 95%;
|
||||
max-height: 85vh;
|
||||
margin: 10px;
|
||||
|
||||
.config-modal-header {
|
||||
padding: 15px 20px;
|
||||
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-actions {
|
||||
padding: 15px 20px;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
.config-action-btn {
|
||||
flex: none;
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-content {
|
||||
padding: 15px 20px;
|
||||
|
||||
.config-categories {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 20px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.charts-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 15px;
|
||||
|
||||
.chart-container {
|
||||
&.small,
|
||||
&.medium,
|
||||
&.large,
|
||||
&.xlarge,
|
||||
&.full-width {
|
||||
grid-column: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.drag-handle {
|
||||
opacity: 1;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
|
||||
.pi {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-section {
|
||||
padding: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.header-card {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.charts-grid {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.config-modal-overlay {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.config-modal {
|
||||
max-width: 100%;
|
||||
max-height: 90vh;
|
||||
|
||||
.config-modal-header {
|
||||
padding: 12px 15px;
|
||||
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.config-modal-actions {
|
||||
padding: 12px 15px;
|
||||
}
|
||||
|
||||
.config-modal-content {
|
||||
padding: 12px 15px;
|
||||
}
|
||||
}
|
||||
|
||||
.drag-handle {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
|
||||
.pi {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+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'}
|
||||
];
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {combineLatest, map, Observable} from 'rxjs';
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class LibrariesSummaryService {
|
||||
private bookService = inject(BookService);
|
||||
private libraryFilterService = inject(LibraryFilterService);
|
||||
|
||||
selectedLibrary$ = this.libraryFilterService.selectedLibrary$;
|
||||
|
||||
getBooksSummary(): Observable<{
|
||||
totalBooks: number;
|
||||
totalSizeKb: number;
|
||||
totalAuthors: number;
|
||||
totalSeries: number;
|
||||
totalPublishers: number;
|
||||
}> {
|
||||
return combineLatest([
|
||||
this.bookService.bookState$,
|
||||
this.selectedLibrary$
|
||||
]).pipe(
|
||||
map(([state, selectedLibraryId]) => {
|
||||
if (!state.loaded || !state.books || state.books.length === 0) {
|
||||
return {totalBooks: 0, totalSizeKb: 0, totalAuthors: 0, totalSeries: 0, totalPublishers: 0};
|
||||
}
|
||||
|
||||
const filteredBooks = selectedLibraryId
|
||||
? state.books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: state.books;
|
||||
|
||||
const totalBooks = filteredBooks.length;
|
||||
const totalSizeKb = filteredBooks.reduce((sum, book) => sum + (book.fileSizeKb || 0), 0);
|
||||
|
||||
const authorSet = new Set<string>();
|
||||
const seriesSet = new Set<string>();
|
||||
const publisherSet = new Set<string>();
|
||||
|
||||
filteredBooks.forEach(book => {
|
||||
if (Array.isArray(book.metadata?.authors)) {
|
||||
book.metadata.authors.forEach(a => {
|
||||
const name = a?.trim();
|
||||
if (name) authorSet.add(name);
|
||||
});
|
||||
}
|
||||
|
||||
const seriesName = book.metadata?.seriesName?.trim();
|
||||
if (seriesName) seriesSet.add(seriesName);
|
||||
|
||||
const publisher = book.metadata?.publisher?.trim();
|
||||
if (publisher) publisherSet.add(publisher);
|
||||
});
|
||||
|
||||
return {
|
||||
totalBooks,
|
||||
totalSizeKb,
|
||||
totalAuthors: authorSet.size,
|
||||
totalSeries: seriesSet.size,
|
||||
totalPublishers: publisherSet.size
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getFormattedSize(): Observable<string> {
|
||||
return this.getBooksSummary().pipe(
|
||||
map(summary => this.formatSizeKb(summary.totalSizeKb))
|
||||
);
|
||||
}
|
||||
|
||||
private formatSizeKb(kb: number): string {
|
||||
if (!kb) return '0 KB';
|
||||
const kilo = 1024;
|
||||
const megaKb = kilo; // 1 MB = 1024 KB
|
||||
const gigaKb = kilo * megaKb; // 1 GB = 1024 * 1024 KB
|
||||
if (kb >= gigaKb) {
|
||||
return (kb / gigaKb).toFixed(2) + ' GB';
|
||||
}
|
||||
if (kb >= megaKb) {
|
||||
return (kb / megaKb).toFixed(2) + ' MB';
|
||||
}
|
||||
return kb + ' KB';
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
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';
|
||||
|
||||
export interface LibraryOption {
|
||||
id: number | null;
|
||||
name: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class LibraryFilterService {
|
||||
private selectedLibrarySubject = new BehaviorSubject<number | null>(null);
|
||||
|
||||
selectedLibrary$ = this.selectedLibrarySubject.asObservable();
|
||||
|
||||
getCurrentSelectedLibrary(): number | null {
|
||||
return this.selectedLibrarySubject.value;
|
||||
}
|
||||
|
||||
setSelectedLibrary(libraryId: number | null): void {
|
||||
this.selectedLibrarySubject.next(libraryId);
|
||||
}
|
||||
|
||||
private bookService = inject(BookService);
|
||||
private libraryService = inject(LibraryService);
|
||||
|
||||
getLibraryOptions(): Observable<LibraryOption[]> {
|
||||
return combineLatest([
|
||||
this.bookService.bookState$,
|
||||
this.libraryService.libraryState$
|
||||
]).pipe(
|
||||
map(([bookState, libraryState]) => {
|
||||
if (!bookState.loaded || !bookState.books || bookState.books.length === 0) {
|
||||
return [{id: null, name: 'All Libraries'}];
|
||||
}
|
||||
|
||||
if (!libraryState.loaded || !libraryState.libraries) {
|
||||
return [{id: null, name: 'All Libraries'}];
|
||||
}
|
||||
|
||||
const libraryMap = new Map<number, string>();
|
||||
bookState.books.forEach(book => {
|
||||
if (!libraryMap.has(book.libraryId)) {
|
||||
const library = libraryState.libraries?.find(lib => lib.id === book.libraryId);
|
||||
const libraryName = library?.name || `Library ${book.libraryId}`;
|
||||
libraryMap.set(book.libraryId, libraryName);
|
||||
}
|
||||
});
|
||||
|
||||
const options: LibraryOption[] = [
|
||||
{id: null, name: 'All Libraries'},
|
||||
...Array.from(libraryMap.entries()).map(([id, name]) => ({id, name}))
|
||||
];
|
||||
|
||||
return options.sort((a, b) => {
|
||||
if (a.id === null) return -1;
|
||||
if (b.id === null) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user