herogpui-components 0.14.0

HeroUI-style component library 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
//! `ContextMenu` (HeroGPUI extension): a secondary press opens the shared
//! Dropdown `Menu` at the pointer; choosing an item, Escape or a press
//! outside closes it; a disabled context menu ignores the press.

use crate::harness;

use gpui::{
    point, prelude::*, px, Bounds, Modifiers, MouseButton, Pixels, TestAppContext,
    VisualTestContext,
};
use harness::{events, open_host, press, still, Events};
use herogpui_components::{
    Breadcrumbs, Button, ColorArea, ContextMenu, Crumb, ListBox, ListBoxItem, MenuBar, MenuBarMenu,
    MenuItem, PickerColor, Table, TreeItem, TreeView,
};

const PANEL: &str = "context-menu";

fn host(cx: &mut TestAppContext, disabled: bool) -> (Events, &mut VisualTestContext) {
    still();
    let seen = events();
    let s = seen.clone();
    let cx = open_host(cx, move || {
        let (a, o) = (s.clone(), s.clone());
        ContextMenu::new(
            "ctx",
            gpui::div().w(px(400.)).h(px(300.)),
            vec![
                MenuItem::new("copy", "Copy"),
                MenuItem::new("paste", "Paste"),
                MenuItem::new("delete", "Delete").danger(),
            ],
        )
        .is_disabled(disabled)
        .disabled_keys(["paste"])
        .on_action(move |key, _, _| a.borrow_mut().push(format!("action:{key}")))
        .on_open_change(move |open, _, _| o.borrow_mut().push(format!("open:{open}")))
        .into_any_element()
    });
    (seen, cx)
}

fn right_click(cx: &mut VisualTestContext, x: f32, y: f32) {
    let at = point(px(x), px(y));
    cx.simulate_mouse_down(at, MouseButton::Right, Modifiers::none());
    cx.simulate_mouse_up(at, MouseButton::Right, Modifiers::none());
    frame(cx);
}

fn frame(cx: &mut VisualTestContext) {
    // Past any exit run (a closing menu stays mounted for its motion).
    cx.executor()
        .advance_clock(std::time::Duration::from_millis(300));
    for _ in 0..3 {
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
    }
}

fn panel(cx: &mut VisualTestContext) -> Option<Bounds<Pixels>> {
    cx.debug_bounds(PANEL)
}

#[gpui::test]
fn secondary_press_opens_at_the_pointer(cx: &mut TestAppContext) {
    let (seen, cx) = host(cx, false);
    frame(cx);
    assert!(panel(cx).is_none(), "closed until a secondary press");
    cx.simulate_click(point(px(100.), px(80.)), Modifiers::none());
    frame(cx);
    assert!(panel(cx).is_none(), "a primary press does not open it");

    right_click(cx, 100., 80.);
    let bounds = panel(cx).expect("the menu opened");
    assert_eq!(bounds.origin, point(px(100.), px(80.)));
    assert_eq!(seen.borrow().as_slice(), ["open:true"]);
}

#[gpui::test]
fn choosing_an_item_acts_and_closes(cx: &mut TestAppContext) {
    let (seen, cx) = host(cx, false);
    frame(cx);
    right_click(cx, 60., 40.);
    let bounds = panel(cx).unwrap();
    // The first row sits at the top of the panel, inside its padding.
    cx.simulate_click(bounds.origin + point(px(24.), px(18.)), Modifiers::none());
    frame(cx);
    assert!(
        seen.borrow().contains(&"action:copy".to_owned()),
        "{:?}",
        seen.borrow()
    );
    assert!(
        seen.borrow().contains(&"open:false".to_owned()),
        "{:?}",
        seen.borrow()
    );
    assert!(panel(cx).is_none());
}

#[gpui::test]
fn escape_and_outside_press_close(cx: &mut TestAppContext) {
    let (seen, cx) = host(cx, false);
    frame(cx);
    right_click(cx, 60., 40.);
    assert!(panel(cx).is_some());
    press(cx, "escape");
    frame(cx);
    assert!(panel(cx).is_none(), "Escape closes");

    right_click(cx, 60., 40.);
    assert!(panel(cx).is_some());
    cx.simulate_click(point(px(390.), px(290.)), Modifiers::none());
    frame(cx);
    assert!(panel(cx).is_none(), "an outside press closes");
    assert!(!seen.borrow().iter().any(|e| e.starts_with("action:")));
}

