Skip to main content

blit_widget/
popover.rs

1use blit::{
2    Id, InteractCx, Scalar, Scope, Sides, Ui,
3    input::Input,
4    state::{NoLayout, Open},
5};
6
7use crate::{
8    Context, interact,
9    layout::{
10        Align, absolute,
11        absolute::{Anchor, Sizing},
12        flex,
13    },
14};
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17pub enum PopoverClose {
18    #[default]
19    Click,
20    Exit,
21    Manual,
22}
23
24blit::builder! {
25    pub struct Popover<'a, T: Scalar> {
26        new(state: &'a mut PopoverState),
27        parent: Id = Id::ROOT,
28        target_anchor: Anchor = Anchor::BottomLeft,
29        child_anchor: Anchor = Anchor::TopLeft,
30        x: T = T::ZERO,
31        y: T = T::ZERO,
32        #[into]
33        width: Sizing<T> = Sizing::fit(),
34        #[into]
35        height: Sizing<T> = Sizing::fit(),
36        hit: Sides<T> = Sides::all(T::ZERO),
37        flip: bool = true,
38        clamp: bool = true,
39        open_on_hover: bool = false,
40        close: PopoverClose = PopoverClose::Click,
41    }
42}
43
44blit::builder! {
45    /// persistent popover visibility
46    #[derive(Debug)]
47    pub struct PopoverState {
48        new(),
49        open: bool = false,
50    }
51}
52
53impl<T: Scalar> Popover<'_, T> {
54    pub fn begin<'a, C, S>(self, mut ui: Ui<'a, C, S>) -> PopoverTrigger<'a, C>
55    where
56        C: Context<Scalar = T>,
57        S: NoLayout,
58    {
59        let state = self.state;
60        let scope = ui.scope();
61        let trigger_id = ui.resolve(scope, TRIGGER);
62        let content_id = ui.resolve(scope, CONTENT);
63        let (press, trigger_area) = {
64            let mut part = ui.node(trigger_id);
65            (part.interact(interact::press()), part.area())
66        };
67        if self.open_on_hover && press.hovered {
68            state.open = true;
69        } else if !self.open_on_hover && press.activated {
70            state.open = !state.open;
71        }
72        // requested while closed too so the opening frame knows where the trigger is
73        let areas = [trigger_area, ui.node(content_id).area()];
74        if state.open {
75            let backdrop_id = ui.resolve(scope, BACKDROP);
76            let backdrop = {
77                let mut part = ui.node(backdrop_id);
78                let backdrop = part.interact(interact::press());
79                part.interact(BlockInput);
80                backdrop
81            };
82            let content_hovered = ui.node(content_id).interact(BlockInput);
83            let pointer_inside = content_hovered
84                || ui
85                    .mouse_position()
86                    .is_some_and(|position| areas.into_iter().flatten().any(|area| area.contains(position)));
87            if match (self.close, ui.input()) {
88                (PopoverClose::Click, _) => backdrop.activated,
89                (PopoverClose::Exit, Input::MouseMove { .. } | Input::MouseLeave) => !pointer_inside,
90                _ => false,
91            } {
92                state.open = false;
93            }
94        }
95        let open = state.open;
96        let mut root = ui.layout(flex::column().align(Align::Start));
97        if open && self.close != PopoverClose::Manual {
98            root.place_in(
99                scope,
100                BACKDROP,
101                self.parent,
102                absolute::place().width(Sizing::full()).height(Sizing::full()),
103            )
104            .parent(self.parent)
105            .z_index(1)
106            .insert(());
107        }
108        PopoverTrigger {
109            press,
110            hit: self.hit,
111            next: PopoverContent {
112                root,
113                scope,
114                trigger_id,
115                open,
116                parent: self.parent,
117                hit: if self.flip {
118                    let horizontal = self.x.max(T::ZERO - self.x);
119                    let vertical = self.y.max(T::ZERO - self.y);
120                    Sides::new()
121                        .top(vertical)
122                        .right(horizontal)
123                        .bottom(vertical)
124                        .left(horizontal)
125                } else {
126                    Sides::new()
127                        .top(self.y.max(T::ZERO))
128                        .right((-self.x).max(T::ZERO))
129                        .bottom((-self.y).max(T::ZERO))
130                        .left(self.x.max(T::ZERO))
131                },
132                place: absolute::place()
133                    .target_anchor(self.target_anchor)
134                    .child_anchor(self.child_anchor)
135                    .x(self.x)
136                    .y(self.y)
137                    .width(self.width)
138                    .height(self.height)
139                    .flip(self.flip)
140                    .clamp(self.clamp),
141            },
142        }
143    }
144}
145
146#[must_use]
147pub struct PopoverTrigger<'a, C: Context> {
148    press: interact::press::Response,
149    hit: Sides<C::Scalar>,
150    next: PopoverContent<'a, C>,
151}
152
153impl<'a, C: Context> PopoverTrigger<'a, C> {
154    pub fn trigger(
155        mut self,
156        trigger: impl FnOnce(Ui<'_, C>, interact::press::Response, bool),
157    ) -> PopoverContent<'a, C> {
158        let press = self.press;
159        let open = self.next.open;
160        self.next
161            .root
162            .child_in(self.next.scope, TRIGGER)
163            .hit(self.hit)
164            .layout(())
165            .child()
166            .build(|ui: Ui<'_, C>| trigger(ui, press, open));
167        self.next
168    }
169}
170
171#[must_use]
172pub struct PopoverContent<'a, C: Context> {
173    root: Ui<'a, C, Open<flex::Layout<C::Scalar>>>,
174    scope: Scope,
175    trigger_id: Id,
176    open: bool,
177    parent: Id,
178    hit: Sides<C::Scalar>,
179    place: absolute::Place<C::Scalar>,
180}
181
182impl<C: Context> PopoverContent<'_, C> {
183    pub fn content(mut self, content: impl FnOnce(Ui<'_, C>)) {
184        if !self.open {
185            return;
186        }
187        // stacks above the backdrop as its later sibling
188        self.root
189            .place_in(self.scope, CONTENT, self.trigger_id, self.place)
190            .parent(self.parent)
191            .z_index(1)
192            .hit(self.hit)
193            .layout(())
194            .child()
195            .build(content);
196    }
197}
198
199const BACKDROP: u8 = 0;
200const TRIGGER: u8 = 1;
201const CONTENT: u8 = 2;
202
203#[derive(Clone, Copy)]
204struct BlockInput;
205
206impl<C: Context> blit::Interact<C> for BlockInput {
207    type State = ();
208    type Response = bool;
209
210    fn update(&self, _: &mut (), cx: &mut InteractCx<'_, C::Scalar>) -> bool {
211        for mut contact in cx.contacts() {
212            contact.capture();
213        }
214        cx.capture_scroll();
215        cx.hovered()
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use std::time::Duration;
222
223    use blit::{
224        Axis, Constraints, FrameInfo, Point as InputPoint, Rect, Scope, Size, Tree,
225        input::{Modifiers, MouseButton, ScrollPhase},
226    };
227
228    use super::*;
229    use crate::{
230        interact,
231        test::{TestContext, step},
232    };
233
234    #[test]
235    fn popover_blocks_background_scroll() {
236        let mut tree = Tree::default();
237        let mut state = PopoverState::new().open(true);
238        let mut next = |input| {
239            step(&mut tree, input, |mut ui: Ui<'_, TestContext>| {
240                let background = ui.interact(interact::scroll()).delta;
241                let mut content = InputPoint::ZERO;
242                Popover::new(&mut state)
243                    .width(100.0)
244                    .height(100.0)
245                    .begin(ui)
246                    .trigger(|_, _, _| ())
247                    .content(|mut ui| content = ui.interact(interact::scroll().axis(Axis::Horizontal)).delta);
248                (background, content)
249            })
250        };
251        next(Input::None);
252        for (position, delta) in [
253            (InputPoint::new(150.0, 150.0), InputPoint::new(0.0, 5.0)),
254            (InputPoint::new(20.0, 20.0), InputPoint::new(0.0, 5.0)),
255            (InputPoint::new(20.0, 20.0), InputPoint::new(5.0, 0.0)),
256        ] {
257            let (background, content) = next(Input::Scroll {
258                position,
259                delta,
260                continuous: false,
261                phase: ScrollPhase::Moved,
262                modifiers: Modifiers::NONE,
263            });
264            assert_eq!(background, InputPoint::ZERO);
265            assert_eq!(content, InputPoint::new(delta.x, 0.0));
266        }
267    }
268
269    // returns the popover's node holding the content
270    fn render(ui: Ui<'_, TestContext>, popover: Popover<'_, f32>) -> Option<Id> {
271        let named_trigger = 1000;
272        let named_content = 1001;
273        let mut part = None;
274        popover
275            .begin(ui)
276            .trigger(|ui, _, _| {
277                ui.layout(())
278                    .child_in(Scope::ROOT, named_trigger)
279                    .constrain(Constraints::tight(Size::new(2.0, 1.0)))
280                    .insert(())
281            })
282            .content(|ui| {
283                part = Some(ui.parent_id());
284                ui.layout(())
285                    .child_in(Scope::ROOT, named_content)
286                    .constrain(Constraints::tight(Size::new(4.0, 3.0)))
287                    .insert(())
288            });
289        part
290    }
291
292    #[test]
293    fn popover_uses_root_constraints_and_close_behavior() {
294        let named_trigger = 1000;
295        let named_content = 1001;
296        let mut tree = Tree::default();
297        let mut context = TestContext;
298        let info = FrameInfo::new(Size::uniform(10.0));
299        let mut state = PopoverState::new();
300
301        tree.build(
302            &mut context,
303            info,
304            Duration::ZERO,
305            Input::None,
306            |ui: Ui<'_, TestContext>| render(ui, Popover::new(&mut state)),
307        );
308        tree.layout(&mut context);
309        let mut expected = [true, true, false].into_iter();
310        for input in [
311            Input::MouseMove {
312                position: InputPoint::new(1.0, 0.5),
313                modifiers: Modifiers::NONE,
314            },
315            Input::MouseMove {
316                position: InputPoint::new(1.0, 1.5),
317                modifiers: Modifiers::NONE,
318            },
319            Input::MouseMove {
320                position: InputPoint::new(9.0, 9.0),
321                modifiers: Modifiers::NONE,
322            },
323        ] {
324            tree.build(&mut context, info, Duration::ZERO, input, |ui: Ui<'_, TestContext>| {
325                render(
326                    ui,
327                    Popover::new(&mut state)
328                        .y(1.0)
329                        .open_on_hover(true)
330                        .close(PopoverClose::Exit),
331                );
332                assert_eq!(state.open, expected.next().unwrap());
333            });
334            tree.layout(&mut context);
335        }
336
337        let mut expected = [true, true, false].into_iter();
338        let (mut part, mut content_area) = (None, None);
339        for input in [
340            Input::MouseDown {
341                position: InputPoint::new(1.0, 0.5),
342                button: MouseButton::Primary,
343                modifiers: Modifiers::NONE,
344            },
345            Input::MouseUp {
346                position: InputPoint::new(1.0, 0.5),
347                button: MouseButton::Primary,
348                modifiers: Modifiers::NONE,
349                leave: false,
350            },
351            Input::MouseDown {
352                position: InputPoint::new(9.0, 9.0),
353                button: MouseButton::Primary,
354                modifiers: Modifiers::NONE,
355            },
356        ] {
357            let released = matches!(input, Input::MouseUp { .. });
358            tree.build(&mut context, info, Duration::ZERO, input, |ui: Ui<'_, TestContext>| {
359                part = render(ui, Popover::new(&mut state).width(5.0).height(4.0));
360                assert_eq!(state.open, expected.next().unwrap());
361            });
362            tree.layout(&mut context);
363            if released {
364                content_area = part.and_then(|id| tree.area(id));
365                assert_eq!(
366                    tree.find(Scope::ROOT, named_content).and_then(|id| tree.area(id)),
367                    Some(Rect::new(0.0, 1.0, 4.0, 3.0))
368                );
369                assert_eq!(
370                    tree.find(Scope::ROOT, named_trigger).and_then(|id| tree.area(id)),
371                    Some(Rect::new(0.0, 0.0, 2.0, 1.0)),
372                );
373            }
374        }
375        assert_eq!(content_area, Some(Rect::new(0.0, 1.0, 5.0, 4.0)));
376    }
377}