Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HybridApp] Receive structured initialProperties (not as url) and improve url handling #56463

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,17 @@ import type {Route} from './ROUTES';
import './setup/backgroundTask';
import {SplashScreenStateContextProvider} from './SplashScreenStateContext';

/** Values passed to our top-level React Native component by HybridApp. Will always be undefined in "pure" NewDot builds. */
/**
* Properties passed to the top-level React Native component by HybridApp.
* These will always be `undefined` in "pure" NewDot builds.
*/
type AppProps = {
/** URL containing all necessary data to run React Native app (e.g. login data) */
/** The URL specifying the initial navigation destination when the app opens */
url?: Route;
/** Serialized configuration data required to initialize the React Native app (e.g. authentication details) */
hybridAppSettings?: string;
/** A timestamp indicating when the initial properties were last updated, used to detect changes */
timestamp?: string;
};

LogBox.ignoreLogs([
Expand All @@ -62,14 +69,18 @@ const fill = {flex: 1};

const StrictModeWrapper = CONFIG.USE_REACT_STRICT_MODE_IN_DEV ? React.StrictMode : ({children}: {children: React.ReactElement}) => children;

function App({url}: AppProps) {
function App({url, hybridAppSettings, timestamp}: AppProps) {
useDefaultDragAndDrop();
OnyxUpdateManager();

return (
<StrictModeWrapper>
<SplashScreenStateContextProvider>
<InitialURLContextProvider url={url}>
<InitialURLContextProvider
url={url}
hybridAppSettings={hybridAppSettings}
timestamp={timestamp}
>
<GestureHandlerRootView style={fill}>
<ComposeProviders
components={[
Expand Down Expand Up @@ -120,3 +131,5 @@ function App({url}: AppProps) {
App.displayName = 'App';

export default App;

export type {AppProps};
4 changes: 0 additions & 4 deletions src/CONST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6600,10 +6600,6 @@ const CONST = {
},
},

HYBRID_APP: {
REORDERING_REACT_NATIVE_ACTIVITY_TO_FRONT: 'reorderingReactNativeActivityToFront',
},

MIGRATED_USER_WELCOME_MODAL: 'migratedUserWelcomeModal',

BASE_LIST_ITEM_TEST_ID: 'base-list-item-',
Expand Down
2 changes: 1 addition & 1 deletion src/components/BookTravelButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ function BookTravelButton({text}: BookTravelButtonProps) {

// Close NewDot if it was opened only for Travel, as its purpose is now fulfilled.
Log.info('[HybridApp] Returning to OldDot after opening TravelDot');
NativeModules.HybridAppModule.closeReactNativeApp(false, false);
NativeModules.HybridAppModule.closeReactNativeApp({shouldSignOut: false, shouldSetNVP: false});
setRootStatusBarEnabled(false);
})
?.catch(() => {
Expand Down
40 changes: 11 additions & 29 deletions src/components/InitialURLContextProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import React, {createContext, useEffect, useMemo, useState} from 'react';
import type {ReactNode} from 'react';
import {Linking} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import {signInAfterTransitionFromOldDot} from '@libs/actions/Session';
import Navigation from '@navigation/Navigation';
import {AppProps} from '@src/App';

Check failure on line 5 in src/components/InitialURLContextProvider.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

All imports in the declaration are only used as types. Use `import type`

Check failure on line 5 in src/components/InitialURLContextProvider.tsx

View workflow job for this annotation

GitHub Actions / ESLint check

All imports in the declaration are only used as types. Use `import type`
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Route} from '@src/ROUTES';
import {useSplashScreenStateContext} from '@src/SplashScreenStateContext';

Expand All @@ -21,46 +18,31 @@
setInitialURL: () => {},
});

type InitialURLContextProviderProps = {
/** URL passed to our top-level React Native component by HybridApp. Will always be undefined in "pure" NewDot builds. */
url?: Route | ValueOf<typeof CONST.HYBRID_APP>;

type InitialURLContextProviderProps = AppProps & {
/** Children passed to the context provider */
children: ReactNode;
};

function InitialURLContextProvider({children, url}: InitialURLContextProviderProps) {
function InitialURLContextProvider({children, url, hybridAppSettings, timestamp}: InitialURLContextProviderProps) {
const [initialURL, setInitialURL] = useState<Route | undefined>();
const [lastVisitedPath] = useOnyx(ONYXKEYS.LAST_VISITED_PATH);
const {splashScreenState, setSplashScreenState} = useSplashScreenStateContext();

useEffect(() => {
if (url !== CONST.HYBRID_APP.REORDERING_REACT_NATIVE_ACTIVITY_TO_FRONT) {
return;
}

if (splashScreenState !== CONST.BOOT_SPLASH_STATE.HIDDEN) {
setSplashScreenState(CONST.BOOT_SPLASH_STATE.READY_TO_BE_HIDDEN);
Navigation.navigate(lastVisitedPath as Route);
}
}, [lastVisitedPath, setSplashScreenState, splashScreenState, url]);

useEffect(() => {
if (url === CONST.HYBRID_APP.REORDERING_REACT_NATIVE_ACTIVITY_TO_FRONT) {
return;
}

if (url) {
signInAfterTransitionFromOldDot(url).then((route) => {
setInitialURL(route);
if (url && hybridAppSettings) {
setInitialURL(url);
signInAfterTransitionFromOldDot(hybridAppSettings).then(() => {
if (splashScreenState === CONST.BOOT_SPLASH_STATE.HIDDEN) {
return;
}
setSplashScreenState(CONST.BOOT_SPLASH_STATE.READY_TO_BE_HIDDEN);
});
return;
}
Linking.getInitialURL().then((initURL) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious about the relevance of this line. Do we even need it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, it’s probably still needed for the standalone NewDot. Even though HybridApp is the only one available on the App Store and Play Store, we still need this for external contributors 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably true but this is old code so I'm not sure

setInitialURL(initURL as Route);
});
}, [setSplashScreenState, url]);
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
war-in marked this conversation as resolved.
Show resolved Hide resolved
}, [url, hybridAppSettings, timestamp]);

const initialUrlContext = useMemo(
() => ({
Expand Down
13 changes: 6 additions & 7 deletions src/components/ScreenWrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import {UNSTABLE_usePreventRemove, useIsFocused, useNavigation, useRoute} from '@react-navigation/native';
import {UNSTABLE_usePreventRemove, useIsFocused, useNavigation} from '@react-navigation/native';
import type {ForwardedRef, ReactNode} from 'react';
import React, {createContext, forwardRef, useContext, useEffect, useMemo, useRef, useState} from 'react';
import type {StyleProp, ViewStyle} from 'react-native';
import {Keyboard, NativeModules, PanResponder, View} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import {PickerAvoidingView} from 'react-native-picker-select';
import type {EdgeInsets} from 'react-native-safe-area-context';
import useEnvironment from '@hooks/useEnvironment';
Expand All @@ -18,6 +19,7 @@ import type {AuthScreensParamList, RootStackParamList} from '@libs/Navigation/ty
import addViewportResizeListener from '@libs/VisualViewport';
import toggleTestToolsModal from '@userActions/TestTool';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import CustomDevMenu from './CustomDevMenu';
import CustomStatusBarAndBackgroundContext from './CustomStatusBarAndBackground/CustomStatusBarAndBackgroundContext';
import FocusTrapForScreens from './FocusTrap/FocusTrapForScreen';
Expand Down Expand Up @@ -154,6 +156,7 @@ function ScreenWrapper(
// since Modals are drawn in separate native view hierarchy we should always add paddings
const ignoreInsetsConsumption = !useContext(ModalContext).default;
const {setRootStatusBarEnabled} = useContext(CustomStatusBarAndBackgroundContext);
const [isSingleNewDotEntry] = useOnyx(ONYXKEYS.IS_SINGLE_NEW_DOT_ENTRY);

// We need to use isSmallScreenWidth instead of shouldUseNarrowLayout for a case where we want to show the offline indicator only on small screens
// eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth
Expand All @@ -165,14 +168,10 @@ function ScreenWrapper(
const maxHeight = shouldEnableMaxHeight ? windowHeight : undefined;
const minHeight = shouldEnableMinHeight && !isSafari() ? initialHeight : undefined;

const route = useRoute();
const shouldReturnToOldDot = useMemo(() => {
return !!route?.params && 'singleNewDotEntry' in route.params && route.params.singleNewDotEntry === 'true';
}, [route?.params]);
const {isBlurred, setIsBlurred} = useInputBlurContext();

UNSTABLE_usePreventRemove(shouldReturnToOldDot, () => {
NativeModules.HybridAppModule?.closeReactNativeApp(false, false);
UNSTABLE_usePreventRemove(isSingleNewDotEntry ?? false, () => {
NativeModules.HybridAppModule?.closeReactNativeApp({shouldSignOut: false, shouldSetNVP: false});
setRootStatusBarEnabled(false);
});

Expand Down
18 changes: 16 additions & 2 deletions src/libs/actions/Delegate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,14 @@ function connect(email: string) {

NetworkStore.setAuthToken(response?.restrictedToken ?? null);
confirmReadyToOpenApp();
openApp().then(() => NativeModules.HybridAppModule?.switchAccount(email, restrictedToken, policyID, String(previousAccountID)));
openApp().then(() =>
NativeModules.HybridAppModule?.switchAccount({
newDotCurrentAccountEmail: email,
authToken: restrictedToken,
policyID,
accountID: String(previousAccountID),
}),
);
});
})
.catch((error) => {
Expand Down Expand Up @@ -238,7 +245,14 @@ function disconnect() {
NetworkStore.setAuthToken(response?.authToken ?? null);

confirmReadyToOpenApp();
openApp().then(() => NativeModules.HybridAppModule?.switchAccount(requesterEmail, authToken, '', ''));
openApp().then(() =>
NativeModules.HybridAppModule?.switchAccount({
newDotCurrentAccountEmail: requesterEmail,
authToken,
policyID: '',
accountID: '',
}),
);
});
})
.catch((error) => {
Expand Down
127 changes: 64 additions & 63 deletions src/libs/actions/Session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ function signOutAndRedirectToSignIn(shouldResetToHome?: boolean, shouldStashSess
if (!isAnonymousUser()) {
// In the HybridApp, we want the Old Dot to handle the sign out process
if (NativeModules.HybridAppModule && killHybridApp) {
NativeModules.HybridAppModule.closeReactNativeApp(true, false);
NativeModules.HybridAppModule.closeReactNativeApp({shouldSignOut: true, shouldSetNVP: false});
return;
}
// We'll only call signOut if we're not stashing the session and this is not a supportal session,
Expand Down Expand Up @@ -514,9 +514,22 @@ function getLastUpdateIDAppliedToClient(): Promise<number> {
});
}

function signInAfterTransitionFromOldDot(transitionURL: string) {
const [route, queryParams] = transitionURL.split('?');
type HybridAppSettings = {
email: string;
authToken: string;
accountID: number;
autoGeneratedLogin: string;
autoGeneratedPassword: string;
clearOnyxOnStart: boolean;
completedHybridAppOnboarding: boolean;
isSingleNewDotEntry: boolean;
primaryLogin: string;
encryptedAuthToken: string;
nudgeMigrationTimestamp?: string;
oldDotOriginalAccountEmail?: string;
};

function signInAfterTransitionFromOldDot(hybridAppSettings: string) {
const {
email,
authToken,
Expand All @@ -530,75 +543,63 @@ function signInAfterTransitionFromOldDot(transitionURL: string) {
isSingleNewDotEntry,
primaryLogin,
oldDotOriginalAccountEmail,
} = Object.fromEntries(
queryParams.split('&').map((param) => {
const [key, value] = param.split('=');
return [key, value];
}),
);
} = JSON.parse(hybridAppSettings) as HybridAppSettings;

const clearOnyxForNewAccount = () => {
if (clearOnyxOnStart !== 'true') {
if (!clearOnyxOnStart) {
return Promise.resolve();
}

return Onyx.clear(KEYS_TO_PRESERVE);
};

const setSessionDataAndOpenApp = new Promise<Route>((resolve) => {
clearOnyxForNewAccount()
.then(() => {
// This section controls copilot changes
const currentUserEmail = getCurrentUserEmail();

// If ND and OD account are the same - do nothing
if (email === currentUserEmail) {
return;
}

// If account was changed to original one on OD side - clear onyx
if (!oldDotOriginalAccountEmail) {
return Onyx.clear(KEYS_TO_PRESERVE_DELEGATE_ACCESS);
}

// If we're already logged in - do nothing, data will be set in next step
if (currentUserEmail) {
return;
}

// If we're not logged in - set stashed data
return Onyx.multiSet({
[ONYXKEYS.STASHED_CREDENTIALS]: {autoGeneratedLogin, autoGeneratedPassword},
});
})
.then(() =>
Onyx.multiSet({
[ONYXKEYS.SESSION]: {email, authToken, encryptedAuthToken: decodeURIComponent(encryptedAuthToken), accountID: Number(accountID)},
[ONYXKEYS.CREDENTIALS]: {autoGeneratedLogin, autoGeneratedPassword},
[ONYXKEYS.IS_SINGLE_NEW_DOT_ENTRY]: isSingleNewDotEntry === 'true',
[ONYXKEYS.NVP_TRYNEWDOT]: {
classicRedirect: {completedHybridAppOnboarding: completedHybridAppOnboarding === 'true'},
nudgeMigration: nudgeMigrationTimestamp ? {timestamp: new Date(nudgeMigrationTimestamp)} : undefined,
},
}).then(() => Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin})),
)
.then(() => {
if (clearOnyxOnStart === 'true') {
return openApp();
}
return getLastUpdateIDAppliedToClient().then((lastUpdateId) => {
return reconnectApp(lastUpdateId);
});
})
.catch((error) => {
Log.hmmm('[HybridApp] Initialization of HybridApp has failed. Forcing transition', {error});
})
.finally(() => {
resolve(`${route}${isSingleNewDotEntry === 'true' ? '?singleNewDotEntry=true' : ''}` as Route);
});
});
return clearOnyxForNewAccount()
.then(() => {
// This section controls copilot changes
const currentUserEmail = getCurrentUserEmail();

// If ND and OD account are the same - do nothing
if (email === currentUserEmail) {
return;
}

return setSessionDataAndOpenApp;
// If account was changed to original one on OD side - clear onyx
if (!oldDotOriginalAccountEmail) {
return Onyx.clear(KEYS_TO_PRESERVE_DELEGATE_ACCESS);
}

// If we're already logged in - do nothing, data will be set in next step
if (currentUserEmail) {
return;
}

// If we're not logged in - set stashed data
return Onyx.multiSet({
[ONYXKEYS.STASHED_CREDENTIALS]: {autoGeneratedLogin, autoGeneratedPassword},
});
})
.then(() =>
Onyx.multiSet({
[ONYXKEYS.SESSION]: {email, authToken, encryptedAuthToken: decodeURIComponent(encryptedAuthToken), accountID: Number(accountID)},
[ONYXKEYS.CREDENTIALS]: {autoGeneratedLogin, autoGeneratedPassword},
[ONYXKEYS.IS_SINGLE_NEW_DOT_ENTRY]: isSingleNewDotEntry,
[ONYXKEYS.NVP_TRYNEWDOT]: {
classicRedirect: {completedHybridAppOnboarding},
nudgeMigration: nudgeMigrationTimestamp ? {timestamp: new Date(nudgeMigrationTimestamp)} : undefined,
},
}).then(() => Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin})),
)
.then(() => {
if (clearOnyxOnStart) {
return openApp();
}
return getLastUpdateIDAppliedToClient().then((lastUpdateId) => {
return reconnectApp(lastUpdateId);
});
})
.catch((error) => {
Log.hmmm('[HybridApp] Initialization of HybridApp has failed. Forcing transition', {error});
});
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/libs/actions/Welcome/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import type Onboarding from '@src/types/onyx/Onboarding';
import type TryNewDot from '@src/types/onyx/TryNewDot';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import * as OnboardingFlow from './OnboardingFlow';

Check failure on line 14 in src/libs/actions/Welcome/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Namespace imports are not allowed. Use named imports instead. Example: import { method } from "./libs/module"

type OnboardingData = Onboarding | undefined;

Expand Down Expand Up @@ -145,7 +145,7 @@

// No matter what the response is, we want to mark the onboarding as completed (user saw the explanation modal)
Log.info(`[HybridApp] Onboarding status has changed. Propagating new value to OldDot`, true);
NativeModules.HybridAppModule.completeOnboarding(true);
NativeModules.HybridAppModule.completeOnboarding({status: true});
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/pages/ErrorPage/SessionExpiredPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import Navigation from '@libs/Navigation/Navigation';
import * as Session from '@userActions/Session';

Check failure on line 12 in src/pages/ErrorPage/SessionExpiredPage.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Namespace imports from @userActions are not allowed. Use named imports instead. Example: import { action } from "@userActions/module"

function SessionExpiredPage() {
const styles = useThemeStyles();
Expand Down Expand Up @@ -37,7 +37,7 @@
Navigation.goBack();
return;
}
NativeModules.HybridAppModule.closeReactNativeApp(true, false);
NativeModules.HybridAppModule.closeReactNativeApp({shouldSignOut: true, shouldSetNVP: false});
}}
>
{translate('deeplinkWrapper.signIn')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function BaseOnboardingEmployees({shouldUseNativeStyles, route}: BaseOnboardingE
);
}

NativeModules.HybridAppModule.closeReactNativeApp(false, true);
NativeModules.HybridAppModule.closeReactNativeApp({shouldSignOut: false, shouldSetNVP: true});
setRootStatusBarEnabled(false);
}}
pressOnEnter
Expand Down
Loading
Loading