mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 12:46:55 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1ee5dee63 |
@@ -146,10 +146,9 @@ 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 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).
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
+16
-51
@@ -14,37 +14,14 @@ value.
|
||||
|
||||
`components/indicator-motion` owns the two pieces every indicator shares:
|
||||
|
||||
- `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.
|
||||
- `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.
|
||||
- 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,
|
||||
@@ -111,43 +88,31 @@ 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 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.
|
||||
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.
|
||||
|
||||
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
|
||||
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
|
||||
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 and the value
|
||||
the clock started from. The driver
|
||||
current step. The JS thread works out that step from the time it started the clock. 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 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.
|
||||
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.
|
||||
|
||||
Do not apply Unistyles dynamic styles to these `Animated.View`s; see
|
||||
[unistyles.md](unistyles.md#reanimated-animatedview--dynamic-styles-crashes).
|
||||
|
||||
@@ -35,42 +35,26 @@ 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 each span ends and when the
|
||||
// native driver says where a stopped clock is.
|
||||
// A driver that advances nothing by itself, so the test decides when it ends.
|
||||
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 });
|
||||
}
|
||||
return {
|
||||
drive(_elapsedMs: Animated.Value, fromMs: number): ClockDriver {
|
||||
spansFromMs.push(fromMs);
|
||||
return {
|
||||
start(ended) {
|
||||
onEnd = ended;
|
||||
},
|
||||
stop(onHeld) {
|
||||
reports.push(onHeld);
|
||||
end(false);
|
||||
},
|
||||
};
|
||||
const driver: ClockDriver = {
|
||||
start(ended) {
|
||||
onEnd = ended;
|
||||
},
|
||||
/** What the native driver reports when it has counted a whole span. */
|
||||
stop: () => end(false),
|
||||
};
|
||||
return {
|
||||
drive: () => driver,
|
||||
/** What the native driver does when two frames carry the same timestamp. */
|
||||
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", () => {
|
||||
@@ -125,7 +109,7 @@ describe("indicator clock", () => {
|
||||
const shimmerPeriodMs = shimmerSteps * STEP_MS;
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, heldDriver().drive);
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs);
|
||||
const stop = clock.run();
|
||||
|
||||
// The shared clock has been running for a while when the shimmer appears.
|
||||
@@ -159,110 +143,35 @@ describe("indicator clock", () => {
|
||||
expect(read(shimmer)).toBe(0);
|
||||
});
|
||||
|
||||
test("a span that ends under a running indicator is followed by one from where it ended", async () => {
|
||||
let nowMs = 0;
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
// The JS thread hears about the end a few milliseconds after it.
|
||||
nowMs = 600_012;
|
||||
driver.finish();
|
||||
|
||||
expect(driver.running()).toBe(true);
|
||||
expect(driver.spansFromMs).toEqual([0, 600_000]);
|
||||
|
||||
stop();
|
||||
await commit();
|
||||
expect(driver.running()).toBe(false);
|
||||
});
|
||||
|
||||
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", () => {
|
||||
test("a clock the driver ends under a running indicator starts again at the current time", () => {
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
nowMs = 600_012;
|
||||
nowMs = 37_650;
|
||||
driver.finish();
|
||||
// The second span started at 600 000 on the clock, 12 ms late on the JS thread.
|
||||
nowMs = 640_012;
|
||||
|
||||
expect(driver.running()).toBe(true);
|
||||
expect(read(elapsedMs)).toBe(37_650);
|
||||
|
||||
stop();
|
||||
expect(driver.running()).toBe(false);
|
||||
});
|
||||
|
||||
test("a clock that starts again keeps a cycle with its own phase on its first step", () => {
|
||||
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;
|
||||
driver.finish();
|
||||
nowMs = 40_000;
|
||||
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
|
||||
elapsedMs.setValue(640_000);
|
||||
elapsedMs.setValue(40_000);
|
||||
stop();
|
||||
|
||||
expect(read(shimmer)).toBeLessThan(STEP_MS);
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
import { useEffect } from "react";
|
||||
import { Animated, Easing } from "react-native";
|
||||
import { Animated } from "react-native";
|
||||
|
||||
// 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;
|
||||
// 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 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
|
||||
@@ -20,8 +14,7 @@ const SPAN_MS = 10 * 60 * 1000;
|
||||
const STEP_LEAD = 1 / 8;
|
||||
|
||||
/**
|
||||
* Milliseconds for which the clock has run, counted on the UI thread by React Native's native
|
||||
* animation driver.
|
||||
* Milliseconds, 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
|
||||
@@ -44,75 +37,50 @@ 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. 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.
|
||||
*/
|
||||
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
/** What advances the clock's value through one span, or until it is stopped. */
|
||||
/** What advances the clock's value until it is stopped. */
|
||||
export interface ClockDriver {
|
||||
start(onEnd: (result: { finished: boolean }) => void): void;
|
||||
/** Stops counting, then reports the time the clock stopped at. */
|
||||
stop(onHeld: (heldMs: number) => void): void;
|
||||
stop(): void;
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
function decayForever(elapsedMs: Animated.Value): ClockDriver {
|
||||
return Animated.decay(elapsedMs, CLOCK_CONFIG);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* `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.
|
||||
*/
|
||||
export function createIndicatorClock(
|
||||
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
|
||||
now: () => number = () => performance.now(),
|
||||
drive: (elapsedMs: Animated.Value, fromMs: number) => ClockDriver = countSpan,
|
||||
drive: (elapsedMs: Animated.Value) => ClockDriver = decayForever,
|
||||
): IndicatorClock {
|
||||
let runners = 0;
|
||||
let ticking: ClockDriver | null = null;
|
||||
// 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;
|
||||
let startedAtMs = 0;
|
||||
|
||||
function currentStepStartMs(stepMs: number): number {
|
||||
const elapsed = ticking ? now() - zeroAtMs : heldMs;
|
||||
return Math.floor(elapsed / stepMs) * stepMs;
|
||||
if (!ticking) {
|
||||
return 0;
|
||||
}
|
||||
return Math.floor((now() - startedAtMs) / stepMs) * stepMs;
|
||||
}
|
||||
|
||||
function count(fromMs: number) {
|
||||
zeroAtMs = now() - fromMs;
|
||||
const driver = drive(elapsedMs, fromMs);
|
||||
// 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);
|
||||
ticking = driver;
|
||||
driver.start(({ finished }) => {
|
||||
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;
|
||||
if (finished && ticking === driver) tick();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -131,13 +99,16 @@ export function createIndicatorClock(
|
||||
run() {
|
||||
runners += 1;
|
||||
if (!ticking) {
|
||||
count(heldMs);
|
||||
startedAtMs = now();
|
||||
tick();
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
// 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);
|
||||
if (runners === 0) {
|
||||
const stopped = ticking;
|
||||
ticking = null;
|
||||
stopped?.stop();
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -35,21 +35,15 @@ function useReducedMotion(): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* What a running indicator does right now.
|
||||
* 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.
|
||||
*
|
||||
* - `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.
|
||||
* An indicator that is not moving draws its resting frame and runs nothing.
|
||||
*/
|
||||
export type IndicatorMotion = "moving" | "held" | "resting";
|
||||
|
||||
export function useIndicatorMotion(): IndicatorMotion {
|
||||
export function useIndicatorMotion(): boolean {
|
||||
const panelActive = useRetainedPanelActive();
|
||||
const appVisible = useAppVisible();
|
||||
const reducedMotion = useReducedMotion();
|
||||
if (reducedMotion) return "resting";
|
||||
return panelActive && appVisible ? "moving" : "held";
|
||||
return panelActive && appVisible && !reducedMotion;
|
||||
}
|
||||
|
||||
@@ -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 appears.
|
||||
* pass so the highlight enters from the left when it starts moving.
|
||||
*/
|
||||
export const LabelShimmer = memo(function LabelShimmer({
|
||||
label,
|
||||
@@ -61,23 +61,21 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
const motion = useIndicatorMotion();
|
||||
// A held band stays on the clock, so it keeps its place and its pass.
|
||||
const sweeping = motion !== "resting" && measured;
|
||||
const moving = useIndicatorMotion() && measured;
|
||||
const [gradientId] = useState(
|
||||
() => `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
|
||||
);
|
||||
useRunningClock(sharedIndicatorClock, motion === "moving" && measured);
|
||||
useRunningClock(sharedIndicatorClock, moving);
|
||||
|
||||
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 appears, so each appearance begins a new pass.
|
||||
// Built again each time the band starts moving, so each start begins a new pass.
|
||||
const bandStyle = useMemo(
|
||||
() =>
|
||||
sweeping
|
||||
moving
|
||||
? [
|
||||
styles.band,
|
||||
{ width: peakWidth, height },
|
||||
@@ -92,7 +90,7 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
},
|
||||
]
|
||||
: null,
|
||||
[durationMs, fromX, height, sweeping, peakWidth, steps, toX],
|
||||
[durationMs, fromX, height, moving, peakWidth, steps, toX],
|
||||
);
|
||||
const maskElement = useMemo(
|
||||
() => (
|
||||
@@ -112,7 +110,7 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
[height, label, labelStyle, secondaryLabel, secondaryLabelStyle, width],
|
||||
);
|
||||
|
||||
if (!sweeping) {
|
||||
if (!moving) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { labelSpan, secondarySpan } = measurements;
|
||||
const moving = useIndicatorMotion() === "moving";
|
||||
const moving = useIndicatorMotion();
|
||||
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 motion = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, motion === "moving");
|
||||
const moving = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, moving);
|
||||
|
||||
return (
|
||||
<StatusRingFrame backdrop={backdrop}>
|
||||
<Animated.View style={[rotatorStyles.rotator, motion !== "resting" && turning]}>
|
||||
<Animated.View style={[rotatorStyles.rotator, moving && 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() === "moving";
|
||||
const moving = useIndicatorMotion();
|
||||
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
|
||||
|
||||
return (
|
||||
|
||||
@@ -34,9 +34,8 @@ const resting = DOTS.map((dot) => ({
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const motion = useIndicatorMotion();
|
||||
const dots = motion === "resting" ? resting : blinking;
|
||||
const moving = motion === "moving";
|
||||
const moving = useIndicatorMotion();
|
||||
const motion = moving ? blinking : resting;
|
||||
|
||||
useEffect(() => {
|
||||
if (!moving) return;
|
||||
@@ -49,7 +48,7 @@ export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
{DOTS.map((dot) => (
|
||||
<Animated.View
|
||||
key={dot}
|
||||
style={[layout.dots[dot], dots[dot]]}
|
||||
style={[layout.dots[dot], motion[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() === "moving";
|
||||
const moving = useIndicatorMotion();
|
||||
|
||||
return (
|
||||
<View style={layout.container} testID="synced-loader">
|
||||
|
||||
@@ -41,28 +41,21 @@ describe("synced loader step ticker", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("holds its step while no loader runs and continues from it", () => {
|
||||
test("starts mid-cycle on the step the wall clock is on", () => {
|
||||
vi.setSystemTime(950 * 4 + 500);
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
vi.advanceTimersByTime(400);
|
||||
vi.advanceTimersByTime(140);
|
||||
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: 0, atMs: 0 },
|
||||
{ step: 1, atMs: 159 },
|
||||
{ step: 2, atMs: 317 },
|
||||
{ step: 2, atMs: 10_400 },
|
||||
{ step: 3, atMs: 10_475 },
|
||||
{ step: 3, atMs: 950 * 4 + 500 },
|
||||
{ step: 4, atMs: 950 * 4 + 634 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("catches up after a late wake-up instead of drifting", () => {
|
||||
test("catches up to the wall clock after a late wake-up instead of drifting", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
|
||||
@@ -3,15 +3,12 @@ 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 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.
|
||||
* 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.
|
||||
*/
|
||||
export interface SyncedLoaderStepTicker {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** Ticks until the returned function is called. Publishes the current step at once. */
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
@@ -20,21 +17,17 @@ 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 runMs = ranMs + Date.now() - startedAtMs;
|
||||
publish(getSyncedLoaderStep(runMs));
|
||||
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(runMs));
|
||||
const nowMs = Date.now();
|
||||
publish(getSyncedLoaderStep(nowMs));
|
||||
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(nowMs));
|
||||
}
|
||||
|
||||
return {
|
||||
run() {
|
||||
runners += 1;
|
||||
if (timer === null) {
|
||||
startedAtMs = Date.now();
|
||||
tick();
|
||||
}
|
||||
return () => {
|
||||
@@ -42,7 +35,6 @@ export function createSyncedLoaderStepTicker(
|
||||
if (runners === 0 && timer !== null) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
ranMs += Date.now() - startedAtMs;
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// @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,15 +178,18 @@ 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 && !createMutation.isPending) {
|
||||
if (canCreateNow && !isCreatePending) {
|
||||
const pendingInput = pendingCreateInput;
|
||||
setPendingCreateInput(null);
|
||||
createMutation.mutate(pendingInput);
|
||||
mutateCreate(pendingInput);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -196,21 +199,22 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
|
||||
}
|
||||
}, [
|
||||
canCreateNow,
|
||||
createMutation,
|
||||
hasHydratedWorkspaces,
|
||||
isCreatePending,
|
||||
isMissingWorkspaceDirectory,
|
||||
mutateCreate,
|
||||
onWorkspacePathUnavailable,
|
||||
pendingCreateInput,
|
||||
]);
|
||||
|
||||
const createTerminal = useCallback(
|
||||
(createInput: PendingTerminalCreateInput) => {
|
||||
if (createMutation.isPending || pendingCreateInput) {
|
||||
if (isCreatePending || pendingCreateInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (canCreateNow) {
|
||||
createMutation.mutate(createInput);
|
||||
mutateCreate(createInput);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -224,9 +228,10 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
|
||||
},
|
||||
[
|
||||
canCreateNow,
|
||||
createMutation,
|
||||
hasHydratedWorkspaces,
|
||||
isCreatePending,
|
||||
isMissingWorkspaceDirectory,
|
||||
mutateCreate,
|
||||
onTerminalCreateQueued,
|
||||
onWorkspacePathUnavailable,
|
||||
pendingCreateInput,
|
||||
|
||||
Reference in New Issue
Block a user