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