Skip to content

Commit

Permalink
refactor: next id query (#10541)
Browse files Browse the repository at this point in the history
* refactor: next id query

* refactor: next id query
  • Loading branch information
zhouhanseng committed Aug 21, 2023
1 parent bec6e62 commit 1131d7e
Show file tree
Hide file tree
Showing 13 changed files with 75 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function SelectProfileDialog({ open, profiles, selectedProfiles, onClose,
const type = resolveNextIDPlatform(valueToSearch)

const value = resolveValueToSearch(valueToSearch)
const { loading: searchLoading, value: NextIDResults } = usePersonasFromNextID(
const { isLoading: searchLoading, data: NextIDResults } = usePersonasFromNextID(
value,
type ?? NextIDPlatform.NextID,
false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function SelectRecipientsUI(props: SelectRecipientsUIProps) {
const currentIdentity = useCurrentIdentity()
const type = resolveNextIDPlatform(valueToSearch)
const _value = resolveValueToSearch(valueToSearch)
const { loading: searchLoading, value: NextIDResults } = usePersonasFromNextID(
const { isLoading: searchLoading, data: NextIDResults } = usePersonasFromNextID(
_value,
type ?? NextIDPlatform.NextID,
false,
Expand Down
20 changes: 11 additions & 9 deletions packages/plugin-infra/src/site-adaptor/useSocialIdentity.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
import { useEffect } from 'react'
import { useAsyncRetry } from 'react-use'
import { MaskMessages, type SocialIdentity } from '@masknet/shared-base'
import type { IdentityResolved } from '../types.js'
import { useSiteAdaptorContext } from '../dom/useSiteAdaptorContext.js'
import { useQuery } from '@tanstack/react-query'

/**
* Get the social identity of the given identity
*/
export function useSocialIdentity(identity: IdentityResolved | null | undefined) {
const { getSocialIdentity, getNextIDPlatform } = useSiteAdaptorContext()

const result = useAsyncRetry<SocialIdentity | undefined>(async () => {
if (!identity) return
const platform = getNextIDPlatform()

const platform = getNextIDPlatform()
if (!platform) return
const result = useQuery<SocialIdentity | undefined, Error>({
queryKey: ['next-id', identity, platform],
enabled: Boolean(identity && platform),
queryFn: async () => {
if (!platform || !identity) return
return getSocialIdentity(platform, identity)
},
})

return getSocialIdentity(platform, identity)
}, [identity])

useEffect(() => MaskMessages.events.ownProofChanged.on(result.retry), [result.retry])
useEffect(() => MaskMessages.events.ownProofChanged.on(() => result.refetch()), [result.refetch])

return result
}
4 changes: 2 additions & 2 deletions packages/plugins/Avatar/src/Application/NFTAvatarDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ export function NFTAvatarDialog({ startPicking, ...rest }: NFTAvatarDialogProps)
const initialEntries = useMemo(() => {
return [RoutePaths.Exit, startPicking ? RoutePaths.NFTPicker : RoutePaths.Personas]
}, [!startPicking])
const { loading, value: socialIdentity } = useLastRecognizedSocialIdentity()
const { isLoading, data: socialIdentity } = useLastRecognizedSocialIdentity()
return (
<MemoryRouter initialEntries={initialEntries} initialIndex={1}>
<AvatarManagementProvider socialIdentity={socialIdentity}>
<RouterDialog {...rest}>
<DialogContent className={classes.root}>
{loading ? (
{isLoading ? (
<Box className={classes.Box}>
<LoadingBase />
</Box>
Expand Down
8 changes: 4 additions & 4 deletions packages/plugins/Avatar/src/Application/PersonaPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function PersonaPage() {
const dismissAlert = useCallback(() => setVisible(false), [])
const navigate = useNavigate()
const { setProofs, setTokenInfo, setProof } = useAvatarManagement()
const { loading, value: socialIdentity } = useLastRecognizedSocialIdentity()
const { isLoading, data: socialIdentity } = useLastRecognizedSocialIdentity()
const network = socialIdentity?.identifier?.network.replace('.com', '')
const userId = socialIdentity?.identifier?.userId

Expand All @@ -36,10 +36,10 @@ export function PersonaPage() {
(x: PersonaInformation) => x.identifier.rawPublicKey.toLowerCase() === _persona?.rawPublicKey.toLowerCase(),
)

const { value: bindingPersonas = EMPTY_LIST } = usePersonasFromNextID(
const { data: bindingPersonas = EMPTY_LIST } = usePersonasFromNextID(
_persona?.publicKeyAsHex ?? '',
NextIDPlatform.NextID,
true,
false,
)

const bindingProofs = useMemo(
Expand Down Expand Up @@ -67,7 +67,7 @@ export function PersonaPage() {
return (
<>
<DialogContent sx={{ flex: 1, height: 464, padding: 2 }}>
{loading ? (
{isLoading ? (
<Stack justifyContent="center" alignItems="center" height="100%">
<LoadingBase />
</Stack>
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/Avatar/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export async function getNFTAvatarByUserId(
): Promise<NextIDAvatarMeta | undefined> {
const platform = getSiteType() === EnhanceableSite.Twitter ? NextIDPlatform.Twitter : undefined
if (!platform) return
const bindings = await NextIDProof.queryAllExistedBindingsByPlatform(platform, userId, true)
const bindings = await NextIDProof.queryAllExistedBindingsByPlatform(platform, userId)

if (persona) {
const binding = bindings.filter((x) => x.persona.toLowerCase() === persona.toLowerCase())?.[0]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export function ConsoleContent(props: ConsoleContentProps) {
name: 'Visiting Public Key',
content: (
<Typography variant="body2" style={{ width: 280, wordBreak: 'break-all' }}>
{currentVisitingSocialIdentity?.value?.publicKey}
{currentVisitingSocialIdentity.data?.publicKey}
</Typography>
),
},
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/Tips/src/components/TipsButton/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function TipButton(props: Props) {

const { pluginID } = useNetworkContext()
const visitingIdentity = useCurrentVisitingIdentity()
const { value: identity } = useSocialIdentityByUserId(receiverUserId)
const { data: identity } = useSocialIdentityByUserId(receiverUserId)

const isVisitingUser = visitingIdentity?.identifier?.userId === receiverUserId
const isRuntimeAvailable = useMemo(() => {
Expand Down
10 changes: 5 additions & 5 deletions packages/shared/src/UI/components/PersonaSelectPanel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const PersonaSelectPanel = memo<PersonaSelectPanelProps>((props) => {

const [, handleVerifyNextID] = useNextIDVerify()
const currentProfileIdentify = useLastRecognizedIdentity()
const { value: personas = EMPTY_LIST, loading, error, retry } = useConnectedPersonas()
const { data: personas = EMPTY_LIST, isLoading, error, refetch } = useConnectedPersonas()
const { openDashboard, attachProfile, setCurrentPersonaIdentifier } = useSiteAdaptorContext()

useEffect(() => {
Expand All @@ -88,7 +88,7 @@ export const PersonaSelectPanel = memo<PersonaSelectPanelProps>((props) => {
)

useLayoutEffect(() => {
if (personas.length || loading || error) return
if (personas.length || isLoading || error) return

onClose?.()
LeavePageConfirmModal.open({
Expand All @@ -101,7 +101,7 @@ export const PersonaSelectPanel = memo<PersonaSelectPanelProps>((props) => {
actionHint: t.applications_create_persona_action(),
},
})
}, [!personas.length, loading, !error, openDashboard])
}, [!personas.length, isLoading, !error, openDashboard])

const actionButton = useMemo(() => {
let isConnected = true
Expand Down Expand Up @@ -205,7 +205,7 @@ export const PersonaSelectPanel = memo<PersonaSelectPanelProps>((props) => {
selectedPersona?.persona.linkedProfiles,
])

if (loading) {
if (isLoading) {
return (
<Stack justifyContent="center" alignItems="center" height="100%">
<LoadingBase size={24} />
Expand All @@ -214,7 +214,7 @@ export const PersonaSelectPanel = memo<PersonaSelectPanelProps>((props) => {
}

if (error) {
return <ErrorPanel onRetry={retry} />
return <ErrorPanel onRetry={refetch} />
}

if (!personas.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ function Content(props: ProfileTabContentProps) {
const [currentTrendingIndex, setCurrentTrendingIndex] = useState(0)
const trendingResult = collectionList?.[currentTrendingIndex]

const { value: identity } = useSocialIdentityByUserId(currentVisitingUserId)
const { data: identity } = useSocialIdentityByUserId(currentVisitingUserId)

const { value: nextIdBindings = EMPTY_LIST } = useAsync(async () => {
if (!currentVisitingUserId) return EMPTY_LIST
Expand Down
55 changes: 33 additions & 22 deletions packages/shared/src/hooks/useConnectedPersonas.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,47 @@
import { useEffect } from 'react'
import { useAsyncRetry } from 'react-use'
import { EMPTY_LIST, MaskMessages, NextIDPlatform } from '@masknet/shared-base'
import {
EMPTY_LIST,
MaskMessages,
NextIDPlatform,
type BindingProof,
type PersonaInformation,
} from '@masknet/shared-base'
import { NextIDProof } from '@masknet/web3-providers'
import { useAllPersonas, useSiteAdaptorContext } from '@masknet/plugin-infra/content-script'
import { useQuery } from '@tanstack/react-query'

export function useConnectedPersonas() {
const personasInDB = useAllPersonas()
const { getPersonaAvatars } = useSiteAdaptorContext()

const result = useAsyncRetry(async () => {
const allPersonaPublicKeys = personasInDB.map((x) => x.identifier.publicKeyAsHex)
const allPersonaIdentifiers = personasInDB.map((x) => x.identifier)
const result = useQuery<
Array<{ persona: PersonaInformation; proof: BindingProof[]; avatar: string | undefined }>,
Error
>({
queryFn: async () => {
const allPersonaPublicKeys = personasInDB.map((x) => x.identifier.publicKeyAsHex)
const allPersonaIdentifiers = personasInDB.map((x) => x.identifier)

const avatars = await getPersonaAvatars?.(allPersonaIdentifiers)
const allNextIDBindings = await NextIDProof.queryExistedBindingByPlatform(
NextIDPlatform.NextID,
allPersonaPublicKeys.join(','),
)
const avatars = await getPersonaAvatars?.(allPersonaIdentifiers)
const allNextIDBindings = await NextIDProof.queryAllExistedBindingsByPlatform(
NextIDPlatform.NextID,
allPersonaPublicKeys.join(','),
)

return personasInDB.map((x) => {
return {
persona: x,
proof:
allNextIDBindings
.find((p) => p.persona.toLowerCase() === x.identifier.publicKeyAsHex.toLowerCase())
?.proofs.filter((x) => x.is_valid) ?? EMPTY_LIST,
avatar: avatars?.get(x.identifier),
}
})
}, [personasInDB, getPersonaAvatars])
return personasInDB.map((x) => {
return {
persona: x,
proof:
allNextIDBindings
.find((p) => p.persona.toLowerCase() === x.identifier.publicKeyAsHex.toLowerCase())
?.proofs.filter((x) => x.is_valid) ?? EMPTY_LIST,
avatar: avatars?.get(x.identifier),
}
})
},
})

useEffect(() => MaskMessages.events.ownProofChanged.on(result.retry), [result.retry])
useEffect(() => MaskMessages.events.ownProofChanged.on(() => result.refetch()), [result.refetch])

return result
}
21 changes: 13 additions & 8 deletions packages/shared/src/hooks/usePersonasFromNextID.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
import { useEffect } from 'react'
import { useAsyncRetry } from 'react-use'
import { EMPTY_LIST, MaskMessages, type NextIDPlatform } from '@masknet/shared-base'
import { EMPTY_LIST, MaskMessages, type NextIDPersonaBindings, type NextIDPlatform } from '@masknet/shared-base'
import { NextIDProof } from '@masknet/web3-providers'
import { useQuery } from '@tanstack/react-query'

/**
* Get all personas bound with the given identity from NextID service
*/
export function usePersonasFromNextID(userId: string, platform: NextIDPlatform, exact?: boolean) {
const asyncRetry = useAsyncRetry(async () => {
if (!platform || !userId) return EMPTY_LIST
return NextIDProof.queryAllExistedBindingsByPlatform(platform, userId, exact)
}, [platform, userId, exact])
useEffect(() => MaskMessages.events.ownProofChanged.on(asyncRetry.retry), [asyncRetry.retry])
return asyncRetry
const result = useQuery<NextIDPersonaBindings[], Error>({
queryKey: ['next-id', 'personas', userId],
enabled: Boolean(platform && userId),
queryFn: async () => {
if (!platform || !userId) return EMPTY_LIST
return NextIDProof.queryAllExistedBindingsByPlatform(platform, userId, exact)
},
})

useEffect(() => MaskMessages.events.ownProofChanged.on(() => result.refetch), [result.refetch])
return result
}
2 changes: 1 addition & 1 deletion packages/web3-providers/src/NextID/proof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ export class NextIDProofAPI implements NextIDBaseAPI.Proof {
): Promise<NextIDPersonaBindings | null> {
if (!platform && !identity) return null

const result = await this.queryExistedBindingByPlatform(platform, identity, 1)
const result = await this.queryAllExistedBindingsByPlatform(platform, identity)
if (publicKey) return result.find((x) => x.persona === publicKey) ?? null
return first(result) ?? null
}
Expand Down

0 comments on commit 1131d7e

Please sign in to comment.