pax-runtime-api 0.39.1

Userland constructs used at the runtime API boundary of Pax Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Layout units, axes, and common properties shared by renderable nodes.

use super::*;

/// A spatial size value that can be either a concrete pixel value like `25px`, a percent of parent bounds like `50%`,
/// or an additive/subtractive combination of the two like `(100% - 10px)`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Hash)]
#[serde(crate = "crate::serde")]
pub enum Size {
    /// Concrete pixel length, such as `25px`.
    Pixels(Numeric),
    /// Percent length relative to the relevant parent bound, such as `50%`.
    Percent(Numeric),
    /// Additive pixel and percent components, such as `100% - 10px`.
    Combined(Numeric, Numeric),
}

impl Display for Size {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Size::Pixels(val) => write!(f, "{}px", val),
            Size::Percent(val) => write!(f, "{}%", val),
            Size::Combined(pix, per) => write!(f, "{}px + {}%", pix, per),
        }
    }
}

impl Neg for Size {
    type Output = Size;
    fn neg(self) -> Self::Output {
        match self {
            Size::Pixels(pix) => Size::Pixels(-pix),
            Size::Percent(per) => Size::Percent(-per),
            Size::Combined(pix, per) => Size::Combined(-pix, -per),
        }
    }
}

impl Add for Size {
    type Output = Size;
    fn add(self, rhs: Self) -> Self::Output {
        let mut pixel_component: Numeric = Default::default();
        let mut percent_component: Numeric = Default::default();

        [self, rhs].iter().for_each(|size| match size {
            Size::Pixels(s) => pixel_component = pixel_component + *s,
            Size::Percent(s) => percent_component = percent_component + *s,
            Size::Combined(s0, s1) => {
                pixel_component = pixel_component + *s0;
                percent_component = percent_component + *s1;
            }
        });

        Size::Combined(pixel_component, percent_component)
    }
}

impl Add<Percent> for Size {
    type Output = Size;
    fn add(self, rhs: Percent) -> Self::Output {
        self + Size::Percent(rhs.0)
    }
}

impl Sub<Percent> for Size {
    type Output = Size;
    fn sub(self, rhs: Percent) -> Self::Output {
        self - Size::Percent(rhs.0)
    }
}

impl Add<Size> for Percent {
    type Output = Size;
    fn add(self, rhs: Size) -> Self::Output {
        Size::Percent(self.0) + rhs
    }
}

impl Sub<Size> for Percent {
    type Output = Size;
    fn sub(self, rhs: Size) -> Self::Output {
        Size::Percent(self.0) - rhs
    }
}

impl Sub for Size {
    type Output = Size;
    fn sub(self, rhs: Self) -> Self::Output {
        let mut pixel_component: Numeric = Default::default();
        let mut percent_component: Numeric = Default::default();

        let sizes = [(self, 1), (rhs, -1)];
        for (size, multiplier) in sizes.iter() {
            match size {
                Size::Pixels(s) => {
                    pixel_component = pixel_component + *s * Numeric::from(*multiplier)
                }
                Size::Percent(s) => {
                    percent_component = percent_component + *s * Numeric::from(*multiplier)
                }
                Size::Combined(s0, s1) => {
                    pixel_component = pixel_component + *s0 * Numeric::from(*multiplier);
                    percent_component = percent_component + *s1 * Numeric::from(*multiplier);
                }
            }
        }

        Size::Combined(pixel_component, percent_component)
    }
}

impl Size {
    #[allow(non_snake_case)]
    /// Returns a zero-pixel size.
    pub fn ZERO() -> Self {
        Size::Pixels(Numeric::F64(0.0))
    }

    /// Returns the wrapped percent value normalized as a float, such that 100% => 1.0.
    /// Panics if wrapped type is not a percentage.
    pub fn expect_percent(&self) -> f64 {
        match &self {
            Size::Percent(val) => val.to_float() / 100.0,
            Size::Pixels(val) => {
                log::warn!("Percentage value expected but stored value was pixel.");
                val.to_float() / 100.0
            }
            Size::Combined(_, percent) => {
                log::warn!("Percentage value expected but stored value was a combination.");
                percent.to_float() / 100.0
            }
        }
    }

