Skip to content
Merged
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
41 changes: 41 additions & 0 deletions src/hooks/useIsPastDate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import CONST from '@src/CONST';

import {isPast} from 'date-fns';
import {useEffect, useState} from 'react';

/**
* Returns whether `date` has passed, and re-renders exactly once when it does.
* A plain `isPast(date)` in render is memoized by React Compiler on `date`, so it would never flip while `date` stays the same.
*/
function useIsPastDate(date: string | undefined): boolean {
const [passedDate, setPassedDate] = useState<string>();
const hasPassed = !!date && (passedDate === date || isPast(date));

useEffect(() => {
if (!date || hasPassed) {
return;
}
const targetTime = new Date(date).getTime();
if (Number.isNaN(targetTime)) {
return;
}
let timeoutID: ReturnType<typeof setTimeout> | undefined;

// setTimeout overflows above CONST.LIMIT_TIMEOUT, so wait in LIMIT_TIMEOUT steps until the target is in range (same as UserStatusHandler)
const scheduleTimeout = () => {
const remainingTime = targetTime - Date.now();
if (remainingTime > CONST.LIMIT_TIMEOUT) {
timeoutID = setTimeout(scheduleTimeout, CONST.LIMIT_TIMEOUT);
return;
}
timeoutID = setTimeout(() => setPassedDate(date), Math.max(remainingTime, 0));
};
scheduleTimeout();

return () => clearTimeout(timeoutID);
}, [date, hasPassed]);

return hasPassed;
}

export default useIsPastDate;
5 changes: 3 additions & 2 deletions src/pages/inbox/HeaderView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import useHasTeam2025Pricing from '@hooks/useHasTeam2025Pricing';
import useInitialFocusRef from '@hooks/useInitialFocusRef';
import useIsInSidePanel from '@hooks/useIsInSidePanel';
import useIsPaidPolicyAdmin from '@hooks/useIsPaidPolicyAdmin';
import useIsPastDate from '@hooks/useIsPastDate';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
Expand Down Expand Up @@ -99,7 +100,6 @@ import {accountIDSelector, isPersonalDetailOptimistic} from '@selectors/Personal
import {getStableReportSelector} from '@selectors/Report';
import {pendingChatMembersSelector} from '@selectors/ReportMetaData';
import {latestCalendlyCallSelector} from '@selectors/ReportNameValuePairs';
import {isPast} from 'date-fns';
import React, {useMemo} from 'react';
import {Keyboard, View} from 'react-native';

Expand Down Expand Up @@ -141,6 +141,7 @@ function HeaderView({onNavigationMenuButtonClicked, reportID}: HeaderViewProps)
}),
});
const [latestScheduledCall] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`, {selector: latestCalendlyCallSelector});
const isScheduledCallPast = useIsPastDate(latestScheduledCall?.eventTime);
const [reportMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_METADATA}${report?.reportID}`, {selector: pendingChatMembersSelector});
const isReportArchived = useReportIsArchived(report?.reportID);
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
Expand Down Expand Up @@ -352,7 +353,7 @@ function HeaderView({onNavigationMenuButtonClicked, reportID}: HeaderViewProps)
!shouldMirrorSidePanelHeader;
const shouldShowOnBoardingHelpDropdownButton = (shouldShowRegisterForWebinar || shouldShowGuideBooking) && !isReportArchived && !shouldMirrorSidePanelHeader;
const shouldShowEarlyDiscountBanner = shouldShowDiscount && isChatUsedForOnboarding && !shouldMirrorSidePanelHeader;
const hasActiveScheduledCall = latestScheduledCall && !isPast(latestScheduledCall.eventTime) && latestScheduledCall.status !== CONST.SCHEDULE_CALL_STATUS.CANCELLED;
const hasActiveScheduledCall = !!latestScheduledCall && !isScheduledCallPast && latestScheduledCall.status !== CONST.SCHEDULE_CALL_STATUS.CANCELLED;
// Not gated on !shouldUseNarrowLayout like the side-panel case: isInNarrowPaneModal makes
// shouldUseNarrowLayout true for any RHP regardless of actual screen width.
const shouldShowCloseButton = (!!isInSidePanel && !shouldUseNarrowLayout) || isAgentReportInRHP;
Expand Down
109 changes: 109 additions & 0 deletions tests/unit/useIsPastDateTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import {act, renderHook} from '@testing-library/react-native';

import useIsPastDate from '@hooks/useIsPastDate';

import CONST from '@src/CONST';

const ONE_MINUTE_MS = 60 * 1000;

function getDateFromNow(offsetMs: number) {
return new Date(Date.now() + offsetMs).toISOString();
}

describe('useIsPastDate', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('returns false until the date passes and true right after', () => {
// Given a date one minute in the future
const date = getDateFromNow(ONE_MINUTE_MS);
const {result} = renderHook(() => useIsPastDate(date));
expect(result.current).toBe(false);

// When time moves to just before the date
act(() => {
jest.advanceTimersByTime(ONE_MINUTE_MS - 1000);
});

// Then it still reports the date as upcoming
expect(result.current).toBe(false);

// When time moves past the date without any other re-render trigger
act(() => {
jest.advanceTimersByTime(1000);
});

// Then it flips to true on its own, because the hook schedules a re-render for the moment the date passes
expect(result.current).toBe(true);
});

it('resets to false when a passed date is replaced by a future one', () => {
// Given a date that has already been reached while the hook is mounted
const {result, rerender} = renderHook(({date}: {date: string}) => useIsPastDate(date), {initialProps: {date: getDateFromNow(ONE_MINUTE_MS)}});
act(() => {
jest.advanceTimersByTime(ONE_MINUTE_MS);
});
expect(result.current).toBe(true);

// When the date is replaced by a new future one, like a call rescheduled after the previous one passed
rerender({date: getDateFromNow(ONE_MINUTE_MS)});

// Then it reports the new date as upcoming, because the passed state belongs to the old date only
expect(result.current).toBe(false);

// When the new date passes
act(() => {
jest.advanceTimersByTime(ONE_MINUTE_MS);
});

// Then it flips to true again
expect(result.current).toBe(true);
});

it('returns true immediately for a date that already passed', () => {
// Given a date one minute in the past
const date = getDateFromNow(-ONE_MINUTE_MS);

// When the hook renders
const {result} = renderHook(() => useIsPastDate(date));

// Then it reports the date as passed without waiting for a timer
expect(result.current).toBe(true);
});

it('returns false when there is no date', () => {
// Given no date
// When the hook renders
const {result} = renderHook(() => useIsPastDate(undefined));

// Then it reports false, so callers treat a missing date as not passed
expect(result.current).toBe(false);
});

it('flips at the date even when it is further away than the maximum setTimeout delay', () => {
// Given a date beyond CONST.LIMIT_TIMEOUT, where a single setTimeout would overflow and fire immediately
const date = getDateFromNow(CONST.LIMIT_TIMEOUT + ONE_MINUTE_MS);
const {result} = renderHook(() => useIsPastDate(date));

// When the first LIMIT_TIMEOUT step elapses
act(() => {
jest.advanceTimersByTime(CONST.LIMIT_TIMEOUT);
});

// Then it is still upcoming, because the hook re-arms instead of firing early
expect(result.current).toBe(false);

// When the remaining time elapses
act(() => {
jest.advanceTimersByTime(ONE_MINUTE_MS);
});

// Then it flips exactly at the date
expect(result.current).toBe(true);
});
});
Loading