| 1 | use gpui::{Action, App, FocusHandle, InteractiveElement as _, IntoElement, Styled, Window, div}; |
| 2 | |
| 3 | /// A focus node of a dialog control's own, so the control can dispatch its |
| 4 | /// action on the dialog it sits in rather than on whatever holds focus when |
| 5 | /// it is clicked. |
| 6 | /// |
| 7 | /// [`Window::dispatch_action`] routes along the focused element. A surface |
| 8 | /// that keeps taking focus back — a native web view, an always-on-top window |
| 9 | /// — leaves every dialog button inert that way: the click lands, the action |
| 10 | /// is dispatched, and no dialog is on the focus path to handle it. Dispatching |
| 11 | /// from a node inside the control instead walks the control's own ancestors, |
| 12 | /// which end at exactly the dialog it belongs to, stacked dialogs included. |
| 13 | /// |
| 14 | /// Create it where the control renders, so the keyed state lives in that |
| 15 | /// control's scope, and place [`Self::element`] inside the control. |
| 16 | #[derive(Clone)] |
| 17 | pub(crate) struct DialogDispatchAnchor { |
| 18 | handle: FocusHandle, |
| 19 | } |
| 20 | |
| 21 | impl DialogDispatchAnchor { |
| 22 | pub(crate) fn new(key: &'static str, window: &mut Window, cx: &mut App) -> Self { |
| 23 | let handle = window |
| 24 | .use_keyed_state(key, cx, |_, cx| cx.focus_handle()) |
| 25 | .read(cx) |
| 26 | .clone(); |
| 27 | Self { handle } |
| 28 | } |
| 29 | |
| 30 | /// A zero-size, out-of-flow node that tracks the handle. It is never |
| 31 | /// hovered, so it takes no focus of its own and does not enter the Tab |
| 32 | /// order; it only gives the handle a place in the dispatch tree. |
| 33 | pub(crate) fn element(&self) -> impl IntoElement { |
| 34 | div().absolute().size_0().track_focus(&self.handle) |
| 35 | } |
| 36 | |
| 37 | /// Dispatches `action` from the anchor, falling back to the focused |
| 38 | /// element only if the anchor was never rendered. |
| 39 | pub(crate) fn dispatch(&self, action: &dyn Action, window: &mut Window, cx: &mut App) { |
| 40 | if self.handle.is_focused(window) || self.is_rendered(window) { |
| 41 | self.handle.dispatch_action(action, window, cx); |
| 42 | } else { |
| 43 | window.dispatch_action(action.boxed_clone(), cx); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn is_rendered(&self, window: &Window) -> bool { |
| 48 | // `FocusHandle::dispatch_action` is a no-op for a handle the rendered |
| 49 | // frame does not contain; `contains` answers from that same frame. |
| 50 | self.handle.contains(&self.handle, window) |
| 51 | } |
| 52 | } |