Images d'épisodes et fiches affichées tout de suite
deploy / deploy (push) Successful in 45s

- Épisodes d'une saison gardés sur l'appareil (titres, dates, images) : la liste s'affiche dès l'ouverture, rafraîchie en arrière-plan après 12 h
- Images des épisodes autour du prochain à voir demandées tout de suite (plus en « paresseux ») et préchargées
- Préchargement au toucher d'une série en cours : saison en cours et images des épisodes suivants (data-prefetch-season / -ep)
- lazyPreload : un écran préchargé (fiche, stats, réglages, profils…) s'affiche sans l'attente d'environ 300 ms que React.lazy imposait à la première ouverture
- L'administration n'est plus préchargée pour tout le monde

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-11-29 15:53:45 +00:00
1 parent 11d4de5894
commit ac27542947
12 files changed
+261 -97

No files matched your search

+20 -28
View File
@@ -1,42 +1,34 @@
import { preloadSocial, SocialProvider } from './components/social/SocialProvider'
import { ToastProvider } from './components/Toast'
import { lazy, Suspense, useCallback, useEffect, useState } from 'react'
import { Suspense, useCallback, useEffect, useState } from 'react'
import BottomNav, { type Tab } from './components/BottomNav'
import SideNav from './components/SideNav'
import HomePage from './pages/HomePage'
import CatalogPage from './pages/CatalogPage'
import CatalogPage, { preloadCatalogViews } from './pages/CatalogPage'
import { lazyPreload } from './lib/lazyPreload'
import SyncIndicator from './components/SyncIndicator'
import { useMedia } from './store'
import { prefetchTitle, setPrefetchKey, type SearchResult } from './lib/catalogApi'
import type { MediaItem } from './types'
import type { Completion } from './lib/seasons'
// Écrans moins fréquents : chargés à la demande (démarrage plus léger), puis préchargés quand l'app est au repos
const loaders = {
// Fiche d'un titre et recherche pour ajouter : les plus utilisés, préchargés dès que l'app est au repos
TitleSheet: () => import('./components/title/TitleSheet'),
AddTitle: () => import('./components/title/AddTitle'),
EditDetails: () => import('./components/title/EditDetails'),
PersonSheet: () => import('./components/person/PersonSheet'),
Roulette: () => import('./components/Roulette'),
CalendarView: () => import('./components/CalendarView'),
StatsPage: () => import('./pages/StatsPage'),
SettingsPage: () => import('./pages/SettingsPage'),
AdminPage: () => import('./pages/AdminPage'),
NotFoundPage: () => import('./pages/NotFoundPage'),
}
const TitleSheet = lazy(loaders.TitleSheet)
const AddTitle = lazy(loaders.AddTitle)
const EditDetails = lazy(loaders.EditDetails)
const PersonSheet = lazy(loaders.PersonSheet)
const Roulette = lazy(loaders.Roulette)
const CalendarView = lazy(loaders.CalendarView)
const StatsPage = lazy(loaders.StatsPage)
const SettingsPage = lazy(loaders.SettingsPage)
const AdminPage = lazy(loaders.AdminPage)
const NotFoundPage = lazy(loaders.NotFoundPage)
// Écrans chargés à la demande (démarrage plus léger), puis préchargés quand l'app est au repos.
// lazyPreload : un écran préchargé s'affiche sans aucune attente (React.lazy seul le retardait d'environ 300 ms).
const TitleSheet = lazyPreload(() => import('./components/title/TitleSheet'))
const AddTitle = lazyPreload(() => import('./components/title/AddTitle'))
const EditDetails = lazyPreload(() => import('./components/title/EditDetails'))
const PersonSheet = lazyPreload(() => import('./components/person/PersonSheet'))
const Roulette = lazyPreload(() => import('./components/Roulette'))
const CalendarView = lazyPreload(() => import('./components/CalendarView'))
const StatsPage = lazyPreload(() => import('./pages/StatsPage'))
const SettingsPage = lazyPreload(() => import('./pages/SettingsPage'))
const NotFoundPage = lazyPreload(() => import('./pages/NotFoundPage'))
// Administration : réservée aux admins, jamais préchargée
const AdminPage = lazyPreload(() => import('./pages/AdminPage'))
function preloadScreens() {
for (const load of Object.values(loaders)) void load().catch(() => {})
// Les plus utilisés d'abord
for (const screen of [TitleSheet, AddTitle, StatsPage, SettingsPage, PersonSheet, CalendarView, Roulette, EditDetails, NotFoundPage]) void screen.preload().catch(() => {})
preloadCatalogViews()
preloadSocial()
}
@@ -74,7 +66,7 @@ export default function App() {
const onPointer = (e: PointerEvent) => {
if (e.type === 'pointerover' && e.pointerType !== 'mouse') return
const el = e.target instanceof Element ? e.target.closest('[data-prefetch]') : null
if (el) prefetchTitle(el.getAttribute('data-prefetch'))
if (el) prefetchTitle(el.getAttribute('data-prefetch'), Number(el.getAttribute('data-prefetch-season')) || undefined, Number(el.getAttribute('data-prefetch-ep')) || undefined)
}
document.addEventListener('pointerdown', onPointer, { capture: true, passive: true })
document.addEventListener('pointerover', onPointer, { passive: true })
+23 -9
View File
@@ -1,7 +1,7 @@
import { Check, Loader2, Lock } from 'lucide-react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { locale, t } from '../i18n'
import { getTmdbSeasonEpisodes, type EpisodeInfo } from '../lib/catalogApi'
import { cachedSeasonEpisodes, episodeWindow, getTmdbSeasonEpisodes, preloadImages, type EpisodeInfo } from '../lib/catalogApi'
import { episodeCap, episodesBeforeSeason, seasonPosition } from '../lib/franchise'
import { tmdbSized } from '../lib/tmdbImage'
import { cx, todayISO } from '../lib/utils'
@@ -35,7 +35,8 @@ export default function EpisodeList({ form, aired, onChange, fallbackImage }: Pr
if (current) setViewSeason(current)
}, [current])
const viewSeason = seasons ? Math.min(Math.max(1, picked), seasons.length) : 1
const [episodes, setEpisodes] = useState<EpisodeInfo[]>()
// Liste reçue pour une saison donnée ; en attendant, la copie gardée sur l'appareil s'affiche tout de suite
const [fetched, setFetched] = useState<{ key: string; list: EpisodeInfo[] }>()
const [loading, setLoading] = useState(false)
const listRef = useRef<HTMLDivElement>(null)
const today = todayISO()
@@ -49,23 +50,36 @@ export default function EpisodeList({ form, aired, onChange, fallbackImage }: Pr
const extra = seasons && viewSeason === seasons.length ? Math.max(0, (episodeCap(form) ?? 0) - episodesBeforeSeason(seasons, seasons.length + 1)) : 0
const size = seasons ? Math.min((seasons[viewSeason - 1] ?? 0) + extra, MAX_GENERIC) : Math.min(episodeCap(form) ?? 0, MAX_GENERIC)
const seasonNum = seasons ? viewSeason : 1
const listKey = `${form.externalId}:${seasonNum}`
const known = isTmdb ? cachedSeasonEpisodes(form.externalId, seasonNum) : undefined
const shownList = fetched?.key === listKey ? fetched.list : known
const episodes = shownList?.length ? shownList : undefined
useEffect(() => {
if (!isTmdb || !navigator.onLine) return setEpisodes(undefined)
if (!isTmdb || !navigator.onLine) return
let alive = true
setLoading(true)
getTmdbSeasonEpisodes(form.externalId!, seasons ? viewSeason : 1, key!)
.then((list) => alive && setEpisodes(list.length ? list : undefined))
.catch(() => alive && setEpisodes(undefined))
// Indicateur seulement quand rien n'est encore affiché (sinon la liste gardée est remplacée sans bruit)
if (!cachedSeasonEpisodes(form.externalId, seasonNum)?.length) setLoading(true)
getTmdbSeasonEpisodes(form.externalId!, seasonNum, key!)
.then((list) => alive && setFetched({ key: `${form.externalId}:${seasonNum}`, list }))
.catch(() => {})
.finally(() => alive && setLoading(false))
return () => {
alive = false
}
}, [isTmdb, form.externalId, viewSeason, seasons, key])
}, [isTmdb, form.externalId, seasonNum, key])
// Les infos TMDB complètent la liste ; sans elles (AniList, hors-ligne), on numérote simplement
const count = Math.max(size, seasons ? 0 : (episodes?.length ?? 0))
const rows: EpisodeInfo[] = Array.from({ length: count }, (_, k) => episodes?.find((e) => e.number === k + 1) ?? { number: k + 1 })
const watchedHere = Math.max(0, Math.min(count, form.episodesWatched - before))
// Épisodes visibles à l'ouverture (autour du prochain à voir) : images demandées tout de suite
const visible = new Set(episodeWindow(rows, watchedHere + 1).map((e) => e.number))
useEffect(() => {
if (episodes) preloadImages(episodeWindow(episodes, watchedHere + 1).map((e) => e.still))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [episodes])
// Ouvre la liste au niveau du prochain épisode à voir
useLayoutEffect(() => {
@@ -129,7 +143,7 @@ export default function EpisodeList({ form, aired, onChange, fallbackImage }: Pr
>
<span className="relative aspect-video w-28 shrink-0 overflow-hidden rounded-lg border border-line bg-surface-2">
{e.still ? (
<img src={e.still} alt="" loading="lazy" className="size-full object-cover" />
<img src={e.still} alt="" loading={visible.has(e.number) ? 'eager' : 'lazy'} decoding="async" className="size-full object-cover" />
) : fallbackImage ? (
// Pas d'image pour cet épisode : celle de la série, assombrie, avec le numéro par-dessus
<>
+4 -3
View File
@@ -13,6 +13,7 @@ import { useMedia } from '../store'
import { useToast } from './Toast'
import { FilmStrip } from './ui'
import type { MediaItem } from '../types'
import { prefetchAttrs } from '../lib/prefetch'
/** Où j'en suis : « S2 · É3 » (épisode suivant à voir) */
export function nextEpisodeLabel(item: MediaItem): string | undefined {
@@ -110,7 +111,7 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
if (Math.abs(dx) > 45) go(current + (dx < 0 ? 1 : -1))
}}
>
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="relative block aspect-video w-full overflow-hidden bg-surface-2 lg:aspect-auto lg:h-full lg:min-h-[22rem]" aria-label={t('card.open', { title: item.title })}>
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="relative block aspect-video w-full overflow-hidden bg-surface-2 lg:aspect-auto lg:h-full lg:min-h-[22rem]" aria-label={t('card.open', { title: item.title })}>
{items.map((it, k) => {
const image = it.backdrop ?? it.poster
return image ? (
@@ -164,7 +165,7 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
<Check size={17} /> {waitingLabel(item)}
</span>
) : null}
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="btn btn-ghost px-4">
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="btn btn-ghost px-4">
<Info size={17} /> {t('homeHero.details')}
</button>
</div>
@@ -196,7 +197,7 @@ export function ContinueCard({ item, onOpen }: { item: MediaItem; onOpen: (item:
return (
<article className="flex h-[5.5rem] w-72 shrink-0 overflow-hidden rounded-md border border-line bg-surface">
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-stretch text-start" aria-label={t('card.open', { title: item.title })}>
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-stretch text-start" aria-label={t('card.open', { title: item.title })}>
<span className="block w-[3.6rem] shrink-0 bg-surface-2">{image && <img src={image} alt="" loading="lazy" className="size-full object-cover" />}</span>
<span className="flex min-w-0 flex-1 flex-col justify-center px-3">
<span className="block truncate font-bold text-base leading-tight">{item.title}</span>
+2 -1
View File
@@ -8,6 +8,7 @@ import type { MediaItem } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
import { EmptyState } from './ui'
import { prefetchAttrs } from '../lib/prefetch'
type Kind = 'fini' | 'revu' | 'commence' | 'abandonne'
@@ -90,7 +91,7 @@ export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => v
const d = new Date(e.date + 'T12:00:00')
return (
<li key={e.item.id + e.date + e.kind}>
<button data-prefetch={e.item.externalId} onClick={() => onOpen(e.item)} className="flex w-full items-center gap-3 py-2.5 text-start">
<button {...prefetchAttrs(e.item)} onClick={() => onOpen(e.item)} className="flex w-full items-center gap-3 py-2.5 text-start">
<span className="w-9 shrink-0 text-center">
<span className="block text-xl font-bold leading-none tabular-nums">{d.getDate()}</span>
<span className="block text-[10px] text-ink-3">{d.toLocaleDateString(locale(), { weekday: 'short' }).replace('.', '')}</span>
+3 -2
View File
@@ -10,6 +10,7 @@ import type { MediaItem } from '../types'
import { StatusPill, TypeBadge } from './Badges'
import Poster from './Poster'
import { RatingBadge } from './Rating'
import { prefetchAttrs } from '../lib/prefetch'
function Progress({ item }: { item: MediaItem }) {
const cap = episodeCap(item)
@@ -52,7 +53,7 @@ export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: Media
return (
<article>
<div className="relative">
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="block w-full" aria-label={t('card.open', { title: item.title })}>
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="block w-full" aria-label={t('card.open', { title: item.title })}>
<Poster src={item.poster} title={item.title} />
</button>
<TypeBadge item={item} className="pointer-events-none absolute start-2 top-2 border-transparent bg-bg/85" />
@@ -69,7 +70,7 @@ export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: Media
</button>
)}
</div>
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="block w-full text-start">
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="block w-full text-start">
<h3 className="mt-2.5 line-clamp-2 font-sans text-sm font-semibold leading-snug tracking-normal">{item.title}</h3>
<div className="mt-1 flex items-center justify-between gap-2">
<StatusPill status={item.status} />
+4 -3
View File
@@ -11,6 +11,7 @@ import { RatingBadge } from './Rating'
import TopFiveEditor from './TopFiveEditor'
import SharePreview from './SharePreview'
import { LinkArrow, SectionTitle } from './ui'
import { prefetchAttrs } from '../lib/prefetch'
/** Chiffre géant en contour (rouge pour le n°1, gris pour les autres). */
function RankNumber({ rank, big }: { rank: number; big?: boolean }) {
@@ -110,7 +111,7 @@ export default function TopFive({ onOpen, items: others }: { onOpen: (item: Medi
<RankNumber rank={1} big />
</span>
{first ? (
<button data-prefetch={first.externalId} onClick={() => onOpen(first)} className="relative z-10 w-32 lg:w-40">
<button {...prefetchAttrs(first)} onClick={() => onOpen(first)} className="relative z-10 w-32 lg:w-40">
<Poster src={first.poster} title={first.title} />
</button>
) : (
@@ -121,7 +122,7 @@ export default function TopFive({ onOpen, items: others }: { onOpen: (item: Medi
<span className="eyebrow text-accent">{t('top.number', { rank: 1 })} · {current.plural}</span>
{first ? (
<>
<button data-prefetch={first.externalId} onClick={() => onOpen(first)} className="mt-1.5 block text-start text-lg font-bold leading-snug">
<button {...prefetchAttrs(first)} onClick={() => onOpen(first)} className="mt-1.5 block text-start text-lg font-bold leading-snug">
{first.title}
</button>
<div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-ink-3">
@@ -149,7 +150,7 @@ export default function TopFive({ onOpen, items: others }: { onOpen: (item: Medi
</span>
<div className="relative z-10 ms-4">
{item ? (
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="block w-full">
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="block w-full">
<Poster src={item.poster} title={item.title} />
</button>
) : (
+13 -22
View File
@@ -1,4 +1,5 @@
import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { createContext, Suspense, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { lazyPreload } from '../../lib/lazyPreload'
import { cachedMyProfile, getFollowRequests, getMyProfile, unreadNotifications, type Profile, type ProfileCard } from '../../lib/cloud/social'
import { useMedia } from '../../store'
import type { MediaItem } from '../../types'
@@ -37,28 +38,18 @@ interface SocialApi {
bumpShared: () => void
}
// Écrans sociaux chargés à la demande (préchargés par App au repos via preloadSocial)
const socialLoaders = {
NotificationsSheet: () => import('./NotificationsSheet'),
EditProfile: () => import('./EditProfile'),
FollowList: () => import('./FollowList'),
PeopleSearch: () => import('./PeopleSearch'),
ProfileView: () => import('./ProfileView'),
TitleReviews: () => import('./TitleReviews'),
ItemPeek: () => import('./ItemPeek'),
SharedLists: () => import('./SharedLists'),
}
const NotificationsSheet = lazy(socialLoaders.NotificationsSheet)
const EditProfile = lazy(socialLoaders.EditProfile)
const FollowList = lazy(socialLoaders.FollowList)
const PeopleSearch = lazy(socialLoaders.PeopleSearch)
const ProfileView = lazy(socialLoaders.ProfileView)
const TitleReviews = lazy(socialLoaders.TitleReviews)
const ItemPeek = lazy(socialLoaders.ItemPeek)
const SharedListSheet = lazy(() => socialLoaders.SharedLists().then((m) => ({ default: m.SharedListSheet })))
const InvitePeople = lazy(() => socialLoaders.SharedLists().then((m) => ({ default: m.InvitePeople })))
// Écrans sociaux chargés à la demande (préchargés par App au repos via preloadSocial ; affichés sans attente une fois préchargés)
const NotificationsSheet = lazyPreload(() => import('./NotificationsSheet'))
const EditProfile = lazyPreload(() => import('./EditProfile'))
const FollowList = lazyPreload(() => import('./FollowList'))
const PeopleSearch = lazyPreload(() => import('./PeopleSearch'))
const ProfileView = lazyPreload(() => import('./ProfileView'))
const TitleReviews = lazyPreload(() => import('./TitleReviews'))
const ItemPeek = lazyPreload(() => import('./ItemPeek'))
const SharedListSheet = lazyPreload(() => import('./SharedLists').then((m) => ({ default: m.SharedListSheet })))
const InvitePeople = lazyPreload(() => import('./SharedLists').then((m) => ({ default: m.InvitePeople })))
export function preloadSocial() {
for (const load of Object.values(socialLoaders)) void load().catch(() => {})
for (const screen of [ProfileView, ItemPeek, NotificationsSheet, TitleReviews, PeopleSearch, FollowList, EditProfile, SharedListSheet, InvitePeople]) void screen.preload().catch(() => {})
}
const SocialContext = createContext<SocialApi>({
+131 -24
View File
@@ -332,30 +332,128 @@ export interface EpisodeInfo {
runtime?: number
}
const seasonCache = new Map<string, EpisodeInfo[]>()
// Épisodes d'une saison gardés sur l'appareil : la liste (titres, dates, images) s'affiche dès l'ouverture
// de la fiche, puis est rafraîchie en arrière-plan si elle date de plus de 12 h (nouveaux épisodes, images)
const SEASONS_KEY = 'azuucine:seasons'
const SEASONS_FRESH = 12 * 3600_000
const SEASONS_MAX_AGE = 30 * 24 * 3600_000
const SEASONS_BUDGET = 400_000
type SeasonEntry = { at: number; eps: EpisodeInfo[] }
let seasonsMem: Map<string, SeasonEntry> | undefined
let seasonsSave: ReturnType<typeof setTimeout> | undefined
const seasonsInflight = new Map<string, Promise<EpisodeInfo[]>>()
/** Épisodes d'une saison (titre, image, date de diffusion). Gardés en mémoire le temps de la session. */
function toEpisode(v: unknown): EpisodeInfo | null {
if (!Array.isArray(v)) return null
const [number, name, still, date, runtime] = v as unknown[]
if (typeof number !== 'number' || !Number.isInteger(number) || number < 1) return null
return {
number,
name: typeof name === 'string' ? cleanText(name, LIMITS.title) : undefined,
still: typeof still === 'string' && isSafeTmdbPath(still) ? `${TMDB_IMG}/w300${still}` : undefined,
date: typeof date === 'string' ? safeDay(date) : undefined,
runtime: typeof runtime === 'number' && runtime > 0 && runtime < 1000 ? runtime : undefined,
}
}
function seasonsStore(): Map<string, SeasonEntry> {
if (seasonsMem) return seasonsMem
seasonsMem = new Map()
try {
const raw = JSON.parse(localStorage.getItem(SEASONS_KEY) ?? '{}') as Record<string, unknown>
const now = Date.now()
for (const [k, v] of Object.entries(raw ?? {})) {
const e = v as { at?: unknown; eps?: unknown }
if (!/^tmdb:tv:\d{1,10}:\d{1,3}:[a-z]{2}(-[A-Z]{2})?$/.test(k) || typeof e?.at !== 'number' || now - e.at > SEASONS_MAX_AGE || !Array.isArray(e.eps)) continue
seasonsMem.set(k, { at: e.at, eps: e.eps.map(toEpisode).filter((x): x is EpisodeInfo => !!x) })
}
} catch {
/* copie illisible ou stockage bloqué : on repart de zéro */
}
return seasonsMem
}
function saveSeasons() {
clearTimeout(seasonsSave)
seasonsSave = setTimeout(() => {
try {
// Les plus récentes d'abord ; on s'arrête avant de dépasser le budget (le stockage sert aussi au reste de l'app)
const out: Record<string, unknown> = {}
let size = 2
for (const [k, { at, eps }] of [...seasonsStore().entries()].sort((a, b) => b[1].at - a[1].at)) {
const value = { at, eps: eps.map((e) => [e.number, e.name ?? null, e.still ? e.still.replace(`${TMDB_IMG}/w300`, '') : null, e.date ?? null, e.runtime ?? null]) }
const piece = JSON.stringify(value).length + k.length + 4
if (size + piece > SEASONS_BUDGET) break
out[k] = value
size += piece
}
localStorage.setItem(SEASONS_KEY, JSON.stringify(out))
} catch {
/* stockage plein ou bloqué : la liste sera simplement redemandée */
}
}, 800)
}
const seasonKey = (externalId: string, season: number) => `${externalId}:${season}:${tmdbLanguage()}`
/** Épisodes d'une saison déjà connus sur l'appareil (affichage immédiat), même anciens. */
export function cachedSeasonEpisodes(externalId: string | undefined, season: number): EpisodeInfo[] | undefined {
return externalId?.startsWith('tmdb:tv:') ? seasonsStore().get(seasonKey(externalId, season))?.eps : undefined
}
/** Épisodes d'une saison (titre, image, date de diffusion), gardés sur l'appareil. */
export async function getTmdbSeasonEpisodes(externalId: string, season: number, key: string): Promise<EpisodeInfo[]> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:tv:') || !Number.isInteger(season) || season < 1 || season > 999) return []
const cacheKey = `${externalId}:${season}:${tmdbLanguage()}`
const cached = seasonCache.get(cacheKey)
if (cached) return cached
const d = await tmdbFetch<{ episodes?: { episode_number?: number; name?: string; still_path?: string | null; air_date?: string; runtime?: number }[] }>(
`/tv/${externalId.split(':')[2]}/season/${season}`,
key,
)
const list = (Array.isArray(d.episodes) ? d.episodes : [])
.filter((e) => Number.isInteger(e.episode_number) && e.episode_number! > 0)
.slice(0, 1000)
.map((e) => ({
number: e.episode_number!,
name: cleanText(e.name, LIMITS.title),
still: isSafeTmdbPath(e.still_path) ? `${TMDB_IMG}/w300${e.still_path}` : undefined,
date: safeDay(e.air_date),
runtime: typeof e.runtime === 'number' && e.runtime > 0 && e.runtime < 1000 ? Math.round(e.runtime) : undefined,
}))
seasonCache.set(cacheKey, list)
return list
const cacheKey = seasonKey(externalId, season)
const hit = seasonsStore().get(cacheKey)
if (hit && Date.now() - hit.at < SEASONS_FRESH) return hit.eps
let p = seasonsInflight.get(cacheKey)
if (!p) {
p = tmdbFetch<{ episodes?: { episode_number?: number; name?: string; still_path?: string | null; air_date?: string; runtime?: number }[] }>(
`/tv/${externalId.split(':')[2]}/season/${season}`,
key,
)
.then((d) => {
const list = (Array.isArray(d.episodes) ? d.episodes : [])
.filter((e) => Number.isInteger(e.episode_number) && e.episode_number! > 0)
.slice(0, 1000)
.map((e) => ({
number: e.episode_number!,
name: cleanText(e.name, LIMITS.title),
still: isSafeTmdbPath(e.still_path) ? `${TMDB_IMG}/w300${e.still_path}` : undefined,
date: safeDay(e.air_date),
runtime: typeof e.runtime === 'number' && e.runtime > 0 && e.runtime < 1000 ? Math.round(e.runtime) : undefined,
}))
seasonsStore().set(cacheKey, { at: Date.now(), eps: list })
saveSeasons()
return list
})
.finally(() => seasonsInflight.delete(cacheKey))
seasonsInflight.set(cacheKey, p)
}
return p
}
// Images déjà demandées pendant cette session (préchargement)
const preloaded = new Set<string>()
/** Fait télécharger des images à l'avance (le service worker les garde) : elles s'affichent sans attendre. */
export function preloadImages(urls: (string | undefined)[]): void {
for (const url of urls) {
if (!url || preloaded.has(url)) continue
if (preloaded.size > 500) preloaded.clear()
preloaded.add(url)
const img = new Image()
img.decoding = 'async'
img.referrerPolicy = 'no-referrer'
img.src = url
}
}
/** Images des épisodes autour du prochain à voir (ceux qu'on voit en ouvrant la fiche). */
export function episodeWindow(list: EpisodeInfo[], nextEpisode: number): EpisodeInfo[] {
const from = Math.max(1, nextEpisode - 2)
return list.filter((e) => e.number >= from && e.number < from + 8)
}
// ─────────────────────────── AniList ───────────────────────────
@@ -1240,12 +1338,21 @@ export function getPublicRatings(externalId: string): Promise<PublicRatings | nu
let prefetchKey: string | undefined
export const setPrefetchKey = (key?: string) => void (prefetchKey = key)
/** Commence à charger une fiche dès qu'on touche son affiche : elle s'ouvre avec ses infos déjà là. */
export function prefetchTitle(externalId: string | null | undefined): void {
/**
* Commence à charger une fiche dès qu'on touche son affiche : elle s'ouvre avec ses infos déjà là.
* Série : aussi la saison en cours et les images des épisodes autour du prochain à voir.
*/
export function prefetchTitle(externalId: string | null | undefined, season?: number, nextEpisode?: number): void {
if (!externalId || !navigator.onLine || !isSafeExternalId(externalId)) return
const isTmdb = externalId.startsWith('tmdb:')
if (!isTmdb || prefetchKey?.trim()) void getTitleExtras(externalId, prefetchKey).catch(() => {})
const key = prefetchKey?.trim()
if (!isTmdb || key) void getTitleExtras(externalId, prefetchKey).catch(() => {})
if (isTmdb) void getPublicRatings(externalId).catch(() => {})
if (key && season && externalId.startsWith('tmdb:tv:')) {
void getTmdbSeasonEpisodes(externalId, season, key)
.then((list) => preloadImages(episodeWindow(list, nextEpisode ?? 1).map((e) => e.still)))
.catch(() => {})
}
}
/** Infos de la fiche (note moyenne, votes, casting…), gardées en mémoire le temps de la session. */
+34
View File
@@ -0,0 +1,34 @@
import { lazy, useState, type ComponentProps, type ComponentType } from 'react'
/**
* Comme React.lazy, mais un écran déjà préchargé s'affiche tout de suite.
*
* Avec React.lazy seul, la première ouverture d'un écran le « met en attente » même si son code est déjà
* téléchargé, et React retarde alors volontairement son apparition (~300 ms, contre le clignotement).
* Ici, une fois `preload()` terminé, le vrai composant est rendu directement : aucune attente.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function lazyPreload<T extends ComponentType<any>>(factory: () => Promise<{ default: T }>) {
let loaded: T | undefined
let pending: Promise<{ default: T }> | undefined
const load = () =>
(pending ??= factory().then(
(m) => {
loaded = m.default
return m
},
(e: unknown) => {
pending = undefined // échec (hors-ligne…) : on pourra réessayer
throw e
},
))
const Lazy = lazy(load)
function Preloaded(props: ComponentProps<T>) {
// Choix fait une fois pour toute la vie de l'écran : passer de l'un à l'autre le recréerait (état perdu)
const [direct] = useState(() => loaded !== undefined)
const Component = (direct ? loaded : Lazy) as ComponentType<ComponentProps<T>>
return <Component {...props} />
}
return Object.assign(Preloaded, { preload: () => load().then(() => undefined) })
}
+17
View File
@@ -0,0 +1,17 @@
import { TYPE_BY_VALUE } from './constants'
import { seasonPosition } from './franchise'
import type { MediaItem } from '../types'
/**
* Attributs à poser sur un bouton qui ouvre la fiche d'un titre de ma bibliothèque : dès qu'on le touche,
* l'app précharge la fiche (écouteur global dans App.tsx). Série : aussi la saison en cours et les images
* des épisodes autour du prochain à voir.
*/
export function prefetchAttrs(item: Pick<MediaItem, 'externalId' | 'type' | 'episodesWatched' | 'seasons' | 'season'>): Record<string, string | undefined> {
if (!item.externalId) return {}
if (!TYPE_BY_VALUE[item.type]?.episodic || !item.externalId.startsWith('tmdb:tv:')) return { 'data-prefetch': item.externalId }
const pos = seasonPosition(item)
const season = pos?.season ?? 1
const next = (pos ? pos.episode : item.episodesWatched) + 1
return { 'data-prefetch': item.externalId, 'data-prefetch-season': String(season), 'data-prefetch-ep': String(next) }
}
+8 -4
View File
@@ -1,7 +1,8 @@
import { genreLabel, subtypeLabel } from '../lib/genres'
import { locale, t } from '../i18n'
import { CheckSquare, Hash, Heart, Search, SlidersHorizontal, X } from 'lucide-react'
import { lazy, Suspense, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'
import { Suspense, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'
import { lazyPreload } from '../lib/lazyPreload'
import { StatusDot } from '../components/Badges'
import { MediaCard } from '../components/MediaCard'
import { EmptyState, PageHeader } from '../components/ui'
@@ -15,9 +16,12 @@ import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape'
import type { MediaItem, MediaType, WatchStatus } from '../types'
// Onglets « Journal » et « Listes » : chargés quand on les ouvre (gardés sur l'appareil par le service worker)
const JournalView = lazy(() => import('../components/JournalView'))
const ListsView = lazy(() => import('../components/ListsView'))
// Onglets « Journal » et « Listes » : chargés à la demande, préchargés au repos (affichés sans attente ensuite)
const JournalView = lazyPreload(() => import('../components/JournalView'))
const ListsView = lazyPreload(() => import('../components/ListsView'))
export function preloadCatalogViews() {
for (const view of [JournalView, ListsView]) void view.preload().catch(() => {})
}
type SortKey = 'recent' | 'rating' | 'title' | 'watched'
+2 -1
View File
@@ -18,6 +18,7 @@ import { calendarEvents } from '../lib/releases'
import { todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { prefetchAttrs } from '../lib/prefetch'
interface Props {
onOpen: (item: MediaItem) => void
@@ -42,7 +43,7 @@ function PosterStrip({ items, onOpen }: { items: MediaItem[]; onOpen: (item: Med
return (
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{items.map((item) => (
<button key={item.id} data-prefetch={item.externalId} onClick={() => onOpen(item)} className="w-32 shrink-0 text-start">
<button key={item.id} {...prefetchAttrs(item)} 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">