Files
bobinoo/src/pages/HomePage.tsx
T
Claude 4b9f1e73e3
deploy / deploy (push) Successful in 39s
Nouveau thème « Encre » (clair et sombre)
- Blanc pur et noir (noir profond et blanc en sombre), accent vert d'eau, coins droits, filets fins
- Police Epilogue (embarquée, variable) à la place d'Inter ; mentions légales à jour
- Titres de section soulignés d'un filet ; bannière d'accueil sans cadre ; « À voir » en affiches simples
- Progression des épisodes en fine barre découpée (plus de pellicule) ; billet « Reprendre » conservé
- Icône, barre du navigateur, pages légales / 404 et carte de partage aux nouvelles couleurs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
2026-11-27 21:12:08 +00:00

258 lines
12 KiB
TypeScript

import { useSocial } from '../components/social/SocialProvider'
import { t } from '../i18n'
import { Bell, CalendarDays, Dices, Plus } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { TYPE_BY_VALUE } from '../lib/constants'
import Avatar from '../components/social/Avatar'
import FriendsFeed from '../components/social/FriendsFeed'
import Poster from '../components/Poster'
import HomeHero, { ContinueCard } from '../components/HomeHero'
import { progressView } from '../lib/rewatch'
import type { Tab } from '../components/BottomNav'
import { EmptyState, LinkArrow, PageHeader, SectionTitle } from '../components/ui'
import LatestReleases from '../components/LatestReleases'
import type { SearchResult } from '../lib/catalogApi'
import { CACHE_EVENT, isCaughtUp, loadAiring, needsCheck, refreshAiring, saveAiring, trackable } from '../lib/airing'
import { useOnResume } from '../lib/onResume'
import { calendarEvents } from '../lib/releases'
import { todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
interface Props {
onOpen: (item: MediaItem) => void
onAdd: () => void
onNavigate: (tab: Tab) => void
onRoulette: () => void
/** Fiche d'un titre pas encore dans ma bibliothèque (« Dernières sorties ») */
onOpenSeed: (seed: SearchResult) => void
onCalendar: () => void
}
// Rang aléatoire par titre, tiré une fois par lancement de l'app
const shuffle = new Map<string, number>()
function shuffleRank(id: string): number {
let r = shuffle.get(id)
if (r === undefined) shuffle.set(id, (r = Math.random()))
return r
}
/** Rangée d'affiches. */
function PosterStrip({ items, onOpen }: { items: MediaItem[]; onOpen: (item: MediaItem) => void }) {
return (
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{items.map((item) => (
<button key={item.id} onClick={() => onOpen(item)} className="w-32 shrink-0 text-start">
<Poster src={item.poster} title={item.title} />
<p className="mt-2 truncate text-sm font-semibold leading-snug">{item.title}</p>
<p className="flex gap-2 truncate text-xs text-ink-3">
<span>{TYPE_BY_VALUE[item.type].label}</span>
{item.year && <span>{item.year}</span>}
</p>
</button>
))}
</div>
)
}
export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCalendar, onOpenSeed }: Props) {
const { items, loading, account, settings, patchMany } = useMedia()
const social = useSocial()
// Sorties dans les 7 prochains jours (pastille sur l'icône calendrier)
// Vérification discrète des nouveaux épisodes (au plus toutes les 12 h) : pastille du calendrier et nombre d'épisodes à jour
// Revérifié aussi au retour dans l'app : un épisode sorti entre-temps fait réapparaître la série dans « Continuer »
const airingStarted = useRef(false)
const airingRunning = useRef(false)
// Vérification des sorties en cours (au lancement) : sert à ne pas afficher une série dont on ignore encore si je suis à jour
const [checkingAiring, setCheckingAiring] = useState(() => navigator.onLine)
const latest = useRef({ items, tmdbKey: settings.tmdbKey })
latest.current = { items, tmdbKey: settings.tmdbKey }
const checkAiring = useCallback(() => {
const { items, tmdbKey } = latest.current
if (airingRunning.current) return
const cache = loadAiring()
if (!navigator.onLine || !trackable(items).some((i) => needsCheck(i, cache))) {
setCheckingAiring(false)
return
}
airingRunning.current = true
setCheckingAiring(true)
void refreshAiring(items, cache, tmdbKey)
.then((next) => {
saveAiring(next)
const patches = trackable(items).flatMap((i) => {
const info = next[i.id]
if (!info) return []
const patch: Partial<MediaItem> = {}
// Total relevé aux épisodes sortis. Aussi pour une fiche « Terminé » dont la série continue :
// sinon, une fois à jour, les nouveaux épisodes ne pouvaient plus jamais être cochés (le statut ne change pas ici)
if ((i.status !== 'termine' || !info.ended) && info.aired > (i.episodesTotal ?? 0)) patch.episodesTotal = info.aired
// Découpage par saison (nouvelle saison annoncée, ou fiche ajoutée avant le suivi par saison)
if (info.seasonSizes && info.seasonSizes.join() !== (i.seasons ?? []).join()) patch.seasons = info.seasonSizes
if (info.backdrop && !i.backdrop) patch.backdrop = info.backdrop
return Object.keys(patch).length ? [{ id: i.id, patch }] : []
})
if (patches.length) return patchMany(patches)
})
.catch(() => {})
.finally(() => {
airingRunning.current = false
setCheckingAiring(false)
})
}, [patchMany])
useEffect(() => {
if (loading || airingStarted.current) return
airingStarted.current = true
checkAiring()
}, [loading, checkAiring])
useOnResume(checkAiring, !loading)
// Séries arrivées après le lancement (synchro du compte) : on vérifie aussi leurs sorties
const unknownCount = useMemo(() => {
const cache = loadAiring()
return trackable(items).filter((i) => !cache[i.id]).length
}, [items])
useEffect(() => {
if (loading || !airingStarted.current || !unknownCount) return
const id = setTimeout(checkAiring, 800)
return () => clearTimeout(id)
}, [loading, unknownCount, checkAiring])
const [cacheVersion, setCacheVersion] = useState(0)
useEffect(() => {
const bump = () => setCacheVersion((v) => v + 1)
window.addEventListener(CACHE_EVENT, bump)
return () => window.removeEventListener(CACHE_EVENT, bump)
}, [])
const soon = useMemo(() => {
const today = todayISO()
const now = new Date()
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7)
const end = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
return calendarEvents(items).filter((e) => e.date >= today && e.date <= end).length
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, cacheVersion])
// En cours, sans les séries où j'ai tout vu en attendant le prochain épisode
const airing = useMemo(() => loadAiring(), [cacheVersion]) // eslint-disable-line react-hooks/exhaustive-deps
// Pendant la vérification, une série suivie dont on ne connaît pas encore les sorties reste masquée :
// sinon elle s'affichait puis disparaissait quelques secondes après (une fois vue « à jour »).
// Listes de l'accueil recalculées seulement quand la bibliothèque ou les sorties changent
const hideUnknown = checkingAiring || loading
// Un revisionnage en cours apparaît comme une série en cours (avec sa propre progression)
const inProgress = useMemo(
() => items.map(progressView).filter((i) => i.status === 'en_cours' && !isCaughtUp(i, airing) && !(hideUnknown && !airing[i.id] && trackable([i]).length > 0)),
[items, airing, hideUnknown],
)
// Bannière : ce que je regarde en ce moment (le plus récemment touché), sinon le prochain « à voir »
const byRecent = useMemo(() => [...inProgress].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)), [inProgress])
const firstToWatch = items.find((i) => i.status === 'a_voir')
const featured = (byRecent.length ? byRecent.slice(0, 8) : firstToWatch ? [firstToWatch] : [])
// « À voir » tiré au hasard (ordre fixé pour la session : la rangée ne bouge pas à chaque modification)
const toWatch = useMemo(
() =>
items
.filter((i) => i.status === 'a_voir')
.map((i) => ({ i, r: shuffleRank(i.id) }))
.sort((a, b) => a.r - b.r)
.slice(0, 12)
.map((x) => x.i),
[items],
)
const seeAll = <LinkArrow onClick={() => onNavigate('catalog')}>{t('home.seeAll')}</LinkArrow>
return (
<>
<PageHeader
title="Bobin"
accent="oo"
wordmark
subtitle={t('home.subtitle')}
action={
<span className="flex shrink-0 items-center gap-2">
{social.enabled && (
<button
onClick={social.openNotifications}
className="relative grid size-11 shrink-0 place-items-center rounded-full border border-line text-ink-2 transition-colors active:bg-surface-2"
aria-label={social.unread ? t('notif.unread', { count: social.unread }) : t('notif.title')}
>
<Bell size={20} />
{social.unread > 0 && (
<span className="absolute -end-1 -top-1 grid min-w-5 place-items-center rounded-full bg-accent-fill px-1 text-[10px] font-bold text-on-accent">{social.unread > 99 ? '99+' : social.unread}</span>
)}
</button>
)}
<button
onClick={onRoulette}
className="grid size-11 shrink-0 place-items-center rounded-full border border-line text-ink-2 transition-colors active:bg-surface-2"
aria-label={t('roulette.name')}
>
<Dices size={20} />
</button>
<button
onClick={onCalendar}
className="relative grid size-11 shrink-0 place-items-center rounded-full border border-line text-ink-2 transition-colors active:bg-surface-2"
aria-label={soon ? t('home.calendarSoon', { count: soon }) : t('calendar.title')}
>
<CalendarDays size={20} />
{soon > 0 && (
<span className="absolute -end-1 -top-1 grid min-w-5 place-items-center rounded-full bg-accent-fill px-1 text-[10px] font-bold text-on-accent">{soon}</span>
)}
</button>
{social.enabled && (
<button onClick={() => (social.me ? social.openProfile(social.me.username) : social.openSearch())} className="relative shrink-0 rounded-full" aria-label={t('social.myProfile')}>
<Avatar url={social.me?.avatarUrl} name={social.me?.displayName ?? '?'} size={44} />
{social.requests.length > 0 && (
<span className="absolute -end-1 -top-1 grid min-w-5 place-items-center rounded-full bg-accent-fill px-1 text-[10px] font-bold text-on-accent">{social.requests.length}</span>
)}
</button>
)}
</span>
}
/>
{!loading && items.length === 0 ? (
<>
<EmptyState
title={t('home.emptyTitle')}
text={account ? t('home.emptyCloud') : t('home.emptyLocal')}
action={
<button onClick={onAdd} className="btn btn-primary">
<Plus size={18} /> {t('nav.addTitle')}
</button>
}
/>
<FriendsFeed />
</>
) : (
<>
{featured.length > 0 && <HomeHero items={featured} onOpen={onOpen} />}
{inProgress.length > 0 && (
<>
<SectionTitle>{t('homeHero.continueRow')}</SectionTitle>
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{[...inProgress]
.sort((x, y) => y.updatedAt.localeCompare(x.updatedAt))
.map((item) => (
<ContinueCard key={item.id} item={item} onOpen={onOpen} />
))}
</div>
</>
)}
<FriendsFeed />
{toWatch.length > 0 && (
<>
<SectionTitle action={seeAll}>{t('status.a_voir')}</SectionTitle>
<PosterStrip items={toWatch} onOpen={onOpen} />
</>
)}
<LatestReleases onOpenSeed={onOpenSeed} />
</>
)}
</>
)
}