Skip to content

Commit

Permalink
fix: refacto front state machine
Browse files Browse the repository at this point in the history
Signed-off-by: clegirar <clemntgirard@gmail.com>
  • Loading branch information
clegirar committed May 13, 2022
1 parent 86eb664 commit 2a1479f
Show file tree
Hide file tree
Showing 34 changed files with 496 additions and 851 deletions.
19 changes: 10 additions & 9 deletions js/packages/components/chat/DeviceList.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import React, { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { View } from 'react-native'
import { useSelector } from 'react-redux'

import { berty } from '@berty/api/root.pb'
import { ButtonDropDown } from '@berty/components/shared-components'
import { useStyles } from '@berty/contexts/styles'
import { selectClient } from '@berty/redux/reducers/ui.reducer'
import { useMessengerClient } from '@berty/store'
import { getDevicesForConversationAndMember } from '@berty/utils/messenger/devices'
import { getSharedPushTokensForConversation } from '@berty/utils/notification/notif-push'

Expand All @@ -19,23 +18,25 @@ const UserDevicesList: React.FC<{ memberPk: string; conversationPk: string }> =
const { t } = useTranslation()
const [tokens, setTokens] = useState<berty.messenger.v1.ISharedPushToken[]>([])
const [devices, setDevices] = useState<berty.messenger.v1.IDevice[]>([])
const client = useSelector(selectClient)
const messengerClient = useMessengerClient()

useEffect(() => {
if (!client) {
if (!messengerClient) {
return
}

getSharedPushTokensForConversation(client, conversationPk).then(setTokens).catch(console.warn)
}, [conversationPk, client, setTokens])
getSharedPushTokensForConversation(messengerClient, conversationPk)
.then(setTokens)
.catch(console.warn)
}, [conversationPk, messengerClient, setTokens])

useEffect(() => {
if (!client) {
if (!messengerClient) {
return
}

getDevicesForConversationAndMember(client, conversationPk, memberPk).then(setDevices)
}, [conversationPk, client, memberPk, setDevices])
getDevicesForConversationAndMember(messengerClient, conversationPk, memberPk).then(setDevices)
}, [conversationPk, messengerClient, memberPk, setDevices])

const tokensMap = Object.fromEntries(tokens.map(t => [t.devicePublicKey, t.token]))

Expand Down
7 changes: 4 additions & 3 deletions js/packages/components/chat/EnableNotificationsButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import PermissionsContext from '@berty/contexts/permissions.context'
import { useStyles } from '@berty/contexts/styles'
import { useAccount, useConversation } from '@berty/hooks'
import { useNavigation } from '@berty/navigation'
import { selectClient, selectProtocolClient } from '@berty/redux/reducers/ui.reducer'
import { selectProtocolClient } from '@berty/redux/reducers/ui.reducer'
import { useMessengerClient } from '@berty/store'
import { numberifyLong } from '@berty/utils/convert/long'
import { conversationPushToggleState, pushAvailable } from '@berty/utils/notification/notif-push'

