gpui-material-components 0.3.2

Material 3 Expressive desktop components for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
use std::{ops::Index, time::Duration};

use gpui::{Bounds, Context, ElementId, Pixels, point, px, size};
use web_time::Instant;

use super::{PaneExpansionAnchor, PaneOverlayAlignment};

/// Roles in a Material three-pane scaffold.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PaneRole {
    /// Main workspace or detail pane.
    #[default]
    Primary,
    /// Supporting or master list pane.
    Secondary,
    /// Auxiliary or extra pane.
    Tertiary,
}

impl PaneRole {
    pub(super) const ALL: [Self; 3] = [Self::Primary, Self::Secondary, Self::Tertiary];

    pub(super) fn index(self) -> usize {
        match self {
            Self::Primary => 0,
            Self::Secondary => 1,
            Self::Tertiary => 2,
        }
    }
}

/// The strategy used when resolving a pane from navigation and the directive.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PaneAdaptStrategy {
    /// Hide the pane when horizontal partitions are exhausted.
    #[default]
    Hide,
    /// Stack the pane beneath the specified anchor role in tall single-column viewports.
    Reflow(PaneRole),
    /// Present the pane as a floating overlay aligned within the band.
    Levitate(PaneOverlayAlignment),
}

/// A pane's realized presentation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PanePlacement {
    /// The pane is not displayed.
    #[default]
    Hidden,
    /// The pane occupies a standard inline column.
    Expanded,
    /// The pane is stacked vertically beneath the given anchor role.
    Reflow(PaneRole),
    /// The pane floats as an overlay with the given alignment.
    Levitate(PaneOverlayAlignment),
}

/// Presentation of the three roles, independent of their navigation content keys.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PaneLayoutValue([PanePlacement; 3]);

impl PaneLayoutValue {
    /// Creates a layout value specifying the placement for each of the three pane roles.
    pub fn new(primary: PanePlacement, secondary: PanePlacement, tertiary: PanePlacement) -> Self {
        Self([primary, secondary, tertiary])
    }

    /// Returns the realized placement for `role`.
    pub fn placement(self, role: PaneRole) -> PanePlacement {
        self[role]
    }

    fn set(&mut self, role: PaneRole, placement: PanePlacement) {
        self.0[role.index()] = placement;
    }
}

impl Index<PaneRole> for PaneLayoutValue {
    type Output = PanePlacement;

    fn index(&self, role: PaneRole) -> &Self::Output {
        &self.0[role.index()]
    }
}

/// A history entry with an optional stable domain content key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaneDestination {
    /// Target pane role for this history entry.
    pub role: PaneRole,
    /// Optional domain content identifier used to distinguish entries within the same role.
    pub content_key: Option<ElementId>,
}

impl PaneDestination {
    /// Creates a destination targeting `role` with no content key.
    pub fn new(role: PaneRole) -> Self {
        Self {
            role,
            content_key: None,
        }
    }

    /// Attaches a stable domain content key to this destination.
    pub fn content_key(mut self, key: impl Into<ElementId>) -> Self {
        self.content_key = Some(key.into());
        self
    }
}

/// How many destinations a back operation can skip.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PaneBackBehavior {
    /// Pop exactly one destination from the history stack.
    PopLatest,
    /// Pop until the resolved [`PaneLayoutValue`] changes.
    #[default]
    PopUntilScaffoldValueChange,
    /// Pop until the active [`PaneRole`] changes.
    PopUntilCurrentDestinationChange,
    /// Pop until either the content key or the resolved [`PaneLayoutValue`] changes.
    PopUntilContentChange,
}

#[derive(Clone, Copy)]
pub(super) struct Adaptation {
    pub horizontal: usize,
    pub vertical: usize,
    pub strategies: [Option<PaneAdaptStrategy>; 3],
}

impl Default for Adaptation {
    fn default() -> Self {
        Self {
            horizontal: 1,
            vertical: 1,
            strategies: [Some(PaneAdaptStrategy::Hide); 3],
        }
    }
}

