about summary refs log tree commit diff
path: root/src/view/com/modals
diff options
context:
space:
mode:
Diffstat (limited to 'src/view/com/modals')
-rw-r--r--src/view/com/modals/AddAppPasswords.tsx15
-rw-r--r--src/view/com/modals/ChangePassword.tsx336
-rw-r--r--src/view/com/modals/DeleteAccount.tsx22
-rw-r--r--src/view/com/modals/Modal.tsx4
-rw-r--r--src/view/com/modals/Modal.web.tsx3
5 files changed, 359 insertions, 21 deletions
diff --git a/src/view/com/modals/AddAppPasswords.tsx b/src/view/com/modals/AddAppPasswords.tsx
index 5048a0041..a8913dd54 100644
--- a/src/view/com/modals/AddAppPasswords.tsx
+++ b/src/view/com/modals/AddAppPasswords.tsx
@@ -62,7 +62,8 @@ export function Component({}: {}) {
   const {_} = useLingui()
   const {closeModal} = useModalControls()
   const {data: passwords} = useAppPasswordsQuery()
-  const createMutation = useAppPasswordCreateMutation()
+  const {mutateAsync: mutateAppPassword, isPending} =
+    useAppPasswordCreateMutation()
   const [name, setName] = useState(
     shadesOfBlue[Math.floor(Math.random() * shadesOfBlue.length)],
   )
@@ -107,7 +108,7 @@ export function Component({}: {}) {
     }
 
     try {
-      const newPassword = await createMutation.mutateAsync({name})
+      const newPassword = await mutateAppPassword({name})
       if (newPassword) {
         setAppPassword(newPassword.password)
       } else {
@@ -170,13 +171,10 @@ export function Component({}: {}) {
               autoFocus={true}
               maxLength={32}
               selectTextOnFocus={true}
-              multiline={true} // need this to be true otherwise selectTextOnFocus doesn't work
-              numberOfLines={1} // hack for multiline so only one line shows (android)
-              scrollEnabled={false} // hack for multiline so only one line shows (ios)
-              blurOnSubmit={true} // hack for multiline so it submits
-              editable={!appPassword}
+              blurOnSubmit={true}
+              editable={!isPending}
               returnKeyType="done"
-              onEndEditing={createAppPassword}
+              onSubmitEditing={createAppPassword}
               accessible={true}
               accessibilityLabel={_(msg`Name`)}
               accessibilityHint={_(msg`Input name for app password`)}
@@ -253,7 +251,6 @@ const styles = StyleSheet.create({
     width: '100%',
     paddingVertical: 10,
     paddingHorizontal: 8,
-    marginTop: 6,
     fontSize: 17,
     letterSpacing: 0.25,
     fontWeight: '400',
diff --git a/src/view/com/modals/ChangePassword.tsx b/src/view/com/modals/ChangePassword.tsx
new file mode 100644
index 000000000..d8add9794
--- /dev/null
+++ b/src/view/com/modals/ChangePassword.tsx
@@ -0,0 +1,336 @@
+import React, {useState} from 'react'
+import {
+  ActivityIndicator,
+  SafeAreaView,
+  StyleSheet,
+  TouchableOpacity,
+  View,
+} from 'react-native'
+import {ScrollView} from './util'
+import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
+import {TextInput} from './util'
+import {Text} from '../util/text/Text'
+import {Button} from '../util/forms/Button'
+import {ErrorMessage} from '../util/error/ErrorMessage'
+import {s, colors} from 'lib/styles'
+import {usePalette} from 'lib/hooks/usePalette'
+import {isAndroid, isWeb} from 'platform/detection'
+import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
+import {cleanError, isNetworkError} from 'lib/strings/errors'
+import {checkAndFormatResetCode} from 'lib/strings/password'
+import {Trans, msg} from '@lingui/macro'
+import {useLingui} from '@lingui/react'
+import {useModalControls} from '#/state/modals'
+import {useSession, getAgent} from '#/state/session'
+import * as EmailValidator from 'email-validator'
+import {logger} from '#/logger'
+
+enum Stages {
+  RequestCode,
+  ChangePassword,
+  Done,
+}
+
+export const snapPoints = isAndroid ? ['90%'] : ['45%']
+
+export function Component() {
+  const pal = usePalette('default')
+  const {currentAccount} = useSession()
+  const {_} = useLingui()
+  const [stage, setStage] = useState<Stages>(Stages.RequestCode)
+  const [isProcessing, setIsProcessing] = useState<boolean>(false)
+  const [resetCode, setResetCode] = useState<string>('')
+  const [newPassword, setNewPassword] = useState<string>('')
+  const [error, setError] = useState<string>('')
+  const {isMobile} = useWebMediaQueries()
+  const {closeModal} = useModalControls()
+  const agent = getAgent()
+
+  const onRequestCode = async () => {
+    if (
+      !currentAccount?.email ||
+      !EmailValidator.validate(currentAccount.email)
+    ) {
+      return setError(_(msg`Your email appears to be invalid.`))
+    }
+
+    setError('')
+    setIsProcessing(true)
+    try {
+      await agent.com.atproto.server.requestPasswordReset({
+        email: currentAccount.email,
+      })
+      setStage(Stages.ChangePassword)
+    } catch (e: any) {
+      const errMsg = e.toString()
+      logger.warn('Failed to request password reset', {error: e})
+      if (isNetworkError(e)) {
+        setError(
+          _(
+            msg`Unable to contact your service. Please check your Internet connection.`,
+          ),
+        )
+      } else {
+        setError(cleanError(errMsg))
+      }
+    } finally {
+      setIsProcessing(false)
+    }
+  }
+
+  const onChangePassword = async () => {
+    const formattedCode = checkAndFormatResetCode(resetCode)
+    // TODO Better password strength check
+    if (!formattedCode || !newPassword) {
+      setError(
+        _(
+          msg`You have entered an invalid code. It should look like XXXXX-XXXXX.`,
+        ),
+      )
+      return
+    }
+
+    setError('')
+    setIsProcessing(true)
+    try {
+      await agent.com.atproto.server.resetPassword({
+        token: formattedCode,
+        password: newPassword,
+      })
+      setStage(Stages.Done)
+    } catch (e: any) {
+      const errMsg = e.toString()
+      logger.warn('Failed to set new password', {error: e})
+      if (isNetworkError(e)) {
+        setError(
+          'Unable to contact your service. Please check your Internet connection.',
+        )
+      } else {
+        setError(cleanError(errMsg))
+      }
+    } finally {
+      setIsProcessing(false)
+    }
+  }
+
+  const onBlur = () => {
+    const formattedCode = checkAndFormatResetCode(resetCode)
+    if (!formattedCode) {
+      setError(
+        _(
+          msg`You have entered an invalid code. It should look like XXXXX-XXXXX.`,
+        ),
+      )
+      return
+    }
+    setResetCode(formattedCode)
+  }
+
+  return (
+    <SafeAreaView style={[pal.view, s.flex1]}>
+      <ScrollView
+        contentContainerStyle={[
+          styles.container,
+          isMobile && styles.containerMobile,
+        ]}
+        keyboardShouldPersistTaps="handled">
+        <View>
+          <View style={styles.titleSection}>
+            <Text type="title-lg" style={[pal.text, styles.title]}>
+              {stage !== Stages.Done ? 'Change Password' : 'Password Changed'}
+            </Text>
+          </View>
+
+          <Text type="lg" style={[pal.textLight, {marginBottom: 10}]}>
+            {stage === Stages.RequestCode ? (
+              <Trans>
+                If you want to change your password, we will send you a code to
+                verify that this is your account.
+              </Trans>
+            ) : stage === Stages.ChangePassword ? (
+              <Trans>
+                Enter the code you received to change your password.
+              </Trans>
+            ) : (
+              <Trans>Your password has been changed successfully!</Trans>
+            )}
+          </Text>
+
+          {stage === Stages.RequestCode && (
+            <View style={[s.flexRow, s.justifyCenter, s.mt10]}>
+              <TouchableOpacity
+                testID="skipSendEmailButton"
+                onPress={() => setStage(Stages.ChangePassword)}
+                accessibilityRole="button"
+                accessibilityLabel={_(msg`Go to next`)}
+                accessibilityHint={_(msg`Navigates to the next screen`)}>
+                <Text type="xl" style={[pal.link, s.pr5]}>
+                  <Trans>Already have a code?</Trans>
+                </Text>
+              </TouchableOpacity>
+            </View>
+          )}
+          {stage === Stages.ChangePassword && (
+            <View style={[pal.border, styles.group]}>
+              <View style={[styles.groupContent]}>
+                <FontAwesomeIcon
+                  icon="ticket"
+                  style={[pal.textLight, styles.groupContentIcon]}
+                />
+                <TextInput
+                  testID="codeInput"
+                  style={[pal.text, styles.textInput]}
+                  placeholder="Reset code"
+                  placeholderTextColor={pal.colors.textLight}
+                  value={resetCode}
+                  onChangeText={setResetCode}
+                  onFocus={() => setError('')}
+                  onBlur={onBlur}
+                  accessible={true}
+                  accessibilityLabel={_(msg`Reset Code`)}
+                  accessibilityHint=""
+                  autoCapitalize="none"
+                  autoCorrect={false}
+                  autoComplete="off"
+                />
+              </View>
+              <View
+                style={[
+                  pal.borderDark,
+                  styles.groupContent,
+                  styles.groupBottom,
+                ]}>
+                <FontAwesomeIcon
+                  icon="lock"
+                  style={[pal.textLight, styles.groupContentIcon]}
+                />
+                <TextInput
+                  testID="codeInput"
+                  style={[pal.text, styles.textInput]}
+                  placeholder="New password"
+                  placeholderTextColor={pal.colors.textLight}
+                  onChangeText={setNewPassword}
+                  secureTextEntry
+                  accessible={true}
+                  accessibilityLabel={_(msg`New Password`)}
+                  accessibilityHint=""
+                  autoCapitalize="none"
+                  autoComplete="new-password"
+                />
+              </View>
+            </View>
+          )}
+          {error ? (
+            <ErrorMessage message={error} style={styles.error} />
+          ) : undefined}
+        </View>
+        <View style={[styles.btnContainer]}>
+          {isProcessing ? (
+            <View style={styles.btn}>
+              <ActivityIndicator color="#fff" />
+            </View>
+          ) : (
+            <View style={{gap: 6}}>
+              {stage === Stages.RequestCode && (
+                <Button
+                  testID="requestChangeBtn"
+                  type="primary"
+                  onPress={onRequestCode}
+                  accessibilityLabel={_(msg`Request Code`)}
+                  accessibilityHint=""
+                  label={_(msg`Request Code`)}
+                  labelContainerStyle={{justifyContent: 'center', padding: 4}}
+                  labelStyle={[s.f18]}
+                />
+              )}
+              {stage === Stages.ChangePassword && (
+                <Button
+                  testID="confirmBtn"
+                  type="primary"
+                  onPress={onChangePassword}
+                  accessibilityLabel={_(msg`Next`)}
+                  accessibilityHint=""
+                  label={_(msg`Next`)}
+                  labelContainerStyle={{justifyContent: 'center', padding: 4}}
+                  labelStyle={[s.f18]}
+                />
+              )}
+              <Button
+                testID="cancelBtn"
+                type={stage !== Stages.Done ? 'default' : 'primary'}
+                onPress={() => {
+                  closeModal()
+                }}
+                accessibilityLabel={
+                  stage !== Stages.Done ? _(msg`Cancel`) : _(msg`Close`)
+                }
+                accessibilityHint=""
+                label={stage !== Stages.Done ? _(msg`Cancel`) : _(msg`Close`)}
+                labelContainerStyle={{justifyContent: 'center', padding: 4}}
+                labelStyle={[s.f18]}
+              />
+            </View>
+          )}
+        </View>
+      </ScrollView>
+    </SafeAreaView>
+  )
+}
+
+const styles = StyleSheet.create({
+  container: {
+    justifyContent: 'space-between',
+  },
+  containerMobile: {
+    paddingHorizontal: 18,
+    paddingBottom: 35,
+  },
+  titleSection: {
+    paddingTop: isWeb ? 0 : 4,
+    paddingBottom: isWeb ? 14 : 10,
+  },
+  title: {
+    textAlign: 'center',
+    fontWeight: '600',
+    marginBottom: 5,
+  },
+  error: {
+    borderRadius: 6,
+  },
+  textInput: {
+    width: '100%',
+    paddingHorizontal: 14,
+    paddingVertical: 10,
+    fontSize: 16,
+  },
+  btn: {
+    flexDirection: 'row',
+    alignItems: 'center',
+    justifyContent: 'center',
+    borderRadius: 32,
+    padding: 14,
+    backgroundColor: colors.blue3,
+  },
+  btnContainer: {
+    paddingTop: 20,
+  },
+  group: {
+    borderWidth: 1,
+    borderRadius: 10,
+    marginVertical: 20,
+  },
+  groupLabel: {
+    paddingHorizontal: 20,
+    paddingBottom: 5,
+  },
+  groupContent: {
+    flexDirection: 'row',
+    alignItems: 'center',
+  },
+  groupBottom: {
+    borderTopWidth: 1,
+  },
+  groupContentIcon: {
+    marginLeft: 10,
+  },
+})
diff --git a/src/view/com/modals/DeleteAccount.tsx b/src/view/com/modals/DeleteAccount.tsx
index 945d7bc89..40d78cfe0 100644
--- a/src/view/com/modals/DeleteAccount.tsx
+++ b/src/view/com/modals/DeleteAccount.tsx
@@ -1,11 +1,12 @@
 import React from 'react'
 import {
+  SafeAreaView,
   ActivityIndicator,
   StyleSheet,
   TouchableOpacity,
   View,
 } from 'react-native'
-import {TextInput} from './util'
+import {TextInput, ScrollView} from './util'
 import LinearGradient from 'react-native-linear-gradient'
 import * as Toast from '../util/Toast'
 import {Text} from '../util/text/Text'
@@ -20,8 +21,9 @@ import {Trans, msg} from '@lingui/macro'
 import {useLingui} from '@lingui/react'
 import {useModalControls} from '#/state/modals'
 import {useSession, useSessionApi, getAgent} from '#/state/session'
+import {isAndroid} from 'platform/detection'
 
-export const snapPoints = ['60%']
+export const snapPoints = isAndroid ? ['90%'] : ['55%']
 
 export function Component({}: {}) {
   const pal = usePalette('default')
@@ -76,8 +78,10 @@ export function Component({}: {}) {
     closeModal()
   }
   return (
-    <View style={[styles.container, pal.view]}>
-      <View style={[styles.innerContainer, pal.view]}>
+    <SafeAreaView style={[s.flex1]}>
+      <ScrollView
+        contentContainerStyle={[pal.view]}
+        keyboardShouldPersistTaps="handled">
         <View style={[styles.titleContainer, pal.view]}>
           <Text type="title-xl" style={[s.textCenter, pal.text]}>
             <Trans>Delete Account</Trans>
@@ -234,18 +238,12 @@ export function Component({}: {}) {
             )}
           </>
         )}
-      </View>
-    </View>
+      </ScrollView>
+    </SafeAreaView>
   )
 }
 
 const styles = StyleSheet.create({
-  container: {
-    flex: 1,
-  },
-  innerContainer: {
-    paddingBottom: 20,
-  },
   titleContainer: {
     display: 'flex',
     flexDirection: 'row',
diff --git a/src/view/com/modals/Modal.tsx b/src/view/com/modals/Modal.tsx
index 7f814d971..4aa10d75b 100644
--- a/src/view/com/modals/Modal.tsx
+++ b/src/view/com/modals/Modal.tsx
@@ -36,6 +36,7 @@ import * as ModerationDetailsModal from './ModerationDetails'
 import * as BirthDateSettingsModal from './BirthDateSettings'
 import * as VerifyEmailModal from './VerifyEmail'
 import * as ChangeEmailModal from './ChangeEmail'
+import * as ChangePasswordModal from './ChangePassword'
 import * as SwitchAccountModal from './SwitchAccount'
 import * as LinkWarningModal from './LinkWarning'
 import * as EmbedConsentModal from './EmbedConsent'
@@ -172,6 +173,9 @@ export function ModalsContainer() {
   } else if (activeModal?.name === 'change-email') {
     snapPoints = ChangeEmailModal.snapPoints
     element = <ChangeEmailModal.Component />
+  } else if (activeModal?.name === 'change-password') {
+    snapPoints = ChangePasswordModal.snapPoints
+    element = <ChangePasswordModal.Component />
   } else if (activeModal?.name === 'switch-account') {
     snapPoints = SwitchAccountModal.snapPoints
     element = <SwitchAccountModal.Component />
diff --git a/src/view/com/modals/Modal.web.tsx b/src/view/com/modals/Modal.web.tsx
index d79663746..384a4772a 100644
--- a/src/view/com/modals/Modal.web.tsx
+++ b/src/view/com/modals/Modal.web.tsx
@@ -34,6 +34,7 @@ import * as ModerationDetailsModal from './ModerationDetails'
 import * as BirthDateSettingsModal from './BirthDateSettings'
 import * as VerifyEmailModal from './VerifyEmail'
 import * as ChangeEmailModal from './ChangeEmail'
+import * as ChangePasswordModal from './ChangePassword'
 import * as LinkWarningModal from './LinkWarning'
 import * as EmbedConsentModal from './EmbedConsent'
 
@@ -134,6 +135,8 @@ function Modal({modal}: {modal: ModalIface}) {
     element = <VerifyEmailModal.Component {...modal} />
   } else if (modal.name === 'change-email') {
     element = <ChangeEmailModal.Component />
+  } else if (modal.name === 'change-password') {
+    element = <ChangePasswordModal.Component />
   } else if (modal.name === 'link-warning') {
     element = <LinkWarningModal.Component {...modal} />
   } else if (modal.name === 'embed-consent') {