Introduced additional library charts to surface meaningful insights (#2390)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+34
@@ -0,0 +1,34 @@
|
||||
<div class="completion-timeline-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar completion-title-icon"></i>
|
||||
Reading Progress
|
||||
</h3>
|
||||
<p class="chart-description">Monthly book completion statistics</p>
|
||||
</div>
|
||||
<div class="year-selector">
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(-1)"
|
||||
title="Previous year">
|
||||
<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="Next year">
|
||||
<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>
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
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';
|
||||
|
||||
type CompletionChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-completion-timeline-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
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 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;
|
||||
return `${label}: ${value} book${value !== 1 ? 's' : ''}`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Month',
|
||||
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: 'Number of Books',
|
||||
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: '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: 'Active Reading',
|
||||
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: '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: '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
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<div class="favorite-days-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar-plus favorite-days-icon"></i>
|
||||
Favorite Reading Days
|
||||
</h3>
|
||||
<p class="chart-description">Reading sessions and duration by day of the week</p>
|
||||
</div>
|
||||
<div class="filter-controls">
|
||||
<p-select
|
||||
[options]="yearOptions"
|
||||
[(ngModel)]="selectedYear"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Select Year"
|
||||
[style]="{'min-width': '90px'}">
|
||||
</p-select>
|
||||
<p-select
|
||||
[options]="monthOptions"
|
||||
[(ngModel)]="selectedMonth"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Select Month"
|
||||
[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>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
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 {FormsModule} from '@angular/forms';
|
||||
import {FavoriteDaysResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
type FavoriteDaysChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-favorite-days-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Select, FormsModule],
|
||||
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 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 }[] = [
|
||||
{label: 'All Months', value: null},
|
||||
{label: 'January', value: 1},
|
||||
{label: 'February', value: 2},
|
||||
{label: 'March', value: 3},
|
||||
{label: 'April', value: 4},
|
||||
{label: 'May', value: 5},
|
||||
{label: 'June', value: 6},
|
||||
{label: 'July', value: 7},
|
||||
{label: 'August', value: 8},
|
||||
{label: 'September', value: 9},
|
||||
{label: 'October', value: 10},
|
||||
{label: 'November', value: 11},
|
||||
{label: 'December', value: 12}
|
||||
];
|
||||
|
||||
constructor() {
|
||||
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;
|
||||
if (label === 'Sessions') {
|
||||
return `${label}: ${value} session${value !== 1 ? 's' : ''}`;
|
||||
} 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: 'Day of Week',
|
||||
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: 'Number of Sessions',
|
||||
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: 'Duration (hours)',
|
||||
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: 'All Years', value: null}];
|
||||
for (let year = currentYear; year >= currentYear - 10; year--) {
|
||||
this.yearOptions.push({label: year.toString(), value: year});
|
||||
}
|
||||
}
|
||||
|
||||
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: '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: 'Duration (hours)',
|
||||
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'
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<div class="genre-stats-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-bar genre-title-icon"></i>
|
||||
Reading by Genre
|
||||
</h3>
|
||||
<p class="chart-description">Top genres by total reading time</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
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 {GenreStatsResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
type GenreChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-genre-stats-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
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 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: 'Genres',
|
||||
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: 'Time Read',
|
||||
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);
|
||||
|
||||
if (days > 0) {
|
||||
const remainingHours = hours % 24;
|
||||
if (remainingHours > 0) {
|
||||
return `${days} ${days === 1 ? 'day' : 'days'} ${remainingHours} ${remainingHours === 1 ? 'hr' : 'hrs'}`;
|
||||
}
|
||||
return `${days} ${days === 1 ? 'day' : 'days'}`;
|
||||
} else if (hours > 0) {
|
||||
const remainingMinutes = minutes % 60;
|
||||
if (remainingMinutes > 0) {
|
||||
return `${hours} ${hours === 1 ? 'hr' : 'hrs'} ${remainingMinutes} min`;
|
||||
}
|
||||
return `${hours} ${hours === 1 ? 'hr' : 'hrs'}`;
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes} min`;
|
||||
}
|
||||
return `${seconds} sec`;
|
||||
},
|
||||
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: 'Reading Time',
|
||||
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
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<div class="peak-hours-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-clock peak-hours-icon"></i>
|
||||
Peak Reading Hours
|
||||
</h3>
|
||||
<p class="chart-description">Reading activity by hour of the day</p>
|
||||
</div>
|
||||
<div class="filter-controls">
|
||||
<p-select
|
||||
[options]="yearOptions"
|
||||
[(ngModel)]="selectedYear"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Select Year"
|
||||
[style]="{'min-width': '100px'}">
|
||||
</p-select>
|
||||
<p-select
|
||||
[options]="monthOptions"
|
||||
[(ngModel)]="selectedMonth"
|
||||
(onChange)="onFilterChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Select Month"
|
||||
[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>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
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 {FormsModule} from '@angular/forms';
|
||||
import {PeakHoursResponse, UserStatsService} from '../../../../../settings/user-management/user-stats.service';
|
||||
|
||||
type PeakHoursChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-peak-hours-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective, Select, FormsModule],
|
||||
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 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 }[] = [
|
||||
{label: 'All Months', value: null},
|
||||
{label: 'January', value: 1},
|
||||
{label: 'February', value: 2},
|
||||
{label: 'March', value: 3},
|
||||
{label: 'April', value: 4},
|
||||
{label: 'May', value: 5},
|
||||
{label: 'June', value: 6},
|
||||
{label: 'July', value: 7},
|
||||
{label: 'August', value: 8},
|
||||
{label: 'September', value: 9},
|
||||
{label: 'October', value: 10},
|
||||
{label: 'November', value: 11},
|
||||
{label: 'December', value: 12}
|
||||
];
|
||||
|
||||
constructor() {
|
||||
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;
|
||||
if (label === 'Sessions') {
|
||||
return `${label}: ${value} session${value !== 1 ? 's' : ''}`;
|
||||
} else {
|
||||
return `${label}: ${value} min`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Hour of Day',
|
||||
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: 'Number of Sessions',
|
||||
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: 'Avg Duration (min)',
|
||||
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: 'All Years', value: null}];
|
||||
for (let year = currentYear; year >= currentYear - 10; year--) {
|
||||
this.yearOptions.push({label: year.toString(), value: year});
|
||||
}
|
||||
}
|
||||
|
||||
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: '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: 'Avg Duration (min)',
|
||||
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`;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<div class="personal-rating-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-star-fill personal-rating-icon"></i>
|
||||
Personal Rating Distribution
|
||||
</h3>
|
||||
<p class="chart-description">Books by your rating (1–10)</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
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],
|
||||
templateUrl: './personal-rating-chart.component.html',
|
||||
styleUrls: ['./personal-rating-chart.component.scss']
|
||||
})
|
||||
export class PersonalRatingChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
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) => `Personal Rating: ${context[0].label}`,
|
||||
label: (context) => {
|
||||
const value = context.parsed.y;
|
||||
return `${value} book${value === 1 ? '' : 's'}`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Personal Rating',
|
||||
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: 'Number of Books',
|
||||
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}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<RatingChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books by Personal Rating',
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<RatingChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
catchError((error) => {
|
||||
console.error('Error processing personal rating data:', error);
|
||||
return EMPTY;
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculatePersonalRatingStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: RatingStats[]): void {
|
||||
try {
|
||||
// Always show all rating labels from 1-10, even if there's no data
|
||||
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]);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels: allLabels,
|
||||
datasets: [{
|
||||
label: 'Books by Personal Rating',
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private calculatePersonalRatingStats(): RatingStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processPersonalRatingStats(currentState.books!);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private 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
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<div class="rating-taste-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-scatter rating-taste-icon"></i>
|
||||
Rating Taste Comparison
|
||||
</h3>
|
||||
<p class="chart-description">Compare your personal ratings against external ratings (Goodreads, Amazon, etc.)</p>
|
||||
</div>
|
||||
@if (totalRatedBooks > 0) {
|
||||
<div class="stats-badge">
|
||||
<span class="badge-value">{{ totalRatedBooks }}</span>
|
||||
<span class="badge-label">books analyzed</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
<div class="quadrant-labels">
|
||||
<div class="quadrant-label top-left">Hidden Gems 💎</div>
|
||||
<div class="quadrant-label top-right">Popular Favorites ⭐</div>
|
||||
<div class="quadrant-label bottom-left">Agreed Misses 👎</div>
|
||||
<div class="quadrant-label bottom-right">Overrated 📉</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (quadrants.length > 0) {
|
||||
<div class="taste-insights">
|
||||
<div class="insights-header">
|
||||
<h4>Your Taste Profile</h4>
|
||||
@if (averageDeviation > 0) {
|
||||
<div class="deviation-badge" [class.unique]="averageDeviation > 1" [class.mainstream]="averageDeviation <= 0.5">
|
||||
<span class="deviation-label">Avg. deviation:</span>
|
||||
<span class="deviation-value">{{ averageDeviation.toFixed(2) }} ★</span>
|
||||
<span class="deviation-desc">
|
||||
@if (averageDeviation > 1) {
|
||||
(Unique taste)
|
||||
} @else if (averageDeviation <= 0.5) {
|
||||
(Mainstream)
|
||||
} @else {
|
||||
(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>
|
||||
}
|
||||
|
||||
@if (totalRatedBooks === 0) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No books with both personal and external ratings found.</p>
|
||||
<small>Rate your books and ensure they have external ratings from Goodreads, Amazon, etc.</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, ScatterDataPoint} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
interface TasteQuadrant {
|
||||
name: string;
|
||||
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>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-rating-taste-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './rating-taste-chart.component.html',
|
||||
styleUrls: ['./rating-taste-chart.component.scss']
|
||||
})
|
||||
export class RatingTasteChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'scatter' as const;
|
||||
public quadrants: TasteQuadrant[] = [];
|
||||
public totalRatedBooks = 0;
|
||||
public averageDeviation = 0;
|
||||
|
||||
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: 'External Rating (1-5 scale)',
|
||||
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: 'Your Personal Rating (normalized from 1-10)',
|
||||
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 || 'Unknown Book';
|
||||
},
|
||||
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 [
|
||||
`Your Rating: ${point.personalRating}/10 (${point.personalRatingNormalized.toFixed(1)}/5)`,
|
||||
`External Rating: ${point.externalRating.toFixed(1)}/5`,
|
||||
`Difference: ${diffText} (on 5-point scale)`,
|
||||
`Category: ${point.quadrant}`
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
elements: {
|
||||
point: {
|
||||
radius: 6,
|
||||
hoverRadius: 9,
|
||||
borderWidth: 2
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<RatingTasteChartData>({
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<RatingTasteChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing rating taste data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({datasets: []});
|
||||
this.quadrants = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
const ratedBooks = this.getBooksWithBothRatings(filteredBooks);
|
||||
|
||||
if (ratedBooks.length === 0) {
|
||||
this.chartDataSubject.next({datasets: []});
|
||||
this.quadrants = [];
|
||||
this.totalRatedBooks = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
this.totalRatedBooks = ratedBooks.length;
|
||||
const dataPoints = this.categorizeBooks(ratedBooks);
|
||||
this.updateChartData(dataPoints);
|
||||
this.calculateStatistics(dataPoints);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private 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[]>([
|
||||
['Hidden Gems', []],
|
||||
['Popular Favorites', []],
|
||||
['Overrated', []],
|
||||
['Agreed Misses', []]
|
||||
]);
|
||||
|
||||
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 = 'Popular Favorites';
|
||||
} else if (personalRatingNormalized >= 3 && externalRating < 3) {
|
||||
quadrant = 'Hidden Gems';
|
||||
} else if (personalRatingNormalized < 3 && externalRating >= 3) {
|
||||
quadrant = 'Overrated';
|
||||
} else {
|
||||
quadrant = 'Agreed Misses';
|
||||
}
|
||||
|
||||
const dataPoint: BookDataPoint = {
|
||||
x: externalRating,
|
||||
y: personalRatingNormalized,
|
||||
bookTitle,
|
||||
personalRating,
|
||||
personalRatingNormalized,
|
||||
externalRating,
|
||||
quadrant
|
||||
};
|
||||
|
||||
categories.get(quadrant)!.push(dataPoint);
|
||||
});
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
private updateChartData(dataPoints: Map<string, BookDataPoint[]>): void {
|
||||
const quadrantColors: Record<string, { bg: string, border: string }> = {
|
||||
'Popular Favorites': {bg: 'rgba(76, 175, 80, 0.7)', border: '#4caf50'},
|
||||
'Hidden Gems': {bg: 'rgba(156, 39, 176, 0.7)', border: '#9c27b0'},
|
||||
'Overrated': {bg: 'rgba(255, 152, 0, 0.7)', border: '#ff9800'},
|
||||
'Agreed Misses': {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
|
||||
}));
|
||||
|
||||
this.chartDataSubject.next({datasets});
|
||||
}
|
||||
|
||||
private calculateStatistics(dataPoints: Map<string, BookDataPoint[]>): void {
|
||||
const quadrantInfo: Record<string, { description: string, icon: string, color: string }> = {
|
||||
'Popular Favorites': {
|
||||
description: 'Books you and the public both love',
|
||||
icon: '⭐',
|
||||
color: '#4caf50'
|
||||
},
|
||||
'Hidden Gems': {
|
||||
description: 'Books you rate higher than the public',
|
||||
icon: '💎',
|
||||
color: '#9c27b0'
|
||||
},
|
||||
'Overrated': {
|
||||
description: 'Popular books that disappointed you',
|
||||
icon: '📉',
|
||||
color: '#ff9800'
|
||||
},
|
||||
'Agreed Misses': {
|
||||
description: 'Books neither you nor public enjoyed',
|
||||
icon: '👎',
|
||||
color: '#9e9e9e'
|
||||
}
|
||||
};
|
||||
|
||||
this.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++;
|
||||
});
|
||||
});
|
||||
this.averageDeviation = totalPoints > 0 ? totalDeviation / totalPoints : 0;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<div class="read-status-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-book read-status-icon"></i>
|
||||
Reading Status Distribution
|
||||
</h3>
|
||||
<p class="chart-description">Books by their reading status</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, Chart, TooltipItem} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
|
||||
interface ReadingStatusStats {
|
||||
status: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
const STATUS_COLOR_MAP: Record<string, string> = {
|
||||
'Unread': '#6c757d', // Gray
|
||||
'Currently Reading': '#17a2b8', // Cyan
|
||||
'Re-reading': '#6f42c1', // Purple
|
||||
'Read': '#28a745', // Green
|
||||
'Partially Read': '#ffc107', // Yellow
|
||||
'Paused': '#fd7e14', // Orange
|
||||
"Won't Read": '#dc3545', // Red
|
||||
'Abandoned': '#e74c3c', // Light Red
|
||||
'No Status': '#343a40' // Dark Gray
|
||||
} 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],
|
||||
templateUrl: './read-status-chart.component.html',
|
||||
styleUrls: ['./read-status-chart.component.scss']
|
||||
})
|
||||
export class ReadStatusChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
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: this.formatTooltipLabel
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<StatusChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
data: [],
|
||||
backgroundColor: [...Object.values(STATUS_COLOR_MAP)],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<StatusChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
catchError((error) => {
|
||||
console.error('Error processing reading status stats:', error);
|
||||
return EMPTY;
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateReadingStatusStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: ReadingStatusStats[]): void {
|
||||
try {
|
||||
const labels = stats.map(s => s.status);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
const colors = stats.map(s => STATUS_COLOR_MAP[s.status] || '#6c757d');
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
data: dataValues,
|
||||
backgroundColor: colors,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateReadingStatusStats(): ReadingStatusStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processReadingStatusStats(currentState.books!);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private 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),
|
||||
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]: 'Unread',
|
||||
[ReadStatus.READING]: 'Currently Reading',
|
||||
[ReadStatus.RE_READING]: 'Re-reading',
|
||||
[ReadStatus.READ]: 'Read',
|
||||
[ReadStatus.PARTIALLY_READ]: 'Partially Read',
|
||||
[ReadStatus.PAUSED]: 'Paused',
|
||||
[ReadStatus.WONT_READ]: "Won't Read",
|
||||
[ReadStatus.ABANDONED]: 'Abandoned',
|
||||
[ReadStatus.UNSET]: 'No Status'
|
||||
};
|
||||
|
||||
if (!status) return 'No Status';
|
||||
return STATUS_MAPPING[status] ?? 'No Status';
|
||||
}
|
||||
|
||||
private generateLegendLabels(chart: Chart) {
|
||||
const data = chart.data;
|
||||
if (!data.labels?.length || !data.datasets?.[0]?.data?.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dataset = data.datasets[0];
|
||||
const dataValues = dataset.data as number[];
|
||||
|
||||
return data.labels.map((label: unknown, index: number) => {
|
||||
const isVisible = typeof chart.getDataVisibility === 'function'
|
||||
? chart.getDataVisibility(index)
|
||||
: !((chart.getDatasetMeta && (chart.getDatasetMeta(0)?.data?.[index] as any)?.hidden) || false);
|
||||
|
||||
return {
|
||||
text: `${String(label)} (${dataValues[index]})`,
|
||||
fillStyle: (dataset.backgroundColor as string[])[index],
|
||||
strokeStyle: '#ffffff',
|
||||
lineWidth: 1,
|
||||
hidden: !isVisible,
|
||||
index,
|
||||
fontColor: '#ffffff'
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: TooltipItem<any>): string {
|
||||
const dataIndex = context.dataIndex;
|
||||
const dataset = context.dataset;
|
||||
const value = dataset.data[dataIndex] as number;
|
||||
const label = context.chart.data.labels?.[dataIndex] || 'Unknown';
|
||||
const total = (dataset.data as number[]).reduce((a: number, b: number) => a + b, 0);
|
||||
const percentage = ((value / total) * 100).toFixed(1);
|
||||
return `${label}: ${value} books (${percentage}%)`;
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
<div class="backlog-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-clock backlog-icon"></i>
|
||||
Reading Backlog Analysis
|
||||
</h3>
|
||||
<p class="chart-description">Track how long books sit in your library and your reading patterns over time</p>
|
||||
</div>
|
||||
@if (stats) {
|
||||
<div class="health-score" [class]="getHealthScoreClass()">
|
||||
<div class="score-circle">
|
||||
<span class="score-value">{{ stats.backlogHealthScore }}</span>
|
||||
</div>
|
||||
<div class="score-info">
|
||||
<span class="score-label">Backlog Health</span>
|
||||
<span class="score-status">{{ getHealthScoreLabel() }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (stats) {
|
||||
<div class="stats-overview">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon books-icon">
|
||||
<i class="pi pi-book"></i>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-value">{{ stats.totalBooks }}</span>
|
||||
<span class="stat-label">Total Books</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon unread-icon">
|
||||
<i class="pi pi-inbox"></i>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-value">{{ stats.unreadBooks }}</span>
|
||||
<span class="stat-label">In Backlog</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon age-icon">
|
||||
<i class="pi pi-calendar"></i>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-value">{{ formatDays(stats.avgBacklogAge) }}</span>
|
||||
<span class="stat-label">Avg. Library Age</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon velocity-icon">
|
||||
<i class="pi pi-bolt"></i>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-value">{{ stats.readingVelocity }}</span>
|
||||
<span class="stat-label">Completed (6mo)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
@if (stats) {
|
||||
<div class="insights-section">
|
||||
<h4>Key Insights</h4>
|
||||
<div class="insights-grid">
|
||||
@if (stats.quickestRead) {
|
||||
<div class="insight-card quickest">
|
||||
<div class="insight-icon">
|
||||
<i class="pi pi-forward"></i>
|
||||
</div>
|
||||
<div class="insight-content">
|
||||
<span class="insight-title">Quickest Read</span>
|
||||
<span class="insight-book">{{ stats.quickestRead.title }}</span>
|
||||
<span class="insight-detail">Read in {{ formatDays(stats.quickestRead.daysToComplete!) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (stats.longestWait) {
|
||||
<div class="insight-card longest">
|
||||
<div class="insight-icon">
|
||||
<i class="pi pi-hourglass"></i>
|
||||
</div>
|
||||
<div class="insight-content">
|
||||
<span class="insight-title">Longest Wait</span>
|
||||
<span class="insight-book">{{ stats.longestWait.title }}</span>
|
||||
<span class="insight-detail">Waited {{ formatDays(stats.longestWait.daysToComplete!) }} to read</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (stats.oldestUnread) {
|
||||
<div class="insight-card oldest">
|
||||
<div class="insight-icon">
|
||||
<i class="pi pi-history"></i>
|
||||
</div>
|
||||
<div class="insight-content">
|
||||
<span class="insight-title">Oldest Unread</span>
|
||||
<span class="insight-book">{{ stats.oldestUnread.title }}</span>
|
||||
<span class="insight-detail">Waiting for {{ formatDays(stats.oldestUnread.daysInLibrary) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (stats.avgDaysToRead > 0) {
|
||||
<div class="insight-card average">
|
||||
<div class="insight-icon">
|
||||
<i class="pi pi-chart-line"></i>
|
||||
</div>
|
||||
<div class="insight-content">
|
||||
<span class="insight-title">Average Time to Read</span>
|
||||
<span class="insight-value-large">{{ formatDays(stats.avgDaysToRead) }}</span>
|
||||
<span class="insight-detail">From acquisition to completion</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bucket-details">
|
||||
<h4>Backlog Breakdown</h4>
|
||||
<div class="bucket-list">
|
||||
@for (bucket of buckets; track bucket.label) {
|
||||
@if (bucket.unread + bucket.reading + bucket.completed > 0) {
|
||||
<div class="bucket-item">
|
||||
<div class="bucket-header">
|
||||
<span class="bucket-label">{{ bucket.label }}</span>
|
||||
<span class="bucket-range">{{ bucket.range }}</span>
|
||||
<span class="bucket-total">{{ bucket.unread + bucket.reading + bucket.completed }} books</span>
|
||||
</div>
|
||||
<div class="bucket-bars">
|
||||
<div class="bucket-bar-container">
|
||||
@if (bucket.unread > 0) {
|
||||
<div class="bucket-bar unread"
|
||||
[style.flex]="bucket.unread"
|
||||
[title]="bucket.unread + ' unread'">
|
||||
{{ bucket.unread }}
|
||||
</div>
|
||||
}
|
||||
@if (bucket.reading > 0) {
|
||||
<div class="bucket-bar reading"
|
||||
[style.flex]="bucket.reading"
|
||||
[title]="bucket.reading + ' reading'">
|
||||
{{ bucket.reading }}
|
||||
</div>
|
||||
}
|
||||
@if (bucket.completed > 0) {
|
||||
<div class="bucket-bar completed"
|
||||
[style.flex]="bucket.completed"
|
||||
[title]="bucket.completed + ' completed'">
|
||||
{{ bucket.completed }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@if (bucket.avgDaysToRead !== null) {
|
||||
<span class="bucket-avg">Avg. {{ formatDays(bucket.avgDaysToRead) }} to read</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!stats) {
|
||||
<div class="no-data-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>No books with addition dates found.</p>
|
||||
<small>Backlog analysis requires books with "Added On" dates in your library.</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+485
@@ -0,0 +1,485 @@
|
||||
.backlog-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 1.5rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
|
||||
.chart-title {
|
||||
flex: 1;
|
||||
min-width: 250px;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
.health-score {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 2px solid;
|
||||
|
||||
&.healthy {
|
||||
border-color: rgba(76, 175, 80, 0.5);
|
||||
background: rgba(76, 175, 80, 0.1);
|
||||
|
||||
.score-circle {
|
||||
background: linear-gradient(135deg, #4caf50, #81c784);
|
||||
}
|
||||
}
|
||||
|
||||
&.moderate {
|
||||
border-color: rgba(255, 193, 7, 0.5);
|
||||
background: rgba(255, 193, 7, 0.1);
|
||||
|
||||
.score-circle {
|
||||
background: linear-gradient(135deg, #ffc107, #ffca28);
|
||||
}
|
||||
}
|
||||
|
||||
&.unhealthy {
|
||||
border-color: rgba(239, 83, 80, 0.5);
|
||||
background: rgba(239, 83, 80, 0.1);
|
||||
|
||||
.score-circle {
|
||||
background: linear-gradient(135deg, #ef5350, #e57373);
|
||||
}
|
||||
}
|
||||
|
||||
.score-circle {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
.score-value {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
}
|
||||
}
|
||||
|
||||
.score-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.score-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.score-status {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.backlog-icon {
|
||||
font-size: 1.5rem;
|
||||
color: #2196f3;
|
||||
}
|
||||
|
||||
.stats-overview {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
.stat-icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.1rem;
|
||||
|
||||
&.books-icon {
|
||||
background: rgba(33, 150, 243, 0.2);
|
||||
color: #2196f3;
|
||||
}
|
||||
|
||||
&.unread-icon {
|
||||
background: rgba(239, 83, 80, 0.2);
|
||||
color: #ef5350;
|
||||
}
|
||||
|
||||
&.age-icon {
|
||||
background: rgba(156, 39, 176, 0.2);
|
||||
color: #9c27b0;
|
||||
}
|
||||
|
||||
&.velocity-icon {
|
||||
background: rgba(76, 175, 80, 0.2);
|
||||
color: #4caf50;
|
||||
}
|
||||
}
|
||||
|
||||
.stat-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 280px;
|
||||
width: 100%;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.insights-section {
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
h4 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.insights-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 10px;
|
||||
border-left: 3px solid;
|
||||
|
||||
&.quickest {
|
||||
border-left-color: #4caf50;
|
||||
|
||||
.insight-icon {
|
||||
color: #4caf50;
|
||||
background: rgba(76, 175, 80, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
&.longest {
|
||||
border-left-color: #ff9800;
|
||||
|
||||
.insight-icon {
|
||||
color: #ff9800;
|
||||
background: rgba(255, 152, 0, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
&.oldest {
|
||||
border-left-color: #ef5350;
|
||||
|
||||
.insight-icon {
|
||||
color: #ef5350;
|
||||
background: rgba(239, 83, 80, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
&.average {
|
||||
border-left-color: #2196f3;
|
||||
|
||||
.insight-icon {
|
||||
color: #2196f3;
|
||||
background: rgba(33, 150, 243, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
.insight-icon {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.insight-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
|
||||
.insight-title {
|
||||
font-size: 0.7rem;
|
||||
color: var(--text-secondary-color);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.insight-book {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color, #ffffff);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.insight-value-large {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #ffffff);
|
||||
}
|
||||
|
||||
.insight-detail {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-secondary-color);
|
||||
margin-top: 0.15rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.bucket-details {
|
||||
h4 {
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.bucket-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.bucket-item {
|
||||
padding: 0.75rem 1rem;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
|
||||
.bucket-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.bucket-label {
|
||||
font-weight: 500;
|
||||
color: var(--text-color, #ffffff);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.bucket-range {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary-color);
|
||||
padding: 0.15rem 0.5rem;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.bucket-total {
|
||||
margin-left: auto;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.bucket-bars {
|
||||
.bucket-bar-container {
|
||||
display: flex;
|
||||
height: 24px;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.bucket-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
color: #ffffff;
|
||||
min-width: 24px;
|
||||
transition: flex 0.3s ease;
|
||||
|
||||
&.unread {
|
||||
background: rgba(239, 83, 80, 0.8);
|
||||
}
|
||||
|
||||
&.reading {
|
||||
background: rgba(255, 193, 7, 0.8);
|
||||
}
|
||||
|
||||
&.completed {
|
||||
background: rgba(76, 175, 80, 0.8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.bucket-avg {
|
||||
display: block;
|
||||
margin-top: 0.5rem;
|
||||
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-header {
|
||||
.health-score {
|
||||
.score-circle {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
|
||||
.score-value {
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.stats-overview {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
|
||||
.stat-card {
|
||||
.stat-content {
|
||||
.stat-value {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
.insights-section {
|
||||
.insights-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.chart-header {
|
||||
.chart-title {
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.stats-overview {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.75rem;
|
||||
|
||||
.stat-card {
|
||||
padding: 0.75rem;
|
||||
|
||||
.stat-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
height: 220px;
|
||||
}
|
||||
|
||||
.bucket-details {
|
||||
.bucket-item {
|
||||
.bucket-header {
|
||||
flex-wrap: wrap;
|
||||
|
||||
.bucket-total {
|
||||
width: 100%;
|
||||
margin-left: 0;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+470
@@ -0,0 +1,470 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
|
||||
interface BacklogBucket {
|
||||
label: string;
|
||||
range: string;
|
||||
unread: number;
|
||||
reading: number;
|
||||
completed: number;
|
||||
avgDaysToRead: number | null;
|
||||
books: BookBacklogInfo[];
|
||||
}
|
||||
|
||||
interface BookBacklogInfo {
|
||||
title: string;
|
||||
addedOn: Date;
|
||||
daysInLibrary: number;
|
||||
daysToComplete: number | null;
|
||||
status: ReadStatus;
|
||||
}
|
||||
|
||||
interface BacklogStats {
|
||||
totalBooks: number;
|
||||
unreadBooks: number;
|
||||
avgBacklogAge: number;
|
||||
avgDaysToRead: number;
|
||||
oldestUnread: BookBacklogInfo | null;
|
||||
quickestRead: BookBacklogInfo | null;
|
||||
longestWait: BookBacklogInfo | null;
|
||||
readingVelocity: number;
|
||||
backlogHealthScore: number;
|
||||
}
|
||||
|
||||
type BacklogChartData = ChartData<'bar', number[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-backlog-chart',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
templateUrl: './reading-backlog-chart.component.html',
|
||||
styleUrls: ['./reading-backlog-chart.component.scss']
|
||||
})
|
||||
export class ReadingBacklogChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public buckets: BacklogBucket[] = [];
|
||||
public stats: BacklogStats | null = null;
|
||||
|
||||
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,
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Number of Books',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(255, 255, 255, 0.1)'
|
||||
}
|
||||
},
|
||||
y: {
|
||||
stacked: true,
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Time in Library',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 12,
|
||||
weight: 500
|
||||
}
|
||||
},
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
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: 'rect',
|
||||
padding: 15
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.95)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#2196f3',
|
||||
borderWidth: 2,
|
||||
cornerRadius: 8,
|
||||
padding: 12,
|
||||
titleFont: {size: 13, weight: 'bold'},
|
||||
bodyFont: {size: 11},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const bucket = this.buckets[context[0].dataIndex];
|
||||
return bucket ? `${bucket.label} (${bucket.range})` : '';
|
||||
},
|
||||
afterBody: (context) => {
|
||||
const bucket = this.buckets[context[0].dataIndex];
|
||||
if (!bucket) return [];
|
||||
const lines = [];
|
||||
if (bucket.avgDaysToRead !== null) {
|
||||
lines.push(`Avg. days to read: ${bucket.avgDaysToRead.toFixed(0)}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<BacklogChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<BacklogChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing backlog data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private calculateAndUpdateChart(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.buckets = [];
|
||||
this.stats = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
const booksWithDates = this.getBooksWithAddedDate(filteredBooks);
|
||||
|
||||
if (booksWithDates.length === 0) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.buckets = [];
|
||||
this.stats = null;
|
||||
return;
|
||||
}
|
||||
|
||||
this.buckets = this.calculateBacklogBuckets(booksWithDates);
|
||||
this.stats = this.calculateBacklogStats(booksWithDates);
|
||||
this.updateChartData();
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private getBooksWithAddedDate(books: Book[]): Book[] {
|
||||
return books.filter(book => book.addedOn);
|
||||
}
|
||||
|
||||
private calculateBacklogBuckets(books: Book[]): BacklogBucket[] {
|
||||
const now = new Date();
|
||||
const bucketDefs = [
|
||||
{label: 'Fresh', range: '< 1 week', minDays: 0, maxDays: 7},
|
||||
{label: 'Recent', range: '1-4 weeks', minDays: 7, maxDays: 30},
|
||||
{label: 'Settling', range: '1-3 months', minDays: 30, maxDays: 90},
|
||||
{label: 'Established', range: '3-6 months', minDays: 90, maxDays: 180},
|
||||
{label: 'Seasoned', range: '6-12 months', minDays: 180, maxDays: 365},
|
||||
{label: 'Vintage', range: '1-2 years', minDays: 365, maxDays: 730},
|
||||
{label: 'Archive', range: '2+ years', minDays: 730, maxDays: Infinity}
|
||||
];
|
||||
|
||||
return bucketDefs.map(def => {
|
||||
const bucketBooks: BookBacklogInfo[] = [];
|
||||
let unread = 0;
|
||||
let reading = 0;
|
||||
let completed = 0;
|
||||
let totalDaysToRead = 0;
|
||||
let completedCount = 0;
|
||||
|
||||
books.forEach(book => {
|
||||
const addedDate = new Date(book.addedOn!);
|
||||
const daysInLibrary = Math.floor((now.getTime() - addedDate.getTime()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (daysInLibrary >= def.minDays && daysInLibrary < def.maxDays) {
|
||||
let daysToComplete: number | null = null;
|
||||
|
||||
if (book.dateFinished) {
|
||||
const finishedDate = new Date(book.dateFinished);
|
||||
daysToComplete = Math.floor((finishedDate.getTime() - addedDate.getTime()) / (1000 * 60 * 60 * 24));
|
||||
if (daysToComplete < 0) daysToComplete = 0;
|
||||
}
|
||||
|
||||
const bookInfo: BookBacklogInfo = {
|
||||
title: book.metadata?.title || book.fileName || 'Unknown',
|
||||
addedOn: addedDate,
|
||||
daysInLibrary,
|
||||
daysToComplete,
|
||||
status: book.readStatus || ReadStatus.UNSET
|
||||
};
|
||||
|
||||
bucketBooks.push(bookInfo);
|
||||
|
||||
switch (book.readStatus) {
|
||||
case ReadStatus.READING:
|
||||
case ReadStatus.RE_READING:
|
||||
reading++;
|
||||
break;
|
||||
case ReadStatus.READ:
|
||||
completed++;
|
||||
if (daysToComplete !== null) {
|
||||
totalDaysToRead += daysToComplete;
|
||||
completedCount++;
|
||||
}
|
||||
break;
|
||||
case ReadStatus.UNREAD:
|
||||
case ReadStatus.UNSET:
|
||||
case ReadStatus.PAUSED:
|
||||
case ReadStatus.WONT_READ:
|
||||
case ReadStatus.ABANDONED:
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
default:
|
||||
unread++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
label: def.label,
|
||||
range: def.range,
|
||||
unread,
|
||||
reading,
|
||||
completed,
|
||||
avgDaysToRead: completedCount > 0 ? totalDaysToRead / completedCount : null,
|
||||
books: bucketBooks
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private calculateBacklogStats(books: Book[]): BacklogStats {
|
||||
const now = new Date();
|
||||
let totalDaysInLibrary = 0;
|
||||
let totalDaysToRead = 0;
|
||||
let completedWithDates = 0;
|
||||
let unreadBooks = 0;
|
||||
let oldestUnread: BookBacklogInfo | null = null;
|
||||
let quickestRead: BookBacklogInfo | null = null;
|
||||
let longestWait: BookBacklogInfo | null = null;
|
||||
let recentlyCompleted = 0;
|
||||
|
||||
const sixMonthsAgo = new Date();
|
||||
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
|
||||
|
||||
books.forEach(book => {
|
||||
const addedDate = new Date(book.addedOn!);
|
||||
const daysInLibrary = Math.floor((now.getTime() - addedDate.getTime()) / (1000 * 60 * 60 * 24));
|
||||
totalDaysInLibrary += daysInLibrary;
|
||||
|
||||
let daysToComplete: number | null = null;
|
||||
if (book.dateFinished) {
|
||||
const finishedDate = new Date(book.dateFinished);
|
||||
daysToComplete = Math.floor((finishedDate.getTime() - addedDate.getTime()) / (1000 * 60 * 60 * 24));
|
||||
if (daysToComplete < 0) daysToComplete = 0;
|
||||
|
||||
if (finishedDate > sixMonthsAgo) {
|
||||
recentlyCompleted++;
|
||||
}
|
||||
}
|
||||
|
||||
const bookInfo: BookBacklogInfo = {
|
||||
title: book.metadata?.title || book.fileName || 'Unknown',
|
||||
addedOn: addedDate,
|
||||
daysInLibrary,
|
||||
daysToComplete,
|
||||
status: book.readStatus || ReadStatus.UNSET
|
||||
};
|
||||
|
||||
const isUnread = book.readStatus === ReadStatus.UNREAD ||
|
||||
book.readStatus === ReadStatus.UNSET ||
|
||||
book.readStatus === ReadStatus.PAUSED ||
|
||||
!book.readStatus;
|
||||
|
||||
if (isUnread) {
|
||||
unreadBooks++;
|
||||
if (!oldestUnread || daysInLibrary > oldestUnread.daysInLibrary) {
|
||||
oldestUnread = bookInfo;
|
||||
}
|
||||
}
|
||||
|
||||
if (book.readStatus === ReadStatus.READ && daysToComplete !== null) {
|
||||
totalDaysToRead += daysToComplete;
|
||||
completedWithDates++;
|
||||
|
||||
if (!quickestRead || daysToComplete < (quickestRead.daysToComplete || Infinity)) {
|
||||
quickestRead = bookInfo;
|
||||
}
|
||||
if (!longestWait || daysToComplete > (longestWait.daysToComplete || 0)) {
|
||||
longestWait = bookInfo;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const avgBacklogAge = books.length > 0 ? totalDaysInLibrary / books.length : 0;
|
||||
const avgDaysToRead = completedWithDates > 0 ? totalDaysToRead / completedWithDates : 0;
|
||||
const readingVelocity = recentlyCompleted; // Books completed in last 6 months
|
||||
|
||||
// Backlog health score (0-100)
|
||||
// Lower unread percentage = better
|
||||
// Lower avg backlog age = better
|
||||
// Higher reading velocity = better
|
||||
const unreadPercentage = books.length > 0 ? (unreadBooks / books.length) * 100 : 0;
|
||||
const ageScore = Math.max(0, 100 - (avgBacklogAge / 365) * 50); // Penalize old backlogs
|
||||
const velocityScore = Math.min(100, readingVelocity * 10); // Reward active reading
|
||||
const completionScore = 100 - unreadPercentage;
|
||||
|
||||
const backlogHealthScore = Math.round((ageScore * 0.3 + velocityScore * 0.3 + completionScore * 0.4));
|
||||
|
||||
return {
|
||||
totalBooks: books.length,
|
||||
unreadBooks,
|
||||
avgBacklogAge,
|
||||
avgDaysToRead,
|
||||
oldestUnread,
|
||||
quickestRead,
|
||||
longestWait,
|
||||
readingVelocity,
|
||||
backlogHealthScore: Math.min(100, Math.max(0, backlogHealthScore))
|
||||
};
|
||||
}
|
||||
|
||||
private updateChartData(): void {
|
||||
const labels = this.buckets.map(b => b.label);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Unread',
|
||||
data: this.buckets.map(b => b.unread),
|
||||
backgroundColor: 'rgba(239, 83, 80, 0.8)',
|
||||
borderColor: '#ef5350',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4
|
||||
},
|
||||
{
|
||||
label: 'Reading',
|
||||
data: this.buckets.map(b => b.reading),
|
||||
backgroundColor: 'rgba(255, 193, 7, 0.8)',
|
||||
borderColor: '#ffc107',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4
|
||||
},
|
||||
{
|
||||
label: 'Completed',
|
||||
data: this.buckets.map(b => b.completed),
|
||||
backgroundColor: 'rgba(76, 175, 80, 0.8)',
|
||||
borderColor: '#4caf50',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
getHealthScoreClass(): string {
|
||||
if (!this.stats) return '';
|
||||
if (this.stats.backlogHealthScore >= 70) return 'healthy';
|
||||
if (this.stats.backlogHealthScore >= 40) return 'moderate';
|
||||
return 'unhealthy';
|
||||
}
|
||||
|
||||
getHealthScoreLabel(): string {
|
||||
if (!this.stats) return '';
|
||||
if (this.stats.backlogHealthScore >= 70) return 'Healthy';
|
||||
if (this.stats.backlogHealthScore >= 40) return 'Moderate';
|
||||
return 'Needs Attention';
|
||||
}
|
||||
|
||||
formatDays(days: number): string {
|
||||
const roundedDays = Math.round(days);
|
||||
if (roundedDays < 7) return `${roundedDays} day${roundedDays !== 1 ? 's' : ''}`;
|
||||
const weeks = Math.round(roundedDays / 7);
|
||||
if (roundedDays < 30) return `${weeks} week${weeks !== 1 ? 's' : ''}`;
|
||||
const months = Math.round(roundedDays / 30);
|
||||
if (roundedDays < 365) return `${months} month${months !== 1 ? 's' : ''}`;
|
||||
const years = Math.round((roundedDays / 365) * 10) / 10; // Round to 1 decimal
|
||||
return `${years} year${years >= 2 ? 's' : ''}`;
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
<div class="reading-dna-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-line reading-dna-icon"></i>
|
||||
Reading DNA Profile
|
||||
</h3>
|
||||
<p class="chart-description">Your unique reading personality across 8 key dimensions</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
@if (personalityInsights.length > 0) {
|
||||
<div class="personality-insights">
|
||||
<h4>Your Reading Personality Traits</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>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
|
||||
+563
@@ -0,0 +1,563 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
|
||||
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],
|
||||
templateUrl: './reading-dna-chart.component.html',
|
||||
styleUrls: ['./reading-dna-chart.component.scss']
|
||||
})
|
||||
export class ReadingDNAChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
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: function (label: string) {
|
||||
const icons: Record<string, string> = {
|
||||
'Adventurous': '🌟',
|
||||
'Perfectionist': '💎',
|
||||
'Intellectual': '🧠',
|
||||
'Emotional': '💖',
|
||||
'Patient': '🕰️',
|
||||
'Social': '👥',
|
||||
'Nostalgic': '📚',
|
||||
'Ambitious': '🚀'
|
||||
};
|
||||
return [icons[label] || '', 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 `${label} Personality`;
|
||||
},
|
||||
label: (context) => {
|
||||
const score = context.parsed.r;
|
||||
const insight = this.personalityInsights.find(i => i.trait === context.label);
|
||||
|
||||
return [
|
||||
`Score: ${score.toFixed(1)}/100`,
|
||||
'',
|
||||
insight ? insight.description : 'Your reading personality trait'
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
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 chartDataSubject = new BehaviorSubject<ReadingDNAChartData>({
|
||||
labels: [
|
||||
'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional',
|
||||
'Patient', 'Social', 'Nostalgic', 'Ambitious'
|
||||
],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<ReadingDNAChartData> = this.chartDataSubject.asObservable();
|
||||
public personalityInsights: PersonalityInsight[] = [];
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
catchError((error) => {
|
||||
console.error('Error processing reading DNA data:', error);
|
||||
return EMPTY;
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(() => {
|
||||
const profile = this.calculateReadingDNAData();
|
||||
this.updateChartData(profile);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(profile: ReadingDNAProfile | null): void {
|
||||
try {
|
||||
if (!profile) {
|
||||
this.chartDataSubject.next({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.personalityInsights = [];
|
||||
return;
|
||||
}
|
||||
|
||||
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'
|
||||
];
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels: [
|
||||
'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional',
|
||||
'Patient', 'Social', 'Nostalgic', 'Ambitious'
|
||||
],
|
||||
datasets: [{
|
||||
label: 'Reading DNA Profile',
|
||||
data,
|
||||
backgroundColor: 'rgba(233, 30, 99, 0.2)',
|
||||
borderColor: '#e91e63',
|
||||
borderWidth: 3,
|
||||
pointBackgroundColor: gradientColors,
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 3,
|
||||
pointRadius: 5,
|
||||
pointHoverRadius: 8,
|
||||
fill: true
|
||||
}]
|
||||
});
|
||||
|
||||
this.personalityInsights = this.convertToPersonalityInsights(profile);
|
||||
} catch (error) {
|
||||
console.error('Error updating reading DNA chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateReadingDNAData(): ReadingDNAProfile | null {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.analyzeReadingDNA(currentState.books!);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private analyzeReadingDNA(books: Book[]): ReadingDNAProfile {
|
||||
if (books.length === 0) {
|
||||
return this.getDefaultProfile();
|
||||
}
|
||||
|
||||
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)
|
||||
};
|
||||
}
|
||||
|
||||
private calculateAdventurousScore(books: Book[]): number {
|
||||
const genres = new Set<string>();
|
||||
const languages = new Set<string>();
|
||||
const formats = new Set<string>();
|
||||
|
||||
books.forEach(book => {
|
||||
book.metadata?.categories?.forEach(cat => genres.add(cat.toLowerCase()));
|
||||
if (book.metadata?.language) languages.add(book.metadata.language);
|
||||
formats.add(book.bookType);
|
||||
});
|
||||
|
||||
const genreScore = Math.min(60, genres.size * 4);
|
||||
const languageScore = Math.min(20, languages.size * 10);
|
||||
const formatScore = Math.min(20, formats.size * 7);
|
||||
|
||||
return genreScore + languageScore + formatScore;
|
||||
}
|
||||
|
||||
private calculatePerfectionistScore(books: Book[]): number {
|
||||
const completedBooks = books.filter(b => b.readStatus === ReadStatus.READ);
|
||||
const completionRate = completedBooks.length / books.length;
|
||||
|
||||
const qualityBooks = books.filter(book => {
|
||||
const metadata = book.metadata;
|
||||
if (!metadata) return false;
|
||||
return (metadata.goodreadsRating && metadata.goodreadsRating >= 4.0) ||
|
||||
(metadata.amazonRating && metadata.amazonRating >= 4.0) ||
|
||||
(book.personalRating && book.personalRating >= 4);
|
||||
});
|
||||
|
||||
const qualityRate = qualityBooks.length / books.length;
|
||||
const completionScore = completionRate * 60;
|
||||
const qualityScore = qualityRate * 40;
|
||||
|
||||
return Math.min(100, completionScore + qualityScore);
|
||||
}
|
||||
|
||||
private calculateIntellectualScore(books: Book[]): number {
|
||||
const intellectualGenres = [
|
||||
'philosophy', 'science', 'history', 'biography', 'politics',
|
||||
'psychology', 'sociology', 'economics', 'technology', 'mathematics',
|
||||
'physics', 'chemistry', 'medicine', 'law', 'education',
|
||||
'anthropology', 'archaeology', 'astronomy', 'biology', 'geology',
|
||||
'linguistics', 'neuroscience', 'quantum physics', 'engineering',
|
||||
'computer science', 'artificial intelligence', 'data science',
|
||||
'research', 'academic', 'scholarly', 'theoretical', 'scientific',
|
||||
'analytical', 'critical thinking', 'logic', 'rhetoric',
|
||||
'cultural studies', 'international relations', 'diplomacy',
|
||||
'public policy', 'governance', 'constitutional law', 'ethics',
|
||||
'moral philosophy', 'epistemology', 'metaphysics', 'theology',
|
||||
'religious studies', 'comparative religion', 'apologetics'
|
||||
];
|
||||
|
||||
const intellectualBooks = books.filter(book => {
|
||||
if (!book.metadata?.categories) return false;
|
||||
return book.metadata.categories.some(cat =>
|
||||
intellectualGenres.some(genre => cat.toLowerCase().includes(genre))
|
||||
);
|
||||
});
|
||||
|
||||
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, (intellectualRate * 70) + (longBookRate * 30));
|
||||
}
|
||||
|
||||
private calculateEmotionalScore(books: Book[]): number {
|
||||
const emotionalGenres = [
|
||||
'fiction', 'romance', 'drama', 'literary', 'contemporary',
|
||||
'memoir', 'poetry', 'young adult', 'coming of age', 'family',
|
||||
'love story', 'relationships', 'emotional', 'heartbreak',
|
||||
'healing', 'self-help', 'personal development', 'inspirational',
|
||||
'motivational', 'spiritual', 'mindfulness', 'meditation',
|
||||
'grief', 'loss', 'trauma', 'recovery', 'therapy',
|
||||
'women\'s fiction', 'chick lit', 'new adult', 'teen',
|
||||
'childhood', 'parenting', 'motherhood', 'fatherhood',
|
||||
'friendship', 'betrayal', 'forgiveness', 'redemption',
|
||||
'slice of life', 'domestic fiction', 'family saga',
|
||||
'generational saga', 'multicultural', 'immigrant stories',
|
||||
'lgbtq+', 'queer fiction', 'feminist', 'gender studies',
|
||||
'social issues', 'mental health', 'addiction', 'wellness',
|
||||
'autobiography', 'personal narrative', 'diary', 'journal'
|
||||
];
|
||||
|
||||
const emotionalBooks = books.filter(book => {
|
||||
if (!book.metadata?.categories) return false;
|
||||
return book.metadata.categories.some(cat =>
|
||||
emotionalGenres.some(genre => cat.toLowerCase().includes(genre))
|
||||
);
|
||||
});
|
||||
|
||||
const personallyRatedBooks = books.filter(book => book.personalRating);
|
||||
|
||||
const emotionalRate = emotionalBooks.length / books.length;
|
||||
const ratingEngagement = personallyRatedBooks.length / books.length;
|
||||
|
||||
return Math.min(100, (emotionalRate * 60) + (ratingEngagement * 40));
|
||||
}
|
||||
|
||||
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 => {
|
||||
const progress = Math.max(
|
||||
book.epubProgress?.percentage || 0,
|
||||
book.pdfProgress?.percentage || 0,
|
||||
book.cbxProgress?.percentage || 0,
|
||||
book.koreaderProgress?.percentage || 0,
|
||||
book.koboProgress?.percentage || 0
|
||||
);
|
||||
return progress > 50;
|
||||
});
|
||||
|
||||
const longBookRate = longBooks.length / books.length;
|
||||
const seriesRate = seriesBooks.length / books.length;
|
||||
const progressRate = progressBooks.length / books.length;
|
||||
|
||||
return Math.min(100, (longBookRate * 40) + (seriesRate * 35) + (progressRate * 25));
|
||||
}
|
||||
|
||||
private calculateSocialScore(books: Book[]): number {
|
||||
const popularBooks = books.filter(book => {
|
||||
const metadata = book.metadata;
|
||||
if (!metadata) return false;
|
||||
return (metadata.goodreadsReviewCount && metadata.goodreadsReviewCount > 1000) ||
|
||||
(metadata.amazonReviewCount && metadata.amazonReviewCount > 500);
|
||||
});
|
||||
|
||||
const mainstreamGenres = [
|
||||
'thriller', 'mystery', 'romance', 'fantasy', 'science fiction',
|
||||
'horror', 'adventure', 'bestseller', 'contemporary', 'popular',
|
||||
'crime', 'detective', 'suspense', 'action', 'espionage',
|
||||
'spy', 'police procedural', 'cozy mystery', 'psychological thriller',
|
||||
'domestic thriller', 'legal thriller', 'medical thriller',
|
||||
'urban fantasy', 'paranormal', 'supernatural', 'magic',
|
||||
'dystopian', 'post-apocalyptic', 'cyberpunk', 'space opera',
|
||||
'military science fiction', 'hard science fiction', 'steampunk',
|
||||
'alternate history', 'time travel', 'vampire', 'werewolf',
|
||||
'zombie', 'ghost', 'gothic', 'dark fantasy', 'epic fantasy',
|
||||
'sword and sorcery', 'high fantasy', 'historical romance',
|
||||
'regency romance', 'western', 'sports', 'celebrity',
|
||||
'entertainment', 'pop culture', 'reality tv', 'social media',
|
||||
'true crime', 'celebrity biography', 'gossip', 'lifestyle',
|
||||
'fashion', 'beauty', 'cooking', 'travel', 'humor',
|
||||
'comedy', 'satire', 'graphic novel', 'manga', 'comic'
|
||||
];
|
||||
|
||||
const mainstreamBooks = books.filter(book => {
|
||||
if (!book.metadata?.categories) return false;
|
||||
return book.metadata.categories.some(cat =>
|
||||
mainstreamGenres.some(genre => cat.toLowerCase().includes(genre))
|
||||
);
|
||||
});
|
||||
|
||||
const popularRate = popularBooks.length / books.length;
|
||||
const mainstreamRate = mainstreamBooks.length / books.length;
|
||||
|
||||
return Math.min(100, (popularRate * 50) + (mainstreamRate * 50));
|
||||
}
|
||||
|
||||
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 < classicThreshold;
|
||||
});
|
||||
|
||||
const classicGenres = [
|
||||
'classic', 'literature', 'historical', 'vintage', 'traditional',
|
||||
'heritage', 'timeless', 'canonical', 'masterpiece', 'landmark',
|
||||
'seminal', 'influential', 'groundbreaking', 'pioneering',
|
||||
'classical literature', 'world literature', 'nobel prize',
|
||||
'pulitzer prize', 'booker prize', 'national book award',
|
||||
'literary fiction', 'modernist', 'post-modernist', 'realist',
|
||||
'naturalist', 'romantic', 'victorian', 'edwardian',
|
||||
'renaissance', 'enlightenment', 'ancient', 'medieval',
|
||||
'colonial', 'antebellum', 'gilded age', 'jazz age',
|
||||
'lost generation', 'beat generation', 'harlem renaissance',
|
||||
'golden age', 'silver age', 'folk tales', 'fairy tales',
|
||||
'mythology', 'legends', 'folklore', 'oral tradition',
|
||||
'epic poetry', 'sonnets', 'ballads', 'odes',
|
||||
'dramatic works', 'shakespearean', 'greek tragedy',
|
||||
'roman literature', 'biblical', 'religious classics',
|
||||
'philosophical classics', 'historical classics'
|
||||
];
|
||||
|
||||
const oldBookRate = oldBooks.length / books.length;
|
||||
const classicRate = classicGenres.length / books.length;
|
||||
|
||||
return Math.min(100, (oldBookRate * 60) + (classicRate * 40));
|
||||
}
|
||||
|
||||
private calculateAmbitiousScore(books: Book[]): number {
|
||||
const totalBooks = books.length;
|
||||
const volumeScore = Math.min(40, totalBooks * 2);
|
||||
|
||||
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;
|
||||
|
||||
const challengingScore = challengingRate * 35;
|
||||
const completionBonus = completionRate * 25;
|
||||
|
||||
return Math.min(100, volumeScore + challengingScore + completionBonus);
|
||||
}
|
||||
|
||||
private getDefaultProfile(): ReadingDNAProfile {
|
||||
return {
|
||||
adventurous: 50,
|
||||
perfectionist: 50,
|
||||
intellectual: 50,
|
||||
emotional: 50,
|
||||
patient: 50,
|
||||
social: 50,
|
||||
nostalgic: 50,
|
||||
ambitious: 50
|
||||
};
|
||||
}
|
||||
|
||||
private convertToPersonalityInsights(profile: ReadingDNAProfile): PersonalityInsight[] {
|
||||
return [
|
||||
{
|
||||
trait: 'Adventurous',
|
||||
score: profile.adventurous,
|
||||
description: 'You explore diverse genres and experimental content',
|
||||
color: '#e91e63'
|
||||
},
|
||||
{
|
||||
trait: 'Perfectionist',
|
||||
score: profile.perfectionist,
|
||||
description: 'You prefer high-quality books and finish what you start',
|
||||
color: '#2196f3'
|
||||
},
|
||||
{
|
||||
trait: 'Intellectual',
|
||||
score: profile.intellectual,
|
||||
description: 'You gravitate toward complex, educational material',
|
||||
color: '#00bcd4'
|
||||
},
|
||||
{
|
||||
trait: 'Emotional',
|
||||
score: profile.emotional,
|
||||
description: 'You connect emotionally with fiction and personal stories',
|
||||
color: '#ff9800'
|
||||
},
|
||||
{
|
||||
trait: 'Patient',
|
||||
score: profile.patient,
|
||||
description: 'You tackle long books and complete series',
|
||||
color: '#9c27b0'
|
||||
},
|
||||
{
|
||||
trait: 'Social',
|
||||
score: profile.social,
|
||||
description: 'You enjoy popular, widely-discussed books',
|
||||
color: '#3f51b5'
|
||||
},
|
||||
{
|
||||
trait: 'Nostalgic',
|
||||
score: profile.nostalgic,
|
||||
description: 'You appreciate classic literature and older works',
|
||||
color: '#673ab7'
|
||||
},
|
||||
{
|
||||
trait: 'Ambitious',
|
||||
score: profile.ambitious,
|
||||
description: 'You challenge yourself with volume and difficulty',
|
||||
color: '#009688'
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
<div class="reading-habits-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-line reading-habits-icon"></i>
|
||||
Reading Habits Analysis
|
||||
</h3>
|
||||
<p class="chart-description">Your behavioral reading patterns across 8 key dimensions</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
@if (habitInsights.length > 0) {
|
||||
<div class="habit-insights">
|
||||
<h4>Your Reading Habit Patterns</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>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
|
||||
+588
@@ -0,0 +1,588 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
|
||||
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],
|
||||
templateUrl: './reading-habits-chart.component.html',
|
||||
styleUrls: ['./reading-habits-chart.component.scss']
|
||||
})
|
||||
export class ReadingHabitsChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
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: function (label: string) {
|
||||
const icons: Record<string, string> = {
|
||||
'Consistency': '📅',
|
||||
'Multitasking': '📚',
|
||||
'Completionism': '✅',
|
||||
'Exploration': '🔍',
|
||||
'Organization': '📋',
|
||||
'Intensity': '⚡',
|
||||
'Methodology': '🎯',
|
||||
'Momentum': '🔥'
|
||||
};
|
||||
return [icons[label] || '', 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 `${label} Habit`;
|
||||
},
|
||||
label: (context) => {
|
||||
const score = context.parsed.r;
|
||||
const insight = this.habitInsights.find(i => i.habit === context.label);
|
||||
|
||||
return [
|
||||
`Score: ${score.toFixed(1)}/100`,
|
||||
'',
|
||||
insight ? insight.description : 'Your reading habit pattern'
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
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 chartDataSubject = new BehaviorSubject<ReadingHabitsChartData>({
|
||||
labels: [
|
||||
'Consistency', 'Multitasking', 'Completionism', 'Exploration',
|
||||
'Organization', 'Intensity', 'Methodology', 'Momentum'
|
||||
],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<ReadingHabitsChartData> = this.chartDataSubject.asObservable();
|
||||
public habitInsights: HabitInsight[] = [];
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
catchError((error) => {
|
||||
console.error('Error processing reading habits data:', error);
|
||||
return EMPTY;
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(() => {
|
||||
const profile = this.calculateReadingHabitsData();
|
||||
this.updateChartData(profile);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(profile: ReadingHabitsProfile | null): void {
|
||||
try {
|
||||
if (!profile) {
|
||||
this.chartDataSubject.next({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
this.habitInsights = [];
|
||||
return;
|
||||
}
|
||||
|
||||
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'
|
||||
];
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels: [
|
||||
'Consistency', 'Multitasking', 'Completionism', 'Exploration',
|
||||
'Organization', 'Intensity', 'Methodology', 'Momentum'
|
||||
],
|
||||
datasets: [{
|
||||
label: 'Reading Habits Profile',
|
||||
data,
|
||||
backgroundColor: 'rgba(156, 39, 176, 0.2)',
|
||||
borderColor: '#9c27b0',
|
||||
borderWidth: 3,
|
||||
pointBackgroundColor: habitColors,
|
||||
pointBorderColor: '#ffffff',
|
||||
pointBorderWidth: 3,
|
||||
pointRadius: 5,
|
||||
pointHoverRadius: 8,
|
||||
fill: true
|
||||
}]
|
||||
});
|
||||
|
||||
this.habitInsights = this.convertToHabitInsights(profile);
|
||||
} catch (error) {
|
||||
console.error('Error updating reading habits chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateReadingHabitsData(): ReadingHabitsProfile | null {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.analyzeReadingHabits(currentState.books!);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private analyzeReadingHabits(books: Book[]): ReadingHabitsProfile {
|
||||
if (books.length === 0) {
|
||||
return this.getDefaultProfile();
|
||||
}
|
||||
|
||||
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)
|
||||
};
|
||||
}
|
||||
|
||||
private calculateConsistencyScore(books: Book[]): number {
|
||||
const booksWithDates = books.filter(book => book.dateFinished || book.addedOn);
|
||||
if (booksWithDates.length === 0) return 30;
|
||||
|
||||
const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ && book.dateFinished);
|
||||
if (completedBooks.length < 2) return 25;
|
||||
|
||||
let consistencyScore = 50;
|
||||
|
||||
const inProgress = books.filter(book =>
|
||||
book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING
|
||||
);
|
||||
const progressRate = inProgress.length / books.length;
|
||||
consistencyScore += progressRate * 30;
|
||||
|
||||
const sortedByCompletion = completedBooks
|
||||
.sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime());
|
||||
|
||||
if (sortedByCompletion.length >= 3) {
|
||||
consistencyScore += 20;
|
||||
}
|
||||
|
||||
return Math.min(100, consistencyScore);
|
||||
}
|
||||
|
||||
private calculateMultitaskingScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const currentlyReading = books.filter(book => book.readStatus === ReadStatus.READING);
|
||||
const reReading = books.filter(book => book.readStatus === ReadStatus.RE_READING);
|
||||
const activeBooks = currentlyReading.length + reReading.length;
|
||||
|
||||
const booksWithProgress = books.filter(book => {
|
||||
const progress = Math.max(
|
||||
book.epubProgress?.percentage || 0,
|
||||
book.pdfProgress?.percentage || 0,
|
||||
book.cbxProgress?.percentage || 0,
|
||||
book.koreaderProgress?.percentage || 0,
|
||||
book.koboProgress?.percentage || 0
|
||||
);
|
||||
return progress > 0 && progress < 100;
|
||||
});
|
||||
|
||||
const multitaskingScore = Math.min(60, activeBooks * 15);
|
||||
const progressScore = Math.min(40, (booksWithProgress.length / books.length) * 80);
|
||||
|
||||
return Math.min(100, multitaskingScore + progressScore);
|
||||
}
|
||||
|
||||
private calculateCompletionismScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const completed = books.filter(book => book.readStatus === ReadStatus.READ);
|
||||
const abandoned = books.filter(book => book.readStatus === ReadStatus.ABANDONED);
|
||||
const unfinished = books.filter(book => book.readStatus === ReadStatus.UNREAD || book.readStatus === ReadStatus.UNSET);
|
||||
|
||||
const completionRate = completed.length / (books.length - unfinished.length);
|
||||
const abandonmentRate = abandoned.length / books.length;
|
||||
|
||||
const completionScore = completionRate * 70;
|
||||
const abandonmentPenalty = abandonmentRate * 30;
|
||||
|
||||
return Math.max(0, Math.min(100, completionScore - abandonmentPenalty + 30));
|
||||
}
|
||||
|
||||
private calculateExplorationScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const authors = new Set<string>();
|
||||
const authorCounts = new Map<string, number>();
|
||||
|
||||
books.forEach(book => {
|
||||
book.metadata?.authors?.forEach(author => {
|
||||
const authorName = author.toLowerCase();
|
||||
authors.add(authorName);
|
||||
authorCounts.set(authorName, (authorCounts.get(authorName) || 0) + 1);
|
||||
});
|
||||
});
|
||||
|
||||
const authorDiversityScore = Math.min(50, authors.size * 2);
|
||||
const maxBooksPerAuthor = Math.max(...Array.from(authorCounts.values()));
|
||||
const concentrationPenalty = Math.max(0, (maxBooksPerAuthor - 3) * 5);
|
||||
|
||||
const years = new Set<number>();
|
||||
books.forEach(book => {
|
||||
if (book.metadata?.publishedDate) {
|
||||
years.add(new Date(book.metadata.publishedDate).getFullYear());
|
||||
}
|
||||
});
|
||||
const temporalScore = Math.min(30, years.size * 2);
|
||||
|
||||
const languages = new Set<string>();
|
||||
books.forEach(book => {
|
||||
if (book.metadata?.language) languages.add(book.metadata.language);
|
||||
});
|
||||
const languageScore = Math.min(20, (languages.size - 1) * 10);
|
||||
|
||||
return Math.max(10, Math.min(100, authorDiversityScore + temporalScore + languageScore - concentrationPenalty));
|
||||
}
|
||||
|
||||
private calculateOrganizationScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const seriesBooks = books.filter(book => book.metadata?.seriesName && book.metadata?.seriesNumber);
|
||||
const seriesScore = (seriesBooks.length / books.length) * 40;
|
||||
|
||||
const wellOrganizedBooks = books.filter(book => {
|
||||
const metadata = book.metadata;
|
||||
if (!metadata) return false;
|
||||
|
||||
const hasBasicInfo = metadata.title && metadata.authors && metadata.authors.length > 0;
|
||||
const hasDetailedInfo = metadata.publishedDate || metadata.publisher || metadata.isbn10;
|
||||
const hasCategories = metadata.categories && metadata.categories.length > 0;
|
||||
|
||||
return hasBasicInfo && (hasDetailedInfo || hasCategories);
|
||||
});
|
||||
|
||||
const metadataScore = (wellOrganizedBooks.length / books.length) * 35;
|
||||
|
||||
const ratedBooks = books.filter(book => book.personalRating);
|
||||
const ratingScore = (ratedBooks.length / books.length) * 25;
|
||||
|
||||
return Math.min(100, seriesScore + metadataScore + ratingScore);
|
||||
}
|
||||
|
||||
private calculateIntensityScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const booksWithPages = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 0);
|
||||
if (booksWithPages.length === 0) return 40;
|
||||
|
||||
const averagePages = booksWithPages.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0) / booksWithPages.length;
|
||||
const intensityFromLength = Math.min(50, averagePages / 8);
|
||||
|
||||
const highProgressBooks = books.filter(book => {
|
||||
const progress = Math.max(
|
||||
book.epubProgress?.percentage || 0,
|
||||
book.pdfProgress?.percentage || 0,
|
||||
book.cbxProgress?.percentage || 0,
|
||||
book.koreaderProgress?.percentage || 0
|
||||
);
|
||||
return progress > 75;
|
||||
});
|
||||
|
||||
const progressScore = (highProgressBooks.length / books.length) * 30;
|
||||
|
||||
const completedSeriesBooks = books.filter(book =>
|
||||
book.metadata?.seriesName && book.readStatus === ReadStatus.READ
|
||||
);
|
||||
const seriesIntensityScore = (completedSeriesBooks.length / books.length) * 20;
|
||||
|
||||
return Math.min(100, intensityFromLength + progressScore + seriesIntensityScore);
|
||||
}
|
||||
|
||||
private calculateMethodologyScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const seriesBooks = books.filter(book => book.metadata?.seriesName);
|
||||
const seriesGroups = new Map<string, Book[]>();
|
||||
|
||||
seriesBooks.forEach(book => {
|
||||
const seriesName = book.metadata!.seriesName!.toLowerCase();
|
||||
if (!seriesGroups.has(seriesName)) {
|
||||
seriesGroups.set(seriesName, []);
|
||||
}
|
||||
seriesGroups.get(seriesName)!.push(book);
|
||||
});
|
||||
|
||||
let systematicSeriesScore = 0;
|
||||
seriesGroups.forEach(books => {
|
||||
if (books.length > 1) {
|
||||
const orderedBooks = books.filter(book => book.metadata?.seriesNumber).sort((a, b) =>
|
||||
(a.metadata?.seriesNumber || 0) - (b.metadata?.seriesNumber || 0)
|
||||
);
|
||||
if (orderedBooks.length >= 2) {
|
||||
systematicSeriesScore += 20;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const authorBooks = new Map<string, Book[]>();
|
||||
books.forEach(book => {
|
||||
book.metadata?.authors?.forEach(author => {
|
||||
const authorName = author.toLowerCase();
|
||||
if (!authorBooks.has(authorName)) {
|
||||
authorBooks.set(authorName, []);
|
||||
}
|
||||
authorBooks.get(authorName)!.push(book);
|
||||
});
|
||||
});
|
||||
|
||||
const systematicAuthors = Array.from(authorBooks.values()).filter(books => books.length >= 2).length;
|
||||
const authorMethodologyScore = Math.min(30, systematicAuthors * 5);
|
||||
|
||||
const categoryBooks = new Map<string, number>();
|
||||
books.forEach(book => {
|
||||
book.metadata?.categories?.forEach(category => {
|
||||
const cat = category.toLowerCase();
|
||||
categoryBooks.set(cat, (categoryBooks.get(cat) || 0) + 1);
|
||||
});
|
||||
});
|
||||
|
||||
const majorCategories = Array.from(categoryBooks.values()).filter(count => count >= 3).length;
|
||||
const categoryMethodologyScore = Math.min(25, majorCategories * 8);
|
||||
|
||||
const baseMethodologyScore = books.length >= 10 ? 15 : Math.max(5, books.length);
|
||||
|
||||
return Math.min(100, systematicSeriesScore + authorMethodologyScore + categoryMethodologyScore + baseMethodologyScore);
|
||||
}
|
||||
|
||||
private calculateMomentumScore(books: Book[]): number {
|
||||
// ...existing code from service...
|
||||
const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ && book.dateFinished);
|
||||
|
||||
if (completedBooks.length === 0) {
|
||||
const activeBooks = books.filter(book =>
|
||||
book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING
|
||||
);
|
||||
return Math.min(40, activeBooks.length * 10);
|
||||
}
|
||||
|
||||
const sortedBooks = completedBooks.sort((a, b) =>
|
||||
new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime()
|
||||
);
|
||||
|
||||
let momentumScore = 20;
|
||||
|
||||
const sixMonthsAgo = new Date();
|
||||
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
|
||||
|
||||
const recentCompletions = sortedBooks.filter(book =>
|
||||
new Date(book.dateFinished!) > sixMonthsAgo
|
||||
);
|
||||
|
||||
momentumScore += Math.min(40, recentCompletions.length * 5);
|
||||
|
||||
const currentlyReading = books.filter(book =>
|
||||
book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING
|
||||
);
|
||||
|
||||
momentumScore += Math.min(25, currentlyReading.length * 8);
|
||||
|
||||
const highProgressBooks = books.filter(book => {
|
||||
const progress = Math.max(
|
||||
book.epubProgress?.percentage || 0,
|
||||
book.pdfProgress?.percentage || 0,
|
||||
book.cbxProgress?.percentage || 0,
|
||||
book.koreaderProgress?.percentage || 0
|
||||
);
|
||||
return progress > 50 && progress < 100;
|
||||
});
|
||||
|
||||
momentumScore += Math.min(15, highProgressBooks.length * 3);
|
||||
|
||||
return Math.min(100, momentumScore);
|
||||
}
|
||||
|
||||
private getDefaultProfile(): ReadingHabitsProfile {
|
||||
return {
|
||||
consistency: 40,
|
||||
multitasking: 30,
|
||||
completionism: 50,
|
||||
exploration: 45,
|
||||
organization: 35,
|
||||
intensity: 40,
|
||||
methodology: 35,
|
||||
momentum: 30
|
||||
};
|
||||
}
|
||||
|
||||
private convertToHabitInsights(profile: ReadingHabitsProfile): HabitInsight[] {
|
||||
return [
|
||||
{
|
||||
habit: 'Consistency',
|
||||
score: profile.consistency,
|
||||
description: 'You maintain regular reading patterns and schedules',
|
||||
color: '#9c27b0'
|
||||
},
|
||||
{
|
||||
habit: 'Multitasking',
|
||||
score: profile.multitasking,
|
||||
description: 'You juggle multiple books simultaneously',
|
||||
color: '#e91e63'
|
||||
},
|
||||
{
|
||||
habit: 'Completionism',
|
||||
score: profile.completionism,
|
||||
description: 'You finish books rather than abandon them',
|
||||
color: '#ff5722'
|
||||
},
|
||||
{
|
||||
habit: 'Exploration',
|
||||
score: profile.exploration,
|
||||
description: 'You actively seek out new authors and genres',
|
||||
color: '#ff9800'
|
||||
},
|
||||
{
|
||||
habit: 'Organization',
|
||||
score: profile.organization,
|
||||
description: 'You maintain systematic book tracking and metadata',
|
||||
color: '#ffc107'
|
||||
},
|
||||
{
|
||||
habit: 'Intensity',
|
||||
score: profile.intensity,
|
||||
description: 'You prefer longer, immersive reading sessions',
|
||||
color: '#4caf50'
|
||||
},
|
||||
{
|
||||
habit: 'Methodology',
|
||||
score: profile.methodology,
|
||||
description: 'You follow systematic approaches to book selection',
|
||||
color: '#2196f3'
|
||||
},
|
||||
{
|
||||
habit: 'Momentum',
|
||||
score: profile.momentum,
|
||||
description: 'You maintain active reading streaks and continuity',
|
||||
color: '#673ab7'
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<div class="reading-heatmap-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar reading-heatmap-icon"></i>
|
||||
Reading Activity Heatmap
|
||||
</h3>
|
||||
<p class="chart-description">Monthly reading activity over the past 10 years</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
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],
|
||||
templateUrl: './reading-heatmap-chart.component.html',
|
||||
styleUrls: ['./reading-heatmap-chart.component.scss']
|
||||
})
|
||||
export class ReadingHeatmapChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
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;
|
||||
return `${point.v} book${point.v === 1 ? '' : 's'} read`;
|
||||
}
|
||||
}
|
||||
},
|
||||
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: 'Books Read',
|
||||
data: []
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<HeatmapChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
catchError((error) => {
|
||||
console.error('Error processing reading heatmap data:', error);
|
||||
return EMPTY;
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateHeatmapData();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
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: 'Books Read',
|
||||
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(): YearMonthData[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processHeatmapData(currentState.books!);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private 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);
|
||||
}
|
||||
}
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<div class="reading-progress-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-chart-bar reading-progress-icon"></i>
|
||||
Reading Progress Distribution
|
||||
</h3>
|
||||
<p class="chart-description">Books by reading completion status</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<canvas baseChart
|
||||
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="chartOptions"
|
||||
[type]="chartType">
|
||||
</canvas>
|
||||
</div>
|
||||
</div>
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
|
||||
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],
|
||||
templateUrl: './reading-progress-chart.component.html',
|
||||
styleUrls: ['./reading-progress-chart.component.scss']
|
||||
})
|
||||
export class ReadingProgressChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
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 description = rangeInfo ? ` (${rangeInfo.desc})` : '';
|
||||
return `${value} book${value === 1 ? '' : 's'}${description} - ${percentage}%`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {display: false}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<ProgressChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books by Progress',
|
||||
data: [],
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<ProgressChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
catchError((error) => {
|
||||
console.error('Error processing reading progress data:', error);
|
||||
return EMPTY;
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateReadingProgressStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: ReadingProgressStats[]): void {
|
||||
try {
|
||||
const labels = stats.map(s => s.progressRange);
|
||||
const dataValues = stats.map(s => s.count);
|
||||
|
||||
this.chartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'Books by Progress',
|
||||
data: dataValues,
|
||||
backgroundColor: [...CHART_COLORS],
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 2,
|
||||
hoverBorderWidth: 3,
|
||||
hoverBorderColor: '#ffffff'
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating reading progress chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateReadingProgressStats(): ReadingProgressStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.processReadingProgressStats(currentState.books!);
|
||||
}
|
||||
|
||||
private isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as { loaded: boolean }).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as { books: unknown }).books) &&
|
||||
(state as { books: Book[] }).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private 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;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
<div class="reading-session-heatmap-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-calendar heatmap-title-icon"></i>
|
||||
Reading Session Activity
|
||||
</h3>
|
||||
<p class="chart-description">Daily overview of your reading sessions across the year</p>
|
||||
</div>
|
||||
<div class="year-selector">
|
||||
<button type="button"
|
||||
class="year-nav-btn"
|
||||
(click)="changeYear(-1)"
|
||||
title="Previous year">
|
||||
<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="Next year">
|
||||
<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>
|
||||
</div>
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
.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;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
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';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
type SessionHeatmapChartData = ChartData<'matrix', MatrixDataPoint[], string>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-session-heatmap',
|
||||
standalone: true,
|
||||
imports: [CommonModule, BaseChartDirective],
|
||||
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'];
|
||||
|
||||
private readonly userStatsService = inject(UserStatsService);
|
||||
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} reading session${point.v === 1 ? '' : 's'}`;
|
||||
}
|
||||
}
|
||||
},
|
||||
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);
|
||||
}
|
||||
|
||||
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 dateStr = currentDate.toISOString().split('T')[0];
|
||||
|
||||
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 getDateFromWeek(year: number, week: number): Date {
|
||||
const date = new Date(year, 0, 1);
|
||||
date.setDate(date.getDate() + (week * 7) - date.getDay());
|
||||
return date;
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
<div class="timeline-container">
|
||||
<div class="timeline-header">
|
||||
<div class="header-title">
|
||||
<h3>
|
||||
<i class="pi pi-clock timeline-title-icon"></i>
|
||||
Reading Session Timeline
|
||||
</h3>
|
||||
<p class="timeline-subtitle">Weekly overview of your reading sessions and patterns</p>
|
||||
</div>
|
||||
<div class="week-info">
|
||||
<button type="button"
|
||||
class="week-nav-btn"
|
||||
(click)="changeWeek(-1)"
|
||||
title="Previous week">
|
||||
<i class="pi pi-chevron-left"></i>
|
||||
</button>
|
||||
<div class="week-display">
|
||||
<span class="week-label">Week {{ currentWeek }}</span>
|
||||
<span class="week-dates">{{ getWeekDateRange() }}</span>
|
||||
</div>
|
||||
<button type="button"
|
||||
class="week-nav-btn"
|
||||
(click)="changeWeek(1)"
|
||||
title="Next week">
|
||||
<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="Select Year"
|
||||
[style]="{'min-width': '120px'}">
|
||||
</p-select>
|
||||
<p-select
|
||||
[options]="weekOptions"
|
||||
[(ngModel)]="currentWeek"
|
||||
(onChange)="onWeekChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Select Week"
|
||||
[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]="getTooltipContent(session)"
|
||||
[escape]="false"
|
||||
tooltipPosition="top"
|
||||
[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>
|
||||
+636
@@ -0,0 +1,636 @@
|
||||
.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);
|
||||
}
|
||||
}
|
||||
|
||||
&: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 .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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
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';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
interface DayTimeline {
|
||||
day: string;
|
||||
dayOfWeek: number;
|
||||
sessions: TimelineSession[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-reading-session-timeline',
|
||||
standalone: true,
|
||||
imports: [CommonModule, Select, FormsModule, Tooltip],
|
||||
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);
|
||||
|
||||
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: `Week ${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 duration = item.totalDurationSeconds / 60;
|
||||
const endTime = new Date(startTime.getTime() + item.totalDurationSeconds * 1000);
|
||||
|
||||
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 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) {
|
||||
tracks.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;
|
||||
}
|
||||
|
||||
return {
|
||||
startHour,
|
||||
startMinute,
|
||||
endHour,
|
||||
endMinute,
|
||||
duration: session.duration,
|
||||
left,
|
||||
width,
|
||||
bookTitle: session.bookTitle,
|
||||
bookId: session.bookId,
|
||||
bookType: session.bookType,
|
||||
level,
|
||||
totalLevels
|
||||
};
|
||||
}
|
||||
|
||||
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.getThumbnailUrl1(bookId);
|
||||
}
|
||||
|
||||
public getTooltipContent(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 || 'Reading Session'}</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">Time:</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">Duration:</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">Format:</span>
|
||||
<span class="session-tooltip-value">${session.bookType || 'Unknown'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
<div class="series-progress-container">
|
||||
<div class="chart-header">
|
||||
<div class="chart-title">
|
||||
<h3>
|
||||
<i class="pi pi-list series-icon"></i>
|
||||
Series Progress Tracker
|
||||
</h3>
|
||||
<p class="chart-description">Track your reading progress across book series</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">Series</span>
|
||||
</div>
|
||||
<div class="stat-pill">
|
||||
<span class="pill-value">{{ stats.avgSeriesCompletion }}%</span>
|
||||
<span class="pill-label">Avg. Completion</span>
|
||||
</div>
|
||||
@if (stats.highestRatedSeries) {
|
||||
<div class="stat-pill highlight">
|
||||
<span class="pill-value">{{ stats.highestRatedSeries.avgPersonalRating?.toFixed(1) }}</span>
|
||||
<span class="pill-label">Top Rated</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>Series Breakdown</h4>
|
||||
<span class="series-count">{{ filteredSeriesList.length }} of {{ seriesList.length }}</span>
|
||||
</div>
|
||||
|
||||
<div class="controls-row">
|
||||
<div class="search-box">
|
||||
<i class="pi pi-search"></i>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search series..."
|
||||
[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">All Status</option>
|
||||
<option value="in-progress">In Progress</option>
|
||||
<option value="completed">Completed</option>
|
||||
<option value="not-started">Not Started</option>
|
||||
</select>
|
||||
|
||||
<select class="sort-select" [value]="sortBy" (change)="onSortChange($any($event.target).value)">
|
||||
<option value="progress">Sort by Progress</option>
|
||||
<option value="rating">Sort by Rating</option>
|
||||
<option value="books">Sort by Books</option>
|
||||
<option value="name">Sort by Name</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">
|
||||
{{ series.booksRead }}/{{ series.booksOwned }} read
|
||||
@if (series.totalInSeries) {
|
||||
<span class="total-hint">({{ series.totalInSeries }} in series)</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">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>No series matching "{{ 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">
|
||||
Page {{ currentPage + 1 }} of {{ 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>No series found in your library.</p>
|
||||
<small>Books need series metadata to appear here.</small>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+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: 220px;
|
||||
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.5rem;
|
||||
max-height: 400px;
|
||||
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.65rem 0.85rem;
|
||||
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.6rem;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
.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.5rem;
|
||||
padding-top: 0.4rem;
|
||||
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: 180px;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+645
@@ -0,0 +1,645 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {catchError, filter, first, switchMap, takeUntil} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
import {BookService} from '../../../../../book/service/book.service';
|
||||
import {BookState} from '../../../../../book/model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../../../book/model/book.model';
|
||||
import {LibraryFilterService} from '../../../library-stats/service/library-filter.service';
|
||||
|
||||
interface SeriesInfo {
|
||||
name: string;
|
||||
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],
|
||||
templateUrl: './series-progress-chart.component.html',
|
||||
styleUrls: ['./series-progress-chart.component.scss']
|
||||
})
|
||||
export class SeriesProgressChartComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly chartType = 'bar' as const;
|
||||
public 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: 'Completion %',
|
||||
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 = [
|
||||
`Read: ${series.booksRead}/${series.booksOwned} owned`
|
||||
];
|
||||
if (series.totalInSeries) {
|
||||
lines.push(`Series total: ${series.totalInSeries} books`);
|
||||
}
|
||||
if (series.avgPersonalRating) {
|
||||
lines.push(`Your rating: ${series.avgPersonalRating.toFixed(1)}/10`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly chartDataSubject = new BehaviorSubject<SeriesChartData>({
|
||||
labels: [],
|
||||
datasets: []
|
||||
});
|
||||
|
||||
public readonly chartData$: Observable<SeriesChartData> = this.chartDataSubject.asObservable();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing series data:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.calculateAndUpdateChart();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
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(): void {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
this.chartDataSubject.next({labels: [], datasets: []});
|
||||
this.seriesList = [];
|
||||
this.displayedSeries = [];
|
||||
this.stats = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.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 isValidBookState(state: unknown): state is BookState {
|
||||
return (
|
||||
typeof state === 'object' &&
|
||||
state !== null &&
|
||||
'loaded' in state &&
|
||||
typeof (state as {loaded: boolean}).loaded === 'boolean' &&
|
||||
'books' in state &&
|
||||
Array.isArray((state as {books: unknown}).books) &&
|
||||
(state as {books: Book[]}).books.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private 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: 'Read',
|
||||
data: readPercentages,
|
||||
backgroundColor: 'rgba(76, 175, 80, 0.85)',
|
||||
borderColor: '#4caf50',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: 'Reading',
|
||||
data: readingPercentages,
|
||||
backgroundColor: 'rgba(255, 193, 7, 0.85)',
|
||||
borderColor: '#ffc107',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: 'Partially Read',
|
||||
data: partiallyReadPercentages,
|
||||
backgroundColor: 'rgba(255, 152, 0, 0.85)',
|
||||
borderColor: '#ff9800',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: 'Paused',
|
||||
data: pausedPercentages,
|
||||
backgroundColor: 'rgba(33, 150, 243, 0.85)',
|
||||
borderColor: '#2196f3',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: 'Abandoned',
|
||||
data: abandonedPercentages,
|
||||
backgroundColor: 'rgba(239, 83, 80, 0.85)',
|
||||
borderColor: '#ef5350',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: 'Won\'t Read',
|
||||
data: wontReadPercentages,
|
||||
backgroundColor: 'rgba(158, 158, 158, 0.6)',
|
||||
borderColor: '#9e9e9e',
|
||||
borderWidth: 1,
|
||||
borderRadius: 2
|
||||
},
|
||||
{
|
||||
label: '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';
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {ReadingSessionHeatmapComponent} from '../charts/reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {FavoriteDaysChartComponent} from '../charts/favorite-days-chart/favorite-days-chart.component';
|
||||
import {PeakHoursChartComponent} from '../charts/peak-hours-chart/peak-hours-chart.component';
|
||||
import {ReadingSessionTimelineComponent} from '../charts/reading-session-timeline/reading-session-timeline.component';
|
||||
import {ReadingHeatmapChartComponent} from '../charts/reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {PersonalRatingChartComponent} from '../charts/personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingProgressChartComponent} from '../charts/reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from '../charts/read-status-chart/read-status-chart.component';
|
||||
import {GenreStatsChartComponent} from '../charts/genre-stats-chart/genre-stats-chart.component';
|
||||
import {CompletionTimelineChartComponent} from '../charts/completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {RatingTasteChartComponent} from '../charts/rating-taste-chart/rating-taste-chart.component';
|
||||
import {SeriesProgressChartComponent} from '../charts/series-progress-chart/series-progress-chart.component';
|
||||
import {ReadingDNAChartComponent} from '../charts/reading-dna-chart/reading-dna-chart.component';
|
||||
import {ReadingHabitsChartComponent} from '../charts/reading-habits-chart/reading-habits-chart.component';
|
||||
import {ReadingBacklogChartComponent} from '../charts/reading-backlog-chart/reading-backlog-chart.component';
|
||||
|
||||
export interface UserChartConfig {
|
||||
id: string;
|
||||
title: string;
|
||||
component: unknown;
|
||||
enabled: boolean;
|
||||
sizeClass: string;
|
||||
order: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class UserChartConfigService {
|
||||
private readonly STORAGE_KEY = 'userStatsChartConfig';
|
||||
|
||||
private readonly defaultCharts: UserChartConfig[] = [
|
||||
{id: 'heatmap', title: 'Reading Session Heatmap', component: ReadingSessionHeatmapComponent, enabled: true, sizeClass: 'chart-full', order: 0},
|
||||
{id: 'favorite-days', title: 'Favorite Reading Days', component: FavoriteDaysChartComponent, enabled: true, sizeClass: 'chart-medium', order: 1},
|
||||
{id: 'peak-hours', title: 'Peak Reading Hours', component: PeakHoursChartComponent, enabled: true, sizeClass: 'chart-medium', order: 2},
|
||||
{id: 'timeline', title: 'Reading Session Timeline', component: ReadingSessionTimelineComponent, enabled: true, sizeClass: 'chart-full', order: 3},
|
||||
{id: 'reading-heatmap', title: 'Reading Activity Heatmap', component: ReadingHeatmapChartComponent, enabled: true, sizeClass: 'chart-small-square', order: 4},
|
||||
{id: 'personal-rating', title: 'Personal Rating Distribution', component: PersonalRatingChartComponent, enabled: true, sizeClass: 'chart-small-square', order: 5},
|
||||
{id: 'reading-progress', title: 'Reading Progress Distribution', component: ReadingProgressChartComponent, enabled: true, sizeClass: 'chart-small-square', order: 6},
|
||||
{id: 'read-status', title: 'Reading Status Distribution', component: ReadStatusChartComponent, enabled: true, sizeClass: 'chart-small-square', order: 7},
|
||||
{id: 'genre-stats', title: 'Genre Statistics', component: GenreStatsChartComponent, enabled: true, sizeClass: 'chart-medium', order: 8},
|
||||
{id: 'completion-timeline', title: 'Completion Timeline', component: CompletionTimelineChartComponent, enabled: true, sizeClass: 'chart-medium', order: 9},
|
||||
{id: 'rating-taste', title: 'Rating Taste Comparison', component: RatingTasteChartComponent, enabled: true, sizeClass: 'chart-medium', order: 10},
|
||||
{id: 'series-progress', title: 'Series Progress Tracker', component: SeriesProgressChartComponent, enabled: true, sizeClass: 'chart-medium', order: 11},
|
||||
{id: 'reading-dna', title: 'Reading DNA Profile', component: ReadingDNAChartComponent, enabled: true, sizeClass: 'chart-medium', order: 12},
|
||||
{id: 'reading-habits', title: 'Reading Habits Analysis', component: ReadingHabitsChartComponent, enabled: true, sizeClass: 'chart-medium', order: 13},
|
||||
{id: 'reading-backlog', title: 'Reading Backlog Analysis', component: ReadingBacklogChartComponent, enabled: true, sizeClass: 'chart-full', order: 14},
|
||||
];
|
||||
|
||||
private chartsSubject = new BehaviorSubject<UserChartConfig[]>(this.loadChartConfig());
|
||||
public charts$: Observable<UserChartConfig[]> = this.chartsSubject.asObservable();
|
||||
|
||||
getVisibleCharts(): UserChartConfig[] {
|
||||
return this.chartsSubject.value.filter(chart => chart.enabled);
|
||||
}
|
||||
|
||||
toggleChart(chartId: string): void {
|
||||
const charts = this.chartsSubject.value;
|
||||
const chart = charts.find(c => c.id === chartId);
|
||||
if (chart) {
|
||||
chart.enabled = !chart.enabled;
|
||||
this.saveChartConfig(charts);
|
||||
this.chartsSubject.next([...charts]);
|
||||
}
|
||||
}
|
||||
|
||||
reorderCharts(previousIndex: number, currentIndex: number): void {
|
||||
const charts = [...this.chartsSubject.value];
|
||||
const [movedChart] = charts.splice(previousIndex, 1);
|
||||
charts.splice(currentIndex, 0, movedChart);
|
||||
|
||||
charts.forEach((chart, index) => {
|
||||
chart.order = index;
|
||||
});
|
||||
|
||||
this.saveChartConfig(charts);
|
||||
this.chartsSubject.next(charts);
|
||||
}
|
||||
|
||||
resetLayout(): void {
|
||||
const resetCharts = JSON.parse(JSON.stringify(this.defaultCharts));
|
||||
this.saveChartConfig(resetCharts);
|
||||
this.chartsSubject.next(resetCharts);
|
||||
}
|
||||
|
||||
private saveChartConfig(charts: UserChartConfig[]): void {
|
||||
const config = charts.map(chart => ({
|
||||
id: chart.id,
|
||||
enabled: chart.enabled,
|
||||
sizeClass: chart.sizeClass,
|
||||
order: chart.order
|
||||
}));
|
||||
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(config));
|
||||
}
|
||||
|
||||
private loadChartConfig(): UserChartConfig[] {
|
||||
const savedConfig = localStorage.getItem(this.STORAGE_KEY);
|
||||
if (!savedConfig) {
|
||||
return JSON.parse(JSON.stringify(this.defaultCharts));
|
||||
}
|
||||
|
||||
try {
|
||||
const config = JSON.parse(savedConfig);
|
||||
const charts = JSON.parse(JSON.stringify(this.defaultCharts));
|
||||
|
||||
config.forEach((saved: Partial<UserChartConfig>) => {
|
||||
const chart = charts.find((c: UserChartConfig) => c.id === saved.id);
|
||||
if (chart) {
|
||||
chart.enabled = saved.enabled;
|
||||
chart.sizeClass = saved.sizeClass;
|
||||
chart.order = saved.order ?? chart.order;
|
||||
}
|
||||
});
|
||||
|
||||
charts.sort((a: UserChartConfig, b: UserChartConfig) => a.order - b.order);
|
||||
|
||||
return charts;
|
||||
} catch (e) {
|
||||
console.error('Failed to load chart config', e);
|
||||
return JSON.parse(JSON.stringify(this.defaultCharts));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,24 +4,24 @@ import {Subject} from 'rxjs';
|
||||
import {CdkDragDrop, DragDropModule} from '@angular/cdk/drag-drop';
|
||||
import {DialogModule} from 'primeng/dialog';
|
||||
import {ButtonModule} from 'primeng/button';
|
||||
import {ReadingSessionHeatmapComponent} from '../reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {ReadingSessionTimelineComponent} from '../reading-session-timeline/reading-session-timeline.component';
|
||||
import {GenreStatsChartComponent} from '../genre-stats-chart/genre-stats-chart.component';
|
||||
import {CompletionTimelineChartComponent} from '../completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {takeUntil} from 'rxjs/operators';
|
||||
import {FavoriteDaysChartComponent} from '../favorite-days-chart/favorite-days-chart.component';
|
||||
import {PeakHoursChartComponent} from '../peak-hours-chart/peak-hours-chart.component';
|
||||
import {ReadingDNAChartComponent} from '../reading-dna-chart/reading-dna-chart.component';
|
||||
import {ReadingHabitsChartComponent} from '../reading-habits-chart/reading-habits-chart.component';
|
||||
import {UserChartConfig, UserChartConfigService} from '../../service/user-chart-config.service';
|
||||
import {ReadingHeatmapChartComponent} from '../reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {PersonalRatingChartComponent} from '../personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingProgressChartComponent} from '../reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from '../read-status-chart/read-status-chart.component';
|
||||
import {RatingTasteChartComponent} from '../rating-taste-chart/rating-taste-chart.component';
|
||||
import {ReadingBacklogChartComponent} from '../reading-backlog-chart/reading-backlog-chart.component';
|
||||
import {SeriesProgressChartComponent} from '../series-progress-chart/series-progress-chart.component';
|
||||
import {PeakHoursChartComponent} from './charts/peak-hours-chart/peak-hours-chart.component';
|
||||
import {FavoriteDaysChartComponent} from './charts/favorite-days-chart/favorite-days-chart.component';
|
||||
import {ReadingDNAChartComponent} from './charts/reading-dna-chart/reading-dna-chart.component';
|
||||
import {CompletionTimelineChartComponent} from './charts/completion-timeline-chart/completion-timeline-chart.component';
|
||||
import {ReadingHabitsChartComponent} from './charts/reading-habits-chart/reading-habits-chart.component';
|
||||
import {GenreStatsChartComponent} from './charts/genre-stats-chart/genre-stats-chart.component';
|
||||
import {ReadingHeatmapChartComponent} from './charts/reading-heatmap-chart/reading-heatmap-chart.component';
|
||||
import {ReadingSessionTimelineComponent} from './charts/reading-session-timeline/reading-session-timeline.component';
|
||||
import {PersonalRatingChartComponent} from './charts/personal-rating-chart/personal-rating-chart.component';
|
||||
import {ReadingSessionHeatmapComponent} from './charts/reading-session-heatmap/reading-session-heatmap.component';
|
||||
import {ReadingProgressChartComponent} from './charts/reading-progress-chart/reading-progress-chart.component';
|
||||
import {ReadStatusChartComponent} from './charts/read-status-chart/read-status-chart.component';
|
||||
import {RatingTasteChartComponent} from './charts/rating-taste-chart/rating-taste-chart.component';
|
||||
import {SeriesProgressChartComponent} from './charts/series-progress-chart/series-progress-chart.component';
|
||||
import {ReadingBacklogChartComponent} from './charts/reading-backlog-chart/reading-backlog-chart.component';
|
||||
import {UserChartConfig, UserChartConfigService} from './service/user-chart-config.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-stats',
|
||||
|
||||
Reference in New Issue
Block a user