diff --git a/src/components/social/NotificationsSheet.tsx b/src/components/social/NotificationsSheet.tsx new file mode 100644 index 0000000..ad92a63 --- /dev/null +++ b/src/components/social/NotificationsSheet.tsx @@ -0,0 +1,103 @@ +import { Loader2 } from 'lucide-react' +import { useEffect, useState } from 'react' +import { t, type TKey } from '../../i18n' +import { acceptFollower, getNotifications, markNotificationsRead, removeFollower, type FollowNotification } from '../../lib/cloud/social' +import { timeAgo } from '../../lib/timeAgo' +import { cx } from '../../lib/utils' +import Avatar from './Avatar' +import Sheet from './Sheet' +import { useSocial } from './SocialProvider' + +const TEXT: Record = { + new_follower: 'notif.newFollower', + follow_request: 'notif.followRequest', + unfollow: 'notif.unfollow', + follow_accepted: 'notif.followAccepted', +} + +/** Qui s'est abonné, désabonné, a demandé à s'abonner ou a accepté ma demande. Ouvrir la liste la marque comme lue. */ +export default function NotificationsSheet({ onClose, onSeen }: { onClose: () => void; onSeen: () => void }) { + const social = useSocial() + const [list, setList] = useState() + const [error, setError] = useState(false) + const [busy, setBusy] = useState() + + useEffect(() => { + let alive = true + getNotifications() + .then((l) => { + if (!alive) return + setList(l) + if (l.some((n) => !n.read)) void markNotificationsRead().then(onSeen, () => {}) + else onSeen() + }) + .catch(() => alive && setError(true)) + return () => { + alive = false + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + const pending = new Set(social.requests.map((r) => r.id)) + const answer = async (id: string, accept: boolean) => { + setBusy(id) + try { + if (accept) await acceptFollower(id) + else await removeFollower(id) + await social.refresh() + setList(await getNotifications()) + } catch { + /* réseau : rien ne change */ + } finally { + setBusy(undefined) + } + } + + return ( + +
+ {error ? ( +

{t('notif.error')}

+ ) : list === undefined ? ( +

+ +

+ ) : list.length === 0 ? ( +

{t('notif.empty')}

+ ) : ( +
    + {list.map((n) => ( +
  • + + {n.kind === 'follow_request' && pending.has(n.actor.id) && ( + + + + + )} +
  • + ))} +
+ )} +
+
+ ) +} diff --git a/src/components/social/SocialProvider.tsx b/src/components/social/SocialProvider.tsx index a205b26..cc38617 100644 --- a/src/components/social/SocialProvider.tsx +++ b/src/components/social/SocialProvider.tsx @@ -1,5 +1,6 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react' -import { getFollowRequests, getMyProfile, type Profile, type ProfileCard } from '../../lib/cloud/social' +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' @@ -20,6 +21,9 @@ interface SocialApi { enabled: boolean me: Profile | null requests: ProfileCard[] + /** Notifications d'abonnement non lues */ + unread: number + openNotifications: () => void refresh: () => Promise openProfile: (username: string) => void openSearch: () => void @@ -44,6 +48,8 @@ const SocialContext = createContext({ enabled: false, me: null, requests: [], + unread: 0, + openNotifications: () => {}, refresh: async () => {}, openProfile: () => {}, openSearch: () => {}, @@ -70,6 +76,7 @@ type Overlay = | { 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({ @@ -86,6 +93,7 @@ export function SocialProvider({ const enabled = !!account const [me, setMe] = useState(null) const [requests, setRequests] = useState([]) + 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) @@ -116,6 +124,8 @@ export function SocialProvider({ } 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(() => { @@ -123,6 +133,14 @@ export function SocialProvider({ }, [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 }]), []) @@ -181,6 +199,8 @@ export function SocialProvider({ enabled, me, requests, + unread, + openNotifications: () => push({ kind: 'notifications' }), refresh, openProfile: (username) => push({ kind: 'profile', username }), openSearch: () => push({ kind: 'search' }), @@ -194,7 +214,7 @@ export function SocialProvider({ sharedTick, bumpShared, }), - [enabled, me, requests, refresh, push, openItem, openTitle, sharedTick, bumpShared], + [enabled, me, requests, unread, refresh, push, openItem, openTitle, sharedTick, bumpShared], ) return ( @@ -214,6 +234,8 @@ export function SocialProvider({ close(o.uid)} onOpenProfile={(u) => push({ kind: 'profile', username: u })} /> ) : o.kind === 'sharedList' ? ( close(o.uid)} /> + ) : o.kind === 'notifications' ? ( + close(o.uid)} onSeen={() => setUnread(0)} /> ) : ( close(o.uid)} /> ), diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts index c271311..310a8aa 100644 --- a/src/i18n/locales/ar.ts +++ b/src/i18n/locales/ar.ts @@ -787,6 +787,15 @@ const dict: Translations = { 'social.requestsTab_many': 'الطلبات ({count})', 'social.noFollowing': 'لا تتابع أحدًا بعد.', 'social.noFollowers': 'لا متابعين بعد.', + 'notif.title': 'الإشعارات', + 'notif.empty': 'عندما يتابعك أحد أو يلغي متابعتك، ستراه هنا.', + 'notif.error': 'تعذّر تحميل الإشعارات.', + 'notif.newFollower': '{name} يتابعك', + 'notif.followRequest': '{name} يطلب متابعتك', + 'notif.unfollow': '{name} ألغى متابعتك', + 'notif.followAccepted': '{name} قبل طلبك', + 'notif.unread_one': '{count} إشعار جديد', + 'notif.unread_other': '{count} إشعارات جديدة', 'social.accept': 'قبول', 'social.decline': 'رفض', 'social.removeFollower': 'إزالة', diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index a6636a6..233b42c 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Anfragen ({count})', 'social.noFollowing': 'Du folgst noch niemandem.', 'social.noFollowers': 'Noch keine Follower.', + 'notif.title': 'Benachrichtigungen', + 'notif.empty': 'Wenn dir jemand folgt oder entfolgt, siehst du es hier.', + 'notif.error': 'Benachrichtigungen konnten nicht geladen werden.', + 'notif.newFollower': '{name} folgt dir', + 'notif.followRequest': '{name} möchte dir folgen', + 'notif.unfollow': '{name} folgt dir nicht mehr', + 'notif.followAccepted': '{name} hat deine Anfrage angenommen', + 'notif.unread_one': '{count} neue Benachrichtigung', + 'notif.unread_other': '{count} neue Benachrichtigungen', 'social.accept': 'Annehmen', 'social.decline': 'Ablehnen', 'social.removeFollower': 'Entfernen', diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 4c408f4..e97c802 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Requests ({count})', 'social.noFollowing': 'Not following anyone yet.', 'social.noFollowers': 'No followers yet.', + 'notif.title': 'Notifications', + 'notif.empty': 'When someone follows or unfollows you, you\'ll see it here.', + 'notif.error': 'Couldn\'t load notifications.', + 'notif.newFollower': '{name} followed you', + 'notif.followRequest': '{name} asked to follow you', + 'notif.unfollow': '{name} unfollowed you', + 'notif.followAccepted': '{name} accepted your request', + 'notif.unread_one': '{count} new notification', + 'notif.unread_other': '{count} new notifications', 'social.accept': 'Accept', 'social.decline': 'Decline', 'social.removeFollower': 'Remove', diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index e89c5c0..2c75231 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Solicitudes ({count})', 'social.noFollowing': 'Todavía no sigues a nadie.', 'social.noFollowers': 'Todavía no tienes seguidores.', + 'notif.title': 'Notificaciones', + 'notif.empty': 'Cuando alguien te siga o deje de seguirte, lo verás aquí.', + 'notif.error': 'No se pudieron cargar las notificaciones.', + 'notif.newFollower': '{name} te sigue', + 'notif.followRequest': '{name} quiere seguirte', + 'notif.unfollow': '{name} ya no te sigue', + 'notif.followAccepted': '{name} aceptó tu solicitud', + 'notif.unread_one': '{count} notificación nueva', + 'notif.unread_other': '{count} notificaciones nuevas', 'social.accept': 'Aceptar', 'social.decline': 'Rechazar', 'social.removeFollower': 'Eliminar', diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 7eb6769..c2a1bf2 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -690,6 +690,15 @@ const dict = { 'social.requestsTab_other': 'Demandes ({count})', 'social.noFollowing': 'Aucun abonnement pour l\'instant.', 'social.noFollowers': 'Aucun abonné pour l\'instant.', + 'notif.title': 'Notifications', + 'notif.empty': 'Quand quelqu\'un s\'abonne ou se désabonne, tu le verras ici.', + 'notif.error': 'Impossible de charger les notifications.', + 'notif.newFollower': '{name} te suit', + 'notif.followRequest': '{name} demande à te suivre', + 'notif.unfollow': '{name} ne te suit plus', + 'notif.followAccepted': '{name} a accepté ta demande', + 'notif.unread_one': '{count} nouvelle notification', + 'notif.unread_other': '{count} nouvelles notifications', 'social.accept': 'Accepter', 'social.decline': 'Refuser', 'social.removeFollower': 'Retirer', diff --git a/src/i18n/locales/hi.ts b/src/i18n/locales/hi.ts index ced0897..1402892 100644 --- a/src/i18n/locales/hi.ts +++ b/src/i18n/locales/hi.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'रिक्वेस्ट ({count})', 'social.noFollowing': 'अभी आप किसी को फ़ॉलो नहीं कर रहे।', 'social.noFollowers': 'अभी कोई फ़ॉलोअर नहीं।', + 'notif.title': 'सूचनाएँ', + 'notif.empty': 'जब कोई आपको फ़ॉलो या अनफ़ॉलो करेगा, आप उसे यहाँ देखेंगे।', + 'notif.error': 'सूचनाएँ लोड नहीं हो सकीं।', + 'notif.newFollower': '{name} आपको फ़ॉलो करते हैं', + 'notif.followRequest': '{name} आपको फ़ॉलो करना चाहते हैं', + 'notif.unfollow': '{name} ने आपको अनफ़ॉलो किया', + 'notif.followAccepted': '{name} ने आपका अनुरोध स्वीकार किया', + 'notif.unread_one': '{count} नई सूचना', + 'notif.unread_other': '{count} नई सूचनाएँ', 'social.accept': 'स्वीकार करें', 'social.decline': 'अस्वीकार करें', 'social.removeFollower': 'हटाएँ', diff --git a/src/i18n/locales/id.ts b/src/i18n/locales/id.ts index 608dd3b..f1bd5e5 100644 --- a/src/i18n/locales/id.ts +++ b/src/i18n/locales/id.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Permintaan ({count})', 'social.noFollowing': 'Belum mengikuti siapa pun.', 'social.noFollowers': 'Belum ada pengikut.', + 'notif.title': 'Notifikasi', + 'notif.empty': 'Saat seseorang mengikuti atau berhenti mengikutimu, kamu akan melihatnya di sini.', + 'notif.error': 'Notifikasi tidak dapat dimuat.', + 'notif.newFollower': '{name} mengikutimu', + 'notif.followRequest': '{name} ingin mengikutimu', + 'notif.unfollow': '{name} berhenti mengikutimu', + 'notif.followAccepted': '{name} menerima permintaanmu', + 'notif.unread_one': '{count} notifikasi baru', + 'notif.unread_other': '{count} notifikasi baru', 'social.accept': 'Terima', 'social.decline': 'Tolak', 'social.removeFollower': 'Hapus', diff --git a/src/i18n/locales/it.ts b/src/i18n/locales/it.ts index e972014..c752205 100644 --- a/src/i18n/locales/it.ts +++ b/src/i18n/locales/it.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Richieste ({count})', 'social.noFollowing': 'Non segui ancora nessuno.', 'social.noFollowers': 'Ancora nessun follower.', + 'notif.title': 'Notifiche', + 'notif.empty': 'Quando qualcuno inizia o smette di seguirti, lo vedrai qui.', + 'notif.error': 'Impossibile caricare le notifiche.', + 'notif.newFollower': '{name} ti segue', + 'notif.followRequest': '{name} chiede di seguirti', + 'notif.unfollow': '{name} non ti segue più', + 'notif.followAccepted': '{name} ha accettato la tua richiesta', + 'notif.unread_one': '{count} nuova notifica', + 'notif.unread_other': '{count} nuove notifiche', 'social.accept': 'Accetta', 'social.decline': 'Rifiuta', 'social.removeFollower': 'Rimuovi', diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index 316a91d..20d9ebf 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'リクエスト({count})', 'social.noFollowing': 'まだ誰もフォローしていません。', 'social.noFollowers': 'まだフォロワーはいません。', + 'notif.title': '通知', + 'notif.empty': '誰かにフォローまたはフォロー解除されると、ここに表示されます。', + 'notif.error': '通知を読み込めませんでした。', + 'notif.newFollower': '{name}さんがあなたをフォローしました', + 'notif.followRequest': '{name}さんがフォローをリクエストしました', + 'notif.unfollow': '{name}さんがフォローを解除しました', + 'notif.followAccepted': '{name}さんがリクエストを承認しました', + 'notif.unread_one': '新しい通知 {count} 件', + 'notif.unread_other': '新しい通知 {count} 件', 'social.accept': '承認', 'social.decline': '拒否', 'social.removeFollower': '削除', diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 7b7dfd3..8205839 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': '요청 ({count})', 'social.noFollowing': '아직 팔로우한 사람이 없어요.', 'social.noFollowers': '아직 팔로워가 없어요.', + 'notif.title': '알림', + 'notif.empty': '누군가 나를 팔로우하거나 언팔로우하면 여기에 표시돼요.', + 'notif.error': '알림을 불러오지 못했어요.', + 'notif.newFollower': '{name}님이 나를 팔로우해요', + 'notif.followRequest': '{name}님이 팔로우를 요청했어요', + 'notif.unfollow': '{name}님이 언팔로우했어요', + 'notif.followAccepted': '{name}님이 요청을 수락했어요', + 'notif.unread_one': '새 알림 {count}개', + 'notif.unread_other': '새 알림 {count}개', 'social.accept': '수락', 'social.decline': '거절', 'social.removeFollower': '삭제', diff --git a/src/i18n/locales/nl.ts b/src/i18n/locales/nl.ts index b903f5d..e3c9a12 100644 --- a/src/i18n/locales/nl.ts +++ b/src/i18n/locales/nl.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Verzoeken ({count})', 'social.noFollowing': 'Je volgt nog niemand.', 'social.noFollowers': 'Nog geen volgers.', + 'notif.title': 'Meldingen', + 'notif.empty': 'Als iemand je volgt of ontvolgt, zie je het hier.', + 'notif.error': 'Meldingen konden niet worden geladen.', + 'notif.newFollower': '{name} volgt je', + 'notif.followRequest': '{name} wil je volgen', + 'notif.unfollow': '{name} volgt je niet meer', + 'notif.followAccepted': '{name} heeft je verzoek geaccepteerd', + 'notif.unread_one': '{count} nieuwe melding', + 'notif.unread_other': '{count} nieuwe meldingen', 'social.accept': 'Accepteren', 'social.decline': 'Weigeren', 'social.removeFollower': 'Verwijderen', diff --git a/src/i18n/locales/pl.ts b/src/i18n/locales/pl.ts index ffd78a0..ac5187d 100644 --- a/src/i18n/locales/pl.ts +++ b/src/i18n/locales/pl.ts @@ -754,6 +754,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Prośby ({count})', 'social.noFollowing': 'Na razie nikogo nie obserwujesz.', 'social.noFollowers': 'Na razie brak obserwujących.', + 'notif.title': 'Powiadomienia', + 'notif.empty': 'Gdy ktoś zacznie lub przestanie cię obserwować, zobaczysz to tutaj.', + 'notif.error': 'Nie udało się wczytać powiadomień.', + 'notif.newFollower': '{name} obserwuje cię', + 'notif.followRequest': '{name} prosi o możliwość obserwowania', + 'notif.unfollow': '{name} już cię nie obserwuje', + 'notif.followAccepted': '{name} zaakceptował(a) twoją prośbę', + 'notif.unread_one': '{count} nowe powiadomienie', + 'notif.unread_other': '{count} nowych powiadomień', 'social.accept': 'Akceptuj', 'social.decline': 'Odrzuć', 'social.removeFollower': 'Usuń', diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index 4cfbf21..09859a6 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Solicitações ({count})', 'social.noFollowing': 'Você ainda não segue ninguém.', 'social.noFollowers': 'Nenhum seguidor por enquanto.', + 'notif.title': 'Notificações', + 'notif.empty': 'Quando alguém te seguir ou deixar de seguir, verás aqui.', + 'notif.error': 'Não foi possível carregar as notificações.', + 'notif.newFollower': '{name} segue-te', + 'notif.followRequest': '{name} pediu para te seguir', + 'notif.unfollow': '{name} deixou de te seguir', + 'notif.followAccepted': '{name} aceitou o teu pedido', + 'notif.unread_one': '{count} nova notificação', + 'notif.unread_other': '{count} novas notificações', 'social.accept': 'Aceitar', 'social.decline': 'Recusar', 'social.removeFollower': 'Remover', diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 3971afb..29deca0 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -754,6 +754,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Запросы ({count})', 'social.noFollowing': 'Ты пока ни на кого не подписан.', 'social.noFollowers': 'Подписчиков пока нет.', + 'notif.title': 'Уведомления', + 'notif.empty': 'Когда кто-то подпишется или отпишется, ты увидишь это здесь.', + 'notif.error': 'Не удалось загрузить уведомления.', + 'notif.newFollower': '{name} подписался(-ась) на тебя', + 'notif.followRequest': '{name} хочет подписаться на тебя', + 'notif.unfollow': '{name} отписался(-ась) от тебя', + 'notif.followAccepted': '{name} принял(а) твой запрос', + 'notif.unread_one': '{count} новое уведомление', + 'notif.unread_other': 'Новых уведомлений: {count}', 'social.accept': 'Принять', 'social.decline': 'Отклонить', 'social.removeFollower': 'Удалить', diff --git a/src/i18n/locales/th.ts b/src/i18n/locales/th.ts index c38ade2..731c8b3 100644 --- a/src/i18n/locales/th.ts +++ b/src/i18n/locales/th.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'คำขอ ({count})', 'social.noFollowing': 'ยังไม่ได้ติดตามใคร', 'social.noFollowers': 'ยังไม่มีผู้ติดตาม', + 'notif.title': 'การแจ้งเตือน', + 'notif.empty': 'เมื่อมีคนติดตามหรือเลิกติดตามคุณ คุณจะเห็นที่นี่', + 'notif.error': 'โหลดการแจ้งเตือนไม่ได้', + 'notif.newFollower': '{name} ติดตามคุณ', + 'notif.followRequest': '{name} ขอติดตามคุณ', + 'notif.unfollow': '{name} เลิกติดตามคุณ', + 'notif.followAccepted': '{name} ยอมรับคำขอของคุณ', + 'notif.unread_one': 'การแจ้งเตือนใหม่ {count} รายการ', + 'notif.unread_other': 'การแจ้งเตือนใหม่ {count} รายการ', 'social.accept': 'ยอมรับ', 'social.decline': 'ปฏิเสธ', 'social.removeFollower': 'นำออก', diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index 2aeb7e2..9b1bf4d 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'İstekler ({count})', 'social.noFollowing': 'Henüz kimseyi takip etmiyorsun.', 'social.noFollowers': 'Henüz takipçi yok.', + 'notif.title': 'Bildirimler', + 'notif.empty': 'Biri seni takip ettiğinde veya takibi bıraktığında burada göreceksin.', + 'notif.error': 'Bildirimler yüklenemedi.', + 'notif.newFollower': '{name} seni takip ediyor', + 'notif.followRequest': '{name} seni takip etmek istiyor', + 'notif.unfollow': '{name} seni takip etmeyi bıraktı', + 'notif.followAccepted': '{name} isteğini kabul etti', + 'notif.unread_one': '{count} yeni bildirim', + 'notif.unread_other': '{count} yeni bildirim', 'social.accept': 'Kabul et', 'social.decline': 'Reddet', 'social.removeFollower': 'Çıkar', diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts index 6aa7f73..fb912e8 100644 --- a/src/i18n/locales/vi.ts +++ b/src/i18n/locales/vi.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': 'Yêu cầu ({count})', 'social.noFollowing': 'Bạn chưa theo dõi ai.', 'social.noFollowers': 'Chưa có người theo dõi.', + 'notif.title': 'Thông báo', + 'notif.empty': 'Khi ai đó theo dõi hoặc bỏ theo dõi bạn, bạn sẽ thấy ở đây.', + 'notif.error': 'Không tải được thông báo.', + 'notif.newFollower': '{name} đã theo dõi bạn', + 'notif.followRequest': '{name} muốn theo dõi bạn', + 'notif.unfollow': '{name} đã bỏ theo dõi bạn', + 'notif.followAccepted': '{name} đã chấp nhận yêu cầu của bạn', + 'notif.unread_one': '{count} thông báo mới', + 'notif.unread_other': '{count} thông báo mới', 'social.accept': 'Chấp nhận', 'social.decline': 'Từ chối', 'social.removeFollower': 'Gỡ', diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index ef1302f..fb4015e 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -688,6 +688,15 @@ const dict: Translations = { 'social.requestsTab_other': '申请({count})', 'social.noFollowing': '还没有关注任何人。', 'social.noFollowers': '还没有粉丝。', + 'notif.title': '通知', + 'notif.empty': '有人关注或取消关注你时,会显示在这里。', + 'notif.error': '无法加载通知。', + 'notif.newFollower': '{name} 关注了你', + 'notif.followRequest': '{name} 请求关注你', + 'notif.unfollow': '{name} 取消关注了你', + 'notif.followAccepted': '{name} 接受了你的请求', + 'notif.unread_one': '{count} 条新通知', + 'notif.unread_other': '{count} 条新通知', 'social.accept': '同意', 'social.decline': '拒绝', 'social.removeFollower': '移除', diff --git a/src/lib/cloud/social.ts b/src/lib/cloud/social.ts index 15b4d95..34a19d6 100644 --- a/src/lib/cloud/social.ts +++ b/src/lib/cloud/social.ts @@ -218,6 +218,41 @@ export async function getFollowList(userId: string, kind: 'followers' | 'followi } export const getFollowRequests = async () => toCards(await rpc('get_follow_requests')) +// ─── Notifications (abonnements uniquement) ─── + +export type NotificationKind = 'new_follower' | 'follow_request' | 'unfollow' | 'follow_accepted' +const NOTIFICATION_KINDS: NotificationKind[] = ['new_follower', 'follow_request', 'unfollow', 'follow_accepted'] + +export interface FollowNotification { + id: number + kind: NotificationKind + createdAt: string + read: boolean + actor: ProfileCard +} + +export async function getNotifications(): Promise { + const raw = await rpc('get_notifications') + if (!Array.isArray(raw)) return [] + return raw.slice(0, 100).flatMap((n): FollowNotification[] => { + if (!isPlainObject(n) || typeof n.id !== 'number' || !NOTIFICATION_KINDS.includes(n.kind as NotificationKind)) return [] + const actor = toCard(n.actor) + const createdAt = safeIso(n.created_at) + return actor && createdAt ? [{ id: n.id, kind: n.kind as NotificationKind, createdAt, read: n.read === true, actor }] : [] + }) +} + +export async function unreadNotifications(): Promise { + const n = await rpc('unread_notifications') + return typeof n === 'number' && Number.isFinite(n) ? Math.max(0, Math.min(999, Math.round(n))) : 0 +} + +/** Tout marquer comme lu (la fonction ne renvoie rien : pas de JSON à lire). */ +export async function markNotificationsRead() { + const res = await cloudFetch('/rest/v1/rpc/mark_notifications_read', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }) + if (!res.ok) throw new Error(t('social.err.server', { status: res.status })) +} + // ─── Abonnements ─── async function ok(res: Response) { diff --git a/src/pages/HomePage.tsx b/src/pages/HomePage.tsx index 56fc233..ed7fe76 100644 --- a/src/pages/HomePage.tsx +++ b/src/pages/HomePage.tsx @@ -1,6 +1,6 @@ import { useSocial } from '../components/social/SocialProvider' import { t } from '../i18n' -import { CalendarDays, Dices, Plus } from 'lucide-react' +import { Bell, CalendarDays, Dices, Plus } from 'lucide-react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { TYPE_BY_VALUE } from '../lib/constants' import Avatar from '../components/social/Avatar' @@ -169,6 +169,18 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale subtitle={t('home.subtitle')} action={ + {social.enabled && ( + + )}