#[gpui::test]
fn disabled_ignores_the_secondary_press(cx: &mut TestAppContext) {
    let (seen, cx) = host(cx, true);
    frame(cx);
    right_click(cx, 60., 40.);
    assert!(panel(cx).is_none());
    assert!(seen.borrow().is_empty());
}

/// A context menu whose area holds one focusable child, for the keyboard
/// paths. Returns the child's focus handle.
fn keyboard_host(
    cx: &mut TestAppContext,
    disabled: bool,
) -> (Events, gpui::FocusHandle, &mut VisualTestContext) {
    still();
    let seen = events();
    let s = seen.clone();
    let child_focus = cx.update(|cx| cx.focus_handle());
    let focus = child_focus.clone();
    let cx = open_host(cx, move || {
        let (a, o) = (s.clone(), s.clone());
        // Inset from the window edge, past the positioner's edge margin.
        gpui::div()
            .p(px(40.))
            .child(
                ContextMenu::new(
                    "kctx",
                    gpui::div()
                        .w(px(400.))
                        .h(px(300.))
                        .p(px(40.))
                        .child(
                            gpui::div()
                                .id("kctx-child")
                                .track_focus(&focus)
                                .w(px(80.))
                                .h(px(24.))
                                .debug_selector(|| "kctx-child".into()),
                        )
                        .debug_selector(|| "kctx-area".into()),
                    vec![
                        MenuItem::new("copy", "Copy"),
                        MenuItem::new("paste", "Paste"),
                    ],
                )
                .is_disabled(disabled)
                .on_action(move |key, _, _| a.borrow_mut().push(format!("action:{key}")))
                .on_open_change(move |open, _, _| o.borrow_mut().push(format!("open:{open}"))),
            )
            .into_any_element()
    });
    (seen, child_focus, cx)
}

fn focus(cx: &mut VisualTestContext, handle: &gpui::FocusHandle) {
    let handle = handle.clone();
    cx.update(|window, cx| window.focus(&handle, cx));
    frame(cx);
}

#[gpui::test]
fn shift_f10_opens_at_the_area_with_the_first_item_focused(cx: &mut TestAppContext) {
    let (seen, child, cx) = keyboard_host(cx, false);
    frame(cx);
    focus(cx, &child);
    press(cx, "f10");
    frame(cx);
    assert!(panel(cx).is_none(), "F10 alone is not the context-menu key");

    press(cx, "shift-f10");
    frame(cx);
    let area = cx.debug_bounds("kctx-area").expect("area laid out");
    let bounds = panel(cx).expect("Shift+F10 opened the menu");
    assert_eq!(bounds.origin, area.origin, "anchored at the area's corner");
    assert_eq!(seen.borrow().as_slice(), ["open:true"]);

    // The first item holds the focus, so Enter chooses it without an arrow.
    press(cx, "enter");
    frame(cx);
    assert!(panel(cx).is_none());
    assert!(
        seen.borrow().contains(&"action:copy".to_owned()),
        "{:?}",
        seen.borrow()
    );
    let refocused = cx.update(|window, _| child.is_focused(window));
    assert!(refocused, "dismissal hands the focus back to the child");
}

#[gpui::test]
fn shift_f10_opens_below_a_focused_herogpui_button(cx: &mut TestAppContext) {
    still();
    let cx = open_host(cx, move || {
        gpui::div()
            .p(px(40.))
            .child(ContextMenu::new(
                "button-context-menu",
                gpui::div()
                    .w(px(400.))
                    .h(px(300.))
                    .p(px(40.))
                    .debug_selector(|| "button-context-area".into())
                    .child(Button::new("context-button").label("Actions").w(px(120.))),
                vec![MenuItem::new("copy", "Copy")],
            ))
            .into_any_element()
    });
    frame(cx);
    press(cx, "tab");
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    let area = cx.debug_bounds("button-context-area").unwrap();
    let menu = panel(cx).expect("keyboard menu opened");
    assert_eq!(menu.left(), area.left() + px(40.));
    assert_eq!(menu.top(), area.top() + px(76.));
}