    /// Returns the pixel value
    /// Panics if wrapped type is not pixels.
    pub fn expect_pixels(&self) -> Numeric {
        match &self {
            Size::Pixels(val) => val.clone(),
            Size::Percent(val) => {
                log::warn!("Pixel value expected but stored value was percentage.");
                val.clone()
            }
            Size::Combined(pixels, _) => {
                log::warn!("Pixel value expected but stored value was a combination.");
                pixels.clone()
            }
        }
    }
}

/// Model of 2D cartesian axes, used to disambiguate calculations that depend on axis direction (e.g. width vs height)
#[derive(Clone, Copy)]
pub enum Axis {
    /// Horizontal axis.
    X,
    /// Vertical axis.
    Y,
}

/// Controls whether a node participates in parent layout measurement.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
#[serde(crate = "crate::serde")]
pub enum LayoutRole {
    /// Normal layout behavior. The node contributes to parent hulls, autosize, and flow.
    #[default]
    Default,
    /// Parent-local positioning that does not contribute to parent hulls, autosize, or flow.
    ///
    /// `Breakout` remains in the normal render, hit-test, scroll, and clipping trees; it does
    /// not portal above ancestor frames, masks, or scrollers.
    Breakout,
}

impl Interpolatable for LayoutRole {}
impl HelperFunctions for LayoutRole {}

impl Size {
    /// Evaluate a Size in the context of `bounds` and a target `axis`.
    /// Returns a `Pixel` value as a simple f64; calculates `Percent` with respect to `bounds` & `axis`
    pub fn evaluate(&self, bounds: (f64, f64), axis: Axis) -> f64 {
        let target_bound = match axis {
            Axis::X => bounds.0,
            Axis::Y => bounds.1,
        };
        match &self {
            Size::Pixels(num) => num.to_float(),
            Size::Percent(num) => target_bound * (num.to_float() / 100.0),
            Size::Combined(pixel_component, percent_component) => {
                //first calc percent, then add pixel
                (target_bound * (percent_component.to_float() / 100.0)) + pixel_component.to_float()
            }
        }
    }
}

// Compiler-facing metadata for one common property.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CommonProperty {
    // Compiler-facing property name.
    name: String,
    // Compiler-facing type spelling.
    property_type: String,
    // Whether the property may be omitted without falling back to a concrete runtime value.
    optional: bool,
}

/// Properties shared by every renderable Pax node.
///
/// Each property here is special-cased by the compiler when parsing element properties,
/// for example `<SomeElement width={...} />`.
#[derive(Debug, Default, Clone)]
pub struct CommonProperties {
    /// Optional stable node identifier.
    pub id: LocalProperty<Option<String>>,
    /// Horizontal position.
    pub x: LocalProperty<Option<Size>>,
    /// Vertical position.
    pub y: LocalProperty<Option<Size>>,
    /// Symmetric inner spacing applied to this node's child layout area on the x axis.
    pub padding_x: LocalProperty<Option<Size>>,
    /// Symmetric inner spacing applied to this node's child layout area on the y axis.
    pub padding_y: LocalProperty<Option<Size>>,
    /// Horizontal extent.
    pub width: LocalProperty<Option<Size>>,
    /// Vertical extent.
    pub height: LocalProperty<Option<Size>>,
    /// Horizontal transform origin, relative to the node's own bounds.
    pub anchor_x: LocalProperty<Option<Size>>,
    /// Vertical transform origin, relative to the node's own bounds.
    pub anchor_y: LocalProperty<Option<Size>>,
    /// Horizontal scale coefficient.
    // TODO: change scale to Percent (can't be px).
    pub scale_x: LocalProperty<Option<Size>>,
    /// Vertical scale coefficient.
    pub scale_y: LocalProperty<Option<Size>>,
    /// Horizontal skew.
    pub skew_x: LocalProperty<Option<Rotation>>,
    /// Vertical skew.
    pub skew_y: LocalProperty<Option<Rotation>>,
    /// Rotation around the z axis.
    pub rotate: LocalProperty<Option<Rotation>>,
    /// Full composed transform.
    pub transform: LocalProperty<Option<Transform2D>>,
    /// Opacity of this node's subtree. WGPU and browser Piet compose each canvas
    /// portion before fading it; live native surfaces currently fade separately.
    pub opacity: LocalProperty<Option<Opacity>>,
    /// Controls whether this node participates in parent layout measurement and flow.
    pub layout_role: LocalProperty<Option<LayoutRole>>,
    /// Allows a node to render outside an ancestor clipping frame.
    pub unclippable: LocalProperty<Option<bool>>,
    // Internal hit-testing override, used by generated components and tooling.
    pub _raycastable: LocalProperty<Option<bool>>,
    // Internal suspension flag used by runtime/designtime systems.
    pub _suspended: LocalProperty<Option<bool>>,
}

