style.rs

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