Skip to main content

pax_std/core/
text.rs

1use pax_runtime::{
2    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
3};
4
5use pax_engine::api::{Color, Fill, Layer, Numeric, Property, RenderContext, Size};
6use pax_engine::*;
7
8use pax_message::{
9    AnyCreatePatch, ColorMessage, FontPatch, FontStyleMessage, FontWeightMessage,
10    TextAlignHorizontalMessage, TextAlignVerticalMessage, TextPatch, TextStyleMessage,
11    WebFontMessage,
12};
13
14use pax_runtime::api::{borrow, borrow_mut, use_RefCell};
15
16use_RefCell!();
17use std::rc::Rc;
18#[cfg(feature = "designtime")]
19use {
20    kurbo::{RoundedRect, Shape},
21    pax_runtime::DEBUG_TEXT_GREEN_BACKGROUND,
22};
23
24use crate::common::{native_surface_opacity, patch_if_needed};
25
26/// Renders and styles text through the target's native text system.
27///
28/// A constrained width with an omitted height allows native measurement to
29/// determine the height of wrapped content. Selection, editing, font loading,
30/// and accessibility behavior depend on the target's native implementation;
31/// test the intended interaction on each shipping target.
32#[pax]
33#[engine_import_path("pax_engine")]
34#[custom(Default)]
35#[primitive("pax_std::core::text::TextInstance")]
36pub struct Text {
37    /// Whether the text can be edited by the user.
38    pub editable: Property<bool>,
39    /// Requests selectable text. On the current iOS/iPadOS path, non-editable
40    /// text uses the interactive selection view only when `clip` is enabled.
41    pub selectable: Property<bool>,
42    /// Whether text overflow is clipped to the node bounds.
43    pub clip: Property<bool>,
44    /// Text content to display.
45    pub text: Property<String>,
46    /// Text styling.
47    pub style: Property<TextStyle>,
48    // Secondary style link used by native text patch plumbing.
49    pub _style_link: Property<TextStyle>,
50    /// Whether `text` should be interpreted as Markdown.
51    pub markdown: Property<bool>,
52    /// Whether long text lines should wrap inside the node bounds.
53    pub wrap: Property<bool>,
54}
55
56impl Default for Text {
57    fn default() -> Self {
58        Self {
59            editable: Property::new(false),
60            selectable: Property::new(true),
61            clip: Property::new(false),
62            text: Property::new("".to_string()),
63            style: Property::new(TextStyle::default()),
64            _style_link: Property::new(TextStyle::default()),
65            markdown: Property::new(false),
66            wrap: Property::new(true),
67        }
68    }
69}
70
71// Runtime instance backing `<Text>`.
72pub struct TextInstance {
73    base: BaseInstance,
74    measurement_state: RefCell<TextMeasurementState>,
75}
76
77#[derive(Clone, PartialEq)]
78struct TextMeasurementKey {
79    content: String,
80    markdown: bool,
81    wrap: bool,
82    clip: bool,
83    editable: bool,
84    selectable: bool,
85    style: TextStyleMessage,
86    style_link: TextStyleMessage,
87    width_constraint_bits: Option<u64>,
88    height_constraint_bits: Option<u64>,
89}
90
91#[derive(Default)]
92struct TextMeasurementState {
93    next_generation: u64,
94    requested_key: Option<TextMeasurementKey>,
95    pending_generation: Option<u64>,
96}
97
98impl TextInstance {
99    fn request_measurement_generation(
100        &self,
101        key: TextMeasurementKey,
102        has_current_measurement: bool,
103    ) -> Option<u64> {
104        let mut state = self.measurement_state.borrow_mut();
105        let key_changed = state.requested_key.as_ref() != Some(&key);
106        if key_changed || (!has_current_measurement && state.pending_generation.is_none()) {
107            state.next_generation = state.next_generation.wrapping_add(1).max(1);
108            let generation = state.next_generation;
109            state.requested_key = Some(key);
110            state.pending_generation = Some(generation);
111            Some(generation)
112        } else {
113            None
114        }
115    }
116
117    fn clear_measurement_request(&self, expanded_node: &Rc<ExpandedNode>) {
118        let mut state = self.measurement_state.borrow_mut();
119        state.requested_key = None;
120        state.pending_generation = None;
121        if expanded_node.measured_size.get().is_some() {
122            expanded_node.measured_size.set(None);
123        }
124    }
125
126    fn accept_measurement_response(
127        &self,
128        expanded_node: &Rc<ExpandedNode>,
129        generation: u64,
130        width: f64,
131        height: f64,
132    ) {
133        let mut state = self.measurement_state.borrow_mut();
134        if state.pending_generation != Some(generation) {
135            return;
136        }
137        state.pending_generation = None;
138        drop(state);
139        expanded_node.set_measured_size(width, height);
140    }
141}
142
143impl InstanceNode for TextInstance {
144    fn instantiate(args: InstantiationArgs) -> Rc<Self>
145    where
146        Self: Sized,
147    {
148        Rc::new(Self {
149            base: BaseInstance::new(
150                args,
151                InstanceFlags {
152                    invisible_to_slot: false,
153                    invisible_to_raycasting: false,
154                    layer: Layer::Native,
155                    is_component: false,
156                    is_slot: false,
157                },
158            ),
159            measurement_state: RefCell::new(TextMeasurementState::default()),
160        })
161    }
162
163    fn render(
164        &self,
165        _expanded_node: &ExpandedNode,
166        _context: &Rc<RuntimeContext>,
167        _rc: &mut dyn RenderContext,
168    ) {
169        //no-op -- only native rendering for Text (unless/until we support rasterizing text, which Piet should be able to handle!)
170
171        #[cfg(feature = "designtime")]
172        if DEBUG_TEXT_GREEN_BACKGROUND {
173            let tab = _expanded_node.transform_and_bounds.get();
174            let width: f64 = tab.bounds.0;
175            let height: f64 = tab.bounds.1;
176            let rect = RoundedRect::new(0.0, 0.0, width, height, 0.0);
177            let bez_path = rect.to_path(0.1);
178            let transformed_bez_path = Into::<kurbo::Affine>::into(tab.transform) * bez_path;
179            _rc.fill(
180                _expanded_node.occlusion.get().render_layer_id,
181                transformed_bez_path,
182                &Fill::Solid(Color::rgba(0.into(), 255.into(), 0.into(), 100.into())),
183            );
184        }
185    }
186
187    fn handle_mount(
188        self: Rc<Self>,
189        expanded_node: &Rc<ExpandedNode>,
190        context: &Rc<RuntimeContext>,
191    ) {
192        // Send creation message
193        let id = expanded_node.id.to_u32();
194        context.enqueue_native_message(pax_message::NativeMessage::TextCreate(AnyCreatePatch {
195            id,
196            parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
197            render_layer_id: 0,
198        }));
199
200        // send update message when relevant properties change
201        let weak_self_ref = Rc::downgrade(&expanded_node);
202        let instance = Rc::clone(&self);
203        let context = Rc::clone(context);
204        let last_patch = Rc::new(RefCell::new(TextPatch {
205            id,
206            ..Default::default()
207        }));
208
209        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
210            .values()
211            .cloned()
212            .map(|v| v.get_untyped_property().clone())
213            .chain([
214                expanded_node.transform_and_bounds.untyped(),
215                expanded_node.computed_opacity.untyped(),
216                expanded_node.occlusion.untyped(),
217            ])
218            .collect();
219
220        expanded_node
221            .changed_listener
222            .replace_with(Property::computed(
223                move || {
224                    let Some(expanded_node) = weak_self_ref.upgrade() else {
225                        return;
226                    };
227                    let mut old_state = borrow_mut!(last_patch);
228
229                    let mut patch = TextPatch {
230                        id,
231                        ..Default::default()
232                    };
233                    expanded_node.with_properties_unwrapped(|properties: &mut Text| {
234                        let computed_tab = expanded_node.transform_and_bounds.get();
235                        let (width, height) = computed_tab.bounds;
236                        let cp = expanded_node.get_common_properties();
237                        let cp = borrow!(cp);
238                        // send width/height only if common props exist, otherwise we are in "listening mode"
239                        // trying to infer width and height from the engine. To signal this we
240                        // send width/height = -1.0, telling chassis that "you tell me!".
241                        let (width, height) = (
242                            cp.width.get().is_some().then_some(width).unwrap_or(-1.0),
243                            cp.height.get().is_some().then_some(height).unwrap_or(-1.0),
244                        );
245                        let content = properties.text.get();
246                        let markdown = properties.markdown.get();
247                        let wrap = properties.wrap.get();
248                        let style: TextStyleMessage = (&properties.style.get()).into();
249                        let style_link: TextStyleMessage = (&properties._style_link.get()).into();
250                        let editable = properties.editable.get();
251                        let selectable = properties.selectable.get();
252                        let clip = properties.clip.get();
253
254                        let updates = [
255                            // Content
256                            patch_if_needed(
257                                &mut old_state.content,
258                                &mut patch.content,
259                                content.clone(),
260                            ),
261                            patch_if_needed(&mut old_state.markdown, &mut patch.markdown, markdown),
262                            patch_if_needed(&mut old_state.wrap, &mut patch.wrap, wrap),
263                            // Styles
264                            patch_if_needed(&mut old_state.style, &mut patch.style, style.clone()),
265                            patch_if_needed(
266                                &mut old_state.style_link,
267                                &mut patch.style_link,
268                                style_link.clone(),
269                            ),
270                            patch_if_needed(&mut old_state.editable, &mut patch.editable, editable),
271                            patch_if_needed(
272                                &mut old_state.selectable,
273                                &mut patch.selectable,
274                                selectable,
275                            ),
276                            patch_if_needed(&mut old_state.clip, &mut patch.clip, clip),
277                            // Transform and bounds
278                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
279                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
280                            patch_if_needed(
281                                &mut old_state.parent_frame,
282                                &mut patch.parent_frame,
283                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
284                            ),
285                            patch_if_needed(
286                                &mut old_state.z_index,
287                                &mut patch.z_index,
288                                expanded_node.occlusion.get().z_index,
289                            ),
290                            patch_if_needed(
291                                &mut old_state.transform,
292                                &mut patch.transform,
293                                computed_tab.transform.coeffs().to_vec(),
294                            ),
295                            patch_if_needed(
296                                &mut old_state.opacity,
297                                &mut patch.opacity,
298                                native_surface_opacity(&expanded_node, &context),
299                            ),
300                        ];
301                        let measurement_key = text_measurement_key(
302                            content.clone(),
303                            markdown,
304                            wrap,
305                            clip,
306                            editable,
307                            selectable,
308                            style,
309                            style_link,
310                            width,
311                            height,
312                        );
313                        if let Some(measurement_key) = measurement_key {
314                            patch.measure_generation = instance.request_measurement_generation(
315                                measurement_key,
316                                expanded_node.measured_size.get().is_some(),
317                            );
318                        } else {
319                            instance.clear_measurement_request(&expanded_node);
320                        }
321
322                        if updates.into_iter().any(|v| v == true)
323                            || patch.measure_generation.is_some()
324                        {
325                            // HACK: markdown flag and content is needed at the same time, so if we have one,
326                            // include the other:
327                            if patch.markdown.is_some() && patch.content.is_none() {
328                                patch.content = Some(content);
329                            }
330                            if patch.content.is_some() && patch.markdown.is_none() {
331                                patch.markdown = Some(markdown);
332                            }
333                            context.enqueue_native_message(pax_message::NativeMessage::TextUpdate(
334                                patch,
335                            ));
336                        }
337                    });
338                    ()
339                },
340                &deps,
341            ));
342    }
343
344    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
345        let id = expanded_node.id.to_u32();
346        expanded_node
347            .changed_listener
348            .replace_with(Property::default());
349        context.enqueue_native_message(pax_message::NativeMessage::TextDelete(id));
350    }
351
352    fn resolve_debug(
353        &self,
354        f: &mut std::fmt::Formatter,
355        expanded_node: Option<&ExpandedNode>,
356    ) -> std::fmt::Result {
357        match expanded_node {
358            Some(expanded_node) => expanded_node.with_properties_unwrapped(|r: &mut Text| {
359                f.debug_struct("Text").field("text", &r.text.get()).finish()
360            }),
361            None => f.debug_struct("Text").finish_non_exhaustive(),
362        }
363    }
364
365    fn base(&self) -> &BaseInstance {
366        &self.base
367    }
368
369    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
370        // Native text occludes by its frame; content/style updates are native patches.
371        false
372    }
373
374    fn handle_native_interrupt(
375        &self,
376        expanded_node: &Rc<ExpandedNode>,
377        interrupt: &pax_message::NativeInterrupt,
378    ) {
379        if let pax_message::NativeInterrupt::TextInput(args) = interrupt {
380            expanded_node.with_properties_unwrapped(|properties: &mut Text| {
381                properties.text.set(args.text.clone())
382            });
383        } else if let pax_message::NativeInterrupt::TextMeasurementResponse(args) = interrupt {
384            self.accept_measurement_response(
385                expanded_node,
386                args.generation,
387                args.width,
388                args.height,
389            );
390        } else {
391            log::warn!("text element was handed interrupt it doesn't use");
392        }
393    }
394}
395
396fn explicit_constraint_bits(value: f64) -> Option<u64> {
397    (value >= 0.0).then_some(value.to_bits())
398}
399
400fn text_measurement_key(
401    content: String,
402    markdown: bool,
403    wrap: bool,
404    clip: bool,
405    editable: bool,
406    selectable: bool,
407    style: TextStyleMessage,
408    style_link: TextStyleMessage,
409    width: f64,
410    height: f64,
411) -> Option<TextMeasurementKey> {
412    if width >= 0.0 && height >= 0.0 {
413        return None;
414    }
415
416    Some(TextMeasurementKey {
417        content,
418        markdown,
419        wrap,
420        clip,
421        editable,
422        selectable,
423        style,
424        style_link,
425        width_constraint_bits: explicit_constraint_bits(width),
426        height_constraint_bits: explicit_constraint_bits(height),
427    })
428}
429
430/// Struct describing platform-agnostic text display properties.
431#[pax]
432#[engine_import_path("pax_engine")]
433#[custom(Default)]
434pub struct TextStyle {
435    #[serde(default)]
436    /// Font family/source/style/weight configuration.
437    pub font: Property<Font>,
438    #[serde(default)]
439    /// Font size, in pixels.
440    pub font_size: Property<Size>,
441    #[serde(default)]
442    /// Text color. Native text patches reduce gradient fills to their first
443    /// stop's color; use a solid fill for predictable text color.
444    pub fill: Property<Fill>,
445    #[serde(default)]
446    /// Whether text should be underlined.
447    pub underline: Property<bool>,
448    #[serde(default)]
449    /// Alignment for multiline text layout.
450    pub align_multiline: Property<TextAlignHorizontal>,
451    #[serde(default)]
452    /// Vertical text alignment within its bounds.
453    pub align_vertical: Property<TextAlignVertical>,
454    #[serde(default)]
455    /// Horizontal text alignment within its bounds.
456    pub align_horizontal: Property<TextAlignHorizontal>,
457}
458
459impl Default for TextStyle {
460    fn default() -> Self {
461        Self {
462            font: Property::new(Font::default()),
463            font_size: Property::new(Size::Pixels(Numeric::F64(20.0))),
464            fill: Property::new(Fill::Solid(Color::BLACK)),
465            underline: Property::new(false),
466            align_multiline: Property::new(TextAlignHorizontal::Left),
467            align_vertical: Property::new(TextAlignVertical::Top),
468            align_horizontal: Property::new(TextAlignHorizontal::Left),
469        }
470    }
471}
472
473impl<'a> Into<TextStyleMessage> for &'a TextStyle {
474    fn into(self) -> TextStyleMessage {
475        TextStyleMessage {
476            font: Some(self.font.get().clone().into()),
477            font_size: Some(self.font_size.get().expect_pixels().to_float()),
478            fill: Some(Into::<ColorMessage>::into(&match self.fill.get() {
479                Fill::Solid(color) => color,
480                Fill::LinearGradient(lgrad) => lgrad
481                    .stops
482                    .first()
483                    .map(|f| f.color.clone())
484                    .unwrap_or_default(),
485                Fill::RadialGradient(rgrad) => rgrad
486                    .stops
487                    .first()
488                    .map(|f| f.color.clone())
489                    .unwrap_or_default(),
490            })),
491            underline: Some(self.underline.get().clone()),
492            align_multiline: Some(Into::<TextAlignHorizontalMessage>::into(
493                &self.align_multiline.get(),
494            )),
495            align_vertical: Some(Into::<TextAlignVerticalMessage>::into(
496                &self.align_vertical.get(),
497            )),
498            align_horizontal: Some(Into::<TextAlignHorizontalMessage>::into(
499                &self.align_horizontal.get(),
500            )),
501        }
502    }
503}
504
505impl PartialEq for TextStyle {
506    fn eq(&self, other: &Self) -> bool {
507        let text_style_message: TextStyleMessage = other.into();
508        self == &text_style_message
509    }
510}
511
512impl PartialEq<TextStyleMessage> for TextStyle {
513    fn eq(&self, other: &TextStyleMessage) -> bool {
514        let font_equal = other
515            .font
516            .as_ref()
517            .map_or(false, |font| self.font.get().eq(font));
518
519        let font_size_approx_equal = other.font_size.map_or(false, |size| {
520            (Numeric::F64(size).to_float()
521                - self.font_size.get().expect_pixels().clone().to_float())
522            .abs()
523                < 1e-3
524        });
525
526        let fill_equal = other.fill.as_ref().map_or(false, |fill| {
527            match self.fill.get() {
528                Fill::Solid(color) => color,
529                Fill::LinearGradient(lgrad) => lgrad
530                    .stops
531                    .first()
532                    .map(|f| f.color.clone())
533                    .unwrap_or_default(),
534                Fill::RadialGradient(rgrad) => rgrad
535                    .stops
536                    .first()
537                    .map(|f| f.color.clone())
538                    .unwrap_or_default(),
539            }
540            .eq(fill)
541        });
542
543        let underline_equal = other
544            .underline
545            .map_or(false, |underline| underline == self.underline.get().clone());
546
547        let align_multiline_equal = other
548            .align_multiline
549            .as_ref()
550            .map_or(false, |align_multiline| {
551                self.align_multiline.get().eq(align_multiline)
552            });
553
554        let align_vertical_equal = other
555            .align_vertical
556            .as_ref()
557            .map_or(false, |align_vertical| {
558                self.align_vertical.get().eq(align_vertical)
559            });
560
561        let align_horizontal_equal = other
562            .align_horizontal
563            .as_ref()
564            .map_or(false, |align_horizontal| {
565                self.align_horizontal.get().eq(align_horizontal)
566            });
567
568        font_equal
569            && font_size_approx_equal
570            && fill_equal
571            && underline_equal
572            && align_multiline_equal
573            && align_vertical_equal
574            && align_horizontal_equal
575    }
576}
577
578/// Describes a font available to native text renderers.
579///
580/// Pax templates may use either the explicit [`Font::Web`] constructor or a
581/// contextual shorthand. A string names a locally available family with an
582/// empty source URL and normal style and weight:
583///
584/// ```pax
585/// font: "Times New Roman"
586/// ```
587///
588/// Named object fields describe font sources and optional modifiers. Omitted
589/// fields retain their defaults. Supplying `family` without `url` selects a
590/// locally available family, matching the string shorthand. `weight` accepts
591/// either [`FontWeight`] or its CSS numeric equivalent from `100` through
592/// `900`:
593///
594/// ```pax
595/// font: {
596///     family: "Inter"
597///     url: "https://example.com/Inter-Italic.ttf"
598///     style: FontStyle::Italic
599///     weight: 700
600/// }
601/// ```
602///
603/// Nonempty URLs identify font files, except that Google Fonts URLs containing
604/// `fonts.googleapis.com/css` receive special stylesheet handling. Relative
605/// asset URLs work on web; the native Web-font loader does not resolve them
606/// into application bundle resources. Native targets also require the actual
607/// font family name, rather than a browser-only alias.
608///
609/// Font shorthand has no positional ("magic index") fields: named keys are
610/// canonical, and positional list/tuple forms are not accepted. Use the
611/// explicit [`Font::Web`] constructor as verbose longhand when needed.
612#[pax]
613#[engine_import_path("pax_engine")]
614#[custom(Default, CoercionRules)]
615pub enum Font {
616    /// Font described by family name, source URL, style, and weight.
617    Web(String, String, FontStyle, FontWeight),
618}
619
620impl Default for Font {
621    fn default() -> Self {
622        Self::Web("Roboto".to_string(),
623    "https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap".to_string()
624                  , FontStyle::Normal, FontWeight::Normal)
625    }
626}
627
628/// Describes available font styles.
629#[pax]
630#[engine_import_path("pax_engine")]
631pub enum FontStyle {
632    #[default]
633    Normal,
634    Italic,
635    Oblique,
636}
637
638/// Describes available font weights.
639#[pax]
640#[engine_import_path("pax_engine")]
641#[derive(PartialEq)]
642pub enum FontWeight {
643    Thin,
644    ExtraLight,
645    Light,
646    #[default]
647    Normal,
648    Medium,
649    SemiBold,
650    Bold,
651    ExtraBold,
652    Black,
653}
654
655impl CoercionRules for Font {
656    fn try_coerce(value: PaxValue) -> Result<Self, String> {
657        match value {
658            PaxValue::String(family) => Ok(Self::Web(
659                family,
660                String::new(),
661                FontStyle::Normal,
662                FontWeight::Normal,
663            )),
664            PaxValue::Object(fields) => Self::from_object(fields),
665            PaxValue::Enum(contents) => {
666                let (enum_name, variant_name, values) = *contents;
667                if enum_name != "Font" || variant_name != "Web" {
668                    return Err(format!(
669                        "expected Font::Web, got {enum_name}::{variant_name}"
670                    ));
671                }
672                if values.len() != 4 {
673                    return Err(format!(
674                        "Font::Web expects 4 arguments, got {}",
675                        values.len()
676                    ));
677                }
678
679                let mut values = values.into_iter();
680                Ok(Self::Web(
681                    String::try_coerce(values.next().unwrap())?,
682                    String::try_coerce(values.next().unwrap())?,
683                    Self::coerce_style(values.next().unwrap())?,
684                    Self::coerce_weight(values.next().unwrap())?,
685                ))
686            }
687            PaxValue::Option(value) => match *value {
688                Some(value) => Self::try_coerce(value),
689                None => Err("None can't be coerced into Font".to_string()),
690            },
691            value => Err(format!("{value:?} can't be coerced into Font")),
692        }
693    }
694}
695
696impl Font {
697    fn from_object(fields: Vec<(String, PaxValue)>) -> Result<Self, String> {
698        let mut family = None;
699        let mut url = None;
700        let mut style = None;
701        let mut weight = None;
702
703        for (key, value) in fields {
704            let field = match key.as_str() {
705                "family" => &mut family,
706                "url" => &mut url,
707                "style" => &mut style,
708                "weight" => &mut weight,
709                _ => return Err(format!("unknown Font field `{key}`")),
710            };
711            if field.replace(value).is_some() {
712                return Err(format!("duplicate Font field `{key}`"));
713            }
714        }
715
716        let family_was_supplied = family.is_some();
717        let Self::Web(default_family, default_url, default_style, default_weight) = Self::default();
718        let family = family
719            .map(String::try_coerce)
720            .transpose()?
721            .unwrap_or(default_family);
722        let url = match url {
723            Some(url) => String::try_coerce(url)?,
724            None if family_was_supplied => String::new(),
725            None => default_url,
726        };
727        let style = style
728            .map(Self::coerce_style)
729            .transpose()?
730            .unwrap_or(default_style);
731        let weight = weight
732            .map(Self::coerce_weight)
733            .transpose()?
734            .unwrap_or(default_weight);
735
736        Ok(Self::Web(family, url, style, weight))
737    }
738
739    fn enum_type_name(value: &PaxValue) -> Option<&str> {
740        match value {
741            PaxValue::Enum(contents) => Some(contents.0.as_str()),
742            _ => None,
743        }
744    }
745
746    fn coerce_style(value: PaxValue) -> Result<FontStyle, String> {
747        if Self::enum_type_name(&value) != Some("FontStyle") {
748            return Err("expected FontStyle".to_string());
749        }
750        FontStyle::try_coerce(value)
751    }
752
753    fn coerce_weight(value: PaxValue) -> Result<FontWeight, String> {
754        if let PaxValue::Numeric(value) = value {
755            let value = value.to_float();
756            if !value.is_finite() || value.fract() != 0.0 {
757                return Err("font weight must be a whole CSS weight from 100 to 900".to_string());
758            }
759            return match value as i32 {
760                100 => Ok(FontWeight::Thin),
761                200 => Ok(FontWeight::ExtraLight),
762                300 => Ok(FontWeight::Light),
763                400 => Ok(FontWeight::Normal),
764                500 => Ok(FontWeight::Medium),
765                600 => Ok(FontWeight::SemiBold),
766                700 => Ok(FontWeight::Bold),
767                800 => Ok(FontWeight::ExtraBold),
768                900 => Ok(FontWeight::Black),
769                _ => Err(
770                    "font weight must be one of 100, 200, 300, 400, 500, 600, 700, 800, or 900"
771                        .to_string(),
772                ),
773            };
774        }
775        if Self::enum_type_name(&value) != Some("FontWeight") {
776            return Err("expected FontWeight or a numeric CSS weight".to_string());
777        }
778        FontWeight::try_coerce(value)
779    }
780}
781
782#[cfg(test)]
783mod font_coercion_tests {
784    use super::*;
785
786    fn string(value: &str) -> PaxValue {
787        PaxValue::String(value.to_string())
788    }
789
790    fn enum_value(type_name: &str, variant_name: &str) -> PaxValue {
791        PaxValue::Enum(Box::new((
792            type_name.to_string(),
793            variant_name.to_string(),
794            vec![],
795        )))
796    }
797
798    fn object(fields: Vec<(&str, PaxValue)>) -> PaxValue {
799        PaxValue::Object(
800            fields
801                .into_iter()
802                .map(|(key, value)| (key.to_string(), value))
803                .collect(),
804        )
805    }
806
807    fn numeric(value: i32) -> PaxValue {
808        PaxValue::Numeric(value.into())
809    }
810
811    fn assert_web(
812        font: Font,
813        expected_family: &str,
814        expected_url: &str,
815        expected_style: FontStyle,
816        expected_weight: FontWeight,
817    ) {
818        let Font::Web(family, url, style, weight) = font;
819        assert_eq!(family, expected_family);
820        assert_eq!(url, expected_url);
821        assert!(matches!(
822            (style, expected_style),
823            (FontStyle::Normal, FontStyle::Normal)
824                | (FontStyle::Italic, FontStyle::Italic)
825                | (FontStyle::Oblique, FontStyle::Oblique)
826        ));
827        assert_eq!(weight, expected_weight);
828    }
829
830    #[test]
831    fn string_coerces_to_local_family_defaults() {
832        assert_web(
833            Font::try_coerce(string("Times New Roman")).unwrap(),
834            "Times New Roman",
835            "",
836            FontStyle::Normal,
837            FontWeight::Normal,
838        );
839    }
840
841    #[test]
842    fn object_shorthand_supports_named_fields_and_defaults() {
843        let family = "Inter";
844        let url = "https://example.com/inter.css";
845
846        assert_web(
847            Font::try_coerce(object(vec![
848                ("family", string(family)),
849                ("url", string(url)),
850            ]))
851            .unwrap(),
852            family,
853            url,
854            FontStyle::Normal,
855            FontWeight::Normal,
856        );
857        assert_web(
858            Font::try_coerce(object(vec![
859                ("family", string(family)),
860                ("weight", numeric(700)),
861            ]))
862            .unwrap(),
863            family,
864            "",
865            FontStyle::Normal,
866            FontWeight::Bold,
867        );
868        assert_web(
869            Font::try_coerce(object(vec![
870                ("style", enum_value("FontStyle", "Italic")),
871                ("weight", enum_value("FontWeight", "Medium")),
872            ]))
873            .unwrap(),
874            "Roboto",
875            "https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap",
876            FontStyle::Italic,
877            FontWeight::Medium,
878        );
879    }
880
881    #[test]
882    fn explicit_web_constructor_remains_supported() {
883        let value = PaxValue::Enum(Box::new((
884            "Font".to_string(),
885            "Web".to_string(),
886            vec![
887                string("Inter"),
888                string("https://example.com/inter.css"),
889                enum_value("FontStyle", "Normal"),
890                enum_value("FontWeight", "SemiBold"),
891            ],
892        )));
893
894        assert_web(
895            Font::try_coerce(value).unwrap(),
896            "Inter",
897            "https://example.com/inter.css",
898            FontStyle::Normal,
899            FontWeight::SemiBold,
900        );
901    }
902
903    #[test]
904    fn numeric_css_weights_cover_every_runtime_variant() {
905        let cases = [
906            (100, FontWeight::Thin),
907            (200, FontWeight::ExtraLight),
908            (300, FontWeight::Light),
909            (400, FontWeight::Normal),
910            (500, FontWeight::Medium),
911            (600, FontWeight::SemiBold),
912            (700, FontWeight::Bold),
913            (800, FontWeight::ExtraBold),
914            (900, FontWeight::Black),
915        ];
916
917        for (weight, expected) in cases {
918            assert_web(
919                Font::try_coerce(object(vec![("weight", numeric(weight))])).unwrap(),
920                "Roboto",
921                "https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap",
922                FontStyle::Normal,
923                expected,
924            );
925        }
926    }
927
928    #[test]
929    fn list_shorthand_and_invalid_object_fields_are_rejected() {
930        assert!(Font::try_coerce(PaxValue::Vec(vec![
931            string("Inter"),
932            string("https://example.com/inter.css"),
933        ]))
934        .is_err());
935        assert!(Font::try_coerce(object(vec![("weight", numeric(450))])).is_err());
936        assert!(Font::try_coerce(object(vec![("unknown", string("value"))])).is_err());
937        assert!(Font::try_coerce(object(vec![
938            ("family", string("Inter")),
939            ("family", string("Roboto")),
940        ]))
941        .is_err());
942    }
943}
944
945/// Describes available horizontal text alignments.
946#[pax]
947#[engine_import_path("pax_engine")]
948pub enum TextAlignHorizontal {
949    #[default]
950    Left,
951    Center,
952    Right,
953}
954
955/// Describes available vertical text alignments.
956#[pax]
957#[engine_import_path("pax_engine")]
958pub enum TextAlignVertical {
959    #[default]
960    Top,
961    Center,
962    Bottom,
963}
964
965impl Into<TextAlignHorizontalMessage> for &TextAlignHorizontal {
966    fn into(self) -> TextAlignHorizontalMessage {
967        match self {
968            TextAlignHorizontal::Center => TextAlignHorizontalMessage::Center,
969            TextAlignHorizontal::Left => TextAlignHorizontalMessage::Left,
970            TextAlignHorizontal::Right => TextAlignHorizontalMessage::Right,
971        }
972    }
973}
974
975impl PartialEq<TextAlignHorizontalMessage> for TextAlignHorizontal {
976    fn eq(&self, other: &TextAlignHorizontalMessage) -> bool {
977        match (self, other) {
978            (TextAlignHorizontal::Center, TextAlignHorizontalMessage::Center) => true,
979            (TextAlignHorizontal::Left, TextAlignHorizontalMessage::Left) => true,
980            (TextAlignHorizontal::Right, TextAlignHorizontalMessage::Right) => true,
981            _ => false,
982        }
983    }
984}
985
986// Converts an optional horizontal alignment to its native patch representation.
987pub fn opt_align_to_message(
988    opt_alignment: &Option<TextAlignHorizontal>,
989) -> Option<TextAlignHorizontalMessage> {
990    opt_alignment.as_ref().map(|alignment| match alignment {
991        TextAlignHorizontal::Center => TextAlignHorizontalMessage::Center,
992        TextAlignHorizontal::Left => TextAlignHorizontalMessage::Left,
993        TextAlignHorizontal::Right => TextAlignHorizontalMessage::Right,
994    })
995}
996
997// Compares an optional Pax value against an optional native patch value.
998pub fn opt_value_eq_opt_msg<T, U>(opt_value: &Option<T>, opt_value_msg: &Option<U>) -> bool
999where
1000    T: PartialEq<U>,
1001{
1002    match (opt_value, opt_value_msg) {
1003        (Some(value), Some(value_msg)) => value.eq(value_msg),
1004        (None, None) => true,
1005        _ => false,
1006    }
1007}
1008
1009impl Into<TextAlignVerticalMessage> for &TextAlignVertical {
1010    fn into(self) -> TextAlignVerticalMessage {
1011        match self {
1012            TextAlignVertical::Top => TextAlignVerticalMessage::Top,
1013            TextAlignVertical::Center => TextAlignVerticalMessage::Center,
1014            TextAlignVertical::Bottom => TextAlignVerticalMessage::Bottom,
1015        }
1016    }
1017}
1018
1019impl PartialEq<TextAlignVerticalMessage> for TextAlignVertical {
1020    fn eq(&self, other: &TextAlignVerticalMessage) -> bool {
1021        match (self, other) {
1022            (TextAlignVertical::Top, TextAlignVerticalMessage::Top) => true,
1023            (TextAlignVertical::Center, TextAlignVerticalMessage::Center) => true,
1024            (TextAlignVertical::Bottom, TextAlignVerticalMessage::Bottom) => true,
1025            _ => false,
1026        }
1027    }
1028}
1029
1030impl From<Font> for FontPatch {
1031    fn from(font: Font) -> Self {
1032        match font {
1033            Font::Web(family, url, style, weight) => FontPatch::Web(WebFontMessage {
1034                family: Some(family),
1035                url: Some(url),
1036                style: Some(style.into()),
1037                weight: Some(weight.into()),
1038            }),
1039        }
1040    }
1041}
1042
1043impl PartialEq<FontStyleMessage> for FontStyle {
1044    fn eq(&self, other: &FontStyleMessage) -> bool {
1045        match (self, other) {
1046            (FontStyle::Normal, FontStyleMessage::Normal) => true,
1047            (FontStyle::Italic, FontStyleMessage::Italic) => true,
1048            (FontStyle::Oblique, FontStyleMessage::Oblique) => true,
1049            _ => false,
1050        }
1051    }
1052}
1053
1054impl PartialEq<FontPatch> for Font {
1055    fn eq(&self, other: &FontPatch) -> bool {
1056        match (self, other) {
1057            (Font::Web(family, url, style, weight), FontPatch::Web(web_font_patch)) => {
1058                web_font_patch
1059                    .family
1060                    .as_ref()
1061                    .map_or(false, |f| f == family)
1062                    && web_font_patch.url.as_ref().map_or(false, |u| u == url)
1063                    && web_font_patch.style.as_ref().map_or(false, |s| style.eq(s))
1064                    && web_font_patch
1065                        .weight
1066                        .as_ref()
1067                        .map_or(false, |w| FontWeightMessage::from(weight.clone()).eq(w))
1068            }
1069            _ => false,
1070        }
1071    }
1072}
1073
1074impl From<FontStyleMessage> for FontStyle {
1075    fn from(style_msg: FontStyleMessage) -> Self {
1076        match style_msg {
1077            FontStyleMessage::Normal => FontStyle::Normal,
1078            FontStyleMessage::Italic => FontStyle::Italic,
1079            FontStyleMessage::Oblique => FontStyle::Oblique,
1080        }
1081    }
1082}
1083
1084impl From<FontStyle> for FontStyleMessage {
1085    fn from(style: FontStyle) -> Self {
1086        match style {
1087            FontStyle::Normal => FontStyleMessage::Normal,
1088            FontStyle::Italic => FontStyleMessage::Italic,
1089            FontStyle::Oblique => FontStyleMessage::Oblique,
1090        }
1091    }
1092}
1093
1094impl From<FontWeightMessage> for FontWeight {
1095    fn from(weight_msg: FontWeightMessage) -> Self {
1096        match weight_msg {
1097            FontWeightMessage::Thin => FontWeight::Thin,
1098            FontWeightMessage::ExtraLight => FontWeight::ExtraLight,
1099            FontWeightMessage::Light => FontWeight::Light,
1100            FontWeightMessage::Normal => FontWeight::Normal,
1101            FontWeightMessage::Medium => FontWeight::Medium,
1102            FontWeightMessage::SemiBold => FontWeight::SemiBold,
1103            FontWeightMessage::Bold => FontWeight::Bold,
1104            FontWeightMessage::ExtraBold => FontWeight::ExtraBold,
1105            FontWeightMessage::Black => FontWeight::Black,
1106        }
1107    }
1108}
1109
1110impl From<FontWeight> for FontWeightMessage {
1111    fn from(weight: FontWeight) -> Self {
1112        match weight {
1113            FontWeight::Thin => FontWeightMessage::Thin,
1114            FontWeight::ExtraLight => FontWeightMessage::ExtraLight,
1115            FontWeight::Light => FontWeightMessage::Light,
1116            FontWeight::Normal => FontWeightMessage::Normal,
1117            FontWeight::Medium => FontWeightMessage::Medium,
1118            FontWeight::SemiBold => FontWeightMessage::SemiBold,
1119            FontWeight::Bold => FontWeightMessage::Bold,
1120            FontWeight::ExtraBold => FontWeightMessage::ExtraBold,
1121            FontWeight::Black => FontWeightMessage::Black,
1122        }
1123    }
1124}
1125
1126impl FontWeight {
1127    /// Returns the next heavier named font weight.
1128    pub fn increase(weight: FontWeight) -> FontWeight {
1129        match weight {
1130            FontWeight::Thin => FontWeight::ExtraLight,
1131            FontWeight::ExtraLight => FontWeight::Light,
1132            FontWeight::Light => FontWeight::Normal,
1133            FontWeight::Normal => FontWeight::Medium,
1134            FontWeight::Medium => FontWeight::SemiBold,
1135            FontWeight::SemiBold => FontWeight::Bold,
1136            FontWeight::Bold => FontWeight::ExtraBold,
1137            FontWeight::ExtraBold => FontWeight::Black,
1138            FontWeight::Black => FontWeight::Black,
1139        }
1140    }
1141    /// Returns the next lighter named font weight.
1142    pub fn decrease(weight: FontWeight) -> FontWeight {
1143        match weight {
1144            FontWeight::Thin => FontWeight::Thin,
1145            FontWeight::ExtraLight => FontWeight::Thin,
1146            FontWeight::Light => FontWeight::ExtraLight,
1147            FontWeight::Normal => FontWeight::Light,
1148            FontWeight::Medium => FontWeight::Normal,
1149            FontWeight::SemiBold => FontWeight::Medium,
1150            FontWeight::Bold => FontWeight::SemiBold,
1151            FontWeight::ExtraBold => FontWeight::Bold,
1152            FontWeight::Black => FontWeight::ExtraBold,
1153        }
1154    }
1155}