#[gpui::test]
fn shift_f10_opens_below_a_focused_breadcrumb(cx: &mut TestAppContext) {
    still();
    let cx = open_host(cx, move || {
        gpui::div()
            .p(px(40.))
            .child(ContextMenu::new(
                "crumb-context-menu",
                gpui::div()
                    .w(px(400.))
                    .h(px(300.))
                    .p(px(40.))
                    .debug_selector(|| "crumb-context-area".into())
                    .child(Breadcrumbs::new(vec![
                        Crumb::new("Build"),
                        Crumb::new("Live"),
                    ])),
                vec![MenuItem::new("copy", "Copy")],
            ))
            .into_any_element()
    });
    frame(cx);
    press(cx, "tab");
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    let area = cx.debug_bounds("crumb-context-area").unwrap();
    let menu = panel(cx).expect("keyboard menu opened");
    assert_eq!(menu.left(), area.left() + px(40.));
    assert_eq!(menu.top(), area.top() + px(60.));
}

#[gpui::test]
fn shift_f10_opens_below_a_focused_color_area(cx: &mut TestAppContext) {
    still();
    let cx = open_host(cx, move || {
        gpui::div()
            .p(px(40.))
            .child(ContextMenu::new(
                "color-context-menu",
                gpui::div()
                    .w(px(400.))
                    .h(px(300.))
                    .p(px(40.))
                    .debug_selector(|| "color-context-area".into())
                    .child(
                        ColorArea::new("context-color", PickerColor::hsb(210., 0.5, 0.5))
                            .size(px(120.), px(80.)),
                    ),
                vec![MenuItem::new("copy", "Copy")],
            ))
            .into_any_element()
    });
    frame(cx);
    press(cx, "tab");
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    let area = cx.debug_bounds("color-context-area").unwrap();
    let menu = panel(cx).expect("keyboard menu opened");
    assert_eq!(menu.left(), area.left() + px(40.));
    assert_eq!(menu.top(), area.top() + px(120.));
}

#[gpui::test]
fn shift_f10_opens_below_a_focused_menu_bar_trigger(cx: &mut TestAppContext) {
    still();
    let cx = open_host(cx, move || {
        gpui::div()
            .p(px(40.))
            .child(ContextMenu::new(
                "menu-bar-context-menu",
                gpui::div()
                    .w(px(400.))
                    .h(px(300.))
                    .p(px(40.))
                    .child(MenuBar::new(
                        "context-menu-bar",
                        vec![MenuBarMenu::new(
                            "file",
                            "File",
                            vec![MenuItem::new("new", "New")],
                        )],
                    )),
                vec![MenuItem::new("copy", "Copy")],
            ))
            .into_any_element()
    });
    frame(cx);
    press(cx, "tab");
    frame(cx);
    let trigger = cx.debug_bounds("menu-bar-trigger-file").unwrap();
    press(cx, "shift-f10");
    frame(cx);
    let menu = panel(cx).expect("keyboard menu opened");
    assert_eq!(menu.left(), trigger.left());
    assert_eq!(menu.top(), trigger.bottom());
}

#[gpui::test]
fn shift_f10_uses_the_active_list_row_instead_of_the_list_box(cx: &mut TestAppContext) {
    still();
    let cx = open_host(cx, move || {
        gpui::div()
            .p(px(40.))
            .child(ContextMenu::new(
                "list-context-menu",
                gpui::div()
                    .w(px(400.))
                    .h(px(300.))
                    .p(px(40.))
                    .debug_selector(|| "list-context-area".into())
                    .child(
                        ListBox::new(
                            "list-context-list",
                            vec![
                                ListBoxItem::new("first", "First"),
                                ListBoxItem::new("second", "Second"),
                            ],
                        )
                        .w(px(220.)),
                    ),
                vec![MenuItem::new("copy", "Copy")],
            ))
            .into_any_element()
    });
    frame(cx);
    let area = cx.debug_bounds("list-context-area").unwrap();
    cx.simulate_click(area.origin + point(px(70.), px(62.)), Modifiers::none());
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    let area = cx.debug_bounds("list-context-area").unwrap();
    let menu = panel(cx).expect("keyboard menu opened");
    assert_eq!(menu.left(), area.left() + px(44.));
    assert_eq!(menu.top(), area.top() + px(80.));
}

