Skip to main content

gpui_material_components/navigation/multi_pane/
state.rs

1use std::{ops::Index, time::Duration};
2
3use gpui::{Bounds, Context, ElementId, Pixels, point, px, size};
4use web_time::Instant;
5
6use super::{PaneExpansionAnchor, PaneOverlayAlignment};
7
8/// Roles in a Material three-pane scaffold.
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10pub enum PaneRole {
11    #[default]
12    Primary,
13    Secondary,
14    Tertiary,
15}
16
17impl PaneRole {
18    pub(super) const ALL: [Self; 3] = [Self::Primary, Self::Secondary, Self::Tertiary];
19
20    pub(super) fn index(self) -> usize {
21        match self {
22            Self::Primary => 0,
23            Self::Secondary => 1,
24            Self::Tertiary => 2,
25        }
26    }
27}
28
29/// The strategy used when resolving a pane from navigation and the directive.
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum PaneAdaptStrategy {
32    #[default]
33    Hide,
34    Reflow(PaneRole),
35    Levitate(PaneOverlayAlignment),
36}
37
38/// A pane's realized presentation.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum PanePlacement {
41    #[default]
42    Hidden,
43    Expanded,
44    Reflow(PaneRole),
45    Levitate(PaneOverlayAlignment),
46}
47
48/// Presentation of the three roles, independent of their navigation content keys.
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub struct PaneLayoutValue([PanePlacement; 3]);
51
52impl PaneLayoutValue {
53    pub fn new(primary: PanePlacement, secondary: PanePlacement, tertiary: PanePlacement) -> Self {
54        Self([primary, secondary, tertiary])
55    }
56
57    pub fn placement(self, role: PaneRole) -> PanePlacement {
58        self[role]
59    }
60
61    fn set(&mut self, role: PaneRole, placement: PanePlacement) {
62        self.0[role.index()] = placement;
63    }
64}
65
66impl Index<PaneRole> for PaneLayoutValue {
67    type Output = PanePlacement;
68
69    fn index(&self, role: PaneRole) -> &Self::Output {
70        &self.0[role.index()]
71    }
72}
73
74/// A history entry with an optional stable domain content key.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct PaneDestination {
77    pub role: PaneRole,
78    pub content_key: Option<ElementId>,
79}
80
81impl PaneDestination {
82    pub fn new(role: PaneRole) -> Self {
83        Self {
84            role,
85            content_key: None,
86        }
87    }
88
89    pub fn content_key(mut self, key: impl Into<ElementId>) -> Self {
90        self.content_key = Some(key.into());
91        self
92    }
93}
94
95/// How many destinations a back operation can skip.
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub enum PaneBackBehavior {
98    PopLatest,
99    #[default]
100    PopUntilScaffoldValueChange,
101    PopUntilCurrentDestinationChange,
102    PopUntilContentChange,
103}
104
105#[derive(Clone, Copy)]
106pub(super) struct Adaptation {
107    pub horizontal: usize,
108    pub vertical: usize,
109    pub strategies: [Option<PaneAdaptStrategy>; 3],
110}
111
112impl Default for Adaptation {
113    fn default() -> Self {
114        Self {
115            horizontal: 1,
116            vertical: 1,
117            strategies: [Some(PaneAdaptStrategy::Hide); 3],
118        }
119    }
120}
121
122impl Adaptation {
123    pub fn resolve(self, history: &[PaneDestination], aware: bool) -> PaneLayoutValue {
124        let mut value = PaneLayoutValue::default();
125        let horizontal = self.horizontal.clamp(1, 3);
126        let vertical = self.vertical.clamp(1, 3);
127        let active = history.last().map(|destination| destination.role);
128        let prior = history
129            .iter()
130            .rev()
131            .take(if aware { history.len() } else { 1 });
132        if let Some(role) = active
133            && let Some(PaneAdaptStrategy::Levitate(alignment)) = self.strategies[role.index()]
134        {
135            value.set(role, PanePlacement::Levitate(alignment));
136        }
137        let mut expanded = 0;
138        let mut reflowed = 0;
139        let mut seen = [false; 3];
140        let mut seen_count = 0;
141        for role in prior
142            .map(|destination| destination.role)
143            .chain(PaneRole::ALL)
144        {
145            if !std::mem::replace(&mut seen[role.index()], true) {
146                seen_count += 1;
147            } else {
148                continue;
149            }
150            if value[role] != PanePlacement::Hidden {
151                if seen_count == 3 {
152                    break;
153                }
154                continue;
155            }
156            match self.strategies[role.index()] {
157                Some(PaneAdaptStrategy::Reflow(anchor))
158                    if horizontal == 1
159                        && reflowed + 1 < vertical
160                        && anchor != role
161                        && self.strategies[anchor.index()].is_some_and(|strategy| {
162                            !matches!(strategy, PaneAdaptStrategy::Levitate(_))
163                        })
164                        && (value[anchor] == PanePlacement::Expanded || expanded == 0) =>
165                {
166                    value.set(anchor, PanePlacement::Expanded);
167                    value.set(role, PanePlacement::Reflow(anchor));
168                    expanded = 1;
169                    reflowed += 1;
170                }
171                Some(PaneAdaptStrategy::Hide | PaneAdaptStrategy::Reflow(_))
172                    if expanded < horizontal =>
173                {
174                    value.set(role, PanePlacement::Expanded);
175                    expanded += 1;
176                }
177                _ => {}
178            }
179            if seen_count == 3 {
180                break;
181            }
182        }
183        value
184    }
185
186    fn normalize(self, value: PaneLayoutValue) -> PaneLayoutValue {
187        let mut safe = value;
188        for role in PaneRole::ALL {
189            if self.strategies[role.index()].is_none()
190                || matches!(value[role], PanePlacement::Reflow(anchor)
191                    if self.strategies[anchor.index()].is_none() || value[anchor] != PanePlacement::Expanded)
192            {
193                safe.set(role, PanePlacement::Hidden);
194            }
195        }
196        safe
197    }
198}
199
200#[derive(Clone, Copy, Debug, PartialEq)]
201enum Intent {
202    Navigate,
203    Animate(PaneLayoutValue),
204    Snap(PaneLayoutValue),
205    Seek(PaneLayoutValue, f32),
206    SeekBack(PaneBackBehavior, f32),
207}
208
209#[derive(Clone, Copy, PartialEq, Eq)]
210enum Timing {
211    Animate,
212    Snap,
213    Seek,
214}
215
216pub(super) type Frames = [Option<Bounds<Pixels>>; 3];
217
218#[derive(Clone, Copy)]
219struct Motion {
220    from: Frames,
221    started: Instant,
222    timing: Timing,
223}
224
225pub(super) struct DisplayedPanes {
226    pub frames: Frames,
227    pub animate_next_frame: bool,
228}
229
230/// Retained presentation, expansion and navigation state for a single adaptive layout.
231pub struct AdaptivePaneState {
232    history: Vec<PaneDestination>,
233    history_aware: bool,
234    adaptation: Adaptation,
235    expansion: [Option<PaneExpansionAnchor>; 9],
236    current: PaneLayoutValue,
237    target: PaneLayoutValue,
238    progress: f32,
239    intent: Intent,
240    motion: Option<Motion>,
241    displayed: Frames,
242    measured: bool,
243}
244
245impl AdaptivePaneState {
246    pub fn new(initial: PaneDestination) -> Self {
247        let mut value = PaneLayoutValue::default();
248        value.set(initial.role, PanePlacement::Expanded);
249        Self {
250            history: vec![initial],
251            history_aware: true,
252            adaptation: Adaptation::default(),
253            expansion: [None; 9],
254            current: value,
255            target: value,
256            progress: 0.,
257            intent: Intent::Navigate,
258            motion: None,
259            displayed: [None; 3],
260            measured: false,
261        }
262    }
263
264    pub fn current_destination(&self) -> &PaneDestination {
265        self.history
266            .last()
267            .expect("initial destination is retained")
268    }
269
270    pub fn history(&self) -> &[PaneDestination] {
271        &self.history
272    }
273
274    pub fn set_history_aware(&mut self, aware: bool, cx: &mut Context<Self>) {
275        if self.history_aware != aware {
276            self.history_aware = aware;
277            cx.notify();
278        }
279    }
280
281    pub fn navigate_to(&mut self, destination: PaneDestination, cx: &mut Context<Self>) {
282        if self.current_destination() != &destination {
283            self.history.push(destination);
284            cx.notify();
285        }
286        self.follow_navigation(cx);
287    }
288
289    pub fn can_navigate_back(&self, behavior: PaneBackBehavior) -> bool {
290        self.back_index(behavior).is_some()
291    }
292
293    pub fn previous_value(&self, behavior: PaneBackBehavior) -> Option<PaneLayoutValue> {
294        self.back_index(behavior).map(|ix| self.history_value(ix))
295    }
296
297    pub fn navigate_back(&mut self, behavior: PaneBackBehavior, cx: &mut Context<Self>) -> bool {
298        let Some(ix) = self.back_index(behavior) else {
299            return false;
300        };
301        self.history.truncate(ix + 1);
302        self.intent = Intent::Navigate;
303        cx.notify();
304        true
305    }
306
307    /// Previews a back transition without modifying history.
308    pub fn seek_back(
309        &mut self,
310        behavior: PaneBackBehavior,
311        progress: f32,
312        cx: &mut Context<Self>,
313    ) -> bool {
314        if !self.can_navigate_back(behavior) {
315            return false;
316        }
317        self.request(Intent::SeekBack(behavior, fraction(progress)), cx);
318        true
319    }
320
321    pub fn current_value(&self) -> PaneLayoutValue {
322        self.current
323    }
324
325    pub fn target_value(&self) -> PaneLayoutValue {
326        self.target
327    }
328
329    /// Transition progress, or zero once the layout settles.
330    pub fn progress(&self) -> f32 {
331        self.progress
332    }
333
334    pub fn snap_to(&mut self, value: PaneLayoutValue, cx: &mut Context<Self>) {
335        self.request(Intent::Snap(value), cx);
336    }
337
338    pub fn animate_to(&mut self, value: PaneLayoutValue, cx: &mut Context<Self>) {
339        self.request(Intent::Animate(value), cx);
340    }
341
342    pub fn seek_to(&mut self, value: PaneLayoutValue, progress: f32, cx: &mut Context<Self>) {
343        self.request(Intent::Seek(value, fraction(progress)), cx);
344    }
345
346    pub fn follow_navigation(&mut self, cx: &mut Context<Self>) {
347        self.request(Intent::Navigate, cx);
348    }
349
350    pub fn expansion(&self, start: PaneRole, end: PaneRole) -> Option<PaneExpansionAnchor> {
351        self.expansion[start.index() * 3 + end.index()]
352    }
353
354    /// Retains a logical boundary specification, applied when this pair shares a band.
355    pub fn set_expansion(
356        &mut self,
357        start: PaneRole,
358        end: PaneRole,
359        anchor: PaneExpansionAnchor,
360        cx: &mut Context<Self>,
361    ) {
362        if start != end && anchor.position(px(1.)).is_some() {
363            self.replace_expansion(start, end, Some(anchor), cx);
364        }
365    }
366
367    pub fn clear_expansion(&mut self, start: PaneRole, end: PaneRole, cx: &mut Context<Self>) {
368        self.replace_expansion(start, end, None, cx);
369    }
370
371    fn replace_expansion(
372        &mut self,
373        start: PaneRole,
374        end: PaneRole,
375        value: Option<PaneExpansionAnchor>,
376        cx: &mut Context<Self>,
377    ) {
378        let entry = &mut self.expansion[start.index() * 3 + end.index()];
379        if *entry != value {
380            *entry = value;
381            cx.notify();
382        }
383    }
384
385    fn request(&mut self, intent: Intent, cx: &mut Context<Self>) {
386        if self.intent != intent {
387            self.intent = intent;
388            cx.notify();
389        }
390    }
391
392    fn history_value(&self, end: usize) -> PaneLayoutValue {
393        self.adaptation
394            .resolve(&self.history[..=end], self.history_aware)
395    }
396
397    fn back_index(&self, behavior: PaneBackBehavior) -> Option<usize> {
398        let last = self.history.len() - 1;
399        let current = self.current_destination();
400        let value = self.history_value(last);
401        (0..last).rev().find(|&index| {
402            let prior = &self.history[index];
403            match behavior {
404                PaneBackBehavior::PopLatest => true,
405                PaneBackBehavior::PopUntilScaffoldValueChange => self.history_value(index) != value,
406                PaneBackBehavior::PopUntilCurrentDestinationChange => prior.role != current.role,
407                PaneBackBehavior::PopUntilContentChange => {
408                    prior.content_key != current.content_key || self.history_value(index) != value
409                }
410            }
411        })
412    }
413
414    pub(super) fn project(&mut self, adaptation: Adaptation) -> PaneLayoutValue {
415        self.adaptation = adaptation;
416        match self.intent {
417            Intent::Navigate => self.history_value(self.history.len() - 1),
418            Intent::Animate(value) | Intent::Snap(value) | Intent::Seek(value, _) => {
419                adaptation.normalize(value)
420            }
421            Intent::SeekBack(behavior, _) => self
422                .previous_value(behavior)
423                .unwrap_or_else(|| self.history_value(self.history.len() - 1)),
424        }
425    }
426
427    pub(super) fn sample(
428        &mut self,
429        value: PaneLayoutValue,
430        target: Frames,
431        now: Instant,
432        duration: Duration,
433        cx: &mut Context<Self>,
434    ) -> DisplayedPanes {
435        let before = (self.current, self.target, self.progress);
436        let (timing, sought) = match self.intent {
437            Intent::Snap(_) => (Timing::Snap, 0.),
438            Intent::Seek(_, fraction) | Intent::SeekBack(_, fraction) => (Timing::Seek, fraction),
439            _ => (Timing::Animate, 0.),
440        };
441        let unsettled = timing == Timing::Seek || duration > Duration::ZERO;
442        let changed = self.target != value;
443        self.target = value;
444        if !self.measured || timing == Timing::Snap || !unsettled {
445            self.motion = None;
446            self.current = value;
447            self.progress = 0.;
448            self.displayed = target;
449            self.measured = true;
450        } else if changed || self.motion.is_some_and(|motion| motion.timing != timing) {
451            self.motion = Some(Motion {
452                from: self.displayed,
453                started: now,
454                timing,
455            });
456        }
457        let mut animate_next_frame = false;
458        if let Some(motion) = self.motion {
459            let raw = if timing == Timing::Seek {
460                sought
461            } else {
462                ((now - motion.started).as_secs_f32() / duration.as_secs_f32()).clamp(0., 1.)
463            };
464            if raw >= 1. && timing == Timing::Animate {
465                self.motion = None;
466                self.current = value;
467                self.progress = 0.;
468                self.displayed = target;
469            } else {
470                self.progress = raw;
471                let visual = if timing == Timing::Seek {
472                    raw
473                } else {
474                    raw * raw * (3. - 2. * raw)
475                };
476                self.displayed = std::array::from_fn(|ix| {
477                    target[ix].map(|end| blend(motion.from[ix], end, visual))
478                });
479                animate_next_frame = timing == Timing::Animate;
480            }
481        } else {
482            self.displayed = target;
483        }
484        if before != (self.current, self.target, self.progress) {
485            let state = cx.weak_entity();
486            cx.defer(move |cx| {
487                let _ = state.update(cx, |_, cx| cx.notify());
488            });
489        }
490        DisplayedPanes {
491            frames: self.displayed,
492            animate_next_frame,
493        }
494    }
495
496    pub(super) fn is_transitioning(&self) -> bool {
497        self.motion.is_some()
498    }
499}
500
501fn fraction(value: f32) -> f32 {
502    if value.is_finite() {
503        value.clamp(0., 1.)
504    } else {
505        0.
506    }
507}
508
509fn blend(from: Option<Bounds<Pixels>>, to: Bounds<Pixels>, fraction: f32) -> Bounds<Pixels> {
510    let from = from.unwrap_or_else(|| Bounds::new(to.center(), size(px(0.), px(0.))));
511    let interpolate = |a, b| a + (b - a) * fraction;
512    Bounds::new(
513        point(
514            interpolate(from.left(), to.left()),
515            interpolate(from.top(), to.top()),
516        ),
517        size(
518            interpolate(from.size.width, to.size.width),
519            interpolate(from.size.height, to.size.height),
520        ),
521    )
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    #[test]
529    fn adaptation_resolve_short_circuits_duplicate_history_entries() {
530        let adaptation = Adaptation {
531            horizontal: 2,
532            vertical: 1,
533            strategies: [
534                Some(PaneAdaptStrategy::Hide),
535                Some(PaneAdaptStrategy::Hide),
536                Some(PaneAdaptStrategy::Hide),
537            ],
538        };
539        let mut history = vec![PaneDestination::new(PaneRole::Tertiary)];
540        for ix in 0..200 {
541            let role = if ix % 2 == 0 {
542                PaneRole::Primary
543            } else {
544                PaneRole::Secondary
545            };
546            history.push(PaneDestination::new(role).content_key(ix));
547        }
548        let resolved = adaptation.resolve(&history, true);
549        assert_eq!(
550            resolved,
551            PaneLayoutValue::new(
552                PanePlacement::Expanded,
553                PanePlacement::Expanded,
554                PanePlacement::Hidden,
555            )
556        );
557    }
558}