Add more user-specific charts (#1991)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2025-12-26 12:08:27 -07:00
committed by GitHub
co-authored by acx10
parent ad8904550b
commit 2c1e8a99e3
53 changed files with 3411 additions and 2120 deletions
@@ -0,0 +1,37 @@
<div class="reading-dna-container">
<div class="chart-header">
<div class="chart-title">
<h3>
<i class="pi pi-chart-line reading-dna-icon"></i>
Reading DNA Profile
</h3>
<p class="chart-description">Your unique reading personality across 8 key dimensions</p>
</div>
</div>
<div class="chart-wrapper">
<canvas baseChart
[data]="(chartData$ | async) ?? {labels: [], datasets: []}"
[options]="chartOptions"
[type]="chartType">
</canvas>
</div>
@if (personalityInsights.length > 0) {
<div class="personality-insights">
<h4>Your Reading Personality Traits</h4>
<div class="insights-grid">
@for (insight of personalityInsights; track insight.trait) {
<div class="insight-card">
<div class="insight-header">
<span class="insight-trait">{{ insight.trait }}</span>
<span class="insight-score" [style.color]="insight.color">{{ insight.score.toFixed(0) }}%</span>
</div>
<div class="insight-progress">
<div class="progress-bar" [style.width.%]="insight.score" [style.background-color]="insight.color"></div>
</div>
<p class="insight-description">{{ insight.description }}</p>
</div>
}
</div>
</div>
}
</div>
@@ -0,0 +1,137 @@
.reading-dna-container {
width: 100%;
}
.chart-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 0.5rem;
.chart-title {
flex: 1;
h3 {
color: var(--text-color, #ffffff);
font-size: 1.25rem;
font-weight: 500;
margin: 0 0 0.5rem 0;
display: flex;
align-items: center;
gap: 0.5rem;
}
.chart-description {
color: var(--text-secondary-color);
font-size: 0.9rem;
margin: 0;
line-height: 1.4;
}
}
}
.reading-dna-icon {
font-size: 1.5rem;
color: rgba(79, 195, 247, 1);
}
.chart-wrapper {
position: relative;
height: 450px;
width: 100%;
margin-bottom: 2rem;
}
.personality-insights {
margin-top: 2rem;
h4 {
color: var(--text-color, #ffffff);
font-size: 1.1rem;
font-weight: 500;
margin: 0 0 1rem 0;
}
.insights-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1rem;
}
.insight-card {
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
padding: 1rem;
border: 1px solid rgba(255, 255, 255, 0.1);
.insight-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
.insight-trait {
color: var(--text-color, #ffffff);
font-weight: 500;
font-size: 0.95rem;
}
.insight-score {
font-weight: 600;
font-size: 1rem;
}
}
.insight-progress {
height: 6px;
background: rgba(255, 255, 255, 0.1);
border-radius: 3px;
overflow: hidden;
margin-bottom: 0.5rem;
.progress-bar {
height: 100%;
border-radius: 3px;
transition: width 0.3s ease;
}
}
.insight-description {
color: var(--text-secondary-color);
font-size: 0.85rem;
margin: 0;
line-height: 1.4;
}
}
}
@media (max-width: 768px) {
.chart-wrapper {
height: 350px;
}
.personality-insights {
.insights-grid {
grid-template-columns: 1fr;
}
}
}
@media (max-width: 480px) {
.chart-header {
.chart-title {
h3 {
font-size: 1rem;
}
.chart-description {
font-size: 0.8rem;
}
}
}
.chart-wrapper {
height: 300px;
}
}
@@ -0,0 +1,551 @@
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 ReadingDNAProfile {
adventurous: number;
perfectionist: number;
intellectual: number;
emotional: number;
patient: number;
social: number;
nostalgic: number;
ambitious: number;
}
interface PersonalityInsight {
trait: string;
score: number;
description: string;
color: string;
}
type ReadingDNAChartData = ChartData<'radar', number[], string>;
@Component({
selector: 'app-reading-dna-chart',
standalone: true,
imports: [CommonModule, BaseChartDirective],
templateUrl: './reading-dna-chart.component.html',
styleUrls: ['./reading-dna-chart.component.scss']
})
export class ReadingDNAChartComponent implements OnInit, OnDestroy {
private readonly bookService = inject(BookService);
private readonly destroy$ = new Subject<void>();
public readonly chartType = 'radar' as const;
public readonly chartOptions: ChartConfiguration<'radar'>['options'] = {
responsive: true,
maintainAspectRatio: false,
scales: {
r: {
beginAtZero: true,
min: 0,
max: 100,
ticks: {
stepSize: 20,
color: 'rgba(255, 255, 255, 0.6)',
font: {
family: "'Inter', sans-serif",
size: 12
},
backdropColor: 'transparent',
showLabelBackdrop: false
},
grid: {
color: 'rgba(255, 255, 255, 0.2)',
circular: true
},
angleLines: {
color: 'rgba(255, 255, 255, 0.3)'
},
pointLabels: {
color: '#ffffff',
font: {
family: "'Inter', sans-serif",
size: 12
},
padding: 25,
callback: function (label: string) {
const icons: Record<string, string> = {
'Adventurous': '🌟',
'Perfectionist': '💎',
'Intellectual': '🧠',
'Emotional': '💖',
'Patient': '🕰️',
'Social': '👥',
'Nostalgic': '📚',
'Ambitious': '🚀'
};
return [icons[label] || '', label];
}
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
enabled: true,
backgroundColor: 'rgba(0, 0, 0, 0.95)',
titleColor: '#ffffff',
bodyColor: '#ffffff',
borderColor: '#4fc3f7',
borderWidth: 2,
cornerRadius: 8,
padding: 16,
titleFont: {size: 14, weight: 'bold'},
bodyFont: {size: 12},
callbacks: {
title: (context) => {
const label = context[0]?.label || '';
return `${label} Personality`;
},
label: (context) => {
const score = context.parsed.r;
const insight = this.personalityInsights.find(i => i.trait === context.label);
return [
`Score: ${score.toFixed(1)}/100`,
'',
insight ? insight.description : 'Your reading personality trait'
];
}
}
}
},
interaction: {
intersect: false,
mode: 'point'
},
elements: {
line: {
borderWidth: 3,
tension: 0.1
},
point: {
radius: 5,
hoverRadius: 8,
borderWidth: 3,
backgroundColor: 'rgba(255, 255, 255, 0.8)'
}
}
};
private readonly chartDataSubject = new BehaviorSubject<ReadingDNAChartData>({
labels: [
'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional',
'Patient', 'Social', 'Nostalgic', 'Ambitious'
],
datasets: []
});
public readonly chartData$: Observable<ReadingDNAChartData> = this.chartDataSubject.asObservable();
public personalityInsights: PersonalityInsight[] = [];
ngOnInit(): void {
this.bookService.bookState$
.pipe(
filter(state => state.loaded),
first(),
catchError((error) => {
console.error('Error processing reading DNA data:', error);
return EMPTY;
}),
takeUntil(this.destroy$)
)
.subscribe(() => {
const profile = this.calculateReadingDNAData();
this.updateChartData(profile);
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private updateChartData(profile: ReadingDNAProfile | null): void {
try {
if (!profile) {
this.chartDataSubject.next({
labels: [],
datasets: []
});
this.personalityInsights = [];
return;
}
const data = [
profile.adventurous,
profile.perfectionist,
profile.intellectual,
profile.emotional,
profile.patient,
profile.social,
profile.nostalgic,
profile.ambitious
];
const gradientColors = [
'#ff6b9d', '#45aaf2', '#96f7d2', '#feca57',
'#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3'
];
this.chartDataSubject.next({
labels: [
'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional',
'Patient', 'Social', 'Nostalgic', 'Ambitious'
],
datasets: [{
label: 'Reading DNA Profile',
data,
backgroundColor: 'rgba(79, 195, 247, 0.2)',
borderColor: '#4fc3f7',
borderWidth: 3,
pointBackgroundColor: gradientColors,
pointBorderColor: '#ffffff',
pointBorderWidth: 3,
pointRadius: 5,
pointHoverRadius: 8,
fill: true
}]
});
this.personalityInsights = this.convertToPersonalityInsights(profile);
} catch (error) {
console.error('Error updating reading DNA chart data:', error);
}
}
private calculateReadingDNAData(): ReadingDNAProfile | null {
const currentState = this.bookService.getCurrentBookState();
if (!this.isValidBookState(currentState)) {
return null;
}
return this.analyzeReadingDNA(currentState.books!);
}
private isValidBookState(state: any): boolean {
return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0;
}
private analyzeReadingDNA(books: Book[]): ReadingDNAProfile {
if (books.length === 0) {
return this.getDefaultProfile();
}
return {
adventurous: this.calculateAdventurousScore(books),
perfectionist: this.calculatePerfectionistScore(books),
intellectual: this.calculateIntellectualScore(books),
emotional: this.calculateEmotionalScore(books),
patient: this.calculatePatienceScore(books),
social: this.calculateSocialScore(books),
nostalgic: this.calculateNostalgicScore(books),
ambitious: this.calculateAmbitiousScore(books)
};
}
private calculateAdventurousScore(books: Book[]): number {
const genres = new Set<string>();
const languages = new Set<string>();
const formats = new Set<string>();
books.forEach(book => {
book.metadata?.categories?.forEach(cat => genres.add(cat.toLowerCase()));
if (book.metadata?.language) languages.add(book.metadata.language);
formats.add(book.bookType);
});
const genreScore = Math.min(60, genres.size * 4);
const languageScore = Math.min(20, languages.size * 10);
const formatScore = Math.min(20, formats.size * 7);
return genreScore + languageScore + formatScore;
}
private calculatePerfectionistScore(books: Book[]): number {
const completedBooks = books.filter(b => b.readStatus === ReadStatus.READ);
const completionRate = completedBooks.length / books.length;
const qualityBooks = books.filter(book => {
const metadata = book.metadata;
if (!metadata) return false;
return (metadata.goodreadsRating && metadata.goodreadsRating >= 4.0) ||
(metadata.amazonRating && metadata.amazonRating >= 4.0) ||
(book.personalRating && book.personalRating >= 4);
});
const qualityRate = qualityBooks.length / books.length;
const completionScore = completionRate * 60;
const qualityScore = qualityRate * 40;
return Math.min(100, completionScore + qualityScore);
}
private calculateIntellectualScore(books: Book[]): number {
const intellectualGenres = [
'philosophy', 'science', 'history', 'biography', 'politics',
'psychology', 'sociology', 'economics', 'technology', 'mathematics',
'physics', 'chemistry', 'medicine', 'law', 'education',
'anthropology', 'archaeology', 'astronomy', 'biology', 'geology',
'linguistics', 'neuroscience', 'quantum physics', 'engineering',
'computer science', 'artificial intelligence', 'data science',
'research', 'academic', 'scholarly', 'theoretical', 'scientific',
'analytical', 'critical thinking', 'logic', 'rhetoric',
'cultural studies', 'international relations', 'diplomacy',
'public policy', 'governance', 'constitutional law', 'ethics',
'moral philosophy', 'epistemology', 'metaphysics', 'theology',
'religious studies', 'comparative religion', 'apologetics'
];
const intellectualBooks = books.filter(book => {
if (!book.metadata?.categories) return false;
return book.metadata.categories.some(cat =>
intellectualGenres.some(genre => cat.toLowerCase().includes(genre))
);
});
const longBooks = books.filter(book =>
book.metadata?.pageCount && book.metadata.pageCount > 400
);
const intellectualRate = intellectualBooks.length / books.length;
const longBookRate = longBooks.length / books.length;
return Math.min(100, (intellectualRate * 70) + (longBookRate * 30));
}
private calculateEmotionalScore(books: Book[]): number {
const emotionalGenres = [
'fiction', 'romance', 'drama', 'literary', 'contemporary',
'memoir', 'poetry', 'young adult', 'coming of age', 'family',
'love story', 'relationships', 'emotional', 'heartbreak',
'healing', 'self-help', 'personal development', 'inspirational',
'motivational', 'spiritual', 'mindfulness', 'meditation',
'grief', 'loss', 'trauma', 'recovery', 'therapy',
'women\'s fiction', 'chick lit', 'new adult', 'teen',
'childhood', 'parenting', 'motherhood', 'fatherhood',
'friendship', 'betrayal', 'forgiveness', 'redemption',
'slice of life', 'domestic fiction', 'family saga',
'generational saga', 'multicultural', 'immigrant stories',
'lgbtq+', 'queer fiction', 'feminist', 'gender studies',
'social issues', 'mental health', 'addiction', 'wellness',
'autobiography', 'personal narrative', 'diary', 'journal'
];
const emotionalBooks = books.filter(book => {
if (!book.metadata?.categories) return false;
return book.metadata.categories.some(cat =>
emotionalGenres.some(genre => cat.toLowerCase().includes(genre))
);
});
const personallyRatedBooks = books.filter(book => book.personalRating);
const emotionalRate = emotionalBooks.length / books.length;
const ratingEngagement = personallyRatedBooks.length / books.length;
return Math.min(100, (emotionalRate * 60) + (ratingEngagement * 40));
}
private calculatePatienceScore(books: Book[]): number {
const longBooks = books.filter(book =>
book.metadata?.pageCount && book.metadata.pageCount > 500
);
const seriesBooks = books.filter(book =>
book.metadata?.seriesName && book.metadata?.seriesNumber
);
const progressBooks = books.filter(book => {
const progress = Math.max(
book.epubProgress?.percentage || 0,
book.pdfProgress?.percentage || 0,
book.cbxProgress?.percentage || 0,
book.koreaderProgress?.percentage || 0,
book.koboProgress?.percentage || 0
);
return progress > 50;
});
const longBookRate = longBooks.length / books.length;
const seriesRate = seriesBooks.length / books.length;
const progressRate = progressBooks.length / books.length;
return Math.min(100, (longBookRate * 40) + (seriesRate * 35) + (progressRate * 25));
}
private calculateSocialScore(books: Book[]): number {
const popularBooks = books.filter(book => {
const metadata = book.metadata;
if (!metadata) return false;
return (metadata.goodreadsReviewCount && metadata.goodreadsReviewCount > 1000) ||
(metadata.amazonReviewCount && metadata.amazonReviewCount > 500);
});
const mainstreamGenres = [
'thriller', 'mystery', 'romance', 'fantasy', 'science fiction',
'horror', 'adventure', 'bestseller', 'contemporary', 'popular',
'crime', 'detective', 'suspense', 'action', 'espionage',
'spy', 'police procedural', 'cozy mystery', 'psychological thriller',
'domestic thriller', 'legal thriller', 'medical thriller',
'urban fantasy', 'paranormal', 'supernatural', 'magic',
'dystopian', 'post-apocalyptic', 'cyberpunk', 'space opera',
'military science fiction', 'hard science fiction', 'steampunk',
'alternate history', 'time travel', 'vampire', 'werewolf',
'zombie', 'ghost', 'gothic', 'dark fantasy', 'epic fantasy',
'sword and sorcery', 'high fantasy', 'historical romance',
'regency romance', 'western', 'sports', 'celebrity',
'entertainment', 'pop culture', 'reality tv', 'social media',
'true crime', 'celebrity biography', 'gossip', 'lifestyle',
'fashion', 'beauty', 'cooking', 'travel', 'humor',
'comedy', 'satire', 'graphic novel', 'manga', 'comic'
];
const mainstreamBooks = books.filter(book => {
if (!book.metadata?.categories) return false;
return book.metadata.categories.some(cat =>
mainstreamGenres.some(genre => cat.toLowerCase().includes(genre))
);
});
const popularRate = popularBooks.length / books.length;
const mainstreamRate = mainstreamBooks.length / books.length;
return Math.min(100, (popularRate * 50) + (mainstreamRate * 50));
}
private calculateNostalgicScore(books: Book[]): number {
const currentYear = new Date().getFullYear();
const classicThreshold = currentYear - 30;
const oldBooks = books.filter(book => {
if (!book.metadata?.publishedDate) return false;
const pubYear = new Date(book.metadata.publishedDate).getFullYear();
return pubYear < classicThreshold;
});
const classicGenres = [
'classic', 'literature', 'historical', 'vintage', 'traditional',
'heritage', 'timeless', 'canonical', 'masterpiece', 'landmark',
'seminal', 'influential', 'groundbreaking', 'pioneering',
'classical literature', 'world literature', 'nobel prize',
'pulitzer prize', 'booker prize', 'national book award',
'literary fiction', 'modernist', 'post-modernist', 'realist',
'naturalist', 'romantic', 'victorian', 'edwardian',
'renaissance', 'enlightenment', 'ancient', 'medieval',
'colonial', 'antebellum', 'gilded age', 'jazz age',
'lost generation', 'beat generation', 'harlem renaissance',
'golden age', 'silver age', 'folk tales', 'fairy tales',
'mythology', 'legends', 'folklore', 'oral tradition',
'epic poetry', 'sonnets', 'ballads', 'odes',
'dramatic works', 'shakespearean', 'greek tragedy',
'roman literature', 'biblical', 'religious classics',
'philosophical classics', 'historical classics'
];
const oldBookRate = oldBooks.length / books.length;
const classicRate = classicGenres.length / books.length;
return Math.min(100, (oldBookRate * 60) + (classicRate * 40));
}
private calculateAmbitiousScore(books: Book[]): number {
const totalBooks = books.length;
const volumeScore = Math.min(40, totalBooks * 2);
const challengingBooks = books.filter(book =>
book.metadata?.pageCount && book.metadata.pageCount > 600
);
const completedChallenging = challengingBooks.filter(book =>
book.readStatus === ReadStatus.READ
);
const challengingRate = challengingBooks.length / books.length;
const completionRate = challengingBooks.length > 0 ?
completedChallenging.length / challengingBooks.length : 0;
const challengingScore = challengingRate * 35;
const completionBonus = completionRate * 25;
return Math.min(100, volumeScore + challengingScore + completionBonus);
}
private getDefaultProfile(): ReadingDNAProfile {
return {
adventurous: 50,
perfectionist: 50,
intellectual: 50,
emotional: 50,
patient: 50,
social: 50,
nostalgic: 50,
ambitious: 50
};
}
private convertToPersonalityInsights(profile: ReadingDNAProfile): PersonalityInsight[] {
return [
{
trait: 'Adventurous',
score: profile.adventurous,
description: 'You explore diverse genres and experimental content',
color: '#ff6b9d'
},
{
trait: 'Perfectionist',
score: profile.perfectionist,
description: 'You prefer high-quality books and finish what you start',
color: '#45aaf2'
},
{
trait: 'Intellectual',
score: profile.intellectual,
description: 'You gravitate toward complex, educational material',
color: '#96f7d2'
},
{
trait: 'Emotional',
score: profile.emotional,
description: 'You connect emotionally with fiction and personal stories',
color: '#feca57'
},
{
trait: 'Patient',
score: profile.patient,
description: 'You tackle long books and complete series',
color: '#ff9ff3'
},
{
trait: 'Social',
score: profile.social,
description: 'You enjoy popular, widely-discussed books',
color: '#54a0ff'
},
{
trait: 'Nostalgic',
score: profile.nostalgic,
description: 'You appreciate classic literature and older works',
color: '#5f27cd'
},
{
trait: 'Ambitious',
score: profile.ambitious,
description: 'You challenge yourself with volume and difficulty',
color: '#00d2d3'
}
];
}
}