refactor: remove electron-related code

This commit is contained in:
codytseng
2024-12-21 23:20:30 +08:00
parent bed8df06e8
commit 2b1e6fe8f5
200 changed files with 2771 additions and 8432 deletions

8
src/hooks/index.tsx Normal file
View File

@@ -0,0 +1,8 @@
export * from './use-toast'
export * from './useFetchEvent'
export * from './useFetchFollowings'
export * from './useFetchNip05'
export * from './useFetchProfile'
export * from './useFetchRelayInfos'
export * from './useSearchParams'
export * from './useSearchProfiles'

189
src/hooks/use-toast.ts Normal file
View File

@@ -0,0 +1,189 @@
'use client'
// Inspired by react-hot-toast library
import * as React from 'react'
import type { ToastActionElement, ToastProps } from '@/components/ui/toast'
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: 'ADD_TOAST',
UPDATE_TOAST: 'UPDATE_TOAST',
DISMISS_TOAST: 'DISMISS_TOAST',
REMOVE_TOAST: 'REMOVE_TOAST'
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType['ADD_TOAST']
toast: ToasterToast
}
| {
type: ActionType['UPDATE_TOAST']
toast: Partial<ToasterToast>
}
| {
type: ActionType['DISMISS_TOAST']
toastId?: ToasterToast['id']
}
| {
type: ActionType['REMOVE_TOAST']
toastId?: ToasterToast['id']
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: 'REMOVE_TOAST',
toastId: toastId
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case 'ADD_TOAST':
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT)
}
case 'UPDATE_TOAST':
return {
...state,
toasts: state.toasts.map((t) => (t.id === action.toast.id ? { ...t, ...action.toast } : t))
}
case 'DISMISS_TOAST': {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false
}
: t
)
}
}
case 'REMOVE_TOAST':
if (action.toastId === undefined) {
return {
...state,
toasts: []
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId)
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, 'id'>
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: 'UPDATE_TOAST',
toast: { ...props, id }
})
const dismiss = () => dispatch({ type: 'DISMISS_TOAST', toastId: id })
dispatch({
type: 'ADD_TOAST',
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
}
}
})
return {
id: id,
dismiss,
update
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId })
}
}
export { useToast, toast }

View File

@@ -0,0 +1,38 @@
import client from '@/services/client.service'
import { Event } from 'nostr-tools'
import { useEffect, useState } from 'react'
export function useFetchEvent(id?: string) {
const [isFetching, setIsFetching] = useState(true)
const [error, setError] = useState<Error | null>(null)
const [event, setEvent] = useState<Event | undefined>(undefined)
useEffect(() => {
const fetchEvent = async () => {
setIsFetching(true)
if (!id) {
setIsFetching(false)
setError(new Error('No id provided'))
return
}
try {
const event = await client.fetchEvent(id)
if (event) {
setEvent(event)
}
} catch (error) {
setError(error as Error)
} finally {
setIsFetching(false)
}
}
fetchEvent().catch((err) => {
setError(err as Error)
setIsFetching(false)
})
}, [id])
return { isFetching, error, event }
}

View File

@@ -0,0 +1,31 @@
import { tagNameEquals } from '@/lib/tag'
import client from '@/services/client.service'
import { Event } from 'nostr-tools'
import { useEffect, useState } from 'react'
export function useFetchFollowings(pubkey?: string | null) {
const [followListEvent, setFollowListEvent] = useState<Event | null>(null)
const [followings, setFollowings] = useState<string[]>([])
useEffect(() => {
const init = async () => {
if (!pubkey) return
const event = await client.fetchFollowListEvent(pubkey)
if (!event) return
setFollowListEvent(event)
setFollowings(
event.tags
.filter(tagNameEquals('p'))
.map(([, pubkey]) => pubkey)
.filter(Boolean)
.reverse()
)
}
init()
}, [pubkey])
return { followings, followListEvent }
}

View File

@@ -0,0 +1,19 @@
import { verifyNip05 } from '@/lib/nip05'
import { useEffect, useState } from 'react'
export function useFetchNip05(nip05?: string, pubkey?: string) {
const [nip05IsVerified, setNip05IsVerified] = useState(false)
const [nip05Name, setNip05Name] = useState<string>('')
const [nip05Domain, setNip05Domain] = useState<string>('')
useEffect(() => {
if (!nip05 || !pubkey) return
verifyNip05(nip05, pubkey).then(({ isVerified, nip05Name, nip05Domain }) => {
setNip05IsVerified(isVerified)
setNip05Name(nip05Name)
setNip05Domain(nip05Domain)
})
}, [nip05, pubkey])
return { nip05IsVerified, nip05Name, nip05Domain }
}

