div.rs

  1use crate::{
  2    element::{AnyElement, Element, Layout, ParentElement},
  3    interactive::{InteractionHandlers, Interactive},
  4    layout_context::LayoutContext,
  5    paint_context::PaintContext,
  6    style::{Style, StyleHelpers, StyleRefinement, Styleable},
  7};
  8use anyhow::Result;
  9use gpui::LayoutId;
 10use smallvec::SmallVec;
 11
 12pub struct Div<V: 'static> {
 13    style: StyleRefinement,
 14    handlers: InteractionHandlers<V>,
 15    children: SmallVec<[AnyElement<V>; 2]>,
 16}
 17
 18pub fn div<V>() -> Div<V> {
 19    Div {
 20        style: Default::default(),
 21        handlers: Default::default(),
 22        children: Default::default(),
 23    }
 24}
 25
 26impl<V: 'static> Element<V> for Div<V> {
 27    type Layout = ();
 28
 29    fn layout(&mut self, view: &mut V, cx: &mut LayoutContext<V>) -> Result<Layout<V, ()>>
 30    where
 31        Self: Sized,
 32    {
 33        let children = self
 34            .children
 35            .iter_mut()
 36            .map(|child| child.layout(view, cx))
 37            .collect::<Result<Vec<LayoutId>>>()?;
 38
 39        cx.add_layout_node(self.style(), (), children)
 40    }
 41
 42    fn paint(&mut self, view: &mut V, layout: &mut Layout<V, ()>, cx: &mut PaintContext<V>)
 43    where
 44        Self: Sized,
 45    {
 46        let style = self.style();
 47
 48        style.paint_background::<V, Self>(layout, cx);
 49        for child in &mut self.children {
 50            child.paint(view, cx);
 51        }
 52    }
 53}
 54
 55impl<V> Styleable for Div<V> {
 56    type Style = Style;
 57
 58    fn declared_style(&mut self) -> &mut StyleRefinement {
 59        &mut self.style
 60    }
 61}
 62
 63impl<V> StyleHelpers for Div<V> {}
 64
 65impl<V> Interactive<V> for Div<V> {
 66    fn interaction_handlers(&mut self) -> &mut InteractionHandlers<V> {
 67        &mut self.handlers
 68    }
 69}
 70
 71impl<V: 'static> ParentElement<V> for Div<V> {
 72    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]> {
 73        &mut self.children
 74    }
 75}
 76
 77#[test]
 78fn test() {
 79    // let elt = div().w_auto();
 80}
 81
 82// trait Element<V: 'static> {
 83//     type Style;
 84
 85//     fn layout()
 86// }
 87
 88// trait Stylable<V: 'static>: Element<V> {
 89//     type Style;
 90
 91//     fn with_style(self, style: Self::Style) -> Self;
 92// }
 93
 94// pub struct HoverStyle<S> {
 95//     default: S,
 96//     hovered: S,
 97// }
 98
 99// struct Hover<V: 'static, C: Stylable<V>> {
100//     child: C,
101//     style: HoverStyle<C::Style>,
102// }
103
104// impl<V: 'static, C: Stylable<V>> Hover<V, C> {
105//     fn new(child: C, style: HoverStyle<C::Style>) -> Self {
106//         Self { child, style }
107//     }
108// }