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