bevy_ui_builders/label/
builder.rs

1//! LabelBuilder implementation
2
3use bevy::prelude::*;
4use super::types::*;
5
6/// Builder for creating labels with consistent styling
7pub struct LabelBuilder {
8    text: String,
9    style: LabelStyle,
10    font_size: Option<f32>,
11    color: Option<Color>,
12    margin: UiRect,
13    text_align: JustifyContent,
14}
15
16impl LabelBuilder {
17    pub fn new(text: impl Into<String>) -> Self {
18        Self {
19            text: text.into(),
20            style: LabelStyle::Body,
21            font_size: None,
22            color: None,
23            margin: UiRect::all(Val::Px(0.0)),
24            text_align: JustifyContent::Start,
25        }
26    }
27
28    pub fn style(mut self, style: LabelStyle) -> Self {
29        self.style = style;
30        self
31    }
32
33    /// Override the font size
34    pub fn font_size(mut self, size: f32) -> Self {
35        self.font_size = Some(size);
36        self
37    }
38
39    /// Override the text color
40    pub fn color(mut self, color: Color) -> Self {
41        self.color = Some(color);
42        self
43    }
44
45    pub fn margin(mut self, margin: UiRect) -> Self {
46        self.margin = margin;
47        self
48    }
49
50    /// Set text alignment
51    pub fn text_align(mut self, align: JustifyContent) -> Self {
52        self.text_align = align;
53        self
54    }
55
56    pub fn build(self, parent: &mut ChildSpawnerCommands) -> Entity {
57        let font_size = self.font_size.unwrap_or_else(|| self.style.font_size());
58        let text_color = self.color.unwrap_or_else(|| self.style.text_color());
59
60        parent
61            .spawn((
62                Node {
63                    margin: self.margin,
64                    justify_content: self.text_align,
65                    ..default()
66                },
67                BackgroundColor(Color::NONE),
68            ))
69            .with_children(|container| {
70                // The actual text entity
71                container.spawn((
72                    Text::new(self.text.clone()),
73                    TextFont {
74                        font_size,
75                        ..default()
76                    },
77                    TextColor(text_color),
78                    super::types::Label { style: self.style },
79                ));
80            })
81            .id()
82    }
83}
84
85/// Convenience function to create a label builder
86pub fn label(text: impl Into<String>) -> LabelBuilder {
87    LabelBuilder::new(text)
88}