Expand All @@ -24,7 +25,7 @@ const EnableNotificationsButton: React.FC<{

const conv = useConversation(conversationPk)
const account = useAccount()
const client = useSelector(selectClient)
const messengerClient = useMessengerClient()
const { permissions } = useContext(PermissionsContext)

const pushTokenShared = useMemo(
Expand Down Expand Up @@ -68,7 +69,7 @@ const EnableNotificationsButton: React.FC<{
actionToggle={async () => {
await conversationPushToggleState({
t,
messengerClient: client,
messengerClient,
protocolClient,
conversation: conv,
navigate,
Expand Down
13 changes: 2 additions & 11 deletions js/packages/components/debug/AppInspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -397,10 +397,7 @@ const AccountsInspector: React.FC<{
)
}

const AppInspector: React.FC<{ embedded: boolean; error: Error | null }> = ({
embedded,
error,
}) => {
const AppInspector: React.FC<{ error: Error | null }> = ({ error }) => {
const [lastUpdate, setLastUpdate] = useState(Date.now())
const { t }: { t: any } = useTranslation()
const { text } = useStyles()
Expand Down Expand Up @@ -440,13 +437,7 @@ const AppInspector: React.FC<{ embedded: boolean; error: Error | null }> = ({
<UnifiedText style={[styles.text, styles.header2]}>
{t('debug.inspector.accounts.title')}
</UnifiedText>
{embedded ? (
<AccountsInspector lastRefresh={lastUpdate} setLastUpdate={setLastUpdate} />
) : (
<UnifiedText style={[styles.text]}>
{t('debug.inspector.accounts.unsupported-remote-mode')}
</UnifiedText>
)}
<AccountsInspector lastRefresh={lastUpdate} setLastUpdate={setLastUpdate} />
</ScrollView>
<View style={{ position: 'absolute', bottom: 30, left: 0, right: 0 }}>
<View style={{ flexDirection: 'row', paddingHorizontal: 12 }}>
Expand Down
5 changes: 2 additions & 3 deletions js/packages/components/error.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import RNRestart from 'react-native-restart'
import { useAppDimensions } from '@berty/contexts/app-dimensions.context'
import { useStyles } from '@berty/contexts/styles'
import { useAppSelector } from '@berty/hooks'
import { selectDebugMode, selectEmbedded } from '@berty/redux/reducers/ui.reducer'
import { selectDebugMode } from '@berty/redux/reducers/ui.reducer'
import { useThemeColor } from '@berty/store'

import AppInspector from './debug/AppInspector'
Expand Down Expand Up @@ -273,7 +273,6 @@ export const ErrorScreen: React.FC = ({ children }) => {
const [error, setError] = React.useState<Error | null>(null)

const debugMode = useAppSelector(selectDebugMode)
const embedded = useAppSelector(selectEmbedded)

const errorHandler = (err: Error) => {
setError(err)
Expand All @@ -288,7 +287,7 @@ export const ErrorScreen: React.FC = ({ children }) => {
}, [error])

if (debugMode) {
return <AppInspector embedded={embedded} error={error} />
return <AppInspector error={error} />
}

if (error !== null) {
Expand Down
147 changes: 6 additions & 141 deletions js/packages/components/gates.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,11 @@
import React from 'react'
import {
ActivityIndicator,
Button,
TextInput,
View,
Image,
StatusBar,
Platform,
} from 'react-native'
import * as Progress from 'react-native-progress'
import { View, Image, StatusBar } from 'react-native'
import { useSelector } from 'react-redux'

import source from '@berty/assets/images/loader_dots.gif'
import { useAppDimensions } from '@berty/contexts/app-dimensions.context'
import { useStyles } from '@berty/contexts/styles'
import { useAppDispatch } from '@berty/hooks'
import { useDeleteAccount, useRestart } from '@berty/hooks'
import {
selectDaemonAddress,
selectEmbedded,
selectMessengerisClosing,
selectMessengerIsReadyingBasics,
selectStreamError,
selectStreamInProgress,
setDaemonAddress,
} from '@berty/redux/reducers/ui.reducer'
import { selectMessengerIsNotReady } from '@berty/redux/reducers/ui.reducer'
import { useThemeColor } from '@berty/store'

import { UnifiedText } from './shared-components/UnifiedText'

export const LoaderDots: React.FC = () => {
const colors = useThemeColor()

Expand All @@ -51,108 +28,12 @@ export const LoaderDots: React.FC = () => {
)
}

const StreamInProgressCmp: React.FC<{}> = () => {
const { text } = useStyles()
const { scaleSize } = useAppDimensions()
export const LoaderGate: React.FC = ({ children }) => {
const colors = useThemeColor()
const stream = useSelector(selectStreamInProgress)

return (
<View style={{ backgroundColor: colors['main-background'], flex: 1 }}>
<StatusBar backgroundColor={colors['main-background']} barStyle='dark-content' />

<UnifiedText
style={[
text.align.center,
{
position: 'absolute',
top: 60 * scaleSize,
left: 0,
right: 0,
},
]}
>
{stream?.stream || 'Test'}
</UnifiedText>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}
>
<UnifiedText style={[text.align.center]}>{stream?.msg.doing || 'Doing'}</UnifiedText>
<UnifiedText style={[text.align.center]}>
{stream?.msg.completed || '0'} / {stream?.msg.total || '6'}
</UnifiedText>
{Platform.OS === 'web' ? (
<ActivityIndicator size='large' />
) : (
<Progress.Bar progress={stream?.msg.progress || 0} width={200} color='#3946E1' />
)}
</View>
</View>
)
}

const gutter = 50
const isNotReady = useSelector(selectMessengerIsNotReady)

export const StreamGate: React.FC = ({ children }) => {
const streamInProgress = useSelector(selectStreamInProgress)
const embedded = useSelector(selectEmbedded)
const streamError = useSelector(selectStreamError)
const deleteAccount = useDeleteAccount()
const daemonAddress = useSelector(selectDaemonAddress)
const dispatch = useAppDispatch()
const restart = useRestart()

const [newAddress, setNewAddress] = React.useState(daemonAddress)
const colors = useThemeColor()
const changeAddress = React.useCallback(() => {
dispatch(setDaemonAddress({ value: newAddress }))
}, [dispatch, newAddress])

if (streamError && !streamInProgress) {
return (
<View
style={[
{
padding: gutter,
alignItems: 'center',
justifyContent: 'center',
paddingBottom: 30,
height: '100%',
width: '100%',
},
]}
>
<StatusBar backgroundColor={colors['main-background']} barStyle='dark-content' />
<UnifiedText style={{ color: colors['warning-asset'] }}>
{streamError.toString()}
</UnifiedText>
<UnifiedText style={{ marginTop: gutter }}>
Likely couldn't connect to the node, or the connection dropped
</UnifiedText>
{embedded || (
<>
<TextInput
onChangeText={setNewAddress}
value={newAddress}
style={{ backgroundColor: colors['secondary-text'] }}
/>
<Button title='Change node address' onPress={changeAddress} />
</>
)}
<View style={{ marginTop: gutter }}>
<Button onPress={() => restart()} title='Restart' />
</View>
<View style={{ marginTop: gutter }}>
<Button onPress={() => deleteAccount()} title='Delete account' />
</View>
</View>
)
} else if (streamInProgress?.msg) {
return <StreamInProgressCmp />
if (isNotReady) {
return <LoaderDots />
}
return (
<>
Expand All @@ -161,19 +42,3 @@ export const StreamGate: React.FC = ({ children }) => {
</>
)
}

export const ListGate: React.FC = ({ children }) => {
const colors = useThemeColor()
const isClosing = useSelector(selectMessengerisClosing)
const isReadyingBasics = useSelector(selectMessengerIsReadyingBasics)

if (!isClosing && !isReadyingBasics) {
return (
<>
<StatusBar backgroundColor={colors['main-background']} barStyle='dark-content' />
{children}
</>
)
}
return <LoaderDots />
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const FingerprintContentText: React.FC<FingerprintContentProps> = ({ fingerprint
style={[
text.bold,
_styles.fingerprintContentText,
{ fontFamily: 'Courier, monospace', color: colors['background-header'] },
{ fontFamily: 'Courier', color: colors['background-header'] },
]}
>
{fingerprint.toUpperCase()}
Expand Down
22 changes: 6 additions & 16 deletions js/packages/hooks/accounts.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useCallback } from 'react'

import beapi from '@berty/api'
import { selectEmbedded, selectSelectedAccount } from '@berty/redux/reducers/ui.reducer'
import { selectSelectedAccount } from '@berty/redux/reducers/ui.reducer'
import {
createNewAccount,
deleteAccount,
Expand All @@ -14,38 +14,28 @@ import { useAccount } from './messenger.hooks'

export const useDeleteAccount = () => {
const dispatch = useAppDispatch()
const embedded = useAppSelector(selectEmbedded)
const selectedAccount = useAppSelector(selectSelectedAccount)
return useCallback(
() => deleteAccount(embedded, selectedAccount, dispatch),
[embedded, selectedAccount, dispatch],
)
return useCallback(() => deleteAccount(selectedAccount, dispatch), [selectedAccount, dispatch])
}

export const useSwitchAccount = () => {
const dispatch = useAppDispatch()
const embedded = useAppSelector(selectEmbedded)
return useCallback(
(account: string) => switchAccount(embedded, account, dispatch),
[embedded, dispatch],
)
return useCallback((account: string) => switchAccount(account, dispatch), [dispatch])
}

export const useCreateNewAccount = () => {
const dispatch = useAppDispatch()
const embedded = useAppSelector(selectEmbedded)
return useCallback(
(newConfig?: beapi.account.INetworkConfig) => createNewAccount(embedded, dispatch, newConfig),
[embedded, dispatch],
(newConfig?: beapi.account.INetworkConfig) => createNewAccount(dispatch, newConfig),
[dispatch],
)
}

/**
* Returns a function to update the AccountService account
*/
export const useUpdateAccount = () => {
const embedded = useAppSelector(selectEmbedded)
return useCallback((payload: any) => updateAccount(embedded, payload), [embedded])
return useCallback((payload: any) => updateAccount(payload), [])
}

export const useAccountServices = (): Array<beapi.messenger.IServiceToken> => {
Expand Down
8 changes: 2 additions & 6 deletions js/packages/hooks/ui.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
PersistentOptionsKeys,
selectPersistentOptions,
} from '@berty/redux/reducers/persistentOptions.reducer'
import { selectEmbedded, selectSelectedAccount } from '@berty/redux/reducers/ui.reducer'
import { selectSelectedAccount } from '@berty/redux/reducers/ui.reducer'
import { restart } from '@berty/utils/accounts/accountUtils'
import { SoundKey } from '@berty/utils/sound/sound.types'
import { playSound } from '@berty/utils/sound/sounds'
Expand All @@ -26,10 +26,6 @@ export const usePlaySound = () => {

export const useRestart = () => {
const dispatch = useAppDispatch()
const embedded = useAppSelector(selectEmbedded)
const selectedAccount = useAppSelector(selectSelectedAccount)
return useCallback(
() => restart(embedded, selectedAccount, dispatch),
[selectedAccount, embedded, dispatch],
)
return useCallback(() => restart(selectedAccount, dispatch), [selectedAccount, dispatch])
}

0 comments on commit 2a1479f

Please sign in to comment.