From 1b185e5e9dd6b8e3703e3b8dbc6a03199dacb56b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 17:24:12 +0000 Subject: [PATCH] =?UTF-8?q?Refonte=20de=20la=20fiche,=20pseudo=20=C3=A0=20?= =?UTF-8?q?l'inscription,=20notifications,=20retour=20arri=C3=A8re?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe --- src/App.tsx | 59 +- src/components/AuthScreen.tsx | 28 +- src/components/CalendarView.tsx | 6 +- src/components/DatabaseSearch.tsx | 170 ----- src/components/ItemHero.tsx | 91 --- src/components/MediaForm.tsx | 639 ---------------- src/components/Roulette.tsx | 6 +- src/components/TopFiveEditor.tsx | 6 +- src/components/social/ItemPeek.tsx | 2 + src/components/social/Sheet.tsx | 6 +- src/components/title/AddTitle.tsx | 161 ++++ src/components/title/EditDetails.tsx | 209 +++++ src/components/title/ReviewEditor.tsx | 43 ++ src/components/title/TitleSheet.tsx | 721 ++++++++++++++++++ src/i18n/locales/ar.ts | 45 ++ src/i18n/locales/de.ts | 33 + src/i18n/locales/en.ts | 33 + src/i18n/locales/es.ts | 33 + src/i18n/locales/fr.ts | 33 + src/i18n/locales/hi.ts | 33 + src/i18n/locales/id.ts | 33 + src/i18n/locales/it.ts | 33 + src/i18n/locales/ja.ts | 33 + src/i18n/locales/ko.ts | 33 + src/i18n/locales/nl.ts | 33 + src/i18n/locales/pl.ts | 41 + src/i18n/locales/pt.ts | 33 + src/i18n/locales/ru.ts | 41 + src/i18n/locales/th.ts | 33 + src/i18n/locales/tr.ts | 33 + src/i18n/locales/vi.ts | 33 + src/i18n/locales/zh.ts | 33 + src/index.css | 30 + src/lib/airing.ts | 3 + src/lib/backNav.ts | 74 ++ src/lib/catalogApi.ts | 154 ++++ src/lib/cloud/auth.ts | 7 +- src/lib/scrollLock.ts | 18 +- src/pages/HomePage.tsx | 23 +- ...261008140000_episode_notifications_fix.sql | 79 ++ .../20261008150000_signup_username.sql | 41 + 41 files changed, 2260 insertions(+), 938 deletions(-) delete mode 100644 src/components/DatabaseSearch.tsx delete mode 100644 src/components/ItemHero.tsx delete mode 100644 src/components/MediaForm.tsx create mode 100644 src/components/title/AddTitle.tsx create mode 100644 src/components/title/EditDetails.tsx create mode 100644 src/components/title/ReviewEditor.tsx create mode 100644 src/components/title/TitleSheet.tsx create mode 100644 src/lib/backNav.ts create mode 100644 supabase/migrations/20261008140000_episode_notifications_fix.sql create mode 100644 supabase/migrations/20261008150000_signup_username.sql diff --git a/src/App.tsx b/src/App.tsx index ee5dce3..224eafb 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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(routeFromHash) - const [editor, setEditor] = useState(null) + const [opened, setOpened] = useState(null) + const [adding, setAdding] = useState(false) + const [manual, setManual] = useState(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 ( @@ -67,15 +79,32 @@ export default function App() { {roulette && setRoulette(false)} onOpen={openItem} />} {calendar && setCalendar(false)} onOpen={openItem} />} - {editor && ( - setEditor(null)} - onOpenItem={(i) => setEditor(i)} - onGoToSettings={() => { - setEditor(null) - go('settings') + {adding && ( + setAdding(false)} + onPick={(seed) => setOpened({ seed })} + onOpenItem={openItem} + onManual={(title) => setManual(title)} + onGoToSettings={toSettings} + /> + )} + {opened && ( + setOpened(null)} + onGoToSettings={toSettings} + /> + )} + {manual !== null && ( + setManual(null)} + onCreated={(item) => { + setManual(null) + setAdding(false) + setOpened({ item }) }} /> )} diff --git a/src/components/AuthScreen.tsx b/src/components/AuthScreen.tsx index 402ba90..8603436 100644 --- a/src/components/AuthScreen.tsx +++ b/src/components/AuthScreen.tsx @@ -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('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() const [info, setInfo] = useState(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 }) {
{mode === 'forgot' &&

{t('auth.forgotTitle')}

} + {mode === 'signup' && ( +
+
+ @ + setUsername(e.target.value.toLowerCase())} + placeholder={t('welcome.usernamePh')} + aria-label={t('social.username')} + autoComplete="username" + autoCapitalize="off" + spellCheck={false} + maxLength={21} + required + /> +
+

{t('social.usernameRule')}

+
+ )} 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 ( -
+
-
+
{/* Toutes les sorties / mes titres */}
diff --git a/src/components/DatabaseSearch.tsx b/src/components/DatabaseSearch.tsx deleted file mode 100644 index 7b550de..0000000 --- a/src/components/DatabaseSearch.tsx +++ /dev/null @@ -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) => 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([]) - const [loading, setLoading] = useState(false) - const [picking, setPicking] = useState() - const [error, setError] = useState() - 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 ( -
-
- {t('search.fillFrom')} - {t('search.allKinds')} -
- -
- - setQuery(e.target.value)} - placeholder="Parasite, Frieren, Crash Landing on You…" - className="field ps-10" - enterKeyHint="search" - autoComplete="off" - /> - {loading && } -
- - {!hasKey && ( -
- {t('search.animeOnly')} - {onGoToSettings && ( - - )} -
- )} - - {error &&

{error}

} - - {results.length > 0 && ( -
    - {results.map((r) => { - const mine = inLibrary(r) - const already = !!mine - return ( -
  • - -
  • - ) - })} -
- )} - - {!loading && !error && query.trim().length >= 2 && results.length === 0 && ( -

{t('search.noResults')}

- )} - -

