gpui-material-components 0.2.0

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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
use std::cell::{Cell, RefCell};
use std::rc::Rc;

use crate::menu_appearance::Paint;
pub use crate::menu_appearance::{MenuColor, MenuItemStyle, MenuSurfaceStyle};

use crate::motion::{OverlayMotion, ScaledOverlay, menu_pivot};
use crate::{Icon, IconName};
use gpui::{
    Anchor, AnyElement, App, Bounds, ElementId, Focusable, InteractiveElement, IntoElement,
    MouseButton, ParentElement, Pixels, Point, RenderOnce, Role, ScrollHandle, SharedString,
    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
};
use gpui_base::{
    Popover, PopoverState, Positioner,
    actions::{Cancel, Confirm},
};
use gpui_material_foundation::{ThemeScope, current_material_theme, logical_anchor};
use gpui_material_theme::{CornerShape, Direction};

mod content;

use content::{MenuExitRow, menu_content, menu_exit};

type Action = Rc<dyn Fn(&mut Window, &mut App)>;
type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type ItemContent = Rc<dyn Fn() -> AnyElement>;
type ComposedTrigger = Box<dyn FnOnce(bool, Action) -> AnyElement>;

/// An item in a Material menu. Callers retain command and selection state.
pub struct MenuItem {
    id: ElementId,
    label: SharedString,
    disabled: bool,
    kind: Kind,
    slots: ItemSlots,
    on_checked_change: Option<Change>,
    style: MenuItemStyle,
}

enum Kind {
    Action(Option<Action>),
    Check(bool, Option<Action>),
    Select(bool, Option<Action>),
    Heading,
    Section {
        rows: Vec<MenuItem>,
        style: MenuSurfaceStyle,
        inactive_shape: Option<CornerShape>,
    },
    Submenu(Vec<MenuItem>),
}

#[derive(Clone, Default)]
struct ItemSlots {
    content: Option<ItemContent>,
    leading: Option<ItemContent>,
    supporting: Option<ItemContent>,
    trailing: Option<ItemContent>,
    selection_icon: Option<ItemContent>,
}

impl ItemSlots {
    fn label(&self, label: SharedString) -> AnyElement {
        self.content
            .as_ref()
            .map_or_else(|| label.into_any_element(), |content| content())
    }

    fn children(
        &self,
        label: SharedString,
        marked: bool,
        submenu: bool,
        paint: Paint<'_>,
        supporting_color: gpui::Hsla,
    ) -> Vec<AnyElement> {
        let motion = paint.motion;
        let icon_size = motion.px(18.);
        let leading = if marked {
            Some(self.selection_icon.as_ref().map_or_else(
                || {
                    Icon::new(IconName::Check)
                        .size(icon_size)
                        .into_any_element()
                },
                |icon| icon(),
            ))
        } else {
            self.leading.as_ref().map(|icon| icon())
        };
        let supporting_scale = paint.theme.typography.text_scale();
        let body = div()
            .flex_1()
            .min_w_0()
            .overflow_hidden()
            .child(div().truncate().child(self.label(label)))
            .children(self.supporting.as_ref().map(|supporting| {
                div()
                    .text_size(motion.px(12. * supporting_scale))
                    .line_height(motion.px(16. * supporting_scale))
                    .text_color(supporting_color)
                    .child(supporting())
            }));
        let mut children = vec![
            div()
                .min_w(icon_size)
                .flex_none()
                .children(leading)
                .into_any_element(),
            body.into_any_element(),
        ];
        children.extend(self.trailing.as_ref().map(|trailing| trailing()));
        children.extend(submenu.then(|| {
            Icon::new(IconName::ChevronRight)
                .size(icon_size)
                .mirror_in_rtl(true)
                .into_any_element()
        }));
        children
    }
}