#[gpui::test]
fn shift_f10_uses_the_active_tree_row(cx: &mut TestAppContext) {
    still();
    let cx = open_host(cx, move || {
        gpui::div()
            .p(px(40.))
            .child(ContextMenu::new(
                "tree-context-menu",
                gpui::div()
                    .w(px(400.))
                    .h(px(300.))
                    .p(px(40.))
                    .child(TreeView::new(
                        "context-tree",
                        vec![
                            TreeItem::new("first", "First"),
                            TreeItem::new("second", "Second"),
                        ],
                    )),
                vec![MenuItem::new("copy", "Copy")],
            ))
            .into_any_element()
    });
    frame(cx);
    press(cx, "tab");
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    let row = cx.debug_bounds("context-tree-row-first").unwrap();
    let menu = panel(cx).expect("keyboard menu opened");
    assert_eq!(menu.left(), row.left());
    assert_eq!(menu.top(), row.bottom());
}

#[gpui::test]
fn shift_f10_uses_the_active_table_row(cx: &mut TestAppContext) {
    still();
    let cx = open_host(cx, move || {
        gpui::div()
            .p(px(40.))
            .child(ContextMenu::new(
                "table-context-menu",
                gpui::div().w(px(400.)).h(px(300.)).p(px(40.)).child(
                    Table::new(vec!["Name".into(), "Role".into()])
                        .id("context-table")
                        .row(vec![
                            gpui::div().child("Alice").into_any_element(),
                            gpui::div().child("Developer").into_any_element(),
                        ]),
                ),
                vec![MenuItem::new("copy", "Copy")],
            ))
            .into_any_element()
    });
    frame(cx);
    press(cx, "tab");
    press(cx, "down");
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    let cell = cx.debug_bounds("table-row-track-0-0").unwrap();
    let menu = panel(cx).expect("keyboard menu opened");
    assert_eq!(menu.left(), cell.left());
    assert_eq!(menu.top(), cell.bottom());
}

#[gpui::test]
fn the_context_menu_key_opens_and_escape_restores_focus(cx: &mut TestAppContext) {
    let (seen, child, cx) = keyboard_host(cx, false);
    frame(cx);
    focus(cx, &child);
    press(cx, "menu");
    frame(cx);
    assert!(panel(cx).is_some(), "the ContextMenu key opens it");
    let in_child = cx.update(|window, _| child.is_focused(window));
    assert!(!in_child, "the menu took the focus");
    press(cx, "escape");
    frame(cx);
    assert!(panel(cx).is_none());
    let back = cx.update(|window, _| child.is_focused(window));
    assert!(back, "Escape hands the focus back");

    // The web spelling of the same key.
    press(cx, "contextmenu");
    frame(cx);
    assert!(panel(cx).is_some());
    assert_eq!(
        seen.borrow().as_slice(),
        ["open:true", "open:false", "open:true"]
    );
}

#[gpui::test]
fn modified_keys_do_not_open(cx: &mut TestAppContext) {
    let (_, child, cx) = keyboard_host(cx, false);
    frame(cx);
    focus(cx, &child);
    for keys in ["ctrl-shift-f10", "alt-shift-f10", "shift-menu"] {
        press(cx, keys);
        frame(cx);
        assert!(panel(cx).is_none(), "{keys} must not open the menu");
    }
}

#[gpui::test]
fn a_disabled_menu_ignores_the_keyboard(cx: &mut TestAppContext) {
    let (seen, child, cx) = keyboard_host(cx, true);
    frame(cx);
    focus(cx, &child);
    press(cx, "shift-f10");
    frame(cx);
    assert!(panel(cx).is_none(), "a disabled menu ignores the keyboard");
    assert!(seen.borrow().is_empty());
}