- - {t('search.privacy', { source: hasKey ? 'TMDB / AniList' : 'AniList' })} -

-
- ) -} diff --git a/src/components/ItemHero.tsx b/src/components/ItemHero.tsx deleted file mode 100644 index a6e81cb..0000000 --- a/src/components/ItemHero.tsx +++ /dev/null @@ -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 ( -
-
- {image && } -
-
- -
-
- -
-
-

{form.title}

- {form.originalTitle &&

{form.originalTitle}

} -
-
- -
-
- {meta && {meta}} - {form.publicRating != null && ( - - - {formatRating(form.publicRating, settings.ratingScale)} - - )} -
- -
- - -
- - {form.overview && ( - - )} -
-
- ) -} diff --git a/src/components/MediaForm.tsx b/src/components/MediaForm.tsx deleted file mode 100644 index 798ec42..0000000 --- a/src/components/MediaForm.tsx +++ /dev/null @@ -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 ( -
- {title &&

{title}

} - {children} -
- ) -} - -function Field({ label, children }: { label: string; children: ReactNode }) { - return ( - - ) -} - -/** 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 ( -
- - {t('public.label')} {show(pub)} · {source} - - {gapText && = 0.5 ? 'text-accent' : 'text-ink-3')}>{gapText}} -
- ) -} - -/** 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 ( -
- {dates.length > 0 ? ( -
    - {dates.map((d, k) => ( -
  • - {new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' })} - -
  • - ))} -
- ) : ( -

{t('form.rewatchHint')}

- )} -
- setDraft(e.target.value)} aria-label={t('form.rewatchDate')} /> - -
-
- ) -} - -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(() => { - 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() - const [posterError, setPosterError] = useState() - const fileRef = useRef(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 = {} - 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 = (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) => { - setForm((f) => { - const next: MediaInput = { ...f } - for (const key of METADATA_KEYS) { - if (data[key] !== undefined) (next as unknown as Record)[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 ( -
- {/* En-tête */} -
-
- -

- {item ? t('form.editTitle') : t('form.newTitle')} - {item ? t('form.editAccent') : t('form.newAccent')} -

- -
-
- - { - e.preventDefault() - void submit() - }} - > - {hasHero && ( - setEditInfo((v) => !v)} - primary={primary} - /> - )} -
- {/* Recherche en ligne */} - {(!hasHero || editInfo || showSearch) && (showSearch ? ( - - ) : ( - - ))} - - {/* Affiche + titres (modifiables) */} - {(!hasHero || editInfo) && ( - <> -
-
- - onPickImage(e.target.files?.[0])} /> - {form.poster && ( - - )} -
-
- - set('title', e.target.value)} placeholder={t('form.titlePh')} required /> - - - set('originalTitle', e.target.value)} placeholder={t('form.originalTitlePh')} /> - -
-
- {form.overview && !hasHero && ( -
- {t('form.synopsis')} -

{form.overview}

-
- )} - - )} - - {/* Année, dates de visionnage, genres */} -
-
- - set('startDate', e.target.value || undefined)} /> - - - set('endDate', e.target.value || undefined)} /> - -
-
- - set('year', toNum(e.target.value))} placeholder="2024" /> - -
- {t('form.genres')} - set('genres', g)} - suggestions={genreSuggestions} - placeholder={t('form.genresPh')} - display={genreLabel} - normalize={canonicalGenre} - /> -
-
-
- - {/* Statut */} -
-
- {STATUSES.map((s) => ( - - ))} -
-
- - {/* Épisodes / durée */} - {typeInfo.episodic ? ( -
- {/* Liste d'épisodes pour une fiche liée (TMDB / AniList) ; compteur + total modifiable pour une fiche manuelle */} - {form.seasons || (form.externalId && form.episodesTotal) ? ( - setForm((f) => withEpisodes(f, n, season))} /> - ) : ( -
-
- {t('home.episodesSeen')} -
- - {form.episodesWatched} - -
-
-
- - set('episodesTotal', toNum(e.target.value))} placeholder="?" /> - - - set('season', toNum(e.target.value))} placeholder="1" /> - -
-
- )} -
- ) : ( -
- - set('duration', toNum(e.target.value))} placeholder={String(DEFAULT_FILM_MINUTES)} /> - -
- )} - - {/* Note */} -
-
- set('rating', v)} scale={settings.ratingScale} /> - {form.publicRating != null && } - -
- {t('form.criteria')} -
- {CRITERIA.map((c) => ( -
- {c.label} - - setForm((f) => { - const criteria = { ...f.criteria } - if (v == null) delete criteria[c.key] - else criteria[c.key] = v - return { ...f, criteria } - }) - } - /> -
- ))} -
-
-
-
- - {(form.status === 'termine' || (form.rewatchDates?.length ?? 0) > 0) && ( -
- set('rewatchDates', d.length ? d : undefined)} /> -
- )} - - {/* Type */} -
-
- {MEDIA_TYPES.map((mt) => ( - - ))} -
- {form.type === 'autre' && ( - - set('subtype', e.target.value)} placeholder={t('form.subtypePh')} /> - - {subtypeSuggestions().map((s) => ( - - - )} -
- -
- {lists.length > 0 && ( -
- {lists.map((l) => { - const on = form.listIds?.includes(l.id) - return ( - - ) - })} -
- )} - set('listIds', [...(form.listIds ?? []), l.id])} /> -
- -
-