View File

@@ -0,0 +1,35 @@
import client from '@/services/client.service'
import { TProfile } from '@/types'
import { useEffect, useState } from 'react'
export function useFetchProfile(id?: string) {
const [isFetching, setIsFetching] = useState(true)
const [error, setError] = useState<Error | null>(null)
const [profile, setProfile] = useState<TProfile | null>(null)
useEffect(() => {
const fetchProfile = async () => {
setIsFetching(true)
try {
if (!id) {
setIsFetching(false)
setError(new Error('No id provided'))
return
}
const profile = await client.fetchProfile(id)
if (profile) {
setProfile(profile)
}
} catch (err) {
setError(err as Error)
} finally {
setIsFetching(false)
}
}
fetchProfile()
}, [id])
return { isFetching, error, profile }
}

View File

@@ -0,0 +1,37 @@
import { checkAlgoRelay } from '@/lib/relay'
import client from '@/services/client.service'
import { TRelayInfo } from '@/types'
import { useEffect, useState } from 'react'
export function useFetchRelayInfos(urls: string[]) {
const [isFetching, setIsFetching] = useState(true)
const [relayInfos, setRelayInfos] = useState<(TRelayInfo | undefined)[]>([])
const [areAlgoRelays, setAreAlgoRelays] = useState(false)
const urlsString = JSON.stringify(urls)
useEffect(() => {
const fetchRelayInfos = async () => {
setIsFetching(true)
if (urls.length === 0) {
return setIsFetching(false)
}
const timer = setTimeout(() => {
setIsFetching(false)
}, 5000)
try {
const relayInfos = await client.fetchRelayInfos(urls)
setRelayInfos(relayInfos)
setAreAlgoRelays(relayInfos.every((relayInfo) => checkAlgoRelay(relayInfo)))
} catch (err) {
console.error(err)
} finally {
clearTimeout(timer)
setIsFetching(false)
}
}
fetchRelayInfos()
}, [urlsString])
return { relayInfos, isFetching, areAlgoRelays }
}

View File

@@ -0,0 +1,23 @@
import { TRelayList } from '@/types'
import { useEffect, useState } from 'react'
import client from '@/services/client.service'
export function useFetchRelayList(pubkey?: string | null) {
const [relayList, setRelayList] = useState<TRelayList>({ write: [], read: [] })
useEffect(() => {
const fetchRelayList = async () => {
if (!pubkey) return
try {
const relayList = await client.fetchRelayList(pubkey)
setRelayList(relayList)
} catch (err) {
console.error(err)
}
}
fetchRelayList()
}, [pubkey])
return relayList
}

View File

@@ -0,0 +1,13 @@
import { TWebMetadata } from '@/types'
import { useEffect, useState } from 'react'
import webService from '@/services/web.service'
export function useFetchWebMetadata(url: string) {
const [metadata, setMetadata] = useState<TWebMetadata>({})
useEffect(() => {
webService.fetchWebMetadata(url).then((metadata) => setMetadata(metadata))
}, [url])
return metadata
}

View File

@@ -0,0 +1,24 @@
export function useSearchParams() {
const searchParams = new URLSearchParams(window.location.search)
return {
searchParams,
get: (key: string) => searchParams.get(key),
set: (key: string, value: string) => {
searchParams.set(key, value)
window.history.replaceState(
null,
'',
`${window.location.pathname}?${searchParams.toString()}`
)
},
delete: (key: string) => {
searchParams.delete(key)
window.history.replaceState(
null,
'',
`${window.location.pathname}?${searchParams.toString()}`
)
}
}
}

View File

@@ -0,0 +1,41 @@
import { useRelaySettings } from '@/providers/RelaySettingsProvider'
import client from '@/services/client.service'
import { TProfile } from '@/types'
import { useEffect, useState } from 'react'
export function useSearchProfiles(search: string, limit: number) {
const { searchableRelayUrls } = useRelaySettings()
const [isFetching, setIsFetching] = useState(true)
const [error, setError] = useState<Error | null>(null)
const [profiles, setProfiles] = useState<TProfile[]>([])
useEffect(() => {
const fetchProfiles = async () => {
if (!search) return
setIsFetching(true)
setProfiles([])
if (searchableRelayUrls.length === 0) {
setIsFetching(false)
return
}
try {
const profiles = await client.fetchProfiles(searchableRelayUrls, {
search,
limit
})
if (profiles) {
setProfiles(profiles)
}
} catch (err) {
setError(err as Error)
} finally {
setIsFetching(false)
}
}
fetchProfiles()
}, [searchableRelayUrls, search, limit])
return { isFetching, error, profiles }
}