- É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:
12 files changed
+261
-97
No files matched your search
+131
-24
@@ -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. */
|
||||
|
||||
@@ -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) })
|
||||
}
|
||||
@@ -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) }
|
||||
}
|
||||
Reference in new issue
Block a user