about summary refs log tree commit diff
path: root/src/view/com/auth/server-input/index.tsx
blob: 9fd426a9b3f687d2330bac99e2c175dbbe5f6884 (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
239
import {useCallback, useImperativeHandle, useRef, useState} from 'react'
import {View} from 'react-native'
import {useWindowDimensions} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'

import {BSKY_SERVICE} from '#/lib/constants'
import {logEvent} from '#/lib/statsig/statsig'
import * as persisted from '#/state/persisted'
import {useSession} from '#/state/session'
import {atoms as a, useBreakpoints, useTheme} from '#/alf'
import {Admonition} from '#/components/Admonition'
import {Button, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
import * as TextField from '#/components/forms/TextField'
import * as ToggleButton from '#/components/forms/ToggleButton'
import {Globe_Stroke2_Corner0_Rounded as Globe} from '#/components/icons/Globe'
import {InlineLinkText} from '#/components/Link'
import {P, Text} from '#/components/Typography'

export function ServerInputDialog({
  control,
  onSelect,
}: {
  control: Dialog.DialogOuterProps['control']
  onSelect: (url: string) => void
}) {
  const {height} = useWindowDimensions()
  const formRef = useRef<DialogInnerRef>(null)

  // persist these options between dialog open/close
  const [fixedOption, setFixedOption] = useState(BSKY_SERVICE)
  const [previousCustomAddress, setPreviousCustomAddress] = useState('')

  const onClose = useCallback(() => {
    const result = formRef.current?.getFormState()
    if (result) {
      onSelect(result)
      if (result !== BSKY_SERVICE) {
        setPreviousCustomAddress(result)
      }
    }
    logEvent('signin:hostingProviderPressed', {
      hostingProviderDidChange: fixedOption !== BSKY_SERVICE,
    })
  }, [onSelect, fixedOption])

  return (
    <Dialog.Outer
      control={control}
      onClose={onClose}
      nativeOptions={{minHeight: height / 2}}>
      <Dialog.Handle />
      <DialogInner
        formRef={formRef}
        fixedOption={fixedOption}
        setFixedOption={setFixedOption}
        initialCustomAddress={previousCustomAddress}
      />
    </Dialog.Outer>
  )
}

type DialogInnerRef = {getFormState: () => string | null}

function DialogInner({
  formRef,
  fixedOption,
  setFixedOption,
  initialCustomAddress,
}: {
  formRef: React.Ref<DialogInnerRef>
  fixedOption: string
  setFixedOption: (opt: string) => void
  initialCustomAddress: string
}) {
  const control = Dialog.useDialogContext()
  const {_} = useLingui()
  const t = useTheme()
  const {accounts} = useSession()
  const {gtMobile} = useBreakpoints()
  const [customAddress, setCustomAddress] = useState(initialCustomAddress)
  const [pdsAddressHistory, setPdsAddressHistory] = useState<string[]>(
    persisted.get('pdsAddressHistory') || [],
  )

  useImperativeHandle(
    formRef,
    () => ({
      getFormState: () => {
        let url
        if (fixedOption === 'custom') {
          url = customAddress.trim().toLowerCase()
          if (!url) {
            return null
          }
        } else {
          url = fixedOption
        }
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
          if (url === 'localhost' || url.startsWith('localhost:')) {
            url = `http://${url}`
          } else {
            url = `https://${url}`
          }
        }

        if (fixedOption === 'custom') {
          if (!pdsAddressHistory.includes(url)) {
            const newHistory = [url, ...pdsAddressHistory.slice(0, 4)]
            setPdsAddressHistory(newHistory)
            persisted.write('pdsAddressHistory', newHistory)
          }
        }

        return url
      },
    }),
    [customAddress, fixedOption, pdsAddressHistory],
  )

  const isFirstTimeUser = accounts.length === 0

  return (
    <Dialog.ScrollableInner
      accessibilityDescribedBy="dialog-description"
      accessibilityLabelledBy="dialog-title">
      <View style={[a.relative, a.gap_md, a.w_full]}>
        <Text nativeID="dialog-title" style={[a.text_2xl, a.font_bold]}>
          <Trans>Choose your account provider</Trans>
        </Text>
        <ToggleButton.Group
          label="Preferences"
          values={[fixedOption]}
          onChange={values => setFixedOption(values[0])}>
          <ToggleButton.Button name={BSKY_SERVICE} label={_(msg`Bluesky`)}>
            <ToggleButton.ButtonText>{_(msg`Bluesky`)}</ToggleButton.ButtonText>
          </ToggleButton.Button>
          <ToggleButton.Button
            testID="customSelectBtn"
            name="custom"
            label={_(msg`Custom`)}>
            <ToggleButton.ButtonText>{_(msg`Custom`)}</ToggleButton.ButtonText>
          </ToggleButton.Button>
        </ToggleButton.Group>

        {fixedOption === BSKY_SERVICE && isFirstTimeUser && (
          <Admonition type="tip">
            <Trans>
              Bluesky is an open network where you can choose your own provider.
              If you're new here, we recommend sticking with the default Bluesky
              Social option.
            </Trans>
          </Admonition>
        )}

        {fixedOption === 'custom' && (
          <View
            style={[
              a.border,
              t.atoms.border_contrast_low,
              a.rounded_sm,
              a.px_md,
              a.py_md,
            ]}>
            <TextField.LabelText nativeID="address-input-label">
              <Trans>Server address</Trans>
            </TextField.LabelText>
            <TextField.Root>
              <TextField.Icon icon={Globe} />
              <Dialog.Input
                testID="customServerTextInput"
                value={customAddress}
                onChangeText={setCustomAddress}
                label="my-server.com"
                accessibilityLabelledBy="address-input-label"
                autoCapitalize="none"
                keyboardType="url"
              />
            </TextField.Root>
            {pdsAddressHistory.length > 0 && (
              <View style={[a.flex_row, a.flex_wrap, a.mt_xs]}>
                {pdsAddressHistory.map(uri => (
                  <Button
                    key={uri}
                    variant="ghost"
                    color="primary"
                    label={uri}
                    style={[a.px_sm, a.py_xs, a.rounded_sm, a.gap_sm]}
                    onPress={() => setCustomAddress(uri)}>
                    <ButtonText>{uri}</ButtonText>
                  </Button>
                ))}
              </View>
            )}
          </View>
        )}

        <View style={[a.py_xs]}>
          <P
            style={[
              t.atoms.text_contrast_medium,
              a.text_sm,
              a.leading_snug,
              a.flex_1,
            ]}>
            {isFirstTimeUser ? (
              <Trans>
                If you're a developer, you can host your own server.
              </Trans>
            ) : (
              <Trans>
                Bluesky is an open network where you can choose your hosting
                provider. If you're a developer, you can host your own server.
              </Trans>
            )}{' '}
            <InlineLinkText
              label={_(msg`Learn more about self hosting your PDS.`)}
              to="https://atproto.com/guides/self-hosting">
              <Trans>Learn more.</Trans>
            </InlineLinkText>
          </P>
        </View>

        <View style={gtMobile && [a.flex_row, a.justify_end]}>
          <Button
            testID="doneBtn"
            variant="outline"
            color="primary"
            size="small"
            onPress={() => control.close()}
            label={_(msg`Done`)}>
            <ButtonText>{_(msg`Done`)}</ButtonText>
          </Button>
        </View>
      </View>
    </Dialog.ScrollableInner>
  )
}