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            font_family: "Helvetica".into(), // todo!("Get a font we know exists on the system")
169            font_features: FontFeatures::default(),
170            font_size: rems(1.).into(),
171            line_height: phi(),
172            font_weight: FontWeight::default(),
173            font_style: FontStyle::default(),
174            background_color: None,
175            underline: None,
176            white_space: WhiteSpace::Normal,
177        }
178    }
179}
180
181impl TextStyle {
182    pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
183        let style = style.into();
184        if let Some(weight) = style.font_weight {
185            self.font_weight = weight;
186        }
187        if let Some(style) = style.font_style {
188            self.font_style = style;
189        }
190
191        if let Some(color) = style.color {
192            self.color = self.color.blend(color);
193        }
194
195        if let Some(factor) = style.fade_out {
196            self.color.fade_out(factor);
197        }
198
199        if let Some(background_color) = style.background_color {
200            self.background_color = Some(background_color);
201        }
202
203        if let Some(underline) = style.underline {
204            self.underline = Some(underline);
205        }
206
207        self
208    }
209
210    pub fn font(&self) -> Font {
211        Font {
212            family: self.font_family.clone(),
213            features: self.font_features,
214            weight: self.font_weight,
215            style: self.font_style,
216        }
217    }
218
219    /// Returns the rounded line height in pixels.
220    pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
221        self.line_height.to_pixels(self.font_size, rem_size).round()
222    }
223
224    pub fn to_run(&self, len: usize) -> TextRun {
225        TextRun {
226            len,
227            font: Font {
228                family: self.font_family.clone(),
229                features: Default::default(),
230                weight: self.font_weight,
231                style: self.font_style,
232            },
233            color: self.color,
234            background_color: self.background_color,
235            underline: self.underline,
236        }
237    }
238}
239
240#[derive(Copy, Clone, Debug, Default, PartialEq)]
241pub struct HighlightStyle {
242    pub color: Option<Hsla>,
243    pub font_weight: Option<FontWeight>,
244    pub font_style: Option<FontStyle>,
245    pub background_color: Option<Hsla>,
246    pub underline: Option<UnderlineStyle>,
247    pub fade_out: Option<f32>,
248}
249
250impl Eq for HighlightStyle {}
251
252impl Style {
253    pub fn text_style(&self) -> Option<&TextStyleRefinement> {
254        if self.text.is_some() {
255            Some(&self.text)
256        } else {
257            None
258        }
259    }
260
261    pub fn overflow_mask(
262        &self,
263        bounds: Bounds<Pixels>,
264        rem_size: Pixels,
265    ) -> Option<ContentMask<Pixels>> {
266        match self.overflow {
267            Point {
268                x: Overflow::Visible,
269                y: Overflow::Visible,
270            } => None,
271            _ => {
272                let mut min = bounds.origin;
273                let mut max = bounds.lower_right();
274
275                if self
276                    .border_color
277                    .map_or(false, |color| !color.is_transparent())
278                {
279                    min.x += self.border_widths.left.to_pixels(rem_size);
280                    max.x -= self.border_widths.right.to_pixels(rem_size);
281                    min.y += self.border_widths.top.to_pixels(rem_size);
282                    max.y -= self.border_widths.bottom.to_pixels(rem_size);
283                }
284
285                let bounds = match (
286                    self.overflow.x == Overflow::Visible,
287                    self.overflow.y == Overflow::Visible,
288                ) {
289                    // x and y both visible
290                    (true, true) => return None,
291                    // x visible, y hidden
292                    (true, false) => Bounds::from_corners(
293                        point(min.x, bounds.origin.y),
294                        point(max.x, bounds.lower_right().y),
295                    ),
296                    // x hidden, y visible
297                    (false, true) => Bounds::from_corners(
298                        point(bounds.origin.x, min.y),
299                        point(bounds.lower_right().x, max.y),
300                    ),
301                    // both hidden
302                    (false, false) => Bounds::from_corners(min, max),
303                };
304
305                Some(ContentMask { bounds })
306            }
307        }
308    }
309
310    // pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
311    // where
312    //     C: BorrowAppContext,
313    //     F: FnOnce(&mut C) -> R,
314    // {
315    //     if self.text.is_some() {
316    //         cx.with_text_style(Some(self.text.clone()), f)
317    //     } else {
318    //         f(cx)
319    //     }
320    // }
321
322    // /// Apply overflow to content mask
323    // pub fn apply_overflow<C, F, R>(&self, bounds: Bounds<Pixels>, cx: &mut C, f: F) -> R
324    // where
325    //     C: BorrowWindow,
326    //     F: FnOnce(&mut C) -> R,
327    // {
328    //     let current_mask = cx.content_mask();
329
330    //     let min = current_mask.bounds.origin;
331    //     let max = current_mask.bounds.lower_right();
332
333    //     let mask_bounds = match (
334    //         self.overflow.x == Overflow::Visible,
335    //         self.overflow.y == Overflow::Visible,
336    //     ) {
337    //         // x and y both visible
338    //         (true, true) => return f(cx),
339    //         // x visible, y hidden
340    //         (true, false) => Bounds::from_corners(
341    //             point(min.x, bounds.origin.y),
342    //             point(max.x, bounds.lower_right().y),
343    //         ),
344    //         // x hidden, y visible
345    //         (false, true) => Bounds::from_corners(
346    //             point(bounds.origin.x, min.y),
347    //             point(bounds.lower_right().x, max.y),
348    //         ),
349    //         // both hidden
350    //         (false, false) => bounds,
351    //     };
352    //     let mask = ContentMask {
353    //         bounds: mask_bounds,
354    //     };
355
356    //     cx.with_content_mask(Some(mask), f)
357    // }
358
359    /// Paints the background of an element styled with this style.
360    pub fn paint(
361        &self,
362        bounds: Bounds<Pixels>,
363        cx: &mut WindowContext,
364        continuation: impl FnOnce(&mut WindowContext),
365    ) {
366        #[cfg(debug_assertions)]
367        if self.debug_below {
368            cx.set_global(DebugBelow)
369        }
370
371        #[cfg(debug_assertions)]
372        if self.debug || cx.has_global::<DebugBelow>() {
373            cx.paint_quad(crate::outline(bounds, crate::red()));
374        }
375
376        let rem_size = cx.rem_size();
377
378        cx.with_z_index(0, |cx| {
379            cx.paint_shadows(
380                bounds,
381                self.corner_radii.to_pixels(bounds.size, rem_size),
382                &self.box_shadow,
383            );
384        });
385
386        let background_color = self.background.as_ref().and_then(Fill::color);
387        if background_color.map_or(false, |color| !color.is_transparent()) {
388            cx.with_z_index(1, |cx| {
389                let mut border_color = background_color.unwrap_or_default();
390                border_color.a = 0.;
391                cx.paint_quad(quad(
392                    bounds,
393                    self.corner_radii.to_pixels(bounds.size, rem_size),
394                    background_color.unwrap_or_default(),
395                    Edges::default(),
396                    border_color,
397                ));
398            });
399        }
400
401        cx.with_z_index(2, |cx| {
402            continuation(cx);
403        });
404
405        if self.is_border_visible() {
406            cx.with_z_index(3, |cx| {
407                let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
408                let border_widths = self.border_widths.to_pixels(rem_size);
409                let max_border_width = border_widths.max();
410                let max_corner_radius = corner_radii.max();
411
412                let top_bounds = Bounds::from_corners(
413                    bounds.origin,
414                    bounds.upper_right()
415                        + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
416                );
417                let bottom_bounds = Bounds::from_corners(
418                    bounds.lower_left()
419                        - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
420                    bounds.lower_right(),
421                );
422                let left_bounds = Bounds::from_corners(
423                    top_bounds.lower_left(),
424                    bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
425                );
426                let right_bounds = Bounds::from_corners(
427                    top_bounds.lower_right() - point(max_border_width, Pixels::ZERO),
428                    bottom_bounds.upper_right(),
429                );
430
431                let mut background = self.border_color.unwrap_or_default();
432                background.a = 0.;
433                let quad = quad(
434                    bounds,
435                    corner_radii,
436                    background,
437                    border_widths,
438                    self.border_color.unwrap_or_default(),
439                );
440
441                cx.with_content_mask(Some(ContentMask { bounds: top_bounds }), |cx| {
442                    cx.paint_quad(quad.clone());
443                });
444                cx.with_content_mask(
445                    Some(ContentMask {
446                        bounds: right_bounds,
447                    }),
448                    |cx| {
449                        cx.paint_quad(quad.clone());
450                    },
451                );
452                cx.with_content_mask(
453                    Some(ContentMask {
454                        bounds: bottom_bounds,
455                    }),
456                    |cx| {
457                        cx.paint_quad(quad.clone());
458                    },
459                );
460                cx.with_content_mask(
461                    Some(ContentMask {
462                        bounds: left_bounds,
463                    }),
464                    |cx| {
465                        cx.paint_quad(quad);
466                    },
467                );
468            });
469        }
470
471        #[cfg(debug_assertions)]
472        if self.debug_below {
473            cx.remove_global::<DebugBelow>();
474        }
475    }
476
477    fn is_border_visible(&self) -> bool {
478        self.border_color
479            .map_or(false, |color| !color.is_transparent())
480            && self.border_widths.any(|length| !length.is_zero())
481    }
482}
483
484impl Default for Style {
485    fn default() -> Self {
486        Style {
487            display: Display::Block,
488            visibility: Visibility::Visible,
489            overflow: Point {
490                x: Overflow::Visible,
491                y: Overflow::Visible,
492            },
493            scrollbar_width: 0.0,
494            position: Position::Relative,
495            inset: Edges::auto(),
496            margin: Edges::<Length>::zero(),
497            padding: Edges::<DefiniteLength>::zero(),
498            border_widths: Edges::<AbsoluteLength>::zero(),
499            size: Size::auto(),
500            min_size: Size::auto(),
501            max_size: Size::auto(),
502            aspect_ratio: None,
503            gap: Size::default(),
504            // Aligment
505            align_items: None,
506            align_self: None,
507            align_content: None,
508            justify_content: None,
509            // Flexbox
510            flex_direction: FlexDirection::Row,
511            flex_wrap: FlexWrap::NoWrap,
512            flex_grow: 0.0,
513            flex_shrink: 1.0,
514            flex_basis: Length::Auto,
515            background: None,
516            border_color: None,
517            corner_radii: Corners::default(),
518            box_shadow: Default::default(),
519            text: TextStyleRefinement::default(),
520            mouse_cursor: None,
521            z_index: None,
522
523            #[cfg(debug_assertions)]
524            debug: false,
525            #[cfg(debug_assertions)]
526            debug_below: false,
527        }
528    }
529}
530
531#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
532#[refineable(Debug)]
533pub struct UnderlineStyle {
534    pub thickness: Pixels,
535    pub color: Option<Hsla>,
536    pub wavy: bool,
537}
538
539#[derive(Clone, Debug)]
540pub enum Fill {
541    Color(Hsla),
542}
543
544impl Fill {
545    pub fn color(&self) -> Option<Hsla> {
546        match self {
547            Fill::Color(color) => Some(*color),
548        }
549    }
550}
551
552impl Default for Fill {
553    fn default() -> Self {
554        Self::Color(Hsla::default())
555    }
556}
557
558impl From<Hsla> for Fill {
559    fn from(color: Hsla) -> Self {
560        Self::Color(color)
561    }
562}
563
564impl From<Rgba> for Fill {
565    fn from(color: Rgba) -> Self {
566        Self::Color(color.into())
567    }
568}
569
570impl From<TextStyle> for HighlightStyle {
571    fn from(other: TextStyle) -> Self {
572        Self::from(&other)
573    }
574}
575
576impl From<&TextStyle> for HighlightStyle {
577    fn from(other: &TextStyle) -> Self {
578        Self {
579            color: Some(other.color),
580            font_weight: Some(other.font_weight),
581            font_style: Some(other.font_style),
582            background_color: other.background_color,
583            underline: other.underline,
584            fade_out: None,
585        }
586    }
587}
588
589impl HighlightStyle {
590    pub fn highlight(&mut self, other: HighlightStyle) {
591        match (self.color, other.color) {
592            (Some(self_color), Some(other_color)) => {
593                self.color = Some(Hsla::blend(other_color, self_color));
594            }
595            (None, Some(other_color)) => {
596                self.color = Some(other_color);
597            }
598            _ => {}
599        }
600
601        if other.font_weight.is_some() {
602            self.font_weight = other.font_weight;
603        }
604
605        if other.font_style.is_some() {
606            self.font_style = other.font_style;
607        }
608
609        if other.background_color.is_some() {
610            self.background_color = other.background_color;
611        }
612
613        if other.underline.is_some() {
614            self.underline = other.underline;
615        }
616
617        match (other.fade_out, self.fade_out) {
618            (Some(source_fade), None) => self.fade_out = Some(source_fade),
619            (Some(source_fade), Some(dest_fade)) => {
620                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
621            }
622            _ => {}
623        }
624    }
625}
626
627impl From<Hsla> for HighlightStyle {
628    fn from(color: Hsla) -> Self {
629        Self {
630            color: Some(color),
631            ..Default::default()
632        }
633    }
634}
635
636impl From<FontWeight> for HighlightStyle {
637    fn from(font_weight: FontWeight) -> Self {
638        Self {
639            font_weight: Some(font_weight),
640            ..Default::default()
641        }
642    }
643}
644
645impl From<FontStyle> for HighlightStyle {
646    fn from(font_style: FontStyle) -> Self {
647        Self {
648            font_style: Some(font_style),
649            ..Default::default()
650        }
651    }
652}
653
654impl From<Rgba> for HighlightStyle {
655    fn from(color: Rgba) -> Self {
656        Self {
657            color: Some(color.into()),
658            ..Default::default()
659        }
660    }
661}
662
663pub fn combine_highlights(
664    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
665    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
666) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
667    let mut endpoints = Vec::new();
668    let mut highlights = Vec::new();
669    for (range, highlight) in a.into_iter().chain(b) {
670        if !range.is_empty() {
671            let highlight_id = highlights.len();
672            endpoints.push((range.start, highlight_id, true));
673            endpoints.push((range.end, highlight_id, false));
674            highlights.push(highlight);
675        }
676    }
677    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
678    let mut endpoints = endpoints.into_iter().peekable();
679
680    let mut active_styles = HashSet::default();
681    let mut ix = 0;
682    iter::from_fn(move || {
683        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
684            let prev_index = mem::replace(&mut ix, *endpoint_ix);
685            if ix > prev_index && !active_styles.is_empty() {
686                let mut current_style = HighlightStyle::default();
687                for highlight_id in &active_styles {
688                    current_style.highlight(highlights[*highlight_id]);
689                }
690                return Some((prev_index..ix, current_style));
691            }
692
693            if *is_start {
694                active_styles.insert(*highlight_id);
695            } else {
696                active_styles.remove(highlight_id);
697            }
698            endpoints.next();
699        }
700        None
701    })
702}
703
704#[cfg(test)]
705mod tests {
706    use crate::{blue, green, red, yellow};
707
708    use super::*;
709
710    #[test]
711    fn test_combine_highlights() {
712        assert_eq!(
713            combine_highlights(
714                [
715                    (0..5, green().into()),
716                    (4..10, FontWeight::BOLD.into()),
717                    (15..20, yellow().into()),
718                ],
719                [
720                    (2..6, FontStyle::Italic.into()),
721                    (1..3, blue().into()),
722                    (21..23, red().into()),
723                ]
724            )
725            .collect::<Vec<_>>(),
726            [
727                (
728                    0..1,
729                    HighlightStyle {
730                        color: Some(green()),
731                        ..Default::default()
732                    }
733                ),
734                (
735                    1..2,
736                    HighlightStyle {
737                        color: Some(green()),
738                        ..Default::default()
739                    }
740                ),
741                (
742                    2..3,
743                    HighlightStyle {
744                        color: Some(green()),
745                        font_style: Some(FontStyle::Italic),
746                        ..Default::default()
747                    }
748                ),
749                (
750                    3..4,
751                    HighlightStyle {
752                        color: Some(green()),
753                        font_style: Some(FontStyle::Italic),
754                        ..Default::default()
755                    }
756                ),
757                (
758                    4..5,
759                    HighlightStyle {
760                        color: Some(green()),
761                        font_weight: Some(FontWeight::BOLD),
762                        font_style: Some(FontStyle::Italic),
763                        ..Default::default()
764                    }
765                ),
766                (
767                    5..6,
768                    HighlightStyle {
769                        font_weight: Some(FontWeight::BOLD),
770                        font_style: Some(FontStyle::Italic),
771                        ..Default::default()
772                    }
773                ),
774                (
775                    6..10,
776                    HighlightStyle {
777                        font_weight: Some(FontWeight::BOLD),
778                        ..Default::default()
779                    }
780                ),
781                (
782                    15..20,
783                    HighlightStyle {
784                        color: Some(yellow()),
785                        ..Default::default()
786                    }
787                ),
788                (
789                    21..23,
790                    HighlightStyle {
791                        color: Some(red()),
792                        ..Default::default()
793                    }
794                )
795            ]
796        );
797    }
798}