style.rs

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