gpui-deck 0.0.4

Headless GPUI primitives with application-owned presentation.
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
//! Window content and modal focus navigation.
//! Modified for GPUI Deck: removed styled-layer plugins and rich-text hosting.
use crate::StyledExt;
use gpui::{
    Action, AnyView, App, Context, InteractiveElement, IntoElement, KeyBinding, ParentElement,
    Render, StyleRefinement, Styled, Subscription, Window, actions, div,
};

actions!(root, [Tab, TabPrev]);
const CONTEXT: &str = "Root";

/// Scan at most one cycle of the rendered tab order, preserving containment
/// regardless of how many controls exist behind a modal. GPUI exposes traversal
/// but not candidate enumeration. This scan is synchronous: only the final
/// focus path is published at the next draw, not the background candidates.
fn advance_focus(window: &mut Window, cx: &mut App, advance: fn(&mut Window, &mut App)) {
    let Some(container) = crate::active_focus_trap(window, cx) else {
        advance(window, cx);
        return;
    };

    advance(window, cx);
    // GPUI's tab order can cycle short of the whole window (a stop whose
    // previous stop is itself), so the walk ends at the first repeated stop,
    // not only on a return to the one it began with.
    let mut visited = Vec::new();
    while !container.contains_focused(window, cx) {
        let focused = window.focused(cx);
        if visited.contains(&focused) {
            // No tab stop in the trap is reachable. Its own handle remains a
            // safe focus target even when excluded from ordinary tab order.
            container.focus(window, cx);
            break;
        }
        visited.push(focused);
        advance(window, cx);
    }
}

pub(crate) fn init(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("tab", Tab, Some(CONTEXT)),
        KeyBinding::new("shift-tab", TabPrev, Some(CONTEXT)),
    ]);
}

/// The window's content and overlay host, independent of any styled component library.
pub struct Root {
    view: AnyView,
    style: StyleRefinement,
    /// Runs Tab and Shift-Tab while nothing in the window is focused. GPUI
    /// then dispatches from the window's root element, above this root's key
    /// context, so the context bindings match nothing there.
    _unfocused_tab: Subscription,
}

impl Root {
    pub fn new(view: impl Into<AnyView>, window: &mut Window, cx: &mut Context<Self>) -> Self {
        #[cfg(all(target_os = "macos", not(test)))]
        crate::install_window_hit_test_forwarder(window);
        let window_handle = window.window_handle();
        let unfocused_tab = cx.observe_keystrokes(move |_, event, window, cx| {
            // Only a key that no binding took, in this window, with nothing
            // focused, so an application binding for Tab still wins.
            if event.action.is_some()
                || window.window_handle() != window_handle
                || window.focused(cx).is_some()
            {
                return;
            }
            // Read the keymap so that rebinding the actions carries over.
            let bound_to = |action: &dyn Action, cx: &App| {
                cx.key_bindings()
                    .borrow()
                    .bindings_for_action(action)
                    .any(|binding| {
                        binding.match_keystrokes(std::slice::from_ref(&event.keystroke))
                            == Some(false)
                    })
            };
            if bound_to(&Tab, cx) {
                advance_focus(window, cx, Window::focus_next);
            } else if bound_to(&TabPrev, cx) {
                advance_focus(window, cx, Window::focus_prev);
            }
        });
        Self {
            view: view.into(),
            style: StyleRefinement::default(),
            _unfocused_tab: unfocused_tab,
        }
    }

    /// The original application content entity.
    pub fn view(&self) -> &AnyView {
        &self.view
    }

