Skip to main content

motion/
lib.rs

1//! Animation kit — a named motion catalog as reusable helpers over gpui
2//! [`Animation`]/[`AnimationExt`].
3//!
4//! Catalog (docs/research/feature-inventory.md §1.12):
5//! - `fade-in`   0.5s  cubic-bezier(0.16,1,0.3,1), translateY 4→0 (entrances)
6//! - `fade-quick` 0.15s
7//! - `menu-in`   0.14s scale 0.96 + translateY −2 (popovers)
8//! - `dialog-in` 0.18s scale 0.96→1
9//! - `splash-out` 0.5s opacity + translateY −6, 0.15s delay
10//! - `pulse` 2.4s staggered cell opacity 0.08→1, scale 0.9→1 (loaders)
11//! - `gradient-spin-pulse` 750ms per-cell phase wave (working indicator)
12//! - 200ms ease-out width/height transitions (sidebar/panes)
13//!
14//! Custom easing is a closure over gpui's `Fn(f32) -> f32` easing shape; CSS
15//! `cubic-bezier()` is evaluated exactly by [`CubicBezier`].
16//!
17//! Reduced motion: gpui's `App::reduce_motion` flag is honored *automatically* by
18//! every `with_animation` element — oneshot animations snap to their end state,
19//! repeating ones to their start state, and no frames are scheduled.
20//! [`AppExt`] carries that switch and the rest of the app-level settings; pure
21//! helpers take the flag explicitly where they run outside elements.
22//!
23//! translateY is implemented as a relative-position `top` inset: taffy applies
24//! relative insets after layout, so — like a CSS transform — siblings never move.
25//! gpui has no scale transform for `div`s at the pinned rev (only `svg`
26//! transformations), so `menu-in`/`dialog-in` approximate their scale component
27//! with fade + translate.
28
29use std::{
30    cell::RefCell,
31    collections::HashMap,
32    sync::atomic::{AtomicU32, Ordering},
33    time::Duration,
34};
35
36use web_time::Instant;
37
38use gpui::{
39    Animation, AnimationElement, App, Context, ElementId, EntityId, Global, Hsla, IntoElement,
40    Rgba, SharedString, Styled, Window, px,
41};
42
43/// What the catalog's one-shot entrances are built on. Repeats belong on
44/// [`pulse_delta`], which leases the view instead of pinning the window.
45pub use gpui::AnimationExt;
46
47mod app;
48pub mod phase;
49
50pub use app::AppExt;
51
52// ---------------------------------------------------------------------------
53// The clock — one leased drive for everything that repeats
54// ---------------------------------------------------------------------------
55
56/// Redraw rate for the pulse/spinner loaders.
57///
58/// 2026-08, M-series laptop: one spinner drawn at 120Hz cost 36% of a core —
59/// the window redraw, with the animation math itself at 0.3%. 30fps is
60/// visually equivalent for these chunky cell waves at a quarter of the draws,
61/// and a window with no spinner mounted schedules nothing at all.
62const PULSE_FPS: f32 = 30.0;
63
64/// How long a view stays on the tick list after its last spinner paint. One
65/// lease outlives a few missed frames; an unmounted spinner stops renewing and
66/// the view drops off, letting the clock park.
67const PULSE_LEASE: Duration = Duration::from_millis(300);
68
69/// Redraw rate for hover fades. [`HOVER_FADE`] is 150ms, so this paints it in
70/// nine steps — the drive it replaces ran at the display's rate, whatever that
71/// was.
72const HOVER_FPS: f32 = 60.0;
73
74/// Floor on how long the clock sleeps between wake-ups, so a lease asking for
75/// an absurd rate cannot turn the loop into a spin.
76const MIN_SLEEP: Duration = Duration::from_millis(1);
77
78/// One view's claim on the clock.
79struct Lease {
80    /// The fastest rate anything on this view has claimed.
81    period: Duration,
82    /// When this view is next owed a redraw.
83    due: Instant,
84    /// A notify is out and the render it provoked has not renewed this lease
85    /// yet. Read by [`Painter::woken`] — never by the schedule, because a
86    /// claim taken from an *event* is renewed by no render at all: a hover
87    /// fade would paint one frame and freeze there.
88    in_flight: bool,
89    /// When the claim lapses if nothing renews it.
90    until: Instant,
91}
92
93#[derive(Default)]
94struct PulseClock {
95    /// Set on first use. Everything here reads the executor's clock rather than
96    /// `Instant::now()` — one time source for scheduling and for phase, and the
97    /// only way a test can advance a second of animation without waiting one.
98    epoch: Option<Instant>,
99    leases: HashMap<EntityId, Lease>,
100    running: bool,
101}
102
103impl PulseClock {
104    /// When the loop should next wake: the earliest thing owed to anyone, or
105    /// the earliest lapse, whichever comes first.
106    ///
107    /// Every lease answers with a real time. A lease that fell back to its
108    /// *lapse* while waiting on a render is what held every drive in the
109    /// library to one frame per lease rather than one per period — a spinner
110    /// asking for 30fps drew about 5.
111    fn next_wake(&self) -> Option<Instant> {
112        self.leases
113            .values()
114            .map(|lease| lease.due.min(lease.until))
115            .min()
116    }
117}
118
119impl Global for PulseClock {}
120
121/// A component's line back to the view that paints it.
122///
123/// Component state that outlives a render — a hover fade, a gesture — has to
124/// name its view, because event-dispatch context cannot resolve one and the
125/// only alternative left is refreshing the whole window. Holding a `Painter`
126/// is what makes the two sanctioned frame requests reachable, and it is the
127/// one surface to review when asking who in the library can ask for a frame.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
129pub struct Painter(EntityId);
130
131impl Painter {
132    /// The view this render belongs to. Take it once, where the state is
133    /// built, and keep it for as long as the state lives.
134    pub fn of<T: 'static>(cx: &Context<T>) -> Self {
135        Self(cx.entity_id())
136    }
137
138    /// Redraw this view once.
139    pub fn notify(self, cx: &mut App) {
140        cx.notify(self.0);
141    }
142
143    /// Claim `fps` redraws a second, lapsing `until` from now unless something
144    /// renews it. One timer serves the whole app: it wakes only when a view is
145    /// owed a frame, notifies that view alone, and parks when the last claim
146    /// lapses.
147    ///
148    /// This is the drive for any repeating animation, yours included. gpui's
149    /// `with_animation(…).repeat()` asks the *window* for a frame at the
150    /// display's rate for as long as it stays mounted, and one such element is
151    /// enough to hold the whole window there.
152    ///
153    /// Renew it from `render` — that is what makes a claim self-cancelling,
154    /// since an element that unmounts stops renewing and drops off. The rate is
155    /// a per-view minimum of everything claiming it, so a 60fps claim never
156    /// drags a 30fps one up with it.
157    pub fn lease(self, fps: f32, until: Duration, cx: &mut App) {
158        lease(self.0, fps, until, cx);
159    }
160
161    /// Whether the clock is what asked for the render running now, rather than
162    /// the app. True only in the render a tick provoked: the clock clears what
163    /// this view is owed when it notifies, and the render's own [`lease`] is
164    /// what puts it back. Read it before renewing.
165    pub fn woken(self, cx: &App) -> bool {
166        cx.try_global::<PulseClock>()
167            .and_then(|clock| clock.leases.get(&self.0))
168            .is_some_and(|lease| lease.in_flight)
169    }
170}
171
172impl From<Painter> for EntityId {
173    fn from(painter: Painter) -> Self {
174        painter.0
175    }
176}
177
178impl From<EntityId> for Painter {
179    fn from(view: EntityId) -> Self {
180        Self(view)
181    }
182}
183
184fn lease(view: EntityId, fps: f32, until: Duration, cx: &mut App) {
185    // Nobody is looking. Refusing the claim is enough to stop the clock: the
186    // ones already held lapse, the loop runs out of work and parks, and the
187    // refresh gpui does on activation brings the renders that claim again.
188    if cx.pause_when_inactive() && cx.active_window().is_none() {
189        return;
190    }
191    let now = cx.background_executor().now();
192    let period = Duration::from_secs_f32(1.0 / fps.clamp(1.0, 240.0));
193    let clock = cx.default_global::<PulseClock>();
194    clock
195        .leases
196        .entry(view)
197        .and_modify(|lease| {
198            lease.period = lease.period.min(period);
199            // The tick already booked the next slot; this render only pulls it
200            // earlier if the claim is faster. Re-dating it from *now* would add
201            // the frame's own cost to every period — 30fps drew 20.
202            lease.due = lease.due.min(now + period);
203            lease.in_flight = false;
204            lease.until = lease.until.max(now + until);
205        })
206        .or_insert(Lease {
207            period,
208            due: now + period,
209            in_flight: false,
210            until: now + until,
211        });
212    if clock.running {
213        return;
214    }
215    clock.running = true;
216    cx.spawn(async move |cx| {
217        loop {
218            let sleep = cx.update(|cx| {
219                let now = cx.background_executor().now();
220                let clock = cx.default_global::<PulseClock>();
221                clock
222                    .next_wake()
223                    .map(|wake| wake.saturating_duration_since(now).max(MIN_SLEEP))
224            });
225            let Some(sleep) = sleep else { break };
226            cx.background_executor().timer(sleep).await;
227            let parked = cx.update(|cx| {
228                let now = cx.background_executor().now();
229                // The clock is the fade store's tick too: it is what advances
230                // the frame counter that evicts fades whose elements went away.
231                tick_hover_fades();
232                let clock = cx.default_global::<PulseClock>();
233                clock.leases.retain(|_, lease| lease.until > now);
234                if clock.leases.is_empty() {
235                    clock.running = false;
236                    return true;
237                }
238                // Owed a frame now. The slot moves on whatever happens next,
239                // so the cadence is the period and not the period plus however
240                // long the frame took.
241                let mut owed = Vec::new();
242                for (view, lease) in clock.leases.iter_mut() {
243                    if lease.due > now {
244                        continue;
245                    }
246                    lease.due += lease.period;
247                    // Frames are costing more than the rate asked for; the next
248                    // slot is now rather than a run of slots already missed.
249                    if lease.due <= now {
250                        lease.due = now + lease.period;
251                    }
252                    lease.in_flight = true;
253                    owed.push(*view);
254                }
255                for view in owed {
256                    cx.notify(view);
257                }
258                false
259            });
260            if parked {
261                break;
262            }
263        }
264    })
265    .detach();
266}
267
268/// Current phase `[0,1)` of a repeating spec, plus a [`lease`] that keeps the
269/// calling view re-rendering at [`PULSE_FPS`] while its spinner stays mounted.
270/// All cells across all views share one epoch, so multi-instance loaders stay
271/// phase-locked. Reduced motion returns a static 0 and schedules nothing.
272pub fn pulse_delta(spec: &MotionSpec, painter: Painter, cx: &mut App) -> f32 {
273    if cx.reduce_motion() {
274        return 0.0;
275    }
276    painter.lease(PULSE_FPS, PULSE_LEASE, cx);
277    let now = cx.background_executor().now();
278    let clock = cx.default_global::<PulseClock>();
279    let epoch = *clock.epoch.get_or_insert(now);
280    let period = spec.total().as_secs_f32();
281    ((now - epoch).as_secs_f32() / period).fract()
282}
283
284// ---------------------------------------------------------------------------
285// Cubic bezier
286// ---------------------------------------------------------------------------
287
288/// A CSS `cubic-bezier(x1, y1, x2, y2)` timing function (endpoints fixed at
289/// (0,0) and (1,1)). Evaluation solves x(t) = input by Newton iteration with a
290/// bisection fallback — the standard UnitBezier approach.
291#[derive(Debug, Clone, Copy, PartialEq)]
292pub struct CubicBezier {
293    pub x1: f32,
294    pub y1: f32,
295    pub x2: f32,
296    pub y2: f32,
297}
298
299impl CubicBezier {
300    pub const fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
301        Self { x1, y1, x2, y2 }
302    }
303
304    fn coefficients(a: f32, b: f32) -> (f32, f32, f32) {
305        let c = 3.0 * a;
306        let bb = 3.0 * (b - a) - c;
307        let aa = 1.0 - c - bb;
308        (aa, bb, c)
309    }
310
311    fn sample_x(&self, t: f32) -> f32 {
312        let (a, b, c) = Self::coefficients(self.x1, self.x2);
313        ((a * t + b) * t + c) * t
314    }
315
316    fn sample_y(&self, t: f32) -> f32 {
317        let (a, b, c) = Self::coefficients(self.y1, self.y2);
318        ((a * t + b) * t + c) * t
319    }
320
321    fn sample_x_derivative(&self, t: f32) -> f32 {
322        let (a, b, c) = Self::coefficients(self.x1, self.x2);
323        (3.0 * a * t + 2.0 * b) * t + c
324    }
325
326    /// Curve parameter `t` for a given progress `x` (both 0..1).
327    fn solve_t_for_x(&self, x: f32) -> f32 {
328        // Newton–Raphson.
329        let mut t = x;
330        for _ in 0..8 {
331            let err = self.sample_x(t) - x;
332            if err.abs() < 1e-6 {
333                return t;
334            }
335            let d = self.sample_x_derivative(t);
336            if d.abs() < 1e-6 {
337                break;
338            }
339            t -= err / d;
340        }
341        // Bisection fallback (x(t) is monotonic for valid CSS beziers).
342        let (mut lo, mut hi) = (0.0_f32, 1.0_f32);
343        for _ in 0..32 {
344            let mid = (lo + hi) / 2.0;
345            if self.sample_x(mid) < x {
346                lo = mid
347            } else {
348                hi = mid
349            }
350        }
351        (lo + hi) / 2.0
352    }
353
354    /// Eased output for input progress `x ∈ [0,1]` (clamped).
355    pub fn eval(&self, x: f32) -> f32 {
356        if x <= 0.0 {
357            return 0.0;
358        }
359        if x >= 1.0 {
360            return 1.0;
361        }
362        // f32 rounding can push sample_y a hair past 1.0 (observed 1.000000119
363        // near the end of menu animations); gpui's animation element asserts
364        // `delta ∈ [0,1]` and aborts, so clamp the output hard.
365        self.sample_y(self.solve_t_for_x(x)).clamp(0.0, 1.0)
366    }
367
368    /// This curve as a gpui easing closure.
369    pub fn easing(self) -> impl Fn(f32) -> f32 + 'static {
370        move |x| self.eval(x)
371    }
372}
373
374/// The signature entrance curve — CSS `cubic-bezier(0.16, 1, 0.3, 1)`.
375pub const EASE_OUT_EXPO: CubicBezier = CubicBezier::new(0.16, 1.0, 0.3, 1.0);
376/// CSS `ease-out` — width/height transitions.
377pub const EASE_OUT: CubicBezier = CubicBezier::new(0.0, 0.0, 0.58, 1.0);
378/// CSS `ease` — quick fades, menu/dialog pops.
379pub const EASE: CubicBezier = CubicBezier::new(0.25, 0.1, 0.25, 1.0);
380/// Sidebar resort glide — CSS `cubic-bezier(0.22, 1, 0.36, 1)` (used from M3b).
381pub const EASE_RESORT: CubicBezier = CubicBezier::new(0.22, 1.0, 0.36, 1.0);
382/// CSS `ease-in-out` — the transcript scroll glide (browser smooth-scroll
383/// shape: gentle start, cruise, gentle landing).
384pub const EASE_IN_OUT: CubicBezier = CubicBezier::new(0.42, 0.0, 0.58, 1.0);
385
386// ---------------------------------------------------------------------------
387// Motion specs (the catalog)
388// ---------------------------------------------------------------------------
389
390/// One catalog entry: duration + optional delay + curve. The delay is folded into
391/// the gpui animation timeline (gpui `Animation` has no native delay): the
392/// animation runs for `delay + duration` and [`progress`](Self::progress) holds 0
393/// until the delay has elapsed.
394#[derive(Debug, Clone, Copy, PartialEq)]
395pub struct MotionSpec {
396    pub duration_ms: u64,
397    pub delay_ms: u64,
398    pub curve: CubicBezier,
399}
400
401impl MotionSpec {
402    pub const fn new(duration_ms: u64, curve: CubicBezier) -> Self {
403        Self {
404            duration_ms,
405            delay_ms: 0,
406            curve,
407        }
408    }
409
410    pub const fn with_delay(mut self, delay_ms: u64) -> Self {
411        self.delay_ms = delay_ms;
412        self
413    }
414
415    /// Wall-clock span of the whole timeline (delay + duration).
416    pub fn total(&self) -> Duration {
417        Duration::from_millis(self.delay_ms + self.duration_ms)
418    }
419
420    /// Eased progress (0..1) for a raw timeline delta (0..1 across [`total`](Self::total)).
421    /// Pure — unit-testable without a window.
422    pub fn progress(&self, raw_delta: f32) -> f32 {
423        let total = (self.delay_ms + self.duration_ms) as f32;
424        if total <= 0.0 || self.duration_ms == 0 {
425            return 1.0;
426        }
427        let t =
428            (raw_delta.clamp(0.0, 1.0) * total - self.delay_ms as f32) / self.duration_ms as f32;
429        self.curve.eval(t.clamp(0.0, 1.0))
430    }
431
432    /// A oneshot gpui [`Animation`] for this spec (delay folded in).
433    /// Wall-clock span honors [`speed_scale`] (measurement knob).
434    pub fn animation(&self) -> Animation {
435        let spec = *self;
436        Animation::new(spec.total().mul_f32(speed_scale())).with_easing(move |d| spec.progress(d))
437    }
438}
439
440/// Entrances: 0.5s expo-out fade + 4px rise.
441pub const FADE_IN: MotionSpec = MotionSpec::new(500, EASE_OUT_EXPO);
442/// Quick fade: 0.15s.
443pub const FADE_QUICK: MotionSpec = MotionSpec::new(150, EASE);
444/// Popover-in: 0.14s (scale 0.96 approximated, translateY −2).
445pub const MENU_IN: MotionSpec = MotionSpec::new(140, EASE);
446/// Popover-out: 0.1s — quicker than the entrance (exits should get out of the
447/// way; matches the Radix convention of a shorter close than open).
448pub const MENU_OUT: MotionSpec = MotionSpec::new(100, EASE);
449/// Dialog-in: 0.18s (scale 0.96→1 approximated).
450pub const DIALOG_IN: MotionSpec = MotionSpec::new(180, EASE);
451/// Boot splash exit: 0.5s fade + 6px lift after a 0.15s hold.
452pub const SPLASH_OUT: MotionSpec = MotionSpec::new(500, EASE).with_delay(150);
453/// Sidebar / pane width+height transitions: 200ms ease-out.
454pub const RESIZE: MotionSpec = MotionSpec::new(200, EASE_OUT);
455/// Terminal tab drag-reorder sliding transforms: 150ms (§1.10).
456pub const TAB_SLIDE: MotionSpec = MotionSpec::new(150, EASE_OUT);
457/// Diff-pane per-file collapse: 180ms height (§1.11).
458pub const COLLAPSE: MotionSpec = MotionSpec::new(180, EASE_OUT);
459/// Canvas nodes gliding to where a layout put them — [`RESIZE`]'s 200ms
460/// ease-out, for a move the reader caused rather than one they are dragging.
461pub const LAYOUT: MotionSpec = MotionSpec::new(200, EASE_OUT);
462/// Diff-pane chevron rotate: 200ms (§1.11; approximated as a crossfade — gpui
463/// divs have no rotation transform at the pinned rev, same caveat as scale).
464pub const CHEVRON: MotionSpec = MotionSpec::new(200, EASE);
465/// Rail-tick / scroll-to-row glide: 500ms ease-in-out over the whole distance
466/// (Electron parity — the original rail rode the browser's native smooth
467/// scroll, a fixed-duration gentle ease, never percent-of-remaining).
468pub const SCROLL_GLIDE: MotionSpec = MotionSpec::new(500, EASE_IN_OUT);
469/// Tailwind's default transition curve — CSS `cubic-bezier(0.4, 0, 0.2, 1)`
470/// (`transition-colors` et al. carry it unless overridden).
471pub const EASE_TAILWIND: CubicBezier = CubicBezier::new(0.4, 0.0, 0.2, 1.0);
472/// CSS `transition-colors` default: 150ms over [`EASE_TAILWIND`] — the temporal
473/// blend every interactive hover wash rides in the original.
474pub const HOVER_FADE: MotionSpec = MotionSpec::new(150, EASE_TAILWIND);
475/// Pulse loader period: 2.4s.
476pub const PULSE: MotionSpec = MotionSpec::new(2400, EASE);
477/// Gradient matrix spinner wave period: 750ms.
478pub const GRADIENT_SPIN: MotionSpec = MotionSpec::new(750, EASE);
479/// Orb cluster breath: 2s, and `EASE_IN_OUT` because a breath has no edges —
480/// the two spinners tick, this one swells.
481pub const ORB: MotionSpec = MotionSpec::new(phase::ORB_MS, EASE_IN_OUT);
482
483// ---------------------------------------------------------------------------
484// Element helpers (paint-layer entrances/exits)
485// ---------------------------------------------------------------------------
486
487/// Standard entrance: opacity 0→1 + translateY 4→0 over [`FADE_IN`].
488pub fn fade_in<E>(id: impl Into<ElementId>, element: E) -> AnimationElement<E>
489where
490    E: Styled + IntoElement + 'static,
491{
492    element.with_animation(id, FADE_IN.animation(), |el, t| {
493        el.relative().opacity(t).top(px(4.0 * (1.0 - t)))
494    })
495}
496
497/// Quick opacity-only fade over [`FADE_QUICK`].
498pub fn fade_quick<E>(id: impl Into<ElementId>, element: E) -> AnimationElement<E>
499where
500    E: Styled + IntoElement + 'static,
501{
502    element.with_animation(id, FADE_QUICK.animation(), |el, t| el.opacity(t))
503}
504
505/// Popover entrance: fade + translateY −2→0 over [`MENU_IN`].
506/// (the original also scales 0.96→1; divs have no scale transform in gpui — approximated.)
507pub fn menu_in<E>(id: impl Into<ElementId>, element: E) -> AnimationElement<E>
508where
509    E: Styled + IntoElement + 'static,
510{
511    element.with_animation(id, MENU_IN.animation(), |el, t| {
512        el.relative()
513            .opacity(0.3 + 0.7 * t)
514            .top(px(-2.0 * (1.0 - t)))
515    })
516}
517
518/// Popover exit: the reverse of [`menu_in`] — fade to 0 + translateY 0→−2 over
519/// [`MENU_OUT`]. Unlike the entrances, the eased progress `t` comes from the
520/// caller (computed off `bezel::popover::Popup`'s closing instant at render
521/// time): `with_animation`'s element-id-keyed clock replays from 0 on remount
522/// (the hover-blend comment's warning), and a replay mid-exit is a full-opacity
523/// flash. The wall-clock progress is monotonic by construction; the animation
524/// wrapper here only pumps frames for the exit's span, its own delta unused.
525pub fn menu_out<E>(id: impl Into<ElementId>, t: f32, element: E) -> AnimationElement<E>
526where
527    E: Styled + IntoElement + 'static,
528{
529    element.with_animation(id, MENU_OUT.animation(), move |el, _| {
530        el.relative().opacity(1.0 - t).top(px(-2.0 * t))
531    })
532}
533
534/// Dialog entrance over [`DIALOG_IN`] (scale approximated with fade + 2px rise).
535pub fn dialog_in<E>(id: impl Into<ElementId>, element: E) -> AnimationElement<E>
536where
537    E: Styled + IntoElement + 'static,
538{
539    element.with_animation(id, DIALOG_IN.animation(), |el, t| {
540        el.relative().opacity(t).top(px(2.0 * (1.0 - t)))
541    })
542}
543
544/// Boot-splash exit: hold 150ms, then fade out + lift 6px over 500ms.
545pub fn splash_out<E>(id: impl Into<ElementId>, element: E) -> AnimationElement<E>
546where
547    E: Styled + IntoElement + 'static,
548{
549    element.with_animation(id, SPLASH_OUT.animation(), |el, t| {
550        el.opacity(1.0 - t).top(px(-6.0 * t))
551    })
552}
553
554// ---------------------------------------------------------------------------
555// Loader math (pure; rendered by bezel::loaders)
556// ---------------------------------------------------------------------------
557
558// The loader constants and math live in `crate::phase` (pure phase
559// functions); this crate animates them with gpui.
560pub use crate::phase::{
561    ORB_BLOOM_RINGS, ORB_RING_DOT, ORB_RING_DOTS, ORB_RING_RADIUS, ORB_SEATS, ORBS,
562    PULSE_MIN_OPACITY, PULSE_MIN_SCALE, PULSE_STAGGER, gspin_opacity, orb_bloom_opacity,
563    orb_bloom_radius, orb_converge_radius, orb_drift, orb_glow, orb_opacity, orb_ring_seat,
564    orb_size, pulse_opacity, pulse_scale, pulse_wave, staggered_phase,
565};
566
567/// Gradient-matrix spinner wave: intensity (0..1) of cell `wave_index` out of
568/// `wave_count` diagonals, at raw delta `raw_delta` of the 750ms period. The wave
569/// front travels across diagonals once per period.
570pub fn matrix_wave(raw_delta: f32, wave_index: usize, wave_count: usize) -> f32 {
571    let count = wave_count.max(1) as f32;
572    pulse_wave(staggered_phase(raw_delta, wave_index, 1.0 / count))
573}
574
575/// Linear interpolation (layout tweens).
576pub fn lerp(from: f32, to: f32, t: f32) -> f32 {
577    from + (to - from) * t
578}
579
580// ---------------------------------------------------------------------------
581// Hover color fades (CSS `transition-colors` parity)
582// ---------------------------------------------------------------------------
583//
584// gpui `.hover()` styles snap by construction — the style applies the frame
585// the pointer enters. The original CSS puts Tailwind `transition-colors`
586// (150ms, cubic-bezier(0.4, 0, 0.2, 1)) on every interactive wash, so hover
587// states FADE. This is the manual-drive tween for that (the shell `WidthTween`
588// pattern — never `with_animation`, whose element-id-keyed clock replays on
589// remount): a per-element-key hover progress, advanced from wall time on each
590// evaluation, with the render tail requesting frames while any fade is
591// mid-flight.
592//
593// The store is a main-thread `thread_local` rather than a gpui Global so the
594// many free-function element builders (window-control buttons, popover menu
595// rows, markdown code blocks) can blend colors without threading `cx` through
596// every signature. All access happens on the UI thread (element builders,
597// mouse listeners, the render tail).
598//
599// Staleness: an element that unmounts mid-hover never gets its leave event, so
600// entries are stamped with a frame counter on every read and pruned by the
601// clock's tick when a full tick passes without a read — a reopened menu never
602// inherits a dead entry's wash.
603
604/// One element's hover fade: progress runs `origin → target` over
605/// [`HOVER_FADE`], re-anchored at `origin` whenever the pointer flips
606/// direction mid-flight so the blend is continuous.
607#[derive(Debug, Clone, Copy)]
608pub struct FadeEntry {
609    origin: f32,
610    target: f32,
611    started: Instant,
612    /// Frame counter at the last read (liveness stamp — see module notes).
613    seen: u64,
614}
615
616impl FadeEntry {
617    fn value(&self, now: Instant, duration: Duration) -> f32 {
618        let elapsed = now.saturating_duration_since(self.started);
619        if duration.is_zero() || elapsed >= duration {
620            return self.target;
621        }
622        let raw = elapsed.as_secs_f32() / duration.as_secs_f32();
623        lerp(self.origin, self.target, HOVER_FADE.curve.eval(raw))
624    }
625
626    fn settled(&self, now: Instant, duration: Duration) -> bool {
627        self.origin == self.target || now.saturating_duration_since(self.started) >= duration
628    }
629}
630
631/// Which fade: the view that paints it, and which element inside that view.
632///
633/// The view is half the identity because the store is one map for the whole
634/// app. Keyed on the string alone, two views using `"row-3"` trade each other's
635/// wash — which is why the ghost button used to ask callers for a key unique
636/// across the entire program.
637#[derive(Debug, Clone, PartialEq, Eq, Hash)]
638pub struct Fade {
639    pub painter: Painter,
640    pub key: SharedString,
641}
642
643impl Fade {
644    pub fn new(painter: Painter, key: impl Into<SharedString>) -> Self {
645        Self {
646            painter,
647            key: key.into(),
648        }
649    }
650}
651
652/// Per-fade progress store. Pure core (explicit `now`) — unit-testable; the
653/// thread-local wrappers below feed it the clock.
654#[derive(Default)]
655pub struct HoverFades {
656    pub entries: HashMap<Fade, FadeEntry>,
657    frame: u64,
658}
659
660impl HoverFades {
661    pub fn duration() -> Duration {
662        HOVER_FADE.total().mul_f32(speed_scale())
663    }
664
665    /// Pointer entered (`hovered`) or left the element behind `fade`. Reduced
666    /// motion snaps straight to the endpoint.
667    pub fn set_at(&mut self, fade: &Fade, hovered: bool, reduced: bool, now: Instant) {
668        let target = if hovered { 1.0 } else { 0.0 };
669        let duration = Self::duration();
670        let current = self
671            .entries
672            .get(fade)
673            .map(|e| e.value(now, duration))
674            .unwrap_or(0.0);
675        if target == 0.0 && !self.entries.contains_key(fade) {
676            return; // never-hovered element reporting a leave — nothing to do
677        }
678        let origin = if reduced { target } else { current };
679        let seen = self.frame;
680        self.entries.insert(
681            fade.clone(),
682            FadeEntry {
683                origin,
684                target,
685                started: now,
686                seen,
687            },
688        );
689    }
690
691    /// Hover progress (0..1) for `fade` at `now`; stamps liveness.
692    pub fn value_at(&mut self, fade: &Fade, now: Instant) -> f32 {
693        let frame = self.frame;
694        match self.entries.get_mut(fade) {
695            Some(entry) => {
696                entry.seen = frame;
697                entry.value(now, Self::duration())
698            }
699            None => 0.0,
700        }
701    }
702
703    /// Once-per-frame bookkeeping: advance the frame counter, prune entries
704    /// that settled back to rest or went a full frame unread (unmounted), and
705    /// report whether any fade is still mid-flight (→ keep frames coming).
706    pub fn tick_at(&mut self, now: Instant) -> bool {
707        self.frame += 1;
708        let frame = self.frame;
709        let duration = Self::duration();
710        let mut active = false;
711        self.entries.retain(|_, entry| {
712            // Unread through the whole previous frame: the element unmounted
713            // (its leave event will never come) — drop the entry.
714            if entry.seen + 1 < frame {
715                return false;
716            }
717            let settled = entry.settled(now, duration);
718            if !settled {
719                active = true;
720            }
721            // Settled at rest — steady state, indistinguishable from absent.
722            !(settled && entry.target == 0.0)
723        });
724        active
725    }
726}
727
728thread_local! {
729    static HOVER_FADES: RefCell<HoverFades> = RefCell::new(HoverFades::default());
730}
731
732/// Hover progress (0..1) for `fade` this frame.
733pub fn hover_t(fade: &Fade) -> f32 {
734    HOVER_FADES.with(|fades| fades.borrow_mut().value_at(fade, Instant::now()))
735}
736
737/// Record a hover flip for `fade` (reduced motion snaps). Prefer
738/// [`hover_listener`], which also asks the clock for the frames to paint it.
739pub fn set_hover(fade: &Fade, hovered: bool, reduced: bool) {
740    HOVER_FADES.with(|fades| {
741        fades
742            .borrow_mut()
743            .set_at(fade, hovered, reduced, Instant::now())
744    });
745}
746
747/// An `.on_hover` listener driving the fade — pair with [`hover_t`] or
748/// [`hover_blend`] reads of the same [`Fade`] in the same element.
749///
750/// The view comes in on the `Fade` rather than being resolved here: this runs in
751/// event-dispatch context, where `Window::current_view()` asserts.
752pub fn hover_listener(fade: Fade) -> impl Fn(&bool, &mut Window, &mut App) + 'static {
753    move |hovered, _window, cx| {
754        set_hover(&fade, *hovered, cx.reduced_motion());
755        fade.painter.lease(HOVER_FPS, HoverFades::duration(), cx);
756    }
757}
758
759/// Once-per-tick bookkeeping for the fade store, driven by the clock.
760fn tick_hover_fades() {
761    HOVER_FADES.with(|fades| {
762        fades.borrow_mut().tick_at(Instant::now());
763    });
764}
765
766/// Blend two colors by `t` the way the browser transitions them: component
767/// interpolation in sRGB with premultiplied alpha — a wash fading in from
768/// transparent brightens without passing through grey.
769pub fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla {
770    let t = t.clamp(0.0, 1.0);
771    if t <= 0.0 {
772        return from;
773    }
774    if t >= 1.0 {
775        return to;
776    }
777    let (f, g) = (Rgba::from(from), Rgba::from(to));
778    let a = lerp(f.a, g.a, t);
779    if a <= f32::EPSILON {
780        // Both endpoints (effectively) transparent — carry the target's hue.
781        return Hsla::from(Rgba { a: 0.0, ..g });
782    }
783    Hsla::from(Rgba {
784        r: lerp(f.r * f.a, g.r * g.a, t) / a,
785        g: lerp(f.g * f.a, g.g * g.a, t) / a,
786        b: lerp(f.b * f.a, g.b * g.a, t) / a,
787        a,
788    })
789}
790
791/// The standard hover blend: rest → hover color at this fade's progress.
792pub fn hover_blend(fade: &Fade, rest: Hsla, hover: Hsla) -> Hsla {
793    mix(rest, hover, hover_t(fade))
794}
795
796// ---------------------------------------------------------------------------
797// Speed and reduced motion
798// ---------------------------------------------------------------------------
799
800/// Process-wide motion speed, as f32 bits: every catalog timeline is multiplied
801/// by it.
802///
803/// An atomic mirror rather than a gpui global, for exactly the reason
804/// `theme::current_appearance` is one: the timelines are read from free
805/// functions deep inside element builders — [`HoverFades::duration`], the
806/// popover exit clock — that have no `cx` in scope. Speed is genuinely
807/// process-wide, one setting for every window, so a single mirror is sound.
808static SPEED: AtomicU32 = AtomicU32::new(1.0f32.to_bits());
809
810/// How far every timeline in the catalog is stretched. `1.0` is the designed
811/// speed.
812pub fn speed_scale() -> f32 {
813    f32::from_bits(SPEED.load(Ordering::Relaxed))
814}
815
816/// Stretch every catalog timeline by `scale` — `10.0` slows the 200ms pane
817/// tweens to 2s, so a screenshot burst can sample the geometry frame by frame.
818///
819/// Configuration in code, like the rest of bezel: an app that wants this on a
820/// setting, or hanging off its own theme, calls this from wherever that lives.
821/// It used to read a `BEZEL_MOTION_SCALE` environment variable, which meant the
822/// one knob in the library that no app could reach.
823///
824/// Clamped to `0.01..=100.0`; a non-finite `scale` resets to `1.0` rather than
825/// poisoning every duration with a NaN.
826pub fn set_speed(scale: f32) {
827    let scale = if scale.is_finite() {
828        scale.clamp(0.01, 100.0)
829    } else {
830        1.0
831    };
832    SPEED.store(scale.to_bits(), Ordering::Relaxed);
833}
834
835/// [`SPEED`] is process-wide, so a test that moves it must hold this lock and
836/// restore `1.0` before letting go — every fade and exit timing asserted
837/// anywhere is measured in it. The same arrangement as
838/// `theme::lock_appearance`, and public for the same reason: such tests
839/// exist in other crates too. Not part of the API.
840#[doc(hidden)]
841pub fn lock_speed() -> std::sync::MutexGuard<'static, ()> {
842    static SPEED_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
843    SPEED_LOCK.lock().unwrap_or_else(|e| e.into_inner())
844}