Skip to content

Commit

Permalink
[Issue-1049]: Improve deeplink (Add more deeplink type)
Browse files Browse the repository at this point in the history
  • Loading branch information
dominhquang committed Oct 9, 2023
1 parent 5f9e390 commit 10d707f
Show file tree
Hide file tree
Showing 10 changed files with 263 additions and 100 deletions.
128 changes: 126 additions & 2 deletions src/AppNavigator.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NavigationState } from '@react-navigation/routers';
import { ALL_ACCOUNT_KEY } from '@subwallet/extension-base/constants';
import React, { ComponentType, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import React, { ComponentType, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { LinkingOptions, NavigationContainer, StackActions, useNavigationContainerRef } from '@react-navigation/native';
import AttachReadOnly from 'screens/Account/AttachReadOnly';
import ConnectKeystone from 'screens/Account/ConnectQrSigner/ConnectKeystone';
Expand Down Expand Up @@ -53,7 +53,7 @@ import { AddProvider } from 'screens/AddProvider';
import TransactionScreen from 'screens/Transaction/TransactionScreen';
import SendNFT from 'screens/Transaction/NFT';
import changeNavigationBarColor from 'react-native-navigation-bar-color';
import { Keyboard, Platform, StatusBar } from 'react-native';
import { Keyboard, Linking, Platform, StatusBar } from 'react-native';
import { useSubWalletTheme } from 'hooks/useSubWalletTheme';
import { Home } from 'screens/Home';
import { deviceWidth } from 'constants/index';
Expand All @@ -72,6 +72,11 @@ import { STATUS_BAR_LIGHT_CONTENT } from 'styles/sharedStyles';
import { UnlockModal } from 'components/common/Modal/UnlockModal';
import { AppModalContext } from 'providers/AppModalContext';
import { PortalHost } from '@gorhom/portal';
import { findAccountByAddress } from 'utils/index';
import { CurrentAccountInfo } from '@subwallet/extension-base/background/KoniTypes';
import { saveCurrentAccountAddress, updateAssetSetting } from 'messaging/index';
import urlParse from 'url-parse';
import useChainChecker from 'hooks/chain/useChainChecker';

interface Props {
isAppReady: boolean;
Expand All @@ -97,6 +102,65 @@ const config: LinkingOptions<RootStackParamList>['config'] = {
name: name => name || '',
},
},
Home: {
path: 'home',
screens: {
Main: {
path: 'main',
screens: {
Tokens: {
path: 'tokens',
initialRouteName: 'TokenGroups',
screens: {
TokenGroupsDetail: {
path: 'token-groups-detail',
stringify: {
address: (address: string) => address,
slug: (slug: string) => slug,
},
},
},
},
NFTs: {
path: 'nfts',
screens: {
Collection: {
path: 'collection',
stringify: {
collectionId: (collectionId: string) => collectionId,
},
},
NftDetail: {
path: 'nft-detail',
stringify: {
collectionId: (collectionId: string) => collectionId,
nftId: (nftId: string) => nftId,
},
},
},
},
Crowdloans: {
path: 'crowdloans',
},
Staking: {
path: 'staking',
screens: {
StakingBalances: {
path: 'staking-balances',
stringify: {
chain: (chain: string) => chain,
type: (type: string) => type,
},
},
},
},
Browser: {
path: 'browser-home',
},
},
},
},
},
},
};

Expand Down Expand Up @@ -132,6 +196,10 @@ const ConnectionListScreen = (props: JSX.IntrinsicAttributes) => {
return withPageWrapper(ConnectionList as ComponentType, ['walletConnect'])(props);
};

type DeepLinkSubscriptionType = {
url: string;
};

