gpui-material-components 0.1.1

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
use std::time::Duration;

use gpui::{
    AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, Element, ElementId, Entity,
    GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId, ParentElement,
    Pixels, Point, RenderOnce, Size, Style, Styled, Window, div, point, prelude::FluentBuilder,
    relative, size,
};
use gpui_base::TestSupportExt;
use gpui_material_foundation::window_material_theme;
use gpui_material_theme::{Direction, WidthClass};
use web_time::Instant;

use super::{
    NavigationBar, NavigationBarLayout, NavigationItems, NavigationRail, RailMode, Scaffold,
    rail::length,
};

/// Current Material 3 Expressive navigation presentations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AdaptiveNavigationType {
    ShortBarCompact,
    ShortBarMedium,
    RailCollapsed,
    RailExpanded,
    /// Leaves the scaffold's existing slots in place.
    None,
}

impl AdaptiveNavigationType {
    pub fn for_width(width: Pixels) -> Self {
        match WidthClass::from_width(width.into()) {
            WidthClass::Compact => Self::ShortBarCompact,
            WidthClass::Medium => Self::ShortBarMedium,
            _ => Self::RailCollapsed,
        }
    }

    fn is_rail(self) -> bool {
        matches!(self, Self::RailCollapsed | Self::RailExpanded)
    }
}

/// Available scaffold space for an application-supplied navigation policy.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AdaptiveNavigationInfo {
    pub available_size: Size<Pixels>,
    pub width_class: WidthClass,
    pub direction: Direction,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AdaptiveNavigationVisibility {
    #[default]
    Shown,
    Hidden,
}

impl AdaptiveNavigationVisibility {
    fn fraction(self) -> f32 {
        f32::from(self == Self::Shown)
    }
}

struct Transition {
    from: f32,
    started: Instant,
}

/// Retained navigation visibility, independent of the current presentation.
pub struct AdaptiveNavigationState {
    current: AdaptiveNavigationVisibility,
    target: AdaptiveNavigationVisibility,
    fraction: f32,
    duration: Duration,
    transition: Option<Transition>,
}

impl Default for AdaptiveNavigationState {
    fn default() -> Self {
        Self::new(AdaptiveNavigationVisibility::Shown)
    }
}

impl AdaptiveNavigationState {
    pub fn new(initial: AdaptiveNavigationVisibility) -> Self {
        Self {
            current: initial,
            target: initial,
            fraction: initial.fraction(),
            duration: Duration::from_millis(240),
            transition: None,
        }
    }

    pub fn transition_duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    /// Last settled visibility.
    pub fn current_value(&self) -> AdaptiveNavigationVisibility {
        self.current
    }

    pub fn target_value(&self) -> AdaptiveNavigationVisibility {
        self.target
    }

    pub fn is_animating(&self) -> bool {
        self.transition.is_some()
    }

    /// The currently visible fraction of the slot, in 0..=1.
    pub fn progress(&self) -> f32 {
        self.fraction
    }

    pub fn show(&mut self, cx: &mut Context<Self>) {
        self.animate_to(AdaptiveNavigationVisibility::Shown, cx);
    }

    pub fn hide(&mut self, cx: &mut Context<Self>) {
        self.animate_to(AdaptiveNavigationVisibility::Hidden, cx);
    }

    pub fn toggle(&mut self, cx: &mut Context<Self>) {
        match self.target {
            AdaptiveNavigationVisibility::Shown => self.hide(cx),
            AdaptiveNavigationVisibility::Hidden => self.show(cx),
        }
    }

    pub fn snap_to(&mut self, value: AdaptiveNavigationVisibility, cx: &mut Context<Self>) {
        if self.current != value || self.target != value || self.is_animating() {
            self.target = value;
            self.settle();
            cx.notify();
        }
    }

    fn animate_to(&mut self, target: AdaptiveNavigationVisibility, cx: &mut Context<Self>) {
        if self.duration.is_zero() || cx.reduce_motion() {
            self.snap_to(target, cx);
            return;
        }
        self.sample(cx);
        if self.target != target {
            self.target = target;
            if self.fraction == target.fraction() {
                self.settle();
            } else {
                self.transition = Some(Transition {
                    from: self.fraction,
                    started: cx.background_executor().now(),
                });
            }
            cx.notify();
        }
    }

