Skip to content

Fix flakey #focus mode auto switching #61913

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
74 changes: 74 additions & 0 deletions src/components/PriorityModeController.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {useEffect, useMemo, useRef, useState} from 'react';
import {useOnyx} from 'react-native-onyx';
import {setFocusModeNotification} from '@libs/actions/PriorityMode';
import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import {isReportParticipant, isValidReport} from '@libs/ReportUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import SCREENS from '@src/SCREENS';
import Log from '@libs/Log';
import navigationRef from "@libs/Navigation/navigationRef";
import { useNavigation } from "@react-navigation/native";

export default function PriorityModeController() {
const [accountID] = useOnyx(ONYXKEYS.SESSION, {selector: (session) => session?.accountID});

Check failure on line 14 in src/components/PriorityModeController.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

useOnyx() calls require you to pass the "canBeMissing" param
const [isLoadingReportData] = useOnyx(ONYXKEYS.IS_LOADING_REPORT_DATA);

Check failure on line 15 in src/components/PriorityModeController.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

useOnyx() calls require you to pass the "canBeMissing" param
const [isInFocusMode] = useOnyx(ONYXKEYS.NVP_PRIORITY_MODE, {selector: (priorityMode) => priorityMode === CONST.PRIORITY_MODE.GSD});

Check failure on line 16 in src/components/PriorityModeController.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

useOnyx() calls require you to pass the "canBeMissing" param
const [hasTriedFocusMode] = useOnyx(ONYXKEYS.NVP_TRY_FOCUS_MODE);

Check failure on line 17 in src/components/PriorityModeController.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

useOnyx() calls require you to pass the "canBeMissing" param
const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);

Check failure on line 18 in src/components/PriorityModeController.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

useOnyx() calls require you to pass the "canBeMissing" param
const currentRouteName = useCurrentRouteName();

const validReportCount = useMemo(() => {
let count = 0;
Object.values(allReports ?? {}).forEach((report) => {
if (!isValidReport(report) || !isReportParticipant(accountID ?? CONST.DEFAULT_NUMBER_ID, report)) {
return;
}

count++;
});
return count;
}, [accountID, allReports]);

// We set this when we have finally auto-switched the user of #focus mode to prevent duplication.
const hasSwitched = useRef(false);

// Listen for state changes and trigger the #focus mode when appropriate
useEffect(() => {
if (hasSwitched.current || !accountID || isLoadingReportData === true || isInFocusMode === true || hasTriedFocusMode === true) {
return;
}

if (validReportCount < CONST.REPORT.MAX_COUNT_BEFORE_FOCUS_UPDATE) {
Log.info('[PriorityModeController] Not switching user to focus mode as they do not have enough reports', false, {validReportCount});
return;
}

// We wait for the user to navigate back to the homescreen before triggering this switch
const isNarrowLayout = getIsNarrowLayout();
if ((isNarrowLayout && currentRouteName !== SCREENS.HOME) || (!isNarrowLayout && currentRouteName !== SCREENS.REPORT)) {
Log.info("[PriorityModeController] Not switching user to focus mode as they aren't on the homescreen", false, {validReportCount, currentRouteName});
return;
}

Log.info('[PriorityModeController] Switching user to focus mode', false, {validReportCount, hasTriedFocusMode, isInFocusMode, currentRouteName});
setFocusModeNotification(true);
hasSwitched.current = true;
}, [accountID, currentRouteName, hasTriedFocusMode, isInFocusMode, isLoadingReportData, validReportCount]);

return null;
}

