Skip to content
Open
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
25 changes: 14 additions & 11 deletions src/components/ValidateCodeCountdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,20 @@ import type {ValidateCodeCountdownProps} from './types';
function ValidateCodeCountdown({onCountdownFinish, requestedAt, ref}: ValidateCodeCountdownProps) {
const {translate} = useLocalize();

// Seed from the time the code was actually requested so a reload mid-countdown resumes at the correct value instead of restarting at the full delay.
const [startedAt, setStartedAt] = useState(() => Date.now());
const anchor = requestedAt ?? startedAt;

// Seeding from the request time lets a reload mid-countdown resume instead of restarting at the full delay.
const [timeRemaining, setTimeRemaining] = useState<number>(
() => DateUtils.getRemainingSecondsInWindow(requestedAt, CONST.REQUEST_CODE_DELAY * CONST.MILLISECONDS_PER_SECOND) || CONST.REQUEST_CODE_DELAY,
() => DateUtils.getRemainingSecondsInWindow(anchor, CONST.REQUEST_CODE_DELAY * CONST.MILLISECONDS_PER_SECOND) || CONST.REQUEST_CODE_DELAY,
);
const timerRef = useRef<NodeJS.Timeout | undefined>(undefined);

useImperativeHandle(ref, () => ({
resetCountdown: () => setTimeRemaining(CONST.REQUEST_CODE_DELAY),
resetCountdown: () => {
setStartedAt(Date.now());
setTimeRemaining(CONST.REQUEST_CODE_DELAY);
},
}));

useEffect(() => {
Expand All @@ -30,21 +36,18 @@ function ValidateCodeCountdown({onCountdownFinish, requestedAt, ref}: ValidateCo
return;
}

// When anchored to `requestedAt`, align the next tick to the wall-clock second boundary so every tab/reload flips the
// displayed second at the same instant instead of drifting by each tab's own mount offset. Without an anchor (the
// `hasValidateCodeBeenSent` flows) there is nothing to align to, so fall back to a fixed 1s cadence.
const msUntilNextTick = requestedAt ? CONST.MILLISECONDS_PER_SECOND - ((Date.now() - requestedAt) % CONST.MILLISECONDS_PER_SECOND) : CONST.MILLISECONDS_PER_SECOND;
// Align to the anchor's second boundary so every tab and reload flips the same second at the same instant.
const msUntilNextTick = CONST.MILLISECONDS_PER_SECOND - ((Date.now() - anchor) % CONST.MILLISECONDS_PER_SECOND);

timerRef.current = setTimeout(() => {
// With an anchor, re-derive from the wall clock so the countdown self-corrects against setTimeout drift,
// background-tab throttling, and cross-tab phase differences. Without one, keep the simple decrement.
setTimeRemaining((prev) => (requestedAt ? DateUtils.getRemainingSecondsInWindow(requestedAt, CONST.REQUEST_CODE_DELAY * CONST.MILLISECONDS_PER_SECOND) : prev - 1));
// Recompute instead of decrementing: a throttled tab or a suspended app delivers fewer callbacks than seconds.
setTimeRemaining(DateUtils.getRemainingSecondsInWindow(anchor, CONST.REQUEST_CODE_DELAY * CONST.MILLISECONDS_PER_SECOND));
Comment thread
mukhrr marked this conversation as resolved.
}, msUntilNextTick);

return () => {
clearTimeout(timerRef.current);
};
}, [onCountdownFinish, timeRemaining, requestedAt]);
}, [onCountdownFinish, timeRemaining, anchor]);

// Announce countdown start/reset/expiration for screen readers.
// We check timeRemaining === 1 (not 0) because the component unmounts immediately at 0s, so the expired announcement wouldn't be spoken.
Expand Down
5 changes: 4 additions & 1 deletion src/libs/DateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,10 @@ function getRemainingSecondsInWindow(requestedAt: number | undefined, windowMs:
if (!requestedAt) {
return 0;
}
return Math.max(0, Math.ceil((windowMs - (Date.now() - requestedAt)) / CONST.MILLISECONDS_PER_SECOND));
const remainingSeconds = Math.ceil((windowMs - (Date.now() - requestedAt)) / CONST.MILLISECONDS_PER_SECOND);

// A backward clock correction leaves `requestedAt` in the future, which would otherwise report more than the window.
return Math.min(windowMs / CONST.MILLISECONDS_PER_SECOND, Math.max(0, remainingSeconds));
}

