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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
use std::collections::{BTreeMap, HashMap};
use std::iter;
use std::rc::Rc;
use_RefCell!();
use crate::api::{math::Point2, CommonProperties, RenderContext, SceneAmbientLight, SceneLight};
use pax_manifest::cartridge_generation::ComponentTransitionConfig;
use pax_manifest::{
SettingsBlockElement, TemplateNodeSelectorInfo, TypeId, UniqueTemplateNodeIdentifier,
};
use pax_message::NativeInterrupt;
use pax_runtime_api::pax_value::PaxAny;
use pax_runtime_api::{borrow, use_RefCell, Variable};
use piet::{Color, StrokeStyle};
use crate::api::{Layer, Scroll, Window};
use crate::{
create_new_common_properties, create_new_common_properties_from_columns,
property_columns_from_defined_properties, update_existing_common_properties,
update_existing_common_properties_from_columns, ErasedComponentDescriptor, ExpandedNode,
HandlerRegistry, ReceivedChildrenSource, RuntimeContext, RuntimePropertiesStackFrame,
TemplatePropertyPlan,
};
use pax_manifest::ValueDefinition;
/// Type aliases to make it easier to work with nested Rcs and
/// RefCells for instance nodes.
pub type InstanceNodePtr = Rc<dyn InstanceNode>;
pub type InstanceNodePtrList = RefCell<Vec<InstanceNodePtr>>;
pub type CommonPropertiesFactory = Box<
dyn Fn(
Rc<RuntimePropertiesStackFrame>,
Option<Rc<ExpandedNode>>,
) -> Option<Rc<RefCell<CommonProperties>>>,
>;
pub type PropertiesFactory = Box<
dyn Fn(
Rc<RuntimePropertiesStackFrame>,
Option<Rc<ExpandedNode>>,
) -> Option<Rc<RefCell<PaxAny>>>,
>;
pub type PropertiesScopeFactory = Box<dyn Fn(Rc<RefCell<PaxAny>>) -> HashMap<String, Variable>>;
/// Structured initialization for node-local common properties.
pub enum CommonPropertiesInit {
Default,
Inline {
defined_properties: BTreeMap<String, ValueDefinition>,
},
Template(Rc<TemplatePropertyPlan>),
Factory(CommonPropertiesFactory),
}
impl CommonPropertiesInit {
fn requires_pre_node_binding(&self) -> bool {
match self {
Self::Factory(_) => true,
Self::Inline { defined_properties } => defined_properties
.values()
.any(crate::value_uses_local_property_scope),
Self::Template(plan) => plan.requires_pre_node_binding,
Self::Default => false,
}
}
/// Allocate stable slots without binding structured template expressions.
/// Legacy factories retain their existing pre-node callback contract.
pub(crate) fn allocate(
&self,
stack: Rc<RuntimePropertiesStackFrame>,
) -> Rc<RefCell<CommonProperties>> {
match self {
Self::Factory(factory) => {
factory(stack, None).expect("common properties factory must allocate properties")
}
_ => Rc::new(RefCell::new(CommonProperties::default())),
}
}
pub fn materialize(
&self,
stack_frame: Rc<RuntimePropertiesStackFrame>,
expanded_node: Option<Rc<ExpandedNode>>,
) -> Option<Rc<RefCell<CommonProperties>>> {
match self {
CommonPropertiesInit::Default => expanded_node
.is_none()
.then(|| Rc::new(RefCell::new(CommonProperties::default()))),
CommonPropertiesInit::Inline { defined_properties } => {
if let Some(expanded_node) = expanded_node {
update_existing_common_properties(
&expanded_node,
defined_properties,
&stack_frame,
);
None
} else {
Some(create_new_common_properties(
defined_properties,
&stack_frame,
))
}
}
CommonPropertiesInit::Template(plan) => {
let columns = plan.resolve(expanded_node.as_ref());
if let Some(node) = expanded_node {
update_existing_common_properties_from_columns(&node, &columns, &stack_frame);
None
} else {
Some(create_new_common_properties_from_columns(
&columns,
&stack_frame,
))
}
}
CommonPropertiesInit::Factory(factory) => factory(stack_frame, expanded_node),
}
}
}
/// Structured initialization for node-local typed properties.
pub enum PropertiesInit {
DescriptorDefault(&'static ErasedComponentDescriptor),
DescriptorInline {
descriptor: &'static ErasedComponentDescriptor,
defined_properties: BTreeMap<String, ValueDefinition>,
},
Template {
descriptor: &'static ErasedComponentDescriptor,
plan: Rc<TemplatePropertyPlan>,
},
Factory(PropertiesFactory),
}
impl PropertiesInit {
/// Use an already constructed root while preserving its settings bindings.
/// The allocation is shared directly; no descriptor default or value
/// conversion may replace its property identities or Rust dependencies.
pub fn adopt(self, properties: Rc<RefCell<PaxAny>>) -> Self {
Self::Factory(Box::new(move |stack, node| {
if node.is_none() {
Some(properties.clone())
} else {
self.materialize(stack, node)
}
}))
}
fn requires_pre_node_binding(&self) -> bool {
match self {
Self::Factory(_) => true,
Self::DescriptorInline {
defined_properties, ..
} => defined_properties
.values()
.any(crate::value_uses_local_property_scope),
Self::Template { plan, .. } => plan.requires_pre_node_binding,
Self::DescriptorDefault(_) => false,
}
}
/// Allocate the component's own defaults once before node-local binding.
pub(crate) fn allocate(&self, stack: Rc<RuntimePropertiesStackFrame>) -> Rc<RefCell<PaxAny>> {
match self {
Self::DescriptorDefault(descriptor)
| Self::DescriptorInline { descriptor, .. }
| Self::Template { descriptor, .. } => {
Rc::new(RefCell::new((descriptor.create_properties)()))
}
Self::Factory(factory) => {
factory(stack, None).expect("properties factory must allocate properties")
}
}
}
pub fn materialize(
&self,
stack_frame: Rc<RuntimePropertiesStackFrame>,
expanded_node: Option<Rc<ExpandedNode>>,
) -> Option<Rc<RefCell<PaxAny>>> {
match self {
PropertiesInit::DescriptorDefault(descriptor) => expanded_node
.is_none()
.then(|| Rc::new(RefCell::new((descriptor.create_properties)()))),
PropertiesInit::DescriptorInline {
descriptor,
defined_properties,
} => {
if let Some(expanded_node) = expanded_node {
let outer_ref = expanded_node.properties.borrow();
let rc = Rc::clone(&outer_ref);
let mut inner_ref = (*rc).borrow_mut();
(descriptor.apply_defined_properties)(
descriptor.typed_descriptor,
&mut inner_ref,
&property_columns_from_defined_properties(defined_properties),
&stack_frame,
Some(&expanded_node),
);
None
} else {
let mut properties = (descriptor.create_properties)();
(descriptor.apply_defined_properties)(
descriptor.typed_descriptor,
&mut properties,
&property_columns_from_defined_properties(defined_properties),
&stack_frame,
None,
);
Some(Rc::new(RefCell::new(properties)))
}
}
PropertiesInit::Template { descriptor, plan } => {
let columns = plan.resolve(expanded_node.as_ref());
if let Some(node) = expanded_node {
let properties = Rc::clone(&node.properties.borrow());
(descriptor.apply_defined_properties)(
descriptor.typed_descriptor,
&mut properties.borrow_mut(),
&columns,
&stack_frame,
Some(&node),
);
None
} else {
let mut properties = (descriptor.create_properties)();
(descriptor.apply_defined_properties)(
descriptor.typed_descriptor,
&mut properties,
&columns,
&stack_frame,
None,
);
Some(Rc::new(RefCell::new(properties)))
}
}
PropertiesInit::Factory(factory) => factory(stack_frame, expanded_node),
}
}
}
/// How an expanded node should expose component-local symbols into scope.
pub enum PropertiesScopeInit {
None,
Descriptor(&'static ErasedComponentDescriptor),
Factory(PropertiesScopeFactory),
}
impl PropertiesScopeInit {
pub fn build(&self, properties: Rc<RefCell<PaxAny>>) -> HashMap<String, Variable> {
match self {
PropertiesScopeInit::None => HashMap::new(),
PropertiesScopeInit::Descriptor(descriptor) => {
let props_ref = borrow!(properties.as_ref());
(descriptor.build_property_scope)(descriptor.typed_descriptor, &props_ref)
}
PropertiesScopeInit::Factory(factory) => factory(properties),
}
}
}
/// Construction payload used when compiler-generated code instantiates an `InstanceNode`.
pub struct InstantiationArgs {
pub prototypical_common_properties: CommonPropertiesInit,
pub prototypical_properties: PropertiesInit,
pub handler_registry: Option<Rc<RefCell<HandlerRegistry>>>,
pub children: Option<InstanceNodePtrList>,
pub component_template: Option<InstanceNodePtrList>,
pub component_settings: Option<Vec<SettingsBlockElement>>,
pub template_node_identifier: Option<UniqueTemplateNodeIdentifier>,
pub template_node_type_id: Option<TypeId>,
pub template_node_selector_info: Option<TemplateNodeSelectorInfo>,
pub transition_config: ComponentTransitionConfig,
// Used by RuntimePropertyStackFrame to pull out struct's properties based on their names
pub properties_scope: PropertiesScopeInit,
}
/// Lightweight clone of reusable base-node data for helper constructors.
pub struct ReusableInstanceNodeArgs {
pub handler_registry: Option<Rc<RefCell<HandlerRegistry>>>,
pub children: InstanceNodePtrList,
pub template_node_identifier: Option<UniqueTemplateNodeIdentifier>,
pub template_node_type_id: Option<TypeId>,
pub template_node_selector_info: Option<TemplateNodeSelectorInfo>,
}
impl ReusableInstanceNodeArgs {
/// Capture the reusable portions of a `BaseInstance`.
pub fn new(base: &BaseInstance) -> Self {
ReusableInstanceNodeArgs {
handler_registry: base.handler_registry.clone(),
children: base.instance_children.clone(),
template_node_identifier: base.template_node_identifier.clone(),
template_node_type_id: base.template_node_type_id.clone(),
template_node_selector_info: base.template_node_selector_info.clone(),
}
}
}
#[derive(Clone)]
/// Coarse runtime category for an instance node.
pub enum NodeType {
Component,
Primitive,
}
impl std::fmt::Debug for dyn InstanceNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.resolve_debug(f, None)
}
}
/// Central runtime representation of a properties-computable and renderable node.
/// `InstanceNode`s are conceptually stateless, and rely on [`ExpandedNode`]s for stateful representations.
///
/// An `InstanceNode` sits in between a `pax_compiler::TemplateNodeDefinition`, the
/// compile-time `definition` analogue to this `instance`, and [`ExpandedNode`].
///
/// There is a 1:1 relationship between `pax_compiler::TemplateNodeDefinition`s and `InstanceNode`s.
/// There is a one-to-many relationship between one `InstanceNode` and possibly many variant [`ExpandedNode`]s,
/// due to duplication via `for`.
///
/// `InstanceNode`s are architecturally "type-aware" — they can perform type-specific operations e.g. on the state stored in [`ExpandedNode`], while
/// [`ExpandedNode`]s are "type-blind". The latter store polymorphic data but cannot operate on it without the type-aware assistance of their linked `InstanceNode`.
///
/// (See `RepeatInstance::expand_node` where we visit a singular `InstanceNode` several times, producing multiple [`ExpandedNode`]s.)
pub trait InstanceNode {
/// Resolve a userland subtree filter from ordinary reactive properties. Returning `Some`
/// replaces the subtree's GPU presentation, preserving original native coverage/hit testing.
/// Effect primitives must be `Layer::Canvas`, subscribe their inputs to canvas dirtification,
/// and exclude shader-only properties from `property_requires_occlusion_recompute`.
/// A shader primitive returns `Some` throughout its mounted lifetime; use an identity
/// recipe (or an identity parameter value) to disable filtering.
/// Available with the opt-in `shaders` Cargo feature.
#[cfg(feature = "shaders")]
fn shader_effect(&self, _node: &ExpandedNode) -> Option<pax_runtime_api::ShaderEffect> {
None
}
/// Whether ordinary render hooks are valid inside a detached vector alpha source.
/// Native surfaces and cross-surface containers require separate capture support.
fn supports_alpha_source_render(&self) -> bool {
false
}
///Retrieves the base instance, containing common functionality that all instances share
fn base(&self) -> &BaseInstance;
fn instantiate(args: InstantiationArgs) -> Rc<Self>
where
Self: Sized;
fn resolve_debug(
&self,
f: &mut std::fmt::Formatter,
expanded_node: Option<&ExpandedNode>,
) -> std::fmt::Result;
/// Whether this instance has per-frame update work that cannot be driven entirely through
/// reactive property effects.
fn requires_non_reactive_update(&self, _expanded_node: &ExpandedNode) -> bool {
false
}
/// Whether this primitive can contribute direct or ambient scene lighting.
///
/// Lighting primitives must return `true` even while disabled. The runtime uses
/// this stable capability at mount/replacement to register contributors without
/// polling every scene node during rendering.
fn has_scene_lighting(&self) -> bool {
false
}
/// Returns a resolved light contribution for a primitive with `has_scene_lighting()`.
fn resolve_scene_light(
&self,
_expanded_node: &ExpandedNode,
_context: &RuntimeContext,
) -> Option<SceneLight> {
None
}
/// Returns a resolved ambient contribution for a primitive with `has_scene_lighting()`.
fn resolve_scene_ambient_light(
&self,
_expanded_node: &ExpandedNode,
_context: &RuntimeContext,
) -> Option<SceneAmbientLight> {
None
}
/// Whether this node establishes a lexical boundary for descendant lights.
fn establishes_light_frame(&self) -> bool {
false
}
/// Updates the expanded node, recomputing its properties and possibly updating its children.
fn update(self: Rc<Self>, _expanded_node: &Rc<ExpandedNode>, _context: &Rc<RuntimeContext>) {}
/// Second lifecycle method during each render loop, occurs after
/// properties have been computed, but before rendering
/// Example use-case: perform side-effects to the drawing contexts.
/// This is how `Frame` performs clipping, for example.
/// Occurs in a pre-order traversal of the render tree.
#[allow(unused_variables)]
fn handle_pre_render(
&self,
expanded_node: &ExpandedNode,
context: &Rc<RuntimeContext>,
rcs: &mut dyn RenderContext,
) {
//no-op default implementation
}
/// Prepare primitive-local paint geometry independently of drawing or surface readiness.
///
/// The default is conservatively unbounded. Bounded primitives should return their
/// actual local coverage; the runtime shares its transformed result with replay selection.
/// This must be a side-effect-free read of settled properties. Results are retained
/// until `RuntimeContext::mark_canvas_node_dirty` invalidates the node, so a primitive's
/// reactive drawing dependencies must include every input used here. Surface replay
/// reuses the prepared record without invoking this method again.
fn prepare_canvas_geometry(
&self,
_node: &ExpandedNode,
) -> crate::scene_geometry::CanvasGeometry {
Default::default()
}
/// Third lifecycle method during each render loop, occurs
/// after all descendents have been rendered.
/// Occurs in a post-order traversal of the render tree. Most primitives
/// are expected to draw their contents to the rendering context during this event.
#[allow(unused_variables)]
fn render(
&self,
expanded_node: &ExpandedNode,
context: &Rc<RuntimeContext>,
rcs: &mut dyn RenderContext,
) {
}
/// Fourth and final lifecycle method during each render loop, occurs
/// after all descendents have been rendered AND the current node has been rendered.
/// Useful for clean-up, e.g. this is where `Frame` cleans up the drawing contexts
/// to stop clipping.
/// Occurs in a post-order traversal of the render tree.
#[allow(unused_variables)]
fn handle_post_render(
&self,
expanded_node: &ExpandedNode,
context: &Rc<RuntimeContext>,
rcs: &mut dyn RenderContext,
) {
//no-op default implementation
}
/// Fires during the tick when a node is first attached to the render tree. For example,
/// this event fires by all nodes on the global first tick, and by all nodes in a subtree
/// when a `Conditional` subsequently turns on a subtree (i.e. when the `Conditional`s criterion becomes `true` after being `false` through the end of at least 1 frame.)
/// A use-case: send a message to native renderers that a `Text` element should be rendered and tracked
#[allow(unused_variables)]
fn handle_mount(
self: Rc<Self>,
expanded_node: &Rc<ExpandedNode>,
context: &Rc<RuntimeContext>,
) {
let env = Rc::clone(&expanded_node.stack);
let children = borrow!(self.base().get_instance_children());
let children_with_envs = children.iter().cloned().zip(iter::repeat(env));
let new_children = expanded_node.generate_children(
children_with_envs,
context,
&expanded_node.parent_frame,
true,
);
expanded_node.children.set(new_children);
#[cfg(feature = "shaders")]
if self.shader_effect(expanded_node).is_some() {
crate::bind_shader_effect(expanded_node, context);
}
}
/// Fires during element unmount, when an element is about to be removed from the render tree (e.g. by a `Conditional`)
/// A use-case: send a message to native renderers that a `Text` element should be removed
#[allow(unused_variables)]
fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
// let new_children =
// expanded_node.generate_children(vec![], context, &expanded_node.parent_frame);
// expanded_node.children.set(new_children);
}
/// Invoked by event interrupts to pass scroll information to render node
#[allow(unused_variables)]
fn handle_scroll(&self, args_scroll: Scroll) {
//no-op default implementation
}
fn get_template(&self) -> Option<&InstanceNodePtrList> {
None
}
/// Used by frame to control content clipping
fn clips_content(&self, _expanded_node: &ExpandedNode) -> bool {
false
}
/// Override when a primitive needs a more precise hit region than its layout bounds.
fn ray_cast_test(&self, expanded_node: &ExpandedNode, ray: Point2<Window>) -> bool {
let t_and_b = expanded_node.transform_and_bounds.get();
let inverted_transform = t_and_b.transform.inverse();
let transformed_ray = inverted_transform * ray;
let (width, height) = t_and_b.bounds;
transformed_ray.x > 0.0
&& transformed_ray.y > 0.0
&& transformed_ray.x < width
&& transformed_ray.y < height
}
/// Used by scroller-like primitives to allocate a browser-owned presentation layer.
fn scrolls_content(&self, _expanded_node: &ExpandedNode) -> bool {
false
}
/// Returns whether changes to a named typed property invalidate native compositing.
/// Leaf changes update indexed coverage; changes to clipping or layer ownership
/// reconcile the inherited structure.
///
/// Common geometry, transform, opacity, and child-list dependencies are tracked separately
/// for every node. Override this for typed properties that only affect local content or
/// native patches and cannot change occlusion coverage, clipping, z-order, or layer
/// ownership.
fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
true
}
/// True when an otherwise layout-only primitive currently materializes a native surface.
fn materializes_native_surface(&self, _expanded_node: &ExpandedNode) -> bool {
false
}
/// True when a materialized native surface should be projected before descendants.
///
/// Most renderables are post-order so their own pixels sit above descendants in logical
/// tree order. Native backing surfaces, such as liquid-glass Groups, need the opposite:
/// the chassis should create/project the native surface before descendant content while
/// still including the surface in native occlusion and vector-mask computation.
fn materializes_native_surface_before_children(&self, _expanded_node: &ExpandedNode) -> bool {
false
}
/// Returns the current browser-owned scroll offset in local scroller coordinates.
fn resolve_scroll_offset(&self, _expanded_node: &ExpandedNode) -> Option<(f64, f64)> {
None
}
/// Selects which engine child family should be normalized into
/// `received_children` for semantic container-style consumers.
///
/// This hook is about provenance, not semantics:
/// - `Owned` means the node's active child tree is already its received
/// payload
/// - `Projected` means the node receives payload from its caller and the
/// runtime delivers that payload through projection so `slot(...)` can
/// consume it
///
/// The default remains heuristic for now: components normalize projected
/// children, while other nodes normalize owned children.
fn received_children_source(&self) -> ReceivedChildrenSource {
if self.base().flags().is_component {
ReceivedChildrenSource::Projected
} else {
ReceivedChildrenSource::Owned
}
}
fn handle_native_interrupt(
&self,
_expanded_node: &Rc<ExpandedNode>,
_interrupt: &NativeInterrupt,
) {
// no-op for many
}
fn handle_control_flow_node_expansion(
self: Rc<Self>,
_expanded_node: &Rc<ExpandedNode>,
_context: &Rc<RuntimeContext>,
) {
}
fn handle_setup_projected_children(
self: Rc<Self>,
_expanded_node: &Rc<ExpandedNode>,
_context: &Rc<RuntimeContext>,
) {
}
fn resolve_coverage_path(&self, _expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
None
}
/// Resolves vector paint for an alpha-mask source without rendering or
/// mutating the source's retained canvas state.
/// Paint-local coverage without common node/ancestor opacity. The Mask consumer
/// applies the source subtree's opacity factors relative to its own boundary.
fn resolve_alpha_mask_paints(
&self,
_expanded_node: &ExpandedNode,
) -> Vec<pax_runtime_api::AlphaMaskPaint> {
Vec::new()
}
/// Returns coverage used by the occlusion/native-mask/layer-partition pass.
///
/// The default uses the same coverage path as masks and hit-style geometry, but primitives
/// with render-side animation may return a conservative stable path here so animation-only
/// properties do not force the occlusion pass to rebuild expensive geometry every frame.
fn resolve_occlusion_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
self.resolve_coverage_path(expanded_node)
}
fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
expanded_node.computed_opacity.get()
}
fn resolve_effect_clip_path(&self, _expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
None
}
}
/// Shared storage carried by every concrete `InstanceNode`.
pub struct BaseInstance {
pub handler_registry: Option<Rc<RefCell<HandlerRegistry>>>,
pub instance_prototypical_properties: PropertiesInit,
pub instance_prototypical_common_properties: CommonPropertiesInit,
pub component_settings: Option<Vec<SettingsBlockElement>>,
pub template_node_identifier: Option<UniqueTemplateNodeIdentifier>,
pub template_node_type_id: Option<TypeId>,
pub template_node_selector_info: Option<TemplateNodeSelectorInfo>,
pub transition_config: ComponentTransitionConfig,
pub properties_scope: PropertiesScopeInit,
instance_children: InstanceNodePtrList,
flags: InstanceFlags,
}
#[derive(Clone)]
/// Static traversal/rendering flags for a concrete instance node.
pub struct InstanceFlags {
/// Used for exotic tree traversals for `Slot`, e.g. for `Stacker` > `Repeat` > `Rectangle`
/// where the repeated `Rectangle`s need to be be considered direct children of `Stacker`.
/// `Repeat` and `Conditional` set this true so their active children can be
/// considered direct projected children by slot-driven containers.
pub invisible_to_slot: bool,
/// Certain elements, such as Groups and Components, are invisible to ray-casting.
/// Since these container elements are on top of the elements they contain,
/// this is needed otherwise the containers would intercept rays that should hit their contents.
pub invisible_to_raycasting: bool,
/// The layer type (`Layer::Native`, `Layer::NativeNonOccluding`, or `Layer::Canvas`)
/// for this RenderNode.
/// Default is `Layer::Canvas`, and must be overwritten for `InstanceNode`s that manage native
/// content.
pub layer: Layer,
/// Only true for ComponentInstance
pub is_component: bool,
/// Is this node a `Slot`?
pub is_slot: bool,
}
impl BaseInstance {
pub(crate) fn requires_pre_node_binding(&self) -> bool {
self.instance_prototypical_common_properties
.requires_pre_node_binding()
|| self
.instance_prototypical_properties
.requires_pre_node_binding()
|| matches!(self.properties_scope, PropertiesScopeInit::Factory(_))
}
/// Bind after stable slots and selector identity exist, before publishing
/// the final scope and activating listeners/lifecycle handlers.
/// Paired template initializers share one fresh resolution per bind, including
/// removal resets on reload. Custom factories keep their ordered callbacks.
pub(crate) fn bind_properties(&self, node: &Rc<ExpandedNode>) {
if let (
CommonPropertiesInit::Template(common_plan),
PropertiesInit::Template { descriptor, plan },
) = (
&self.instance_prototypical_common_properties,
&self.instance_prototypical_properties,
) {
if Rc::ptr_eq(common_plan, plan) {
let columns = plan.resolve(Some(node));
update_existing_common_properties_from_columns(node, &columns, &node.stack);
let properties = Rc::clone(&node.properties.borrow());
(descriptor.apply_defined_properties)(
descriptor.typed_descriptor,
&mut properties.borrow_mut(),
&columns,
&node.stack,
Some(node),
);
return;
}
}
self.instance_prototypical_common_properties
.materialize(Rc::clone(&node.stack), Some(Rc::clone(node)));
self.instance_prototypical_properties
.materialize(Rc::clone(&node.stack), Some(Rc::clone(node)));
}
/// Build shared instance state from compiler-generated instantiation args.
pub fn new(args: InstantiationArgs, flags: InstanceFlags) -> Self {
BaseInstance {
handler_registry: args.handler_registry,
instance_prototypical_common_properties: args.prototypical_common_properties,
instance_prototypical_properties: args.prototypical_properties,
component_settings: args.component_settings,
instance_children: args.children.unwrap_or_default(),
flags,
template_node_identifier: args.template_node_identifier,
template_node_type_id: args.template_node_type_id,
template_node_selector_info: args.template_node_selector_info,
transition_config: args.transition_config,
properties_scope: args.properties_scope,
}
}
/// Returns a handle to a node-managed HandlerRegistry, a mapping between event types and handlers.
/// Each node that can handle events is responsible for implementing this; Component instances generate
/// the necessary code to wire up userland events like `<SomeNode @click=self.handler>`. Primitives must handle
/// this explicitly, see e.g. `[pax_std::drawing::rectangle::RectangleInstance#get_handler_registry]`.
pub fn get_handler_registry(&self) -> Option<Rc<RefCell<HandlerRegistry>>> {
match &self.handler_registry {
Some(registry) => Some(Rc::clone(registry)),
_ => None,
}
}
/// Return the list of instance nodes that are children of this one. Intuitively, this returns
/// the nodes owned directly by this instance's definition.
///
/// For `Component`s, this returns the root(s) of the component template, not the
/// projected children supplied by the containing component.
pub fn get_instance_children(&self) -> &InstanceNodePtrList {
&self.instance_children
}
/// Static behavior flags for this instance.
pub fn flags(&self) -> &InstanceFlags {
&self.flags
}
pub fn transition_config(&self) -> &ComponentTransitionConfig {
&self.transition_config
}
}
/// Resolved stroke style used by canvas drawing primitives.
pub struct StrokeInstance {
pub color: Color,
pub width: f64,
pub style: StrokeStyle,
}