    fn settle(&mut self) {
        self.current = self.target;
        self.fraction = self.target.fraction();
        self.transition = None;
    }

    fn sample(&mut self, cx: &mut Context<Self>) {
        let Some(transition) = &self.transition else {
            return;
        };
        let elapsed = cx.background_executor().now() - transition.started;
        if elapsed >= self.duration || cx.reduce_motion() {
            self.settle();
            cx.notify();
        } else {
            let fraction = (elapsed.as_secs_f64() / self.duration.as_secs_f64()) as f32;
            let eased = fraction * fraction * (3. - 2. * fraction);
            let next = transition.from + (self.target.fraction() - transition.from) * eased;
            if next != self.fraction {
                self.fraction = next;
                cx.notify();
            }
        }
    }
}

type Policy = Box<dyn FnOnce(AdaptiveNavigationInfo) -> AdaptiveNavigationType>;
type NavigationContent = Box<dyn FnOnce(AdaptiveNavigationType, AnyElement) -> AnyElement>;
type Configure<T> = Box<dyn FnOnce(AdaptiveNavigationType, T) -> T>;

/// Material 3 navigation suite for the existing Scaffold bar and rail slots.
#[derive(IntoElement)]
pub struct AdaptiveNavigation {
    scaffold: Scaffold,
    items: NavigationItems,
    width: Pixels,
    height: Option<Pixels>,
    policy: Option<Policy>,
    state: Option<Entity<AdaptiveNavigationState>>,
    content: Option<NavigationContent>,
    bar: Option<Configure<NavigationBar>>,
    rail: Option<Configure<NavigationRail>>,
}

impl AdaptiveNavigation {
    /// Uses the available width of the scaffold in logical units.
    pub fn new(scaffold: Scaffold, items: NavigationItems, available_width: Pixels) -> Self {
        Self {
            scaffold,
            items,
            width: available_width,
            height: None,
            policy: None,
            state: None,
            content: None,
            bar: None,
            rail: None,
        }
    }

    /// Supplies the bounded scaffold size when it differs from the viewport.
    pub fn available_size(mut self, size: Size<Pixels>) -> Self {
        self.width = size.width;
        self.height = Some(size.height);
        self
    }

    pub fn navigation_type(self, kind: AdaptiveNavigationType) -> Self {
        self.navigation_policy(move |_| kind)
    }

    pub fn navigation_policy(
        mut self,
        policy: impl FnOnce(AdaptiveNavigationInfo) -> AdaptiveNavigationType + 'static,
    ) -> Self {
        self.policy = Some(Box::new(policy));
        self
    }

    pub fn state(mut self, state: &Entity<AdaptiveNavigationState>) -> Self {
        self.state = Some(state.clone());
        self
    }

    /// Composes or replaces the standard navigation in its scaffold slot.
    pub fn navigation_content<E: IntoElement>(
        mut self,
        build: impl FnOnce(AdaptiveNavigationType, AnyElement) -> E + 'static,
    ) -> Self {
        self.content = Some(Box::new(move |kind, default| {
            build(kind, default).into_any_element()
        }));
        self
    }

    pub fn navigation_bar(
        mut self,
        build: impl FnOnce(AdaptiveNavigationType, NavigationBar) -> NavigationBar + 'static,
    ) -> Self {
        self.bar = Some(Box::new(build));
        self
    }

    pub fn navigation_rail(
        mut self,
        build: impl FnOnce(AdaptiveNavigationType, NavigationRail) -> NavigationRail + 'static,
    ) -> Self {
        self.rail = Some(Box::new(build));
        self
    }
}