#[gpui::test]
fn a_primary_press_focuses_an_area_with_no_focusable_content(cx: &mut TestAppContext) {
    let (seen, cx) = host(cx, false);
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    assert!(
        panel(cx).is_none(),
        "nothing inside the area holds the focus yet"
    );
    cx.simulate_click(point(px(100.), px(80.)), Modifiers::none());
    frame(cx);
    press(cx, "shift-f10");
    frame(cx);
    assert!(panel(cx).is_some(), "the press focused the area itself");
    assert_eq!(seen.borrow().as_slice(), ["open:true"]);
}

fn styled_host(cx: &mut TestAppContext, seen: Events) -> &mut VisualTestContext {
    still();
    open_host(cx, move || {
        let seen = seen.clone();
        ContextMenu::new(
            "styled-ctx",
            gpui::div().w(px(400.)).h(px(300.)),
            vec![MenuItem::new("copy", "C"), MenuItem::new("paste", "P")],
        )
        .recipe("accent")
        .item_content(|key, _| {
            let key = key.clone();
            gpui::div()
                .w(px(20.))
                .h(px(20.))
                .debug_selector(move || format!("label-{key}"))
                .into_any_element()
        })
        .item_start_content(move |key, state| {
            seen.borrow_mut()
                .push(format!("{key}:focused={}", state.is_focused));
            let key = key.clone();
            (key.as_ref() == "copy").then(|| {
                gpui::div()
                    .w(px(12.))
                    .h(px(12.))
                    .debug_selector(move || format!("start-{key}"))
                    .into_any_element()
            })
        })
        .into_any_element()
    })
}

#[gpui::test]
fn a_recipe_styles_the_context_menu_panel(cx: &mut TestAppContext) {
    use herogpui_theme::{set_theme, ComponentColor, ComponentTheme, ComponentThemes, MenuStyle};

    let cx = styled_host(cx, events());
    right_click(cx, 10., 10.);
    assert_eq!(
        panel(cx).expect("the menu opened").size.width,
        px(220.),
        "a recipe the theme does not define adds no override"
    );

    let hover = gpui::rgb(0x2255aa).into();
    cx.update(|window, cx| {
        set_theme(
            herogpui_theme::Theme::builder("app", herogpui_theme::Theme::light())
                .components(
                    ComponentThemes::default().menu(
                        ComponentTheme::default().recipe(
                            "accent",
                            MenuStyle::default()
                                .panel_min_width(px(128.))
                                .row_hover_bg(ComponentColor::Literal(hover)),
                        ),
                    ),
                )
                .build(),
            cx,
        );
        window.refresh();
    });
    frame(cx);
    assert_eq!(panel(cx).expect("still open").size.width, px(128.));

    let row = cx.debug_bounds("label-copy").expect("row laid out");
    cx.simulate_mouse_move(row.center(), None, Modifiers::none());
    let painted = harness::painted(cx);
    assert!(
        !painted.filled(hover).is_empty(),
        "the recipe's row hover fill reaches the hovered row"
    );
}

#[gpui::test]
fn item_start_content_leads_the_row_and_sees_its_state(cx: &mut TestAppContext) {
    let seen = events();
    let cx = styled_host(cx, seen.clone());
    right_click(cx, 10., 10.);

    let start = cx
        .debug_bounds("start-copy")
        .expect("leading element drawn");
    let label = cx.debug_bounds("label-copy").expect("label drawn");
    assert!(start.right() <= label.left(), "the element leads the label");
    assert!(start.top() >= label.top() && start.bottom() <= label.bottom() + px(4.));
    assert!(
        cx.debug_bounds("start-paste").is_none(),
        "a row whose closure returns None draws no leading element"
    );

    seen.borrow_mut().clear();
    press(cx, "down");
    frame(cx);
    assert!(
        seen.borrow()
            .iter()
            .any(|entry| entry == "copy:focused=true"),
        "the closure receives the row's focus: {:?}",
        seen.borrow()
    );
}