about summary refs log tree commit diff
path: root/src/components/dms/NewChat.tsx
blob: 55285daeda2be55efd9495386156848d5599248b (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import React, {useCallback, useMemo, useRef, useState} from 'react'
import {Keyboard, View} from 'react-native'
import {AppBskyActorDefs, moderateProfile} from '@atproto/api'
import {BottomSheetFlatListMethods} from '@discord/bottom-sheet'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'

import {sanitizeDisplayName} from '#/lib/strings/display-names'
import {sanitizeHandle} from '#/lib/strings/handles'
import {isWeb} from '#/platform/detection'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useGetConvoForMembers} from '#/state/queries/messages/get-convo-for-members'
import {useActorAutocompleteQuery} from 'state/queries/actor-autocomplete'
import {FAB} from '#/view/com/util/fab/FAB'
import * as Toast from '#/view/com/util/Toast'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, useTheme, web} from '#/alf'
import * as Dialog from '#/components/Dialog'
import * as TextField from '#/components/forms/TextField'
import {MagnifyingGlass2_Stroke2_Corner0_Rounded as Search} from '#/components/icons/MagnifyingGlass2'
import {Button} from '../Button'
import {Envelope_Stroke2_Corner0_Rounded as Envelope} from '../icons/Envelope'
import {ListMaybePlaceholder} from '../Lists'
import {Text} from '../Typography'

export function NewChat({
  control,
  onNewChat,
}: {
  control: Dialog.DialogControlProps
  onNewChat: (chatId: string) => void
}) {
  const t = useTheme()
  const {_} = useLingui()

  const {mutate: createChat} = useGetConvoForMembers({
    onSuccess: data => {
      onNewChat(data.convo.id)
    },
    onError: error => {
      Toast.show(error.message)
    },
  })

  const onCreateChat = useCallback(
    (did: string) => {
      control.close(() => createChat([did]))
    },
    [control, createChat],
  )

  return (
    <>
      <FAB
        testID="newChatFAB"
        onPress={control.open}
        icon={<Envelope size="xl" fill={t.palette.white} />}
        accessibilityRole="button"
        accessibilityLabel={_(msg`New chat`)}
        accessibilityHint=""
      />

      <Dialog.Outer
        control={control}
        testID="newChatDialog"
        nativeOptions={{sheet: {snapPoints: ['100%']}}}>
        <Dialog.Handle />
        <SearchablePeopleList onCreateChat={onCreateChat} />
      </Dialog.Outer>
    </>
  )
}

function SearchablePeopleList({
  onCreateChat,
}: {
  onCreateChat: (did: string) => void
}) {
  const t = useTheme()
  const {_} = useLingui()
  const moderationOpts = useModerationOpts()
  const control = Dialog.useDialogContext()
  const listRef = useRef<BottomSheetFlatListMethods>(null)

  const [searchText, setSearchText] = useState('')

  const {
    data: actorAutocompleteData,
    isFetching,
    isError,
    refetch,
  } = useActorAutocompleteQuery(searchText, true)

  const renderItem = useCallback(
    ({item: profile}: {item: AppBskyActorDefs.ProfileView}) => {
      if (!moderationOpts) return null
      const moderation = moderateProfile(profile, moderationOpts)
      return (
        <Button
          label={profile.displayName || sanitizeHandle(profile.handle)}
          onPress={() => onCreateChat(profile.did)}>
          {({hovered, pressed}) => (
            <View
              style={[
                a.flex_1,
                a.px_md,
                a.py_sm,
                a.gap_md,
                a.align_center,
                a.flex_row,
                a.rounded_sm,
                pressed
                  ? t.atoms.bg_contrast_25
                  : hovered
                  ? t.atoms.bg_contrast_50
                  : t.atoms.bg,
              ]}>
              <UserAvatar
                size={40}
                avatar={profile.avatar}
                moderation={moderation.ui('avatar')}
                type={profile.associated?.labeler ? 'labeler' : 'user'}
              />
              <View style={{flex: 1}}>
                <Text
                  style={[t.atoms.text, a.font_bold, a.leading_snug]}
                  numberOfLines={1}>
                  {sanitizeDisplayName(
                    profile.displayName || sanitizeHandle(profile.handle),
                    moderation.ui('displayName'),
                  )}
                </Text>
                <Text style={t.atoms.text_contrast_high} numberOfLines={1}>
                  {sanitizeHandle(profile.handle, '@')}
                </Text>
              </View>
            </View>
          )}
        </Button>
      )
    },
    [
      moderationOpts,
      onCreateChat,
      t.atoms.bg_contrast_25,
      t.atoms.bg_contrast_50,
      t.atoms.bg,
      t.atoms.text,
      t.atoms.text_contrast_high,
    ],
  )

  const listHeader = useMemo(() => {
    return (
      <View style={[a.relative, a.mb_lg]}>
        {/* cover top corners */}
        <View
          style={[
            a.absolute,
            a.inset_0,
            {
              borderBottomLeftRadius: 8,
              borderBottomRightRadius: 8,
            },
            t.atoms.bg,
          ]}
        />
        <Dialog.Close />
        <Text
          style={[
            a.text_2xl,
            a.font_bold,
            a.leading_tight,
            a.pb_lg,
            web(a.pt_lg),
          ]}>
          <Trans>Start a new chat</Trans>
        </Text>
        <TextField.Root>
          <TextField.Icon icon={Search} />
          <TextField.Input
            label={_(msg`Search profiles`)}
            placeholder={_(msg`Search`)}
            value={searchText}
            onChangeText={text => {
              setSearchText(text)
              listRef.current?.scrollToOffset({offset: 0, animated: false})
            }}
            returnKeyType="search"
            clearButtonMode="while-editing"
            maxLength={50}
            onKeyPress={({nativeEvent}) => {
              if (nativeEvent.key === 'Escape') {
                control.close()
              }
            }}
            autoCorrect={false}
            autoComplete="off"
            autoCapitalize="none"
          />
        </TextField.Root>
      </View>
    )
  }, [t.atoms.bg, _, control, searchText])

  return (
    <Dialog.InnerFlatList
      ref={listRef}
      data={actorAutocompleteData}
      renderItem={renderItem}
      ListHeaderComponent={
        <>
          {listHeader}
          {searchText.length > 0 && !actorAutocompleteData?.length && (
            <ListMaybePlaceholder
              isLoading={isFetching}
              isError={isError}
              onRetry={refetch}
              hideBackButton={true}
              emptyType="results"
              sideBorders={false}
              emptyMessage={
                isError
                  ? _(msg`No search results found for "${searchText}".`)
                  : _(msg`Could not load profiles. Please try again later.`)
              }
            />
          )}
        </>
      }
      stickyHeaderIndices={[0]}
      keyExtractor={(item: AppBskyActorDefs.ProfileView) => item.did}
      // @ts-expect-error web only
      style={isWeb && {minHeight: '100vh'}}
      onScrollBeginDrag={() => Keyboard.dismiss()}
    />
  )
}