style.rs

  1use crate::{
  2    color::Hsla,
  3    elements::hoverable::{hoverable, Hoverable},
  4    elements::pressable::{pressable, Pressable},
  5    ViewContext,
  6};
  7pub use fonts::Style as FontStyle;
  8pub use fonts::Weight as FontWeight;
  9pub use gpui::taffy::style::{
 10    AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
 11    Overflow, Position,
 12};
 13use gpui::{
 14    fonts::{self, TextStyleRefinement},
 15    geometry::{
 16        rect::RectF, relative, vector::Vector2F, AbsoluteLength, DefiniteLength, Edges,
 17        EdgesRefinement, Length, Point, PointRefinement, Size, SizeRefinement,
 18    },
 19    scene, taffy, WindowContext,
 20};
 21use gpui2_macros::styleable_helpers;
 22use refineable::{Refineable, RefinementCascade};
 23use std::sync::Arc;
 24
 25#[derive(Clone, Refineable, Debug)]
 26#[refineable(debug)]
 27pub struct Style {
 28    /// What layout strategy should be used?
 29    pub display: Display,
 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 fill: 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: CornerRadii,
103
104    /// The color of text within this element. Cascades to children unless overridden.
105    pub text_color: Option<Hsla>,
106
107    /// The font size in rems.
108    pub font_size: Option<f32>,
109
110    pub font_family: Option<Arc<str>>,
111
112    pub font_weight: Option<FontWeight>,
113
114    pub font_style: Option<FontStyle>,
115}
116
117impl Style {
118    pub fn text_style(&self, cx: &WindowContext) -> Option<TextStyleRefinement> {
119        if self.text_color.is_none()
120            && self.font_size.is_none()
121            && self.font_family.is_none()
122            && self.font_weight.is_none()
123            && self.font_style.is_none()
124        {
125            return None;
126        }
127
128        Some(TextStyleRefinement {
129            color: self.text_color.map(Into::into),
130            font_family: self.font_family.clone(),
131            font_size: self.font_size.map(|size| size * cx.rem_size()),
132            font_weight: self.font_weight,
133            font_style: self.font_style,
134            underline: None,
135        })
136    }
137
138    pub fn to_taffy(&self, rem_size: f32) -> taffy::style::Style {
139        taffy::style::Style {
140            display: self.display,
141            overflow: self.overflow.clone().into(),
142            scrollbar_width: self.scrollbar_width,
143            position: self.position,
144            inset: self.inset.to_taffy(rem_size),
145            size: self.size.to_taffy(rem_size),
146            min_size: self.min_size.to_taffy(rem_size),
147            max_size: self.max_size.to_taffy(rem_size),
148            aspect_ratio: self.aspect_ratio,
149            margin: self.margin.to_taffy(rem_size),
150            padding: self.padding.to_taffy(rem_size),
151            border: self.border_widths.to_taffy(rem_size),
152            align_items: self.align_items,
153            align_self: self.align_self,
154            align_content: self.align_content,
155            justify_content: self.justify_content,
156            gap: self.gap.to_taffy(rem_size),
157            flex_direction: self.flex_direction,
158            flex_wrap: self.flex_wrap,
159            flex_basis: self.flex_basis.to_taffy(rem_size).into(),
160            flex_grow: self.flex_grow,
161            flex_shrink: self.flex_shrink,
162            ..Default::default() // Ignore grid properties for now
163        }
164    }
165
166    /// Paints the background of an element styled with this style.
167    pub fn paint_background<V: 'static>(&self, bounds: RectF, cx: &mut ViewContext<V>) {
168        let rem_size = cx.rem_size();
169        if let Some(color) = self.fill.as_ref().and_then(Fill::color) {
170            cx.scene().push_quad(gpui::Quad {
171                bounds,
172                background: Some(color.into()),
173                corner_radii: self.corner_radii.to_gpui(bounds.size(), rem_size),
174                border: Default::default(),
175            });
176        }
177    }
178
179    /// Paints the foreground of an element styled with this style.
180    pub fn paint_foreground<V: 'static>(&self, bounds: RectF, cx: &mut ViewContext<V>) {
181        let rem_size = cx.rem_size();
182
183        if let Some(color) = self.border_color {
184            let border = self.border_widths.to_pixels(rem_size);
185            if !border.is_empty() {
186                cx.scene().push_quad(gpui::Quad {
187                    bounds,
188                    background: None,
189                    corner_radii: self.corner_radii.to_gpui(bounds.size(), rem_size),
190                    border: scene::Border {
191                        color: color.into(),
192                        top: border.top,
193                        right: border.right,
194                        bottom: border.bottom,
195                        left: border.left,
196                    },
197                });
198            }
199        }
200    }
201}
202
203impl Default for Style {
204    fn default() -> Self {
205        Style {
206            display: Display::Block,
207            overflow: Point {
208                x: Overflow::Visible,
209                y: Overflow::Visible,
210            },
211            scrollbar_width: 0.0,
212            position: Position::Relative,
213            inset: Edges::auto(),
214            margin: Edges::<Length>::zero(),
215            padding: Edges::<DefiniteLength>::zero(),
216            border_widths: Edges::<AbsoluteLength>::zero(),
217            size: Size::auto(),
218            min_size: Size::auto(),
219            max_size: Size::auto(),
220            aspect_ratio: None,
221            gap: Size::zero(),
222            // Aligment
223            align_items: None,
224            align_self: None,
225            align_content: None,
226            justify_content: None,
227            // Flexbox
228            flex_direction: FlexDirection::Row,
229            flex_wrap: FlexWrap::NoWrap,
230            flex_grow: 0.0,
231            flex_shrink: 1.0,
232            flex_basis: Length::Auto,
233            fill: None,
234            border_color: None,
235            corner_radii: CornerRadii::default(),
236            text_color: None,
237            font_size: Some(1.),
238            font_family: None,
239            font_weight: None,
240            font_style: None,
241        }
242    }
243}
244
245#[derive(Clone, Debug)]
246pub enum Fill {
247    Color(Hsla),
248}
249
250impl Fill {
251    pub fn color(&self) -> Option<Hsla> {
252        match self {
253            Fill::Color(color) => Some(*color),
254        }
255    }
256}
257
258impl Default for Fill {
259    fn default() -> Self {
260        Self::Color(Hsla::default())
261    }
262}
263
264impl From<Hsla> for Fill {
265    fn from(color: Hsla) -> Self {
266        Self::Color(color)
267    }
268}
269
270#[derive(Clone, Refineable, Default, Debug)]
271#[refineable(debug)]
272pub struct CornerRadii {
273    top_left: AbsoluteLength,
274    top_right: AbsoluteLength,
275    bottom_left: AbsoluteLength,
276    bottom_right: AbsoluteLength,
277}
278
279impl CornerRadii {
280    pub fn to_gpui(&self, box_size: Vector2F, rem_size: f32) -> gpui::scene::CornerRadii {
281        let max_radius = box_size.x().min(box_size.y()) / 2.;
282
283        gpui::scene::CornerRadii {
284            top_left: self.top_left.to_pixels(rem_size).min(max_radius),
285            top_right: self.top_right.to_pixels(rem_size).min(max_radius),
286            bottom_left: self.bottom_left.to_pixels(rem_size).min(max_radius),
287            bottom_right: self.bottom_right.to_pixels(rem_size).min(max_radius),
288        }
289    }
290}
291
292pub trait Styleable {
293    type Style: Refineable + Default;
294
295    fn style_cascade(&mut self) -> &mut RefinementCascade<Self::Style>;
296    fn declared_style(&mut self) -> &mut <Self::Style as Refineable>::Refinement;
297
298    fn computed_style(&mut self) -> Self::Style {
299        Self::Style::from_refinement(&self.style_cascade().merged())
300    }
301
302    fn hover(self) -> Hoverable<Self>
303    where
304        Self: Sized,
305    {
306        hoverable(self)
307    }
308
309    fn active(self) -> Pressable<Self>
310    where
311        Self: Sized,
312    {
313        pressable(self)
314    }
315}
316
317use crate as gpui2;
318
319// Helpers methods that take and return mut self. This includes tailwind style methods for standard sizes etc.
320//
321// Example:
322// // Sets the padding to 0.5rem, just like class="p-2" in Tailwind.
323// fn p_2(mut self) -> Self;
324pub trait StyleHelpers: Sized + Styleable<Style = Style> {
325    styleable_helpers!();
326
327    fn full(mut self) -> Self {
328        self.declared_style().size.width = Some(relative(1.).into());
329        self.declared_style().size.height = Some(relative(1.).into());
330        self
331    }
332
333    fn relative(mut self) -> Self {
334        self.declared_style().position = Some(Position::Relative);
335        self
336    }
337
338    fn absolute(mut self) -> Self {
339        self.declared_style().position = Some(Position::Absolute);
340        self
341    }
342
343    fn block(mut self) -> Self {
344        self.declared_style().display = Some(Display::Block);
345        self
346    }
347
348    fn flex(mut self) -> Self {
349        self.declared_style().display = Some(Display::Flex);
350        self
351    }
352
353    fn flex_col(mut self) -> Self {
354        self.declared_style().flex_direction = Some(FlexDirection::Column);
355        self
356    }
357
358    fn flex_row(mut self) -> Self {
359        self.declared_style().flex_direction = Some(FlexDirection::Row);
360        self
361    }
362
363    fn flex_1(mut self) -> Self {
364        self.declared_style().flex_grow = Some(1.);
365        self.declared_style().flex_shrink = Some(1.);
366        self.declared_style().flex_basis = Some(relative(0.).into());
367        self
368    }
369
370    fn flex_auto(mut self) -> Self {
371        self.declared_style().flex_grow = Some(1.);
372        self.declared_style().flex_shrink = Some(1.);
373        self.declared_style().flex_basis = Some(Length::Auto);
374        self
375    }
376
377    fn flex_initial(mut self) -> Self {
378        self.declared_style().flex_grow = Some(0.);
379        self.declared_style().flex_shrink = Some(1.);
380        self.declared_style().flex_basis = Some(Length::Auto);
381        self
382    }
383
384    fn flex_none(mut self) -> Self {
385        self.declared_style().flex_grow = Some(0.);
386        self.declared_style().flex_shrink = Some(0.);
387        self
388    }
389
390    fn grow(mut self) -> Self {
391        self.declared_style().flex_grow = Some(1.);
392        self
393    }
394
395    fn items_start(mut self) -> Self {
396        self.declared_style().align_items = Some(AlignItems::FlexStart);
397        self
398    }
399
400    fn items_end(mut self) -> Self {
401        self.declared_style().align_items = Some(AlignItems::FlexEnd);
402        self
403    }
404
405    fn items_center(mut self) -> Self {
406        self.declared_style().align_items = Some(AlignItems::Center);
407        self
408    }
409
410    fn justify_between(mut self) -> Self {
411        self.declared_style().justify_content = Some(JustifyContent::SpaceBetween);
412        self
413    }
414
415    fn justify_center(mut self) -> Self {
416        self.declared_style().justify_content = Some(JustifyContent::Center);
417        self
418    }
419
420    fn justify_start(mut self) -> Self {
421        self.declared_style().justify_content = Some(JustifyContent::Start);
422        self
423    }
424
425    fn justify_end(mut self) -> Self {
426        self.declared_style().justify_content = Some(JustifyContent::End);
427        self
428    }
429
430    fn justify_around(mut self) -> Self {
431        self.declared_style().justify_content = Some(JustifyContent::SpaceAround);
432        self
433    }
434
435    fn fill<F>(mut self, fill: F) -> Self
436    where
437        F: Into<Fill>,
438    {
439        self.declared_style().fill = Some(fill.into());
440        self
441    }
442
443    fn border_color<C>(mut self, border_color: C) -> Self
444    where
445        C: Into<Hsla>,
446    {
447        self.declared_style().border_color = Some(border_color.into());
448        self
449    }
450
451    fn text_color<C>(mut self, color: C) -> Self
452    where
453        C: Into<Hsla>,
454    {
455        self.declared_style().text_color = Some(color.into());
456        self
457    }
458
459    fn text_xs(mut self) -> Self {
460        self.declared_style().font_size = Some(0.75);
461        self
462    }
463
464    fn text_sm(mut self) -> Self {
465        self.declared_style().font_size = Some(0.875);
466        self
467    }
468
469    fn text_base(mut self) -> Self {
470        self.declared_style().font_size = Some(1.0);
471        self
472    }
473
474    fn text_lg(mut self) -> Self {
475        self.declared_style().font_size = Some(1.125);
476        self
477    }
478
479    fn text_xl(mut self) -> Self {
480        self.declared_style().font_size = Some(1.25);
481        self
482    }
483
484    fn text_2xl(mut self) -> Self {
485        self.declared_style().font_size = Some(1.5);
486        self
487    }
488
489    fn text_3xl(mut self) -> Self {
490        self.declared_style().font_size = Some(1.875);
491        self
492    }
493
494    fn font(mut self, family_name: impl Into<Arc<str>>) -> Self {
495        self.declared_style().font_family = Some(family_name.into());
496        self
497    }
498}