feat: following's favoriate relays

This commit is contained in:
codytseng
2025-04-06 00:34:32 +08:00
parent 328477a1f3
commit 1e6e37f5e5
18 changed files with 280 additions and 37 deletions

View File

@@ -0,0 +1,96 @@
import { toRelay } from '@/lib/link'
import { useSecondaryPage } from '@/PageManager'
import { useNostr } from '@/providers/NostrProvider'
import client from '@/services/client.service'
import relayInfoService from '@/services/relay-info.service'
import { TNip66RelayInfo } from '@/types'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import RelaySimpleInfo, { RelaySimpleInfoSkeleton } from '../RelaySimpleInfo'
const SHOW_COUNT = 10
export default function FollowingFavoriteRelayList() {
const { t } = useTranslation()
const { push } = useSecondaryPage()
const { pubkey } = useNostr()
const [loading, setLoading] = useState(true)
const [relays, setRelays] = useState<(TNip66RelayInfo & { users: string[] })[]>([])
const [showCount, setShowCount] = useState(SHOW_COUNT)
const bottomRef = useRef<HTMLDivElement>(null)
useEffect(() => {
setLoading(true)
const init = async () => {
if (!pubkey) return
const relayMap =
(await client.fetchFollowingFavoriteRelays(pubkey)) ?? new Map<string, Set<string>>()
const relayUrls = Array.from(relayMap.keys())
const relayInfos = await relayInfoService.getRelayInfos(relayUrls ?? [])
setRelays(
(relayInfos.filter(Boolean) as TNip66RelayInfo[])
.map((relayInfo) => {
const users = Array.from(relayMap.get(relayInfo.url) ?? [])
return {
...relayInfo,
users
}
})
.sort((a, b) => b.users.length - a.users.length)
)
}
init().finally(() => {
setLoading(false)
})
}, [pubkey])
useEffect(() => {
const options = {
root: null,
rootMargin: '10px',
threshold: 1
}
const observerInstance = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && showCount < relays.length) {
setShowCount((prev) => prev + SHOW_COUNT)
}
}, options)
const currentBottomRef = bottomRef.current
if (currentBottomRef) {
observerInstance.observe(currentBottomRef)
}
return () => {
if (observerInstance && currentBottomRef) {
observerInstance.unobserve(currentBottomRef)
}
}
}, [showCount, relays])
return (
<div>
{relays.slice(0, showCount).map((relay) => (
<RelaySimpleInfo
key={relay.url}
relayInfo={relay}
className="clickable p-4 border-b"
onClick={(e) => {
e.stopPropagation()
push(toRelay(relay.url))
}}
/>
))}
{showCount < relays.length && <div ref={bottomRef} />}
{loading && <RelaySimpleInfoSkeleton />}
{!loading && (
<div className="text-center text-muted-foreground text-sm mt-2">
{relays.length === 0 ? t('no relays found') : t('no more relays')}
</div>
)}
</div>
)
}

View File

