Some chart shuffles

This commit is contained in:
acx10
2025-12-27 11:53:53 -07:00
parent 3fc4d08def
commit 81757317e5
27 changed files with 919 additions and 339 deletions
@@ -45,7 +45,7 @@
.chart-wrapper {
position: relative;
height: 350px;
height: 300px;
width: 100%;
}
@@ -37,7 +37,7 @@
.chart-wrapper {
position: relative;
height: 350px;
height: 300px;
width: 100%;
}
@@ -37,7 +37,7 @@ export class GenreStatsChartComponent implements OnInit, OnDestroy {
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {top: 10, bottom: 10, left: 10, right: 10}
padding: {top: 10}
},
plugins: {
legend: {display: false},
@@ -45,7 +45,7 @@
.chart-wrapper {
position: relative;
height: 350px;
height: 300px;
width: 100%;
}
@@ -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>
@@ -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;
}
}
@@ -0,0 +1,248 @@
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 {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: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.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
};
});
}
}
@@ -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>
@@ -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;
}
}
@@ -0,0 +1,249 @@
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 {Book, ReadStatus} from '../../../book/model/book.model';
interface ReadingStatusStats {
status: string;
count: number;
percentage: number;
}
const CHART_COLORS = [
'#28a745', '#17a2b8', '#ffc107', '#6f42c1',
'#fd7e14', '#6c757d', '#dc3545', '#343a40', '#e9ecef'
] 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: [...CHART_COLORS],
...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 = this.getColorsForData(stats.length);
this.chartDataSubject.next({
labels,
datasets: [{
data: dataValues,
backgroundColor: colors,
...CHART_DEFAULTS
}]
});
} catch (error) {
console.error('Error updating chart data:', error);
}
}
private getColorsForData(dataLength: number): string[] {
const colors = [...CHART_COLORS];
while (colors.length < dataLength) {
colors.push(...CHART_COLORS);
}
return colors.slice(0, dataLength);
}
private calculateReadingStatusStats(): ReadingStatusStats[] {
const currentState = this.bookService.getCurrentBookState();
if (!this.isValidBookState(currentState)) {
return [];
}
return this.processReadingStatusStats(currentState.books!);
}
private isValidBookState(state: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.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: any) {
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: string, index: number) => {
const isVisible = typeof chart.getDataVisibility === 'function'
? chart.getDataVisibility(index)
: !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false);
return {
text: `${label} (${dataValues[index]})`,
fillStyle: (dataset.backgroundColor as string[])[index],
strokeStyle: '#ffffff',
lineWidth: 1,
hidden: !isVisible,
index,
fontColor: '#ffffff'
};
});
}
private formatTooltipLabel(context: 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}%)`;
}
}
@@ -43,6 +43,9 @@ export class ReadingDNAChartComponent implements OnInit, OnDestroy {
public readonly chartOptions: ChartConfiguration<'radar'>['options'] = {
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {top: 15}
},
scales: {
r: {
beginAtZero: true,
@@ -43,6 +43,9 @@ export class ReadingHabitsChartComponent implements OnInit, OnDestroy {
public readonly chartOptions: ChartConfiguration<'radar'>['options'] = {
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {top: 15}
},
scales: {
r: {
beginAtZero: true,
@@ -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>
@@ -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;
}
}
@@ -0,0 +1,239 @@
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 {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: 30
}
},
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',
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 currentMonth = new Date().getMonth();
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) => {
const maxMonth = year === currentYear ? currentMonth : 11;
for (let month = 0; month <= maxMonth; 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 - 0.5;
}
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: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.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);
}
}
@@ -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>
@@ -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;
}
}
@@ -0,0 +1,227 @@
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 {Book} from '../../../book/model/book.model';
interface ReadingProgressStats {
progressRange: string;
count: number;
description: string;
}
const CHART_COLORS = [
'#6c757d', '#ffc107', '#fd7e14', '#17a2b8', '#6f42c1', '#28a745'
] 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: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.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;
}
}
@@ -6,7 +6,7 @@
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: flex-start;
margin-bottom: 1rem;
margin-bottom: 0.5rem;
gap: 1rem;
.header-title {
@@ -184,7 +184,7 @@
.hour-label {
display: none;
font-size: 0.7rem;
font-size: 0.75rem;
color: rgba(255, 255, 255, 0.6);
position: absolute;
left: 0;
@@ -177,16 +177,6 @@
</div>
@switch (chartConfig.id) {
@case ('readingStatus') {
<h3>Reading Status</h3>
<div class="chart-wrapper status-chart">
<canvas baseChart
[data]="(readStatusChartService.statusChartData$ | async) ?? {labels: [], datasets: []}"
[options]="readStatusChartService.statusChartOptions"
[type]="readStatusChartService.statusChartType">
</canvas>
</div>
}
@case ('bookFormats') {
<h3>Book Formats</h3>
<div class="chart-wrapper book-type-chart">
@@ -257,16 +247,6 @@
</canvas>
</div>
}
@case ('readingProgress') {
<h3>Reading Progress</h3>
<div class="chart-wrapper progress-chart">
<canvas baseChart
[data]="(readingProgressChartService.progressChartData$ | async) ?? {labels: [], datasets: []}"
[options]="readingProgressChartService.progressChartOptions"
[type]="readingProgressChartService.progressChartType">
</canvas>
</div>
}
@case ('externalRating') {
<h3>External Rating Distribution</h3>
<div class="chart-wrapper rating-chart">
@@ -277,16 +257,6 @@
</canvas>
</div>
}
@case ('personalRating') {
<h3>Personal Rating Distribution</h3>
<div class="chart-wrapper personal-rating-chart">
<canvas baseChart
[data]="(personalRatingChartService.personalRatingChartData$ | async) ?? {labels: [], datasets: []}"
[options]="personalRatingChartService.personalRatingChartOptions"
[type]="personalRatingChartService.personalRatingChartType">
</canvas>
</div>
}
@case ('pageCount') {
<h3>Page Count Distribution</h3>
<div class="chart-wrapper page-count-chart">
@@ -497,7 +497,6 @@
&.progress-chart,
&.rating-chart,
&.personal-rating-chart,
&.page-count-chart,
&.reading-speed-chart,
&.quality-chart,
@@ -894,7 +893,6 @@
&.progress-chart,
&.rating-chart,
&.personal-rating-chart,
&.page-count-chart,
&.reading-speed-chart,
&.quality-chart,
@@ -983,7 +981,6 @@
&.progress-chart,
&.rating-chart,
&.personal-rating-chart,
&.page-count-chart,
&.reading-speed-chart,
&.quality-chart,
@@ -13,12 +13,9 @@ import {MatrixController, MatrixElement} from 'chartjs-chart-matrix';
import {PageTitleService} from "../../../shared/service/page-title.service";
import {LibraryFilterService, LibraryOption} from '../service/library-filter.service';
import {LibrariesSummaryService} from '../service/libraries-summary.service';
import {ReadStatusChartService} from '../service/read-status-chart.service';
import {BookTypeChartService} from '../service/book-type-chart.service';
import {ReadingProgressChartService} from '../service/reading-progress-chart-service';
import {PageCountChartService} from '../service/page-count-chart.service';
import {BookRatingChartService} from '../service/book-rating-chart.service';
import {PersonalRatingChartService} from '../service/personal-rating-chart.service';
import {PublicationYearChartService} from '../service/publication-year-chart-service';
import {AuthorPopularityChartService} from '../service/author-popularity-chart.service';
import {ReadingCompletionChartService} from '../service/reading-completion-chart.service';
@@ -50,12 +47,9 @@ export class StatsComponent implements OnInit, OnDestroy {
private readonly libraryFilterService = inject(LibraryFilterService);
private readonly librariesSummaryService = inject(LibrariesSummaryService);
protected readonly readStatusChartService = inject(ReadStatusChartService);
protected readonly bookTypeChartService = inject(BookTypeChartService);
protected readonly readingProgressChartService = inject(ReadingProgressChartService);
protected readonly pageCountChartService = inject(PageCountChartService);
protected readonly bookRatingChartService = inject(BookRatingChartService);
protected readonly personalRatingChartService = inject(PersonalRatingChartService);
protected readonly publicationYearChartService = inject(PublicationYearChartService);
protected readonly authorPopularityChartService = inject(AuthorPopularityChartService);
protected readonly readingCompletionChartService = inject(ReadingCompletionChartService);
@@ -210,13 +204,5 @@ export class StatsComponent implements OnInit, OnDestroy {
this.chartConfigService.resetPositions();
}
trackByTrait(index: number, insight: any): string {
return insight.trait;
}
trackByHabit(index: number, habit: any): string {
return habit.habit;
}
protected readonly ChartDataLabels = ChartDataLabels;
}
@@ -92,6 +92,18 @@
@case ('reading-habits') {
<app-reading-habits-chart></app-reading-habits-chart>
}
@case ('reading-heatmap') {
<app-reading-heatmap-chart></app-reading-heatmap-chart>
}
@case ('personal-rating') {
<app-personal-rating-chart></app-personal-rating-chart>
}
@case ('reading-progress') {
<app-reading-progress-chart></app-reading-progress-chart>
}
@case ('read-status') {
<app-read-status-chart></app-read-status-chart>
}
}
</div>
}
@@ -274,6 +274,61 @@
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
@media (max-width: 1440px) {
.charts-container {
grid-template-columns: repeat(12, 1fr);
}
.chart-card {
&.chart-small-square {
grid-column: span 4;
}
&.chart-small {
grid-column: span 4;
}
&.chart-medium {
grid-column: span 6;
}
&.chart-large {
grid-column: span 8;
}
&.chart-wide {
grid-column: span 12;
}
&.chart-full {
grid-column: span 12;
}
}
}
@media (max-width: 1024px) {
.charts-container {
grid-template-columns: repeat(6, 1fr);
}
.chart-card {
&.chart-small-square,
&.chart-small {
grid-column: span 3;
}
&.chart-medium {
grid-column: span 3;
}
&.chart-large,
&.chart-wide,
&.chart-full {
grid-column: span 6;
}
}
}
@media (max-width: 768px) {
.user-stats-container {
padding: 1rem;
@@ -355,7 +410,7 @@
}
.charts-container {
grid-template-columns: repeat(6, 1fr);
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
}
@@ -367,12 +422,18 @@
}
&.chart-small-square,
&.chart-small,
&.chart-medium,
&.chart-small {
grid-column: span 1;
}
&.chart-medium {
grid-column: span 1;
}
&.chart-large,
&.chart-wide,
&.chart-full {
grid-column: span 6;
grid-column: span 2;
}
}
}
@@ -15,6 +15,10 @@ import {PeakHoursChartComponent} from '../peak-hours-chart/peak-hours-chart.comp
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';
@Component({
selector: 'app-user-stats',
@@ -31,7 +35,11 @@ import {UserChartConfig, UserChartConfigService} from '../../service/user-chart-
FavoriteDaysChartComponent,
PeakHoursChartComponent,
ReadingDNAChartComponent,
ReadingHabitsChartComponent
ReadingHabitsChartComponent,
ReadingHeatmapChartComponent,
PersonalRatingChartComponent,
ReadingProgressChartComponent,
ReadStatusChartComponent
],
templateUrl: './user-stats.component.html',
styleUrls: ['./user-stats.component.scss']