style.rs

  1use std::{iter, mem, ops::Range};
  2
  3use crate::{
  4    black, phi, point, quad, rems, AbsoluteLength, BorrowAppContext, Bounds, ContentMask, Corners,
  5    CornersRefinement, CursorStyle, DefiniteLength, Edges, EdgesRefinement, ElementContext, Font,
  6    FontFeatures, FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba,
  7    SharedString, Size, 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<u8>,
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    pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
312    where
313        C: BorrowAppContext,
314        F: FnOnce(&mut C) -> R,
315    {
316        if self.text.is_some() {
317            cx.with_text_style(Some(self.text.clone()), f)
318        } else {
319            f(cx)
320        }
321    }
322
323    /// Paints the background of an element styled with this style.
324    pub fn paint(
325        &self,
326        bounds: Bounds<Pixels>,
327        cx: &mut ElementContext,
328        continuation: impl FnOnce(&mut ElementContext),
329    ) {
330        #[cfg(debug_assertions)]
331        if self.debug_below {
332            cx.set_global(DebugBelow)
333        }
334
335        #[cfg(debug_assertions)]
336        if self.debug || cx.has_global::<DebugBelow>() {
337            cx.paint_quad(crate::outline(bounds, crate::red()));
338        }
339
340        let rem_size = cx.rem_size();
341
342        cx.with_z_index(0, |cx| {
343            cx.paint_shadows(
344                bounds,
345                self.corner_radii.to_pixels(bounds.size, rem_size),
346                &self.box_shadow,
347            );
348        });
349
350        let background_color = self.background.as_ref().and_then(Fill::color);
351        if background_color.map_or(false, |color| !color.is_transparent()) {
352            cx.with_z_index(0, |cx| {
353                let mut border_color = background_color.unwrap_or_default();
354                border_color.a = 0.;
355                cx.paint_quad(quad(
356                    bounds,
357                    self.corner_radii.to_pixels(bounds.size, rem_size),
358                    background_color.unwrap_or_default(),
359                    Edges::default(),
360                    border_color,
361                ));
362            });
363        }
364
365        cx.with_z_index(0, |cx| {
366            continuation(cx);
367        });
368
369        if self.is_border_visible() {
370            cx.with_z_index(0, |cx| {
371                let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
372                let border_widths = self.border_widths.to_pixels(rem_size);
373                let max_border_width = border_widths.max();
374                let max_corner_radius = corner_radii.max();
375
376                let top_bounds = Bounds::from_corners(
377                    bounds.origin,
378                    bounds.upper_right()
379                        + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
380                );
381                let bottom_bounds = Bounds::from_corners(
382                    bounds.lower_left()
383                        - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
384                    bounds.lower_right(),
385                );
386                let left_bounds = Bounds::from_corners(
387                    top_bounds.lower_left(),
388                    bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
389                );
390                let right_bounds = Bounds::from_corners(
391                    top_bounds.lower_right() - point(max_border_width, Pixels::ZERO),
392                    bottom_bounds.upper_right(),
393                );
394
395                let mut background = self.border_color.unwrap_or_default();
396                background.a = 0.;
397                let quad = quad(
398                    bounds,
399                    corner_radii,
400                    background,
401                    border_widths,
402                    self.border_color.unwrap_or_default(),
403                );
404
405                cx.with_content_mask(Some(ContentMask { bounds: top_bounds }), |cx| {
406                    cx.paint_quad(quad.clone());
407                });
408                cx.with_content_mask(
409                    Some(ContentMask {
410                        bounds: right_bounds,
411                    }),
412                    |cx| {
413                        cx.paint_quad(quad.clone());
414                    },
415                );
416                cx.with_content_mask(
417                    Some(ContentMask {
418                        bounds: bottom_bounds,
419                    }),
420                    |cx| {
421                        cx.paint_quad(quad.clone());
422                    },
423                );
424                cx.with_content_mask(
425                    Some(ContentMask {
426                        bounds: left_bounds,
427                    }),
428                    |cx| {
429                        cx.paint_quad(quad);
430                    },
431                );
432            });
433        }
434
435        #[cfg(debug_assertions)]
436        if self.debug_below {
437            cx.remove_global::<DebugBelow>();
438        }
439    }
440
441    fn is_border_visible(&self) -> bool {
442        self.border_color
443            .map_or(false, |color| !color.is_transparent())
444            && self.border_widths.any(|length| !length.is_zero())
445    }
446}
447
448impl Default for Style {
449    fn default() -> Self {
450        Style {
451            display: Display::Block,
452            visibility: Visibility::Visible,
453            overflow: Point {
454                x: Overflow::Visible,
455                y: Overflow::Visible,
456            },
457            scrollbar_width: 0.0,
458            position: Position::Relative,
459            inset: Edges::auto(),
460            margin: Edges::<Length>::zero(),
461            padding: Edges::<DefiniteLength>::zero(),
462            border_widths: Edges::<AbsoluteLength>::zero(),
463            size: Size::auto(),
464            min_size: Size::auto(),
465            max_size: Size::auto(),
466            aspect_ratio: None,
467            gap: Size::default(),
468            // Alignment
469            align_items: None,
470            align_self: None,
471            align_content: None,
472            justify_content: None,
473            // Flexbox
474            flex_direction: FlexDirection::Row,
475            flex_wrap: FlexWrap::NoWrap,
476            flex_grow: 0.0,
477            flex_shrink: 1.0,
478            flex_basis: Length::Auto,
479            background: None,
480            border_color: None,
481            corner_radii: Corners::default(),
482            box_shadow: Default::default(),
483            text: TextStyleRefinement::default(),
484            mouse_cursor: None,
485            z_index: None,
486
487            #[cfg(debug_assertions)]
488            debug: false,
489            #[cfg(debug_assertions)]
490            debug_below: false,
491        }
492    }
493}
494
495#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
496#[refineable(Debug)]
497pub struct UnderlineStyle {
498    pub thickness: Pixels,
499    pub color: Option<Hsla>,
500    pub wavy: bool,
501}
502
503#[derive(Clone, Debug)]
504pub enum Fill {
505    Color(Hsla),
506}
507
508impl Fill {
509    pub fn color(&self) -> Option<Hsla> {
510        match self {
511            Fill::Color(color) => Some(*color),
512        }
513    }
514}
515
516impl Default for Fill {
517    fn default() -> Self {
518        Self::Color(Hsla::default())
519    }
520}
521
522impl From<Hsla> for Fill {
523    fn from(color: Hsla) -> Self {
524        Self::Color(color)
525    }
526}
527
528impl From<Rgba> for Fill {
529    fn from(color: Rgba) -> Self {
530        Self::Color(color.into())
531    }
532}
533
534impl From<TextStyle> for HighlightStyle {
535    fn from(other: TextStyle) -> Self {
536        Self::from(&other)
537    }
538}
539
540impl From<&TextStyle> for HighlightStyle {
541    fn from(other: &TextStyle) -> Self {
542        Self {
543            color: Some(other.color),
544            font_weight: Some(other.font_weight),
545            font_style: Some(other.font_style),
546            background_color: other.background_color,
547            underline: other.underline,
548            fade_out: None,
549        }
550    }
551}
552
553impl HighlightStyle {
554    pub fn highlight(&mut self, other: HighlightStyle) {
555        match (self.color, other.color) {
556            (Some(self_color), Some(other_color)) => {
557                self.color = Some(Hsla::blend(other_color, self_color));
558            }
559            (None, Some(other_color)) => {
560                self.color = Some(other_color);
561            }
562            _ => {}
563        }
564
565        if other.font_weight.is_some() {
566            self.font_weight = other.font_weight;
567        }
568
569        if other.font_style.is_some() {
570            self.font_style = other.font_style;
571        }
572
573        if other.background_color.is_some() {
574            self.background_color = other.background_color;
575        }
576
577        if other.underline.is_some() {
578            self.underline = other.underline;
579        }
580
581        match (other.fade_out, self.fade_out) {
582            (Some(source_fade), None) => self.fade_out = Some(source_fade),
583            (Some(source_fade), Some(dest_fade)) => {
584                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
585            }
586            _ => {}
587        }
588    }
589}
590
591impl From<Hsla> for HighlightStyle {
592    fn from(color: Hsla) -> Self {
593        Self {
594            color: Some(color),
595            ..Default::default()
596        }
597    }
598}
599
600impl From<FontWeight> for HighlightStyle {
601    fn from(font_weight: FontWeight) -> Self {
602        Self {
603            font_weight: Some(font_weight),
604            ..Default::default()
605        }
606    }
607}
608
609impl From<FontStyle> for HighlightStyle {
610    fn from(font_style: FontStyle) -> Self {
611        Self {
612            font_style: Some(font_style),
613            ..Default::default()
614        }
615    }
616}
617
618impl From<Rgba> for HighlightStyle {
619    fn from(color: Rgba) -> Self {
620        Self {
621            color: Some(color.into()),
622            ..Default::default()
623        }
624    }
625}
626
627pub fn combine_highlights(
628    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
629    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
630) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
631    let mut endpoints = Vec::new();
632    let mut highlights = Vec::new();
633    for (range, highlight) in a.into_iter().chain(b) {
634        if !range.is_empty() {
635            let highlight_id = highlights.len();
636            endpoints.push((range.start, highlight_id, true));
637            endpoints.push((range.end, highlight_id, false));
638            highlights.push(highlight);
639        }
640    }
641    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
642    let mut endpoints = endpoints.into_iter().peekable();
643
644    let mut active_styles = HashSet::default();
645    let mut ix = 0;
646    iter::from_fn(move || {
647        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
648            let prev_index = mem::replace(&mut ix, *endpoint_ix);
649            if ix > prev_index && !active_styles.is_empty() {
650                let mut current_style = HighlightStyle::default();
651                for highlight_id in &active_styles {
652                    current_style.highlight(highlights[*highlight_id]);
653                }
654                return Some((prev_index..ix, current_style));
655            }
656
657            if *is_start {
658                active_styles.insert(*highlight_id);
659            } else {
660                active_styles.remove(highlight_id);
661            }
662            endpoints.next();
663        }
664        None
665    })
666}
667
668#[cfg(test)]
669mod tests {
670    use crate::{blue, green, red, yellow};
671
672    use super::*;
673
674    #[test]
675    fn test_combine_highlights() {
676        assert_eq!(
677            combine_highlights(
678                [
679                    (0..5, green().into()),
680                    (4..10, FontWeight::BOLD.into()),
681                    (15..20, yellow().into()),
682                ],
683                [
684                    (2..6, FontStyle::Italic.into()),
685                    (1..3, blue().into()),
686                    (21..23, red().into()),
687                ]
688            )
689            .collect::<Vec<_>>(),
690            [
691                (
692                    0..1,
693                    HighlightStyle {
694                        color: Some(green()),
695                        ..Default::default()
696                    }
697                ),
698                (
699                    1..2,
700                    HighlightStyle {
701                        color: Some(green()),
702                        ..Default::default()
703                    }
704                ),
705                (
706                    2..3,
707                    HighlightStyle {
708                        color: Some(green()),
709                        font_style: Some(FontStyle::Italic),
710                        ..Default::default()
711                    }
712                ),
713                (
714                    3..4,
715                    HighlightStyle {
716                        color: Some(green()),
717                        font_style: Some(FontStyle::Italic),
718                        ..Default::default()
719                    }
720                ),
721                (
722                    4..5,
723                    HighlightStyle {
724                        color: Some(green()),
725                        font_weight: Some(FontWeight::BOLD),
726                        font_style: Some(FontStyle::Italic),
727                        ..Default::default()
728                    }
729                ),
730                (
731                    5..6,
732                    HighlightStyle {
733                        font_weight: Some(FontWeight::BOLD),
734                        font_style: Some(FontStyle::Italic),
735                        ..Default::default()
736                    }
737                ),
738                (
739                    6..10,
740                    HighlightStyle {
741                        font_weight: Some(FontWeight::BOLD),
742                        ..Default::default()
743                    }
744                ),
745                (
746                    15..20,
747                    HighlightStyle {
748                        color: Some(yellow()),
749                        ..Default::default()
750                    }
751                ),
752                (
753                    21..23,
754                    HighlightStyle {
755                        color: Some(red()),
756                        ..Default::default()
757                    }
758                )
759            ]
760        );
761    }
762}