style.rs

  1use crate::{
  2    phi, point, rems, AbsoluteLength, BorrowAppContext, BorrowWindow, Bounds, ContentMask, Corners,
  3    CornersRefinement, DefiniteLength, Edges, EdgesRefinement, Font, FontFeatures, FontStyle,
  4    FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Quad, Rems, Result, RunStyle,
  5    SharedString, Size, SizeRefinement, ViewContext, WindowContext,
  6};
  7use refineable::Refineable;
  8pub use taffy::style::{
  9    AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
 10    Overflow, Position,
 11};
 12
 13#[derive(Clone, Refineable, Debug)]
 14#[refineable(debug)]
 15pub struct Style {
 16    /// What layout strategy should be used?
 17    pub display: Display,
 18
 19    // Overflow properties
 20    /// How children overflowing their container should affect layout
 21    #[refineable]
 22    pub overflow: Point<Overflow>,
 23    /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
 24    pub scrollbar_width: f32,
 25
 26    // Position properties
 27    /// What should the `position` value of this struct use as a base offset?
 28    pub position: Position,
 29    /// How should the position of this element be tweaked relative to the layout defined?
 30    #[refineable]
 31    pub inset: Edges<Length>,
 32
 33    // Size properies
 34    /// Sets the initial size of the item
 35    #[refineable]
 36    pub size: Size<Length>,
 37    /// Controls the minimum size of the item
 38    #[refineable]
 39    pub min_size: Size<Length>,
 40    /// Controls the maximum size of the item
 41    #[refineable]
 42    pub max_size: Size<Length>,
 43    /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
 44    pub aspect_ratio: Option<f32>,
 45
 46    // Spacing Properties
 47    /// How large should the margin be on each side?
 48    #[refineable]
 49    pub margin: Edges<Length>,
 50    /// How large should the padding be on each side?
 51    #[refineable]
 52    pub padding: Edges<DefiniteLength>,
 53    /// How large should the border be on each side?
 54    #[refineable]
 55    pub border_widths: Edges<AbsoluteLength>,
 56
 57    // Alignment properties
 58    /// How this node's children aligned in the cross/block axis?
 59    pub align_items: Option<AlignItems>,
 60    /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
 61    pub align_self: Option<AlignSelf>,
 62    /// How should content contained within this item be aligned in the cross/block axis
 63    pub align_content: Option<AlignContent>,
 64    /// How should contained within this item be aligned in the main/inline axis
 65    pub justify_content: Option<JustifyContent>,
 66    /// How large should the gaps between items in a flex container be?
 67    #[refineable]
 68    pub gap: Size<DefiniteLength>,
 69
 70    // Flexbox properies
 71    /// Which direction does the main axis flow in?
 72    pub flex_direction: FlexDirection,
 73    /// Should elements wrap, or stay in a single line?
 74    pub flex_wrap: FlexWrap,
 75    /// Sets the initial main axis size of the item
 76    pub flex_basis: Length,
 77    /// The relative rate at which this item grows when it is expanding to fill space, 0.0 is the default value, and this value must be positive.
 78    pub flex_grow: f32,
 79    /// The relative rate at which this item shrinks when it is contracting to fit into space, 1.0 is the default value, and this value must be positive.
 80    pub flex_shrink: f32,
 81
 82    /// The fill color of this element
 83    pub fill: Option<Fill>,
 84
 85    /// The border color of this element
 86    pub border_color: Option<Hsla>,
 87
 88    /// The radius of the corners of this element
 89    #[refineable]
 90    pub corner_radii: Corners<AbsoluteLength>,
 91
 92    /// TEXT
 93    pub text: TextStyleRefinement,
 94}
 95
 96#[derive(Refineable, Clone, Debug)]
 97#[refineable(debug)]
 98pub struct TextStyle {
 99    pub color: Hsla,
100    pub font_family: SharedString,
101    pub font_features: FontFeatures,
102    pub font_size: Rems,
103    pub line_height: DefiniteLength,
104    pub font_weight: FontWeight,
105    pub font_style: FontStyle,
106    pub underline: Option<UnderlineStyle>,
107}
108
109impl Default for TextStyle {
110    fn default() -> Self {
111        TextStyle {
112            color: Hsla::default(),
113            font_family: SharedString::default(),
114            font_features: FontFeatures::default(),
115            font_size: rems(1.),
116            line_height: phi(),
117            font_weight: FontWeight::default(),
118            font_style: FontStyle::default(),
119            underline: None,
120        }
121    }
122}
123
124impl TextStyle {
125    pub fn highlight(mut self, style: HighlightStyle) -> Result<Self> {
126        if let Some(weight) = style.font_weight {
127            self.font_weight = weight;
128        }
129        if let Some(style) = style.font_style {
130            self.font_style = style;
131        }
132
133        if let Some(color) = style.color {
134            self.color = self.color.blend(color);
135        }
136
137        if let Some(factor) = style.fade_out {
138            self.color.fade_out(factor);
139        }
140
141        if let Some(underline) = style.underline {
142            self.underline = Some(underline);
143        }
144
145        Ok(self)
146    }
147
148    pub fn to_run(&self) -> RunStyle {
149        RunStyle {
150            font: Font {
151                family: self.font_family.clone(),
152                features: Default::default(),
153                weight: self.font_weight,
154                style: self.font_style,
155            },
156            color: self.color,
157            underline: self.underline.clone(),
158        }
159    }
160}
161
162#[derive(Clone, Debug, Default, PartialEq)]
163pub struct HighlightStyle {
164    pub color: Option<Hsla>,
165    pub font_weight: Option<FontWeight>,
166    pub font_style: Option<FontStyle>,
167    pub underline: Option<UnderlineStyle>,
168    pub fade_out: Option<f32>,
169}
170
171impl Eq for HighlightStyle {}
172
173impl Style {
174    pub fn text_style(&self, _cx: &WindowContext) -> Option<&TextStyleRefinement> {
175        if self.text.is_some() {
176            Some(&self.text)
177        } else {
178            None
179        }
180    }
181
182    pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
183    where
184        C: BorrowAppContext,
185        F: FnOnce(&mut C) -> R,
186    {
187        if self.text.is_some() {
188            cx.with_text_style(self.text.clone(), f)
189        } else {
190            f(cx)
191        }
192    }
193
194    /// Apply overflow to content mask
195    pub fn apply_overflow<C, F, R>(&self, bounds: Bounds<Pixels>, cx: &mut C, f: F) -> R
196    where
197        C: BorrowWindow,
198        F: FnOnce(&mut C) -> R,
199    {
200        let current_mask = cx.content_mask();
201
202        let min = current_mask.bounds.origin;
203        let max = current_mask.bounds.lower_right();
204
205        let mask_corner_radii = Corners::default();
206        let mask_bounds = match (
207            self.overflow.x == Overflow::Visible,
208            self.overflow.y == Overflow::Visible,
209        ) {
210            // x and y both visible
211            (true, true) => return f(cx),
212            // x visible, y hidden
213            (true, false) => Bounds::from_corners(
214                point(min.x, bounds.origin.y),
215                point(max.x, bounds.lower_right().y),
216            ),
217            // x hidden, y visible
218            (false, true) => Bounds::from_corners(
219                point(bounds.origin.x, min.y),
220                point(bounds.lower_right().x, max.y),
221            ),
222            // both hidden
223            (false, false) => bounds,
224        };
225        let mask = ContentMask {
226            bounds: mask_bounds,
227            corner_radii: mask_corner_radii,
228        };
229
230        cx.with_content_mask(mask, f)
231    }
232
233    /// Paints the background of an element styled with this style.
234    pub fn paint<V: 'static>(&self, order: u32, bounds: Bounds<Pixels>, cx: &mut ViewContext<V>) {
235        let rem_size = cx.rem_size();
236        let scale = cx.scale_factor();
237
238        let background_color = self.fill.as_ref().and_then(Fill::color);
239        if background_color.is_some() || self.is_border_visible() {
240            let layer_id = cx.current_layer_id();
241            cx.scene().insert(
242                layer_id,
243                Quad {
244                    order,
245                    bounds: bounds.scale(scale),
246                    clip_bounds: bounds.scale(scale), // todo!
247                    clip_corner_radii: self
248                        .corner_radii
249                        .map(|length| length.to_pixels(rem_size).scale(scale)),
250                    background: background_color.unwrap_or_default(),
251                    border_color: self.border_color.unwrap_or_default(),
252                    corner_radii: self
253                        .corner_radii
254                        .map(|length| length.to_pixels(rem_size).scale(scale)),
255                    border_widths: self
256                        .border_widths
257                        .map(|length| length.to_pixels(rem_size).scale(scale)),
258                },
259            );
260        }
261    }
262
263    fn is_border_visible(&self) -> bool {
264        self.border_color
265            .map_or(false, |color| !color.is_transparent())
266            && self.border_widths.any(|length| !length.is_zero())
267    }
268}
269
270impl Default for Style {
271    fn default() -> Self {
272        Style {
273            display: Display::Block,
274            overflow: Point {
275                x: Overflow::Visible,
276                y: Overflow::Visible,
277            },
278            scrollbar_width: 0.0,
279            position: Position::Relative,
280            inset: Edges::auto(),
281            margin: Edges::<Length>::zero(),
282            padding: Edges::<DefiniteLength>::zero(),
283            border_widths: Edges::<AbsoluteLength>::zero(),
284            size: Size::auto(),
285            min_size: Size::auto(),
286            max_size: Size::auto(),
287            aspect_ratio: None,
288            gap: Size::zero(),
289            // Aligment
290            align_items: None,
291            align_self: None,
292            align_content: None,
293            justify_content: None,
294            // Flexbox
295            flex_direction: FlexDirection::Row,
296            flex_wrap: FlexWrap::NoWrap,
297            flex_grow: 0.0,
298            flex_shrink: 1.0,
299            flex_basis: Length::Auto,
300            fill: None,
301            border_color: None,
302            corner_radii: Corners::default(),
303            text: TextStyleRefinement::default(),
304        }
305    }
306}
307
308#[derive(Refineable, Clone, Default, Debug, PartialEq, Eq)]
309#[refineable(debug)]
310pub struct UnderlineStyle {
311    pub thickness: Pixels,
312    pub color: Option<Hsla>,
313    pub squiggly: bool,
314}
315
316#[derive(Clone, Debug)]
317pub enum Fill {
318    Color(Hsla),
319}
320
321impl Fill {
322    pub fn color(&self) -> Option<Hsla> {
323        match self {
324            Fill::Color(color) => Some(*color),
325        }
326    }
327}
328
329impl Default for Fill {
330    fn default() -> Self {
331        Self::Color(Hsla::default())
332    }
333}
334
335impl From<Hsla> for Fill {
336    fn from(color: Hsla) -> Self {
337        Self::Color(color)
338    }
339}
340
341impl From<TextStyle> for HighlightStyle {
342    fn from(other: TextStyle) -> Self {
343        Self::from(&other)
344    }
345}
346
347impl From<&TextStyle> for HighlightStyle {
348    fn from(other: &TextStyle) -> Self {
349        Self {
350            color: Some(other.color),
351            font_weight: Some(other.font_weight),
352            font_style: Some(other.font_style),
353            underline: other.underline.clone(),
354            fade_out: None,
355        }
356    }
357}
358
359impl HighlightStyle {
360    pub fn highlight(&mut self, other: HighlightStyle) {
361        match (self.color, other.color) {
362            (Some(self_color), Some(other_color)) => {
363                self.color = Some(Hsla::blend(other_color, self_color));
364            }
365            (None, Some(other_color)) => {
366                self.color = Some(other_color);
367            }
368            _ => {}
369        }
370
371        if other.font_weight.is_some() {
372            self.font_weight = other.font_weight;
373        }
374
375        if other.font_style.is_some() {
376            self.font_style = other.font_style;
377        }
378
379        if other.underline.is_some() {
380            self.underline = other.underline;
381        }
382
383        match (other.fade_out, self.fade_out) {
384            (Some(source_fade), None) => self.fade_out = Some(source_fade),
385            (Some(source_fade), Some(dest_fade)) => {
386                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
387            }
388            _ => {}
389        }
390    }
391}
392
393impl From<Hsla> for HighlightStyle {
394    fn from(color: Hsla) -> Self {
395        Self {
396            color: Some(color),
397            ..Default::default()
398        }
399    }
400}