@@ -1,11 +1,10 @@
import { Skeleton } from '@/components/ui/skeleton'
import { toRelay } from '@/lib/link'
import { useSecondaryPage } from '@/PageManager'
import relayInfoService from '@/services/relay-info.service'
import { TNip66RelayInfo } from '@/types'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import RelaySimpleInfo from '../RelaySimpleInfo'
import RelaySimpleInfo, { RelaySimpleInfoSkeleton } from '../RelaySimpleInfo'
import SearchInput from '../SearchInput'
export default function RelayList() {
@@ -69,7 +68,7 @@ export default function RelayList() {
return (
<div>
<div className="px-4 py-2 sticky top-12 bg-background z-30">
<div className="px-4 py-2">
<SearchInput placeholder={t('Search relays')} value={input} onChange={handleInputChange} />
</div>
{relays.slice(0, showCount).map((relay) => (
@@ -84,22 +83,7 @@ export default function RelayList() {
/>
))}
{showCount < relays.length && <div ref={bottomRef} />}
{loading && (
<div className="p-4 space-y-2">
<div className="flex items-start justify-between gap-2 w-full">
<div className="flex flex-1 w-0 items-center gap-2">
<Skeleton className="h-9 w-9 rounded-full" />
<div className="flex-1 w-0 space-y-1">
<Skeleton className="w-40 h-5" />
<Skeleton className="w-20 h-4" />
</div>
</div>
<Skeleton className="w-5 h-5 rounded-lg" />
</div>
<Skeleton className="w-full h-4" />
<Skeleton className="w-2/3 h-4" />
</div>
)}
{loading && <RelaySimpleInfoSkeleton />}
{!loading && relays.length === 0 && (
<div className="text-center text-muted-foreground text-sm">{t('no relays found')}</div>
)}

View File

@@ -1,9 +1,12 @@
import { Skeleton } from '@/components/ui/skeleton'
import { cn } from '@/lib/utils'
import { TNip66RelayInfo } from '@/types'
import { HTMLProps } from 'react'
import { useTranslation } from 'react-i18next'
import RelayBadges from '../RelayBadges'
import RelayIcon from '../RelayIcon'
import SaveRelayDropdownMenu from '../SaveRelayDropdownMenu'
import { HTMLProps } from 'react'
import { SimpleUserAvatar } from '../UserAvatar'
export default function RelaySimpleInfo({
relayInfo,
@@ -11,9 +14,11 @@ export default function RelaySimpleInfo({
className,
...props
}: HTMLProps<HTMLDivElement> & {
relayInfo?: TNip66RelayInfo
relayInfo?: TNip66RelayInfo & { users?: string[] }
hideBadge?: boolean
}) {
const { t } = useTranslation()
return (
<div className={cn('space-y-1', className)} {...props}>
<div className="flex items-start justify-between gap-2 w-full">
@@ -30,6 +35,37 @@ export default function RelaySimpleInfo({
</div>
{!hideBadge && relayInfo && <RelayBadges relayInfo={relayInfo} />}
{!!relayInfo?.description && <div className="line-clamp-4">{relayInfo.description}</div>}
{!!relayInfo?.users?.length && (
<div className="flex items-center gap-2">
<div className="text-muted-foreground">{t('Favorited by')} </div>
<div className="flex items-center gap-1">
{relayInfo.users.slice(0, 10).map((user) => (
<SimpleUserAvatar key={user} userId={user} size="xSmall" />
))}
{relayInfo.users.length > 10 && (
<div className="text-muted-foreground text-xs rounded-full bg-muted w-5 h-5 flex items-center justify-center">
+{relayInfo.users.length - 10}
</div>
)}
</div>
</div>
)}
</div>
)
}
export function RelaySimpleInfoSkeleton() {
return (
<div className="p-4 space-y-2">
<div className="flex items-center gap-2 w-full">
<Skeleton className="h-9 w-9 rounded-full" />
<div className="flex-1 w-0 space-y-1">
<Skeleton className="w-40 h-5" />
<Skeleton className="w-20 h-4" />
</div>
</div>
<Skeleton className="w-full h-4" />
<Skeleton className="w-2/3 h-4" />
</div>
)
}

View File

@@ -203,6 +203,9 @@ export default {
'Not found the note': 'لم يتم العثور على الملاحظة',
'no more replies': 'لا توجد مزيد من الردود',
'Relay sets': 'مجموعات الريلاي',
'Favorite Relays': 'الريلايات المفضلة'
'Favorite Relays': 'الريلايات المفضلة',
"Following's Favorites": 'المفضلات من المتابعين',
'no more relays': 'لا توجد مزيد من الريلايات',
'Favorited by': 'المفضلة من قبل'
}
}

View File

@@ -207,6 +207,9 @@ export default {
'Not found the note': 'Die Notiz wurde nicht gefunden',
'no more replies': 'keine weiteren Antworten',
'Relay sets': 'Relay-Sets',
'Favorite Relays': 'Lieblings-Relays'
'Favorite Relays': 'Lieblings-Relays',
"Following's Favorites": 'Favoriten der Folgenden',
'no more relays': 'keine weiteren Relays',
'Favorited by': 'Favorisiert von'
}
}

View File

@@ -203,6 +203,9 @@ export default {
'Not found the note': 'Not found the note',
'no more replies': 'no more replies',
'Relay sets': 'Relay sets',
'Favorite Relays': 'Favorite Relays'
'Favorite Relays': 'Favorite Relays',
"Following's Favorites": "Following's Favorites",
'no more relays': 'no more relays',
'Favorited by': 'Favorited by'
}
}

View File

@@ -206,6 +206,9 @@ export default {
'Not found the note': 'No se encontró la nota',
'no more replies': 'no hay más respuestas',
'Relay sets': 'Conjuntos de relés',
'Favorite Relays': 'Relés favoritos'
'Favorite Relays': 'Relés favoritos',
"Following's Favorites": 'Favoritos de los seguidos',
'no more relays': 'no hay más relés',
'Favorited by': 'Favoritado por'
}
}

View File

@@ -206,6 +206,9 @@ export default {
'Not found the note': 'Note introuvable',
'no more replies': 'aucune autre réponse',
'Relay sets': 'Groupes de relais',
'Favorite Relays': 'Relais favoris'
'Favorite Relays': 'Relais favoris',
"Following's Favorites": "Following's Favorites",
'no more relays': 'aucun autre relais',
'Favorited by': 'Favorisé par'
}
}

View File

@@ -206,6 +206,9 @@ export default {
'Not found the note': 'Non è stata trovata la nota',
'no more replies': 'niente più repliche',
'Relay sets': 'Set di Relay',
'Favorite Relays': 'Relay preferiti'
'Favorite Relays': 'Relay preferiti',
"Following's Favorites": 'Preferiti dei seguiti',
'no more relays': 'niente più relay',
'Favorited by': 'Preferito da'
}
}

View File

@@ -204,6 +204,9 @@ export default {
'Not found the note': 'ノートが見つかりません',
'no more replies': 'これ以上の返信はありません',
'Relay sets': 'リレイセット',
'Favorite Relays': 'お気に入りのリレイ'
'Favorite Relays': 'お気に入りのリレイ',
"Following's Favorites": 'フォロー中のお気に入り',
'no more relays': 'これ以上のリレイはありません',
'Favorited by': 'お気に入り'
}
}

View File

@@ -205,6 +205,9 @@ export default {
'Not found the note': 'Nie znaleziono wpisu',
'no more replies': 'brak kolejnych odpowiedzi',
'Relay sets': 'Zestawy transmiterów',
'Favorite Relays': 'Ulubione transmitery'
'Favorite Relays': 'Ulubione transmitery',
"Following's Favorites": 'Ulubione transmitery obserwowanych',
'no more relays': 'brak kolejnych transmiterów',
'Favorited by': 'Ulubione przez'
}
}

