style.rs

  1use std::{iter, mem, ops::Range};
  2
  3use crate::{
  4    black, phi, point, quad, rems, AbsoluteLength, Bounds, ContentMask, Corners, CornersRefinement,
  5    CursorStyle, DefiniteLength, Edges, EdgesRefinement, ElementContext, Font, FontFeatures,
  6    FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba, SharedString, Size,
  7    SizeRefinement, Styled, TextRun,
  8};
  9use collections::HashSet;
 10use refineable::{Cascade, Refineable};
 11use smallvec::SmallVec;
 12pub use taffy::style::{
 13    AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
 14    Overflow, Position,
 15};
 16
 17#[cfg(debug_assertions)]
 18pub struct DebugBelow;
 19
 20pub type StyleCascade = Cascade<Style>;
 21
 22#[derive(Clone, Refineable, Debug)]
 23#[refineable(Debug)]
 24pub struct Style {
 25    /// What layout strategy should be used?
 26    pub display: Display,
 27
 28    /// Should the element be painted on screen?
 29    pub visibility: Visibility,
 30
 31    // Overflow properties
 32    /// How children overflowing their container should affect layout
 33    #[refineable]
 34    pub overflow: Point<Overflow>,
 35    /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
 36    pub scrollbar_width: f32,
 37
 38    // Position properties
 39    /// What should the `position` value of this struct use as a base offset?
 40    pub position: Position,
 41    /// How should the position of this element be tweaked relative to the layout defined?
 42    #[refineable]
 43    pub inset: Edges<Length>,
 44
 45    // Size properties
 46    /// Sets the initial size of the item
 47    #[refineable]
 48    pub size: Size<Length>,
 49    /// Controls the minimum size of the item
 50    #[refineable]
 51    pub min_size: Size<Length>,
 52    /// Controls the maximum size of the item
 53    #[refineable]
 54    pub max_size: Size<Length>,
 55    /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
 56    pub aspect_ratio: Option<f32>,
 57
 58    // Spacing Properties
 59    /// How large should the margin be on each side?
 60    #[refineable]
 61    pub margin: Edges<Length>,
 62    /// How large should the padding be on each side?
 63    #[refineable]
 64    pub padding: Edges<DefiniteLength>,
 65    /// How large should the border be on each side?
 66    #[refineable]
 67    pub border_widths: Edges<AbsoluteLength>,
 68
 69    // Alignment properties
 70    /// How this node's children aligned in the cross/block axis?
 71    pub align_items: Option<AlignItems>,
 72    /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
 73    pub align_self: Option<AlignSelf>,
 74    /// How should content contained within this item be aligned in the cross/block axis
 75    pub align_content: Option<AlignContent>,
 76    /// How should contained within this item be aligned in the main/inline axis
 77    pub justify_content: Option<JustifyContent>,
 78    /// How large should the gaps between items in a flex container be?
 79    #[refineable]
 80    pub gap: Size<DefiniteLength>,
 81
 82    // Flexbox properties
 83    /// Which direction does the main axis flow in?
 84    pub flex_direction: FlexDirection,
 85    /// Should elements wrap, or stay in a single line?
 86    pub flex_wrap: FlexWrap,
 87    /// Sets the initial main axis size of the item
 88    pub flex_basis: Length,
 89    /// 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.
 90    pub flex_grow: f32,
 91    /// 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.
 92    pub flex_shrink: f32,
 93
 94    /// The fill color of this element
 95    pub background: Option<Fill>,
 96
 97    /// The border color of this element
 98    pub border_color: Option<Hsla>,
 99
100    /// The radius of the corners of this element
101    #[refineable]
102    pub corner_radii: Corners<AbsoluteLength>,
103
104    /// Box Shadow of the element
105    pub box_shadow: SmallVec<[BoxShadow; 2]>,
106
107    /// TEXT
108    pub text: TextStyleRefinement,
109
110    /// The mouse cursor style shown when the mouse pointer is over an element.
111    pub mouse_cursor: Option<CursorStyle>,
112
113    pub z_index: Option<u16>,
114
115    #[cfg(debug_assertions)]
116    pub debug: bool,
117    #[cfg(debug_assertions)]
118    pub debug_below: bool,
119}
120
121impl Styled for StyleRefinement {
122    fn style(&mut self) -> &mut StyleRefinement {
123        self
124    }
125}
126
127#[derive(Default, Clone, Copy, Debug, Eq, PartialEq)]
128pub enum Visibility {
129    #[default]
130    Visible,
131    Hidden,
132}
133
134#[derive(Clone, Debug)]
135pub struct BoxShadow {
136    pub color: Hsla,
137    pub offset: Point<Pixels>,
138    pub blur_radius: Pixels,
139    pub spread_radius: Pixels,
140}
141
142#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
143pub enum WhiteSpace {
144    #[default]
145    Normal,
146    Nowrap,
147}
148
149#[derive(Refineable, Clone, Debug, PartialEq)]
150#[refineable(Debug)]
151pub struct TextStyle {
152    pub color: Hsla,
153    pub font_family: SharedString,
154    pub font_features: FontFeatures,
155    pub font_size: AbsoluteLength,
156    pub line_height: DefiniteLength,
157    pub font_weight: FontWeight,
158    pub font_style: FontStyle,
159    pub background_color: Option<Hsla>,
160    pub underline: Option<UnderlineStyle>,
161    pub white_space: WhiteSpace,
162}
163
164impl Default for TextStyle {
165    fn default() -> Self {
166        TextStyle {
167            color: black(),
168            // Helvetica is a web safe font, so it should be available
169            font_family: "Helvetica".into(),
170            font_features: FontFeatures::default(),
171            font_size: rems(1.).into(),
172            line_height: phi(),
173            font_weight: FontWeight::default(),
174            font_style: FontStyle::default(),
175            background_color: None,
176            underline: None,
177            white_space: WhiteSpace::Normal,
178        }
179    }
180}
181
182impl TextStyle {
183    pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
184        let style = style.into();
185        if let Some(weight) = style.font_weight {
186            self.font_weight = weight;
187        }
188        if let Some(style) = style.font_style {
189            self.font_style = style;
190        }
191
192        if let Some(color) = style.color {
193            self.color = self.color.blend(color);
194        }
195
196        if let Some(factor) = style.fade_out {
197            self.color.fade_out(factor);
198        }
199
200        if let Some(background_color) = style.background_color {
201            self.background_color = Some(background_color);
202        }
203
204        if let Some(underline) = style.underline {
205            self.underline = Some(underline);
206        }
207
208        self
209    }
210
211    pub fn font(&self) -> Font {
212        Font {
213            family: self.font_family.clone(),
214            features: self.font_features,
215            weight: self.font_weight,
216            style: self.font_style,
217        }
218    }
219
220    /// Returns the rounded line height in pixels.
221    pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
222        self.line_height.to_pixels(self.font_size, rem_size).round()
223    }
224
225    pub fn to_run(&self, len: usize) -> TextRun {
226        TextRun {
227            len,
228            font: Font {
229                family: self.font_family.clone(),
230                features: Default::default(),
231                weight: self.font_weight,
232                style: self.font_style,
233            },
234            color: self.color,
235            background_color: self.background_color,
236            underline: self.underline,
237        }
238    }
239}
240
241#[derive(Copy, Clone, Debug, Default, PartialEq)]
242pub struct HighlightStyle {
243    pub color: Option<Hsla>,
244    pub font_weight: Option<FontWeight>,
245    pub font_style: Option<FontStyle>,
246    pub background_color: Option<Hsla>,
247    pub underline: Option<UnderlineStyle>,
248    pub fade_out: Option<f32>,
249}
250
251impl Eq for HighlightStyle {}
252
253impl Style {
254    pub fn text_style(&self) -> Option<&TextStyleRefinement> {
255        if self.text.is_some() {
256            Some(&self.text)
257        } else {
258            None
259        }
260    }
261
262    pub fn overflow_mask(
263        &self,
264        bounds: Bounds<Pixels>,
265        rem_size: Pixels,
266    ) -> Option<ContentMask<Pixels>> {
267        match self.overflow {
268            Point {
269                x: Overflow::Visible,
270                y: Overflow::Visible,
271            } => None,
272            _ => {
273                let mut min = bounds.origin;
274                let mut max = bounds.lower_right();
275
276                if self
277                    .border_color
278                    .map_or(false, |color| !color.is_transparent())
279                {
280                    min.x += self.border_widths.left.to_pixels(rem_size);
281                    max.x -= self.border_widths.right.to_pixels(rem_size);
282                    min.y += self.border_widths.top.to_pixels(rem_size);
283                    max.y -= self.border_widths.bottom.to_pixels(rem_size);
284                }
285
286                let bounds = match (
287                    self.overflow.x == Overflow::Visible,
288                    self.overflow.y == Overflow::Visible,
289                ) {
290                    // x and y both visible
291                    (true, true) => return None,
292                    // x visible, y hidden
293                    (true, false) => Bounds::from_corners(
294                        point(min.x, bounds.origin.y),
295                        point(max.x, bounds.lower_right().y),
296                    ),
297                    // x hidden, y visible
298                    (false, true) => Bounds::from_corners(
299                        point(bounds.origin.x, min.y),
300                        point(bounds.lower_right().x, max.y),
301                    ),
302                    // both hidden
303                    (false, false) => Bounds::from_corners(min, max),
304                };
305
306                Some(ContentMask { bounds })
307            }
308        }
309    }
310
311    /// Paints the background of an element styled with this style.
312    pub fn paint(
313        &self,
314        bounds: Bounds<Pixels>,
315        cx: &mut ElementContext,
316        continuation: impl FnOnce(&mut ElementContext),
317    ) {
318        #[cfg(debug_assertions)]
319        if self.debug_below {
320            cx.set_global(DebugBelow)
321        }
322
323        #[cfg(debug_assertions)]
324        if self.debug || cx.has_global::<DebugBelow>() {
325            cx.paint_quad(crate::outline(bounds, crate::red()));
326        }
327
328        let rem_size = cx.rem_size();
329
330        cx.with_z_index(0, |cx| {
331            cx.paint_shadows(
332                bounds,
333                self.corner_radii.to_pixels(bounds.size, rem_size),
334                &self.box_shadow,
335            );
336        });
337
338        let background_color = self.background.as_ref().and_then(Fill::color);
339        if background_color.map_or(false, |color| !color.is_transparent()) {
340            cx.with_z_index(1, |cx| {
341                let mut border_color = background_color.unwrap_or_default();
342                border_color.a = 0.;
343                cx.paint_quad(quad(
344                    bounds,
345                    self.corner_radii.to_pixels(bounds.size, rem_size),
346                    background_color.unwrap_or_default(),
347                    Edges::default(),
348                    border_color,
349                ));
350            });
351        }
352
353        cx.with_z_index(2, |cx| {
354            continuation(cx);
355        });
356
357        if self.is_border_visible() {
358            cx.with_z_index(3, |cx| {
359                let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
360                let border_widths = self.border_widths.to_pixels(rem_size);
361                let max_border_width = border_widths.max();
362                let max_corner_radius = corner_radii.max();
363
364                let top_bounds = Bounds::from_corners(
365                    bounds.origin,
366                    bounds.upper_right()
367                        + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
368                );
369                let bottom_bounds = Bounds::from_corners(
370                    bounds.lower_left()
371                        - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
372                    bounds.lower_right(),
373                );
374                let left_bounds = Bounds::from_corners(
375                    top_bounds.lower_left(),
376                    bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
377                );
378                let right_bounds = Bounds::from_corners(
379                    top_bounds.lower_right() - point(max_border_width, Pixels::ZERO),
380                    bottom_bounds.upper_right(),
381                );
382
383                let mut background = self.border_color.unwrap_or_default();
384                background.a = 0.;
385                let quad = quad(
386                    bounds,
387                    corner_radii,
388                    background,
389                    border_widths,
390                    self.border_color.unwrap_or_default(),
391                );
392
393                cx.with_content_mask(Some(ContentMask { bounds: top_bounds }), |cx| {
394                    cx.paint_quad(quad.clone());
395                });
396                cx.with_content_mask(
397                    Some(ContentMask {
398                        bounds: right_bounds,
399                    }),
400                    |cx| {
401                        cx.paint_quad(quad.clone());
402                    },
403                );
404                cx.with_content_mask(
405                    Some(ContentMask {
406                        bounds: bottom_bounds,
407                    }),
408                    |cx| {
409                        cx.paint_quad(quad.clone());
410                    },
411                );
412                cx.with_content_mask(
413                    Some(ContentMask {
414                        bounds: left_bounds,
415                    }),
416                    |cx| {
417                        cx.paint_quad(quad);
418                    },
419                );
420            });
421        }
422
423        #[cfg(debug_assertions)]
424        if self.debug_below {
425            cx.remove_global::<DebugBelow>();
426        }
427    }
428
429    fn is_border_visible(&self) -> bool {
430        self.border_color
431            .map_or(false, |color| !color.is_transparent())
432            && self.border_widths.any(|length| !length.is_zero())
433    }
434}
435
436impl Default for Style {
437    fn default() -> Self {
438        Style {
439            display: Display::Block,
440            visibility: Visibility::Visible,
441            overflow: Point {
442                x: Overflow::Visible,
443                y: Overflow::Visible,
444            },
445            scrollbar_width: 0.0,
446            position: Position::Relative,
447            inset: Edges::auto(),
448            margin: Edges::<Length>::zero(),
449            padding: Edges::<DefiniteLength>::zero(),
450            border_widths: Edges::<AbsoluteLength>::zero(),
451            size: Size::auto(),
452            min_size: Size::auto(),
453            max_size: Size::auto(),
454            aspect_ratio: None,
455            gap: Size::default(),
456            // Alignment
457            align_items: None,
458            align_self: None,
459            align_content: None,
460            justify_content: None,
461            // Flexbox
462            flex_direction: FlexDirection::Row,
463            flex_wrap: FlexWrap::NoWrap,
464            flex_grow: 0.0,
465            flex_shrink: 1.0,
466            flex_basis: Length::Auto,
467            background: None,
468            border_color: None,
469            corner_radii: Corners::default(),
470            box_shadow: Default::default(),
471            text: TextStyleRefinement::default(),
472            mouse_cursor: None,
473            z_index: None,
474
475            #[cfg(debug_assertions)]
476            debug: false,
477            #[cfg(debug_assertions)]
478            debug_below: false,
479        }
480    }
481}
482
483#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
484#[refineable(Debug)]
485pub struct UnderlineStyle {
486    pub thickness: Pixels,
487    pub color: Option<Hsla>,
488    pub wavy: bool,
489}
490
491#[derive(Clone, Debug)]
492pub enum Fill {
493    Color(Hsla),
494}
495
496impl Fill {
497    pub fn color(&self) -> Option<Hsla> {
498        match self {
499            Fill::Color(color) => Some(*color),
500        }
501    }
502}
503
504impl Default for Fill {
505    fn default() -> Self {
506        Self::Color(Hsla::default())
507    }
508}
509
510impl From<Hsla> for Fill {
511    fn from(color: Hsla) -> Self {
512        Self::Color(color)
513    }
514}
515
516impl From<Rgba> for Fill {
517    fn from(color: Rgba) -> Self {
518        Self::Color(color.into())
519    }
520}
521
522impl From<TextStyle> for HighlightStyle {
523    fn from(other: TextStyle) -> Self {
524        Self::from(&other)
525    }
526}
527
528impl From<&TextStyle> for HighlightStyle {
529    fn from(other: &TextStyle) -> Self {
530        Self {
531            color: Some(other.color),
532            font_weight: Some(other.font_weight),
533            font_style: Some(other.font_style),
534            background_color: other.background_color,
535            underline: other.underline,
536            fade_out: None,
537        }
538    }
539}
540
541impl HighlightStyle {
542    pub fn highlight(&mut self, other: HighlightStyle) {
543        match (self.color, other.color) {
544            (Some(self_color), Some(other_color)) => {
545                self.color = Some(Hsla::blend(other_color, self_color));
546            }
547            (None, Some(other_color)) => {
548                self.color = Some(other_color);
549            }
550            _ => {}
551        }
552
553        if other.font_weight.is_some() {
554            self.font_weight = other.font_weight;
555        }
556
557        if other.font_style.is_some() {
558            self.font_style = other.font_style;
559        }
560
561        if other.background_color.is_some() {
562            self.background_color = other.background_color;
563        }
564
565        if other.underline.is_some() {
566            self.underline = other.underline;
567        }
568
569        match (other.fade_out, self.fade_out) {
570            (Some(source_fade), None) => self.fade_out = Some(source_fade),
571            (Some(source_fade), Some(dest_fade)) => {
572                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
573            }
574            _ => {}
575        }
576    }
577}
578
579impl From<Hsla> for HighlightStyle {
580    fn from(color: Hsla) -> Self {
581        Self {
582            color: Some(color),
583            ..Default::default()
584        }
585    }
586}
587
588impl From<FontWeight> for HighlightStyle {
589    fn from(font_weight: FontWeight) -> Self {
590        Self {
591            font_weight: Some(font_weight),
592            ..Default::default()
593        }
594    }
595}
596
597impl From<FontStyle> for HighlightStyle {
598    fn from(font_style: FontStyle) -> Self {
599        Self {
600            font_style: Some(font_style),
601            ..Default::default()
602        }
603    }
604}
605
606impl From<Rgba> for HighlightStyle {
607    fn from(color: Rgba) -> Self {
608        Self {
609            color: Some(color.into()),
610            ..Default::default()
611        }
612    }
613}
614
615pub fn combine_highlights(
616    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
617    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
618) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
619    let mut endpoints = Vec::new();
620    let mut highlights = Vec::new();
621    for (range, highlight) in a.into_iter().chain(b) {
622        if !range.is_empty() {
623            let highlight_id = highlights.len();
624            endpoints.push((range.start, highlight_id, true));
625            endpoints.push((range.end, highlight_id, false));
626            highlights.push(highlight);
627        }
628    }
629    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
630    let mut endpoints = endpoints.into_iter().peekable();
631
632    let mut active_styles = HashSet::default();
633    let mut ix = 0;
634    iter::from_fn(move || {
635        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
636            let prev_index = mem::replace(&mut ix, *endpoint_ix);
637            if ix > prev_index && !active_styles.is_empty() {
638                let mut current_style = HighlightStyle::default();
639                for highlight_id in &active_styles {
640                    current_style.highlight(highlights[*highlight_id]);
641                }
642                return Some((prev_index..ix, current_style));
643            }
644
645            if *is_start {
646                active_styles.insert(*highlight_id);
647            } else {
648                active_styles.remove(highlight_id);
649            }
650            endpoints.next();
651        }
652        None
653    })
654}
655
656#[cfg(test)]
657mod tests {
658    use crate::{blue, green, red, yellow};
659
660    use super::*;
661
662    #[test]
663    fn test_combine_highlights() {
664        assert_eq!(
665            combine_highlights(
666                [
667                    (0..5, green().into()),
668                    (4..10, FontWeight::BOLD.into()),
669                    (15..20, yellow().into()),
670                ],
671                [
672                    (2..6, FontStyle::Italic.into()),
673                    (1..3, blue().into()),
674                    (21..23, red().into()),
675                ]
676            )
677            .collect::<Vec<_>>(),
678            [
679                (
680                    0..1,
681                    HighlightStyle {
682                        color: Some(green()),
683                        ..Default::default()
684                    }
685                ),
686                (
687                    1..2,
688                    HighlightStyle {
689                        color: Some(green()),
690                        ..Default::default()
691                    }
692                ),
693                (
694                    2..3,
695                    HighlightStyle {
696                        color: Some(green()),
697                        font_style: Some(FontStyle::Italic),
698                        ..Default::default()
699                    }
700                ),
701                (
702                    3..4,
703                    HighlightStyle {
704                        color: Some(green()),
705                        font_style: Some(FontStyle::Italic),
706                        ..Default::default()
707                    }
708                ),
709                (
710                    4..5,
711                    HighlightStyle {
712                        color: Some(green()),
713                        font_weight: Some(FontWeight::BOLD),
714                        font_style: Some(FontStyle::Italic),
715                        ..Default::default()
716                    }
717                ),
718                (
719                    5..6,
720                    HighlightStyle {
721                        font_weight: Some(FontWeight::BOLD),
722                        font_style: Some(FontStyle::Italic),
723                        ..Default::default()
724                    }
725                ),
726                (
727                    6..10,
728                    HighlightStyle {
729                        font_weight: Some(FontWeight::BOLD),
730                        ..Default::default()
731                    }
732                ),
733                (
734                    15..20,
735                    HighlightStyle {
736                        color: Some(yellow()),
737                        ..Default::default()
738                    }
739                ),
740                (
741                    21..23,
742                    HighlightStyle {
743                        color: Some(red()),
744                        ..Default::default()
745                    }
746                )
747            ]
748        );
749    }
750}