freya_core/render/utils/
label.rs

1use freya_engine::prelude::*;
2use freya_native_core::{
3    prelude::NodeType,
4    real_dom::NodeImmutable,
5};
6use torin::{
7    node::Node,
8    prelude::Size2D,
9};
10
11use super::ParagraphData;
12use crate::{
13    dom::*,
14    states::FontStyleState,
15};
16
17pub fn create_label(
18    node: &DioxusNode,
19    torin_node: &Node,
20    area_size: &Size2D,
21    font_collection: &FontCollection,
22    default_font_family: &[String],
23    scale_factor: f32,
24) -> ParagraphData {
25    let font_style = &*node.get::<FontStyleState>().unwrap();
26
27    let mut paragraph_style = ParagraphStyle::default();
28    paragraph_style.set_text_align(font_style.text_align);
29    paragraph_style.set_max_lines(font_style.max_lines);
30    paragraph_style.set_replace_tab_characters(true);
31    paragraph_style.set_text_height_behavior(font_style.text_height);
32
33    if let Some(ellipsis) = font_style.text_overflow.get_ellipsis() {
34        paragraph_style.set_ellipsis(ellipsis);
35    }
36
37    let text_style =
38        font_style.text_style(default_font_family, scale_factor, font_style.text_height);
39    paragraph_style.set_text_style(&text_style);
40
41    let mut paragraph_builder = ParagraphBuilder::new(&paragraph_style, font_collection);
42
43    for child in node.children() {
44        if let NodeType::Text(text) = &*child.node_type() {
45            paragraph_builder.add_text(text);
46        }
47    }
48
49    let mut paragraph = paragraph_builder.build();
50    paragraph.layout(
51        if font_style.max_lines == Some(1) && font_style.text_align == TextAlign::default() {
52            f32::MAX
53        } else {
54            area_size.width + 1.0
55        },
56    );
57
58    // Relayout the paragraph so that its aligned based on its longest width
59    match font_style.text_align {
60        TextAlign::Center | TextAlign::Justify | TextAlign::Right | TextAlign::End
61            if torin_node.width.inner_sized() =>
62        {
63            paragraph.layout(paragraph.longest_line() + 1.);
64        }
65        _ => {}
66    }
67
68    ParagraphData {
69        size: Size2D::new(paragraph.longest_line(), paragraph.height()),
70        paragraph,
71    }
72}