function useCurrentRouteName() {
const navigation = useNavigation();
const [currentRouteName, setCurrentRouteName] = useState<string | undefined>('');

useEffect(() => {
const unsubscribe = navigation.addListener('state', () => {
setCurrentRouteName(navigationRef.getCurrentRoute()?.name);
});
return () => unsubscribe();
}, [navigation]);

return currentRouteName;
}
14 changes: 2 additions & 12 deletions src/libs/Navigation/AppNavigator/AuthScreens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ import * as App from '@userActions/App';
import * as Download from '@userActions/Download';
import * as Modal from '@userActions/Modal';
import * as PersonalDetails from '@userActions/PersonalDetails';
import * as PriorityMode from '@userActions/PriorityMode';
import * as Report from '@userActions/Report';
import * as Session from '@userActions/Session';
import * as User from '@userActions/User';
Expand All @@ -59,6 +58,7 @@ import type * as OnyxTypes from '@src/types/onyx';
import type {SelectedTimezone, Timezone} from '@src/types/onyx/PersonalDetails';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type ReactComponentModule from '@src/types/utils/ReactComponentModule';
import PriorityModeController from '@components/PriorityModeController';
import createRootStackNavigator from './createRootStackNavigator';
import {reportsSplitsWithEnteringAnimation, settingsSplitWithEnteringAnimation, workspaceSplitsWithoutEnteringAnimation} from './createRootStackNavigator/GetStateForActionHandlers';
import defaultScreenOptions from './defaultScreenOptions';
Expand Down Expand Up @@ -239,13 +239,6 @@ function AuthScreens({session, lastOpenedPublicRoomID, initialLastUpdateIDApplie
// State to track whether the delegator's authentication is completed before displaying data
const [isDelegatorFromOldDotIsReady, setIsDelegatorFromOldDotIsReady] = useState(false);

useEffect(() => {
const unsubscribe = navigation.addListener('state', () => {
PriorityMode.autoSwitchToFocusMode();
});
return () => unsubscribe();
}, [navigation]);

// On HybridApp we need to prevent flickering during transition to OldDot
const shouldRenderOnboardingExclusivelyOnHybridApp = useMemo(() => {
return CONFIG.IS_HYBRID_APP && Navigation.getActiveRoute().includes(ROUTES.ONBOARDING_ACCOUNTING.route) && isOnboardingCompleted === true;
Expand Down Expand Up @@ -328,10 +321,6 @@ function AuthScreens({session, lastOpenedPublicRoomID, initialLastUpdateIDApplie
}
Download.clearDownloads();

Navigation.isNavigationReady().then(() => {
PriorityMode.autoSwitchToFocusMode();
});

const unsubscribeOnyxModal = onyxSubscribe({
key: ONYXKEYS.MODAL,
callback: (modalArg) => {
Expand Down Expand Up @@ -729,6 +718,7 @@ function AuthScreens({session, lastOpenedPublicRoomID, initialLastUpdateIDApplie
/>
</RootStack.Navigator>
<SearchRouterModal />
<PriorityModeController />
</ComposeProviders>
);
}
Expand Down
3 changes: 0 additions & 3 deletions src/libs/ReportUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
import {isApprover as isApproverMember} from './actions/Policy/Member';
import {createDraftWorkspace} from './actions/Policy/Policy';
import {autoSwitchToFocusMode} from './actions/PriorityMode';
import {hasCreditBankAccount} from './actions/ReimbursementAccount/store';

Check failure on line 76 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / typecheck

Module '"./actions/PriorityMode"' declares 'autoSwitchToFocusMode' locally, but it is not exported.

Check failure on line 76 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'autoSwitchToFocusMode' is defined but never used

Check failure on line 76 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / ESLint check

'autoSwitchToFocusMode' is defined but never used
import {handleReportChanged} from './actions/Report';
import type {GuidedSetupData, TaskForParameters} from './actions/Report';
import {isAnonymousUser as isAnonymousUserSession} from './actions/Session';
Expand Down Expand Up @@ -907,9 +907,6 @@
module.triggerUnreadUpdate();
});

// Each time a new report is added we will check to see if the user should be switched
autoSwitchToFocusMode();

if (!value) {
return;
}
Expand Down
32 changes: 18 additions & 14 deletions src/libs/actions/PriorityMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,14 @@
* - Reports to load (in ReconnectApp or OpenApp). As we check the count of the reports to determine whether the user is eligible to be automatically switched.
*/

let resolveIsReadyPromise: (args?: unknown[]) => void;
let isReadyPromise = new Promise((resolve) => {
type FocusModeState = {
allReports: OnyxCollection<Report>;
hasTriedFocusMode: boolean;
isInFocusMode: boolean;
}

let resolveIsReadyPromise: (state: FocusModeState) => void;
let isReadyPromise = new Promise<FocusModeState>((resolve) => {
resolveIsReadyPromise = resolve;
});

Expand All @@ -35,8 +41,7 @@
/**
* Debounce the prompt to promote focus mode as many reports updates could happen in a short burst
*/
// eslint-disable-next-line @typescript-eslint/no-use-before-define
const autoSwitchToFocusMode = debounce(tryFocusModeUpdate, 300, {leading: true});

Check failure on line 44 in src/libs/actions/PriorityMode.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'autoSwitchToFocusMode' is assigned a value but never used

Check failure on line 44 in src/libs/actions/PriorityMode.ts

View workflow job for this annotation

GitHub Actions / ESLint check

'autoSwitchToFocusMode' is assigned a value but never used

let isLoadingReportData = true;
Onyx.connect({
Expand All @@ -44,8 +49,6 @@
initWithStoredValues: false,
callback: (value) => {
isLoadingReportData = value ?? false;

// eslint-disable-next-line @typescript-eslint/no-use-before-define
checkRequiredData();
},
});
Expand All @@ -55,8 +58,6 @@
key: ONYXKEYS.NVP_PRIORITY_MODE,
callback: (priorityMode) => {
isInFocusMode = priorityMode === CONST.PRIORITY_MODE.GSD;

// eslint-disable-next-line @typescript-eslint/no-use-before-define
checkRequiredData();
},
});
Expand All @@ -66,8 +67,6 @@
key: ONYXKEYS.NVP_TRY_FOCUS_MODE,
callback: (val) => {
hasTriedFocusMode = val;

// eslint-disable-next-line @typescript-eslint/no-use-before-define
checkRequiredData();
},
});
Expand All @@ -81,7 +80,7 @@
},
});

function resetHasReadRequiredDataFromStorage() {

Check failure on line 83 in src/libs/actions/PriorityMode.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'resetHasReadRequiredDataFromStorage' is defined but never used

Check failure on line 83 in src/libs/actions/PriorityMode.ts

View workflow job for this annotation

GitHub Actions / ESLint check

'resetHasReadRequiredDataFromStorage' is defined but never used
// Create a new promise and a new resolve function
isReadyPromise = new Promise((resolve) => {
resolveIsReadyPromise = resolve;
Expand All @@ -94,11 +93,11 @@
return;
}

resolveIsReadyPromise();
resolveIsReadyPromise({allReports, hasTriedFocusMode, isInFocusMode});
}

function tryFocusModeUpdate() {
isReadyPromise.then(() => {
isReadyPromise.then((state) => {
// User is signed out so do not try to switch them
if (!currentUserAccountID) {
return;
Expand All @@ -114,13 +113,13 @@
}

// Check to see if the user is using #focus mode, has tried it before, or we have already switched them over automatically.
if ((isInFocusMode ?? false) || hasTriedFocusMode) {
if ((state.isInFocusMode ?? false) || state.hasTriedFocusMode) {
Log.info('Not switching user to optimized focus mode.', false, {isInFocusMode, hasTriedFocusMode});
return;
}

const validReports = [];
Object.keys(allReports ?? {}).forEach((key) => {
Object.keys(state.allReports ?? {}).forEach((key) => {
const report = allReports?.[key];
if (!report) {
return;
Expand Down Expand Up @@ -149,4 +148,9 @@
});
}

export {resetHasReadRequiredDataFromStorage, autoSwitchToFocusMode};
function setFocusModeNotification(value: boolean) {
Onyx.set(ONYXKEYS.FOCUS_MODE_NOTIFICATION, value);
}

// eslint-disable-next-line import/prefer-default-export
export {setFocusModeNotification};
2 changes: 0 additions & 2 deletions src/libs/actions/Session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ import {hideContextMenu} from '@pages/home/report/ContextMenu/ReportActionContex
import {KEYS_TO_PRESERVE, openApp, reconnectApp} from '@userActions/App';
import {KEYS_TO_PRESERVE_DELEGATE_ACCESS} from '@userActions/Delegate';
import * as Device from '@userActions/Device';
import * as PriorityMode from '@userActions/PriorityMode';
import redirectToSignIn from '@userActions/SignInRedirect';
import Timing from '@userActions/Timing';
import * as Welcome from '@userActions/Welcome';
Expand Down Expand Up @@ -887,7 +886,6 @@ function cleanupSession() {
Pusher.disconnect();
Timers.clearAll();
Welcome.resetAllChecks();
PriorityMode.resetHasReadRequiredDataFromStorage();
MainQueue.clear();
HttpUtils.cancelPendingRequests();
PersistedRequests.clear();
Expand Down
Loading