diff --git a/src/components/Disagreements.tsx b/src/components/Disagreements.tsx deleted file mode 100644 index 9c603ff..0000000 --- a/src/components/Disagreements.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import { t } from '../i18n' -import { Loader2, RefreshCw } from 'lucide-react' -import { useMemo, useState } from 'react' -import { fetchPublicRatings, missingPublic } from '../lib/publicRatings' -import { cx, formatRating } from '../lib/utils' -import { useMedia } from '../store' -import type { MediaItem, RatingScale } from '../types' -import Poster from './Poster' -import { SectionTitle } from './ui' - -/** Écart signé, arrondi au dixième dans l'échelle choisie (« 0 » plutôt que « +0,0 »). */ -const signed = (v: number, scale: RatingScale) => { - const r = Math.round((scale === '5' ? v / 2 : v) * 10) / 10 - if (r === 0) return '0' - return `${r > 0 ? '+' : '−'}${String(Math.abs(r)).replace('.', t('common.decimalSep'))}` -} - -function Row({ item, scale }: { item: MediaItem; scale: RatingScale }) { - const gap = item.rating! - item.publicRating! - // barre centrée : moitié gauche = moins aimé, moitié droite = plus aimé (écart max affiché : 5 points /10) - const width = Math.min(50, (Math.abs(gap) / 5) * 50) - return ( -
  • -
    - -
    -
    -

    {item.title}

    -

    - {t('public.me')} {formatRating(item.rating, scale)} · {t('public.label')} {formatRating(item.publicRating, scale)} -

    -
    - - = 0 ? 'bg-accent' : 'bg-ink-3')} - style={gap >= 0 ? { left: '50%', width: `${width}%` } : { right: '50%', width: `${width}%` }} - /> -
    -
    - = 0 ? 'text-accent' : 'text-ink-2')}>{signed(gap, scale)} -
  • - ) -} - -/** Stats « Moi vs le public » : écarts entre mes notes et la moyenne TMDB / AniList. */ -export default function Disagreements({ scoped }: { scoped: MediaItem[] }) { - const { items, settings, patchMany } = useMedia() - const scale = settings.ratingScale - const [progress, setProgress] = useState<[number, number]>() - const [message, setMessage] = useState() - - const compared = useMemo(() => scoped.filter((i) => i.rating != null && i.publicRating != null), [scoped]) - const rated = useMemo(() => items.filter((i) => i.rating != null), [items]) - const missing = useMemo(() => missingPublic(rated, settings.tmdbKey).length, [rated, settings.tmdbKey, progress]) - - const run = async () => { - if (!navigator.onLine) return setMessage(t('common.offline')) - setMessage(undefined) - setProgress([0, missing]) - try { - const patches = await fetchPublicRatings(rated, settings.tmdbKey, (done, total) => setProgress([done, total])) - if (patches.length) await patchMany(patches) - setMessage(patches.length ? t('public.added', { count: patches.length }) : t('public.noneFound')) - } finally { - setProgress(undefined) - } - } - - const gaps = compared.map((i) => i.rating! - i.publicRating!) - const avg = gaps.length ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0 - const agree = gaps.length ? Math.round((gaps.filter((g) => Math.abs(g) <= 1).length / gaps.length) * 100) : 0 - const sorted = [...compared].sort((a, b) => b.rating! - b.publicRating! - (a.rating! - a.publicRating!)) - const loved = sorted.filter((i) => i.rating! - i.publicRating! >= 1).slice(0, 5) - const hated = sorted.filter((i) => i.rating! - i.publicRating! <= -1).reverse().slice(0, 5) - - const fetchButton = - missing > 0 || progress ? ( - - ) : undefined - - return ( - <> - {t('public.title')} - {message &&

    {message}

    } - - {compared.length === 0 ? ( -

    - {missing > 0 - ? t('public.hintFetch') - : settings.tmdbKey - ? t('public.hintNone') - : t('public.hintKey')} -

    - ) : ( - <> -
    -
    -
    {t('public.avgGap')}
    -
    = 0.3 && 'text-accent')}>{signed(avg, scale)}
    -
    {Math.abs(avg) < 0.3 ? t('public.average') : avg > 0 ? t('public.generous') : t('public.harsh')}
    -
    -
    -
    {t('public.agreeTitle')}
    -
    {agree} %
    -
    - {scale === '5' ? t('public.within5', { count: compared.length }) : t('public.within10', { count: compared.length })} -
    -
    -
    - - {loved.length > 0 && ( -
    -

    - {t('public.lovedPre')}{t('public.lovedAccent')}{t('public.lovedPost')} -

    - -
    - )} - {hated.length > 0 && ( -
    -

    - {t('public.hatedPre')}{t('public.hatedAccent')}{t('public.hatedPost')} -

    - -
    - )} - {!loved.length && !hated.length &&

    {t('public.allAgree')}

    } - - )} - - ) -} diff --git a/src/lib/publicRatings.ts b/src/lib/publicRatings.ts deleted file mode 100644 index 6f69084..0000000 --- a/src/lib/publicRatings.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { MediaInput, MediaItem } from '../types' -import { getAniListPublicRatings, getTmdbPublicRating } from './catalogApi' -import { isSafeExternalId, readStorage } from './security' - -/** - * Récupère la note moyenne du public (TMDB / AniList) pour les fiches qui n'en ont pas. - * Les titres sans note fiable (trop peu de votes) sont mémorisés pour ne pas être redemandés à chaque fois. - */ - -const CHECKED_KEY = 'azuucine:public-checked' -const RECHECK_MS = 30 * 24 * 3600 * 1000 - -function loadChecked(): Record { - const raw = readStorage(CHECKED_KEY, {}) - const out: Record = {} - if (raw && typeof raw === 'object' && !Array.isArray(raw)) { - for (const [k, v] of Object.entries(raw as Record)) if (typeof v === 'number') out[k] = v - } - return out -} - -function saveChecked(c: Record) { - try { - localStorage.setItem(CHECKED_KEY, JSON.stringify(c)) - } catch { - /* ignore */ - } -} - -/** Fiches notées par moi, reliées à une base, sans note publique (et pas vérifiées récemment). */ -export function missingPublic(items: MediaItem[], tmdbKey?: string): MediaItem[] { - const checked = loadChecked() - const now = Date.now() - return items.filter( - (i) => - i.publicRating == null && - isSafeExternalId(i.externalId) && - (i.externalId.startsWith('anilist:') || !!tmdbKey) && - !(checked[i.id] && now - checked[i.id] < RECHECK_MS), - ) -} - -export async function fetchPublicRatings( - items: MediaItem[], - tmdbKey: string | undefined, - onProgress?: (done: number, total: number) => void, -): Promise<{ id: string; patch: Partial }[]> { - const todo = missingPublic(items, tmdbKey).slice(0, 400) - const patches: { id: string; patch: Partial }[] = [] - const checked = loadChecked() - let done = 0 - const total = todo.length - - const ani = todo.filter((i) => i.externalId!.startsWith('anilist:')) - if (ani.length) { - try { - const map = await getAniListPublicRatings(ani.map((i) => Number(i.externalId!.split(':')[1]))) - for (const i of ani) { - const r = map.get(Number(i.externalId!.split(':')[1])) - if (r) patches.push({ id: i.id, patch: { publicRating: r } }) - checked[i.id] = Date.now() - } - } catch { - /* réseau : on réessaiera */ - } - done += ani.length - onProgress?.(done, total) - } - - if (tmdbKey) { - const tmdb = todo.filter((i) => i.externalId!.startsWith('tmdb:')) - for (let k = 0; k < tmdb.length; k += 4) { - await Promise.all( - tmdb.slice(k, k + 4).map(async (i) => { - try { - const r = await getTmdbPublicRating(i.externalId!, tmdbKey) - if (r) patches.push({ id: i.id, patch: { publicRating: r } }) - checked[i.id] = Date.now() - } catch { - /* ignore ce titre */ - } - }), - ) - done += tmdb.slice(k, k + 4).length - onProgress?.(done, total) - } - } - saveChecked(checked) - return patches -} diff --git a/src/pages/StatsPage.tsx b/src/pages/StatsPage.tsx index 75dae72..52df023 100644 --- a/src/pages/StatsPage.tsx +++ b/src/pages/StatsPage.tsx @@ -1,429 +1,14 @@ -import { genreLabel } from '../lib/genres' -import { locale, t } from '../i18n' -import { Star } from 'lucide-react' -import { useMemo, useState, type ReactNode } from 'react' -import Disagreements from '../components/Disagreements' -import Poster from '../components/Poster' -import { EmptyState, PageHeader, SectionTitle } from '../components/ui' -import { MEDIA_TYPES, STATUSES } from '../lib/constants' -import { availableYears, computeStats, countries, itemsForPeriod, monthly, records, watchMinutes } from '../lib/stats' -import { cx, formatDuration, formatRating } from '../lib/utils' -import { useMedia } from '../store' -import type { MediaItem, MediaType } from '../types' - -/** Couleurs des types (palette catégorielle validée pour fond sombre, ordre fixe). */ -const TYPE_COLORS: Record = { - film: '#3987e5', - serie: '#d95926', - anime: '#199e70', - kdrama: '#c98500', - cdrama: '#d55181', - autre: '#008300', -} - -type Tab = 'overview' | 'habits' | 'tastes' -const TABS: { value: Tab; readonly label: string }[] = [ - { value: 'overview', get label() { return t('stats.overview') } }, - { value: 'habits', get label() { return t('stats.habits') } }, - { value: 'tastes', get label() { return t('stats.tastes') } }, -] - -const fmtInt = (n: number) => n.toLocaleString(locale()) - -/** Colonnes verticales d'une seule couleur ; toucher une colonne affiche sa valeur. */ -function Columns({ - data, - format, - height = 140, - selected, - onSelect, -}: { - data: { key: string; label: string; value: number }[] - format: (v: number) => string - height?: number - selected?: string - onSelect: (key: string) => void -}) { - const max = Math.max(1, ...data.map((d) => d.value)) - return ( -
    -
    - {data.map((d) => { - const on = d.key === selected - return ( - - ) - })} -
    -
    - {data.map((d) => ( - - {d.label} - - ))} -
    -
    - ) -} - -function Tile({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) { - return ( -
    -
    {label}
    -
    {value}
    - {hint &&
    {hint}
    } -
    - ) -} - -function MiniPoster({ item, caption }: { item: MediaItem; caption: string }) { - return ( -
    -
    - -
    -
    -

    {item.title}

    -

    {caption}

    -
    -
    - ) -} +import { t } from '../i18n' +import { PageHeader } from '../components/ui' +/** Statistiques : en cours de refonte complète. */ export default function StatsPage() { - const { items, settings, loading } = useMedia() - const scale = settings.ratingScale - const years = useMemo(() => availableYears(items), [items]) - const [year, setYear] = useState('') - const [tab, setTab] = useState('overview') - const [metric, setMetric] = useState<'count' | 'minutes'>('count') - const [month, setMonth] = useState() - const [ratingBin, setRatingBin] = useState() - - const scoped = useMemo(() => itemsForPeriod(items, year), [items, year]) - const s = useMemo(() => computeStats(scoped), [scoped]) - const months = useMemo(() => monthly(items, year), [items, year]) - const geo = useMemo(() => countries(scoped), [scoped]) - const rec = useMemo(() => records(scoped), [scoped]) - - if (loading) return - if (items.length === 0) { - return ( - <> - - - - ) - } - - const hours = Math.round(s.totalMinutes / 60) - const days = s.totalMinutes / 1440 - const typeTotal = s.byType.reduce((sum, bt) => sum + bt.minutes, 0) - const typeRows = s.byType.filter((bt) => bt.value > 0).sort((a, b) => b.minutes - a.minutes) - - // Mois sélectionné par défaut : le plus chargé - const busiest = months.reduce((best, m) => (m[metric] > best[metric] ? m : best), months[0]) - const shownMonth = months.find((m) => m.key === month) ?? busiest - - // Histogramme des notes - const ratingCols = - scale === '5' - ? s.ratingBuckets.map((v, i) => ({ key: String(i), label: formatRating(i + 1, '5'), value: v })) - : s.ratingBuckets.map((v, i) => ({ key: String(i), label: String(i + 1), value: v })) - const shownRating = ratingCols.find((c) => c.key === ratingBin) ?? ratingCols.reduce((a, b) => (b.value > a.value ? b : a), ratingCols[0]) - - const maxGenre = Math.max(1, ...s.topGenres.map((g) => g.value)) - const maxCountry = Math.max(1, ...geo.list.map((c) => c.count)) - const periodLabel = year || t('stats.sinceStart') - return ( <> - - - {/* Période + onglets, collants en haut */} -
    -
    - {['', ...years].map((y) => ( - - ))} -
    -
    - {TABS.map((tb) => ( - - ))} -
    + +
    +

    Soon

    - - {tab === 'overview' && ( - <> - {/* Le grand chiffre */} -
    - {t('home.screenTime')} · {periodLabel} -
    - {fmtInt(hours)} - {t('stats.hours', { count: hours })} -
    -

    - {t('stats.nonStopPre')} - {days >= 1 ? t('stats.days', { count: Math.round(days) }) : formatDuration(s.totalMinutes)} - {t('stats.nonStopPost')} - {' · '} - {t('stats.finishedN', { count: s.completed })} · {t('stats.episodesN', { count: s.episodesWatched })} -

    -
    - - {/* Répartition par type : barre empilée + légende */} - {t('stats.timeByType')} - {typeTotal > 0 ? ( - <> -
    - {typeRows.map((row) => - row.minutes > 0 ? ( - - ) : null, - )} -
    -
      - {typeRows.map((row) => ( -
    • - - {row.label} - {t('journal.seen', { count: row.completed })} - {formatDuration(row.minutes)} - {Math.round((row.minutes / typeTotal) * 100)} % -
    • - ))} -
    - - ) : ( -

    {t('stats.noTime')}

    - )} - -
    - - - {formatRating(Math.round(s.avgRating * 10) / 10, scale)} - /{scale} - - ) : ( - '—' - ) - } - hint={t('stats.rated', { count: s.ratedCount })} - /> - -
    - - {/* Statuts en pastilles */} - {t('stats.statuses')} -
    - {s.byStatus.map((st) => ( -
    -
    {st.value}
    -
    {STATUSES.find((x) => x.value === st.status)?.label}
    -
    - ))} -
    - - )} - - {tab === 'habits' && ( - <> - - {(['count', 'minutes'] as const).map((m) => ( - - ))} -
    - } - > - {year ? t('stats.monthByMonth', { year }) : t('stats.last12')} - -
    -

    - {new Date(`${shownMonth.key}-15T12:00:00`).toLocaleDateString(locale(), { month: 'long', year: 'numeric' })} - - {' · '} - {t('stats.monthFinished', { count: shownMonth.count })} · {formatDuration(shownMonth.minutes)} - -

    - ({ key: m.key, label: m.initial, value: metric === 'count' ? m.count : m.minutes }))} - format={(v) => (metric === 'count' ? t('account.nTitles', { count: v }) : formatDuration(v))} - selected={shownMonth.key} - onSelect={setMonth} - /> - {busiest[metric] > 0 && ( -

    - {t('stats.busiest')} {new Date(`${busiest.key}-15T12:00:00`).toLocaleDateString(locale(), { month: 'long', year: 'numeric' })} -

    - )} -
    - - {t('stats.records')} -
    - {rec.marathon && ( -
    - {t('stats.marathon')} -
    - -
    -
    - )} - {rec.longestFilm && ( -
    - {t('stats.longestFilm')} -
    - -
    -
    - )} - {!rec.marathon && !rec.longestFilm &&

    {t('stats.noRecords')}

    } -
    - - {s.topPlatforms.length > 0 && ( - <> - {t('stats.platforms')} -
    - {s.topPlatforms.map((p, i) => ( - - {p.label} - {p.value} - - ))} -
    - - )} - - )} - - {tab === 'tastes' && ( - <> - {rec.bestRated && rec.bestRated.length > 0 && ( - <> - {t('stats.bestRated')} · {periodLabel} -
    - {rec.bestRated.map((item) => ( -
    - -

    {item.title}

    -

    - - {formatRating(item.rating, scale)} -

    -
    - ))} -
    - - )} - - {t('stats.myRatings')} - {s.ratedCount > 0 ? ( -
    -

    - {t('account.nTitles', { count: shownRating.value })} - {t('stats.ratedAs', { count: shownRating.value, rating: `${shownRating.label}${scale === '5' ? ' ★' : '/10'}` })} -

    - t('account.nTitles', { count: v })} height={110} selected={shownRating.key} onSelect={setRatingBin} /> -
    - ) : ( -

    {t('stats.noRatings')}

    - )} - - - - {t('stats.favGenres')} - {s.topGenres.length ? ( -
    - {s.topGenres.map((g, i) => { - const r = g.value / maxGenre - return ( - 0.6 ? 'text-ink' : 'text-ink-2')} - style={{ fontSize: `${0.85 + r * 1.15}rem` }} - title={t('account.nTitles', { count: g.value })} - > - {genreLabel(g.label)} - {g.value} - - ) - })} -
    - ) : ( -

    {t('stats.noGenres')}

    - )} - - {t('stats.countries')} - {geo.list.length ? ( -
      - {geo.list.slice(0, 8).map((c) => ( -
    • - {c.flag} - {c.name} - - - - {c.count} -
    • - ))} -
    - ) : null} - {geo.missing > 0 && ( -

    - {geo.list.length === 0 ? t('stats.noCountryLegacy', { count: geo.missing }) : t('stats.noCountry', { count: geo.missing })} -

    - )} - - {t('stats.byType')} -
    - {MEDIA_TYPES.map((mt) => { - const row = s.byType.find((b) => b.type === mt.value)! - return ( -
    - -
    {row.value}
    -
    {mt.label}
    -
    - ) - })} -
    - - )} - -

    - {t('stats.footnote')} -

    ) }