feat: optimize notifications

This commit is contained in:
codytseng
2025-09-05 22:08:17 +08:00
parent 47e7a18f2e
commit 2855754648
26 changed files with 520 additions and 234 deletions

View File

@@ -1,14 +1,13 @@
import { getEmbeddedPubkeys } from '@/lib/event'
import ParentNotePreview from '@/components/ParentNotePreview'
import { getEmbeddedPubkeys, getParentBech32Id } from '@/lib/event'
import { toNote } from '@/lib/link'
import { cn } from '@/lib/utils'
import { useSecondaryPage } from '@/PageManager'
import { useNostr } from '@/providers/NostrProvider'
import { AtSign, MessageCircle } from 'lucide-react'
import { AtSign, MessageCircle, Quote } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useMemo } from 'react'
import ContentPreview from '../../ContentPreview'
import { FormattedTimestamp } from '../../FormattedTimestamp'
import UserAvatar from '../../UserAvatar'
import { useTranslation } from 'react-i18next'
import Notification from './Notification'
export function MentionNotification({
notification,
@@ -17,6 +16,7 @@ export function MentionNotification({
notification: Event
isNew?: boolean
}) {
const { t } = useTranslation()
const { push } = useSecondaryPage()
const { pubkey } = useNostr()
const isMention = useMemo(() => {
@@ -24,25 +24,40 @@ export function MentionNotification({
const mentions = getEmbeddedPubkeys(notification)
return mentions.includes(pubkey)
}, [pubkey, notification])
const parentEventId = useMemo(() => getParentBech32Id(notification), [notification])
return (
<div
className="flex gap-2 items-center cursor-pointer py-2"
onClick={() => push(toNote(notification))}
>
<UserAvatar userId={notification.pubkey} size="small" />
{isMention ? (
<AtSign size={24} className="text-pink-400" />
) : (
<MessageCircle size={24} className="text-blue-400" />
)}
<ContentPreview
className={cn('truncate flex-1 w-0', isNew ? 'font-semibold' : 'text-muted-foreground')}
event={notification}
/>
<div className="text-muted-foreground">
<FormattedTimestamp timestamp={notification.created_at} short />
</div>
</div>
<Notification
notificationId={notification.id}
icon={
isMention ? (
<AtSign size={24} className="text-pink-400" />
) : parentEventId ? (
<MessageCircle size={24} className="text-blue-400" />
) : (
<Quote size={24} className="text-green-400" />
)
}
sender={notification.pubkey}
sentAt={notification.created_at}
targetEvent={notification}
middle={
parentEventId && (
<ParentNotePreview
eventId={parentEventId}
className=""
onClick={(e) => {
e.stopPropagation()
push(toNote(parentEventId))
}}
/>
)
}
description={
isMention ? t('mentioned you in a note') : parentEventId ? '' : t('quoted your note')
}
isNew={isNew}
showStats
/>
)
}

View File

@@ -0,0 +1,117 @@
import ContentPreview from '@/components/ContentPreview'
import { FormattedTimestamp } from '@/components/FormattedTimestamp'
import NoteStats from '@/components/NoteStats'
import { Skeleton } from '@/components/ui/skeleton'
import UserAvatar from '@/components/UserAvatar'
import Username from '@/components/Username'
import { toNote, toProfile } from '@/lib/link'
import { cn } from '@/lib/utils'
import { useSecondaryPage } from '@/PageManager'
import { useNostr } from '@/providers/NostrProvider'
import { useNotification } from '@/providers/NotificationProvider'
import { NostrEvent } from 'nostr-tools'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
export default function Notification({
icon,
notificationId,
sender,
sentAt,
description,
middle = null,
targetEvent,
isNew = false,
showStats = false
}: {
icon: React.ReactNode
notificationId: string
sender: string
sentAt: number
description: string
middle?: React.ReactNode
targetEvent?: NostrEvent
isNew?: boolean
showStats?: boolean
}) {
const { t } = useTranslation()
const { push } = useSecondaryPage()
const { pubkey } = useNostr()
const { isNotificationRead, markNotificationAsRead } = useNotification()
const unread = useMemo(
() => isNew && !isNotificationRead(notificationId),
[isNew, isNotificationRead, notificationId]
)
return (
<div
className="clickable flex items-start gap-2 cursor-pointer py-2 px-4 border-b"
onClick={() => {
markNotificationAsRead(notificationId)
if (targetEvent) {
push(toNote(targetEvent.id))
} else if (pubkey) {
push(toProfile(pubkey))
}
}}
>
<div className="flex gap-2 items-center mt-1.5">
{icon}
<UserAvatar userId={sender} size="medium" />
</div>
<div className="flex-1 w-0">
<div className="flex items-center justify-between gap-1">
<div className="flex gap-1 items-center">
<Username
userId={sender}
className="flex-1 max-w-fit truncate font-semibold"
skeletonClassName="h-4"
/>
<div className="shrink-0 text-muted-foreground text-sm">{description}</div>
</div>
{unread && (
<button
className="m-0.5 size-3 bg-primary rounded-full shrink-0 transition-all hover:ring-4 hover:ring-primary/20"
title={t('Mark as read')}
onClick={(e) => {
e.stopPropagation()
markNotificationAsRead(notificationId)
}}
/>
)}
</div>
{middle}
{targetEvent && (
<ContentPreview
className={cn('line-clamp-2', !unread && 'text-muted-foreground')}
event={targetEvent}
/>
)}
<FormattedTimestamp timestamp={sentAt} className="shrink-0 text-muted-foreground text-sm" />
{showStats && targetEvent && <NoteStats event={targetEvent} className="mt-1" />}
</div>
</div>
)
}
export function NotificationSkeleton() {
return (
<div className="flex items-start gap-2 cursor-pointer py-2 px-4">
<div className="flex gap-2 items-center mt-1.5">
<Skeleton className="w-6 h-6" />
<Skeleton className="w-9 h-9 rounded-full" />
</div>
<div className="flex-1 w-0">
<div className="py-1">
<Skeleton className="w-16 h-4" />
</div>
<div className="py-1">
<Skeleton className="w-full h-4" />
</div>
<div className="py-1">
<Skeleton className="w-12 h-4" />
</div>
</div>
</div>
)
}

View File

@@ -1,14 +1,10 @@
import { useFetchEvent } from '@/hooks'
import { toNote } from '@/lib/link'
import { generateBech32IdFromETag, tagNameEquals } from '@/lib/tag'
import { cn } from '@/lib/utils'
import { useSecondaryPage } from '@/PageManager'
import { Vote } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useMemo } from 'react'
import ContentPreview from '../../ContentPreview'
import { FormattedTimestamp } from '../../FormattedTimestamp'
import UserAvatar from '../../UserAvatar'
import Notification from './Notification'
import { useTranslation } from 'react-i18next'
export function PollResponseNotification({
notification,
@@ -17,7 +13,7 @@ export function PollResponseNotification({
notification: Event
isNew?: boolean
}) {
const { push } = useSecondaryPage()
const { t } = useTranslation()
const eventId = useMemo(() => {
const eTag = notification.tags.find(tagNameEquals('e'))
return eTag ? generateBech32IdFromETag(eTag) : undefined
@@ -29,19 +25,14 @@ export function PollResponseNotification({
}
return (
<div
className="flex gap-2 items-center cursor-pointer py-2"
onClick={() => push(toNote(pollEvent))}
>
<UserAvatar userId={notification.pubkey} size="small" />
<Vote size={24} className="text-violet-400" />
<ContentPreview
className={cn('truncate flex-1 w-0', isNew ? 'font-semibold' : 'text-muted-foreground')}
event={pollEvent}
/>
<div className="text-muted-foreground">
<FormattedTimestamp timestamp={notification.created_at} short />
</div>
</div>
<Notification
notificationId={notification.id}
icon={<Vote size={24} className="text-violet-400" />}
sender={notification.pubkey}
sentAt={notification.created_at}
targetEvent={pollEvent}
description={t('voted in your poll')}
isNew={isNew}
/>
)
}

View File

@@ -1,16 +1,12 @@
import Image from '@/components/Image'
import { useFetchEvent } from '@/hooks'
import { toNote } from '@/lib/link'
import { generateBech32IdFromETag, tagNameEquals } from '@/lib/tag'
import { cn } from '@/lib/utils'
import { useSecondaryPage } from '@/PageManager'
import { useNostr } from '@/providers/NostrProvider'
import { Heart } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useMemo } from 'react'
import ContentPreview from '../../ContentPreview'
import { FormattedTimestamp } from '../../FormattedTimestamp'
import UserAvatar from '../../UserAvatar'
import { useTranslation } from 'react-i18next'
import Notification from './Notification'
export function ReactionNotification({
notification,
@@ -19,7 +15,7 @@ export function ReactionNotification({
notification: Event
isNew?: boolean
}) {
const { push } = useSecondaryPage()
const { t } = useTranslation()
const { pubkey } = useNostr()
const eventId = useMemo(() => {
const targetPubkey = notification.tags.findLast(tagNameEquals('p'))?.[1]
@@ -58,21 +54,14 @@ export function ReactionNotification({
}
return (
<div
className="flex items-center justify-between cursor-pointer py-2"
onClick={() => push(toNote(event))}
>
<div className="flex gap-2 items-center flex-1">
<UserAvatar userId={notification.pubkey} size="small" />
<div className="text-xl min-w-6 text-center">{reaction}</div>
<ContentPreview
className={cn('truncate flex-1 w-0', isNew ? 'font-semibold' : 'text-muted-foreground')}
event={event}
/>
</div>
<div className="text-muted-foreground">
<FormattedTimestamp timestamp={notification.created_at} short />
</div>
</div>
<Notification
notificationId={notification.id}
icon={<div className="text-xl min-w-6 text-center">{reaction}</div>}
sender={notification.pubkey}
sentAt={notification.created_at}
targetEvent={event}
description={t('reacted to your note')}
isNew={isNew}
/>
)
}

View File

@@ -1,13 +1,9 @@
import { toNote } from '@/lib/link'
import { cn } from '@/lib/utils'
import { useSecondaryPage } from '@/PageManager'
import client from '@/services/client.service'
import { Repeat } from 'lucide-react'
import { Event, validateEvent } from 'nostr-tools'
import { useMemo } from 'react'
import ContentPreview from '../../ContentPreview'
import { FormattedTimestamp } from '../../FormattedTimestamp'
import UserAvatar from '../../UserAvatar'
import { useTranslation } from 'react-i18next'
import Notification from './Notification'
export function RepostNotification({
notification,
@@ -16,7 +12,7 @@ export function RepostNotification({
notification: Event
isNew?: boolean
}) {
const { push } = useSecondaryPage()
const { t } = useTranslation()
const event = useMemo(() => {
try {
const event = JSON.parse(notification.content) as Event
@@ -31,19 +27,14 @@ export function RepostNotification({
if (!event) return null
return (
<div
className="flex gap-2 items-center cursor-pointer py-2"
onClick={() => push(toNote(event))}
>
<UserAvatar userId={notification.pubkey} size="small" />
<Repeat size={24} className="text-green-400" />
<ContentPreview
className={cn('truncate flex-1 w-0', isNew ? 'font-semibold' : 'text-muted-foreground')}
event={event}
/>
<div className="text-muted-foreground">
<FormattedTimestamp timestamp={notification.created_at} short />
</div>
</div>
<Notification
notificationId={notification.id}
icon={<Repeat size={24} className="text-green-400" />}
sender={notification.pubkey}
sentAt={notification.created_at}
targetEvent={event}
description={t('reposted your note')}
isNew={isNew}
/>
)
}

View File

@@ -1,17 +1,11 @@
import { useFetchEvent } from '@/hooks'
import { getZapInfoFromEvent } from '@/lib/event-metadata'
import { formatAmount } from '@/lib/lightning'
import { toNote, toProfile } from '@/lib/link'
import { cn } from '@/lib/utils'
import { useSecondaryPage } from '@/PageManager'
import { useNostr } from '@/providers/NostrProvider'
import { Zap } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import ContentPreview from '../../ContentPreview'
import { FormattedTimestamp } from '../../FormattedTimestamp'
import UserAvatar from '../../UserAvatar'
import Notification from './Notification'
export function ZapNotification({
notification,
@@ -21,38 +15,28 @@ export function ZapNotification({
isNew?: boolean
}) {
const { t } = useTranslation()
const { push } = useSecondaryPage()
const { pubkey } = useNostr()
const { senderPubkey, eventId, amount, comment } = useMemo(
() => getZapInfoFromEvent(notification) ?? ({} as any),
[notification]
)
const { event, isFetching } = useFetchEvent(eventId)
const { event } = useFetchEvent(eventId)
if (!senderPubkey || !amount) return null
return (
<div
className="flex items-center justify-between cursor-pointer py-2"
onClick={() => (eventId ? push(toNote(eventId)) : pubkey ? push(toProfile(pubkey)) : null)}
>
<div className="flex gap-2 items-center flex-1 w-0">
<UserAvatar userId={senderPubkey} size="small" />
<Zap size={24} className="text-yellow-400 shrink-0" />
<Notification
notificationId={notification.id}
icon={<Zap size={24} className="text-yellow-400 shrink-0" />}
sender={senderPubkey}
sentAt={notification.created_at}
targetEvent={event}
middle={
<div className="font-semibold text-yellow-400 shrink-0">
{formatAmount(amount)} {t('sats')}
{formatAmount(amount)} {t('sats')} {comment}
</div>
{comment && <div className="text-yellow-400 truncate">{comment}</div>}
{eventId && !isFetching && (
<ContentPreview
className={cn('truncate flex-1 w-0', isNew ? 'font-semibold' : 'text-muted-foreground')}
event={event}
/>
)}
</div>
<div className="text-muted-foreground shrink-0">
<FormattedTimestamp timestamp={notification.created_at} short />
</div>
</div>
}
description={event ? t('zapped your note') : t('zapped you')}
isNew={isNew}
/>
)
}

View File

@@ -1,6 +1,5 @@
import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'
import { BIG_RELAY_URLS, ExtendedKind } from '@/constants'
import { compareEvents } from '@/lib/event'
import { usePrimaryPage } from '@/PageManager'
import { useNostr } from '@/providers/NostrProvider'
import { useNotification } from '@/providers/NotificationProvider'
@@ -9,30 +8,39 @@ import client from '@/services/client.service'
import noteStatsService from '@/services/note-stats.service'
import { TNotificationType } from '@/types'
import dayjs from 'dayjs'
import { Event, kinds } from 'nostr-tools'
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import { NostrEvent, kinds, matchFilter } from 'nostr-tools'
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState
} from 'react'
import { useTranslation } from 'react-i18next'
import PullToRefresh from 'react-simple-pull-to-refresh'
import Tabs from '../Tabs'
import { NotificationItem } from './NotificationItem'
import { NotificationSkeleton } from './NotificationItem/Notification'
const LIMIT = 100
const SHOW_COUNT = 30
const NotificationList = forwardRef((_, ref) => {
const { t } = useTranslation()
const { current } = usePrimaryPage()
const { current, display } = usePrimaryPage()
const active = useMemo(() => current === 'notifications' && display, [current, display])
const { pubkey } = useNostr()
const { hideUntrustedNotifications, isUserTrusted } = useUserTrust()
const { clearNewNotifications, getNotificationsSeenAt } = useNotification()
const { getNotificationsSeenAt } = useNotification()
const [notificationType, setNotificationType] = useState<TNotificationType>('all')
const [lastReadTime, setLastReadTime] = useState(0)
const [refreshCount, setRefreshCount] = useState(0)
const [timelineKey, setTimelineKey] = useState<string | undefined>(undefined)
const [loading, setLoading] = useState(true)
const [notifications, setNotifications] = useState<Event[]>([])
const [newNotifications, setNewNotifications] = useState<Event[]>([])
const [oldNotifications, setOldNotifications] = useState<Event[]>([])
const [notifications, setNotifications] = useState<NostrEvent[]>([])
const [visibleNotifications, setVisibleNotifications] = useState<NostrEvent[]>([])
const [showCount, setShowCount] = useState(SHOW_COUNT)
const [until, setUntil] = useState<number | undefined>(dayjs().unix())
const bottomRef = useRef<HTMLDivElement | null>(null)
@@ -73,6 +81,25 @@ const NotificationList = forwardRef((_, ref) => {
[loading]
)
const handleNewEvent = useCallback(
(event: NostrEvent) => {
if (event.pubkey === pubkey) return
setNotifications((oldEvents) => {
const index = oldEvents.findIndex((oldEvent) => compareEvents(oldEvent, event) <= 0)
if (index !== -1 && oldEvents[index].id === event.id) {
return oldEvents
}
noteStatsService.updateNoteStatsByEvents([event])
if (index === -1) {
return [...oldEvents, event]
}
return [...oldEvents.slice(0, index), event, ...oldEvents.slice(index)]
})
},
[pubkey]
)
useEffect(() => {
if (current !== 'notifications') return
@@ -86,7 +113,6 @@ const NotificationList = forwardRef((_, ref) => {
setNotifications([])
setShowCount(SHOW_COUNT)
setLastReadTime(getNotificationsSeenAt())
clearNewNotifications()
const relayList = await client.fetchRelayList(pubkey)
const { closer, timelineKey } = await client.subscribeTimeline(
@@ -112,17 +138,7 @@ const NotificationList = forwardRef((_, ref) => {
}
},
onNew: (event) => {
if (event.pubkey === pubkey) return
setNotifications((oldEvents) => {
const index = oldEvents.findIndex(
(oldEvent) => oldEvent.created_at < event.created_at
)
if (index === -1) {
return [...oldEvents, event]
}
return [...oldEvents.slice(0, index), event, ...oldEvents.slice(index)]
})
noteStatsService.updateNoteStatsByEvents([event])
handleNewEvent(event)
}
}
)
@@ -136,21 +152,39 @@ const NotificationList = forwardRef((_, ref) => {
}
}, [pubkey, refreshCount, filterKinds, current])
useEffect(() => {
if (!active || !pubkey) return
const handler = (data: Event) => {
const customEvent = data as CustomEvent<NostrEvent>
const evt = customEvent.detail
if (
matchFilter(
{
kinds: filterKinds,
'#p': [pubkey]
},
evt
)
) {
handleNewEvent(evt)
}
}
client.addEventListener('newEvent', handler)
return () => {
client.removeEventListener('newEvent', handler)
}
}, [pubkey, active, filterKinds, handleNewEvent])
useEffect(() => {
let visibleNotifications = notifications.slice(0, showCount)
if (hideUntrustedNotifications) {
visibleNotifications = visibleNotifications.filter((event) => isUserTrusted(event.pubkey))
}
const index = visibleNotifications.findIndex((event) => event.created_at <= lastReadTime)
if (index === -1) {
setNewNotifications(visibleNotifications)
setOldNotifications([])
} else {
setNewNotifications(visibleNotifications.slice(0, index))
setOldNotifications(visibleNotifications.slice(index))
}
}, [notifications, lastReadTime, showCount, hideUntrustedNotifications, isUserTrusted])
setVisibleNotifications(visibleNotifications)
}, [notifications, showCount, hideUntrustedNotifications, isUserTrusted])
useEffect(() => {
const options = {
@@ -228,28 +262,18 @@ const NotificationList = forwardRef((_, ref) => {
}}
pullingContent=""
>
<div className="px-4 pt-2">
{newNotifications.map((notification) => (
<NotificationItem key={notification.id} notification={notification} isNew />
))}
{!!newNotifications.length && (
<div className="relative my-2">
<Separator />
<span className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-background px-2 text-xs text-muted-foreground">
{t('Earlier notifications')}
</span>
</div>
)}
{oldNotifications.map((notification) => (
<NotificationItem key={notification.id} notification={notification} />
<div>
{visibleNotifications.map((notification) => (
<NotificationItem
key={notification.id}
notification={notification}
isNew={notification.created_at > lastReadTime}
/>
))}
<div className="text-center text-sm text-muted-foreground">
{until || loading ? (
<div ref={bottomRef}>
<div className="flex gap-2 items-center h-11 py-2">
<Skeleton className="w-7 h-7 rounded-full" />
<Skeleton className="h-6 flex-1 w-0" />
</div>
<NotificationSkeleton />
</div>
) : (
t('no more notifications')

View File

@@ -125,9 +125,9 @@ export default function ReplyNoteList({ index, event }: { index?: number; event:
}
}
client.addEventListener('eventPublished', handleEventPublished)
client.addEventListener('newEvent', handleEventPublished)
return () => {
client.removeEventListener('eventPublished', handleEventPublished)
client.removeEventListener('newEvent', handleEventPublished)
}
}, [rootInfo, onNewReply])

View File

@@ -375,6 +375,14 @@ export default {
'اكتب للبحث عن أشخاص، كلمات مفتاحية، أو ريلايات',
'Hide content mentioning muted users': 'إخفاء المحتوى الذي يذكر المستخدمين المكتومين',
'This note mentions a user you muted': 'هذه الملاحظة تذكر مستخدماً قمت بكتمه',
Filter: 'مرشح'
Filter: 'مرشح',
'mentioned you in a note': 'ذكرك في ملاحظة',
'quoted your note': 'اقتبس ملاحظتك',
'voted in your poll': 'صوت في استطلاعك',
'reacted to your note': 'تفاعل مع ملاحظتك',
'reposted your note': 'أعاد نشر ملاحظتك',
'zapped your note': 'زاب ملاحظتك',
'zapped you': 'زابك',
'Mark as read': 'تعليم كمقروء'
}
}

View File

@@ -384,6 +384,14 @@ export default {
'Hide content mentioning muted users': 'Inhalte ausblenden, die stumme Benutzer erwähnen',
'This note mentions a user you muted':
'Diese Notiz erwähnt einen Benutzer, den Sie stumm geschaltet haben',
Filter: 'Filter'
Filter: 'Filter',
'mentioned you in a note': 'hat Sie in einer Notiz erwähnt',
'quoted your note': 'hat Ihre Notiz zitiert',
'voted in your poll': 'hat in Ihrer Umfrage abgestimmt',
'reacted to your note': 'hat auf Ihre Notiz reagiert',
'reposted your note': 'hat Ihre Notiz geteilt',
'zapped your note': 'hat Ihre Notiz gezappt',
'zapped you': 'hat Sie gezappt',
'Mark as read': 'Als gelesen markieren'
}
}

View File

@@ -374,6 +374,14 @@ export default {
'Type searching for people, keywords, or relays',
'Hide content mentioning muted users': 'Hide content mentioning muted users',
'This note mentions a user you muted': 'This note mentions a user you muted',
Filter: 'Filter'
Filter: 'Filter',
'mentioned you in a note': 'mentioned you in a note',
'quoted your note': 'quoted your note',
'voted in your poll': 'voted in your poll',
'reacted to your note': 'reacted to your note',
'reposted your note': 'reposted your note',
'zapped your note': 'zapped your note',
'zapped you': 'zapped you',
'Mark as read': 'Mark as read'
}
}

View File

@@ -380,6 +380,14 @@ export default {
'Escribe para buscar personas, palabras clave o relés',
'Hide content mentioning muted users': 'Ocultar contenido que mencione usuarios silenciados',
'This note mentions a user you muted': 'Esta nota menciona a un usuario que silenciaste',
Filter: 'Filtro'
Filter: 'Filtro',
'mentioned you in a note': 'te mencionó en una nota',
'quoted your note': 'citó tu nota',
'voted in your poll': 'votó en tu encuesta',
'reacted to your note': 'reaccionó a tu nota',
'reposted your note': 'reposteó tu nota',
'zapped your note': 'zappeó tu nota',
'zapped you': 'te zappeó',
'Mark as read': 'Marcar como leído'
}
}

View File

@@ -376,6 +376,14 @@ export default {
'برای جستجو افراد، کلمات کلیدی یا رله‌ها تایپ کنید',
'Hide content mentioning muted users': 'مخفی کردن محتوای اشاره کننده به کاربران بی‌صدا شده',
'This note mentions a user you muted': 'این یادداشت به کاربری که بی‌صدا کرده‌اید اشاره می‌کند',
Filter: 'فیلتر'
Filter: 'فیلتر',
'mentioned you in a note': 'در یادداشتی از شما نام برد',
'quoted your note': 'یادداشت شما را نقل قول کرد',
'voted in your poll': 'در نظرسنجی شما رأی داد',
'reacted to your note': 'به یادداشت شما واکنش نشان داد',
'reposted your note': 'یادداشت شما را بازنشر کرد',
'zapped your note': 'یادداشت شما را زپ کرد',
'zapped you': 'شما را زپ کرد',
'Mark as read': 'علامت‌گذاری به عنوان خوانده شده'
}
}

View File

@@ -384,6 +384,14 @@ export default {
'Masquer le contenu mentionnant des utilisateurs masqués',
'This note mentions a user you muted':
'Cette note mentionne un utilisateur que vous avez masqué',
Filter: 'Filtre'
Filter: 'Filtre',
'mentioned you in a note': 'vous a mentionné dans une note',
'quoted your note': 'a cité votre note',
'voted in your poll': 'a voté dans votre sondage',
'reacted to your note': 'a réagi à votre note',
'reposted your note': 'a repartagé votre note',
'zapped your note': 'a zappé votre note',
'zapped you': 'vous a zappé',
'Mark as read': 'Marquer comme lu'
}
}

View File

@@ -380,6 +380,14 @@ export default {
'Digita per cercare persone, parole chiave o relays',
'Hide content mentioning muted users': 'Nascondi contenuto che menziona utenti silenziati',
'This note mentions a user you muted': 'Questa nota menziona un utente che hai silenziato',
Filter: 'Filtro'
Filter: 'Filtro',
'mentioned you in a note': 'ti ha menzionato in una nota',
'quoted your note': 'ha citato la tua nota',
'voted in your poll': 'ha votato nel tuo sondaggio',
'reacted to your note': 'ha reagito alla tua nota',
'reposted your note': 'ha ricondiviso la tua nota',
'zapped your note': 'ha zappato la tua nota',
'zapped you': 'ti ha zappato',
'Mark as read': 'Segna come letto'
}
}

View File

@@ -377,6 +377,14 @@ export default {
'人、キーワード、またはリレーを検索するために入力してください',
'Hide content mentioning muted users': 'ミュートしたユーザーを言及するコンテンツを非表示',
'This note mentions a user you muted': 'このノートはミュートしたユーザーを言及しています',
Filter: 'フィルター'
Filter: 'フィルター',
'mentioned you in a note': 'ノートであなたに言及しました',
'quoted your note': 'あなたのノートを引用しました',
'voted in your poll': 'あなたの投票に投票しました',
'reacted to your note': 'あなたのノートにリアクションしました',
'reposted your note': 'あなたのノートをリポストしました',
'zapped your note': 'あなたのノートにザップしました',
'zapped you': 'あなたにザップしました',
'Mark as read': '既読にする'
}
}

View File

@@ -377,6 +377,14 @@ export default {
'사람, 키워드 또는 릴레이를 검색하려면 입력하세요',
'Hide content mentioning muted users': '뮤트된 사용자를 언급하는 콘텐츠 숨기기',
'This note mentions a user you muted': '이 노트는 뮤트한 사용자를 언급합니다',
Filter: '필터'
Filter: '필터',
'mentioned you in a note': '노트에서 당신을 언급했습니다',
'quoted your note': '당신의 노트를 인용했습니다',
'voted in your poll': '당신의 투표에 참여했습니다',
'reacted to your note': '당신의 노트에 반응했습니다',
'reposted your note': '당신의 노트를 리포스트했습니다',
'zapped your note': '당신의 노트를 잽했습니다',
'zapped you': '당신을 잽했습니다',
'Mark as read': '읽음으로 표시'
}
}

View File

@@ -381,6 +381,14 @@ export default {
'Wpisz, aby wyszukać osoby, słowa kluczowe lub przekaźniki',
'Hide content mentioning muted users': 'Ukryj treści wspominające wyciszonych użytkowników',
'This note mentions a user you muted': 'Ten wpis wspomina użytkownika, którego wyciszyłeś',
Filter: 'Filtr'
Filter: 'Filtr',
'mentioned you in a note': 'wspomniał o tobie w notatce',
'quoted your note': 'zacytował twoją notatkę',
'voted in your poll': 'zagłosował w twojej ankiecie',
'reacted to your note': 'zareagował na twoją notatkę',
'reposted your note': 'przepostował twoją notatkę',
'zapped your note': 'zappował twoją notatkę',
'zapped you': 'zappował cię',
'Mark as read': 'Oznacz jako przeczytane'
}
}

View File

@@ -377,6 +377,14 @@ export default {
'Digite para buscar pessoas, palavras-chave ou relays',
'Hide content mentioning muted users': 'Ocultar conteúdo que menciona usuários silenciados',
'This note mentions a user you muted': 'Esta nota menciona um usuário que você silenciou',
Filter: 'Filtro'
Filter: 'Filtro',
'mentioned you in a note': 'mencionou você em uma nota',
'quoted your note': 'citou sua nota',
'voted in your poll': 'votou na sua enquete',
'reacted to your note': 'reagiu à sua nota',
'reposted your note': 'republicou sua nota',
'zapped your note': 'zappeou sua nota',
'zapped you': 'zappeou você',
'Mark as read': 'Marcar como lida'
}
}

View File

@@ -380,6 +380,14 @@ export default {
'Digite para buscar pessoas, palavras-chave ou relays',
'Hide content mentioning muted users': 'Ocultar conteúdo que menciona utilizadores silenciados',
'This note mentions a user you muted': 'Esta nota menciona um utilizador que silenciou',
Filter: 'Filtro'
Filter: 'Filtro',
'mentioned you in a note': 'mencionou-o numa nota',
'quoted your note': 'citou a sua nota',
'voted in your poll': 'votou na sua sondagem',
'reacted to your note': 'reagiu à sua nota',
'reposted your note': 'republicou a sua nota',
'zapped your note': 'zappeou a sua nota',
'zapped you': 'zappeou-o',
'Mark as read': 'Marcar como lida'
}
}

View File

@@ -381,6 +381,14 @@ export default {
'Hide content mentioning muted users': 'Скрыть контент, упоминающий заглушённых пользователей',
'This note mentions a user you muted':
'Эта заметка упоминает пользователя, которого вы заглушили',
Filter: 'Фильтр'
Filter: 'Фильтр',
'mentioned you in a note': 'упомянул вас в заметке',
'quoted your note': 'процитировал вашу заметку',
'voted in your poll': 'проголосовал в вашем опросе',
'reacted to your note': 'отреагировал на вашу заметку',
'reposted your note': 'репостнул вашу заметку',
'zapped your note': 'заппил вашу заметку',
'zapped you': 'заппил вас',
'Mark as read': 'Отметить как прочитанное'
}
}

View File

@@ -372,6 +372,14 @@ export default {
'Type searching for people, keywords, or relays': 'พิมพ์เพื่อค้นหาผู้คน คีย์เวิร์ด หรือรีเลย์',
'Hide content mentioning muted users': 'ซ่อนเนื้อหาที่กล่าวถึงผู้ใช้ที่ปิดเสียง',
'This note mentions a user you muted': 'โน้ตนี้กล่าวถึงผู้ใช้ที่คุณปิดเสียง',
Filter: 'ตัวกรอง'
Filter: 'ตัวกรอง',
'mentioned you in a note': 'ได้กล่าวถึงคุณในโน้ต',
'quoted your note': 'ได้ยกคำพูดจากโน้ตของคุณ',
'voted in your poll': 'ได้โหวตในการสำรวจของคุณ',
'reacted to your note': 'ได้แสดงปฏิกิริยาต่อโน้ตของคุณ',
'reposted your note': 'ได้รีโพสต์โน้ตของคุณ',
'zapped your note': 'ได้แซปโน้ตของคุณ',
'zapped you': 'ได้แซปคุณ',
'Mark as read': 'ทำเครื่องหมายว่าอ่านแล้ว'
}
}

View File

@@ -370,6 +370,14 @@ export default {
'Type searching for people, keywords, or relays': '输入以搜索用户、关键词或服务器',
'Hide content mentioning muted users': '隐藏提及已屏蔽用户的内容',
'This note mentions a user you muted': '此笔记提及了您已屏蔽的用户',
Filter: '过滤器'
Filter: '过滤器',
'mentioned you in a note': '在笔记中提及了您',
'quoted your note': '引用了您的笔记',
'voted in your poll': '在您的投票中投票',
'reacted to your note': '对您的笔记做出了反应',
'reposted your note': '转发了您的笔记',
'zapped your note': '打闪了您的笔记',
'zapped you': '给您打闪',
'Mark as read': '标记为已读'
}
}

View File

@@ -80,7 +80,7 @@ type TNostrContext = {
updateMuteListEvent: (muteListEvent: Event, privateTags: string[][]) => Promise<void>
updateBookmarkListEvent: (bookmarkListEvent: Event) => Promise<void>
updateFavoriteRelaysEvent: (favoriteRelaysEvent: Event) => Promise<void>
updateNotificationsSeenAt: () => Promise<void>
updateNotificationsSeenAt: (skipPublish?: boolean) => Promise<void>
}
const NostrContext = createContext<TNostrContext | undefined>(undefined)
@@ -711,7 +711,7 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
setFavoriteRelaysEvent(newFavoriteRelaysEvent)
}
const updateNotificationsSeenAt = async () => {
const updateNotificationsSeenAt = async (skipPublish = false) => {
if (!account) return
const now = dayjs().unix()
@@ -724,8 +724,9 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
const lastPublishedSeenNotificationsAtEventAt =
lastPublishedSeenNotificationsAtEventAtMap.get(account.pubkey) ?? -1
if (
lastPublishedSeenNotificationsAtEventAt < 0 ||
now - lastPublishedSeenNotificationsAtEventAt > 10 * 60 // 10 minutes
!skipPublish &&
(lastPublishedSeenNotificationsAtEventAt < 0 ||
now - lastPublishedSeenNotificationsAtEventAt > 10 * 60) // 10 minutes
) {
await publish(createSeenNotificationsAtDraftEvent())
lastPublishedSeenNotificationsAtEventAtMap.set(account.pubkey, now)

View File

@@ -1,9 +1,11 @@
import { BIG_RELAY_URLS, ExtendedKind } from '@/constants'
import { isMentioningMutedUsers } from '@/lib/event'
import { compareEvents, isMentioningMutedUsers } from '@/lib/event'
import { usePrimaryPage } from '@/PageManager'
import client from '@/services/client.service'
import { kinds } from 'nostr-tools'
import storage from '@/services/local-storage.service'
import { kinds, NostrEvent } from 'nostr-tools'
import { SubCloser } from 'nostr-tools/abstract-pool'
import { createContext, useContext, useEffect, useRef, useState } from 'react'
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { useContentPolicy } from './ContentPolicyProvider'
import { useMuteList } from './MuteListProvider'
import { useNostr } from './NostrProvider'
@@ -12,7 +14,8 @@ import { useUserTrust } from './UserTrustProvider'
type TNotificationContext = {
hasNewNotification: boolean
getNotificationsSeenAt: () => number
clearNewNotifications: () => Promise<void>
isNotificationRead: (id: string) => boolean
markNotificationAsRead: (id: string) => void
}
const NotificationContext = createContext<TNotificationContext | undefined>(undefined)
@@ -26,25 +29,69 @@ export const useNotification = () => {
}
export function NotificationProvider({ children }: { children: React.ReactNode }) {
const { current } = usePrimaryPage()
const active = useMemo(() => current === 'notifications', [current])
const { pubkey, notificationsSeenAt, updateNotificationsSeenAt } = useNostr()
const { hideUntrustedNotifications, isUserTrusted } = useUserTrust()
const { mutePubkeySet } = useMuteList()
const { hideContentMentioningMutedUsers } = useContentPolicy()
const [newNotificationIds, setNewNotificationIds] = useState(new Set<string>())
const subCloserRef = useRef<SubCloser | null>(null)
const [newNotifications, setNewNotifications] = useState<NostrEvent[]>([])
const [readNotificationIdSet, setReadNotificationIdSet] = useState<Set<string>>(new Set())
const filteredNewNotifications = useMemo(() => {
if (active || notificationsSeenAt < 0) {
return []
}
const filtered: NostrEvent[] = []
for (const notification of newNotifications) {
if (notification.created_at <= notificationsSeenAt || filtered.length >= 10) {
break
}
if (
mutePubkeySet.has(notification.pubkey) ||
(hideContentMentioningMutedUsers && isMentioningMutedUsers(notification, mutePubkeySet)) ||
(hideUntrustedNotifications && !isUserTrusted(notification.pubkey))
) {
continue
}
filtered.push(notification)
}
return filtered
}, [
newNotifications,
notificationsSeenAt,
mutePubkeySet,
hideContentMentioningMutedUsers,
hideUntrustedNotifications,
isUserTrusted,
active
])
useEffect(() => {
if (!pubkey || notificationsSeenAt < 0) return
setNewNotifications([])
updateNotificationsSeenAt(!active)
}, [active])
setNewNotificationIds(new Set())
useEffect(() => {
if (!pubkey) return
setNewNotifications([])
setReadNotificationIdSet(new Set())
// Track if component is mounted
const isMountedRef = { current: true }
const subCloserRef: {
current: SubCloser | null
} = { current: null }
const subscribe = async () => {
if (subCloserRef.current) {
subCloserRef.current.close()
subCloserRef.current = null
}
if (!isMountedRef.current) return null
try {
let eosed = false
const relayList = await client.fetchRelayList(pubkey)
const relayUrls = relayList.read.concat(BIG_RELAY_URLS).slice(0, 4)
const subCloser = client.subscribe(
@@ -53,32 +100,39 @@ export function NotificationProvider({ children }: { children: React.ReactNode }
{
kinds: [
kinds.ShortTextNote,
kinds.Reaction,
kinds.Repost,
kinds.Reaction,
kinds.Zap,
ExtendedKind.COMMENT,
ExtendedKind.POLL_RESPONSE,
ExtendedKind.VOICE_COMMENT
ExtendedKind.VOICE_COMMENT,
ExtendedKind.POLL
],
'#p': [pubkey],
since: notificationsSeenAt,
limit: 20
}
],
{
oneose: (e) => {
if (e) {
eosed = e
setNewNotifications((prev) => {
return [...prev.sort((a, b) => compareEvents(b, a))]
})
}
},
onevent: (evt) => {
// Only show notification if not from self and not muted
if (
evt.pubkey !== pubkey &&
!mutePubkeySet.has(evt.pubkey) &&
(!hideContentMentioningMutedUsers || !isMentioningMutedUsers(evt, mutePubkeySet)) &&
(!hideUntrustedNotifications || isUserTrusted(evt.pubkey))
) {
setNewNotificationIds((prev) => {
if (prev.has(evt.id)) {
if (evt.pubkey !== pubkey) {
setNewNotifications((prev) => {
if (!eosed) {
return [evt, ...prev]
}
if (prev.length && compareEvents(prev[0], evt) >= 0) {
return prev
}
return new Set([...prev, evt.id])
client.emitNewEvent(evt)
return [evt, ...prev]
})
}
},
@@ -88,7 +142,7 @@ export function NotificationProvider({ children }: { children: React.ReactNode }
}
// Only reconnect if still mounted and not a manual close
if (isMountedRef.current && subCloserRef.current) {
if (isMountedRef.current) {
setTimeout(() => {
if (isMountedRef.current) {
subscribe()
@@ -127,17 +181,10 @@ export function NotificationProvider({ children }: { children: React.ReactNode }
subCloserRef.current = null
}
}
}, [notificationsSeenAt, pubkey])
}, [pubkey])
useEffect(() => {
if (newNotificationIds.size >= 10 && subCloserRef.current) {
subCloserRef.current.close()
subCloserRef.current = null
}
}, [newNotificationIds])
useEffect(() => {
const newNotificationCount = newNotificationIds.size
const newNotificationCount = filteredNewNotifications.length
// Update title
if (newNotificationCount > 0) {
@@ -175,30 +222,33 @@ export function NotificationProvider({ children }: { children: React.ReactNode }
})
}
}
}, [newNotificationIds])
}, [filteredNewNotifications])
const getNotificationsSeenAt = () => {
return notificationsSeenAt
if (notificationsSeenAt >= 0) {
return notificationsSeenAt
}
if (pubkey) {
return storage.getLastReadNotificationTime(pubkey)
}
return 0
}
const clearNewNotifications = async () => {
if (!pubkey) return
const isNotificationRead = (notificationId: string): boolean => {
return readNotificationIdSet.has(notificationId)
}
if (subCloserRef.current) {
subCloserRef.current.close()
subCloserRef.current = null
}
setNewNotificationIds(new Set())
await updateNotificationsSeenAt()
const markNotificationAsRead = (notificationId: string): void => {
setReadNotificationIdSet((prev) => new Set([...prev, notificationId]))
}
return (
<NotificationContext.Provider
value={{
hasNewNotification: newNotificationIds.size > 0,
clearNewNotifications,
getNotificationsSeenAt
hasNewNotification: filteredNewNotifications.length > 0,
getNotificationsSeenAt,
isNotificationRead,
markNotificationAsRead
}}
>
{children}

View File

@@ -164,7 +164,7 @@ class ClientService extends EventTarget {
})
})
)
this.dispatchEvent(new CustomEvent('eventPublished', { detail: event }))
this.emitNewEvent(event)
return result
} catch (error) {
if (error instanceof AggregateError) {
@@ -174,6 +174,10 @@ class ClientService extends EventTarget {
}
}
emitNewEvent(event: NEvent) {
this.dispatchEvent(new CustomEvent('newEvent', { detail: event }))
}
async signHttpAuth(url: string, method: string, description = '') {
if (!this.signer) {
throw new Error('Please login first to sign the event')