style.rs

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