label_like.rs

  1use gpui::{relative, AnyElement, Div, Styled};
  2use smallvec::SmallVec;
  3
  4use crate::prelude::*;
  5
  6#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
  7pub enum LabelSize {
  8    #[default]
  9    Default,
 10    Small,
 11}
 12
 13#[derive(Default, PartialEq, Copy, Clone)]
 14pub enum LineHeightStyle {
 15    #[default]
 16    TextLabel,
 17    /// Sets the line height to 1
 18    UILabel,
 19}
 20
 21pub trait LabelCommon {
 22    fn size(self, size: LabelSize) -> Self;
 23    fn line_height_style(self, line_height_style: LineHeightStyle) -> Self;
 24    fn color(self, color: Color) -> Self;
 25    fn strikethrough(self, strikethrough: bool) -> Self;
 26}
 27
 28#[derive(IntoElement)]
 29pub struct LabelLike {
 30    size: LabelSize,
 31    line_height_style: LineHeightStyle,
 32    pub(crate) color: Color,
 33    strikethrough: bool,
 34    children: SmallVec<[AnyElement; 2]>,
 35}
 36
 37impl LabelLike {
 38    pub fn new() -> Self {
 39        Self {
 40            size: LabelSize::Default,
 41            line_height_style: LineHeightStyle::default(),
 42            color: Color::Default,
 43            strikethrough: false,
 44            children: SmallVec::new(),
 45        }
 46    }
 47}
 48
 49impl LabelCommon for LabelLike {
 50    fn size(mut self, size: LabelSize) -> Self {
 51        self.size = size;
 52        self
 53    }
 54
 55    fn line_height_style(mut self, line_height_style: LineHeightStyle) -> Self {
 56        self.line_height_style = line_height_style;
 57        self
 58    }
 59
 60    fn color(mut self, color: Color) -> Self {
 61        self.color = color;
 62        self
 63    }
 64
 65    fn strikethrough(mut self, strikethrough: bool) -> Self {
 66        self.strikethrough = strikethrough;
 67        self
 68    }
 69}
 70
 71impl ParentElement for LabelLike {
 72    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
 73        &mut self.children
 74    }
 75}
 76
 77impl RenderOnce for LabelLike {
 78    type Rendered = Div;
 79
 80    fn render(self, cx: &mut WindowContext) -> Self::Rendered {
 81        div()
 82            .when(self.strikethrough, |this| {
 83                this.relative().child(
 84                    div()
 85                        .absolute()
 86                        .top_1_2()
 87                        .w_full()
 88                        .h_px()
 89                        .bg(Color::Hidden.color(cx)),
 90                )
 91            })
 92            .map(|this| match self.size {
 93                LabelSize::Default => this.text_ui(),
 94                LabelSize::Small => this.text_ui_sm(),
 95            })
 96            .when(self.line_height_style == LineHeightStyle::UILabel, |this| {
 97                this.line_height(relative(1.))
 98            })
 99            .text_color(self.color.color(cx))
100            .children(self.children)
101    }
102}