div.rs

  1use crate::{
  2    AnyElement, Bounds, Element, Interactive, LayoutId, MouseEventListeners, Overflow,
  3    ParentElement, Pixels, Point, Refineable, RefinementCascade, Result, Style, StyleHelpers,
  4    Styled, ViewContext,
  5};
  6use parking_lot::Mutex;
  7use smallvec::SmallVec;
  8use std::sync::Arc;
  9use util::ResultExt;
 10
 11pub struct Div<S: 'static> {
 12    styles: RefinementCascade<Style>,
 13    listeners: MouseEventListeners<S>,
 14    children: SmallVec<[AnyElement<S>; 2]>,
 15    scroll_state: Option<ScrollState>,
 16}
 17
 18pub fn div<S>() -> Div<S> {
 19    Div {
 20        styles: Default::default(),
 21        listeners: Default::default(),
 22        children: Default::default(),
 23        scroll_state: None,
 24    }
 25}
 26
 27impl<S: 'static + Send + Sync> Element for Div<S> {
 28    type State = S;
 29    type FrameState = Vec<LayoutId>;
 30
 31    fn layout(
 32        &mut self,
 33        view: &mut S,
 34        cx: &mut ViewContext<S>,
 35    ) -> Result<(LayoutId, Self::FrameState)> {
 36        let style = self.computed_style();
 37        let child_layout_ids = style.apply_text_style(cx, |cx| self.layout_children(view, cx))?;
 38        let layout_id = cx.request_layout(style.into(), child_layout_ids.clone())?;
 39        Ok((layout_id, child_layout_ids))
 40    }
 41
 42    fn paint(
 43        &mut self,
 44        bounds: Bounds<Pixels>,
 45        state: &mut S,
 46        child_layout_ids: &mut Self::FrameState,
 47        cx: &mut ViewContext<S>,
 48    ) -> Result<()> {
 49        let style = self.computed_style();
 50        cx.stack(0, |cx| style.paint(bounds, cx));
 51
 52        let overflow = &style.overflow;
 53        style.apply_text_style(cx, |cx| {
 54            cx.stack(1, |cx| {
 55                style.apply_overflow(bounds, cx, |cx| {
 56                    self.listeners.paint(bounds, cx);
 57                    self.paint_children(overflow, state, cx)
 58                })
 59            })
 60        })?;
 61        self.handle_scroll(bounds, style.overflow.clone(), child_layout_ids, cx);
 62
 63        // todo!("enable inspector")
 64        // if cx.is_inspector_enabled() {
 65        //     self.paint_inspector(parent_origin, layout, cx);
 66        // }
 67        //
 68
 69        Ok(())
 70    }
 71}
 72
 73impl<S: 'static> Div<S> {
 74    pub fn overflow_hidden(mut self) -> Self {
 75        self.declared_style().overflow.x = Some(Overflow::Hidden);
 76        self.declared_style().overflow.y = Some(Overflow::Hidden);
 77        self
 78    }
 79
 80    pub fn overflow_hidden_x(mut self) -> Self {
 81        self.declared_style().overflow.x = Some(Overflow::Hidden);
 82        self
 83    }
 84
 85    pub fn overflow_hidden_y(mut self) -> Self {
 86        self.declared_style().overflow.y = Some(Overflow::Hidden);
 87        self
 88    }
 89
 90    pub fn overflow_scroll(mut self, scroll_state: ScrollState) -> Self {
 91        self.scroll_state = Some(scroll_state);
 92        self.declared_style().overflow.x = Some(Overflow::Scroll);
 93        self.declared_style().overflow.y = Some(Overflow::Scroll);
 94        self
 95    }
 96
 97    pub fn overflow_x_scroll(mut self, scroll_state: ScrollState) -> Self {
 98        self.scroll_state = Some(scroll_state);
 99        self.declared_style().overflow.x = Some(Overflow::Scroll);
100        self
101    }
102
103    pub fn overflow_y_scroll(mut self, scroll_state: ScrollState) -> Self {
104        self.scroll_state = Some(scroll_state);
105        self.declared_style().overflow.y = Some(Overflow::Scroll);
106        self
107    }
108
109    fn scroll_offset(&self, overflow: &Point<Overflow>) -> Point<Pixels> {
110        let mut offset = Point::default();
111        if overflow.y == Overflow::Scroll {
112            offset.y = self.scroll_state.as_ref().unwrap().y();
113        }
114        if overflow.x == Overflow::Scroll {
115            offset.x = self.scroll_state.as_ref().unwrap().x();
116        }
117
118        offset
119    }
120
121    fn layout_children(&mut self, view: &mut S, cx: &mut ViewContext<S>) -> Result<Vec<LayoutId>> {
122        self.children
123            .iter_mut()
124            .map(|child| child.layout(view, cx))
125            .collect::<Result<Vec<LayoutId>>>()
126    }
127
128    fn paint_children(
129        &mut self,
130        overflow: &Point<Overflow>,
131        state: &mut S,
132        cx: &mut ViewContext<S>,
133    ) -> Result<()> {
134        let scroll_offset = self.scroll_offset(overflow);
135        for child in &mut self.children {
136            child.paint(state, Some(scroll_offset), cx)?;
137        }
138        Ok(())
139    }
140
141    fn handle_scroll(
142        &mut self,
143        bounds: Bounds<Pixels>,
144        overflow: Point<Overflow>,
145        child_layout_ids: &[LayoutId],
146        cx: &mut ViewContext<S>,
147    ) {
148        if overflow.y == Overflow::Scroll || overflow.x == Overflow::Scroll {
149            let mut scroll_max = Point::default();
150            for child_layout_id in child_layout_ids {
151                if let Some(child_bounds) = cx.layout_bounds(*child_layout_id).log_err() {
152                    scroll_max = scroll_max.max(&child_bounds.lower_right());
153                }
154            }
155            scroll_max -= bounds.size;
156
157            // todo!("handle scroll")
158            // let scroll_state = self.scroll_state.as_ref().unwrap().clone();
159            // cx.on_event(order, move |_, event: &ScrollWheelEvent, cx| {
160            //     if bounds.contains_point(event.position) {
161            //         let scroll_delta = match event.delta {
162            //             ScrollDelta::Pixels(delta) => delta,
163            //             ScrollDelta::Lines(delta) => cx.text_style().font_size * delta,
164            //         };
165            //         if overflow.x == Overflow::Scroll {
166            //             scroll_state.set_x(
167            //                 (scroll_state.x() - scroll_delta.x())
168            //                     .max(px(0.))
169            //                     .min(scroll_max.x),
170            //             );
171            //         }
172            //         if overflow.y == Overflow::Scroll {
173            //             scroll_state.set_y(
174            //                 (scroll_state.y() - scroll_delta.y())
175            //                     .max(px(0.))
176            //                     .min(scroll_max.y),
177            //             );
178            //         }
179            //         cx.repaint();
180            //     } else {
181            //         cx.bubble_event();
182            //     }
183            // })
184        }
185    }
186
187    // fn paint_inspector(
188    //     &self,
189    //     parent_origin: Point<Pixels>,
190    //     layout: &Layout,
191    //     cx: &mut ViewContext<V>,
192    // ) {
193    //     let style = self.styles.merged();
194    //     let bounds = layout.bounds;
195
196    //     let hovered = bounds.contains_point(cx.mouse_position());
197    //     if hovered {
198    //         let rem_size = cx.rem_size();
199    //         // cx.scene().push_quad(scene::Quad {
200    //         //     bounds,
201    //         //     background: Some(hsla(0., 0., 1., 0.05).into()),
202    //         //     border: gpui::Border {
203    //         //         color: hsla(0., 0., 1., 0.2).into(),
204    //         //         top: 1.,
205    //         //         right: 1.,
206    //         //         bottom: 1.,
207    //         //         left: 1.,
208    //         //     },
209    //         //     corner_radii: CornerRadii::default()
210    //         //         .refined(&style.corner_radii)
211    //         //         .to_gpui(bounds.size(), rem_size),
212    //         // })
213    //     }
214
215    //     // let pressed = Cell::new(hovered && cx.is_mouse_down(MouseButton::Left));
216    //     // cx.on_event(layout.order, move |_, event: &MouseButtonEvent, _| {
217    //     //     if bounds.contains_point(event.position) {
218    //     //         if event.is_down {
219    //     //             pressed.set(true);
220    //     //         } else if pressed.get() {
221    //     //             pressed.set(false);
222    //     //             eprintln!("clicked div {:?} {:#?}", bounds, style);
223    //     //         }
224    //     //     }
225    //     // });
226
227    //     // let hovered = Cell::new(hovered);
228    //     // cx.on_event(layout.order, move |_, event: &MouseMovedEvent, cx| {
229    //     //     cx.bubble_event();
230    //     //     let hovered_now = bounds.contains_point(event.position);
231    //     //     if hovered.get() != hovered_now {
232    //     //         hovered.set(hovered_now);
233    //     //         cx.repaint();
234    //     //     }
235    //     // });
236    // }
237    //
238}
239
240impl<V> Styled for Div<V> {
241    type Style = Style;
242
243    fn style_cascade(&mut self) -> &mut RefinementCascade<Self::Style> {
244        &mut self.styles
245    }
246
247    fn declared_style(&mut self) -> &mut <Self::Style as Refineable>::Refinement {
248        self.styles.base()
249    }
250}
251
252impl<V> StyleHelpers for Div<V> {}
253
254impl<V: Send + Sync + 'static> Interactive<V> for Div<V> {
255    fn listeners(&mut self) -> &mut MouseEventListeners<V> {
256        &mut self.listeners
257    }
258}
259
260impl<V: 'static> ParentElement<V> for Div<V> {
261    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]> {
262        &mut self.children
263    }
264}
265
266#[derive(Default, Clone)]
267pub struct ScrollState(Arc<Mutex<Point<Pixels>>>);
268
269impl ScrollState {
270    pub fn x(&self) -> Pixels {
271        self.0.lock().x
272    }
273
274    pub fn set_x(&self, value: Pixels) {
275        self.0.lock().x = value;
276    }
277
278    pub fn y(&self) -> Pixels {
279        self.0.lock().y
280    }
281
282    pub fn set_y(&self, value: Pixels) {
283        self.0.lock().y = value;
284    }
285}