BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / popover.rs

popover.rs

popover.rs 19.6 KiB Download Raw
1use std::rc::Rc;
2
3use gpui::{
4 Anchor, AnyElement, App, Context, DismissEvent, ElementId, EventEmitter, FocusHandle,
5 Focusable, InteractiveElement as _, IntoElement, KeyBinding, MouseButton, ParentElement as _,
6 Render, RenderOnce, Role, StatefulInteractiveElement as _, StyleRefinement, Styled,
7 Subscription, Window, div, prelude::FluentBuilder as _,
8};
9
10use crate::{
11 DeferredPopover, GlobalState, Popup, ResolvedPosition, Selectable, StyledExt as _,
12 actions::{Cancel, Confirm},
13};
14
15const CONTEXT: &str = "Popover";
16
17pub(crate) fn init(cx: &mut App) {
18 cx.bind_keys([
19 KeyBinding::new("escape", Cancel, Some(CONTEXT)),
20 KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
21 KeyBinding::new("space", Confirm { secondary: false }, Some(CONTEXT)),
22 ]);
23}
24
25type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
26
27/// State and focus lifecycle for an unstyled popover.
28///
29/// Applications own trigger/content construction, positioning, appearance, and
30/// animation. This state owns the controlled open lifecycle, dismissal, focus
31/// capture and restoration, and deferred-popup registration.
32pub struct PopoverState {
33 focus_handle: FocusHandle,
34 tracked_focus_handle: Option<FocusHandle>,
35 previous_focus_handle: Option<FocusHandle>,
36 open: bool,
37 on_open_change: Option<OpenChangeHandler>,
38 dismiss_subscription: Option<Subscription>,
39 /// Held while open, so that a state collected without being closed — this
40 /// lives in element state — takes its registration with it.
41 deferred_context: Option<DeferredPopover>,
42}
43
44impl PopoverState {
45 pub fn new(default_open: bool, cx: &mut App) -> Self {
46 Self {
47 focus_handle: cx.focus_handle(),
48 tracked_focus_handle: None,
49 previous_focus_handle: None,
50 open: default_open,
51 on_open_change: None,
52 dismiss_subscription: None,
53 deferred_context: None,
54 }
55 }
56
57 pub fn is_open(&self) -> bool {
58 self.open
59 }
60
61 pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
62 if self.open {
63 self.toggle_open(window, cx);
64 }
65 }
66
67 pub fn show(&mut self, window: &mut Window, cx: &mut Context<Self>) {
68 if !self.open {
69 self.toggle_open(window, cx);
70 }
71 }
72
73 #[doc(hidden)]
74 pub fn set_open(&mut self, open: bool, cx: &mut Context<Self>) {
75 self.open = open;
76 self.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx));
77 }
78
79 #[doc(hidden)]
80 pub fn sync_open(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
81 self.transition_to(open, false, window, cx);
82 }
83
84 #[doc(hidden)]
85 pub fn toggle_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
86 self.transition_to(!self.open, true, window, cx);
87 }
88
89 fn transition_to(
90 &mut self,
91 opening: bool,
92 announce: bool,
93 window: &mut Window,
94 cx: &mut Context<Self>,
95 ) {
96 if self.open == opening {
97 return;
98 }
99 if opening {
100 self.previous_focus_handle = window.focused(cx);
101 }
102 self.set_open(opening, cx);
103
104 if self.open {
105 // Weak: the subscription is stored on this state, so a strong
106 // handle would keep the state, and its deferred-popover
107 // registration, alive after its trigger is gone.
108 let state = cx.entity().downgrade();
109 self.tracked_focus_handle
110 .clone()
111 .unwrap_or_else(|| self.focus_handle.clone())
112 .focus(window, cx);
113
114 self.dismiss_subscription =
115 Some(
116 window.subscribe(&cx.entity(), cx, move |_, _: &DismissEvent, window, cx| {
117 _ = state.update(cx, |state, cx| state.dismiss(window, cx));
118 window.refresh();
119 }),
120 );
121 } else {
122 self.dismiss_subscription = None;
123 if let Some(previous) = self.previous_focus_handle.take() {
124 if self.focus_handle.contains_focused(window, cx) {
125 previous.focus(window, cx);
126 }
127 }
128 }
129
130 if announce && let Some(callback) = self.on_open_change.as_ref() {
131 callback(&opening, window, cx);
132 }
133 cx.notify();
134 }
135
136 #[doc(hidden)]
137 pub fn track_focus(&mut self, focus_handle: Option<FocusHandle>) {
138 self.tracked_focus_handle = focus_handle;
139 }
140
141 #[doc(hidden)]
142 pub fn set_on_open_change(&mut self, handler: Option<OpenChangeHandler>) {
143 self.on_open_change = handler;
144 }
145
146 #[doc(hidden)]
147 pub fn on_action_cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
148 self.dismiss(window, cx);
149 }
150}
151
152impl Focusable for PopoverState {
153 fn focus_handle(&self, _: &App) -> FocusHandle {
154 self.focus_handle.clone()
155 }
156}
157
158impl Render for PopoverState {
159 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
160 div()
161 }
162}
163
164impl EventEmitter<DismissEvent> for PopoverState {}
165
166type TriggerBuilder = Box<dyn FnOnce(bool, &Window, &App) -> AnyElement>;
167type ContentBuilder =
168 Box<dyn FnOnce(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> AnyElement>;
169
170/// An unstyled popover owning trigger interaction, open state, dismissal, and focus.
171#[derive(IntoElement)]
172pub struct Popover {
173 id: ElementId,
174 style: StyleRefinement,
175 anchor: Anchor,
176 offset: gpui::Pixels,
177 on_position: Option<Box<dyn Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>)>>,
178 default_open: bool,
179 open: Option<bool>,
180 tracked_focus_handle: Option<FocusHandle>,
181 trigger: Option<TriggerBuilder>,
182 content: Option<ContentBuilder>,
183 mouse_button: MouseButton,
184 overlay_closable: bool,
185 on_open_change: Option<OpenChangeHandler>,
186}
187
188impl Popover {
189 pub fn new(id: impl Into<ElementId>) -> Self {
190 Self {
191 id: id.into(),
192 style: StyleRefinement::default(),
193 anchor: Anchor::TopLeft,
194 offset: gpui::px(0.),
195 on_position: None,
196 default_open: false,
197 open: None,
198 tracked_focus_handle: None,
199 trigger: None,
200 content: None,
201 mouse_button: MouseButton::Left,
202 overlay_closable: true,
203 on_open_change: None,
204 }
205 }
206
207 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
208 self.anchor = anchor.into();
209 self
210 }
211
212 /// Gap from the trigger along the anchor's outward direction, zero by default.
213 pub fn offset(mut self, offset: gpui::Pixels) -> Self {
214 self.offset = offset;
215 self
216 }
217
218 /// Observe geometry to supply presentation such as a pointer arrow.
219 pub fn on_position(
220 mut self,
221 callback: impl Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>) + 'static,
222 ) -> Self {
223 self.on_position = Some(Box::new(callback));
224 self
225 }
226
227 pub fn mouse_button(mut self, mouse_button: MouseButton) -> Self {
228 self.mouse_button = mouse_button;
229 self
230 }
231
232 pub fn trigger<T>(mut self, trigger: T) -> Self
233 where
234 T: Selectable + IntoElement + 'static,
235 {
236 self.trigger = Some(Box::new(|is_open, _, _| {
237 let open = trigger.is_open();
238 trigger.open(open || is_open).into_any_element()
239 }));
240 self
241 }
242
243 /// Supplies a trigger builder for higher-level presentation facades.
244 #[doc(hidden)]
245 pub fn trigger_with(
246 mut self,
247 trigger: impl FnOnce(bool, &Window, &App) -> AnyElement + 'static,
248 ) -> Self {
249 self.trigger = Some(Box::new(trigger));
250 self
251 }
252
253 pub fn default_open(mut self, open: bool) -> Self {
254 self.default_open = open;
255 self
256 }
257
258 pub fn open(mut self, open: bool) -> Self {
259 self.open = Some(open);
260 self
261 }
262
263 pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
264 self.tracked_focus_handle = Some(handle.clone());
265 self
266 }
267
268 pub fn overlay_closable(mut self, closable: bool) -> Self {
269 self.overlay_closable = closable;
270 self
271 }
272
273 pub fn on_open_change(
274 mut self,
275 callback: impl Fn(&bool, &mut Window, &mut App) + 'static,
276 ) -> Self {
277 self.on_open_change = Some(Rc::new(callback));
278 self
279 }
280
281 pub fn content<F, E>(mut self, content: F) -> Self
282 where
283 E: IntoElement,
284 F: FnOnce(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> E + 'static,
285 {
286 self.content = Some(Box::new(move |state, window, cx| {
287 content(state, window, cx).into_any_element()
288 }));
289 self
290 }
291}
292
293/// Styles the trigger container: the element that takes part in the parent
294/// layout and whose bounds the popup is anchored to.
295impl Styled for Popover {
296 fn style(&mut self) -> &mut StyleRefinement {
297 &mut self.style
298 }
299}
300
301impl RenderOnce for Popover {
302 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
303 let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| {
304 PopoverState::new(self.default_open, cx)
305 });
306 state.update(cx, |state, cx| {
307 state.track_focus(self.tracked_focus_handle);
308 state.set_on_open_change(self.on_open_change);
309 if let Some(open) = self.open {
310 state.sync_open(open, window, cx);
311 }
312 });
313
314 let open = state.read(cx).is_open();
315 let focus_handle = state.read(cx).focus_handle(cx);
316 let Some(trigger) = self.trigger else {
317 return div().id("empty").into_any_element();
318 };
319 let parent_view_id = window.current_view();
320 let popup = Popup::new(self.id, trigger(open, window, cx))
321 .refine_style(&self.style)
322 .anchor(self.anchor)
323 .offset(self.offset)
324 .when_some(self.on_position, |this, callback| {
325 this.on_position(callback)
326 })
327 .key_context(CONTEXT)
328 .on_action({
329 let state = state.clone();
330 move |_: &Confirm, window, cx| {
331 if state.read(cx).focus_handle.contains_focused(window, cx) {
332 cx.propagate();
333 return;
334 }
335 state.update(cx, |state, cx| state.toggle_open(window, cx));
336 cx.notify(parent_view_id);
337 }
338 })
339 .on_mouse_down(self.mouse_button, {
340 let state = state.clone();
341 move |_, window, cx| {
342 cx.stop_propagation();
343 state.update(cx, |state, cx| {
344 if state.is_open() == open {
345 state.toggle_open(window, cx);
346 }
347 });
348 cx.notify(parent_view_id);
349 }
350 });
351 if !open {
352 return popup.into_any_element();
353 }
354
355 let content = div()
356 .id("content")
357 // A popover surface is a non-modal dialog: it takes focus and is
358 // dismissed with Escape, which is what this role tells assistive
359 // technology to expect.
360 .role(Role::Dialog)
361 .occlude()
362 .tab_group()
363 .track_focus(&focus_handle)
364 .key_context(CONTEXT)
365 .on_action(window.listener_for(&state, PopoverState::on_action_cancel))
366 .when_some(self.content, |this, content| {
367 this.child(state.update(cx, |state, cx| (content)(state, window, cx)))
368 })
369 .when(self.overlay_closable, |this| {
370 this.on_mouse_down_out({
371 let state = state.clone();
372 move |_, window, cx| {
373 state.update(cx, |state, cx| state.dismiss(window, cx));
374 cx.notify(parent_view_id);
375 }
376 })
377 });
378 popup.content(content).into_any_element()
379 }
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385 use gpui::{AppContext as _, Context, Render, point, px};
386 use std::{cell::RefCell, rc::Rc};
387
388 /// Popover state lives in element state, which is collected as soon as it
389 /// stops being rendered — a trigger scrolled out of a virtual list, a panel
390 /// closed with its menu open. A registration that outlived it would leave
391 /// the application believing a popup is open for the rest of the session.
392 #[gpui::test]
393 fn a_state_dropped_while_open_closes_the_deferred_context(cx: &mut gpui::TestAppContext) {
394 let state = cx.update(|cx| {
395 GlobalState::init(cx);
396 let state = cx.new(|cx| PopoverState::new(false, cx));
397 state.update(cx, |state, cx| state.set_open(true, cx));
398 assert!(GlobalState::is_in_deferred_context(cx));
399 state
400 });
401
402 cx.update(|_| drop(state));
403 cx.update(|cx| assert!(!GlobalState::is_in_deferred_context(cx)));
404 }
405
406 #[gpui::test]
407 fn open_state_registers_and_unregisters_deferred_context(cx: &mut gpui::TestAppContext) {
408 cx.update(|cx| {
409 GlobalState::init(cx);
410 let state = cx.new(|cx| PopoverState::new(false, cx));
411
412 state.update(cx, |state, cx| state.set_open(true, cx));
413 assert!(state.read(cx).is_open());
414 assert!(GlobalState::is_in_deferred_context(cx));
415
416 state.update(cx, |state, cx| state.set_open(false, cx));
417 assert!(!state.read(cx).is_open());
418 assert!(!GlobalState::is_in_deferred_context(cx));
419 });
420 }
421
422 struct PopoverHarness {
423 changes: Rc<RefCell<Vec<bool>>>,
424 default_open: bool,
425 }
426
427 struct KeyboardPopoverHarness {
428 trigger_focus: FocusHandle,
429 }
430
431 impl Render for KeyboardPopoverHarness {
432 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
433 Popover::new("keyboard-popover")
434 .trigger(
435 crate::Button::new("keyboard-trigger")
436 .track_focus(&self.trigger_focus)
437 .child("Open"),
438 )
439 .content(|_, _, _| {
440 div()
441 .debug_selector(|| "keyboard-popover-content".into())
442 .size(px(40.))
443 })
444 }
445 }
446
447 impl Render for PopoverHarness {
448 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
449 let changes = self.changes.clone();
450 Popover::new("base-popover")
451 .default_open(self.default_open)
452 .trigger_with(|_, _, _| div().child("Open").into_any_element())
453 .content(|_, _, _| {
454 div()
455 .debug_selector(|| "base-popover-content".into())
456 .size(px(40.))
457 })
458 .on_open_change(move |open, _, _| changes.borrow_mut().push(*open))
459 }
460 }
461
462 #[gpui::test]
463 fn unstyled_popover_owns_pointer_open_and_outside_dismiss(cx: &mut gpui::TestAppContext) {
464 cx.update(crate::init);
465 let changes = Rc::new(RefCell::new(Vec::new()));
466 let (_, cx) = cx.add_window_view({
467 let changes = changes.clone();
468 move |_, _| PopoverHarness {
469 changes,
470 default_open: false,
471 }
472 });
473 cx.update(|window, cx| window.draw(cx).clear(cx));
474
475 cx.simulate_click(point(px(20.), px(10.)), Default::default());
476 cx.update(|window, cx| window.draw(cx).clear(cx));
477 assert!(cx.debug_bounds("base-popover-content").is_some());
478
479 cx.simulate_click(point(px(300.), px(300.)), Default::default());
480 cx.update(|window, cx| window.draw(cx).clear(cx));
481 assert!(cx.debug_bounds("base-popover-content").is_none());
482 assert_eq!(&*changes.borrow(), &[true, false]);
483 }
484
485 #[gpui::test]
486 fn default_open_renders_content_without_activation(cx: &mut gpui::TestAppContext) {
487 cx.update(crate::init);
488 let (_, cx) = cx.add_window_view(|_, _| PopoverHarness {
489 changes: Rc::new(RefCell::new(Vec::new())),
490 default_open: true,
491 });
492 cx.update(|window, cx| window.draw(cx).clear(cx));
493 cx.update(|window, cx| window.draw(cx).clear(cx));
494 assert!(cx.debug_bounds("base-popover-content").is_some());
495 }
496
497 /// A trigger that keeps "open" and "selected" apart, the way a downstream
498 /// sidebar row does: it is selected when it is the current view, and open
499 /// only while its popover is showing.
500 #[derive(IntoElement)]
501 struct RecordingTrigger {
502 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
503 selected: bool,
504 open: bool,
505 }
506
507 impl Selectable for RecordingTrigger {
508 fn selected(mut self, selected: bool) -> Self {
509 self.calls.borrow_mut().push(("selected", selected));
510 self.selected = selected;
511 self
512 }
513
514 fn is_selected(&self) -> bool {
515 self.selected
516 }
517
518 fn open(mut self, open: bool) -> Self {
519 self.calls.borrow_mut().push(("open", open));
520 self.open = open;
521 self
522 }
523
524 fn is_open(&self) -> bool {
525 self.open
526 }
527 }
528
529 impl RenderOnce for RecordingTrigger {
530 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
531 div().size(px(40.)).child("Open")
532 }
533 }
534
535 struct RecordingTriggerHarness {
536 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
537 }
538
539 impl Render for RecordingTriggerHarness {
540 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
541 Popover::new("recording-popover")
542 .trigger(RecordingTrigger {
543 calls: self.calls.clone(),
544 selected: false,
545 open: false,
546 })
547 .content(|_, _, _| div().size(px(40.)))
548 }
549 }
550
551 #[gpui::test]
552 fn an_open_popover_tells_its_trigger_it_is_open_not_selected(cx: &mut gpui::TestAppContext) {
553 cx.update(crate::init);
554 let calls = Rc::new(RefCell::new(Vec::new()));
555 let (_, cx) = cx.add_window_view({
556 let calls = calls.clone();
557 move |_, _| RecordingTriggerHarness { calls }
558 });
559 cx.update(|window, cx| window.draw(cx).clear(cx));
560 calls.borrow_mut().clear();
561
562 cx.simulate_click(point(px(20.), px(10.)), Default::default());
563 cx.update(|window, cx| window.draw(cx).clear(cx));
564
565 let calls = calls.borrow();
566 assert!(
567 calls.contains(&("open", true)),
568 "an open popover marks its trigger open, got {calls:?}"
569 );
570 assert!(
571 !calls.iter().any(|(name, _)| *name == "selected"),
572 "opening must not touch the trigger's own selection, got {calls:?}"
573 );
574 }
575
576 #[gpui::test]
577 fn keyboard_activation_opens_the_popover(cx: &mut gpui::TestAppContext) {
578 cx.update(crate::init);
579 let (view, cx) = cx.add_window_view(|_, cx| KeyboardPopoverHarness {
580 trigger_focus: cx.focus_handle(),
581 });
582 cx.update(|window, cx| window.draw(cx).clear(cx));
583
584 cx.update(|window, cx| {
585 let focus = view.read(cx).trigger_focus.clone();
586 focus.focus(window, cx);
587 });
588 cx.simulate_keystrokes("enter");
589 cx.update(|window, cx| window.draw(cx).clear(cx));
590
591 assert!(cx.debug_bounds("keyboard-popover-content").is_some());
592 }
593}