Skip to content
Closed
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
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@
"react-native-localize": "^3.5.4",
"react-native-nitro-modules": "0.35.0",
"react-native-nitro-sqlite": "9.6.0",
"react-native-onyx": "3.0.88",
"react-native-onyx": "git+https://github.com/callstack-internal/react-native-onyx.git#a5f78e58fb830925e7c2f1b52ce4ce15b2872ccf",
"react-native-pager-view": "8.0.0",
"react-native-pdf": "7.0.2",
"react-native-permissions": "^5.4.0",
Expand Down
4 changes: 4 additions & 0 deletions src/ONYXKEYS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,9 @@ const ONYXKEYS = {
/** List of span operations to highlight in Sentry debug logs */
SENTRY_DEBUG_HIGHLIGHTED_SPAN_OPS: 'sentryDebugHighlightedSpanOps',

/** Dev toggle: off (default) forces useOnyx `subscribed: true` everywhere; on lets it follow the enclosing OnyxFocusBoundary's focus */
SHOULD_ONYX_SUBSCRIBED_FOLLOW_FOCUS: 'shouldOnyxSubscribedFollowFocus',

/** Stores new group chat draft */
NEW_GROUP_CHAT_DRAFT: 'newGroupChatDraft',

Expand Down Expand Up @@ -1664,6 +1667,7 @@ type OnyxValuesMapping = {
[ONYXKEYS.IS_SENTRY_DEBUG_ENABLED]: boolean;
[ONYXKEYS.IS_SENTRY_SEND_ENABLED]: boolean;
[ONYXKEYS.SENTRY_DEBUG_HIGHLIGHTED_SPAN_OPS]: string[];
[ONYXKEYS.SHOULD_ONYX_SUBSCRIBED_FOLLOW_FOCUS]: boolean;
[ONYXKEYS.CACHED_PDF_PATHS]: Record<string, string>;
[ONYXKEYS.POLICY_OWNERSHIP_CHANGE_CHECKS]: Record<string, OnyxTypes.PolicyOwnershipChangeChecks>;
[ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE]: OnyxTypes.QuickAction;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import getInitialNumToRender from '@pages/inbox/report/getInitialNumReportAction
import ReportActionIndexContext from '@pages/inbox/report/ReportActionIndexContext';
import ReportActionsListItemRenderer from '@pages/inbox/report/ReportActionsListItemRenderer';
import {getUnreadMarkerReportAction} from '@pages/inbox/report/shouldDisplayNewMarkerOnReportAction';
import useFocusCatchUpTime from '@pages/inbox/report/useFocusCatchUpTime';
import useReportUnreadMessageScrollTracking from '@pages/inbox/report/useReportUnreadMessageScrollTracking';

import variables from '@styles/variables';
Expand Down Expand Up @@ -217,6 +218,10 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps)
const lastVisibleActionCreated = getReportLastVisibleActionCreated(report, transactionThreadReport);
const hasNewestReportAction = lastAction?.created === lastVisibleActionCreated;
const userActiveSince = useRef<string>(DateUtils.getDBTime());
// Actions created at or before this time arrived while the screen was blurred (focus-gated
// catch-up), so the unread-marker computation and mark-as-read effect must treat them as a
// refocus (baseline's focus-keyed path), not as watched-live arrivals
const focusedSince = useFocusCatchUpTime();

const reportActionIDs = useMemo(() => {
return reportActions?.map((action) => action.reportActionID) ?? [];
Expand Down Expand Up @@ -360,6 +365,12 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps)
return;
}

// Catch-up delivery: these actions arrived while blurred, so this run replicates what the
// focus-keyed mark-as-read effect below does at refocus on a live subscription — read only
// when watching at the bottom, and never arm `readActionSkipped` (a live subscription's
// blurred run returns before arming it, so scrolling down later must not auto-read).
const isCatchUp = !!focusedSince && !!lastAction && lastAction.created <= focusedSince;

if (isUnread(report, transactionThreadReport, isReportArchived) || (lastAction && isCurrentActionUnread(report, lastAction, visibleReportActions))) {
// On desktop, when the notification center is displayed, isVisible will return false.
// Currently, there's no programmatic way to dismiss the notification center panel.
Expand All @@ -373,7 +384,7 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps)
if (isFromNotification) {
Navigation.setParams({referrer: undefined});
}
} else {
} else if (!isCatchUp) {
readActionSkipped.current = true;
}
}
Expand Down Expand Up @@ -426,6 +437,11 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps)
return lastIndex > -1 ? lastIndex : undefined;
}, [getLocalDateFromDatetime, isOffline, lastOfflineAt, lastOnlineAt, reportActions, currentUserAccountID]);

