ailloli_ui_widgets/text/
label.rs

1//! Retained shaped text label with static or reactive string content.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use ailloli_ui_core::event::Event;
5use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle};
6use ailloli_ui_core::{Color, Constraints, FontId, Rect, Size, TextStyle};
7use ailloli_ui_runtime::component::{Binding, IntoView, View, Widget};
8use ailloli_ui_runtime::input::EventCtx;
9use ailloli_ui_runtime::layout::{LayoutArtifact, LayoutResult};
10use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx};
11use ailloli_ui_runtime::scene::PaintCtx;
12use ailloli_ui_runtime::{DrawCmd, DrawText};
13use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
14
15/// Text label shaped through [`TextSystem`] with static or reactive content.
16///
17/// Defaults to 14-logical-pixel white UI text and
18/// [`WrapMode::WordOrAnywhere`]. Without a text system, layout falls back to
19/// zero width and `1.2 * px_size` height, while paint emits nothing.
20/// Reactive content is observed during layout. Until a newer layout commits,
21/// paint keeps using the previously shaped artifact instead of fitting new
22/// content into stale bounds.
23///
24/// # Examples
25///
26/// ```
27/// use ailloli_ui_widgets::text::Text;
28/// let label = Text::new("Hello").size(16.0).nowrap();
29/// let _ = label;
30/// ```
31pub struct Text {
32    /// Outer logical sizing policy.
33    pub(crate) layout: LayoutStyle,
34    /// Parent-flex participation metadata.
35    pub(crate) flex_item: FlexItemStyle,
36    /// Static or reactive UTF-8 label content.
37    content: Binding<String>,
38    /// Font, size, color, and line-height configuration.
39    style: TextStyle,
40    /// Wrapping policy used during text layout.
41    wrap_mode: WrapMode,
42}
43
44crate::impl_layout_builders_unit!(Text);
45
46impl Text {
47    /// Creates a label from a static string or reactive string binding.
48    ///
49    /// # Examples
50    ///
51    /// ```
52    /// use ailloli_ui_widgets::text::Text;
53    /// let label = Text::new(String::from("Hello"));
54    /// let _ = label;
55    /// ```
56    pub fn new(content: impl Into<Binding<String>>) -> Self {
57        Self {
58            layout: LayoutStyle::default(),
59            flex_item: FlexItemStyle::default(),
60            content: content.into(),
61            style: TextStyle::new(FontId::Ui, 14, Color::WHITE),
62            wrap_mode: WrapMode::WordOrAnywhere,
63        }
64    }
65
66    /// Replaces the static or reactive content binding.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// use ailloli_ui_widgets::text::Text;
72    /// let label = Text::new("old").content("new");
73    /// let _ = label;
74    /// ```
75    pub fn content(mut self, content: impl Into<Binding<String>>) -> Self {
76        self.content = content.into();
77        self
78    }
79
80    /// Sets the font size after rounding to an integer logical pixel.
81    ///
82    /// The result is clamped to `1..=u16::MAX`; `NaN` becomes one and positive
83    /// infinity saturates at `u16::MAX` through Rust's float-to-int cast.
84    ///
85    /// # Examples
86    ///
87    /// ```
88    /// use ailloli_ui_widgets::text::Text;
89    /// let label = Text::new("Hello").size(15.6);
90    /// let _ = label;
91    /// ```
92    pub fn size(mut self, size: f32) -> Self {
93        self.style.px_size = size.round().max(1.0) as u16;
94        self
95    }
96
97    /// Replaces the complete font, size, color, and decoration style.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// use ailloli_ui_core::{Color, FontId, TextStyle};
103    /// use ailloli_ui_widgets::text::Text;
104    /// let label = Text::new("Code").style(TextStyle::new(FontId::Mono, 13, Color::WHITE));
105    /// let _ = label;
106    /// ```
107    pub fn style(mut self, style: TextStyle) -> Self {
108        self.style = style;
109        self
110    }
111
112    /// Replaces the shaping wrap policy.
113    ///
114    /// # Examples
115    ///
116    /// ```
117    /// use ailloli_ui_widgets::text::{Text, WrapMode};
118    /// let label = Text::new("two words").wrap_mode(WrapMode::Word);
119    /// let _ = label;
120    /// ```
121    pub fn wrap_mode(mut self, wrap_mode: WrapMode) -> Self {
122        self.wrap_mode = wrap_mode;
123        self
124    }
125
126    /// Selects wrapping at word boundaries only.
127    ///
128    /// # Examples
129    ///
130    /// ```
131    /// use ailloli_ui_widgets::text::Text;
132    /// let label = Text::new("two words").wrap_words();
133    /// let _ = label;
134    /// ```
135    pub fn wrap_words(self) -> Self {
136        self.wrap_mode(WrapMode::Word)
137    }
138
139    /// Selects word wrapping with arbitrary fallback breaks.
140    ///
141    /// # Examples
142    ///
143    /// ```
144    /// use ailloli_ui_widgets::text::Text;
145    /// let label = Text::new("averylongword").wrap_anywhere();
146    /// let _ = label;
147    /// ```
148    pub fn wrap_anywhere(self) -> Self {
149        self.wrap_mode(WrapMode::WordOrAnywhere)
150    }
151
152    /// Disables wrapping regardless of available width.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// use ailloli_ui_widgets::text::Text;
158    /// let label = Text::new("one line").nowrap();
159    /// let _ = label;
160    /// ```
161    pub fn nowrap(self) -> Self {
162        self.wrap_mode(WrapMode::NoWrap)
163    }
164}
165
166/// Frozen retained state used by the public [`Text`] builder.
167///
168/// This low-level type is public for runtime composition but its fields remain
169/// private; applications normally construct [`Text`] instead.
170///
171/// # Examples
172///
173/// ```
174/// use ailloli_ui_runtime::component::{IntoView, View};
175/// use ailloli_ui_widgets::text::Text;
176/// let _view: View<()> = Text::new("Hello").into_view();
177/// ```
178pub struct TextWidget {
179    /// Outer logical sizing policy.
180    layout: LayoutStyle,
181    /// Static or reactive UTF-8 label content.
182    content: Binding<String>,
183    /// Font, size, color, and line-height configuration.
184    style: TextStyle,
185    /// Wrapping policy used during text layout.
186    wrap_mode: WrapMode,
187}
188
189/// Shapes one label and bounds its line width to a non-negative value.
190fn layout_via_system(
191    ts: &mut TextSystem,
192    text: &str,
193    style: TextStyle,
194    max_width: f32,
195    wrap_mode: WrapMode,
196) -> ailloli_ui_text::TextLayoutHandle {
197    ts.layout_cached(TextLayoutParams {
198        text,
199        style,
200        max_width: Some(max_width.max(0.0)),
201        wrap_mode,
202    })
203}
204
205/// Implements binding-aware layout, artifact reuse, and baseline painting.
206impl<A: 'static> Widget<A> for TextWidget {
207    fn debug_name(&self) -> &'static str {
208        "Text"
209    }
210
211    fn layout_dependency_revision(&self) -> u64 {
212        self.content.revision()
213    }
214
215    fn layout(
216        &self,
217        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
218        ctx: &mut LayoutCtx<'_>,
219        _children: &mut [LayoutChild],
220        constraints: Constraints,
221    ) -> LayoutResult {
222        let content = self.content.read();
223        // Shaping must use the same declarative width ceiling that will size
224        // the widget. Applying `max_width` only after intrinsic measurement
225        // can report a one-line height to a flex parent, then reshape into two
226        // lines during the tight Commit pass and paint outside that stale slot.
227        let constraints = constraints.normalized();
228        let resolved = self.layout.resolve(constraints);
229        let max_w = if resolved.width.is_some() {
230            // Explicit widths obey the parent's complete interval, just like
231            // the final `apply_layout_size` call below.
232            resolved.size(0.0, 0.0, constraints).0
233        } else {
234            // An intrinsic width ignores the parent's minimum, but both the
235            // parent maximum and a declarative `max_width` cap shaping.
236            resolved
237                .max_width
238                .unwrap_or(constraints.max_w)
239                .min(constraints.max_w)
240        };
241        let prepared = ctx
242            .text_system
243            .as_deref_mut()
244            .map(|ts| layout_via_system(ts, &content, self.style, max_w, self.wrap_mode));
245        let intrinsic = if let Some(prepared) = prepared.as_ref() {
246            Size::new(prepared.metrics.width, prepared.metrics.height)
247        } else {
248            Size::new(0.0, self.style.px_size as f32 * 1.2)
249        };
250        let size = apply_layout_size(intrinsic, self.layout, constraints);
251        LayoutResult {
252            size,
253            children: Vec::new(),
254            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
255            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
256            overlay_hit_bounds: Vec::new(),
257            clip: None,
258            is_window_root_clip: false,
259            artifact: prepared.map(LayoutArtifact::Text),
260        }
261    }
262
263    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
264        let Some(LayoutArtifact::Text(prepared)) = layout.artifact.as_ref() else {
265            return;
266        };
267        let prepared = prepared.clone();
268        let baseline = prepared.lines.first().map(|l| l.baseline_y).unwrap_or(0.0);
269        let cmd = DrawCmd::Text(DrawText {
270            // Contract: pos.y is baseline (baseline contract).
271            pos: [bounds.x, bounds.y + baseline],
272            color: self.style.color,
273            decoration: self.style.decoration,
274            layout: prepared,
275        });
276
277        ctx.push(cmd);
278    }
279
280    fn can_replay_committed_text_artifact(&self) -> bool {
281        true
282    }
283
284    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
285    }
286}
287
288/// Converts the builder into a retained leaf widget.
289impl<A: 'static> IntoView<A> for Text {
290    fn into_view(self) -> View<A> {
291        finish_view_sized(
292            View::leaf(TextWidget {
293                layout: self.layout,
294                content: self.content,
295                style: self.style,
296                wrap_mode: self.wrap_mode,
297            }),
298            self.flex_item,
299            LayoutSizeHint::from_layout(self.layout),
300        )
301    }
302}