refactor(frontend): rename booklore-ui to frontend
- Frontend path: - rename the tracked Angular app tree from `booklore-ui/` to `frontend/` - preserve file contents during the move so this commit stays focused on the path change itself - Frontend docs: - update the moved frontend README and contribution guide where they refer to the renamed folder - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
// Shared chart styles for consistency across all chart components
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
|
||||
.badge-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 0.75rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 0.9rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
.badge-value {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.authorUniverse'">
|
||||
<div class="author-universe-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-globe author-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
@if (totalAuthors > 0) {
|
||||
<div class="author-count-badge">
|
||||
{{ t('authorsBadge', { count: totalAuthors }) }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalAuthors > 0) {
|
||||
<div class="chart-legend-info">
|
||||
<span class="legend-note">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
{{ t('legendNote') }}
|
||||
</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>{{ t('noData') }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
@use '../../../_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+562
@@ -0,0 +1,562 @@
|
||||
import {Component, effect, inject, OnDestroy} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {Chart, ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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, TranslocoDirective],
|
||||
templateUrl: './author-universe-chart.component.html',
|
||||
styleUrls: ['./author-universe-chart.component.scss']
|
||||
})
|
||||
export class AuthorUniverseChartComponent implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly syncChartEffect = effect(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.calculateAndUpdateChart(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
document.getElementById('author-chart-tooltip')?.remove();
|
||||
}
|
||||
|
||||
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: this.t.translate('statsLibrary.authorUniverse.axisBooks'),
|
||||
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: this.t.translate('statsLibrary.authorUniverse.axisRating'),
|
||||
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: false,
|
||||
external: (context) => this.handleExternalTooltip(context)
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: true,
|
||||
mode: 'nearest'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(books: Book[], selectedLibraryId: number | null): void {
|
||||
if (books.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.totalAuthors = 0;
|
||||
this.topAuthors = [];
|
||||
this.insights = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(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 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: this.t.translate('statsLibrary.authorUniverse.legend75to100'),
|
||||
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: this.t.translate('statsLibrary.authorUniverse.legend50to74'),
|
||||
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: this.t.translate('statsLibrary.authorUniverse.legend25to49'),
|
||||
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: this.t.translate('statsLibrary.authorUniverse.legend1to24'),
|
||||
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: this.t.translate('statsLibrary.authorUniverse.legendUnread'),
|
||||
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(this.t.translate('statsLibrary.authorUniverse.insightMostCollected', {name: mostProlific.name, count: mostProlific.bookCount}));
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightHighestRated', {name: highestRated.name, rating: `${highestRated.avgRating.toFixed(1)}\u2605`}));
|
||||
}
|
||||
|
||||
// Most pages by author
|
||||
const mostPages = authorStats.reduce((a, b) => a.totalPages > b.totalPages ? a : b);
|
||||
if (mostPages.totalPages > 0) {
|
||||
insights.push(this.t.translate('statsLibrary.authorUniverse.insightMostPages', {name: mostPages.name, count: mostPages.totalPages.toLocaleString()}));
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightMostRead', {name: bestCompletion.name, percent: Math.round(bestCompletion.completionRate)}));
|
||||
}
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightHiddenGem', {name: gem.name, rating: `${gem.avgRating.toFixed(1)}\u2605`, count: gem.bookCount}));
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightBiggestBacklog', {name: biggestBacklog.name, count: unreadCount}));
|
||||
}
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightTop3Concentration', {percent: concentration}));
|
||||
}
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightLongestReads', {name: longestReads.name, pages: avgPages}));
|
||||
}
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightMostVersatile', {name: mostVersatile.name, count: mostVersatile.categories.length}));
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightUntouchedAuthor', {name: topUnread.name, count: topUnread.bookCount}));
|
||||
}
|
||||
|
||||
// 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(this.t.translate('statsLibrary.authorUniverse.insightOverallProgress', {percent: overallProgress}));
|
||||
}
|
||||
|
||||
return insights;
|
||||
}
|
||||
|
||||
private handleExternalTooltip(context: { chart: Chart; tooltip: any }): void {
|
||||
const {chart, tooltip} = context;
|
||||
let tooltipEl = document.getElementById('author-chart-tooltip');
|
||||
|
||||
if (!tooltipEl) {
|
||||
tooltipEl = document.createElement('div');
|
||||
tooltipEl.id = 'author-chart-tooltip';
|
||||
Object.assign(tooltipEl.style, {
|
||||
position: 'fixed',
|
||||
zIndex: '9999',
|
||||
background: 'rgba(0, 0, 0, 0.95)',
|
||||
border: '2px solid #8b5cf6',
|
||||
borderRadius: '8px',
|
||||
padding: '12px 16px',
|
||||
pointerEvents: 'none',
|
||||
opacity: '0',
|
||||
transition: 'opacity 0.15s ease',
|
||||
transform: 'translate(-50%, calc(-100% - 12px))',
|
||||
maxWidth: '280px',
|
||||
whiteSpace: 'nowrap',
|
||||
fontFamily: "'Inter', sans-serif"
|
||||
});
|
||||
document.body.appendChild(tooltipEl);
|
||||
}
|
||||
|
||||
if (tooltip.opacity === 0) {
|
||||
tooltipEl.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
|
||||
// Only use the first (nearest) data point
|
||||
const dataPoint = tooltip.dataPoints?.[0];
|
||||
if (!dataPoint) {
|
||||
tooltipEl.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
|
||||
const raw = dataPoint.raw as BubbleDataPoint;
|
||||
const stats = raw.authorStats;
|
||||
|
||||
const ratingText = stats.avgRating > 0
|
||||
? `${stats.avgRating.toFixed(2)} \u2605`
|
||||
: this.t.translate('statsLibrary.authorUniverse.tooltipNoRatings');
|
||||
|
||||
const categoriesHtml = stats.categories.length > 0
|
||||
? `<div style="color:rgba(255,255,255,0.9);font-size:12px;line-height:1.6">${this.t.translate('statsLibrary.authorUniverse.tooltipGenres', {genres: stats.categories.slice(0, 3).join(', ')})}</div>`
|
||||
: '';
|
||||
|
||||
const booksLine = this.t.translate('statsLibrary.authorUniverse.tooltipBooks', {count: stats.bookCount});
|
||||
const pagesLine = this.t.translate('statsLibrary.authorUniverse.tooltipTotalPages', {count: stats.totalPages.toLocaleString()});
|
||||
const ratingLine = this.t.translate('statsLibrary.authorUniverse.tooltipAvgRating', {rating: ratingText});
|
||||
const readLine = this.t.translate('statsLibrary.authorUniverse.tooltipRead', {read: stats.readCount, total: stats.bookCount, percent: Math.round(stats.completionRate)});
|
||||
|
||||
tooltipEl.innerHTML = `
|
||||
<div style="color:#fff;font-size:14px;font-weight:700;margin-bottom:6px">${stats.name}</div>
|
||||
<div style="color:rgba(255,255,255,0.9);font-size:12px;line-height:1.6">${booksLine}</div>
|
||||
<div style="color:rgba(255,255,255,0.9);font-size:12px;line-height:1.6">${pagesLine}</div>
|
||||
<div style="color:rgba(255,255,255,0.9);font-size:12px;line-height:1.6">${ratingLine}</div>
|
||||
<div style="color:rgba(255,255,255,0.9);font-size:12px;line-height:1.6">${readLine}</div>
|
||||
${categoriesHtml}
|
||||
`;
|
||||
|
||||
const canvasRect = chart.canvas.getBoundingClientRect();
|
||||
tooltipEl.style.opacity = '1';
|
||||
tooltipEl.style.left = (canvasRect.left + tooltip.caretX) + 'px';
|
||||
tooltipEl.style.top = (canvasRect.top + tooltip.caretY) + 'px';
|
||||
}
|
||||
|
||||
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})`;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.bookFormats'">
|
||||
<div class="book-formats-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-file formats-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalBooks() > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks() === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@use '../../../_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;
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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, TranslocoDirective],
|
||||
templateUrl: './book-formats-chart.component.html',
|
||||
styleUrls: ['./book-formats-chart.component.scss']
|
||||
})
|
||||
export class BookFormatsChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly filteredBooks = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.filterBooksByLibrary(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
});
|
||||
|
||||
public readonly chartType = 'pie' as const;
|
||||
public readonly formatStats = computed(() => this.calculateFormatStats(this.filteredBooks()));
|
||||
public readonly totalBooks = computed(() => this.filteredBooks().length);
|
||||
|
||||
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 this.t.translate('statsLibrary.bookFormats.tooltipLabel', {label: context.label, value, percentage});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed<FormatChartData>(() => {
|
||||
const stats = this.formatStats();
|
||||
if (stats.length === 0) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const labels = stats.map(s => s.format);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => FORMAT_COLORS[s.format] || '#6B7280');
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 2,
|
||||
hoverBorderColor: '#ffffff',
|
||||
hoverBorderWidth: 3
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
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.primaryFile?.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);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.language'">
|
||||
<div class="language-chart-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-globe language-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (booksWithLanguage() > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (booksWithLanguage() === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@use '../../../_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;
|
||||
}
|
||||
}
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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, TranslocoDirective],
|
||||
templateUrl: './language-chart.component.html',
|
||||
styleUrls: ['./language-chart.component.scss']
|
||||
})
|
||||
export class LanguageChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly filteredBooks = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.filterBooksByLibrary(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
});
|
||||
|
||||
public readonly chartType = 'pie' as const;
|
||||
public readonly languageStats = computed(() => this.calculateLanguageStats(this.filteredBooks()));
|
||||
public readonly totalBooks = computed(() => this.filteredBooks().length);
|
||||
public readonly booksWithLanguage = computed(() => this.languageStats().reduce((sum, s) => sum + s.count, 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 this.t.translate('statsLibrary.language.tooltipLabel', {label: context.label, value, percentage});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed<LanguageChartData>(() => {
|
||||
const stats = this.languageStats();
|
||||
if (stats.length === 0) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
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]);
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 2,
|
||||
hoverBorderColor: '#ffffff',
|
||||
hoverBorderWidth: 3
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.metadataScore'">
|
||||
<div class="metadata-score-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-check-circle score-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalBooks() > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks() === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@use '../../../_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;
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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_RANGE_KEYS = ['excellent', 'good', 'fair', 'poor', 'veryPoor'] as const;
|
||||
|
||||
const SCORE_RANGE_DEFS: { key: typeof SCORE_RANGE_KEYS[number]; min: number; max: number; color: string }[] = [
|
||||
{key: 'excellent', min: 90, max: 100, color: '#16A34A'},
|
||||
{key: 'good', min: 70, max: 89, color: '#22C55E'},
|
||||
{key: 'fair', min: 50, max: 69, color: '#F59E0B'},
|
||||
{key: 'poor', min: 25, max: 49, color: '#F97316'},
|
||||
{key: 'veryPoor', min: 0, max: 24, color: '#DC2626'}
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-score-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, TranslocoDirective],
|
||||
templateUrl: './metadata-score-chart.component.html',
|
||||
styleUrls: ['./metadata-score-chart.component.scss']
|
||||
})
|
||||
export class MetadataScoreChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly booksWithScore = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
return filteredBooks.filter(b => b.metadataMatchScore != null && b.metadataMatchScore >= 0);
|
||||
});
|
||||
|
||||
public readonly chartType = 'doughnut' as const;
|
||||
public readonly scoreStats = computed(() => this.calculateScoreStats(this.booksWithScore()));
|
||||
public readonly totalBooks = computed(() => this.booksWithScore().length);
|
||||
public readonly averageScore = computed(() => this.calculateAverageScore(this.booksWithScore()));
|
||||
|
||||
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 this.t.translate('statsLibrary.metadataScore.tooltipLabel', {value, percentage});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed<ScoreChartData>(() => {
|
||||
const stats = this.scoreStats();
|
||||
if (stats.length === 0) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const labels = stats.map(s => s.range);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => s.color);
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 2,
|
||||
hoverBorderColor: '#ffffff',
|
||||
hoverBorderWidth: 3
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
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_RANGE_DEFS.forEach(range => {
|
||||
rangeCounts.set(range.key, {count: 0, color: range.color});
|
||||
});
|
||||
|
||||
books.forEach(book => {
|
||||
const score = book.metadataMatchScore!;
|
||||
for (const range of SCORE_RANGE_DEFS) {
|
||||
if (score >= range.min && score <= range.max) {
|
||||
const data = rangeCounts.get(range.key)!;
|
||||
data.count++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const total = books.length;
|
||||
return SCORE_RANGE_DEFS
|
||||
.map(range => {
|
||||
const data = rangeCounts.get(range.key)!;
|
||||
return {
|
||||
range: this.t.translate(`statsLibrary.metadataScore.${range.key}`),
|
||||
count: data.count,
|
||||
percentage: (data.count / total) * 100,
|
||||
color: data.color
|
||||
};
|
||||
})
|
||||
.filter(stat => stat.count > 0);
|
||||
}
|
||||
|
||||
private calculateAverageScore(books: Book[]): number {
|
||||
if (books.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const total = books.reduce((sum, book) => sum + (book.metadataMatchScore || 0), 0);
|
||||
return Math.round(total / books.length);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.pageCount'">
|
||||
<div class="page-count-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-book page-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalBooks() > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks() === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@use '../../../_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;
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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, TranslocoDirective],
|
||||
templateUrl: './page-count-chart.component.html',
|
||||
styleUrls: ['./page-count-chart.component.scss']
|
||||
})
|
||||
export class PageCountChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly booksWithPageCount = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
return filteredBooks.filter(b => b.metadata?.pageCount != null && b.metadata.pageCount > 0);
|
||||
});
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public readonly totalBooks = computed(() => this.booksWithPageCount().length);
|
||||
|
||||
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) => this.t.translate('statsLibrary.pageCount.tooltipTitle', {label: context[0].label}),
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
return value === 1
|
||||
? this.t.translate('statsLibrary.pageCount.tooltipLabel', {value})
|
||||
: this.t.translate('statsLibrary.pageCount.tooltipLabelPlural', {value});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsLibrary.pageCount.axisPageCount'),
|
||||
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: this.t.translate('statsLibrary.pageCount.axisBooks'),
|
||||
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}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed<PageChartData>(() => {
|
||||
const booksWithPageCount = this.booksWithPageCount();
|
||||
if (booksWithPageCount.length === 0) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const stats = this.calculatePageStats(booksWithPageCount);
|
||||
const labels = stats.map(s => s.range);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => s.color);
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(() => 'rgba(255, 255, 255, 0.2)'),
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.7
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
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
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.publicationTimeline'">
|
||||
<div class="publication-timeline-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar timeline-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
@if (totalBooks() > 0) {
|
||||
<div class="books-count-badge">
|
||||
{{ t('booksWithDates', { count: totalBooks() }) }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalBooks() > 0) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (insights(); as insights) {
|
||||
<div class="insights-section">
|
||||
<div class="insights-row">
|
||||
@if (insights.oldestBook) {
|
||||
<div class="insight-item oldest">
|
||||
<span class="insight-label">{{ t('insightOldest') }}</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">{{ t('insightAverageYear') }}</span>
|
||||
<span class="insight-value">{{ insights.averageYear }}</span>
|
||||
<span class="insight-detail">{{ t('insightMedian', { year: insights.medianYear }) }}</span>
|
||||
</div>
|
||||
|
||||
@if (insights.newestBook) {
|
||||
<div class="insight-item newest">
|
||||
<span class="insight-label">{{ t('insightNewest') }}</span>
|
||||
<span class="insight-value">{{ insights.newestBook.year }}</span>
|
||||
<span class="insight-detail" [title]="insights.newestBook.title">{{ insights.newestBook.title }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="insight-item common-year">
|
||||
<span class="insight-label">{{ t('insightMostCommonYear') }}</span>
|
||||
<span class="insight-value">{{ insights.mostCommonYear.year }}</span>
|
||||
<span class="insight-detail">{{ t('insightMostCommonYearBooks', { count: insights.mostCommonYear.count }) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="insights-row">
|
||||
<div class="insight-item timespan">
|
||||
<span class="insight-label">{{ t('insightTimeSpan') }}</span>
|
||||
<span class="insight-value">{{ insights.timeSpan }}</span>
|
||||
<span class="insight-detail">{{ t('insightYearsOfLiterature') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item peak">
|
||||
<span class="insight-label">{{ t('insightPeakDecade') }}</span>
|
||||
<span class="insight-value">{{ insights.peakDecade }}</span>
|
||||
<span class="insight-detail">{{ t('insightPeakDecadeBooks', { count: insights.peakDecadeCount }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item golden-era">
|
||||
<span class="insight-label">{{ t('insightGoldenEra') }}</span>
|
||||
<span class="insight-value">{{ insights.goldenEra.start }}-{{ insights.goldenEra.end }}</span>
|
||||
<span class="insight-detail">{{ t('insightGoldenEraRange', { count: insights.goldenEra.count }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item rarity">
|
||||
<span class="insight-label">{{ t('insightRarityScore') }}</span>
|
||||
<span class="insight-value">{{ insights.rarityScore }}%</span>
|
||||
<span class="insight-detail">{{ t('insightRarePicks') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@if (totalBooks() === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
@use '../../../_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: 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.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;
|
||||
}
|
||||
}
|
||||
|
||||
&.golden-era {
|
||||
.insight-value {
|
||||
color: #fb923c;
|
||||
}
|
||||
}
|
||||
|
||||
&.common-year {
|
||||
.insight-value {
|
||||
color: #34d399;
|
||||
}
|
||||
}
|
||||
|
||||
&.rarity {
|
||||
.insight-value {
|
||||
color: #f87171;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.insights-row + .insights-row {
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 320px;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.insights-row {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
|
||||
.insight-item {
|
||||
padding: 0.5rem;
|
||||
|
||||
.insight-value {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.insight-label {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+357
@@ -0,0 +1,357 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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 };
|
||||
goldenEra: { start: number; end: number; count: number };
|
||||
mostCommonYear: { year: number; count: number };
|
||||
rarityScore: 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, TranslocoDirective],
|
||||
templateUrl: './publication-timeline-chart.component.html',
|
||||
styleUrls: ['./publication-timeline-chart.component.scss']
|
||||
})
|
||||
export class PublicationTimelineChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly booksWithDate = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
return filteredBooks.filter(b => b.metadata?.publishedDate);
|
||||
});
|
||||
private readonly decadeStats = computed(() => this.calculateDecadeStats(this.booksWithDate()));
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public chartOptions: ChartConfiguration<'bar'>['options'];
|
||||
public readonly insights = computed(() => {
|
||||
const booksWithDate = this.booksWithDate();
|
||||
return booksWithDate.length > 0 ? this.calculateInsights(booksWithDate) : null;
|
||||
});
|
||||
public readonly totalBooks = computed(() => this.booksWithDate().length);
|
||||
public readonly chartData = computed<TimelineChartData>(() => {
|
||||
const stats = this.decadeStats();
|
||||
if (stats.length === 0) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const labels = stats.map(s => s.label);
|
||||
const data = stats.map(s => s.count);
|
||||
const colors = stats.map(s => s.color);
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors,
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.85
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
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: this.t.translate('statsLibrary.publicationTimeline.axisNumberOfBooks'),
|
||||
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;
|
||||
return value === 1
|
||||
? this.t.translate('statsLibrary.publicationTimeline.tooltipBook', {value})
|
||||
: this.t.translate('statsLibrary.publicationTimeline.tooltipBooks', {value});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
peakDecadeCount = count;
|
||||
}
|
||||
}
|
||||
|
||||
const timeSpan = oldest && newest ? newest.year - oldest.year : 0;
|
||||
|
||||
// Golden Era: best 20-year window
|
||||
let goldenEra = {start: 0, end: 0, count: 0};
|
||||
if (years.length > 0) {
|
||||
for (let i = 0; i < years.length; i++) {
|
||||
const windowStart = years[i];
|
||||
const windowEnd = windowStart + 19;
|
||||
const windowCount = years.filter(y => y >= windowStart && y <= windowEnd).length;
|
||||
if (windowCount > goldenEra.count) {
|
||||
goldenEra = {start: windowStart, end: windowEnd, count: windowCount};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Most Common Year
|
||||
const yearCounts = new Map<number, number>();
|
||||
for (const y of years) {
|
||||
yearCounts.set(y, (yearCounts.get(y) || 0) + 1);
|
||||
}
|
||||
let mostCommonYear = {year: 0, count: 0};
|
||||
for (const [y, c] of yearCounts) {
|
||||
if (c > mostCommonYear.count) {
|
||||
mostCommonYear = {year: y, count: c};
|
||||
}
|
||||
}
|
||||
|
||||
// Rarity Score: % of books in decades with fewer than 3 books
|
||||
let rareBooks = 0;
|
||||
for (const [_, count] of decadeCounts) {
|
||||
if (count < 3) rareBooks += count;
|
||||
}
|
||||
const rarityScore = years.length > 0 ? Math.round((rareBooks / years.length) * 100) : 0;
|
||||
|
||||
return {
|
||||
oldestBook: oldest,
|
||||
newestBook: newest,
|
||||
averageYear,
|
||||
medianYear,
|
||||
totalWithDate: years.length,
|
||||
timeSpan,
|
||||
peakDecade,
|
||||
peakDecadeCount,
|
||||
centuryBreakdown: {c21, c20, older},
|
||||
goldenEra,
|
||||
mostCommonYear,
|
||||
rarityScore
|
||||
};
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.publicationTrend'">
|
||||
<div class="publication-trend-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-line trend-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</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()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (insights(); as insights) {
|
||||
<div class="insights-section">
|
||||
<div class="insights-row">
|
||||
<div class="insight-item peak">
|
||||
<span class="insight-label">{{ t('insightPeakYear') }}</span>
|
||||
<span class="insight-value">{{ insights.peakYear }}</span>
|
||||
<span class="insight-detail">{{ t('insightPeakYearBooks', { count: insights.peakYearCount }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item recent">
|
||||
<span class="insight-label">{{ t('insightLast10Years') }}</span>
|
||||
<span class="insight-value">{{ insights.booksLast10YearsPercent }}%</span>
|
||||
<span class="insight-detail">{{ t('insightLast10YearsBooks', { count: insights.booksLast10Years }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item average">
|
||||
<span class="insight-label">{{ t('insightAvgPerYear') }}</span>
|
||||
<span class="insight-value">{{ insights.averageBooksPerYear }}</span>
|
||||
<span class="insight-detail">{{ t('insightBooksPerYear') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item productive">
|
||||
<span class="insight-label">{{ t('insightBest5YearSpan') }}</span>
|
||||
<span class="insight-value">{{ insights.mostProductiveSpan }}</span>
|
||||
<span class="insight-detail">{{ t('insightMostBooksPublished') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item timespan">
|
||||
<span class="insight-label">{{ t('insightTimeSpan') }}</span>
|
||||
<span class="insight-value">{{ insights.timeSpan }}</span>
|
||||
<span class="insight-detail">{{ t('insightYearsCovered') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item century21">
|
||||
<span class="insight-label">{{ t('insightCentury21') }}</span>
|
||||
<span class="insight-value">{{ insights.century21Percent }}%</span>
|
||||
<span class="insight-detail">{{ t('insightCentury21Books', { count: insights.century21Books }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item classics">
|
||||
<span class="insight-label">{{ t('insightClassics') }}</span>
|
||||
<span class="insight-value">{{ insights.classicBooksPercent }}%</span>
|
||||
<span class="insight-detail">{{ t('insightClassicsPre1970', { count: insights.classicBooks }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item unique">
|
||||
<span class="insight-label">{{ t('insightUniqueYears') }}</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>{{ t('noData') }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
@use '../../../_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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, TranslocoDirective],
|
||||
templateUrl: './publication-trend-chart.component.html',
|
||||
styleUrls: ['./publication-trend-chart.component.scss']
|
||||
})
|
||||
export class PublicationTrendChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly booksWithDate = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
return filteredBooks.filter(b => b.metadata?.publishedDate);
|
||||
});
|
||||
private readonly yearCounts = computed(() => this.calculateYearCounts(this.booksWithDate()));
|
||||
|
||||
public readonly chartType = 'line' as const;
|
||||
public chartOptions: ChartConfiguration<'line'>['options'];
|
||||
public readonly insights = computed(() => {
|
||||
const booksWithDate = this.booksWithDate();
|
||||
if (booksWithDate.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.calculateInsights(this.yearCounts(), booksWithDate.length);
|
||||
});
|
||||
public readonly totalBooks = computed(() => this.booksWithDate().length);
|
||||
public readonly yearRange = computed(() => {
|
||||
const years = Array.from(this.yearCounts().keys()).sort((a, b) => a - b);
|
||||
if (years.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${years[0]} - ${years[years.length - 1]}`;
|
||||
});
|
||||
public readonly chartData = computed<TrendChartData>(() => {
|
||||
const yearCounts = this.yearCounts();
|
||||
const years = Array.from(yearCounts.keys()).sort((a, b) => a - b);
|
||||
|
||||
if (years.length === 0) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const minYear = years[0];
|
||||
const maxYear = years[years.length - 1];
|
||||
const labels: string[] = [];
|
||||
const data: number[] = [];
|
||||
|
||||
for (let year = minYear; year <= maxYear; year++) {
|
||||
labels.push(year.toString());
|
||||
data.push(yearCounts.get(year) || 0);
|
||||
}
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
data,
|
||||
borderColor: '#06b6d4',
|
||||
backgroundColor: 'rgba(6, 182, 212, 0.1)',
|
||||
pointBackgroundColor: '#06b6d4',
|
||||
pointBorderColor: '#ffffff',
|
||||
fill: true
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
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: this.t.translate('statsLibrary.publicationTrend.axisPublicationYear'),
|
||||
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: this.t.translate('statsLibrary.publicationTrend.axisBooks'),
|
||||
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) => this.t.translate('statsLibrary.publicationTrend.tooltipTitle', {year: context[0].label}),
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
return value === 1
|
||||
? this.t.translate('statsLibrary.publicationTrend.tooltipBook', {value})
|
||||
: this.t.translate('statsLibrary.publicationTrend.tooltipBooks', {value});
|
||||
}
|
||||
}
|
||||
},
|
||||
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 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}`;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.readingJourney'">
|
||||
<div class="reading-journey-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-directions journey-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
@if (dateRange()) {
|
||||
<div class="date-range-badge">
|
||||
{{ dateRange() }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalBooks() > 0 && insights(); as insights) {
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
<div class="insights-section">
|
||||
<div class="insights-row">
|
||||
<div class="insight-item backlog">
|
||||
<span class="insight-label">{{ t('insightCurrentBacklog') }}</span>
|
||||
<span class="insight-value">{{ insights.currentBacklog }}</span>
|
||||
<span class="insight-detail">{{ t('insightBacklogPercent', { percent: insights.backlogPercent }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item time-to-read">
|
||||
<span class="insight-label">{{ t('insightAvgTimeToFinish') }}</span>
|
||||
<span class="insight-value">{{ insights.avgTimeToFinishDays }}</span>
|
||||
<span class="insight-detail">{{ t('insightDaysAfterAdding') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item productive">
|
||||
<span class="insight-label">{{ t('insightBestReadingMonth') }}</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">{{ t('insightPeakAcquisition') }}</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">{{ t('insightFinishRate') }}</span>
|
||||
<span class="insight-value">{{ insights.finishRate }}</span>
|
||||
<span class="insight-detail">{{ t('insightBooksPerMonthAvg') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item streak">
|
||||
<span class="insight-label">{{ t('insightLongestStreak') }}</span>
|
||||
<span class="insight-value">{{ insights.longestStreak }}</span>
|
||||
<span class="insight-detail">{{ t('insightConsecutiveMonths') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item recent">
|
||||
<span class="insight-label">{{ t('insightLast3Months') }}</span>
|
||||
<span class="insight-value">{{ insights.recentActivity }}</span>
|
||||
<span class="insight-detail">{{ t('insightRecentlyFinished') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="insight-item total">
|
||||
<span class="insight-label">{{ t('insightCompletion') }}</span>
|
||||
<span class="insight-value">{{ insights.totalFinished }}/{{ insights.totalAdded }}</span>
|
||||
<span class="insight-detail">{{ t('insightBooksFinished') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (totalBooks() === 0 || !insights()) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
@use '../../../_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.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.insight-detail {
|
||||
font-size: 0.75rem;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+429
@@ -0,0 +1,429 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {LibraryFilterService} from '../../service/library-filter.service';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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, TranslocoDirective],
|
||||
templateUrl: './reading-journey-chart.component.html',
|
||||
styleUrls: ['./reading-journey-chart.component.scss']
|
||||
})
|
||||
export class ReadingJourneyChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly filteredBooks = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.filterBooksByLibrary(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
});
|
||||
private readonly monthlyData = computed(() => this.calculateMonthlyData(this.filteredBooks()));
|
||||
|
||||
public readonly chartType = 'line' as const;
|
||||
public chartOptions: ChartConfiguration<'line'>['options'];
|
||||
public readonly insights = computed(() => {
|
||||
const filteredBooks = this.filteredBooks();
|
||||
const monthlyData = this.monthlyData();
|
||||
return filteredBooks.length > 0 ? this.calculateInsights(filteredBooks, monthlyData) : null;
|
||||
});
|
||||
public readonly totalBooks = computed(() => this.filteredBooks().length);
|
||||
public readonly dateRange = computed(() => {
|
||||
const monthlyData = this.monthlyData();
|
||||
if (monthlyData.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${monthlyData[0].label} - ${monthlyData[monthlyData.length - 1].label}`;
|
||||
});
|
||||
public readonly chartData = computed<JourneyChartData>(() => {
|
||||
const monthlyData = this.monthlyData();
|
||||
if (monthlyData.length === 0) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const labels = monthlyData.map(d => d.label);
|
||||
const addedData = monthlyData.map(d => d.cumulativeAdded);
|
||||
const finishedData = monthlyData.map(d => d.cumulativeFinished);
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: this.t.translate('statsLibrary.readingJourney.legendBooksAdded'),
|
||||
data: addedData,
|
||||
borderColor: '#3b82f6',
|
||||
backgroundColor: 'rgba(59, 130, 246, 0.1)',
|
||||
pointBackgroundColor: '#3b82f6',
|
||||
pointBorderColor: '#ffffff',
|
||||
fill: true,
|
||||
order: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsLibrary.readingJourney.legendBooksFinished'),
|
||||
data: finishedData,
|
||||
borderColor: '#10b981',
|
||||
backgroundColor: 'rgba(16, 185, 129, 0.2)',
|
||||
pointBackgroundColor: '#10b981',
|
||||
pointBorderColor: '#ffffff',
|
||||
fill: true,
|
||||
order: 1
|
||||
}
|
||||
]
|
||||
};
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
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: this.t.translate('statsLibrary.readingJourney.axisMonth'),
|
||||
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: this.t.translate('statsLibrary.readingJourney.axisCumulativeBooks'),
|
||||
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 [`\n${this.t.translate('statsLibrary.readingJourney.tooltipBacklog', {count: backlog})}`];
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: false
|
||||
}
|
||||
},
|
||||
elements: {
|
||||
line: {
|
||||
tension: 0.3,
|
||||
borderWidth: 3
|
||||
},
|
||||
point: {
|
||||
radius: 3,
|
||||
hoverRadius: 6,
|
||||
borderWidth: 2
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'index'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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
|
||||
? this.t.translate('statsLibrary.readingJourney.recentActivityBooks', {count: recentFinished})
|
||||
: this.t.translate('statsLibrary.readingJourney.recentActivityNone');
|
||||
|
||||
// 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
|
||||
};
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary.topItems'">
|
||||
<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>
|
||||
{{ t('titlePrefix') }} {{ selectedDataType.label }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('descriptionPrefix') }} {{ selectedDataType.label.toLowerCase() }} {{ t('descriptionSuffix') }}</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">{{ t('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>{{ t('noDataPrefix') }} {{ selectedDataType.label.toLowerCase() }} {{ t('noDataSuffix') }}</p>
|
||||
<small>{{ t('noDataHintPrefix') }} {{ selectedDataType.label.toLowerCase() }} {{ t('noDataHintSuffix') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
@use '../../../_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;
|
||||
}
|
||||
}
|
||||
+444
@@ -0,0 +1,444 @@
|
||||
import {Component, effect, inject, Input, 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, Observable} from 'rxjs';
|
||||
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 {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
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_DEFS: { key: string; value: DataType; icon: string; color: string }[] = [
|
||||
{key: 'authors', value: 'authors', icon: 'pi-th-large', color: '#2563EB'},
|
||||
{key: 'categories', value: 'categories', icon: 'pi-user', color: '#0D9488'},
|
||||
{key: 'series', value: 'series', icon: 'pi-tag', color: '#DB2777'},
|
||||
{key: 'publishers', value: 'publishers', icon: 'pi-building', color: '#7C3AED'},
|
||||
{key: 'tags', value: 'tags', icon: 'pi-bookmark', color: '#EAB308'},
|
||||
{key: 'moods', value: 'moods', icon: 'pi-heart', color: '#EA580C'}
|
||||
];
|
||||
|
||||
const READ_STATUS_KEYS: Record<ReadStatus, string> = {
|
||||
[ReadStatus.READ]: 'read',
|
||||
[ReadStatus.READING]: 'reading',
|
||||
[ReadStatus.RE_READING]: 'reReading',
|
||||
[ReadStatus.UNREAD]: 'unread',
|
||||
[ReadStatus.PARTIALLY_READ]: 'partiallyRead',
|
||||
[ReadStatus.PAUSED]: 'paused',
|
||||
[ReadStatus.WONT_READ]: 'wontRead',
|
||||
[ReadStatus.ABANDONED]: 'abandoned',
|
||||
[ReadStatus.UNSET]: 'notSet'
|
||||
};
|
||||
|
||||
const READ_STATUS_COLORS: Record<ReadStatus, string> = {
|
||||
[ReadStatus.READ]: '#22c55e',
|
||||
[ReadStatus.READING]: '#3b82f6',
|
||||
[ReadStatus.RE_READING]: '#8b5cf6',
|
||||
[ReadStatus.UNREAD]: '#6b7280',
|
||||
[ReadStatus.PARTIALLY_READ]: '#f59e0b',
|
||||
[ReadStatus.PAUSED]: '#eab308',
|
||||
[ReadStatus.WONT_READ]: '#ef4444',
|
||||
[ReadStatus.ABANDONED]: '#dc2626',
|
||||
[ReadStatus.UNSET]: '#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, TranslocoDirective],
|
||||
templateUrl: './top-items-chart.component.html',
|
||||
styleUrls: ['./top-items-chart.component.scss']
|
||||
})
|
||||
export class TopItemsChartComponent implements OnInit {
|
||||
@Input() initialDataType: DataType | null = null;
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public readonly chartData$: Observable<ItemChartData>;
|
||||
public chartOptions: ChartConfiguration<'bar'>['options'];
|
||||
public dataTypeOptions: DataTypeOption[];
|
||||
public selectedDataType: DataTypeOption;
|
||||
|
||||
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 t = inject(TranslocoService);
|
||||
private readonly syncChartEffect = effect(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.loadAndProcessData(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
});
|
||||
private readonly chartDataSubject: BehaviorSubject<ItemChartData>;
|
||||
private lastCalculatedStats: ItemStats[] = [];
|
||||
private allBooks: Book[] = [];
|
||||
|
||||
constructor() {
|
||||
this.dataTypeOptions = DATA_TYPE_DEFS.map(def => ({
|
||||
label: this.t.translate(`statsLibrary.topItems.dataTypes.${def.key}`),
|
||||
value: def.value,
|
||||
icon: def.icon,
|
||||
color: def.color
|
||||
}));
|
||||
this.selectedDataType = this.dataTypeOptions[0];
|
||||
this.chartDataSubject = new BehaviorSubject<ItemChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
this.initChartOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
if (this.initialDataType) {
|
||||
const initialOption = this.dataTypeOptions.find(opt => opt.value === this.initialDataType);
|
||||
if (initialOption) {
|
||||
this.selectedDataType = initialOption;
|
||||
this.initChartOptions();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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: this.t.translate('statsLibrary.topItems.axisNumberOfBooks'),
|
||||
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(books: Book[], selectedLibraryId: number | null): void {
|
||||
if (books.length === 0) {
|
||||
this.allBooks = [];
|
||||
this.updateChartData([]);
|
||||
return;
|
||||
}
|
||||
|
||||
this.allBooks = this.filterBooksByLibrary(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 statusKey = READ_STATUS_KEYS[status];
|
||||
const color = READ_STATUS_COLORS[status];
|
||||
return {
|
||||
label: this.t.translate(`statsLibrary.topItems.readStatus.${statusKey}`),
|
||||
data: stats.map(s => s.statusBreakdown[status]),
|
||||
backgroundColor: color,
|
||||
borderColor: 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
|
||||
|
||||
// 1. Top item
|
||||
const top = stats[0];
|
||||
this.insights.push({
|
||||
icon: 'pi-trophy',
|
||||
label: this.t.translate('statsLibrary.topItems.insightTop', {type: typeName}),
|
||||
value: this.t.translate('statsLibrary.topItems.insightTopValue', {name: top.name, count: top.count})
|
||||
});
|
||||
|
||||
// 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: this.t.translate('statsLibrary.topItems.insightMostCompleted'),
|
||||
value: this.t.translate('statsLibrary.topItems.insightMostCompletedValue', {name: mostRead.name, percent: readPct})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 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: this.t.translate('statsLibrary.topItems.insightTop5Coverage'),
|
||||
value: this.t.translate('statsLibrary.topItems.insightTop5CoverageValue', {percent: concentration})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Average books per item
|
||||
if (stats.length > 0) {
|
||||
const avgBooks = (this.totalBooks / stats.length).toFixed(1);
|
||||
this.insights.push({
|
||||
icon: 'pi-book',
|
||||
label: this.t.translate('statsLibrary.topItems.insightAvgPer', {type: typeName}),
|
||||
value: this.t.translate('statsLibrary.topItems.insightAvgPerValue', {avg: avgBooks})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 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 || this.t.translate('statsLibrary.pageCount.axisBooks');
|
||||
return value === 1
|
||||
? this.t.translate('statsLibrary.topItems.tooltipBook', {status: statusLabel, value})
|
||||
: this.t.translate('statsLibrary.topItems.tooltipBooks', {status: statusLabel, value});
|
||||
}
|
||||
|
||||
private truncateTitle(title: string, maxLength: number): string {
|
||||
return title.length > maxLength ? title.substring(0, maxLength) + '...' : title;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsLibrary'">
|
||||
<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">{{ t('main.title') }}</label>
|
||||
<div class="dropdown-row">
|
||||
<p-select
|
||||
fluid
|
||||
id="library-dropdown"
|
||||
[options]="libraryOptions()"
|
||||
[ngModel]="selectedLibrary()"
|
||||
optionLabel="name"
|
||||
size="small"
|
||||
[placeholder]="t('main.selectLibrary')"
|
||||
(ngModelChange)="onLibraryChange($event)"
|
||||
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]="t('main.totalBooks')">
|
||||
<i class="pi pi-book"></i>
|
||||
<span class="total-label">{{ t('main.books') }}</span>
|
||||
<span class="total-value">{{ booksSummary().totalBooks }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-authors" [title]="t('main.totalAuthors')">
|
||||
<i class="pi pi-users"></i>
|
||||
<span class="total-label">{{ t('main.authors') }}</span>
|
||||
<span class="total-value">{{ booksSummary().totalAuthors }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-series" [title]="t('main.totalSeries')">
|
||||
<i class="pi pi-bookmark"></i>
|
||||
<span class="total-label">{{ t('main.series') }}</span>
|
||||
<span class="total-value">{{ booksSummary().totalSeries }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-publishers" [title]="t('main.totalPublishers')">
|
||||
<i class="pi pi-building"></i>
|
||||
<span class="total-label">{{ t('main.publishers') }}</span>
|
||||
<span class="total-value">{{ booksSummary().totalPublishers }}</span>
|
||||
</div>
|
||||
|
||||
<div class="total-item total-size" [title]="t('main.totalSize')">
|
||||
<i class="pi pi-file"></i>
|
||||
<span class="total-label">{{ t('main.librarySize') }}</span>
|
||||
<span class="total-value">{{ totalSize() }}</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> {{ t('config.title') }}</h3>
|
||||
<button type="button" class="close-btn" (click)="closeConfigPanel()" [title]="t('config.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> {{ t('config.enableAll') }}
|
||||
</button>
|
||||
<button type="button" class="config-action-btn disable-all" (click)="disableAllCharts()">
|
||||
<i class="pi pi-times"></i> {{ t('config.disableAll') }}
|
||||
</button>
|
||||
<button type="button" class="config-action-btn reset-order" (click)="resetChartOrder()">
|
||||
<i class="pi pi-refresh"></i> {{ t('config.resetOrder') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="config-modal-content">
|
||||
<div class="config-categories">
|
||||
<div class="config-category">
|
||||
<h4>{{ t('config.smallCharts') }}</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>{{ t('config.largeCharts') }}</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>{{ t('config.xlargeCharts') }}</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]="t('main.dragToReorder')">
|
||||
<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">
|
||||
{{ t('main.loading') }}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!isLoading() && !hasData()) {
|
||||
<div class="no-data-message">
|
||||
{{ t('main.noData') }}
|
||||
<small>{{ t('main.noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
@@ -0,0 +1,634 @@
|
||||
.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;
|
||||
}
|
||||
|
||||
.dropdown-row {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
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';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {LibraryService} from '../../../book/service/library.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,
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './library-stats.component.html',
|
||||
styleUrls: ['./library-stats.component.scss']
|
||||
})
|
||||
export class LibraryStatsComponent {
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly librariesSummaryService = inject(LibrariesSummaryService);
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryService = inject(LibraryService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
public readonly isLoading = computed(() =>
|
||||
this.bookService.isBooksLoading() || this.libraryService.isLibrariesLoading()
|
||||
);
|
||||
public readonly hasData = computed(() => this.booksSummary().totalBooks > 0);
|
||||
public readonly libraryOptions = this.libraryFilterService.libraryOptions;
|
||||
public readonly booksSummary = this.librariesSummaryService.booksSummary;
|
||||
public readonly totalSize = this.librariesSummaryService.formattedSize;
|
||||
public readonly selectedLibrary = computed<LibraryOption | null>(() => {
|
||||
const options = this.libraryOptions();
|
||||
|
||||
if (options.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return options.find(option => option.id === this.libraryFilterService.selectedLibrary()) ?? options[0];
|
||||
});
|
||||
public showConfigPanel = false;
|
||||
|
||||
public chartsConfig: ChartConfig[] = this.buildChartsConfig();
|
||||
|
||||
onLibraryChange(selectedLibrary: LibraryOption | null): void {
|
||||
if (!selectedLibrary) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.libraryFilterService.setSelectedLibrary(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 = this.buildChartsConfig();
|
||||
}
|
||||
|
||||
private buildChartsConfig(): ChartConfig[] {
|
||||
return [
|
||||
{id: 'bookFormats', name: this.t.translate('statsLibrary.chartNames.bookFormats'), enabled: true, category: 'small'},
|
||||
{id: 'languageDistribution', name: this.t.translate('statsLibrary.chartNames.languages'), enabled: true, category: 'small'},
|
||||
{id: 'metadataScore', name: this.t.translate('statsLibrary.chartNames.metadataScore'), enabled: true, category: 'small'},
|
||||
{id: 'pageCountDistribution', name: this.t.translate('statsLibrary.chartNames.pageCount'), enabled: true, category: 'small'},
|
||||
{id: 'publicationTimeline', name: this.t.translate('statsLibrary.chartNames.publicationTimeline'), enabled: true, category: 'large'},
|
||||
{id: 'readingJourney', name: this.t.translate('statsLibrary.chartNames.readingJourney'), enabled: true, category: 'large'},
|
||||
{id: 'topItems', name: this.t.translate('statsLibrary.chartNames.topItems'), enabled: true, category: 'large'},
|
||||
{id: 'authorUniverse', name: this.t.translate('statsLibrary.chartNames.authorUniverse'), enabled: true, category: 'large'},
|
||||
{id: 'publicationTrend', name: this.t.translate('statsLibrary.chartNames.publicationTrend'), enabled: true, category: 'xlarge'}
|
||||
];
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import {computed, inject, Injectable} from '@angular/core';
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
|
||||
export interface BooksSummary {
|
||||
totalBooks: number;
|
||||
totalSizeKb: number;
|
||||
totalAuthors: number;
|
||||
totalSeries: number;
|
||||
totalPublishers: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class LibrariesSummaryService {
|
||||
private bookService = inject(BookService);
|
||||
private libraryFilterService = inject(LibraryFilterService);
|
||||
readonly booksSummary = computed<BooksSummary>(() => {
|
||||
const books = this.bookService.books();
|
||||
const selectedLibraryId = this.libraryFilterService.selectedLibrary();
|
||||
|
||||
if (books.length === 0) {
|
||||
return {totalBooks: 0, totalSizeKb: 0, totalAuthors: 0, totalSeries: 0, totalPublishers: 0};
|
||||
}
|
||||
|
||||
const filteredBooks = selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: 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(author => {
|
||||
const name = author?.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
|
||||
};
|
||||
});
|
||||
readonly formattedSize = computed(() => this.formatSizeKb(this.booksSummary().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';
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import {computed, inject, Injectable, signal} from '@angular/core';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
import {LibraryService} from '../../../../book/service/library.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
export interface LibraryOption {
|
||||
id: number | null;
|
||||
name: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class LibraryFilterService {
|
||||
private readonly selectedLibraryId = signal<number | null>(null);
|
||||
|
||||
readonly selectedLibrary = computed(() => {
|
||||
const selectedLibraryId = this.selectedLibraryId();
|
||||
return this.libraryOptions().some(option => option.id === selectedLibraryId)
|
||||
? selectedLibraryId
|
||||
: null;
|
||||
});
|
||||
|
||||
setSelectedLibrary(libraryId: number | null): void {
|
||||
this.selectedLibraryId.set(libraryId);
|
||||
}
|
||||
|
||||
private bookService = inject(BookService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private t = inject(TranslocoService);
|
||||
readonly libraryOptions = computed(() => {
|
||||
const books = this.bookService.books();
|
||||
const libraries = this.libraryService.libraries();
|
||||
|
||||
if (books.length === 0) {
|
||||
return [{id: null, name: this.t.translate('statsLibrary.libraryFilter.allLibraries')}];
|
||||
}
|
||||
|
||||
const libraryMap = new Map<number, string>();
|
||||
books.forEach(book => {
|
||||
if (!libraryMap.has(book.libraryId)) {
|
||||
const library = libraries.find(lib => lib.id === book.libraryId);
|
||||
const libraryName = library?.name || this.t.translate('statsLibrary.libraryFilter.libraryFallback', {id: book.libraryId}) as string;
|
||||
libraryMap.set(book.libraryId, libraryName);
|
||||
}
|
||||
});
|
||||
|
||||
const options: LibraryOption[] = [
|
||||
{id: null, name: this.t.translate('statsLibrary.libraryFilter.allLibraries')},
|
||||
...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);
|
||||
});
|
||||
});
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.bookFlow'">
|
||||
<div class="book-flow-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-arrows-h book-flow-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (hasData) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card total">
|
||||
<span class="stat-value">{{ totalBooks }}</span>
|
||||
<span class="stat-label">{{ t('totalBooks') }}</span>
|
||||
</div>
|
||||
<div class="stat-card quarter">
|
||||
<span class="stat-value">{{ topQuarter }}</span>
|
||||
<span class="stat-label">{{ t('busiestQuarter') }}</span>
|
||||
</div>
|
||||
<div class="stat-card status">
|
||||
<span class="stat-value">{{ topStatus }}</span>
|
||||
<span class="stat-label">{{ t('topStatus') }}</span>
|
||||
</div>
|
||||
<div class="stat-card completion">
|
||||
<span class="stat-value">{{ completionRate }}</span>
|
||||
<span class="stat-label">{{ t('completionRate') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="canvas-wrapper">
|
||||
<canvas #flowCanvas></canvas>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
.book-flow-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.book-flow-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #26c6da;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
flex: 1;
|
||||
min-width: 80px;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.3rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
.stat-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
&.total .stat-value { color: #42a5f5; }
|
||||
&.quarter .stat-value { color: #26c6da; }
|
||||
&.status .stat-value { color: #66bb6a; }
|
||||
&.rating .stat-value { color: #ffc107; }
|
||||
&.completion .stat-value { color: #ab47bc; }
|
||||
}
|
||||
}
|
||||
|
||||
.canvas-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 500px;
|
||||
canvas { display: block; }
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
i { font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5; }
|
||||
p { font-size: 1rem; margin: 0 0 0.5rem 0; color: var(--text-color, #ffffff); }
|
||||
small { font-size: 0.85rem; opacity: 0.7; }
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.canvas-wrapper { height: 400px; }
|
||||
}
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
import {AfterViewInit, Component, effect, ElementRef, inject, ViewChild} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface SankeyNode {
|
||||
id: string;
|
||||
label: string;
|
||||
column: number;
|
||||
y: number;
|
||||
height: number;
|
||||
color: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface SankeyLink {
|
||||
source: SankeyNode;
|
||||
target: SankeyNode;
|
||||
value: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-flow-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, Tooltip, TranslocoDirective],
|
||||
templateUrl: './book-flow-chart.component.html',
|
||||
styleUrls: ['./book-flow-chart.component.scss']
|
||||
})
|
||||
export class BookFlowChartComponent implements AfterViewInit {
|
||||
@ViewChild('flowCanvas', {static: false}) canvasRef!: ElementRef<HTMLCanvasElement>;
|
||||
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly syncChartEffect = effect(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
this.dataReady = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.processData(this.bookService.books());
|
||||
this.dataReady = true;
|
||||
this.tryRender();
|
||||
});
|
||||
|
||||
public hasData = false;
|
||||
public totalBooks = 0;
|
||||
public topQuarter = '';
|
||||
public topStatus = '';
|
||||
public completionRate = '';
|
||||
|
||||
private nodes: SankeyNode[] = [];
|
||||
private links: SankeyLink[] = [];
|
||||
private canvasReady = false;
|
||||
private dataReady = false;
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
this.canvasReady = true;
|
||||
this.tryRender();
|
||||
}
|
||||
|
||||
private tryRender(): void {
|
||||
if (this.canvasReady && this.dataReady && this.hasData) {
|
||||
requestAnimationFrame(() => this.draw());
|
||||
}
|
||||
}
|
||||
|
||||
private processData(books: Book[]): void {
|
||||
this.hasData = false;
|
||||
this.totalBooks = 0;
|
||||
this.topQuarter = '';
|
||||
this.topStatus = '';
|
||||
this.completionRate = '';
|
||||
this.nodes = [];
|
||||
this.links = [];
|
||||
|
||||
if (books.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const quarterMap = new Map<string, number>();
|
||||
const statusMap = new Map<string, number>();
|
||||
const ratingMap = new Map<string, number>();
|
||||
const quarterToStatus = new Map<string, Map<string, number>>();
|
||||
const statusToRating = new Map<string, Map<string, number>>();
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
'Read': '#66bb6a', 'Reading': '#42a5f5', 'Unread': '#78909c',
|
||||
'Paused': '#ffa726', 'Abandoned': '#ef5350', 'Other': '#ab47bc'
|
||||
};
|
||||
|
||||
const ratingColors: Record<string, string> = {
|
||||
'Rated 4-5': '#66bb6a', 'Rated 3': '#ffc107',
|
||||
'Rated 1-2': '#ef5350', 'Unrated': '#78909c'
|
||||
};
|
||||
|
||||
for (const book of books) {
|
||||
const addedOn = book.addedOn;
|
||||
let quarter = 'Unknown';
|
||||
if (addedOn) {
|
||||
const date = new Date(addedOn);
|
||||
const q = Math.ceil((date.getMonth() + 1) / 3);
|
||||
quarter = `${date.getFullYear()} Q${q}`;
|
||||
}
|
||||
|
||||
let status = 'Other';
|
||||
switch (book.readStatus) {
|
||||
case ReadStatus.READ: status = 'Read'; break;
|
||||
case ReadStatus.READING: case ReadStatus.RE_READING: status = 'Reading'; break;
|
||||
case ReadStatus.UNREAD: case ReadStatus.UNSET: status = 'Unread'; break;
|
||||
case ReadStatus.PAUSED: status = 'Paused'; break;
|
||||
case ReadStatus.ABANDONED: case ReadStatus.WONT_READ: status = 'Abandoned'; break;
|
||||
}
|
||||
|
||||
let ratingBucket = 'Unrated';
|
||||
const rating = book.personalRating;
|
||||
if (rating && rating > 0) {
|
||||
const normalized = rating / 2;
|
||||
if (normalized >= 4) ratingBucket = 'Rated 4-5';
|
||||
else if (normalized >= 3) ratingBucket = 'Rated 3';
|
||||
else ratingBucket = 'Rated 1-2';
|
||||
}
|
||||
|
||||
quarterMap.set(quarter, (quarterMap.get(quarter) || 0) + 1);
|
||||
statusMap.set(status, (statusMap.get(status) || 0) + 1);
|
||||
ratingMap.set(ratingBucket, (ratingMap.get(ratingBucket) || 0) + 1);
|
||||
|
||||
if (!quarterToStatus.has(quarter)) quarterToStatus.set(quarter, new Map());
|
||||
const qsMap = quarterToStatus.get(quarter)!;
|
||||
qsMap.set(status, (qsMap.get(status) || 0) + 1);
|
||||
|
||||
if (!statusToRating.has(status)) statusToRating.set(status, new Map());
|
||||
const srMap = statusToRating.get(status)!;
|
||||
srMap.set(ratingBucket, (srMap.get(ratingBucket) || 0) + 1);
|
||||
}
|
||||
|
||||
if (quarterMap.size === 0) return;
|
||||
this.hasData = true;
|
||||
this.totalBooks = books.length;
|
||||
|
||||
const sortedQuarters = [...quarterMap.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 8);
|
||||
|
||||
this.topQuarter = sortedQuarters[0]?.[0] || '';
|
||||
const topStatusEntry = [...statusMap.entries()].sort((a, b) => b[1] - a[1])[0];
|
||||
this.topStatus = topStatusEntry?.[0] || '';
|
||||
|
||||
const readCount = statusMap.get('Read') || 0;
|
||||
this.completionRate = books.length > 0 ? Math.round((readCount / books.length) * 100) + '%' : '0%';
|
||||
|
||||
const quarterColors = ['#42a5f5', '#26c6da', '#66bb6a', '#ffa726', '#ab47bc', '#ef5350', '#ec407a', '#7e57c2'];
|
||||
|
||||
const totalHeight = 420;
|
||||
const padding = 6;
|
||||
|
||||
const createColumnNodes = (
|
||||
entries: [string, number][],
|
||||
column: number,
|
||||
colors: Record<string, string> | string[]
|
||||
): SankeyNode[] => {
|
||||
const total = entries.reduce((s, e) => s + e[1], 0);
|
||||
let currentY = 30;
|
||||
return entries.map(([id, count], i) => {
|
||||
const height = Math.max(10, (count / total) * (totalHeight - entries.length * padding));
|
||||
const node: SankeyNode = {
|
||||
id, label: id, column,
|
||||
y: currentY, height,
|
||||
color: Array.isArray(colors) ? colors[i % colors.length] : (colors[id] || '#78909c'),
|
||||
count
|
||||
};
|
||||
currentY += height + padding;
|
||||
return node;
|
||||
});
|
||||
};
|
||||
|
||||
const quarterNodes = createColumnNodes(sortedQuarters, 0, quarterColors);
|
||||
const statusEntries = [...statusMap.entries()].sort((a, b) => b[1] - a[1]);
|
||||
const statusNodes = createColumnNodes(statusEntries, 1, statusColors);
|
||||
const ratingEntries = [...ratingMap.entries()].sort((a, b) => b[1] - a[1]);
|
||||
const ratingNodes = createColumnNodes(ratingEntries, 2, ratingColors);
|
||||
|
||||
this.nodes = [...quarterNodes, ...statusNodes, ...ratingNodes];
|
||||
this.links = [];
|
||||
|
||||
const findNode = (id: string, col: number) => this.nodes.find(n => n.id === id && n.column === col);
|
||||
|
||||
for (const [quarter, statusCounts] of quarterToStatus) {
|
||||
const qNode = findNode(quarter, 0);
|
||||
if (!qNode) continue;
|
||||
for (const [status, count] of statusCounts) {
|
||||
const sNode = findNode(status, 1);
|
||||
if (sNode) {
|
||||
this.links.push({source: qNode, target: sNode, value: count, color: qNode.color});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [status, ratingCounts] of statusToRating) {
|
||||
const sNode = findNode(status, 1);
|
||||
if (!sNode) continue;
|
||||
for (const [rating, count] of ratingCounts) {
|
||||
const rNode = findNode(rating, 2);
|
||||
if (rNode) {
|
||||
this.links.push({source: sNode, target: rNode, value: count, color: sNode.color});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private draw(): void {
|
||||
const canvas = this.canvasRef?.nativeElement;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const rect = canvas.parentElement!.getBoundingClientRect();
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
canvas.width = rect.width * dpr;
|
||||
canvas.height = 480 * dpr;
|
||||
canvas.style.width = rect.width + 'px';
|
||||
canvas.style.height = '480px';
|
||||
ctx.scale(dpr, dpr);
|
||||
|
||||
const width = rect.width;
|
||||
const nodeWidth = 18;
|
||||
const leftMargin = 100;
|
||||
const rightMargin = 110;
|
||||
const colX = [leftMargin, width * 0.45, width - rightMargin];
|
||||
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
|
||||
ctx.font = '11px Inter, sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(this.t.translate('statsUser.bookFlow.colAdded'), colX[0] + nodeWidth / 2, 18);
|
||||
ctx.fillText(this.t.translate('statsUser.bookFlow.colStatus'), colX[1] + nodeWidth / 2, 18);
|
||||
ctx.fillText(this.t.translate('statsUser.bookFlow.colRating'), colX[2] + nodeWidth / 2, 18);
|
||||
|
||||
const sourceOffsets = new Map<string, number>();
|
||||
const targetOffsets = new Map<string, number>();
|
||||
|
||||
for (const link of this.links) {
|
||||
const sKey = `${link.source.id}-${link.source.column}`;
|
||||
const tKey = `${link.target.id}-${link.target.column}`;
|
||||
const sOff = sourceOffsets.get(sKey) || 0;
|
||||
const tOff = targetOffsets.get(tKey) || 0;
|
||||
|
||||
const linkHeight = Math.max(1, (link.value / link.source.count) * link.source.height);
|
||||
const tLinkHeight = Math.max(1, (link.value / link.target.count) * link.target.height);
|
||||
|
||||
const x0 = colX[link.source.column] + nodeWidth;
|
||||
const y0 = link.source.y + sOff + linkHeight / 2;
|
||||
const x1 = colX[link.target.column];
|
||||
const y1 = link.target.y + tOff + tLinkHeight / 2;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x0, y0 - linkHeight / 2);
|
||||
const cpx = (x0 + x1) / 2;
|
||||
ctx.bezierCurveTo(cpx, y0 - linkHeight / 2, cpx, y1 - tLinkHeight / 2, x1, y1 - tLinkHeight / 2);
|
||||
ctx.lineTo(x1, y1 + tLinkHeight / 2);
|
||||
ctx.bezierCurveTo(cpx, y1 + tLinkHeight / 2, cpx, y0 + linkHeight / 2, x0, y0 + linkHeight / 2);
|
||||
ctx.closePath();
|
||||
|
||||
ctx.fillStyle = link.color + '55';
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = link.color + '30';
|
||||
ctx.lineWidth = 0.5;
|
||||
ctx.stroke();
|
||||
|
||||
sourceOffsets.set(sKey, sOff + linkHeight);
|
||||
targetOffsets.set(tKey, tOff + tLinkHeight);
|
||||
}
|
||||
|
||||
for (const node of this.nodes) {
|
||||
const x = colX[node.column];
|
||||
|
||||
ctx.fillStyle = node.color;
|
||||
ctx.globalAlpha = 0.92;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, node.y, nodeWidth, node.height, 3);
|
||||
ctx.fill();
|
||||
ctx.globalAlpha = 1;
|
||||
|
||||
ctx.strokeStyle = 'rgba(255, 255, 255, 0.15)';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, node.y, nodeWidth, node.height, 3);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
|
||||
ctx.font = '11px Inter, sans-serif';
|
||||
const labelX = node.column === 2 ? x + nodeWidth + 8 : x - 8;
|
||||
ctx.textAlign = node.column === 2 ? 'left' : 'right';
|
||||
ctx.textBaseline = 'middle';
|
||||
const label = node.label.length > 18 ? node.label.substring(0, 16) + '..' : node.label;
|
||||
ctx.fillText(`${label} (${node.count})`, labelX, node.y + node.height / 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.bookLength'">
|
||||
<div class="book-length-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-book book-length-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
@if (totalRatedBooks() > 0) {
|
||||
<div class="stats-badge">
|
||||
<span class="badge-value">{{ totalRatedBooks() }}</span>
|
||||
<span class="badge-label">{{ t('booksAnalyzed') }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (totalRatedBooks() > 0) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card">
|
||||
<span class="stat-value-sm">{{ sweetSpot() }}</span>
|
||||
<span class="stat-label">{{ t('sweetSpot') }}</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-value-sm">{{ highestRatedLength() }}</span>
|
||||
<span class="stat-label">{{ t('highestRated') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
.book-length-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: rgba(0, 188, 212, 0.15);
|
||||
border: 1px solid rgba(0, 188, 212, 0.3);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
|
||||
.badge-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: #00bcd4;
|
||||
}
|
||||
|
||||
.badge-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.book-length-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #00bcd4;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
flex: 1;
|
||||
|
||||
.stat-value-sm {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color, #ffffff);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 400px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 350px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.stats-badge .badge-value {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
}
|
||||
}
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ChartConfiguration, ChartData, ScatterDataPoint} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface BookScatterPoint extends ScatterDataPoint {
|
||||
bookTitle: string;
|
||||
readStatus: string;
|
||||
}
|
||||
|
||||
type LengthChartData = ChartData<'scatter', BookScatterPoint[], string>;
|
||||
|
||||
interface BookLengthMetrics {
|
||||
totalRatedBooks: number;
|
||||
sweetSpot: string;
|
||||
highestRatedLength: string;
|
||||
chartData: LengthChartData;
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, { bg: string; border: string }> = {
|
||||
'read': {bg: 'rgba(76, 175, 80, 0.7)', border: '#4caf50'},
|
||||
'reading': {bg: 'rgba(33, 150, 243, 0.7)', border: '#2196f3'},
|
||||
'abandoned': {bg: 'rgba(244, 67, 54, 0.7)', border: '#f44336'},
|
||||
'other': {bg: 'rgba(158, 158, 158, 0.7)', border: '#9e9e9e'}
|
||||
};
|
||||
|
||||
const PAGE_RANGES = [
|
||||
{label: '0-100', min: 0, max: 100},
|
||||
{label: '101-200', min: 101, max: 200},
|
||||
{label: '201-300', min: 201, max: 300},
|
||||
{label: '301-400', min: 301, max: 400},
|
||||
{label: '401-500', min: 401, max: 500},
|
||||
{label: '501+', min: 501, max: Infinity}
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-length-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './book-length-chart.component.html',
|
||||
styleUrls: ['./book-length-chart.component.scss']
|
||||
})
|
||||
export class BookLengthChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly metrics = computed<BookLengthMetrics>(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
return this.calculateMetrics(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'scatter' as const;
|
||||
public readonly sweetSpot = computed(() => this.metrics().sweetSpot);
|
||||
public readonly highestRatedLength = computed(() => this.metrics().highestRatedLength);
|
||||
public readonly totalRatedBooks = computed(() => this.metrics().totalRatedBooks);
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'scatter'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, right: 20, bottom: 10, left: 10}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.bookLength.axisPageCount'),
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 12, weight: 'bold'}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'}
|
||||
},
|
||||
y: {
|
||||
min: 0,
|
||||
max: 10,
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.bookLength.axisPersonalRating'),
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 12, weight: 'bold'}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
stepSize: 1,
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle',
|
||||
padding: 15
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#00bcd4',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const point = context[0].raw as BookScatterPoint;
|
||||
return point.bookTitle || this.t.translate('statsUser.bookLength.tooltipUnknownBook');
|
||||
},
|
||||
label: (context) => {
|
||||
const point = context.raw as BookScatterPoint;
|
||||
return [
|
||||
this.t.translate('statsUser.bookLength.tooltipPages', {count: point.x}),
|
||||
this.t.translate('statsUser.bookLength.tooltipRating', {rating: point.y}),
|
||||
this.t.translate('statsUser.bookLength.tooltipStatus', {status: point.readStatus})
|
||||
];
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
elements: {
|
||||
point: {
|
||||
radius: 6,
|
||||
hoverRadius: 9,
|
||||
borderWidth: 2
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed(() => this.metrics().chartData);
|
||||
|
||||
private calculateMetrics(books: Book[]): BookLengthMetrics {
|
||||
if (books.length === 0) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
const ratedBooks = books.filter(b =>
|
||||
b.personalRating != null && b.personalRating > 0 &&
|
||||
b.metadata?.pageCount != null && b.metadata.pageCount > 0
|
||||
);
|
||||
|
||||
const totalRatedBooks = ratedBooks.length;
|
||||
if (totalRatedBooks === 0) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
const grouped = new Map<string, { label: string; points: BookScatterPoint[] }>();
|
||||
for (const book of ratedBooks) {
|
||||
const statusKey = this.getStatusKey(book.readStatus);
|
||||
const statusLabel = this.getStatusLabel(book.readStatus);
|
||||
if (!grouped.has(statusKey)) grouped.set(statusKey, {label: statusLabel, points: []});
|
||||
grouped.get(statusKey)!.points.push({
|
||||
x: book.metadata!.pageCount!,
|
||||
y: book.personalRating!,
|
||||
bookTitle: book.metadata?.title || book.fileName || 'Unknown',
|
||||
readStatus: statusLabel
|
||||
});
|
||||
}
|
||||
|
||||
const datasets = Array.from(grouped.entries()).map(([key, {label, points}]) => {
|
||||
const colors = STATUS_COLORS[key] || STATUS_COLORS['other'];
|
||||
return {
|
||||
label: `${label} (${points.length})`,
|
||||
data: points,
|
||||
backgroundColor: colors.bg,
|
||||
borderColor: colors.border,
|
||||
pointRadius: 6,
|
||||
pointHoverRadius: 9,
|
||||
pointBorderWidth: 2
|
||||
};
|
||||
});
|
||||
|
||||
// Add trend line
|
||||
const allPoints = ratedBooks.map(b => ({x: b.metadata!.pageCount!, y: b.personalRating!}));
|
||||
const trend = this.computeTrendLine(allPoints);
|
||||
if (trend) {
|
||||
datasets.push({
|
||||
label: this.t.translate('statsUser.bookLength.trend'),
|
||||
data: trend as BookScatterPoint[],
|
||||
backgroundColor: 'transparent',
|
||||
borderColor: 'rgba(255, 255, 255, 0.4)',
|
||||
pointRadius: 0,
|
||||
pointHoverRadius: 0,
|
||||
pointBorderWidth: 0
|
||||
});
|
||||
}
|
||||
|
||||
const {sweetSpot, highestRatedLength} = this.computeStats(ratedBooks);
|
||||
return {
|
||||
totalRatedBooks,
|
||||
sweetSpot,
|
||||
highestRatedLength,
|
||||
chartData: {datasets}
|
||||
};
|
||||
}
|
||||
|
||||
private getStatusKey(status?: ReadStatus): string {
|
||||
if (!status) return 'other';
|
||||
switch (status) {
|
||||
case ReadStatus.READ:
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
return 'read';
|
||||
case ReadStatus.READING:
|
||||
case ReadStatus.RE_READING:
|
||||
return 'reading';
|
||||
case ReadStatus.ABANDONED:
|
||||
case ReadStatus.WONT_READ:
|
||||
return 'abandoned';
|
||||
default:
|
||||
return 'other';
|
||||
}
|
||||
}
|
||||
|
||||
private getStatusLabel(status?: ReadStatus): string {
|
||||
if (!status) return this.t.translate('statsUser.bookLength.statusOther');
|
||||
switch (status) {
|
||||
case ReadStatus.READ:
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
return this.t.translate('statsUser.bookLength.statusRead');
|
||||
case ReadStatus.READING:
|
||||
case ReadStatus.RE_READING:
|
||||
return this.t.translate('statsUser.bookLength.statusReading');
|
||||
case ReadStatus.ABANDONED:
|
||||
case ReadStatus.WONT_READ:
|
||||
return this.t.translate('statsUser.bookLength.statusAbandoned');
|
||||
default:
|
||||
return this.t.translate('statsUser.bookLength.statusOther');
|
||||
}
|
||||
}
|
||||
|
||||
private computeStats(books: Book[]): Pick<BookLengthMetrics, 'sweetSpot' | 'highestRatedLength'> {
|
||||
let bestRange = '';
|
||||
let bestAvg = 0;
|
||||
|
||||
for (const range of PAGE_RANGES) {
|
||||
const rangeBooks = books.filter(b =>
|
||||
b.metadata!.pageCount! >= range.min && b.metadata!.pageCount! <= range.max
|
||||
);
|
||||
if (rangeBooks.length >= 2) {
|
||||
const avg = rangeBooks.reduce((s, b) => s + b.personalRating!, 0) / rangeBooks.length;
|
||||
if (avg > bestAvg) {
|
||||
bestAvg = avg;
|
||||
bestRange = range.label;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sweetSpot = bestRange ? `${bestRange} pages (avg ${bestAvg.toFixed(1)})` : '-';
|
||||
const highestRated = books.reduce((a, b) => (a.personalRating! >= b.personalRating! ? a : b));
|
||||
const highestRatedLength = `${highestRated.metadata!.pageCount} pages`;
|
||||
|
||||
return {sweetSpot, highestRatedLength};
|
||||
}
|
||||
|
||||
private computeTrendLine(points: { x: number; y: number }[]): { x: number; y: number }[] | null {
|
||||
if (points.length < 2) return null;
|
||||
|
||||
const n = points.length;
|
||||
let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
|
||||
for (const p of points) {
|
||||
sumX += p.x;
|
||||
sumY += p.y;
|
||||
sumXY += p.x * p.y;
|
||||
sumX2 += p.x * p.x;
|
||||
}
|
||||
|
||||
const denominator = n * sumX2 - sumX * sumX;
|
||||
if (denominator === 0) return null;
|
||||
|
||||
const slope = (n * sumXY - sumX * sumY) / denominator;
|
||||
const intercept = (sumY - slope * sumX) / n;
|
||||
|
||||
const minX = Math.min(...points.map(p => p.x));
|
||||
const maxX = Math.max(...points.map(p => p.x));
|
||||
|
||||
return [
|
||||
{x: minX, y: Math.max(0, Math.min(10, slope * minX + intercept))},
|
||||
{x: maxX, y: Math.max(0, Math.min(10, slope * maxX + intercept))}
|
||||
];
|
||||
}
|
||||
|
||||
private emptyMetrics(): BookLengthMetrics {
|
||||
return {
|
||||
totalRatedBooks: 0,
|
||||
sweetSpot: '',
|
||||
highestRatedLength: '',
|
||||
chartData: {datasets: []}
|
||||
};
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.completionRace'">
|
||||
<div class="completion-race-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-flag completion-race-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
<div class="year-selector">
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(-1)"
|
||||
[title]="t('previousYear')">
|
||||
<i class="pi pi-chevron-left"></i>
|
||||
</button>
|
||||
<span class="current-year">{{ currentYear }}</span>
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(1)"
|
||||
[title]="t('nextYear')">
|
||||
<i class="pi pi-chevron-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalBooks > 0) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card">
|
||||
<span class="stat-value">{{ totalBooks }}</span>
|
||||
<span class="stat-label">{{ t('books') }}</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-value">{{ totalSessions }}</span>
|
||||
<span class="stat-label">{{ t('sessions') }}</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-value">{{ avgDaysToFinish }}d</span>
|
||||
<span class="stat-label">{{ t('avgDays') }}</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-value">{{ medianDaysToFinish }}d</span>
|
||||
<span class="stat-label">{{ t('medianDays') }}</span>
|
||||
</div>
|
||||
<div class="stat-card fastest">
|
||||
<span class="stat-value">{{ fastestDays }}</span>
|
||||
<span class="stat-subtitle">{{ fastestTitle }}</span>
|
||||
<span class="stat-label">{{ t('fastest') }}</span>
|
||||
</div>
|
||||
<div class="stat-card slowest">
|
||||
<span class="stat-value">{{ slowestDays }}</span>
|
||||
<span class="stat-subtitle">{{ slowestTitle }}</span>
|
||||
<span class="stat-label">{{ t('slowest') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (totalBooks === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData', { year: currentYear }) }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
.completion-race-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.completion-race-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #4caf50;
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
.year-nav-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 0.6rem;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.current-year {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
min-width: 4.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
min-width: 80px;
|
||||
flex: 1;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: #4caf50;
|
||||
}
|
||||
|
||||
.stat-subtitle {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-align: center;
|
||||
line-height: 1.3;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
&.fastest .stat-value {
|
||||
color: #4caf50;
|
||||
}
|
||||
|
||||
&.slowest .stat-value {
|
||||
color: #ff9800;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 400px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
.stat-card {
|
||||
min-width: 70px;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 350px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
gap: 0.5rem;
|
||||
|
||||
.stat-card {
|
||||
padding: 0.4rem 0.5rem;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {CompletionRaceResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface BookRace {
|
||||
bookId: number;
|
||||
bookTitle: string;
|
||||
sessions: { dayNumber: number; progress: number; date: string }[];
|
||||
totalDays: number;
|
||||
}
|
||||
|
||||
type RaceChartData = ChartData<'line', { x: number; y: number }[], number>;
|
||||
|
||||
const LINE_COLORS = [
|
||||
'#4caf50', '#2196f3', '#ff9800', '#e91e63', '#9c27b0',
|
||||
'#00bcd4', '#ff5722', '#8bc34a', '#3f51b5', '#ffc107',
|
||||
'#795548', '#607d8b', '#f44336', '#009688', '#cddc39'
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-completion-race-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './completion-race-chart.component.html',
|
||||
styleUrls: ['./completion-race-chart.component.scss']
|
||||
})
|
||||
export class CompletionRaceChartComponent implements OnInit, OnDestroy {
|
||||
@Input() initialYear: number = new Date().getFullYear();
|
||||
|
||||
public currentYear: number = new Date().getFullYear();
|
||||
public readonly chartType = 'line' as const;
|
||||
public readonly chartData$: Observable<RaceChartData>;
|
||||
public chartOptions: ChartConfiguration<'line'>['options'];
|
||||
|
||||
public totalBooks = 0;
|
||||
public avgDaysToFinish = 0;
|
||||
public medianDaysToFinish = 0;
|
||||
public totalSessions = 0;
|
||||
public fastestDays = '';
|
||||
public fastestTitle = '';
|
||||
public slowestDays = '';
|
||||
public slowestTitle = '';
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<RaceChartData>;
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<RaceChartData>({labels: [], datasets: []});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10, left: 10, right: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
boxWidth: 12,
|
||||
padding: 8,
|
||||
usePointStyle: true,
|
||||
pointStyle: 'line'
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
title: (context) => context[0].dataset.label || '',
|
||||
label: (context) => {
|
||||
const progress = (context.parsed.y ?? 0).toFixed(1);
|
||||
const day = context.parsed.x;
|
||||
return this.t.translate('statsUser.completionRace.tooltipDayProgress', {day, progress});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'linear',
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.completionRace.axisDaysSinceFirstSession'),
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 12, weight: 'bold'}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
min: 0,
|
||||
max: 100,
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.completionRace.axisProgress'),
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 12, weight: 'bold'}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
callback: (value) => `${value}%`
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
border: {display: false}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
mode: 'nearest',
|
||||
intersect: false
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.currentYear = this.initialYear;
|
||||
this.loadData(this.currentYear);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
public changeYear(delta: number): void {
|
||||
this.currentYear += delta;
|
||||
this.loadData(this.currentYear);
|
||||
}
|
||||
|
||||
private loadData(year: number): void {
|
||||
this.userStatsService.getCompletionRace(year)
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading completion race:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => this.processData(data));
|
||||
}
|
||||
|
||||
private processData(data: CompletionRaceResponse[]): void {
|
||||
const bookMap = new Map<number, { title: string; sessions: { date: Date; progress: number }[] }>();
|
||||
|
||||
for (const item of data) {
|
||||
if (!bookMap.has(item.bookId)) {
|
||||
bookMap.set(item.bookId, {title: item.bookTitle, sessions: []});
|
||||
}
|
||||
bookMap.get(item.bookId)!.sessions.push({
|
||||
date: new Date(item.sessionDate),
|
||||
progress: Math.min(item.endProgress, 100)
|
||||
});
|
||||
}
|
||||
|
||||
const races: BookRace[] = [];
|
||||
bookMap.forEach((value, bookId) => {
|
||||
if (value.sessions.length === 0) return;
|
||||
const firstDate = value.sessions[0].date;
|
||||
const sessionPoints = value.sessions.map(s => ({
|
||||
dayNumber: Math.floor((s.date.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24)),
|
||||
progress: s.progress,
|
||||
date: s.date.toLocaleDateString()
|
||||
}));
|
||||
const totalDays = sessionPoints.length > 0 ? sessionPoints[sessionPoints.length - 1].dayNumber : 0;
|
||||
races.push({bookId, bookTitle: value.title, sessions: sessionPoints, totalDays});
|
||||
});
|
||||
|
||||
this.totalBooks = races.length;
|
||||
|
||||
if (races.length > 0) {
|
||||
const days = races.map(r => r.totalDays).sort((a, b) => a - b);
|
||||
const fastest = races.reduce((a, b) => a.totalDays <= b.totalDays ? a : b);
|
||||
const slowest = races.reduce((a, b) => a.totalDays >= b.totalDays ? a : b);
|
||||
this.avgDaysToFinish = Math.round(days.reduce((a, b) => a + b, 0) / days.length);
|
||||
this.medianDaysToFinish = days.length % 2 === 0
|
||||
? Math.round((days[days.length / 2 - 1] + days[days.length / 2]) / 2)
|
||||
: days[Math.floor(days.length / 2)];
|
||||
this.totalSessions = races.reduce((sum, r) => sum + r.sessions.length, 0);
|
||||
this.fastestDays = `${fastest.totalDays}d`;
|
||||
this.fastestTitle = fastest.bookTitle.length > 25 ? fastest.bookTitle.substring(0, 25) + '...' : fastest.bookTitle;
|
||||
this.slowestDays = `${slowest.totalDays}d`;
|
||||
this.slowestTitle = slowest.bookTitle.length > 25 ? slowest.bookTitle.substring(0, 25) + '...' : slowest.bookTitle;
|
||||
} else {
|
||||
this.avgDaysToFinish = 0;
|
||||
this.medianDaysToFinish = 0;
|
||||
this.totalSessions = 0;
|
||||
this.fastestDays = '-';
|
||||
this.fastestTitle = '';
|
||||
this.slowestDays = '-';
|
||||
this.slowestTitle = '';
|
||||
}
|
||||
|
||||
const datasets = races.map((race, i) => {
|
||||
const color = LINE_COLORS[i % LINE_COLORS.length];
|
||||
return {
|
||||
label: race.bookTitle.length > 30 ? race.bookTitle.substring(0, 30) + '...' : race.bookTitle,
|
||||
data: race.sessions.map(s => ({x: s.dayNumber, y: s.progress})),
|
||||
borderColor: color,
|
||||
backgroundColor: color,
|
||||
fill: false,
|
||||
tension: 0.3,
|
||||
stepped: 'before' as const,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 5,
|
||||
borderWidth: 2
|
||||
};
|
||||
});
|
||||
|
||||
this.chartDataSubject.next({datasets});
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.completionTimeline'">
|
||||
<div class="completion-timeline-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar completion-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
<div class="year-selector">
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(-1)"
|
||||
[title]="t('previousYear')">
|
||||
<i class="pi pi-chevron-left"></i>
|
||||
</button>
|
||||
<span class="current-year">{{ currentYear }}</span>
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(1)"
|
||||
[title]="t('nextYear')">
|
||||
<i class="pi pi-chevron-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
.completion-timeline-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
.year-nav-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 0.6rem 0.6rem;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.current-year {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
min-width: 4.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.completion-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(251, 191, 36, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 350px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
justify-content: center;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
.current-year {
|
||||
font-size: 1rem;
|
||||
min-width: 4rem;
|
||||
}
|
||||
|
||||
.year-nav-btn {
|
||||
padding: 0.6rem 0.6rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {CompletionTimelineResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
type CompletionChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-completion-timeline-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, TranslocoDirective],
|
||||
templateUrl: './completion-timeline-chart.component.html',
|
||||
styleUrls: ['./completion-timeline-chart.component.scss']
|
||||
})
|
||||
export class CompletionTimelineChartComponent implements OnInit, OnDestroy {
|
||||
@Input() initialYear: number = new Date().getFullYear();
|
||||
|
||||
public currentYear: number = new Date().getFullYear();
|
||||
public readonly chartType = 'bar' as const;
|
||||
public readonly chartData$: Observable<CompletionChartData>;
|
||||
public readonly chartOptions: ChartConfiguration['options'];
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<CompletionChartData>;
|
||||
|
||||
private readonly monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<CompletionChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10, left: 10, right: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
boxWidth: 12,
|
||||
padding: 10
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const label = context.dataset.label || '';
|
||||
const value = context.parsed.y;
|
||||
const key = value !== 1 ? 'statsUser.completionTimeline.tooltipBooks' : 'statsUser.completionTimeline.tooltipBook';
|
||||
return this.t.translate(key, {label, value});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.completionTimeline.axisMonth'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {display: false},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.completionTimeline.axisNumberOfBooks'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.currentYear = this.initialYear;
|
||||
this.loadCompletionTimeline(this.currentYear);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
public changeYear(delta: number): void {
|
||||
this.currentYear += delta;
|
||||
this.loadCompletionTimeline(this.currentYear);
|
||||
}
|
||||
|
||||
private loadCompletionTimeline(year: number): void {
|
||||
this.userStatsService.getCompletionTimelineForYear(year)
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading completion timeline:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => {
|
||||
this.updateChartData(data);
|
||||
});
|
||||
}
|
||||
|
||||
private updateChartData(timeline: CompletionTimelineResponse[]): void {
|
||||
const monthlyData = new Map<number, CompletionTimelineResponse>();
|
||||
timeline.forEach(item => {
|
||||
monthlyData.set(item.month, item);
|
||||
});
|
||||
|
||||
const labels = this.monthNames;
|
||||
|
||||
const completedBooks = this.monthNames.map((_, index) => {
|
||||
const monthData = monthlyData.get(index + 1);
|
||||
if (!monthData) return 0;
|
||||
const read = monthData.statusBreakdown['READ'] || 0;
|
||||
const partiallyRead = monthData.statusBreakdown['PARTIALLY_READ'] || 0;
|
||||
return read + partiallyRead;
|
||||
});
|
||||
|
||||
const activeReading = this.monthNames.map((_, index) => {
|
||||
const monthData = monthlyData.get(index + 1);
|
||||
if (!monthData) return 0;
|
||||
const reading = monthData.statusBreakdown['READING'] || 0;
|
||||
const reReading = monthData.statusBreakdown['RE_READING'] || 0;
|
||||
return reading + reReading;
|
||||
});
|
||||
|
||||
const pausedBooks = this.monthNames.map((_, index) => {
|
||||
const monthData = monthlyData.get(index + 1);
|
||||
return monthData?.statusBreakdown['PAUSED'] || 0;
|
||||
});
|
||||
|
||||
const discontinuedBooks = this.monthNames.map((_, index) => {
|
||||
const monthData = monthlyData.get(index + 1);
|
||||
if (!monthData) return 0;
|
||||
const abandoned = monthData.statusBreakdown['ABANDONED'] || 0;
|
||||
const wontRead = monthData.statusBreakdown['WONT_READ'] || 0;
|
||||
return abandoned + wontRead;
|
||||
});
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: this.t.translate('statsUser.completionTimeline.completed'),
|
||||
data: completedBooks,
|
||||
backgroundColor: 'rgba(106, 176, 76, 0.8)',
|
||||
borderColor: 'rgba(106, 176, 76, 1)',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.completionTimeline.activeReading'),
|
||||
data: activeReading,
|
||||
backgroundColor: 'rgba(59, 130, 246, 0.8)',
|
||||
borderColor: 'rgba(59, 130, 246, 1)',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.completionTimeline.paused'),
|
||||
data: pausedBooks,
|
||||
backgroundColor: 'rgba(255, 193, 7, 0.8)',
|
||||
borderColor: 'rgba(255, 193, 7, 1)',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.completionTimeline.discontinued'),
|
||||
data: discontinuedBooks,
|
||||
backgroundColor: 'rgba(239, 68, 68, 0.8)',
|
||||
borderColor: 'rgba(239, 68, 68, 1)',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.favoriteDays'">
|
||||
<div class="favorite-days-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar-plus favorite-days-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
<div class="filter-controls">
|
||||
<p-select
|
||||
[options]="yearOptions"
|
||||
[(ngModel)]="selectedYear"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectYear')"
|
||||
[style]="{'min-width': '90px'}">
|
||||
</p-select>
|
||||
<p-select
|
||||
[options]="monthOptions"
|
||||
[(ngModel)]="selectedMonth"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectMonth')"
|
||||
[style]="{'min-width': '120px'}">
|
||||
</p-select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
.favorite-days-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.favorite-days-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(139, 92, 246, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
.filter-controls {
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
|
||||
::ng-deep p-select {
|
||||
width: 100%;
|
||||
|
||||
.p-select {
|
||||
width: 100% !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {FavoriteDaysResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
type FavoriteDaysChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-favorite-days-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Select, FormsModule, Tooltip, TranslocoDirective],
|
||||
templateUrl: './favorite-days-chart.component.html',
|
||||
styleUrls: ['./favorite-days-chart.component.scss']
|
||||
})
|
||||
export class FavoriteDaysChartComponent implements OnInit, OnDestroy {
|
||||
public readonly chartType = 'bar' as const;
|
||||
public readonly chartData$: Observable<FavoriteDaysChartData>;
|
||||
public readonly chartOptions: ChartConfiguration['options'];
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<FavoriteDaysChartData>;
|
||||
|
||||
private readonly allDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
|
||||
public selectedYear: number | null = null;
|
||||
public selectedMonth: number | null = null;
|
||||
public yearOptions: { label: string; value: number | null }[] = [];
|
||||
public monthOptions: { label: string; value: number | null }[] = [];
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<FavoriteDaysChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10, left: 10, right: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
boxWidth: 12,
|
||||
padding: 10
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const label = context.dataset.label || '';
|
||||
const value = context.parsed.y;
|
||||
const sessionsLabel = this.t.translate('statsUser.favoriteDays.sessions');
|
||||
if (label === sessionsLabel) {
|
||||
const key = value !== 1 ? 'statsUser.favoriteDays.tooltipSessionsPlural' : 'statsUser.favoriteDays.tooltipSessions';
|
||||
return this.t.translate(key, {label, value});
|
||||
} else {
|
||||
const hours = Math.floor(value);
|
||||
const minutes = Math.floor((value % 1) * 60);
|
||||
return `${label}: ${hours}h ${minutes}m`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.favoriteDays.axisDayOfWeek'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {display: false},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'left',
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.favoriteDays.axisNumberOfSessions'),
|
||||
color: 'rgba(139, 92, 246, 1)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
border: {display: false}
|
||||
},
|
||||
y1: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'right',
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.favoriteDays.axisDurationHours'),
|
||||
color: 'rgba(236, 72, 153, 1)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
callback: function (value) {
|
||||
return (typeof value === 'number' ? value.toFixed(1) : '0.0') + 'h';
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
drawOnChartArea: false
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
this.initializeYearOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadFavoriteDays();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private initializeYearOptions(): void {
|
||||
const currentYear = new Date().getFullYear();
|
||||
this.yearOptions = [{label: this.t.translate('statsUser.favoriteDays.allYears'), value: null}];
|
||||
for (let year = currentYear; year >= currentYear - 10; year--) {
|
||||
this.yearOptions.push({label: year.toString(), value: year});
|
||||
}
|
||||
const monthKeys = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
|
||||
this.monthOptions = [
|
||||
{label: this.t.translate('statsUser.favoriteDays.allMonths'), value: null},
|
||||
...monthKeys.map((key, i) => ({label: this.t.translate(`statsUser.favoriteDays.${key}`), value: i + 1}))
|
||||
];
|
||||
}
|
||||
|
||||
public onFilterChange(): void {
|
||||
this.loadFavoriteDays();
|
||||
}
|
||||
|
||||
private loadFavoriteDays(): void {
|
||||
const year = this.selectedYear ?? undefined;
|
||||
const month = this.selectedMonth ?? undefined;
|
||||
|
||||
this.userStatsService.getFavoriteDays(year, month)
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading favorite days:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => {
|
||||
this.updateChartData(data);
|
||||
});
|
||||
}
|
||||
|
||||
private updateChartData(favoriteDays: FavoriteDaysResponse[]): void {
|
||||
const dayMap = new Map<number, FavoriteDaysResponse>();
|
||||
favoriteDays.forEach(item => {
|
||||
dayMap.set(item.dayOfWeek - 1, item);
|
||||
});
|
||||
|
||||
const labels = this.allDays;
|
||||
const sessionCounts = this.allDays.map((_, index) => {
|
||||
const dayData = dayMap.get(index);
|
||||
return dayData?.sessionCount || 0;
|
||||
});
|
||||
|
||||
const durations = this.allDays.map((_, index) => {
|
||||
const dayData = dayMap.get(index);
|
||||
return dayData ? dayData.totalDurationSeconds / 3600 : 0; // Convert to hours
|
||||
});
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: this.t.translate('statsUser.favoriteDays.sessions'),
|
||||
data: sessionCounts,
|
||||
backgroundColor: 'rgba(139, 92, 246, 0.8)',
|
||||
borderColor: 'rgba(139, 92, 246, 1)',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6,
|
||||
yAxisID: 'y'
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.favoriteDays.durationHours'),
|
||||
data: durations,
|
||||
backgroundColor: 'rgba(236, 72, 153, 0.8)',
|
||||
borderColor: 'rgba(236, 72, 153, 1)',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6,
|
||||
yAxisID: 'y1'
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.genreStats'">
|
||||
<div class="genre-stats-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-bar genre-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
.genre-stats-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.genre-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(34, 197, 94, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {GenreStatsResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
type GenreChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-genre-stats-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './genre-stats-chart.component.html',
|
||||
styleUrls: ['./genre-stats-chart.component.scss']
|
||||
})
|
||||
export class GenreStatsChartComponent implements OnInit, OnDestroy {
|
||||
@Input() maxGenres: number = 35;
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public readonly chartData$: Observable<GenreChartData>;
|
||||
public readonly chartOptions: ChartConfiguration['options'];
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<GenreChartData>;
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<GenreChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const dataIndex = context.dataIndex;
|
||||
const dataset = context.dataset;
|
||||
const label = context.chart.data.labels?.[dataIndex] as string;
|
||||
const minutes = Math.floor((dataset.data[dataIndex] as number) / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const mins = minutes % 60;
|
||||
|
||||
const timeStr = hours > 0
|
||||
? `${hours}h ${mins}m`
|
||||
: `${mins}m`;
|
||||
|
||||
return `${label}: ${timeStr}`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.genreStats.axisGenres'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
maxRotation: 90,
|
||||
minRotation: 90,
|
||||
callback: (value, index) => {
|
||||
const label = this.chartDataSubject.value.labels?.[index] as string;
|
||||
const maxLength = 12;
|
||||
if (label && label.length > maxLength) {
|
||||
return label.substring(0, maxLength) + '...';
|
||||
}
|
||||
return label;
|
||||
}
|
||||
},
|
||||
grid: {display: false},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.genreStats.axisTimeRead'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
callback: (value) => {
|
||||
const seconds = value as number;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
const dayLabel = days === 1 ? this.t.translate('statsUser.genreStats.day') : this.t.translate('statsUser.genreStats.days');
|
||||
const hrLabel = (h: number) => h === 1 ? this.t.translate('statsUser.genreStats.hr') : this.t.translate('statsUser.genreStats.hrs');
|
||||
const minLabel = this.t.translate('statsUser.genreStats.min');
|
||||
const secLabel = this.t.translate('statsUser.genreStats.sec');
|
||||
|
||||
if (days > 0) {
|
||||
const remainingHours = hours % 24;
|
||||
if (remainingHours > 0) {
|
||||
return `${days} ${dayLabel} ${remainingHours} ${hrLabel(remainingHours)}`;
|
||||
}
|
||||
return `${days} ${dayLabel}`;
|
||||
} else if (hours > 0) {
|
||||
const remainingMinutes = minutes % 60;
|
||||
if (remainingMinutes > 0) {
|
||||
return `${hours} ${hrLabel(hours)} ${remainingMinutes} ${minLabel}`;
|
||||
}
|
||||
return `${hours} ${hrLabel(hours)}`;
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes} ${minLabel}`;
|
||||
}
|
||||
return `${seconds} ${secLabel}`;
|
||||
},
|
||||
stepSize: undefined,
|
||||
maxTicksLimit: 8
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadGenreStats();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private loadGenreStats(): void {
|
||||
this.userStatsService.getGenreStats()
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading genre stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => {
|
||||
this.updateChartData(data);
|
||||
});
|
||||
}
|
||||
|
||||
private updateChartData(genreStats: GenreStatsResponse[]): void {
|
||||
const sortedStats = [...genreStats]
|
||||
.sort((a, b) => b.totalDurationSeconds - a.totalDurationSeconds)
|
||||
.slice(0, this.maxGenres);
|
||||
|
||||
const labels = sortedStats.map(stat => stat.genre);
|
||||
const durations = sortedStats.map(stat => stat.totalDurationSeconds);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: this.t.translate('statsUser.genreStats.readingTime'),
|
||||
data: durations,
|
||||
backgroundColor: 'rgba(34, 197, 94, 0.8)',
|
||||
borderColor: 'rgba(34, 197, 94, 1)',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.pageTurner'">
|
||||
<div class="page-turner-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-bolt page-turner-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stats-row">
|
||||
<div class="stat-item">
|
||||
<span class="stat-value" [title]="stats.mostGripping">{{ stats.mostGripping | slice:0:18 }}</span>
|
||||
<span class="stat-label">{{ t('mostGripping') }}</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-value">{{ stats.avgGripScore }}</span>
|
||||
<span class="stat-label">{{ t('avgGripScore') }}</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-value" [title]="stats.guiltyPleasure">{{ stats.guiltyPleasure | slice:0:18 }}</span>
|
||||
<span class="stat-label">{{ t('guiltyPleasure') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (topBooks.length > 0) {
|
||||
<div class="top-books">
|
||||
@for (book of topBooks; track book.bookId; let i = $index) {
|
||||
<div class="top-book-card">
|
||||
<div class="book-rank">#{{ i + 1 }}</div>
|
||||
<div class="book-info">
|
||||
<span class="book-name">{{ book.bookTitle | slice:0:30 }}</span>
|
||||
<div class="book-indicators">
|
||||
<span class="indicator" [title]="t('sessionDurationTrend')">
|
||||
<i class="pi pi-clock"></i> {{ getAccelerationLabel(book.sessionAcceleration) }}
|
||||
</span>
|
||||
<span class="indicator" [title]="t('gapBetweenSessionsTrend')">
|
||||
<i class="pi pi-calendar"></i> {{ getGapLabel(book.gapReduction) }}
|
||||
</span>
|
||||
@if (book.finishBurst) {
|
||||
<span class="indicator burst">
|
||||
<i class="pi pi-forward"></i> {{ t('finishBurst') }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="book-score">{{ book.gripScore }}</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
.page-turner-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.page-turner-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(251, 146, 60, 1);
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-bottom: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.stat-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
flex: 1;
|
||||
min-width: 100px;
|
||||
|
||||
.stat-value {
|
||||
color: #ffffff;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.top-books {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.top-book-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
|
||||
.book-rank {
|
||||
color: rgba(251, 146, 60, 1);
|
||||
font-weight: 700;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.book-info {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
|
||||
.book-name {
|
||||
color: #ffffff;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
display: block;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.book-indicators {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
margin-top: 0.2rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.indicator {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.7rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
|
||||
&.burst {
|
||||
color: rgba(251, 146, 60, 0.9);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.book-score {
|
||||
color: rgba(251, 146, 60, 1);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 400px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.top-books {
|
||||
flex-direction: column;
|
||||
|
||||
.top-book-card {
|
||||
min-width: unset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header .chart-title h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
gap: 0.5rem;
|
||||
|
||||
.stat-item {
|
||||
min-width: 80px;
|
||||
padding: 0.4rem 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 350px;
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {PageTurnerScoreResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
type PageTurnerChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-page-turner-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './page-turner-chart.component.html',
|
||||
styleUrls: ['./page-turner-chart.component.scss']
|
||||
})
|
||||
export class PageTurnerChartComponent implements OnInit, OnDestroy {
|
||||
public readonly chartType = 'bar' as const;
|
||||
public readonly chartData$: Observable<PageTurnerChartData>;
|
||||
public readonly chartOptions: ChartConfiguration['options'];
|
||||
|
||||
public stats = {mostGripping: '', avgGripScore: 0, guiltyPleasure: ''};
|
||||
public topBooks: PageTurnerScoreResponse[] = [];
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<PageTurnerChartData>;
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<PageTurnerChartData>({labels: [], datasets: []});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
|
||||
this.chartOptions = {
|
||||
indexAxis: 'y',
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {padding: {top: 10, bottom: 10, left: 10, right: 10}},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: 'rgba(251, 146, 60, 0.8)',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
displayColors: false,
|
||||
padding: 16,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
label: () => ''
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.pageTurner.axisGripScore'),
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 13, weight: 'bold'}
|
||||
},
|
||||
min: 0,
|
||||
max: 100,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {display: false},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadData();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private loadData(): void {
|
||||
this.userStatsService.getPageTurnerScores()
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading page turner scores:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => {
|
||||
this.updateStats(data);
|
||||
this.updateChartData(data);
|
||||
});
|
||||
}
|
||||
|
||||
private updateStats(data: PageTurnerScoreResponse[]): void {
|
||||
if (data.length === 0) {
|
||||
this.stats = {mostGripping: '-', avgGripScore: 0, guiltyPleasure: '-'};
|
||||
this.topBooks = [];
|
||||
return;
|
||||
}
|
||||
|
||||
this.stats.mostGripping = data[0].bookTitle;
|
||||
this.stats.avgGripScore = Math.round(data.reduce((sum, d) => sum + d.gripScore, 0) / data.length);
|
||||
|
||||
const guiltyPleasure = data.find(d => d.gripScore >= 60 && d.personalRating != null && d.personalRating <= 3);
|
||||
this.stats.guiltyPleasure = guiltyPleasure?.bookTitle || '-';
|
||||
|
||||
this.topBooks = data.slice(0, 3);
|
||||
}
|
||||
|
||||
private updateChartData(data: PageTurnerScoreResponse[]): void {
|
||||
const top15 = data.slice(0, 15);
|
||||
|
||||
const labels = top15.map(d => d.bookTitle.length > 25 ? d.bookTitle.substring(0, 25) + '...' : d.bookTitle);
|
||||
const values = top15.map(d => d.gripScore);
|
||||
const bgColors = top15.map(d => {
|
||||
const t = d.gripScore / 100;
|
||||
const r = Math.round(59 + t * (239 - 59));
|
||||
const g = Math.round(130 + t * (68 - 130));
|
||||
const b = Math.round(246 + t * (68 - 246));
|
||||
return `rgba(${r}, ${g}, ${b}, 0.85)`;
|
||||
});
|
||||
|
||||
if (this.chartOptions?.plugins?.tooltip?.callbacks) {
|
||||
this.chartOptions.plugins.tooltip.callbacks.label = (context) => {
|
||||
const idx = context.dataIndex;
|
||||
const item = top15[idx];
|
||||
if (!item) return '';
|
||||
const lines = [
|
||||
this.t.translate('statsUser.pageTurner.tooltipGripScore', {score: item.gripScore}),
|
||||
this.t.translate('statsUser.pageTurner.tooltipSessions', {count: item.totalSessions}),
|
||||
this.t.translate('statsUser.pageTurner.tooltipAvgSession', {minutes: Math.round(item.avgSessionDurationSeconds / 60)}),
|
||||
];
|
||||
if (item.personalRating) {
|
||||
lines.push(this.t.translate('statsUser.pageTurner.tooltipRating', {rating: item.personalRating}));
|
||||
}
|
||||
return lines;
|
||||
};
|
||||
}
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.pageTurner.gripScore'),
|
||||
data: values,
|
||||
backgroundColor: bgColors,
|
||||
borderColor: bgColors.map(c => c.replace('0.85', '1')),
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.7
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
getAccelerationLabel(value: number): string {
|
||||
if (value > 5) return this.t.translate('statsUser.pageTurner.increasing');
|
||||
if (value < -5) return this.t.translate('statsUser.pageTurner.decreasing');
|
||||
return this.t.translate('statsUser.pageTurner.steady');
|
||||
}
|
||||
|
||||
getGapLabel(value: number): string {
|
||||
if (value < -2) return this.t.translate('statsUser.pageTurner.shrinking');
|
||||
if (value > 2) return this.t.translate('statsUser.pageTurner.growing');
|
||||
return this.t.translate('statsUser.pageTurner.steady');
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.peakHours'">
|
||||
<div class="peak-hours-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-clock peak-hours-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
<div class="filter-controls">
|
||||
<p-select
|
||||
[options]="yearOptions"
|
||||
[(ngModel)]="selectedYear"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectYear')"
|
||||
[style]="{'min-width': '100px'}">
|
||||
</p-select>
|
||||
<p-select
|
||||
[options]="monthOptions"
|
||||
[(ngModel)]="selectedMonth"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectMonth')"
|
||||
[style]="{'min-width': '130px'}">
|
||||
</p-select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
.peak-hours-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.peak-hours-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(34, 197, 94, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
.filter-controls {
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
|
||||
::ng-deep p-select {
|
||||
width: 100%;
|
||||
|
||||
.p-select {
|
||||
width: 100% !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {PeakHoursResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
type PeakHoursChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-peak-hours-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Select, FormsModule, Tooltip, TranslocoDirective],
|
||||
templateUrl: './peak-hours-chart.component.html',
|
||||
styleUrls: ['./peak-hours-chart.component.scss']
|
||||
})
|
||||
export class PeakHoursChartComponent implements OnInit, OnDestroy {
|
||||
public readonly chartType = 'line' as const;
|
||||
public readonly chartData$: Observable<PeakHoursChartData>;
|
||||
public readonly chartOptions: ChartConfiguration['options'];
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<PeakHoursChartData>;
|
||||
|
||||
public selectedYear: number | null = null;
|
||||
public selectedMonth: number | null = null;
|
||||
public yearOptions: { label: string; value: number | null }[] = [];
|
||||
public monthOptions: { label: string; value: number | null }[] = [];
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<PeakHoursChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10, left: 10, right: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
boxWidth: 12,
|
||||
padding: 10
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const label = context.dataset.label || '';
|
||||
const value = context.parsed.y;
|
||||
const sessionsLabel = this.t.translate('statsUser.peakHours.sessions');
|
||||
if (label === sessionsLabel) {
|
||||
const key = value !== 1 ? 'statsUser.peakHours.tooltipSessionsPlural' : 'statsUser.peakHours.tooltipSessions';
|
||||
return this.t.translate(key, {label, value});
|
||||
} else {
|
||||
return this.t.translate('statsUser.peakHours.tooltipMin', {label, value});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.peakHours.axisHourOfDay'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'left',
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.peakHours.axisNumberOfSessions'),
|
||||
color: 'rgba(34, 197, 94, 0.9)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
border: {display: false}
|
||||
},
|
||||
y1: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'right',
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.peakHours.axisAvgDuration'),
|
||||
color: 'rgba(251, 191, 36, 0.9)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 13,
|
||||
weight: 'bold'
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
callback: function (value) {
|
||||
return (typeof value === 'number' ? Math.round(value) : '0') + 'm';
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
drawOnChartArea: false
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
this.initializeYearOptions();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadPeakHours();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private initializeYearOptions(): void {
|
||||
const currentYear = new Date().getFullYear();
|
||||
this.yearOptions = [{label: this.t.translate('statsUser.peakHours.allYears'), value: null}];
|
||||
for (let year = currentYear; year >= currentYear - 10; year--) {
|
||||
this.yearOptions.push({label: year.toString(), value: year});
|
||||
}
|
||||
const monthKeys = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
|
||||
this.monthOptions = [
|
||||
{label: this.t.translate('statsUser.peakHours.allMonths'), value: null},
|
||||
...monthKeys.map((key, i) => ({label: this.t.translate(`statsUser.peakHours.${key}`), value: i + 1}))
|
||||
];
|
||||
}
|
||||
|
||||
public onFilterChange(): void {
|
||||
this.loadPeakHours();
|
||||
}
|
||||
|
||||
private loadPeakHours(): void {
|
||||
const year = this.selectedYear ?? undefined;
|
||||
const month = this.selectedMonth ?? undefined;
|
||||
|
||||
this.userStatsService.getPeakHours(year, month)
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading peak hours:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => {
|
||||
this.updateChartData(data);
|
||||
});
|
||||
}
|
||||
|
||||
private updateChartData(peakHours: PeakHoursResponse[]): void {
|
||||
const hourMap = new Map<number, PeakHoursResponse>();
|
||||
peakHours.forEach(item => {
|
||||
hourMap.set(item.hourOfDay, item);
|
||||
});
|
||||
|
||||
const allHours = Array.from({length: 24}, (_, i) => i);
|
||||
const labels = allHours.map(h => this.formatHour(h));
|
||||
|
||||
const sessionCounts = allHours.map(hour => {
|
||||
const hourData = hourMap.get(hour);
|
||||
return hourData?.sessionCount || 0;
|
||||
});
|
||||
|
||||
// Calculate average duration per session (in minutes) for each hour
|
||||
const avgDurations = allHours.map(hour => {
|
||||
const hourData = hourMap.get(hour);
|
||||
if (hourData && hourData.sessionCount > 0) {
|
||||
return Math.round(hourData.totalDurationSeconds / 60 / hourData.sessionCount);
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: this.t.translate('statsUser.peakHours.sessions'),
|
||||
data: sessionCounts,
|
||||
borderColor: 'rgba(34, 197, 94, 0.9)',
|
||||
backgroundColor: 'rgba(34, 197, 94, 0.1)',
|
||||
borderWidth: 2,
|
||||
tension: 0.4,
|
||||
fill: true,
|
||||
pointRadius: 4,
|
||||
pointHoverRadius: 6,
|
||||
pointBackgroundColor: 'rgba(34, 197, 94, 0.9)',
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 2,
|
||||
yAxisID: 'y'
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.peakHours.avgDurationMin'),
|
||||
data: avgDurations,
|
||||
borderColor: 'rgba(251, 191, 36, 0.9)',
|
||||
backgroundColor: 'rgba(251, 191, 36, 0.1)',
|
||||
borderWidth: 2,
|
||||
tension: 0.4,
|
||||
fill: true,
|
||||
pointRadius: 4,
|
||||
pointHoverRadius: 6,
|
||||
pointBackgroundColor: 'rgba(251, 191, 36, 0.9)',
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 2,
|
||||
yAxisID: 'y1'
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private formatHour(hour: number): string {
|
||||
if (hour === 0) return '12 AM';
|
||||
if (hour === 12) return '12 PM';
|
||||
if (hour < 12) return `${hour} AM`;
|
||||
return `${hour - 12} PM`;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.personalRating'">
|
||||
<div class="personal-rating-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-star-fill personal-rating-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
.personal-rating-container {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.personal-rating-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #FACC15;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
min-width: 300px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
min-width: 400px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
min-width: 350px;
|
||||
}
|
||||
}
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface RatingStats {
|
||||
ratingRange: string;
|
||||
count: number;
|
||||
averageRating: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#DC2626', // Red (rating 1)
|
||||
'#EA580C', // Red-orange (rating 2)
|
||||
'#F59E0B', // Orange (rating 3)
|
||||
'#EAB308', // Yellow-orange (rating 4)
|
||||
'#FACC15', // Yellow (rating 5)
|
||||
'#BEF264', // Yellow-green (rating 6)
|
||||
'#65A30D', // Green (rating 7)
|
||||
'#16A34A', // Green (rating 8)
|
||||
'#059669', // Teal-green (rating 9)
|
||||
'#2563EB' // Blue (rating 10)
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
hoverBorderWidth: 2,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
const RATING_RANGES = [
|
||||
{range: '1', min: 1.0, max: 1.0},
|
||||
{range: '2', min: 2.0, max: 2.0},
|
||||
{range: '3', min: 3.0, max: 3.0},
|
||||
{range: '4', min: 4.0, max: 4.0},
|
||||
{range: '5', min: 5.0, max: 5.0},
|
||||
{range: '6', min: 6.0, max: 6.0},
|
||||
{range: '7', min: 7.0, max: 7.0},
|
||||
{range: '8', min: 8.0, max: 8.0},
|
||||
{range: '9', min: 9.0, max: 9.0},
|
||||
{range: '10', min: 10.0, max: 10.0}
|
||||
] as const;
|
||||
|
||||
type RatingChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-personal-rating-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './personal-rating-chart.component.html',
|
||||
styleUrls: ['./personal-rating-chart.component.scss']
|
||||
})
|
||||
export class PersonalRatingChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly ratingStats = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.calculatePersonalRatingStats(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 25}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
title: (context) => this.t.translate('statsUser.personalRating.tooltipTitle', {label: context[0].label}),
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
const key = value === 1 ? 'statsUser.personalRating.tooltipBook' : 'statsUser.personalRating.tooltipBooks';
|
||||
return this.t.translate(key, {value});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.personalRating.axisPersonalRating'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {display: false},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.personalRating.axisNumberOfBooks'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
}
|
||||
},
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
stepSize: 1,
|
||||
maxTicksLimit: 8
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed<RatingChartData>(() => {
|
||||
try {
|
||||
const stats = this.ratingStats();
|
||||
const allLabels = RATING_RANGES.map(r => r.range);
|
||||
const dataValues = allLabels.map(label => {
|
||||
const stat = stats.find(s => s.ratingRange === label);
|
||||
return stat ? stat.count : 0;
|
||||
});
|
||||
const colors = allLabels.map((_, index) => CHART_COLORS[index % CHART_COLORS.length]);
|
||||
|
||||
return {
|
||||
labels: allLabels,
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.personalRating.booksByPersonalRating'),
|
||||
data: dataValues,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(color => color),
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
barPercentage: 0.8,
|
||||
categoryPercentage: 0.6
|
||||
}]
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error updating personal rating chart data:', error);
|
||||
return {
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.personalRating.booksByPersonalRating'),
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
private calculatePersonalRatingStats(books: Book[]): RatingStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processPersonalRatingStats(books);
|
||||
}
|
||||
|
||||
private processPersonalRatingStats(books: Book[]): RatingStats[] {
|
||||
const rangeCounts = new Map<string, { count: number, totalRating: number }>();
|
||||
RATING_RANGES.forEach(range => rangeCounts.set(range.range, {count: 0, totalRating: 0}));
|
||||
|
||||
books.forEach(book => {
|
||||
const personalRating = book.personalRating;
|
||||
|
||||
if (personalRating && personalRating > 0) {
|
||||
for (const range of RATING_RANGES) {
|
||||
if (personalRating >= range.min && personalRating <= range.max) {
|
||||
const rangeData = rangeCounts.get(range.range)!;
|
||||
rangeData.count++;
|
||||
rangeData.totalRating += personalRating;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Return all ratings, including those with 0 count
|
||||
return RATING_RANGES.map(range => {
|
||||
const data = rangeCounts.get(range.range)!;
|
||||
return {
|
||||
ratingRange: range.range,
|
||||
count: data.count,
|
||||
averageRating: data.count > 0 ? data.totalRating / data.count : 0
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.publicationEra'">
|
||||
<div class="publication-era-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-history publication-era-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
@if (hasData) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card best">
|
||||
<span class="stat-value">{{ bestDecade }}</span>
|
||||
<span class="stat-label">{{ t('bestDecade') }}</span>
|
||||
</div>
|
||||
<div class="stat-card avg">
|
||||
<span class="stat-value">{{ bestAvgRating }}/10</span>
|
||||
<span class="stat-label">{{ t('avgRating') }}</span>
|
||||
</div>
|
||||
<div class="stat-card total">
|
||||
<span class="stat-value">{{ totalRated }}</span>
|
||||
<span class="stat-label">{{ t('booksRated') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart [data]="chartData" [options]="chartOptions" [type]="chartType"></canvas>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
.publication-era-container { width: 100%; }
|
||||
.chart-header {
|
||||
display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.5rem;
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
h3 { color: var(--text-color, #ffffff); font-size: 1.25rem; font-weight: 500; margin: 0 0 0.5rem 0; display: flex; align-items: center; gap: 0.5rem; }
|
||||
.chart-description { color: var(--text-secondary-color); font-size: 0.9rem; margin: 0; line-height: 1.4; }
|
||||
}
|
||||
}
|
||||
.publication-era-icon { font-size: 1.5rem; color: #673ab7; }
|
||||
.stats-row {
|
||||
display: flex; gap: 0.75rem; margin-bottom: 1rem; flex-wrap: wrap;
|
||||
.stat-card {
|
||||
display: flex; flex-direction: column; align-items: center;
|
||||
background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px; padding: 0.5rem 1rem; flex: 1; min-width: 80px;
|
||||
.stat-value { font-size: 1.5rem; font-weight: 600; color: var(--text-color, #ffffff); }
|
||||
.stat-label { font-size: 0.75rem; color: var(--text-secondary-color); text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.25rem; }
|
||||
&.best .stat-value { color: #673ab7; }
|
||||
&.avg .stat-value { color: #ffc107; }
|
||||
&.total .stat-value { color: #42a5f5; }
|
||||
}
|
||||
}
|
||||
.chart-wrapper { position: relative; height: 350px; width: 100%; }
|
||||
.no-data-message {
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 3rem; text-align: center; color: var(--text-secondary-color);
|
||||
i { font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5; }
|
||||
p { font-size: 1rem; margin: 0 0 0.5rem 0; color: var(--text-color, #ffffff); }
|
||||
small { font-size: 0.85rem; opacity: 0.7; }
|
||||
}
|
||||
@media (max-width: 768px) { .chart-wrapper { height: 280px; } }
|
||||
@media (max-width: 480px) { .chart-header .chart-title h3 { font-size: 1rem; } }
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import {Component, effect, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-publication-era-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './publication-era-chart.component.html',
|
||||
styleUrls: ['./publication-era-chart.component.scss']
|
||||
})
|
||||
export class PublicationEraChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly syncChartEffect = effect(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.processData(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'line' as const;
|
||||
public hasData = false;
|
||||
public bestDecade = '';
|
||||
public bestAvgRating = 0;
|
||||
public totalRated = 0;
|
||||
|
||||
private readonly DECADE_COLORS = [
|
||||
'#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
|
||||
'#2196f3', '#00bcd4', '#009688', '#4caf50',
|
||||
'#8bc34a', '#ff9800'
|
||||
];
|
||||
|
||||
public chartData: ChartData<'line', number[], string> = {labels: [], datasets: []};
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'line'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: {duration: 400},
|
||||
layout: {padding: {top: 10, right: 10}},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true, position: 'bottom',
|
||||
labels: {color: 'rgba(255, 255, 255, 0.8)', font: {family: "'Inter', sans-serif", size: 11}, boxWidth: 12, padding: 12}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff', bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff', borderWidth: 1, cornerRadius: 6, padding: 10,
|
||||
callbacks: {
|
||||
label: (ctx) => {
|
||||
return `${ctx.dataset.label}: ${ctx.parsed.y} books`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
grid: {color: 'rgba(255, 255, 255, 0.08)'},
|
||||
ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}},
|
||||
title: {display: true, text: 'Rating Range', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
grid: {color: 'rgba(255, 255, 255, 0.08)'},
|
||||
ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}, stepSize: 1},
|
||||
title: {display: true, text: 'Books', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}}
|
||||
}
|
||||
},
|
||||
interaction: {mode: 'index', intersect: false}
|
||||
};
|
||||
|
||||
private processData(books: Book[]): void {
|
||||
if (books.length === 0) {
|
||||
this.hasData = false;
|
||||
this.bestDecade = '';
|
||||
this.bestAvgRating = 0;
|
||||
this.totalRated = 0;
|
||||
this.chartData = {labels: [], datasets: []};
|
||||
return;
|
||||
}
|
||||
|
||||
const ratedBooks = books.filter(b => b.metadata?.publishedDate && b.personalRating && b.personalRating > 0);
|
||||
if (ratedBooks.length < 3) return;
|
||||
|
||||
this.totalRated = ratedBooks.length;
|
||||
|
||||
const decadeData = new Map<string, Map<number, number>>();
|
||||
const decadeAvg = new Map<string, {total: number; count: number}>();
|
||||
const ratingLabels = ['1-2', '3-4', '5-6', '7-8', '9-10'];
|
||||
|
||||
for (const book of ratedBooks) {
|
||||
const pubYear = new Date(book.metadata!.publishedDate!).getFullYear();
|
||||
if (pubYear < 1900 || pubYear > 2030) continue;
|
||||
const decade = `${Math.floor(pubYear / 10) * 10}s`;
|
||||
const rating = book.personalRating!;
|
||||
const bucket = Math.min(4, Math.floor((rating - 1) / 2));
|
||||
|
||||
if (!decadeData.has(decade)) decadeData.set(decade, new Map());
|
||||
const dMap = decadeData.get(decade)!;
|
||||
dMap.set(bucket, (dMap.get(bucket) || 0) + 1);
|
||||
|
||||
if (!decadeAvg.has(decade)) decadeAvg.set(decade, {total: 0, count: 0});
|
||||
const avg = decadeAvg.get(decade)!;
|
||||
avg.total += rating;
|
||||
avg.count++;
|
||||
}
|
||||
|
||||
if (decadeData.size === 0) return;
|
||||
|
||||
const decades = [...decadeData.keys()].sort();
|
||||
let bestDec = '';
|
||||
let bestAvg = 0;
|
||||
for (const [dec, avg] of decadeAvg) {
|
||||
const a = avg.total / avg.count;
|
||||
if (a > bestAvg) { bestAvg = a; bestDec = dec; }
|
||||
}
|
||||
this.bestDecade = bestDec;
|
||||
this.bestAvgRating = Math.round(bestAvg * 10) / 10;
|
||||
|
||||
const datasets = decades.map((decade, i) => {
|
||||
const dMap = decadeData.get(decade)!;
|
||||
return {
|
||||
label: decade,
|
||||
data: ratingLabels.map((_, idx) => dMap.get(idx) || 0),
|
||||
borderColor: this.DECADE_COLORS[i % this.DECADE_COLORS.length],
|
||||
backgroundColor: this.DECADE_COLORS[i % this.DECADE_COLORS.length] + '20',
|
||||
borderWidth: 2.5,
|
||||
pointRadius: 5,
|
||||
pointBackgroundColor: this.DECADE_COLORS[i % this.DECADE_COLORS.length],
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 1.5,
|
||||
tension: 0.3,
|
||||
fill: false
|
||||
};
|
||||
});
|
||||
|
||||
this.chartData = {labels: ratingLabels, datasets};
|
||||
this.hasData = true;
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.ratingTaste'">
|
||||
<div class="rating-taste-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-scatter rating-taste-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
@if (totalRatedBooks() > 0) {
|
||||
<div class="stats-badge">
|
||||
<span class="badge-value">{{ totalRatedBooks() }}</span>
|
||||
<span class="badge-label">{{ t('booksAnalyzed') }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
<div class="quadrant-labels">
|
||||
<div class="quadrant-label top-left">{{ t('quadrantHiddenGems') }} 💎</div>
|
||||
<div class="quadrant-label top-right">{{ t('quadrantPopularFavorites') }} ⭐</div>
|
||||
<div class="quadrant-label bottom-left">{{ t('quadrantAgreedMisses') }} 👎</div>
|
||||
<div class="quadrant-label bottom-right">{{ t('quadrantOverrated') }} 📉</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (quadrants().length > 0) {
|
||||
<div class="taste-insights">
|
||||
<div class="insights-header">
|
||||
<h4>{{ t('tasteProfile') }}</h4>
|
||||
@if (averageDeviation() > 0) {
|
||||
<div class="deviation-badge" [class.unique]="averageDeviation() > 1" [class.mainstream]="averageDeviation() <= 0.5">
|
||||
<span class="deviation-label">{{ t('avgDeviation') }}</span>
|
||||
<span class="deviation-value">{{ averageDeviation().toFixed(2) }} ★</span>
|
||||
<span class="deviation-desc">
|
||||
@if (averageDeviation() > 1) {
|
||||
({{ t('uniqueTaste') }})
|
||||
} @else if (averageDeviation() <= 0.5) {
|
||||
({{ t('mainstream') }})
|
||||
} @else {
|
||||
({{ t('balanced') }})
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="quadrants-grid">
|
||||
@for (quadrant of quadrants(); track quadrant.name) {
|
||||
<div class="quadrant-card" [style.border-left-color]="quadrant.color">
|
||||
<div class="quadrant-header">
|
||||
<span class="quadrant-icon">{{ quadrant.icon }}</span>
|
||||
<span class="quadrant-name">{{ quadrant.name }}</span>
|
||||
<span class="quadrant-count" [style.background-color]="quadrant.color">{{ quadrant.count }}</span>
|
||||
</div>
|
||||
<p class="quadrant-description">{{ quadrant.description }}</p>
|
||||
<div class="quadrant-bar">
|
||||
<div class="bar-fill"
|
||||
[style.width.%]="(quadrant.count / totalRatedBooks()) * 100"
|
||||
[style.background-color]="quadrant.color">
|
||||
</div>
|
||||
</div>
|
||||
<span class="quadrant-percentage">{{ ((quadrant.count / totalRatedBooks()) * 100).toFixed(0) }}%</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
.rating-taste-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;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: rgba(156, 39, 176, 0.15);
|
||||
border: 1px solid rgba(156, 39, 176, 0.3);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
|
||||
.badge-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: #9c27b0;
|
||||
}
|
||||
|
||||
.badge-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rating-taste-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(156, 39, 176, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 500px;
|
||||
width: 100%;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
.quadrant-labels {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
pointer-events: none;
|
||||
|
||||
.quadrant-label {
|
||||
position: absolute;
|
||||
font-size: 0.7rem;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
font-weight: 500;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
|
||||
&.top-left {
|
||||
top: 60px;
|
||||
left: 60px;
|
||||
}
|
||||
|
||||
&.top-right {
|
||||
top: 60px;
|
||||
right: 30px;
|
||||
}
|
||||
|
||||
&.bottom-left {
|
||||
bottom: 60px;
|
||||
left: 60px;
|
||||
}
|
||||
|
||||
&.bottom-right {
|
||||
bottom: 60px;
|
||||
right: 30px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.taste-insights {
|
||||
margin-top: 1.5rem;
|
||||
|
||||
.insights-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
|
||||
h4 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.1rem;
|
||||
font-weight: 500;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.deviation-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.4rem 0.75rem;
|
||||
border-radius: 20px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
font-size: 0.85rem;
|
||||
|
||||
.deviation-label {
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
|
||||
.deviation-value {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.deviation-desc {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
&.unique {
|
||||
background: rgba(156, 39, 176, 0.2);
|
||||
border: 1px solid rgba(156, 39, 176, 0.3);
|
||||
|
||||
.deviation-value {
|
||||
color: #9c27b0;
|
||||
}
|
||||
}
|
||||
|
||||
&.mainstream {
|
||||
background: rgba(76, 175, 80, 0.2);
|
||||
border: 1px solid rgba(76, 175, 80, 0.3);
|
||||
|
||||
.deviation-value {
|
||||
color: #4caf50;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.quadrants-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.quadrant-card {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-left: 4px solid;
|
||||
position: relative;
|
||||
|
||||
.quadrant-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.quadrant-icon {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.quadrant-name {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
font-size: 0.95rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.quadrant-count {
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
color: #ffffff;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 12px;
|
||||
min-width: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.quadrant-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.8rem;
|
||||
margin: 0 0 0.75rem 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.quadrant-bar {
|
||||
height: 4px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 0.25rem;
|
||||
|
||||
.bar-fill {
|
||||
height: 100%;
|
||||
border-radius: 2px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.quadrant-percentage {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 420px;
|
||||
|
||||
.quadrant-labels {
|
||||
.quadrant-label {
|
||||
font-size: 0.6rem;
|
||||
padding: 0.15rem 0.35rem;
|
||||
|
||||
&.top-left {
|
||||
top: 50px;
|
||||
left: 40px;
|
||||
}
|
||||
|
||||
&.top-right {
|
||||
top: 50px;
|
||||
right: 15px;
|
||||
}
|
||||
|
||||
&.bottom-left {
|
||||
bottom: 50px;
|
||||
left: 40px;
|
||||
}
|
||||
|
||||
&.bottom-right {
|
||||
bottom: 50px;
|
||||
right: 15px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.taste-insights {
|
||||
.quadrants-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-badge {
|
||||
.badge-value {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 350px;
|
||||
}
|
||||
|
||||
.taste-insights {
|
||||
.insights-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ChartConfiguration, ChartData, ScatterDataPoint} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface TasteQuadrant {
|
||||
name: string;
|
||||
description: string;
|
||||
count: number;
|
||||
color: string;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
interface BookDataPoint extends ScatterDataPoint {
|
||||
bookTitle: string;
|
||||
personalRating: number;
|
||||
personalRatingNormalized: number;
|
||||
externalRating: number;
|
||||
quadrant: string;
|
||||
}
|
||||
|
||||
type RatingTasteChartData = ChartData<'scatter', BookDataPoint[], string>;
|
||||
|
||||
interface RatingTasteMetrics {
|
||||
quadrants: TasteQuadrant[];
|
||||
totalRatedBooks: number;
|
||||
averageDeviation: number;
|
||||
chartData: RatingTasteChartData;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-rating-taste-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './rating-taste-chart.component.html',
|
||||
styleUrls: ['./rating-taste-chart.component.scss']
|
||||
})
|
||||
export class RatingTasteChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly metrics = computed<RatingTasteMetrics>(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
return this.calculateMetrics(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
});
|
||||
|
||||
public readonly chartType = 'scatter' as const;
|
||||
public readonly quadrants = computed(() => this.metrics().quadrants);
|
||||
public readonly totalRatedBooks = computed(() => this.metrics().totalRatedBooks);
|
||||
public readonly averageDeviation = computed(() => this.metrics().averageDeviation);
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'scatter'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 20, right: 20, bottom: 10, left: 10}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
min: 0,
|
||||
max: 5,
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.ratingTaste.axisExternalRating'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
stepSize: 1,
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)',
|
||||
drawTicks: true
|
||||
}
|
||||
},
|
||||
y: {
|
||||
min: 0,
|
||||
max: 5,
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.ratingTaste.axisPersonalRating'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
stepSize: 1,
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)',
|
||||
drawTicks: true
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle',
|
||||
padding: 15
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#9c27b0',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const point = context[0].raw as BookDataPoint;
|
||||
return point.bookTitle || this.t.translate('statsUser.ratingTaste.tooltipUnknownBook');
|
||||
},
|
||||
label: (context) => {
|
||||
const point = context.raw as BookDataPoint;
|
||||
const diff = point.personalRatingNormalized - point.externalRating;
|
||||
const diffText = diff > 0 ? `+${diff.toFixed(1)}` : diff.toFixed(1);
|
||||
return [
|
||||
this.t.translate('statsUser.ratingTaste.tooltipYourRating', {rating: point.personalRating, normalized: point.personalRatingNormalized.toFixed(1)}),
|
||||
this.t.translate('statsUser.ratingTaste.tooltipExternalRating', {rating: point.externalRating.toFixed(1)}),
|
||||
this.t.translate('statsUser.ratingTaste.tooltipDifference', {diff: diffText}),
|
||||
this.t.translate('statsUser.ratingTaste.tooltipCategory', {category: point.quadrant})
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
elements: {
|
||||
point: {
|
||||
radius: 6,
|
||||
hoverRadius: 9,
|
||||
borderWidth: 2
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed(() => this.metrics().chartData);
|
||||
|
||||
private calculateMetrics(books: Book[], selectedLibraryId: string | number | null): RatingTasteMetrics {
|
||||
if (books.length === 0) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(books, selectedLibraryId);
|
||||
const ratedBooks = this.getBooksWithBothRatings(filteredBooks);
|
||||
|
||||
if (ratedBooks.length === 0) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
const totalRatedBooks = ratedBooks.length;
|
||||
const dataPoints = this.categorizeBooks(ratedBooks);
|
||||
const chartData = this.buildChartData(dataPoints);
|
||||
const {quadrants, averageDeviation} = this.calculateStatistics(dataPoints);
|
||||
|
||||
return {
|
||||
quadrants,
|
||||
totalRatedBooks,
|
||||
averageDeviation,
|
||||
chartData
|
||||
};
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private getBooksWithBothRatings(books: Book[]): Book[] {
|
||||
return books.filter(book => {
|
||||
const hasPersonalRating = book.personalRating && book.personalRating > 0;
|
||||
const hasExternalRating = this.getExternalRating(book) > 0;
|
||||
return hasPersonalRating && hasExternalRating;
|
||||
});
|
||||
}
|
||||
|
||||
private getExternalRating(book: Book): number {
|
||||
const ratings: number[] = [];
|
||||
|
||||
if (book.metadata?.goodreadsRating) ratings.push(book.metadata.goodreadsRating);
|
||||
if (book.metadata?.amazonRating) ratings.push(book.metadata.amazonRating);
|
||||
if (book.metadata?.hardcoverRating) ratings.push(book.metadata.hardcoverRating);
|
||||
if (book.metadata?.lubimyczytacRating) ratings.push(book.metadata.lubimyczytacRating);
|
||||
if (book.metadata?.ranobedbRating) ratings.push(book.metadata.ranobedbRating);
|
||||
|
||||
if (ratings.length > 0) {
|
||||
return ratings.reduce((sum, rating) => sum + rating, 0) / ratings.length;
|
||||
}
|
||||
|
||||
if (book.metadata?.rating) return book.metadata.rating;
|
||||
return 0;
|
||||
}
|
||||
|
||||
private categorizeBooks(books: Book[]): Map<string, BookDataPoint[]> {
|
||||
const categories = new Map<string, BookDataPoint[]>([
|
||||
[this.t.translate('statsUser.ratingTaste.quadrantHiddenGems'), []],
|
||||
[this.t.translate('statsUser.ratingTaste.quadrantPopularFavorites'), []],
|
||||
[this.t.translate('statsUser.ratingTaste.quadrantOverrated'), []],
|
||||
[this.t.translate('statsUser.ratingTaste.quadrantAgreedMisses'), []]
|
||||
]);
|
||||
|
||||
books.forEach(book => {
|
||||
const personalRating = book.personalRating!;
|
||||
// Normalize personal rating from 1-10 to 1-5 scale for comparison
|
||||
const personalRatingNormalized = personalRating / 2;
|
||||
const externalRating = this.getExternalRating(book);
|
||||
const bookTitle = book.metadata?.title || book.fileName || 'Unknown';
|
||||
|
||||
// Use normalized rating (3 is midpoint on 1-5 scale) for quadrant calculation
|
||||
let quadrant: string;
|
||||
if (personalRatingNormalized >= 3 && externalRating >= 3) {
|
||||
quadrant = this.t.translate('statsUser.ratingTaste.quadrantPopularFavorites');
|
||||
} else if (personalRatingNormalized >= 3 && externalRating < 3) {
|
||||
quadrant = this.t.translate('statsUser.ratingTaste.quadrantHiddenGems');
|
||||
} else if (personalRatingNormalized < 3 && externalRating >= 3) {
|
||||
quadrant = this.t.translate('statsUser.ratingTaste.quadrantOverrated');
|
||||
} else {
|
||||
quadrant = this.t.translate('statsUser.ratingTaste.quadrantAgreedMisses');
|
||||
}
|
||||
|
||||
const dataPoint: BookDataPoint = {
|
||||
x: externalRating,
|
||||
y: personalRatingNormalized,
|
||||
bookTitle,
|
||||
personalRating,
|
||||
personalRatingNormalized,
|
||||
externalRating,
|
||||
quadrant
|
||||
};
|
||||
|
||||
categories.get(quadrant)!.push(dataPoint);
|
||||
});
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
private buildChartData(dataPoints: Map<string, BookDataPoint[]>): RatingTasteChartData {
|
||||
const pf = this.t.translate('statsUser.ratingTaste.quadrantPopularFavorites');
|
||||
const hg = this.t.translate('statsUser.ratingTaste.quadrantHiddenGems');
|
||||
const or = this.t.translate('statsUser.ratingTaste.quadrantOverrated');
|
||||
const am = this.t.translate('statsUser.ratingTaste.quadrantAgreedMisses');
|
||||
const quadrantColors: Record<string, { bg: string, border: string }> = {
|
||||
[pf]: {bg: 'rgba(76, 175, 80, 0.7)', border: '#4caf50'},
|
||||
[hg]: {bg: 'rgba(156, 39, 176, 0.7)', border: '#9c27b0'},
|
||||
[or]: {bg: 'rgba(255, 152, 0, 0.7)', border: '#ff9800'},
|
||||
[am]: {bg: 'rgba(158, 158, 158, 0.7)', border: '#9e9e9e'}
|
||||
};
|
||||
|
||||
const datasets = Array.from(dataPoints.entries())
|
||||
.filter(([_, points]) => points.length > 0)
|
||||
.map(([label, points]) => ({
|
||||
label: `${label} (${points.length})`,
|
||||
data: points,
|
||||
backgroundColor: quadrantColors[label].bg,
|
||||
borderColor: quadrantColors[label].border,
|
||||
pointRadius: 6,
|
||||
pointHoverRadius: 9,
|
||||
pointBorderWidth: 2
|
||||
}));
|
||||
|
||||
return {datasets};
|
||||
}
|
||||
|
||||
private calculateStatistics(dataPoints: Map<string, BookDataPoint[]>): Pick<RatingTasteMetrics, 'quadrants' | 'averageDeviation'> {
|
||||
const pfKey = this.t.translate('statsUser.ratingTaste.quadrantPopularFavorites');
|
||||
const hgKey = this.t.translate('statsUser.ratingTaste.quadrantHiddenGems');
|
||||
const orKey = this.t.translate('statsUser.ratingTaste.quadrantOverrated');
|
||||
const amKey = this.t.translate('statsUser.ratingTaste.quadrantAgreedMisses');
|
||||
const quadrantInfo: Record<string, { description: string, icon: string, color: string }> = {
|
||||
[pfKey]: {
|
||||
description: this.t.translate('statsUser.ratingTaste.quadrantDescPopularFavorites'),
|
||||
icon: '⭐',
|
||||
color: '#4caf50'
|
||||
},
|
||||
[hgKey]: {
|
||||
description: this.t.translate('statsUser.ratingTaste.quadrantDescHiddenGems'),
|
||||
icon: '💎',
|
||||
color: '#9c27b0'
|
||||
},
|
||||
[orKey]: {
|
||||
description: this.t.translate('statsUser.ratingTaste.quadrantDescOverrated'),
|
||||
icon: '📉',
|
||||
color: '#ff9800'
|
||||
},
|
||||
[amKey]: {
|
||||
description: this.t.translate('statsUser.ratingTaste.quadrantDescAgreedMisses'),
|
||||
icon: '👎',
|
||||
color: '#9e9e9e'
|
||||
}
|
||||
};
|
||||
|
||||
const quadrants = Array.from(dataPoints.entries()).map(([name, points]) => ({
|
||||
name,
|
||||
description: quadrantInfo[name].description,
|
||||
count: points.length,
|
||||
color: quadrantInfo[name].color,
|
||||
icon: quadrantInfo[name].icon
|
||||
}));
|
||||
|
||||
// Calculate average deviation from external ratings (using normalized personal rating)
|
||||
let totalDeviation = 0;
|
||||
let totalPoints = 0;
|
||||
dataPoints.forEach(points => {
|
||||
points.forEach(point => {
|
||||
totalDeviation += Math.abs(point.personalRatingNormalized - point.externalRating);
|
||||
totalPoints++;
|
||||
});
|
||||
});
|
||||
const averageDeviation = totalPoints > 0 ? totalDeviation / totalPoints : 0;
|
||||
|
||||
return {quadrants, averageDeviation};
|
||||
}
|
||||
|
||||
private emptyMetrics(): RatingTasteMetrics {
|
||||
return {
|
||||
quadrants: [],
|
||||
totalRatedBooks: 0,
|
||||
averageDeviation: 0,
|
||||
chartData: {datasets: []}
|
||||
};
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readStatus'">
|
||||
<div class="read-status-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-book read-status-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
.read-status-container {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.read-status-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #17a2b8;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
min-width: 300px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
min-width: 400px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
min-width: 350px;
|
||||
}
|
||||
}
|
||||
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData, Chart} from 'chart.js';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface ReadingStatusStats {
|
||||
status: string;
|
||||
rawStatus: ReadStatus;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
const STATUS_COLOR_MAP: Record<string, string> = {
|
||||
[ReadStatus.UNREAD]: '#6c757d',
|
||||
[ReadStatus.READING]: '#17a2b8',
|
||||
[ReadStatus.RE_READING]: '#6f42c1',
|
||||
[ReadStatus.READ]: '#28a745',
|
||||
[ReadStatus.PARTIALLY_READ]: '#ffc107',
|
||||
[ReadStatus.PAUSED]: '#fd7e14',
|
||||
[ReadStatus.WONT_READ]: '#dc3545',
|
||||
[ReadStatus.ABANDONED]: '#e74c3c',
|
||||
[ReadStatus.UNSET]: '#343a40'
|
||||
} as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
type StatusChartData = ChartData<'doughnut', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-read-status-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './read-status-chart.component.html',
|
||||
styleUrls: ['./read-status-chart.component.scss']
|
||||
})
|
||||
export class ReadStatusChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly readingStatusStats = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.calculateReadingStatusStats(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'doughnut' as const;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 15}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
padding: 15,
|
||||
usePointStyle: true,
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
generateLabels: this.generateLegendLabels.bind(this)
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
title: (context) => context[0]?.label || '',
|
||||
label: (context) => {
|
||||
const dataIndex = context.dataIndex;
|
||||
const dataset = context.dataset;
|
||||
const value = dataset.data[dataIndex] as number;
|
||||
const label = context.chart.data.labels?.[dataIndex] || '';
|
||||
const total = (dataset.data as number[]).reduce((a: number, b: number) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
return this.t.translate('statsUser.readStatus.tooltipLabel', {label, value, percentage});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed<StatusChartData>(() => {
|
||||
try {
|
||||
const stats = this.readingStatusStats();
|
||||
const labels = stats.map(s => s.status);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
const colors = stats.map(s => STATUS_COLOR_MAP[s.rawStatus] || '#6c757d');
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
data: dataValues,
|
||||
backgroundColor: colors.length > 0 ? colors : [...Object.values(STATUS_COLOR_MAP)],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
return {
|
||||
labels: [],
|
||||
datasets: [{
|
||||
data: [],
|
||||
backgroundColor: [...Object.values(STATUS_COLOR_MAP)],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
private calculateReadingStatusStats(books: Book[]): ReadingStatusStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processReadingStatusStats(books);
|
||||
}
|
||||
|
||||
private processReadingStatusStats(books: Book[]): ReadingStatusStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const statusMap = this.buildStatusMap(books);
|
||||
return this.convertMapToStats(statusMap, books.length);
|
||||
}
|
||||
|
||||
private buildStatusMap(books: Book[]): Map<ReadStatus, number> {
|
||||
const statusMap = new Map<ReadStatus, number>();
|
||||
|
||||
for (const book of books) {
|
||||
const rawStatus = book.readStatus;
|
||||
const status: ReadStatus = Object.values(ReadStatus).includes(rawStatus as ReadStatus)
|
||||
? (rawStatus as ReadStatus)
|
||||
: ReadStatus.UNSET;
|
||||
|
||||
statusMap.set(status, (statusMap.get(status) || 0) + 1);
|
||||
}
|
||||
|
||||
return statusMap;
|
||||
}
|
||||
|
||||
private convertMapToStats(statusMap: Map<ReadStatus, number>, totalBooks: number): ReadingStatusStats[] {
|
||||
return Array.from(statusMap.entries())
|
||||
.map(([status, count]) => ({
|
||||
status: this.formatReadStatus(status),
|
||||
rawStatus: status,
|
||||
count,
|
||||
percentage: Number(((count / totalBooks) * 100).toFixed(1))
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
private formatReadStatus(status: ReadStatus | null | undefined): string {
|
||||
const STATUS_MAPPING: Record<string, string> = {
|
||||
[ReadStatus.UNREAD]: this.t.translate('statsUser.readStatus.unread'),
|
||||
[ReadStatus.READING]: this.t.translate('statsUser.readStatus.currentlyReading'),
|
||||
[ReadStatus.RE_READING]: this.t.translate('statsUser.readStatus.reReading'),
|
||||
[ReadStatus.READ]: this.t.translate('statsUser.readStatus.read'),
|
||||
[ReadStatus.PARTIALLY_READ]: this.t.translate('statsUser.readStatus.partiallyRead'),
|
||||
[ReadStatus.PAUSED]: this.t.translate('statsUser.readStatus.paused'),
|
||||
[ReadStatus.WONT_READ]: this.t.translate('statsUser.readStatus.wontRead'),
|
||||
[ReadStatus.ABANDONED]: this.t.translate('statsUser.readStatus.abandoned'),
|
||||
[ReadStatus.UNSET]: this.t.translate('statsUser.readStatus.noStatus')
|
||||
};
|
||||
|
||||
if (!status) return this.t.translate('statsUser.readStatus.noStatus');
|
||||
return STATUS_MAPPING[status] ?? this.t.translate('statsUser.readStatus.noStatus');
|
||||
}
|
||||
|
||||
private generateLegendLabels(chart: Chart) {
|
||||
const data = chart.data;
|
||||
if (!data.labels?.length || !data.datasets?.[0]?.data?.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dataset = data.datasets[0];
|
||||
const dataValues = dataset.data as number[];
|
||||
|
||||
return data.labels.map((label: unknown, index: number) => {
|
||||
const isVisible = typeof chart.getDataVisibility === 'function'
|
||||
? chart.getDataVisibility(index)
|
||||
: !((chart.getDatasetMeta && (chart.getDatasetMeta(0)?.data?.[index] as any)?.hidden) || false);
|
||||
|
||||
return {
|
||||
text: `${String(label)} (${dataValues[index]})`,
|
||||
fillStyle: (dataset.backgroundColor as string[])[index],
|
||||
strokeStyle: '#ffffff',
|
||||
lineWidth: 1,
|
||||
hidden: !isVisible,
|
||||
index,
|
||||
fontColor: '#ffffff'
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readingClock'">
|
||||
<div class="reading-clock-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-clock reading-clock-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (hasData) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card peak">
|
||||
<span class="stat-value">{{ peakHour }}</span>
|
||||
<span class="stat-label">{{ t('peakHour') }}</span>
|
||||
</div>
|
||||
<div class="stat-card total">
|
||||
<span class="stat-value">{{ totalHoursRead }}h</span>
|
||||
<span class="stat-label">{{ t('totalRead') }}</span>
|
||||
</div>
|
||||
<div class="stat-card type">
|
||||
<span class="stat-value">{{ readerType }}</span>
|
||||
<span class="stat-label">{{ t('readerType') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (!hasData) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
.reading-clock-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.reading-clock-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #42a5f5;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
flex: 1;
|
||||
min-width: 80px;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
&.peak .stat-value {
|
||||
color: #ff9800;
|
||||
}
|
||||
|
||||
&.total .stat-value {
|
||||
color: #42a5f5;
|
||||
}
|
||||
|
||||
&.type .stat-value {
|
||||
color: #9c27b0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 350px;
|
||||
aspect-ratio: 1;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header .chart-title h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
gap: 0.5rem;
|
||||
|
||||
.stat-card {
|
||||
padding: 0.4rem 0.5rem;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 280px;
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {PeakHoursResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
type ClockChartData = ChartData<'polarArea', number[], string>;
|
||||
|
||||
const HOUR_LABELS = [
|
||||
'12am', '1am', '2am', '3am', '4am', '5am',
|
||||
'6am', '7am', '8am', '9am', '10am', '11am',
|
||||
'12pm', '1pm', '2pm', '3pm', '4pm', '5pm',
|
||||
'6pm', '7pm', '8pm', '9pm', '10pm', '11pm'
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-clock-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-clock-chart.component.html',
|
||||
styleUrls: ['./reading-clock-chart.component.scss']
|
||||
})
|
||||
export class ReadingClockChartComponent implements OnInit, OnDestroy {
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'polarArea' as const;
|
||||
public peakHour = '';
|
||||
public totalHoursRead = 0;
|
||||
public readerType = '';
|
||||
public hasData = false;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'polarArea'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => HOUR_LABELS[context[0].dataIndex],
|
||||
label: (context) => {
|
||||
const minutes = context.parsed.r;
|
||||
if (minutes >= 60) {
|
||||
const hrs = Math.floor(minutes / 60);
|
||||
const mins = Math.round(minutes % 60);
|
||||
return this.t.translate('statsUser.readingClock.tooltipReading', {time: `${hrs}h ${mins}m`});
|
||||
}
|
||||
return this.t.translate('statsUser.readingClock.tooltipReading', {time: `${Math.round(minutes)}m`});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
r: {
|
||||
ticks: {display: false},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
pointLabels: {
|
||||
display: true,
|
||||
color: 'rgba(255, 255, 255, 0.7)',
|
||||
font: {family: "'Inter', sans-serif", size: 10}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<ClockChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<ClockChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userStatsService.getPeakHours()
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading peak hours:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => this.processData(data));
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private processData(data: PeakHoursResponse[]): void {
|
||||
if (!data || data.length === 0) {
|
||||
this.hasData = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.hasData = true;
|
||||
|
||||
// Build 24-hour array
|
||||
const hourMinutes = new Array(24).fill(0);
|
||||
let totalSeconds = 0;
|
||||
let peakIdx = 0;
|
||||
let peakVal = 0;
|
||||
|
||||
for (const entry of data) {
|
||||
const minutes = entry.totalDurationSeconds / 60;
|
||||
hourMinutes[entry.hourOfDay] = minutes;
|
||||
totalSeconds += entry.totalDurationSeconds;
|
||||
if (minutes > peakVal) {
|
||||
peakVal = minutes;
|
||||
peakIdx = entry.hourOfDay;
|
||||
}
|
||||
}
|
||||
|
||||
this.peakHour = HOUR_LABELS[peakIdx];
|
||||
this.totalHoursRead = Math.round(totalSeconds / 3600);
|
||||
|
||||
// Night owl vs early bird
|
||||
const nightHours = [20, 21, 22, 23, 0, 1, 2];
|
||||
const morningHours = [5, 6, 7, 8, 9, 10, 11];
|
||||
const nightTotal = nightHours.reduce((sum, h) => sum + hourMinutes[h], 0);
|
||||
const morningTotal = morningHours.reduce((sum, h) => sum + hourMinutes[h], 0);
|
||||
|
||||
if (nightTotal > morningTotal * 1.2) {
|
||||
this.readerType = this.t.translate('statsUser.readingClock.nightOwl');
|
||||
} else if (morningTotal > nightTotal * 1.2) {
|
||||
this.readerType = this.t.translate('statsUser.readingClock.earlyBird');
|
||||
} else {
|
||||
this.readerType = this.t.translate('statsUser.readingClock.balanced');
|
||||
}
|
||||
|
||||
// Generate colors: cool blues for low, warm oranges for peak
|
||||
const maxMinutes = Math.max(...hourMinutes, 1);
|
||||
const colors = hourMinutes.map(minutes => {
|
||||
const ratio = minutes / maxMinutes;
|
||||
if (ratio >= 0.7) return 'rgba(255, 152, 0, 0.8)'; // Warm orange
|
||||
if (ratio >= 0.4) return 'rgba(255, 193, 7, 0.7)'; // Yellow
|
||||
if (ratio >= 0.15) return 'rgba(100, 181, 246, 0.6)'; // Light blue
|
||||
return 'rgba(66, 133, 244, 0.35)'; // Cool blue
|
||||
});
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels: HOUR_LABELS,
|
||||
datasets: [{
|
||||
data: hourMinutes,
|
||||
backgroundColor: colors,
|
||||
borderColor: colors.map(c => c.replace(/[\d.]+\)$/, '1)')),
|
||||
borderWidth: 1
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readingDebt'">
|
||||
<div class="reading-debt-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-bar reading-debt-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
@if (hasData) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card backlog">
|
||||
<span class="stat-value">{{ currentBacklog }}</span>
|
||||
<span class="stat-label">{{ t('currentBacklog') }}</span>
|
||||
</div>
|
||||
<div class="stat-card trend">
|
||||
<span class="stat-value">{{ trend }}</span>
|
||||
<span class="stat-label">{{ t('trendLabel') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart [data]="chartData" [options]="chartOptions" [type]="chartType"></canvas>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
.reading-debt-container { width: 100%; }
|
||||
.chart-header {
|
||||
display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.5rem;
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
h3 { color: var(--text-color, #ffffff); font-size: 1.25rem; font-weight: 500; margin: 0 0 0.5rem 0; display: flex; align-items: center; gap: 0.5rem; }
|
||||
.chart-description { color: var(--text-secondary-color); font-size: 0.9rem; margin: 0; line-height: 1.4; }
|
||||
}
|
||||
}
|
||||
.reading-debt-icon { font-size: 1.5rem; color: #ef5350; }
|
||||
.stats-row {
|
||||
display: flex; gap: 0.75rem; margin-bottom: 1rem; flex-wrap: wrap;
|
||||
.stat-card {
|
||||
display: flex; flex-direction: column; align-items: center;
|
||||
background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px; padding: 0.5rem 1rem; flex: 1; min-width: 80px;
|
||||
.stat-value { font-size: 1.5rem; font-weight: 600; color: var(--text-color, #ffffff); }
|
||||
.stat-label { font-size: 0.75rem; color: var(--text-secondary-color); text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.25rem; }
|
||||
&.backlog .stat-value { color: #ffc107; }
|
||||
&.trend .stat-value { color: #42a5f5; }
|
||||
}
|
||||
}
|
||||
.chart-wrapper { position: relative; height: 350px; width: 100%; }
|
||||
.no-data-message {
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 3rem; text-align: center; color: var(--text-secondary-color);
|
||||
i { font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5; }
|
||||
p { font-size: 1rem; margin: 0 0 0.5rem 0; color: var(--text-color, #ffffff); }
|
||||
small { font-size: 0.85rem; opacity: 0.7; }
|
||||
}
|
||||
@media (max-width: 768px) { .chart-wrapper { height: 280px; } }
|
||||
@media (max-width: 480px) { .chart-header .chart-title h3 { font-size: 1rem; } }
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import {Component, effect, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-debt-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-debt-chart.component.html',
|
||||
styleUrls: ['./reading-debt-chart.component.scss']
|
||||
})
|
||||
export class ReadingDebtChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly syncChartEffect = effect(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.processData(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public hasData = false;
|
||||
public currentBacklog = 0;
|
||||
public trend = '';
|
||||
|
||||
public chartData: ChartData<'bar', number[], string> = {labels: [], datasets: []};
|
||||
|
||||
public chartOptions: ChartConfiguration<'bar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: {duration: 400},
|
||||
layout: {padding: {top: 10}},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true, position: 'bottom',
|
||||
labels: {color: 'rgba(255, 255, 255, 0.8)', font: {family: "'Inter', sans-serif", size: 11}, boxWidth: 12, padding: 15}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff', bodyColor: '#ffffff', borderColor: '#ffffff',
|
||||
borderWidth: 1, cornerRadius: 6, padding: 10
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
grid: {color: 'rgba(255, 255, 255, 0.08)'},
|
||||
ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 10}}
|
||||
},
|
||||
y: {
|
||||
grid: {color: 'rgba(255, 255, 255, 0.08)'},
|
||||
ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}}
|
||||
},
|
||||
y1: {
|
||||
position: 'right',
|
||||
grid: {drawOnChartArea: false},
|
||||
ticks: {color: 'rgba(255, 193, 7, 0.8)', font: {size: 11}}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private processData(books: ReturnType<BookService['books']>): void {
|
||||
if (books.length === 0) {
|
||||
this.hasData = false;
|
||||
this.currentBacklog = 0;
|
||||
this.trend = '';
|
||||
this.chartData = {labels: [], datasets: []};
|
||||
return;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const monthlyAdded = new Map<string, number>();
|
||||
const monthlyFinished = new Map<string, number>();
|
||||
const months: string[] = [];
|
||||
const monthLabels: string[] = [];
|
||||
const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
|
||||
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
months.push(key);
|
||||
monthLabels.push(`${monthNames[d.getMonth()]} ${String(d.getFullYear()).slice(2)}`);
|
||||
monthlyAdded.set(key, 0);
|
||||
monthlyFinished.set(key, 0);
|
||||
}
|
||||
|
||||
for (const book of books) {
|
||||
if (book.addedOn) {
|
||||
const d = new Date(book.addedOn);
|
||||
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
if (monthlyAdded.has(key)) monthlyAdded.set(key, monthlyAdded.get(key)! + 1);
|
||||
}
|
||||
if (book.dateFinished) {
|
||||
const d = new Date(book.dateFinished);
|
||||
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
if (monthlyFinished.has(key)) monthlyFinished.set(key, monthlyFinished.get(key)! + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const added = months.map(m => monthlyAdded.get(m) || 0);
|
||||
const finished = months.map(m => monthlyFinished.get(m) || 0);
|
||||
|
||||
if (added.every(v => v === 0) && finished.every(v => v === 0)) {
|
||||
this.hasData = false;
|
||||
this.currentBacklog = 0;
|
||||
this.trend = '';
|
||||
this.chartData = {labels: [], datasets: []};
|
||||
return;
|
||||
}
|
||||
|
||||
const backlog: number[] = [];
|
||||
let running = 0;
|
||||
for (let i = 0; i < months.length; i++) {
|
||||
running += added[i] - finished[i];
|
||||
backlog.push(running);
|
||||
}
|
||||
this.currentBacklog = running;
|
||||
this.trend = running > (backlog[0] || 0) ? this.t.translate('statsUser.readingDebt.growing') : this.t.translate('statsUser.readingDebt.shrinking');
|
||||
|
||||
this.chartData = {
|
||||
labels: monthLabels,
|
||||
datasets: [
|
||||
{
|
||||
label: this.t.translate('statsUser.readingDebt.booksAdded'),
|
||||
data: added,
|
||||
backgroundColor: 'rgba(239, 83, 80, 0.7)',
|
||||
borderColor: '#ef5350',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
order: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.readingDebt.booksFinished'),
|
||||
data: finished,
|
||||
backgroundColor: 'rgba(102, 187, 106, 0.7)',
|
||||
borderColor: '#66bb6a',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
order: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.readingDebt.backlog'),
|
||||
data: backlog,
|
||||
type: 'line' as const,
|
||||
borderColor: '#ffc107',
|
||||
backgroundColor: 'rgba(255, 193, 7, 0.1)',
|
||||
borderWidth: 2,
|
||||
pointRadius: 3,
|
||||
pointBackgroundColor: '#ffc107',
|
||||
fill: false,
|
||||
tension: 0.3,
|
||||
yAxisID: 'y1',
|
||||
order: 1
|
||||
} as any
|
||||
]
|
||||
};
|
||||
this.hasData = true;
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readingDna'">
|
||||
<div class="reading-dna-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-line reading-dna-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
@if (personalityInsights().length > 0) {
|
||||
<div class="personality-insights">
|
||||
<h4>{{ t('personalityTraits') }}</h4>
|
||||
<div class="insights-grid">
|
||||
@for (insight of personalityInsights(); track insight.trait) {
|
||||
<div class="insight-card">
|
||||
<div class="insight-header">
|
||||
<span class="insight-trait">{{ insight.trait }}</span>
|
||||
<span class="insight-score" [style.color]="insight.color">{{ insight.score.toFixed(0) }}%</span>
|
||||
</div>
|
||||
<div class="insight-progress">
|
||||
<div class="progress-bar" [style.width.%]="insight.score" [style.background-color]="insight.color"></div>
|
||||
</div>
|
||||
<p class="insight-description">{{ insight.description }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
.reading-dna-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.reading-dna-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(79, 195, 247, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 450px;
|
||||
width: 100%;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.personality-insights {
|
||||
margin-top: 2rem;
|
||||
|
||||
h4 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.1rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
.insight-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.insight-trait {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.insight-score {
|
||||
font-weight: 600;
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-progress {
|
||||
height: 6px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
border-radius: 3px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.85rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 350px;
|
||||
}
|
||||
|
||||
.personality-insights {
|
||||
.insights-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
}
|
||||
}
|
||||
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface ReadingDNAProfile {
|
||||
adventurous: number;
|
||||
perfectionist: number;
|
||||
intellectual: number;
|
||||
emotional: number;
|
||||
patient: number;
|
||||
social: number;
|
||||
nostalgic: number;
|
||||
ambitious: number;
|
||||
}
|
||||
|
||||
interface PersonalityInsight {
|
||||
trait: string;
|
||||
score: number;
|
||||
description: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
type ReadingDNAChartData = ChartData<'radar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-dna-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-dna-chart.component.html',
|
||||
styleUrls: ['./reading-dna-chart.component.scss']
|
||||
})
|
||||
export class ReadingDNAChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly profile = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.calculateReadingDNAData(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'radar' as const;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'radar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 15}
|
||||
},
|
||||
scales: {
|
||||
r: {
|
||||
beginAtZero: true,
|
||||
min: 0,
|
||||
max: 100,
|
||||
ticks: {
|
||||
stepSize: 20,
|
||||
color: 'rgba(255, 255, 255, 0.6)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
backdropColor: 'transparent',
|
||||
showLabelBackdrop: false
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.2)',
|
||||
circular: true
|
||||
},
|
||||
angleLines: {
|
||||
color: 'rgba(255, 255, 255, 0.3)'
|
||||
},
|
||||
pointLabels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
padding: 25,
|
||||
callback: (label: string) => {
|
||||
const traitKeys = ['adventurous', 'perfectionist', 'intellectual', 'emotional', 'patient', 'social', 'nostalgic', 'ambitious'];
|
||||
const icons = ['🌟', '💎', '🧠', '💖', '🕰️', '👥', '📚', '🚀'];
|
||||
const translatedLabels = traitKeys.map(k => this.t.translate(`statsUser.readingDna.traits.${k}`));
|
||||
const idx = translatedLabels.indexOf(label);
|
||||
return [idx >= 0 ? icons[idx] : '', label];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#e91e63',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 16,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const label = context[0]?.label || '';
|
||||
return this.t.translate('statsUser.readingDna.tooltipPersonality', {label});
|
||||
},
|
||||
label: (context) => {
|
||||
const score = context.parsed.r;
|
||||
const insight = this.personalityInsights().find(i => i.trait === context.label);
|
||||
|
||||
return [
|
||||
this.t.translate('statsUser.readingDna.tooltipScore', {score}),
|
||||
'',
|
||||
insight ? insight.description : this.t.translate('statsUser.readingDna.tooltipDefaultDescription')
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
},
|
||||
elements: {
|
||||
line: {
|
||||
borderWidth: 3,
|
||||
tension: 0.1
|
||||
},
|
||||
point: {
|
||||
radius: 5,
|
||||
hoverRadius: 8,
|
||||
borderWidth: 3,
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.8)'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly traitKeys = ['adventurous', 'perfectionist', 'intellectual', 'emotional', 'patient', 'social', 'nostalgic', 'ambitious'];
|
||||
public readonly chartData = computed<ReadingDNAChartData>(() => {
|
||||
const profile = this.profile();
|
||||
if (!profile) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const data = [
|
||||
profile.adventurous,
|
||||
profile.perfectionist,
|
||||
profile.intellectual,
|
||||
profile.emotional,
|
||||
profile.patient,
|
||||
profile.social,
|
||||
profile.nostalgic,
|
||||
profile.ambitious
|
||||
];
|
||||
|
||||
const gradientColors = [
|
||||
'#e91e63', '#2196f3', '#00bcd4', '#ff9800',
|
||||
'#9c27b0', '#3f51b5', '#673ab7', '#009688'
|
||||
];
|
||||
|
||||
const translatedLabels = this.traitKeys.map(k => this.t.translate(`statsUser.readingDna.traits.${k}`));
|
||||
|
||||
return {
|
||||
labels: translatedLabels,
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.readingDna.readingDnaProfile'),
|
||||
data,
|
||||
backgroundColor: 'rgba(233, 30, 99, 0.2)',
|
||||
borderColor: '#e91e63',
|
||||
borderWidth: 3,
|
||||
pointBackgroundColor: gradientColors,
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 3,
|
||||
pointRadius: 5,
|
||||
pointHoverRadius: 8,
|
||||
fill: true
|
||||
}]
|
||||
};
|
||||
});
|
||||
public readonly personalityInsights = computed(() => {
|
||||
const profile = this.profile();
|
||||
return profile ? this.buildPersonalityInsights(profile) : [];
|
||||
});
|
||||
|
||||
private calculateReadingDNAData(books: Book[]): ReadingDNAProfile | null {
|
||||
if (books.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.analyzeReadingDNA(books);
|
||||
}
|
||||
|
||||
private analyzeReadingDNA(books: Book[]): ReadingDNAProfile | null {
|
||||
if (books.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
adventurous: this.calculateAdventurousScore(books),
|
||||
perfectionist: this.calculatePerfectionistScore(books),
|
||||
intellectual: this.calculateIntellectualScore(books),
|
||||
emotional: this.calculateEmotionalScore(books),
|
||||
patient: this.calculatePatienceScore(books),
|
||||
social: this.calculateSocialScore(books),
|
||||
nostalgic: this.calculateNostalgicScore(books),
|
||||
ambitious: this.calculateAmbitiousScore(books)
|
||||
};
|
||||
}
|
||||
|
||||
// Genre diversity + language variety
|
||||
private calculateAdventurousScore(books: Book[]): number {
|
||||
const genres = new Set<string>();
|
||||
const languages = new Set<string>();
|
||||
|
||||
books.forEach(book => {
|
||||
book.metadata?.categories?.forEach(cat => genres.add(cat.toLowerCase()));
|
||||
if (book.metadata?.language) languages.add(book.metadata.language);
|
||||
});
|
||||
|
||||
// Having unique genres equal to 40% of book count = max genre diversity
|
||||
const diversityRatio = genres.size / Math.max(1, books.length * 0.4);
|
||||
const genreScore = Math.min(75, diversityRatio * 75);
|
||||
|
||||
// Each language beyond the first adds 12.5 pts
|
||||
const languageScore = Math.min(25, Math.max(0, languages.size - 1) * 12.5);
|
||||
|
||||
return Math.min(100, Math.round(genreScore + languageScore));
|
||||
}
|
||||
|
||||
// Completion rate + high personal ratings
|
||||
private calculatePerfectionistScore(books: Book[]): number {
|
||||
const completedBooks = books.filter(b => b.readStatus === ReadStatus.READ);
|
||||
const completionRate = completedBooks.length / books.length;
|
||||
|
||||
const ratedBooks = books.filter(book => book.personalRating);
|
||||
const highRatedBooks = ratedBooks.filter(book => book.personalRating! >= 4);
|
||||
const highRatingRate = ratedBooks.length > 0 ? highRatedBooks.length / ratedBooks.length : 0;
|
||||
|
||||
return Math.min(100, Math.round(completionRate * 60 + highRatingRate * 40));
|
||||
}
|
||||
|
||||
// Non-fiction/academic genre proportion + long books
|
||||
private calculateIntellectualScore(books: Book[]): number {
|
||||
const intellectualGenres = [
|
||||
'philosophy', 'history', 'biography', 'politics', 'psychology',
|
||||
'economics', 'mathematics', 'engineering', 'medicine', 'law',
|
||||
'education', 'sociology', 'nonfiction', 'non-fiction', 'academic'
|
||||
];
|
||||
|
||||
const intellectualBooks = books.filter(book =>
|
||||
this.bookMatchesGenres(book, intellectualGenres)
|
||||
);
|
||||
|
||||
const longBooks = books.filter(book =>
|
||||
book.metadata?.pageCount && book.metadata.pageCount > 400
|
||||
);
|
||||
|
||||
const intellectualRate = intellectualBooks.length / books.length;
|
||||
const longBookRate = longBooks.length / books.length;
|
||||
|
||||
return Math.min(100, Math.round(intellectualRate * 70 + longBookRate * 30));
|
||||
}
|
||||
|
||||
// Emotionally-driven genre proportion + rating engagement
|
||||
private calculateEmotionalScore(books: Book[]): number {
|
||||
const emotionalGenres = [
|
||||
'romance', 'memoir', 'poetry', 'drama', 'self-help',
|
||||
'autobiography', 'literary fiction', 'coming of age'
|
||||
];
|
||||
|
||||
const emotionalBooks = books.filter(book =>
|
||||
this.bookMatchesGenres(book, emotionalGenres)
|
||||
);
|
||||
|
||||
const ratedBooks = books.filter(book => book.personalRating);
|
||||
const ratingEngagement = ratedBooks.length / books.length;
|
||||
const emotionalRate = emotionalBooks.length / books.length;
|
||||
|
||||
return Math.min(100, Math.round(emotionalRate * 70 + ratingEngagement * 30));
|
||||
}
|
||||
|
||||
// Long books + series reading + in-progress commitment
|
||||
private calculatePatienceScore(books: Book[]): number {
|
||||
const longBooks = books.filter(book =>
|
||||
book.metadata?.pageCount && book.metadata.pageCount > 500
|
||||
);
|
||||
|
||||
const seriesBooks = books.filter(book =>
|
||||
book.metadata?.seriesName && book.metadata?.seriesNumber
|
||||
);
|
||||
|
||||
const progressBooks = books.filter(book => this.getBookProgress(book) > 50);
|
||||
|
||||
const longBookRate = longBooks.length / books.length;
|
||||
const seriesRate = seriesBooks.length / books.length;
|
||||
const progressRate = progressBooks.length / books.length;
|
||||
|
||||
return Math.min(100, Math.round(longBookRate * 40 + seriesRate * 35 + progressRate * 25));
|
||||
}
|
||||
|
||||
// Popular/mainstream genre proportion + high review counts
|
||||
private calculateSocialScore(books: Book[]): number {
|
||||
const mainstreamGenres = [
|
||||
'thriller', 'mystery', 'crime', 'suspense', 'horror',
|
||||
'fantasy', 'science fiction', 'adventure', 'true crime',
|
||||
'humor', 'graphic novel', 'manga', 'comic'
|
||||
];
|
||||
|
||||
const mainstreamBooks = books.filter(book =>
|
||||
this.bookMatchesGenres(book, mainstreamGenres)
|
||||
);
|
||||
|
||||
const popularBooks = books.filter(book => {
|
||||
const m = book.metadata;
|
||||
if (!m) return false;
|
||||
return (m.goodreadsReviewCount && m.goodreadsReviewCount > 10000) ||
|
||||
(m.amazonReviewCount && m.amazonReviewCount > 2000);
|
||||
});
|
||||
|
||||
const mainstreamRate = mainstreamBooks.length / books.length;
|
||||
const popularRate = popularBooks.length / books.length;
|
||||
|
||||
return Math.min(100, Math.round(mainstreamRate * 50 + popularRate * 50));
|
||||
}
|
||||
|
||||
// Old publication dates + classic genre proportion
|
||||
private calculateNostalgicScore(books: Book[]): number {
|
||||
const currentYear = new Date().getFullYear();
|
||||
const classicThreshold = currentYear - 30;
|
||||
|
||||
const oldBooks = books.filter(book => {
|
||||
if (!book.metadata?.publishedDate) return false;
|
||||
const pubYear = new Date(book.metadata.publishedDate).getFullYear();
|
||||
return pubYear > 0 && pubYear < classicThreshold;
|
||||
});
|
||||
|
||||
const classicGenres = [
|
||||
'classic', 'mythology', 'folklore', 'fairy tale',
|
||||
'ancient', 'medieval', 'victorian', 'gothic'
|
||||
];
|
||||
|
||||
const classicBooks = books.filter(book =>
|
||||
this.bookMatchesGenres(book, classicGenres)
|
||||
);
|
||||
|
||||
const oldBookRate = oldBooks.length / books.length;
|
||||
const classicRate = classicBooks.length / books.length;
|
||||
|
||||
return Math.min(100, Math.round(oldBookRate * 60 + classicRate * 40));
|
||||
}
|
||||
|
||||
// Library volume + challenging book proportion + completion of challenging books
|
||||
private calculateAmbitiousScore(books: Book[]): number {
|
||||
// Need ~100 books to max out the volume component
|
||||
const volumeScore = Math.min(40, books.length * 0.4);
|
||||
|
||||
const challengingBooks = books.filter(book =>
|
||||
book.metadata?.pageCount && book.metadata.pageCount > 600
|
||||
);
|
||||
|
||||
const completedChallenging = challengingBooks.filter(book =>
|
||||
book.readStatus === ReadStatus.READ
|
||||
);
|
||||
|
||||
const challengingRate = challengingBooks.length / books.length;
|
||||
const completionRate = challengingBooks.length > 0 ?
|
||||
completedChallenging.length / challengingBooks.length : 0;
|
||||
|
||||
return Math.min(100, Math.round(volumeScore + challengingRate * 35 + completionRate * 25));
|
||||
}
|
||||
|
||||
private bookMatchesGenres(book: Book, genres: string[]): boolean {
|
||||
if (!book.metadata?.categories) return false;
|
||||
return book.metadata.categories.some(cat =>
|
||||
genres.some(genre => cat.toLowerCase().includes(genre))
|
||||
);
|
||||
}
|
||||
|
||||
private getBookProgress(book: Book): number {
|
||||
return Math.max(
|
||||
book.epubProgress?.percentage || 0,
|
||||
book.pdfProgress?.percentage || 0,
|
||||
book.cbxProgress?.percentage || 0,
|
||||
book.koreaderProgress?.percentage || 0,
|
||||
book.koboProgress?.percentage || 0
|
||||
);
|
||||
}
|
||||
|
||||
private getTraitDescription(traitKey: string, score: number): string {
|
||||
const level = score < 33 ? 'low' : score < 67 ? 'mid' : 'high';
|
||||
return this.t.translate(`statsUser.readingDna.descriptions.${traitKey}.${level}`);
|
||||
}
|
||||
|
||||
private buildPersonalityInsights(profile: ReadingDNAProfile): PersonalityInsight[] {
|
||||
const traitColors = ['#e91e63', '#2196f3', '#00bcd4', '#ff9800', '#9c27b0', '#3f51b5', '#673ab7', '#009688'];
|
||||
|
||||
return this.traitKeys.map((key, i) => ({
|
||||
trait: this.t.translate(`statsUser.readingDna.traits.${key}`),
|
||||
score: profile[key as keyof ReadingDNAProfile],
|
||||
description: this.getTraitDescription(key, profile[key as keyof ReadingDNAProfile]),
|
||||
color: traitColors[i]
|
||||
}));
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readingHabits'">
|
||||
<div class="reading-habits-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-line reading-habits-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
@if (habitInsights().length > 0) {
|
||||
<div class="habit-insights">
|
||||
<h4>{{ t('habitPatterns') }}</h4>
|
||||
<div class="insights-grid">
|
||||
@for (insight of habitInsights(); track insight.habit) {
|
||||
<div class="insight-card">
|
||||
<div class="insight-header">
|
||||
<span class="insight-trait">{{ insight.habit }}</span>
|
||||
<span class="insight-score" [style.color]="insight.color">{{ insight.score.toFixed(0) }}%</span>
|
||||
</div>
|
||||
<div class="insight-progress">
|
||||
<div class="progress-bar" [style.width.%]="insight.score" [style.background-color]="insight.color"></div>
|
||||
</div>
|
||||
<p class="insight-description">{{ insight.description }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
.reading-habits-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.reading-habits-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(156, 39, 176, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 450px;
|
||||
width: 100%;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.habit-insights {
|
||||
margin-top: 2rem;
|
||||
|
||||
h4 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.1rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
.insight-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.insight-trait {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.insight-score {
|
||||
font-weight: 600;
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-progress {
|
||||
height: 6px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
border-radius: 3px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.insight-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.85rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 350px;
|
||||
}
|
||||
|
||||
.habit-insights {
|
||||
.insights-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
}
|
||||
}
|
||||
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface ReadingHabitsProfile {
|
||||
consistency: number;
|
||||
multitasking: number;
|
||||
completionism: number;
|
||||
exploration: number;
|
||||
organization: number;
|
||||
intensity: number;
|
||||
methodology: number;
|
||||
momentum: number;
|
||||
}
|
||||
|
||||
interface HabitInsight {
|
||||
habit: string;
|
||||
score: number;
|
||||
description: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
type ReadingHabitsChartData = ChartData<'radar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-habits-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-habits-chart.component.html',
|
||||
styleUrls: ['./reading-habits-chart.component.scss']
|
||||
})
|
||||
export class ReadingHabitsChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly profile = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.calculateReadingHabitsData(this.bookService.books());
|
||||
});
|
||||
|
||||
private readonly habitKeys = ['consistency', 'multitasking', 'completionism', 'exploration', 'organization', 'intensity', 'methodology', 'momentum'];
|
||||
|
||||
public readonly chartType = 'radar' as const;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'radar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 15}
|
||||
},
|
||||
scales: {
|
||||
r: {
|
||||
beginAtZero: true,
|
||||
min: 0,
|
||||
max: 100,
|
||||
ticks: {
|
||||
stepSize: 20,
|
||||
color: 'rgba(255, 255, 255, 0.6)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
backdropColor: 'transparent',
|
||||
showLabelBackdrop: false
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.2)',
|
||||
circular: true
|
||||
},
|
||||
angleLines: {
|
||||
color: 'rgba(255, 255, 255, 0.3)'
|
||||
},
|
||||
pointLabels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
padding: 25,
|
||||
callback: (label: string) => {
|
||||
const icons = ['📅', '📚', '✅', '🔍', '📋', '⚡', '🎯', '🔥'];
|
||||
const translatedLabels = this.habitKeys.map(k => this.t.translate(`statsUser.readingHabits.habits.${k}`));
|
||||
const idx = translatedLabels.indexOf(label);
|
||||
return [idx >= 0 ? icons[idx] : '', label];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#9c27b0',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 16,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const label = context[0]?.label || '';
|
||||
return this.t.translate('statsUser.readingHabits.tooltipHabit', {label});
|
||||
},
|
||||
label: (context) => {
|
||||
const score = context.parsed.r;
|
||||
const insight = this.habitInsights().find(i => i.habit === context.label);
|
||||
|
||||
return [
|
||||
this.t.translate('statsUser.readingHabits.tooltipScore', {score}),
|
||||
'',
|
||||
insight ? insight.description : this.t.translate('statsUser.readingHabits.tooltipDefaultDescription')
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
},
|
||||
elements: {
|
||||
line: {
|
||||
borderWidth: 3,
|
||||
tension: 0.1
|
||||
},
|
||||
point: {
|
||||
radius: 5,
|
||||
hoverRadius: 8,
|
||||
borderWidth: 3,
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.8)'
|
||||
}
|
||||
}
|
||||
};
|
||||
public readonly chartData = computed<ReadingHabitsChartData>(() => {
|
||||
const profile = this.profile();
|
||||
if (!profile) {
|
||||
return {labels: [], datasets: []};
|
||||
}
|
||||
|
||||
const data = [
|
||||
profile.consistency,
|
||||
profile.multitasking,
|
||||
profile.completionism,
|
||||
profile.exploration,
|
||||
profile.organization,
|
||||
profile.intensity,
|
||||
profile.methodology,
|
||||
profile.momentum
|
||||
];
|
||||
|
||||
const habitColors = [
|
||||
'#9c27b0', '#e91e63', '#ff5722', '#ff9800',
|
||||
'#ffc107', '#4caf50', '#2196f3', '#673ab7'
|
||||
];
|
||||
|
||||
const translatedLabels = this.habitKeys.map(k => this.t.translate(`statsUser.readingHabits.habits.${k}`));
|
||||
|
||||
return {
|
||||
labels: translatedLabels,
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.readingHabits.readingHabitsProfile'),
|
||||
data,
|
||||
backgroundColor: 'rgba(156, 39, 176, 0.2)',
|
||||
borderColor: '#9c27b0',
|
||||
borderWidth: 3,
|
||||
pointBackgroundColor: habitColors,
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 3,
|
||||
pointRadius: 5,
|
||||
pointHoverRadius: 8,
|
||||
fill: true
|
||||
}]
|
||||
};
|
||||
});
|
||||
public readonly habitInsights = computed(() => {
|
||||
const profile = this.profile();
|
||||
return profile ? this.buildHabitInsights(profile) : [];
|
||||
});
|
||||
|
||||
private calculateReadingHabitsData(books: Book[]): ReadingHabitsProfile | null {
|
||||
if (books.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.analyzeReadingHabits(books);
|
||||
}
|
||||
|
||||
private analyzeReadingHabits(books: Book[]): ReadingHabitsProfile | null {
|
||||
if (books.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
consistency: this.calculateConsistencyScore(books),
|
||||
multitasking: this.calculateMultitaskingScore(books),
|
||||
completionism: this.calculateCompletionismScore(books),
|
||||
exploration: this.calculateExplorationScore(books),
|
||||
organization: this.calculateOrganizationScore(books),
|
||||
intensity: this.calculateIntensityScore(books),
|
||||
methodology: this.calculateMethodologyScore(books),
|
||||
momentum: this.calculateMomentumScore(books)
|
||||
};
|
||||
}
|
||||
|
||||
// Regularity of reading over time (coefficient of variation of gaps between completions)
|
||||
private calculateConsistencyScore(books: Book[]): number {
|
||||
const completedBooks = books
|
||||
.filter(book => book.readStatus === ReadStatus.READ && book.dateFinished)
|
||||
.sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime());
|
||||
|
||||
if (completedBooks.length < 3) {
|
||||
return Math.min(20, completedBooks.length * 10);
|
||||
}
|
||||
|
||||
const dates = completedBooks.map(b => new Date(b.dateFinished!).getTime());
|
||||
const gaps: number[] = [];
|
||||
for (let i = 1; i < dates.length; i++) {
|
||||
gaps.push((dates[i] - dates[i - 1]) / (1000 * 60 * 60 * 24));
|
||||
}
|
||||
|
||||
const meanGap = gaps.reduce((a, b) => a + b, 0) / gaps.length;
|
||||
if (meanGap === 0) return 50; // all finished same day — likely bulk import
|
||||
|
||||
const variance = gaps.reduce((sum, g) => sum + Math.pow(g - meanGap, 2), 0) / gaps.length;
|
||||
const stdDev = Math.sqrt(variance);
|
||||
const cv = stdDev / meanGap; // coefficient of variation: < 0.5 = very regular, > 2 = very irregular
|
||||
|
||||
const regularityScore = Math.max(0, Math.min(70, (1 - cv / 2) * 70));
|
||||
const volumeBonus = Math.min(30, completedBooks.length * 1.5);
|
||||
|
||||
return Math.min(100, Math.round(regularityScore + volumeBonus));
|
||||
}
|
||||
|
||||
// How many books are being read simultaneously
|
||||
private calculateMultitaskingScore(books: Book[]): number {
|
||||
const activeBooks = books.filter(book =>
|
||||
book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING
|
||||
).length;
|
||||
|
||||
// 1 active = 10, 2 = 30, 3 = 50, 4 = 65, 5+ = 75+
|
||||
const activeScore = Math.min(75, activeBooks <= 1 ? activeBooks * 10 : 10 + (activeBooks - 1) * 20);
|
||||
|
||||
// Partial-progress books (started but not currently reading or finished)
|
||||
const partialBooks = books.filter(book => {
|
||||
if (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING) return false;
|
||||
if (book.readStatus === ReadStatus.READ) return false;
|
||||
const progress = this.getBookProgress(book);
|
||||
return progress > 10 && progress < 90;
|
||||
});
|
||||
const partialScore = Math.min(25, partialBooks.length * 5);
|
||||
|
||||
return Math.min(100, Math.round(activeScore + partialScore));
|
||||
}
|
||||
|
||||
// Completion rate vs abandonment among started books
|
||||
private calculateCompletionismScore(books: Book[]): number {
|
||||
const started = books.filter(b =>
|
||||
b.readStatus === ReadStatus.READ ||
|
||||
b.readStatus === ReadStatus.ABANDONED ||
|
||||
b.readStatus === ReadStatus.READING ||
|
||||
b.readStatus === ReadStatus.RE_READING ||
|
||||
this.getBookProgress(b) > 0
|
||||
);
|
||||
|
||||
if (started.length === 0) return 0;
|
||||
|
||||
const completed = books.filter(b => b.readStatus === ReadStatus.READ);
|
||||
const abandoned = books.filter(b => b.readStatus === ReadStatus.ABANDONED);
|
||||
|
||||
const completionRate = completed.length / started.length;
|
||||
const abandonmentRate = abandoned.length / started.length;
|
||||
|
||||
const completionScore = completionRate * 75;
|
||||
const loyaltyScore = (1 - abandonmentRate) * 25;
|
||||
|
||||
return Math.min(100, Math.round(completionScore + loyaltyScore));
|
||||
}
|
||||
|
||||
// Author diversity relative to library size + publication era spread + languages
|
||||
private calculateExplorationScore(books: Book[]): number {
|
||||
const authors = new Set<string>();
|
||||
books.forEach(book => {
|
||||
book.metadata?.authors?.forEach(a => authors.add(a.toLowerCase()));
|
||||
});
|
||||
|
||||
// Unique authors relative to book count (1:1 ratio = max diversity)
|
||||
const authorRatio = authors.size / Math.max(1, books.length);
|
||||
const diversityScore = Math.min(60, authorRatio * 60);
|
||||
|
||||
// Publication era spread
|
||||
const years: number[] = [];
|
||||
books.forEach(book => {
|
||||
if (book.metadata?.publishedDate) {
|
||||
const year = new Date(book.metadata.publishedDate).getFullYear();
|
||||
if (year > 0) years.push(year);
|
||||
}
|
||||
});
|
||||
let temporalScore = 0;
|
||||
if (years.length >= 2) {
|
||||
const yearSpread = Math.max(...years) - Math.min(...years);
|
||||
temporalScore = Math.min(25, yearSpread * 0.5);
|
||||
}
|
||||
|
||||
// Language variety
|
||||
const languages = new Set<string>();
|
||||
books.forEach(book => {
|
||||
if (book.metadata?.language) languages.add(book.metadata.language);
|
||||
});
|
||||
const languageScore = Math.min(15, Math.max(0, languages.size - 1) * 7.5);
|
||||
|
||||
return Math.min(100, Math.round(diversityScore + temporalScore + languageScore));
|
||||
}
|
||||
|
||||
// Library curation: rating discipline + read status management + series tracking
|
||||
private calculateOrganizationScore(books: Book[]): number {
|
||||
// Rating discipline: % of completed books with personal ratings
|
||||
const completedBooks = books.filter(b => b.readStatus === ReadStatus.READ);
|
||||
const ratedCompleted = completedBooks.filter(b => b.personalRating);
|
||||
const ratingRate = completedBooks.length > 0 ? ratedCompleted.length / completedBooks.length : 0;
|
||||
const ratingScore = ratingRate * 40;
|
||||
|
||||
// Read status discipline: % of books with a status set (not UNSET)
|
||||
const statusSet = books.filter(b => b.readStatus && b.readStatus !== ReadStatus.UNSET);
|
||||
const statusRate = statusSet.length / books.length;
|
||||
const statusScore = statusRate * 35;
|
||||
|
||||
// Series tracking: % of series books with series numbers
|
||||
const seriesBooks = books.filter(b => b.metadata?.seriesName);
|
||||
const numberedSeries = seriesBooks.filter(b => b.metadata?.seriesNumber);
|
||||
const seriesRate = seriesBooks.length > 0 ? numberedSeries.length / seriesBooks.length : 1;
|
||||
const seriesScore = seriesRate * 25;
|
||||
|
||||
return Math.min(100, Math.round(ratingScore + statusScore + seriesScore));
|
||||
}
|
||||
|
||||
// Average book length + deep reading progress
|
||||
private calculateIntensityScore(books: Book[]): number {
|
||||
const booksWithPages = books.filter(b => b.metadata?.pageCount && b.metadata.pageCount > 0);
|
||||
if (booksWithPages.length === 0) return 0;
|
||||
|
||||
const avgPages = booksWithPages.reduce((sum, b) => sum + (b.metadata?.pageCount || 0), 0) / booksWithPages.length;
|
||||
// 200 avg = 20, 400 avg = 40, 600+ avg = 60
|
||||
const lengthScore = Math.min(60, avgPages / 10);
|
||||
|
||||
// Books read past 75% progress
|
||||
const deepReaders = books.filter(b => this.getBookProgress(b) > 75);
|
||||
const progressScore = books.length > 0 ? Math.min(40, (deepReaders.length / books.length) * 40) : 0;
|
||||
|
||||
return Math.min(100, Math.round(lengthScore + progressScore));
|
||||
}
|
||||
|
||||
// Reading series in order + deep author dives + focused genre reading
|
||||
private calculateMethodologyScore(books: Book[]): number {
|
||||
// Series order discipline
|
||||
const seriesBooks = books.filter(b => b.metadata?.seriesName && b.metadata?.seriesNumber);
|
||||
const seriesGroups = new Map<string, Book[]>();
|
||||
seriesBooks.forEach(book => {
|
||||
const name = book.metadata!.seriesName!.toLowerCase();
|
||||
if (!seriesGroups.has(name)) seriesGroups.set(name, []);
|
||||
seriesGroups.get(name)!.push(book);
|
||||
});
|
||||
|
||||
let orderedSeries = 0;
|
||||
let totalMultiBookSeries = 0;
|
||||
seriesGroups.forEach(group => {
|
||||
if (group.length < 2) return;
|
||||
totalMultiBookSeries++;
|
||||
|
||||
const sorted = [...group].sort((a, b) =>
|
||||
(a.metadata?.seriesNumber || 0) - (b.metadata?.seriesNumber || 0)
|
||||
);
|
||||
|
||||
// Check if completion dates follow series number order
|
||||
const datesInOrder = sorted.every((book, i) => {
|
||||
if (i === 0) return true;
|
||||
if (!book.dateFinished || !sorted[i - 1].dateFinished) return true;
|
||||
return new Date(book.dateFinished) >= new Date(sorted[i - 1].dateFinished!);
|
||||
});
|
||||
|
||||
if (datesInOrder) orderedSeries++;
|
||||
});
|
||||
|
||||
const orderScore = totalMultiBookSeries > 0
|
||||
? (orderedSeries / totalMultiBookSeries) * 50
|
||||
: 25;
|
||||
|
||||
// Deep author dives (3+ books by same author)
|
||||
const authorCounts = new Map<string, number>();
|
||||
books.forEach(book => {
|
||||
book.metadata?.authors?.forEach(a => {
|
||||
const name = a.toLowerCase();
|
||||
authorCounts.set(name, (authorCounts.get(name) || 0) + 1);
|
||||
});
|
||||
});
|
||||
const deepDiveAuthors = Array.from(authorCounts.values()).filter(c => c >= 3).length;
|
||||
const authorDepthScore = Math.min(30, deepDiveAuthors * 10);
|
||||
|
||||
// Focused genre reading (5+ books in a genre)
|
||||
const genreCounts = new Map<string, number>();
|
||||
books.forEach(book => {
|
||||
book.metadata?.categories?.forEach(cat => {
|
||||
genreCounts.set(cat.toLowerCase(), (genreCounts.get(cat.toLowerCase()) || 0) + 1);
|
||||
});
|
||||
});
|
||||
const focusedGenres = Array.from(genreCounts.values()).filter(c => c >= 5).length;
|
||||
const genreDepthScore = Math.min(20, focusedGenres * 5);
|
||||
|
||||
return Math.min(100, Math.round(orderScore + authorDepthScore + genreDepthScore));
|
||||
}
|
||||
|
||||
// Recent reading activity + currently reading + acceleration
|
||||
private calculateMomentumScore(books: Book[]): number {
|
||||
const now = new Date();
|
||||
const threeMonthsAgo = new Date(now);
|
||||
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
|
||||
const sixMonthsAgo = new Date(now);
|
||||
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
|
||||
|
||||
// Recent completions (last 6 months): ~1 per month = ~45pts
|
||||
const recentCompletions = books.filter(b =>
|
||||
b.readStatus === ReadStatus.READ && b.dateFinished &&
|
||||
new Date(b.dateFinished) > sixMonthsAgo
|
||||
);
|
||||
const recentScore = Math.min(45, recentCompletions.length * 7.5);
|
||||
|
||||
// Currently reading
|
||||
const activeBooks = books.filter(b =>
|
||||
b.readStatus === ReadStatus.READING || b.readStatus === ReadStatus.RE_READING
|
||||
);
|
||||
const activeScore = Math.min(30, activeBooks.length * 10);
|
||||
|
||||
// Almost-done books (>70% progress, not yet finished)
|
||||
const almostDone = books.filter(b => {
|
||||
const p = this.getBookProgress(b);
|
||||
return p > 70 && p < 100 && b.readStatus !== ReadStatus.READ;
|
||||
});
|
||||
const progressScore = Math.min(25, almostDone.length * 8);
|
||||
|
||||
return Math.min(100, Math.round(recentScore + activeScore + progressScore));
|
||||
}
|
||||
|
||||
private getBookProgress(book: Book): number {
|
||||
return Math.max(
|
||||
book.epubProgress?.percentage || 0,
|
||||
book.pdfProgress?.percentage || 0,
|
||||
book.cbxProgress?.percentage || 0,
|
||||
book.koreaderProgress?.percentage || 0,
|
||||
book.koboProgress?.percentage || 0
|
||||
);
|
||||
}
|
||||
|
||||
private getHabitDescription(habitKey: string, score: number): string {
|
||||
const level = score < 33 ? 'low' : score < 67 ? 'mid' : 'high';
|
||||
return this.t.translate(`statsUser.readingHabits.descriptions.${habitKey}.${level}`);
|
||||
}
|
||||
|
||||
private buildHabitInsights(profile: ReadingHabitsProfile): HabitInsight[] {
|
||||
const habitColors = ['#9c27b0', '#e91e63', '#ff5722', '#ff9800', '#ffc107', '#4caf50', '#2196f3', '#673ab7'];
|
||||
|
||||
return this.habitKeys.map((key, i) => ({
|
||||
habit: this.t.translate(`statsUser.readingHabits.habits.${key}`),
|
||||
score: profile[key as keyof ReadingHabitsProfile],
|
||||
description: this.getHabitDescription(key, profile[key as keyof ReadingHabitsProfile]),
|
||||
color: habitColors[i]
|
||||
}));
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readingHeatmap'">
|
||||
<div class="reading-heatmap-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar reading-heatmap-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
.reading-heatmap-container {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.reading-heatmap-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(239, 71, 111, 1);
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
min-width: 300px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
min-width: 400px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 250px;
|
||||
min-width: 350px;
|
||||
}
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
import {Component, effect, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface MatrixDataPoint {
|
||||
x: number; // month (0-11)
|
||||
y: number; // year index
|
||||
v: number; // book count
|
||||
}
|
||||
|
||||
interface YearMonthData {
|
||||
year: number;
|
||||
month: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
|
||||
type HeatmapChartData = ChartData<'matrix', MatrixDataPoint[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-heatmap-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-heatmap-chart.component.html',
|
||||
styleUrls: ['./reading-heatmap-chart.component.scss']
|
||||
})
|
||||
export class ReadingHeatmapChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly syncChartEffect = effect(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = this.calculateHeatmapData(this.bookService.books());
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
|
||||
public readonly chartType = 'matrix' as const;
|
||||
|
||||
private yearLabels: string[] = [];
|
||||
private maxBookCount = 1;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {
|
||||
top: 20
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ef476f',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
displayColors: false,
|
||||
padding: 16,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const point = context[0].raw as MatrixDataPoint;
|
||||
const year = this.yearLabels[point.y];
|
||||
const month = MONTH_NAMES[point.x];
|
||||
return `${month} ${year}`;
|
||||
},
|
||||
label: (context) => {
|
||||
const point = context.raw as MatrixDataPoint;
|
||||
const key = point.v === 1 ? 'statsUser.readingHeatmap.tooltipBook' : 'statsUser.readingHeatmap.tooltipBooks';
|
||||
return this.t.translate(key, {value: point.v});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: true,
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10,
|
||||
weight: 'bold'
|
||||
},
|
||||
formatter: (value: MatrixDataPoint) => value.v > 0 ? value.v.toString() : ''
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'linear',
|
||||
position: 'bottom',
|
||||
ticks: {
|
||||
stepSize: 1,
|
||||
callback: (value) => MONTH_NAMES[value as number] || '',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {display: false},
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
offset: true,
|
||||
ticks: {
|
||||
stepSize: 1,
|
||||
callback: (value) => this.yearLabels[value as number] || '',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {display: false},
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<HeatmapChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.readingHeatmap.booksRead'),
|
||||
data: []
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<HeatmapChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
private updateChartData(yearMonthData: YearMonthData[]): void {
|
||||
const currentYear = new Date().getFullYear();
|
||||
const years = Array.from({length: 10}, (_, i) => currentYear - 9 + i);
|
||||
|
||||
this.yearLabels = years.map(String);
|
||||
this.maxBookCount = Math.max(1, ...yearMonthData.map(d => d.count));
|
||||
|
||||
const heatmapData: MatrixDataPoint[] = [];
|
||||
|
||||
years.forEach((year, yearIndex) => {
|
||||
for (let month = 0; month <= 11; month++) {
|
||||
const dataPoint = yearMonthData.find(d => d.year === year && d.month === month + 1);
|
||||
heatmapData.push({
|
||||
x: month,
|
||||
y: yearIndex,
|
||||
v: dataPoint?.count || 0
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (this.chartOptions?.scales?.['y']) {
|
||||
(this.chartOptions.scales['y'] as any).max = years.length - 1;
|
||||
}
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.readingHeatmap.booksRead'),
|
||||
data: heatmapData,
|
||||
backgroundColor: (context) => {
|
||||
const point = context.raw as MatrixDataPoint;
|
||||
if (!point?.v) return 'rgba(255, 255, 255, 0.05)';
|
||||
|
||||
const intensity = point.v / this.maxBookCount;
|
||||
const alpha = Math.max(0.2, Math.min(1.0, intensity * 0.8 + 0.2));
|
||||
return `rgba(239, 71, 111, ${alpha})`;
|
||||
},
|
||||
borderColor: 'rgba(255, 255, 255, 0.2)',
|
||||
borderWidth: 1,
|
||||
width: ({chart}) => (chart.chartArea?.width || 0) / 12 - 1,
|
||||
height: ({chart}) => (chart.chartArea?.height || 0) / years.length - 1
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
private calculateHeatmapData(books: Book[]): YearMonthData[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processHeatmapData(books);
|
||||
}
|
||||
|
||||
private processHeatmapData(books: Book[]): YearMonthData[] {
|
||||
const yearMonthMap = new Map<string, number>();
|
||||
const currentYear = new Date().getFullYear();
|
||||
const startYear = currentYear - 9;
|
||||
|
||||
books
|
||||
.filter(book => book.dateFinished)
|
||||
.forEach(book => {
|
||||
const finishedDate = new Date(book.dateFinished!);
|
||||
const year = finishedDate.getFullYear();
|
||||
|
||||
if (year >= startYear && year <= currentYear) {
|
||||
const month = finishedDate.getMonth() + 1;
|
||||
const key = `${year}-${month}`;
|
||||
yearMonthMap.set(key, (yearMonthMap.get(key) || 0) + 1);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(yearMonthMap.entries())
|
||||
.map(([key, count]) => {
|
||||
const [year, month] = key.split('-').map(Number);
|
||||
return {year, month, count};
|
||||
})
|
||||
.sort((a, b) => a.year - b.year || a.month - b.month);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readingProgress'">
|
||||
<div class="reading-progress-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-bar reading-progress-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
.reading-progress-container {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.reading-progress-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #17a2b8;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
min-width: 300px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
min-width: 400px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
min-width: 350px;
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface ReadingProgressStats {
|
||||
progressRange: string;
|
||||
count: number;
|
||||
description: string;
|
||||
}
|
||||
|
||||
const CHART_COLORS = [
|
||||
'#6c757d', // Gray - Not Started (0%)
|
||||
'#ffc107', // Yellow - Just Started (1-25%)
|
||||
'#fd7e14', // Orange - Getting Into It (26-50%)
|
||||
'#17a2b8', // Cyan - Halfway Through (51-75%)
|
||||
'#6f42c1', // Purple - Almost Finished (76-99%)
|
||||
'#28a745' // Green - Completed (100%)
|
||||
] as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
hoverBorderWidth: 2,
|
||||
hoverBorderColor: '#ffffff'
|
||||
} as const;
|
||||
|
||||
const PROGRESS_RANGES = [
|
||||
{range: '0%', min: 0, max: 0, desc: 'Not Started'},
|
||||
{range: '1-25%', min: 0.1, max: 25, desc: 'Just Started'},
|
||||
{range: '26-50%', min: 26, max: 50, desc: 'Getting Into It'},
|
||||
{range: '51-75%', min: 51, max: 75, desc: 'Halfway Through'},
|
||||
{range: '76-99%', min: 76, max: 99, desc: 'Almost Finished'},
|
||||
{range: '100%', min: 100, max: 100, desc: 'Completed'}
|
||||
] as const;
|
||||
|
||||
type ProgressChartData = ChartData<'doughnut', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-progress-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-progress-chart.component.html',
|
||||
styleUrls: ['./reading-progress-chart.component.scss']
|
||||
})
|
||||
export class ReadingProgressChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly progressStats = computed(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.calculateReadingProgressStats(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'doughnut' as const;
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'doughnut'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 15}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12
|
||||
},
|
||||
padding: 15,
|
||||
usePointStyle: true,
|
||||
pointStyle: 'circle',
|
||||
generateLabels: (chart) => {
|
||||
const data = chart.data;
|
||||
if (data.labels?.length && data.datasets?.length) {
|
||||
return data.labels.map((label, i) => {
|
||||
const value = data.datasets[0].data[i] as number;
|
||||
const isVisible = typeof chart.getDataVisibility === 'function'
|
||||
? chart.getDataVisibility(i)
|
||||
: true;
|
||||
|
||||
return {
|
||||
text: `${label}: ${value}`,
|
||||
fillStyle: (data.datasets[0].backgroundColor as string[])[i],
|
||||
strokeStyle: '#ffffff',
|
||||
lineWidth: 1,
|
||||
hidden: !isVisible,
|
||||
index: i,
|
||||
fontColor: '#ffffff'
|
||||
};
|
||||
});
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
title: (context) => context[0].label,
|
||||
label: (context) => {
|
||||
const value = context.parsed;
|
||||
const total = (context.dataset.data as number[]).reduce((a, b) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
const label = context.label;
|
||||
const rangeInfo = PROGRESS_RANGES.find(r => r.range === label);
|
||||
const descKeys: Record<string, string> = {
|
||||
'Not Started': 'notStarted', 'Just Started': 'justStarted',
|
||||
'Getting Into It': 'gettingIntoIt', 'Halfway Through': 'halfwayThrough',
|
||||
'Almost Finished': 'almostFinished', 'Completed': 'completed'
|
||||
};
|
||||
const description = rangeInfo ? this.t.translate(`statsUser.readingProgress.${descKeys[rangeInfo.desc] || 'notStarted'}`) : '';
|
||||
const plural = value === 1 ? '' : 's';
|
||||
return this.t.translate('statsUser.readingProgress.tooltipLabel', {value, plural, description, percentage});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed<ProgressChartData>(() => {
|
||||
try {
|
||||
const stats = this.progressStats();
|
||||
const labels = stats.map(s => s.progressRange);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
|
||||
return {
|
||||
labels,
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.readingProgress.booksByProgress'),
|
||||
data: dataValues,
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
}]
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error updating reading progress chart data:', error);
|
||||
return {
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.readingProgress.booksByProgress'),
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
private calculateReadingProgressStats(books: Book[]): ReadingProgressStats[] {
|
||||
if (books.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processReadingProgressStats(books);
|
||||
}
|
||||
|
||||
private processReadingProgressStats(books: Book[]): ReadingProgressStats[] {
|
||||
const rangeCounts = new Map<string, number>();
|
||||
PROGRESS_RANGES.forEach(range => rangeCounts.set(range.range, 0));
|
||||
|
||||
for (const book of books) {
|
||||
const progress = this.getBookProgress(book);
|
||||
|
||||
for (const range of PROGRESS_RANGES) {
|
||||
if (progress >= range.min && progress <= range.max) {
|
||||
rangeCounts.set(range.range, (rangeCounts.get(range.range) || 0) + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PROGRESS_RANGES.map(range => ({
|
||||
progressRange: range.range,
|
||||
count: rangeCounts.get(range.range) || 0,
|
||||
description: range.desc
|
||||
}));
|
||||
}
|
||||
|
||||
private getBookProgress(book: Book): number {
|
||||
if (book.pdfProgress?.percentage) return book.pdfProgress.percentage;
|
||||
if (book.epubProgress?.percentage) return book.epubProgress.percentage;
|
||||
if (book.cbxProgress?.percentage) return book.cbxProgress.percentage;
|
||||
if (book.koreaderProgress?.percentage) return book.koreaderProgress.percentage;
|
||||
if (book.koboProgress?.percentage) return book.koboProgress.percentage;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.sessionHeatmap'">
|
||||
<div class="reading-session-heatmap-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar heatmap-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
<div class="year-selector">
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(-1)"
|
||||
[title]="t('previousYear')">
|
||||
<i class="pi pi-chevron-left"></i>
|
||||
</button>
|
||||
<span class="current-year">{{ currentYear }}</span>
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(1)"
|
||||
[title]="t('nextYear')">
|
||||
<i class="pi pi-chevron-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="header-spacer"></div>
|
||||
</div>
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (hasStreakData) {
|
||||
<div class="chart-footer">
|
||||
<div class="footer-pills left">
|
||||
<span class="pill current">
|
||||
<span class="pill-value">{{ currentStreak }}</span> {{ t('currentStreak') }}
|
||||
</span>
|
||||
<span class="pill longest">
|
||||
<span class="pill-value">{{ longestStreak }}</span> {{ t('longestStreak') }}
|
||||
</span>
|
||||
<span class="pill total">
|
||||
<span class="pill-value">{{ totalReadingDays }}</span> {{ t('totalDays') }}
|
||||
</span>
|
||||
<span class="pill consistency">
|
||||
<span class="pill-value">{{ consistencyPercent }}%</span> {{ t('consistency') }}
|
||||
</span>
|
||||
</div>
|
||||
@if (milestones.length > 0) {
|
||||
<div class="footer-pills right">
|
||||
@for (milestone of milestones; track milestone.label) {
|
||||
<span class="pill milestone" [class.unlocked]="milestone.unlocked" [class.locked]="!milestone.unlocked">
|
||||
<span class="pill-icon">{{ milestone.icon }}</span> {{ milestone.label }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
.reading-session-heatmap-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto 1fr;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
justify-self: center;
|
||||
|
||||
.year-nav-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 0.6rem 0.6rem;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.current-year {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
min-width: 4.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.header-spacer {
|
||||
// Empty spacer for grid layout balance
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-height: 200px;
|
||||
height: 200px;
|
||||
|
||||
canvas {
|
||||
width: 100% !important;
|
||||
height: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
.heatmap-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(59, 130, 246, 1);
|
||||
vertical-align: middle;
|
||||
margin-right: 0.25em;
|
||||
}
|
||||
|
||||
.chart-footer {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.footer-pills {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
|
||||
&.right {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.35rem 0.65rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-color, #ffffff);
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
|
||||
.pill-value {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
&.current .pill-value { color: #ff9800; }
|
||||
&.longest .pill-value { color: #4caf50; }
|
||||
&.total .pill-value { color: #2196f3; }
|
||||
&.consistency .pill-value { color: #9c27b0; }
|
||||
|
||||
&.milestone.unlocked {
|
||||
border-color: rgba(76, 175, 80, 0.3);
|
||||
background: rgba(76, 175, 80, 0.1);
|
||||
}
|
||||
|
||||
&.milestone.locked {
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.75rem;
|
||||
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
justify-self: stretch;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.header-spacer {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-footer {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
.current-year {
|
||||
font-size: 1rem;
|
||||
min-width: 4rem;
|
||||
}
|
||||
|
||||
.year-nav-btn {
|
||||
padding: 0.6rem 0.6rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Chart, ChartConfiguration, ChartData, registerables} from 'chart.js';
|
||||
import {MatrixController, MatrixElement} from 'chartjs-chart-matrix';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, takeUntil} from 'rxjs/operators';
|
||||
import {ReadingSessionHeatmapResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
const DAY_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
|
||||
interface MatrixDataPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
v: number;
|
||||
date: string;
|
||||
}
|
||||
|
||||
interface Milestone {
|
||||
label: string;
|
||||
icon: string;
|
||||
requirement: number;
|
||||
type: 'streak' | 'total';
|
||||
unlocked: boolean;
|
||||
}
|
||||
|
||||
type SessionHeatmapChartData = ChartData<'matrix', MatrixDataPoint[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-session-heatmap',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-session-heatmap.component.html',
|
||||
styleUrls: ['./reading-session-heatmap.component.scss']
|
||||
})
|
||||
export class ReadingSessionHeatmapComponent implements OnInit, OnDestroy {
|
||||
@Input() initialYear: number = new Date().getFullYear();
|
||||
|
||||
public currentYear: number = new Date().getFullYear();
|
||||
public readonly chartType = 'matrix' as const;
|
||||
public readonly chartData$: Observable<SessionHeatmapChartData>;
|
||||
public readonly chartOptions: ChartConfiguration['options'];
|
||||
|
||||
public currentStreak = 0;
|
||||
public longestStreak = 0;
|
||||
public totalReadingDays = 0;
|
||||
public consistencyPercent = 0;
|
||||
public milestones: Milestone[] = [];
|
||||
public hasStreakData = false;
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
private readonly translocoService = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
private readonly chartDataSubject: BehaviorSubject<SessionHeatmapChartData>;
|
||||
private maxSessionCount = 1;
|
||||
|
||||
constructor() {
|
||||
this.chartDataSubject = new BehaviorSubject<SessionHeatmapChartData>({
|
||||
labels: [],
|
||||
datasets: [{label: 'Reading Sessions', data: []}]
|
||||
});
|
||||
this.chartData$ = this.chartDataSubject.asObservable();
|
||||
|
||||
this.chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 20, bottom: 20, left: 10, right: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: false,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const point = context[0].raw as MatrixDataPoint;
|
||||
const date = new Date(point.date);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
weekday: 'short',
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
},
|
||||
label: (context) => {
|
||||
const point = context.raw as MatrixDataPoint;
|
||||
return point.v === 1
|
||||
? this.translocoService.translate('statsUser.sessionHeatmap.readingSession', {count: point.v})
|
||||
: this.translocoService.translate('statsUser.sessionHeatmap.readingSessions_plural', {count: point.v});
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'linear',
|
||||
position: 'top',
|
||||
min: 0,
|
||||
max: 52,
|
||||
ticks: {
|
||||
stepSize: 4,
|
||||
callback: (value) => {
|
||||
const weekNum = value as number;
|
||||
if (weekNum % 4 === 0) {
|
||||
const date = this.getDateFromWeek(this.currentYear, weekNum);
|
||||
return MONTH_NAMES[date.getMonth()];
|
||||
}
|
||||
return '';
|
||||
},
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {display: false},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
min: 0,
|
||||
max: 6,
|
||||
ticks: {
|
||||
stepSize: 1,
|
||||
callback: (value) => {
|
||||
const dayIndex = value as number;
|
||||
return dayIndex >= 0 && dayIndex <= 6 ? DAY_NAMES[dayIndex] : '';
|
||||
},
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
Chart.register(...registerables, MatrixController, MatrixElement);
|
||||
this.currentYear = this.initialYear;
|
||||
this.loadYearData(this.currentYear);
|
||||
this.loadStreakData();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
public changeYear(delta: number): void {
|
||||
this.currentYear += delta;
|
||||
this.loadYearData(this.currentYear);
|
||||
}
|
||||
|
||||
private loadYearData(year: number): void {
|
||||
this.userStatsService.getHeatmapForYear(year)
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading reading session heatmap:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => {
|
||||
this.updateChartData(data);
|
||||
});
|
||||
}
|
||||
|
||||
private updateChartData(sessionData: ReadingSessionHeatmapResponse[]): void {
|
||||
const sessionMap = new Map<string, number>();
|
||||
sessionData.forEach(item => {
|
||||
sessionMap.set(item.date, item.count);
|
||||
});
|
||||
|
||||
this.maxSessionCount = Math.max(1, ...sessionData.map(d => d.count));
|
||||
|
||||
const heatmapData: MatrixDataPoint[] = [];
|
||||
const startDate = new Date(this.currentYear, 0, 1);
|
||||
const endDate = new Date(this.currentYear, 11, 31);
|
||||
|
||||
const firstMonday = new Date(startDate);
|
||||
const dayOfWeek = firstMonday.getDay();
|
||||
const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
|
||||
firstMonday.setDate(firstMonday.getDate() - daysToMonday);
|
||||
|
||||
let weekIndex = 0;
|
||||
const currentDate = new Date(firstMonday);
|
||||
|
||||
while (currentDate <= endDate || weekIndex === 0) {
|
||||
for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
|
||||
const year = currentDate.getFullYear();
|
||||
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(currentDate.getDate()).padStart(2, '0');
|
||||
const dateStr = `${year}-${month}-${day}`;
|
||||
|
||||
if (currentDate >= startDate && currentDate <= endDate) {
|
||||
const count = sessionMap.get(dateStr) || 0;
|
||||
|
||||
heatmapData.push({
|
||||
x: weekIndex,
|
||||
y: dayOfWeek,
|
||||
v: count,
|
||||
date: dateStr
|
||||
});
|
||||
}
|
||||
|
||||
currentDate.setDate(currentDate.getDate() + 1);
|
||||
}
|
||||
|
||||
weekIndex++;
|
||||
|
||||
if (currentDate > endDate) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Reading Sessions',
|
||||
data: heatmapData,
|
||||
backgroundColor: (context) => {
|
||||
const point = context.raw as MatrixDataPoint;
|
||||
if (!point?.v) return 'rgba(255, 255, 255, 0.05)';
|
||||
|
||||
const intensity = point.v / this.maxSessionCount;
|
||||
const alpha = Math.max(0.3, Math.min(0.9, intensity * 0.6 + 0.3));
|
||||
return `rgba(59, 130, 246, ${alpha})`;
|
||||
},
|
||||
borderColor: 'rgba(255, 255, 255, 0.1)',
|
||||
borderWidth: 1
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
private loadStreakData(): void {
|
||||
this.userStatsService.getReadingDates()
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
catchError((error) => {
|
||||
console.error('Error loading reading dates:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe((data) => this.processStreakData(data));
|
||||
}
|
||||
|
||||
private processStreakData(data: ReadingSessionHeatmapResponse[]): void {
|
||||
if (!data || data.length === 0) {
|
||||
this.hasStreakData = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.hasStreakData = true;
|
||||
this.totalReadingDays = data.length;
|
||||
|
||||
const sortedDates = Array.from(new Set(data.map(d => d.date))).sort();
|
||||
const dateSet = new Set(sortedDates);
|
||||
|
||||
// Calculate all streaks
|
||||
const streakLengths: number[] = [];
|
||||
let streakStart: string | null = null;
|
||||
let prevDate: string | null = null;
|
||||
let lastStreakEnd: string | null = null;
|
||||
let lastStreakLength = 0;
|
||||
|
||||
for (const dateStr of sortedDates) {
|
||||
if (!prevDate || !this.isConsecutiveDay(prevDate, dateStr)) {
|
||||
if (prevDate && streakStart) {
|
||||
const len = this.daysBetween(streakStart, prevDate) + 1;
|
||||
streakLengths.push(len);
|
||||
lastStreakEnd = prevDate;
|
||||
lastStreakLength = len;
|
||||
}
|
||||
streakStart = dateStr;
|
||||
}
|
||||
prevDate = dateStr;
|
||||
}
|
||||
if (prevDate && streakStart) {
|
||||
const len = this.daysBetween(streakStart, prevDate) + 1;
|
||||
streakLengths.push(len);
|
||||
lastStreakEnd = prevDate;
|
||||
lastStreakLength = len;
|
||||
}
|
||||
|
||||
this.longestStreak = streakLengths.length > 0 ? Math.max(...streakLengths) : 0;
|
||||
|
||||
// Current streak
|
||||
const today = this.toDateStr(new Date());
|
||||
const yesterday = this.toDateStr(new Date(Date.now() - 86400000));
|
||||
|
||||
if ((dateSet.has(today) || dateSet.has(yesterday)) && (lastStreakEnd === today || lastStreakEnd === yesterday)) {
|
||||
this.currentStreak = lastStreakLength;
|
||||
} else {
|
||||
this.currentStreak = 0;
|
||||
}
|
||||
|
||||
// Consistency
|
||||
if (sortedDates.length >= 2) {
|
||||
const totalPossibleDays = this.daysBetween(sortedDates[0], today) + 1;
|
||||
this.consistencyPercent = totalPossibleDays > 0
|
||||
? Math.round((this.totalReadingDays / totalPossibleDays) * 100)
|
||||
: 0;
|
||||
}
|
||||
|
||||
// Milestones
|
||||
this.milestones = [
|
||||
{label: this.translocoService.translate('statsUser.sessionHeatmap.milestone7DayStreak'), icon: '\uD83D\uDD25', requirement: 7, type: 'streak', unlocked: this.longestStreak >= 7},
|
||||
{label: this.translocoService.translate('statsUser.sessionHeatmap.milestone30DayStreak'), icon: '\u26A1', requirement: 30, type: 'streak', unlocked: this.longestStreak >= 30},
|
||||
{label: this.translocoService.translate('statsUser.sessionHeatmap.milestone100ReadingDays'), icon: '\uD83D\uDCDA', requirement: 100, type: 'total', unlocked: this.totalReadingDays >= 100},
|
||||
{label: this.translocoService.translate('statsUser.sessionHeatmap.milestone365ReadingDays'), icon: '\uD83C\uDFC6', requirement: 365, type: 'total', unlocked: this.totalReadingDays >= 365},
|
||||
{label: this.translocoService.translate('statsUser.sessionHeatmap.milestoneYearOfReading'), icon: '\uD83D\uDC51', requirement: 365, type: 'streak', unlocked: this.longestStreak >= 365},
|
||||
];
|
||||
}
|
||||
|
||||
private toDateStr(d: Date): string {
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
private isConsecutiveDay(dateStr1: string, dateStr2: string): boolean {
|
||||
const d1 = new Date(dateStr1);
|
||||
const d2 = new Date(dateStr2);
|
||||
return Math.abs(d2.getTime() - d1.getTime() - 86400000) < 3600000;
|
||||
}
|
||||
|
||||
private daysBetween(dateStr1: string, dateStr2: string): number {
|
||||
return Math.round((new Date(dateStr2).getTime() - new Date(dateStr1).getTime()) / 86400000);
|
||||
}
|
||||
|
||||
private getDateFromWeek(year: number, week: number): Date {
|
||||
const date = new Date(year, 0, 1);
|
||||
date.setDate(date.getDate() + (week * 7) - date.getDay());
|
||||
return date;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.sessionTimeline'">
|
||||
<div class="timeline-container">
|
||||
<div class="timeline-header">
|
||||
<div class="header-title">
|
||||
<h3>
|
||||
<i class="pi pi-clock timeline-title-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="timeline-subtitle">{{ t('description') }}</p>
|
||||
</div>
|
||||
<div class="week-info">
|
||||
<button type="button"
|
||||
class="week-nav-btn"
|
||||
(click)="changeWeek(-1)"
|
||||
[title]="t('previousWeek')">
|
||||
<i class="pi pi-chevron-left"></i>
|
||||
</button>
|
||||
<div class="week-display">
|
||||
<span class="week-label">{{ t('week', { number: currentWeek }) }}</span>
|
||||
<span class="week-dates">{{ getWeekDateRange() }}</span>
|
||||
</div>
|
||||
<button type="button"
|
||||
class="week-nav-btn"
|
||||
(click)="changeWeek(1)"
|
||||
[title]="t('nextWeek')">
|
||||
<i class="pi pi-chevron-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="filter-controls">
|
||||
<p-select
|
||||
[options]="yearOptions"
|
||||
[(ngModel)]="currentYear"
|
||||
(onChange)="onYearChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectYear')"
|
||||
[style]="{'min-width': '120px'}">
|
||||
</p-select>
|
||||
<p-select
|
||||
[options]="weekOptions"
|
||||
[(ngModel)]="currentWeek"
|
||||
(onChange)="onWeekChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectWeek')"
|
||||
[style]="{'min-width': '120px'}">
|
||||
</p-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="timeline-content">
|
||||
<div class="hour-markers">
|
||||
<div class="day-label-spacer"></div>
|
||||
<div class="hour-grid">
|
||||
@for (hour of hourLabels; track $index) {
|
||||
<div class="hour-marker" [class.major]="$index % 3 === 0">
|
||||
<span class="hour-label">{{ hour }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="timeline-rows">
|
||||
@for (dayData of timelineData; track dayData.dayOfWeek) {
|
||||
<div class="timeline-row">
|
||||
<div class="day-label">{{ dayData.day }}</div>
|
||||
<div class="timeline-track">
|
||||
<div class="grid-lines">
|
||||
@for (hour of hourLabels; track $index) {
|
||||
<div class="grid-line" [class.major]="$index % 6 === 0"></div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="sessions">
|
||||
@for (session of dayData.sessions; track $index) {
|
||||
<div class="session-block"
|
||||
[class]="'book-type-' + (session.bookType || 'default').toLowerCase()"
|
||||
[style.left.%]="session.left"
|
||||
[style.width.%]="session.width"
|
||||
[style.top]="session.totalLevels > 1 ? 'calc(' + session.level + ' / ' + session.totalLevels + ' * 100% + ' + session.level * 2 + 'px)' : '0'"
|
||||
[style.height]="session.totalLevels > 1 ? 'calc((1 / ' + session.totalLevels + ' * 100%) - ' + (session.totalLevels - 1) * 2 / session.totalLevels + 'px)' : '100%'"
|
||||
[pTooltip]="session.tooltipContent"
|
||||
[escape]="false"
|
||||
tooltipPosition="top"
|
||||
tooltipStyleClass="session-timeline-tooltip"
|
||||
[appendTo]="'body'">
|
||||
@if (isDurationGreaterThanOneHour(session.duration)) {
|
||||
<div class="session-content">
|
||||
<span class="session-time">
|
||||
{{ formatTime(session.startHour, session.startMinute) }}
|
||||
</span>
|
||||
<span class="session-duration">
|
||||
{{ formatDurationCompact(session.duration) }}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+646
@@ -0,0 +1,646 @@
|
||||
.timeline-container {
|
||||
width: 100%;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.timeline-header {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto 1fr;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 1rem;
|
||||
|
||||
.header-title {
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
}
|
||||
|
||||
.timeline-subtitle {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.week-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-self: center;
|
||||
|
||||
.week-nav-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 0.6rem 0.6rem;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.week-display {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
min-width: 120px;
|
||||
|
||||
.week-label {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
white-space: nowrap;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.week-dates {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
white-space: nowrap;
|
||||
margin-top: 0.1rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
justify-self: end;
|
||||
}
|
||||
}
|
||||
|
||||
.week-info-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
padding: 0.75rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
.week-nav-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 0.6rem 6rem;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.week-display {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
min-width: 150px;
|
||||
|
||||
.week-label {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.week-dates {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-secondary-color);
|
||||
white-space: nowrap;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-content {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.hour-markers {
|
||||
display: flex;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.day-label-spacer {
|
||||
width: 100px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.hour-grid {
|
||||
flex: 1;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(24, 1fr);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.hour-marker {
|
||||
position: relative;
|
||||
height: 20px;
|
||||
|
||||
&.major {
|
||||
.hour-label {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.hour-label {
|
||||
display: none;
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
position: absolute;
|
||||
left: 0;
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-rows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.timeline-row {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
overflow: visible;
|
||||
|
||||
.day-label {
|
||||
width: 50px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
.timeline-track {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border-radius: 4px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
min-height: 35px;
|
||||
overflow: visible;
|
||||
}
|
||||
}
|
||||
|
||||
.grid-lines {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(24, 1fr);
|
||||
pointer-events: none;
|
||||
|
||||
.grid-line {
|
||||
border-right: 1px solid rgba(255, 255, 255, 0.05);
|
||||
|
||||
&:last-child {
|
||||
border-right: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sessions {
|
||||
position: absolute;
|
||||
inset: 4px;
|
||||
pointer-events: none;
|
||||
overflow: visible;
|
||||
|
||||
.session-block {
|
||||
position: absolute;
|
||||
border-radius: 4px;
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
overflow: visible;
|
||||
box-sizing: border-box;
|
||||
|
||||
&.book-type-epub, &.book-type-default {
|
||||
background: color-mix(in srgb, var(--book-type-epub-color) 80%, transparent);
|
||||
border: 1px solid var(--book-type-epub-color);
|
||||
box-shadow: 0 2px 4px color-mix(in srgb, var(--book-type-epub-color) 30%, transparent);
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 8px color-mix(in srgb, var(--book-type-epub-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&.book-type-pdf {
|
||||
background: color-mix(in srgb, var(--book-type-pdf-color) 80%, transparent);
|
||||
border: 1px solid var(--book-type-pdf-color);
|
||||
box-shadow: 0 2px 4px color-mix(in srgb, var(--book-type-pdf-color) 30%, transparent);
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 8px color-mix(in srgb, var(--book-type-pdf-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&.book-type-cbx {
|
||||
background: color-mix(in srgb, var(--book-type-cbx-color) 80%, transparent);
|
||||
border: 1px solid var(--book-type-cbx-color);
|
||||
box-shadow: 0 2px 4px color-mix(in srgb, var(--book-type-cbx-color) 30%, transparent);
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 8px color-mix(in srgb, var(--book-type-cbx-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&.book-type-fb2 {
|
||||
background: color-mix(in srgb, var(--book-type-fb2-color) 80%, transparent);
|
||||
border: 1px solid var(--book-type-fb2-color);
|
||||
box-shadow: 0 2px 4px color-mix(in srgb, var(--book-type-fb2-color) 30%, transparent);
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 8px color-mix(in srgb, var(--book-type-fb2-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&.book-type-mobi {
|
||||
background: color-mix(in srgb, var(--book-type-mobi-color) 80%, transparent);
|
||||
border: 1px solid var(--book-type-mobi-color);
|
||||
box-shadow: 0 2px 4px color-mix(in srgb, var(--book-type-mobi-color) 30%, transparent);
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 8px color-mix(in srgb, var(--book-type-mobi-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&.book-type-azw3 {
|
||||
background: color-mix(in srgb, var(--book-type-azw3-color) 80%, transparent);
|
||||
border: 1px solid var(--book-type-azw3-color);
|
||||
box-shadow: 0 2px 4px color-mix(in srgb, var(--book-type-azw3-color) 30%, transparent);
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 8px color-mix(in srgb, var(--book-type-azw3-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&.book-type-audiobook {
|
||||
background: color-mix(in srgb, var(--book-type-audiobook-color) 80%, transparent);
|
||||
border: 1px solid var(--book-type-audiobook-color);
|
||||
box-shadow: 0 2px 4px color-mix(in srgb, var(--book-type-audiobook-color) 30%, transparent);
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 8px color-mix(in srgb, var(--book-type-audiobook-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.session-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
padding: 4px 8px;
|
||||
color: white;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
gap: 2px;
|
||||
overflow: hidden;
|
||||
|
||||
.session-time {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 100%;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.session-duration {
|
||||
font-size: 0.65rem;
|
||||
opacity: 0.9;
|
||||
white-space: nowrap;
|
||||
line-height: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .session-timeline-tooltip.p-tooltip {
|
||||
--p-tooltip-max-width: 300px;
|
||||
--p-tooltip-background: rgba(30, 30, 30, 0.98);
|
||||
--p-tooltip-color: #ffffff;
|
||||
--p-tooltip-border-radius: 12px;
|
||||
--p-tooltip-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
|
||||
--p-tooltip-padding: 0 !important;
|
||||
--p-tooltip-gutter: 12px;
|
||||
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
min-width: 320px;
|
||||
padding: 0 !important;
|
||||
|
||||
.p-tooltip-text {
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.session-tooltip-content {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.session-tooltip-cover {
|
||||
flex-shrink: 0;
|
||||
width: 80px;
|
||||
height: 120px;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 4px;
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
.session-tooltip-details {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.session-tooltip-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
|
||||
i {
|
||||
font-size: 1.1rem;
|
||||
color: rgba(239, 68, 68, 1);
|
||||
}
|
||||
}
|
||||
|
||||
.session-tooltip-title {
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.session-tooltip-divider {
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg,
|
||||
transparent 0%,
|
||||
rgba(255, 255, 255, 0.1) 50%,
|
||||
transparent 100%);
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.session-tooltip-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.625rem;
|
||||
}
|
||||
|
||||
.session-tooltip-row {
|
||||
display: grid;
|
||||
grid-template-columns: auto auto 1fr;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
font-size: 0.875rem;
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
width: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.session-tooltip-label {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.session-tooltip-value {
|
||||
color: #ffffff;
|
||||
text-align: right;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-title-icon {
|
||||
font-size: 1.5rem;
|
||||
color: rgba(239, 68, 68, 1);
|
||||
vertical-align: middle;
|
||||
margin-right: 0.25em;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.timeline-header {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.75rem;
|
||||
|
||||
.header-title {
|
||||
grid-column: 1;
|
||||
}
|
||||
|
||||
.week-info {
|
||||
grid-column: 1;
|
||||
justify-self: stretch;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
grid-column: 1;
|
||||
justify-self: stretch;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.5rem;
|
||||
|
||||
::ng-deep p-select {
|
||||
width: 100%;
|
||||
|
||||
.p-select {
|
||||
width: 100% !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.timeline-header {
|
||||
.header-title {
|
||||
h3 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.timeline-subtitle {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.week-info {
|
||||
padding: 0.6rem 0.6rem;
|
||||
|
||||
.week-display {
|
||||
min-width: 100px;
|
||||
|
||||
.week-label {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.week-dates {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
}
|
||||
|
||||
.week-nav-btn {
|
||||
padding: 0.35rem 0.5rem;
|
||||
|
||||
i {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-content {
|
||||
min-height: 300px;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.timeline-row {
|
||||
.day-label {
|
||||
width: 70px;
|
||||
font-size: 0.75rem;
|
||||
padding-right: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.hour-markers {
|
||||
.day-label-spacer {
|
||||
width: 70px;
|
||||
}
|
||||
}
|
||||
|
||||
.hour-marker {
|
||||
.hour-label {
|
||||
font-size: 0.6rem;
|
||||
}
|
||||
}
|
||||
|
||||
.session-block {
|
||||
.session-content {
|
||||
font-size: 0.65rem;
|
||||
|
||||
.session-duration {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.session-tooltip {
|
||||
min-width: 240px;
|
||||
max-width: 280px;
|
||||
font-size: 0.85rem;
|
||||
|
||||
.tooltip-header {
|
||||
padding: 0.75rem;
|
||||
|
||||
.tooltip-title {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.tooltip-body {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.tooltip-row {
|
||||
font-size: 0.8rem;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.timeline-header {
|
||||
.header-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.timeline-subtitle {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.week-info {
|
||||
.week-display {
|
||||
min-width: 90px;
|
||||
|
||||
.week-label {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.week-dates {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
import {Component, inject, Input, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {catchError} from 'rxjs/operators';
|
||||
import {of} from 'rxjs';
|
||||
import {Select} from 'primeng/select';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {
|
||||
addWeeks,
|
||||
endOfISOWeek,
|
||||
getISOWeek,
|
||||
getISOWeeksInYear,
|
||||
getISOWeekYear,
|
||||
setISOWeek,
|
||||
setISOWeekYear,
|
||||
startOfISOWeek
|
||||
} from 'date-fns';
|
||||
import {BookType} from '../../../../../book/model/book.model';
|
||||
import {ReadingSessionTimelineResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
import {UrlHelperService} from '../../../../../../shared/service/url-helper.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface ReadingSession {
|
||||
startTime: Date;
|
||||
endTime: Date;
|
||||
duration: number;
|
||||
bookTitle?: string;
|
||||
bookId: number;
|
||||
bookType: BookType;
|
||||
}
|
||||
|
||||
interface TimelineSession {
|
||||
startHour: number;
|
||||
startMinute: number;
|
||||
endHour: number;
|
||||
endMinute: number;
|
||||
duration: number;
|
||||
left: number;
|
||||
width: number;
|
||||
bookTitle?: string;
|
||||
bookId: number;
|
||||
bookType: BookType;
|
||||
level: number;
|
||||
totalLevels: number;
|
||||
tooltipContent: string;
|
||||
}
|
||||
|
||||
interface DayTimeline {
|
||||
day: string;
|
||||
dayOfWeek: number;
|
||||
sessions: TimelineSession[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-session-timeline',
|
||||
standalone: true,
|
||||
imports: [CommonModule, Select, FormsModule, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-session-timeline.component.html',
|
||||
styleUrls: ['./reading-session-timeline.component.scss']
|
||||
})
|
||||
export class ReadingSessionTimelineComponent implements OnInit {
|
||||
@Input() initialYear: number = new Date().getFullYear();
|
||||
@Input() weekNumber: number = getISOWeek(new Date());
|
||||
|
||||
private userStatsService = inject(UserStatsService);
|
||||
private urlHelperService = inject(UrlHelperService);
|
||||
private translocoService = inject(TranslocoService);
|
||||
|
||||
public daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
public hourLabels: string[] = [];
|
||||
public timelineData: DayTimeline[] = [];
|
||||
public currentYear: number = new Date().getFullYear();
|
||||
public currentWeek: number = getISOWeek(new Date());
|
||||
private currentDate: Date = new Date();
|
||||
|
||||
public yearOptions: { label: string; value: number }[] = [];
|
||||
public weekOptions: { label: string; value: number }[] = [];
|
||||
|
||||
ngOnInit(): void {
|
||||
this.currentYear = this.initialYear;
|
||||
this.currentWeek = this.weekNumber;
|
||||
this.updateDateFromYearAndWeek();
|
||||
this.initializeYearOptions();
|
||||
this.ensureYearInOptions();
|
||||
this.updateWeekOptions();
|
||||
this.initializeHourLabels();
|
||||
this.loadReadingSessions();
|
||||
}
|
||||
|
||||
private initializeYearOptions(): void {
|
||||
const currentYear = new Date().getFullYear();
|
||||
this.yearOptions = [];
|
||||
for (let year = currentYear; year >= currentYear - 10; year--) {
|
||||
this.yearOptions.push({label: year.toString(), value: year});
|
||||
}
|
||||
}
|
||||
|
||||
private updateWeekOptions(): void {
|
||||
const weeksInYear = getISOWeeksInYear(this.currentDate);
|
||||
this.weekOptions = [];
|
||||
for (let week = 1; week <= weeksInYear; week++) {
|
||||
this.weekOptions.push({label: this.translocoService.translate('statsUser.sessionTimeline.week', {number: week}), value: week});
|
||||
}
|
||||
}
|
||||
|
||||
public onYearChange(): void {
|
||||
this.updateDateFromYearAndWeek();
|
||||
const maxWeeks = getISOWeeksInYear(this.currentDate);
|
||||
if (this.currentWeek > maxWeeks) {
|
||||
this.currentWeek = maxWeeks;
|
||||
this.updateDateFromYearAndWeek();
|
||||
}
|
||||
this.updateWeekOptions();
|
||||
this.loadReadingSessions();
|
||||
}
|
||||
|
||||
public onWeekChange(): void {
|
||||
this.updateDateFromYearAndWeek();
|
||||
this.loadReadingSessions();
|
||||
}
|
||||
|
||||
private initializeHourLabels(): void {
|
||||
for (let i = 0; i < 24; i++) {
|
||||
const hour = i === 0 ? 12 : i > 12 ? i - 12 : i;
|
||||
const period = i < 12 ? 'AM' : 'PM';
|
||||
this.hourLabels.push(`${hour} ${period}`);
|
||||
}
|
||||
}
|
||||
|
||||
private loadReadingSessions(): void {
|
||||
this.userStatsService.getTimelineForWeek(this.currentYear, this.currentWeek)
|
||||
.pipe(
|
||||
catchError((error) => {
|
||||
console.error('Error loading reading sessions:', error);
|
||||
return of([]);
|
||||
})
|
||||
)
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
const sessions = this.convertResponseToSessions(response);
|
||||
this.processSessionData(sessions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private convertResponseToSessions(response: ReadingSessionTimelineResponse[]): ReadingSession[] {
|
||||
const sessions: ReadingSession[] = [];
|
||||
|
||||
response.forEach((item) => {
|
||||
const startTime = new Date(item.startDate);
|
||||
const endTime = new Date(startTime.getTime() + item.totalDurationSeconds * 1000);
|
||||
const duration = item.totalDurationSeconds / 60;
|
||||
|
||||
sessions.push({
|
||||
startTime,
|
||||
endTime,
|
||||
duration,
|
||||
bookId: item.bookId,
|
||||
bookTitle: item.bookTitle,
|
||||
bookType: item.bookType
|
||||
});
|
||||
});
|
||||
|
||||
return sessions.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());
|
||||
}
|
||||
|
||||
public changeWeek(delta: number): void {
|
||||
this.currentDate = addWeeks(this.currentDate, delta);
|
||||
this.currentYear = getISOWeekYear(this.currentDate);
|
||||
this.currentWeek = getISOWeek(this.currentDate);
|
||||
|
||||
this.ensureYearInOptions();
|
||||
this.updateWeekOptions();
|
||||
this.loadReadingSessions();
|
||||
}
|
||||
|
||||
private ensureYearInOptions(): void {
|
||||
if (!this.yearOptions.some(option => option.value === this.currentYear)) {
|
||||
this.yearOptions.unshift({label: this.currentYear.toString(), value: this.currentYear});
|
||||
this.yearOptions.sort((a, b) => b.value - a.value);
|
||||
}
|
||||
}
|
||||
|
||||
private updateDateFromYearAndWeek(): void {
|
||||
this.currentDate = setISOWeek(setISOWeekYear(new Date(), this.currentYear), this.currentWeek);
|
||||
}
|
||||
|
||||
public getWeekDateRange(): string {
|
||||
const weekStart = startOfISOWeek(this.currentDate);
|
||||
const weekEnd = endOfISOWeek(this.currentDate);
|
||||
|
||||
const formatDate = (date: Date) => {
|
||||
const month = date.toLocaleDateString('en-US', {month: 'short'});
|
||||
const day = date.getDate();
|
||||
return `${month} ${day}`;
|
||||
};
|
||||
|
||||
return `${formatDate(weekStart)} - ${formatDate(weekEnd)}`;
|
||||
}
|
||||
|
||||
private processSessionData(sessions: ReadingSession[]): void {
|
||||
const dayMap = new Map<number, ReadingSession[]>();
|
||||
|
||||
sessions.forEach(session => {
|
||||
const sessionStart = new Date(session.startTime);
|
||||
const sessionEnd = new Date(session.endTime);
|
||||
|
||||
if (sessionStart.getDate() === sessionEnd.getDate()) {
|
||||
const dayOfWeek = sessionStart.getDay();
|
||||
if (!dayMap.has(dayOfWeek)) {
|
||||
dayMap.set(dayOfWeek, []);
|
||||
}
|
||||
dayMap.get(dayOfWeek)!.push(session);
|
||||
} else {
|
||||
let currentStart = new Date(sessionStart);
|
||||
|
||||
while (currentStart < sessionEnd) {
|
||||
const dayOfWeek = currentStart.getDay();
|
||||
const endOfDay = new Date(currentStart);
|
||||
endOfDay.setHours(23, 59, 59, 999);
|
||||
|
||||
const segmentEnd = sessionEnd < endOfDay ? sessionEnd : endOfDay;
|
||||
const segmentDuration = Math.floor((segmentEnd.getTime() - currentStart.getTime()) / (1000 * 60));
|
||||
|
||||
if (!dayMap.has(dayOfWeek)) {
|
||||
dayMap.set(dayOfWeek, []);
|
||||
}
|
||||
|
||||
dayMap.get(dayOfWeek)!.push({
|
||||
startTime: new Date(currentStart),
|
||||
endTime: new Date(segmentEnd),
|
||||
duration: segmentDuration,
|
||||
bookTitle: session.bookTitle,
|
||||
bookId: session.bookId,
|
||||
bookType: session.bookType
|
||||
});
|
||||
|
||||
currentStart = new Date(segmentEnd);
|
||||
currentStart.setDate(currentStart.getDate() + 1);
|
||||
currentStart.setHours(0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.timelineData = [];
|
||||
const displayOrder = [1, 2, 3, 4, 5, 6, 0];
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const dayOfWeek = displayOrder[i];
|
||||
const sessionsForDay = dayMap.get(dayOfWeek) || [];
|
||||
const timelineSessions = this.layoutSessionsForDay(sessionsForDay);
|
||||
|
||||
this.timelineData.push({
|
||||
day: this.daysOfWeek[i],
|
||||
dayOfWeek: dayOfWeek,
|
||||
sessions: timelineSessions
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly MAX_TRACKS = 3;
|
||||
|
||||
private layoutSessionsForDay(sessions: ReadingSession[]): TimelineSession[] {
|
||||
if (sessions.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
sessions.sort((a, b) => {
|
||||
if (a.startTime.getTime() !== b.startTime.getTime()) {
|
||||
return a.startTime.getTime() - b.startTime.getTime();
|
||||
}
|
||||
return b.endTime.getTime() - a.endTime.getTime();
|
||||
});
|
||||
|
||||
const tracks: ReadingSession[][] = [];
|
||||
|
||||
sessions.forEach(session => {
|
||||
let placed = false;
|
||||
for (let i = 0; i < tracks.length; i++) {
|
||||
const lastSessionInTrack = tracks[i][tracks[i].length - 1];
|
||||
if (session.startTime >= lastSessionInTrack.endTime) {
|
||||
tracks[i].push(session);
|
||||
placed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!placed) {
|
||||
if (tracks.length < ReadingSessionTimelineComponent.MAX_TRACKS) {
|
||||
tracks.push([session]);
|
||||
} else {
|
||||
tracks[tracks.length - 1].push(session);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const totalLevels = tracks.length;
|
||||
const timelineSessions: TimelineSession[] = [];
|
||||
|
||||
tracks.forEach((track, level) => {
|
||||
track.forEach(session => {
|
||||
timelineSessions.push(this.convertToTimelineSession(session, level, totalLevels));
|
||||
});
|
||||
});
|
||||
|
||||
return timelineSessions;
|
||||
}
|
||||
|
||||
private convertToTimelineSession(session: ReadingSession, level: number, totalLevels: number): TimelineSession {
|
||||
const startHour = session.startTime.getHours();
|
||||
const startMinute = session.startTime.getMinutes();
|
||||
const endHour = session.endTime.getHours();
|
||||
const endMinute = session.endTime.getMinutes();
|
||||
|
||||
const startDecimal = startHour + startMinute / 60;
|
||||
const endDecimal = endHour + endMinute / 60;
|
||||
|
||||
const left = (startDecimal / 24) * 100;
|
||||
let width = ((endDecimal - startDecimal) / 24) * 100;
|
||||
|
||||
if (width < 0.5) {
|
||||
width = 0.5;
|
||||
}
|
||||
|
||||
const timelineSession: TimelineSession = {
|
||||
startHour,
|
||||
startMinute,
|
||||
endHour,
|
||||
endMinute,
|
||||
duration: session.duration,
|
||||
left,
|
||||
width,
|
||||
bookTitle: session.bookTitle,
|
||||
bookId: session.bookId,
|
||||
bookType: session.bookType,
|
||||
level,
|
||||
totalLevels,
|
||||
tooltipContent: ''
|
||||
};
|
||||
timelineSession.tooltipContent = this.buildTooltipContent(timelineSession);
|
||||
return timelineSession;
|
||||
}
|
||||
|
||||
public formatTime(hour: number, minute: number): string {
|
||||
const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
|
||||
const period = hour < 12 ? 'AM' : 'PM';
|
||||
const displayMinute = minute.toString().padStart(2, '0');
|
||||
return `${displayHour}:${displayMinute} ${period}`;
|
||||
}
|
||||
|
||||
public formatDuration(minutes: number): string {
|
||||
const totalSeconds = Math.round(minutes * 60);
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const mins = Math.floor((totalSeconds % 3600) / 60);
|
||||
const secs = totalSeconds % 60;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (hours) parts.push(`${hours}h`);
|
||||
if (mins || hours) parts.push(`${mins}m`);
|
||||
parts.push(`${secs}s`);
|
||||
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
public formatDurationCompact(minutes: number): string {
|
||||
const totalSeconds = Math.round(minutes * 60);
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const mins = Math.floor((totalSeconds % 3600) / 60);
|
||||
const secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) return `${hours}h${mins > 0 ? mins + 'm' : ''}`;
|
||||
if (mins > 0) return `${mins}m${secs > 0 ? secs + 's' : ''}`;
|
||||
return `${secs}s`;
|
||||
}
|
||||
|
||||
public isDurationGreaterThanOneHour(minutes: number): boolean {
|
||||
return minutes >= 60;
|
||||
}
|
||||
|
||||
public getCoverUrl(bookId: number): string {
|
||||
return this.urlHelperService.getDirectThumbnailUrl(bookId);
|
||||
}
|
||||
|
||||
private buildTooltipContent(session: TimelineSession): string {
|
||||
return `
|
||||
<div class="session-tooltip-content">
|
||||
<div class="session-tooltip-cover">
|
||||
<img src="${this.getCoverUrl(session.bookId)}" alt="Book Cover">
|
||||
</div>
|
||||
<div class="session-tooltip-details">
|
||||
<div class="session-tooltip-header">
|
||||
<i class="pi pi-book"></i>
|
||||
<span class="session-tooltip-title">${session.bookTitle || this.translocoService.translate('statsUser.sessionTimeline.readingSession')}</span>
|
||||
</div>
|
||||
<div class="session-tooltip-divider"></div>
|
||||
<div class="session-tooltip-body">
|
||||
<div class="session-tooltip-row">
|
||||
<i class="pi pi-clock"></i>
|
||||
<span class="session-tooltip-label">${this.translocoService.translate('statsUser.sessionTimeline.tooltipTime')}</span>
|
||||
<span class="session-tooltip-value">
|
||||
${this.formatTime(session.startHour, session.startMinute)} - ${this.formatTime(session.endHour, session.endMinute)}
|
||||
</span>
|
||||
</div>
|
||||
<div class="session-tooltip-row">
|
||||
<i class="pi pi-hourglass"></i>
|
||||
<span class="session-tooltip-label">${this.translocoService.translate('statsUser.sessionTimeline.tooltipDuration')}</span>
|
||||
<span class="session-tooltip-value">${this.formatDuration(session.duration)}</span>
|
||||
</div>
|
||||
<div class="session-tooltip-row">
|
||||
<i class="pi pi-file"></i>
|
||||
<span class="session-tooltip-label">${this.translocoService.translate('statsUser.sessionTimeline.tooltipFormat')}</span>
|
||||
<span class="session-tooltip-value">${session.bookType || this.translocoService.translate('statsUser.sessionTimeline.unknown')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.readingSurvival'">
|
||||
<div class="reading-survival-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-line reading-survival-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (totalStarted() > 0) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card">
|
||||
<span class="stat-value">{{ totalStarted() }}</span>
|
||||
<span class="stat-label">{{ t('started') }}</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-value">{{ completionRate() }}%</span>
|
||||
<span class="stat-label">{{ t('completionRate') }}</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-value">{{ medianDropout() }}</span>
|
||||
<span class="stat-label">{{ t('medianDropout') }}</span>
|
||||
</div>
|
||||
<div class="stat-card danger">
|
||||
<span class="stat-value">{{ dangerZoneRange() }}</span>
|
||||
<span class="stat-subtitle">{{ dangerZoneDrop() }}</span>
|
||||
<span class="stat-label">{{ t('dangerZone') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="chartData()"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (totalStarted() === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
.reading-survival-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.reading-survival-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #e91e63;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
flex: 1;
|
||||
min-width: 80px;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: #e91e63;
|
||||
}
|
||||
|
||||
.stat-subtitle {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
&.danger .stat-value {
|
||||
color: #ff5722;
|
||||
}
|
||||
|
||||
&.danger .stat-subtitle {
|
||||
color: #ff5722;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.stats-row .stat-card {
|
||||
min-width: 70px;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 280px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header .chart-title h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
gap: 0.5rem;
|
||||
|
||||
.stat-card {
|
||||
padding: 0.4rem 0.5rem;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import {Component, computed, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
type SurvivalChartData = ChartData<'line', number[], string>;
|
||||
|
||||
interface SurvivalMetrics {
|
||||
totalStarted: number;
|
||||
completionRate: number;
|
||||
medianDropout: string;
|
||||
dangerZoneRange: string;
|
||||
dangerZoneDrop: string;
|
||||
chartData: SurvivalChartData;
|
||||
}
|
||||
|
||||
const THRESHOLDS = [0, 10, 25, 50, 75, 90, 100];
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-survival-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './reading-survival-chart.component.html',
|
||||
styleUrls: ['./reading-survival-chart.component.scss']
|
||||
})
|
||||
export class ReadingSurvivalChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly survivalMetrics = computed<SurvivalMetrics>(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
return this.calculateSurvivalMetrics(this.bookService.books());
|
||||
});
|
||||
|
||||
public readonly chartType = 'line' as const;
|
||||
public readonly totalStarted = computed(() => this.survivalMetrics().totalStarted);
|
||||
public readonly completionRate = computed(() => this.survivalMetrics().completionRate);
|
||||
public readonly medianDropout = computed(() => this.survivalMetrics().medianDropout);
|
||||
public readonly dangerZoneRange = computed(() => this.survivalMetrics().dangerZoneRange);
|
||||
public readonly dangerZoneDrop = computed(() => this.survivalMetrics().dangerZoneDrop);
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'line'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {top: 10, bottom: 10, left: 10, right: 10}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#e91e63',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 12},
|
||||
callbacks: {
|
||||
title: (context) => this.t.translate('statsUser.readingSurvival.tooltipProgress', {label: context[0].label}),
|
||||
label: (context) => this.t.translate('statsUser.readingSurvival.tooltipSurvival', {value: (context.parsed.y ?? 0).toFixed(1)})
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.readingSurvival.axisProgressThreshold'),
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 12, weight: 'bold'}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11}
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
border: {display: false}
|
||||
},
|
||||
y: {
|
||||
min: 0,
|
||||
max: 100,
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.readingSurvival.axisBooksSurviving'),
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 12, weight: 'bold'}
|
||||
},
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {family: "'Inter', sans-serif", size: 11},
|
||||
callback: (value) => `${value}%`
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
border: {display: false}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public readonly chartData = computed(() => this.survivalMetrics().chartData);
|
||||
|
||||
private calculateSurvivalMetrics(books: Book[]): SurvivalMetrics {
|
||||
if (books.length === 0) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
const startedBooks = books.filter(b => this.getBookProgress(b) > 0);
|
||||
const totalStarted = startedBooks.length;
|
||||
|
||||
if (totalStarted === 0) {
|
||||
return this.emptyMetrics();
|
||||
}
|
||||
|
||||
const progresses = startedBooks.map(b => this.getBookProgress(b));
|
||||
const survivalValues = THRESHOLDS.map(threshold => {
|
||||
const survived = progresses.filter(p => p >= threshold).length;
|
||||
return (survived / totalStarted) * 100;
|
||||
});
|
||||
|
||||
const completionRate = Math.round(survivalValues[survivalValues.length - 1]);
|
||||
|
||||
let medianIdx = survivalValues.findIndex(v => v < 50);
|
||||
let medianDropout = '';
|
||||
if (medianIdx === -1) {
|
||||
medianDropout = '100%+';
|
||||
} else if (medianIdx === 0) {
|
||||
medianDropout = `${THRESHOLDS[0]}%`;
|
||||
} else {
|
||||
medianDropout = `${THRESHOLDS[medianIdx - 1]}-${THRESHOLDS[medianIdx]}%`;
|
||||
}
|
||||
|
||||
let maxDrop = 0;
|
||||
let dangerIdx = 0;
|
||||
for (let i = 1; i < survivalValues.length; i++) {
|
||||
const drop = survivalValues[i - 1] - survivalValues[i];
|
||||
if (drop > maxDrop) {
|
||||
maxDrop = drop;
|
||||
dangerIdx = i;
|
||||
}
|
||||
}
|
||||
const dangerZoneRange = `${THRESHOLDS[dangerIdx - 1]}-${THRESHOLDS[dangerIdx]}%`;
|
||||
const dangerZoneDrop = `-${maxDrop.toFixed(0)}%`;
|
||||
|
||||
const labels = THRESHOLDS.map(t => `${t}%`);
|
||||
return {
|
||||
totalStarted,
|
||||
completionRate,
|
||||
medianDropout,
|
||||
dangerZoneRange,
|
||||
dangerZoneDrop,
|
||||
chartData: {
|
||||
labels,
|
||||
datasets: [{
|
||||
label: this.t.translate('statsUser.readingSurvival.survivalRate'),
|
||||
data: survivalValues,
|
||||
borderColor: '#e91e63',
|
||||
backgroundColor: 'rgba(233, 30, 99, 0.15)',
|
||||
fill: true,
|
||||
stepped: true,
|
||||
pointRadius: 5,
|
||||
pointHoverRadius: 7,
|
||||
pointBackgroundColor: '#e91e63',
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 2,
|
||||
borderWidth: 2
|
||||
}]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private emptyMetrics(): SurvivalMetrics {
|
||||
return {
|
||||
totalStarted: 0,
|
||||
completionRate: 0,
|
||||
medianDropout: '',
|
||||
dangerZoneRange: '',
|
||||
dangerZoneDrop: '',
|
||||
chartData: {labels: [], datasets: []}
|
||||
};
|
||||
}
|
||||
|
||||
private getBookProgress(book: Book): number {
|
||||
if (book.pdfProgress?.percentage) return book.pdfProgress.percentage;
|
||||
if (book.epubProgress?.percentage) return book.epubProgress.percentage;
|
||||
if (book.cbxProgress?.percentage) return book.cbxProgress.percentage;
|
||||
if (book.koreaderProgress?.percentage) return book.koreaderProgress.percentage;
|
||||
if (book.koboProgress?.percentage) return book.koboProgress.percentage;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.seriesProgress'">
|
||||
<div class="series-progress-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-list series-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
@if (stats) {
|
||||
<div class="series-summary">
|
||||
<span class="summary-item completed">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
{{ stats.completedSeries }}
|
||||
</span>
|
||||
<span class="summary-item in-progress">
|
||||
<i class="pi pi-spinner"></i>
|
||||
{{ stats.inProgressSeries }}
|
||||
</span>
|
||||
<span class="summary-item not-started">
|
||||
<i class="pi pi-clock"></i>
|
||||
{{ stats.notStartedSeries }}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (stats) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-pill">
|
||||
<span class="pill-value">{{ stats.totalSeries }}</span>
|
||||
<span class="pill-label">{{ t('series') }}</span>
|
||||
</div>
|
||||
<div class="stat-pill">
|
||||
<span class="pill-value">{{ stats.avgSeriesCompletion }}%</span>
|
||||
<span class="pill-label">{{ t('avgCompletion') }}</span>
|
||||
</div>
|
||||
@if (stats.highestRatedSeries) {
|
||||
<div class="stat-pill highlight">
|
||||
<span class="pill-value">{{ stats.highestRatedSeries.avgPersonalRating?.toFixed(1) }}</span>
|
||||
<span class="pill-label">{{ t('topRated') }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (seriesList.length > 0) {
|
||||
<div class="series-details">
|
||||
<div class="details-header">
|
||||
<h4>{{ t('seriesBreakdown') }}</h4>
|
||||
<span class="series-count">{{ t('ofTotal', { filtered: filteredSeriesList.length, total: seriesList.length }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="controls-row">
|
||||
<div class="search-box">
|
||||
<i class="pi pi-search"></i>
|
||||
<input
|
||||
type="text"
|
||||
[placeholder]="t('searchSeries')"
|
||||
[value]="searchTerm"
|
||||
(input)="onSearchChange($any($event.target).value)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="filter-controls">
|
||||
<select class="filter-select" [value]="filterStatus" (change)="onFilterChange($any($event.target).value)">
|
||||
<option value="all">{{ t('allStatus') }}</option>
|
||||
<option value="in-progress">{{ t('inProgress') }}</option>
|
||||
<option value="completed">{{ t('completed') }}</option>
|
||||
<option value="not-started">{{ t('notStarted') }}</option>
|
||||
</select>
|
||||
|
||||
<select class="sort-select" [value]="sortBy" (change)="onSortChange($any($event.target).value)">
|
||||
<option value="progress">{{ t('sortByProgress') }}</option>
|
||||
<option value="rating">{{ t('sortByRating') }}</option>
|
||||
<option value="books">{{ t('sortByBooks') }}</option>
|
||||
<option value="name">{{ t('sortByName') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="series-list">
|
||||
@for (series of displayedSeries; track series.name) {
|
||||
<div class="series-card" [class]="series.status">
|
||||
<div class="series-main">
|
||||
<div class="series-status-icon" [style.color]="getStatusColor(series.status)">
|
||||
<i [class]="'pi ' + getStatusIcon(series.status)"></i>
|
||||
</div>
|
||||
<div class="series-info">
|
||||
<span class="series-name">{{ series.name }}</span>
|
||||
<div class="series-meta">
|
||||
<span class="books-count">
|
||||
{{ t('booksRead', { read: series.booksRead, owned: series.booksOwned }) }}
|
||||
@if (series.totalInSeries) {
|
||||
<span class="total-hint">{{ t('inSeriesHint', { total: series.totalInSeries }) }}</span>
|
||||
}
|
||||
</span>
|
||||
@if (series.avgPersonalRating) {
|
||||
<span class="rating">
|
||||
<i class="pi pi-star-fill"></i>
|
||||
{{ series.avgPersonalRating.toFixed(1) }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="series-progress">
|
||||
<div class="progress-bar-container">
|
||||
<div class="progress-bar read" [style.width.%]="series.completionPercentage"></div>
|
||||
@if (series.booksReading > 0) {
|
||||
<div class="progress-bar reading"
|
||||
[style.width.%]="(series.booksReading / series.booksOwned) * 100"
|
||||
[style.left.%]="series.completionPercentage">
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<span class="progress-text">{{ series.completionPercentage }}%</span>
|
||||
</div>
|
||||
@if (series.nextUnread && series.status !== 'completed') {
|
||||
<div class="next-up">
|
||||
<span class="next-label">{{ t('next') }}</span>
|
||||
<span class="next-title">{{ series.nextUnread }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (filteredSeriesList.length === 0 && searchTerm) {
|
||||
<div class="no-results">
|
||||
<i class="pi pi-search"></i>
|
||||
<span>{{ t('noMatchingSearch', { term: searchTerm }) }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (getTotalPages() > 1) {
|
||||
<div class="pagination">
|
||||
<button
|
||||
class="page-btn"
|
||||
[disabled]="!hasPrevPage()"
|
||||
(click)="prevPage()">
|
||||
<i class="pi pi-chevron-left"></i>
|
||||
</button>
|
||||
<span class="page-info">
|
||||
{{ t('pageInfo', { current: currentPage + 1, total: getTotalPages() }) }}
|
||||
</span>
|
||||
<button
|
||||
class="page-btn"
|
||||
[disabled]="!hasNextPage()"
|
||||
(click)="nextPage()">
|
||||
<i class="pi pi-chevron-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!stats) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+545
@@ -0,0 +1,545 @@
|
||||
.series-progress-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
|
||||
h3 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 0.5rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.series-summary {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
|
||||
.summary-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.35rem 0.6rem;
|
||||
border-radius: 16px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
|
||||
i {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
&.completed {
|
||||
background: rgba(76, 175, 80, 0.2);
|
||||
color: #4caf50;
|
||||
}
|
||||
|
||||
&.in-progress {
|
||||
background: rgba(255, 193, 7, 0.2);
|
||||
color: #ffc107;
|
||||
}
|
||||
|
||||
&.not-started {
|
||||
background: rgba(158, 158, 158, 0.2);
|
||||
color: #9e9e9e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.series-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #673ab7;
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.stat-pill {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.85rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 20px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
.pill-value {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.pill-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
|
||||
&.highlight {
|
||||
background: rgba(103, 58, 183, 0.15);
|
||||
border-color: rgba(103, 58, 183, 0.3);
|
||||
|
||||
.pill-value {
|
||||
color: #673ab7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.series-details {
|
||||
.details-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.75rem;
|
||||
|
||||
h4 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 0.95rem;
|
||||
font-weight: 500;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.series-count {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.controls-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.search-box {
|
||||
flex: 1;
|
||||
min-width: 150px;
|
||||
max-width: 250px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.4rem 0.65rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 6px;
|
||||
|
||||
i {
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 0.8rem;
|
||||
font-family: inherit;
|
||||
|
||||
&::placeholder {
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
|
||||
.filter-select,
|
||||
.sort-select {
|
||||
padding: 0.4rem 0.5rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 6px;
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 0.75rem;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
|
||||
option {
|
||||
background: #1e1e1e;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
border-color: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
border-color: #673ab7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.series-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
max-height: 360px;
|
||||
overflow-y: auto;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.no-results {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 1.5rem;
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 0.85rem;
|
||||
|
||||
i {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
|
||||
.page-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 6px;
|
||||
color: var(--text-color, #ffffff);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
i {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(103, 58, 183, 0.3);
|
||||
border-color: #673ab7;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.page-info {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
min-width: 80px;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.series-card {
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-left: 3px solid;
|
||||
|
||||
&.completed {
|
||||
border-left-color: #4caf50;
|
||||
}
|
||||
|
||||
&.in-progress {
|
||||
border-left-color: #ffc107;
|
||||
}
|
||||
|
||||
&.not-started {
|
||||
border-left-color: #9e9e9e;
|
||||
}
|
||||
|
||||
&.abandoned {
|
||||
border-left-color: #ef5350;
|
||||
}
|
||||
|
||||
.series-main {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.35rem;
|
||||
|
||||
.series-status-icon {
|
||||
font-size: 0.9rem;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
.series-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
.series-name {
|
||||
display: block;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color, #ffffff);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.series-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.2rem;
|
||||
|
||||
.books-count {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
.total-hint {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.rating {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
font-size: 0.75rem;
|
||||
color: #ffc107;
|
||||
|
||||
i {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.series-progress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
.progress-bar-container {
|
||||
flex: 1;
|
||||
height: 6px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
.progress-bar {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
height: 100%;
|
||||
border-radius: 3px;
|
||||
transition: width 0.3s ease;
|
||||
|
||||
&.read {
|
||||
left: 0;
|
||||
background: linear-gradient(90deg, #4caf50, #66bb6a);
|
||||
}
|
||||
|
||||
&.reading {
|
||||
background: #ffc107;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
min-width: 32px;
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
|
||||
.next-up {
|
||||
margin-top: 0.35rem;
|
||||
padding-top: 0.3rem;
|
||||
border-top: 1px dashed rgba(255, 255, 255, 0.1);
|
||||
font-size: 0.7rem;
|
||||
|
||||
.next-label {
|
||||
color: var(--text-secondary-color);
|
||||
margin-right: 0.35rem;
|
||||
}
|
||||
|
||||
.next-title {
|
||||
color: #673ab7;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.no-data-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2.5rem;
|
||||
text-align: center;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 0.75rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 0.95rem;
|
||||
margin: 0 0 0.35rem 0;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chart-header {
|
||||
.series-summary {
|
||||
width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
.stat-pill {
|
||||
flex: 1;
|
||||
min-width: 80px;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 240px;
|
||||
}
|
||||
|
||||
.series-details {
|
||||
.controls-row {
|
||||
flex-direction: column;
|
||||
|
||||
.search-box {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
width: 100%;
|
||||
|
||||
.filter-select,
|
||||
.sort-select {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.series-summary {
|
||||
.summary-item {
|
||||
padding: 0.25rem 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.stats-row {
|
||||
gap: 0.5rem;
|
||||
|
||||
.stat-pill {
|
||||
padding: 0.4rem 0.6rem;
|
||||
|
||||
.pill-value {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.pill-label {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.series-details {
|
||||
.series-card {
|
||||
padding: 0.5rem 0.65rem;
|
||||
|
||||
.series-main {
|
||||
.series-info {
|
||||
.series-name {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+612
@@ -0,0 +1,612 @@
|
||||
import {Component, effect, inject} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface SeriesInfo {
|
||||
name: string;
|
||||
booksOwned: number;
|
||||
booksRead: number;
|
||||
booksReading: number;
|
||||
booksPartiallyRead: number;
|
||||
booksPaused: number;
|
||||
booksAbandoned: number;
|
||||
booksWontRead: number;
|
||||
booksUnread: number;
|
||||
totalInSeries: number | null;
|
||||
completionPercentage: number;
|
||||
avgPersonalRating: number | null;
|
||||
avgExternalRating: number | null;
|
||||
nextUnread: string | null;
|
||||
status: 'completed' | 'in-progress' | 'not-started' | 'abandoned' | 'paused';
|
||||
}
|
||||
|
||||
interface SeriesStats {
|
||||
totalSeries: number;
|
||||
completedSeries: number;
|
||||
inProgressSeries: number;
|
||||
notStartedSeries: number;
|
||||
avgSeriesCompletion: number;
|
||||
mostReadSeries: SeriesInfo | null;
|
||||
highestRatedSeries: SeriesInfo | null;
|
||||
}
|
||||
|
||||
type SeriesChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-series-progress-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
|
||||
templateUrl: './series-progress-chart.component.html',
|
||||
styleUrls: ['./series-progress-chart.component.scss']
|
||||
})
|
||||
export class SeriesProgressChartComponent {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly syncChartEffect = effect(() => {
|
||||
if (this.bookService.isBooksLoading()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.calculateAndUpdateChart(this.bookService.books(), this.libraryFilterService.selectedLibrary());
|
||||
});
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public seriesList: SeriesInfo[] = [];
|
||||
public filteredSeriesList: SeriesInfo[] = [];
|
||||
public stats: SeriesStats | null = null;
|
||||
public displayedSeries: SeriesInfo[] = [];
|
||||
public chartSeries: SeriesInfo[] = [];
|
||||
|
||||
// Pagination & filtering
|
||||
public searchTerm = '';
|
||||
public currentPage = 0;
|
||||
public readonly PAGE_SIZE = 10;
|
||||
public readonly CHART_DISPLAY_COUNT = 8;
|
||||
public sortBy: 'progress' | 'rating' | 'books' | 'name' = 'progress';
|
||||
public filterStatus: 'all' | 'completed' | 'in-progress' | 'not-started' | 'paused' | 'abandoned' = 'all';
|
||||
|
||||
public readonly chartOptions: ChartConfiguration<'bar'>['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
indexAxis: 'y',
|
||||
layout: {
|
||||
padding: {top: 10, right: 20, bottom: 10, left: 10}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
stacked: true,
|
||||
max: 100,
|
||||
title: {
|
||||
display: true,
|
||||
text: this.t.translate('statsUser.seriesProgress.axisCompletion'),
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11,
|
||||
weight: 500
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
},
|
||||
callback: (value) => `${value}%`
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
}
|
||||
},
|
||||
y: {
|
||||
stacked: true,
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
display: false
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10
|
||||
},
|
||||
usePointStyle: true,
|
||||
pointStyle: 'rect',
|
||||
padding: 12
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#673ab7',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 12, weight: 'bold'},
|
||||
bodyFont: {size: 10},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const series = this.chartSeries[context[0].dataIndex];
|
||||
return series ? series.name : '';
|
||||
},
|
||||
afterBody: (context) => {
|
||||
const series = this.chartSeries[context[0].dataIndex];
|
||||
if (!series) return [];
|
||||
const lines = [
|
||||
this.t.translate('statsUser.seriesProgress.tooltipRead', {read: series.booksRead, owned: series.booksOwned})
|
||||
];
|
||||
if (series.totalInSeries) {
|
||||
lines.push(this.t.translate('statsUser.seriesProgress.tooltipSeriesTotal', {total: series.totalInSeries}));
|
||||
}
|
||||
if (series.avgPersonalRating) {
|
||||
lines.push(this.t.translate('statsUser.seriesProgress.tooltipYourRating', {rating: series.avgPersonalRating.toFixed(1)}));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<SeriesChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<SeriesChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
onSearchChange(term: string): void {
|
||||
this.searchTerm = term.toLowerCase().trim();
|
||||
this.currentPage = 0;
|
||||
this.applyFiltersAndSort();
|
||||
}
|
||||
|
||||
onSortChange(sortBy: 'progress' | 'rating' | 'books' | 'name'): void {
|
||||
this.sortBy = sortBy;
|
||||
this.currentPage = 0;
|
||||
this.applyFiltersAndSort();
|
||||
}
|
||||
|
||||
onFilterChange(status: 'all' | 'completed' | 'in-progress' | 'not-started' | 'paused' | 'abandoned'): void {
|
||||
this.filterStatus = status;
|
||||
this.currentPage = 0;
|
||||
this.applyFiltersAndSort();
|
||||
}
|
||||
|
||||
nextPage(): void {
|
||||
if (this.hasNextPage()) {
|
||||
this.currentPage++;
|
||||
this.updateDisplayedSeries();
|
||||
}
|
||||
}
|
||||
|
||||
prevPage(): void {
|
||||
if (this.hasPrevPage()) {
|
||||
this.currentPage--;
|
||||
this.updateDisplayedSeries();
|
||||
}
|
||||
}
|
||||
|
||||
hasNextPage(): boolean {
|
||||
return (this.currentPage + 1) * this.PAGE_SIZE < this.filteredSeriesList.length;
|
||||
}
|
||||
|
||||
hasPrevPage(): boolean {
|
||||
return this.currentPage > 0;
|
||||
}
|
||||
|
||||
getTotalPages(): number {
|
||||
return Math.ceil(this.filteredSeriesList.length / this.PAGE_SIZE);
|
||||
}
|
||||
|
||||
private applyFiltersAndSort(): void {
|
||||
let filtered = [...this.seriesList];
|
||||
|
||||
// Apply search filter
|
||||
if (this.searchTerm) {
|
||||
filtered = filtered.filter(s =>
|
||||
s.name.toLowerCase().includes(this.searchTerm)
|
||||
);
|
||||
}
|
||||
|
||||
// Apply status filter
|
||||
if (this.filterStatus !== 'all') {
|
||||
filtered = filtered.filter(s => s.status === this.filterStatus);
|
||||
}
|
||||
|
||||
// Apply sorting
|
||||
filtered.sort((a, b) => {
|
||||
switch (this.sortBy) {
|
||||
case 'progress':
|
||||
return b.completionPercentage - a.completionPercentage;
|
||||
case 'rating':
|
||||
return (b.avgPersonalRating || 0) - (a.avgPersonalRating || 0);
|
||||
case 'books':
|
||||
return b.booksOwned - a.booksOwned;
|
||||
case 'name':
|
||||
return a.name.localeCompare(b.name);
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
this.filteredSeriesList = filtered;
|
||||
this.updateDisplayedSeries();
|
||||
this.updateChartSeries();
|
||||
this.updateChartData();
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(books: Book[], selectedLibraryId: number | null): void {
|
||||
if (books.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.seriesList = [];
|
||||
this.displayedSeries = [];
|
||||
this.stats = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(books, selectedLibraryId);
|
||||
const seriesBooks = this.getBooksInSeries(filteredBooks);
|
||||
|
||||
if (seriesBooks.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.seriesList = [];
|
||||
this.filteredSeriesList = [];
|
||||
this.displayedSeries = [];
|
||||
this.chartSeries = [];
|
||||
this.stats = null;
|
||||
return;
|
||||
}
|
||||
|
||||
this.seriesList = this.calculateSeriesInfo(seriesBooks);
|
||||
this.stats = this.calculateSeriesStats(this.seriesList);
|
||||
this.currentPage = 0;
|
||||
this.applyFiltersAndSort();
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private getBooksInSeries(books: Book[]): Book[] {
|
||||
return books.filter(book => book.metadata?.seriesName);
|
||||
}
|
||||
|
||||
private calculateSeriesInfo(books: Book[]): SeriesInfo[] {
|
||||
const seriesMap = new Map<string, Book[]>();
|
||||
|
||||
books.forEach(book => {
|
||||
const seriesName = book.metadata!.seriesName!;
|
||||
if (!seriesMap.has(seriesName)) {
|
||||
seriesMap.set(seriesName, []);
|
||||
}
|
||||
seriesMap.get(seriesName)!.push(book);
|
||||
});
|
||||
|
||||
const seriesInfoList: SeriesInfo[] = [];
|
||||
|
||||
seriesMap.forEach((seriesBooks, seriesName) => {
|
||||
const booksOwned = seriesBooks.length;
|
||||
let booksRead = 0;
|
||||
let booksReading = 0;
|
||||
let booksPartiallyRead = 0;
|
||||
let booksPaused = 0;
|
||||
let booksAbandoned = 0;
|
||||
let booksWontRead = 0;
|
||||
let booksUnread = 0;
|
||||
let totalRating = 0;
|
||||
let ratedCount = 0;
|
||||
let totalExternalRating = 0;
|
||||
let externalRatedCount = 0;
|
||||
let totalInSeries: number | null = null;
|
||||
let nextUnread: string | null = null;
|
||||
|
||||
// Sort by series number for finding next unread
|
||||
const sortedBooks = [...seriesBooks].sort((a, b) => {
|
||||
const numA = a.metadata?.seriesNumber || 999;
|
||||
const numB = b.metadata?.seriesNumber || 999;
|
||||
return numA - numB;
|
||||
});
|
||||
|
||||
sortedBooks.forEach(book => {
|
||||
// Track series total
|
||||
if (book.metadata?.seriesTotal && (!totalInSeries || book.metadata.seriesTotal > totalInSeries)) {
|
||||
totalInSeries = book.metadata.seriesTotal;
|
||||
}
|
||||
|
||||
// Count by status - handle ALL ReadStatus values
|
||||
switch (book.readStatus) {
|
||||
case ReadStatus.READ:
|
||||
booksRead++;
|
||||
break;
|
||||
case ReadStatus.READING:
|
||||
case ReadStatus.RE_READING:
|
||||
booksReading++;
|
||||
break;
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
booksPartiallyRead++;
|
||||
if (!nextUnread) {
|
||||
nextUnread = book.metadata?.title || book.fileName || null;
|
||||
}
|
||||
break;
|
||||
case ReadStatus.PAUSED:
|
||||
booksPaused++;
|
||||
if (!nextUnread) {
|
||||
nextUnread = book.metadata?.title || book.fileName || null;
|
||||
}
|
||||
break;
|
||||
case ReadStatus.ABANDONED:
|
||||
booksAbandoned++;
|
||||
break;
|
||||
case ReadStatus.WONT_READ:
|
||||
booksWontRead++;
|
||||
break;
|
||||
case ReadStatus.UNREAD:
|
||||
case ReadStatus.UNSET:
|
||||
default:
|
||||
booksUnread++;
|
||||
if (!nextUnread) {
|
||||
nextUnread = book.metadata?.title || book.fileName || null;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Personal rating
|
||||
if (book.personalRating && book.personalRating > 0) {
|
||||
totalRating += book.personalRating;
|
||||
ratedCount++;
|
||||
}
|
||||
|
||||
// External rating
|
||||
const extRating = this.getExternalRating(book);
|
||||
if (extRating > 0) {
|
||||
totalExternalRating += extRating;
|
||||
externalRatedCount++;
|
||||
}
|
||||
});
|
||||
|
||||
// Calculate completion percentage based on what we own (excluding won't read/abandoned)
|
||||
const relevantBooks = booksOwned - booksWontRead - booksAbandoned;
|
||||
const completionPercentage = relevantBooks > 0 ? Math.round((booksRead / relevantBooks) * 100) : 0;
|
||||
|
||||
// Determine series status based on comprehensive analysis
|
||||
let status: 'completed' | 'in-progress' | 'not-started' | 'abandoned' | 'paused';
|
||||
if (booksRead === relevantBooks && relevantBooks > 0) {
|
||||
status = 'completed';
|
||||
} else if (booksReading > 0) {
|
||||
status = 'in-progress';
|
||||
} else if (booksPaused > 0 && booksRead > 0) {
|
||||
status = 'paused';
|
||||
} else if (booksRead > 0 || booksPartiallyRead > 0) {
|
||||
status = 'in-progress';
|
||||
} else if ((booksAbandoned > 0 || booksWontRead > 0) && booksRead === 0 && booksReading === 0) {
|
||||
status = 'abandoned';
|
||||
} else {
|
||||
status = 'not-started';
|
||||
}
|
||||
|
||||
seriesInfoList.push({
|
||||
name: seriesName,
|
||||
booksOwned,
|
||||
booksRead,
|
||||
booksReading,
|
||||
booksPartiallyRead,
|
||||
booksPaused,
|
||||
booksAbandoned,
|
||||
booksWontRead,
|
||||
booksUnread,
|
||||
totalInSeries,
|
||||
completionPercentage,
|
||||
avgPersonalRating: ratedCount > 0 ? totalRating / ratedCount : null,
|
||||
avgExternalRating: externalRatedCount > 0 ? totalExternalRating / externalRatedCount : null,
|
||||
nextUnread,
|
||||
status
|
||||
});
|
||||
});
|
||||
|
||||
// Sort by: in-progress first, then by completion %, then by books owned
|
||||
return seriesInfoList.sort((a, b) => {
|
||||
// Priority: in-progress > not-started > completed > abandoned
|
||||
const statusOrder = {'in-progress': 0, 'paused': 1, 'not-started': 2, 'completed': 3, 'abandoned': 4};
|
||||
const statusDiff = statusOrder[a.status] - statusOrder[b.status];
|
||||
if (statusDiff !== 0) return statusDiff;
|
||||
|
||||
// Then by books owned (more books = more interesting)
|
||||
return b.booksOwned - a.booksOwned;
|
||||
});
|
||||
}
|
||||
|
||||
private getExternalRating(book: Book): number {
|
||||
const ratings: number[] = [];
|
||||
if (book.metadata?.goodreadsRating) ratings.push(book.metadata.goodreadsRating);
|
||||
if (book.metadata?.amazonRating) ratings.push(book.metadata.amazonRating);
|
||||
if (book.metadata?.hardcoverRating) ratings.push(book.metadata.hardcoverRating);
|
||||
|
||||
if (ratings.length > 0) {
|
||||
return ratings.reduce((sum, r) => sum + r, 0) / ratings.length;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private calculateSeriesStats(seriesList: SeriesInfo[]): SeriesStats {
|
||||
const completedSeries = seriesList.filter(s => s.status === 'completed').length;
|
||||
const inProgressSeries = seriesList.filter(s => s.status === 'in-progress').length;
|
||||
const notStartedSeries = seriesList.filter(s => s.status === 'not-started').length;
|
||||
|
||||
const totalCompletion = seriesList.reduce((sum, s) => sum + s.completionPercentage, 0);
|
||||
const avgSeriesCompletion = seriesList.length > 0 ? Math.round(totalCompletion / seriesList.length) : 0;
|
||||
|
||||
const mostReadSeries = [...seriesList].sort((a, b) => b.booksRead - a.booksRead)[0] || null;
|
||||
|
||||
const ratedSeries = seriesList.filter(s => s.avgPersonalRating !== null);
|
||||
const highestRatedSeries = ratedSeries.length > 0
|
||||
? [...ratedSeries].sort((a, b) => (b.avgPersonalRating || 0) - (a.avgPersonalRating || 0))[0]
|
||||
: null;
|
||||
|
||||
return {
|
||||
totalSeries: seriesList.length,
|
||||
completedSeries,
|
||||
inProgressSeries,
|
||||
notStartedSeries,
|
||||
avgSeriesCompletion,
|
||||
mostReadSeries,
|
||||
highestRatedSeries
|
||||
};
|
||||
}
|
||||
|
||||
private updateDisplayedSeries(): void {
|
||||
const start = this.currentPage * this.PAGE_SIZE;
|
||||
const end = start + this.PAGE_SIZE;
|
||||
this.displayedSeries = this.filteredSeriesList.slice(start, end);
|
||||
}
|
||||
|
||||
private updateChartSeries(): void {
|
||||
// For chart, show top series by in-progress first, then by books owned
|
||||
const chartData = [...this.seriesList]
|
||||
.sort((a, b) => {
|
||||
const statusOrder = {'in-progress': 0, 'paused': 1, 'not-started': 2, 'completed': 3, 'abandoned': 4};
|
||||
const statusDiff = statusOrder[a.status] - statusOrder[b.status];
|
||||
if (statusDiff !== 0) return statusDiff;
|
||||
return b.booksOwned - a.booksOwned;
|
||||
})
|
||||
.slice(0, this.CHART_DISPLAY_COUNT);
|
||||
|
||||
this.chartSeries = chartData;
|
||||
}
|
||||
|
||||
private updateChartData(): void {
|
||||
const labels = this.chartSeries.map(s =>
|
||||
s.name.length > 25 ? s.name.substring(0, 22) + '...' : s.name
|
||||
);
|
||||
|
||||
const readPercentages = this.chartSeries.map(s =>
|
||||
s.booksOwned > 0 ? Math.round((s.booksRead / s.booksOwned) * 100) : 0
|
||||
);
|
||||
const readingPercentages = this.chartSeries.map(s =>
|
||||
s.booksOwned > 0 ? Math.round((s.booksReading / s.booksOwned) * 100) : 0
|
||||
);
|
||||
const partiallyReadPercentages = this.chartSeries.map(s =>
|
||||
s.booksOwned > 0 ? Math.round((s.booksPartiallyRead / s.booksOwned) * 100) : 0
|
||||
);
|
||||
const pausedPercentages = this.chartSeries.map(s =>
|
||||
s.booksOwned > 0 ? Math.round((s.booksPaused / s.booksOwned) * 100) : 0
|
||||
);
|
||||
const abandonedPercentages = this.chartSeries.map(s =>
|
||||
s.booksOwned > 0 ? Math.round((s.booksAbandoned / s.booksOwned) * 100) : 0
|
||||
);
|
||||
const wontReadPercentages = this.chartSeries.map(s =>
|
||||
s.booksOwned > 0 ? Math.round((s.booksWontRead / s.booksOwned) * 100) : 0
|
||||
);
|
||||
const unreadPercentages = this.chartSeries.map(s =>
|
||||
s.booksOwned > 0 ? Math.round((s.booksUnread / s.booksOwned) * 100) : 0
|
||||
);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: this.t.translate('statsUser.seriesProgress.read'),
|
||||
data: readPercentages,
|
||||
backgroundColor: 'rgba(76, 175, 80, 0.85)',
|
||||
borderColor: '#4caf50',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.seriesProgress.reading'),
|
||||
data: readingPercentages,
|
||||
backgroundColor: 'rgba(255, 193, 7, 0.85)',
|
||||
borderColor: '#ffc107',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.seriesProgress.partiallyRead'),
|
||||
data: partiallyReadPercentages,
|
||||
backgroundColor: 'rgba(255, 152, 0, 0.85)',
|
||||
borderColor: '#ff9800',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.seriesProgress.paused'),
|
||||
data: pausedPercentages,
|
||||
backgroundColor: 'rgba(33, 150, 243, 0.85)',
|
||||
borderColor: '#2196f3',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.seriesProgress.abandoned'),
|
||||
data: abandonedPercentages,
|
||||
backgroundColor: 'rgba(239, 83, 80, 0.85)',
|
||||
borderColor: '#ef5350',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.seriesProgress.wontRead'),
|
||||
data: wontReadPercentages,
|
||||
backgroundColor: 'rgba(158, 158, 158, 0.6)',
|
||||
borderColor: '#9e9e9e',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: this.t.translate('statsUser.seriesProgress.unread'),
|
||||
data: unreadPercentages,
|
||||
backgroundColor: 'rgba(158, 158, 158, 0.3)',
|
||||
borderColor: '#9e9e9e',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
getStatusIcon(status: string): string {
|
||||
switch (status) {
|
||||
case 'completed': return 'pi-check-circle';
|
||||
case 'in-progress': return 'pi-spinner';
|
||||
case 'not-started': return 'pi-clock';
|
||||
case 'paused': return 'pi-pause';
|
||||
case 'abandoned': return 'pi-times-circle';
|
||||
default: return 'pi-question-circle';
|
||||
}
|
||||
}
|
||||
|
||||
getStatusColor(status: string): string {
|
||||
switch (status) {
|
||||
case 'completed': return '#4caf50';
|
||||
case 'in-progress': return '#ffc107';
|
||||
case 'not-started': return '#9e9e9e';
|
||||
case 'paused': return '#2196f3';
|
||||
case 'abandoned': return '#ef5350';
|
||||
default: return '#9e9e9e';
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser.sessionArchetypes'">
|
||||
<div class="session-archetypes-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-bolt session-archetypes-icon"></i>
|
||||
{{ t('title') }}
|
||||
<i class="pi pi-question-circle chart-info-icon"
|
||||
[pTooltip]="t('tooltip')"
|
||||
tooltipPosition="bottom"
|
||||
tooltipStyleClass="chart-info-tooltip"
|
||||
[appendTo]="'body'"></i>
|
||||
</h3>
|
||||
<p class="chart-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
<div class="year-nav">
|
||||
<button class="nav-btn" (click)="changeYear(-1)"><i class="pi pi-chevron-left"></i></button>
|
||||
<span class="year-label">{{ currentYear }}</span>
|
||||
<button class="nav-btn" (click)="changeYear(1)"><i class="pi pi-chevron-right"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
@if (hasData) {
|
||||
<div class="stats-row">
|
||||
<div class="stat-card sessions">
|
||||
<span class="stat-value">{{ sessionCount }}</span>
|
||||
<span class="stat-label">{{ t('sessions') }}</span>
|
||||
</div>
|
||||
<div class="stat-card archetype">
|
||||
<span class="stat-value">{{ dominantArchetype }}</span>
|
||||
<span class="stat-label">{{ t('dominantType') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart [data]="chartData" [options]="chartOptions" [type]="chartType"></canvas>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noData') }}</p>
|
||||
<small>{{ t('noDataHint') }}</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user