style.rs

  1use crate::{
  2    black, phi, point, rems, AbsoluteLength, BorrowAppContext, BorrowWindow, Bounds, ContentMask,
  3    Corners, CornersRefinement, DefiniteLength, Edges, EdgesRefinement, Font, FontFeatures,
  4    FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rems, Result, Rgba,
  5    SharedString, Size, SizeRefinement, Styled, TextRun, 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 background: 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
104impl Styled for StyleRefinement {
105    fn style(&mut self) -> &mut StyleRefinement {
106        self
107    }
108}
109
110#[derive(Clone, Debug)]
111pub struct BoxShadow {
112    pub color: Hsla,
113    pub offset: Point<Pixels>,
114    pub blur_radius: Pixels,
115    pub spread_radius: Pixels,
116}
117
118#[derive(Refineable, Clone, Debug)]
119#[refineable(debug)]
120pub struct TextStyle {
121    pub color: Hsla,
122    pub font_family: SharedString,
123    pub font_features: FontFeatures,
124    pub font_size: Rems,
125    pub line_height: DefiniteLength,
126    pub font_weight: FontWeight,
127    pub font_style: FontStyle,
128    pub underline: Option<UnderlineStyle>,
129}
130
131impl Default for TextStyle {
132    fn default() -> Self {
133        TextStyle {
134            color: black(),
135            font_family: "Helvetica".into(), // todo!("Get a font we know exists on the system")
136            font_features: FontFeatures::default(),
137            font_size: rems(1.),
138            line_height: phi(),
139            font_weight: FontWeight::default(),
140            font_style: FontStyle::default(),
141            underline: None,
142        }
143    }
144}
145
146impl TextStyle {
147    pub fn highlight(mut self, style: HighlightStyle) -> Result<Self> {
148        if let Some(weight) = style.font_weight {
149            self.font_weight = weight;
150        }
151        if let Some(style) = style.font_style {
152            self.font_style = style;
153        }
154
155        if let Some(color) = style.color {
156            self.color = self.color.blend(color);
157        }
158
159        if let Some(factor) = style.fade_out {
160            self.color.fade_out(factor);
161        }
162
163        if let Some(underline) = style.underline {
164            self.underline = Some(underline);
165        }
166
167        Ok(self)
168    }
169
170    pub fn to_run(&self, len: usize) -> TextRun {
171        TextRun {
172            len,
173            font: Font {
174                family: self.font_family.clone(),
175                features: Default::default(),
176                weight: self.font_weight,
177                style: self.font_style,
178            },
179            color: self.color,
180            underline: self.underline.clone(),
181        }
182    }
183}
184
185#[derive(Copy, Clone, Debug, Default, PartialEq)]
186pub struct HighlightStyle {
187    pub color: Option<Hsla>,
188    pub font_weight: Option<FontWeight>,
189    pub font_style: Option<FontStyle>,
190    pub underline: Option<UnderlineStyle>,
191    pub fade_out: Option<f32>,
192}
193
194impl Eq for HighlightStyle {}
195
196impl Style {
197    pub fn text_style(&self, _cx: &WindowContext) -> Option<&TextStyleRefinement> {
198        if self.text.is_some() {
199            Some(&self.text)
200        } else {
201            None
202        }
203    }
204
205    pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
206    where
207        C: BorrowAppContext,
208        F: FnOnce(&mut C) -> R,
209    {
210        if self.text.is_some() {
211            cx.with_text_style(self.text.clone(), f)
212        } else {
213            f(cx)
214        }
215    }
216
217    /// Apply overflow to content mask
218    pub fn apply_overflow<C, F, R>(&self, bounds: Bounds<Pixels>, cx: &mut C, f: F) -> R
219    where
220        C: BorrowWindow,
221        F: FnOnce(&mut C) -> R,
222    {
223        let current_mask = cx.content_mask();
224
225        let min = current_mask.bounds.origin;
226        let max = current_mask.bounds.lower_right();
227
228        let mask_bounds = match (
229            self.overflow.x == Overflow::Visible,
230            self.overflow.y == Overflow::Visible,
231        ) {
232            // x and y both visible
233            (true, true) => return f(cx),
234            // x visible, y hidden
235            (true, false) => Bounds::from_corners(
236                point(min.x, bounds.origin.y),
237                point(max.x, bounds.lower_right().y),
238            ),
239            // x hidden, y visible
240            (false, true) => Bounds::from_corners(
241                point(bounds.origin.x, min.y),
242                point(bounds.lower_right().x, max.y),
243            ),
244            // both hidden
245            (false, false) => bounds,
246        };
247        let mask = ContentMask {
248            bounds: mask_bounds,
249        };
250
251        cx.with_content_mask(mask, f)
252    }
253
254    /// Paints the background of an element styled with this style.
255    pub fn paint<V: 'static>(&self, bounds: Bounds<Pixels>, cx: &mut ViewContext<V>) {
256        let rem_size = cx.rem_size();
257
258        cx.stack(0, |cx| {
259            cx.paint_shadows(
260                bounds,
261                self.corner_radii.to_pixels(bounds.size, rem_size),
262                &self.box_shadow,
263            );
264        });
265
266        let background_color = self.background.as_ref().and_then(Fill::color);
267        if background_color.is_some() || self.is_border_visible() {
268            cx.stack(1, |cx| {
269                cx.paint_quad(
270                    bounds,
271                    self.corner_radii.to_pixels(bounds.size, rem_size),
272                    background_color.unwrap_or_default(),
273                    self.border_widths.to_pixels(rem_size),
274                    self.border_color.unwrap_or_default(),
275                );
276            });
277        }
278    }
279
280    fn is_border_visible(&self) -> bool {
281        self.border_color
282            .map_or(false, |color| !color.is_transparent())
283            && self.border_widths.any(|length| !length.is_zero())
284    }
285}
286
287impl Default for Style {
288    fn default() -> Self {
289        Style {
290            display: Display::Block,
291            overflow: Point {
292                x: Overflow::Visible,
293                y: Overflow::Visible,
294            },
295            scrollbar_width: 0.0,
296            position: Position::Relative,
297            inset: Edges::auto(),
298            margin: Edges::<Length>::zero(),
299            padding: Edges::<DefiniteLength>::zero(),
300            border_widths: Edges::<AbsoluteLength>::zero(),
301            size: Size::auto(),
302            min_size: Size::auto(),
303            max_size: Size::auto(),
304            aspect_ratio: None,
305            gap: Size::zero(),
306            // Aligment
307            align_items: None,
308            align_self: None,
309            align_content: None,
310            justify_content: None,
311            // Flexbox
312            flex_direction: FlexDirection::Row,
313            flex_wrap: FlexWrap::NoWrap,
314            flex_grow: 0.0,
315            flex_shrink: 1.0,
316            flex_basis: Length::Auto,
317            background: None,
318            border_color: None,
319            corner_radii: Corners::default(),
320            box_shadow: Default::default(),
321            text: TextStyleRefinement::default(),
322            z_index: None,
323        }
324    }
325}
326
327#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
328#[refineable(debug)]
329pub struct UnderlineStyle {
330    pub thickness: Pixels,
331    pub color: Option<Hsla>,
332    pub wavy: bool,
333}
334
335#[derive(Clone, Debug)]
336pub enum Fill {
337    Color(Hsla),
338}
339
340impl Fill {
341    pub fn color(&self) -> Option<Hsla> {
342        match self {
343            Fill::Color(color) => Some(*color),
344        }
345    }
346}
347
348impl Default for Fill {
349    fn default() -> Self {
350        Self::Color(Hsla::default())
351    }
352}
353
354impl From<Hsla> for Fill {
355    fn from(color: Hsla) -> Self {
356        Self::Color(color)
357    }
358}
359
360impl From<TextStyle> for HighlightStyle {
361    fn from(other: TextStyle) -> Self {
362        Self::from(&other)
363    }
364}
365
366impl From<&TextStyle> for HighlightStyle {
367    fn from(other: &TextStyle) -> Self {
368        Self {
369            color: Some(other.color),
370            font_weight: Some(other.font_weight),
371            font_style: Some(other.font_style),
372            underline: other.underline.clone(),
373            fade_out: None,
374        }
375    }
376}
377
378impl HighlightStyle {
379    pub fn highlight(&mut self, other: HighlightStyle) {
380        match (self.color, other.color) {
381            (Some(self_color), Some(other_color)) => {
382                self.color = Some(Hsla::blend(other_color, self_color));
383            }
384            (None, Some(other_color)) => {
385                self.color = Some(other_color);
386            }
387            _ => {}
388        }
389
390        if other.font_weight.is_some() {
391            self.font_weight = other.font_weight;
392        }
393
394        if other.font_style.is_some() {
395            self.font_style = other.font_style;
396        }
397
398        if other.underline.is_some() {
399            self.underline = other.underline;
400        }
401
402        match (other.fade_out, self.fade_out) {
403            (Some(source_fade), None) => self.fade_out = Some(source_fade),
404            (Some(source_fade), Some(dest_fade)) => {
405                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
406            }
407            _ => {}
408        }
409    }
410}
411
412impl From<Hsla> for HighlightStyle {
413    fn from(color: Hsla) -> Self {
414        Self {
415            color: Some(color),
416            ..Default::default()
417        }
418    }
419}
420
421impl From<Rgba> for HighlightStyle {
422    fn from(color: Rgba) -> Self {
423        Self {
424            color: Some(color.into()),
425            ..Default::default()
426        }
427    }
428}