Skip to main content

arc_motion/
layout.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Shared layout (`layoutId`) & FLIP bounds/corner-radius handoff registry.
3
4use std::collections::HashMap;
5
6use arc_tokens::{ArcMotionTokens, SpringSpec};
7use gpui_kit::{
8    App, Bounds, Corners, ElementId, Global, Pixels, Point, SharedString, Window, bounds, point,
9    px, size,
10};
11
12use crate::{clock::motion_now, spring::SpringSolver};
13
14/// Measured layout snapshot of an element (position, size, corner radii).
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub struct LayoutSnapshot {
17    pub bounds: Bounds<Pixels>,
18    pub corner_radii: Corners<Pixels>,
19}
20
21impl LayoutSnapshot {
22    pub fn new(bounds: Bounds<Pixels>, corner_radii: Corners<Pixels>) -> Self {
23        Self {
24            bounds,
25            corner_radii,
26        }
27    }
28
29    pub fn uniform_radius(bounds: Bounds<Pixels>, radius: Pixels) -> Self {
30        Self {
31            bounds,
32            corner_radii: Corners::all(radius),
33        }
34    }
35}
36
37/// Active target reported by a `layoutId` participant.
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct LayoutTarget {
40    pub bounds: Bounds<Pixels>,
41    pub corner_radii: Corners<Pixels>,
42}
43
44/// Interpolated FLIP result for the current paint frame.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct LayoutFlipSample {
47    pub bounds: Bounds<Pixels>,
48    pub corner_radii: Corners<Pixels>,
49    pub settled: bool,
50}
51
52#[derive(Clone, Debug)]
53struct ActiveFlip {
54    from: LayoutSnapshot,
55    to: LayoutSnapshot,
56    started_at_secs: f64,
57    spec: SpringSpec,
58}
59
60impl ActiveFlip {
61    fn sample(&self, now_secs: f64) -> LayoutFlipSample {
62        let elapsed = (now_secs - self.started_at_secs).max(0.0);
63        let x = SpringSolver::new(
64            self.spec,
65            f64::from(f32::from(self.from.bounds.origin.x)),
66            f64::from(f32::from(self.to.bounds.origin.x)),
67            0.0,
68        )
69        .sample(elapsed);
70        let y = SpringSolver::new(
71            self.spec,
72            f64::from(f32::from(self.from.bounds.origin.y)),
73            f64::from(f32::from(self.to.bounds.origin.y)),
74            0.0,
75        )
76        .sample(elapsed);
77        let w = SpringSolver::new(
78            self.spec,
79            f64::from(f32::from(self.from.bounds.size.width)),
80            f64::from(f32::from(self.to.bounds.size.width)),
81            0.0,
82        )
83        .sample(elapsed);
84        let h = SpringSolver::new(
85            self.spec,
86            f64::from(f32::from(self.from.bounds.size.height)),
87            f64::from(f32::from(self.to.bounds.size.height)),
88            0.0,
89        )
90        .sample(elapsed);
91
92        let r_tl = SpringSolver::new(
93            self.spec,
94            f64::from(f32::from(self.from.corner_radii.top_left)),
95            f64::from(f32::from(self.to.corner_radii.top_left)),
96            0.0,
97        )
98        .sample(elapsed);
99        let r_tr = SpringSolver::new(
100            self.spec,
101            f64::from(f32::from(self.from.corner_radii.top_right)),
102            f64::from(f32::from(self.to.corner_radii.top_right)),
103            0.0,
104        )
105        .sample(elapsed);
106        let r_br = SpringSolver::new(
107            self.spec,
108            f64::from(f32::from(self.from.corner_radii.bottom_right)),
109            f64::from(f32::from(self.to.corner_radii.bottom_right)),
110            0.0,
111        )
112        .sample(elapsed);
113        let r_bl = SpringSolver::new(
114            self.spec,
115            f64::from(f32::from(self.from.corner_radii.bottom_left)),
116            f64::from(f32::from(self.to.corner_radii.bottom_left)),
117            0.0,
118        )
119        .sample(elapsed);
120
121        let settled = x.settled && y.settled && w.settled && h.settled;
122        LayoutFlipSample {
123            bounds: bounds(
124                point(px(x.value), px(y.value)),
125                size(px(w.value.max(0.0)), px(h.value.max(0.0))),
126            ),
127            corner_radii: Corners {
128                top_left: px(r_tl.value.max(0.0)),
129                top_right: px(r_tr.value.max(0.0)),
130                bottom_right: px(r_br.value.max(0.0)),
131                bottom_left: px(r_bl.value.max(0.0)),
132            },
133            settled,
134        }
135    }
136}
137
138/// Scoped key isolating `layoutId` groups (matching Motion's `<LayoutGroup id={scope}>`).
139#[derive(Clone, Debug, Eq, Hash, PartialEq)]
140struct LayoutKey {
141    scope: SharedString,
142    layout_id: SharedString,
143}
144
145#[derive(Clone, Debug)]
146struct Entry {
147    /// Last known rendered snapshot (continuously updated so mid-flight handoff starts from current).
148    last_rendered: LayoutSnapshot,
149    /// Active target being animated toward.
150    active_target: LayoutSnapshot,
151    /// Optional running FLIP spring.
152    flip: Option<ActiveFlip>,
153}
154
155/// Window/App-level registry storing `layoutId` bounds & corner radii for shared-layout handoffs.
156#[derive(Default)]
157pub struct LayoutRegistry {
158    entries: HashMap<LayoutKey, Entry>,
159}
160
161impl Global for LayoutRegistry {}
162
163impl LayoutRegistry {
164    /// Registers or updates the target bounds for `(scope, layout_id)` and returns the
165    /// interpolated FLIP bounds for the current frame.
166    pub fn sample(
167        &mut self,
168        scope: impl Into<SharedString>,
169        layout_id: impl Into<SharedString>,
170        target: LayoutSnapshot,
171        spec: SpringSpec,
172        now_secs: f64,
173        reduced_motion: bool,
174    ) -> LayoutFlipSample {
175        let key = LayoutKey {
176            scope: scope.into(),
177            layout_id: layout_id.into(),
178        };
179
180        let Some(entry) = self.entries.get_mut(&key) else {
181            self.entries.insert(
182                key,
183                Entry {
184                    last_rendered: target,
185                    active_target: target,
186                    flip: None,
187                },
188            );
189            return LayoutFlipSample {
190                bounds: target.bounds,
191                corner_radii: target.corner_radii,
192                settled: true,
193            };
194        };
195
196        if reduced_motion {
197            entry.last_rendered = target;
198            entry.active_target = target;
199            entry.flip = None;
200            return LayoutFlipSample {
201                bounds: target.bounds,
202                corner_radii: target.corner_radii,
203                settled: true,
204            };
205        }
206
207        if !snapshots_close(&entry.active_target, &target) {
208            let from = entry.last_rendered;
209            entry.active_target = target;
210            entry.flip = Some(ActiveFlip {
211                from,
212                to: target,
213                started_at_secs: now_secs,
214                spec,
215            });
216        }
217
218        if let Some(flip) = &entry.flip {
219            let sample = flip.sample(now_secs);
220            entry.last_rendered = LayoutSnapshot::new(sample.bounds, sample.corner_radii);
221            if sample.settled {
222                entry.flip = None;
223            }
224            sample
225        } else {
226            entry.last_rendered = target;
227            LayoutFlipSample {
228                bounds: target.bounds,
229                corner_radii: target.corner_radii,
230                settled: true,
231            }
232        }
233    }
234
235    pub fn remove(&mut self, scope: &str, layout_id: &str) {
236        self.entries.remove(&LayoutKey {
237            scope: SharedString::from(scope.to_owned()),
238            layout_id: SharedString::from(layout_id.to_owned()),
239        });
240    }
241}
242
243fn snapshots_close(a: &LayoutSnapshot, b: &LayoutSnapshot) -> bool {
244    let eps = 0.25_f32;
245    let dx = (f32::from(a.bounds.origin.x) - f32::from(b.bounds.origin.x)).abs();
246    let dy = (f32::from(a.bounds.origin.y) - f32::from(b.bounds.origin.y)).abs();
247    let dw = (f32::from(a.bounds.size.width) - f32::from(b.bounds.size.width)).abs();
248    let dh = (f32::from(a.bounds.size.height) - f32::from(b.bounds.size.height)).abs();
249    let dr = (f32::from(a.corner_radii.top_left) - f32::from(b.corner_radii.top_left)).abs();
250    dx < eps && dy < eps && dw < eps && dh < eps && dr < eps
251}
252
253/// Convenience helper for GPUI prepaint/paint phases: updates the global `LayoutRegistry`
254/// and schedules another animation frame while the FLIP spring is moving.
255pub fn sample_shared_layout(
256    scope: impl Into<SharedString>,
257    layout_id: impl Into<SharedString>,
258    target: LayoutSnapshot,
259    spec: Option<SpringSpec>,
260    window: &mut Window,
261    cx: &mut App,
262) -> LayoutFlipSample {
263    let now = motion_now(cx);
264    let reduced = cx.reduce_motion();
265    let spec = spec.unwrap_or(ArcMotionTokens::DEFAULT.spring.morph);
266    if !cx.has_global::<LayoutRegistry>() {
267        cx.set_global(LayoutRegistry::default());
268    }
269    let sample = cx
270        .global_mut::<LayoutRegistry>()
271        .sample(scope, layout_id, target, spec, now, reduced);
272    if !sample.settled {
273        window.request_animation_frame();
274    }
275    sample
276}
277
278/// Helper computing the translation delta from a target bounds to the current FLIP bounds.
279pub fn flip_offset(current: Bounds<Pixels>, target: Bounds<Pixels>) -> Point<Pixels> {
280    point(
281        current.origin.x - target.origin.x,
282        current.origin.y - target.origin.y,
283    )
284}
285
286/// Helper converting an `ElementId` into a stable layout scope string.
287pub fn layout_scope_key(id: &ElementId) -> SharedString {
288    SharedString::from(format!("{id:?}"))
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn shared_layout_handoff_interpolates_position_size_and_radius() {
297        let mut reg = LayoutRegistry::default();
298        let spec = ArcMotionTokens::DEFAULT.spring.morph;
299
300        let tab_a = LayoutSnapshot::uniform_radius(
301            bounds(point(px(0.0), px(0.0)), size(px(80.0), px(36.0))),
302            px(15.0),
303        );
304        let tab_b = LayoutSnapshot::uniform_radius(
305            bounds(point(px(90.0), px(0.0)), size(px(120.0), px(36.0))),
306            px(18.0),
307        );
308
309        let initial = reg.sample("tabs-1", "selection", tab_a, spec, 0.0, false);
310        assert!(initial.settled);
311        assert_eq!(initial.bounds, tab_a.bounds);
312
313        // Switch active tab to tab_b at t = 0.0
314        let start = reg.sample("tabs-1", "selection", tab_b, spec, 0.0, false);
315        assert!(!start.settled);
316        assert!((f32::from(start.bounds.origin.x) - 0.0).abs() < 1.0);
317
318        // Mid-flight at t = 0.12s: smoothly between tab_a and tab_b, never overshooting (bounce=0)
319        let mid = reg.sample("tabs-1", "selection", tab_b, spec, 0.12, false);
320        let mid_x = f32::from(mid.bounds.origin.x);
321        let mid_w = f32::from(mid.bounds.size.width);
322        let mid_r = f32::from(mid.corner_radii.top_left);
323        assert!(mid_x > 10.0 && mid_x < 90.0, "mid_x={mid_x}");
324        assert!(mid_w > 85.0 && mid_w < 120.0, "mid_w={mid_w}");
325        assert!(mid_r > 15.0 && mid_r < 18.0, "mid_r={mid_r}");
326
327        // Settled at t = 1.0s
328        let end = reg.sample("tabs-1", "selection", tab_b, spec, 1.0, false);
329        assert!(end.settled);
330        assert_eq!(end.bounds, tab_b.bounds);
331        assert_eq!(end.corner_radii, tab_b.corner_radii);
332    }
333
334    #[test]
335    fn reduced_motion_snaps_shared_layout_immediately() {
336        let mut reg = LayoutRegistry::default();
337        let spec = ArcMotionTokens::DEFAULT.spring.morph;
338        let a = LayoutSnapshot::uniform_radius(
339            bounds(point(px(0.0), px(0.0)), size(px(80.0), px(36.0))),
340            px(15.0),
341        );
342        let b = LayoutSnapshot::uniform_radius(
343            bounds(point(px(160.0), px(0.0)), size(px(100.0), px(36.0))),
344            px(15.0),
345        );
346        reg.sample("tabs-2", "selection", a, spec, 0.0, true);
347        let snapped = reg.sample("tabs-2", "selection", b, spec, 0.01, true);
348        assert!(snapped.settled);
349        assert_eq!(snapped.bounds, b.bounds);
350    }
351}