style.rs

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