View File

@@ -205,6 +205,9 @@ export default {
'Not found the note': 'Nota não encontrada',
'no more replies': 'não há mais respostas',
'Relay sets': 'Conjuntos de relé',
'Favorite Relays': 'Relés favoritos'
'Favorite Relays': 'Relés favoritos',
"Following's Favorites": 'Favoritos de quem você segue',
'no more relays': 'não há mais relés',
'Favorited by': 'Favoritado por'
}
}

View File

@@ -206,6 +206,9 @@ export default {
'Not found the note': 'Nota não encontrada',
'no more replies': 'não há mais respostas',
'Relay sets': 'Conjuntos de Relé',
'Favorite Relays': 'Relés Favoritos'
'Favorite Relays': 'Relés Favoritos',
"Following's Favorites": 'Favoritos de quem você segue',
'no more relays': 'não há mais relés',
'Favorited by': 'Favoritado por'
}
}

View File

@@ -207,6 +207,9 @@ export default {
'Not found the note': 'Заметка не найдена',
'no more replies': 'больше нет ответов',
'Relay sets': 'Наборы ретрансляторов',
'Favorite Relays': 'Избранные ретрансляторы'
'Favorite Relays': 'Избранные ретрансляторы',
"Following's Favorites": 'Избранные ретрансляторы подписчиков',
'no more relays': 'больше нет ретрансляторов',
'Favorited by': 'Избранные у'
}
}

View File

@@ -204,6 +204,9 @@ export default {
'Not found the note': '未找到该笔记',
'no more replies': '没有更多回复了',
'Relay sets': '服务器组',
'Favorite Relays': '收藏的服务器'
'Favorite Relays': '收藏的服务器',
"Following's Favorites": '关注人的收藏',
'no more relays': '没有更多服务器了',
'Favorited by': '收藏自'
}
}

View File