// Catch-up deliveries must not count as "received live with window focus" — otherwise the
// isNewMessage heuristic suppresses the unread marker and the push-down effect below advances
// unreadMarkerTime past them, swallowing the marker permanently.
const isCatchUpAfterRefocus = !!focusedSince && !!lastAction && lastAction.created <= focusedSince;

/**
* The reportActionID the unread marker should display above
*/
Expand All @@ -438,7 +454,7 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps)
isScrolledOverThreshold: scrollingVerticalBottomOffset.current >= CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD,
isOffline,
isReversed: true,
hasWindowFocus: Visibility.hasFocus(),
hasWindowFocus: Visibility.hasFocus() && !isCatchUpAfterRefocus,
});

const {isFloatingMessageCounterVisible, setIsFloatingMessageCounterVisible, trackVerticalScrolling, onViewableItemsChanged} = useReportUnreadMessageScrollTracking({
Expand Down
9 changes: 9 additions & 0 deletions src/components/OnyxFocusBoundary/OnyxFocusDefaultContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import {createContext} from 'react';

/**
* Subtree default for `useOnyx`'s `subscribed`, provided by `OnyxFocusBoundary`. `undefined` = no
* boundary above.
*/
const OnyxFocusDefaultContext = createContext<boolean | undefined>(undefined);

export default OnyxFocusDefaultContext;
27 changes: 27 additions & 0 deletions src/components/OnyxFocusBoundary/index.native.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import ONYXKEYS from '@src/ONYXKEYS';
import type ChildrenProps from '@src/types/utils/ChildrenProps';

import {useIsFocused} from '@react-navigation/core';
import React, {useDeferredValue} from 'react';
// eslint-disable-next-line no-restricted-imports
import {useOnyx as originalUseOnyx} from 'react-native-onyx';

import OnyxFocusDefaultContext from './OnyxFocusDefaultContext';

/**
* Native variant — see index.tsx for the full contract. Blur closes in the deferred lane too:
* at press time the JS thread is busy mounting the next screen and background writes land after
* the transition, so an urgent close costs render time without muting anything.
*/
function OnyxFocusBoundary({children}: ChildrenProps) {
const isFocused = useIsFocused();
const deferredIsFocused = useDeferredValue(isFocused);
// Temporary Test Tools toggle, read once per boundary; off = `undefined` = "no boundary".
const [shouldFollowFocus] = originalUseOnyx(ONYXKEYS.SHOULD_ONYX_SUBSCRIBED_FOLLOW_FOCUS);

const subscribedDefault = shouldFollowFocus ? deferredIsFocused : undefined;

return <OnyxFocusDefaultContext.Provider value={subscribedDefault}>{children}</OnyxFocusDefaultContext.Provider>;
}

export default OnyxFocusBoundary;
32 changes: 32 additions & 0 deletions src/components/OnyxFocusBoundary/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import ONYXKEYS from '@src/ONYXKEYS';
import type ChildrenProps from '@src/types/utils/ChildrenProps';

import {useIsFocused} from '@react-navigation/core';
import React, {useDeferredValue} from 'react';
// eslint-disable-next-line no-restricted-imports
import {useOnyx as originalUseOnyx} from 'react-native-onyx';

import OnyxFocusDefaultContext from './OnyxFocusDefaultContext';

/**
* Makes navigation focus the default `subscribed` for every `useOnyx` in the subtree: blurred screens
* stay cache-warm but stop re-rendering. An explicit `subscribed: true` opts a key out (e.g. for
* effects that must run while blurred). Wrap the whole screen component — must be inside a navigator
* screen, and only descendants are covered.
*
* Web variant: blur closes the gate urgently (`isFocused &&`) because Onyx writes land inside the
* navigation span and must be muted right away; refocus opens it in the deferred lane so the
* catch-up re-render yields to the navigation animation. Native (index.native.tsx) defers both.
*/
function OnyxFocusBoundary({children}: ChildrenProps) {
const isFocused = useIsFocused();
const deferredIsFocused = useDeferredValue(isFocused);
// Temporary Test Tools toggle, read once per boundary; off = `undefined` = "no boundary".
const [shouldFollowFocus] = originalUseOnyx(ONYXKEYS.SHOULD_ONYX_SUBSCRIBED_FOLLOW_FOCUS);

const subscribedDefault = shouldFollowFocus ? isFocused && deferredIsFocused : undefined;

return <OnyxFocusDefaultContext.Provider value={subscribedDefault}>{children}</OnyxFocusDefaultContext.Provider>;
}

export default OnyxFocusBoundary;
15 changes: 14 additions & 1 deletion src/components/TestToolMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {useIsAgentAccount} from '@libs/SessionUtils';

import {setShouldFailAllRequests, setShouldForceOffline, setShouldSimulatePoorConnection} from '@userActions/Network';
import {expireSessionWithDelay, invalidateAuthToken, invalidateCredentials} from '@userActions/Session';
import {setIsDebugModeEnabled, setShouldShowBranchNameInTitle, setShouldUseStagingServer} from '@userActions/User';
import {setIsDebugModeEnabled, setShouldOnyxSubscribedFollowFocus, setShouldShowBranchNameInTitle, setShouldUseStagingServer} from '@userActions/User';

import CONFIG from '@src/CONFIG';
import ONYXKEYS from '@src/ONYXKEYS';
Expand All @@ -31,6 +31,7 @@ function TestToolMenu() {
const [shouldUseStagingServer = isUsingStagingApi()] = useOnyx(ONYXKEYS.SHOULD_USE_STAGING_SERVER);
const [isDebugModeEnabled = false] = useOnyx(ONYXKEYS.IS_DEBUG_MODE_ENABLED);
const [shouldShowBranchNameInTitle = false] = useOnyx(ONYXKEYS.SHOULD_SHOW_BRANCH_NAME_IN_TITLE);
const [shouldOnyxSubscribedFollowFocus = false] = useOnyx(ONYXKEYS.SHOULD_ONYX_SUBSCRIBED_FOLLOW_FOCUS);
const styles = useThemeStyles();
const {translate} = useLocalize();
const {clearLHNCache} = useSidebarOrderedReportsActions();
Expand All @@ -49,6 +50,18 @@ function TestToolMenu() {
>
{translate('initialSettingsPage.troubleshoot.testingPreferences')}
</Text>

{/* Off (default): useOnyx always live. On: `subscribed` follows OnyxFocusBoundary focus */}
<TestToolRow
title="useOnyx subscribed follows focus"
isTitleAccessible={false}
>
<Switch
accessibilityLabel="useOnyx subscribed follows focus"
isOn={shouldOnyxSubscribedFollowFocus}
onToggle={() => setShouldOnyxSubscribedFollowFocus(!shouldOnyxSubscribedFollowFocus)}
/>
</TestToolRow>
{isAuthenticated && (
<>
{/* When toggled the app will be put into debug mode. */}
Expand Down
6 changes: 5 additions & 1 deletion src/hooks/useOnyx.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import OnyxFocusDefaultContext from '@components/OnyxFocusBoundary/OnyxFocusDefaultContext';
import {SearchQueryContext, SearchResultsContext} from '@components/Search/SearchContext';
import {useIsOnSearch} from '@components/Search/SearchScopeProvider';

Expand Down Expand Up @@ -77,6 +78,8 @@ const useOnyx: OriginalUseOnyx = <TKey extends OnyxKey, TReturnValue = OnyxValue
const isSnapshotCompatibleKey = !key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT) && CONST.SEARCH.SNAPSHOT_ONYX_KEYS.some((snapshotKey) => key.startsWith(snapshotKey));
const isOnSearch = useIsOnSearch();

const subscribedContextDefault = use(OnyxFocusDefaultContext);

let currentSearchHash: number | undefined;
let shouldUseLiveData = false;
if (isOnSearch && isSnapshotCompatibleKey) {
Expand All @@ -95,7 +98,8 @@ const useOnyx: OriginalUseOnyx = <TKey extends OnyxKey, TReturnValue = OnyxValue
// Create selector function that handles both regular and snapshot data
const selector = !selectorProp || !shouldUseSnapshot ? selectorProp : (data: OnyxValue<OnyxKey> | undefined) => selectorProp(getKeyData(data as SearchResults, key));

const onyxOptions: UseOnyxOptions<OnyxKey, OnyxValue<OnyxKey>> = {...optionsWithoutSelector, selector};
const subscribed = useOnyxOptions?.subscribed ?? subscribedContextDefault ?? true;
const onyxOptions: UseOnyxOptions<OnyxKey, OnyxValue<OnyxKey>> = {...optionsWithoutSelector, selector, subscribed};
const snapshotKey = shouldUseSnapshot ? (`${ONYXKEYS.COLLECTION.SNAPSHOT}${currentSearchHash}` as OnyxKey) : key;

const originalResult = originalUseOnyx(snapshotKey, onyxOptions, dependencies);
Expand Down
5 changes: 5 additions & 0 deletions src/libs/actions/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,10 @@ function setShouldShowBranchNameInTitle(value: boolean) {
Onyx.set(ONYXKEYS.SHOULD_SHOW_BRANCH_NAME_IN_TITLE, value);
}

function setShouldOnyxSubscribedFollowFocus(value: boolean) {
Onyx.set(ONYXKEYS.SHOULD_ONYX_SUBSCRIBED_FOLLOW_FOCUS, value);
}

function lockAccount(currentUserAccountID: number, accountID: number | undefined, domainAccountID: number | undefined, domainName: string | undefined) {
let domainOptimisticData: DomainOnyxUpdate[] = [];
let domainFailureData: DomainOnyxUpdate[] = [];
Expand Down Expand Up @@ -2040,6 +2044,7 @@ export {
clearValidateCodeActionError,
setIsDebugModeEnabled,
setShouldShowBranchNameInTitle,
setShouldOnyxSubscribedFollowFocus,
lockAccount,
requestUnlockAccount,
respondToProactiveAppReview,
Expand Down
14 changes: 12 additions & 2 deletions src/pages/Search/SearchMoneyRequestReportPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import DragAndDropProvider from '@components/DragAndDrop/Provider';
import MoneyRequestReportView from '@components/MoneyRequestReportView/MoneyRequestReportView';
import OnyxFocusBoundary from '@components/OnyxFocusBoundary';
import ScreenWrapper from '@components/ScreenWrapper';
import {useSearchResultsContext} from '@components/Search/SearchContext';
import useRHPWidth from '@components/WideRHPContextProvider/useRHPWidth';
Expand Down Expand Up @@ -76,7 +77,8 @@ function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) {

const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportIDFromRoute}`);
const [hasReportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportIDFromRoute}`, {selector: Boolean});
const [deleteTransactionNavigateBackUrl] = useOnyx(ONYXKEYS.NVP_DELETE_TRANSACTION_NAVIGATE_BACK_URL);
// Must stay live while blurred: the clearing effect below only acts while unfocused, so focus-gating would starve it.
const [deleteTransactionNavigateBackUrl] = useOnyx(ONYXKEYS.NVP_DELETE_TRANSACTION_NAVIGATE_BACK_URL, {subscribed: true});

const parentReportAction = useParentReportAction(report);

Expand Down Expand Up @@ -421,4 +423,12 @@ function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) {
);
}

export default SearchMoneyRequestReportPage;
function SearchMoneyRequestReportPageWithOnyxBoundary(props: SearchMoneyRequestPageProps) {
return (
<OnyxFocusBoundary>
<SearchMoneyRequestReportPage {...props} />
</OnyxFocusBoundary>
);
}

export default SearchMoneyRequestReportPageWithOnyxBoundary;
29 changes: 29 additions & 0 deletions src/pages/inbox/report/useFocusCatchUpTime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import OnyxFocusDefaultContext from '@components/OnyxFocusBoundary/OnyxFocusDefaultContext';

import DateUtils from '@libs/DateUtils';

import {useIsFocused} from '@react-navigation/native';
import {use, useState} from 'react';

/**
* DB timestamp of this screen's last blur -> focus transition. On focus-gated screens
* (`OnyxFocusBoundary`), blurred-period Onyx changes are delivered in one catch-up render after
* refocus, so actions with `created` at or before this time arrived while the user was not watching.
* Returns `null` when the screen is not focus-gated or has not been blurred yet, so guards built on
* it stay inert. Never stamps on mount.
*/
function useFocusCatchUpTime(): string | null {
const isFocusGated = use(OnyxFocusDefaultContext) !== undefined;
const isFocused = useIsFocused();

// State adjusted during render (not a ref) so callers can use the value in the render phase.
// Skipped entirely when ungated, so those screens pay no render-phase setState re-run.
const [focusState, setFocusState] = useState<{isFocused: boolean; focusedSince: string | null}>({isFocused, focusedSince: null});
if (isFocusGated && focusState.isFocused !== isFocused) {
setFocusState({isFocused, focusedSince: isFocused ? DateUtils.getDBTime() : focusState.focusedSince});
}

return isFocusGated ? focusState.focusedSince : null;
}

export default useFocusCatchUpTime;
Loading