1use refineable::Refineable as _;
2
3use crate::{Bounds, Element, ElementContext, IntoElement, Pixels, Style, StyleRefinement, Styled};
4
5/// Construct a canvas element with the given paint callback.
6/// Useful for adding short term custom drawing to a view.
7pub fn canvas<T>(
8 after_layout: impl 'static + FnOnce(Bounds<Pixels>, &mut ElementContext) -> T,
9 paint: impl 'static + FnOnce(Bounds<Pixels>, T, &mut ElementContext),
10) -> Canvas<T> {
11 Canvas {
12 after_layout: Some(Box::new(after_layout)),
13 paint: Some(Box::new(paint)),
14 style: StyleRefinement::default(),
15 }
16}
17
18/// A canvas element, meant for accessing the low level paint API without defining a whole
19/// custom element
20pub struct Canvas<T> {
21 after_layout: Option<Box<dyn FnOnce(Bounds<Pixels>, &mut ElementContext) -> T>>,
22 paint: Option<Box<dyn FnOnce(Bounds<Pixels>, T, &mut ElementContext)>>,
23 style: StyleRefinement,
24}
25
26impl<T: 'static> IntoElement for Canvas<T> {
27 type Element = Self;
28
29 fn into_element(self) -> Self::Element {
30 self
31 }
32}
33
34impl<T: 'static> Element for Canvas<T> {
35 type BeforeLayout = Style;
36 type AfterLayout = Option<T>;
37
38 fn before_layout(&mut self, cx: &mut ElementContext) -> (crate::LayoutId, Self::BeforeLayout) {
39 let mut style = Style::default();
40 style.refine(&self.style);
41 let layout_id = cx.request_layout(&style, []);
42 (layout_id, style)
43 }
44
45 fn after_layout(
46 &mut self,
47 bounds: Bounds<Pixels>,
48 _before_layout: &mut Style,
49 cx: &mut ElementContext,
50 ) -> Option<T> {
51 Some(self.after_layout.take().unwrap()(bounds, cx))
52 }
53
54 fn paint(
55 &mut self,
56 bounds: Bounds<Pixels>,
57 style: &mut Style,
58 after_layout: &mut Self::AfterLayout,
59 cx: &mut ElementContext,
60 ) {
61 let after_layout = after_layout.take().unwrap();
62 style.paint(bounds, cx, |cx| {
63 (self.paint.take().unwrap())(bounds, after_layout, cx)
64 });
65 }
66}
67
68impl<T> Styled for Canvas<T> {
69 fn style(&mut self) -> &mut crate::StyleRefinement {
70 &mut self.style
71 }
72}