about summary refs log tree commit diff
path: root/src/view
diff options
context:
space:
mode:
authorPaul Frazee <pfrazee@gmail.com>2023-11-16 11:11:56 -0800
committerGitHub <noreply@github.com>2023-11-16 11:11:56 -0800
commit9f7a162a96200aaca0512765eff938a88c84d6d6 (patch)
treed88bd9fe72c7ec6d1bc156a02b25828fb2905a96 /src/view
parent310a7eaca747e53fb24692998ffe9343762d681f (diff)
downloadvoidsky-9f7a162a96200aaca0512765eff938a88c84d6d6.tar.zst
Refactor app passwords to use react-query (#1932)
Diffstat (limited to 'src/view')
-rw-r--r--src/view/com/modals/AddAppPasswords.tsx25
-rw-r--r--src/view/com/util/Toast.tsx6
-rw-r--r--src/view/com/util/Toast.web.tsx9
-rw-r--r--src/view/screens/AppPasswords.tsx139
4 files changed, 121 insertions, 58 deletions
diff --git a/src/view/com/modals/AddAppPasswords.tsx b/src/view/com/modals/AddAppPasswords.tsx
index 095ad48bd..812a36f45 100644
--- a/src/view/com/modals/AddAppPasswords.tsx
+++ b/src/view/com/modals/AddAppPasswords.tsx
@@ -3,7 +3,6 @@ import {StyleSheet, TextInput, View, TouchableOpacity} from 'react-native'
 import {Text} from '../util/text/Text'
 import {Button} from '../util/forms/Button'
 import {s} from 'lib/styles'
-import {useStores} from 'state/index'
 import {usePalette} from 'lib/hooks/usePalette'
 import {isNative} from 'platform/detection'
 import {
@@ -16,6 +15,10 @@ import {logger} from '#/logger'
 import {Trans, msg} from '@lingui/macro'
 import {useLingui} from '@lingui/react'
 import {useModalControls} from '#/state/modals'
+import {
+  useAppPasswordsQuery,
+  useAppPasswordCreateMutation,
+} from '#/state/queries/app-passwords'
 
 export const snapPoints = ['70%']
 
@@ -56,9 +59,10 @@ const shadesOfBlue: string[] = [
 
 export function Component({}: {}) {
   const pal = usePalette('default')
-  const store = useStores()
   const {_} = useLingui()
   const {closeModal} = useModalControls()
+  const {data: passwords} = useAppPasswordsQuery()
+  const createMutation = useAppPasswordCreateMutation()
   const [name, setName] = useState(
     shadesOfBlue[Math.floor(Math.random() * shadesOfBlue.length)],
   )
@@ -82,25 +86,34 @@ export function Component({}: {}) {
     if (!name || !name.trim()) {
       Toast.show(
         'Please enter a name for your app password. All spaces is not allowed.',
+        'times',
       )
       return
     }
     // if name is too short (under 4 chars), we don't allow it
     if (name.length < 4) {
-      Toast.show('App Password names must be at least 4 characters long.')
+      Toast.show(
+        'App Password names must be at least 4 characters long.',
+        'times',
+      )
+      return
+    }
+
+    if (passwords?.find(p => p.name === name)) {
+      Toast.show('This name is already in use', 'times')
       return
     }
 
     try {
-      const newPassword = await store.me.createAppPassword(name)
+      const newPassword = await createMutation.mutateAsync({name})
       if (newPassword) {
         setAppPassword(newPassword.password)
       } else {
-        Toast.show('Failed to create app password.')
+        Toast.show('Failed to create app password.', 'times')
         // TODO: better error handling (?)
       }
     } catch (e) {
-      Toast.show('Failed to create app password.')
+      Toast.show('Failed to create app password.', 'times')
       logger.error('Failed to create app password', {error: e})
     }
   }
diff --git a/src/view/com/util/Toast.tsx b/src/view/com/util/Toast.tsx
index 4c9045d1e..c7134febe 100644
--- a/src/view/com/util/Toast.tsx
+++ b/src/view/com/util/Toast.tsx
@@ -1,6 +1,7 @@
 import RootSiblings from 'react-native-root-siblings'
 import React from 'react'
 import {Animated, StyleSheet, View} from 'react-native'
+import {Props as FontAwesomeProps} from '@fortawesome/react-native-fontawesome'
 import {Text} from './text/Text'
 import {colors} from 'lib/styles'
 import {useTheme} from 'lib/ThemeContext'
@@ -9,7 +10,10 @@ import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
 
 const TIMEOUT = 4e3
 
-export function show(message: string) {
+export function show(
+  message: string,
+  _icon: FontAwesomeProps['icon'] = 'check',
+) {
   const item = new RootSiblings(<Toast message={message} />)
   setTimeout(() => {
     item.destroy()
diff --git a/src/view/com/util/Toast.web.tsx b/src/view/com/util/Toast.web.tsx
index c295bad69..beb67c30c 100644
--- a/src/view/com/util/Toast.web.tsx
+++ b/src/view/com/util/Toast.web.tsx
@@ -7,12 +7,14 @@ import {StyleSheet, Text, View} from 'react-native'
 import {
   FontAwesomeIcon,
   FontAwesomeIconStyle,
+  Props as FontAwesomeProps,
 } from '@fortawesome/react-native-fontawesome'
 
 const DURATION = 3500
 
 interface ActiveToast {
   text: string
+  icon: FontAwesomeProps['icon']
 }
 type GlobalSetActiveToast = (_activeToast: ActiveToast | undefined) => void
 
@@ -36,7 +38,7 @@ export const ToastContainer: React.FC<ToastContainerProps> = ({}) => {
       {activeToast && (
         <View style={styles.container}>
           <FontAwesomeIcon
-            icon="check"
+            icon={activeToast.icon}
             size={24}
             style={styles.icon as FontAwesomeIconStyle}
           />
@@ -49,11 +51,12 @@ export const ToastContainer: React.FC<ToastContainerProps> = ({}) => {
 
 // methods
 // =
-export function show(text: string) {
+
+export function show(text: string, icon: FontAwesomeProps['icon'] = 'check') {
   if (toastTimeout) {
     clearTimeout(toastTimeout)
   }
-  globalSetActiveToast?.({text})
+  globalSetActiveToast?.({text, icon})
   toastTimeout = setTimeout(() => {
     globalSetActiveToast?.(undefined)
   }, DURATION)
diff --git a/src/view/screens/AppPasswords.tsx b/src/view/screens/AppPasswords.tsx
index 092f4bc2c..b2eee392a 100644
--- a/src/view/screens/AppPasswords.tsx
+++ b/src/view/screens/AppPasswords.tsx
@@ -1,15 +1,18 @@
 import React from 'react'
-import {StyleSheet, TouchableOpacity, View} from 'react-native'
+import {
+  ActivityIndicator,
+  StyleSheet,
+  TouchableOpacity,
+  View,
+} from 'react-native'
 import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
 import {ScrollView} from 'react-native-gesture-handler'
 import {Text} from '../com/util/text/Text'
 import {Button} from '../com/util/forms/Button'
 import * as Toast from '../com/util/Toast'
-import {useStores} from 'state/index'
 import {usePalette} from 'lib/hooks/usePalette'
 import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
 import {withAuthRequired} from 'view/com/auth/withAuthRequired'
-import {observer} from 'mobx-react-lite'
 import {NativeStackScreenProps} from '@react-navigation/native-stack'
 import {CommonNavigatorParams} from 'lib/routes/types'
 import {useAnalytics} from 'lib/analytics/analytics'
@@ -21,16 +24,22 @@ import {useLingui} from '@lingui/react'
 import {useSetMinimalShellMode} from '#/state/shell'
 import {useModalControls} from '#/state/modals'
 import {useLanguagePrefs} from '#/state/preferences'
+import {
+  useAppPasswordsQuery,
+  useAppPasswordDeleteMutation,
+} from '#/state/queries/app-passwords'
+import {ErrorScreen} from '../com/util/error/ErrorScreen'
+import {cleanError} from '#/lib/strings/errors'
 
 type Props = NativeStackScreenProps<CommonNavigatorParams, 'AppPasswords'>
 export const AppPasswords = withAuthRequired(
-  observer(function AppPasswordsImpl({}: Props) {
+  function AppPasswordsImpl({}: Props) {
     const pal = usePalette('default')
-    const store = useStores()
     const setMinimalShellMode = useSetMinimalShellMode()
     const {screen} = useAnalytics()
     const {isTabletOrDesktop} = useWebMediaQueries()
     const {openModal} = useModalControls()
+    const {data: appPasswords, error} = useAppPasswordsQuery()
 
     useFocusEffect(
       React.useCallback(() => {
@@ -43,8 +52,27 @@ export const AppPasswords = withAuthRequired(
       openModal({name: 'add-app-password'})
     }, [openModal])
 
+    if (error) {
+      return (
+        <CenteredView
+          style={[
+            styles.container,
+            isTabletOrDesktop && styles.containerDesktop,
+            pal.view,
+            pal.border,
+          ]}
+          testID="appPasswordsScreen">
+          <ErrorScreen
+            title="Oops!"
+            message="There was an issue with fetching your app passwords"
+            details={cleanError(error)}
+          />
+        </CenteredView>
+      )
+    }
+
     // no app passwords (empty) state
-    if (store.me.appPasswords.length === 0) {
+    if (appPasswords?.length === 0) {
       return (
         <CenteredView
           style={[
@@ -82,33 +110,47 @@ export const AppPasswords = withAuthRequired(
       )
     }
 
-    // has app passwords
-    return (
-      <CenteredView
-        style={[
-          styles.container,
-          isTabletOrDesktop && styles.containerDesktop,
-          pal.view,
-          pal.border,
-        ]}
-        testID="appPasswordsScreen">
-        <AppPasswordsHeader />
-        <ScrollView
+    if (appPasswords?.length) {
+      // has app passwords
+      return (
+        <CenteredView
           style={[
-            styles.scrollContainer,
+            styles.container,
+            isTabletOrDesktop && styles.containerDesktop,
+            pal.view,
             pal.border,
-            !isTabletOrDesktop && styles.flex1,
-          ]}>
-          {store.me.appPasswords.map((password, i) => (
-            <AppPassword
-              key={password.name}
-              testID={`appPassword-${i}`}
-              name={password.name}
-              createdAt={password.createdAt}
-            />
-          ))}
-          {isTabletOrDesktop && (
-            <View style={[styles.btnContainer, styles.btnContainerDesktop]}>
+          ]}
+          testID="appPasswordsScreen">
+          <AppPasswordsHeader />
+          <ScrollView
+            style={[
+              styles.scrollContainer,
+              pal.border,
+              !isTabletOrDesktop && styles.flex1,
+            ]}>
+            {appPasswords.map((password, i) => (
+              <AppPassword
+                key={password.name}
+                testID={`appPassword-${i}`}
+                name={password.name}
+                createdAt={password.createdAt}
+              />
+            ))}
+            {isTabletOrDesktop && (
+              <View style={[styles.btnContainer, styles.btnContainerDesktop]}>
+                <Button
+                  testID="appPasswordBtn"
+                  type="primary"
+                  label="Add App Password"
+                  style={styles.btn}
+                  labelStyle={styles.btnLabel}
+                  onPress={onAdd}
+                />
+              </View>
+            )}
+          </ScrollView>
+          {!isTabletOrDesktop && (
+            <View style={styles.btnContainer}>
               <Button
                 testID="appPasswordBtn"
                 type="primary"
@@ -119,22 +161,23 @@ export const AppPasswords = withAuthRequired(
               />
             </View>
           )}
-        </ScrollView>
-        {!isTabletOrDesktop && (
-          <View style={styles.btnContainer}>
-            <Button
-              testID="appPasswordBtn"
-              type="primary"
-              label="Add App Password"
-              style={styles.btn}
-              labelStyle={styles.btnLabel}
-              onPress={onAdd}
-            />
-          </View>
-        )}
+        </CenteredView>
+      )
+    }
+
+    return (
+      <CenteredView
+        style={[
+          styles.container,
+          isTabletOrDesktop && styles.containerDesktop,
+          pal.view,
+          pal.border,
+        ]}
+        testID="appPasswordsScreen">
+        <ActivityIndicator />
       </CenteredView>
     )
-  }),
+  },
 )
 
 function AppPasswordsHeader() {
@@ -169,10 +212,10 @@ function AppPassword({
   createdAt: string
 }) {
   const pal = usePalette('default')
-  const store = useStores()
   const {_} = useLingui()
   const {openModal} = useModalControls()
   const {contentLanguages} = useLanguagePrefs()
+  const deleteMutation = useAppPasswordDeleteMutation()
 
   const onDelete = React.useCallback(async () => {
     openModal({
@@ -180,11 +223,11 @@ function AppPassword({
       title: 'Delete App Password',
       message: `Are you sure you want to delete the app password "${name}"?`,
       async onPressConfirm() {
-        await store.me.deleteAppPassword(name)
+        await deleteMutation.mutateAsync({name})
         Toast.show('App password deleted')
       },
     })
-  }, [store, openModal, name])
+  }, [deleteMutation, openModal, name])
 
   const primaryLocale =
     contentLanguages.length > 0 ? contentLanguages[0] : 'en-US'