impl Adaptation {
    pub fn resolve(self, history: &[PaneDestination], aware: bool) -> PaneLayoutValue {
        let mut value = PaneLayoutValue::default();
        let horizontal = self.horizontal.clamp(1, 3);
        let vertical = self.vertical.clamp(1, 3);
        let active = history.last().map(|destination| destination.role);
        let prior = history
            .iter()
            .rev()
            .take(if aware { history.len() } else { 1 });
        if let Some(role) = active
            && let Some(PaneAdaptStrategy::Levitate(alignment)) = self.strategies[role.index()]
        {
            value.set(role, PanePlacement::Levitate(alignment));
        }
        let mut expanded = 0;
        let mut reflowed = 0;
        let mut seen = [false; 3];
        let mut seen_count = 0;
        for role in prior
            .map(|destination| destination.role)
            .chain(PaneRole::ALL)
        {
            if !std::mem::replace(&mut seen[role.index()], true) {
                seen_count += 1;
            } else {
                continue;
            }
            if value[role] != PanePlacement::Hidden {
                if seen_count == 3 {
                    break;
                }
                continue;
            }
            match self.strategies[role.index()] {
                Some(PaneAdaptStrategy::Reflow(anchor))
                    if horizontal == 1
                        && reflowed + 1 < vertical
                        && anchor != role
                        && self.strategies[anchor.index()].is_some_and(|strategy| {
                            !matches!(strategy, PaneAdaptStrategy::Levitate(_))
                        })
                        && (value[anchor] == PanePlacement::Expanded || expanded == 0) =>
                {
                    value.set(anchor, PanePlacement::Expanded);
                    value.set(role, PanePlacement::Reflow(anchor));
                    expanded = 1;
                    reflowed += 1;
                }
                Some(PaneAdaptStrategy::Hide | PaneAdaptStrategy::Reflow(_))
                    if expanded < horizontal =>
                {
                    value.set(role, PanePlacement::Expanded);
                    expanded += 1;
                }
                _ => {}
            }
            if seen_count == 3 {
                break;
            }
        }
        value
    }