const AppNavigator = ({ isAppReady }: Props) => {
const isDarkMode = true;
const theme = isDarkMode ? THEME_PRESET.dark : THEME_PRESET.light;
Expand All @@ -145,6 +213,12 @@ const AppNavigator = ({ isAppReady }: Props) => {
const { isLocked } = useAppLock();
const [isNavigationReady, setNavigationReady] = useState<boolean>(false);
const appModalContext = useContext(AppModalContext);
const isLockedRef = useRef(isLocked);
const { checkChainConnected } = useChainChecker();

useEffect(() => {
isLockedRef.current = isLocked;
}, [isLocked]);

const needMigrate = useMemo(
() =>
Expand All @@ -157,6 +231,56 @@ const AppNavigator = ({ isAppReady }: Props) => {
const linking: LinkingOptions<RootStackParamList> = {
prefixes: deeplinks,
config,
async getInitialURL() {
return Linking.getInitialURL();
},
subscribe: listener => {
const onReceiveURL = ({ url }: DeepLinkSubscriptionType) => {
const parseUrl = new urlParse(url);
const urlQuery = parseUrl.query.substring(1);
const urlQueryMap: Record<string, string> = {};
urlQuery.split('&').forEach(item => {
const splitItem = item.split('=');
urlQueryMap[splitItem[0]] = splitItem[1];
});

const accountByAddress = findAccountByAddress(accounts, urlQueryMap.address);
//change account follow url
if (accountByAddress) {
const accountInfo = {
address: urlQueryMap.address,
} as CurrentAccountInfo;

saveCurrentAccountAddress(accountInfo).catch(e => {
console.error('There is a problem when set Current Account', e);
});
} else {
saveCurrentAccountAddress({ address: 'ALL' }).catch(e => {
console.error('There is a problem when set Current Account', e);
});
}
//enable Network
const originChain = urlQueryMap.slug ? urlQueryMap.slug.split('-')[1].toLowerCase() : '';
const isChainConnected = checkChainConnected(originChain);

if (!isChainConnected && originChain) {
updateAssetSetting({
tokenSlug: urlQueryMap.slug,
assetSetting: {
visible: true,
},
autoEnableNativeToken: true,
});
}
if (isLockedRef.current || hasConfirmations) {
return;
}
listener(url);
};
const linkingListener = Linking.addEventListener('url', onReceiveURL);

return () => linkingListener.remove();
},
};

const onError = (error: Error, stackTrace: string) => {
Expand Down
4 changes: 4 additions & 0 deletions src/AppNew.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,11 @@ AppState.addEventListener('change', (state: string) => {
});

let firstTimeCheckPincode: boolean | undefined;
export let prevDeeplinkUrl = '';

export function setPrevDeeplinkUrl(value: string) {
prevDeeplinkUrl = value;
}
export const AppNew = () => {
const isDarkMode = true;
const theme = isDarkMode ? THEME_PRESET.dark : THEME_PRESET.light;
Expand Down
2 changes: 1 addition & 1 deletion src/routes/home.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { BrowserHomeProps, RootStackParamList } from 'routes/index';

export type CryptoStackParamList = {
TokenGroups: undefined;
TokenGroupsDetail: { slug: string };
TokenGroupsDetail: { slug: string; address?: string };
};

export type CryptoNavigationProps = NativeStackScreenProps<CryptoStackParamList & RootStackParamList>['navigation'];
Expand Down
3 changes: 1 addition & 2 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { NavigatorScreenParams } from '@react-navigation/native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { KeypairType } from '@polkadot/util-crypto/types';
import { HomeStackParamList } from 'routes/home';
import { ConfirmationsQueue } from '@subwallet/extension-base/background/KoniTypes';
import { NftTransferActionStackParamList } from 'routes/nft/transferAction';
import { SigningActionStackParamList } from 'routes/signing';
Expand All @@ -11,7 +10,7 @@ import { WrapperParamList } from 'routes/wrapper';
export type RootStackParamList = {
LockScreen: undefined;
LoadingScreen: undefined;
Home: NavigatorScreenParams<HomeStackParamList> | undefined;
Home: NavigatorScreenParams<WrapperParamList> | undefined;
CreatePassword: {
pathName:
| 'CreateAccount'
Expand Down
2 changes: 1 addition & 1 deletion src/routes/staking/stakingScreen.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NativeStackScreenProps } from '@react-navigation/native-stack';

export type StakingScreenStackParamList = {
StakingBalances: undefined;
StakingBalances: { chain?: string; type?: string };
Stake: { chain?: string; type?: string };
Unbond: { chain?: string; type?: string };
ClaimReward: { chain?: string; type?: string };
Expand Down
10 changes: 3 additions & 7 deletions src/screens/Home/Crypto/TokenGroupsDetail.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import { ListRenderItemInfo, View } from 'react-native';
import { CryptoNavigationProps, TokenGroupsDetailProps } from 'routes/home';
import { SwNumberProps } from 'components/design-system-ui/number';
Expand Down Expand Up @@ -52,6 +52,8 @@ export const TokenGroupsDetail = ({

return '';
}, [tokenGroupSlug, assetRegistryMap, multiChainAssetMap]);

console.log('groupSymbol', groupSymbol);
const currentAccount = useSelector((state: RootState) => state.accountState.currentAccount);

const {
Expand Down Expand Up @@ -177,12 +179,6 @@ export const TokenGroupsDetail = ({
[isShowBalance, onClickItem, theme.colorBgSecondary],
);

useEffect(() => {
if (!isTokenGroupComputing && !isAccountBalanceComputing && !tokenBalanceItems.length) {
navigation.navigate('Home', { screen: 'Tokens', params: { screen: 'TokenGroups' } });
}
}, [isAccountBalanceComputing, isTokenGroupComputing, navigation, tokenBalanceItems]);

return (
<ScreenContainer gradientBackground={GradientBackgroundColorSet[2]}>
<>
Expand Down
27 changes: 25 additions & 2 deletions src/screens/Home/Staking/Balance/StakingBalanceList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { setAdjustPan } from 'rn-android-keyboard-adjust';
import BigNumber from 'bignumber.js';
import { useSelector } from 'react-redux';
import { RootState } from 'stores/index';
import { StakingBalancesProps } from 'routes/staking/stakingScreen';

enum FilterValue {
NOMINATED = 'nominated',
Expand Down Expand Up @@ -54,10 +55,15 @@ const searchFunction = (items: StakingDataType[], searchString: string) => {
});
};

const StakingBalanceList = () => {
export const StakingBalanceList = ({
route: {
params: { chain: _stakingChain, type: _stakingType },
},
}: StakingBalancesProps) => {
const theme = useSubWalletTheme().swThemes;
const { data, priceMap } = useGetStakingList();
const navigation = useNavigation<RootNavigationProps>();
const { isLocked } = useSelector((state: RootState) => state.accountState);
const isShowBalance = useSelector((state: RootState) => state.settings.isShowBalance);
const [isRefresh, refresh] = useRefresh();
const [selectedItem, setSelectedItem] = useState<StakingDataType | undefined>(undefined);
Expand All @@ -73,7 +79,7 @@ const StakingBalanceList = () => {
{ label: i18n.filterOptions.nominated, value: FilterValue.NOMINATED },
{ label: i18n.filterOptions.pooled, value: FilterValue.POOLED },
];
const stakingList = useMemo(() => {
const stakingList: StakingDataType[] = useMemo(() => {
if (!data.length) {
return [];
}
Expand All @@ -92,6 +98,23 @@ const StakingBalanceList = () => {
return result;
}, [data, priceMap]);

useEffect(() => {
if (detailModalVisible || isLocked) {
return;
}
if (_stakingChain && _stakingType) {
const selectedValue = stakingList.find(
item => item.chainStakingMetadata?.chain === _stakingChain && item.chainStakingMetadata?.type === _stakingType,
);

if (selectedValue) {
setSelectedItem(selectedValue);
setDetailModalVisible(true);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const renderEmpty = () => {
return (
<EmptyList
Expand Down
7 changes: 4 additions & 3 deletions src/screens/Home/Staking/StakingScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import React from 'react';
import StakingBalanceList from 'screens/Home/Staking/Balance/StakingBalanceList';
import React, { ComponentType } from 'react';
import { StakingBalanceList } from 'screens/Home/Staking/Balance/StakingBalanceList';
import withPageWrapper from 'components/pageWrapper';

const StakingScreen = () => {
Expand All @@ -10,7 +10,8 @@ const StakingScreen = () => {
<StakingScreenStack.Navigator screenOptions={{ headerShown: false, animation: 'slide_from_right' }}>
<StakingScreenStack.Screen
name="StakingBalances"
component={withPageWrapper(StakingBalanceList, ['staking', 'price'])}
component={withPageWrapper(StakingBalanceList as ComponentType, ['staking', 'price'])}
initialParams={{}}
/>
</StakingScreenStack.Navigator>
);
Expand Down
Loading

0 comments on commit 10d707f

Please sign in to comment.