impl MenuItem {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            disabled: false,
            kind: Kind::Action(None),
            slots: ItemSlots::default(),
            on_checked_change: None,
            style: MenuItemStyle::default(),
        }
    }

    pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
        Self {
            kind: Kind::Heading,
            ..Self::new(id, title)
        }
    }

    /// Creates a surfaced group with rows in the owning menu's navigation order.
    pub fn section(
        id: impl Into<ElementId>,
        name: impl Into<SharedString>,
        rows: impl IntoIterator<Item = MenuItem>,
    ) -> Self {
        Self {
            kind: Kind::Section {
                rows: rows.into_iter().collect(),
                style: MenuSurfaceStyle::default(),
                inactive_shape: None,
            },
            ..Self::new(id, name)
        }
    }

    /// Sets the styled section's surface appearance.
    pub fn group_appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
        if let Kind::Section { style, .. } = &mut self.kind {
            *style = appearance;
        }
        self
    }

    /// Sets the section shape used after the pointer leaves the section.
    pub fn inactive_shape(mut self, shape: CornerShape) -> Self {
        if let Kind::Section { inactive_shape, .. } = &mut self.kind {
            *inactive_shape = Some(shape);
        }
        self
    }

    /// Configures the appearance of an action, checked or selected row.
    pub fn appearance(mut self, style: MenuItemStyle) -> Self {
        self.style = style;
        self
    }

    pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
        self.kind = Kind::Submenu(items.into_iter().collect());
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn checked(mut self, checked: bool) -> Self {
        self.kind = Kind::Check(checked, self.action());
        self
    }

    pub fn selected(mut self, selected: bool) -> Self {
        self.kind = Kind::Select(selected, self.action());
        self
    }

    /// Replaces the visible label while retaining the name passed to `new`.
    /// Supply a repeatable factory so the content also appears during exit.
    pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
        self.slots.content = Some(Rc::new(move || build().into_any_element()));
        self
    }

    /// Supplies a decorative element at the logical start of an unmarked row.
    pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
        self.slots.leading = Some(Rc::new(move || build().into_any_element()));
        self
    }

    /// Supplies additional visual content below the label.
    pub fn supporting<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
        self.slots.supporting = Some(Rc::new(move || build().into_any_element()));
        self
    }

    /// Supplies decorative content at the logical end of the row.
    pub fn trailing<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
        self.slots.trailing = Some(Rc::new(move || build().into_any_element()));
        self
    }

    /// Replaces the leading check mark of a checked or selected row.
    pub fn selection_icon<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
        self.slots.selection_icon = Some(Rc::new(move || build().into_any_element()));
        self
    }

    /// Requests the inverse of the supplied checked value on activation.
    /// The checked callback takes precedence over `on_activate` on checked rows.
    pub fn on_checked_change(
        mut self,
        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_checked_change = Some(Rc::new(callback));
        self
    }

    fn action(&self) -> Option<Action> {
        match &self.kind {
            Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
                action.clone()
            }
            _ => None,
        }
    }

    fn activation(&self) -> Option<Action> {
        if let Kind::Check(checked, _) = self.kind
            && let Some(callback) = &self.on_checked_change
        {
            let callback = callback.clone();
            return Some(Rc::new(move |window, cx| callback(!checked, window, cx)));
        }
        self.action()
    }

    pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        match &mut self.kind {
            Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
                *handler = Some(Rc::new(action));
            }
            _ => {}
        }
        self
    }
}

/// Positions a Material menu against a caller-owned, keyboard-focusable trigger.
/// Pointer and keyboard activation use the same Base popover focus lifecycle.
#[derive(IntoElement)]
pub struct Menu {
    id: ElementId,
    trigger: AnyElement,
    items: Vec<MenuItem>,
    mouse_button: MouseButton,
    anchor: Anchor,
    close_parent: Option<Action>,
    enabled: bool,
    ancestor: Option<Rc<PopupBounds>>,
    composed_trigger: Option<ComposedTrigger>,
    open: Option<bool>,
    on_open_change: Option<Change>,
    on_dismiss: Option<Action>,
    color: MenuColor,
    appearance: MenuSurfaceStyle,
    decoration: Option<ItemContent>,
    scroll: Option<ScrollHandle>,
    offset: Pixels,
    position: Option<Point<Pixels>>,
}