    fn normalize(self, value: PaneLayoutValue) -> PaneLayoutValue {
        let mut safe = value;
        for role in PaneRole::ALL {
            if self.strategies[role.index()].is_none()
                || matches!(value[role], PanePlacement::Reflow(anchor)
                    if self.strategies[anchor.index()].is_none() || value[anchor] != PanePlacement::Expanded)
            {
                safe.set(role, PanePlacement::Hidden);
            }
        }
        safe
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Intent {
    Navigate,
    Animate(PaneLayoutValue),
    Snap(PaneLayoutValue),
    Seek(PaneLayoutValue, f32),
    SeekBack(PaneBackBehavior, f32),
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Timing {
    Animate,
    Snap,
    Seek,
}

pub(super) type Frames = [Option<Bounds<Pixels>>; 3];

#[derive(Clone, Copy)]
struct Motion {
    from: Frames,
    started: Instant,
    timing: Timing,
}

pub(super) struct DisplayedPanes {
    pub frames: Frames,
    pub animate_next_frame: bool,
}

/// Retained presentation, expansion and navigation state for a single adaptive layout.
pub struct AdaptivePaneState {
    history: Vec<PaneDestination>,
    history_aware: bool,
    adaptation: Adaptation,
    expansion: [Option<PaneExpansionAnchor>; 9],
    current: PaneLayoutValue,
    target: PaneLayoutValue,
    progress: f32,
    intent: Intent,
    motion: Option<Motion>,
    displayed: Frames,
    measured: bool,
}

impl AdaptivePaneState {
    /// Creates retained multi-pane state seeded with an initial active destination.
    pub fn new(initial: PaneDestination) -> Self {
        let mut value = PaneLayoutValue::default();
        value.set(initial.role, PanePlacement::Expanded);
        Self {
            history: vec![initial],
            history_aware: true,
            adaptation: Adaptation::default(),
            expansion: [None; 9],
            current: value,
            target: value,
            progress: 0.,
            intent: Intent::Navigate,
            motion: None,
            displayed: [None; 3],
            measured: false,
        }
    }

    /// Returns the most recent destination on the navigation stack.
    pub fn current_destination(&self) -> &PaneDestination {
        self.history
            .last()
            .expect("initial destination is retained")
    }

    /// Returns the full navigation history stack in chronological order.
    pub fn history(&self) -> &[PaneDestination] {
        &self.history
    }

    /// Controls whether prior history entries influence which secondary panes remain visible (default `true`).
    pub fn set_history_aware(&mut self, aware: bool, cx: &mut Context<Self>) {
        if self.history_aware != aware {
            self.history_aware = aware;
            cx.notify();
        }
    }

    /// Pushes `destination` onto the navigation history (if different from current) and follows navigation.
    pub fn navigate_to(&mut self, destination: PaneDestination, cx: &mut Context<Self>) {
        if self.current_destination() != &destination {
            self.history.push(destination);
            cx.notify();
        }
        self.follow_navigation(cx);
    }

    /// Returns whether navigating back with `behavior` has a valid target in history.
    pub fn can_navigate_back(&self, behavior: PaneBackBehavior) -> bool {
        self.back_index(behavior).is_some()
    }

    /// Computes the [`PaneLayoutValue`] that a back navigation with `behavior` would produce.
    pub fn previous_value(&self, behavior: PaneBackBehavior) -> Option<PaneLayoutValue> {
        self.back_index(behavior).map(|ix| self.history_value(ix))
    }

    /// Pops history according to `behavior`. Returns `false` if back navigation is unavailable.
    pub fn navigate_back(&mut self, behavior: PaneBackBehavior, cx: &mut Context<Self>) -> bool {
        let Some(ix) = self.back_index(behavior) else {
            return false;
        };
        self.history.truncate(ix + 1);
        self.intent = Intent::Navigate;
        cx.notify();
        true
    }

    /// Previews a back transition without modifying history.
    pub fn seek_back(
        &mut self,
        behavior: PaneBackBehavior,
        progress: f32,
        cx: &mut Context<Self>,
    ) -> bool {
        if !self.can_navigate_back(behavior) {
            return false;
        }
        self.request(Intent::SeekBack(behavior, fraction(progress)), cx);
        true
    }

    /// Returns the last settled layout value.
    pub fn current_value(&self) -> PaneLayoutValue {
        self.current
    }

    /// Returns the layout value currently settled at or transitioning toward.
    pub fn target_value(&self) -> PaneLayoutValue {
        self.target
    }

    /// Transition progress, or zero once the layout settles.
    pub fn progress(&self) -> f32 {
        self.progress
    }

    /// Snaps immediately to `value` without animation, overriding navigation projection until [`Self::follow_navigation`].
    pub fn snap_to(&mut self, value: PaneLayoutValue, cx: &mut Context<Self>) {
        self.request(Intent::Snap(value), cx);
    }

    /// Animates to `value`, overriding navigation projection until [`Self::follow_navigation`].
    pub fn animate_to(&mut self, value: PaneLayoutValue, cx: &mut Context<Self>) {
        self.request(Intent::Animate(value), cx);
    }

    /// Seeks partway (`progress` in `0.0..=1.0`) toward `value`.
    pub fn seek_to(&mut self, value: PaneLayoutValue, progress: f32, cx: &mut Context<Self>) {
        self.request(Intent::Seek(value, fraction(progress)), cx);
    }

    /// Resumes projecting pane placements automatically from navigation history and viewport directives.
    pub fn follow_navigation(&mut self, cx: &mut Context<Self>) {
        self.request(Intent::Navigate, cx);
    }

    /// Returns the saved split anchor between `start` and `end`, if any.
    pub fn expansion(&self, start: PaneRole, end: PaneRole) -> Option<PaneExpansionAnchor> {
        self.expansion[start.index() * 3 + end.index()]
    }

    /// Retains a logical boundary specification, applied when this pair shares a band.
    pub fn set_expansion(
        &mut self,
        start: PaneRole,
        end: PaneRole,
        anchor: PaneExpansionAnchor,
        cx: &mut Context<Self>,
    ) {
        if start != end && anchor.position(px(1.)).is_some() {
            self.replace_expansion(start, end, Some(anchor), cx);
        }
    }

    /// Clears any saved split anchor between `start` and `end`, restoring default sizing.
    pub fn clear_expansion(&mut self, start: PaneRole, end: PaneRole, cx: &mut Context<Self>) {
        self.replace_expansion(start, end, None, cx);
    }

    fn replace_expansion(
        &mut self,
        start: PaneRole,
        end: PaneRole,
        value: Option<PaneExpansionAnchor>,
        cx: &mut Context<Self>,
    ) {
        let entry = &mut self.expansion[start.index() * 3 + end.index()];
        if *entry != value {
            *entry = value;
            cx.notify();
        }
    }

    fn request(&mut self, intent: Intent, cx: &mut Context<Self>) {
        if self.intent != intent {
            self.intent = intent;
            cx.notify();
        }
    }

    fn history_value(&self, end: usize) -> PaneLayoutValue {
        self.adaptation
            .resolve(&self.history[..=end], self.history_aware)
    }

    fn back_index(&self, behavior: PaneBackBehavior) -> Option<usize> {
        let last = self.history.len() - 1;
        let current = self.current_destination();
        let value = self.history_value(last);
        (0..last).rev().find(|&index| {
            let prior = &self.history[index];
            match behavior {
                PaneBackBehavior::PopLatest => true,
                PaneBackBehavior::PopUntilScaffoldValueChange => self.history_value(index) != value,
                PaneBackBehavior::PopUntilCurrentDestinationChange => prior.role != current.role,
                PaneBackBehavior::PopUntilContentChange => {
                    prior.content_key != current.content_key || self.history_value(index) != value
                }
            }
        })
    }

    pub(super) fn project(&mut self, adaptation: Adaptation) -> PaneLayoutValue {
        self.adaptation = adaptation;
        match self.intent {
            Intent::Navigate => self.history_value(self.history.len() - 1),
            Intent::Animate(value) | Intent::Snap(value) | Intent::Seek(value, _) => {
                adaptation.normalize(value)
            }
            Intent::SeekBack(behavior, _) => self
                .previous_value(behavior)
                .unwrap_or_else(|| self.history_value(self.history.len() - 1)),
        }
    }

    pub(super) fn sample(
        &mut self,
        value: PaneLayoutValue,
        target: Frames,
        now: Instant,
        duration: Duration,
        cx: &mut Context<Self>,
    ) -> DisplayedPanes {
        let before = (self.current, self.target, self.progress);
        let (timing, sought) = match self.intent {
            Intent::Snap(_) => (Timing::Snap, 0.),
            Intent::Seek(_, fraction) | Intent::SeekBack(_, fraction) => (Timing::Seek, fraction),
            _ => (Timing::Animate, 0.),
        };
        let unsettled = timing == Timing::Seek || duration > Duration::ZERO;
        let changed = self.target != value;
        self.target = value;
        if !self.measured || timing == Timing::Snap || !unsettled {
            self.motion = None;
            self.current = value;
            self.progress = 0.;
            self.displayed = target;
            self.measured = true;
        } else if changed || self.motion.is_some_and(|motion| motion.timing != timing) {
            self.motion = Some(Motion {
                from: self.displayed,
                started: now,
                timing,
            });
        }
        let mut animate_next_frame = false;
        if let Some(motion) = self.motion {
            let raw = if timing == Timing::Seek {
                sought
            } else {
                ((now - motion.started).as_secs_f32() / duration.as_secs_f32()).clamp(0., 1.)
            };
            if raw >= 1. && timing == Timing::Animate {
                self.motion = None;
                self.current = value;
                self.progress = 0.;
                self.displayed = target;
            } else {
                self.progress = raw;
                let visual = if timing == Timing::Seek {
                    raw
                } else {
                    raw * raw * (3. - 2. * raw)
                };
                self.displayed = std::array::from_fn(|ix| {
                    target[ix].map(|end| blend(motion.from[ix], end, visual))
                });
                animate_next_frame = timing == Timing::Animate;
            }
        } else {
            self.displayed = target;
        }
        if before != (self.current, self.target, self.progress) {
            let state = cx.weak_entity();
            cx.defer(move |cx| {
                let _ = state.update(cx, |_, cx| cx.notify());
            });
        }
        DisplayedPanes {
            frames: self.displayed,
            animate_next_frame,
        }
    }

    pub(super) fn is_transitioning(&self) -> bool {
        self.motion.is_some()
    }
}

fn fraction(value: f32) -> f32 {
    if value.is_finite() {
        value.clamp(0., 1.)
    } else {
        0.
    }
}

fn blend(from: Option<Bounds<Pixels>>, to: Bounds<Pixels>, fraction: f32) -> Bounds<Pixels> {
    let from = from.unwrap_or_else(|| Bounds::new(to.center(), size(px(0.), px(0.))));
    let interpolate = |a, b| a + (b - a) * fraction;
    Bounds::new(
        point(
            interpolate(from.left(), to.left()),
            interpolate(from.top(), to.top()),
        ),
        size(
            interpolate(from.size.width, to.size.width),
            interpolate(from.size.height, to.size.height),
        ),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adaptation_resolve_short_circuits_duplicate_history_entries() {
        let adaptation = Adaptation {
            horizontal: 2,
            vertical: 1,
            strategies: [
                Some(PaneAdaptStrategy::Hide),
                Some(PaneAdaptStrategy::Hide),
                Some(PaneAdaptStrategy::Hide),
            ],
        };
        let mut history = vec![PaneDestination::new(PaneRole::Tertiary)];
        for ix in 0..200 {
            let role = if ix % 2 == 0 {
                PaneRole::Primary
            } else {
                PaneRole::Secondary
            };
            history.push(PaneDestination::new(role).content_key(ix));
        }
        let resolved = adaptation.resolve(&history, true);
        assert_eq!(
            resolved,
            PaneLayoutValue::new(
                PanePlacement::Expanded,
                PanePlacement::Expanded,
                PanePlacement::Hidden,
            )
        );
    }
}