Refonte de la fiche, pseudo à l'inscription, notifications, retour arrière
deploy / deploy (push) Successful in 39s

1. Inscription par email : pseudo demandé dans le formulaire (envoyé dans
   les métadonnées, repris par le trigger azuu_new_user s'il est libre).
   Google inchangé.
2. Nouveaux épisodes : le serveur retient le dernier épisode connu
   (episode_seen) et ne notifie plus le passé, les séries terminées ni les
   décalages de numérotation TMDB/AniList. Côté app, l'encart « Nouveautés »
   ignore les séries terminées (Friends, Naruto).
3. Fenêtres figées sur mobile : la page derrière est bloquée (iOS) et le
   contenu ne défile que verticalement.
4. Geste / bouton retour : ferme la fenêtre du dessus (historique synchronisé
   avec la pile des fenêtres).
5. Casting (photos, rôles, doubleurs) sur la fiche.
6. Refonte complète de l'ajout et de la notation, façon Letterboxd :
   recherche → fiche ; Vu / En cours / À voir, note, coup de cœur, avis,
   épisodes, suivi enregistrés immédiatement ; note moyenne du public avec
   nombre de votes et répartition (AniList). L'ancien formulaire est supprimé.

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-10-08 17:43:04 +00:00
1 parent 0e2b54a5c8
commit 1b185e5e9d
41 files changed
+2260 -938

No files matched your search

+44 -15
View File
@@ -2,7 +2,9 @@ import { SocialProvider } from './components/social/SocialProvider'
import { useEffect, useState } from 'react'
import BottomNav, { type Tab } from './components/BottomNav'
import SideNav from './components/SideNav'
import MediaForm from './components/MediaForm'
import AddTitle from './components/title/AddTitle'
import EditDetails from './components/title/EditDetails'
import TitleSheet from './components/title/TitleSheet'
import Roulette from './components/Roulette'
import CalendarView from './components/CalendarView'
import HomePage from './pages/HomePage'
@@ -11,6 +13,7 @@ import StatsPage from './pages/StatsPage'
import SettingsPage from './pages/SettingsPage'
import AdminPage from './pages/AdminPage'
import { useMedia } from './store'
import type { SearchResult } from './lib/catalogApi'
import type { MediaItem } from './types'
const TABS: Tab[] = ['home', 'catalog', 'stats', 'settings']
@@ -23,13 +26,15 @@ function routeFromHash(): Route {
return (TABS as string[]).includes(h) ? (h as Tab) : 'home'
}
/** Formulaire ouvert : null = fermé, 'new' = ajout, sinon la fiche à éditer. */
export type EditorState = null | 'new' | MediaItem
/** Fiche ouverte : un titre de ma bibliothèque, ou un résultat de recherche pas encore ajouté. */
type Opened = { item: MediaItem; seed?: undefined } | { seed: SearchResult; item?: undefined }
export default function App() {
const { error } = useMedia()
const [route, setRoute] = useState<Route>(routeFromHash)
const [editor, setEditor] = useState<EditorState>(null)
const [opened, setOpened] = useState<Opened | null>(null)
const [adding, setAdding] = useState(false)
const [manual, setManual] = useState<string | null>(null)
const [roulette, setRoulette] = useState(false)
const [calendar, setCalendar] = useState(false)
@@ -46,8 +51,15 @@ export default function App() {
// Dans la barre de navigation, l'administration reste rattachée à « Réglages »
const navTab: Tab = route === 'admin' ? 'settings' : route
const openItem = (item: MediaItem) => setEditor(item)
const openNew = () => setEditor('new')
const openItem = (item: MediaItem) => setOpened({ item })
const openNew = () => setAdding(true)
const toSettings = () => {
setOpened(null)
setAdding(false)
setManual(null)
// Laisse les fenêtres retirer leur entrée d'historique avant de changer d'onglet
setTimeout(() => go('settings'), 50)
}
return (
<SocialProvider onOpenOwnItem={openItem}>
@@ -67,15 +79,32 @@ export default function App() {
{roulette && <Roulette onClose={() => setRoulette(false)} onOpen={openItem} />}
{calendar && <CalendarView onClose={() => setCalendar(false)} onOpen={openItem} />}
{editor && (
<MediaForm
key={editor === 'new' ? 'new' : editor.id}
item={editor === 'new' ? undefined : editor}
onClose={() => setEditor(null)}
onOpenItem={(i) => setEditor(i)}
onGoToSettings={() => {
setEditor(null)
go('settings')
{adding && (
<AddTitle
onClose={() => setAdding(false)}
onPick={(seed) => setOpened({ seed })}
onOpenItem={openItem}
onManual={(title) => setManual(title)}
onGoToSettings={toSettings}
/>
)}
{opened && (
<TitleSheet
key={opened.item ? opened.item.id : opened.seed.externalId}
item={opened.item}
seed={opened.seed}
onClose={() => setOpened(null)}
onGoToSettings={toSettings}
/>
)}
{manual !== null && (
<EditDetails
initialTitle={manual}
onClose={() => setManual(null)}
onCreated={(item) => {
setManual(null)
setAdding(false)
setOpened({ item })
}}
/>
)}
+27 -1
View File
@@ -3,7 +3,9 @@ import { LanguageSelect } from '../i18n/react'
import { Eye, EyeOff, Loader2 } from 'lucide-react'
import { useState, type FormEvent, type ReactNode } from 'react'
import { PASSWORD_MIN, requestPasswordReset, signIn, signInWithGoogle, signUp, updatePassword } from '../lib/cloud/auth'
import { USERNAME_RE } from '../lib/cloud/social'
import { cx } from '../lib/utils'
import { RANDOM_USERNAME } from './social/WelcomeProfile'
type Mode = 'login' | 'signup' | 'forgot'
@@ -50,11 +52,14 @@ function Shell({ children, subtitle }: { children: ReactNode; subtitle: string }
export default function AuthScreen({ notice }: { notice?: string }) {
const [mode, setMode] = useState<Mode>('login')
const [email, setEmail] = useState('')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [confirm, setConfirm] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
const [info, setInfo] = useState<string | undefined>(notice)
const cleanUsername = username.trim().replace(/^@/, '').toLowerCase()
const usernameOk = USERNAME_RE.test(cleanUsername) && !RANDOM_USERNAME.test(cleanUsername)
const switchTo = (m: Mode) => {
setMode(m)
@@ -78,12 +83,13 @@ export default function AuthScreen({ notice }: { notice?: string }) {
e.preventDefault()
setError(undefined)
setInfo(undefined)
if (mode === 'signup' && !usernameOk) return setError(t('social.usernameRule'))
if (mode === 'signup' && password !== confirm) return setError(t('auth.mismatch'))
setBusy(true)
try {
if (mode === 'login') await signIn(email, password)
else if (mode === 'signup') {
const needsConfirm = await signUp(email, password)
const needsConfirm = await signUp(email, password, cleanUsername)
if (needsConfirm) {
setInfo(t('auth.created', { email: email.trim() }))
setMode('login')
@@ -134,6 +140,26 @@ export default function AuthScreen({ notice }: { notice?: string }) {
<form onSubmit={submit} className="space-y-3">
{mode === 'forgot' && <h2 className="mb-1 text-lg font-semibold">{t('auth.forgotTitle')}</h2>}
{mode === 'signup' && (
<div>
<div className="relative">
<span className="pointer-events-none absolute start-3.5 top-1/2 -translate-y-1/2 text-ink-3">@</span>
<input
className="field ps-8"
value={username}
onChange={(e) => setUsername(e.target.value.toLowerCase())}
placeholder={t('welcome.usernamePh')}
aria-label={t('social.username')}
autoComplete="username"
autoCapitalize="off"
spellCheck={false}
maxLength={21}
required
/>
</div>
<p className={cx('mt-1.5 text-xs', username && !usernameOk ? 'text-accent' : 'text-ink-3')}>{t('social.usernameRule')}</p>
</div>
)}
<input
className="field"
type="email"
+4 -2
View File
@@ -8,6 +8,7 @@ import { cachedMonth, isBrowsableMonth, loadMonth, RELEASE_CATEGORIES } from '..
import { remotePosterToLocal } from '../lib/image'
import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases'
import { readStorage } from '../lib/security'
import { useBackToClose } from '../lib/backNav'
import { useScrollLock } from '../lib/scrollLock'
import { cx, normalizeText, todayISO } from '../lib/utils'
import { useMedia } from '../store'
@@ -110,6 +111,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
const request = useRef(0)
useScrollLock()
useBackToClose(onClose)
useEffect(() => {
try {
@@ -325,7 +327,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
const browsable = isBrowsableMonth(mid)
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('calendar.title')}>
<div className="sheet sheet-in" role="dialog" aria-modal="true" aria-label={t('calendar.title')}>
<header className="safe-top border-b border-line">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
@@ -348,7 +350,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="sheet-scroll">
<div className="safe-bottom mx-auto max-w-2xl px-4 pb-16 pt-4">
{/* Toutes les sorties / mes titres */}
<div className="mb-3 grid grid-cols-2 gap-1 rounded-full border border-line p-1">
-170
View File
@@ -1,170 +0,0 @@
import { t } from '../i18n'
import { Check, Loader2, Search } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { getTmdbDetails, searchAll, type SearchResult } from '../lib/catalogApi'
import { findFranchiseItem } from '../lib/franchise'
import { remotePosterToLocal } from '../lib/image'
import { cx } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput, MediaItem } from '../types'
interface Props {
/** Reçoit les métadonnées trouvées (titre, type, genres, épisodes, affiche…). */
onPick: (data: Partial<MediaInput>) => void
initialQuery?: string
/** Identifiant externe de la fiche en cours d'édition (pour ne pas la signaler comme doublon). */
currentExternalId?: string
onGoToSettings?: () => void
/** Nouvelle fiche : si le titre (ou une autre saison) est déjà dans la bibliothèque, on ouvre la fiche existante. */
onOpenExisting?: (item: MediaItem) => void
}
/** Recherche un titre (films, séries et animes en une seule fois) et remplit la fiche automatiquement. */
export default function DatabaseSearch({ onPick, initialQuery = '', currentExternalId, onGoToSettings, onOpenExisting }: Props) {
const { items, settings } = useMedia()
const hasKey = !!settings.tmdbKey?.trim()
const [query, setQuery] = useState(initialQuery)
const [results, setResults] = useState<SearchResult[]>([])
const [loading, setLoading] = useState(false)
const [picking, setPicking] = useState<string>()
const [error, setError] = useState<string>()
const requestId = useRef(0)
const others = items.filter((i) => !currentExternalId || i.externalId !== currentExternalId)
/** Déjà dans ma bibliothèque : même référence, ou une autre saison de la même série. */
const inLibrary = (r: SearchResult) =>
others.find((i) => i.externalId === r.externalId) ??
findFranchiseItem(others, [r.title, r.originalTitle, ...(r.altTitles ?? [])], { type: r.typeGuess })
// Recherche avec un petit délai pendant la frappe
useEffect(() => {
const q = query.trim()
// Toute réponse d'une recherche précédente devient caduque
const id = ++requestId.current
setError(undefined)
if (q.length < 2) {
setResults([])
setLoading(false)
return
}
setLoading(true)
const timer = setTimeout(async () => {
try {
const res = await searchAll(q, hasKey ? settings.tmdbKey : undefined)
if (id === requestId.current) setResults(res)
} catch (e) {
if (id === requestId.current) {
setResults([])
setError(navigator.onLine ? (e as Error).message : t('search.offline'))
}
} finally {
if (id === requestId.current) setLoading(false)
}
}, 450)
return () => clearTimeout(timer)
}, [query, hasKey, settings.tmdbKey])
const pick = async (r: SearchResult) => {
const mine = onOpenExisting && inLibrary(r)
if (mine) return onOpenExisting(mine)
setPicking(r.externalId)
setError(undefined)
try {
const data = r.source === 'tmdb' ? await getTmdbDetails(r, settings.tmdbKey!) : { ...r.prefill }
// TMDB autorise la copie locale de l'affiche (visible hors-ligne) ; AniList non, on garde l'URL.
if (r.posterUrl) data.poster = r.source === 'tmdb' ? await remotePosterToLocal(r.posterUrl) : r.posterUrl
onPick(data)
setResults([])
setQuery('')
} catch (e) {
setError((e as Error).message)
} finally {
setPicking(undefined)
}
}
return (
<div className="card p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<span className="eyebrow">{t('search.fillFrom')}</span>
<span className="text-[11px] text-ink-3">{t('search.allKinds')}</span>
</div>
<div className="relative">
<Search size={17} className="pointer-events-none absolute start-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Parasite, Frieren, Crash Landing on You…"
className="field ps-10"
enterKeyHint="search"
autoComplete="off"
/>
{loading && <Loader2 size={17} className="absolute end-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</div>
{!hasKey && (
<div className="mt-2 text-xs text-ink-3">
{t('search.animeOnly')}
{onGoToSettings && (
<button type="button" onClick={onGoToSettings} className="ms-1 font-medium text-ink">
{t('search.openSettings')} <span className="text-accent">→</span>
</button>
)}
</div>
)}
{error && <p className="mt-2 text-sm text-accent">{error}</p>}
{results.length > 0 && (
<ul className="-mx-1 mt-3 max-h-[22rem] divide-y divide-line overflow-y-auto overscroll-contain">
{results.map((r) => {
const mine = inLibrary(r)
const already = !!mine
return (
<li key={r.externalId}>
<button
type="button"
onClick={() => pick(r)}
disabled={!!picking}
className="flex w-full items-center gap-3 rounded-lg px-1 py-2.5 text-start transition-colors active:bg-surface-2 disabled:opacity-60"
>
{r.thumb ? (
<img src={r.thumb} alt="" loading="lazy" className="h-[4.2rem] w-11 shrink-0 rounded-md border border-line object-cover" />
) : (
<span className="grid h-[4.2rem] w-11 shrink-0 place-items-center rounded-md border border-line bg-surface-2 text-ink-3">
{r.title.charAt(0)}
</span>
)}
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{r.title}</span>
{r.originalTitle && <span className="block truncate text-xs text-ink-3">{r.originalTitle}</span>}
<span className="mt-1 block text-[10.5px] uppercase text-ink-3">
{[r.kindLabel, r.year].filter(Boolean).join(' · ')}
{already && <span className="text-accent"> · {mine.externalId === r.externalId ? t('search.already') : t('search.alreadySeries')}</span>}
</span>
</span>
{picking === r.externalId ? (
<Loader2 size={18} className="shrink-0 animate-spin text-ink-3" />
) : (
<span className="shrink-0 text-accent">→</span>
)}
</button>
</li>
)
})}
</ul>
)}
{!loading && !error && query.trim().length >= 2 && results.length === 0 && (
<p className="mt-3 text-sm text-ink-3">{t('search.noResults')}</p>
)}
<p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-ink-3">
<Check size={12} className="mt-0.5 shrink-0" />
{t('search.privacy', { source: hasKey ? 'TMDB / AniList' : 'AniList' })}
</p>
</div>
)
}
-91
View File
@@ -1,91 +0,0 @@
import { Check, Pencil, Star } from 'lucide-react'
import { useState } from 'react'
import { t } from '../i18n'
import { genreLabel } from '../lib/genres'
import { formatRating } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput } from '../types'
import Poster from './Poster'
export interface HeroAction {
label: string
onClick?: () => void
/** Déjà fait (tout vu) : bouton affiché comme validé */
done?: boolean
}
interface Props {
form: MediaInput
typeLabel: string
editing: boolean
onEdit: () => void
primary: HeroAction
}
/** En-tête d'une fiche, façon plateforme de streaming : grande image, titre, infos et action principale. */
export default function ItemHero({ form, typeLabel, editing, onEdit, primary }: Props) {
const { settings } = useMedia()
const [moreText, setMoreText] = useState(false)
const image = form.backdrop ?? form.poster
const meta = [typeLabel, form.year, ...form.genres.slice(0, 3).map(genreLabel)].filter(Boolean).join(' · ')
return (
<section>
<div className="relative h-56 overflow-hidden bg-surface-2 sm:h-72">
{image && <img src={image} alt="" className={form.backdrop ? 'size-full object-cover' : 'size-full scale-110 object-cover blur-md'} />}
<div className="absolute inset-0 bg-bg/55" />
</div>
<div className="relative mx-auto -mt-24 flex max-w-2xl items-end gap-4 px-4">
<div className="w-24 shrink-0 sm:w-28">
<Poster src={form.poster} title={form.title} />
</div>
<div className="min-w-0 flex-1 pb-1">
<h1 className="line-clamp-3 text-2xl font-bold leading-tight">{form.title}</h1>
{form.originalTitle && <p className="mt-0.5 truncate text-sm text-ink-3">{form.originalTitle}</p>}
</div>
</div>
<div className="mx-auto mt-4 max-w-2xl px-4">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-2">
{meta && <span>{meta}</span>}
{form.publicRating != null && (
<span className="flex items-center gap-1 font-semibold text-ink">
<Star size={12} className="fill-accent text-accent" />
{formatRating(form.publicRating, settings.ratingScale)}
</span>
)}
</div>
<div className="mt-4 flex gap-2">
<button
type="button"
onClick={primary.onClick}
disabled={!primary.onClick}
className={primary.done ? 'btn btn-ghost flex-1 py-3' : 'btn btn-primary flex-1 py-3'}
>
{primary.done && <Check size={17} />}
{primary.label}
</button>
<button
type="button"
onClick={onEdit}
aria-pressed={editing}
className={editing ? 'btn btn-light px-4' : 'btn btn-ghost px-4'}
aria-label={t('hero.edit')}
title={t('hero.edit')}
>
<Pencil size={17} />
</button>
</div>
{form.overview && (
<button type="button" onClick={() => setMoreText((v) => !v)} className="mt-4 block text-start text-sm leading-relaxed text-ink-2">
<span className={moreText ? 'whitespace-pre-line' : 'line-clamp-3'}>{form.overview}</span>
{form.overview.length > 160 && <span className="mt-1 block text-xs font-medium text-ink">{moreText ? t('hero.less') : t('hero.more')}</span>}
</button>
)}
</div>
</section>
)
}
-639
View File
@@ -1,639 +0,0 @@
import { locale, t } from '../i18n'
import { Check, Heart, ImagePlus, Loader2, MessagesSquare, Minus, Plus, Share2, Trash2, X } from 'lucide-react'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { CRITERIA, DEFAULT_FILM_MINUTES, MEDIA_TYPES, STATUSES, TYPE_BY_VALUE } from '../lib/constants'
import { canonicalGenre, canonicalSubtype, genreLabel, genreSuggestions as defaultGenres, subtypeLabel, subtypeSuggestions } from '../lib/genres'
import { fileToPosterDataURL } from '../lib/image'
import { getTmdbCredits, getTmdbExtras } from '../lib/catalogApi'
import { episodeCap, seasonPosition } from '../lib/franchise'
import { renderItemCard, slug } from '../lib/shareCard'
import { useScrollLock } from '../lib/scrollLock'
import { cx, formatDate, formatRating, todayISO } from '../lib/utils'
import { airedCount, nextAirDate, useAiringCache } from '../lib/airing'
import { useMedia } from '../store'
import type { MediaInput, MediaItem, RatingScale, WatchStatus } from '../types'
import { StatusDot } from './Badges'
import ConfirmDialog from './ConfirmDialog'
import SharePreview from './SharePreview'
import DatabaseSearch from './DatabaseSearch'
import EpisodeList from './EpisodeList'
import ItemHero, { type HeroAction } from './ItemHero'
import { useSocial } from './social/SocialProvider'
import { NewListForm } from './ListsView'
import Poster from './Poster'
import { RatingInput } from './Rating'
import TagInput from './TagInput'
const EMPTY: MediaInput = {
title: '',
type: 'film',
status: 'a_voir',
criteria: {},
episodesWatched: 0,
genres: [],
}
/** Champs « catalogue » qu'une recherche TMDB/AniList peut remplir. Le reste (statut, note, avis…) n'est jamais touché. */
const METADATA_KEYS = [
'title',
'originalTitle',
'type',
'subtype',
'year',
'overview',
'duration',
'episodesTotal',
'seasons',
'episodeDuration',
'poster',
'backdrop',
'externalId',
'countries',
'publicRating',
] as const
function Section({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="space-y-3">
{title && <h3 className="eyebrow text-ink-2">{title}</h3>}
{children}
</section>
)
}
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="block">
<span className="label">{label}</span>
{children}
</label>
)
}
/** input number → nombre ou undefined si vide */
const toNum = (v: string) => (v === '' ? undefined : Math.max(0, Number(v)))
interface Props {
item?: MediaItem
onClose: () => void
onGoToSettings?: () => void
/** Ouvre une autre fiche (titre déjà dans la bibliothèque) */
onOpenItem?: (item: MediaItem) => void
}
/** « Moi vs le public » : ma note comparée à la moyenne TMDB / AniList. */
function PublicCompare({ mine, pub, scale, source }: { mine?: number; pub: number; scale: RatingScale; source: string }) {
const gap = mine != null ? mine - pub : undefined
const show = (v: number) => formatRating(v, scale) + (scale === '5' ? '/5' : '/10')
const gapText =
gap == null
? undefined
: Math.abs(gap) < 0.5
? t('public.agree')
: gap > 0
? t('public.more', { gap: formatRating(Math.abs(gap), scale) })
: t('public.less', { gap: formatRating(Math.abs(gap), scale) })
return (
<div className="flex items-center justify-between gap-3 rounded-xl border border-line px-3 py-2.5 text-sm">
<span className="text-ink-2">
{t('public.label')} <span className="font-semibold text-ink">{show(pub)}</span> <span className="text-xs text-ink-3">· {source}</span>
</span>
{gapText && <span className={cx('text-end text-xs font-semibold', gap! >= 0.5 ? 'text-accent' : 'text-ink-3')}>{gapText}</span>}
</div>
)
}
/** Liste des dates de revisionnage (films comme séries). */
function Rewatches({ dates, onChange }: { dates: string[]; onChange: (d: string[]) => void }) {
const [draft, setDraft] = useState(todayISO())
const add = () => {
if (!/^\d{4}-\d{2}-\d{2}$/.test(draft) || dates.length >= 100) return
onChange([...dates, draft].sort().reverse())
}
return (
<div className="card p-4">
{dates.length > 0 ? (
<ul className="mb-3 divide-y divide-line">
{dates.map((d, k) => (
<li key={d + k} className="flex items-center justify-between py-2 text-sm">
<span className="capitalize">{new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' })}</span>
<button type="button" onClick={() => onChange(dates.filter((_, j) => j !== k))} className="grid size-8 place-items-center rounded-full text-ink-3" aria-label={t('form.removeRewatch')}>
<X size={16} />
</button>
</li>
))}
</ul>
) : (
<p className="mb-3 text-sm text-ink-3">{t('form.rewatchHint')}</p>
)}
<div className="flex gap-2">
<input className="field flex-1" type="date" value={draft} max={todayISO()} onChange={(e) => setDraft(e.target.value)} aria-label={t('form.rewatchDate')} />
<button type="button" onClick={add} className="btn btn-ghost shrink-0">
<Plus size={16} /> {t('journal.rewatched')}
</button>
</div>
</div>
)
}
export default function MediaForm({ item, onClose, onGoToSettings, onOpenItem }: Props) {
const social = useSocial()
const { add, update, remove, items, settings, lists, patchMany } = useMedia()
const [form, setForm] = useState<MediaInput>(() => {
if (!item) return EMPTY
const { id: _id, createdAt: _c, updatedAt: _u, ...rest } = item
return rest
})
const [saving, setSaving] = useState(false)
const [criteriaOpen] = useState(() => Object.keys(item?.criteria ?? {}).length > 0)
const [showSearch, setShowSearch] = useState(!item)
const [filledFrom, setFilledFrom] = useState<string>()
const [posterError, setPosterError] = useState<string>()
const fileRef = useRef<HTMLInputElement>(null)
const typeInfo = TYPE_BY_VALUE[form.type]
// Bloque le défilement de la page derrière la feuille
useScrollLock()
// Fiche TMDB ajoutée avant ces nouveautés : grande image et saisons récupérées en arrière-plan (et gardées)
const extId = form.externalId
useEffect(() => {
const key = settings.tmdbKey?.trim()
const isTv = extId?.startsWith('tmdb:tv:')
if (!extId?.startsWith('tmdb:') || !key || !navigator.onLine || (form.backdrop && (!isTv || form.seasons))) return
let alive = true
getTmdbExtras(extId, key)
.then(({ seasons, total, backdrop }) => {
if (!alive) return
const patch: Partial<MediaInput> = {}
if (backdrop && !form.backdrop) patch.backdrop = backdrop
if (seasons && !form.seasons) {
patch.seasons = seasons
if ((total ?? 0) > (form.episodesTotal ?? 0)) patch.episodesTotal = total
}
if (!Object.keys(patch).length) return
setForm((f) => (f.externalId === extId ? { ...f, ...patch } : f))
if (item && item.externalId === extId) void patchMany([{ id: item.id, patch }])
})
.catch(() => {})
return () => {
alive = false
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [extId])
const [editInfo, setEditInfo] = useState(false)
/** En-tête façon plateforme : dès qu'un titre est lié à TMDB / AniList, ou pour une fiche existante */
const hasHero = !!form.title.trim() && (!!form.externalId || !!item)
/** Nouveaux épisodes vus : le statut et les dates suivent. */
const withEpisodes = (f: MediaInput, n: number, season?: number): MediaInput => {
const cap = episodeCap(f)
const watched = Math.max(0, cap ? Math.min(n, cap) : n)
const next: MediaInput = { ...f, episodesWatched: watched, season: f.seasons ? season ?? seasonPosition({ ...f, episodesWatched: watched, season: undefined })?.season : f.season }
if (watched > 0 && (f.status === 'a_voir' || f.status === 'pause')) {
next.status = 'en_cours'
next.startDate = f.startDate ?? todayISO()
}
if (cap && watched >= cap) {
next.status = 'termine'
next.endDate = f.endDate ?? todayISO()
} else if (f.status === 'termine' && watched < (f.episodesWatched ?? 0)) {
next.status = 'en_cours'
next.endDate = undefined
}
return next
}
/** Bouton principal de l'en-tête : épisode suivant (séries) ou « vu » (films). */
// Épisodes déjà sortis (fiche suivie) : on ne coche pas un épisode à venir
const airingCache = useAiringCache()
const aired = item ? airedCount({ id: item.id, type: form.type, externalId: form.externalId }, airingCache) : undefined
const primary: HeroAction = (() => {
if (typeInfo.episodic) {
const cap = episodeCap(form)
if (cap && form.episodesWatched >= cap) return { label: t('hero.allSeen'), done: true }
if (aired != null && form.episodesWatched >= aired) {
const date = item ? nextAirDate({ id: item.id, type: form.type, externalId: form.externalId }, airingCache) : undefined
return { label: date ? t('hero.nextOn', { date: formatDate(date) }) : t('hero.upToDate'), done: true }
}
const nextPos = seasonPosition({ ...form, episodesWatched: form.episodesWatched + 1, season: undefined })
const ep = t('episodes.short', { n: nextPos ? nextPos.episode : form.episodesWatched + 1 })
const label = t('hero.seenEp', { ep: nextPos ? `${t('episodes.seasonShort', { n: nextPos.season })} · ${ep}` : ep })
return { label, onClick: () => setForm((f) => withEpisodes(f, f.episodesWatched + 1)) }
}
if (form.status === 'termine') return { label: t('hero.seen'), done: true }
return { label: t('hero.markSeen'), onClick: () => setStatus('termine') }
})()
const set = <K extends keyof MediaInput>(key: K, value: MediaInput[K]) => setForm((f) => ({ ...f, [key]: value }))
// Suggestions = listes par défaut + ce que j'ai déjà utilisé
const genreSuggestions = useMemo(() => [...new Set([...items.flatMap((i) => i.genres.map(genreLabel)), ...defaultGenres()])], [items])
/** Applique les infos trouvées en ligne sans écraser mon suivi (statut, note, épisodes vus, avis…). */
const applyMetadata = (data: Partial<MediaInput>) => {
setForm((f) => {
const next: MediaInput = { ...f }
for (const key of METADATA_KEYS) {
if (data[key] !== undefined) (next as unknown as Record<string, unknown>)[key] = data[key]
}
// Découpage par saison : celui de la nouvelle source (ou aucun)
next.seasons = data.seasons
next.backdrop = data.backdrop
if (data.type && data.type !== 'autre') next.subtype = undefined
if (data.genres?.length) next.genres = [...new Set([...f.genres, ...data.genres])]
if (data.platform && !f.platform) next.platform = data.platform
const cap = episodeCap(next)
if (cap && next.episodesWatched > cap) next.episodesWatched = cap
return next
})
setFilledFrom(data.externalId?.startsWith('anilist') ? 'AniList' : 'TMDB')
setShowSearch(false)
}
const setStatus = (status: WatchStatus) =>
setForm((f) => {
const next = { ...f, status }
// « À voir » : pas encore regardé, donc pas de dates
if (status === 'a_voir') {
next.startDate = undefined
next.endDate = undefined
}
if (status === 'en_cours' && !f.startDate) next.startDate = todayISO()
if (status === 'termine') {
if (!f.endDate) next.endDate = todayISO()
const cap = episodeCap(f)
if (cap && TYPE_BY_VALUE[f.type].episodic) next.episodesWatched = cap
}
return next
})
// Même règles que la liste d'épisodes : le statut et les dates suivent
const changeEpisodes = (delta: number) => setForm((f) => withEpisodes(f, f.episodesWatched + delta))
const onPickImage = async (file?: File) => {
if (!file) return
setPosterError(undefined)
try {
set('poster', await fileToPosterDataURL(file))
} catch (e) {
setPosterError((e as Error).message)
}
}
const submit = async () => {
if (!form.title.trim()) return
setSaving(true)
const clean: MediaInput = {
...form,
title: form.title.trim(),
originalTitle: form.originalTitle?.trim() || undefined,
subtype: form.type === 'autre' ? (form.subtype?.trim() ? canonicalSubtype(form.subtype) : undefined) : undefined,
platform: form.platform?.trim() || undefined,
notes: form.notes?.trim() || undefined,
poster: form.poster?.trim() || undefined,
overview: form.overview?.trim() || undefined,
}
const pos = seasonPosition(clean)
if (pos) clean.season = pos.season
try {
if (item) await update(item.id, clean)
else await add(clean)
onClose()
} finally {
setSaving(false)
}
}
const [confirmDelete, setConfirmDelete] = useState(false)
const [sharing, setSharing] = useState(false)
const [preview, setPreview] = useState<{ blob: Blob; filename: string }>()
const shareCard = async () => {
if (!item) return
setSharing(true)
try {
// Générique (réalisation, production, casting) depuis TMDB si possible
let credits
if (settings.tmdbKey && form.externalId?.startsWith('tmdb:') && navigator.onLine) {
credits = await getTmdbCredits(form.externalId, settings.tmdbKey).catch(() => undefined)
}
const blob = await renderItemCard({ ...item, ...form }, settings.ratingScale, credits)
setPreview({ blob, filename: `azuucine-${slug(form.title)}.png` })
} finally {
setSharing(false)
}
}
const onDelete = async () => {
if (!item) return
setConfirmDelete(false)
await remove(item.id)
onClose()
}
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={item ? t('common.edit') : t('common.add')}>
{/* En-tête */}
<header className="safe-top border-b border-line bg-bg">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="flex-1 text-center text-base font-semibold">
{item ? t('form.editTitle') : t('form.newTitle')}
<span className="text-accent">{item ? t('form.editAccent') : t('form.newAccent')}</span>
</h2>
<button onClick={submit} disabled={!form.title.trim() || saving} className="btn btn-light px-4 py-2 text-sm">
{t('common.save')}
</button>
</div>
</header>
<form
className="flex-1 overflow-y-auto overscroll-contain"
onSubmit={(e) => {
e.preventDefault()
void submit()
}}
>
{hasHero && (
<ItemHero
form={form}
typeLabel={form.type === 'autre' && form.subtype ? subtypeLabel(form.subtype) : typeInfo.label}
editing={editInfo}
onEdit={() => setEditInfo((v) => !v)}
primary={primary}
/>
)}
<div className="safe-bottom mx-auto max-w-2xl space-y-9 px-4 py-6 pb-16">
{/* Recherche en ligne */}
{(!hasHero || editInfo || showSearch) && (showSearch ? (
<DatabaseSearch
onPick={applyMetadata}
initialQuery={item ? form.title : ''}
currentExternalId={item?.externalId}
onGoToSettings={onGoToSettings}
onOpenExisting={!item && onOpenItem ? onOpenItem : undefined}
/>
) : (
<button
type="button"
onClick={() => setShowSearch(true)}
className="flex w-full items-center justify-between rounded-2xl border border-dashed border-line-strong px-4 py-3 text-start text-sm text-ink-2"
>
<span>
{filledFrom ? (
<>
{t('form.filledFrom')} <span className="text-ink">{filledFrom}</span> — {t('form.canEdit')}
</>
) : (
t('form.fillFromDb')
)}
</span>
<span className="text-accent">→</span>
</button>
))}
{/* Affiche + titres (modifiables) */}
{(!hasHero || editInfo) && (
<>
<div className="flex gap-4">
<div className="w-28 shrink-0">
<button type="button" onClick={() => fileRef.current?.click()} className="relative block w-full" aria-label={t('form.pickPoster')}>
<Poster src={form.poster} title={form.title || '?'} />
<span className="absolute bottom-2 end-2 grid size-8 place-items-center rounded-full bg-bg/85 text-ink">
<ImagePlus size={15} />
</span>
</button>
<input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => onPickImage(e.target.files?.[0])} />
{form.poster && (
<button type="button" onClick={() => set('poster', undefined)} className="mt-2 w-full text-xs text-ink-3">
{t('form.removeImage')}
</button>
)}
</div>
<div className="min-w-0 flex-1 space-y-4">
<Field label={t('form.title')}>
<input className="field" value={form.title} onChange={(e) => set('title', e.target.value)} placeholder={t('form.titlePh')} required />
</Field>
<Field label={t('form.originalTitle')}>
<input className="field" value={form.originalTitle ?? ''} onChange={(e) => set('originalTitle', e.target.value)} placeholder={t('form.originalTitlePh')} />
</Field>
</div>
</div>
{form.overview && !hasHero && (
<details className="-mt-3 text-sm text-ink-2">
<summary className="eyebrow cursor-pointer select-none">{t('form.synopsis')}</summary>
<p className="mt-2 whitespace-pre-line leading-relaxed">{form.overview}</p>
</details>
)}
</>
)}
{/* Année, dates de visionnage, genres */}
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<Field label={t('form.startShort')}>
<input className="field px-3" type="date" value={form.startDate ?? ''} onChange={(e) => set('startDate', e.target.value || undefined)} />
</Field>
<Field label={t('form.endShort')}>
<input className="field px-3" type="date" value={form.endDate ?? ''} onChange={(e) => set('endDate', e.target.value || undefined)} />
</Field>
</div>
<div className="grid grid-cols-[5rem_minmax(0,1fr)] items-start gap-3">
<Field label={t('form.year')}>
<input className="field px-3" type="number" inputMode="numeric" value={form.year ?? ''} onChange={(e) => set('year', toNum(e.target.value))} placeholder="2024" />
</Field>
<div>
<span className="label">{t('form.genres')}</span>
<TagInput
value={form.genres}
onChange={(g) => set('genres', g)}
suggestions={genreSuggestions}
placeholder={t('form.genresPh')}
display={genreLabel}
normalize={canonicalGenre}
/>
</div>
</div>
</div>
{/* Statut */}
<Section title={t('form.status')}>
<div className="flex flex-wrap gap-2">
{STATUSES.map((s) => (
<button key={s.value} type="button" onClick={() => setStatus(s.value)} className={cx('chip', form.status === s.value && 'chip-on')}>
<StatusDot status={s.value} />
{s.label}
</button>
))}
</div>
</Section>
{/* Épisodes / durée */}
{typeInfo.episodic ? (
<Section title={t('form.episodes')}>
{/* Liste d'épisodes pour une fiche liée (TMDB / AniList) ; compteur + total modifiable pour une fiche manuelle */}
{form.seasons || (form.externalId && form.episodesTotal) ? (
<EpisodeList form={form} aired={aired} onChange={(n, season) => setForm((f) => withEpisodes(f, n, season))} />
) : (
<div className="card space-y-5 p-4">
<div className="flex items-center justify-between">
<span className="text-sm text-ink-2">{t('home.episodesSeen')}</span>
<div className="flex items-center gap-3">
<button type="button" onClick={() => changeEpisodes(-1)} className="grid size-10 place-items-center rounded-full border border-line-strong text-ink-2" aria-label={t('form.minusEp')}>
<Minus size={17} />
</button>
<span className="min-w-16 text-center text-2xl font-bold tabular-nums">{form.episodesWatched}</span>
<button type="button" onClick={() => changeEpisodes(1)} className="grid size-10 place-items-center rounded-full bg-accent-fill text-on-accent" aria-label={t('form.plusEp')}>
<Plus size={17} strokeWidth={2.5} />
</button>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<Field label={t('form.total')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.episodesTotal ?? ''} onChange={(e) => set('episodesTotal', toNum(e.target.value))} placeholder="?" />
</Field>
<Field label={t('form.season')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.season ?? ''} onChange={(e) => set('season', toNum(e.target.value))} placeholder="1" />
</Field>
</div>
</div>
)}
</Section>
) : (
<Section title={t('form.duration')}>
<Field label={t('form.durationMin')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.duration ?? ''} onChange={(e) => set('duration', toNum(e.target.value))} placeholder={String(DEFAULT_FILM_MINUTES)} />
</Field>
</Section>
)}
{/* Note */}
<Section title={t('form.myRating')}>
<div className="card space-y-4 p-4">
<RatingInput value={form.rating} onChange={(v) => set('rating', v)} scale={settings.ratingScale} />
{form.publicRating != null && <PublicCompare mine={form.rating} pub={form.publicRating} scale={settings.ratingScale} source={form.externalId?.startsWith('anilist:') ? 'AniList' : 'TMDB'} />}
<button type="button" onClick={() => set('favorite', !form.favorite)} className={cx('chip', form.favorite && 'border-accent text-ink')}>
<Heart size={15} className={form.favorite ? 'fill-accent text-accent' : ''} />
{t('form.favorite')}
</button>
<details className="border-t border-line pt-3" open={criteriaOpen}>
<summary className="cursor-pointer select-none text-sm text-ink-2">{t('form.criteria')}</summary>
<div className="mt-4 space-y-4">
{CRITERIA.map((c) => (
<div key={c.key}>
<span className="eyebrow mb-1.5 block">{c.label}</span>
<RatingInput
size="sm"
label={c.label}
scale={settings.ratingScale}
value={form.criteria[c.key]}
onChange={(v) =>
setForm((f) => {
const criteria = { ...f.criteria }
if (v == null) delete criteria[c.key]
else criteria[c.key] = v
return { ...f, criteria }
})
}
/>
</div>
))}
</div>
</details>
</div>
</Section>
{(form.status === 'termine' || (form.rewatchDates?.length ?? 0) > 0) && (
<Section title={t('form.rewatches')}>
<Rewatches dates={form.rewatchDates ?? []} onChange={(d) => set('rewatchDates', d.length ? d : undefined)} />
</Section>
)}
{/* Type */}
<Section title={t('form.type')}>
<div className="flex flex-wrap gap-2">
{MEDIA_TYPES.map((mt) => (
<button key={mt.value} type="button" onClick={() => set('type', mt.value)} className={cx('chip', form.type === mt.value && 'chip-on')}>
{mt.label}
</button>
))}
</div>
{form.type === 'autre' && (
<Field label={t('form.subtype')}>
<input className="field" list="subtypes" value={form.subtype ? subtypeLabel(form.subtype) : ''} onChange={(e) => set('subtype', e.target.value)} placeholder={t('form.subtypePh')} />
<datalist id="subtypes">
{subtypeSuggestions().map((s) => (
<option key={s} value={s} />
))}
</datalist>
</Field>
)}
</Section>
<Section title={t('lists.myLists')}>
{lists.length > 0 && (
<div className="flex flex-wrap gap-2">
{lists.map((l) => {
const on = form.listIds?.includes(l.id)
return (
<button
key={l.id}
type="button"
onClick={() =>
set('listIds', on ? form.listIds!.filter((x) => x !== l.id) : [...(form.listIds ?? []), l.id])
}
className={cx('chip', on && 'chip-on')}
>
{on && <Check size={14} />}
{l.name}
</button>
)
})}
</div>
)}
<NewListForm onCreated={(l) => set('listIds', [...(form.listIds ?? []), l.id])} />
</Section>
<Section title={t('form.review')}>
<textarea className="field min-h-32 resize-y" value={form.notes ?? ''} onChange={(e) => set('notes', e.target.value)} placeholder={t('form.reviewPh')} />
{form.externalId && social.enabled && (
<button type="button" onClick={() => social.openReviews(form.externalId!, form.title)} className="mt-3 flex w-full items-center justify-center gap-2 rounded-xl border border-line py-2.5 text-sm font-medium text-ink-2 transition-colors active:bg-surface-2">
<MessagesSquare size={16} /> {t('reviews.seeAll')}
</button>
)}
</Section>
<div className="space-y-2 border-t border-line pt-6">
<button type="submit" disabled={!form.title.trim() || saving} className="btn btn-primary w-full py-3">
{item ? t('form.saveChanges') : t('form.addToLibrary')} <span aria-hidden>→</span>
</button>
{item && (
<button type="button" onClick={shareCard} disabled={sharing} className="btn btn-ghost w-full">
{sharing ? <Loader2 size={17} className="animate-spin" /> : <Share2 size={17} />} {t('form.shareImage')}
</button>
)}
{item && (
<button type="button" onClick={() => setConfirmDelete(true)} className="btn w-full text-ink-3">
<Trash2 size={17} /> {t('form.delete')}
</button>
)}
</div>
</div>
</form>
{preview && <SharePreview blob={preview.blob} filename={preview.filename} title={form.title} onClose={() => setPreview(undefined)} />}
<ConfirmDialog
open={confirmDelete}
title={t('confirm.title')}
message={item ? t('form.deleteConfirm', { title: item.title }) : undefined}
confirmLabel={t('common.delete')}
onConfirm={onDelete}
onCancel={() => setConfirmDelete(false)}
/>
</div>
)
}
+4 -2
View File
@@ -21,6 +21,7 @@ import type { MediaItem } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
import { RatingBadge } from './Rating'
import { useBackToClose } from '../lib/backNav'
import { useScrollLock } from '../lib/scrollLock'
const CARD = 112 // largeur d'une affiche dans le rouleau (w-28)
@@ -73,6 +74,7 @@ export default function Roulette({ onClose, onOpen }: Props) {
// Bloque le défilement derrière + mémorise les filtres
useScrollLock()
useBackToClose(onClose)
useEffect(() => saveFilters(filters), [filters])
// Changer les filtres efface le tirage en cours
@@ -153,7 +155,7 @@ export default function Roulette({ onClose, onOpen }: Props) {
const winnerIndex = result ? reel.indexOf(result, reel.length > TARGET ? TARGET : 0) : -1
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('roulette.name')}>
<div className="sheet sheet-in" role="dialog" aria-modal="true" aria-label={t('roulette.name')}>
<header className="safe-top border-b border-line">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
@@ -166,7 +168,7 @@ export default function Roulette({ onClose, onOpen }: Props) {
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="sheet-scroll">
<div className="safe-bottom mx-auto max-w-2xl pb-16">
{/* Rouleau d'affiches */}
<div ref={viewport} dir="ltr" className="relative mt-6 h-[184px] overflow-hidden">
+4 -2
View File
@@ -7,6 +7,7 @@ import { useMedia } from '../store'
import type { TopCategory } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
import { useBackToClose } from '../lib/backNav'
import { useScrollLock } from '../lib/scrollLock'
interface Props {
@@ -31,6 +32,7 @@ export default function TopFiveEditor({ category: initialCategory, onClose }: Pr
const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items])
useScrollLock()
useBackToClose(onClose)
/** Changer de catégorie enregistre d'abord celle en cours. */
const switchCategory = async (cat: TopCategory) => {
@@ -68,7 +70,7 @@ export default function TopFiveEditor({ category: initialCategory, onClose }: Pr
}
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('top.editLabel')}>
<div className="sheet sheet-in" role="dialog" aria-modal="true" aria-label={t('top.editLabel')}>
<header className="safe-top border-b border-line">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
@@ -83,7 +85,7 @@ export default function TopFiveEditor({ category: initialCategory, onClose }: Pr
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="sheet-scroll">
<div className="safe-bottom mx-auto max-w-2xl space-y-6 px-4 py-5 pb-16">
<div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4">
{TOP_CATEGORIES.filter((c) => c.value === category || settings.topCategories.includes(c.value)).map((c) => (
+2
View File
@@ -2,6 +2,7 @@ import { Check, Loader2, MessagesSquare, Plus, Star } from 'lucide-react'
import { useEffect, useState } from 'react'
import { t } from '../../i18n'
import { genreLabel } from '../../lib/genres'
import { useBackToClose } from '../../lib/backNav'
import { useScrollLock } from '../../lib/scrollLock'
import { titleReviews, type TitleReview } from '../../lib/cloud/reviews'
import { useSocial } from './SocialProvider'
@@ -48,6 +49,7 @@ export default function ItemPeek({ item, owner, onClose }: { item: MediaItem; ow
)
useScrollLock()
useBackToClose(onClose)
useEscape(onClose)
+4 -2
View File
@@ -1,6 +1,7 @@
import { X } from 'lucide-react'
import { type ReactNode } from 'react'
import { t } from '../../i18n'
import { useBackToClose } from '../../lib/backNav'
import { useScrollLock } from '../../lib/scrollLock'
import { useEscape } from '../../lib/escape'
import { cx } from '../../lib/utils'
@@ -9,8 +10,9 @@ import { cx } from '../../lib/utils'
export default function Sheet({ title, onClose, right, children, label, elevated }: { title: ReactNode; onClose: () => void; right?: ReactNode; children: ReactNode; label: string; elevated?: boolean }) {
useScrollLock()
useEscape(onClose)
useBackToClose(onClose)
return (
<div className={cx('sheet-in fixed inset-0 flex flex-col bg-bg', elevated ? 'z-[70]' : 'z-50')} role="dialog" aria-modal="true" aria-label={label}>
<div className={cx('sheet sheet-in', elevated && 'z-[70]')} role="dialog" aria-modal="true" aria-label={label}>
<header className="safe-top border-b border-line">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
@@ -20,7 +22,7 @@ export default function Sheet({ title, onClose, right, children, label, elevated
<span className="flex size-10 items-center justify-end">{right}</span>
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="sheet-scroll">
<div className="safe-bottom mx-auto max-w-2xl pb-16">{children}</div>
</div>
</div>
+161
View File
@@ -0,0 +1,161 @@
import { Check, Loader2, PenLine, Search, X } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { t } from '../../i18n'
import { useBackToClose } from '../../lib/backNav'
import { useEscape } from '../../lib/escape'
import { searchAll, type SearchResult } from '../../lib/catalogApi'
import { findFranchiseItem } from '../../lib/franchise'
import { useScrollLock } from '../../lib/scrollLock'
import { useMedia } from '../../store'
import type { MediaItem } from '../../types'
/**
* « Ajouter » : on cherche le titre (films, séries et animes en une fois), puis on ouvre sa fiche pour le noter / l'ajouter.
* Si le titre, ou une autre saison de la même série, est déjà dans la bibliothèque, on ouvre directement ma fiche.
*/
export default function AddTitle({
onClose,
onPick,
onOpenItem,
onManual,
onGoToSettings,
}: {
onClose: () => void
onPick: (r: SearchResult) => void
onOpenItem: (item: MediaItem) => void
onManual: (title: string) => void
onGoToSettings?: () => void
}) {
const { items, settings } = useMedia()
useScrollLock()
useEscape(onClose)
useBackToClose(onClose)
const hasKey = !!settings.tmdbKey?.trim()
const [query, setQuery] = useState('')
const [results, setResults] = useState<SearchResult[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string>()
const request = useRef(0)
const inLibrary = (r: SearchResult) =>
items.find((i) => i.externalId === r.externalId) ?? findFranchiseItem(items, [r.title, r.originalTitle, ...(r.altTitles ?? [])], { type: r.typeGuess })
useEffect(() => {
const q = query.trim()
// Toute réponse d'une recherche précédente devient caduque
const id = ++request.current
setError(undefined)
if (q.length < 2) {
setResults([])
setLoading(false)
return
}
setLoading(true)
const timer = setTimeout(async () => {
try {
const res = await searchAll(q, hasKey ? settings.tmdbKey : undefined)
if (id === request.current) setResults(res)
} catch (e) {
if (id === request.current) {
setResults([])
setError(navigator.onLine ? (e as Error).message : t('search.offline'))
}
} finally {
if (id === request.current) setLoading(false)
}
}, 350)
return () => clearTimeout(timer)
}, [query, hasKey, settings.tmdbKey])
const searched = query.trim().length >= 2
return (
<div className="sheet sheet-in" role="dialog" aria-modal="true" aria-label={t('title.addTitle')}>
<header className="safe-top border-b border-line">
<div className="mx-auto max-w-2xl px-3 pb-3 pt-2.5">
<div className="flex items-center gap-2">
<button onClick={onClose} className="grid size-10 shrink-0 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{t('title.addTitle')}</h2>
<span className="size-10 shrink-0" />
</div>
<div className="relative mt-2">
<Search size={18} className="pointer-events-none absolute start-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('title.searchPh')}
className="field ps-10"
enterKeyHint="search"
autoComplete="off"
autoFocus
/>
{loading && <Loader2 size={17} className="absolute end-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</div>
</div>
</header>
<div className="sheet-scroll">
<div className="safe-bottom mx-auto max-w-2xl px-4 pb-16 pt-2">
{!hasKey && (
<div className="mt-4 rounded-2xl border border-dashed border-line-strong p-4 text-sm text-ink-2">
{t('search.animeOnly')}
{onGoToSettings && (
<button onClick={onGoToSettings} className="mt-2 block font-medium text-ink">
{t('search.openSettings')} <span className="text-accent">→</span>
</button>
)}
</div>
)}
{error && <p className="mt-4 text-sm text-accent">{error}</p>}
{results.length > 0 && (
<ul className="divide-y divide-line">
{results.map((r) => {
const mine = inLibrary(r)
return (
<li key={r.externalId}>
<button onClick={() => (mine ? onOpenItem(mine) : onPick(r))} className="flex w-full items-center gap-3 py-3 text-start active:bg-surface">
{r.thumb ? (
<img src={r.thumb} alt="" loading="lazy" className="h-[5.25rem] w-14 shrink-0 rounded-lg border border-line bg-surface-2 object-cover" />
) : (
<span className="grid h-[5.25rem] w-14 shrink-0 place-items-center rounded-lg border border-line bg-surface-2 font-semibold text-ink-3">{r.title.charAt(0)}</span>
)}
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold">{r.title}</span>
{r.originalTitle && <span className="block truncate text-xs text-ink-3">{r.originalTitle}</span>}
<span className="mt-1 block text-[11px] uppercase tracking-wide text-ink-3">{[r.year, r.kindLabel].filter(Boolean).join(' · ')}</span>
{mine && (
<span className="mt-1 inline-flex items-center gap-1 text-xs text-accent">
<Check size={12} /> {t('title.inLibrary')}
</span>
)}
</span>
<span className="shrink-0 text-accent">→</span>
</button>
</li>
)
})}
</ul>
)}
{!loading && !error && searched && results.length === 0 && <p className="mt-6 text-center text-sm text-ink-3">{t('title.noResults')}</p>}
{!searched && <p className="mt-8 text-center text-sm text-ink-3">{t('title.searchHint')}</p>}
<button onClick={() => onManual(query.trim())} className="mt-8 flex w-full items-center gap-3 rounded-2xl border border-dashed border-line-strong px-4 py-3.5 text-start">
<PenLine size={18} className="shrink-0 text-accent" />
<span>
<span className="block text-sm font-medium">{t('title.manual')}</span>
<span className="block text-xs text-ink-3">{t('title.manualHint')}</span>
</span>
</button>
<p className="mt-6 text-center text-[11px] leading-relaxed text-ink-3">{t('search.privacy', { source: hasKey ? 'TMDB / AniList' : 'AniList' })}</p>
</div>
</div>
</div>
)
}
+209
View File
@@ -0,0 +1,209 @@
import { ImagePlus, X } from 'lucide-react'
import { useMemo, useRef, useState, type ReactNode } from 'react'
import { t } from '../../i18n'
import { useBackToClose } from '../../lib/backNav'
import { useEscape } from '../../lib/escape'
import { DEFAULT_FILM_MINUTES, MEDIA_TYPES, TYPE_BY_VALUE } from '../../lib/constants'
import { canonicalGenre, canonicalSubtype, genreLabel, genreSuggestions as defaultGenres, subtypeLabel, subtypeSuggestions } from '../../lib/genres'
import { fileToPosterDataURL } from '../../lib/image'
import { useScrollLock } from '../../lib/scrollLock'
import { cx } from '../../lib/utils'
import { useMedia } from '../../store'
import type { MediaInput, MediaItem } from '../../types'
import Poster from '../Poster'
import TagInput from '../TagInput'
const toNum = (v: string) => (v === '' ? undefined : Math.max(0, Math.round(Number(v))))
function Field({ label, children, className }: { label: string; children: ReactNode; className?: string }) {
return (
<label className={cx('block', className)}>
<span className="label">{label}</span>
{children}
</label>
)
}
type Draft = Pick<MediaInput, 'title' | 'originalTitle' | 'type' | 'subtype' | 'year' | 'poster' | 'episodesTotal' | 'season' | 'episodeDuration' | 'duration' | 'genres' | 'overview'>
/**
* Infos d'un titre (titre, type, affiche, épisodes…).
* Sert à corriger une fiche, ou à créer un titre introuvable en ligne (`item` absent).
*/
export default function EditDetails({
item,
initialTitle = '',
onClose,
onCreated,
}: {
item?: MediaItem
initialTitle?: string
onClose: () => void
onCreated?: (item: MediaItem) => void
onGoToSettings?: () => void
}) {
const { items, add, update } = useMedia()
useScrollLock()
useEscape(onClose)
useBackToClose(onClose)
const [draft, setDraft] = useState<Draft>(() => ({
title: item?.title ?? initialTitle,
originalTitle: item?.originalTitle,
type: item?.type ?? 'film',
subtype: item?.subtype,
year: item?.year,
poster: item?.poster,
episodesTotal: item?.episodesTotal,
season: item?.season,
episodeDuration: item?.episodeDuration,
duration: item?.duration,
genres: item?.genres ?? [],
overview: item?.overview,
}))
const [saving, setSaving] = useState(false)
const [posterError, setPosterError] = useState<string>()
const fileRef = useRef<HTMLInputElement>(null)
const set = <K extends keyof Draft>(k: K, v: Draft[K]) => setDraft((d) => ({ ...d, [k]: v }))
const typeInfo = TYPE_BY_VALUE[draft.type]
const genreSuggestions = useMemo(() => [...new Set([...items.flatMap((i) => i.genres.map(genreLabel)), ...defaultGenres()])], [items])
const pickImage = async (file?: File) => {
if (!file) return
setPosterError(undefined)
try {
set('poster', await fileToPosterDataURL(file))
} catch (e) {
setPosterError((e as Error).message)
}
}
const submit = async () => {
if (!draft.title.trim() || saving) return
setSaving(true)
const clean: Draft = {
...draft,
title: draft.title.trim(),
originalTitle: draft.originalTitle?.trim() || undefined,
subtype: draft.type === 'autre' && draft.subtype?.trim() ? canonicalSubtype(draft.subtype) : undefined,
overview: draft.overview?.trim() || undefined,
poster: draft.poster || undefined,
}
try {
if (item) {
const patch: Partial<MediaInput> = { ...clean }
if (clean.episodesTotal && item.episodesWatched > clean.episodesTotal) patch.episodesWatched = clean.episodesTotal
await update(item.id, patch)
onClose()
} else {
const created = await add({ ...clean, status: 'a_voir', criteria: {}, episodesWatched: 0 })
onCreated?.(created)
}
} finally {
setSaving(false)
}
}
return (
<div className="sheet sheet-in z-[60]" role="dialog" aria-modal="true" aria-label={t('hero.edit')}>
<header className="safe-top border-b border-line">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{item ? t('hero.edit') : t('title.manualTitle')}</h2>
<button onClick={submit} disabled={!draft.title.trim() || saving} className="btn btn-light px-4 py-2 text-sm">
{item ? t('common.save') : t('common.add')}
</button>
</div>
</header>
<form
className="sheet-scroll"
onSubmit={(e) => {
e.preventDefault()
void submit()
}}
>
<div className="safe-bottom mx-auto max-w-2xl space-y-7 px-4 py-6 pb-16">
<div className="flex gap-4">
<div className="w-28 shrink-0">
<button type="button" onClick={() => fileRef.current?.click()} className="relative block w-full" aria-label={t('form.pickPoster')}>
<Poster src={draft.poster} title={draft.title || '?'} />
<span className="absolute bottom-2 end-2 grid size-8 place-items-center rounded-full bg-bg/85 text-ink">
<ImagePlus size={15} />
</span>
</button>
<input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => pickImage(e.target.files?.[0])} />
{draft.poster && (
<button type="button" onClick={() => set('poster', undefined)} className="mt-2 w-full text-xs text-ink-3">
{t('form.removeImage')}
</button>
)}
{posterError && <p className="mt-2 text-xs text-accent">{posterError}</p>}
</div>
<div className="min-w-0 flex-1 space-y-4">
<Field label={t('form.title')}>
<input className="field" value={draft.title} onChange={(e) => set('title', e.target.value)} placeholder={t('form.titlePh')} required autoFocus={!item} />
</Field>
<Field label={t('form.originalTitle')}>
<input className="field" value={draft.originalTitle ?? ''} onChange={(e) => set('originalTitle', e.target.value)} placeholder={t('form.originalTitlePh')} />
</Field>
</div>
</div>
<div>
<span className="label">{t('form.type')}</span>
<div className="flex flex-wrap gap-2">
{MEDIA_TYPES.map((mt) => (
<button key={mt.value} type="button" onClick={() => set('type', mt.value)} className={cx('chip', draft.type === mt.value && 'chip-on')}>
{mt.label}
</button>
))}
</div>
{draft.type === 'autre' && (
<Field label={t('form.subtype')} className="mt-4">
<input className="field" list="subtypes" value={draft.subtype ? subtypeLabel(draft.subtype) : ''} onChange={(e) => set('subtype', e.target.value)} placeholder={t('form.subtypePh')} />
<datalist id="subtypes">
{subtypeSuggestions().map((s) => (
<option key={s} value={s} />
))}
</datalist>
</Field>
)}
</div>
<div className="grid grid-cols-3 gap-3">
<Field label={t('form.year')}>
<input className="field" type="number" inputMode="numeric" value={draft.year ?? ''} onChange={(e) => set('year', toNum(e.target.value))} placeholder="2024" />
</Field>
{typeInfo.episodic ? (
<>
<Field label={t('form.total')} className="col-span-2">
<input className="field" type="number" inputMode="numeric" min={0} value={draft.episodesTotal ?? ''} onChange={(e) => set('episodesTotal', toNum(e.target.value))} placeholder="?" />
</Field>
</>
) : (
<Field label={t('form.durationMin')} className="col-span-2">
<input className="field" type="number" inputMode="numeric" min={0} value={draft.duration ?? ''} onChange={(e) => set('duration', toNum(e.target.value))} placeholder={String(DEFAULT_FILM_MINUTES)} />
</Field>
)}
</div>
{typeInfo.episodic && (
<Field label={t('form.season')} className="w-1/3">
<input className="field" type="number" inputMode="numeric" min={0} value={draft.season ?? ''} onChange={(e) => set('season', toNum(e.target.value))} placeholder="1" />
</Field>
)}
<div>
<span className="label">{t('form.genres')}</span>
<TagInput value={draft.genres} onChange={(g) => set('genres', g)} suggestions={genreSuggestions} placeholder={t('form.genresPh')} display={genreLabel} normalize={canonicalGenre} />
</div>
<Field label={t('form.synopsis')}>
<textarea className="field min-h-28 resize-y" value={draft.overview ?? ''} onChange={(e) => set('overview', e.target.value)} />
</Field>
</div>
</form>
</div>
)
}
+43
View File
@@ -0,0 +1,43 @@
import { X } from 'lucide-react'
import { useState } from 'react'
import { t } from '../../i18n'
import { useBackToClose } from '../../lib/backNav'
import { useEscape } from '../../lib/escape'
import { LIMITS } from '../../lib/security'
/** Écriture de mon avis, en plein écran pour avoir la place d'écrire. */
export default function ReviewEditor({ title, initial, onSave, onClose }: { title: string; initial: string; onSave: (notes: string) => void; onClose: () => void }) {
const [text, setText] = useState(initial)
useEscape(onClose)
useBackToClose(onClose)
const changed = text.trim() !== initial.trim()
return (
<div className="sheet sheet-in z-[60]" role="dialog" aria-modal="true" aria-label={t('form.review')}>
<header className="safe-top border-b border-line">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{title}</h2>
<button onClick={() => onSave(text.trim())} disabled={!changed} className="btn btn-light px-4 py-2 text-sm">
{t('common.save')}
</button>
</div>
</header>
<div className="sheet-scroll">
<div className="safe-bottom mx-auto max-w-2xl px-4 py-5">
<span className="eyebrow">{t('form.review')}</span>
<textarea
className="field mt-2 min-h-[45dvh] resize-none leading-relaxed"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={t('form.reviewPh')}
maxLength={LIMITS.notes}
autoFocus
/>
<p className="mt-2 text-xs text-ink-3">{t('title.reviewPublicHint')}</p>
</div>
</div>
</div>
)
}
+721
View File
@@ -0,0 +1,721 @@
import { locale, t } from '../../i18n'
import { Bookmark, Check, ChevronDown, Eye, Heart, Loader2, MessagesSquare, Minus, MoreHorizontal, Pencil, Play, Plus, Share2, Trash2, X } from 'lucide-react'
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { getTitleExtras, getTmdbCredits, getTmdbDetails, getTmdbExtras, type SearchResult, type TitleExtras } from '../../lib/catalogApi'
import { CRITERIA, STATUS_BY_VALUE, TYPE_BY_VALUE } from '../../lib/constants'
import { genreLabel } from '../../lib/genres'
import { remotePosterToLocal } from '../../lib/image'
import { airedCount, nextAirDate, useAiringCache } from '../../lib/airing'
import { useBackToClose } from '../../lib/backNav'
import { useEscape } from '../../lib/escape'
import { episodeCap, seasonPosition } from '../../lib/franchise'
import { useScrollLock } from '../../lib/scrollLock'
import { renderItemCard, slug } from '../../lib/shareCard'
import { cx, formatDate, formatDuration, formatRating, todayISO } from '../../lib/utils'
import { useMedia } from '../../store'
import type { MediaInput, MediaItem, RatingScale, WatchStatus } from '../../types'
import ConfirmDialog from '../ConfirmDialog'
import EpisodeList from '../EpisodeList'
import { useSocial } from '../social/SocialProvider'
import { NewListForm } from '../ListsView'
import Poster from '../Poster'
import { RatingInput } from '../Rating'
import SharePreview from '../SharePreview'
import EditDetails from './EditDetails'
import ReviewEditor from './ReviewEditor'
/** Suivi « vide » d'un titre qu'on ajoute. */
const BLANK: Pick<MediaInput, 'criteria' | 'episodesWatched' | 'genres'> = { criteria: {}, episodesWatched: 0, genres: [] }
interface Props {
/** Titre déjà dans ma bibliothèque */
item?: MediaItem
/** Titre trouvé en ligne (pas encore ajouté) */
seed?: SearchResult
onClose: () => void
onGoToSettings?: () => void
}
/**
* Fiche d'un titre, façon Letterboxd : tout se fait ici, et chaque geste est enregistré tout de suite.
* Vu / En cours / À voir, note, coup de cœur, avis, épisodes, casting et note moyenne du public.
*/
export default function TitleSheet({ item: initial, seed, onClose, onGoToSettings }: Props) {
const { items, settings, add, update, remove, lists } = useMedia()
const social = useSocial()
useScrollLock()
useEscape(onClose)
useBackToClose(onClose)
// La fiche suit la version à jour de la bibliothèque (ou celle créée depuis cette fiche)
const [itemId, setItemId] = useState<string | undefined>(() => initial?.id ?? (seed && items.find((i) => i.externalId === seed.externalId)?.id))
const item = useMemo(() => (itemId ? items.find((i) => i.id === itemId) : undefined), [items, itemId])
// Infos du catalogue pour un titre pas encore ajouté
const [meta, setMeta] = useState<Partial<MediaInput> | undefined>(() => (seed?.source === 'anilist' ? { ...seed.prefill } : undefined))
const [metaError, setMetaError] = useState<string>()
useEffect(() => {
if (!seed || seed.source !== 'tmdb' || item) return
let alive = true
getTmdbDetails(seed, settings.tmdbKey ?? '')
.then((d) => alive && setMeta(d))
.catch((e: Error) => alive && setMetaError(navigator.onLine ? e.message : t('search.offline')))
return () => {
alive = false
}
}, [seed, item, settings.tmdbKey])
const data: Partial<MediaInput> = item ?? { ...meta, title: meta?.title ?? seed?.title, year: meta?.year ?? seed?.year, type: meta?.type ?? seed?.typeGuess }
const title = data.title ?? seed?.title ?? '?'
const type = data.type ?? 'film'
const episodic = TYPE_BY_VALUE[type].episodic
const externalId = item?.externalId ?? seed?.externalId
const poster = item?.poster ?? seed?.posterUrl
const backdrop = item?.backdrop ?? data.backdrop
// Note moyenne, casting… (en ligne)
const [extras, setExtras] = useState<TitleExtras>()
useEffect(() => {
if (!externalId || !navigator.onLine) return
let alive = true
getTitleExtras(externalId, settings.tmdbKey)
.then((x) => alive && setExtras(x))
.catch(() => {})
return () => {
alive = false
}
}, [externalId, settings.tmdbKey])
// Fiche TMDB ajoutée avant le suivi par saison : grande image et saisons récupérées en arrière-plan (et gardées)
useEffect(() => {
const key = settings.tmdbKey?.trim()
if (!item || !item.externalId?.startsWith('tmdb:') || !key || !navigator.onLine) return
const isTv = item.externalId.startsWith('tmdb:tv:')
if (item.backdrop && (!isTv || item.seasons)) return
let alive = true
getTmdbExtras(item.externalId, key)
.then(({ seasons, total, backdrop: bd }) => {
if (!alive) return
const patch: Partial<MediaInput> = {}
if (bd && !item.backdrop) patch.backdrop = bd
if (seasons && !item.seasons) {
patch.seasons = seasons
if ((total ?? 0) > (item.episodesTotal ?? 0)) patch.episodesTotal = total
}
if (Object.keys(patch).length) void update(item.id, patch)
})
.catch(() => {})
return () => {
alive = false
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [item?.id])
// Garde la note du public de la fiche à jour (utilisée par les stats « Moi vs le public »)
useEffect(() => {
if (item && extras?.average != null && Math.abs((item.publicRating ?? 0) - extras.average) >= 0.1) void update(item.id, { publicRating: extras.average })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [extras?.average, item?.id])
const [busy, setBusy] = useState(false)
const [toast, setToast] = useState<string>()
useEffect(() => {
if (!toast) return
const id = setTimeout(() => setToast(undefined), 2200)
return () => clearTimeout(id)
}, [toast])
/** Applique un changement ; ajoute d'abord le titre à la bibliothèque s'il n'y est pas encore. */
const save = async (patch: Partial<MediaInput>) => {
if (item) return update(item.id, patch)
if (busy || !seed) return
setBusy(true)
try {
const base: Partial<MediaInput> = { ...(seed.source === 'tmdb' ? meta : seed.prefill) }
if (seed.source === 'tmdb' && !meta) Object.assign(base, await getTmdbDetails(seed, settings.tmdbKey ?? ''))
// TMDB autorise la copie locale de l'affiche (visible hors-ligne) ; AniList non, on garde l'adresse.
if (seed.posterUrl) base.poster = seed.source === 'tmdb' ? await remotePosterToLocal(seed.posterUrl).catch(() => seed.posterUrl) : seed.posterUrl
if (extras?.average != null) base.publicRating = extras.average
const created = await add({
...BLANK,
status: 'a_voir',
...base,
title: base.title ?? seed.title,
type: base.type ?? seed.typeGuess,
genres: base.genres ?? [],
...patch,
} as MediaInput)
setItemId(created.id)
setToast(t('title.added'))
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
const status = item?.status
const setStatus = (s: WatchStatus) => {
if (s === status) return
const patch: Partial<MediaInput> = { status: s }
const today = todayISO()
if (s === 'a_voir') Object.assign(patch, { startDate: undefined, endDate: undefined })
if (s === 'en_cours') Object.assign(patch, { startDate: item?.startDate ?? today, endDate: undefined })
if (s === 'termine') {
patch.endDate = item?.endDate ?? today
if (!item?.startDate && !episodic) patch.startDate = patch.endDate
const cap = episodeCap(item ?? { episodesTotal: data.episodesTotal, seasons: data.seasons })
if (episodic && cap) patch.episodesWatched = cap
}
void save(patch)
}
/** Noter un titre pas encore vu le marque comme vu (comme sur Letterboxd). */
const rate = (rating: number | undefined) => {
const patch: Partial<MediaInput> = { rating }
if (rating != null && (!item || item.status === 'a_voir')) {
patch.status = 'termine'
patch.endDate = todayISO()
const cap = episodeCap(item ?? { episodesTotal: data.episodesTotal, seasons: data.seasons })
if (episodic && cap) patch.episodesWatched = cap
}
void save(patch)
}
/** Nouveaux épisodes vus : le statut et les dates suivent (comme la liste d'épisodes). */
const setEpisodes = (n: number, season?: number) => {
if (!item) return
const cap = episodeCap(item)
const watched = Math.max(0, cap ? Math.min(n, cap) : n)
const patch: Partial<MediaInput> = {
episodesWatched: watched,
season: item.seasons ? (season ?? seasonPosition({ ...item, episodesWatched: watched, season: undefined })?.season) : item.season,
}
if (watched > 0 && (item.status === 'a_voir' || item.status === 'pause')) Object.assign(patch, { status: 'en_cours', startDate: item.startDate ?? todayISO() })
if (cap && watched >= cap) Object.assign(patch, { status: 'termine', endDate: item.endDate ?? todayISO() })
else if (item.status === 'termine' && watched < item.episodesWatched) Object.assign(patch, { status: 'en_cours', endDate: undefined })
void update(item.id, patch)
}
// Épisodes déjà sortis (fiche suivie) : on ne coche pas un épisode à venir
const airingCache = useAiringCache()
const airingRef = item ? { id: item.id, type: item.type, externalId: item.externalId } : undefined
const aired = airingRef ? airedCount(airingRef, airingCache) : undefined
/** Bouton principal des épisodes : « J'ai vu S2 · É3 », « À jour », « Tout vu »… */
const nextEpisode = (() => {
if (!item || !episodic) return undefined
const cap = episodeCap(item)
if (cap && item.episodesWatched >= cap) return { label: t('hero.allSeen'), done: true }
if (aired != null && item.episodesWatched >= aired) {
const date = airingRef ? nextAirDate(airingRef, airingCache) : undefined
return { label: date ? t('hero.nextOn', { date: formatDate(date) }) : t('hero.upToDate'), done: true }
}
const pos = seasonPosition({ ...item, episodesWatched: item.episodesWatched + 1, season: undefined })
const ep = t('episodes.short', { n: pos ? pos.episode : item.episodesWatched + 1 })
return { label: t('hero.seenEp', { ep: pos ? `${t('episodes.seasonShort', { n: pos.season })} · ${ep}` : ep }), done: false }
})()
const hasEpisodeList = !!item && (!!item.seasons || (!!item.externalId && !!item.episodesTotal))
const [reviewing, setReviewing] = useState(false)
const [editing, setEditing] = useState(false)
const [moreOpen, setMoreOpen] = useState(false)
const [confirmDelete, setConfirmDelete] = useState(false)
const [preview, setPreview] = useState<{ blob: Blob; filename: string }>()
const [sharing, setSharing] = useState(false)
const shareCard = async () => {
if (!item) return
setSharing(true)
try {
let credits
if (settings.tmdbKey && item.externalId?.startsWith('tmdb:') && navigator.onLine) {
credits = await getTmdbCredits(item.externalId, settings.tmdbKey).catch(() => undefined)
}
const blob = await renderItemCard(item, settings.ratingScale, credits)
setPreview({ blob, filename: `azuucine-${slug(item.title)}.png` })
} finally {
setSharing(false)
}
}
const onDelete = async () => {
if (!item) return
setConfirmDelete(false)
await remove(item.id)
onClose()
}
const average = extras?.average ?? data.publicRating
const source = externalId?.startsWith('anilist:') ? 'AniList' : externalId ? 'TMDB' : undefined
const runtime = type === 'film' ? (data.duration ?? extras?.runtime) : undefined
const metaLine = [
data.year,
data.subtype ? data.subtype : TYPE_BY_VALUE[type].label,
runtime ? formatDuration(runtime) : undefined,
episodic && data.episodesTotal ? t('title.eps', { count: data.episodesTotal }) : undefined,
episodic && extras?.seasons && extras.seasons > 1 ? t('title.seasons', { count: extras.seasons }) : undefined,
].filter(Boolean)
return (
<div className="sheet sheet-in" role="dialog" aria-modal="true" aria-label={title}>
<header className="safe-top border-b border-line bg-bg">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{title}</h2>
{item ? (
<button onClick={() => setMoreOpen(true)} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('title.more')}>
<MoreHorizontal size={22} />
</button>
) : (
<span className="size-10" />
)}
</div>
</header>
<div className="sheet-scroll">
<div className="safe-bottom mx-auto max-w-2xl pb-20">
{/* Image de scène + affiche */}
{(backdrop ?? extras?.backdrop) ? (
<img src={backdrop ?? extras?.backdrop} alt="" className="aspect-[16/8] w-full border-b border-line object-cover opacity-80" />
) : (
<div className="h-6" />
)}
<div className="flex gap-4 px-4">
<div className={cx('relative w-28 shrink-0', (backdrop ?? extras?.backdrop) && '-mt-14')}>
<Poster src={poster} title={title} className="shadow-none" />
</div>
<div className="min-w-0 flex-1 pt-3">
<h1 className="text-2xl leading-tight">{title}</h1>
{data.originalTitle && <p className="mt-1 truncate text-sm text-ink-3">{data.originalTitle}</p>}
{metaLine.length > 0 && <p className="mt-2 text-xs uppercase tracking-wide text-ink-3">{metaLine.join(' · ')}</p>}
{extras && extras.directors.length > 0 && (
<p className="mt-2 text-sm text-ink-2">
{extras.directorKind === 'director' ? t('title.directedBy') : t('title.createdBy')} <span className="text-ink">{extras.directors.join(', ')}</span>
</p>
)}
{status && (
<p className="mt-2 inline-flex items-center gap-1.5 text-xs text-ink-2">
<Check size={13} className="text-accent" /> {t('title.inLibrary')} · {STATUS_BY_VALUE[status].label}
</p>
)}
</div>
</div>
{metaError && !item && <p className="mx-4 mt-4 text-sm text-accent">{metaError}</p>}
{/* Note moyenne du public */}
{source && <PublicRating average={average} votes={extras?.votes} distribution={extras?.distribution} scale={settings.ratingScale} source={source} mine={item?.rating} />}
{/* Mes actions */}
<section className="card mx-4 mt-4 p-4">
<div className="grid grid-cols-3 gap-2">
<StatusButton icon={<Eye size={22} />} label={t('hero.seen')} on={status === 'termine'} onClick={() => setStatus('termine')} disabled={busy} />
{episodic ? (
<StatusButton icon={<Play size={22} />} label={t('status.en_cours')} on={status === 'en_cours'} onClick={() => setStatus('en_cours')} disabled={busy} />
) : (
<StatusButton
icon={<Heart size={22} className={item?.favorite ? 'fill-current' : ''} />}
label={t('form.favorite')}
on={!!item?.favorite}
onClick={() => void save({ favorite: !item?.favorite || undefined, ...(item ? {} : { status: 'termine', endDate: todayISO() }) })}
disabled={busy}
/>
)}
<StatusButton icon={<Bookmark size={22} />} label={t('status.a_voir')} on={status === 'a_voir'} onClick={() => setStatus('a_voir')} disabled={busy} />
</div>
{item && (
<div className="mt-3 flex flex-wrap gap-2">
{(['pause', 'abandonne'] as const).map((s) => (
<button key={s} onClick={() => setStatus(s)} className={cx('chip py-1 text-xs', status === s && 'chip-on')}>
{STATUS_BY_VALUE[s].label}
</button>
))}
</div>
)}
<div className="mt-5 border-t border-line pt-4">
<div className="mb-2 flex items-center justify-between">
<span className="eyebrow">{t('title.yourRating')}</span>
{episodic && (
<button
onClick={() => void save({ favorite: !item?.favorite || undefined })}
className={cx('flex items-center gap-1.5 text-xs font-medium', item?.favorite ? 'text-accent' : 'text-ink-3')}
aria-pressed={!!item?.favorite}
>
<Heart size={15} className={item?.favorite ? 'fill-accent' : ''} /> {t('form.favorite')}
</button>
)}
</div>
<RatingInput value={item?.rating} onChange={rate} scale={settings.ratingScale} />
{item?.rating != null && <Criteria item={item} scale={settings.ratingScale} onChange={(criteria) => void update(item.id, { criteria })} />}
</div>
{busy && (
<p className="mt-3 flex items-center gap-2 text-xs text-ink-3">
<Loader2 size={13} className="animate-spin" /> {t('title.adding')}
</p>
)}
</section>
{/* Épisodes */}
{item && episodic && (
<section className="mx-4 mt-4">
{nextEpisode && (
<button
onClick={nextEpisode.done ? undefined : () => setEpisodes(item.episodesWatched + 1)}
disabled={nextEpisode.done}
className={cx('btn mb-3 w-full py-3', nextEpisode.done ? 'btn-ghost' : 'btn-primary')}
>
{nextEpisode.done && <Check size={17} />}
{nextEpisode.label}
</button>
)}
{hasEpisodeList ? (
<EpisodeList form={item} aired={aired} onChange={setEpisodes} />
) : (
<div className="card p-4">
<div className="flex items-center justify-between gap-3">
<div>
<span className="eyebrow">{t('home.episodesSeen')}</span>
<p className="mt-1 text-2xl font-bold tabular-nums">
{item.episodesWatched}
{episodeCap(item) ? <span className="text-base font-normal text-ink-3"> / {episodeCap(item)}</span> : null}
</p>
</div>
<div className="flex items-center gap-2">
<button onClick={() => setEpisodes(item.episodesWatched - 1)} className="grid size-11 place-items-center rounded-full border border-line-strong text-ink-2" aria-label={t('form.minusEp')}>
<Minus size={18} />
</button>
<button onClick={() => setEpisodes(item.episodesWatched + 1)} className="grid size-11 place-items-center rounded-full bg-accent-fill text-on-accent" aria-label={t('form.plusEp')}>
<Plus size={18} strokeWidth={2.5} />
</button>
</div>
</div>
{episodeCap(item) ? (
<div className="mt-3 h-1 rounded-full bg-surface-2">
<div className="h-full rounded-full bg-accent" style={{ width: `${Math.min(100, (item.episodesWatched / episodeCap(item)!) * 100)}%` }} />
</div>
) : null}
</div>
)}
</section>
)}
{/* Mon avis */}
<section className="mx-4 mt-4">
{item?.notes ? (
<button onClick={() => setReviewing(true)} className="card block w-full p-4 text-left">
<span className="eyebrow flex items-center justify-between">
{t('form.review')} <Pencil size={13} />
</span>
<p className="mt-2 line-clamp-6 whitespace-pre-line text-sm leading-relaxed text-ink">{item.notes}</p>
</button>
) : (
<button onClick={() => setReviewing(true)} disabled={busy} className="flex w-full items-center gap-2 rounded-2xl border border-dashed border-line-strong px-4 py-3.5 text-left text-sm text-ink-2">
<Pencil size={16} className="text-accent" /> {t('title.writeReview')}
</button>
)}
</section>
{externalId && social.enabled && (
<button onClick={() => social.openReviews(externalId, title)} className="mx-4 mt-3 flex w-[calc(100%-2rem)] items-center justify-center gap-2 rounded-xl border border-line py-2.5 text-sm font-medium text-ink-2 active:bg-surface-2">
<MessagesSquare size={16} /> {t('reviews.seeAll')}
</button>
)}
{/* Synopsis et genres */}
{(extras?.tagline || data.overview || (data.genres?.length ?? 0) > 0) && (
<section className="mx-4 mt-8">
{extras?.tagline && <p className="mb-2 text-sm italic text-ink-2">{extras.tagline}</p>}
{data.overview && <Synopsis text={data.overview} />}
{(data.genres?.length ?? 0) > 0 && (
<div className="mt-4 flex flex-wrap gap-2">
{data.genres!.map((g) => (
<span key={g} className="rounded-full border border-line px-3 py-1 text-xs text-ink-2">
{genreLabel(g)}
</span>
))}
</div>
)}
</section>
)}
{/* Casting */}
{extras && extras.cast.length > 0 && (
<section className="mt-8">
<h3 className="eyebrow mx-4 mb-3 text-ink-2">{t('title.cast')}</h3>
<div className="no-scrollbar flex gap-3 overflow-x-auto px-4 pb-1">
{extras.cast.map((c, k) => (
<div key={c.name + k} className="w-[5.5rem] shrink-0 text-center">
{c.photo ? (
<img src={c.photo} alt="" loading="lazy" className="mx-auto size-20 rounded-full border border-line bg-surface-2 object-cover" />
) : (
<span className="mx-auto grid size-20 place-items-center rounded-full border border-line bg-surface-2 text-lg font-semibold text-ink-3">{c.name.charAt(0)}</span>
)}
<p className="mt-2 line-clamp-2 text-xs font-medium leading-snug">{c.name}</p>
{(c.role || c.voice) && <p className="mt-0.5 line-clamp-2 text-[11px] leading-snug text-ink-3">{c.role ?? t('title.voice', { name: c.voice! })}</p>}
</div>
))}
</div>
</section>
)}
{/* Mon suivi : dates, plateforme, listes, revisionnages */}
{item && <Tracking item={item} lists={lists} onChange={(patch) => void update(item.id, patch)} />}
</div>
</div>
{toast && (
<div role="status" className="safe-bottom pointer-events-none fixed inset-x-0 bottom-4 z-[70] flex justify-center px-4">
<span className="rounded-full bg-ink px-4 py-2 text-sm font-medium text-bg">{toast}</span>
</div>
)}
{moreOpen && item && (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 sm:items-center" onClick={() => setMoreOpen(false)}>
<div className="safe-bottom w-full max-w-md rounded-t-3xl border border-line-strong bg-surface p-3 sm:rounded-3xl" onClick={(e) => e.stopPropagation()}>
<MenuButton icon={<Pencil size={18} />} onClick={() => (setMoreOpen(false), setEditing(true))}>
{t('hero.edit')}
</MenuButton>
<MenuButton icon={sharing ? <Loader2 size={18} className="animate-spin" /> : <Share2 size={18} />} onClick={() => (setMoreOpen(false), void shareCard())}>
{t('form.shareImage')}
</MenuButton>
<MenuButton icon={<Trash2 size={18} />} onClick={() => (setMoreOpen(false), setConfirmDelete(true))} danger>
{t('form.delete')}
</MenuButton>
</div>
</div>
)}
{reviewing && (
<ReviewEditor
title={title}
initial={item?.notes ?? ''}
onClose={() => setReviewing(false)}
onSave={async (notes) => {
setReviewing(false)
// Écrire un avis sur un titre pas encore ajouté le marque comme vu
await save({ notes: notes || undefined, ...(item ? {} : { status: 'termine' as const, endDate: todayISO() }) })
}}
/>
)}
{editing && item && <EditDetails item={item} onClose={() => setEditing(false)} onGoToSettings={onGoToSettings} />}
{preview && <SharePreview blob={preview.blob} filename={preview.filename} title={title} onClose={() => setPreview(undefined)} />}
<ConfirmDialog
open={confirmDelete}
title={t('confirm.title')}
message={item ? t('form.deleteConfirm', { title: item.title }) : undefined}
confirmLabel={t('common.delete')}
onConfirm={onDelete}
onCancel={() => setConfirmDelete(false)}
/>
</div>
)
}
function StatusButton({ icon, label, on, onClick, disabled }: { icon: ReactNode; label: string; on: boolean; onClick: () => void; disabled?: boolean }) {
return (
<button
onClick={onClick}
disabled={disabled}
aria-pressed={on}
className={cx(
'flex flex-col items-center gap-1.5 rounded-xl border py-3 text-xs font-medium transition-colors active:scale-[0.97] disabled:opacity-50',
on ? 'border-accent bg-accent-fill text-on-accent' : 'border-line text-ink-2',
)}
>
{icon}
{label}
</button>
)
}
function MenuButton({ icon, children, onClick, danger }: { icon: ReactNode; children: ReactNode; onClick: () => void; danger?: boolean }) {
return (
<button onClick={onClick} className={cx('flex w-full items-center gap-3 rounded-xl px-3 py-3.5 text-left text-[15px] active:bg-surface-2', danger ? 'text-accent' : 'text-ink')}>
{icon}
{children}
</button>
)
}
/** Note moyenne du public, avec la répartition des votes quand la base la donne (AniList). */
function PublicRating({
average,
votes,
distribution,
scale,
source,
mine,
}: {
average?: number
votes?: number
distribution?: { score: number; amount: number }[]
scale: RatingScale
source: string
mine?: number
}) {
const max = Math.max(1, ...(distribution ?? []).map((d) => d.amount))
const compact = new Intl.NumberFormat(locale(), { notation: 'compact', maximumFractionDigits: 1 })
return (
<section className="mx-4 mt-6 flex items-end justify-between gap-4 border-b border-line pb-4">
<div className="shrink-0">
<span className="eyebrow">{t('title.average')}</span>
{average != null ? (
<>
<p className="mt-1 text-4xl font-bold leading-none tabular-nums">
{formatRating(average, scale)}
<span className="text-base font-normal text-ink-3">/{scale}</span>
</p>
<p className="mt-1.5 text-xs text-ink-3">
{votes ? `${t('title.votes', { count: votes, n: compact.format(votes) })} · ` : ''}
{source}
</p>
</>
) : (
<p className="mt-1 text-sm text-ink-3">{t('title.noAverage')}</p>
)}
{mine != null && average != null && (
<p className="mt-1 text-xs text-ink-2">
{t('title.yourRating')} <span className="font-semibold text-ink">{formatRating(mine, scale)}</span>
</p>
)}
</div>
{distribution && distribution.length > 0 && (
<div className="flex h-16 max-w-48 flex-1 items-end gap-[3px]" role="img" aria-label={t('title.distribution')}>
{Array.from({ length: 10 }, (_, k) => {
const amount = distribution.find((d) => d.score === k + 1)?.amount ?? 0
return <span key={k} className="flex-1 rounded-t-sm bg-ink-3" style={{ height: `${Math.max(4, (amount / max) * 100)}%`, opacity: amount ? 1 : 0.3 }} />
})}
</div>
)}
</section>
)
}
function Criteria({ item, scale, onChange }: { item: MediaItem; scale: RatingScale; onChange: (c: MediaItem['criteria']) => void }) {
const [open, setOpen] = useState(() => Object.keys(item.criteria).length > 0)
return (
<div className="mt-3">
<button onClick={() => setOpen((v) => !v)} className="flex items-center gap-1 text-xs text-ink-3" aria-expanded={open}>
{t('title.detailRating')} <ChevronDown size={14} className={cx('transition-transform', open && 'rotate-180')} />
</button>
{open && (
<div className="mt-3 space-y-3">
{CRITERIA.map((c) => (
<div key={c.key} className="flex items-center justify-between gap-3">
<span className="text-sm text-ink-2">{c.label}</span>
<RatingInput
size="sm"
label={c.label}
scale={scale}
value={item.criteria[c.key]}
onChange={(v) => {
const next = { ...item.criteria }
if (v == null) delete next[c.key]
else next[c.key] = v
onChange(next)
}}
/>
</div>
))}
</div>
)}
</div>
)
}
function Synopsis({ text }: { text: string }) {
const [open, setOpen] = useState(false)
const long = text.length > 320
return (
<div>
<p className={cx('whitespace-pre-line text-sm leading-relaxed text-ink-2', long && !open && 'line-clamp-5')}>{text}</p>
{long && (
<button onClick={() => setOpen((v) => !v)} className="mt-1 text-xs font-medium text-ink">
{open ? t('hero.less') : t('hero.more')}
</button>
)}
</div>
)
}
/** Dates, plateforme, listes et revisionnages : enregistrés dès qu'on les change. */
function Tracking({ item, lists, onChange }: { item: MediaItem; lists: { id: string; name: string }[]; onChange: (p: Partial<MediaInput>) => void }) {
const [open, setOpen] = useState(false)
const rewatches = item.rewatchDates ?? []
const summary = [
item.startDate && `${t('form.startShort')} ${formatDate(item.startDate)}`,
item.endDate && `${t('form.endShort')} ${formatDate(item.endDate)}`,
rewatches.length ? t('title.rewatchCount', { count: rewatches.length }) : undefined,
].filter(Boolean)
return (
<section className="mx-4 mt-8 border-t border-line pt-5">
<button onClick={() => setOpen((v) => !v)} aria-expanded={open} className="flex w-full items-center justify-between text-left">
<span>
<span className="eyebrow block text-ink-2">{t('title.myTracking')}</span>
<span className="mt-1 block text-xs text-ink-3">{summary.length ? summary.join(' · ') : t('title.trackingHint')}</span>
</span>
<ChevronDown size={18} className={cx('shrink-0 text-ink-3 transition-transform', open && 'rotate-180')} />
</button>
{open && (
<div className="mt-5 space-y-6">
<div className="grid grid-cols-2 gap-3">
<label className="block">
<span className="label">{t('form.startShort')}</span>
<input className="field" type="date" value={item.startDate ?? ''} max={todayISO()} onChange={(e) => onChange({ startDate: e.target.value || undefined })} />
</label>
<label className="block">
<span className="label">{t('form.endShort')}</span>
<input className="field" type="date" value={item.endDate ?? ''} max={todayISO()} onChange={(e) => onChange({ endDate: e.target.value || undefined })} />
</label>
</div>
<div>
<span className="label">{t('lists.myLists')}</span>
{lists.length > 0 && (
<div className="mb-3 flex flex-wrap gap-2">
{lists.map((l) => {
const on = item.listIds?.includes(l.id)
return (
<button
key={l.id}
onClick={() => onChange({ listIds: on ? item.listIds!.filter((x) => x !== l.id) : [...(item.listIds ?? []), l.id] })}
className={cx('chip', on && 'chip-on')}
>
{on && <Check size={14} />}
{l.name}
</button>
)
})}
</div>
)}
<NewListForm onCreated={(l) => onChange({ listIds: [...(item.listIds ?? []), l.id] })} />
</div>
<div>
<span className="label">{t('form.rewatches')}</span>
{rewatches.length > 0 && (
<ul className="mb-3 divide-y divide-line rounded-xl border border-line px-3">
{rewatches.map((d, k) => (
<li key={d + k} className="flex items-center justify-between py-2 text-sm">
<span>{formatDate(d)}</span>
<button onClick={() => onChange({ rewatchDates: rewatches.filter((_, j) => j !== k).length ? rewatches.filter((_, j) => j !== k) : undefined })} className="grid size-8 place-items-center text-ink-3" aria-label={t('form.removeRewatch')}>
<X size={16} />
</button>
</li>
))}
</ul>
)}
<button
onClick={() => rewatches.length < 100 && onChange({ rewatchDates: [todayISO(), ...rewatches].sort().reverse() })}
className="btn btn-ghost py-2 text-sm"
>
<Plus size={16} /> {t('title.rewatchedToday')}
</button>
</div>
</div>
)}
</section>
)
}
+45
View File
@@ -969,6 +969,51 @@ const dict: Translations = {
'homeHero.details': 'التفاصيل',
'homeHero.continueRow': 'متابعة المشاهدة',
'homeHero.nextUp': 'التالي: {ep}',
'title.addTitle': "إضافة عنوان",
'title.searchPh': "فيلم، مسلسل، أنمي، دراما…",
'title.searchHint': "ابحث عن عنوان ثم افتح صفحته لتقييمه أو وضع علامة مشاهدة أو إضافته إلى قائمتك.",
'title.noResults': "لا توجد نتائج.",
'title.manual': "إضافة يدويًا",
'title.manualHint': "لم تجده؟ أنشئ الصفحة بنفسك.",
'title.manualTitle': "عنوان جديد",
'title.inLibrary': "في مكتبتك",
'title.added': "تمت الإضافة إلى مكتبتك",
'title.adding': "جارٍ الإضافة…",
'title.yourRating': "تقييمك",
'title.average': "متوسط التقييم",
'title.votes_one': "{n} صوت",
'title.votes_other': "{n} صوت",
'title.noAverage': "لا توجد أصوات كافية بعد",
'title.distribution': "توزيع التقييمات",
'title.directedBy': "إخراج",
'title.createdBy': "إنشاء",
'title.eps_one': "{count} حلقة",
'title.eps_other': "{count} حلقة",
'title.seasons_one': "{count} موسم",
'title.seasons_other': "{count} موسم",
'title.cast': "طاقم التمثيل",
'title.voice': "الصوت: {name}",
'title.writeReview': "اكتب مراجعة…",
'title.reviewPublicHint': "مراجعتك ظاهرة في ملفك الشخصي.",
'title.detailRating': "تفصيل تقييمي",
'title.more': "خيارات أخرى",
'title.myTracking': "متابعتي",
'title.trackingHint': "التواريخ، القوائم، إعادة المشاهدة",
'title.rewatchCount_one': "أُعيدت مشاهدته مرة واحدة",
'title.rewatchCount_other': "أُعيدت مشاهدته {count} مرة",
'title.rewatchedToday': "أُعيدت مشاهدته اليوم",
'title.votes_two': "صوتان",
'title.votes_few': "{n} أصوات",
'title.votes_many': "{n} صوتًا",
'title.eps_two': "حلقتان",
'title.eps_few': "{count} حلقات",
'title.eps_many': "{count} حلقة",
'title.seasons_two': "موسمان",
'title.seasons_few': "{count} مواسم",
'title.seasons_many': "{count} موسمًا",
'title.rewatchCount_two': "أُعيدت مشاهدته مرتين",
'title.rewatchCount_few': "أُعيدت مشاهدته {count} مرات",
'title.rewatchCount_many': "أُعيدت مشاهدته {count} مرة",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "Details",
'homeHero.continueRow': "Weiterschauen",
'homeHero.nextUp': "Als Nächstes: {ep}",
'title.addTitle': "Titel hinzufügen",
'title.searchPh': "Film, Serie, Anime, Drama…",
'title.searchHint': "Suche einen Titel und öffne ihn, um ihn zu bewerten, als gesehen zu markieren oder auf deine Merkliste zu setzen.",
'title.noResults': "Keine Ergebnisse.",
'title.manual': "Manuell hinzufügen",
'title.manualHint': "Nicht gefunden? Lege den Titel selbst an.",
'title.manualTitle': "Neuer Titel",
'title.inLibrary': "In deiner Bibliothek",
'title.added': "Zu deiner Bibliothek hinzugefügt",
'title.adding': "Wird hinzugefügt…",
'title.yourRating': "Deine Bewertung",
'title.average': "Durchschnittsbewertung",
'title.votes_one': "{n} Stimme",
'title.votes_other': "{n} Stimmen",
'title.noAverage': "Noch nicht genug Stimmen",
'title.distribution': "Verteilung der Bewertungen",
'title.directedBy': "Regie:",
'title.createdBy': "Erstellt von",
'title.eps_one': "{count} Folge",
'title.eps_other': "{count} Folgen",
'title.seasons_one': "{count} Staffel",
'title.seasons_other': "{count} Staffeln",
'title.cast': "Besetzung",
'title.voice': "Stimme: {name}",
'title.writeReview': "Rezension schreiben…",
'title.reviewPublicHint': "Deine Rezension ist auf deinem Profil sichtbar.",
'title.detailRating': "Bewertung im Detail",
'title.more': "Weitere Optionen",
'title.myTracking': "Mein Verlauf",
'title.trackingHint': "Daten, Listen, erneut gesehen",
'title.rewatchCount_one': "Einmal erneut gesehen",
'title.rewatchCount_other': "{count}-mal erneut gesehen",
'title.rewatchedToday': "Heute erneut gesehen",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "Details",
'homeHero.continueRow': "Continue watching",
'homeHero.nextUp': "Next: {ep}",
'title.addTitle': "Add a title",
'title.searchPh': "Movie, series, anime, drama…",
'title.searchHint': "Search for a title, then open it to rate it, mark it as watched or add it to your watchlist.",
'title.noResults': "No results.",
'title.manual': "Add manually",
'title.manualHint': "Can’t find it? Create it yourself.",
'title.manualTitle': "New title",
'title.inLibrary': "In your library",
'title.added': "Added to your library",
'title.adding': "Adding…",
'title.yourRating': "Your rating",
'title.average': "Average rating",
'title.votes_one': "{n} vote",
'title.votes_other': "{n} votes",
'title.noAverage': "Not enough votes yet",
'title.distribution': "Rating distribution",
'title.directedBy': "Directed by",
'title.createdBy': "Created by",
'title.eps_one': "{count} episode",
'title.eps_other': "{count} episodes",
'title.seasons_one': "{count} season",
'title.seasons_other': "{count} seasons",
'title.cast': "Cast",
'title.voice': "Voice: {name}",
'title.writeReview': "Write a review…",
'title.reviewPublicHint': "Your review is visible on your profile.",
'title.detailRating': "Rate in detail",
'title.more': "More options",
'title.myTracking': "My tracking",
'title.trackingHint': "Dates, lists, rewatches",
'title.rewatchCount_one': "Rewatched once",
'title.rewatchCount_other': "Rewatched {count} times",
'title.rewatchedToday': "Rewatched today",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "Ficha",
'homeHero.continueRow': "Seguir viendo",
'homeHero.nextUp': "Siguiente: {ep}",
'title.addTitle': "Añadir un título",
'title.searchPh': "Película, serie, anime, drama…",
'title.searchHint': "Busca un título y abre su ficha para puntuarlo, marcarlo como visto o añadirlo a tu lista.",
'title.noResults': "Sin resultados.",
'title.manual': "Añadir manualmente",
'title.manualHint': "¿No lo encuentras? Crea la ficha tú mismo.",
'title.manualTitle': "Nuevo título",
'title.inLibrary': "En tu biblioteca",
'title.added': "Añadido a tu biblioteca",
'title.adding': "Añadiendo…",
'title.yourRating': "Tu nota",
'title.average': "Nota media",
'title.votes_one': "{n} voto",
'title.votes_other': "{n} votos",
'title.noAverage': "Aún no hay suficientes votos",
'title.distribution': "Distribución de notas",
'title.directedBy': "Dirigida por",
'title.createdBy': "Creada por",
'title.eps_one': "{count} episodio",
'title.eps_other': "{count} episodios",
'title.seasons_one': "{count} temporada",
'title.seasons_other': "{count} temporadas",
'title.cast': "Reparto",
'title.voice': "Voz: {name}",
'title.writeReview': "Escribir una reseña…",
'title.reviewPublicHint': "Tu reseña es visible en tu perfil.",
'title.detailRating': "Detallar mi nota",
'title.more': "Más opciones",
'title.myTracking': "Mi seguimiento",
'title.trackingHint': "Fechas, listas, revisionados",
'title.rewatchCount_one': "Vuelto a ver una vez",
'title.rewatchCount_other': "Vuelto a ver {count} veces",
'title.rewatchedToday': "Vuelto a ver hoy",
}
export default dict
+33
View File
@@ -848,6 +848,39 @@ const dict = {
'homeHero.details': "Fiche",
'homeHero.continueRow': "Reprendre",
'homeHero.nextUp': "Prochain : {ep}",
'title.addTitle': "Ajouter un titre",
'title.searchPh': "Film, série, anime, drama…",
'title.searchHint': "Cherche un titre puis ouvre sa fiche pour le noter, le marquer comme vu ou l’ajouter à ta liste.",
'title.noResults': "Aucun résultat.",
'title.manual': "Ajouter manuellement",
'title.manualHint': "Introuvable ? Crée la fiche toi-même.",
'title.manualTitle': "Nouveau titre",
'title.inLibrary': "Dans ta bibliothèque",
'title.added': "Ajouté à ta bibliothèque",
'title.adding': "Ajout…",
'title.yourRating': "Ta note",
'title.average': "Note moyenne",
'title.votes_one': "{n} vote",
'title.votes_other': "{n} votes",
'title.noAverage': "Pas encore assez de votes",
'title.distribution': "Répartition des notes",
'title.directedBy': "Réalisé par",
'title.createdBy': "Créé par",
'title.eps_one': "{count} épisode",
'title.eps_other': "{count} épisodes",
'title.seasons_one': "{count} saison",
'title.seasons_other': "{count} saisons",
'title.cast': "Casting",
'title.voice': "Voix : {name}",
'title.writeReview': "Écrire un avis…",
'title.reviewPublicHint': "Ton avis est visible sur ton profil.",
'title.detailRating': "Détailler ma note",
'title.more': "Plus d’options",
'title.myTracking': "Mon suivi",
'title.trackingHint': "Dates, listes, revisionnages",
'title.rewatchCount_one': "Revu {count} fois",
'title.rewatchCount_other': "Revu {count} fois",
'title.rewatchedToday': "Revu aujourd’hui",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': 'जानकारी',
'homeHero.continueRow': 'देखना जारी रखें',
'homeHero.nextUp': 'अगला: {ep}',
'title.addTitle': "शीर्षक जोड़ें",
'title.searchPh': "फ़िल्म, सीरीज़, एनिमे, ड्रामा…",
'title.searchHint': "कोई शीर्षक खोजें, फिर उसे रेट करने, देखा हुआ चिह्नित करने या अपनी सूची में जोड़ने के लिए खोलें।",
'title.noResults': "कोई परिणाम नहीं।",
'title.manual': "मैन्युअल रूप से जोड़ें",
'title.manualHint': "नहीं मिला? ख़ुद बनाएँ।",
'title.manualTitle': "नया शीर्षक",
'title.inLibrary': "आपकी लाइब्रेरी में",
'title.added': "आपकी लाइब्रेरी में जोड़ा गया",
'title.adding': "जोड़ रहे हैं…",
'title.yourRating': "आपकी रेटिंग",
'title.average': "औसत रेटिंग",
'title.votes_one': "{n} वोट",
'title.votes_other': "{n} वोट",
'title.noAverage': "अभी पर्याप्त वोट नहीं",
'title.distribution': "रेटिंग का वितरण",
'title.directedBy': "निर्देशक:",
'title.createdBy': "निर्माता:",
'title.eps_one': "{count} एपिसोड",
'title.eps_other': "{count} एपिसोड",
'title.seasons_one': "{count} सीज़न",
'title.seasons_other': "{count} सीज़न",
'title.cast': "कलाकार",
'title.voice': "आवाज़: {name}",
'title.writeReview': "समीक्षा लिखें…",
'title.reviewPublicHint': "आपकी समीक्षा आपकी प्रोफ़ाइल पर दिखती है।",
'title.detailRating': "रेटिंग विस्तार से",
'title.more': "और विकल्प",
'title.myTracking': "मेरी ट्रैकिंग",
'title.trackingHint': "तारीख़ें, सूचियाँ, दोबारा देखना",
'title.rewatchCount_one': "{count} बार दोबारा देखा",
'title.rewatchCount_other': "{count} बार दोबारा देखा",
'title.rewatchedToday': "आज दोबारा देखा",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': 'Detail',
'homeHero.continueRow': 'Lanjutkan nonton',
'homeHero.nextUp': 'Berikutnya: {ep}',
'title.addTitle': "Tambah judul",
'title.searchPh': "Film, serial, anime, drama…",
'title.searchHint': "Cari judul, lalu buka untuk memberi nilai, menandai sudah ditonton, atau menambahkannya ke daftarmu.",
'title.noResults': "Tidak ada hasil.",
'title.manual': "Tambah manual",
'title.manualHint': "Tidak ketemu? Buat sendiri.",
'title.manualTitle': "Judul baru",
'title.inLibrary': "Di pustakamu",
'title.added': "Ditambahkan ke pustakamu",
'title.adding': "Menambahkan…",
'title.yourRating': "Nilaimu",
'title.average': "Nilai rata-rata",
'title.votes_one': "{n} suara",
'title.votes_other': "{n} suara",
'title.noAverage': "Belum cukup suara",
'title.distribution': "Sebaran nilai",
'title.directedBy': "Disutradarai oleh",
'title.createdBy': "Dibuat oleh",
'title.eps_one': "{count} episode",
'title.eps_other': "{count} episode",
'title.seasons_one': "{count} musim",
'title.seasons_other': "{count} musim",
'title.cast': "Pemeran",
'title.voice': "Suara: {name}",
'title.writeReview': "Tulis ulasan…",
'title.reviewPublicHint': "Ulasanmu terlihat di profilmu.",
'title.detailRating': "Rinci nilaiku",
'title.more': "Opsi lain",
'title.myTracking': "Pelacakanku",
'title.trackingHint': "Tanggal, daftar, tonton ulang",
'title.rewatchCount_one': "Ditonton ulang {count} kali",
'title.rewatchCount_other': "Ditonton ulang {count} kali",
'title.rewatchedToday': "Ditonton ulang hari ini",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "Scheda",
'homeHero.continueRow': "Riprendi",
'homeHero.nextUp': "Prossimo: {ep}",
'title.addTitle': "Aggiungi un titolo",
'title.searchPh': "Film, serie, anime, drama…",
'title.searchHint': "Cerca un titolo e apri la sua scheda per votarlo, segnarlo come visto o aggiungerlo alla tua lista.",
'title.noResults': "Nessun risultato.",
'title.manual': "Aggiungi manualmente",
'title.manualHint': "Non lo trovi? Crea tu la scheda.",
'title.manualTitle': "Nuovo titolo",
'title.inLibrary': "Nella tua libreria",
'title.added': "Aggiunto alla tua libreria",
'title.adding': "Aggiunta…",
'title.yourRating': "Il tuo voto",
'title.average': "Voto medio",
'title.votes_one': "{n} voto",
'title.votes_other': "{n} voti",
'title.noAverage': "Non ci sono ancora abbastanza voti",
'title.distribution': "Distribuzione dei voti",
'title.directedBy': "Regia di",
'title.createdBy': "Creato da",
'title.eps_one': "{count} episodio",
'title.eps_other': "{count} episodi",
'title.seasons_one': "{count} stagione",
'title.seasons_other': "{count} stagioni",
'title.cast': "Cast",
'title.voice': "Voce: {name}",
'title.writeReview': "Scrivi una recensione…",
'title.reviewPublicHint': "La tua recensione è visibile sul tuo profilo.",
'title.detailRating': "Dettaglia il mio voto",
'title.more': "Altre opzioni",
'title.myTracking': "Il mio monitoraggio",
'title.trackingHint': "Date, liste, rewatch",
'title.rewatchCount_one': "Rivisto una volta",
'title.rewatchCount_other': "Rivisto {count} volte",
'title.rewatchedToday': "Rivisto oggi",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "詳細",
'homeHero.continueRow': "続きを見る",
'homeHero.nextUp': "次:{ep}",
'title.addTitle': "作品を追加",
'title.searchPh': "映画、ドラマ、アニメ…",
'title.searchHint': "作品を検索し、詳細ページから評価・視聴済み・見たいリストへの追加ができます。",
'title.noResults': "結果がありません。",
'title.manual': "手動で追加",
'title.manualHint': "見つからない場合は自分で作成できます。",
'title.manualTitle': "新しい作品",
'title.inLibrary': "ライブラリにあります",
'title.added': "ライブラリに追加しました",
'title.adding': "追加中…",
'title.yourRating': "あなたの評価",
'title.average': "平均評価",
'title.votes_one': "{n} 件の評価",
'title.votes_other': "{n} 件の評価",
'title.noAverage': "評価がまだ十分ではありません",
'title.distribution': "評価の分布",
'title.directedBy': "監督",
'title.createdBy': "制作",
'title.eps_one': "{count} 話",
'title.eps_other': "{count} 話",
'title.seasons_one': "{count} シーズン",
'title.seasons_other': "{count} シーズン",
'title.cast': "キャスト",
'title.voice': "声:{name}",
'title.writeReview': "レビューを書く…",
'title.reviewPublicHint': "レビューはプロフィールに表示されます。",
'title.detailRating': "評価を詳しく",
'title.more': "その他のオプション",
'title.myTracking': "視聴記録",
'title.trackingHint': "日付・リスト・再視聴",
'title.rewatchCount_one': "{count} 回再視聴",
'title.rewatchCount_other': "{count} 回再視聴",
'title.rewatchedToday': "今日再視聴",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "상세",
'homeHero.continueRow': "이어 보기",
'homeHero.nextUp': "다음: {ep}",
'title.addTitle': "작품 추가",
'title.searchPh': "영화, 시리즈, 애니, 드라마…",
'title.searchHint': "작품을 검색한 뒤 상세 페이지에서 평가하거나, 봤음으로 표시하거나, 보고 싶은 목록에 추가하세요.",
'title.noResults': "결과가 없어요.",
'title.manual': "직접 추가",
'title.manualHint': "찾을 수 없나요? 직접 만들어 보세요.",
'title.manualTitle': "새 작품",
'title.inLibrary': "내 라이브러리에 있음",
'title.added': "내 라이브러리에 추가했어요",
'title.adding': "추가하는 중…",
'title.yourRating': "내 평점",
'title.average': "평균 평점",
'title.votes_one': "{n}명 평가",
'title.votes_other': "{n}명 평가",
'title.noAverage': "아직 평가가 충분하지 않아요",
'title.distribution': "평점 분포",
'title.directedBy': "감독",
'title.createdBy': "제작",
'title.eps_one': "{count}화",
'title.eps_other': "{count}화",
'title.seasons_one': "시즌 {count}개",
'title.seasons_other': "시즌 {count}개",
'title.cast': "출연진",
'title.voice': "성우: {name}",
'title.writeReview': "감상 쓰기…",
'title.reviewPublicHint': "감상은 내 프로필에 표시돼요.",
'title.detailRating': "평점 자세히",
'title.more': "더 보기 옵션",
'title.myTracking': "내 기록",
'title.trackingHint': "날짜, 목록, 다시 보기",
'title.rewatchCount_one': "{count}번 다시 봄",
'title.rewatchCount_other': "{count}번 다시 봄",
'title.rewatchedToday': "오늘 다시 봄",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "Details",
'homeHero.continueRow': "Verder kijken",
'homeHero.nextUp': "Volgende: {ep}",
'title.addTitle': "Titel toevoegen",
'title.searchPh': "Film, serie, anime, drama…",
'title.searchHint': "Zoek een titel en open hem om hem te beoordelen, als gezien te markeren of op je kijklijst te zetten.",
'title.noResults': "Geen resultaten.",
'title.manual': "Handmatig toevoegen",
'title.manualHint': "Niet gevonden? Maak hem zelf aan.",
'title.manualTitle': "Nieuwe titel",
'title.inLibrary': "In je bibliotheek",
'title.added': "Toegevoegd aan je bibliotheek",
'title.adding': "Toevoegen…",
'title.yourRating': "Jouw beoordeling",
'title.average': "Gemiddelde beoordeling",
'title.votes_one': "{n} stem",
'title.votes_other': "{n} stemmen",
'title.noAverage': "Nog niet genoeg stemmen",
'title.distribution': "Verdeling van de beoordelingen",
'title.directedBy': "Geregisseerd door",
'title.createdBy': "Gemaakt door",
'title.eps_one': "{count} aflevering",
'title.eps_other': "{count} afleveringen",
'title.seasons_one': "{count} seizoen",
'title.seasons_other': "{count} seizoenen",
'title.cast': "Cast",
'title.voice': "Stem: {name}",
'title.writeReview': "Recensie schrijven…",
'title.reviewPublicHint': "Je recensie is zichtbaar op je profiel.",
'title.detailRating': "Beoordeling in detail",
'title.more': "Meer opties",
'title.myTracking': "Mijn voortgang",
'title.trackingHint': "Datums, lijsten, opnieuw bekeken",
'title.rewatchCount_one': "Eén keer opnieuw bekeken",
'title.rewatchCount_other': "{count} keer opnieuw bekeken",
'title.rewatchedToday': "Vandaag opnieuw bekeken",
}
export default dict
+41
View File
@@ -928,6 +928,47 @@ const dict: Translations = {
'homeHero.details': 'Karta',
'homeHero.continueRow': 'Oglądaj dalej',
'homeHero.nextUp': 'Następny: {ep}',
'title.addTitle': "Dodaj tytuł",
'title.searchPh': "Film, serial, anime, drama…",
'title.searchHint': "Wyszukaj tytuł i otwórz go, aby go ocenić, oznaczyć jako obejrzany lub dodać do listy.",
'title.noResults': "Brak wyników.",
'title.manual': "Dodaj ręcznie",
'title.manualHint': "Nie możesz znaleźć? Utwórz go sam.",
'title.manualTitle': "Nowy tytuł",
'title.inLibrary': "W twojej bibliotece",
'title.added': "Dodano do twojej biblioteki",
'title.adding': "Dodawanie…",
'title.yourRating': "Twoja ocena",
'title.average': "Średnia ocena",
'title.votes_one': "{n} głos",
'title.votes_other': "{n} głosu",
'title.noAverage': "Jeszcze za mało głosów",
'title.distribution': "Rozkład ocen",
'title.directedBy': "Reżyseria:",
'title.createdBy': "Twórcy:",
'title.eps_one': "{count} odcinek",
'title.eps_other': "{count} odcinka",
'title.seasons_one': "{count} sezon",
'title.seasons_other': "{count} sezonu",
'title.cast': "Obsada",
'title.voice': "Głos: {name}",
'title.writeReview': "Napisz recenzję…",
'title.reviewPublicHint': "Twoja recenzja jest widoczna na twoim profilu.",
'title.detailRating': "Oceń szczegółowo",
'title.more': "Więcej opcji",
'title.myTracking': "Moje śledzenie",
'title.trackingHint': "Daty, listy, ponowne seanse",
'title.rewatchCount_one': "Obejrzane ponownie {count} raz",
'title.rewatchCount_other': "Obejrzane ponownie {count} raza",
'title.rewatchedToday': "Obejrzane ponownie dziś",
'title.votes_few': "{n} głosy",
'title.votes_many': "{n} głosów",
'title.eps_few': "{count} odcinki",
'title.eps_many': "{count} odcinków",
'title.seasons_few': "{count} sezony",
'title.seasons_many': "{count} sezonów",
'title.rewatchCount_few': "Obejrzane ponownie {count} razy",
'title.rewatchCount_many': "Obejrzane ponownie {count} razy",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "Detalhes",
'homeHero.continueRow': "Continuar assistindo",
'homeHero.nextUp': "Próximo: {ep}",
'title.addTitle': "Adicionar um título",
'title.searchPh': "Filme, série, anime, drama…",
'title.searchHint': "Procure um título e abra a ficha para avaliar, marcar como visto ou adicionar à sua lista.",
'title.noResults': "Nenhum resultado.",
'title.manual': "Adicionar manualmente",
'title.manualHint': "Não encontrou? Crie a ficha você mesmo.",
'title.manualTitle': "Novo título",
'title.inLibrary': "Na sua biblioteca",
'title.added': "Adicionado à sua biblioteca",
'title.adding': "Adicionando…",
'title.yourRating': "Sua nota",
'title.average': "Nota média",
'title.votes_one': "{n} voto",
'title.votes_other': "{n} votos",
'title.noAverage': "Ainda não há votos suficientes",
'title.distribution': "Distribuição das notas",
'title.directedBy': "Dirigido por",
'title.createdBy': "Criado por",
'title.eps_one': "{count} episódio",
'title.eps_other': "{count} episódios",
'title.seasons_one': "{count} temporada",
'title.seasons_other': "{count} temporadas",
'title.cast': "Elenco",
'title.voice': "Voz: {name}",
'title.writeReview': "Escrever uma resenha…",
'title.reviewPublicHint': "Sua resenha fica visível no seu perfil.",
'title.detailRating': "Detalhar minha nota",
'title.more': "Mais opções",
'title.myTracking': "Meu acompanhamento",
'title.trackingHint': "Datas, listas, revisões",
'title.rewatchCount_one': "Revisto uma vez",
'title.rewatchCount_other': "Revisto {count} vezes",
'title.rewatchedToday': "Revisto hoje",
}
export default dict
+41
View File
@@ -928,6 +928,47 @@ const dict: Translations = {
'homeHero.details': 'Карточка',
'homeHero.continueRow': 'Продолжить просмотр',
'homeHero.nextUp': 'Далее: {ep}',
'title.addTitle': "Добавить",
'title.searchPh': "Фильм, сериал, аниме, дорама…",
'title.searchHint': "Найдите название и откройте карточку, чтобы оценить, отметить как просмотренное или добавить в список.",
'title.noResults': "Ничего не найдено.",
'title.manual': "Добавить вручную",
'title.manualHint': "Не нашли? Создайте карточку сами.",
'title.manualTitle': "Новое название",
'title.inLibrary': "В вашей библиотеке",
'title.added': "Добавлено в вашу библиотеку",
'title.adding': "Добавление…",
'title.yourRating': "Ваша оценка",
'title.average': "Средняя оценка",
'title.votes_one': "{n} голос",
'title.votes_other': "{n} голоса",
'title.noAverage': "Пока недостаточно голосов",
'title.distribution': "Распределение оценок",
'title.directedBy': "Режиссёр:",
'title.createdBy': "Создатели:",
'title.eps_one': "{count} серия",
'title.eps_other': "{count} серии",
'title.seasons_one': "{count} сезон",
'title.seasons_other': "{count} сезона",
'title.cast': "В ролях",
'title.voice': "Голос: {name}",
'title.writeReview': "Написать отзыв…",
'title.reviewPublicHint': "Ваш отзыв виден в вашем профиле.",
'title.detailRating': "Подробная оценка",
'title.more': "Ещё",
'title.myTracking': "Мой прогресс",
'title.trackingHint': "Даты, списки, повторные просмотры",
'title.rewatchCount_one': "Пересмотрено {count} раз",
'title.rewatchCount_other': "Пересмотрено {count} раза",
'title.rewatchedToday': "Пересмотрено сегодня",
'title.votes_few': "{n} голоса",
'title.votes_many': "{n} голосов",
'title.eps_few': "{count} серии",
'title.eps_many': "{count} серий",
'title.seasons_few': "{count} сезона",
'title.seasons_many': "{count} сезонов",
'title.rewatchCount_few': "Пересмотрено {count} раза",
'title.rewatchCount_many': "Пересмотрено {count} раз",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': 'รายละเอียด',
'homeHero.continueRow': 'ดูต่อ',
'homeHero.nextUp': 'ต่อไป: {ep}',
'title.addTitle': "เพิ่มเรื่อง",
'title.searchPh': "ภาพยนตร์ ซีรีส์ อนิเมะ ดราม่า…",
'title.searchHint': "ค้นหาเรื่อง แล้วเปิดเพื่อให้คะแนน ทำเครื่องหมายว่าดูแล้ว หรือเพิ่มในรายการของคุณ",
'title.noResults': "ไม่พบผลลัพธ์",
'title.manual': "เพิ่มเอง",
'title.manualHint': "หาไม่เจอ? สร้างเองได้เลย",
'title.manualTitle': "เรื่องใหม่",
'title.inLibrary': "อยู่ในคลังของคุณ",
'title.added': "เพิ่มในคลังของคุณแล้ว",
'title.adding': "กำลังเพิ่ม…",
'title.yourRating': "คะแนนของคุณ",
'title.average': "คะแนนเฉลี่ย",
'title.votes_one': "{n} โหวต",
'title.votes_other': "{n} โหวต",
'title.noAverage': "ยังมีโหวตไม่พอ",
'title.distribution': "การกระจายคะแนน",
'title.directedBy': "กำกับโดย",
'title.createdBy': "สร้างโดย",
'title.eps_one': "{count} ตอน",
'title.eps_other': "{count} ตอน",
'title.seasons_one': "{count} ซีซัน",
'title.seasons_other': "{count} ซีซัน",
'title.cast': "นักแสดง",
'title.voice': "พากย์เสียง: {name}",
'title.writeReview': "เขียนรีวิว…",
'title.reviewPublicHint': "รีวิวของคุณแสดงบนโปรไฟล์",
'title.detailRating': "ให้คะแนนแบบละเอียด",
'title.more': "ตัวเลือกเพิ่มเติม",
'title.myTracking': "การติดตามของฉัน",
'title.trackingHint': "วันที่ รายการ การดูซ้ำ",
'title.rewatchCount_one': "ดูซ้ำ {count} ครั้ง",
'title.rewatchCount_other': "ดูซ้ำ {count} ครั้ง",
'title.rewatchedToday': "ดูซ้ำวันนี้",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "Detaylar",
'homeHero.continueRow': "İzlemeye devam et",
'homeHero.nextUp': "Sıradaki: {ep}",
'title.addTitle': "Başlık ekle",
'title.searchPh': "Film, dizi, anime, drama…",
'title.searchHint': "Bir başlık ara, sonra puanlamak, izlendi olarak işaretlemek ya da listene eklemek için aç.",
'title.noResults': "Sonuç yok.",
'title.manual': "Elle ekle",
'title.manualHint': "Bulamadın mı? Kendin oluştur.",
'title.manualTitle': "Yeni başlık",
'title.inLibrary': "Kitaplığında",
'title.added': "Kitaplığına eklendi",
'title.adding': "Ekleniyor…",
'title.yourRating': "Puanın",
'title.average': "Ortalama puan",
'title.votes_one': "{n} oy",
'title.votes_other': "{n} oy",
'title.noAverage': "Henüz yeterli oy yok",
'title.distribution': "Puan dağılımı",
'title.directedBy': "Yönetmen:",
'title.createdBy': "Yapımcı:",
'title.eps_one': "{count} bölüm",
'title.eps_other': "{count} bölüm",
'title.seasons_one': "{count} sezon",
'title.seasons_other': "{count} sezon",
'title.cast': "Oyuncular",
'title.voice': "Ses: {name}",
'title.writeReview': "Yorum yaz…",
'title.reviewPublicHint': "Yorumun profilinde görünür.",
'title.detailRating': "Puanı ayrıntılandır",
'title.more': "Diğer seçenekler",
'title.myTracking': "Takibim",
'title.trackingHint': "Tarihler, listeler, tekrar izlemeler",
'title.rewatchCount_one': "{count} kez tekrar izlendi",
'title.rewatchCount_other': "{count} kez tekrar izlendi",
'title.rewatchedToday': "Bugün tekrar izlendi",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': 'Chi tiết',
'homeHero.continueRow': 'Xem tiếp',
'homeHero.nextUp': 'Tiếp theo: {ep}',
'title.addTitle': "Thêm phim",
'title.searchPh': "Phim lẻ, phim bộ, anime, drama…",
'title.searchHint': "Tìm một tựa phim rồi mở ra để chấm điểm, đánh dấu đã xem hoặc thêm vào danh sách của bạn.",
'title.noResults': "Không có kết quả.",
'title.manual': "Thêm thủ công",
'title.manualHint': "Không tìm thấy? Tự tạo thẻ phim.",
'title.manualTitle': "Phim mới",
'title.inLibrary': "Trong thư viện của bạn",
'title.added': "Đã thêm vào thư viện",
'title.adding': "Đang thêm…",
'title.yourRating': "Điểm của bạn",
'title.average': "Điểm trung bình",
'title.votes_one': "{n} lượt",
'title.votes_other': "{n} lượt",
'title.noAverage': "Chưa đủ lượt đánh giá",
'title.distribution': "Phân bố điểm",
'title.directedBy': "Đạo diễn",
'title.createdBy': "Sáng tạo bởi",
'title.eps_one': "{count} tập",
'title.eps_other': "{count} tập",
'title.seasons_one': "{count} mùa",
'title.seasons_other': "{count} mùa",
'title.cast': "Diễn viên",
'title.voice': "Lồng tiếng: {name}",
'title.writeReview': "Viết đánh giá…",
'title.reviewPublicHint': "Đánh giá của bạn hiển thị trên trang cá nhân.",
'title.detailRating': "Chấm điểm chi tiết",
'title.more': "Tùy chọn khác",
'title.myTracking': "Theo dõi của tôi",
'title.trackingHint': "Ngày, danh sách, xem lại",
'title.rewatchCount_one': "Đã xem lại {count} lần",
'title.rewatchCount_other': "Đã xem lại {count} lần",
'title.rewatchedToday': "Đã xem lại hôm nay",
}
export default dict
+33
View File
@@ -846,6 +846,39 @@ const dict: Translations = {
'homeHero.details': "详情",
'homeHero.continueRow': "继续观看",
'homeHero.nextUp': "下一集:{ep}",
'title.addTitle': "添加作品",
'title.searchPh': "电影、剧集、动画、电视剧…",
'title.searchHint': "搜索作品,打开详情页即可评分、标记为看过或加入想看。",
'title.noResults': "没有结果。",
'title.manual': "手动添加",
'title.manualHint': "找不到?自己创建条目。",
'title.manualTitle': "新作品",
'title.inLibrary': "已在你的片库中",
'title.added': "已添加到你的片库",
'title.adding': "正在添加…",
'title.yourRating': "你的评分",
'title.average': "平均评分",
'title.votes_one': "{n} 人评分",
'title.votes_other': "{n} 人评分",
'title.noAverage': "评分人数还不够",
'title.distribution': "评分分布",
'title.directedBy': "导演",
'title.createdBy': "创作者",
'title.eps_one': "{count} 集",
'title.eps_other': "{count} 集",
'title.seasons_one': "{count} 季",
'title.seasons_other': "{count} 季",
'title.cast': "演员",
'title.voice': "配音:{name}",
'title.writeReview': "写短评…",
'title.reviewPublicHint': "你的短评会显示在你的主页上。",
'title.detailRating': "细分评分",
'title.more': "更多选项",
'title.myTracking': "我的记录",
'title.trackingHint': "日期、片单、重看",
'title.rewatchCount_one': "重看 {count} 次",
'title.rewatchCount_other': "重看 {count} 次",
'title.rewatchedToday': "今天重看了",
}
export default dict
+30
View File
@@ -224,6 +224,36 @@
padding-bottom: env(safe-area-inset-bottom);
}
/*
* Fenêtres plein écran (fiche, profil, recherche…) : figées à l'écran.
* Seul le contenu défile, verticalement ; ni rebond qui fait bouger la fiche, ni glissement de côté.
*/
@layer components {
.sheet {
position: fixed;
inset: 0;
z-index: 50;
display: flex;
flex-direction: column;
overflow: hidden;
overscroll-behavior: none;
background: var(--color-bg);
}
.sheet-scroll {
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
touch-action: pan-y;
-webkit-overflow-scrolling: touch;
}
/* Carrousels horizontaux à l'intérieur d'une fenêtre */
.sheet-scroll .no-scrollbar {
touch-action: pan-x pan-y;
}
}
/* Apparition douce des feuilles (formulaire, recherche) — pas de fondu de couleur */
@keyframes sheet-in {
from {
+3
View File
@@ -297,6 +297,9 @@ export function novelties(items: MediaItem[], cache: AiringCache): Novelty[] {
const info = cache[item.id]
if (!info) continue
const unwatched = Math.max(0, info.aired - item.episodesWatched)
// Série terminée depuis (ex. Friends) : les épisodes non vus ne sont pas des nouveautés,
// et une « nouvelle saison » n'y est qu'un décalage de numérotation entre TMDB et AniList.
if (info.ended) continue
if (item.status === 'termine') {
// Terminé de mon côté, mais de nouveaux épisodes sont sortis depuis → nouvelle saison
if (unwatched > 0 && episodeCap(item) && info.aired > episodeCap(item)!) out.push({ item, info, unwatched, kind: 'new_season' })
+74
View File
@@ -0,0 +1,74 @@
import { useEffect, useRef } from 'react'
/**
* Bouton / geste « retour » (swipe depuis le bord sur iPhone, bouton retour Android) :
* chaque fenêtre ouverte (fiche, profil, recherche…) a son entrée dans l'historique,
* et revenir en arrière ferme la fenêtre du dessus au lieu de laisser la page « rebondir ».
*
* L'entrée de l'historique porte la profondeur de la pile (`azuuDepth`) : on compare
* simplement cette profondeur au nombre de fenêtres réellement ouvertes.
*/
type CloseFn = () => void
const stack: { close: CloseFn }[] = []
/** Retours déclenchés par nous (fermeture par la croix) : à ne pas traiter comme un geste. */
let ignorePops = 0
let syncTimer = 0
let listening = false
const depthOf = (state: unknown) => {
const d = (state as { azuuDepth?: unknown } | null)?.azuuDepth
return typeof d === 'number' ? d : 0
}
/** Retire de l'historique les entrées des fenêtres fermées autrement que par « retour ». */
function scheduleSync() {
if (syncTimer) return
syncTimer = window.setTimeout(() => {
syncTimer = 0
const extra = depthOf(history.state) - stack.length
if (extra > 0) {
ignorePops++
history.go(-extra)
}
}, 0)
}
function onPop(e: PopStateEvent) {
if (ignorePops > 0) {
ignorePops--
return
}
const depth = depthOf(e.state)
// Ferme les fenêtres au-dessus de l'entrée atteinte (la plus haute d'abord)
while (stack.length > depth) stack.pop()!.close()
// Entrée laissée par une fenêtre déjà fermée : on la saute
scheduleSync()
}
/** Ferme la fenêtre avec le geste / bouton retour du téléphone. */
export function useBackToClose(onClose: CloseFn) {
const closeRef = useRef(onClose)
useEffect(() => {
closeRef.current = onClose
})
useEffect(() => {
if (!listening) {
window.addEventListener('popstate', onPop)
listening = true
}
const entry = { close: () => closeRef.current() }
stack.push(entry)
// Une entrée existe déjà à cette profondeur (fenêtre remontée aussitôt) : on la réutilise
if (depthOf(history.state) < stack.length) {
const base = history.state && typeof history.state === 'object' ? history.state : {}
history.pushState({ ...base, azuuDepth: stack.length }, '')
}
return () => {
const i = stack.indexOf(entry)
if (i >= 0) stack.splice(i, 1)
scheduleSync()
}
}, [])
}
+154
View File
@@ -1014,3 +1014,157 @@ export function releaseToResult(r: GlobalRelease): SearchResult | null {
typeGuess: type,
})
}
// ─────────────────────────── Fiche détaillée (note moyenne, casting) ───────────────────────────
export interface CastMember {
name: string
/** Personnage joué */
role?: string
photo?: string
/** Doubleur·se (animes) */
voice?: string
}
export interface TitleExtras {
/** Image de scène (paysage) */
backdrop?: string
/** Note moyenne du public, sur 10 */
average?: number
votes?: number
/** Répartition des notes du public (AniList) : note sur 10 → nombre de votes */
distribution?: { score: number; amount: number }[]
cast: CastMember[]
/** Réalisation (films) ou création (séries) */
directors: string[]
directorKind: 'director' | 'creator'
tagline?: string
runtime?: number
seasons?: number
}
interface TmdbExtras {
vote_average?: number
vote_count?: number
backdrop_path?: string | null
tagline?: string
runtime?: number
episode_run_time?: number[]
number_of_seasons?: number
created_by?: { name?: string }[]
credits?: {
cast?: { name?: string; character?: string; profile_path?: string | null; order?: number }[]
crew?: { name?: string; job?: string }[]
}
}
const extrasCache = new Map<string, Promise<TitleExtras>>()
async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras> {
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
const cast = (Array.isArray(d.credits?.cast) ? d.credits!.cast! : [])
.slice()
.sort((a, b) => (a.order ?? 99) - (b.order ?? 99))
.slice(0, 20)
.map((c): Partial<CastMember> => ({
name: cleanText(c.name, 60),
role: cleanText(c.character, 80),
photo: isSafeTmdbPath(c.profile_path) ? `${TMDB_IMG}/w185${c.profile_path}` : undefined,
}))
.filter((c): c is CastMember => !!c.name)
const crew = Array.isArray(d.credits?.crew) ? d.credits!.crew! : []
const votes = count(d.vote_count, 100_000_000)
return {
backdrop: isSafeTmdbPath(d.backdrop_path) ? `${TMDB_IMG}/w780${d.backdrop_path}` : undefined,
average: tmdbPublicRating(d.vote_average, d.vote_count),
votes,
cast,
directors:
kind === 'movie'
? names(crew.filter((c) => c.job === 'Director').map((c) => c.name), 3)
: names((Array.isArray(d.created_by) ? d.created_by : []).map((c) => c.name), 3),
directorKind: kind === 'movie' ? 'director' : 'creator',
tagline: cleanText(d.tagline, 200),
runtime: count(kind === 'movie' ? d.runtime : d.episode_run_time?.[0], 6000),
seasons: kind === 'tv' ? count(d.number_of_seasons, 500) : undefined,
}
}
const ANILIST_EXTRAS = `
query ($id: Int) {
Media(id: $id, type: ANIME) {
averageScore
bannerImage
duration
stats { scoreDistribution { score amount } }
characters(sort: [ROLE, RELEVANCE], perPage: 16) {
edges {
node { name { full } image { medium } }
voiceActors(language: JAPANESE, sort: [RELEVANCE]) { name { full } }
}
}
staff(sort: [RELEVANCE], perPage: 12) { edges { role node { name { full } } } }
}
}`
interface AniExtras {
averageScore?: number | null
bannerImage?: string | null
duration?: number | null
stats?: { scoreDistribution?: { score?: number; amount?: number }[] | null } | null
characters?: { edges?: { node?: { name?: { full?: string }; image?: { medium?: string } }; voiceActors?: { name?: { full?: string } }[] }[] } | null
staff?: { edges?: { role?: string; node?: { name?: { full?: string } } }[] } | null
}
async function aniListExtras(externalId: string): Promise<TitleExtras> {
const id = Number(externalId.split(':')[1])
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query: ANILIST_EXTRAS, variables: { id } }),
referrerPolicy: 'no-referrer',
credentials: 'omit',
})
if (res.status === 429) throw new Error(t('err.anilistRate'))
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Media?: AniExtras } }
const m = json.data?.Media ?? {}
const distribution = (Array.isArray(m.stats?.scoreDistribution) ? m.stats!.scoreDistribution! : [])
.map((s) => ({ score: count(s.score, 100), amount: count(s.amount, 100_000_000) ?? 0 }))
.filter((s): s is { score: number; amount: number } => s.score != null && s.score % 10 === 0)
.map((s) => ({ score: s.score / 10, amount: s.amount }))
.sort((a, b) => a.score - b.score)
const votes = distribution.reduce((n, s) => n + s.amount, 0)
const cast = (Array.isArray(m.characters?.edges) ? m.characters!.edges! : [])
.map((e): Partial<CastMember> => ({
name: cleanText(e.node?.name?.full, 60),
photo: safePosterUrl(e.node?.image?.medium),
voice: cleanText(e.voiceActors?.[0]?.name?.full, 60),
}))
.filter((c): c is CastMember => !!c.name)
const staff = Array.isArray(m.staff?.edges) ? m.staff!.edges! : []
return {
backdrop: safePosterUrl(m.bannerImage),
average: typeof m.averageScore === 'number' && m.averageScore > 0 ? Math.round(m.averageScore) / 10 : undefined,
votes: votes || undefined,
distribution: votes ? distribution : undefined,
cast,
directors: names(staff.filter((s) => /^Director$/i.test(s.role ?? '')).map((s) => s.node?.name?.full), 3),
directorKind: 'director',
runtime: count(m.duration, 6000),
}
}
/** Infos de la fiche (note moyenne, votes, casting…), gardées en mémoire le temps de la session. */
export function getTitleExtras(externalId: string, tmdbKey?: string): Promise<TitleExtras> {
if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef')))
const isTmdb = externalId.startsWith('tmdb:')
if (isTmdb && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly')))
const cached = extrasCache.get(externalId)
if (cached) return cached
const p = isTmdb ? tmdbExtras(externalId, tmdbKey!) : aniListExtras(externalId)
extrasCache.set(externalId, p)
p.catch(() => extrasCache.delete(externalId))
return p
}
+5 -2
View File
@@ -160,9 +160,12 @@ export async function signIn(email: string, password: string): Promise<void> {
}
/** Crée un compte. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). */
export async function signUp(email: string, password: string): Promise<boolean> {
/** Inscription. Le pseudo choisi est repris par la base à la création du profil (s'il est libre). */
export async function signUp(email: string, password: string, username?: string): Promise<boolean> {
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
const data = await gotrue(`/signup?redirect_to=${encodeURIComponent(appUrl())}`, { body: { email: cleanEmail(email), password } })
const data = await gotrue(`/signup?redirect_to=${encodeURIComponent(appUrl())}`, {
body: { email: cleanEmail(email), password, ...(username ? { data: { username } } : {}) },
})
const s = toSession(data)
if (s) {
setSession(s)
+15 -3
View File
@@ -2,14 +2,26 @@ import { useEffect } from 'react'
/**
* Bloque le défilement de la page derrière une fenêtre (fiche, profil, aperçu…).
* Sur iPhone, `overflow: hidden` ne suffit pas : la page derrière continuait de glisser et la
* fiche « bougeait ». On fige donc le corps de la page à sa position, puis on la rend à la fermeture.
* Compteur partagé : avec plusieurs fenêtres empilées, la page ne se débloque qu'à la fermeture de la dernière.
*/
let locks = 0
let savedY = 0
function apply(on: boolean) {
for (const el of [document.documentElement, document.body]) {
el.style.overflow = on ? 'hidden' : ''
el.style.overscrollBehavior = on ? 'none' : ''
const html = document.documentElement
const body = document.body
if (on) {
savedY = window.scrollY
html.style.overflow = 'hidden'
html.style.overscrollBehavior = 'none'
Object.assign(body.style, { position: 'fixed', top: `-${savedY}px`, left: '0', right: '0', width: '100%', overflow: 'hidden' })
} else {
html.style.overflow = ''
html.style.overscrollBehavior = ''
Object.assign(body.style, { position: '', top: '', left: '', right: '', width: '', overflow: '' })
window.scrollTo(0, savedY)
}
}
+14 -9
View File
@@ -11,7 +11,7 @@ import Recommendations from '../components/Recommendations'
import HomeHero, { ContinueCard } from '../components/HomeHero'
import type { Tab } from '../components/BottomNav'
import { EmptyState, LinkArrow, PageHeader, SectionTitle, StatTile } from '../components/ui'
import { CACHE_EVENT, isCaughtUp, loadAiring, needsCheck, novelties, refreshAiring, saveAiring, trackable } from '../lib/airing'
import { CACHE_EVENT, isCaughtUp, loadAiring, needsCheck, refreshAiring, saveAiring, trackable } from '../lib/airing'
import { addEpisodeNotifications } from '../lib/cloud/notifications'
import { useOnResume } from '../lib/onResume'
import { calendarEvents } from '../lib/releases'
@@ -72,15 +72,20 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
if (info.backdrop && !i.backdrop) patch.backdrop = info.backdrop
return Object.keys(patch).length ? [{ id: i.id, patch }] : []
})
// Notifications : nouveaux épisodes / saisons des séries suivies (dédoublonné côté serveur)
// Notifications : on envoie le dernier épisode sorti de chaque série encore en diffusion ;
// le serveur retient le précédent et ne signale que ce qui est sorti depuis (le passé n'est pas « nouveau »).
if (social.enabled) {
const notices = novelties(items, next)
.filter((nv) => nv.kind !== 'upcoming')
.map((nv) => ({ item_id: nv.item.id, kind: nv.kind === 'new_season' ? ('new_season' as const) : ('new_episode' as const), episode: nv.info.aired, count: nv.unwatched }))
if (notices.length)
void addEpisodeNotifications(notices).then((n) => {
if (n > 0) void social.refresh()
})
const notices = trackable(items).flatMap((i) => {
const info = next[i.id]
if (!info || info.ended || info.aired < 1 || i.status === 'abandonne') return []
const kind = i.status === 'termine' ? ('new_season' as const) : ('new_episode' as const)
return [{ item_id: i.id, kind, episode: info.aired, count: Math.max(1, info.aired - i.episodesWatched) }]
})
void (async () => {
let created = 0
for (let k = 0; k < notices.length; k += 50) created += await addEpisodeNotifications(notices.slice(k, k + 50))
if (created > 0) void social.refresh()
})()
}
if (patches.length) return patchMany(patches)
})
@@ -0,0 +1,79 @@
-- ─────────────────────────────────────────────────────────────────────────────
-- AzuuCine — notifications « nouvel épisode » : seulement les VRAIS nouveaux épisodes
--
-- Avant : l'app envoyait « épisodes sortis − épisodes vus », donc Friends (5/228 vus)
-- donnait « 223 nouveaux épisodes », et des séries terminées (Naruto) recevaient
-- une « nouvelle saison » à cause d'une numérotation différente TMDB / AniList.
--
-- Maintenant le serveur retient le dernier épisode connu de chaque série (episode_seen) :
-- - premier passage : on mémorise, aucune notification (le passé n'est pas « nouveau ») ;
-- - ensuite : notification seulement si un épisode plus récent est sorti ;
-- - jamais pour une série abandonnée (une série que j'ai terminée peut avoir une nouvelle saison) ;
-- - l'app n'envoie plus les séries dont la diffusion est finie (ex. Friends) ;
-- - un saut de plus de 30 épisodes est ignoré (décalage de numérotation entre bases).
-- Fonctionne quelle que soit la version de l'app (le calcul côté client n'est plus cru).
--
-- À coller dans Supabase → SQL Editor → Run. Peut être relancé sans risque.
-- ─────────────────────────────────────────────────────────────────────────────
create table if not exists public.episode_seen (
user_id uuid not null references auth.users (id) on delete cascade,
item_id text not null,
last_episode integer not null check (last_episode between 0 and 1000000),
updated_at timestamptz not null default now(),
primary key (user_id, item_id)
);
alter table public.episode_seen enable row level security;
alter table public.episode_seen force row level security;
-- Accessible uniquement via add_episode_notifications (security definer)
revoke all on public.episode_seen from public, anon, authenticated;
create or replace function public.add_episode_notifications(p_list jsonb)
returns integer
language plpgsql
security definer
set search_path = ''
as $fn$
declare
me uuid := auth.uid();
e jsonb;
k text;
st text;
ep integer;
prev integer;
n integer := 0;
begin
if me is null or jsonb_typeof(p_list) is distinct from 'array' then return 0; end if;
if not public.azuu_wants(me, 'new_episode') then return 0; end if;
for e in select value from jsonb_array_elements(p_list) limit 50 loop
k := e->>'kind';
if k is null or k not in ('new_episode', 'new_season') then continue; end if;
if coalesce(e->>'episode', '') !~ '^[0-9]{1,6}$' or coalesce(e->>'count', '1') !~ '^[0-9]{1,4}$' then continue; end if;
select i.data->>'status' into st from public.items i where i.user_id = me and i.id = e->>'item_id' and not i.deleted;
if not found then continue; end if;
ep := (e->>'episode')::int;
select s.last_episode into prev from public.episode_seen s where s.user_id = me and s.item_id = e->>'item_id';
insert into public.episode_seen (user_id, item_id, last_episode) values (me, e->>'item_id', ep)
on conflict (user_id, item_id) do update
set last_episode = greatest(public.episode_seen.last_episode, excluded.last_episode), updated_at = now();
if prev is null or ep <= prev or ep - prev > 30 or st = 'abandonne' then continue; end if;
insert into public.notifications (user_id, kind, actor_id, item_id, episode, ep_count, dedup)
values (me, k, null, e->>'item_id', ep, ep - prev, 'ep:' || (e->>'item_id') || ':' || ep)
on conflict (user_id, dedup) where dedup is not null do nothing;
if found then n := n + 1; end if;
end loop;
delete from public.notifications
where user_id = me and id not in (
select id from public.notifications where user_id = me order by created_at desc limit 300
);
return n;
end;
$fn$;
revoke all on function public.add_episode_notifications(jsonb) from public, anon;
grant execute on function public.add_episode_notifications(jsonb) to authenticated;
-- Les fausses notifications déjà créées par l'ancien calcul
delete from public.notifications n
where n.kind in ('new_episode', 'new_season')
and not exists (select 1 from public.episode_seen s where s.user_id = n.user_id and s.item_id = n.item_id);
@@ -0,0 +1,41 @@
-- ─────────────────────────────────────────────────────────────────────────────
-- AzuuCine — inscription par email : le pseudo est choisi dans le formulaire
--
-- L'app envoie le pseudo dans les métadonnées de l'inscription (data.username).
-- S'il est valide et libre, le profil est créé avec ; sinon (pris, réservé…), on garde
-- l'ancien fonctionnement : pseudo aléatoire, puis écran de choix à la première connexion.
-- La connexion Google ne change pas (pas de pseudo dans ses métadonnées).
--
-- Déjà appliqué sur le projet le 8 oct. 2026. Peut être relancé sans risque.
-- ─────────────────────────────────────────────────────────────────────────────
create or replace function public.azuu_new_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $fn$
declare
u text := public.azuu_random_username();
wanted text := lower(trim(coalesce(new.raw_user_meta_data->>'username', '')));
n text := left(trim(regexp_replace(coalesce(new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'name', ''), '[[:cntrl:]]', '', 'g')), 40);
begin
if wanted ~ '^[a-z0-9_]{3,20}$' and not exists (select 1 from public.profiles where username = wanted) then
begin
insert into public.profiles (id, username, display_name) values (new.id, wanted, coalesce(nullif(n, ''), wanted)) on conflict (id) do nothing;
return new;
exception when others then
-- Pseudo réservé ou pris entre-temps : on retombe sur le pseudo aléatoire
null;
end;
end if;
begin
insert into public.profiles (id, username, display_name) values (new.id, u, coalesce(nullif(n, ''), u)) on conflict (id) do nothing;
exception when others then
insert into public.profiles (id, username, display_name) values (new.id, u, u) on conflict (id) do nothing;
end;
return new;
end;
$fn$;
revoke all on function public.azuu_new_user() from public, anon, authenticated;