impl RenderOnce for AdaptiveNavigation {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let viewport = window.viewport_size();
        let available = size(
            length(self.width),
            length(self.height.unwrap_or(viewport.height)),
        );
        let direction = window_material_theme(window, cx).layout.direction;
        let info = AdaptiveNavigationInfo {
            available_size: available,
            width_class: WidthClass::from_width(available.width.into()),
            direction,
        };
        let kind = match self.policy {
            Some(policy) => policy(info),
            None => AdaptiveNavigationType::for_width(available.width),
        };
        let (fraction, moving) = self.state.as_ref().map_or((1., false), |state| {
            state.update(cx, |state, cx| {
                state.sample(cx);
                (state.progress(), state.is_animating())
            })
        });
        if moving {
            window.request_animation_frame();
        }
        let scope = window
            .use_keyed_state(
                (self.items.id().clone(), "adaptive-navigation-focus"),
                cx,
                |_, cx| cx.focus_handle().tab_stop(false),
            )
            .read(cx)
            .clone();
        let items = self.items.retain(window, cx).retain_roving_stop();
        if kind == AdaptiveNavigationType::None || fraction <= 0. {
            if scope.contains_focused(window, cx) {
                let previous = window.focused(cx);
                window.defer(cx, move |window, cx| {
                    if window.focused(cx) == previous {
                        window.focus_next(cx);
                        if window.focused(cx) == previous {
                            window.blur(cx);
                        }
                    }
                });
            }
            return self.scaffold;
        }
        let is_rail = kind.is_rail();
        let default = if is_rail {
            let mode = if kind == AdaptiveNavigationType::RailExpanded {
                RailMode::Expanded
            } else {
                RailMode::Collapsed
            };
            let rail = NavigationRail::new("adaptive-rail", items).mode(mode);
            match self.rail {
                Some(build) => build(kind, rail),
                None => rail,
            }
            .into_any_element()
        } else {
            let layout = if kind == AdaptiveNavigationType::ShortBarMedium {
                NavigationBarLayout::Horizontal
            } else {
                NavigationBarLayout::Vertical
            };
            let bar = NavigationBar::new(items).layout(layout);
            match self.bar {
                Some(build) => build(kind, bar),
                None => bar,
            }
            .into_any_element()
        };
        let content = match self.content {
            Some(build) => build(kind, default),
            None => default,
        };
        let content = div()
            .flex()
            .flex_col()
            .when(is_rail, |content| content.h_full().max_w(available.width))
            .when(!is_rail, |content| content.w_full().max_h(available.height))
            .child(content);
        let slot = div()
            .id("adaptive-navigation-slot")
            .test_support()
            .track_focus(&scope)
            .flex_none()
            .when(is_rail, Styled::h_full)
            .when(!is_rail, Styled::w_full);
        let slot = if fraction < 1. {
            slot.child(SlidingSlot {
                content: content.into_any_element(),
                available,
                fraction,
                is_rail,
                direction,
            })
        } else {
            slot.child(content)
        };
        if is_rail {
            self.scaffold.rail(slot)
        } else {
            self.scaffold.bottom_bar(slot)
        }
    }
}

/// Measures the natural slot once and reserves its animated fraction. The
/// same content is clipped and translated, preserving its layout and IDs.
struct SlidingSlot {
    content: AnyElement,
    available: Size<Pixels>,
    fraction: f32,
    is_rail: bool,
    direction: Direction,
}

impl IntoElement for SlidingSlot {
    type Element = Self;

    fn into_element(self) -> Self {
        self
    }
}

impl Element for SlidingSlot {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, ()) {
        let natural =
            self.content
                .layout_as_root(self.available.map(AvailableSpace::Definite), window, cx);
        let size = if self.is_rail {
            size((natural.width * self.fraction).into(), relative(1.).into())
        } else {
            size(relative(1.).into(), (natural.height * self.fraction).into())
        };
        (
            window.request_layout(
                Style {
                    size,
                    ..Style::default()
                },
                None,
                cx,
            ),
            (),
        )
    }

    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        let cross_fit = if self.is_rail {
            size(self.available.width, bounds.size.height)
        } else {
            size(bounds.size.width, self.available.height)
        };
        let natural =
            self.content
                .layout_as_root(cross_fit.map(AvailableSpace::Definite), window, cx);
        let origin: Point<Pixels> = if self.is_rail && self.direction == Direction::Ltr {
            point(bounds.right() - natural.width, bounds.top())
        } else {
            bounds.origin
        };
        window.with_content_mask(Some(ContentMask { bounds }), |window| {
            self.content.prepaint_at(origin, window, cx);
        });
    }

    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut (),
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        window.with_content_mask(Some(ContentMask { bounds }), |window| {
            self.content.paint(window, cx)
        });
    }
}