Skip to main content

pax_std/core/
text.rs

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