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,
  5    SharedString, Size, SizeRefinement, 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 fill: 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
104#[derive(Clone, Debug)]
105pub struct BoxShadow {
106    pub color: Hsla,
107    pub offset: Point<Pixels>,
108    pub blur_radius: Pixels,
109    pub spread_radius: Pixels,
110}
111
112#[derive(Refineable, Clone, Debug)]
113#[refineable(debug)]
114pub struct TextStyle {
115    pub color: Hsla,
116    pub font_family: SharedString,
117    pub font_features: FontFeatures,
118    pub font_size: Rems,
119    pub line_height: DefiniteLength,
120    pub font_weight: FontWeight,
121    pub font_style: FontStyle,
122    pub underline: Option<UnderlineStyle>,
123}
124
125impl Default for TextStyle {
126    fn default() -> Self {
127        TextStyle {
128            color: black(),
129            font_family: "Helvetica".into(), // todo!("Get a font we know exists on the system")
130            font_features: FontFeatures::default(),
131            font_size: rems(1.),
132            line_height: phi(),
133            font_weight: FontWeight::default(),
134            font_style: FontStyle::default(),
135            underline: None,
136        }
137    }
138}
139
140impl TextStyle {
141    pub fn highlight(mut self, style: HighlightStyle) -> Result<Self> {
142        if let Some(weight) = style.font_weight {
143            self.font_weight = weight;
144        }
145        if let Some(style) = style.font_style {
146            self.font_style = style;
147        }
148
149        if let Some(color) = style.color {
150            self.color = self.color.blend(color);
151        }
152
153        if let Some(factor) = style.fade_out {
154            self.color.fade_out(factor);
155        }
156
157        if let Some(underline) = style.underline {
158            self.underline = Some(underline);
159        }
160
161        Ok(self)
162    }
163
164    pub fn to_run(&self, len: usize) -> TextRun {
165        TextRun {
166            len,
167            font: Font {
168                family: self.font_family.clone(),
169                features: Default::default(),
170                weight: self.font_weight,
171                style: self.font_style,
172            },
173            color: self.color,
174            underline: self.underline.clone(),
175        }
176    }
177}
178
179#[derive(Clone, Debug, Default, PartialEq)]
180pub struct HighlightStyle {
181    pub color: Option<Hsla>,
182    pub font_weight: Option<FontWeight>,
183    pub font_style: Option<FontStyle>,
184    pub underline: Option<UnderlineStyle>,
185    pub fade_out: Option<f32>,
186}
187
188impl Eq for HighlightStyle {}
189
190impl Style {
191    pub fn text_style(&self, _cx: &WindowContext) -> Option<&TextStyleRefinement> {
192        if self.text.is_some() {
193            Some(&self.text)
194        } else {
195            None
196        }
197    }
198
199    pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
200    where
201        C: BorrowAppContext,
202        F: FnOnce(&mut C) -> R,
203    {
204        if self.text.is_some() {
205            cx.with_text_style(self.text.clone(), f)
206        } else {
207            f(cx)
208        }
209    }
210
211    /// Apply overflow to content mask
212    pub fn apply_overflow<C, F, R>(&self, bounds: Bounds<Pixels>, cx: &mut C, f: F) -> R
213    where
214        C: BorrowWindow,
215        F: FnOnce(&mut C) -> R,
216    {
217        let current_mask = cx.content_mask();
218
219        let min = current_mask.bounds.origin;
220        let max = current_mask.bounds.lower_right();
221
222        let mask_bounds = match (
223            self.overflow.x == Overflow::Visible,
224            self.overflow.y == Overflow::Visible,
225        ) {
226            // x and y both visible
227            (true, true) => return f(cx),
228            // x visible, y hidden
229            (true, false) => Bounds::from_corners(
230                point(min.x, bounds.origin.y),
231                point(max.x, bounds.lower_right().y),
232            ),
233            // x hidden, y visible
234            (false, true) => Bounds::from_corners(
235                point(bounds.origin.x, min.y),
236                point(bounds.lower_right().x, max.y),
237            ),
238            // both hidden
239            (false, false) => bounds,
240        };
241        let mask = ContentMask {
242            bounds: mask_bounds,
243        };
244
245        cx.with_content_mask(mask, f)
246    }
247
248    /// Paints the background of an element styled with this style.
249    pub fn paint<V: 'static>(&self, bounds: Bounds<Pixels>, cx: &mut ViewContext<V>) {
250        let rem_size = cx.rem_size();
251
252        cx.stack(0, |cx| {
253            cx.paint_shadows(
254                bounds,
255                self.corner_radii.to_pixels(bounds.size, rem_size),
256                &self.box_shadow,
257            );
258        });
259
260        let background_color = self.fill.as_ref().and_then(Fill::color);
261        if background_color.is_some() || self.is_border_visible() {
262            cx.stack(1, |cx| {
263                cx.paint_quad(
264                    bounds,
265                    self.corner_radii.to_pixels(bounds.size, rem_size),
266                    background_color.unwrap_or_default(),
267                    self.border_widths.to_pixels(rem_size),
268                    self.border_color.unwrap_or_default(),
269                );
270            });
271        }
272    }
273
274    fn is_border_visible(&self) -> bool {
275        self.border_color
276            .map_or(false, |color| !color.is_transparent())
277            && self.border_widths.any(|length| !length.is_zero())
278    }
279}
280
281impl Default for Style {
282    fn default() -> Self {
283        Style {
284            display: Display::Block,
285            overflow: Point {
286                x: Overflow::Visible,
287                y: Overflow::Visible,
288            },
289            scrollbar_width: 0.0,
290            position: Position::Relative,
291            inset: Edges::auto(),
292            margin: Edges::<Length>::zero(),
293            padding: Edges::<DefiniteLength>::zero(),
294            border_widths: Edges::<AbsoluteLength>::zero(),
295            size: Size::auto(),
296            min_size: Size::auto(),
297            max_size: Size::auto(),
298            aspect_ratio: None,
299            gap: Size::zero(),
300            // Aligment
301            align_items: None,
302            align_self: None,
303            align_content: None,
304            justify_content: None,
305            // Flexbox
306            flex_direction: FlexDirection::Row,
307            flex_wrap: FlexWrap::NoWrap,
308            flex_grow: 0.0,
309            flex_shrink: 1.0,
310            flex_basis: Length::Auto,
311            fill: None,
312            border_color: None,
313            corner_radii: Corners::default(),
314            box_shadow: Default::default(),
315            text: TextStyleRefinement::default(),
316            z_index: None,
317        }
318    }
319}
320
321#[derive(Refineable, Clone, Default, Debug, PartialEq, Eq)]
322#[refineable(debug)]
323pub struct UnderlineStyle {
324    pub thickness: Pixels,
325    pub color: Option<Hsla>,
326    pub wavy: bool,
327}
328
329#[derive(Clone, Debug)]
330pub enum Fill {
331    Color(Hsla),
332}
333
334impl Fill {
335    pub fn color(&self) -> Option<Hsla> {
336        match self {
337            Fill::Color(color) => Some(*color),
338        }
339    }
340}
341
342impl Default for Fill {
343    fn default() -> Self {
344        Self::Color(Hsla::default())
345    }
346}
347
348impl From<Hsla> for Fill {
349    fn from(color: Hsla) -> Self {
350        Self::Color(color)
351    }
352}
353
354impl From<TextStyle> for HighlightStyle {
355    fn from(other: TextStyle) -> Self {
356        Self::from(&other)
357    }
358}
359
360impl From<&TextStyle> for HighlightStyle {
361    fn from(other: &TextStyle) -> Self {
362        Self {
363            color: Some(other.color),
364            font_weight: Some(other.font_weight),
365            font_style: Some(other.font_style),
366            underline: other.underline.clone(),
367            fade_out: None,
368        }
369    }
370}
371
372impl HighlightStyle {
373    pub fn highlight(&mut self, other: HighlightStyle) {
374        match (self.color, other.color) {
375            (Some(self_color), Some(other_color)) => {
376                self.color = Some(Hsla::blend(other_color, self_color));
377            }
378            (None, Some(other_color)) => {
379                self.color = Some(other_color);
380            }
381            _ => {}
382        }
383
384        if other.font_weight.is_some() {
385            self.font_weight = other.font_weight;
386        }
387
388        if other.font_style.is_some() {
389            self.font_style = other.font_style;
390        }
391
392        if other.underline.is_some() {
393            self.underline = other.underline;
394        }
395
396        match (other.fade_out, self.fade_out) {
397            (Some(source_fade), None) => self.fade_out = Some(source_fade),
398            (Some(source_fade), Some(dest_fade)) => {
399                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
400            }
401            _ => {}
402        }
403    }
404}
405
406impl From<Hsla> for HighlightStyle {
407    fn from(color: Hsla) -> Self {
408        Self {
409            color: Some(color),
410            ..Default::default()
411        }
412    }
413}