hook.rs

 1use std::ops::Range;
 2
 3use crate::{
 4    geometry::{rect::RectF, vector::Vector2F},
 5    json::json,
 6    AnyElement, Element, SizeConstraint, ViewContext,
 7};
 8
 9pub struct Hook<V> {
10    child: AnyElement<V>,
11    after_layout: Option<Box<dyn FnMut(Vector2F, &mut ViewContext<V>)>>,
12}
13
14impl<V: 'static> Hook<V> {
15    pub fn new(child: impl Element<V>) -> Self {
16        Self {
17            child: child.into_any(),
18            after_layout: None,
19        }
20    }
21
22    pub fn on_after_layout(
23        mut self,
24        f: impl 'static + FnMut(Vector2F, &mut ViewContext<V>),
25    ) -> Self {
26        self.after_layout = Some(Box::new(f));
27        self
28    }
29}
30
31impl<V: 'static> Element<V> for Hook<V> {
32    type LayoutState = ();
33    type PaintState = ();
34
35    fn layout(
36        &mut self,
37        constraint: SizeConstraint,
38        view: &mut V,
39        cx: &mut ViewContext<V>,
40    ) -> (Vector2F, Self::LayoutState) {
41        let size = self.child.layout(constraint, view, cx);
42        if let Some(handler) = self.after_layout.as_mut() {
43            handler(size, cx);
44        }
45        (size, ())
46    }
47
48    fn paint(
49        &mut self,
50        bounds: RectF,
51        visible_bounds: RectF,
52        _: &mut Self::LayoutState,
53        view: &mut V,
54        cx: &mut ViewContext<V>,
55    ) {
56        self.child.paint(bounds.origin(), visible_bounds, view, cx);
57    }
58
59    fn rect_for_text_range(
60        &self,
61        range_utf16: Range<usize>,
62        _: RectF,
63        _: RectF,
64        _: &Self::LayoutState,
65        _: &Self::PaintState,
66        view: &V,
67        cx: &ViewContext<V>,
68    ) -> Option<RectF> {
69        self.child.rect_for_text_range(range_utf16, view, cx)
70    }
71
72    fn debug(
73        &self,
74        _: RectF,
75        _: &Self::LayoutState,
76        _: &Self::PaintState,
77        view: &V,
78        cx: &ViewContext<V>,
79    ) -> serde_json::Value {
80        json!({
81            "type": "Hooks",
82            "child": self.child.debug(view, cx),
83        })
84    }
85}