impl CommonProperties {
    // Returns default Rust expressions for compiler-generated common-property initialization.
    pub fn get_default_properties_literal() -> Vec<(String, String)> {
        Self::get_property_identifiers()
            .iter()
            .map(|id| {
                if id.0 == "transform" {
                    (
                        id.0.to_string(),
                        "Transform2D::default_wrapped()".to_string(),
                    )
                } else {
                    (id.0.to_string(), "Default::default()".to_string())
                }
            })
            .collect()
    }

    // Returns common-property names paired with compiler-facing type spellings.
    pub fn get_property_identifiers() -> Vec<(String, String)> {
        COMMON_PROPERTIES_TYPE
            .iter()
            .map(|(c, t)| (c.to_string(), t.to_string()))
            .collect()
    }

    // Returns common-property metadata in a form consumed by compiler codegen.
    pub fn get_as_common_property() -> Vec<CommonProperty> {
        Self::get_property_identifiers()
            .iter()
            .map(|id| CommonProperty {
                name: id.0.to_string(),
                property_type: id.1.to_string(),
                optional: (id.0 == "transform" || id.0 == "width" || id.0 == "height"),
            })
            .collect()
    }

    // Exposes common properties as PAXEL variables for generated scopes.
    pub fn retrieve_property_scope(&self) -> HashMap<String, Variable> {
        let CommonProperties {
            id,
            x,
            y,
            padding_x,
            padding_y,
            width,
            height,
            anchor_x,
            anchor_y,
            scale_x,
            scale_y,
            skew_x,
            skew_y,
            rotate,
            transform,
            opacity,
            layout_role,
            unclippable,
            _raycastable,
            _suspended,
            // NOTE: remember to add an entry to the hashmap bellow as well
        } = self;

        HashMap::from([
            (
                "id".to_string(),
                Variable::new_from_typed_property(id.clone()),
            ),
            (
                "x".to_string(),
                Variable::new_from_typed_property(x.clone()),
            ),
            (
                "y".to_string(),
                Variable::new_from_typed_property(y.clone()),
            ),
            (
                "padding_x".to_string(),
                Variable::new_from_typed_property(padding_x.clone()),
            ),
            (
                "padding_y".to_string(),
                Variable::new_from_typed_property(padding_y.clone()),
            ),
            (
                "scale_x".to_string(),
                Variable::new_from_typed_property(scale_x.clone()),
            ),
            (
                "scale_y".to_string(),
                Variable::new_from_typed_property(scale_y.clone()),
            ),
            (
                "skew_x".to_string(),
                Variable::new_from_typed_property(skew_x.clone()),
            ),
            (
                "skew_y".to_string(),
                Variable::new_from_typed_property(skew_y.clone()),
            ),
            (
                "rotate".to_string(),
                Variable::new_from_typed_property(rotate.clone()),
            ),
            (
                "anchor_x".to_string(),
                Variable::new_from_typed_property(anchor_x.clone()),
            ),
            (
                "anchor_y".to_string(),
                Variable::new_from_typed_property(anchor_y.clone()),
            ),
            (
                "transform".to_string(),
                Variable::new_from_typed_property(transform.clone()),
            ),
            (
                "opacity".to_string(),
                Variable::new_from_typed_property(opacity.clone()),
            ),
            (
                "layout_role".to_string(),
                Variable::new_from_typed_property(layout_role.clone()),
            ),
            (
                "width".to_string(),
                Variable::new_from_typed_property(width.clone()),
            ),
            (
                "height".to_string(),
                Variable::new_from_typed_property(height.clone()),
            ),
            (
                "unclippable".to_string(),
                Variable::new_from_typed_property(unclippable.clone()),
            ),
            (
                "_raycastable".to_string(),
                Variable::new_from_typed_property(_raycastable.clone()),
            ),
            (
                "_suspended".to_string(),
                Variable::new_from_typed_property(_suspended.clone()),
            ),
        ])
    }
}

