Files
bobinoo/src/components/social/ProfileView.tsx
T
Claude 116efa4a30
deploy / deploy (push) Successful in 1m5s
Profil public : lien bobinoo.org/@pseudo visible sans compte (au choix)
Nouveau réglage « Profil visible sans compte » dans Modifier le profil,
désactivé par défaut et sans effet sur un compte privé. Une fois activé,
le lien bobinoo.org/@pseudo s'ouvre pour tout le monde : photo, bio,
Top 5, titres en cours et derniers vus, avec les notes. Les avis et la
bibliothèque complète restent réservés aux membres.

Côté base, public_profile() est la seule fonction ouverte sans compte :
elle renvoie null pour un profil non public, privé, suspendu ou inconnu
(pas moyen de deviner si un pseudo existe) et ne renvoie que le strict
nécessaire de chaque fiche. Le lien n'est pas indexé par les moteurs de
recherche. Un membre connecté qui ouvre le lien voit le profil comme
avant ; un visiteur peut s'abonner ou rejoindre Bobinoo depuis la page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
2026-12-02 11:14:33 +00:00

526 lines
22 KiB
TypeScript

import { Ban, Check, Loader2, Lock, Share2, Star, UserCheck, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { fmtNumber, t } from '../../i18n'
import { follow, getProfile, getProfileItems, getPublicProfile, PROFILE_ITEMS_PAGE, 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 ReportButton from '../moderation/ReportButton'
import { blockUser, unblockUser, useBlocked } from '../../lib/cloud/moderation'
import Poster from '../Poster'
import { EmptyState, SectionTitle } from '../ui'
import TopFive from '../TopFive'
import Avatar from './Avatar'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
function PosterTile({ item, onOpen, caption }: { item: MediaItem; onOpen: () => void; caption?: string }) {
return (
<button data-prefetch={item.externalId} onClick={onOpen} className="block w-full text-start">
<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)}
</>
)}
{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 ? '—' : fmtNumber(value)}</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).
* `guest` : ouverte sans compte depuis un lien bobinoo.org/@pseudo. Seulement la version publique du profil
* (si la personne l'a activée), et chaque geste (suivre, voir la bibliothèque) propose de créer un compte.
*/
export default function ProfileView({ username, onClose, guest = false }: { username: string; onClose: () => void; guest?: boolean }) {
const social = useSocial()
const { settings, items: myItems, requestAccount } = useMedia()
// Mon profil : affiché tout de suite avec ce qu'on a déjà, puis rechargé
const [profile, setProfile] = useState<Profile | null | undefined>(() => (social.me?.username === username ? social.me : undefined))
const [error, setError] = useState<string>()
const [tab, setTab] = useState<'profile' | 'top' | 'library'>('profile')
const [busy, setBusy] = useState(false)
const [confirmUnfollow, setConfirmUnfollow] = useState(false)
const [toast, setToast] = useState<string>()
const [confirmBlock, setConfirmBlock] = useState(false)
const { isBlocked } = useBlocked(!guest && !!profile && !profile.isMe)
const blocked = !!profile && !profile.isMe && isBlocked(profile.id)
/** `reload` : rechargement après une action (s'abonner, bloquer…) — en cas d'échec, on garde le profil affiché. */
const load = useCallback(
async (reload = false) => {
if (!reload) setError(undefined)
try {
const next = await (guest ? getPublicProfile(username) : getProfile(username))
if (reload) setError(undefined)
setProfile(next)
} catch (e) {
if (reload) return setToast((e as Error).message)
setError((e as Error).message)
setProfile(null)
}
},
[username, guest],
)
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)
// Mon lien, pas encore public : il ne s'ouvrira que pour les membres connectés (on le dit, sans bloquer le partage)
const membersOnly = profile.isMe && !profile.publicLink
try {
if (navigator.share && window.matchMedia?.('(pointer: coarse)').matches) {
await navigator.share({ title: profile.displayName, url })
if (membersOnly) setToast(t('social.linkMembersOnly'))
} else {
await navigator.clipboard.writeText(url)
setToast(membersOnly ? `${t('social.linkCopied')} ${t('social.linkMembersOnly')}` : 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(true)
void social.refresh()
} 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(true)
void social.refresh()
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
// Bloquer : il ne peut plus me suivre ni réagir à mes avis ; ses avis me sont masqués
const doBlock = async () => {
if (!profile) return
setConfirmBlock(false)
setBusy(true)
try {
await blockUser({ id: profile.id, username: profile.username, displayName: profile.displayName, avatarUrl: profile.avatarUrl })
await load(true)
void social.refresh()
setToast(t('block.done', { name: profile.displayName }))
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
const doUnblock = async () => {
if (!profile) return
setBusy(true)
try {
await unblockUser(profile.id)
setToast(t('block.undone', { name: profile.displayName }))
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
const topByCategory = useMemo(() => {
const out: { label: string; single: string; items: MediaItem[] }[] = []
// Mon profil : mes réglages locaux font foi tout de suite (même avant la synchro)
const shown = profile?.isMe ? TOP_CATEGORIES.filter((c) => settings.topCategories.includes(c.value)) : TOP_CATEGORIES
for (const c of shown) {
// Mon profil : mes fiches locales (un Top 5 modifié se voit tout de suite)
const source = profile?.isMe ? myItems.filter((i) => i.top) : (profile?.top ?? [])
const list = source.filter((i) => i.top?.category === c.value).sort((a, b) => a.top!.rank - b.top!.rank)
if (list.length) out.push({ label: c.plural, single: c.label, items: list })
}
return out
}, [profile, settings.topCategories, myItems])
// Mon profil : l'onglet Top 5 est toujours là (c'est ici qu'on le modifie) ; un autre : seulement s'il en a un
const showTop = !!profile && (profile.isMe ? settings.topCategories.length > 0 : topByCategory.length > 0)
// Sans compte : pas de bibliothèque complète (réservée aux membres)
const tabs = (['profile', ...(showTop ? ['top'] : []), ...(guest ? [] : ['library'])] as ('profile' | 'top' | 'library')[])
return (
<Sheet
wide
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">
{guest && !error ? (
<>
<EmptyState title={t('social.publicNotFound')} text={t('social.publicNotFoundHint')} />
<button onClick={requestAccount} className="btn btn-primary mx-auto mt-5 flex px-5 py-2.5">
{t('social.publicJoin')}
</button>
</>
) : (
<EmptyState title={error ? t('social.loadError') : t('social.notFound')} text={error ?? t('social.notFoundHint', { username })} />
)}
</div>
) : (
<>
{/* Bannière + photo */}
<div className={cx('relative aspect-[3/1] w-full overflow-hidden bg-surface-2 lg:aspect-auto', profile.bannerUrl ? 'lg:h-[min(40vh,22rem)]' : 'lg:h-40')}>
{profile.bannerUrl && <img src={profile.bannerUrl} alt="" className="size-full object-cover" />}
</div>
<div className="px-4 lg:px-10">
{/* La photo chevauche la bannière ; les boutons restent en dessous (pt = partie de la photo posée sur la bannière + marge) */}
<div className="relative -mt-11 flex items-start justify-between gap-3 lg:-mt-14">
<Avatar url={profile.avatarUrl} name={profile.displayName} size={88} className="border-4 border-bg" />
{profile.isMe ? (
<button onClick={social.openEdit} className="btn btn-ghost mt-[3.5rem] px-4 py-2 text-sm lg:mt-[4.25rem]">
{t('social.editProfile')}
</button>
) : guest ? (
<button onClick={requestAccount} className="btn btn-primary mt-[3.5rem] px-4 py-2 text-sm lg:mt-[4.25rem]">
<UserPlus size={15} /> {t('social.follow')}
</button>
) : (
<div className="mt-[3.5rem] flex items-center gap-1 lg:mt-[4.25rem]">
{blocked ? (
<button onClick={doUnblock} disabled={busy} className="btn btn-ghost px-4 py-2 text-sm">
{busy ? <Loader2 size={15} className="animate-spin" /> : <UserCheck size={15} />}
{t('block.unblock')}
</button>
) : (
<button
onClick={toggleFollow}
disabled={busy}
className={cx('btn 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>
)}
<ReportButton
target={{ type: 'profile', id: profile.id, userId: profile.id }}
actions={[
blocked
? { icon: <UserCheck size={18} />, label: t('block.unblock'), onClick: () => void doUnblock() }
: { icon: <Ban size={18} />, label: t('block.block'), onClick: () => setConfirmBlock(true) },
]}
/>
</div>
)}
</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-md bg-surface-2 px-2 py-0.5 text-[10px] font-semibold text-ink-2">
{t('social.followsYou')}
</span>
)}
</p>
{profile.bio && <p className="mt-3 whitespace-pre-line text-sm leading-relaxed text-ink-2 lg:max-w-3xl lg:text-base">{profile.bio}</p>}
{blocked && (
<p className="mt-4 flex items-start gap-2.5 rounded-2xl border border-line px-4 py-3 text-sm text-ink-2 lg:max-w-2xl">
<Ban size={16} className="mt-0.5 shrink-0 text-accent" />
{t('block.notice')}
</p>
)}
<div className="mt-5 flex divide-x divide-line rounded-2xl border border-line py-3 lg:max-w-2xl">
<Stat value={profile.visible ? (profile.seen ?? 0) : undefined} label={t('social.seen')} />
<Stat value={profile.followers} label={t('social.followers', { count: profile.followers })} onClick={profile.visible && !guest ? () => social.openFollowList(profile, 'followers') : undefined} />
<Stat value={profile.following} label={t('social.followingCount', { count: profile.following })} onClick={profile.visible && !guest ? () => 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={cx('mt-6 grid gap-1 rounded-md border border-line p-1 lg:max-w-md', tabs.length === 3 ? 'grid-cols-3' : 'grid-cols-2')}>
{tabs.map((v) => (
<button
key={v}
onClick={() => setTab(v)}
className={cx('rounded-md py-2 text-sm font-medium transition-colors', tab === v ? 'bg-ink text-bg' : 'text-ink-3')}
>
{v === 'profile' ? t('social.tabProfile') : v === 'top' ? t('social.top5') : t('social.tabLibrary')}
</button>
))}
</div>
{tab === 'profile' ? (
<>
<ProfileTab profile={profile} topByCategory={topByCategory} onOpen={openItem} />
{guest && (
<div className="mt-10 rounded-2xl border border-line px-5 py-6 text-center lg:max-w-2xl">
<p className="font-semibold">{t('social.publicCtaTitle')}</p>
<p className="mx-auto mt-1 max-w-sm text-sm text-ink-3">{t('social.publicCtaText', { name: profile.displayName })}</p>
<button onClick={requestAccount} className="btn btn-primary mx-auto mt-4 flex px-5 py-2.5">
{t('social.publicJoin')}
</button>
</div>
)}
</>
) : tab === 'top' ? (
<TopTab profile={profile} 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={confirmBlock}
title={t('block.confirmTitle', { name: profile?.displayName ?? '' })}
message={t('block.confirmText')}
confirmLabel={t('block.block')}
danger
onConfirm={doBlock}
onCancel={() => setConfirmBlock(false)}
/>
<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>
)
}
type TopGroup = { label: string; single: string; items: MediaItem[] }
/** Onglet Profil : le n°1 de chaque Top 5, ce que je regarde, mes 5 derniers vus. */
function ProfileTab({ profile, topByCategory, onOpen }: { profile: Profile; topByCategory: TopGroup[]; onOpen: (i: MediaItem) => void }) {
const firsts = topByCategory.flatMap((c) => (c.items[0]?.top?.rank === 1 ? [{ item: c.items[0], category: c.single }] : []))
const recent = profile.recent.slice(0, 5)
return (
<>
{firsts.length > 0 && (
<>
<SectionTitle>{t('social.top1')}</SectionTitle>
<div className="grid grid-cols-5 gap-2 lg:grid-cols-8 lg:gap-3 xl:grid-cols-10">
{firsts.map(({ item, category }) => (
<PosterTile key={item.id} item={item} onOpen={() => onOpen(item)} caption={category} />
))}
</div>
</>
)}
{profile.watching.length > 0 && (
<>
<SectionTitle>{t('social.watching')}</SectionTitle>
<div className="grid grid-cols-4 gap-2.5 sm:grid-cols-5 lg:grid-cols-8 lg:gap-3 xl:grid-cols-10">
{profile.watching.map((item) => (
<PosterTile key={item.id} item={item} onOpen={() => onOpen(item)} />
))}
</div>
</>
)}
<SectionTitle>{t('social.recent')}</SectionTitle>
{recent.length ? (
<div className="grid grid-cols-5 gap-2 lg:grid-cols-8 lg:gap-3 xl:grid-cols-10">
{recent.map((item) => (
<PosterTile key={item.id} item={item} onOpen={() => onOpen(item)} />
))}
</div>
) : (
<p className="text-sm text-ink-3">{t('social.noRecent')}</p>
)}
</>
)
}
/** Onglet Top 5 : le même affichage que l'ancien accueil. Le mien se modifie ici ; celui d'un autre est en lecture seule. */
function TopTab({ profile, onOpen }: { profile: Profile; onOpen: (i: MediaItem) => void }) {
return (
<div className="mt-2">
<TopFive onOpen={onOpen} items={profile.isMe ? undefined : profile.top} />
</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 request = useRef(0)
// Lignes reçues du serveur (y compris celles écartées à la relecture) : décalage de la page suivante
const received = useRef(0)
const loadPage = useCallback(
async (reset: boolean) => {
// Une réponse arrivée après un changement de filtre ne doit pas écraser la nouvelle liste
const id = ++request.current
setLoading(true)
if (reset) {
setList([])
received.current = 0
}
try {
const page = await getProfileItems(profile.id, status || null, reset ? 0 : received.current)
if (id !== request.current) return
received.current += page.received
setList((prev) => {
// Sans doublon (une fiche ne peut apparaître qu'une fois : même clé React)
const base = reset ? [] : prev
const seen = new Set(base.map((i) => i.id))
return [...base, ...page.items.filter((i) => !seen.has(i.id) && !!seen.add(i.id))]
})
setDone(page.received < PROFILE_ITEMS_PAGE)
} catch {
if (id === request.current) setDone(true)
} finally {
if (id === request.current) setLoading(false)
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[profile.id, status],
)
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 lg:grid-cols-6 xl:grid-cols-8 2xl:grid-cols-10">
{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>
)
}