    pub fn read<'a>(window: &'a Window, cx: &'a App) -> &'a Self {
        window
            .root::<Self>()
            .flatten()
            .expect("window must have a GPUI Deck Root")
            .read(cx)
    }
    pub fn update<R>(
        window: &mut Window,
        cx: &mut App,
        f: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>) -> R,
    ) -> R {
        let root = window
            .root::<Self>()
            .flatten()
            .expect("window must have a GPUI Deck Root");
        root.update(cx, |root, cx| f(root, window, cx))
    }
    fn on_action_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
        advance_focus(window, cx, Window::focus_next);
    }

    fn on_action_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
        advance_focus(window, cx, Window::focus_prev);
    }
}
impl Styled for Root {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}
impl Render for Root {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        #[cfg(feature = "test-support")]
        crate::test_support::begin_frame(window);
        #[cfg(not(feature = "test-support"))]
        let _ = window;
        div()
            .id("root")
            .key_context(CONTEXT)
            .on_action(cx.listener(Self::on_action_tab))
            .on_action(cx.listener(Self::on_action_tab_prev))
            .relative()
            .size_full()
            .child(self.view.clone())
            .refine_style(&self.style)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::FocusTrapElement as _;
    use gpui::{AppContext, FocusHandle, Subscription, TestAppContext, VisualTestContext, px};
    use std::{cell::Cell, rc::Rc};

    struct TrapContent {
        background: Vec<FocusHandle>,
        container: FocusHandle,
        controls: Vec<FocusHandle>,
        _focus_subscriptions: Vec<Subscription>,
    }