/**
Expand Down
102 changes: 102 additions & 0 deletions tests/ui/ValidateCodeCountdownTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import {act, render, screen} from '@testing-library/react-native';

import ValidateCodeCountdown from '@components/ValidateCodeCountdown';
import type {ValidateCodeCountdownHandle} from '@components/ValidateCodeCountdown/types';

import CONST from '@src/CONST';

import type ReactNative from 'react-native';

import React, {createRef} from 'react';

jest.mock('@hooks/useLocalize', () =>
jest.fn(() => ({
translate: (key: string, params?: {timeRemaining?: string}) => params?.timeRemaining ?? key,
})),
);
jest.mock('@hooks/useAccessibilityAnnouncement', () => jest.fn());
jest.mock('@components/RenderHTML', () => {
const ReactMock = jest.requireActual<typeof React>('react');
const {Text} = jest.requireActual<typeof ReactNative>('react-native');

return ({html}: {html: string}) => ReactMock.createElement(Text, null, html.replaceAll(/<[^>]*>/g, ''));
});

const BASE_TIME = new Date('2026-08-21T10:00:00.000Z').valueOf();

// One act per tick so React commits the effect that schedules the next one.
function tickSeconds(seconds: number) {
for (let i = 0; i < seconds; i++) {
act(() => jest.advanceTimersByTime(CONST.MILLISECONDS_PER_SECOND));
}
}

// Clock advances with no callback delivered, the way a throttled tab or a backgrounded app behaves.
function suspendFor(milliseconds: number) {
act(() => {
jest.setSystemTime(Date.now() + milliseconds);
jest.advanceTimersByTime(CONST.MILLISECONDS_PER_SECOND);
});
}

function renderCountdown(onCountdownFinish: () => void = jest.fn(), requestedAt?: number) {
const ref = createRef<ValidateCodeCountdownHandle>();
render(
<ValidateCodeCountdown
ref={ref}
requestedAt={requestedAt}
onCountdownFinish={onCountdownFinish}
/>,
);
return ref;
}

describe('ValidateCodeCountdown', () => {
beforeEach(() => {
jest.useFakeTimers();
jest.setSystemTime(BASE_TIME);
});

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

it('reports the time that actually elapsed after the timer was starved of callbacks', () => {
renderCountdown();
expect(screen.getByText('00:30')).toBeOnTheScreen();

tickSeconds(3);
expect(screen.getByText('00:27')).toBeOnTheScreen();

// 14s of the 30s window are gone once the single resume callback lands.
suspendFor(10 * CONST.MILLISECONDS_PER_SECOND);
expect(screen.getByText('00:16')).toBeOnTheScreen();
});

it('finishes once the window has elapsed even if the callbacks never arrived', () => {
const onCountdownFinish = jest.fn();
renderCountdown(onCountdownFinish);

suspendFor(CONST.REQUEST_CODE_DELAY * CONST.MILLISECONDS_PER_SECOND);
expect(onCountdownFinish).toHaveBeenCalled();
});

it('keeps measuring from a persisted requestedAt when one is passed', () => {
renderCountdown(jest.fn(), BASE_TIME - 8 * CONST.MILLISECONDS_PER_SECOND);
expect(screen.getByText('00:22')).toBeOnTheScreen();

suspendFor(10 * CONST.MILLISECONDS_PER_SECOND);
expect(screen.getByText('00:11')).toBeOnTheScreen();
});

it('measures from the resend time after the countdown is reset', () => {
const ref = renderCountdown();

tickSeconds(5);
act(() => ref.current?.resetCountdown());
expect(screen.getByText('00:30')).toBeOnTheScreen();

suspendFor(10 * CONST.MILLISECONDS_PER_SECOND);
expect(screen.getByText('00:19')).toBeOnTheScreen();
});
});
5 changes: 5 additions & 0 deletions tests/unit/DateUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,11 @@ describe('DateUtils', () => {
it('should clamp to 0 once the window has elapsed', () => {
expect(DateUtils.getRemainingSecondsInWindow(Date.now() - 31 * 1000, windowMs)).toBe(0);
});

// A backward clock correction leaves the request timestamp in the future.
it('should clamp to the full window when the timestamp is in the future', () => {
expect(DateUtils.getRemainingSecondsInWindow(Date.now() + 10 * 1000, windowMs)).toBe(30);
});
});

describe('getTimeOfDayGreetingKey', () => {
Expand Down
Loading