Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 67d512ca27 fix(app): hold running indicators in place while their panel is hidden
A ring, loader or shimmer in a panel that was not showing drew its resting
frame. On a phone the sidebar slides into view before its panel counts as
showing, so every ring sat at the resting position during the slide and
jumped to the running position when the slide settled.

A hidden indicator now stays bound to its clock and stops running it. The
clock and the loader's ticker hold the time they have run and count on from
it, so an indicator continues from where it stopped.
2026-12-01 13:25:22 +01:00
Mohamed Boudra bdad80d9bf fix(app): count the indicator clock with a timing the driver cannot end early
The native clock was a decay that never slows. React Native's driver ends
a decay when its value moves less than 0.1 between two frames, and two
frames that carry the same millisecond are enough. #11586 started the
decay again from the JS thread, but every end still showed as a pause and
a jump until the JS thread got to it.

The clock is now a linear timing, which the driver reads off the time
since it started and has no such check. It counts in ten-minute spans.
The end of a span is the one event that reaches the JS thread, which
starts the next span at the current time.
2026-12-01 13:25:22 +01:00
15 changed files with 294 additions and 165 deletions
+4 -3
View File
@@ -146,9 +146,10 @@ definition, no longer eligible to begin.
- Panels whose gesture wrapper already owns visibility use `RetainedPanelActivity` to provide the
same active signal without adding another layout root. Persistent animations, timers, polling, and
shared clocks must subscribe to that signal and stop when their final visible consumer leaves.
- Synchronized step animations use one wall-clock-aligned source. Register a local shared value only
while its retained panel is active so hidden animated styles remain mounted without receiving clock
updates. Do not give every instance its own loop or leave hidden styles subscribed to the source.
- Synchronized step animations use one source. Do not give every instance its own loop. A hidden
instance stops running the source and keeps its place, because the active signal changes after the
panel has slid into view; see
[running-indicators.md](running-indicators.md#hidden-panels).
- Retention order and render order are separate concerns. LRU metadata may change on every switch;
keyed retained roots must keep a stable sibling order. Moving large retained roots triggered Fabric
Differ failures (`addViewAt` / `removeViewAt` view reuse) on Android.
+51 -16
View File
@@ -14,14 +14,37 @@ value.
`components/indicator-motion` owns the two pieces every indicator shares:
- `useIndicatorMotion()` decides whether an indicator may move: not under reduced motion, not in a
retained panel that is not showing, not while the app is in the background. An indicator that may
not move draws its resting frame and runs nothing. Ask this hook; do not read reduced motion or
visibility yourself.
- `useIndicatorMotion()` says what an indicator does now. Ask this hook; do not read reduced motion
or visibility yourself.
- `moving`: it runs.
- `held`: nobody can see it, in a retained panel that is not showing or in an app in the
background. It runs nothing and keeps its place.
- `resting`: the system asks for reduced motion. It draws its resting frame and runs nothing.
- The driver: `loop.web.ts` on web, `clock.ts` on native.
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
## Hidden panels
A phone's sidebar slides into view before its panel counts as showing: the panel's active signal
changes when the slide settles, never during it (see [mobile-panels.md](mobile-panels.md)). An
indicator that changes what it draws on that signal changes it in front of the user. A held ring
that drew its resting position jumped to the running position at the end of every slide.
So on native a held indicator stays bound to its clock and stops running it:
- The clock and the loader's ticker count the time they have run, and hold it while nothing runs
them. They are never set back to zero or to the wall clock.
- While another panel runs the clock, a held view follows it. Measured on an Android emulator with
six held rings behind a running chat, the app drew the same frames a second as with the rings
unbound, and CPU on each thread differed by less than it does between two runs.
- While nothing runs the clock, a held view costs nothing: behind an idle chat the app draws no
frames.
- One commit can stop the last moving indicator and start another, as when the sidebar replaces the
chat. The clock stops after the commit, so it counts through that without a restart.
Web does not do this: a held indicator on web cancels its loop and draws its resting frame.
## Frames
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
@@ -88,31 +111,43 @@ For a transition that is fine. For an indicator that runs for an hour it was 22
the UI thread of an Android emulator.
React Native's own `Animated` with `useNativeDriver: true` updates the view from the native driver
and commits nothing. `clock.ts` builds a clock out of it: a decay that never slows, at one unit per
millisecond, is the time since it started. Decay is the one native-driven animation that computes
its value from the frame timestamp instead of replaying a 60 fps recording, so it is exact at any
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
rotation or a translation, all inside the native driver.
and commits nothing. `clock.ts` builds a clock out of it: a linear timing at one unit per
millisecond is the time since the clock started. `Animated.modulo` and `interpolate` turn the clock
into a rotation or a translation, all inside the native driver.
The driver ends a decay when its value moves less than 0.1 between two frames, whatever the
deceleration. Two frames that carry the same millisecond are enough, and then every indicator on the
clock freezes at once. The clock listens for that end and starts the decay again at the current
The timing counts in spans of ten minutes. The end of a span is the one event that reaches the JS
thread, which starts the next span where that one ended, so a cycle keeps its place from one span to
the next.
The native driver owns the clock's value. The JS thread starts and stops the counting and never
sets the value, so a stopped clock keeps the value its views show. When the clock stops, the driver
reports the value it stopped at, and the next start counts on from it.
Do not drive the clock with a decay. A decay that never slows counts time without spans, but the
driver ends a decay when its value moves less than 0.1 between two frames, whatever the
deceleration. Two frames that carry the same millisecond are enough, and then every indicator on
the clock freezes. Starting the decay again from the JS thread shows as a pause and a jump each
time.
Android replays a timing as 60 positions a second at any refresh rate, and iOS interpolates between
them. Every cycle on the clock is stepped at 30 positions a second, so this does not show. A cycle
without steps would move 60 times a second on a 120 Hz Android display.
`cycle(periodMs, { steps })` holds the position at each step. The driver still ticks every frame,
but a view whose transform did not change is not invalidated, so nothing is drawn between steps.
The native clock starts on the frame where the driver picks it up, so two clocks started at
different times turn their steps over on different frames. That is why the shimmer rides
`sharedIndicatorClock`, the rings' clock, with `phase: "own"`: its pass starts at the clock's
current step. The JS thread works out that step from the time it started the clock. The driver
current step. The JS thread works out that step from the time it started the clock and the value
the clock started from. The driver
starts the clock a frame or two later, so a pass can start one step early or late. The band starts
one band width outside the label, so this does not show.
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
the JS thread once per step, aligned to wall-clock step boundaries, and publishes the step into a
native `Animated.Value`. A wake-up that arrives late publishes the step that is current by then, so
the loader never drifts and every loader shows the same step.
the JS thread once per step and publishes the step into a native `Animated.Value`. A wake-up that
arrives late publishes the step that is current by then, so the loader never drifts. Every loader
reads the one value, so they all show the same step.
Do not apply Unistyles dynamic styles to these `Animated.View`s; see
[unistyles.md](unistyles.md#reanimated-animatedview--dynamic-styles-crashes).
@@ -35,28 +35,44 @@ function frames(hz: number, count: number): number[] {
return Array.from({ length: count }, (_, frame) => (frame * 1000) / hz);
}
// A driver that advances nothing by itself, so the test decides when it ends.
// A driver that advances nothing by itself, so the test decides when each span ends and when the
// native driver says where a stopped clock is.
function heldDriver() {
const spansFromMs: number[] = [];
const reports: ((heldMs: number) => void)[] = [];
let onEnd: ((result: { finished: boolean }) => void) | null = null;
function end(finished: boolean) {
const ended = onEnd;
onEnd = null;
ended?.({ finished });
}
const driver: ClockDriver = {
start(ended) {
onEnd = ended;
},
stop: () => end(false),
};
return {
drive: () => driver,
/** What the native driver does when two frames carry the same timestamp. */
drive(_elapsedMs: Animated.Value, fromMs: number): ClockDriver {
spansFromMs.push(fromMs);
return {
start(ended) {
onEnd = ended;
},
stop(onHeld) {
reports.push(onHeld);
end(false);
},
};
},
/** What the native driver reports when it has counted a whole span. */
finish: () => end(true),
/** The native driver's answer to the oldest stop it has not answered. */
reportHeld: (heldMs: number) => reports.shift()?.(heldMs),
running: () => onEnd !== null,
spansFromMs,
};
}
// The clock stops after the commit that took its last indicator away.
async function commit(): Promise<void> {
await Promise.resolve();
}
describe("indicator clock", () => {
test("a cycle without steps advances with every frame", () => {
expect(positionsAt([0, 16, 450, 899, 900, 916])).toEqual([0, 16, 450, 899, 0, 16]);
@@ -109,7 +125,7 @@ describe("indicator clock", () => {
const shimmerPeriodMs = shimmerSteps * STEP_MS;
let nowMs = 0;
const elapsedMs = new Animated.Value(0);
const clock = createIndicatorClock(elapsedMs, () => nowMs);
const clock = createIndicatorClock(elapsedMs, () => nowMs, heldDriver().drive);
const stop = clock.run();
// The shared clock has been running for a while when the shimmer appears.
@@ -143,35 +159,110 @@ describe("indicator clock", () => {
expect(read(shimmer)).toBe(0);
});
test("a clock the driver ends under a running indicator starts again at the current time", () => {
test("a span that ends under a running indicator is followed by one from where it ended", async () => {
let nowMs = 0;
const elapsedMs = new Animated.Value(0);
const driver = heldDriver();
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
const stop = clock.run();
nowMs = 37_650;
// The JS thread hears about the end a few milliseconds after it.
nowMs = 600_012;
driver.finish();
expect(driver.running()).toBe(true);
expect(read(elapsedMs)).toBe(37_650);
expect(driver.spansFromMs).toEqual([0, 600_000]);
stop();
await commit();
expect(driver.running()).toBe(false);
});
test("a clock that starts again keeps a cycle with its own phase on its first step", () => {
test("a stopped clock holds its time and counts on from it", async () => {
let nowMs = 0;
const driver = heldDriver();
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
const stop = clock.run();
nowMs = 5000;
stop();
await commit();
expect(driver.running()).toBe(false);
// The native driver started counting a frame after the JS thread asked.
driver.reportHeld(4983);
nowMs = 90_000;
clock.run();
expect(driver.spansFromMs).toEqual([0, 4983]);
});
test("a clock restarted before the driver reports counts on from its own reading", async () => {
let nowMs = 0;
const driver = heldDriver();
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
const stopFirst = clock.run();
nowMs = 5000;
stopFirst();
await commit();
const stopSecond = clock.run();
nowMs = 7000;
stopSecond();
await commit();
// The answer to the first stop arrives after the second.
driver.reportHeld(4983);
clock.run();
expect(driver.spansFromMs).toEqual([0, 5000, 7000]);
});
test("the clock keeps counting when one indicator takes over from another in a commit", async () => {
const driver = heldDriver();
const clock = createIndicatorClock(new Animated.Value(0), () => 0, driver.drive);
const stopChat = clock.run();
stopChat();
const stopSidebar = clock.run();
await commit();
expect(driver.running()).toBe(true);
expect(driver.spansFromMs).toEqual([0]);
stopSidebar();
await commit();
expect(driver.running()).toBe(false);
});
test("a cycle with its own phase on a stopped clock starts where the clock will count on", async () => {
let nowMs = 0;
const elapsedMs = new Animated.Value(0);
const driver = heldDriver();
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
const stop = clock.run();
nowMs = 5000;
stop();
await commit();
driver.reportHeld(4983);
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
elapsedMs.setValue(4983);
expect(read(shimmer)).toBeLessThan(STEP_MS);
});
test("a cycle with its own phase starts at its first step in a later span too", () => {
let nowMs = 0;
const elapsedMs = new Animated.Value(0);
const driver = heldDriver();
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
const stop = clock.run();
nowMs = 37_650;
nowMs = 600_012;
driver.finish();
nowMs = 40_000;
// The second span started at 600 000 on the clock, 12 ms late on the JS thread.
nowMs = 640_012;
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
elapsedMs.setValue(40_000);
elapsedMs.setValue(640_000);
stop();
expect(read(shimmer)).toBeLessThan(STEP_MS);
@@ -1,11 +1,17 @@
import { useEffect } from "react";
import { Animated } from "react-native";
import { Animated, Easing } from "react-native";
// A decay that never slows is a clock: with a velocity of one unit per millisecond the value is the
// time since it started. Decay is the one native-driven animation that computes its value from the
// frame's timestamp instead of replaying a 60 fps recording, so the motion is exact at any refresh
// rate and never loops.
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
// The clock counts time in spans this long: a linear timing of one unit per millisecond, which the
// native driver reads off the frame's timestamp. Only the end of a span comes back to the JS
// thread, which starts the next one where that one ended.
//
// A decay that never slows would count without spans, but the driver ends a decay whose value did
// not move between two frames, and two frames that carry the same millisecond are enough. A timing
// has no such check.
//
// The timing is sent to the driver as one value for every 60th of a second, so a longer span costs
// more each time the clock starts.
const SPAN_MS = 10 * 60 * 1000;
// The clock starts on a frame and advances a whole frame at a time, so at 60, 90 and 120 Hz a step
// that is a whole number of frames long would turn over exactly on a frame, and rounding would
@@ -14,7 +20,8 @@ const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: tr
const STEP_LEAD = 1 / 8;
/**
* Milliseconds, counted on the UI thread by React Native's native animation driver.
* Milliseconds for which the clock has run, counted on the UI thread by React Native's native
* animation driver.
*
* Views bound to it are updated by the native driver directly. Nothing reaches the JS thread, React
* does not render, and no shadow tree is committed — which is what a Reanimated shared value costs
@@ -37,50 +44,75 @@ export interface CycleOptions {
export interface IndicatorClock {
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
cycle(periodMs: number, options?: CycleOptions): Animated.AnimatedInterpolation<number>;
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
/**
* Runs the clock until the returned function is called. A clock nobody runs holds its time, and
* counts on from it when it runs again, so a view bound to it stays where it stopped.
*/
run(): () => void;
}
/** What advances the clock's value until it is stopped. */
/** What advances the clock's value through one span, or until it is stopped. */
export interface ClockDriver {
start(onEnd: (result: { finished: boolean }) => void): void;
stop(): void;
/** Stops counting, then reports the time the clock stopped at. */
stop(onHeld: (heldMs: number) => void): void;
}
function decayForever(elapsedMs: Animated.Value): ClockDriver {
return Animated.decay(elapsedMs, CLOCK_CONFIG);
function countSpan(elapsedMs: Animated.Value, fromMs: number): ClockDriver {
const span = Animated.timing(elapsedMs, {
toValue: fromMs + SPAN_MS,
duration: SPAN_MS,
easing: Easing.linear,
useNativeDriver: true,
});
return {
start: (onEnd) => span.start(onEnd),
stop: (onHeld) => elapsedMs.stopAnimation(onHeld),
};
}
/**
* `now` is the JS thread's view of the time the clock reads. The native driver starts the clock a
* frame or two after `run()` is called, so a cycle with its own phase can start a step into its
* pass, or a step before it; the run-in before the first position hides either.
* The native driver owns the clock's time: the JS thread never sets it, only starts and stops the
* counting. `now` lets the JS thread follow along. The native driver starts counting a frame or two
* after it is asked, so a cycle with its own phase can start a step into its pass, or a step
* before it; the run-in before the first position hides either.
*/
export function createIndicatorClock(
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
now: () => number = () => performance.now(),
drive: (elapsedMs: Animated.Value) => ClockDriver = decayForever,
drive: (elapsedMs: Animated.Value, fromMs: number) => ClockDriver = countSpan,
): IndicatorClock {
let runners = 0;
let ticking: ClockDriver | null = null;
let startedAtMs = 0;
// While the clock counts: when, on the JS thread, it read zero.
let zeroAtMs = 0;
// While it does not: the time it holds.
let heldMs = 0;
let lastStopped: ClockDriver | null = null;
function currentStepStartMs(stepMs: number): number {
if (!ticking) {
return 0;
}
return Math.floor((now() - startedAtMs) / stepMs) * stepMs;
const elapsed = ticking ? now() - zeroAtMs : heldMs;
return Math.floor(elapsed / stepMs) * stepMs;
}
// The driver ends a decay whose value did not move between two frames, and two frames that carry
// the same millisecond are enough for that. Nothing tells the indicators, so the clock starts
// again where the time is now.
function tick() {
elapsedMs.setValue(now() - startedAtMs);
const driver = drive(elapsedMs);
function count(fromMs: number) {
zeroAtMs = now() - fromMs;
const driver = drive(elapsedMs, fromMs);
ticking = driver;
driver.start(({ finished }) => {
if (finished && ticking === driver) tick();
if (finished && ticking === driver) count(fromMs + SPAN_MS);
});
}
function hold() {
if (runners > 0 || !ticking) return;
const stopped = ticking;
ticking = null;
lastStopped = stopped;
// The JS thread's reading stands until the native driver reports its own.
heldMs = now() - zeroAtMs;
stopped.stop((reportedMs) => {
if (!ticking && lastStopped === stopped) heldMs = reportedMs;
});
}
@@ -99,16 +131,13 @@ export function createIndicatorClock(
run() {
runners += 1;
if (!ticking) {
startedAtMs = now();
tick();
count(heldMs);
}
return () => {
runners -= 1;
if (runners === 0) {
const stopped = ticking;
ticking = null;
stopped?.stop();
}
// One commit can take the last indicator away and bring another, as when a panel replaces
// another. Stopping after the commit keeps the clock counting through that.
if (runners === 0) queueMicrotask(hold);
};
},
};
@@ -35,15 +35,21 @@ function useReducedMotion(): boolean {
}
/**
* Whether a running indicator may move right now. It holds still when the system asks for reduced
* motion, and while nobody can see it: in a retained panel that is not showing, or in an app that
* is in the background.
* What a running indicator does right now.
*
* An indicator that is not moving draws its resting frame and runs nothing.
* - `moving`: it runs.
* - `held`: nobody can see it, in a retained panel that is not showing or in an app that is in the
* background. It runs nothing and keeps its place, so it continues from there when it is seen
* again. A panel slides into view before it counts as showing, and an indicator that dropped to
* its resting frame would jump when the slide ends.
* - `resting`: the system asks for reduced motion. It draws its resting frame and runs nothing.
*/
export function useIndicatorMotion(): boolean {
export type IndicatorMotion = "moving" | "held" | "resting";
export function useIndicatorMotion(): IndicatorMotion {
const panelActive = useRetainedPanelActive();
const appVisible = useAppVisible();
const reducedMotion = useReducedMotion();
return panelActive && appVisible && !reducedMotion;
if (reducedMotion) return "resting";
return panelActive && appVisible ? "moving" : "held";
}
@@ -50,7 +50,7 @@ const styles = StyleSheet.create({
* Native label shimmer: a gradient band slides behind a mask cut in the shape of the label. The
* native animation driver moves the band; see `indicator-motion/clock.ts`. The band rides the
* shared clock, so its steps turn over on the same frames as the status rings', and starts its own
* pass so the highlight enters from the left when it starts moving.
* pass so the highlight enters from the left when it appears.
*/
export const LabelShimmer = memo(function LabelShimmer({
label,
@@ -61,21 +61,23 @@ export const LabelShimmer = memo(function LabelShimmer({
}: LabelShimmerProps) {
const { rowSize } = measurements;
const measured = rowSize.width > 0 && rowSize.height > 0;
const moving = useIndicatorMotion() && measured;
const motion = useIndicatorMotion();
// A held band stays on the clock, so it keeps its place and its pass.
const sweeping = motion !== "resting" && measured;
const [gradientId] = useState(
() => `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
);
useRunningClock(sharedIndicatorClock, moving);
useRunningClock(sharedIndicatorClock, motion === "moving" && measured);
const { durationMs, steps } = getShimmerCycle(label, secondaryLabel);
const { peakWidth, fromX, toX } = getRowSweep(rowSize.width);
const { width, height } = rowSize;
const trackStyle = useMemo(() => [styles.track, { width, height }], [height, width]);
// Built again each time the band starts moving, so each start begins a new pass.
// Built again each time the band appears, so each appearance begins a new pass.
const bandStyle = useMemo(
() =>
moving
sweeping
? [
styles.band,
{ width: peakWidth, height },
@@ -90,7 +92,7 @@ export const LabelShimmer = memo(function LabelShimmer({
},
]
: null,
[durationMs, fromX, height, moving, peakWidth, steps, toX],
[durationMs, fromX, height, sweeping, peakWidth, steps, toX],
);
const maskElement = useMemo(
() => (
@@ -110,7 +112,7 @@ export const LabelShimmer = memo(function LabelShimmer({
[height, label, labelStyle, secondaryLabel, secondaryLabelStyle, width],
);
if (!moving) {
if (!sweeping) {
return null;
}
@@ -65,7 +65,7 @@ export const LabelShimmer = memo(function LabelShimmer({
measurements,
}: LabelShimmerProps) {
const { labelSpan, secondarySpan } = measurements;
const moving = useIndicatorMotion();
const moving = useIndicatorMotion() === "moving";
const { durationMs, steps } = getShimmerCycle(label, secondaryLabel);
const sweep = getTextSweep({ labelSpan, secondarySpan: secondaryLabel ? secondarySpan : null });
@@ -22,12 +22,12 @@ const turning = { transform: [{ rotate: rotation }] };
/** Native running indicator. The native animation driver turns the quarter; see `clock.ts`. */
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const moving = useIndicatorMotion();
useRunningClock(sharedIndicatorClock, moving);
const motion = useIndicatorMotion();
useRunningClock(sharedIndicatorClock, motion === "moving");
return (
<StatusRingFrame backdrop={backdrop}>
<Animated.View style={[rotatorStyles.rotator, moving && turning]}>
<Animated.View style={[rotatorStyles.rotator, motion !== "resting" && turning]}>
<View style={styles.arc} />
</Animated.View>
</StatusRingFrame>
@@ -23,7 +23,7 @@ const TURNING: IndicatorLoop = {
/** Web running indicator. The browser's compositor turns the quarter; see `loop.web.ts`. */
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const moving = useIndicatorMotion();
const moving = useIndicatorMotion() === "moving";
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
return (
@@ -34,8 +34,9 @@ const resting = DOTS.map((dot) => ({
*/
export function SyncedLoader(props: SyncedLoaderProps) {
const layout = useSyncedLoaderLayout(props);
const moving = useIndicatorMotion();
const motion = moving ? blinking : resting;
const motion = useIndicatorMotion();
const dots = motion === "resting" ? resting : blinking;
const moving = motion === "moving";
useEffect(() => {
if (!moving) return;
@@ -48,7 +49,7 @@ export function SyncedLoader(props: SyncedLoaderProps) {
{DOTS.map((dot) => (
<Animated.View
key={dot}
style={[layout.dots[dot], motion[dot]]}
style={[layout.dots[dot], dots[dot]]}
testID="synced-loader-dot"
/>
))}
@@ -36,7 +36,7 @@ const RESTING = DOTS.map(
*/
export function SyncedLoader(props: SyncedLoaderProps) {
const layout = useSyncedLoaderLayout(props);
const moving = useIndicatorMotion();
const moving = useIndicatorMotion() === "moving";
return (
<View style={layout.container} testID="synced-loader">
@@ -41,21 +41,28 @@ describe("synced loader step ticker", () => {
]);
});
test("starts mid-cycle on the step the wall clock is on", () => {
vi.setSystemTime(950 * 4 + 500);
test("holds its step while no loader runs and continues from it", () => {
const { ticker, published } = startRecordingTicker();
const stop = ticker.run();
vi.advanceTimersByTime(140);
vi.advanceTimersByTime(400);
stop();
vi.advanceTimersByTime(10_000);
const stopAgain = ticker.run();
vi.advanceTimersByTime(80);
stopAgain();
// Stopped 83 ms into step 2, so step 3 comes 75 ms after the loader runs again.
expect(published).toEqual([
{ step: 3, atMs: 950 * 4 + 500 },
{ step: 4, atMs: 950 * 4 + 634 },
{ step: 0, atMs: 0 },
{ step: 1, atMs: 159 },
{ step: 2, atMs: 317 },
{ step: 2, atMs: 10_400 },
{ step: 3, atMs: 10_475 },
]);
});
test("catches up to the wall clock after a late wake-up instead of drifting", () => {
test("catches up after a late wake-up instead of drifting", () => {
const { ticker, published } = startRecordingTicker();
const stop = ticker.run();
@@ -3,12 +3,15 @@ import { getSyncedLoaderStep, getSyncedLoaderStepRemainingMs } from "./state";
/**
* Publishes the loader's step each time it changes, and at no other time.
*
* The loader has six frames a cycle, so it needs six wake-ups a cycle. Each wake-up reads the wall
* clock and sleeps until the next step is due, which keeps a late timer from pushing every later
* step back and keeps every loader in the app on the same step.
* The loader has six frames a cycle, so it needs six wake-ups a cycle. Each wake-up reads the time
* and sleeps until the next step is due, which keeps a late timer from pushing every later step
* back. Every loader in the app reads this one ticker, so they all show the same step.
*/
export interface SyncedLoaderStepTicker {
/** Ticks until the returned function is called. Publishes the current step at once. */
/**
* Ticks until the returned function is called. A ticker nobody runs holds its step, and continues
* from it when it runs again. Publishes the current step at once.
*/
run(): () => void;
}
@@ -17,17 +20,21 @@ export function createSyncedLoaderStepTicker(
): SyncedLoaderStepTicker {
let runners = 0;
let timer: ReturnType<typeof setTimeout> | null = null;
// How long the ticker has run: up to its latest start, and since.
let ranMs = 0;
let startedAtMs = 0;
function tick(): void {
const nowMs = Date.now();
publish(getSyncedLoaderStep(nowMs));
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(nowMs));
const runMs = ranMs + Date.now() - startedAtMs;
publish(getSyncedLoaderStep(runMs));
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(runMs));
}
return {
run() {
runners += 1;
if (timer === null) {
startedAtMs = Date.now();
tick();
}
return () => {
@@ -35,6 +42,7 @@ export function createSyncedLoaderStepTicker(
if (runners === 0 && timer !== null) {
clearTimeout(timer);
timer = null;
ranMs += Date.now() - startedAtMs;
}
};
},
@@ -1,46 +0,0 @@
// @vitest-environment jsdom
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it } from "vitest";
import { useWorkspaceTerminals } from "./use-workspace-terminals";
const noop = () => {};
function renderWorkspaceTerminals() {
const queryClient = new QueryClient();
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const input = {
client: null,
isConnected: false,
isRouteFocused: true,
normalizedServerId: "server",
normalizedWorkspaceId: "workspace",
workspaceDirectory: null,
workspaceScripts: [],
hasHydratedWorkspaces: false,
isMissingWorkspaceDirectory: false,
onTerminalCreated: noop,
onScriptTerminalSelected: noop,
onWorkspacePathUnavailable: noop,
onTerminalCreateQueued: noop,
onTerminalCreateFailed: noop,
};
return renderHook(() => useWorkspaceTerminals(input), { wrapper });
}
describe("useWorkspaceTerminals", () => {
// Every workspace header and pane takes createTerminal through its menus, so a
// new function on an unrelated render re-renders every pane.
it("keeps createTerminal stable when the workspace screen re-renders", () => {
const { result, rerender } = renderWorkspaceTerminals();
const firstCreateTerminal = result.current.createTerminal;
rerender();
expect(result.current.createTerminal).toBe(firstCreateTerminal);
});
});
@@ -178,18 +178,15 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
onTerminalCreateFailed(error instanceof Error ? error.message : String(error));
},
});
// useMutation returns a new object on every render; depend on its stable
// mutate and its pending flag so createTerminal keeps its identity.
const { mutate: mutateCreate, isPending: isCreatePending } = createMutation;
useEffect(() => {
if (!pendingCreateInput) {
return;
}
if (canCreateNow && !isCreatePending) {
if (canCreateNow && !createMutation.isPending) {
const pendingInput = pendingCreateInput;
setPendingCreateInput(null);
mutateCreate(pendingInput);
createMutation.mutate(pendingInput);
return;
}
@@ -199,22 +196,21 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
}
}, [
canCreateNow,
createMutation,
hasHydratedWorkspaces,
isCreatePending,
isMissingWorkspaceDirectory,
mutateCreate,
onWorkspacePathUnavailable,
pendingCreateInput,
]);
const createTerminal = useCallback(
(createInput: PendingTerminalCreateInput) => {
if (isCreatePending || pendingCreateInput) {
if (createMutation.isPending || pendingCreateInput) {
return;
}
if (canCreateNow) {
mutateCreate(createInput);
createMutation.mutate(createInput);
return;
}
@@ -228,10 +224,9 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
},
[
canCreateNow,
createMutation,
hasHydratedWorkspaces,
isCreatePending,
isMissingWorkspaceDirectory,
mutateCreate,
onTerminalCreateQueued,
onWorkspacePathUnavailable,
pendingCreateInput,