#[derive(Default)]
struct PopupBounds {
    trigger: Cell<Bounds<Pixels>>,
    popup: Cell<Bounds<Pixels>>,
    child: RefCell<Option<Rc<PopupBounds>>>,
    presented: RefCell<Option<PresentedMenu>>,
    scroll: ScrollHandle,
    motion: Cell<Option<OverlayMotion>>,
    open: Rc<Cell<bool>>,
}

#[derive(Clone)]
struct MenuPresentation {
    color: MenuColor,
    appearance: MenuSurfaceStyle,
    decoration: Option<ItemContent>,
    scroll: ScrollHandle,
}

struct PresentedMenu {
    items: Vec<MenuExitRow>,
    presentation: MenuPresentation,
}

impl PopupBounds {
    fn contains(&self, point: &Point<Pixels>) -> bool {
        self.trigger.get().contains(point)
            || self.popup.get().contains(point)
            || self
                .child
                .borrow()
                .as_ref()
                .is_some_and(|child| child.open.get() && child.contains(point))
    }
}

impl Menu {
    pub fn new(
        id: impl Into<ElementId>,
        trigger: impl IntoElement,
        items: impl IntoIterator<Item = MenuItem>,
    ) -> Self {
        Self {
            id: id.into(),
            trigger: trigger.into_any_element(),
            items: items.into_iter().collect(),
            mouse_button: MouseButton::Left,
            anchor: Anchor::TopLeft,
            close_parent: None,
            enabled: true,
            ancestor: None,
            composed_trigger: None,
            open: None,
            on_open_change: None,
            on_dismiss: None,
            color: MenuColor::default(),
            appearance: MenuSurfaceStyle::default(),
            decoration: None,
            scroll: None,
            offset: px(4.),
            position: None,
        }
    }

    /// Opens on secondary click; Enter and Space still work on the trigger.
    pub fn context(mut self) -> Self {
        self.mouse_button = MouseButton::Right;
        self
    }

    pub fn anchor(mut self, anchor: Anchor) -> Self {
        self.anchor = anchor;
        self
    }

    /// Sets the outward gap between the trigger and popup.
    pub fn offset(mut self, offset: Pixels) -> Self {
        if f32::from(offset).is_finite() {
            self.offset = offset;
        }
        self
    }

    /// Anchors the popup at a window-local point. It remains clamped to the viewport.
    pub fn position(mut self, position: Point<Pixels>) -> Self {
        self.position = (f32::from(position.x).is_finite() && f32::from(position.y).is_finite())
            .then_some(position);
        self
    }

    /// Applies a semantic color preset to the menu and its submenus.
    pub fn color(mut self, color: MenuColor) -> Self {
        self.color = color;
        self
    }

    /// Applies overrides to this popup's surface.
    pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
        self.appearance = appearance;
        self
    }

    /// Renders arbitrary content before the menu rows. Use a repeatable factory
    /// for content that also needs to appear during exit.
    pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
        self.decoration = Some(Rc::new(move || build().into_any_element()));
        self
    }

    /// Tracks the popup's scrolling through a caller-owned handle.
    pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
        self.scroll = Some(scroll.clone());
        self
    }

    /// Builds a trigger from the displayed open value and its activation callback.
    ///
    /// Keep the trigger focusable and use the supplied callback for a custom
    /// accessibility action. The menu owns pointer and keyboard activation.
    pub fn composed(
        id: impl Into<ElementId>,
        items: impl IntoIterator<Item = MenuItem>,
        trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
    ) -> Self {
        let mut menu = Self::new(id, div(), items);
        menu.composed_trigger = Some(Box::new(trigger));
        menu
    }

    /// Sets the displayed open value from caller-owned state.
    pub fn open(mut self, open: bool) -> Self {
        self.open = Some(open);
        self
    }

    /// Receives user requests to open or close the menu. In controlled mode,
    /// apply the requested value and render with `open` to accept a request.
    pub fn on_open_change(
        mut self,
        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_open_change = Some(Rc::new(callback));
        self
    }

    /// Receives a user request to close. Setting `open(false)` externally
    /// synchronizes the menu without running this callback.
    pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_dismiss = Some(Rc::new(callback));
        self
    }
}

