Add 10 advanced stats charts (#2850)

* Add 10 advanced stats charts with new API endpoints and visualizations

* Fix chart rendering and visual readability across all new stats charts

* Remove 6 charts, fix session archetypes outliers, make book flow half-width

* Revert book flow to full width

* Remove avg rating from book flow chart, reorder charts, cleanup unused imports
This commit is contained in:
ACX
2026-02-22 16:39:22 -07:00
committed by GitHub
parent a6f39a56d2
commit 4e14b7a8e8
24 changed files with 1373 additions and 20 deletions
@@ -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>
@@ -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; }
}
@@ -0,0 +1,300 @@
import {Component, ElementRef, inject, OnDestroy, OnInit, ViewChild, AfterViewInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Tooltip} from 'primeng/tooltip';
import {Subject} from 'rxjs';
import {filter, first, takeUntil} from 'rxjs/operators';
import {BookService} from '../../../../../book/service/book.service';
import {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 OnInit, OnDestroy, AfterViewInit {
@ViewChild('flowCanvas', {static: false}) canvasRef!: ElementRef<HTMLCanvasElement>;
private readonly bookService = inject(BookService);
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
public hasData = false;
public totalBooks = 0;
public topQuarter = '';
public topStatus = '';
public completionRate = '';
private nodes: SankeyNode[] = [];
private links: SankeyLink[] = [];
private canvasReady = false;
private dataReady = false;
ngOnInit(): void {
this.bookService.bookState$
.pipe(filter(state => state.loaded), first(), takeUntil(this.destroy$))
.subscribe(() => {
this.processData();
this.dataReady = true;
this.tryRender();
});
}
ngAfterViewInit(): void {
this.canvasReady = true;
this.tryRender();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private tryRender(): void {
if (this.canvasReady && this.dataReady && this.hasData) {
requestAnimationFrame(() => this.draw());
}
}
private processData(): void {
const currentState = this.bookService.getCurrentBookState();
const books = currentState.books;
if (!books || 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);
}
}
}
@@ -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>
@@ -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; } }
@@ -0,0 +1,149 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BaseChartDirective} from 'ng2-charts';
import {Tooltip} from 'primeng/tooltip';
import {EMPTY, Subject} from 'rxjs';
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
import {ChartConfiguration, ChartData} from 'chart.js';
import {BookService} from '../../../../../book/service/book.service';
import {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 implements OnInit, OnDestroy {
private readonly bookService = inject(BookService);
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
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}
};
ngOnInit(): void {
this.bookService.bookState$
.pipe(filter(state => state.loaded), first(), catchError(() => EMPTY), takeUntil(this.destroy$))
.subscribe(() => this.processData());
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private processData(): void {
const state = this.bookService.getCurrentBookState();
const books = state.books;
if (!books || books.length === 0) 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;
}
}
@@ -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>
@@ -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; } }
@@ -0,0 +1,162 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BaseChartDirective} from 'ng2-charts';
import {Tooltip} from 'primeng/tooltip';
import {EMPTY, Subject} from 'rxjs';
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
import {ChartConfiguration, ChartData} from 'chart.js';
import {BookService} from '../../../../../book/service/book.service';
import {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 implements OnInit, OnDestroy {
private readonly bookService = inject(BookService);
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
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}}
}
}
};
ngOnInit(): void {
this.bookService.bookState$
.pipe(filter(state => state.loaded), first(), catchError(() => EMPTY), takeUntil(this.destroy$))
.subscribe(() => this.processData());
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private processData(): void {
const state = this.bookService.getCurrentBookState();
const books = state.books;
if (!books || books.length === 0) 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)) 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;
}
}
@@ -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>
@@ -0,0 +1,41 @@
.session-archetypes-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; }
}
.year-nav {
display: flex; align-items: center; gap: 0.5rem;
.nav-btn {
background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 6px; color: var(--text-color, #ffffff); padding: 0.3rem 0.5rem;
cursor: pointer; transition: background 0.2s;
&:hover { background: rgba(255, 255, 255, 0.2); }
}
.year-label { color: var(--text-color, #ffffff); font-weight: 600; font-size: 1.1rem; min-width: 50px; text-align: center; }
}
}
.session-archetypes-icon { font-size: 1.5rem; color: #ff9800; }
.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; }
&.sessions .stat-value { color: #ff9800; }
&.archetype .stat-value { color: #42a5f5; font-size: 1.1rem; }
}
}
.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; } }
@@ -0,0 +1,160 @@
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 {EMPTY, Subject} from 'rxjs';
import {catchError, takeUntil} from 'rxjs/operators';
import {ChartConfiguration, ChartData} from 'chart.js';
import {UserStatsService, SessionScatterResponse} from '../../../../../settings/user-management/user-stats.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
const DAY_COLORS = [
'#ef5350', '#ff9800', '#ffc107', '#66bb6a', '#42a5f5', '#7e57c2', '#ec407a'
];
const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
@Component({
selector: 'app-session-archetypes-chart',
standalone: true,
imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective],
templateUrl: './session-archetypes-chart.component.html',
styleUrls: ['./session-archetypes-chart.component.scss']
})
export class SessionArchetypesChartComponent implements OnInit, OnDestroy {
@Input() initialYear = new Date().getFullYear();
private readonly userStatsService = inject(UserStatsService);
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
public readonly chartType = 'scatter' as const;
public currentYear: number = new Date().getFullYear();
public hasData = false;
public sessionCount = 0;
public dominantArchetype = '';
public chartData: ChartData<'scatter', {x: number; y: number}[], string> = {labels: [], datasets: []};
public readonly chartOptions: ChartConfiguration<'scatter'>['options'] = {
responsive: true,
maintainAspectRatio: false,
animation: {duration: 400},
layout: {padding: {top: 10, right: 20}},
plugins: {
legend: {
display: true, position: 'bottom',
labels: {color: 'rgba(255, 255, 255, 0.8)', font: {family: "'Inter', sans-serif", size: 11}, boxWidth: 10, padding: 12}
},
tooltip: {
enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.9)',
titleColor: '#ffffff', bodyColor: '#ffffff',
cornerRadius: 6, padding: 10,
callbacks: {
label: (ctx) => {
const hour = ctx.parsed.x ?? 0;
const h = Math.floor(hour);
const m = Math.round((hour - h) * 60);
const duration = Math.round(ctx.parsed.y ?? 0);
return `${ctx.dataset.label}: ${h}:${String(m).padStart(2, '0')} - ${duration} min`;
}
}
},
datalabels: {display: false}
},
scales: {
x: {
min: 0, max: 24,
grid: {color: 'rgba(255, 255, 255, 0.08)'},
ticks: {
color: 'rgba(255, 255, 255, 0.6)', font: {size: 10}, stepSize: 3,
callback: (val) => {
const h = Number(val);
if (h === 0) return '12am';
if (h === 12) return '12pm';
return h < 12 ? `${h}am` : `${h - 12}pm`;
}
},
title: {display: true, text: 'Time of Day', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}}
},
y: {
min: 0,
grid: {color: 'rgba(255, 255, 255, 0.08)'},
ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}},
title: {display: true, text: 'Duration (min)', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}}
}
}
};
ngOnInit(): void {
this.currentYear = this.initialYear;
this.loadData(this.currentYear);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
changeYear(delta: number): void {
this.currentYear += delta;
this.loadData(this.currentYear);
}
private loadData(year: number): void {
this.userStatsService.getSessionScatter(year)
.pipe(takeUntil(this.destroy$), catchError(() => EMPTY))
.subscribe(data => this.processData(data));
}
private processData(data: SessionScatterResponse[]): void {
if (!data || data.length === 0) {
this.hasData = false;
this.chartData = {labels: [], datasets: []};
return;
}
const durations = data.map(s => s.durationMinutes).sort((a, b) => a - b);
const q1 = durations[Math.floor(durations.length * 0.25)];
const q3 = durations[Math.floor(durations.length * 0.75)];
const iqr = q3 - q1;
const upperFence = q3 + 1.5 * iqr;
const filtered = data.filter(s => s.durationMinutes <= upperFence);
this.sessionCount = filtered.length;
const byDay = new Map<number, {x: number; y: number}[]>();
for (let d = 1; d <= 7; d++) byDay.set(d, []);
const quadrants = {morning: 0, afternoon: 0, evening: 0, night: 0};
for (const s of filtered) {
const points = byDay.get(s.dayOfWeek) || [];
points.push({x: s.hourOfDay, y: s.durationMinutes});
byDay.set(s.dayOfWeek, points);
if (s.hourOfDay >= 5 && s.hourOfDay < 12) quadrants.morning++;
else if (s.hourOfDay >= 12 && s.hourOfDay < 17) quadrants.afternoon++;
else if (s.hourOfDay >= 17 && s.hourOfDay < 22) quadrants.evening++;
else quadrants.night++;
}
const maxQ = Object.entries(quadrants).sort((a, b) => b[1] - a[1])[0];
this.dominantArchetype = this.t.translate(`statsUser.sessionArchetypes.archetype_${maxQ[0]}`);
const datasets = DAY_NAMES.map((name, i) => {
const dayNum = i + 1;
return {
label: name,
data: byDay.get(dayNum) || [],
backgroundColor: DAY_COLORS[i] + 'AA',
borderColor: DAY_COLORS[i],
borderWidth: 1,
pointRadius: 5,
pointHoverRadius: 8
};
}).filter(ds => ds.data.length > 0);
this.chartData = {datasets};
this.hasData = true;
}
}
@@ -20,6 +20,10 @@ import {CompletionRaceChartComponent} from '../charts/completion-race-chart/comp
import {ReadingSurvivalChartComponent} from '../charts/reading-survival-chart/reading-survival-chart.component';
import {ReadingClockChartComponent} from '../charts/reading-clock-chart/reading-clock-chart.component';
import {BookLengthChartComponent} from '../charts/book-length-chart/book-length-chart.component';
import {BookFlowChartComponent} from '../charts/book-flow-chart/book-flow-chart.component';
import {ReadingDebtChartComponent} from '../charts/reading-debt-chart/reading-debt-chart.component';
import {PublicationEraChartComponent} from '../charts/publication-era-chart/publication-era-chart.component';
import {SessionArchetypesChartComponent} from '../charts/session-archetypes-chart/session-archetypes-chart.component';
export interface UserChartConfig {
id: string;
@@ -57,6 +61,10 @@ export class UserChartConfigService {
'series-progress': 'statsUser.chartNames.seriesProgress',
'reading-dna': 'statsUser.chartNames.readingDna',
'reading-habits': 'statsUser.chartNames.readingHabits',
'book-flow': 'statsUser.chartNames.bookFlow',
'reading-debt': 'statsUser.chartNames.readingDebt',
'publication-era': 'statsUser.chartNames.publicationEra',
'session-archetypes': 'statsUser.chartNames.sessionArchetypes',
};
private readonly defaultCharts: UserChartConfig[] = [
@@ -77,8 +85,12 @@ export class UserChartConfigService {
{id: 'book-length', title: 'Book Length Sweet Spot', component: BookLengthChartComponent, enabled: true, sizeClass: 'chart-medium', order: 14},
{id: 'rating-taste', title: 'Rating Taste Comparison', component: RatingTasteChartComponent, enabled: true, sizeClass: 'chart-medium', order: 15},
{id: 'series-progress', title: 'Series Progress Tracker', component: SeriesProgressChartComponent, enabled: true, sizeClass: 'chart-medium', order: 16},
{id: 'reading-dna', title: 'Reading DNA Profile', component: ReadingDNAChartComponent, enabled: true, sizeClass: 'chart-medium', order: 17},
{id: 'reading-habits', title: 'Reading Habits Analysis', component: ReadingHabitsChartComponent, enabled: true, sizeClass: 'chart-medium', order: 18},
{id: 'reading-debt', title: 'Reading Debt Waterfall', component: ReadingDebtChartComponent, enabled: true, sizeClass: 'chart-medium', order: 17},
{id: 'publication-era', title: 'Publication Era vs Rating', component: PublicationEraChartComponent, enabled: true, sizeClass: 'chart-medium', order: 18},
{id: 'session-archetypes', title: 'Session Archetypes', component: SessionArchetypesChartComponent, enabled: true, sizeClass: 'chart-medium', order: 19},
{id: 'book-flow', title: 'Book Flow', component: BookFlowChartComponent, enabled: true, sizeClass: 'chart-medium', order: 20},
{id: 'reading-habits', title: 'Reading Habits Analysis', component: ReadingHabitsChartComponent, enabled: true, sizeClass: 'chart-medium', order: 21},
{id: 'reading-dna', title: 'Reading DNA Profile', component: ReadingDNAChartComponent, enabled: true, sizeClass: 'chart-medium', order: 22}
];
private chartsSubject = new BehaviorSubject<UserChartConfig[]>(this.loadChartConfig());
@@ -126,6 +126,18 @@
@case ('book-length') {
<app-book-length-chart></app-book-length-chart>
}
@case ('book-flow') {
<app-book-flow-chart></app-book-flow-chart>
}
@case ('reading-debt') {
<app-reading-debt-chart></app-reading-debt-chart>
}
@case ('publication-era') {
<app-publication-era-chart></app-publication-era-chart>
}
@case ('session-archetypes') {
<app-session-archetypes-chart [initialYear]="currentYear"></app-session-archetypes-chart>
}
}
</div>
}
@@ -26,6 +26,10 @@ import {CompletionRaceChartComponent} from './charts/completion-race-chart/compl
import {ReadingSurvivalChartComponent} from './charts/reading-survival-chart/reading-survival-chart.component';
import {ReadingClockChartComponent} from './charts/reading-clock-chart/reading-clock-chart.component';
import {BookLengthChartComponent} from './charts/book-length-chart/book-length-chart.component';
import {BookFlowChartComponent} from './charts/book-flow-chart/book-flow-chart.component';
import {ReadingDebtChartComponent} from './charts/reading-debt-chart/reading-debt-chart.component';
import {PublicationEraChartComponent} from './charts/publication-era-chart/publication-era-chart.component';
import {SessionArchetypesChartComponent} from './charts/session-archetypes-chart/session-archetypes-chart.component';
import {UserChartConfig, UserChartConfigService} from './service/user-chart-config.service';
@Component({
@@ -55,6 +59,10 @@ import {UserChartConfig, UserChartConfigService} from './service/user-chart-conf
ReadingSurvivalChartComponent,
ReadingClockChartComponent,
BookLengthChartComponent,
BookFlowChartComponent,
ReadingDebtChartComponent,
PublicationEraChartComponent,
SessionArchetypesChartComponent,
TranslocoDirective
],
templateUrl: './user-stats.component.html',