about summary refs log tree commit diff
path: root/src/view/com/util/UserInfoText.tsx
blob: cdd1f4d9187c6f635c2e91048d1a85f197647b06 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import React, {useState, useEffect} from 'react'
import {AppBskyActorGetProfile as GetProfile} from '@atproto/api'
import {StyleProp, TextStyle} from 'react-native'
import {Link} from './Link'
import {Text} from './Text'
import {LoadingPlaceholder} from './LoadingPlaceholder'
import {useStores} from '../../../state'

export function UserInfoText({
  did,
  attr,
  loading,
  failed,
  prefix,
  style,
  asLink,
}: {
  did: string
  attr?: keyof GetProfile.OutputSchema
  loading?: string
  failed?: string
  prefix?: string
  style?: StyleProp<TextStyle>
  asLink?: boolean
}) {
  attr = attr || 'handle'
  loading = loading || '...'
  failed = failed || 'user'

  const store = useStores()
  const [profile, setProfile] = useState<undefined | GetProfile.OutputSchema>(
    undefined,
  )
  const [didFail, setFailed] = useState<boolean>(false)

  useEffect(() => {
    let aborted = false
    store.profiles.getProfile(did).then(
      v => {
        if (aborted) return
        setProfile(v.data)
      },
      _err => {
        if (aborted) return
        setFailed(true)
      },
    )
    return () => {
      aborted = true
    }
  }, [did, store.api.app.bsky])

  let inner
  if (didFail) {
    inner = <Text style={style}>{failed}</Text>
  } else if (profile) {
    inner = <Text style={style}>{`${prefix || ''}${profile[attr]}`}</Text>
  } else {
    inner = (
      <LoadingPlaceholder
        width={80}
        height={8}
        style={{position: 'relative', top: 1, left: 2}}
      />
    )
  }

  if (asLink) {
    const title = profile?.displayName || profile?.handle || 'User'
    return (
      <Link
        href={`/profile/${profile?.handle ? profile.handle : did}`}
        title={title}>
        {inner}
      </Link>
    )
  }

  return inner
}