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:
+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>
|
||||
+41
@@ -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; } }
|
||||
+160
@@ -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;
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import {computed, Injectable, signal} from '@angular/core';
|
||||
|
||||
export interface UserChartConfig {
|
||||
id: string;
|
||||
enabled: boolean;
|
||||
sizeClass: string;
|
||||
order: number;
|
||||
}
|
||||
|
||||
const DEFAULT_CHARTS: UserChartConfig[] = [
|
||||
{id: 'heatmap', enabled: true, sizeClass: 'chart-full', order: 0},
|
||||
{id: 'favorite-days', enabled: true, sizeClass: 'chart-medium', order: 1},
|
||||
{id: 'peak-hours', enabled: true, sizeClass: 'chart-medium', order: 2},
|
||||
{id: 'timeline', enabled: true, sizeClass: 'chart-full', order: 3},
|
||||
{id: 'reading-heatmap', enabled: true, sizeClass: 'chart-small-square', order: 4},
|
||||
{id: 'personal-rating', enabled: true, sizeClass: 'chart-small-square', order: 5},
|
||||
{id: 'reading-progress', enabled: true, sizeClass: 'chart-small-square', order: 6},
|
||||
{id: 'read-status', enabled: true, sizeClass: 'chart-small-square', order: 7},
|
||||
{id: 'genre-stats', enabled: true, sizeClass: 'chart-medium', order: 8},
|
||||
{id: 'completion-timeline', enabled: true, sizeClass: 'chart-medium', order: 9},
|
||||
{id: 'reading-clock', enabled: true, sizeClass: 'chart-medium', order: 10},
|
||||
{id: 'page-turner', enabled: true, sizeClass: 'chart-medium', order: 11},
|
||||
{id: 'completion-race', enabled: true, sizeClass: 'chart-full', order: 12},
|
||||
{id: 'reading-survival', enabled: true, sizeClass: 'chart-medium', order: 13},
|
||||
{id: 'book-length', enabled: true, sizeClass: 'chart-medium', order: 14},
|
||||
{id: 'rating-taste', enabled: true, sizeClass: 'chart-medium', order: 15},
|
||||
{id: 'series-progress', enabled: true, sizeClass: 'chart-medium', order: 16},
|
||||
{id: 'reading-debt', enabled: true, sizeClass: 'chart-medium', order: 17},
|
||||
{id: 'publication-era', enabled: true, sizeClass: 'chart-medium', order: 18},
|
||||
{id: 'session-archetypes', enabled: true, sizeClass: 'chart-medium', order: 19},
|
||||
{id: 'book-flow', enabled: true, sizeClass: 'chart-medium', order: 20},
|
||||
{id: 'reading-habits', enabled: true, sizeClass: 'chart-medium', order: 21},
|
||||
{id: 'reading-dna', enabled: true, sizeClass: 'chart-medium', order: 22}
|
||||
];
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class UserChartConfigService {
|
||||
private static readonly STORAGE_KEY = 'userStatsChartConfig';
|
||||
|
||||
private readonly _charts = signal<UserChartConfig[]>(this.loadChartConfig());
|
||||
readonly charts = this._charts.asReadonly();
|
||||
readonly visibleCharts = computed(() => this.charts().filter(chart => chart.enabled));
|
||||
|
||||
toggleChart(chartId: string): void {
|
||||
this.saveCharts(this._charts().map(chart =>
|
||||
chart.id === chartId ? {...chart, enabled: !chart.enabled} : chart
|
||||
));
|
||||
}
|
||||
|
||||
reorderCharts(charts: UserChartConfig[], previousIndex: number, currentIndex: number): void {
|
||||
const sourceIds = charts.map(chart => chart.id);
|
||||
const reorderedIds = [...sourceIds];
|
||||
const [movedId] = reorderedIds.splice(previousIndex, 1);
|
||||
reorderedIds.splice(currentIndex, 0, movedId);
|
||||
|
||||
const currentCharts = [...this._charts()].sort((a, b) => a.order - b.order);
|
||||
const chartsById = new Map(currentCharts.map(chart => [chart.id, chart]));
|
||||
let reorderedIndex = 0;
|
||||
|
||||
const nextCharts = currentCharts.map(chart => {
|
||||
const nextId = sourceIds.includes(chart.id) ? reorderedIds[reorderedIndex++] : chart.id;
|
||||
return {
|
||||
...(chartsById.get(nextId) ?? this.getDefaultCharts().find(defaultChart => defaultChart.id === nextId)!),
|
||||
order: currentCharts.findIndex(currentChart => currentChart.id === chart.id)
|
||||
};
|
||||
});
|
||||
|
||||
this.saveCharts(nextCharts);
|
||||
}
|
||||
|
||||
resetLayout(): void {
|
||||
this.saveCharts(this.getDefaultCharts());
|
||||
}
|
||||
|
||||
setAllChartsEnabled(enabled: boolean): void {
|
||||
this.saveCharts(this._charts().map(chart => ({...chart, enabled})));
|
||||
}
|
||||
|
||||
private saveCharts(charts: UserChartConfig[]): void {
|
||||
const nextCharts = [...charts]
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((chart, index) => ({...chart, order: index}));
|
||||
|
||||
this._charts.set(nextCharts);
|
||||
localStorage.setItem(UserChartConfigService.STORAGE_KEY, JSON.stringify(nextCharts));
|
||||
}
|
||||
|
||||
private getDefaultCharts(): UserChartConfig[] {
|
||||
return DEFAULT_CHARTS.map(chart => ({...chart}));
|
||||
}
|
||||
|
||||
private loadChartConfig(): UserChartConfig[] {
|
||||
const savedConfig = localStorage.getItem(UserChartConfigService.STORAGE_KEY);
|
||||
if (!savedConfig) {
|
||||
return this.getDefaultCharts();
|
||||
}
|
||||
|
||||
try {
|
||||
const savedCharts = JSON.parse(savedConfig) as Array<Partial<UserChartConfig>>;
|
||||
const savedChartsById = new Map(savedCharts.map(chart => [chart.id, chart]));
|
||||
|
||||
return this.getDefaultCharts()
|
||||
.map(chart => {
|
||||
const saved = savedChartsById.get(chart.id);
|
||||
return {
|
||||
id: chart.id,
|
||||
enabled: saved?.enabled ?? chart.enabled,
|
||||
sizeClass: saved?.sizeClass ?? chart.sizeClass,
|
||||
order: saved?.order ?? chart.order
|
||||
};
|
||||
})
|
||||
.sort((a, b) => a.order - b.order);
|
||||
} catch (error) {
|
||||
console.error('Failed to load chart config', error);
|
||||
return this.getDefaultCharts();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<ng-container *transloco="let t; prefix: 'statsUser'">
|
||||
<div class="user-stats-container">
|
||||
<div class="header-section">
|
||||
<div class="header-content">
|
||||
<div class="greeting">
|
||||
<i class="pi pi-chart-line"></i>
|
||||
<h2>{{ t('main.title', { name: userName() }) }}</h2>
|
||||
</div>
|
||||
<button class="config-toggle-btn" (click)="toggleConfigPanel()">
|
||||
<i class="pi pi-cog"></i>
|
||||
<span>{{ t('main.customizeLayout') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-dialog
|
||||
[visible]="showConfigPanel()"
|
||||
(visibleChange)="showConfigPanel.set($event)"
|
||||
[modal]="true"
|
||||
[draggable]="false"
|
||||
[resizable]="false"
|
||||
[style]="{width: '600px', maxWidth: '90vw'}"
|
||||
class="config-dialog"
|
||||
[header]="t('main.chartConfig')">
|
||||
|
||||
<div class="config-dialog-content">
|
||||
<div class="config-list" cdkDropList [cdkDropListData]="charts()" (cdkDropListDropped)="drop($event)">
|
||||
@for (chart of charts(); track chart.id) {
|
||||
<div class="config-item" cdkDrag>
|
||||
<div class="drag-handle" cdkDragHandle>
|
||||
<i class="pi pi-bars"></i>
|
||||
</div>
|
||||
<span class="chart-title">{{ t(chartNameKey(chart.id)) }}</span>
|
||||
<button
|
||||
class="visibility-toggle"
|
||||
(click)="toggleChart(chart.id)"
|
||||
[class.disabled]="!chart.enabled">
|
||||
<i [class]="chart.enabled ? 'pi pi-eye' : 'pi pi-eye-slash'"></i>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ng-template pTemplate="footer">
|
||||
<p-button class="reset-btn" (click)="resetLayout()" severity="danger">
|
||||
<i class="pi pi-refresh"></i>
|
||||
<span>{{ t('main.resetLayout') }}</span>
|
||||
</p-button>
|
||||
<p-button class="hide-all-btn" (click)="hideAllCharts()" severity="secondary">
|
||||
<i class="pi pi-eye-slash"></i>
|
||||
<span>{{ t('main.hideAll') }}</span>
|
||||
</p-button>
|
||||
<p-button class="show-all-btn" (click)="showAllCharts()" severity="secondary">
|
||||
<i class="pi pi-eye"></i>
|
||||
<span>{{ t('main.showAll') }}</span>
|
||||
</p-button>
|
||||
<p-button class="close-btn" (click)="toggleConfigPanel()" severity="secondary">
|
||||
<span>{{ t('main.close') }}</span>
|
||||
</p-button>
|
||||
</ng-template>
|
||||
</p-dialog>
|
||||
|
||||
<!-- Charts Container -->
|
||||
<div class="charts-container" cdkDropList [cdkDropListData]="visibleCharts()" (cdkDropListDropped)="drop($event)">
|
||||
@for (chart of visibleCharts(); track chart.id) {
|
||||
<div class="chart-card" [class]="chart.sizeClass" cdkDrag>
|
||||
<div class="chart-drag-handle" cdkDragHandle>
|
||||
<i class="pi pi-arrows-alt"></i>
|
||||
</div>
|
||||
|
||||
@switch (chart.id) {
|
||||
@case ('heatmap') {
|
||||
<app-reading-session-heatmap [initialYear]="currentYear"></app-reading-session-heatmap>
|
||||
}
|
||||
@case ('timeline') {
|
||||
<app-reading-session-timeline [initialYear]="currentYear"></app-reading-session-timeline>
|
||||
}
|
||||
@case ('genre-stats') {
|
||||
<app-genre-stats-chart></app-genre-stats-chart>
|
||||
}
|
||||
@case ('completion-timeline') {
|
||||
<app-completion-timeline-chart [initialYear]="currentYear"></app-completion-timeline-chart>
|
||||
}
|
||||
@case ('favorite-days') {
|
||||
<app-favorite-days-chart></app-favorite-days-chart>
|
||||
}
|
||||
@case ('peak-hours') {
|
||||
<app-peak-hours-chart></app-peak-hours-chart>
|
||||
}
|
||||
@case ('reading-dna') {
|
||||
<app-reading-dna-chart></app-reading-dna-chart>
|
||||
}
|
||||
@case ('reading-habits') {
|
||||
<app-reading-habits-chart></app-reading-habits-chart>
|
||||
}
|
||||
@case ('reading-heatmap') {
|
||||
<app-reading-heatmap-chart></app-reading-heatmap-chart>
|
||||
}
|
||||
@case ('personal-rating') {
|
||||
<app-personal-rating-chart></app-personal-rating-chart>
|
||||
}
|
||||
@case ('reading-progress') {
|
||||
<app-reading-progress-chart></app-reading-progress-chart>
|
||||
}
|
||||
@case ('read-status') {
|
||||
<app-read-status-chart></app-read-status-chart>
|
||||
}
|
||||
@case ('rating-taste') {
|
||||
<app-rating-taste-chart></app-rating-taste-chart>
|
||||
}
|
||||
@case ('series-progress') {
|
||||
<app-series-progress-chart></app-series-progress-chart>
|
||||
}
|
||||
@case ('page-turner') {
|
||||
<app-page-turner-chart></app-page-turner-chart>
|
||||
}
|
||||
@case ('completion-race') {
|
||||
<app-completion-race-chart [initialYear]="currentYear"></app-completion-race-chart>
|
||||
}
|
||||
@case ('reading-survival') {
|
||||
<app-reading-survival-chart></app-reading-survival-chart>
|
||||
}
|
||||
@case ('reading-clock') {
|
||||
<app-reading-clock-chart></app-reading-clock-chart>
|
||||
}
|
||||
@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>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
@@ -0,0 +1,495 @@
|
||||
.user-stats-container {
|
||||
max-width: 1800px;
|
||||
margin: 0 auto;
|
||||
padding: 0.5rem;
|
||||
height: calc(100dvh - 6.25rem);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.header-section {
|
||||
background: var(--card-background);
|
||||
border-radius: 12px;
|
||||
padding: 1rem;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
margin-bottom: 2rem;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 2rem;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.greeting {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
|
||||
i {
|
||||
font-size: 1.5rem;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.config-toggle-btn {
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.config-header {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.config-toggle-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1.25rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-size: 0.9rem;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
background: var(--p-primary-color);
|
||||
color: white;
|
||||
border-color: var(--p-primary-color);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Dialog styles
|
||||
::ng-deep .config-dialog {
|
||||
.p-dialog-header {
|
||||
border-bottom: 1px solid var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.p-dialog-content {
|
||||
background: var(--card-background);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.p-dialog-footer {
|
||||
border-top: 1px solid var(--p-content-border-color);
|
||||
padding: 1rem 1.5rem;
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
justify-content: flex-end;
|
||||
|
||||
.reset-btn {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.hide-all-btn,
|
||||
.show-all-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-dialog-content {
|
||||
.config-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.config-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0.5rem 1.25rem;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
cursor: move;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-color: var(--p-primary-color);
|
||||
}
|
||||
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
color: var(--text-color-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
color: var(--text-color);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.visibility-toggle {
|
||||
padding: 0.5rem;
|
||||
background: transparent;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 6px;
|
||||
color: var(--p-primary-color);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--p-primary-color);
|
||||
color: white;
|
||||
border-color: var(--p-primary-color);
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
color: var(--text-color-secondary);
|
||||
opacity: 0.5;
|
||||
|
||||
&:hover {
|
||||
background: transparent;
|
||||
color: var(--text-color-secondary);
|
||||
border-color: var(--p-content-border-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.charts-container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(12, 1fr);
|
||||
gap: 1.5rem;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
background: var(--card-background);
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
transition: all 0.3s ease;
|
||||
position: relative;
|
||||
overflow: visible;
|
||||
|
||||
&:hover {
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
|
||||
|
||||
.chart-drag-handle {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-drag-handle {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border-radius: 6px;
|
||||
cursor: grab;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease;
|
||||
z-index: 10;
|
||||
color: var(--text-color);
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
&.chart-small-square {
|
||||
grid-column: span 3;
|
||||
}
|
||||
|
||||
&.chart-small {
|
||||
grid-column: span 4;
|
||||
}
|
||||
|
||||
&.chart-medium {
|
||||
grid-column: span 6;
|
||||
}
|
||||
|
||||
&.chart-large {
|
||||
grid-column: span 8;
|
||||
}
|
||||
|
||||
&.chart-wide {
|
||||
grid-column: span 9;
|
||||
}
|
||||
|
||||
&.chart-full {
|
||||
grid-column: span 12;
|
||||
}
|
||||
}
|
||||
|
||||
.cdk-drag-preview {
|
||||
opacity: 0.8;
|
||||
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.cdk-drag-placeholder {
|
||||
opacity: 0.3;
|
||||
border: 2px dashed var(--p-primary-color);
|
||||
}
|
||||
|
||||
.cdk-drag-animating {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
@media (max-width: 1440px) {
|
||||
.charts-container {
|
||||
grid-template-columns: repeat(12, 1fr);
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
&.chart-small-square {
|
||||
grid-column: span 4;
|
||||
}
|
||||
|
||||
&.chart-small {
|
||||
grid-column: span 4;
|
||||
}
|
||||
|
||||
&.chart-medium {
|
||||
grid-column: span 6;
|
||||
}
|
||||
|
||||
&.chart-large {
|
||||
grid-column: span 8;
|
||||
}
|
||||
|
||||
&.chart-wide {
|
||||
grid-column: span 12;
|
||||
}
|
||||
|
||||
&.chart-full {
|
||||
grid-column: span 12;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.charts-container {
|
||||
grid-template-columns: repeat(6, 1fr);
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
&.chart-small-square,
|
||||
&.chart-small {
|
||||
grid-column: span 3;
|
||||
}
|
||||
|
||||
&.chart-medium {
|
||||
grid-column: span 3;
|
||||
}
|
||||
|
||||
&.chart-large,
|
||||
&.chart-wide,
|
||||
&.chart-full {
|
||||
grid-column: span 6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.user-stats-container {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.config-toggle-btn {
|
||||
span {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .config-dialog {
|
||||
.p-dialog-content {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.p_dialog_footer {
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
|
||||
.reset-btn {
|
||||
margin-right: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-panel {
|
||||
padding: 1rem;
|
||||
|
||||
.config-panel-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
|
||||
.reset-btn {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.header-section {
|
||||
padding: 1rem;
|
||||
|
||||
.header-content {
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
position: static;
|
||||
}
|
||||
|
||||
.greeting {
|
||||
position: static;
|
||||
transform: none;
|
||||
|
||||
i {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.25rem;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-toggle-btn {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
margin-left: 0;
|
||||
|
||||
span {
|
||||
display: inline;
|
||||
}
|
||||
}
|
||||
|
||||
.charts-container {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
padding: 1rem;
|
||||
|
||||
.chart-drag-handle {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
&.chart-small-square,
|
||||
&.chart-small {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
&.chart-medium {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
&.chart-large,
|
||||
&.chart-wide,
|
||||
&.chart-full {
|
||||
grid-column: span 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.user-stats-container {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.config-toggle-btn {
|
||||
padding: 0.5rem 0.75rem;
|
||||
}
|
||||
|
||||
::ng-deep .config-dialog {
|
||||
.p-dialog-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.config-panel {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.header-section {
|
||||
padding: 0.75rem;
|
||||
|
||||
.greeting {
|
||||
gap: 0.5rem;
|
||||
|
||||
i {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1rem;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.charts-container {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
padding: 0.75rem;
|
||||
|
||||
&.chart-small-square,
|
||||
&.chart-small,
|
||||
&.chart-medium,
|
||||
&.chart-large,
|
||||
&.chart-wide,
|
||||
&.chart-full {
|
||||
grid-column: span 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import {Component, computed, inject, signal} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {CdkDragDrop, DragDropModule} from '@angular/cdk/drag-drop';
|
||||
import {DialogModule} from 'primeng/dialog';
|
||||
import {ButtonModule} from 'primeng/button';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {TranslocoDirective} from '@jsverse/transloco';
|
||||
import {PeakHoursChartComponent} from './charts/peak-hours-chart/peak-hours-chart.component';
|
||||
import {FavoriteDaysChartComponent} from './charts/favorite-days-chart/favorite-days-chart.component';
|
||||
import {ReadingDNAChartComponent} from './charts/reading-dna-chart/reading-dna-chart.component';
|
||||
import {CompletionTimelineChartComponent} from './charts/completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {ReadingHabitsChartComponent} from './charts/reading-habits-chart/reading-habits-chart.component';
|
||||
import {GenreStatsChartComponent} from './charts/genre-stats-chart/genre-stats-chart.component';
|
||||
import {ReadingHeatmapChartComponent} from './charts/reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {ReadingSessionTimelineComponent} from './charts/reading-session-timeline/reading-session-timeline.component';
|
||||
import {PersonalRatingChartComponent} from './charts/personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingSessionHeatmapComponent} from './charts/reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {ReadingProgressChartComponent} from './charts/reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from './charts/read-status-chart/read-status-chart.component';
|
||||
import {RatingTasteChartComponent} from './charts/rating-taste-chart/rating-taste-chart.component';
|
||||
import {SeriesProgressChartComponent} from './charts/series-progress-chart/series-progress-chart.component';
|
||||
import {PageTurnerChartComponent} from './charts/page-turner-chart/page-turner-chart.component';
|
||||
import {CompletionRaceChartComponent} from './charts/completion-race-chart/completion-race-chart.component';
|
||||
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({
|
||||
selector: 'app-user-stats',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
DragDropModule,
|
||||
DialogModule,
|
||||
ButtonModule,
|
||||
ReadingSessionHeatmapComponent,
|
||||
ReadingSessionTimelineComponent,
|
||||
GenreStatsChartComponent,
|
||||
CompletionTimelineChartComponent,
|
||||
FavoriteDaysChartComponent,
|
||||
PeakHoursChartComponent,
|
||||
ReadingDNAChartComponent,
|
||||
ReadingHabitsChartComponent,
|
||||
ReadingHeatmapChartComponent,
|
||||
PersonalRatingChartComponent,
|
||||
ReadingProgressChartComponent,
|
||||
ReadStatusChartComponent,
|
||||
RatingTasteChartComponent,
|
||||
SeriesProgressChartComponent,
|
||||
PageTurnerChartComponent,
|
||||
CompletionRaceChartComponent,
|
||||
ReadingSurvivalChartComponent,
|
||||
ReadingClockChartComponent,
|
||||
BookLengthChartComponent,
|
||||
BookFlowChartComponent,
|
||||
ReadingDebtChartComponent,
|
||||
PublicationEraChartComponent,
|
||||
SessionArchetypesChartComponent,
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './user-stats.component.html',
|
||||
styleUrls: ['./user-stats.component.scss']
|
||||
})
|
||||
export class UserStatsComponent {
|
||||
private userService = inject(UserService);
|
||||
private chartConfigService = inject(UserChartConfigService);
|
||||
|
||||
public currentYear = new Date().getFullYear();
|
||||
public readonly userName = computed(() => {
|
||||
const user = this.userService.currentUser();
|
||||
return user ? user.name || user.username : '';
|
||||
});
|
||||
public readonly showConfigPanel = signal(false);
|
||||
public readonly charts = this.chartConfigService.charts;
|
||||
public readonly visibleCharts = this.chartConfigService.visibleCharts;
|
||||
|
||||
toggleChart(chartId: string): void {
|
||||
this.chartConfigService.toggleChart(chartId);
|
||||
}
|
||||
|
||||
drop(event: CdkDragDrop<UserChartConfig[]>): void {
|
||||
this.chartConfigService.reorderCharts(event.container.data, event.previousIndex, event.currentIndex);
|
||||
}
|
||||
|
||||
toggleConfigPanel(): void {
|
||||
this.showConfigPanel.update(visible => !visible);
|
||||
}
|
||||
|
||||
resetLayout(): void {
|
||||
this.chartConfigService.resetLayout();
|
||||
}
|
||||
|
||||
hideAllCharts(): void {
|
||||
this.chartConfigService.setAllChartsEnabled(false);
|
||||
}
|
||||
|
||||
showAllCharts(): void {
|
||||
this.chartConfigService.setAllChartsEnabled(true);
|
||||
}
|
||||
|
||||
chartNameKey(chartId: string): string {
|
||||
const [firstSegment, ...rest] = chartId.split('-');
|
||||
const chartName = firstSegment + rest
|
||||
.map(segment => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join('');
|
||||
|
||||
return `chartNames.${chartName}`;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user