expanded.rs

  1use std::ops::Range;
  2
  3use crate::{
  4    geometry::{rect::RectF, vector::Vector2F},
  5    json,
  6    presenter::MeasurementContext,
  7    DebugContext, Element, ElementBox, Event, EventContext, LayoutContext, PaintContext,
  8    SizeConstraint,
  9};
 10use serde_json::json;
 11
 12pub struct Expanded {
 13    child: ElementBox,
 14    full_width: bool,
 15    full_height: bool,
 16}
 17
 18impl Expanded {
 19    pub fn new(child: ElementBox) -> Self {
 20        Self {
 21            child,
 22            full_width: true,
 23            full_height: true,
 24        }
 25    }
 26
 27    pub fn full_width(mut self) -> Self {
 28        self.full_width = true;
 29        self.full_height = false;
 30        self
 31    }
 32
 33    pub fn full_height(mut self) -> Self {
 34        self.full_width = false;
 35        self.full_height = true;
 36        self
 37    }
 38}
 39
 40impl Element for Expanded {
 41    type LayoutState = ();
 42    type PaintState = ();
 43
 44    fn layout(
 45        &mut self,
 46        mut constraint: SizeConstraint,
 47        cx: &mut LayoutContext,
 48    ) -> (Vector2F, Self::LayoutState) {
 49        if self.full_width {
 50            constraint.min.set_x(constraint.max.x());
 51        }
 52        if self.full_height {
 53            constraint.min.set_y(constraint.max.y());
 54        }
 55        let size = self.child.layout(constraint, cx);
 56        (size, ())
 57    }
 58
 59    fn paint(
 60        &mut self,
 61        bounds: RectF,
 62        visible_bounds: RectF,
 63        _: &mut Self::LayoutState,
 64        cx: &mut PaintContext,
 65    ) -> Self::PaintState {
 66        self.child.paint(bounds.origin(), visible_bounds, cx);
 67    }
 68
 69    fn dispatch_event(
 70        &mut self,
 71        event: &Event,
 72        _: RectF,
 73        _: RectF,
 74        _: &mut Self::LayoutState,
 75        _: &mut Self::PaintState,
 76        cx: &mut EventContext,
 77    ) -> bool {
 78        self.child.dispatch_event(event, cx)
 79    }
 80
 81    fn rect_for_text_range(
 82        &self,
 83        range_utf16: Range<usize>,
 84        _: RectF,
 85        _: RectF,
 86        _: &Self::LayoutState,
 87        _: &Self::PaintState,
 88        cx: &MeasurementContext,
 89    ) -> Option<RectF> {
 90        self.child.rect_for_text_range(range_utf16, cx)
 91    }
 92
 93    fn debug(
 94        &self,
 95        _: RectF,
 96        _: &Self::LayoutState,
 97        _: &Self::PaintState,
 98        cx: &DebugContext,
 99    ) -> json::Value {
100        json!({
101            "type": "Expanded",
102            "full_width": self.full_width,
103            "full_height": self.full_height,
104            "child": self.child.debug(cx)
105        })
106    }
107}