fn build_exit_branch(
    id: &ElementId,
    bounds: &Rc<PopupBounds>,
    motion: OverlayMotion,
    direction: Direction,
    window: &Window,
    cx: &App,
) -> gpui::Div {
    // Closing the parent removes Base's nested popup hosts immediately.
    // Use the last presented branch to finish their own visual exits.
    let mut exits = div();
    let mut level = Some(bounds.clone());
    let mut depth = 0;
    while let Some(bounds) = level {
        let Some(previous) = bounds.motion.get() else {
            break;
        };
        let motion = if depth == 0 {
            motion
        } else {
            OverlayMotion {
                scale: 0.8 + (motion.scale - 0.8) * (previous.scale - 0.8) / 0.2,
                alpha: motion.alpha * previous.alpha,
            }
        };
        exits = exits.children(menu_exit(
            (id, depth),
            &bounds,
            motion,
            direction,
            window,
            cx,
        ));
        level = bounds.child.borrow().clone();
        depth += 1;
    }
    exits
}

impl RenderOnce for Menu {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let direction = current_material_theme(window, cx).layout.direction;
        let submenu = self.close_parent.is_some();
        if !self.enabled {
            return self.trigger;
        }
        let view = window.current_view();
        let bounds = window
            .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
                Rc::new(PopupBounds::default())
            })
            .read(cx)
            .clone();
        let open_state = bounds.open.clone();
        let controlled = self.open.is_some();
        let open = self.open.unwrap_or_else(|| open_state.get());
        open_state.set(open);
        let key_state = open_state.clone();
        let trigger_state = open_state.clone();
        let request: Change = {
            let on_open_change = self.on_open_change;
            let on_dismiss = self.on_dismiss;
            Rc::new(move |requested, window, cx| {
                if !controlled {
                    open_state.set(requested);
                    cx.notify(view);
                }
                if let Some(callback) = &on_open_change {
                    callback(requested, window, cx);
                }
                if !requested && let Some(callback) = &on_dismiss {
                    callback(window, cx);
                }
            })
        };
        let trigger: Action = {
            let request = request.clone();
            Rc::new(move |window, cx| {
                let displayed = if controlled {
                    open
                } else {
                    trigger_state.get()
                };
                request(!displayed, window, cx);
            })
        };
        let key_trigger = trigger.clone();
        let mouse_trigger = trigger.clone();
        let popover_request = request.clone();
        let popup_request = request;
        let motion = OverlayMotion::sample(&self.id, open, window, cx);
        let position = bounds.clone();
        let ancestor = self.ancestor.clone();
        let anchor = logical_anchor(self.anchor, direction);
        let explicit_position = self.position;
        let presentation = MenuPresentation {
            color: self.color,
            appearance: self.appearance,
            decoration: self.decoration,
            scroll: self.scroll.unwrap_or_else(|| bounds.scroll.clone()),
        };
        if open {
            *bounds.presented.borrow_mut() = Some(PresentedMenu {
                items: self.items.iter().map(MenuExitRow::from).collect(),
                presentation: presentation.clone(),
            });
        }
        bounds.motion.set(motion);
        let forward = if direction == Direction::Rtl {
            "left"
        } else {
            "right"
        };
        let exit_view = motion
            .filter(|_| !open)
            .map(|motion| build_exit_branch(&self.id, &bounds, motion, direction, window, cx));
        if !open && motion.is_none() {
            bounds.presented.borrow_mut().take();
            bounds.child.borrow_mut().take();
        }
        let menu_id = self.id.clone();
        let menu = Popover::new(self.id)
            .open(open)
            .on_open_change(move |open, window, cx| popover_request(*open, window, cx))
            .anchor(anchor)
            .offset(self.offset)
            .mouse_button(self.mouse_button)
            .overlay_closable(false)
            .on_position(move |resolved, trigger| {
                position.trigger.set(trigger);
                if explicit_position.is_none() {
                    position.popup.set(resolved.bounds);
                }
                if let Some(ancestor) = &ancestor {
                    *ancestor.child.borrow_mut() = Some(position.clone());
                }
            })
            .trigger_with(move |open, _, _| {
                let content = self
                    .composed_trigger
                    .map_or(self.trigger, |build| build(open, trigger));
                div()
                    .id("menu-trigger")
                    .role(Role::Group)
                    .aria_expanded(open)
                    .when(controlled, |trigger| {
                        // Accepting the request through Popover::open applies
                        // the Base focus lifecycle only after the owner agrees.
                        trigger
                            .on_action(move |_: &Confirm, window, cx| key_trigger(window, cx))
                            .on_mouse_down(self.mouse_button, move |_, window, cx| {
                                cx.stop_propagation();
                                mouse_trigger(window, cx);
                            })
                    })
                    .on_key_down(move |event, _, cx| {
                        if submenu && event.keystroke.key == forward && !key_state.get() {
                            key_state.set(true);
                            cx.notify(view);
                            cx.stop_propagation();
                        }
                    })
                    .child(content)
                    .into_any_element()
            })
            .content(move |state, window, cx| {
                let motion = motion.expect("open menu has motion");
                let close_level: Action = if controlled {
                    Rc::new(move |window, cx| popup_request(false, window, cx))
                } else {
                    let own = cx.entity().downgrade();
                    Rc::new(move |window, cx| {
                        let _ = own.update(cx, |state: &mut PopoverState, cx| {
                            state.dismiss(window, cx);
                        });
                    })
                };
                let close: Action = {
                    let close_level = close_level.clone();
                    Rc::new(move |window, cx| {
                        close_level(window, cx);
                        if let Some(close_parent) = &self.close_parent {
                            close_parent(window, cx);
                        }
                    })
                };
                let dismissal = close_level.clone();
                let escape = close_level.clone();
                let item_bounds = bounds.clone();
                let content = window.with_id(menu_id, |window| {
                    menu_content(
                        self.items,
                        close,
                        submenu.then_some(close_level),
                        state.focus_handle(cx),
                        (direction, bounds.clone(), presentation, motion),
                        window,
                        cx,
                    )
                });
                let popup = div()
                    .id("dismiss-menu")
                    .opacity(motion.alpha)
                    .when(controlled, |popup| {
                        popup.on_action(move |_: &Cancel, window, cx| escape(window, cx))
                    })
                    .on_mouse_down_out(move |event, window, cx| {
                        let point = &event.position;
                        if bounds.contains(point) {
                            return;
                        }
                        dismissal(window, cx);
                    })
                    .child(content);
                let pivot = item_bounds.clone();
                let overlay = ScaledOverlay::new(popup, motion, move |menu| {
                    menu_pivot(menu, pivot.trigger.get())
                });
                let overlay = ThemeScope::inherit(overlay, window, cx);
                if let Some(position) = explicit_position {
                    Positioner::corner(anchor, position)
                        .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
                        .occlude()
                        .child(overlay)
                        .into_any_element()
                } else {
                    overlay
                }
            });
        div()
            .relative()
            .child(menu)
            .children(exit_view)
            .into_any_element()
    }
}