Initial commit

This commit is contained in:
Romain committed 2026-10-02 18:50:49 +02:00
commit 459e93d314
100 files changed
+26594

No files matched your search

+196
View File
@@ -0,0 +1,196 @@
import Avatar from './social/Avatar'
import { useSocial } from './social/SocialProvider'
import { locale, t } from '../i18n'
import { CloudOff, KeyRound, Loader2, LogOut, RefreshCw, UserRound } from 'lucide-react'
import { useEffect, useState, type FormEvent } from 'react'
import { PASSWORD_MIN, updatePassword } from '../lib/cloud/auth'
import { cx } from '../lib/utils'
import type { AccountApi } from '../store'
import ConfirmDialog from './ConfirmDialog'
import { SectionTitle } from './ui'
function ago(iso?: string): string {
if (!iso) return t('time.never')
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000)
if (s < 60) return t('time.justNow')
if (s < 3600) return t('time.minutesAgo', { n: Math.floor(s / 60) })
if (s < 86400) return t('time.hoursAgo', { n: Math.floor(s / 3600) })
return t('time.onDate', { date: new Date(iso).toLocaleDateString(locale(), { day: 'numeric', month: 'short' }) })
}
/** Réglages → Mon compte : état de la synchro, mot de passe, déconnexion. */
export default function AccountSection({ account, onMessage }: { account: AccountApi; onMessage: (kind: 'ok' | 'error', text: string) => void }) {
const { sync } = account
const social = useSocial()
const [, tick] = useState(0)
const [pwOpen, setPwOpen] = useState(false)
const [pw, setPw] = useState('')
const [busy, setBusy] = useState<'pw' | 'logout' | 'import' | null>(null)
const [confirmLogout, setConfirmLogout] = useState(false)
// Rafraîchit « il y a x min »
useEffect(() => {
const timer = setInterval(() => tick((n) => n + 1), 30_000)
return () => clearInterval(timer)
}, [])
const statusText =
sync.state === 'syncing'
? t('account.syncing')
: sync.state === 'offline'
? t('account.offline')
: sync.state === 'error'
? t('account.syncError')
: t('account.synced', { when: ago(sync.lastSyncAt) })
const changePassword = async (e: FormEvent) => {
e.preventDefault()
setBusy('pw')
try {
await updatePassword(pw)
setPw('')
setPwOpen(false)
onMessage('ok', t('account.passwordChanged'))
} catch (err) {
onMessage('error', (err as Error).message)
} finally {
setBusy(null)
}
}
const logout = async (force = false) => {
setBusy('logout')
try {
const r = await account.logout(force)
if (r === 'pending') setConfirmLogout(true)
} finally {
setBusy(null)
}
}
const importDevice = async () => {
setBusy('import')
try {
const n = await account.importDeviceData()
onMessage('ok', t('account.imported', { count: n }))
} catch {
onMessage('error', t('account.importFailed'))
} finally {
setBusy(null)
}
}
return (
<>
<SectionTitle>{t('account.title')}</SectionTitle>
<div className="card divide-y divide-line overflow-hidden">
<div className="flex items-center gap-3.5 px-4 py-4">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-surface-2 text-ink-2">
<UserRound size={19} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{account.email}</span>
<span className={cx('mt-0.5 flex items-center gap-1.5 text-xs', sync.state === 'error' ? 'text-accent' : 'text-ink-3')}>
{sync.state === 'offline' && <CloudOff size={12} />}
{statusText}
{sync.pending > 0 && sync.state !== 'syncing' && ` · ${t('account.pending', { count: sync.pending })}`}
</span>
</span>
<button
onClick={() => account.syncNow()}
disabled={sync.state === 'syncing'}
className="grid size-10 shrink-0 place-items-center rounded-full border border-line text-ink-2"
aria-label={t('account.syncNow')}
>
{sync.state === 'syncing' ? <Loader2 size={17} className="animate-spin" /> : <RefreshCw size={17} />}
</button>
</div>
<button
onClick={() => (social.me ? social.openProfile(social.me.username) : social.openSearch())}
className="flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2"
>
<Avatar url={social.me?.avatarUrl} name={social.me?.displayName ?? account.email} size={22} />
<span className="flex-1">
<span className="block font-medium">{t('social.myProfile')}</span>
{social.me && <span className="mt-0.5 block text-xs text-ink-3">@{social.me.username}</span>}
</span>
{social.requests.length > 0 && <span className="rounded-full bg-accent-fill px-2 text-[11px] font-bold text-on-accent">{social.requests.length}</span>}
<span className="text-ink-3">→</span>
</button>
{pwOpen ? (
<form onSubmit={changePassword} className="space-y-2.5 px-4 py-4">
<input
className="field"
type="password"
value={pw}
onChange={(e) => setPw(e.target.value)}
placeholder={t('account.newPasswordPh', { n: PASSWORD_MIN })}
autoComplete="new-password"
minLength={PASSWORD_MIN}
maxLength={72}
required
/>
<div className="grid grid-cols-2 gap-2">
<button type="button" onClick={() => setPwOpen(false)} className="btn btn-ghost text-sm">
{t('common.cancel')}
</button>
<button type="submit" disabled={busy === 'pw'} className="btn btn-light text-sm">
{busy === 'pw' && <Loader2 size={15} className="animate-spin" />}
{t('common.save')}
</button>
</div>
</form>
) : (
<button onClick={() => setPwOpen(true)} className="flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2">
<KeyRound size={19} className="text-ink-2" />
<span className="flex-1 font-medium">{t('account.changePassword')}</span>
<span className="text-ink-3">→</span>
</button>
)}
<button onClick={() => logout(false)} disabled={busy === 'logout'} className="flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2">
{busy === 'logout' ? <Loader2 size={19} className="animate-spin text-ink-2" /> : <LogOut size={19} className="text-ink-2" />}
<span className="flex-1">
<span className="block font-medium">{t('account.logout')}</span>
<span className="mt-0.5 block text-xs text-ink-3">{t('account.logoutHint')}</span>
</span>
<span className="text-ink-3">→</span>
</button>
</div>
{account.deviceData && (
<div className="card mt-3 space-y-3 border-ink p-4">
<p className="text-sm">
{account.deviceData.lists > 0
? t('account.deviceDataWithLists', { titles: t('account.nTitles', { count: account.deviceData.items }), lists: t('account.nLists', { count: account.deviceData.lists }) })
: t('account.deviceData', { titles: t('account.nTitles', { count: account.deviceData.items }) })}
</p>
<div className="grid grid-cols-2 gap-2">
<button onClick={importDevice} disabled={busy === 'import'} className="btn btn-light text-sm">
{busy === 'import' && <Loader2 size={15} className="animate-spin" />}
{t('common.add')}
</button>
<button onClick={account.dismissDeviceData} className="btn btn-ghost text-sm">
{t('account.ignore')}
</button>
</div>
<p className="text-xs text-ink-3">{t('account.deviceHint')}</p>
</div>
)}
<ConfirmDialog
open={confirmLogout}
title={t('account.unsentTitle')}
message={t('account.unsentMessage', { count: sync.pending })}
confirmLabel={t('account.logoutAnyway')}
onConfirm={() => {
setConfirmLogout(false)
void logout(true)
}}
onCancel={() => setConfirmLogout(false)}
/>
</>
)
}
+212
View File
@@ -0,0 +1,212 @@
import { t } from '../i18n'
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, signUp, updatePassword } from '../lib/cloud/auth'
import { cx } from '../lib/utils'
type Mode = 'login' | 'signup' | 'forgot'
function PasswordField({ value, onChange, placeholder, autoComplete }: { value: string; onChange: (v: string) => void; placeholder: string; autoComplete: string }) {
const [show, setShow] = useState(false)
return (
<div className="relative">
<input
className="field pr-11"
type={show ? 'text' : 'password'}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
autoComplete={autoComplete}
minLength={PASSWORD_MIN}
maxLength={72}
required
/>
<button type="button" onClick={() => setShow((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-3" aria-label={show ? t('auth.hidePassword') : t('auth.showPassword')}>
{show ? <EyeOff size={17} /> : <Eye size={17} />}
</button>
</div>
)
}
function Shell({ children, subtitle }: { children: ReactNode; subtitle: string }) {
return (
<div className="safe-top safe-bottom flex min-h-dvh flex-col items-center justify-center bg-bg px-5 py-10">
<div className="w-full max-w-sm">
<h1 className="text-center text-[2.4rem] font-bold leading-none">
Azuu<span className="text-accent">Cine</span>
</h1>
<p className="mt-3 text-center text-sm text-ink-3">{subtitle}</p>
<div className="mt-9">{children}</div>
<div className="mt-10 flex justify-center">
<LanguageSelect className="rounded-full border border-line bg-transparent px-3 py-1.5 text-xs text-ink-3" />
</div>
</div>
</div>
)
}
/** Écran de connexion / inscription (affiché quand les comptes sont activés et qu'on n'est pas connecté). */
export default function AuthScreen({ notice }: { notice?: string }) {
const [mode, setMode] = useState<Mode>('login')
const [email, setEmail] = 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 switchTo = (m: Mode) => {
setMode(m)
setError(undefined)
setInfo(undefined)
}
const submit = async (e: FormEvent) => {
e.preventDefault()
setError(undefined)
setInfo(undefined)
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)
if (needsConfirm) {
setInfo(t('auth.created', { email: email.trim() }))
setMode('login')
setPassword('')
setConfirm('')
}
} else {
await requestPasswordReset(email)
setInfo(t('auth.resetSent'))
setMode('login')
}
} catch (err) {
setError((err as Error).message)
} finally {
setBusy(false)
}
}
return (
<Shell subtitle={t('auth.tagline')}>
{mode !== 'forgot' && (
<div className="mb-5 grid grid-cols-2 gap-1 rounded-full border border-line p-1">
{(['login', 'signup'] as const).map((m) => (
<button
key={m}
type="button"
onClick={() => switchTo(m)}
className={cx('rounded-full py-2 text-sm font-medium transition-colors', mode === m ? 'bg-ink text-bg' : 'text-ink-3')}
>
{m === 'login' ? t('auth.loginTab') : t('auth.signupTab')}
</button>
))}
</div>
)}
<form onSubmit={submit} className="space-y-3">
{mode === 'forgot' && <h2 className="mb-1 text-lg font-semibold">{t('auth.forgotTitle')}</h2>}
<input
className="field"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t('auth.email')}
autoComplete="email"
inputMode="email"
autoCapitalize="off"
spellCheck={false}
maxLength={320}
required
/>
{mode !== 'forgot' && (
<PasswordField value={password} onChange={setPassword} placeholder={t('auth.password')} autoComplete={mode === 'login' ? 'current-password' : 'new-password'} />
)}
{mode === 'signup' && (
<>
<PasswordField value={confirm} onChange={setConfirm} placeholder={t('auth.confirmPassword')} autoComplete="new-password" />
<p className="text-xs text-ink-3">{t('auth.minChars', { n: PASSWORD_MIN })}</p>
</>
)}
{error && (
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm text-ink">
{error}
</p>
)}
{info && (
<p role="status" className="rounded-xl border border-line-strong px-3 py-2.5 text-sm text-ink-2">
{info}
</p>
)}
<button type="submit" disabled={busy} className="btn btn-primary w-full py-3">
{busy && <Loader2 size={17} className="animate-spin" />}
{mode === 'login' ? t('auth.login') : mode === 'signup' ? t('auth.signup') : t('auth.sendLink')}
</button>
</form>
<div className="mt-5 text-center text-sm">
{mode === 'login' && (
<button type="button" onClick={() => switchTo('forgot')} className="text-ink-3">
{t('auth.forgot')}
</button>
)}
{mode === 'forgot' && (
<button type="button" onClick={() => switchTo('login')} className="text-ink-3">
← {t('auth.backToLogin')}
</button>
)}
</div>
<p className="mt-10 text-center text-[11px] leading-relaxed text-ink-3">
{t('auth.privacy')}
</p>
</Shell>
)
}
/** Choix d'un nouveau mot de passe (après le lien « mot de passe oublié »). */
export function NewPasswordScreen({ onDone }: { onDone: () => void }) {
const [password, setPassword] = useState('')
const [confirm, setConfirm] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
const submit = async (e: FormEvent) => {
e.preventDefault()
if (password !== confirm) return setError(t('auth.mismatch'))
setBusy(true)
setError(undefined)
try {
await updatePassword(password)
onDone()
} catch (err) {
setError((err as Error).message)
} finally {
setBusy(false)
}
}
return (
<Shell subtitle={t('auth.newPasswordTitle')}>
<form onSubmit={submit} className="space-y-3">
<PasswordField value={password} onChange={setPassword} placeholder={t('auth.newPassword')} autoComplete="new-password" />
<PasswordField value={confirm} onChange={setConfirm} placeholder={t('auth.confirmPassword')} autoComplete="new-password" />
<p className="text-xs text-ink-3">{t('auth.minChars', { n: PASSWORD_MIN })}</p>
{error && (
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm">
{error}
</p>
)}
<button type="submit" disabled={busy} className="btn btn-primary w-full py-3">
{busy && <Loader2 size={17} className="animate-spin" />}
{t('common.save')}
</button>
</form>
</Shell>
)
}
+27
View File
@@ -0,0 +1,27 @@
import { STATUS_BY_VALUE, TYPE_BY_VALUE } from '../lib/constants'
import { subtypeLabel } from '../lib/genres'
import { cx } from '../lib/utils'
import type { MediaItem, WatchStatus } from '../types'
/** Type du média en petite étiquette sobre (pas de couleur). */
export function TypeBadge({ item, className }: { item: Pick<MediaItem, 'type' | 'subtype'>; className?: string }) {
const info = TYPE_BY_VALUE[item.type]
return (
<span className={cx('inline-flex items-center rounded-full border border-line-strong px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-ink-2', className)}>
{item.type === 'autre' && item.subtype ? subtypeLabel(item.subtype) : info.label}
</span>
)
}
export function StatusDot({ status, className }: { status: WatchStatus; className?: string }) {
return <span className={cx('inline-block size-1.5 shrink-0 rounded-full', STATUS_BY_VALUE[status].dot, className)} />
}
export function StatusPill({ status }: { status: WatchStatus }) {
return (
<span className="inline-flex items-center gap-1.5 text-xs text-ink-2">
<StatusDot status={status} />
{STATUS_BY_VALUE[status].label}
</span>
)
}
+57
View File
@@ -0,0 +1,57 @@
import { t } from '../i18n'
import { BarChart3, Home, LibraryBig, Plus, Settings } from 'lucide-react'
import { cx } from '../lib/utils'
export type Tab = 'home' | 'catalog' | 'stats' | 'settings'
const ITEMS: { tab: Tab; readonly label: string; Icon: typeof Home }[] = [
{ tab: 'home', get label() { return t('nav.home') }, Icon: Home },
{ tab: 'catalog', get label() { return t('nav.catalog') }, Icon: LibraryBig },
{ tab: 'stats', get label() { return t('nav.stats') }, Icon: BarChart3 },
{ tab: 'settings', get label() { return t('nav.settings') }, Icon: Settings },
]
interface Props {
current: Tab
onChange: (tab: Tab) => void
onAdd: () => void
}
export default function BottomNav({ current, onChange, onAdd }: Props) {
const button = ({ tab, label, Icon }: (typeof ITEMS)[number]) => {
const active = current === tab
return (
<button
key={tab}
onClick={() => onChange(tab)}
aria-current={active ? 'page' : undefined}
className={cx('flex flex-1 flex-col items-center gap-1 pb-1.5 pt-2.5 text-[11px] font-medium transition-colors', active ? 'text-ink' : 'text-ink-3')}
>
<Icon size={21} strokeWidth={active ? 2.2 : 1.6} />
<span className="relative">
{label}
{/* soulignement fin, comme le lien actif de rdacet.fr */}
<span className={cx('absolute -bottom-1 left-0 h-px w-full bg-accent transition-opacity', active ? 'opacity-100' : 'opacity-0')} />
</span>
</button>
)
}
return (
<nav className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg/95 backdrop-blur-md">
<div className="mx-auto flex max-w-2xl items-center px-2">
{ITEMS.slice(0, 2).map(button)}
<div className="flex flex-1 justify-center">
<button
onClick={onAdd}
aria-label={t('nav.addTitle')}
className="grid size-12 place-items-center rounded-full bg-accent-fill text-on-accent transition active:scale-95"
>
<Plus size={24} strokeWidth={2.2} />
</button>
</div>
{ITEMS.slice(2).map(button)}
</div>
</nav>
)
}
+477
View File
@@ -0,0 +1,477 @@
import { locale, t } from '../i18n'
import { Check, ChevronLeft, ChevronRight, Loader2, Plus, RefreshCw, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { loadAiring, refreshAiring, saveAiring } from '../lib/airing'
import { getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease, type ReleaseCategory } from '../lib/catalogApi'
import { cachedMonth, isBrowsableMonth, loadMonth, RELEASE_CATEGORIES } from '../lib/globalReleases'
import { remotePosterToLocal } from '../lib/image'
import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases'
import { readStorage } from '../lib/security'
import { cx, normalizeText, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput, MediaItem, MediaType } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
// Initiales des jours, du lundi au dimanche, dans la langue choisie (le 1er janvier 2024 est un lundi)
const weekdays = () => Array.from({ length: 7 }, (_, k) => new Date(2024, 0, 1 + k).toLocaleDateString(locale(), { weekday: 'narrow' }))
const PER_DAY = 20
const PREFS_KEY = 'azuucine:calendar-prefs'
const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
const monthId = (d: Date) => iso(d).slice(0, 7)
const niceDate = (d: string) => new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'long', day: 'numeric', month: 'long' })
type Mode = 'all' | 'mine'
interface Entry {
key: string
date: string
title: string
poster?: string
label: string
type: MediaType
item?: MediaItem
release?: GlobalRelease
pop: number
}
function loadPrefs(): { mode: Mode; cats: ReleaseCategory[] } {
const raw = readStorage(PREFS_KEY, {}) as { mode?: unknown; cats?: unknown }
const valid = RELEASE_CATEGORIES.map((c) => c.value)
const cats = Array.isArray(raw?.cats) ? valid.filter((c) => (raw.cats as unknown[]).includes(c)) : valid
return { mode: raw?.mode === 'mine' ? 'mine' : 'all', cats: cats.length ? cats : valid }
}
function EntryRow({ e, onOpen, onAdd, busy, added }: { e: Entry; onOpen: (i: MediaItem) => void; onAdd: (e: Entry) => void; busy: boolean; added: boolean }) {
const mine = !!e.item
const body = (
<>
<div className="w-11 shrink-0">
<Poster src={e.item?.poster ?? e.poster} title={e.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{e.title}</p>
<p className={cx('mt-0.5 truncate text-xs', mine ? 'text-accent' : 'text-ink-2')}>{e.label}</p>
<div className="mt-1 flex items-center gap-1.5">
<TypeBadge item={{ type: e.type, subtype: e.item?.subtype }} />
{mine && <span className="text-[10px] font-semibold uppercase tracking-[0.04em] text-accent">{t('calendar.inMyList')}</span>}
</div>
</div>
</>
)
if (mine) {
return (
<button onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-left">
{body}
<ChevronRight size={16} className="shrink-0 text-ink-3" />
</button>
)
}
return (
<div className="flex w-full items-center gap-3 py-2.5">
{body}
<button
onClick={() => onAdd(e)}
disabled={busy || added}
className={cx(
'flex h-8 shrink-0 items-center gap-1 rounded-full px-2.5 text-xs font-semibold transition active:scale-95',
added ? 'text-accent' : 'border border-line-strong text-ink-2',
)}
aria-label={added ? t('reco.added', { title: e.title }) : t('reco.addLabel', { title: e.title })}
>
{busy ? <Loader2 size={13} className="animate-spin" /> : added ? <Check size={13} strokeWidth={3} /> : <Plus size={13} strokeWidth={3} />}
{added ? t('reco.addedShort') : t('status.a_voir')}
</button>
</div>
)
}
/** Calendrier des sorties : toutes les sorties (films, séries, animes, dramas) + celles de ma bibliothèque. */
export default function CalendarView({ onClose, onOpen }: { onClose: () => void; onOpen: (item: MediaItem) => void }) {
const { items, settings, patchMany, add } = useMedia()
const hasKey = !!settings.tmdbKey?.trim()
const [prefs, setPrefs] = useState(loadPrefs)
const [releases, setReleases] = useState(loadReleases)
const [loadingMine, setLoadingMine] = useState(false)
const today = todayISO()
const [month, setMonth] = useState(() => {
const d = new Date()
return new Date(d.getFullYear(), d.getMonth(), 1)
})
const [selected, setSelected] = useState<string>()
const [global, setGlobal] = useState<GlobalRelease[]>([])
const [loadingGlobal, setLoadingGlobal] = useState(false)
const [failed, setFailed] = useState(false)
const [expanded, setExpanded] = useState<Set<string>>(new Set())
const [busy, setBusy] = useState<string>()
const [added, setAdded] = useState<Set<string>>(new Set())
const request = useRef(0)
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
useEffect(() => {
try {
localStorage.setItem(PREFS_KEY, JSON.stringify(prefs))
} catch {
/* ignore */
}
}, [prefs])
// Mes titres : prochains épisodes suivis + sorties de « À voir »
const refreshMine = useCallback(
async (force = false) => {
if (!navigator.onLine) return
setLoadingMine(true)
try {
const [airing, rel] = await Promise.all([refreshAiring(items, loadAiring(), settings.tmdbKey, force), refreshReleases(items, settings.tmdbKey, force)])
saveAiring(airing)
setReleases(rel)
const patches = items
.filter((i) => i.status !== 'termine' && airing[i.id] && airing[i.id].aired > (i.episodesTotal ?? 0))
.map((i) => ({ id: i.id, patch: { episodesTotal: airing[i.id].aired } }))
if (patches.length) await patchMany(patches)
} finally {
setLoadingMine(false)
}
},
[items, settings.tmdbKey, patchMany],
)
// Toutes les sorties du mois affiché (+ le mois suivant quand on regarde le mois en cours, pour les 2 prochaines semaines)
const monthsToLoad = useMemo(() => {
const list = [month]
if (monthId(month) === todayISO().slice(0, 7)) list.push(new Date(month.getFullYear(), month.getMonth() + 1, 1))
return list
}, [month])
const refreshGlobal = useCallback(
async (force = false) => {
const id = ++request.current
setGlobal(monthsToLoad.flatMap(cachedMonth))
setFailed(false)
setLoadingGlobal(true)
try {
const all: GlobalRelease[] = []
let anyFailed = false
for (const m of monthsToLoad) {
if (!isBrowsableMonth(monthId(m))) continue
const res = await loadMonth(
m,
RELEASE_CATEGORIES.map((c) => c.value),
settings.tmdbKey,
force,
)
if (id !== request.current) return
all.push(...res.releases)
anyFailed ||= res.failed.length > 0
setGlobal([...all, ...monthsToLoad.slice(monthsToLoad.indexOf(m) + 1).flatMap(cachedMonth)])
}
setFailed(anyFailed)
} finally {
if (id === request.current) setLoadingGlobal(false)
}
},
[monthsToLoad, settings.tmdbKey],
)
useEffect(() => {
void refreshMine(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
void refreshGlobal(false)
}, [refreshGlobal])
// Correspondance avec ma bibliothèque (identifiant de base, sinon titre)
const byExt = useMemo(() => new Map(items.filter((i) => i.externalId).map((i) => [i.externalId!, i])), [items])
const byTitle = useMemo(() => {
const m = new Map<string, MediaItem>()
for (const i of items) for (const t of [i.title, i.originalTitle]) if (t) m.set(normalizeText(t), i)
return m
}, [items])
const entries = useMemo(() => {
const map = new Map<string, Entry>()
for (const ev of calendarEvents(items, releases)) {
const key = `${ev.item.externalId ?? ev.item.id}|${ev.date}`
map.set(key, { key, date: ev.date, title: ev.item.title, label: ev.label, type: ev.item.type, item: ev.item, pop: 200 })
}
for (const r of global) {
const key = `${r.externalId}|${r.date}`
const item = byExt.get(r.externalId) ?? byTitle.get(normalizeText(r.title)) ?? (r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined)
map.set(key, {
key,
date: r.date,
title: item?.title ?? r.title,
poster: r.poster,
label: r.label,
type: item?.type ?? r.cat,
item,
release: r,
pop: item ? 200 : r.pop,
})
}
const cats = new Set<string>(prefs.cats)
return [...map.values()]
.filter((e) => (prefs.mode === 'mine' ? !!e.item : true))
.filter((e) => e.type === 'autre' || cats.has(e.type))
.sort((a, b) => a.date.localeCompare(b.date) || b.pop - a.pop || a.title.localeCompare(b.title, locale()))
}, [items, releases, global, byExt, byTitle, prefs])
const byDay = useMemo(() => {
const m = new Map<string, Entry[]>()
for (const e of entries) m.set(e.date, [...(m.get(e.date) ?? []), e])
return m
}, [entries])
// Grille du mois (semaines commençant le lundi)
const cells = useMemo(() => {
const first = new Date(month)
const offset = (first.getDay() + 6) % 7
const start = new Date(first.getFullYear(), first.getMonth(), 1 - offset)
return Array.from({ length: 42 }, (_, k) => {
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + k)
return { date: iso(d), day: d.getDate(), inMonth: d.getMonth() === month.getMonth() }
}).filter((c, k, all) => k < 35 || all.slice(35).some((x) => x.inMonth))
}, [month])
const mid = monthId(month)
const isCurrent = mid === today.slice(0, 7)
// Mois en cours : les 14 prochains jours (même s'ils débordent sur le mois suivant) ; sinon tout le mois
const lastDay = isCurrent ? iso(new Date(Date.now() + 13 * 86400000)) : `${mid}-31`
const days = [...byDay.keys()].filter((d) => (isCurrent ? d >= today : d.startsWith(mid)) && d <= lastDay).sort()
const tomorrow = iso(new Date(Date.now() + 86400000))
const dayTitle = (d: string) => (d === today ? t('time.today') : d === tomorrow ? t('time.tomorrow') : niceDate(d))
const changeMonth = (delta: number) => {
setSelected(undefined)
setExpanded(new Set())
setMonth((m) => new Date(m.getFullYear(), m.getMonth() + delta, 1))
}
const toggleCat = (c: ReleaseCategory) =>
setPrefs((p) => {
const on = p.cats.includes(c)
const cats = on ? p.cats.filter((x) => x !== c) : [...p.cats, c]
return { ...p, cats: cats.length ? cats : p.cats }
})
const addToWatchlist = async (e: Entry) => {
const r = e.release
if (!r) return
setBusy(e.key)
try {
let data: Partial<MediaInput> = {}
let poster: string | undefined
if (r.externalId.startsWith('anilist:')) {
const res = await getAniListById(r.externalId)
data = { ...res?.prefill }
poster = res?.posterUrl ?? r.poster
} else {
const res = releaseToResult(r)
if (res && hasKey) data = await getTmdbDetails(res, settings.tmdbKey!)
poster = r.poster ? await remotePosterToLocal(r.poster) : undefined
}
await add({
title: r.title,
type: r.cat,
status: 'a_voir',
criteria: {},
episodesWatched: 0,
genres: [],
year: r.year,
externalId: r.externalId,
...data,
poster,
})
setAdded((s) => new Set(s).add(r.externalId))
} catch {
/* réseau : le bouton reste disponible */
} finally {
setBusy(undefined)
}
}
const renderList = (list: Entry[], day: string) => {
const open = expanded.has(day)
const shown = open ? list : list.slice(0, PER_DAY)
return (
<>
<div className="divide-y divide-line">
{shown.map((e) => (
<EntryRow key={e.key} e={e} onOpen={onOpen} onAdd={addToWatchlist} busy={busy === e.key} added={!!e.release && added.has(e.release.externalId)} />
))}
</div>
{list.length > shown.length && (
<button onClick={() => setExpanded((s) => new Set(s).add(day))} className="mt-1 w-full py-2 text-xs font-medium text-ink-3">
{t('calendar.seeMore', { count: list.length - shown.length })} <span className="text-accent">→</span>
</button>
)}
</>
)
}
const loading = loadingGlobal || loadingMine
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')}>
<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="flex-1 text-center text-base font-semibold">
{t('calendar.heading')}<span className="text-accent">{t('calendar.headingAccent')}</span>
</h2>
<button
onClick={() => {
void refreshMine(true)
void refreshGlobal(true)
}}
disabled={loading}
className="grid size-10 place-items-center rounded-full text-ink-2"
aria-label={t('calendar.refresh')}
>
{loading ? <Loader2 size={18} className="animate-spin" /> : <RefreshCw size={18} />}
</button>
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<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">
{(['all', 'mine'] as const).map((m) => (
<button
key={m}
onClick={() => setPrefs((p) => ({ ...p, mode: m }))}
className={cx('rounded-full py-2 text-sm font-medium transition-colors', prefs.mode === m ? 'bg-ink text-bg' : 'text-ink-3')}
>
{m === 'all' ? t('calendar.all') : t('calendar.mine')}
</button>
))}
</div>
<div className="no-scrollbar -mx-4 mb-5 flex gap-2 overflow-x-auto px-4">
{RELEASE_CATEGORIES.map((c) => (
<button key={c.value} onClick={() => toggleCat(c.value)} className={cx('chip shrink-0 py-1! text-[13px]', prefs.cats.includes(c.value) && 'chip-on')}>
{c.label}
</button>
))}
</div>
{/* Mois */}
<div className="mb-3 flex items-center justify-between">
<button onClick={() => changeMonth(-1)} className="grid size-9 place-items-center rounded-full border border-line text-ink-2" aria-label={t('calendar.prevMonth')}>
<ChevronLeft size={18} />
</button>
<span className="text-lg font-bold capitalize">{month.toLocaleDateString(locale(), { month: 'long', year: 'numeric' })}</span>
<button onClick={() => changeMonth(1)} className="grid size-9 place-items-center rounded-full border border-line text-ink-2" aria-label={t('calendar.nextMonth')}>
<ChevronRight size={18} />
</button>
</div>
<div className="grid grid-cols-7 gap-1 text-center">
{weekdays().map((w, k) => (
<span key={k} className="eyebrow py-1">
{w}
</span>
))}
{cells.map((c) => {
const evs = byDay.get(c.date) ?? []
const mine = evs.filter((e) => e.item).length
const isSel = c.date === selected
const isToday = c.date === today
return (
<button
key={c.date}
onClick={() => setSelected(isSel ? undefined : c.date)}
className={cx(
'relative flex aspect-square flex-col items-center justify-center rounded-xl text-sm transition-colors',
!c.inMonth && 'text-ink-3/50',
c.inMonth && !isSel && 'text-ink-2',
isSel && 'bg-ink font-bold text-bg',
!isSel && isToday && 'border border-accent font-bold text-ink',
!isSel && evs.length > 0 && 'bg-surface-2',
!isSel && mine > 0 && 'font-bold text-ink',
)}
aria-label={evs.length ? `${c.date} : ${t('calendar.releases', { count: evs.length })}` : c.date}
>
{c.day}
{evs.length > 0 && (
<span className="absolute bottom-1.5 flex gap-0.5">
{Array.from({ length: Math.min(3, evs.length) }, (_, k) => (
<span key={k} className={cx('size-1 rounded-full', isSel ? 'bg-bg' : k < mine ? 'bg-accent' : 'bg-ink-3')} />
))}
</span>
)}
</button>
)
})}
</div>
<p className="mt-2 flex items-center justify-center gap-4 text-[11px] text-ink-3">
<span className="flex items-center gap-1.5">
<span className="size-1.5 rounded-full bg-accent" /> {t('calendar.inMyListLegend')}
</span>
{prefs.mode === 'all' && (
<span className="flex items-center gap-1.5">
<span className="size-1.5 rounded-full bg-ink-3" /> {t('calendar.others')}
</span>
)}
</p>
{prefs.mode === 'all' && !hasKey && (
<p className="mt-4 rounded-xl border border-line px-3 py-2.5 text-xs leading-relaxed text-ink-2">
{t('calendar.needKey')}
</p>
)}
{prefs.mode === 'all' && !browsable && (
<p className="mt-4 text-center text-xs text-ink-3">{t('calendar.range')}</p>
)}
{failed && <p className="mt-4 text-center text-xs text-ink-3">{t('calendar.failed')}</p>}
{/* Détail du jour choisi, ou liste jour par jour */}
{selected ? (
<section className="mt-6">
<h3 className="mb-1 border-b border-line pb-2 text-sm font-bold first-letter:uppercase">{dayTitle(selected)}</h3>
{byDay.get(selected)?.length ? renderList(byDay.get(selected)!, selected) : <p className="py-3 text-sm text-ink-3">{t('calendar.nothingThatDay')}</p>}
</section>
) : days.length ? (
<>
{isCurrent && <h3 className="eyebrow mt-7 text-ink-2">{t('calendar.next14')}</h3>}
{days.map((d) => (
<section key={d} className="mt-6">
<h3 className="mb-1 flex items-baseline justify-between border-b border-line pb-2">
<span className="text-sm font-bold first-letter:uppercase">{dayTitle(d)}</span>
<span className="text-xs font-semibold text-accent">{byDay.get(d)!.length}</span>
</h3>
{renderList(byDay.get(d)!, d)}
</section>
))}
</>
) : (
<p className="mt-8 flex items-center justify-center gap-2 text-center text-sm text-ink-3">
{loading ? (
<>
<Loader2 size={14} className="animate-spin" /> {t('calendar.loading')}
</>
) : prefs.mode === 'mine' ? (
isCurrent ? t('calendar.noneMine14') : t('calendar.noneMineMonth')
) : (
isCurrent ? t('calendar.none14') : t('calendar.noneMonth')
)}
</p>
)}
<p className="mt-8 text-xs leading-relaxed text-ink-3">
{t('calendar.footer')}
</p>
</div>
</div>
</div>
)
}
+47
View File
@@ -0,0 +1,47 @@
import { t } from '../i18n'
import { useEffect } from 'react'
interface Props {
open: boolean
title: string
message?: string
confirmLabel?: string
onConfirm: () => void
onCancel: () => void
}
/** Fenêtre « Êtes-vous sûr ? » intégrée à l'app (plus fiable que window.confirm sur mobile). */
export default function ConfirmDialog({ open, title, message, confirmLabel = t('common.confirm'), onConfirm, onCancel }: Props) {
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onCancel()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [open, onCancel])
if (!open) return null
return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 p-4 sm:items-center" onClick={onCancel}>
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="confirm-title"
className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5"
onClick={(e) => e.stopPropagation()}
>
<h2 id="confirm-title" className="text-lg">
{title}
</h2>
{message && <p className="mt-2 text-sm leading-relaxed text-ink-2">{message}</p>}
<div className="mt-5 grid grid-cols-2 gap-2">
<button onClick={onCancel} className="btn btn-ghost">
{t('common.cancel')}
</button>
<button onClick={onConfirm} className="btn btn-primary" autoFocus>
{confirmLabel}
</button>
</div>
</div>
</div>
)
}
+176
View File
@@ -0,0 +1,176 @@
import { t } from '../i18n'
import { Check, Loader2, Search } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { getTmdbDetails, searchAniList, searchTmdb, type SearchResult, type Source } from '../lib/catalogApi'
import { remotePosterToLocal } from '../lib/image'
import { cx } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput } 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
}
const SOURCES: { value: Source; readonly label: string; hint: string }[] = [
{ value: 'tmdb', get label() { return t('search.moviesSeries') }, hint: 'TMDB' },
{ value: 'anilist', get label() { return t('typePlural.anime') }, hint: 'AniList' },
]
/** Recherche un titre dans TMDB ou AniList et remplit la fiche automatiquement. */
export default function DatabaseSearch({ onPick, initialQuery = '', currentExternalId, onGoToSettings }: Props) {
const { items, settings } = useMedia()
const hasKey = !!settings.tmdbKey?.trim()
const [source, setSource] = useState<Source>(hasKey ? 'tmdb' : 'anilist')
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 existing = new Set(items.map((i) => i.externalId).filter((id) => id && id !== currentExternalId))
// Recherche avec un petit délai pendant la frappe
useEffect(() => {
const q = query.trim()
setError(undefined)
if (q.length < 2 || (source === 'tmdb' && !hasKey)) {
setResults([])
setLoading(false)
return
}
const id = ++requestId.current
setLoading(true)
const timer = setTimeout(async () => {
try {
const res = source === 'tmdb' ? await searchTmdb(q, settings.tmdbKey!) : await searchAniList(q)
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, source, hasKey, settings.tmdbKey])
const pick = async (r: SearchResult) => {
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>
<div className="flex rounded-full border border-line p-0.5">
{SOURCES.map((s) => (
<button
key={s.value}
type="button"
onClick={() => setSource(s.value)}
className={cx('rounded-full px-3 py-1 text-xs font-medium transition-colors', source === s.value ? 'bg-ink text-bg' : 'text-ink-3')}
>
{s.label}
</button>
))}
</div>
</div>
{source === 'tmdb' && !hasKey ? (
<div className="rounded-xl border border-dashed border-line-strong p-3.5 text-sm text-ink-2">
{t('search.needKey')}
{onGoToSettings && (
<button type="button" onClick={onGoToSettings} className="mt-2 block font-medium text-ink">
{t('search.openSettings')} <span className="text-accent">→</span>
</button>
)}
</div>
) : (
<div className="relative">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={source === 'tmdb' ? 'Parasite, Crash Landing on You…' : 'Frieren, One Piece…'}
className="field pl-10"
enterKeyHint="search"
autoComplete="off"
/>
{loading && <Loader2 size={17} className="absolute right-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</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 already = existing.has(r.externalId)
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-left 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"> · {t('search.already')}</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 && !(source === 'tmdb' && !hasKey) && (
<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: source === 'tmdb' ? 'TMDB' : 'AniList' })}
</p>
</div>
)
}
+143
View File
@@ -0,0 +1,143 @@
import { t } from '../i18n'
import { Loader2, RefreshCw } from 'lucide-react'
import { useMemo, useState } from 'react'
import { fetchPublicRatings, missingPublic } from '../lib/publicRatings'
import { cx, formatRating } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem, RatingScale } from '../types'
import Poster from './Poster'
import { SectionTitle } from './ui'
/** Écart signé, arrondi au dixième dans l'échelle choisie (« 0 » plutôt que « +0,0 »). */
const signed = (v: number, scale: RatingScale) => {
const r = Math.round((scale === '5' ? v / 2 : v) * 10) / 10
if (r === 0) return '0'
return `${r > 0 ? '+' : '−'}${String(Math.abs(r)).replace('.', t('common.decimalSep'))}`
}
function Row({ item, scale }: { item: MediaItem; scale: RatingScale }) {
const gap = item.rating! - item.publicRating!
// barre centrée : moitié gauche = moins aimé, moitié droite = plus aimé (écart max affiché : 5 points /10)
const width = Math.min(50, (Math.abs(gap) / 5) * 50)
return (
<li className="flex items-center gap-3 py-2.5">
<div className="w-9 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{item.title}</p>
<p className="text-[11px] text-ink-3">
{t('public.me')} <span className="text-ink-2">{formatRating(item.rating, scale)}</span> · {t('public.label')} <span className="text-ink-2">{formatRating(item.publicRating, scale)}</span>
</p>
<div className="relative mt-1.5 h-1.5 rounded-full bg-surface-2">
<span className="absolute inset-y-0 left-1/2 w-px bg-line" />
<span
className={cx('absolute inset-y-0 rounded-full', gap >= 0 ? 'bg-accent' : 'bg-ink-3')}
style={gap >= 0 ? { left: '50%', width: `${width}%` } : { right: '50%', width: `${width}%` }}
/>
</div>
</div>
<span className={cx('w-11 shrink-0 text-right text-sm font-bold tabular-nums', gap >= 0 ? 'text-accent' : 'text-ink-2')}>{signed(gap, scale)}</span>
</li>
)
}
/** Stats « Moi vs le public » : écarts entre mes notes et la moyenne TMDB / AniList. */
export default function Disagreements({ scoped }: { scoped: MediaItem[] }) {
const { items, settings, patchMany } = useMedia()
const scale = settings.ratingScale
const [progress, setProgress] = useState<[number, number]>()
const [message, setMessage] = useState<string>()
const compared = useMemo(() => scoped.filter((i) => i.rating != null && i.publicRating != null), [scoped])
const rated = useMemo(() => items.filter((i) => i.rating != null), [items])
const missing = useMemo(() => missingPublic(rated, settings.tmdbKey).length, [rated, settings.tmdbKey, progress])
const run = async () => {
if (!navigator.onLine) return setMessage(t('common.offline'))
setMessage(undefined)
setProgress([0, missing])
try {
const patches = await fetchPublicRatings(rated, settings.tmdbKey, (done, total) => setProgress([done, total]))
if (patches.length) await patchMany(patches)
setMessage(patches.length ? t('public.added', { count: patches.length }) : t('public.noneFound'))
} finally {
setProgress(undefined)
}
}
const gaps = compared.map((i) => i.rating! - i.publicRating!)
const avg = gaps.length ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0
const agree = gaps.length ? Math.round((gaps.filter((g) => Math.abs(g) <= 1).length / gaps.length) * 100) : 0
const sorted = [...compared].sort((a, b) => b.rating! - b.publicRating! - (a.rating! - a.publicRating!))
const loved = sorted.filter((i) => i.rating! - i.publicRating! >= 1).slice(0, 5)
const hated = sorted.filter((i) => i.rating! - i.publicRating! <= -1).reverse().slice(0, 5)
const fetchButton =
missing > 0 || progress ? (
<button onClick={run} disabled={!!progress} className="flex shrink-0 items-center gap-1.5 text-xs font-medium text-ink-3 transition-colors hover:text-ink">
{progress ? <Loader2 size={13} className="animate-spin" /> : <RefreshCw size={13} className="text-accent" />}
{progress ? `${progress[0]}/${progress[1]}` : t('public.fetch', { n: missing })}
</button>
) : undefined
return (
<>
<SectionTitle action={fetchButton}>{t('public.title')}</SectionTitle>
{message && <p className="-mt-2 mb-3 text-xs text-ink-3">{message}</p>}
{compared.length === 0 ? (
<p className="text-sm text-ink-3">
{missing > 0
? t('public.hintFetch')
: settings.tmdbKey
? t('public.hintNone')
: t('public.hintKey')}
</p>
) : (
<>
<div className="grid grid-cols-2 gap-3">
<div className="card p-4">
<div className="eyebrow">{t('public.avgGap')}</div>
<div className={cx('mt-2 text-2xl font-bold leading-none tabular-nums', avg >= 0.3 && 'text-accent')}>{signed(avg, scale)}</div>
<div className="mt-1.5 text-xs text-ink-3">{Math.abs(avg) < 0.3 ? t('public.average') : avg > 0 ? t('public.generous') : t('public.harsh')}</div>
</div>
<div className="card p-4">
<div className="eyebrow">{t('public.agreeTitle')}</div>
<div className="mt-2 text-2xl font-bold leading-none tabular-nums">{agree} %</div>
<div className="mt-1.5 text-xs text-ink-3">
{scale === '5' ? t('public.within5', { count: compared.length }) : t('public.within10', { count: compared.length })}
</div>
</div>
</div>
{loved.length > 0 && (
<div className="card mt-3 px-4 pb-1.5 pt-4">
<h3 className="text-sm font-semibold">
{t('public.lovedPre')}<span className="text-accent">{t('public.lovedAccent')}</span>{t('public.lovedPost')}
</h3>
<ul className="divide-y divide-line">
{loved.map((i) => (
<Row key={i.id} item={i} scale={scale} />
))}
</ul>
</div>
)}
{hated.length > 0 && (
<div className="card mt-3 px-4 pb-1.5 pt-4">
<h3 className="text-sm font-semibold">
{t('public.hatedPre')}<span className="text-ink-2">{t('public.hatedAccent')}</span>{t('public.hatedPost')}
</h3>
<ul className="divide-y divide-line">
{hated.map((i) => (
<Row key={i.id} item={i} scale={scale} />
))}
</ul>
</div>
)}
{!loved.length && !hated.length && <p className="mt-3 text-sm text-ink-3">{t('public.allAgree')}</p>}
</>
)}
</>
)
}
+131
View File
@@ -0,0 +1,131 @@
import { locale, t } from '../i18n'
import { Star } from 'lucide-react'
import { useMemo, useState } from 'react'
import { DEFAULT_FILM_MINUTES, TYPE_BY_VALUE } from '../lib/constants'
import { watchMinutes } from '../lib/stats'
import { cx, formatDuration, formatRating } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
import { EmptyState } from './ui'
type Kind = 'fini' | 'revu' | 'commence' | 'abandonne'
interface Entry {
date: string
item: MediaItem
kind: Kind
minutes: number
}
const kindLabel = (k: Kind) => (k === 'fini' ? t('status.termine') : k === 'revu' ? t('journal.rewatched') : k === 'commence' ? t('journal.started') : t('status.abandonne'))
/** Toutes les dates de visionnage de la bibliothèque, de la plus récente à la plus ancienne. */
function buildEntries(items: MediaItem[]): Entry[] {
const out: Entry[] = []
for (const item of items) {
if (item.status === 'termine' && item.endDate) out.push({ date: item.endDate, item, kind: 'fini', minutes: watchMinutes(item) - rewatchMinutes(item) })
else if ((item.status === 'en_cours' || item.status === 'pause') && item.startDate) out.push({ date: item.startDate, item, kind: 'commence', minutes: 0 })
else if (item.status === 'abandonne' && (item.endDate || item.startDate)) out.push({ date: (item.endDate || item.startDate)!, item, kind: 'abandonne', minutes: 0 })
for (const d of item.rewatchDates ?? []) out.push({ date: d, item, kind: 'revu', minutes: TYPE_BY_VALUE[item.type].episodic ? 0 : item.duration || DEFAULT_FILM_MINUTES })
}
return out.sort((a, b) => b.date.localeCompare(a.date) || a.item.title.localeCompare(b.item.title, locale()))
}
const rewatchMinutes = (i: MediaItem) => (TYPE_BY_VALUE[i.type].episodic ? 0 : (i.rewatchDates?.length ?? 0) * (i.duration || DEFAULT_FILM_MINUTES))
/** Onglet « Journal » du catalogue : chronologie groupée par mois. */
export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, settings } = useMedia()
const entries = useMemo(() => buildEntries(items), [items])
const years = useMemo(() => [...new Set(entries.map((e) => e.date.slice(0, 4)))], [entries])
const [year, setYear] = useState('')
const [shown, setShown] = useState(6)
const months = useMemo(() => {
const list = year ? entries.filter((e) => e.date.startsWith(year)) : entries
const map = new Map<string, Entry[]>()
for (const e of list) map.set(e.date.slice(0, 7), [...(map.get(e.date.slice(0, 7)) ?? []), e])
return [...map.entries()]
}, [entries, year])
if (!entries.length) {
return <EmptyState title={t('journal.emptyTitle')} text={t('journal.emptyText')} />
}
return (
<div className="mt-2">
<div className="no-scrollbar -mx-4 mb-2 flex gap-2 overflow-x-auto px-4">
{['', ...years].map((y) => (
<button
key={y || 'all'}
onClick={() => {
setYear(y)
setShown(6)
}}
className={cx('chip py-1! text-[13px]', year === y && 'chip-on')}
>
{y || t('common.all')}
</button>
))}
</div>
{months.slice(0, shown).map(([key, list]) => {
const label = new Date(key + '-15T12:00:00').toLocaleDateString(locale(), { month: 'long', year: 'numeric' })
const minutes = list.reduce((s, e) => s + e.minutes, 0)
const finished = list.filter((e) => e.kind === 'fini' || e.kind === 'revu').length
return (
<section key={key} className="mt-7">
<div className="mb-1 flex items-baseline justify-between border-b border-line pb-2">
<h3 className="text-lg font-bold capitalize">{label}</h3>
<span className="text-xs text-ink-3">
{t('journal.seen', { count: finished })}
{minutes > 0 && ` · ${formatDuration(minutes)}`}
</span>
</div>
<ul className="divide-y divide-line">
{list.map((e) => {
const d = new Date(e.date + 'T12:00:00')
return (
<li key={e.item.id + e.date + e.kind}>
<button onClick={() => onOpen(e.item)} className="flex w-full items-center gap-3 py-2.5 text-left">
<span className="w-9 shrink-0 text-center">
<span className="block text-xl font-bold leading-none tabular-nums">{d.getDate()}</span>
<span className="block text-[10px] uppercase text-ink-3">{d.toLocaleDateString(locale(), { weekday: 'short' }).replace('.', '')}</span>
</span>
<div className="w-10 shrink-0">
<Poster src={e.item.poster} title={e.item.title} />
</div>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold">{e.item.title}</span>
<span className="mt-1 flex flex-wrap items-center gap-1.5">
<TypeBadge item={e.item} />
{e.kind !== 'fini' && (
<span className={cx('text-[11px] font-semibold', e.kind === 'revu' ? 'text-accent' : 'text-ink-3')}>{kindLabel(e.kind)}</span>
)}
</span>
</span>
{e.item.rating ? (
<span className="flex shrink-0 items-center gap-1 text-xs font-semibold">
<Star size={12} className="fill-accent text-accent" />
{formatRating(e.item.rating, settings.ratingScale)}
</span>
) : null}
</button>
</li>
)
})}
</ul>
</section>
)
})}
{months.length > shown && (
<button onClick={() => setShown((n) => n + 6)} className="btn btn-ghost mt-6 w-full">
{t('journal.more')}
</button>
)}
</div>
)
}
+233
View File
@@ -0,0 +1,233 @@
import { locale, t } from '../i18n'
import { ArrowLeft, Check, Pencil, Plus, Search, Trash2 } from 'lucide-react'
import { useMemo, useState } from 'react'
import { cx, normalizeText } from '../lib/utils'
import { useMedia } from '../store'
import type { CustomList, MediaItem } from '../types'
import { TypeBadge } from './Badges'
import ConfirmDialog from './ConfirmDialog'
import { MediaCard } from './MediaCard'
import Poster from './Poster'
import { EmptyState } from './ui'
/** Mosaïque 2×2 des premières affiches d'une liste. */
function Mosaic({ items }: { items: MediaItem[] }) {
const cells = [0, 1, 2, 3].map((i) => items[i])
return (
<div className="grid grid-cols-2 gap-0.5 overflow-hidden rounded-xl border border-line bg-surface-2">
{cells.map((item, i) =>
item?.poster ? (
<img key={i} src={item.poster} alt="" loading="lazy" className="aspect-[2/3] w-full object-cover" />
) : (
<div key={i} className="aspect-[2/3] w-full bg-surface-2" />
),
)}
</div>
)
}
export function NewListForm({ onCreated, autoFocus }: { onCreated?: (list: CustomList) => void; autoFocus?: boolean }) {
const { createList } = useMedia()
const [name, setName] = useState('')
// Pas de <form> ici : ce champ peut vivre à l'intérieur du formulaire d'une fiche
const submit = () => {
if (!name.trim()) return
onCreated?.(createList(name))
setName('')
}
return (
<div className="flex gap-2">
<input
className="field"
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
submit()
}
}}
placeholder={t('lists.newListPh')}
autoFocus={autoFocus}
enterKeyHint="done"
/>
<button type="button" onClick={submit} disabled={!name.trim()} className="btn btn-light shrink-0 px-4 text-sm">
{t('lists.create')}
</button>
</div>
)
}
function ListDetail({ list, onBack, onOpen }: { list: CustomList; onBack: () => void; onOpen: (item: MediaItem) => void }) {
const { items, renameList, deleteList, toggleInList } = useMedia()
const [renaming, setRenaming] = useState(false)
const [name, setName] = useState(list.name)
const [adding, setAdding] = useState(false)
const [query, setQuery] = useState('')
const [confirm, setConfirm] = useState(false)
const members = items.filter((i) => i.listIds?.includes(list.id))
const candidates = useMemo(() => {
const q = normalizeText(query)
return items
.filter((i) => !q || normalizeText(`${i.title} ${i.originalTitle ?? ''}`).includes(q))
.sort((a, b) => a.title.localeCompare(b.title, locale()))
.slice(0, 80)
}, [items, query])
return (
<>
<button onClick={onBack} className="mt-2 flex items-center gap-1.5 text-sm text-ink-3">
<ArrowLeft size={16} /> {t('lists.myLists')}
</button>
<div className="mb-5 mt-3 flex items-start justify-between gap-3">
{renaming ? (
<form
className="flex flex-1 gap-2"
onSubmit={(e) => {
e.preventDefault()
renameList(list.id, name)
setRenaming(false)
}}
>
<input className="field" value={name} onChange={(e) => setName(e.target.value)} autoFocus />
<button className="btn btn-light shrink-0 px-4 text-sm">OK</button>
</form>
) : (
<div className="min-w-0">
<h2 className="text-2xl leading-tight">{list.name}</h2>
<p className="mt-1 text-sm text-ink-3">
{t('account.nTitles', { count: members.length })}
</p>
</div>
)}
{!renaming && (
<div className="flex shrink-0 gap-1">
<button onClick={() => setRenaming(true)} className="grid size-10 place-items-center rounded-full border border-line text-ink-2" aria-label={t('lists.rename')}>
<Pencil size={16} />
</button>
<button onClick={() => setConfirm(true)} className="grid size-10 place-items-center rounded-full border border-line text-ink-2" aria-label={t('lists.delete')}>
<Trash2 size={16} />
</button>
</div>
)}
</div>
<button onClick={() => setAdding((v) => !v)} className={cx('chip mb-4', adding && 'chip-on')}>
{adding ? <Check size={14} /> : <Plus size={14} />}
{adding ? t('lists.done') : t('lists.addRemove')}
</button>
{adding ? (
<div>
<div className="relative mb-2">
<Search size={17} className="pointer-events-none absolute left-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('lists.searchLibrary')} className="field pl-10" autoFocus />
</div>
<ul className="divide-y divide-line">
{candidates.map((item) => {
const inList = item.listIds?.includes(list.id)
return (
<li key={item.id}>
<button onClick={() => toggleInList(item.id, list.id)} className="flex w-full items-center gap-3 py-2.5 text-left">
<div className="w-9 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{item.title}</p>
<div className="mt-1">
<TypeBadge item={item} />
</div>
</div>
<span
className={cx(
'grid size-7 shrink-0 place-items-center rounded-full border',
inList ? 'border-accent-fill bg-accent-fill text-on-accent' : 'border-line-strong text-transparent',
)}
>
<Check size={14} strokeWidth={3} />
</span>
</button>
</li>
)
})}
</ul>
</div>
) : members.length ? (
<div className="grid grid-cols-2 gap-x-3.5 gap-y-6 sm:grid-cols-3">
{members.map((item) => (
<MediaCard key={item.id} item={item} onOpen={onOpen} />
))}
</div>
) : (
<EmptyState title={t('lists.emptyTitle')} text={t('lists.emptyText')} />
)}
<ConfirmDialog
open={confirm}
title={t('confirm.title')}
message={t('lists.deleteConfirm', { name: list.name })}
confirmLabel={t('common.delete')}
onConfirm={async () => {
setConfirm(false)
await deleteList(list.id)
onBack()
}}
onCancel={() => setConfirm(false)}
/>
</>
)
}
/** Onglet « Listes » du catalogue. */
export default function ListsView({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, lists } = useMedia()
const [openId, setOpenId] = useState<string>()
const [creating, setCreating] = useState(false)
const open = lists.find((l) => l.id === openId)
if (open) return <ListDetail list={open} onBack={() => setOpenId(undefined)} onOpen={onOpen} />
return (
<div className="mt-2">
{creating ? (
<div className="mb-5">
<NewListForm
autoFocus
onCreated={(l) => {
setCreating(false)
setOpenId(l.id)
}}
/>
</div>
) : (
<button onClick={() => setCreating(true)} className="chip mb-5">
<Plus size={14} /> {t('lists.newList')}
</button>
)}
{lists.length === 0 ? (
<EmptyState
title={t('lists.noneTitle')}
text={t('lists.noneText')}
/>
) : (
<div className="grid grid-cols-2 gap-x-3.5 gap-y-6 sm:grid-cols-3">
{lists.map((l) => {
const members = items.filter((i) => i.listIds?.includes(l.id))
return (
<button key={l.id} onClick={() => setOpenId(l.id)} className="text-left">
<Mosaic items={members} />
<p className="mt-2 truncate text-sm font-semibold">{l.name}</p>
<p className="text-xs text-ink-3">
{t('account.nTitles', { count: members.length })}
</p>
</button>
)
})}
</div>
)}
</div>
)
}
+102
View File
@@ -0,0 +1,102 @@
import { t } from '../i18n'
import { Heart, Plus } from 'lucide-react'
import { TYPE_BY_VALUE } from '../lib/constants'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { StatusPill, TypeBadge } from './Badges'
import Poster from './Poster'
import { RatingBadge } from './Rating'
function Progress({ item }: { item: MediaItem }) {
if (!TYPE_BY_VALUE[item.type].episodic || (!item.episodesWatched && !item.episodesTotal)) return null
const pct = item.episodesTotal ? Math.min(100, (item.episodesWatched / item.episodesTotal) * 100) : 0
return (
<div className="mt-1.5">
<div className="flex justify-between text-[10.5px] text-ink-3">
<span>
{item.season ? `S${item.season} · ` : ''}{t('card.ep', { n: item.episodesWatched })}
{item.episodesTotal ? `/${item.episodesTotal}` : ''}
</span>
</div>
{item.episodesTotal ? (
<div className="mt-1.5 h-[3px] overflow-hidden rounded-full bg-line">
<div className="h-full rounded-full bg-accent" style={{ width: `${pct}%` }} />
</div>
) : null}
</div>
)
}
/** Carte verticale (grille du catalogue). */
export function MediaCard({ item, onOpen }: { item: MediaItem; onOpen: (item: MediaItem) => void }) {
const { settings, incrementEpisode } = useMedia()
const canIncrement =
TYPE_BY_VALUE[item.type].episodic &&
item.status === 'en_cours' &&
(!item.episodesTotal || item.episodesWatched < item.episodesTotal)
return (
<article>
<div className="relative">
<button onClick={() => onOpen(item)} className="block w-full" aria-label={t('card.open', { title: item.title })}>
<Poster src={item.poster} title={item.title} />
</button>
<TypeBadge item={item} className="pointer-events-none absolute left-2 top-2 border-transparent bg-bg/85" />
{item.favorite && (
<Heart size={15} className="pointer-events-none absolute right-2 top-2 fill-accent text-accent" />
)}
{canIncrement && (
<button
onClick={() => incrementEpisode(item.id)}
className="absolute bottom-2 right-2 flex h-8 items-center gap-0.5 rounded-full bg-accent-fill px-3 text-xs font-medium text-on-accent transition active:scale-90"
aria-label={t('card.plusOne', { title: item.title })}
>
<Plus size={13} strokeWidth={2.5} />1
</button>
)}
</div>
<button onClick={() => onOpen(item)} className="block w-full text-left">
<h3 className="mt-2.5 line-clamp-2 font-sans text-sm font-semibold leading-snug tracking-normal">{item.title}</h3>
<div className="mt-1 flex items-center justify-between gap-2">
<StatusPill status={item.status} />
<RatingBadge value={item.rating} scale={settings.ratingScale} />
</div>
<Progress item={item} />
</button>
</article>
)
}
/** Ligne horizontale (accueil : « En cours »), avec compteur +1. */
export function MediaRow({ item, onOpen }: { item: MediaItem; onOpen: (item: MediaItem) => void }) {
const { settings, incrementEpisode } = useMedia()
const episodic = TYPE_BY_VALUE[item.type].episodic
const done = !!item.episodesTotal && item.episodesWatched >= item.episodesTotal
return (
<article className="card flex items-center gap-3.5 p-3">
<button onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
<div className="w-14 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<TypeBadge item={item} />
<RatingBadge value={item.rating} scale={settings.ratingScale} />
</div>
<h3 className="mt-1.5 truncate text-[15px] font-semibold leading-tight">{item.title}</h3>
{episodic ? <Progress item={item} /> : <StatusPill status={item.status} />}
</div>
</button>
{episodic && !done && (
<button
onClick={() => incrementEpisode(item.id)}
className="flex h-10 shrink-0 items-center gap-0.5 rounded-full border border-accent px-3.5 text-sm text-accent transition-colors active:bg-accent-fill active:text-on-accent"
aria-label={t('card.plusOne', { title: item.title })}
>
<Plus size={14} strokeWidth={2.5} />1
</button>
)}
</article>
)
}
+555
View File
@@ -0,0 +1,555 @@
import { locale, t } from '../i18n'
import { Check, Heart, ImagePlus, Loader2, Minus, Plus, Share2, Trash2, X } from 'lucide-react'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { CRITERIA, DEFAULT_FILM_MINUTES, MEDIA_TYPES, platformSuggestions as defaultPlatforms, 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 } from '../lib/catalogApi'
import { renderItemCard, slug } from '../lib/shareCard'
import { cx, formatRating, todayISO } from '../lib/utils'
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 { 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',
'episodeDuration',
'poster',
'externalId',
'countries',
'publicRating',
] as const
function Section({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="space-y-3">
<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
}
/** « 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-right 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 }: Props) {
const { add, update, remove, items, settings, lists, account } = 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
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
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])
const platformSuggestions = useMemo(
() => [...new Set([...items.map((i) => i.platform).filter(Boolean), ...defaultPlatforms()])] as string[],
[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]
}
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
if (next.episodesTotal && next.episodesWatched > next.episodesTotal) next.episodesWatched = next.episodesTotal
return next
})
setFilledFrom(data.externalId?.startsWith('anilist') ? 'AniList' : 'TMDB')
setShowSearch(false)
}
const setStatus = (status: WatchStatus) =>
setForm((f) => {
const next = { ...f, status }
if (status === 'en_cours' && !f.startDate) next.startDate = todayISO()
if (status === 'termine') {
if (!f.endDate) next.endDate = todayISO()
if (f.episodesTotal && TYPE_BY_VALUE[f.type].episodic) next.episodesWatched = f.episodesTotal
}
return next
})
const changeEpisodes = (delta: number) =>
setForm((f) => {
let n = Math.max(0, f.episodesWatched + delta)
if (f.episodesTotal) n = Math.min(n, f.episodesTotal)
return { ...f, episodesWatched: n }
})
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,
}
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()
}}
>
<div className="safe-bottom mx-auto max-w-2xl space-y-9 px-4 py-6 pb-16">
{/* Recherche en ligne */}
{showSearch ? (
<DatabaseSearch
onPick={applyMetadata}
initialQuery={item ? form.title : ''}
currentExternalId={item?.externalId}
onGoToSettings={onGoToSettings}
/>
) : (
<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-left 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 */}
<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 right-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 && (
<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>
)}
{/* 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>
{/* 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>
{/* 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>
{/* Épisodes / durée */}
{typeInfo.episodic ? (
<Section title={t('form.episodes')}>
<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}
{form.episodesTotal ? <span className="text-base text-ink-3">/{form.episodesTotal}</span> : null}
</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-3 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>
<Field label={t('form.minPerEp')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.episodeDuration ?? ''} onChange={(e) => set('episodeDuration', toNum(e.target.value))} placeholder={String(typeInfo.episodeMinutes)} />
</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>
)}
{/* Infos */}
<Section title={t('form.info')}>
<div className="grid grid-cols-2 gap-3">
<Field label={t('form.start')}>
<input className="field" type="date" value={form.startDate ?? ''} onChange={(e) => set('startDate', e.target.value || undefined)} />
</Field>
<Field label={t('form.end')}>
<input className="field" type="date" value={form.endDate ?? ''} onChange={(e) => set('endDate', e.target.value || undefined)} />
</Field>
<Field label={t('form.year')}>
<input className="field" type="number" inputMode="numeric" value={form.year ?? ''} onChange={(e) => set('year', toNum(e.target.value))} placeholder="2024" />
</Field>
<Field label={t('form.platform')}>
<input className="field" list="platforms" value={form.platform ?? ''} onChange={(e) => set('platform', e.target.value)} placeholder="Netflix…" />
<datalist id="platforms">
{platformSuggestions.map((p) => (
<option key={p} value={p} />
))}
</datalist>
</Field>
</div>
<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>
</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>
)}
<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')} />
{account && (
<label className="mt-3 flex items-start gap-2.5 text-sm text-ink-2">
<input type="checkbox" className="mt-0.5 size-4 accent-[var(--color-accent)]" checked={!!form.notesPublic} onChange={(e) => set('notesPublic', e.target.checked || undefined)} />
<span>
{t('form.reviewPublic')}
<span className="block text-xs text-ink-3">{t('form.reviewPublicHint')}</span>
</span>
</label>
)}
</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>
)
}
+120
View File
@@ -0,0 +1,120 @@
import { locale, t } from '../i18n'
import { Loader2, RefreshCw } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { loadAiring, needsCheck, novelties, refreshAiring, saveAiring, trackable, type AiringCache } from '../lib/airing'
import { formatDate, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import Poster from './Poster'
import { SectionTitle } from './ui'
const dayLabel = (iso: string) => {
const d = new Date(iso + 'T12:00:00')
const diff = Math.round((d.getTime() - new Date(todayISO() + 'T12:00:00').getTime()) / 86400000)
if (diff <= 0) return t('time.today')
if (diff === 1) return t('time.tomorrow')
if (diff < 7) return d.toLocaleDateString(locale(), { weekday: 'long' })
return t('time.onDate', { date: formatDate(iso) })
}
/** Section « Nouveautés » de l'accueil : nouveaux épisodes et nouvelles saisons. */
export default function NewEpisodes({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, loading, settings, patchMany, update } = useMedia()
const [cache, setCache] = useState<AiringCache>(loadAiring)
const [checking, setChecking] = useState(false)
const started = useRef(false)
const check = useCallback(
async (force = false) => {
setChecking(true)
try {
const next = await refreshAiring(items, loadAiring(), settings.tmdbKey, force)
saveAiring(next)
setCache(next)
// Met à jour le nombre total d'épisodes des séries en cours si de nouveaux sont sortis
const patches = trackable(items)
.filter((i) => i.status !== 'termine' && next[i.id] && next[i.id].aired > (i.episodesTotal ?? 0))
.map((i) => ({ id: i.id, patch: { episodesTotal: next[i.id].aired } }))
if (patches.length) await patchMany(patches)
} finally {
setChecking(false)
}
},
[items, settings.tmdbKey, patchMany],
)
// Vérification automatique au plus toutes les 12 h, au lancement
useEffect(() => {
if (loading || started.current || !navigator.onLine) return
started.current = true
const c = loadAiring()
if (trackable(items).some((i) => needsCheck(i, c))) void check()
}, [loading, items, check])
const list = useMemo(() => novelties(items, cache), [items, cache])
const tracked = trackable(items).length
const hasAniList = trackable(items).some((i) => i.externalId!.startsWith('anilist:'))
if (!tracked) return null
const resume = (item: MediaItem, aired: number) =>
update(item.id, { status: 'en_cours', episodesTotal: aired, startDate: item.startDate ?? todayISO(), endDate: undefined })
return (
<>
<SectionTitle
action={
<button onClick={() => check(true)} disabled={checking} className="flex items-center gap-1.5 text-xs font-medium text-ink-3">
{checking ? <Loader2 size={13} className="animate-spin" /> : <RefreshCw size={13} />}
{checking ? t('settings.checking') : t('newEp.check')}
</button>
}
>
{t('newEp.title')}
</SectionTitle>
{list.length === 0 ? (
<p className="text-sm text-ink-3">
{checking
? t('newEp.checking')
: !settings.tmdbKey && !hasAniList
? t('newEp.needKey')
: t('newEp.nothing', { count: tracked })}
{!checking && !settings.tmdbKey && hasAniList && ` ${t('newEp.needKeyAlso')}`}
</p>
) : (
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{list.map(({ item, info, unwatched, kind }) => (
<div key={item.id} className="card flex w-64 shrink-0 gap-3 p-2.5">
<button onClick={() => onOpen(item)} className="w-14 shrink-0">
<Poster src={item.poster} title={item.title} />
</button>
<div className="flex min-w-0 flex-1 flex-col">
<span className="eyebrow text-accent">
{kind === 'new_season' ? t('newEp.newSeason') : kind === 'new_episodes' ? t('newEp.catchUp') : t('newEp.soon')}
</span>
<button onClick={() => onOpen(item)} className="mt-1 truncate text-left text-sm font-semibold">
{item.title}
</button>
<span className="mt-0.5 text-xs text-ink-2">
{kind === 'upcoming'
? t('newEp.epWhen', { ep: info.next!.episode, when: dayLabel(info.next!.date) })
: t('newEp.available', { count: unwatched })}
</span>
{kind !== 'upcoming' && info.next && (
<span className="text-[11px] text-ink-3">
{t('newEp.next', { ep: info.next.episode, when: dayLabel(info.next.date) })}
</span>
)}
{kind === 'new_season' && (
<button onClick={() => resume(item, info.aired)} className="mt-auto self-start pt-1.5 text-xs font-semibold text-accent">
{t('newEp.resume')} →
</button>
)}
</div>
</div>
))}
</div>
)}
</>
)
}
+25
View File
@@ -0,0 +1,25 @@
import { useState } from 'react'
import { cx } from '../lib/utils'
/** Affiche du média, ou une vignette sobre (aplat + initiale en serif) si aucune image. */
export default function Poster({ src, title, className }: { src?: string; title: string; className?: string }) {
const [broken, setBroken] = useState(false)
if (src && !broken) {
return (
<img
src={src}
alt=""
loading="lazy"
onError={() => setBroken(true)}
className={cx('aspect-[2/3] w-full rounded-xl border border-line bg-surface-2 object-cover', className)}
/>
)
}
const initial = title.trim().charAt(0).toUpperCase() || '?'
return (
<div className={cx('relative grid aspect-[2/3] w-full place-items-center overflow-hidden rounded-xl border border-line bg-surface-2', className)}>
<span className="text-3xl font-bold text-ink-3">{initial}</span>
<span className="absolute bottom-0 left-0 h-[3px] w-1/3 bg-accent-fill" />
</div>
)
}
+99
View File
@@ -0,0 +1,99 @@
import { t } from '../i18n'
import { Star, X } from 'lucide-react'
import type { MouseEvent } from 'react'
import { cx, formatRating } from '../lib/utils'
import type { RatingScale } from '../types'
/** Petite note compacte (étoile + valeur) pour les cartes. */
export function RatingBadge({ value, scale }: { value?: number; scale: RatingScale }) {
if (value == null || value === 0) return null
return (
<span className="inline-flex items-center gap-1 text-xs font-semibold text-ink">
<Star size={12} className="fill-accent text-accent" />
{formatRating(value, scale)}
<span className="font-normal text-ink-3">/{scale}</span>
</span>
)
}
interface InputProps {
/** Valeur interne sur 10 */
value?: number
onChange: (value: number | undefined) => void
scale: RatingScale
size?: 'lg' | 'sm'
label?: string
}
/**
* Saisie de note.
* - Échelle 5 : étoiles avec demi-étoiles (touche la moitié gauche d'une étoile pour ½).
* - Échelle 10 : curseur au pas de 0,5.
* La valeur est toujours stockée sur 10.
*/
export function RatingInput({ value, onChange, scale, size = 'lg', label }: InputProps) {
const px = size === 'lg' ? 34 : 24
if (scale === '10') {
return (
<div className="flex items-center gap-3">
<input
type="range"
min={0}
max={10}
step={0.5}
value={value ?? 0}
aria-label={label ?? t('rating.outOf10')}
onChange={(e) => {
const v = Number(e.target.value)
onChange(v === 0 ? undefined : v)
}}
className="h-2 flex-1 accent-accent-fill"
/>
<span className={cx('w-14 text-right font-semibold tabular-nums', size === 'lg' ? 'text-xl' : 'text-sm')}>
{value ? formatRating(value, '10') : '—'}
<span className="text-xs font-normal text-ink-3">/10</span>
</span>
</div>
)
}
const stars = (value ?? 0) / 2
const pick = (e: MouseEvent<HTMLButtonElement>, index: number) => {
const rect = e.currentTarget.getBoundingClientRect()
const half = e.clientX - rect.left < rect.width / 2
const next = (index + (half ? 0.5 : 1)) * 2
onChange(next === value ? undefined : next) // retoucher la même valeur efface la note
}
return (
<div className="flex items-center gap-1" role="group" aria-label={label ?? 'Note sur 5'}>
{Array.from({ length: 5 }, (_, i) => {
const fill = Math.max(0, Math.min(1, stars - i))
return (
<button
key={i}
type="button"
onClick={(e) => pick(e, i)}
className="relative transition active:scale-90"
style={{ width: px, height: px }}
aria-label={t('rating.stars', { count: i + 1 })}
>
<Star size={px} strokeWidth={1.5} className="absolute inset-0 text-ink-3" />
<span className="absolute inset-0 overflow-hidden" style={{ width: `${fill * 100}%` }}>
<Star size={px} strokeWidth={1.5} className="fill-accent text-accent" />
</span>
</button>
)
})}
<span className={cx('ml-2 tabular-nums text-ink-2', size === 'lg' ? 'text-base' : 'text-xs')}>
{value ? formatRating(value, '5') : ''}
</span>
{value != null && size === 'lg' && (
<button type="button" onClick={() => onChange(undefined)} className="ml-auto p-1 text-ink-3" aria-label={t('rating.clear')}>
<X size={18} />
</button>
)}
</div>
)
}
+153
View File
@@ -0,0 +1,153 @@
import { t } from '../i18n'
import { Check, Loader2, Plus } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { aniListRecommendations, getTmdbDetails, searchAniList, tmdbRecommendations, type SearchResult } from '../lib/catalogApi'
import { remotePosterToLocal } from '../lib/image'
import { normalizeText } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput, MediaItem } from '../types'
import Poster from './Poster'
import { LinkArrow, SectionTitle } from './ui'
// Cache en mémoire le temps de la session (évite de refaire les requêtes)
const cache = new Map<string, SearchResult[]>()
const isLoved = (i: MediaItem) =>
(i.status === 'termine' || i.status === 'en_cours') && !!i.externalId && (!!i.top || i.favorite || (i.rating ?? 0) >= 8)
async function recommendationsFor(seed: MediaItem, tmdbKey?: string): Promise<SearchResult[]> {
const ext = seed.externalId!
if (cache.has(seed.id)) return cache.get(seed.id)!
let recs: SearchResult[] = []
if (ext.startsWith('anilist:')) recs = await aniListRecommendations(ext)
else if (tmdbKey) recs = await tmdbRecommendations(ext, tmdbKey)
else if (seed.type === 'anime') {
// Sans clé TMDB : on retrouve l'anime sur AniList par son titre
const found = (await searchAniList(seed.originalTitle || seed.title))[0]
if (found) recs = await aniListRecommendations(found.externalId)
}
cache.set(seed.id, recs)
return recs
}
/** « Si tu as aimé X » : suggestions à partir de mes titres préférés, ajoutables en un clic. */
export default function Recommendations() {
const { items, settings, add } = useMedia()
const hasKey = !!settings.tmdbKey?.trim()
// Titres « graines » : mes préférés, dans un ordre aléatoire fixé pour la session
const seeds = useMemo(() => {
const loved = items.filter((i) => isLoved(i) && (hasKey || i.externalId!.startsWith('anilist:') || i.type === 'anime'))
return loved.map((i) => ({ i, r: Math.random() })).sort((a, b) => a.r - b.r).map((x) => x.i)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items.length, hasKey])
const [index, setIndex] = useState(0)
const [recs, setRecs] = useState<SearchResult[]>()
const [error, setError] = useState<string>()
const [busy, setBusy] = useState<string>()
const [added, setAdded] = useState<Set<string>>(new Set())
const seed = seeds.length ? seeds[index % seeds.length] : undefined
// Déjà dans ma bibliothèque : même identifiant, ou même titre (les fiches importées viennent parfois d'une autre base)
const owned = useMemo(() => new Set(items.map((i) => i.externalId).filter(Boolean)), [items])
const ownedTitles = useMemo(
() => new Set(items.flatMap((i) => [i.title, i.originalTitle]).filter((s): s is string => !!s).map(normalizeText)),
[items],
)
useEffect(() => {
if (!seed || !navigator.onLine) return
let alive = true
setRecs(undefined)
setError(undefined)
recommendationsFor(seed, settings.tmdbKey)
.then((r) => alive && setRecs(r))
.catch(() => alive && setError(t('reco.error')))
return () => {
alive = false
}
}, [seed, settings.tmdbKey])
if (!seed) {
if (!hasKey && items.some((i) => (i.rating ?? 0) >= 8))
return (
<>
<SectionTitle>{t('reco.title')}</SectionTitle>
<p className="text-sm text-ink-3">{t('reco.needKey')}</p>
</>
)
return null
}
const visible = (recs ?? [])
.filter(
(r) =>
added.has(r.externalId) ||
(!owned.has(r.externalId) && !ownedTitles.has(normalizeText(r.title)) && !(r.originalTitle && ownedTitles.has(normalizeText(r.originalTitle)))),
)
.slice(0, 10)
const addToWatchlist = async (r: SearchResult) => {
setBusy(r.externalId)
try {
const data = r.source === 'tmdb' ? await getTmdbDetails(r, settings.tmdbKey!) : { ...r.prefill }
const poster = r.posterUrl ? (r.source === 'tmdb' ? await remotePosterToLocal(r.posterUrl) : r.posterUrl) : undefined
const input: MediaInput = {
title: r.title,
type: r.typeGuess,
status: 'a_voir',
criteria: {},
episodesWatched: 0,
genres: [],
...data,
poster,
}
await add(input)
setAdded((s) => new Set(s).add(r.externalId))
} finally {
setBusy(undefined)
}
}
return (
<>
<SectionTitle action={seeds.length > 1 ? <LinkArrow onClick={() => setIndex((i) => i + 1)}>{t('reco.other')}</LinkArrow> : undefined}>
{t('reco.ifYouLiked')} <span className="normal-case tracking-normal text-accent">{seed.title}</span>
</SectionTitle>
{error ? (
<p className="text-sm text-ink-3">{error}</p>
) : !recs ? (
<p className="flex items-center gap-2 text-sm text-ink-3">
<Loader2 size={14} className="animate-spin" /> {t('reco.loading')}
</p>
) : visible.length === 0 ? (
<p className="text-sm text-ink-3">{t('reco.none')}</p>
) : (
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{visible.map((r) => {
const done = added.has(r.externalId)
return (
<div key={r.externalId} className="w-28 shrink-0">
<div className="relative">
<Poster src={r.posterUrl ?? r.thumb} title={r.title} />
<button
onClick={() => addToWatchlist(r)}
disabled={done || !!busy}
className="absolute bottom-2 right-2 flex h-8 items-center gap-1 rounded-full bg-accent-fill px-2.5 text-xs font-semibold text-on-accent transition active:scale-90 disabled:opacity-90"
aria-label={done ? t('reco.added', { title: r.title }) : t('reco.addLabel', { title: r.title })}
>
{busy === r.externalId ? <Loader2 size={13} className="animate-spin" /> : done ? <Check size={13} strokeWidth={3} /> : <Plus size={13} strokeWidth={3} />}
{done ? t('reco.addedShort') : t('status.a_voir')}
</button>
</div>
<p className="mt-2 line-clamp-2 text-xs font-medium leading-snug text-ink-2">{r.title}</p>
<p className="text-[11px] text-ink-3">{[r.kindLabel, r.year].filter(Boolean).join(' · ')}</p>
</div>
)
})}
</div>
)}
</>
)
}
+391
View File
@@ -0,0 +1,391 @@
import { genreLabel } from '../lib/genres'
import { locale, t } from '../i18n'
import { Check, Dices, RotateCcw, X } from 'lucide-react'
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type TransitionEvent } from 'react'
import { MEDIA_TYPES, TYPE_BY_VALUE } from '../lib/constants'
import {
buildPool,
loadFilters,
pickRandom,
saveFilters,
sessionMinutes,
SOURCES,
sourcePool,
TIME_OPTIONS,
type RouletteFilters,
} from '../lib/roulette'
import { cx, formatDuration, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
import { RatingBadge } from './Rating'
const CARD = 112 // largeur d'une affiche dans le rouleau (w-28)
const GAP = 12
const STEP = CARD + GAP
const TARGET = 30 // position du gagnant dans le rouleau
const SPIN_MS = 3800
interface Props {
onClose: () => void
onOpen: (item: MediaItem) => void
}
const shuffle = <T,>(arr: T[]) => {
const a = [...arr]
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[a[i], a[j]] = [a[j], a[i]]
}
return a
}
export default function Roulette({ onClose, onOpen }: Props) {
const { items, settings, update, lists } = useMedia()
const [filters, setFilters] = useState<RouletteFilters>(loadFilters)
const pool = useMemo(() => buildPool(items, filters), [items, filters])
const base = useMemo(() => sourcePool(items, filters.sources, filters.listIds), [items, filters.sources, filters.listIds])
const genres = useMemo(() => [...new Set(base.flatMap((i) => i.genres))].sort((a, b) => a.localeCompare(b, locale())), [base])
const platforms = useMemo(() => [...new Set(base.map((i) => i.platform).filter(Boolean) as string[])].sort(), [base])
const [reel, setReel] = useState<MediaItem[]>([])
const [offset, setOffset] = useState(0)
const [animate, setAnimate] = useState(false)
const [spinning, setSpinning] = useState(false)
const [result, setResult] = useState<MediaItem>()
const [started, setStarted] = useState(false)
const rolled = useRef(new Set<string>())
const viewport = useRef<HTMLDivElement>(null)
const pending = useRef<MediaItem | undefined>(undefined)
const spinningRef = useRef(false)
const resultRef = useRef<MediaItem | undefined>(undefined)
resultRef.current = result
const xFor = (index: number, jitter = 0) => {
const w = viewport.current?.clientWidth ?? 360
return w / 2 - (index * STEP + CARD / 2) + jitter
}
// Bloque le défilement derrière + mémorise les filtres
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
useEffect(() => saveFilters(filters), [filters])
// Changer les filtres efface le tirage en cours
useEffect(() => {
setResult(undefined)
setStarted(false)
}, [filters])
// Rouleau « au repos » : les affiches possibles, centrées (sans toucher à un tirage affiché)
useLayoutEffect(() => {
if (spinning || resultRef.current) return
if (!pool.length) {
setReel([])
return
}
let idle = shuffle(pool)
while (idle.length < 9) idle = idle.concat(shuffle(pool))
setAnimate(false)
setReel(idle)
setOffset(xFor(4))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pool, result === undefined])
const setF = (patch: Partial<RouletteFilters>) => setFilters((f) => ({ ...f, ...patch }))
const toggle = <T,>(list: T[], v: T) => (list.includes(v) ? list.filter((x) => x !== v) : [...list, v])
const spin = () => {
const winner = pickRandom(pool, rolled.current)
if (!winner || spinning) return
rolled.current.add(winner.id)
pending.current = winner
setResult(undefined)
setStarted(false)
const strip = Array.from({ length: TARGET + 5 }, () => pool[Math.floor(Math.random() * pool.length)])
strip[TARGET] = winner
setReel(strip)
// L'animation est le cœur de la roulette : on la joue toujours,
// même si Windows / le téléphone a les « effets d'animation » désactivés.
setSpinning(true)
spinningRef.current = true
setAnimate(false)
setOffset(xFor(2))
// On place le rouleau au départ, puis on lance l'animation juste après
window.setTimeout(() => {
setAnimate(true)
setOffset(xFor(TARGET, (Math.random() - 0.5) * (CARD - 30)))
}, 40)
// Filet de sécurité si l'événement de fin d'animation n'arrive pas (onglet en arrière-plan…)
window.setTimeout(finishSpin, SPIN_MS + 400)
}
const finishSpin = () => {
if (!spinningRef.current) return
spinningRef.current = false
setSpinning(false)
setResult(pending.current)
navigator.vibrate?.(35)
}
const onSpinEnd = (e: TransitionEvent<HTMLDivElement>) => {
if (e.target !== e.currentTarget || e.propertyName !== 'transform') return
finishSpin()
}
const watchIt = async () => {
if (!result) return
if (result.status === 'a_voir' || result.status === 'pause') {
await update(result.id, { status: 'en_cours', startDate: result.startDate ?? todayISO() })
}
setStarted(true)
}
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')}>
<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="flex-1 text-center text-base font-semibold">
{t('roulette.heading')}<span className="text-accent">{t('roulette.headingAccent')}</span>
</h2>
<span className="size-10" />
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="safe-bottom mx-auto max-w-2xl pb-16">
{/* Rouleau d'affiches */}
<div ref={viewport} className="relative mt-6 h-[184px] overflow-hidden">
{reel.length > 0 ? (
<div
className="flex gap-3"
style={{
transform: `translateX(${offset}px)`,
transition: animate ? `transform ${SPIN_MS}ms cubic-bezier(0.12, 0.72, 0.1, 1)` : 'none',
}}
onTransitionEnd={onSpinEnd}
>
{reel.map((item, i) => (
<div
key={i}
className={cx(
'w-28 shrink-0 transition-opacity duration-300',
result && i !== winnerIndex && 'opacity-30',
)}
>
<div className={cx('rounded-xl', result && i === winnerIndex && 'ring-2 ring-accent ring-offset-2 ring-offset-bg')}>
<Poster src={item.poster} title={item.title} />
</div>
</div>
))}
</div>
) : (
<div className="flex h-full items-center justify-center gap-3 opacity-40">
{[0, 1, 2].map((k) => (
<div key={k} className="grid aspect-[2/3] w-28 place-items-center rounded-xl border border-dashed border-line-strong text-3xl font-bold text-ink-3">
?
</div>
))}
</div>
)}
{/* Repère central */}
<div className="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-accent/70" />
<div className="pointer-events-none absolute left-1/2 top-0 size-0 -translate-x-1/2 border-x-[7px] border-t-[9px] border-x-transparent border-t-accent" />
<div className="pointer-events-none absolute bottom-0 left-1/2 size-0 -translate-x-1/2 border-x-[7px] border-b-[9px] border-x-transparent border-b-accent" />
</div>
<div className="space-y-8 px-4">
{/* Bouton / résultat */}
{result && !spinning ? (
<div className="sheet-in card mt-6 p-4">
<span className="eyebrow text-accent">{t('roulette.tonight')}</span>
<h3 className="mt-2 text-xl leading-tight">{result.title}</h3>
{result.originalTitle && <p className="text-sm text-ink-3">{result.originalTitle}</p>}
<div className="mt-2.5 flex flex-wrap items-center gap-2 text-xs text-ink-3">
<TypeBadge item={result} />
{result.year && <span>{result.year}</span>}
<span>
{TYPE_BY_VALUE[result.type].episodic
? `${result.episodesTotal ? `${t('roulette.nEps', { n: result.episodesTotal })} · ` : ''}${t('roulette.perEp', { duration: formatDuration(sessionMinutes(result)) })}`
: formatDuration(sessionMinutes(result))}
</span>
{result.platform && <span>· {result.platform}</span>}
<RatingBadge value={result.rating} scale={settings.ratingScale} />
</div>
{result.status === 'pause' && (
<p className="mt-2 text-xs text-ink-2">
{result.episodesTotal
? t('roulette.stoppedAtOf', { ep: result.episodesWatched, total: result.episodesTotal })
: t('roulette.stoppedAt', { ep: result.episodesWatched })}
</p>
)}
{result.overview && <p className="mt-3 line-clamp-4 text-sm leading-relaxed text-ink-2">{result.overview}</p>}
{result.genres.length > 0 && <p className="mt-2 text-xs text-ink-3">{result.genres.slice(0, 4).map(genreLabel).join(' · ')}</p>}
{started ? (
<div className="mt-4 flex items-center justify-between gap-2 rounded-xl bg-surface-2 p-3 text-sm">
<span className="flex items-center gap-2">
<Check size={16} className="text-accent" /> {t('roulette.enjoy')}
</span>
<button onClick={onClose} className="font-medium text-ink">
{t('common.close')} <span className="text-accent">→</span>
</button>
</div>
) : (
<div className="mt-4 grid grid-cols-2 gap-2">
<button onClick={watchIt} className="btn btn-primary">
{t('roulette.watchIt')}
</button>
<button onClick={spin} className="btn btn-ghost">
<RotateCcw size={16} /> {t('roulette.again')}
</button>
</div>
)}
<button onClick={() => onOpen(result)} className="mt-3 w-full text-center text-xs font-medium text-ink-3">
{t('roulette.seeItem')}
</button>
</div>
) : (
<div className="mt-6 text-center">
<button onClick={spin} disabled={!pool.length || spinning} className="btn btn-primary px-8 py-3.5 text-base">
<Dices size={20} className={spinning ? 'animate-spin' : ''} />
{spinning ? t('roulette.spinning') : t('roulette.spin')}
</button>
<p className="mt-2.5 text-xs text-ink-3">
{pool.length
? t('roulette.poolSize', { count: pool.length })
: t('roulette.empty')}
</p>
</div>
)}
{/* Filtres */}
<section className="space-y-5 border-t border-line pt-6">
<h3 className="eyebrow text-ink-2">{t('roulette.inside')}</h3>
<div>
<span className="label">{t('roulette.pickFrom')}</span>
<div className="flex flex-wrap gap-2">
{SOURCES.map((s) => {
const on = filters.sources.includes(s.value)
const count = sourcePool(items, [s.value]).length
return (
<button
key={s.value}
onClick={() => {
const next = toggle(filters.sources, s.value)
if (next.length || filters.listIds.length) setF({ sources: next, genre: '', platform: '' })
}}
disabled={spinning}
className={cx('chip', on && 'chip-on')}
aria-pressed={on}
>
{s.label}
<span className={cx('text-xs', on ? 'opacity-60' : 'text-ink-3')}>{count}</span>
</button>
)
})}
{lists.map((l) => {
const on = filters.listIds.includes(l.id)
const count = items.filter((i) => i.listIds?.includes(l.id)).length
return (
<button
key={l.id}
onClick={() => {
const next = toggle(filters.listIds, l.id)
if (next.length || filters.sources.length) setF({ listIds: next, genre: '', platform: '' })
}}
disabled={spinning}
className={cx('chip', on && 'chip-on')}
aria-pressed={on}
>
{l.name}
<span className={cx('text-xs', on ? 'opacity-60' : 'text-ink-3')}>{count}</span>
</button>
)
})}
</div>
<p className="mt-1.5 text-[11px] text-ink-3">{t('roulette.rewatchHint')}</p>
</div>
<div>
<span className="label">{t('form.type')}</span>
<div className="flex flex-wrap gap-2">
<button onClick={() => setF({ types: [] })} disabled={spinning} className={cx('chip', !filters.types.length && 'chip-on')}>
{t('catalog.all')}
</button>
{MEDIA_TYPES.map((mt) => (
<button
key={mt.value}
onClick={() => setF({ types: toggle(filters.types, mt.value) })}
disabled={spinning}
className={cx('chip', filters.types.includes(mt.value) && 'chip-on')}
>
{mt.label}
</button>
))}
</div>
</div>
<div>
<span className="label">{t('roulette.time')}</span>
<div className="grid grid-cols-4 gap-1 rounded-full border border-line p-1">
{TIME_OPTIONS.map((o) => (
<button
key={o.value}
onClick={() => setF({ time: o.value })}
disabled={spinning}
className={cx('rounded-full py-2 text-xs font-medium transition-colors', filters.time === o.value ? 'bg-ink text-bg' : 'text-ink-3')}
>
{o.label}
</button>
))}
</div>
</div>
{(genres.length > 0 || platforms.length > 0) && (
<div className="grid grid-cols-2 gap-3">
<label className="block">
<span className="label">{t('catalog.genre')}</span>
<select className="field" value={filters.genre} onChange={(e) => setF({ genre: e.target.value })} disabled={spinning}>
<option value="">{t('catalog.all')}</option>
{genres.map((g) => (
<option key={g} value={g}>
{genreLabel(g)}
</option>
))}
</select>
</label>
<label className="block">
<span className="label">{t('form.platform')}</span>
<select className="field" value={filters.platform} onChange={(e) => setF({ platform: e.target.value })} disabled={spinning}>
<option value="">{t('catalog.allRatings')}</option>
{platforms.map((p) => (
<option key={p} value={p}>
{p}
</option>
))}
</select>
</label>
</div>
)}
</section>
</div>
</div>
</div>
</div>
)
}
+66
View File
@@ -0,0 +1,66 @@
import { t } from '../i18n'
import { Download, Share2, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { shareImage } from '../lib/shareCard'
interface Props {
blob: Blob
filename: string
title: string
onClose: () => void
}
/** Aperçu de l'image générée avant de la partager ou de l'enregistrer. */
export default function SharePreview({ blob, filename, title, onClose }: Props) {
const [url, setUrl] = useState<string>()
const [busy, setBusy] = useState(false)
const canShare = useMemo(() => {
try {
return !!navigator.canShare?.({ files: [new File([blob], filename, { type: 'image/png' })] })
} catch {
return false
}
}, [blob, filename])
// L'adresse temporaire de l'image est créée puis libérée avec l'aperçu
useEffect(() => {
const u = URL.createObjectURL(blob)
setUrl(u)
return () => URL.revokeObjectURL(u)
}, [blob])
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const go = async () => {
setBusy(true)
try {
await shareImage(blob, filename, title)
} finally {
setBusy(false)
}
}
return (
<div className="sheet-in fixed inset-0 z-[60] flex flex-col bg-bg/95 backdrop-blur-sm" role="dialog" aria-modal="true" aria-label={t('share.previewLabel')}>
<div className="safe-top flex items-center justify-between 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>
<span className="text-sm font-semibold">{t('share.preview')}</span>
<span className="size-10" />
</div>
<div className="flex min-h-0 flex-1 items-center justify-center px-6">
{url && <img src={url} alt={t('share.posterAlt', { title })} className="max-h-full max-w-full rounded-2xl border border-line object-contain" />}
</div>
<div className="safe-bottom mx-auto grid w-full max-w-md grid-cols-1 gap-2 px-4 pb-4 pt-4">
<button onClick={go} disabled={busy} className="btn btn-primary py-3">
{canShare ? <Share2 size={18} /> : <Download size={18} />}
{canShare ? t('share.share') : t('share.saveImage')}
</button>
</div>
</div>
)
}
+74
View File
@@ -0,0 +1,74 @@
import { t } from '../i18n'
import { X } from 'lucide-react'
import { useMemo, useState } from 'react'
import { normalizeText } from '../lib/utils'
interface Props {
value: string[]
onChange: (tags: string[]) => void
suggestions: string[]
placeholder?: string
/** Texte affiché pour une valeur enregistrée (ex. genre traduit) */
display?: (value: string) => string
/** Valeur enregistrée à partir du texte saisi (ex. nom de référence d'un genre) */
normalize?: (input: string) => string
}
/** Saisie de tags libres avec suggestions tapables. */
export default function TagInput({ value, onChange, suggestions, placeholder, display = (v) => v, normalize = (v) => v }: Props) {
const [text, setText] = useState('')
const add = (raw: string) => {
const typed = raw.trim().replace(/,$/, '').trim()
if (!typed) return
const tag = normalize(typed)
if (!value.some((v) => normalizeText(v) === normalizeText(tag))) onChange([...value, tag])
setText('')
}
const filtered = useMemo(() => {
const q = normalizeText(text)
const taken = new Set(value.map((v) => normalizeText(display(v))))
return suggestions.filter((s) => !taken.has(normalizeText(s)) && (!q || normalizeText(s).includes(q))).slice(0, 12)
}, [text, value, suggestions])
return (
<div>
<div className="field flex flex-wrap items-center gap-1.5 py-2!">
{value.map((tag) => (
<span key={tag} className="inline-flex items-center gap-1 rounded-full border border-line-strong py-1 pl-3 pr-1.5 text-sm text-ink">
{display(tag)}
<button type="button" onClick={() => onChange(value.filter((v) => v !== tag))} aria-label={t('common.removeX', { name: display(tag) })} className="text-ink-3">
<X size={14} />
</button>
</span>
))}
<input
value={text}
onChange={(e) => (e.target.value.endsWith(',') ? add(e.target.value) : setText(e.target.value))}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
add(text)
} else if (e.key === 'Backspace' && !text && value.length) {
onChange(value.slice(0, -1))
}
}}
onBlur={() => add(text)}
placeholder={value.length ? '' : placeholder}
className="min-w-24 flex-1 bg-transparent py-0.5 outline-none placeholder:text-ink-3"
enterKeyHint="done"
/>
</div>
{filtered.length > 0 && (
<div className="no-scrollbar -mx-1 mt-2 flex gap-1.5 overflow-x-auto px-1 pb-1">
{filtered.map((s) => (
<button key={s} type="button" onMouseDown={(e) => e.preventDefault()} onClick={() => add(s)} className="chip py-1! text-xs">
+ {s}
</button>
))}
</div>
)}
</div>
)
}
+162
View File
@@ -0,0 +1,162 @@
import { genreLabel } from '../lib/genres'
import { t } from '../i18n'
import { Loader2, Plus, Share2 } from 'lucide-react'
import { useState, type CSSProperties } from 'react'
import { TOP_CATEGORIES } from '../lib/constants'
import { renderTopCard, slug } from '../lib/shareCard'
import { cx, formatRating } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem, TopCategory } from '../types'
import Poster from './Poster'
import { RatingBadge } from './Rating'
import TopFiveEditor from './TopFiveEditor'
import SharePreview from './SharePreview'
import { LinkArrow, SectionTitle } from './ui'
/** Chiffre géant en contour (rouge pour le n°1, gris pour les autres). */
function RankNumber({ rank, big }: { rank: number; big?: boolean }) {
const style: CSSProperties = {
WebkitTextStroke: big ? '2.5px var(--color-accent)' : '2px var(--color-ink-3)',
color: 'transparent',
fontSize: big ? '10rem' : '5.5rem',
lineHeight: 0.8,
letterSpacing: '-0.06em',
}
return (
<span aria-hidden className="pointer-events-none select-none font-black" style={style}>
{rank}
</span>
)
}
function EmptySlot({ rank, onClick, big }: { rank: number; onClick: () => void; big?: boolean }) {
return (
<button
onClick={onClick}
className={cx(
'grid aspect-[2/3] place-items-center rounded-xl border border-dashed border-line-strong text-ink-3 transition-colors active:bg-surface-2',
big ? 'w-32' : 'w-full',
)}
aria-label={t('top.pick', { rank })}
>
<Plus size={big ? 22 : 18} />
</button>
)
}
export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, settings } = useMedia()
const cats = TOP_CATEGORIES.filter((c) => settings.topCategories.includes(c.value))
const [selected, setSelected] = useState<TopCategory>()
const [editing, setEditing] = useState(false)
const [sharing, setSharing] = useState(false)
const [preview, setPreview] = useState<{ blob: Blob; filename: string; title: string }>()
if (!cats.length) return null
const current = cats.find((c) => c.value === selected) ?? cats[0]
const byRank = new Map(items.filter((i) => i.top?.category === current.value).map((i) => [i.top!.rank, i]))
const first = byRank.get(1)
const edit = () => setEditing(true)
const share = async () => {
setSharing(true)
try {
const blob = await renderTopCard(current.plural, [1, 2, 3, 4, 5].map((r) => byRank.get(r)))
setPreview({ blob, filename: `azuucine-top5-${slug(current.plural)}.png`, title: t('top.shareTitle', { category: current.plural }) })
} finally {
setSharing(false)
}
}
return (
<>
<SectionTitle
action={
<span className="flex items-center gap-4">
<button onClick={share} disabled={sharing} className="flex items-center gap-1 text-xs font-medium text-ink-3" aria-label={t('top.shareLabel')}>
{sharing ? <Loader2 size={13} className="animate-spin" /> : <Share2 size={13} />} {t('share.share')}
</button>
<LinkArrow onClick={edit}>{t('common.edit')}</LinkArrow>
</span>
}
>
{t('top.title')} <span className="text-accent">5</span>
</SectionTitle>
{/* Choix de la catégorie */}
{cats.length > 1 && (
<div className="no-scrollbar -mx-4 mb-5 flex gap-2 overflow-x-auto px-4">
{cats.map((c) => (
<button key={c.value} onClick={() => setSelected(c.value)} className={cx('chip py-1! text-[13px]', current.value === c.value && 'chip-on')}>
{c.plural}
</button>
))}
</div>
)}
{/* N°1 : grand chiffre rouge + affiche + infos */}
<div className="flex items-end">
<div className="relative flex shrink-0 items-end">
<span className="-mr-3 mb-1">
<RankNumber rank={1} big />
</span>
{first ? (
<button onClick={() => onOpen(first)} className="relative z-10 w-32">
<Poster src={first.poster} title={first.title} />
</button>
) : (
<EmptySlot rank={1} onClick={edit} big />
)}
</div>
<div className="min-w-0 flex-1 pb-1 pl-4">
<span className="eyebrow text-accent">{t('top.number', { rank: 1 })} · {current.plural}</span>
{first ? (
<>
<button onClick={() => onOpen(first)} className="mt-1.5 block text-left text-lg font-bold leading-snug">
{first.title}
</button>
<div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-ink-3">
{first.year && <span>{first.year}</span>}
<RatingBadge value={first.rating} scale={settings.ratingScale} />
</div>
{first.genres.length > 0 && <p className="mt-2 line-clamp-1 text-xs text-ink-3">{first.genres.slice(0, 3).map(genreLabel).join(' · ')}</p>}
</>
) : (
<p className="mt-1.5 text-sm text-ink-3">{t('top.pickFirst')}</p>
)}
</div>
</div>
{/* N°2 à 5 : chiffres en contour qui dépassent derrière les affiches */}
<div className="mt-14 grid grid-cols-4 gap-x-2">
{[2, 3, 4, 5].map((rank) => {
const item = byRank.get(rank)
return (
<div key={rank} className="min-w-0">
<div className="relative">
<span className="absolute -left-1 -top-9 z-0">
<RankNumber rank={rank} />
</span>
<div className="relative z-10 ml-4">
{item ? (
<button onClick={() => onOpen(item)} className="block w-full">
<Poster src={item.poster} title={item.title} />
</button>
) : (
<EmptySlot rank={rank} onClick={edit} />
)}
</div>
</div>
<p className="ml-4 mt-1.5 truncate text-[11px] font-medium text-ink-2" title={item?.title}>
{item ? item.title : '—'}
</p>
{item?.rating ? <p className="ml-4 text-[10px] text-ink-3">{formatRating(item.rating, settings.ratingScale)}/{settings.ratingScale}</p> : null}
</div>
)
})}
</div>
{preview && <SharePreview {...preview} onClose={() => setPreview(undefined)} />}
{editing && <TopFiveEditor category={current.value} onClose={() => setEditing(false)} />}
</>
)
}
+186
View File
@@ -0,0 +1,186 @@
import { locale, t } from '../i18n'
import { ChevronDown, ChevronUp, Search, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { TOP_CATEGORIES } from '../lib/constants'
import { cx, formatRating, normalizeText } from '../lib/utils'
import { useMedia } from '../store'
import type { TopCategory } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
interface Props {
category: TopCategory
onClose: () => void
}
/** Composer son Top 5 : 5 places, ajout depuis la bibliothèque, réordonnancement. */
export default function TopFiveEditor({ category: initialCategory, onClose }: Props) {
const { items, settings, setTopList } = useMedia()
const [category, setCategory] = useState(initialCategory)
const currentIds = (cat: TopCategory) =>
items
.filter((i) => i.top?.category === cat)
.sort((a, b) => a.top!.rank - b.top!.rank)
.map((i) => i.id)
const [ids, setIds] = useState<string[]>(() => currentIds(initialCategory))
const [query, setQuery] = useState('')
const [allTypes, setAllTypes] = useState(false)
const [saving, setSaving] = useState(false)
const catInfo = TOP_CATEGORIES.find((c) => c.value === category)!
const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items])
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
/** Changer de catégorie enregistre d'abord celle en cours. */
const switchCategory = async (cat: TopCategory) => {
if (cat === category) return
await setTopList(category, ids)
setCategory(cat)
setIds(currentIds(cat).filter((id) => !ids.includes(id)))
setQuery('')
}
const candidates = useMemo(() => {
const q = normalizeText(query)
return items
.filter((i) => !ids.includes(i.id))
.filter((i) => allTypes || q || i.type === category)
.filter((i) => !q || normalizeText(`${i.title} ${i.originalTitle ?? ''}`).includes(q))
.sort((a, b) => Number(b.type === category) - Number(a.type === category) || (b.rating ?? -1) - (a.rating ?? -1) || a.title.localeCompare(b.title, locale()))
.slice(0, 60)
}, [items, ids, query, allTypes, category])
const move = (index: number, delta: number) =>
setIds((prev) => {
const next = [...prev]
const target = index + delta
if (target < 0 || target >= next.length) return prev
;[next[index], next[target]] = [next[target], next[index]]
return next
})
const save = async () => {
setSaving(true)
await setTopList(category, ids)
setSaving(false)
onClose()
}
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')}>
<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="flex-1 text-center text-base font-semibold">
Top <span className="text-accent">5</span> · {catInfo.plural}
</h2>
<button onClick={save} disabled={saving} className="btn btn-light px-4 py-2 text-sm">
{t('common.save')}
</button>
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<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.map((c) => (
<button key={c.value} onClick={() => switchCategory(c.value)} className={cx('chip py-1! text-[13px]', category === c.value && 'chip-on')}>
{c.plural}
</button>
))}
</div>
{/* Les 5 places */}
<ol className="space-y-2">
{[0, 1, 2, 3, 4].map((index) => {
const item = ids[index] ? byId.get(ids[index]) : undefined
return (
<li key={index} className={cx('flex items-center gap-3 rounded-2xl border p-2.5', item ? 'border-line bg-surface' : 'border-dashed border-line-strong')}>
<span className={cx('w-8 text-center text-3xl font-black', index === 0 ? 'text-accent' : 'text-ink-3')}>{index + 1}</span>
{item ? (
<>
<div className="w-10 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{item.title}</p>
<p className="text-xs text-ink-3">
{[item.year, item.rating ? `${formatRating(item.rating, settings.ratingScale)}/${settings.ratingScale}` : null].filter(Boolean).join(' · ')}
</p>
</div>
<div className="flex shrink-0 items-center">
<button onClick={() => move(index, -1)} disabled={index === 0} className="grid size-9 place-items-center text-ink-2 disabled:opacity-20" aria-label={t('common.moveUp')}>
<ChevronUp size={18} />
</button>
<button onClick={() => move(index, 1)} disabled={index >= ids.length - 1} className="grid size-9 place-items-center text-ink-2 disabled:opacity-20" aria-label={t('common.moveDown')}>
<ChevronDown size={18} />
</button>
<button onClick={() => setIds((p) => p.filter((id) => id !== item.id))} className="grid size-9 place-items-center text-ink-3" aria-label={t('common.removeX', { name: item.title })}>
<X size={17} />
</button>
</div>
</>
) : (
<span className="py-3 text-sm text-ink-3">{t('top.freeSlot')}</span>
)}
</li>
)
})}
</ol>
{/* Ajout depuis la bibliothèque */}
<div>
<div className="mb-3 flex items-center justify-between">
<h3 className="eyebrow text-ink-2">{t('top.addFromLibrary')}</h3>
<button onClick={() => setAllTypes((v) => !v)} className={cx('chip py-0.5! text-xs', allTypes && 'chip-on')}>
{t('top.allTypes')}
</button>
</div>
<div className="relative mb-2">
<Search size={17} className="pointer-events-none absolute left-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('top.searchTitle')} className="field pl-10" />
</div>
{ids.length >= 5 && <p className="py-2 text-xs text-ink-3">{t('top.full')}</p>}
<ul className="divide-y divide-line">
{candidates.map((item) => (
<li key={item.id}>
<button
onClick={() => setIds((p) => (p.length < 5 ? [...p, item.id] : p))}
disabled={ids.length >= 5}
className="flex w-full items-center gap-3 py-2.5 text-left disabled:opacity-40"
>
<div className="w-9 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{item.title}</p>
<div className="mt-1 flex items-center gap-2 text-xs text-ink-3">
<TypeBadge item={item} />
{item.rating ? `${formatRating(item.rating, settings.ratingScale)}/${settings.ratingScale}` : ''}
{item.top && item.top.category !== category && (
<span className="text-accent">
{t('top.number', { rank: item.top.rank })} {TOP_CATEGORIES.find((c) => c.value === item.top!.category)?.plural}
</span>
)}
</div>
</div>
<span className="text-accent">+</span>
</button>
</li>
))}
{candidates.length === 0 && <li className="py-4 text-sm text-ink-3">{t('top.noCandidates')}</li>}
</ul>
</div>
</div>
</div>
</div>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { cx } from '../../lib/utils'
/** Photo de profil ronde, ou initiale sur fond neutre. */
export default function Avatar({ url, name, size = 40, className }: { url?: string; name: string; size?: number; className?: string }) {
const style = { width: size, height: size }
if (url) return <img src={url} alt="" style={style} className={cx('shrink-0 rounded-full border border-line bg-surface-2 object-cover', className)} />
return (
<span style={{ ...style, fontSize: size * 0.42 }} className={cx('grid shrink-0 place-items-center rounded-full border border-line bg-surface-2 font-bold text-ink-2', className)}>
{(name.trim().charAt(0) || '?').toUpperCase()}
</span>
)
}
+176
View File
@@ -0,0 +1,176 @@
import { Camera, ImagePlus, Loader2, Lock, Trash2 } from 'lucide-react'
import { useRef, useState } from 'react'
import { t } from '../../i18n'
import { deleteProfileImage, updateProfile, uploadProfileImage, USERNAME_RE, type ProfilePatch } from '../../lib/cloud/social'
import { cropImageToJpeg } from '../../lib/image'
import { cx } from '../../lib/utils'
import Avatar from './Avatar'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
/** Modifier mon profil : photo, bannière, nom, pseudo, bio, compte privé. */
export default function EditProfile({ onClose }: { onClose: () => void }) {
const { me, refresh } = useSocial()
const [displayName, setDisplayName] = useState(me?.displayName ?? '')
const [username, setUsername] = useState(me?.username ?? '')
const [bio, setBio] = useState(me?.bio ?? '')
const [isPrivate, setIsPrivate] = useState(me?.isPrivate ?? false)
const [avatar, setAvatar] = useState<{ blob?: Blob; preview?: string; removed?: boolean }>({ preview: me?.avatarUrl })
const [banner, setBanner] = useState<{ blob?: Blob; preview?: string; removed?: boolean }>({ preview: me?.bannerUrl })
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string>()
const avatarInput = useRef<HTMLInputElement>(null)
const bannerInput = useRef<HTMLInputElement>(null)
const cleanUsername = username.trim().toLowerCase().replace(/^@/, '')
const usernameOk = USERNAME_RE.test(cleanUsername)
const nameOk = displayName.trim().length >= 1 && displayName.trim().length <= 40
const pick = async (kind: 'avatar' | 'banner', file?: File) => {
if (!file) return
setError(undefined)
try {
const blob = kind === 'avatar' ? await cropImageToJpeg(file, 400, 400) : await cropImageToJpeg(file, 1500, 500, 0.84)
const preview = URL.createObjectURL(blob)
if (kind === 'avatar') setAvatar({ blob, preview })
else setBanner({ blob, preview })
} catch (e) {
setError((e as Error).message)
}
}
const save = async () => {
if (!me || !usernameOk || !nameOk) return
setSaving(true)
setError(undefined)
const uploaded: string[] = []
try {
const patch: ProfilePatch = {}
if (displayName.trim() !== me.displayName) patch.display_name = displayName.trim()
if (cleanUsername !== me.username) patch.username = cleanUsername
if (bio.trim() !== me.bio) patch.bio = bio.trim()
if (isPrivate !== me.isPrivate) patch.is_private = isPrivate
if (avatar.blob) {
patch.avatar_url = await uploadProfileImage('avatar', avatar.blob)
uploaded.push(patch.avatar_url)
} else if (avatar.removed) patch.avatar_url = null
if (banner.blob) {
patch.banner_url = await uploadProfileImage('banner', banner.blob)
uploaded.push(patch.banner_url)
} else if (banner.removed) patch.banner_url = null
if (Object.keys(patch).length) await updateProfile(patch)
// Les anciennes images ne servent plus
if ('avatar_url' in patch) await deleteProfileImage(me.avatarUrl)
if ('banner_url' in patch) await deleteProfileImage(me.bannerUrl)
await refresh()
onClose()
} catch (e) {
for (const url of uploaded) await deleteProfileImage(url)
setError((e as Error).message)
} finally {
setSaving(false)
}
}
if (!me) {
return (
<Sheet label={t('social.editProfile')} title={t('social.editProfile')} onClose={onClose}>
<p className="px-4 py-12 text-center text-sm text-ink-3">{t('social.loadError')}</p>
</Sheet>
)
}
return (
<Sheet
label={t('social.editProfile')}
title={t('social.editProfile')}
onClose={onClose}
right={
<button onClick={save} disabled={saving || !usernameOk || !nameOk} className="btn btn-light px-3 py-1.5 text-sm">
{saving ? <Loader2 size={15} className="animate-spin" /> : t('common.save')}
</button>
}
>
{/* Bannière */}
<button type="button" onClick={() => bannerInput.current?.click()} className="relative block aspect-[3/1] w-full overflow-hidden bg-surface-2" aria-label={t('social.changeBanner')}>
{banner.preview && !banner.removed && <img src={banner.preview} alt="" className="size-full object-cover" />}
<span className="absolute inset-0 grid place-items-center bg-black/25">
<span className="flex items-center gap-2 rounded-full bg-bg/85 px-3 py-1.5 text-xs font-semibold">
<ImagePlus size={14} /> {t('social.changeBanner')}
</span>
</span>
</button>
<input ref={bannerInput} type="file" accept="image/*" hidden onChange={(e) => pick('banner', e.target.files?.[0])} />
<div className="px-4">
<div className="-mt-11 flex items-end gap-3">
<button type="button" onClick={() => avatarInput.current?.click()} className="relative rounded-full" aria-label={t('social.changeAvatar')}>
<Avatar url={avatar.removed ? undefined : avatar.preview} name={displayName || me.username} size={88} className="border-4 border-bg" />
<span className="absolute bottom-1 right-1 grid size-7 place-items-center rounded-full bg-accent-fill text-on-accent">
<Camera size={14} />
</span>
</button>
<input ref={avatarInput} type="file" accept="image/*" hidden onChange={(e) => pick('avatar', e.target.files?.[0])} />
<div className="mb-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-3">
{avatar.preview && !avatar.removed && (
<button type="button" onClick={() => setAvatar({ removed: true })} className="flex items-center gap-1">
<Trash2 size={12} /> {t('social.removeAvatar')}
</button>
)}
{banner.preview && !banner.removed && (
<button type="button" onClick={() => setBanner({ removed: true })} className="flex items-center gap-1">
<Trash2 size={12} /> {t('social.removeBanner')}
</button>
)}
</div>
</div>
<div className="mt-6 space-y-4">
<label className="block">
<span className="label">{t('social.displayName')}</span>
<input className="field" value={displayName} onChange={(e) => setDisplayName(e.target.value)} maxLength={40} required />
</label>
<label className="block">
<span className="label">{t('social.username')}</span>
<div className="relative">
<span className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3">@</span>
<input
className={cx('field pl-8', username && !usernameOk && 'border-accent!')}
value={username}
onChange={(e) => setUsername(e.target.value.toLowerCase())}
maxLength={21}
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
/>
</div>
<span className={cx('mt-1.5 block text-xs', usernameOk ? 'text-ink-3' : 'text-accent')}>{t('social.usernameRule')}</span>
</label>
<label className="block">
<span className="label">{t('social.bio')}</span>
<textarea className="field min-h-24 resize-y" value={bio} onChange={(e) => setBio(e.target.value)} maxLength={300} placeholder={t('social.bioPh')} />
<span className="mt-1 block text-right text-[11px] text-ink-3">{bio.length}/300</span>
</label>
<button type="button" onClick={() => setIsPrivate((v) => !v)} className="flex w-full items-center gap-3 rounded-2xl border border-line px-4 py-3.5 text-left">
<Lock size={18} className="shrink-0 text-ink-2" />
<span className="flex-1">
<span className="block text-sm font-medium">{t('social.privateAccount')}</span>
<span className="mt-0.5 block text-xs text-ink-3">{t('social.privateHint')}</span>
</span>
<span className={cx('relative h-6 w-11 shrink-0 rounded-full transition-colors', isPrivate ? 'bg-accent-fill' : 'bg-surface-2 border border-line-strong')}>
<span className={cx('absolute top-0.5 size-5 rounded-full bg-ink transition-all', isPrivate ? 'left-[22px] bg-on-accent' : 'left-0.5')} />
</span>
</button>
{error && (
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm">
{error}
</p>
)}
<p className="text-xs leading-relaxed text-ink-3">{t('social.publicHint')}</p>
</div>
</div>
</Sheet>
)
}
+96
View File
@@ -0,0 +1,96 @@
import { Loader2 } from 'lucide-react'
import { useEffect, useState } from 'react'
import { t } from '../../i18n'
import { acceptFollower, getFollowList, removeFollower, type Profile, type ProfileCard } from '../../lib/cloud/social'
import { cx } from '../../lib/utils'
import PersonRow from './PersonRow'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
type Tab = 'followers' | 'following' | 'requests'
/** Abonnés / abonnements d'un profil ; pour le mien, aussi les demandes en attente. */
export default function FollowList({ profile, initial, onClose }: { profile: Profile; initial: 'followers' | 'following'; onClose: () => void }) {
const social = useSocial()
const showRequests = profile.isMe && social.requests.length > 0
const [tab, setTab] = useState<Tab>(showRequests && initial === 'followers' ? 'requests' : initial)
const [list, setList] = useState<ProfileCard[]>()
const [busy, setBusy] = useState<string>()
useEffect(() => {
if (tab === 'requests') return setList(social.requests)
let alive = true
setList(undefined)
getFollowList(profile.id, tab)
.then((l) => alive && setList(l))
.catch(() => alive && setList([]))
return () => {
alive = false
}
}, [tab, profile.id, social.requests])
const act = async (person: ProfileCard, action: 'accept' | 'remove') => {
setBusy(person.id)
try {
if (action === 'accept') await acceptFollower(person.id)
else await removeFollower(person.id)
setList((l) => l?.filter((p) => p.id !== person.id))
await social.refresh()
} finally {
setBusy(undefined)
}
}
const tabs: Tab[] = showRequests ? ['requests', 'followers', 'following'] : ['followers', 'following']
return (
<Sheet label={profile.displayName} title={profile.displayName} onClose={onClose}>
<div className="px-4 pt-4">
<div className={cx('grid gap-1 rounded-full border border-line p-1', tabs.length === 3 ? 'grid-cols-3' : 'grid-cols-2')}>
{tabs.map((v) => (
<button key={v} onClick={() => setTab(v)} className={cx('rounded-full py-2 text-xs font-semibold transition-colors', tab === v ? 'bg-ink text-bg' : 'text-ink-3')}>
{v === 'requests'
? t('social.requestsTab', { count: social.requests.length })
: v === 'followers'
? t('social.followers', { count: profile.followers })
: t('social.followingCount', { count: profile.following })}
</button>
))}
</div>
{list === undefined ? (
<p className="flex justify-center py-10">
<Loader2 size={16} className="animate-spin text-ink-3" />
</p>
) : list.length === 0 ? (
<p className="py-10 text-center text-sm text-ink-3">{tab === 'following' ? t('social.noFollowing') : t('social.noFollowers')}</p>
) : (
<div className="mt-3 divide-y divide-line">
{list.map((p) => (
<PersonRow
key={p.id}
person={p}
actions={
tab === 'requests' ? (
<span className="flex shrink-0 gap-1.5">
<button onClick={() => act(p, 'accept')} disabled={!!busy} className="h-8 rounded-full bg-accent-fill px-3 text-xs font-semibold text-on-accent">
{t('social.accept')}
</button>
<button onClick={() => act(p, 'remove')} disabled={!!busy} className="h-8 rounded-full border border-line-strong px-3 text-xs font-semibold text-ink-2">
{t('social.decline')}
</button>
</span>
) : profile.isMe && tab === 'followers' ? (
<button onClick={() => act(p, 'remove')} disabled={!!busy} className="h-8 shrink-0 rounded-full border border-line-strong px-3 text-xs font-semibold text-ink-2">
{t('social.removeFollower')}
</button>
) : undefined
}
/>
))}
</div>
)}
</div>
</Sheet>
)
}
+113
View File
@@ -0,0 +1,113 @@
import { Loader2, Star, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { t } from '../../i18n'
import { getFeed, type FeedEntry } from '../../lib/cloud/social'
import { timeAgo } from '../../lib/timeAgo'
import { formatRating } from '../../lib/utils'
import { useMedia } from '../../store'
import Poster from '../Poster'
import { LinkArrow, SectionTitle } from '../ui'
import Avatar from './Avatar'
import { useSocial } from './SocialProvider'
const VERB = { finished: 'feed.finished', started: 'feed.started', rewatched: 'feed.rewatched', added: 'feed.added' } as const
/** Accueil : ce que regardent mes abonnements. */
export default function FriendsFeed() {
const social = useSocial()
const { settings } = useMedia()
const [entries, setEntries] = useState<FeedEntry[]>()
const [more, setMore] = useState(false)
const [loadingMore, setLoadingMore] = useState(false)
const [shown, setShown] = useState(6)
const load = useCallback(async () => {
try {
const list = await getFeed()
setEntries(list)
setMore(list.length >= 30)
} catch {
setEntries([])
}
}, [])
useEffect(() => {
if (social.enabled && navigator.onLine) void load()
}, [social.enabled, load])
if (!social.enabled) return null
const loadMore = async () => {
if (!entries) return
if (shown < entries.length) return setShown((n) => n + 10)
setLoadingMore(true)
try {
const next = await getFeed(entries[entries.length - 1]?.createdAt)
setEntries([...entries, ...next])
setMore(next.length >= 30)
setShown((n) => n + 10)
} finally {
setLoadingMore(false)
}
}
return (
<>
<SectionTitle action={<LinkArrow onClick={social.openSearch}>{t('social.findFriends')}</LinkArrow>}>{t('feed.title')}</SectionTitle>
{entries === undefined ? (
<p className="flex items-center gap-2 text-sm text-ink-3">
<Loader2 size={14} className="animate-spin" /> {t('social.loading')}
</p>
) : entries.length === 0 ? (
<button onClick={social.openSearch} className="flex w-full items-center gap-3 rounded-2xl border border-dashed border-line-strong p-4 text-left">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-surface-2 text-accent">
<UserPlus size={18} />
</span>
<span className="text-sm text-ink-2">{t('feed.empty')}</span>
</button>
) : (
<>
<ul className="divide-y divide-line">
{entries.slice(0, shown).map((e) => (
<li key={`${e.id}-${e.createdAt}`} className="flex items-center gap-3 py-2.5">
<button onClick={() => social.openProfile(e.user.username)} aria-label={e.user.displayName}>
<Avatar url={e.user.avatarUrl} name={e.user.displayName} size={36} />
</button>
<button onClick={() => social.openItem(e.item, e.user)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
<span className="min-w-0 flex-1">
<span className="line-clamp-2 text-sm leading-snug text-ink-2">
<span className="font-semibold text-ink">{e.user.displayName}</span> {t(VERB[e.kind])}{' '}
<span className="font-semibold text-ink">{e.item.title}</span>
</span>
<span className="mt-0.5 flex items-center gap-2 text-[11px] text-ink-3">
{e.item.rating != null && e.kind !== 'added' && (
<span className="flex items-center gap-0.5 font-semibold text-ink-2">
<Star size={10} className="fill-accent text-accent" />
{formatRating(e.item.rating, settings.ratingScale)}
</span>
)}
{e.item.notes && e.item.notesPublic && <span>{t('feed.review')}</span>}
<span>{timeAgo(e.createdAt)}</span>
</span>
</span>
<span className="w-10 shrink-0">
<Poster src={e.item.poster} title={e.item.title} />
</span>
</button>
</li>
))}
</ul>
{(shown < entries.length || more) && (
<button onClick={loadMore} disabled={loadingMore} className="mt-2 w-full py-2 text-xs font-medium text-ink-3">
{loadingMore ? <Loader2 size={13} className="mx-auto animate-spin" /> : (
<>
{t('social.loadMore')} <span className="text-accent">→</span>
</>
)}
</button>
)}
</>
)}
</>
)
}
+122
View File
@@ -0,0 +1,122 @@
import { Check, Loader2, Plus, Star } from 'lucide-react'
import { useEffect, useState } from 'react'
import { t } from '../../i18n'
import { genreLabel } from '../../lib/genres'
import { cx, formatDate, formatRating, normalizeText } from '../../lib/utils'
import { useMedia } from '../../store'
import type { MediaInput, MediaItem } from '../../types'
import { StatusPill, TypeBadge } from '../Badges'
import Poster from '../Poster'
import Avatar from './Avatar'
export interface PeekOwner {
username: string
displayName: string
avatarUrl?: string
}
/** Aperçu d'un titre de quelqu'un d'autre : sa note, son avis public, et ajout à ma liste « À voir ». */
export default function ItemPeek({ item, owner, onClose }: { item: MediaItem; owner?: PeekOwner; onClose: () => void }) {
const { items, add, settings } = useMedia()
const [busy, setBusy] = useState(false)
const [added, setAdded] = useState(false)
const owned = items.some(
(i) => (item.externalId && i.externalId === item.externalId) || normalizeText(i.title) === normalizeText(item.title),
)
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const addToWatchlist = async () => {
setBusy(true)
try {
const input: MediaInput = {
title: item.title,
originalTitle: item.originalTitle,
type: item.type,
subtype: item.subtype,
year: item.year,
status: 'a_voir',
criteria: {},
episodesWatched: 0,
episodesTotal: item.episodesTotal,
episodeDuration: item.episodeDuration,
duration: item.duration,
genres: item.genres,
platform: item.platform,
poster: item.poster,
overview: item.overview,
externalId: item.externalId,
countries: item.countries,
publicRating: item.publicRating,
}
await add(input)
setAdded(true)
} finally {
setBusy(false)
}
}
return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 sm:items-center sm:p-4" onClick={onClose}>
<div
role="dialog"
aria-modal="true"
aria-label={item.title}
className="sheet-in safe-bottom max-h-[88dvh] w-full max-w-md overflow-y-auto rounded-t-3xl border border-line-strong bg-surface p-5 sm:rounded-3xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex gap-4">
<div className="w-24 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<h2 className="text-lg font-bold leading-snug">{item.title}</h2>
{item.originalTitle && <p className="truncate text-sm text-ink-3">{item.originalTitle}</p>}
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-ink-3">
<TypeBadge item={item} />
{item.year && <span>{item.year}</span>}
</div>
{item.genres.length > 0 && <p className="mt-2 line-clamp-1 text-xs text-ink-3">{item.genres.slice(0, 3).map(genreLabel).join(' · ')}</p>}
</div>
</div>
{owner && (
<div className="mt-5 rounded-2xl border border-line p-3.5">
<div className="flex items-center gap-2.5">
<Avatar url={owner.avatarUrl} name={owner.displayName} size={28} />
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{owner.displayName}</span>
{item.rating != null && (
<span className="flex items-center gap-1 text-sm font-semibold">
<Star size={14} className="fill-accent text-accent" />
{formatRating(item.rating, settings.ratingScale)}
</span>
)}
</div>
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-3">
<StatusPill status={item.status} />
{item.endDate && item.status === 'termine' && <span>{formatDate(item.endDate)}</span>}
{item.favorite && <span className="text-accent">♥ {t('form.favorite')}</span>}
</div>
{item.notes && <p className="mt-3 whitespace-pre-line text-sm leading-relaxed text-ink-2">{item.notes}</p>}
</div>
)}
{item.overview && <p className="mt-4 line-clamp-5 text-sm leading-relaxed text-ink-2">{item.overview}</p>}
<div className="mt-5 grid grid-cols-2 gap-2">
<button onClick={onClose} className="btn btn-ghost">
{t('common.close')}
</button>
<button onClick={addToWatchlist} disabled={busy || added || owned} className={cx('btn', added || owned ? 'btn-ghost' : 'btn-primary')}>
{busy ? <Loader2 size={16} className="animate-spin" /> : added || owned ? <Check size={16} /> : <Plus size={16} />}
{added ? t('reco.addedShort') : owned ? t('social.inLibrary') : t('social.addToWatch')}
</button>
</div>
</div>
</div>
)
}
+89
View File
@@ -0,0 +1,89 @@
import { Loader2, Search } from 'lucide-react'
import { useEffect, useState } from 'react'
import { t } from '../../i18n'
import { profileLink, searchProfiles, type ProfileCard } from '../../lib/cloud/social'
import PersonRow from './PersonRow'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
/** Trouver des amis par pseudo ou par nom. */
export default function PeopleSearch({ onClose }: { onClose: () => void }) {
const { me } = useSocial()
const [q, setQ] = useState('')
const [results, setResults] = useState<ProfileCard[]>([])
const [loading, setLoading] = useState(false)
const [copied, setCopied] = useState(false)
useEffect(() => {
const term = q.trim()
if (term.length < 2) return setResults([])
let alive = true
setLoading(true)
const timer = setTimeout(() => {
searchProfiles(term)
.then((r) => alive && setResults(r))
.catch(() => alive && setResults([]))
.finally(() => alive && setLoading(false))
}, 300)
return () => {
alive = false
clearTimeout(timer)
}
}, [q])
const invite = async () => {
if (!me) return
const url = profileLink(me.username)
try {
if (navigator.share && window.matchMedia?.('(pointer: coarse)').matches) await navigator.share({ title: 'AzuuCine', text: t('social.inviteText'), url })
else {
await navigator.clipboard.writeText(url)
setCopied(true)
}
} catch {
/* annulé */
}
}
return (
<Sheet label={t('social.findFriends')} title={t('social.findFriends')} onClose={onClose}>
<div className="px-4 pt-4">
<div className="relative">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder={t('social.searchPh')}
className="field pl-10"
autoFocus
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
enterKeyHint="search"
/>
{loading && <Loader2 size={17} className="absolute right-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</div>
{results.length > 0 ? (
<div className="mt-3 divide-y divide-line">
{results.map((p) => (
<PersonRow key={p.id} person={p} />
))}
</div>
) : (
q.trim().length >= 2 && !loading && <p className="py-8 text-center text-sm text-ink-3">{t('social.noResults')}</p>
)}
{me && (
<div className="mt-8 rounded-2xl border border-dashed border-line-strong p-4 text-sm">
<p className="text-ink-2">{t('social.inviteHint')}</p>
<button onClick={invite} className="mt-2 font-medium text-ink">
{copied ? t('social.linkCopied') : t('social.shareMyProfile')} <span className="text-accent">→</span>
</button>
</div>
)}
</div>
</Sheet>
)
}
+59
View File
@@ -0,0 +1,59 @@
import { Check, Loader2, Lock } from 'lucide-react'
import { useState, type ReactNode } from 'react'
import { t } from '../../i18n'
import { follow, unfollow, type ProfileCard } from '../../lib/cloud/social'
import { cx } from '../../lib/utils'
import Avatar from './Avatar'
import { useSocial } from './SocialProvider'
/** Ligne « personne » : photo, nom, @pseudo, et bouton d'abonnement (ou actions personnalisées). */
export default function PersonRow({ person, actions }: { person: ProfileCard; actions?: ReactNode }) {
const social = useSocial()
const [relation, setRelation] = useState(person.relation)
const [busy, setBusy] = useState(false)
const isMe = social.me?.id === person.id
const toggle = async () => {
setBusy(true)
try {
if (relation === 'none') setRelation(await follow(person.id))
else {
await unfollow(person.id)
setRelation('none')
}
} catch {
/* réseau : rien ne change */
} finally {
setBusy(false)
}
}
return (
<div className="flex items-center gap-3 py-2.5">
<button onClick={() => social.openProfile(person.username)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
<Avatar url={person.avatarUrl} name={person.displayName} size={44} />
<span className="min-w-0">
<span className="block truncate text-sm font-semibold">{person.displayName}</span>
<span className="flex items-center gap-1 text-xs text-ink-3">
@{person.username}
{person.isPrivate && <Lock size={10} />}
</span>
</span>
</button>
{actions ??
(!isMe && (
<button
onClick={toggle}
disabled={busy}
className={cx(
'flex h-8 shrink-0 items-center gap-1 rounded-full px-3 text-xs font-semibold transition active:scale-95',
relation === 'none' ? 'bg-accent-fill text-on-accent' : 'border border-line-strong text-ink-2',
)}
>
{busy ? <Loader2 size={13} className="animate-spin" /> : relation === 'accepted' ? <Check size={13} /> : null}
{relation === 'accepted' ? t('social.following') : relation === 'pending' ? t('social.requested') : t('social.follow')}
</button>
))}
</div>
)
}
+383
View File
@@ -0,0 +1,383 @@
import { Check, Loader2, Lock, Share2, Star, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { t } from '../../i18n'
import { follow, getProfile, getProfileItems, profileLink, unfollow, type Profile } from '../../lib/cloud/social'
import { STATUSES, TOP_CATEGORIES } from '../../lib/constants'
import { cx, formatRating } from '../../lib/utils'
import { useMedia } from '../../store'
import type { MediaItem, WatchStatus } from '../../types'
import ConfirmDialog from '../ConfirmDialog'
import Poster from '../Poster'
import { EmptyState, SectionTitle } from '../ui'
import Avatar from './Avatar'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
function PosterTile({ item, onOpen, caption }: { item: MediaItem; onOpen: () => void; caption?: string }) {
const { settings } = useMedia()
return (
<button onClick={onOpen} className="block w-full text-left">
<Poster src={item.poster} title={item.title} />
<p className="mt-1.5 truncate text-[11px] font-medium text-ink-2">{item.title}</p>
<p className="flex h-4 items-center gap-1 text-[11px] text-ink-3">
{item.rating != null && (
<>
<Star size={10} className="fill-accent text-accent" />
{formatRating(item.rating, settings.ratingScale)}
</>
)}
{caption && <span className="truncate">{caption}</span>}
</p>
</button>
)
}
function Stat({ value, label, onClick }: { value?: number; label: string; onClick?: () => void }) {
const body = (
<>
<span className="block text-lg font-bold tabular-nums leading-tight">{value == null ? '—' : value.toLocaleString()}</span>
<span className="block text-[11px] text-ink-3">{label}</span>
</>
)
return onClick ? (
<button onClick={onClick} className="flex-1 text-center">
{body}
</button>
) : (
<div className="flex-1 text-center">{body}</div>
)
}
/** Page de profil (la mienne ou celle d'un autre). */
export default function ProfileView({ username, onClose }: { username: string; onClose: () => void }) {
const social = useSocial()
const [profile, setProfile] = useState<Profile | null>()
const [error, setError] = useState<string>()
const [tab, setTab] = useState<'profile' | 'library'>('profile')
const [busy, setBusy] = useState(false)
const [confirmUnfollow, setConfirmUnfollow] = useState(false)
const [toast, setToast] = useState<string>()
const load = useCallback(async () => {
setError(undefined)
try {
setProfile(await getProfile(username))
} catch (e) {
setError((e as Error).message)
setProfile(null)
}
}, [username])
useEffect(() => {
void load()
}, [load])
// Mon profil a changé (modification) : on recharge
useEffect(() => {
if (profile?.isMe && social.me) setProfile(social.me)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [social.me])
useEffect(() => {
if (!toast) return
const timer = setTimeout(() => setToast(undefined), 2500)
return () => clearTimeout(timer)
}, [toast])
const owner = profile ? { username: profile.username, displayName: profile.displayName, avatarUrl: profile.avatarUrl } : undefined
const openItem = (item: MediaItem) => social.openItem(item, profile?.isMe ? undefined : owner)
const share = async () => {
if (!profile) return
const url = profileLink(profile.username)
try {
if (navigator.share && window.matchMedia?.('(pointer: coarse)').matches) await navigator.share({ title: profile.displayName, url })
else {
await navigator.clipboard.writeText(url)
setToast(t('social.linkCopied'))
}
} catch {
/* partage annulé */
}
}
const toggleFollow = async () => {
if (!profile) return
if (profile.relation !== 'none') return setConfirmUnfollow(true)
setBusy(true)
try {
await follow(profile.id)
await load()
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
const doUnfollow = async () => {
if (!profile) return
setConfirmUnfollow(false)
setBusy(true)
try {
await unfollow(profile.id)
await load()
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
const topByCategory = useMemo(() => {
const out: { label: string; items: MediaItem[] }[] = []
for (const c of TOP_CATEGORIES) {
const list = (profile?.top ?? []).filter((i) => i.top?.category === c.value).sort((a, b) => a.top!.rank - b.top!.rank)
if (list.length) out.push({ label: c.plural, items: list })
}
return out
}, [profile])
return (
<Sheet
label={t('social.profile')}
title={profile ? `@${profile.username}` : ''}
onClose={onClose}
right={
profile ? (
<button onClick={share} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('social.shareProfile')}>
<Share2 size={18} />
</button>
) : undefined
}
>
{profile === undefined ? (
<p className="flex items-center justify-center gap-2 py-16 text-sm text-ink-3">
<Loader2 size={16} className="animate-spin" /> {t('social.loading')}
</p>
) : profile === null ? (
<div className="px-4">
<EmptyState title={error ? t('social.loadError') : t('social.notFound')} text={error ?? t('social.notFoundHint', { username })} />
</div>
) : (
<>
{/* Bannière + photo */}
<div className="relative aspect-[3/1] w-full overflow-hidden bg-surface-2">
{profile.bannerUrl && <img src={profile.bannerUrl} alt="" className="size-full object-cover" />}
</div>
<div className="px-4">
<div className="relative -mt-11 flex items-end justify-between gap-3">
<Avatar url={profile.avatarUrl} name={profile.displayName} size={88} className="border-4 border-bg" />
{profile.isMe ? (
<button onClick={social.openEdit} className="btn btn-ghost mb-1 px-4 py-2 text-sm">
{t('social.editProfile')}
</button>
) : (
<button
onClick={toggleFollow}
disabled={busy}
className={cx('btn mb-1 px-4 py-2 text-sm', profile.relation === 'none' ? 'btn-primary' : 'btn-ghost')}
>
{busy ? (
<Loader2 size={15} className="animate-spin" />
) : profile.relation === 'accepted' ? (
<Check size={15} />
) : profile.relation === 'none' ? (
<UserPlus size={15} />
) : null}
{profile.relation === 'accepted'
? t('social.following')
: profile.relation === 'pending'
? t('social.requested')
: profile.followsMe
? t('social.followBack')
: t('social.follow')}
</button>
)}
</div>
<h1 className="mt-3 text-2xl font-bold leading-tight">{profile.displayName}</h1>
<p className="mt-0.5 flex items-center gap-1.5 text-sm text-ink-3">
@{profile.username}
{profile.isPrivate && <Lock size={12} aria-label={t('social.private')} />}
{profile.followsMe && !profile.isMe && (
<span className="rounded-full bg-surface-2 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-ink-2">
{t('social.followsYou')}
</span>
)}
</p>
{profile.bio && <p className="mt-3 whitespace-pre-line text-sm leading-relaxed text-ink-2">{profile.bio}</p>}
<div className="mt-5 flex divide-x divide-line rounded-2xl border border-line py-3">
<Stat value={profile.visible ? (profile.stats?.finished ?? 0) : undefined} label={t('social.seen')} />
<Stat value={profile.followers} label={t('social.followers', { count: profile.followers })} onClick={profile.visible ? () => social.openFollowList(profile, 'followers') : undefined} />
<Stat value={profile.following} label={t('social.followingCount', { count: profile.following })} onClick={profile.visible ? () => social.openFollowList(profile, 'following') : undefined} />
</div>
{profile.isMe && social.requests.length > 0 && (
<button onClick={() => social.openFollowList(profile, 'followers')} className="mt-3 flex w-full items-center justify-between rounded-2xl border border-accent px-4 py-3 text-sm">
<span>{t('social.requests', { count: social.requests.length })}</span>
<span className="text-accent">→</span>
</button>
)}
{!profile.visible ? (
<div className="mt-8 flex flex-col items-center rounded-2xl border border-line px-6 py-10 text-center">
<Lock size={26} className="text-ink-3" />
<p className="mt-3 font-semibold">{t('social.privateTitle')}</p>
<p className="mt-1 text-sm text-ink-3">{t('social.privateText')}</p>
</div>
) : (
<>
<div className="mt-6 grid grid-cols-2 gap-1 rounded-full border border-line p-1">
{(['profile', 'library'] as const).map((v) => (
<button
key={v}
onClick={() => setTab(v)}
className={cx('rounded-full py-2 text-sm font-medium transition-colors', tab === v ? 'bg-ink text-bg' : 'text-ink-3')}
>
{v === 'profile' ? t('social.tabProfile') : t('social.tabLibrary')}
</button>
))}
</div>
{tab === 'profile' ? (
<ProfileTab profile={profile} topByCategory={topByCategory} onOpen={openItem} />
) : (
<LibraryTab profile={profile} onOpen={openItem} />
)}
</>
)}
</div>
</>
)}
{toast && (
<p role="status" className="sheet-in fixed inset-x-4 bottom-8 z-[70] mx-auto max-w-md rounded-2xl border border-line-strong bg-surface-2 p-3.5 text-center text-sm">
{toast}
</p>
)}
<ConfirmDialog
open={confirmUnfollow}
title={profile?.relation === 'pending' ? t('social.cancelRequestTitle') : t('social.unfollowTitle', { name: profile?.displayName ?? '' })}
message={profile?.isPrivate && profile.relation === 'accepted' ? t('social.unfollowPrivate') : undefined}
confirmLabel={profile?.relation === 'pending' ? t('social.cancelRequest') : t('social.unfollow')}
onConfirm={doUnfollow}
onCancel={() => setConfirmUnfollow(false)}
/>
</Sheet>
)
}
function ProfileTab({ profile, topByCategory, onOpen }: { profile: Profile; topByCategory: { label: string; items: MediaItem[] }[]; onOpen: (i: MediaItem) => void }) {
const s = profile.stats
return (
<>
{topByCategory.map((c) => (
<section key={c.label}>
<SectionTitle>
{t('social.top5')} · {c.label}
</SectionTitle>
<div className="grid grid-cols-5 gap-2">
{c.items.map((item) => (
<div key={item.id} className="relative">
<PosterTile item={item} onOpen={() => onOpen(item)} />
<span className="absolute left-1 top-1 grid size-5 place-items-center rounded-full bg-bg/85 text-[10px] font-bold">{item.top!.rank}</span>
</div>
))}
</div>
</section>
))}
<SectionTitle>{t('social.recent')}</SectionTitle>
{profile.recent.length ? (
<div className="grid grid-cols-4 gap-2.5">
{profile.recent.map((item) => (
<PosterTile key={item.id} item={item} onOpen={() => onOpen(item)} />
))}
</div>
) : (
<p className="text-sm text-ink-3">{t('social.noRecent')}</p>
)}
{s && (
<>
<SectionTitle>{t('nav.stats')}</SectionTitle>
<div className="grid grid-cols-2 gap-3">
{[
[s.finishedYear, t('social.statYear')],
[s.films, t('social.statFilms')],
[s.series, t('social.statSeries')],
[s.episodes, t('home.episodesSeen')],
].map(([v, label]) => (
<div key={label as string} className="card p-4">
<div className="eyebrow">{label}</div>
<div className="mt-2 text-2xl font-bold tabular-nums leading-none">{(v as number).toLocaleString()}</div>
</div>
))}
</div>
</>
)}
</>
)
}
function LibraryTab({ profile, onOpen }: { profile: Profile; onOpen: (i: MediaItem) => void }) {
const [status, setStatus] = useState<WatchStatus | ''>('')
const [list, setList] = useState<MediaItem[]>([])
const [loading, setLoading] = useState(false)
const [done, setDone] = useState(false)
const loadPage = useCallback(
async (reset: boolean) => {
setLoading(true)
try {
const page = await getProfileItems(profile.id, status || null, reset ? 0 : list.length)
setList((prev) => (reset ? page : [...prev, ...page]))
setDone(page.length < 48)
} finally {
setLoading(false)
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[profile.id, status, list.length],
)
useEffect(() => {
void loadPage(true)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [profile.id, status])
return (
<div className="mt-5">
<div className="no-scrollbar -mx-4 mb-4 flex gap-2 overflow-x-auto px-4">
<button onClick={() => setStatus('')} className={cx('chip shrink-0 py-1! text-[13px]', !status && 'chip-on')}>
{t('catalog.all')}
</button>
{STATUSES.map((s) => (
<button key={s.value} onClick={() => setStatus(s.value)} className={cx('chip shrink-0 py-1! text-[13px]', status === s.value && 'chip-on')}>
{s.label}
</button>
))}
</div>
{list.length ? (
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4">
{list.map((item) => (
<PosterTile key={item.id} item={item} onOpen={() => onOpen(item)} />
))}
</div>
) : (
!loading && <p className="py-6 text-center text-sm text-ink-3">{t('social.emptyLibrary')}</p>
)}
{loading && (
<p className="flex items-center justify-center gap-2 py-6 text-sm text-ink-3">
<Loader2 size={14} className="animate-spin" />
</p>
)}
{!loading && !done && list.length > 0 && (
<button onClick={() => loadPage(false)} className="btn btn-ghost mt-5 w-full">
{t('social.loadMore')}
</button>
)}
</div>
)
}
+33
View File
@@ -0,0 +1,33 @@
import { X } from 'lucide-react'
import { useEffect, type ReactNode } from 'react'
import { t } from '../../i18n'
/** Écran plein (profil, recherche…) avec en-tête et bouton fermer. */
export default function Sheet({ title, onClose, right, children, label }: { title: ReactNode; onClose: () => void; right?: ReactNode; children: ReactNode; label: string }) {
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => {
document.body.style.overflow = prev
window.removeEventListener('keydown', onKey)
}
}, [onClose])
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" 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')}>
<X size={22} />
</button>
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{title}</h2>
<span className="flex size-10 items-center justify-end">{right}</span>
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="safe-bottom mx-auto max-w-2xl pb-16">{children}</div>
</div>
</div>
)
}
+133
View File
@@ -0,0 +1,133 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { getFollowRequests, getMyProfile, type Profile, type ProfileCard } from '../../lib/cloud/social'
import { useMedia } from '../../store'
import type { MediaItem } from '../../types'
import EditProfile from './EditProfile'
import FollowList from './FollowList'
import ItemPeek, { type PeekOwner } from './ItemPeek'
import PeopleSearch from './PeopleSearch'
import ProfileView from './ProfileView'
interface SocialApi {
/** Réseau disponible (compte connecté) */
enabled: boolean
me: Profile | null
requests: ProfileCard[]
refresh: () => Promise<void>
openProfile: (username: string) => void
openSearch: () => void
openEdit: () => void
openFollowList: (profile: Profile, kind: 'followers' | 'following') => void
peek: (item: MediaItem, owner?: PeekOwner) => void
/** Ouvre la fiche si elle est à moi, sinon l'aperçu */
openItem: (item: MediaItem, owner?: PeekOwner) => void
}
const SocialContext = createContext<SocialApi>({
enabled: false,
me: null,
requests: [],
refresh: async () => {},
openProfile: () => {},
openSearch: () => {},
openEdit: () => {},
openFollowList: () => {},
peek: () => {},
openItem: () => {},
})
export const useSocial = () => useContext(SocialContext)
type Overlay =
| { kind: 'profile'; username: string }
| { kind: 'search' }
| { kind: 'edit' }
| { kind: 'follows'; profile: Profile; list: 'followers' | 'following' }
/** Profils, recherche et aperçus : affichés par-dessus l'app, empilés (le bouton fermer revient au précédent). */
export function SocialProvider({ children, onOpenOwnItem }: { children: ReactNode; onOpenOwnItem: (item: MediaItem) => void }) {
const { account, items } = useMedia()
const enabled = !!account
const [me, setMe] = useState<Profile | null>(null)
const [requests, setRequests] = useState<ProfileCard[]>([])
const [stack, setStack] = useState<Overlay[]>([])
const [peeked, setPeeked] = useState<{ item: MediaItem; owner?: PeekOwner }>()
const refresh = useCallback(async () => {
if (!enabled || !navigator.onLine) return
try {
const [p, r] = await Promise.all([getMyProfile(), getFollowRequests()])
setMe(p)
setRequests(r)
} catch {
/* hors-ligne / serveur pas encore à jour : le reste de l'app fonctionne */
}
}, [enabled])
useEffect(() => {
void refresh()
}, [refresh])
const push = useCallback((o: Overlay) => setStack((s) => [...s.slice(-8), o]), [])
const pop = useCallback(() => setStack((s) => s.slice(0, -1)), [])
// Lien partagé « #/u/pseudo »
useEffect(() => {
if (!enabled) return
const check = () => {
const m = location.hash.match(/^#\/u\/([a-z0-9_]{3,20})$/i)
if (!m) return
history.replaceState(null, '', `${location.pathname}${location.search}#/home`)
push({ kind: 'profile', username: m[1].toLowerCase() })
}
check()
window.addEventListener('hashchange', check)
return () => window.removeEventListener('hashchange', check)
}, [enabled, push])
const openItem = useCallback(
(item: MediaItem, owner?: PeekOwner) => {
const mine = !owner || owner.username === me?.username
const local = mine ? items.find((i) => i.id === item.id) : undefined
if (local) onOpenOwnItem(local)
else setPeeked({ item, owner })
},
[items, me?.username, onOpenOwnItem],
)
const api = useMemo<SocialApi>(
() => ({
enabled,
me,
requests,
refresh,
openProfile: (username) => push({ kind: 'profile', username }),
openSearch: () => push({ kind: 'search' }),
openEdit: () => push({ kind: 'edit' }),
openFollowList: (profile, list) => push({ kind: 'follows', profile, list }),
peek: (item, owner) => setPeeked({ item, owner }),
openItem,
}),
[enabled, me, requests, refresh, push, openItem],
)
return (
<SocialContext.Provider value={api}>
{/* Les écrans sociaux sont placés avant l'app : une fiche ouverte depuis un profil passe au-dessus */}
{enabled &&
stack.map((o, k) =>
o.kind === 'profile' ? (
<ProfileView key={k} username={o.username} onClose={pop} />
) : o.kind === 'search' ? (
<PeopleSearch key={k} onClose={pop} />
) : o.kind === 'edit' ? (
<EditProfile key={k} onClose={pop} />
) : (
<FollowList key={k} profile={o.profile} initial={o.list} onClose={pop} />
),
)}
{children}
{enabled && peeked && <ItemPeek item={peeked.item} owner={peeked.owner} onClose={() => setPeeked(undefined)} />}
</SocialContext.Provider>
)
}
+78
View File
@@ -0,0 +1,78 @@
import { t } from '../i18n'
import type { ReactNode } from 'react'
import { cx } from '../lib/utils'
/** En-tête de page : titre en gras, moitié blanc / moitié rouge. */
export function PageHeader({ title, accent, subtitle, action }: { title: string; accent?: string; subtitle?: string; action?: ReactNode }) {
return (
<header className="flex items-end justify-between gap-3 pb-5 pt-7">
<div className="min-w-0">
<h1 className="text-[1.9rem] leading-tight">
{title}
{accent && <span className="text-accent">{accent}</span>}
</h1>
{subtitle && <p className="mt-1 text-sm text-ink-3">{subtitle}</p>}
</div>
{action}
</header>
)
}
export function StatTile({ label, value, hint, className }: { label: string; value: ReactNode; hint?: string; className?: string }) {
return (
<div className={cx('card p-4', className)}>
<div className="eyebrow">{label}</div>
<div className="mt-2 text-2xl font-bold leading-none tabular-nums">{value}</div>
{hint && <div className="mt-1.5 text-xs text-ink-3">{hint}</div>}
</div>
)
}
/** Titre de section façon Letterboxd : petites capitales grises + filet. */
export function SectionTitle({ children, action }: { children: ReactNode; action?: ReactNode }) {
return (
<div className="mb-4 mt-9 flex items-center justify-between gap-3 border-b border-line pb-2">
<h2 className="eyebrow text-ink-2">{children}</h2>
{action}
</div>
)
}
export function LinkArrow({ onClick, children }: { onClick: () => void; children: ReactNode }) {
return (
<button onClick={onClick} className="shrink-0 text-xs font-medium text-ink-3 transition-colors hover:text-ink">
{children} <span className="text-accent">→</span>
</button>
)
}
/** Liste de barres horizontales (une seule série → une seule couleur, valeurs écrites en clair). */
export function BarList({ data, format = String }: { data: { label: string; value: number }[]; format?: (v: number) => string }) {
const max = Math.max(1, ...data.map((d) => d.value))
if (!data.some((d) => d.value > 0)) return <p className="text-sm text-ink-3">{t('common.noData')}</p>
return (
<ul className="space-y-3">
{data.map((d) => (
<li key={d.label} className="text-sm" title={`${d.label} : ${format(d.value)}`}>
<div className="mb-1.5 flex justify-between gap-2">
<span className="truncate text-ink-2">{d.label}</span>
<span className="shrink-0 text-xs tabular-nums text-ink">{format(d.value)}</span>
</div>
<div className="h-1 rounded-full bg-surface-2">
<div className="h-full rounded-full bg-accent" style={{ width: `${(d.value / max) * 100}%`, minWidth: d.value ? 4 : 0 }} />
</div>
</li>
))}
</ul>
)
}
export function EmptyState({ title, text, action }: { title: string; text?: string; action?: ReactNode }) {
return (
<div className="card mt-4 flex flex-col items-center px-6 py-12 text-center">
<p className="text-lg font-semibold">{title}</p>
{text && <p className="mt-2 max-w-xs text-sm text-ink-2">{text}</p>}
{action && <div className="mt-6">{action}</div>}
</div>
)
}