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 { .chart-wrapper {
position: relative; position: relative;
height: 350px; height: 300px;
width: 100%; width: 100%;
} }
@@ -37,7 +37,7 @@
.chart-wrapper { .chart-wrapper {
position: relative; position: relative;
height: 350px; height: 300px;
width: 100%; width: 100%;
} }
@@ -37,7 +37,7 @@ export class GenreStatsChartComponent implements OnInit, OnDestroy {
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
layout: { layout: {
padding: {top: 10, bottom: 10, left: 10, right: 10} padding: {top: 10}
}, },
plugins: { plugins: {
legend: {display: false}, legend: {display: false},
@@ -45,7 +45,7 @@
.chart-wrapper { .chart-wrapper {
position: relative; position: relative;
height: 350px; height: 300px;
width: 100%; 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;
}
}
@@ -1,10 +1,11 @@
import {inject, Injectable, OnDestroy} from '@angular/core'; 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 {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators'; import {catchError, filter, first, takeUntil} from 'rxjs/operators';
import {LibraryFilterService} from './library-filter.service'; import {ChartConfiguration, ChartData} from 'chart.js';
import {BookService} from '../../book/service/book.service'; import {BookService} from '../../../book/service/book.service';
import {Book} from '../../book/model/book.model'; import {Book} from '../../../book/model/book.model';
import {ChartConfiguration, ChartData, ChartType} from 'chart.js';
interface RatingStats { interface RatingStats {
ratingRange: string; ratingRange: string;
@@ -42,44 +43,65 @@ const RATING_RANGES = [
{range: '7', min: 7.0, max: 7.0}, {range: '7', min: 7.0, max: 7.0},
{range: '8', min: 8.0, max: 8.0}, {range: '8', min: 8.0, max: 8.0},
{range: '9', min: 9.0, max: 9.0}, {range: '9', min: 9.0, max: 9.0},
{range: '10', min: 10.0, max: 10.0}, {range: '10', min: 10.0, max: 10.0}
{range: 'No Rating', min: 0, max: 0}
] as const; ] as const;
type RatingChartData = ChartData<'bar', number[], string>; type RatingChartData = ChartData<'bar', number[], string>;
@Injectable({ @Component({
providedIn: 'root' selector: 'app-personal-rating-chart',
standalone: true,
imports: [CommonModule, BaseChartDirective],
templateUrl: './personal-rating-chart.component.html',
styleUrls: ['./personal-rating-chart.component.scss']
}) })
export class PersonalRatingChartService implements OnDestroy { export class PersonalRatingChartComponent implements OnInit, OnDestroy {
private readonly bookService = inject(BookService); private readonly bookService = inject(BookService);
private readonly libraryFilterService = inject(LibraryFilterService);
private readonly destroy$ = new Subject<void>(); private readonly destroy$ = new Subject<void>();
public readonly personalRatingChartType = 'bar' as const; public readonly chartType = 'bar' as const;
public readonly personalRatingChartOptions: ChartConfiguration['options'] = { public readonly chartOptions: ChartConfiguration['options'] = {
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
layout: {
padding: {top: 25}
},
plugins: { plugins: {
legend: {display: false}, legend: {display: false},
tooltip: { tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)', enabled: true,
backgroundColor: 'rgba(0, 0, 0, 0.9)',
titleColor: '#ffffff', titleColor: '#ffffff',
bodyColor: '#ffffff', bodyColor: '#ffffff',
borderColor: '#666666', borderColor: '#ffffff',
borderWidth: 1, borderWidth: 1,
cornerRadius: 6,
displayColors: true,
padding: 12,
titleFont: {size: 14, weight: 'bold'},
bodyFont: {size: 13},
callbacks: { callbacks: {
title: (context) => `Personal Rating Range: ${context[0].label}`, title: (context) => `Personal Rating: ${context[0].label}`,
label: (context) => { label: (context) => {
const value = context.parsed.y; const value = context.parsed.y;
return `${value} book${value === 1 ? '' : 's'}`; return `${value} book${value === 1 ? '' : 's'}`;
} }
} }
} },
datalabels: {display: false}
}, },
scales: { scales: {
x: { x: {
title: {
display: true,
text: 'Personal Rating',
color: '#ffffff',
font: {
family: "'Inter', sans-serif",
size: 12
}
},
ticks: { ticks: {
color: '#ffffff', color: '#ffffff',
font: { font: {
@@ -87,18 +109,19 @@ export class PersonalRatingChartService implements OnDestroy {
size: 11 size: 11
} }
}, },
grid: {color: 'rgba(255, 255, 255, 0.1)'}, grid: {display: false},
border: {display: false}
},
y: {
title: { title: {
display: true, display: true,
text: 'Personal Rating Range', text: 'Number of Books',
color: '#ffffff', color: '#ffffff',
font: { font: {
family: "'Inter', sans-serif", family: "'Inter', sans-serif",
size: 11.5 size: 12
} }
} },
},
y: {
beginAtZero: true, beginAtZero: true,
ticks: { ticks: {
color: '#ffffff', color: '#ffffff',
@@ -106,23 +129,18 @@ export class PersonalRatingChartService implements OnDestroy {
family: "'Inter', sans-serif", family: "'Inter', sans-serif",
size: 11 size: 11
}, },
stepSize: 1 stepSize: 1,
maxTicksLimit: 8
}, },
grid: {color: 'rgba(255, 255, 255, 0.05)'}, grid: {
title: { color: 'rgba(255, 255, 255, 0.1)'
display: true, },
text: 'Number of Books', border: {display: false}
color: '#ffffff',
font: {
family: "'Inter', sans-serif",
size: 11.5
}
}
} }
} }
}; };
private readonly personalRatingChartDataSubject = new BehaviorSubject<RatingChartData>({ private readonly chartDataSubject = new BehaviorSubject<RatingChartData>({
labels: [], labels: [],
datasets: [{ datasets: [{
label: 'Books by Personal Rating', label: 'Books by Personal Rating',
@@ -132,23 +150,18 @@ export class PersonalRatingChartService implements OnDestroy {
}] }]
}); });
public readonly personalRatingChartData$: Observable<RatingChartData> = public readonly chartData$: Observable<RatingChartData> = this.chartDataSubject.asObservable();
this.personalRatingChartDataSubject.asObservable();
constructor() { ngOnInit(): void {
this.bookService.bookState$ this.bookService.bookState$
.pipe( .pipe(
filter(state => state.loaded), filter(state => state.loaded),
first(), first(),
switchMap(() =>
this.libraryFilterService.selectedLibrary$.pipe(
takeUntil(this.destroy$)
)
),
catchError((error) => { catchError((error) => {
console.error('Error processing personal rating stats:', error); console.error('Error processing personal rating data:', error);
return EMPTY; return EMPTY;
}) }),
takeUntil(this.destroy$)
) )
.subscribe(() => { .subscribe(() => {
const stats = this.calculatePersonalRatingStats(); const stats = this.calculatePersonalRatingStats();
@@ -163,17 +176,25 @@ export class PersonalRatingChartService implements OnDestroy {
private updateChartData(stats: RatingStats[]): void { private updateChartData(stats: RatingStats[]): void {
try { try {
const labels = stats.map(s => s.ratingRange); // Always show all rating labels from 1-10, even if there's no data
const dataValues = stats.map(s => s.count); const allLabels = RATING_RANGES.map(r => r.range);
const colors = stats.map((_, index) => CHART_COLORS[index % CHART_COLORS.length]); 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.personalRatingChartDataSubject.next({ this.chartDataSubject.next({
labels, labels: allLabels,
datasets: [{ datasets: [{
label: 'Books by Personal Rating', label: 'Books by Personal Rating',
data: dataValues, data: dataValues,
backgroundColor: colors, backgroundColor: colors,
...CHART_DEFAULTS borderColor: colors.map(color => color),
borderWidth: 1,
borderRadius: 4,
barPercentage: 0.8,
categoryPercentage: 0.6
}] }]
}); });
} catch (error) { } catch (error) {
@@ -183,26 +204,18 @@ export class PersonalRatingChartService implements OnDestroy {
private calculatePersonalRatingStats(): RatingStats[] { private calculatePersonalRatingStats(): RatingStats[] {
const currentState = this.bookService.getCurrentBookState(); const currentState = this.bookService.getCurrentBookState();
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
if (!this.isValidBookState(currentState)) { if (!this.isValidBookState(currentState)) {
return []; return [];
} }
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId); return this.processPersonalRatingStats(currentState.books!);
return this.processPersonalRatingStats(filteredBooks);
} }
private isValidBookState(state: any): boolean { private isValidBookState(state: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0;
} }
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
return selectedLibraryId
? books.filter(book => book.libraryId === selectedLibraryId)
: books;
}
private processPersonalRatingStats(books: Book[]): RatingStats[] { private processPersonalRatingStats(books: Book[]): RatingStats[] {
const rangeCounts = new Map<string, { count: number, totalRating: number }>(); const rangeCounts = new Map<string, { count: number, totalRating: number }>();
RATING_RANGES.forEach(range => rangeCounts.set(range.range, {count: 0, totalRating: 0})); RATING_RANGES.forEach(range => rangeCounts.set(range.range, {count: 0, totalRating: 0}));
@@ -210,12 +223,9 @@ export class PersonalRatingChartService implements OnDestroy {
books.forEach(book => { books.forEach(book => {
const personalRating = book.personalRating; const personalRating = book.personalRating;
if (!personalRating || personalRating === 0) { if (personalRating && personalRating > 0) {
const noRatingData = rangeCounts.get('No Rating')!;
noRatingData.count++;
} else {
for (const range of RATING_RANGES) { for (const range of RATING_RANGES) {
if (range.range !== 'No Rating' && personalRating >= range.min && personalRating <= range.max) { if (personalRating >= range.min && personalRating <= range.max) {
const rangeData = rangeCounts.get(range.range)!; const rangeData = rangeCounts.get(range.range)!;
rangeData.count++; rangeData.count++;
rangeData.totalRating += personalRating; rangeData.totalRating += personalRating;
@@ -225,6 +235,7 @@ export class PersonalRatingChartService implements OnDestroy {
} }
}); });
// Return all ratings, including those with 0 count
return RATING_RANGES.map(range => { return RATING_RANGES.map(range => {
const data = rangeCounts.get(range.range)!; const data = rangeCounts.get(range.range)!;
return { return {
@@ -232,6 +243,6 @@ export class PersonalRatingChartService implements OnDestroy {
count: data.count, count: data.count,
averageRating: data.count > 0 ? data.totalRating / data.count : 0 averageRating: data.count > 0 ? data.totalRating / data.count : 0
}; };
}).filter(stat => stat.ratingRange !== 'No Rating'); });
} }
} }
@@ -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;
}
}
@@ -1,11 +1,11 @@
import {inject, Injectable, OnDestroy} from '@angular/core'; 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 {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators'; import {catchError, filter, first, takeUntil} from 'rxjs/operators';
import {ChartConfiguration, ChartData, ChartType} from 'chart.js'; import {ChartConfiguration, ChartData} from 'chart.js';
import {BookService} from '../../../book/service/book.service';
import {LibraryFilterService} from './library-filter.service'; import {Book, ReadStatus} from '../../../book/model/book.model';
import {BookService} from '../../book/service/book.service';
import {Book, ReadStatus} from '../../book/model/book.model';
interface ReadingStatusStats { interface ReadingStatusStats {
status: string; status: string;
@@ -27,19 +27,25 @@ const CHART_DEFAULTS = {
type StatusChartData = ChartData<'doughnut', number[], string>; type StatusChartData = ChartData<'doughnut', number[], string>;
@Injectable({ @Component({
providedIn: 'root' selector: 'app-read-status-chart',
standalone: true,
imports: [CommonModule, BaseChartDirective],
templateUrl: './read-status-chart.component.html',
styleUrls: ['./read-status-chart.component.scss']
}) })
export class ReadStatusChartService implements OnDestroy { export class ReadStatusChartComponent implements OnInit, OnDestroy {
private readonly bookService = inject(BookService); private readonly bookService = inject(BookService);
private readonly libraryFilterService = inject(LibraryFilterService);
private readonly destroy$ = new Subject<void>(); private readonly destroy$ = new Subject<void>();
public readonly statusChartType: ChartType = 'doughnut'; public readonly chartType = 'doughnut' as const;
public readonly statusChartOptions: ChartConfiguration['options'] = { public readonly chartOptions: ChartConfiguration['options'] = {
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
layout: {
padding: {top: 15}
},
plugins: { plugins: {
legend: { legend: {
display: true, display: true,
@@ -47,6 +53,11 @@ export class ReadStatusChartService implements OnDestroy {
labels: { labels: {
padding: 15, padding: 15,
usePointStyle: true, usePointStyle: true,
color: '#ffffff',
font: {
family: "'Inter', sans-serif",
size: 12
},
generateLabels: this.generateLegendLabels.bind(this) generateLabels: this.generateLegendLabels.bind(this)
} }
}, },
@@ -62,7 +73,6 @@ export class ReadStatusChartService implements OnDestroy {
padding: 12, padding: 12,
titleFont: {size: 14, weight: 'bold'}, titleFont: {size: 14, weight: 'bold'},
bodyFont: {size: 13}, bodyFont: {size: 13},
position: 'nearest',
callbacks: { callbacks: {
title: (context) => context[0]?.label || '', title: (context) => context[0]?.label || '',
label: this.formatTooltipLabel label: this.formatTooltipLabel
@@ -75,7 +85,7 @@ export class ReadStatusChartService implements OnDestroy {
} }
}; };
private readonly statusChartDataSubject = new BehaviorSubject<StatusChartData>({ private readonly chartDataSubject = new BehaviorSubject<StatusChartData>({
labels: [], labels: [],
datasets: [{ datasets: [{
data: [], data: [],
@@ -84,22 +94,18 @@ export class ReadStatusChartService implements OnDestroy {
}] }]
}); });
public readonly statusChartData$: Observable<StatusChartData> = this.statusChartDataSubject.asObservable(); public readonly chartData$: Observable<StatusChartData> = this.chartDataSubject.asObservable();
constructor() { ngOnInit(): void {
this.bookService.bookState$ this.bookService.bookState$
.pipe( .pipe(
filter(state => state.loaded), filter(state => state.loaded),
first(), first(),
switchMap(() =>
this.libraryFilterService.selectedLibrary$.pipe(
takeUntil(this.destroy$)
)
),
catchError((error) => { catchError((error) => {
console.error('Error processing reading status stats:', error); console.error('Error processing reading status stats:', error);
return EMPTY; return EMPTY;
}) }),
takeUntil(this.destroy$)
) )
.subscribe(() => { .subscribe(() => {
const stats = this.calculateReadingStatusStats(); const stats = this.calculateReadingStatusStats();
@@ -118,7 +124,7 @@ export class ReadStatusChartService implements OnDestroy {
const dataValues = stats.map(s => s.count); const dataValues = stats.map(s => s.count);
const colors = this.getColorsForData(stats.length); const colors = this.getColorsForData(stats.length);
this.statusChartDataSubject.next({ this.chartDataSubject.next({
labels, labels,
datasets: [{ datasets: [{
data: dataValues, data: dataValues,
@@ -141,26 +147,18 @@ export class ReadStatusChartService implements OnDestroy {
private calculateReadingStatusStats(): ReadingStatusStats[] { private calculateReadingStatusStats(): ReadingStatusStats[] {
const currentState = this.bookService.getCurrentBookState(); const currentState = this.bookService.getCurrentBookState();
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
if (!this.isValidBookState(currentState)) { if (!this.isValidBookState(currentState)) {
return []; return [];
} }
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId)); return this.processReadingStatusStats(currentState.books!);
return this.processReadingStatusStats(filteredBooks);
} }
private isValidBookState(state: any): boolean { private isValidBookState(state: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0;
} }
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
return selectedLibraryId && selectedLibraryId !== 'null'
? books.filter(book => String(book.libraryId) === selectedLibraryId)
: books;
}
private processReadingStatusStats(books: Book[]): ReadingStatusStats[] { private processReadingStatusStats(books: Book[]): ReadingStatusStats[] {
if (books.length === 0) { if (books.length === 0) {
return []; return [];
@@ -248,3 +246,4 @@ export class ReadStatusChartService implements OnDestroy {
return `${label}: ${value} books (${percentage}%)`; return `${label}: ${value} books (${percentage}%)`;
} }
} }
@@ -43,6 +43,9 @@ export class ReadingDNAChartComponent implements OnInit, OnDestroy {
public readonly chartOptions: ChartConfiguration<'radar'>['options'] = { public readonly chartOptions: ChartConfiguration<'radar'>['options'] = {
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
layout: {
padding: {top: 15}
},
scales: { scales: {
r: { r: {
beginAtZero: true, beginAtZero: true,
@@ -43,6 +43,9 @@ export class ReadingHabitsChartComponent implements OnInit, OnDestroy {
public readonly chartOptions: ChartConfiguration<'radar'>['options'] = { public readonly chartOptions: ChartConfiguration<'radar'>['options'] = {
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
layout: {
padding: {top: 15}
},
scales: { scales: {
r: { r: {
beginAtZero: true, 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;
}
}
@@ -1,11 +1,11 @@
import {inject, Injectable, OnDestroy} from '@angular/core'; 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 {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators'; import {catchError, filter, first, takeUntil} from 'rxjs/operators';
import {ChartConfiguration, ChartData, ChartType} from 'chart.js'; import {ChartConfiguration, ChartData} from 'chart.js';
import {BookService} from '../../../book/service/book.service';
import {LibraryFilterService} from './library-filter.service'; import {Book} from '../../../book/model/book.model';
import {BookService} from '../../book/service/book.service';
import {Book} from '../../book/model/book.model';
interface ReadingProgressStats { interface ReadingProgressStats {
progressRange: string; progressRange: string;
@@ -33,78 +33,98 @@ const PROGRESS_RANGES = [
{range: '100%', min: 100, max: 100, desc: 'Completed'} {range: '100%', min: 100, max: 100, desc: 'Completed'}
] as const; ] as const;
type ProgressChartData = ChartData<'bar', number[], string>; type ProgressChartData = ChartData<'doughnut', number[], string>;
@Injectable({ @Component({
providedIn: 'root' selector: 'app-reading-progress-chart',
standalone: true,
imports: [CommonModule, BaseChartDirective],
templateUrl: './reading-progress-chart.component.html',
styleUrls: ['./reading-progress-chart.component.scss']
}) })
export class ReadingProgressChartService implements OnDestroy { export class ReadingProgressChartComponent implements OnInit, OnDestroy {
private readonly bookService = inject(BookService); private readonly bookService = inject(BookService);
private readonly libraryFilterService = inject(LibraryFilterService);
private readonly destroy$ = new Subject<void>(); private readonly destroy$ = new Subject<void>();
public readonly progressChartType: ChartType = 'bar'; public readonly chartType = 'doughnut' as const;
public readonly progressChartOptions: ChartConfiguration['options'] = { public readonly chartOptions: ChartConfiguration<'doughnut'>['options'] = {
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
plugins: { layout: {
legend: {display: false}, padding: {top: 15}
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleColor: '#ffffff',
bodyColor: '#ffffff',
borderColor: '#666666',
borderWidth: 1,
callbacks: {
title: (context) => context[0].label,
label: this.formatTooltipLabel
}
}
}, },
scales: { plugins: {
x: { legend: {
ticks: { display: true,
position: 'bottom',
labels: {
color: '#ffffff', color: '#ffffff',
font: { font: {
family: "'Inter', sans-serif", family: "'Inter', sans-serif",
size: 11 size: 12
} },
}, padding: 15,
grid: {color: 'rgba(255, 255, 255, 0.1)'}, usePointStyle: true,
title: { pointStyle: 'circle',
display: true, generateLabels: (chart) => {
text: 'Progress Range', const data = chart.data;
color: '#ffffff', if (data.labels?.length && data.datasets?.length) {
font: { return data.labels.map((label, i) => {
family: "'Inter', sans-serif", const value = data.datasets[0].data[i] as number;
size: 11.5 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 [];
} }
} }
}, },
y: { tooltip: {
beginAtZero: true, enabled: true,
ticks: { backgroundColor: 'rgba(0, 0, 0, 0.9)',
color: '#ffffff', font: { titleColor: '#ffffff',
family: "'Inter', sans-serif", bodyColor: '#ffffff',
size: 11 borderColor: '#ffffff',
}, stepSize: 1 borderWidth: 1,
}, cornerRadius: 6,
grid: {color: 'rgba(255, 255, 255, 0.05)'}, displayColors: true,
title: { padding: 12,
display: true, titleFont: {size: 14, weight: 'bold'},
text: 'Number of Books', bodyFont: {size: 13},
color: '#ffffff', callbacks: {
font: { title: (context) => context[0].label,
family: "'Inter', sans-serif", label: (context) => {
size: 11.5 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 progressChartDataSubject = new BehaviorSubject<ProgressChartData>({ private readonly chartDataSubject = new BehaviorSubject<ProgressChartData>({
labels: [], labels: [],
datasets: [{ datasets: [{
label: 'Books by Progress', label: 'Books by Progress',
@@ -114,23 +134,18 @@ export class ReadingProgressChartService implements OnDestroy {
}] }]
}); });
public readonly progressChartData$: Observable<ProgressChartData> = public readonly chartData$: Observable<ProgressChartData> = this.chartDataSubject.asObservable();
this.progressChartDataSubject.asObservable();
constructor() { ngOnInit(): void {
this.bookService.bookState$ this.bookService.bookState$
.pipe( .pipe(
filter(state => state.loaded), filter(state => state.loaded),
first(), first(),
switchMap(() =>
this.libraryFilterService.selectedLibrary$.pipe(
takeUntil(this.destroy$)
)
),
catchError((error) => { catchError((error) => {
console.error('Error processing reading progress stats:', error); console.error('Error processing reading progress data:', error);
return EMPTY; return EMPTY;
}) }),
takeUntil(this.destroy$)
) )
.subscribe(() => { .subscribe(() => {
const stats = this.calculateReadingProgressStats(); const stats = this.calculateReadingProgressStats();
@@ -148,56 +163,38 @@ export class ReadingProgressChartService implements OnDestroy {
const labels = stats.map(s => s.progressRange); const labels = stats.map(s => s.progressRange);
const dataValues = stats.map(s => s.count); const dataValues = stats.map(s => s.count);
this.progressChartDataSubject.next({ this.chartDataSubject.next({
labels, labels,
datasets: [{ datasets: [{
label: 'Books by Progress', label: 'Books by Progress',
data: dataValues, data: dataValues,
backgroundColor: [...CHART_COLORS], backgroundColor: [...CHART_COLORS],
...CHART_DEFAULTS borderColor: '#ffffff',
borderWidth: 2,
hoverBorderWidth: 3,
hoverBorderColor: '#ffffff'
}] }]
}); });
} catch (error) { } catch (error) {
console.error('Error updating chart data:', error); console.error('Error updating reading progress chart data:', error);
} }
} }
private calculateReadingProgressStats(): ReadingProgressStats[] { private calculateReadingProgressStats(): ReadingProgressStats[] {
const currentState = this.bookService.getCurrentBookState(); const currentState = this.bookService.getCurrentBookState();
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
if (!this.isValidBookState(currentState)) { if (!this.isValidBookState(currentState)) {
return []; return [];
} }
const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId)); return this.processReadingProgressStats(currentState.books!);
return this.processReadingProgressStats(filteredBooks);
}
public updateFromStats(stats: ReadingProgressStats[]): void {
this.updateChartData(stats);
} }
private isValidBookState(state: any): boolean { private isValidBookState(state: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0;
} }
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] {
return selectedLibraryId && selectedLibraryId !== 'null'
? books.filter(book => String(book.libraryId) === selectedLibraryId)
: books;
}
private processReadingProgressStats(books: Book[]): ReadingProgressStats[] { private processReadingProgressStats(books: Book[]): ReadingProgressStats[] {
if (books.length === 0) {
return [];
}
const rangeCounts = this.buildProgressMap(books);
return this.convertMapToStats(rangeCounts);
}
private buildProgressMap(books: Book[]): Map<string, number> {
const rangeCounts = new Map<string, number>(); const rangeCounts = new Map<string, number>();
PROGRESS_RANGES.forEach(range => rangeCounts.set(range.range, 0)); PROGRESS_RANGES.forEach(range => rangeCounts.set(range.range, 0));
@@ -212,10 +209,6 @@ export class ReadingProgressChartService implements OnDestroy {
} }
} }
return rangeCounts;
}
private convertMapToStats(rangeCounts: Map<string, number>): ReadingProgressStats[] {
return PROGRESS_RANGES.map(range => ({ return PROGRESS_RANGES.map(range => ({
progressRange: range.range, progressRange: range.range,
count: rangeCounts.get(range.range) || 0, count: rangeCounts.get(range.range) || 0,
@@ -231,12 +224,4 @@ export class ReadingProgressChartService implements OnDestroy {
if (book.koboProgress?.percentage) return book.koboProgress.percentage; if (book.koboProgress?.percentage) return book.koboProgress.percentage;
return 0; return 0;
} }
private formatTooltipLabel(context: any): string {
const value = context.parsed.y;
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}`;
}
} }
@@ -6,7 +6,7 @@
display: grid; display: grid;
grid-template-columns: 1fr auto 1fr; grid-template-columns: 1fr auto 1fr;
align-items: flex-start; align-items: flex-start;
margin-bottom: 1rem; margin-bottom: 0.5rem;
gap: 1rem; gap: 1rem;
.header-title { .header-title {
@@ -184,7 +184,7 @@
.hour-label { .hour-label {
display: none; display: none;
font-size: 0.7rem; font-size: 0.75rem;
color: rgba(255, 255, 255, 0.6); color: rgba(255, 255, 255, 0.6);
position: absolute; position: absolute;
left: 0; left: 0;
@@ -177,16 +177,6 @@
</div> </div>
@switch (chartConfig.id) { @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') { @case ('bookFormats') {
<h3>Book Formats</h3> <h3>Book Formats</h3>
<div class="chart-wrapper book-type-chart"> <div class="chart-wrapper book-type-chart">
@@ -257,16 +247,6 @@
</canvas> </canvas>
</div> </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') { @case ('externalRating') {
<h3>External Rating Distribution</h3> <h3>External Rating Distribution</h3>
<div class="chart-wrapper rating-chart"> <div class="chart-wrapper rating-chart">
@@ -277,16 +257,6 @@
</canvas> </canvas>
</div> </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') { @case ('pageCount') {
<h3>Page Count Distribution</h3> <h3>Page Count Distribution</h3>
<div class="chart-wrapper page-count-chart"> <div class="chart-wrapper page-count-chart">
@@ -497,7 +497,6 @@
&.progress-chart, &.progress-chart,
&.rating-chart, &.rating-chart,
&.personal-rating-chart,
&.page-count-chart, &.page-count-chart,
&.reading-speed-chart, &.reading-speed-chart,
&.quality-chart, &.quality-chart,
@@ -894,7 +893,6 @@
&.progress-chart, &.progress-chart,
&.rating-chart, &.rating-chart,
&.personal-rating-chart,
&.page-count-chart, &.page-count-chart,
&.reading-speed-chart, &.reading-speed-chart,
&.quality-chart, &.quality-chart,
@@ -983,7 +981,6 @@
&.progress-chart, &.progress-chart,
&.rating-chart, &.rating-chart,
&.personal-rating-chart,
&.page-count-chart, &.page-count-chart,
&.reading-speed-chart, &.reading-speed-chart,
&.quality-chart, &.quality-chart,
@@ -13,12 +13,9 @@ import {MatrixController, MatrixElement} from 'chartjs-chart-matrix';
import {PageTitleService} from "../../../shared/service/page-title.service"; import {PageTitleService} from "../../../shared/service/page-title.service";
import {LibraryFilterService, LibraryOption} from '../service/library-filter.service'; import {LibraryFilterService, LibraryOption} from '../service/library-filter.service';
import {LibrariesSummaryService} from '../service/libraries-summary.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 {BookTypeChartService} from '../service/book-type-chart.service';
import {ReadingProgressChartService} from '../service/reading-progress-chart-service';
import {PageCountChartService} from '../service/page-count-chart.service'; import {PageCountChartService} from '../service/page-count-chart.service';
import {BookRatingChartService} from '../service/book-rating-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 {PublicationYearChartService} from '../service/publication-year-chart-service';
import {AuthorPopularityChartService} from '../service/author-popularity-chart.service'; import {AuthorPopularityChartService} from '../service/author-popularity-chart.service';
import {ReadingCompletionChartService} from '../service/reading-completion-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 libraryFilterService = inject(LibraryFilterService);
private readonly librariesSummaryService = inject(LibrariesSummaryService); private readonly librariesSummaryService = inject(LibrariesSummaryService);
protected readonly readStatusChartService = inject(ReadStatusChartService);
protected readonly bookTypeChartService = inject(BookTypeChartService); protected readonly bookTypeChartService = inject(BookTypeChartService);
protected readonly readingProgressChartService = inject(ReadingProgressChartService);
protected readonly pageCountChartService = inject(PageCountChartService); protected readonly pageCountChartService = inject(PageCountChartService);
protected readonly bookRatingChartService = inject(BookRatingChartService); protected readonly bookRatingChartService = inject(BookRatingChartService);
protected readonly personalRatingChartService = inject(PersonalRatingChartService);
protected readonly publicationYearChartService = inject(PublicationYearChartService); protected readonly publicationYearChartService = inject(PublicationYearChartService);
protected readonly authorPopularityChartService = inject(AuthorPopularityChartService); protected readonly authorPopularityChartService = inject(AuthorPopularityChartService);
protected readonly readingCompletionChartService = inject(ReadingCompletionChartService); protected readonly readingCompletionChartService = inject(ReadingCompletionChartService);
@@ -210,13 +204,5 @@ export class StatsComponent implements OnInit, OnDestroy {
this.chartConfigService.resetPositions(); 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; protected readonly ChartDataLabels = ChartDataLabels;
} }
@@ -92,6 +92,18 @@
@case ('reading-habits') { @case ('reading-habits') {
<app-reading-habits-chart></app-reading-habits-chart> <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> </div>
} }
@@ -274,6 +274,61 @@
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1); 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) { @media (max-width: 768px) {
.user-stats-container { .user-stats-container {
padding: 1rem; padding: 1rem;
@@ -355,7 +410,7 @@
} }
.charts-container { .charts-container {
grid-template-columns: repeat(6, 1fr); grid-template-columns: repeat(2, 1fr);
gap: 1rem; gap: 1rem;
} }
@@ -367,12 +422,18 @@
} }
&.chart-small-square, &.chart-small-square,
&.chart-small, &.chart-small {
&.chart-medium, grid-column: span 1;
}
&.chart-medium {
grid-column: span 1;
}
&.chart-large, &.chart-large,
&.chart-wide, &.chart-wide,
&.chart-full { &.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 {ReadingDNAChartComponent} from '../reading-dna-chart/reading-dna-chart.component';
import {ReadingHabitsChartComponent} from '../reading-habits-chart/reading-habits-chart.component'; import {ReadingHabitsChartComponent} from '../reading-habits-chart/reading-habits-chart.component';
import {UserChartConfig, UserChartConfigService} from '../../service/user-chart-config.service'; 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({ @Component({
selector: 'app-user-stats', selector: 'app-user-stats',
@@ -31,7 +35,11 @@ import {UserChartConfig, UserChartConfigService} from '../../service/user-chart-
FavoriteDaysChartComponent, FavoriteDaysChartComponent,
PeakHoursChartComponent, PeakHoursChartComponent,
ReadingDNAChartComponent, ReadingDNAChartComponent,
ReadingHabitsChartComponent ReadingHabitsChartComponent,
ReadingHeatmapChartComponent,
PersonalRatingChartComponent,
ReadingProgressChartComponent,
ReadStatusChartComponent
], ],
templateUrl: './user-stats.component.html', templateUrl: './user-stats.component.html',
styleUrls: ['./user-stats.component.scss'] styleUrls: ['./user-stats.component.scss']
@@ -16,21 +16,18 @@ export class ChartConfigService {
private readonly STORAGE_KEY = 'booklore-chart-config'; private readonly STORAGE_KEY = 'booklore-chart-config';
private readonly defaultCharts: ChartConfig[] = [ private readonly defaultCharts: ChartConfig[] = [
{id: 'readingStatus', name: 'Reading Status', enabled: true, category: 'small', order: 0}, {id: 'bookFormats', name: 'Book Formats', enabled: true, category: 'small', order: 0},
{id: 'bookFormats', name: 'Book Formats', enabled: true, category: 'small', order: 1}, {id: 'bookMetadataScore', name: 'Book Metadata Score', enabled: true, category: 'small', order: 1},
{id: 'bookMetadataScore', name: 'Book Metadata Score', enabled: true, category: 'small', order: 2}, {id: 'languageDistribution', name: 'Language Distribution', enabled: true, category: 'small', order: 2},
{id: 'languageDistribution', name: 'Language Distribution', enabled: true, category: 'small', order: 3}, {id: 'pageCount', name: 'Page Count Distribution', enabled: true, category: 'medium', order: 3},
{id: 'topAuthors', name: 'Top 25 Authors', enabled: true, category: 'large', order: 4}, {id: 'topAuthors', name: 'Top 25 Authors', enabled: true, category: 'large', order: 4},
{id: 'topCategories', name: 'Top 25 Categories', enabled: true, category: 'large', order: 5}, {id: 'topCategories', name: 'Top 25 Categories', enabled: true, category: 'large', order: 5},
{id: 'monthlyReadingPatterns', name: 'Monthly Reading Patterns', enabled: true, category: 'large', order: 6}, {id: 'monthlyReadingPatterns', name: 'Monthly Reading Patterns', enabled: true, category: 'large', order: 6},
{id: 'readingVelocityTimeline', name: 'Reading Velocity Timeline', enabled: true, category: 'large', order: 7}, {id: 'readingVelocityTimeline', name: 'Reading Velocity Timeline', enabled: true, category: 'large', order: 7},
{id: 'readingProgress', name: 'Reading Progress', enabled: true, category: 'medium', order: 8}, {id: 'topBooksBySize', name: 'Top 20 Largest Books', enabled: true, category: 'large', order: 8},
{id: 'externalRating', name: 'External Rating Distribution', enabled: true, category: 'medium', order: 9}, {id: 'topSeries', name: 'Top 20 Series', enabled: true, category: 'large', order: 9},
{id: 'personalRating', name: 'Personal Rating Distribution', enabled: true, category: 'medium', order: 10}, {id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 10},
{id: 'pageCount', name: 'Page Count Distribution', enabled: true, category: 'medium', order: 11}, {id: 'externalRating', name: 'External Rating Distribution', enabled: true, category: 'medium', order: 11},
{id: 'topBooksBySize', name: 'Top 20 Largest Books', enabled: true, category: 'large', order: 12},
{id: 'topSeries', name: 'Top 20 Series', enabled: true, category: 'large', order: 13},
{id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 14}
]; ];
private chartsConfigSubject = new BehaviorSubject<ChartConfig[]>(this.loadConfig()); private chartsConfigSubject = new BehaviorSubject<ChartConfig[]>(this.loadConfig());
@@ -8,6 +8,10 @@ import {FavoriteDaysChartComponent} from '../component/favorite-days-chart/favor
import {PeakHoursChartComponent} from '../component/peak-hours-chart/peak-hours-chart.component'; import {PeakHoursChartComponent} from '../component/peak-hours-chart/peak-hours-chart.component';
import {ReadingDNAChartComponent} from '../component/reading-dna-chart/reading-dna-chart.component'; import {ReadingDNAChartComponent} from '../component/reading-dna-chart/reading-dna-chart.component';
import {ReadingHabitsChartComponent} from '../component/reading-habits-chart/reading-habits-chart.component'; import {ReadingHabitsChartComponent} from '../component/reading-habits-chart/reading-habits-chart.component';
import {ReadingHeatmapChartComponent} from '../component/reading-heatmap-chart/reading-heatmap-chart.component';
import {PersonalRatingChartComponent} from '../component/personal-rating-chart/personal-rating-chart.component';
import {ReadingProgressChartComponent} from '../component/reading-progress-chart/reading-progress-chart.component';
import {ReadStatusChartComponent} from '../component/read-status-chart/read-status-chart.component';
export interface UserChartConfig { export interface UserChartConfig {
id: string; id: string;
@@ -23,71 +27,20 @@ export interface UserChartConfig {
}) })
export class UserChartConfigService { export class UserChartConfigService {
private readonly STORAGE_KEY = 'userStatsChartConfig'; private readonly STORAGE_KEY = 'userStatsChartConfig';
private readonly defaultCharts: UserChartConfig[] = [ private readonly defaultCharts: UserChartConfig[] = [
{ {id: 'heatmap', title: 'Reading Session Heatmap', component: ReadingSessionHeatmapComponent, enabled: true, sizeClass: 'chart-full', order: 0},
id: 'heatmap', {id: 'favorite-days', title: 'Favorite Reading Days', component: FavoriteDaysChartComponent, enabled: true, sizeClass: 'chart-medium', order: 1},
title: 'Reading Session Heatmap', {id: 'peak-hours', title: 'Peak Reading Hours', component: PeakHoursChartComponent, enabled: true, sizeClass: 'chart-medium', order: 2},
component: ReadingSessionHeatmapComponent, {id: 'timeline', title: 'Reading Session Timeline', component: ReadingSessionTimelineComponent, enabled: true, sizeClass: 'chart-full', order: 3},
enabled: true, {id: 'reading-heatmap', title: 'Reading Activity Heatmap', component: ReadingHeatmapChartComponent, enabled: true, sizeClass: 'chart-small-square', order: 4},
sizeClass: 'chart-full', {id: 'personal-rating', title: 'Personal Rating Distribution', component: PersonalRatingChartComponent, enabled: true, sizeClass: 'chart-small-square', order: 5},
order: 0 {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: 'favorite-days', {id: 'completion-timeline', title: 'Completion Timeline', component: CompletionTimelineChartComponent, enabled: true, sizeClass: 'chart-medium', order: 9},
title: 'Favorite Reading Days', {id: 'reading-dna', title: 'Reading DNA Profile', component: ReadingDNAChartComponent, enabled: true, sizeClass: 'chart-medium', order: 10},
component: FavoriteDaysChartComponent, {id: 'reading-habits', title: 'Reading Habits Analysis', component: ReadingHabitsChartComponent, enabled: true, sizeClass: 'chart-medium', order: 11},
enabled: true,
sizeClass: 'chart-medium',
order: 1
},
{
id: 'peak-hours',
title: 'Peak Reading Hours',
component: PeakHoursChartComponent,
enabled: true,
sizeClass: 'chart-medium',
order: 2
},
{
id: 'genre-stats',
title: 'Genre Statistics',
component: GenreStatsChartComponent,
enabled: true,
sizeClass: 'chart-medium',
order: 3
},
{
id: 'completion-timeline',
title: 'Completion Timeline',
component: CompletionTimelineChartComponent,
enabled: true,
sizeClass: 'chart-medium',
order: 4
},
{
id: 'reading-dna',
title: 'Reading DNA Profile',
component: ReadingDNAChartComponent,
enabled: true,
sizeClass: 'chart-medium',
order: 5
},
{
id: 'reading-habits',
title: 'Reading Habits Analysis',
component: ReadingHabitsChartComponent,
enabled: true,
sizeClass: 'chart-medium',
order: 6
},
{
id: 'timeline',
title: 'Reading Session Timeline',
component: ReadingSessionTimelineComponent,
enabled: true,
sizeClass: 'chart-full',
order: 7
},
]; ];
private chartsSubject = new BehaviorSubject<UserChartConfig[]>(this.loadChartConfig()); private chartsSubject = new BehaviorSubject<UserChartConfig[]>(this.loadChartConfig());