Files
bobinoo/src/components/social/SocialProvider.tsx
T
Claude c66f0f62a6 Notifications d'abonnement (et rien d'autre)
- Cloche sur l'accueil (avec le nombre non lu) : qui s'abonne, demande à s'abonner,
  se désabonne, ou accepte ma demande ; accepter/refuser une demande directement depuis la liste
- Serveur (migration 20261127120000, déjà appliquée) : déclencheur sur follows, une ligne par
  personne et par sens, 200 max par compte ; rien entre comptes bloqués ou suspendus ;
  retirer un abonné, bloquer ou supprimer un compte ne notifie pas
- Fonctions get_notifications / unread_notifications / mark_notifications_read (comptes connectés seulement)
- Textes dans les 18 langues

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
2026-11-27 16:09:55 +00:00

249 lines
9.7 KiB
TypeScript

import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { getFollowRequests, getMyProfile, unreadNotifications, type Profile, type ProfileCard } from '../../lib/cloud/social'
import NotificationsSheet from './NotificationsSheet'
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'
import TitleReviews from './TitleReviews'
import { useOnResume } from '../../lib/onResume'
import WelcomeProfile, { RANDOM_USERNAME } from './WelcomeProfile'
import { InvitePeople, SharedListSheet } from './SharedLists'
import { getAniListById, type SearchResult } from '../../lib/catalogApi'
import { TYPE_BY_VALUE } from '../../lib/constants'
import type { SharedListItem } from '../../lib/cloud/sharedLists'
interface SocialApi {
/** Réseau disponible (compte connecté) */
enabled: boolean
me: Profile | null
requests: ProfileCard[]
/** Notifications d'abonnement non lues */
unread: number
openNotifications: () => void
refresh: () => Promise<void>
openProfile: (username: string) => void
openSearch: () => void
openEdit: () => void
openFollowList: (profile: Profile, kind: 'followers' | 'following') => void
/** Tous les avis sur un titre (amis / autres) */
openReviews: (externalId: string, title: string) => void
/** Ouvre la fiche si elle est à moi, sinon l'aperçu */
openItem: (item: MediaItem, owner?: PeekOwner) => void
/** Liste partagée */
openSharedList: (id: string) => void
/** Inviter des membres dans une liste partagée */
openInvite: (listId: string, listName: string) => void
/** Fiche d'un titre d'une liste partagée : la mienne si je l'ai, sinon la fiche du catalogue (ajout possible) */
openTitle: (title: SharedListItem) => void
/** Change à chaque modification des listes partagées (pour recharger les écrans qui les affichent) */
sharedTick: number
bumpShared: () => void
}
const SocialContext = createContext<SocialApi>({
enabled: false,
me: null,
requests: [],
unread: 0,
openNotifications: () => {},
refresh: async () => {},
openProfile: () => {},
openSearch: () => {},
openEdit: () => {},
openFollowList: () => {},
openReviews: () => {},
openItem: () => {},
openSharedList: () => {},
openInvite: () => {},
openTitle: () => {},
sharedTick: 0,
bumpShared: () => {},
})
export const useSocial = () => useContext(SocialContext)
let overlayUid = 0
type Overlay =
| { kind: 'profile'; username: string }
| { kind: 'search' }
| { kind: 'edit' }
| { kind: 'follows'; profile: Profile; list: 'followers' | 'following' }
| { kind: 'reviews'; externalId: string; title: string }
| { kind: 'sharedList'; id: string }
| { kind: 'invite'; listId: string; listName: string }
| { kind: 'notifications' }
/** 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,
onOpenSeed,
}: {
children: ReactNode
onOpenOwnItem: (item: MediaItem) => void
/** Ouvre la fiche d'un titre pas encore dans ma bibliothèque */
onOpenSeed?: (seed: SearchResult) => void
}) {
const { account, items } = useMedia()
const enabled = !!account
const [me, setMe] = useState<Profile | null>(null)
const [requests, setRequests] = useState<ProfileCard[]>([])
const [unread, setUnread] = useState(0)
const [stack, setStack] = useState<(Overlay & { uid: number })[]>([])
const [peeked, setPeeked] = useState<{ item: MediaItem; owner?: PeekOwner }>()
const [sharedTick, setSharedTick] = useState(0)
const bumpShared = useCallback(() => setSharedTick((n) => n + 1), [])
// « Plus tard » sur le choix du pseudo : redemandé au prochain lancement
const [welcomeLater, setWelcomeLater] = useState(() => {
try {
return sessionStorage.getItem('azuucine:welcome-later') === '1'
} catch {
return false
}
})
const later = useCallback(() => {
setWelcomeLater(true)
try {
sessionStorage.setItem('azuucine:welcome-later', '1')
} catch {
/* ignore */
}
}, [])
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 */
}
// À part : un serveur sans notifications ne doit pas empêcher le reste
unreadNotifications().then(setUnread, () => {})
}, [enabled])
useEffect(() => {
void refresh()
}, [refresh])
// Nouvelles demandes d'abonnement, compteurs… mis à jour au retour sur l'app
useOnResume(() => void refresh(), enabled)
// Pendant que l'app reste ouverte : nouvelles notifications d'abonnement toutes les 2 minutes
useEffect(() => {
if (!enabled) return
const id = setInterval(() => {
if (document.visibilityState === 'visible' && navigator.onLine) unreadNotifications().then(setUnread, () => {})
}, 120_000)
return () => clearInterval(id)
}, [enabled])
// Clé stable par écran (et non sa place dans la pile, qui change quand la pile est écourtée)
const push = useCallback((o: Overlay) => setStack((s) => [...s.slice(-8), { ...o, uid: ++overlayUid }]), [])
const close = useCallback((uid: number) => setStack((s) => s.filter((x) => x.uid !== uid)), [])
// 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 openTitle = useCallback(
async (s: SharedListItem) => {
const local = items.find((i) => i.externalId === s.externalId)
if (local) return onOpenOwnItem(local)
const anilist = s.externalId.startsWith('anilist:')
// AniList : fiche complète si possible (sinon l'instantané de la liste suffit pour l'ouvrir)
const full = anilist && navigator.onLine ? await getAniListById(s.externalId).catch(() => null) : null
onOpenSeed?.(
full ?? {
source: anilist ? 'anilist' : 'tmdb',
externalId: s.externalId,
title: s.title,
year: s.year,
thumb: s.poster,
posterUrl: s.poster,
kindLabel: TYPE_BY_VALUE[s.type].label,
typeGuess: s.type,
prefill: anilist ? { title: s.title, year: s.year, type: s.type, externalId: s.externalId, genres: [] } : undefined,
},
)
},
[items, onOpenOwnItem, onOpenSeed],
)
const api = useMemo<SocialApi>(
() => ({
enabled,
me,
requests,
unread,
openNotifications: () => push({ kind: 'notifications' }),
refresh,
openProfile: (username) => push({ kind: 'profile', username }),
openSearch: () => push({ kind: 'search' }),
openEdit: () => push({ kind: 'edit' }),
openFollowList: (profile, list) => push({ kind: 'follows', profile, list }),
openReviews: (externalId, title) => push({ kind: 'reviews', externalId, title }),
openItem,
openSharedList: (id) => push({ kind: 'sharedList', id }),
openInvite: (listId, listName) => push({ kind: 'invite', listId, listName }),
openTitle: (s) => void openTitle(s),
sharedTick,
bumpShared,
}),
[enabled, me, requests, unread, refresh, push, openItem, openTitle, sharedTick, bumpShared],
)
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) =>
o.kind === 'profile' ? (
<ProfileView key={o.uid} username={o.username} onClose={() => close(o.uid)} />
) : o.kind === 'search' ? (
<PeopleSearch key={o.uid} onClose={() => close(o.uid)} />
) : o.kind === 'edit' ? (
<EditProfile key={o.uid} onClose={() => close(o.uid)} />
) : o.kind === 'follows' ? (
<FollowList key={o.uid} profile={o.profile} initial={o.list} onClose={() => close(o.uid)} />
) : o.kind === 'reviews' ? (
<TitleReviews key={o.uid} externalId={o.externalId} title={o.title} onClose={() => close(o.uid)} onOpenProfile={(u) => push({ kind: 'profile', username: u })} />
) : o.kind === 'sharedList' ? (
<SharedListSheet key={o.uid} id={o.id} onClose={() => close(o.uid)} />
) : o.kind === 'notifications' ? (
<NotificationsSheet key={o.uid} onClose={() => close(o.uid)} onSeen={() => setUnread(0)} />
) : (
<InvitePeople key={o.uid} listId={o.listId} listName={o.listName} onClose={() => close(o.uid)} />
),
)}
{children}
{enabled && me && RANDOM_USERNAME.test(me.username) && !welcomeLater && <WelcomeProfile onLater={later} />}
{enabled && peeked && <ItemPeek item={peeked.item} owner={peeked.owner} onClose={() => setPeeked(undefined)} />}
</SocialContext.Provider>
)
}