style.rs

  1use crate::{
  2    black, phi, point, rems, AbsoluteLength, BorrowAppContext, BorrowWindow, Bounds, ContentMask,
  3    Corners, CornersRefinement, CursorStyle, DefiniteLength, Edges, EdgesRefinement, Font,
  4    FontFeatures, FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba,
  5    SharedString, Size, SizeRefinement, Styled, TextRun, ViewContext,
  6};
  7use refineable::{Cascade, Refineable};
  8use smallvec::SmallVec;
  9pub use taffy::style::{
 10    AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
 11    Overflow, Position,
 12};
 13
 14pub type StyleCascade = Cascade<Style>;
 15
 16#[derive(Clone, Refineable, Debug)]
 17#[refineable(Debug)]
 18pub struct Style {
 19    /// What layout strategy should be used?
 20    pub display: Display,
 21
 22    /// Should the element be painted on screen?
 23    pub visibility: Visibility,
 24
 25    // Overflow properties
 26    /// How children overflowing their container should affect layout
 27    #[refineable]
 28    pub overflow: Point<Overflow>,
 29    /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
 30    pub scrollbar_width: f32,
 31
 32    // Position properties
 33    /// What should the `position` value of this struct use as a base offset?
 34    pub position: Position,
 35    /// How should the position of this element be tweaked relative to the layout defined?
 36    #[refineable]
 37    pub inset: Edges<Length>,
 38
 39    // Size properies
 40    /// Sets the initial size of the item
 41    #[refineable]
 42    pub size: Size<Length>,
 43    /// Controls the minimum size of the item
 44    #[refineable]
 45    pub min_size: Size<Length>,
 46    /// Controls the maximum size of the item
 47    #[refineable]
 48    pub max_size: Size<Length>,
 49    /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
 50    pub aspect_ratio: Option<f32>,
 51
 52    // Spacing Properties
 53    /// How large should the margin be on each side?
 54    #[refineable]
 55    pub margin: Edges<Length>,
 56    /// How large should the padding be on each side?
 57    #[refineable]
 58    pub padding: Edges<DefiniteLength>,
 59    /// How large should the border be on each side?
 60    #[refineable]
 61    pub border_widths: Edges<AbsoluteLength>,
 62
 63    // Alignment properties
 64    /// How this node's children aligned in the cross/block axis?
 65    pub align_items: Option<AlignItems>,
 66    /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
 67    pub align_self: Option<AlignSelf>,
 68    /// How should content contained within this item be aligned in the cross/block axis
 69    pub align_content: Option<AlignContent>,
 70    /// How should contained within this item be aligned in the main/inline axis
 71    pub justify_content: Option<JustifyContent>,
 72    /// How large should the gaps between items in a flex container be?
 73    #[refineable]
 74    pub gap: Size<DefiniteLength>,
 75
 76    // Flexbox properies
 77    /// Which direction does the main axis flow in?
 78    pub flex_direction: FlexDirection,
 79    /// Should elements wrap, or stay in a single line?
 80    pub flex_wrap: FlexWrap,
 81    /// Sets the initial main axis size of the item
 82    pub flex_basis: Length,
 83    /// 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.
 84    pub flex_grow: f32,
 85    /// 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.
 86    pub flex_shrink: f32,
 87
 88    /// The fill color of this element
 89    pub background: Option<Fill>,
 90
 91    /// The border color of this element
 92    pub border_color: Option<Hsla>,
 93
 94    /// The radius of the corners of this element
 95    #[refineable]
 96    pub corner_radii: Corners<AbsoluteLength>,
 97
 98    /// Box Shadow of the element
 99    pub box_shadow: SmallVec<[BoxShadow; 2]>,
100
101    /// TEXT
102    pub text: TextStyleRefinement,
103
104    /// The mouse cursor style shown when the mouse pointer is over an element.
105    pub mouse_cursor: Option<CursorStyle>,
106
107    pub z_index: Option<u32>,
108}
109
110impl Styled for StyleRefinement {
111    fn style(&mut self) -> &mut StyleRefinement {
112        self
113    }
114}
115
116#[derive(Default, Clone, Copy, Debug, Eq, PartialEq)]
117pub enum Visibility {
118    #[default]
119    Visible,
120    Hidden,
121}
122
123#[derive(Clone, Debug)]
124pub struct BoxShadow {
125    pub color: Hsla,
126    pub offset: Point<Pixels>,
127    pub blur_radius: Pixels,
128    pub spread_radius: Pixels,
129}
130
131#[derive(Refineable, Clone, Debug)]
132#[refineable(Debug)]
133pub struct TextStyle {
134    pub color: Hsla,
135    pub font_family: SharedString,
136    pub font_features: FontFeatures,
137    pub font_size: AbsoluteLength,
138    pub line_height: DefiniteLength,
139    pub font_weight: FontWeight,
140    pub font_style: FontStyle,
141    pub underline: Option<UnderlineStyle>,
142}
143
144impl Default for TextStyle {
145    fn default() -> Self {
146        TextStyle {
147            color: black(),
148            font_family: "Helvetica".into(), // todo!("Get a font we know exists on the system")
149            font_features: FontFeatures::default(),
150            font_size: rems(1.).into(),
151            line_height: phi(),
152            font_weight: FontWeight::default(),
153            font_style: FontStyle::default(),
154            underline: None,
155        }
156    }
157}
158
159impl TextStyle {
160    pub fn highlight(mut self, style: HighlightStyle) -> Self {
161        if let Some(weight) = style.font_weight {
162            self.font_weight = weight;
163        }
164        if let Some(style) = style.font_style {
165            self.font_style = style;
166        }
167
168        if let Some(color) = style.color {
169            self.color = self.color.blend(color);
170        }
171
172        if let Some(factor) = style.fade_out {
173            self.color.fade_out(factor);
174        }
175
176        if let Some(underline) = style.underline {
177            self.underline = Some(underline);
178        }
179
180        self
181    }
182
183    pub fn font(&self) -> Font {
184        Font {
185            family: self.font_family.clone(),
186            features: self.font_features.clone(),
187            weight: self.font_weight,
188            style: self.font_style,
189        }
190    }
191
192    pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
193        self.line_height.to_pixels(self.font_size, rem_size)
194    }
195
196    pub fn to_run(&self, len: usize) -> TextRun {
197        TextRun {
198            len,
199            font: Font {
200                family: self.font_family.clone(),
201                features: Default::default(),
202                weight: self.font_weight,
203                style: self.font_style,
204            },
205            color: self.color,
206            underline: self.underline.clone(),
207        }
208    }
209}
210
211#[derive(Copy, Clone, Debug, Default, PartialEq)]
212pub struct HighlightStyle {
213    pub color: Option<Hsla>,
214    pub font_weight: Option<FontWeight>,
215    pub font_style: Option<FontStyle>,
216    pub underline: Option<UnderlineStyle>,
217    pub fade_out: Option<f32>,
218}
219
220impl Eq for HighlightStyle {}
221
222impl Style {
223    pub fn text_style(&self) -> Option<&TextStyleRefinement> {
224        if self.text.is_some() {
225            Some(&self.text)
226        } else {
227            None
228        }
229    }
230
231    pub fn overflow_mask(&self, bounds: Bounds<Pixels>) -> Option<ContentMask<Pixels>> {
232        match self.overflow {
233            Point {
234                x: Overflow::Visible,
235                y: Overflow::Visible,
236            } => None,
237            _ => {
238                let current_mask = bounds;
239                let min = current_mask.origin;
240                let max = current_mask.lower_right();
241                let bounds = match (
242                    self.overflow.x == Overflow::Visible,
243                    self.overflow.y == Overflow::Visible,
244                ) {
245                    // x and y both visible
246                    (true, true) => return None,
247                    // x visible, y hidden
248                    (true, false) => Bounds::from_corners(
249                        point(min.x, bounds.origin.y),
250                        point(max.x, bounds.lower_right().y),
251                    ),
252                    // x hidden, y visible
253                    (false, true) => Bounds::from_corners(
254                        point(bounds.origin.x, min.y),
255                        point(bounds.lower_right().x, max.y),
256                    ),
257                    // both hidden
258                    (false, false) => bounds,
259                };
260                Some(ContentMask { bounds })
261            }
262        }
263    }
264
265    pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
266    where
267        C: BorrowAppContext,
268        F: FnOnce(&mut C) -> R,
269    {
270        if self.text.is_some() {
271            cx.with_text_style(Some(self.text.clone()), f)
272        } else {
273            f(cx)
274        }
275    }
276
277    /// Apply overflow to content mask
278    pub fn apply_overflow<C, F, R>(&self, bounds: Bounds<Pixels>, cx: &mut C, f: F) -> R
279    where
280        C: BorrowWindow,
281        F: FnOnce(&mut C) -> R,
282    {
283        let current_mask = cx.content_mask();
284
285        let min = current_mask.bounds.origin;
286        let max = current_mask.bounds.lower_right();
287
288        let mask_bounds = match (
289            self.overflow.x == Overflow::Visible,
290            self.overflow.y == Overflow::Visible,
291        ) {
292            // x and y both visible
293            (true, true) => return f(cx),
294            // x visible, y hidden
295            (true, false) => Bounds::from_corners(
296                point(min.x, bounds.origin.y),
297                point(max.x, bounds.lower_right().y),
298            ),
299            // x hidden, y visible
300            (false, true) => Bounds::from_corners(
301                point(bounds.origin.x, min.y),
302                point(bounds.lower_right().x, max.y),
303            ),
304            // both hidden
305            (false, false) => bounds,
306        };
307        let mask = ContentMask {
308            bounds: mask_bounds,
309        };
310
311        cx.with_content_mask(Some(mask), f)
312    }
313
314    /// Paints the background of an element styled with this style.
315    pub fn paint<V: 'static>(&self, bounds: Bounds<Pixels>, cx: &mut ViewContext<V>) {
316        let rem_size = cx.rem_size();
317
318        cx.with_z_index(0, |cx| {
319            cx.paint_shadows(
320                bounds,
321                self.corner_radii.to_pixels(bounds.size, rem_size),
322                &self.box_shadow,
323            );
324        });
325
326        let background_color = self.background.as_ref().and_then(Fill::color);
327        if background_color.is_some() || self.is_border_visible() {
328            cx.with_z_index(1, |cx| {
329                cx.paint_quad(
330                    bounds,
331                    self.corner_radii.to_pixels(bounds.size, rem_size),
332                    background_color.unwrap_or_default(),
333                    self.border_widths.to_pixels(rem_size),
334                    self.border_color.unwrap_or_default(),
335                );
336            });
337        }
338    }
339
340    fn is_border_visible(&self) -> bool {
341        self.border_color
342            .map_or(false, |color| !color.is_transparent())
343            && self.border_widths.any(|length| !length.is_zero())
344    }
345}
346
347impl Default for Style {
348    fn default() -> Self {
349        Style {
350            display: Display::Block,
351            visibility: Visibility::Visible,
352            overflow: Point {
353                x: Overflow::Visible,
354                y: Overflow::Visible,
355            },
356            scrollbar_width: 0.0,
357            position: Position::Relative,
358            inset: Edges::auto(),
359            margin: Edges::<Length>::zero(),
360            padding: Edges::<DefiniteLength>::zero(),
361            border_widths: Edges::<AbsoluteLength>::zero(),
362            size: Size::auto(),
363            min_size: Size::auto(),
364            max_size: Size::auto(),
365            aspect_ratio: None,
366            gap: Size::zero(),
367            // Aligment
368            align_items: None,
369            align_self: None,
370            align_content: None,
371            justify_content: None,
372            // Flexbox
373            flex_direction: FlexDirection::Row,
374            flex_wrap: FlexWrap::NoWrap,
375            flex_grow: 0.0,
376            flex_shrink: 1.0,
377            flex_basis: Length::Auto,
378            background: None,
379            border_color: None,
380            corner_radii: Corners::default(),
381            box_shadow: Default::default(),
382            text: TextStyleRefinement::default(),
383            mouse_cursor: None,
384            z_index: None,
385        }
386    }
387}
388
389#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
390#[refineable(Debug)]
391pub struct UnderlineStyle {
392    pub thickness: Pixels,
393    pub color: Option<Hsla>,
394    pub wavy: bool,
395}
396
397#[derive(Clone, Debug)]
398pub enum Fill {
399    Color(Hsla),
400}
401
402impl Fill {
403    pub fn color(&self) -> Option<Hsla> {
404        match self {
405            Fill::Color(color) => Some(*color),
406        }
407    }
408}
409
410impl Default for Fill {
411    fn default() -> Self {
412        Self::Color(Hsla::default())
413    }
414}
415
416impl From<Hsla> for Fill {
417    fn from(color: Hsla) -> Self {
418        Self::Color(color)
419    }
420}
421
422impl From<TextStyle> for HighlightStyle {
423    fn from(other: TextStyle) -> Self {
424        Self::from(&other)
425    }
426}
427
428impl From<&TextStyle> for HighlightStyle {
429    fn from(other: &TextStyle) -> Self {
430        Self {
431            color: Some(other.color),
432            font_weight: Some(other.font_weight),
433            font_style: Some(other.font_style),
434            underline: other.underline.clone(),
435            fade_out: None,
436        }
437    }
438}
439
440impl HighlightStyle {
441    pub fn highlight(&mut self, other: HighlightStyle) {
442        match (self.color, other.color) {
443            (Some(self_color), Some(other_color)) => {
444                self.color = Some(Hsla::blend(other_color, self_color));
445            }
446            (None, Some(other_color)) => {
447                self.color = Some(other_color);
448            }
449            _ => {}
450        }
451
452        if other.font_weight.is_some() {
453            self.font_weight = other.font_weight;
454        }
455
456        if other.font_style.is_some() {
457            self.font_style = other.font_style;
458        }
459
460        if other.underline.is_some() {
461            self.underline = other.underline;
462        }
463
464        match (other.fade_out, self.fade_out) {
465            (Some(source_fade), None) => self.fade_out = Some(source_fade),
466            (Some(source_fade), Some(dest_fade)) => {
467                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
468            }
469            _ => {}
470        }
471    }
472}
473
474impl From<Hsla> for HighlightStyle {
475    fn from(color: Hsla) -> Self {
476        Self {
477            color: Some(color),
478            ..Default::default()
479        }
480    }
481}
482
483impl From<Rgba> for HighlightStyle {
484    fn from(color: Rgba) -> Self {
485        Self {
486            color: Some(color.into()),
487            ..Default::default()
488        }
489    }
490}