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