@@ -1,10 +1,17 @@
import FollowingFavoriteRelayList from '@/components/FollowingFavoriteRelayList'
import RelayList from '@/components/RelayList'
import PrimaryPageLayout from '@/layouts/PrimaryPageLayout'
import { cn } from '@/lib/utils'
import { useDeepBrowsing } from '@/providers/DeepBrowsingProvider'
import { Compass } from 'lucide-react'
import { forwardRef } from 'react'
import { forwardRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
type TExploreTabs = 'following' | 'all'
const ExplorePage = forwardRef((_, ref) => {
const [tab, setTab] = useState<TExploreTabs>('following')
return (
<PrimaryPageLayout
ref={ref}
@@ -12,7 +19,8 @@ const ExplorePage = forwardRef((_, ref) => {
titlebar={<ExplorePageTitlebar />}
displayScrollToTopButton
>
<RelayList />
<Tabs value={tab} setValue={setTab} />
{tab === 'following' ? <FollowingFavoriteRelayList /> : <RelayList />}
</PrimaryPageLayout>
)
})
@@ -29,3 +37,43 @@ function ExplorePageTitlebar() {
</div>
)
}
function Tabs({
value,
setValue
}: {
value: TExploreTabs
setValue: (value: TExploreTabs) => void
}) {
const { t } = useTranslation()
const { deepBrowsing, lastScrollTop } = useDeepBrowsing()
return (
<div
className={cn(
'sticky top-12 bg-background z-30 duration-700 transition-transform select-none',
deepBrowsing && lastScrollTop > 800 ? '-translate-y-[calc(100%+12rem)]' : ''
)}
>
<div className="flex">
<div
className={`w-1/2 text-center py-2 font-semibold clickable cursor-pointer rounded-lg ${value === 'following' ? '' : 'text-muted-foreground'}`}
onClick={() => setValue('following')}
>
{t("Following's Favorites")}
</div>
<div
className={`w-1/2 text-center py-2 font-semibold clickable cursor-pointer rounded-lg ${value === 'all' ? '' : 'text-muted-foreground'}`}
onClick={() => setValue('all')}
>
{t('All')}
</div>
</div>
<div
className={`w-1/2 px-4 sm:px-6 transition-transform duration-500 ${value === 'all' ? 'translate-x-full' : ''}`}
>
<div className="w-full h-1 bg-primary rounded-full" />
</div>
</div>
)
}

View File

@@ -1,8 +1,8 @@
import { BIG_RELAY_URLS } from '@/constants'
import { BIG_RELAY_URLS, ExtendedKind } from '@/constants'
import { getProfileFromProfileEvent, getRelayListFromRelayListEvent } from '@/lib/event'
import { formatPubkey, userIdToPubkey } from '@/lib/pubkey'
import { extractPubkeysFromEventTags } from '@/lib/tag'
import { isLocalNetworkUrl } from '@/lib/url'
import { isLocalNetworkUrl, isWebsocketUrl, normalizeUrl } from '@/lib/url'
import { isSafari } from '@/lib/utils'
import { ISigner, TProfile, TRelayList } from '@/types'
import { sha256 } from '@noble/hashes/sha2'
@@ -67,6 +67,13 @@ class ClientService extends EventTarget {
max: 2000,
fetchMethod: this._fetchFollowListEvent.bind(this)
})
private fetchFollowingFavoriteRelaysCache = new LRUCache<
string,
Promise<Map<string, Set<string>>>
>({
max: 10,
fetchMethod: this._fetchFollowingFavoriteRelays.bind(this)
})
private userIndex = new FlexSearch.Index({
tokenize: 'forward'
@@ -822,6 +829,39 @@ class ClientService extends EventTarget {
return followListEvent ? extractPubkeysFromEventTags(followListEvent.tags) : []
}
async fetchFollowingFavoriteRelays(pubkey: string) {
return this.fetchFollowingFavoriteRelaysCache.fetch(pubkey)
}
private async _fetchFollowingFavoriteRelays(pubkey: string) {
const followings = await this.fetchFollowings(pubkey)
const favoriteRelaysEvents = await this.fetchEvents(BIG_RELAY_URLS, {
authors: followings,
kinds: [ExtendedKind.FAVORITE_RELAYS],
limit: followings.length
})
const alreadyExistsPubkeys = new Set<string>()
const uniqueEvents: NEvent[] = []
favoriteRelaysEvents
.sort((a, b) => b.created_at - a.created_at)
.forEach((event) => {
if (alreadyExistsPubkeys.has(event.pubkey)) return
alreadyExistsPubkeys.add(event.pubkey)
uniqueEvents.push(event)
})
const relayMap = new Map<string, Set<string>>()
uniqueEvents.forEach((event) => {
event.tags.forEach(([tagName, tagValue]) => {
if (tagName === 'relay' && tagValue && isWebsocketUrl(tagValue)) {
const url = normalizeUrl(tagValue)
relayMap.set(url, (relayMap.get(url) || new Set()).add(event.pubkey))
}
})
})
return relayMap
}
updateFollowListCache(event: NEvent) {
this.followListCache.set(event.pubkey, Promise.resolve(event))
}

View File

@@ -66,6 +66,9 @@ class RelayInfoService {
}
async getRelayInfos(urls: string[]) {
if (urls.length === 0) {
return []
}
const relayInfos = await this.fetchDataloader.loadMany(urls)
return relayInfos.map((relayInfo) => (relayInfo instanceof Error ? undefined : relayInfo))
}