    impl Render for TrapContent {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .tab_group()
                .size_full()
                .children(self.background.iter().enumerate().map(|(index, handle)| {
                    div()
                        .id(("background", index))
                        .track_focus(handle)
                        .tab_index(0)
                        .size(px(1.))
                }))
                .child(
                    div()
                        .id("trap")
                        .track_focus(&self.container)
                        .tab_stop(false)
                        .children(self.controls.iter().enumerate().map(|(index, handle)| {
                            div()
                                .id(("control", index))
                                .track_focus(handle)
                                .tab_index(0)
                                .size(px(1.))
                        }))
                        .focus_trap("modal", &self.container),
                )
        }
    }

    fn trap_harness(
        cx: &mut TestAppContext,
        control_count: usize,
    ) -> (
        &mut VisualTestContext,
        FocusHandle,
        Vec<FocusHandle>,
        Vec<FocusHandle>,
        Rc<Cell<usize>>,
    ) {
        cx.update(crate::init);
        let (container, controls, background) = cx.update(|cx| {
            (
                cx.focus_handle(),
                (0..control_count)
                    .map(|_| cx.focus_handle().tab_stop(true))
                    .collect::<Vec<_>>(),
                // Regression: traversing past the modal must cross more than
                // the former 100-attempt limit before reaching its other end.
                (0..256)
                    .map(|_| cx.focus_handle().tab_stop(true))
                    .collect::<Vec<_>>(),
            )
        });
        let background_focuses = Rc::new(Cell::new(0));
        let (_, cx) = cx.add_window_view({
            let container = container.clone();
            let controls = controls.clone();
            let background = background.clone();
            let background_focuses = background_focuses.clone();
            move |window, cx| {
                let content = cx.new(|cx| {
                    let subscriptions = background
                        .iter()
                        .map(|handle| {
                            let focuses = background_focuses.clone();
                            cx.on_focus(handle, window, move |_, _, _| {
                                focuses.set(focuses.get() + 1)
                            })
                        })
                        .collect();
                    TrapContent {
                        background,
                        container,
                        controls,
                        _focus_subscriptions: subscriptions,
                    }
                });
                Root::new(content, window, cx)
            }
        });
        cx.update(|window, _| window.activate_window());
        cx.executor().run_until_parked();
        cx.update(|window, cx| window.draw(cx).clear(cx));
        (cx, container, controls, background, background_focuses)
    }

    fn assert_trapped_focus(
        cx: &mut VisualTestContext,
        container: &FocusHandle,
        expected: &FocusHandle,
    ) {
        cx.update(|window, cx| {
            window.draw(cx).clear(cx);
            assert_eq!(window.focused(cx).as_ref(), Some(expected));
            assert!(container.contains_focused(window, cx));
        });
    }

    #[gpui::test]
    fn focus_trap_wraps_forward_past_more_than_100_background_stops(cx: &mut TestAppContext) {
        let (cx, container, controls, _, background_focuses) = trap_harness(cx, 2);
        cx.update(|window, cx| {
            controls[1].focus(window, cx);
            window.draw(cx).clear(cx);
        });

        cx.dispatch_action(Tab);
        assert_trapped_focus(cx, &container, &controls[0]);
        cx.dispatch_action(Tab);
        assert_trapped_focus(cx, &container, &controls[1]);
        assert_eq!(background_focuses.get(), 0);
    }

    #[gpui::test]
    fn focus_trap_wraps_backward_past_more_than_100_background_stops(cx: &mut TestAppContext) {
        let (cx, container, controls, _, background_focuses) = trap_harness(cx, 2);
        cx.update(|window, cx| {
            controls[0].focus(window, cx);
            window.draw(cx).clear(cx);
        });

        cx.dispatch_action(TabPrev);
        assert_trapped_focus(cx, &container, &controls[1]);
        cx.dispatch_action(TabPrev);
        assert_trapped_focus(cx, &container, &controls[0]);
        assert_eq!(background_focuses.get(), 0);
    }

    #[gpui::test]
    fn focus_trap_without_tab_stops_keeps_its_container_focused(cx: &mut TestAppContext) {
        let (cx, container, _, _, background_focuses) = trap_harness(cx, 0);
        cx.update(|window, cx| {
            container.focus(window, cx);
            window.draw(cx).clear(cx);
        });

        cx.dispatch_action(Tab);
        assert_trapped_focus(cx, &container, &container);
        cx.dispatch_action(TabPrev);
        assert_trapped_focus(cx, &container, &container);
        assert_eq!(background_focuses.get(), 0);
    }

    thread_local! {
        static SCRIPTED_STOPS: std::cell::RefCell<Vec<FocusHandle>> =
            const { std::cell::RefCell::new(Vec::new()) };
    }

    /// Moves focus to the next scripted stop, in place of `focus_prev`. Running
    /// out fails the test, so a search that never stops cannot hang it.
    fn scripted_advance(window: &mut Window, cx: &mut App) {
        SCRIPTED_STOPS
            .with(|stops| stops.borrow_mut().pop())
            .expect("the search kept advancing after a stop repeated")
            .focus(window, cx);
    }

    #[gpui::test]
    fn focus_trap_search_ends_at_a_short_cycle_on_its_container(cx: &mut TestAppContext) {
        let (cx, container, controls, background, _) = trap_harness(cx, 2);
        cx.update(|window, cx| {
            controls[0].focus(window, cx);
            window.draw(cx).clear(cx);
        });
        // A tab order in which the second stop is its own neighbor never
        // returns to the first. Popped from the end: first, second, second.
        let (first, second) = (background[0].clone(), background[1].clone());
        SCRIPTED_STOPS.with(|stops| *stops.borrow_mut() = vec![second.clone(), second, first]);

        cx.update(|window, cx| advance_focus(window, cx, scripted_advance));
        assert_trapped_focus(cx, &container, &container);
        assert!(SCRIPTED_STOPS.with(|stops| stops.borrow().is_empty()));
    }

    #[gpui::test]
    fn inactive_focus_trap_does_not_capture_background_navigation(cx: &mut TestAppContext) {
        let (cx, _, _, background, background_focuses) = trap_harness(cx, 2);
        cx.update(|window, cx| {
            background[0].focus(window, cx);
            window.draw(cx).clear(cx);
        });
        // Prove that the observers used by the containment regressions really
        // receive native focus notifications when a background control is used.
        assert_eq!(background_focuses.get(), 1);

        cx.dispatch_action(Tab);
        cx.update(|window, cx| {
            window.draw(cx).clear(cx);
            assert_eq!(window.focused(cx), Some(background[1].clone()));
        });
        cx.dispatch_action(TabPrev);
        cx.update(|window, cx| {
            window.draw(cx).clear(cx);
            assert_eq!(window.focused(cx), Some(background[0].clone()));
        });
        assert_eq!(background_focuses.get(), 3);
    }

    struct Stops(Vec<FocusHandle>);

    impl Render for Stops {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .tab_group()
                .size_full()
                .children(self.0.iter().enumerate().map(|(index, handle)| {
                    div()
                        .id(("stop", index))
                        .track_focus(handle)
                        .tab_index(0)
                        .size(px(10.))
                }))
        }
    }

    actions!(root_test, [AppTab]);

    #[gpui::test]
    fn tab_and_shift_tab_reach_controls_while_nothing_is_focused(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let stops = cx.update(|cx| {
            (0..3)
                .map(|_| cx.focus_handle().tab_stop(true))
                .collect::<Vec<_>>()
        });
        let (_, cx) = cx.add_window_view({
            let stops = stops.clone();
            move |window, cx| Root::new(cx.new(|_| Stops(stops)), window, cx)
        });
        let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
        draw(cx);
        cx.update(|window, cx| assert!(window.focused(cx).is_none()));

        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert_eq!(window.focused(cx), Some(stops[0].clone())));

        cx.update(|window, cx| window.blur(cx));
        draw(cx);
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        cx.update(|window, cx| assert_eq!(window.focused(cx), Some(stops[2].clone())));

        // An application binding for Tab outside any context takes the key.
        let ran = Rc::new(Cell::new(false));
        cx.update({
            let ran = ran.clone();
            move |window, cx| {
                cx.bind_keys([KeyBinding::new("tab", AppTab, None)]);
                cx.on_action(move |_: &AppTab, _| ran.set(true));
                window.blur(cx);
            }
        });
        draw(cx);
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
        assert!(ran.get());
    }

    mod nested_traps {
        use super::*;

        struct NestedTraps {
            containers: Vec<FocusHandle>,
            controls: Vec<[FocusHandle; 2]>,
            depth: usize,
        }

        impl Render for NestedTraps {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                let mut child = div().into_any_element();
                for index in (0..self.depth).rev() {
                    let control = |side: usize| {
                        div()
                            .id(("nested-control", index * 2 + side))
                            .track_focus(&self.controls[index][side])
                            .tab_index(0)
                            .size(px(10.))
                    };
                    child = div()
                        .tab_stop(false)
                        .child(control(0))
                        .child(child)
                        .child(control(1))
                        .focus_trap(("nested-trap", index), &self.containers[index])
                        .into_any_element();
                }
                div().tab_group().size_full().child(child)
            }
        }

        #[gpui::test]
        fn nested_traps_keep_the_innermost_scope_across_close_and_reopen(cx: &mut TestAppContext) {
            cx.update(crate::init);
            let (containers, controls) = cx.update(|cx| {
                (
                    (0..6).map(|_| cx.focus_handle()).collect::<Vec<_>>(),
                    (0..6)
                        .map(|_| {
                            [
                                cx.focus_handle().tab_stop(true),
                                cx.focus_handle().tab_stop(true),
                            ]
                        })
                        .collect::<Vec<_>>(),
                )
            });
            let (root, cx) = cx.add_window_view({
                let containers = containers.clone();
                let controls = controls.clone();
                move |window, cx| {
                    let view = cx.new(|_| NestedTraps {
                        containers,
                        controls,
                        depth: 6,
                    });
                    Root::new(view, window, cx)
                }
            });
            let view = root.read_with(cx, |root, _| {
                root.view.clone().downcast::<NestedTraps>().unwrap()
            });

            // Retain every container handle while inner scopes disappear and
            // return. Rendered containment, not registration order or ownership
            // lifetime, must decide which remaining scope handles Tab.
            for depth in [6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6] {
                view.update(cx, |view, cx| {
                    view.depth = depth;
                    cx.notify();
                });
                let index = depth - 1;
                cx.update(|window, cx| {
                    controls[index][1].focus(window, cx);
                    window.draw(cx).clear(cx);
                });
                cx.dispatch_action(Tab);
                assert_trapped_focus(cx, &containers[index], &controls[index][0]);
                cx.dispatch_action(TabPrev);
                assert_trapped_focus(cx, &containers[index], &controls[index][1]);
            }
        }
    }
}