Skip to main content

polyhorn_ios/raw/
markup.rs

1use polyhorn_ios_sys::foundation::{
2    NSAttributedString, NSAttributes, NSMutableParagraphStyle, NSTextAlignment,
3};
4use polyhorn_ui::color::{Color, NamedColor};
5use polyhorn_ui::font::{Font, FontFamily, FontSize, FontStyle, FontWeight, GenericFontFamily};
6use polyhorn_ui::styles::{Inherited, TextAlign, TextStyle};
7
8use crate::raw::Convert;
9
10/// Generates a new `NSAttributedString` for the given text with the given text
11/// style.
12pub fn attributed_string(text: &str, style: &TextStyle) -> NSAttributedString {
13    let mut paragraph_style = NSMutableParagraphStyle::new();
14    paragraph_style.set_alignment(match style.text_align {
15        Inherited::Inherited => NSTextAlignment::Left,
16        Inherited::Specified(specified) => match specified {
17            TextAlign::Left => NSTextAlignment::Left,
18            TextAlign::Center => NSTextAlignment::Center,
19            TextAlign::Right => NSTextAlignment::Right,
20        },
21    });
22
23    let font = Font {
24        family: match style.font_family {
25            Inherited::Inherited => FontFamily::Generic(GenericFontFamily::SansSerif),
26            Inherited::Specified(family) => family,
27        },
28        weight: match style.font_weight {
29            Inherited::Inherited => FontWeight::Normal,
30            Inherited::Specified(weight) => weight,
31        },
32        style: match style.font_style {
33            Inherited::Inherited => FontStyle::Normal,
34            Inherited::Specified(style) => style,
35        },
36        size: match style.font_size {
37            Inherited::Inherited => FontSize::Medium,
38            Inherited::Specified(size) => size,
39        },
40    };
41
42    let color = match style.color {
43        Inherited::Inherited => Color::black(),
44        Inherited::Specified(color) => color,
45    }
46    .convert();
47
48    let style = paragraph_style.into();
49
50    NSAttributedString::with_attributes(
51        &text,
52        NSAttributes {
53            font: font.convert(),
54            foreground_color: color,
55            paragraph_style: style,
56        },
57    )
58}