impl Into<Rotation> for Size {
    fn into(self) -> Rotation {
        if let Size::Percent(pix) = self {
            Rotation::Percent(pix)
        } else {
            panic!("Tried to coerce a pixel value into a rotation value; try `%` or `rad` instead of `px`.")
        }
    }
}

impl Size {
    /// Resolves this size against a parent extent in pixels.
    pub fn get_pixels(&self, parent: f64) -> f64 {
        match &self {
            Self::Pixels(p) => p.to_float(),
            Self::Percent(p) => parent * (p.to_float() / 100.0),
            Self::Combined(pix, per) => (parent * (per.to_float() / 100.0)) + pix.to_float(),
        }
    }
}

impl Interpolatable for Size {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        fn components(size: &Size) -> (Numeric, Numeric) {
            match size {
                Size::Pixels(pixels) => (*pixels, Numeric::F64(0.0)),
                Size::Percent(percent) => (Numeric::F64(0.0), *percent),
                Size::Combined(pixels, percent) => (*pixels, *percent),
            }
        }

        fn from_components(pixels: Numeric, percent: Numeric) -> Size {
            let has_pixels = pixels.to_float().abs() > f64::EPSILON;
            let has_percent = percent.to_float().abs() > f64::EPSILON;
            match (has_pixels, has_percent) {
                (true, true) => Size::Combined(pixels, percent),
                (true, false) => Size::Pixels(pixels),
                (false, true) => Size::Percent(percent),
                (false, false) => Size::Pixels(Numeric::F64(0.0)),
            }
        }

        let (self_pixels, self_percent) = components(self);
        let (other_pixels, other_percent) = components(other);
        let t = Numeric::F64(t);

        from_components(
            self_pixels + ((other_pixels - self_pixels) * t),
            self_percent + ((other_percent - self_percent) * t),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn size_interpolation_blends_pixel_and_percent_components() {
        let start = Size::Pixels(0.into());
        let end = Size::Percent(100.into());
        let midpoint = start.interpolate(&end, 0.5);

        assert!((midpoint.get_pixels(200.0) - 100.0).abs() < 0.0001);
    }

    #[test]
    fn size_interpolation_can_settle_from_percent_offset_to_pixel_base() {
        let start = Size::Combined(0.into(), 100.into());
        let end = Size::Pixels(0.into());

        assert!((start.interpolate(&end, 0.5).get_pixels(200.0) - 100.0).abs() < 0.0001);
        assert!(start.interpolate(&end, 1.0).get_pixels(200.0).abs() < 0.0001);
    }
}

impl Default for Size {
    fn default() -> Self {
        Self::Percent(Numeric::F64(100.0))
    }
}

impl Mul for Size {
    type Output = Size;

    fn mul(self, rhs: Self) -> Self::Output {
        match self {
            Size::Pixels(pix0) => {
                match rhs {
                    //multiplying two pixel values adds them,
                    //in the sense of multiplying two affine translations.
                    //this might be wildly unexpected in some cases, so keep an eye on this and
                    //revisit whether to support Percent values in anchor calcs (could rescind)
                    Size::Pixels(pix1) => Size::Pixels(pix0 + pix1),
                    Size::Percent(per1) => Size::Pixels(pix0 * per1),
                    Size::Combined(pix1, per1) => Size::Pixels((pix0 * per1) + pix0 + pix1),
                }
            }
            Size::Percent(per0) => match rhs {
                Size::Pixels(pix1) => Size::Pixels(per0 * pix1),
                Size::Percent(per1) => Size::Percent(per0 * per1),
                Size::Combined(pix1, per1) => Size::Pixels((per0 * pix1) + (per0 * per1)),
            },
            Size::Combined(pix0, per0) => match rhs {
                Size::Pixels(pix1) => Size::Pixels((pix0 * per0) + pix1),
                Size::Percent(per1) => Size::Percent(pix0 * per0 * per1),
                Size::Combined(pix1, per1) => Size::Pixels((pix0 * per0) + (pix1 * per1)),
            },
        }
    }
}