label_like.rs

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