about summary refs log tree commit diff
path: root/src/components/ageAssurance/AgeAssuranceInitDialog.tsx
blob: 08fd5f84fc1ab7a8563cfb3c6225654f11b743d3 (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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import {useState} from 'react'
import {View} from 'react-native'
import {XRPCError} from '@atproto/xrpc'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {validate as validateEmail} from 'email-validator'

import {useCleanError} from '#/lib/hooks/useCleanError'
import {
  SupportCode,
  useCreateSupportLink,
} from '#/lib/hooks/useCreateSupportLink'
import {useGetTimeAgo} from '#/lib/hooks/useTimeAgo'
import {useTLDs} from '#/lib/hooks/useTLDs'
import {isEmailMaybeInvalid} from '#/lib/strings/email'
import {type AppLanguage} from '#/locale/languages'
import {useAgeAssuranceContext} from '#/state/ageAssurance'
import {useInitAgeAssurance} from '#/state/ageAssurance/useInitAgeAssurance'
import {logger} from '#/state/ageAssurance/util'
import {useLanguagePrefs} from '#/state/preferences'
import {useSession} from '#/state/session'
import {atoms as a, useTheme, web} from '#/alf'
import {Admonition} from '#/components/Admonition'
import {AgeAssuranceBadge} from '#/components/ageAssurance/AgeAssuranceBadge'
import {urls} from '#/components/ageAssurance/const'
import {KWS_SUPPORTED_LANGS} from '#/components/ageAssurance/const'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
import {Divider} from '#/components/Divider'
import * as TextField from '#/components/forms/TextField'
import {ShieldCheck_Stroke2_Corner0_Rounded as Shield} from '#/components/icons/Shield'
import {LanguageSelect} from '#/components/LanguageSelect'
import {InlineLinkText} from '#/components/Link'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'

export {useDialogControl} from '#/components/Dialog/context'

export function AgeAssuranceInitDialog({
  control,
}: {
  control: Dialog.DialogControlProps
}) {
  const {_} = useLingui()
  return (
    <Dialog.Outer control={control}>
      <Dialog.Handle />

      <Dialog.ScrollableInner
        label={_(
          msg`Begin the age assurance process by completing the fields below.`,
        )}
        style={[
          web({
            maxWidth: 400,
          }),
        ]}>
        <Inner />
        <Dialog.Close />
      </Dialog.ScrollableInner>
    </Dialog.Outer>
  )
}

function Inner() {
  const t = useTheme()
  const {_} = useLingui()
  const {currentAccount} = useSession()
  const langPrefs = useLanguagePrefs()
  const cleanError = useCleanError()
  const {close} = Dialog.useDialogContext()
  const {lastInitiatedAt} = useAgeAssuranceContext()
  const getTimeAgo = useGetTimeAgo()
  const tlds = useTLDs()
  const createSupportLink = useCreateSupportLink()

  const wasRecentlyInitiated =
    lastInitiatedAt &&
    new Date(lastInitiatedAt).getTime() > Date.now() - 5 * 60 * 1000 // 5 minutes

  const [success, setSuccess] = useState(false)
  const [email, setEmail] = useState(currentAccount?.email || '')
  const [emailError, setEmailError] = useState<string>('')
  const [languageError, setLanguageError] = useState(false)
  const [disabled, setDisabled] = useState(false)
  const [language, setLanguage] = useState<string | undefined>(
    convertToKWSSupportedLanguage(langPrefs.appLanguage),
  )
  const [error, setError] = useState<React.ReactNode>(null)

  const {mutateAsync: init, isPending} = useInitAgeAssurance()

  const runEmailValidation = () => {
    if (validateEmail(email)) {
      setEmailError('')
      setDisabled(false)

      if (tlds && isEmailMaybeInvalid(email, tlds)) {
        setEmailError(
          _(
            msg`Please double-check that you have entered your email address correctly.`,
          ),
        )
        return {status: 'maybe'}
      }

      return {status: 'valid'}
    }

    setEmailError(_(msg`Please enter a valid email address.`))
    setDisabled(true)

    return {status: 'invalid'}
  }

  const onSubmit = async () => {
    setLanguageError(false)

    logger.metric('ageAssurance:initDialogSubmit', {})

    try {
      const {status} = runEmailValidation()

      if (status === 'invalid') return
      if (!language) {
        setLanguageError(true)
        return
      }

      await init({
        email,
        language,
      })

      setSuccess(true)
    } catch (e) {
      let error: React.ReactNode = _(
        msg`Something went wrong, please try again`,
      )

      if (e instanceof XRPCError) {
        if (e.error === 'InvalidEmail') {
          error = _(
            msg`Please enter a valid, non-temporary email address. You may need to access this email in the future.`,
          )
          logger.metric('ageAssurance:initDialogError', {code: 'InvalidEmail'})
        } else if (e.error === 'DidTooLong') {
          error = (
            <>
              <Trans>
                We're having issues initializing the age assurance process for
                your account. Please{' '}
                <InlineLinkText
                  to={createSupportLink({code: SupportCode.AA_DID, email})}
                  label={_(msg`Contact support`)}>
                  contact support
                </InlineLinkText>{' '}
                for assistance.
              </Trans>
            </>
          )
          logger.metric('ageAssurance:initDialogError', {code: 'DidTooLong'})
        } else {
          logger.metric('ageAssurance:initDialogError', {code: 'other'})
        }
      } else {
        const {clean, raw} = cleanError(e)
        error = clean || raw || error
        logger.metric('ageAssurance:initDialogError', {code: 'other'})
      }

      setError(error)
    }
  }

  return (
    <View>
      <View style={[a.align_start]}>
        <AgeAssuranceBadge />

        <Text style={[a.text_xl, a.font_heavy, a.pt_xl, a.pb_md]}>
          {success ? <Trans>Success!</Trans> : <Trans>Verify your age</Trans>}
        </Text>

        <View style={[a.pb_xl, a.gap_sm]}>
          {success ? (
            <Text style={[a.text_sm, a.leading_snug]}>
              <Trans>
                Please check your email inbox for further instructions. It may
                take a minute or two to arrive.
              </Trans>
            </Text>
          ) : (
            <>
              <Text style={[a.text_sm, a.leading_snug]}>
                <Trans>
                  We have partnered with{' '}
                  <InlineLinkText
                    overridePresentation
                    disableMismatchWarning
                    label={_(msg`KWS website`)}
                    to={urls.kwsHome}
                    style={[a.text_sm, a.leading_snug]}>
                    KWS
                  </InlineLinkText>{' '}
                  to verify that you’re an adult. When you click "Begin" below,
                  KWS will check if you have previously verified your age using
                  this email address for other games/services powered by KWS
                  technology. If not, KWS will email you instructions for
                  verifying your age. When you’re done, you'll be brought back
                  to continue using Bluesky.
                </Trans>
              </Text>
              <Text style={[a.text_sm, a.leading_snug]}>
                <Trans>This should only take a few minutes.</Trans>
              </Text>
            </>
          )}
        </View>

        {success ? (
          <View style={[a.w_full]}>
            <Button
              label={_(msg`Close dialog`)}
              size="large"
              variant="solid"
              color="secondary"
              onPress={() => close()}>
              <ButtonText>
                <Trans>Close dialog</Trans>
              </ButtonText>
            </Button>
          </View>
        ) : (
          <>
            <Divider />

            <View style={[a.w_full, a.pt_xl, a.gap_lg, a.pb_lg]}>
              {wasRecentlyInitiated && (
                <Admonition type="warning">
                  <Trans>
                    You initiated this flow already,{' '}
                    {getTimeAgo(lastInitiatedAt, new Date(), {format: 'long'})}{' '}
                    ago. It may take up to 5 minutes for emails to reach your
                    inbox. Please consider waiting a few minutes before trying
                    again.
                  </Trans>
                </Admonition>
              )}

              <View>
                <TextField.LabelText>
                  <Trans>Your email</Trans>
                </TextField.LabelText>
                <TextField.Root isInvalid={!!emailError}>
                  <TextField.Input
                    label={_(msg`Your email`)}
                    placeholder={_(msg`Your email`)}
                    value={email}
                    onChangeText={setEmail}
                    onFocus={() => setEmailError('')}
                    onBlur={() => {
                      runEmailValidation()
                    }}
                    returnKeyType="done"
                    autoCapitalize="none"
                    autoComplete="off"
                    autoCorrect={false}
                    onSubmitEditing={onSubmit}
                  />
                </TextField.Root>

                {emailError ? (
                  <Admonition type="error" style={[a.mt_sm]}>
                    {emailError}
                  </Admonition>
                ) : (
                  <Admonition type="tip" style={[a.mt_sm]}>
                    <Trans>
                      Use your account email address, or another real email
                      address you control, in case KWS or Bluesky needs to
                      contact you.
                    </Trans>
                  </Admonition>
                )}
              </View>

              <View>
                <TextField.LabelText>
                  <Trans>Your preferred language</Trans>
                </TextField.LabelText>
                <LanguageSelect
                  value={language}
                  onChange={value => {
                    setLanguage(value)
                    setLanguageError(false)
                  }}
                  items={KWS_SUPPORTED_LANGS}
                />

                {languageError && (
                  <Admonition type="error" style={[a.mt_sm]}>
                    <Trans>Please select a language</Trans>
                  </Admonition>
                )}
              </View>

              {error && <Admonition type="error">{error}</Admonition>}

              <Button
                disabled={disabled}
                label={_(msg`Begin age assurance process`)}
                size="large"
                variant="solid"
                color="primary"
                onPress={onSubmit}>
                <ButtonText>
                  <Trans>Begin</Trans>
                </ButtonText>
                <ButtonIcon
                  icon={isPending ? Loader : Shield}
                  position="right"
                />
              </Button>
            </View>

            <Text
              style={[a.text_xs, a.leading_snug, t.atoms.text_contrast_medium]}>
              <Trans>
                By continuing, you agree to the{' '}
                <InlineLinkText
                  overridePresentation
                  disableMismatchWarning
                  label={_(msg`KWS Terms of Use`)}
                  to={urls.kwsTermsOfUse}
                  style={[a.text_xs, a.leading_snug]}>
                  KWS Terms of Use
                </InlineLinkText>{' '}
                and acknowledge that KWS will store your verified status with
                your hashed email address in accordance with the{' '}
                <InlineLinkText
                  overridePresentation
                  disableMismatchWarning
                  label={_(msg`KWS Privacy Policy`)}
                  to={urls.kwsPrivacyPolicy}
                  style={[a.text_xs, a.leading_snug]}>
                  KWS Privacy Policy
                </InlineLinkText>
                . This means you wont need to verify again the next time you
                use this email for other apps, games, and services powered by
                KWS technology.
              </Trans>
            </Text>
          </>
        )}
      </View>
    </View>
  )
}

// best-effort mapping of our languages to KWS supported languages
function convertToKWSSupportedLanguage(
  appLanguage: string,
): string | undefined {
  // `${Enum}` is how you get a type of string union of the enum values (???) -sfn
  switch (appLanguage as `${AppLanguage}`) {
    // only en is supported
    case 'en-GB':
      return 'en'
    // pt-PT is pt (pt-BR is supported independently)
    case 'pt-PT':
      return 'pt'
    // only chinese (simplified) is supported, map all chinese variants
    case 'zh-Hans-CN':
    case 'zh-Hant-HK':
    case 'zh-Hant-TW':
      return 'zh-Hans'
    default:
      // try and map directly - if undefined, they will have to pick from the dropdown
      return KWS_SUPPORTED_LANGS.find(v => v.value === appLanguage)?.value
  }
}