Skip to main content

gpui_rhai/
engine.rs

1use std::cell::{Cell, RefCell};
2use std::collections::{BTreeMap, BTreeSet, VecDeque};
3use std::fmt;
4use std::rc::Rc;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::{Duration, Instant};
8
9use rhai::{
10    AST, ASTNode, Array, Dynamic, Engine, EvalAltResult, Expr, FnPtr, FuncArgs, FuncRegistration,
11    ImmutableString, Map, Module, ModuleResolver, Position, Scope, Stmt,
12};
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15
16use crate::asset::{AssetId, ImageDecodeHandle, asset_id_from_script};
17use crate::backend::{AstInterpreter, ExecutionBackend};
18use crate::canvas::register_canvas_api;
19use crate::column_resize::{
20    ColumnMeasurementRegistry, ColumnResizePrimitiveHandler, IntrinsicTextMeasurePrimitiveHandler,
21    column_resize_primitive_descriptor, intrinsic_text_measure_primitive_descriptor,
22};
23use crate::component::{ComponentExportCollector, ComponentExportError, ComponentRegistry};
24use crate::context::{UiContext, register_ui_context_api};
25use crate::date::register_date_api;
26use crate::drag_drop::{
27    DragSourcePrimitiveHandler, DropZonePrimitiveHandler, drag_source_primitive_descriptor,
28    drop_zone_primitive_descriptor,
29};
30use crate::draggable::{DraggablePrimitiveHandler, draggable_primitive_descriptor};
31use crate::motion::register_motion_api;
32use crate::node::{
33    asset_image_node, box_node, canvas_node, column_node, directional_asset_image_node,
34    directional_image_node, error_boundary_node, fragment_node, generic_directional_image_node,
35    generic_image_node, image_node, layer_node, lazy_error_boundary_node, motion_group_node,
36    overlay_node, rich_text_node, row_node, span_value, stack_node, svg_node, text_node,
37};
38use crate::pan_zoom::{PanZoomPrimitiveHandler, pan_zoom_primitive_descriptor};
39use crate::primitive::{PrimitiveDescriptor, PrimitiveError, PrimitiveHandler, PrimitiveRegistry};
40use crate::range_input::{RangeInputPrimitiveHandler, range_input_primitive_descriptor};
41use crate::range_slider::{RangeSliderPrimitiveHandler, range_slider_primitive_descriptor};
42use crate::resizable::{ResizablePrimitiveHandler, resizable_primitive_descriptor};
43use crate::rotatable::{RotatablePrimitiveHandler, rotatable_primitive_descriptor};
44use crate::selection_area::{SelectionAreaPrimitiveHandler, selection_area_primitive_descriptor};
45use crate::sortable::{SortablePrimitiveHandler, sortable_primitive_descriptor};
46use crate::split_resize::{SplitResizePrimitiveHandler, split_resize_primitive_descriptor};
47use crate::style::register_style_api;
48use crate::text_area::{
49    TextAreaPrimitiveHandler, register_text_area_api, text_area_primitive_descriptor,
50};
51use crate::text_input::{TextInputPrimitiveHandler, text_input_primitive_descriptor};
52use crate::value::OpaqueHandle;
53use crate::{
54    ComponentInstancePath, ComponentStateSchema, EventSchema, ExecutionPhase, ModuleId,
55    RenderStateTransaction, UiNode, UiRuntimeState, UiValue,
56};
57use crate::{SubscriptionHandle, TaskHandle};
58
59#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
60pub struct ScriptGeneration(u64);
61
62impl ScriptGeneration {
63    #[must_use]
64    pub const fn get(self) -> u64 {
65        self.0
66    }
67
68    #[cfg(test)]
69    #[must_use]
70    pub(crate) fn initial() -> Self {
71        Self(1)
72    }
73
74    #[cfg(test)]
75    #[must_use]
76    pub(crate) fn next(self) -> Self {
77        Self(self.0.saturating_add(1))
78    }
79}
80
81impl fmt::Display for ScriptGeneration {
82    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
83        self.0.fmt(formatter)
84    }
85}
86
87#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum ExecutionOperation {
90    Compile,
91    Render,
92    /// A formal-component subtree returned without executing its Rhai render.
93    /// The payload is the number of retained formal component instances in the
94    /// reused subtree, including its root.
95    ComponentReuse(usize),
96    VirtualCollection(String),
97    Lifecycle(String),
98    Callback(String),
99}
100
101#[derive(Clone, Debug, Eq, PartialEq)]
102pub struct ExecutionTiming {
103    pub operation: ExecutionOperation,
104    pub source: String,
105    pub duration: Duration,
106    pub operations: u64,
107    /// The effective Host quota captured at the start of this execution.
108    pub operation_limit: u64,
109    /// Cumulative consumption of the enclosing execution round. `operations`
110    /// remains this timing span's delta for performance attribution.
111    pub round_operations: u64,
112    pub operation_semantics: u32,
113    pub slow: bool,
114    pub succeeded: bool,
115}
116
117pub const OPERATION_SEMANTICS_VERSION: u32 = 2;
118
119#[derive(Debug, Error)]
120pub enum RuntimeError {
121    #[error("failed to compile Rhai UI source: {0}")]
122    Compile(#[source] Box<EvalAltResult>),
123    #[error("failed to evaluate Rhai UI source: {0}")]
124    Evaluate(#[source] Box<EvalAltResult>),
125    #[error("callback `{name}` is invalid: {source}")]
126    CallbackDefinition {
127        name: String,
128        #[source]
129        source: Box<EvalAltResult>,
130    },
131    #[error("callback `{name}` cannot be retained: {source}")]
132    RetainedCallback {
133        name: String,
134        source: ScriptCallbackDefinitionError,
135    },
136    #[error(
137        "callback `{name}` belongs to script generation {callback_generation}, but current generation is {current_generation}"
138    )]
139    StaleCallback {
140        name: String,
141        callback_generation: ScriptGeneration,
142        current_generation: ScriptGeneration,
143    },
144    #[error("callback `{name}` belongs to an unmounted incarnation of component `{component}`")]
145    StaleComponentCallback {
146        name: String,
147        component: ComponentInstancePath,
148    },
149    #[error("component runtime failed: {0}")]
150    ComponentRuntime(String),
151    #[error("component invocation `{0}` is not retained in the active generation")]
152    MissingComponentInvocation(ComponentInstancePath),
153    #[error("invalid script import: {0}")]
154    Import(String),
155    #[error(
156        "compiled Rhai source contains an assignment target that Rhai 1.26 cannot evaluate safely at {0}"
157    )]
158    InvalidAssignmentTarget(Position),
159}
160
161#[derive(Debug, Error)]
162pub enum ScriptCallbackDefinitionError {
163    #[error("anonymous or capturing functions cannot escape one synchronous Rhai evaluation")]
164    Anonymous,
165    #[error("curried argument {index} cannot cross the retained callback boundary: {source}")]
166    InvalidCurry {
167        index: usize,
168        source: crate::UiValueError,
169    },
170}
171
172/// Private provenance carried inside a callback prop while a formal component
173/// renders. Rhai clones curried values when a callback is forwarded, so this
174/// survives arbitrary component depth without adding a public constructor or
175/// type. Components treat callback props as opaque; the marker is stripped
176/// before the callback crosses the retained boundary.
177#[derive(Clone, Debug)]
178struct ComponentCallbackBinding {
179    component: ComponentInstancePath,
180    incarnation: crate::ComponentIncarnation,
181    events: BTreeMap<String, EventSchema>,
182    context: Option<crate::invocation::ScriptInvocationContext>,
183    is_node_factory: bool,
184}
185
186#[derive(Clone)]
187pub struct CompiledUi {
188    ast: AST,
189    generation: ScriptGeneration,
190}
191
192#[derive(Clone, Debug)]
193pub struct ScriptCallback {
194    function: FnPtr,
195    curry: Vec<UiValue>,
196    generation: ScriptGeneration,
197    component: Option<ComponentInstancePath>,
198    incarnation: Option<crate::ComponentIncarnation>,
199    events: BTreeMap<String, EventSchema>,
200    #[allow(deprecated)]
201    native_context: Option<crate::invocation::ScriptInvocationContext>,
202    is_node_factory: bool,
203}
204
205impl PartialEq for ScriptCallback {
206    fn eq(&self, other: &Self) -> bool {
207        self.name() == other.name()
208            && self.curry == other.curry
209            && self.generation == other.generation
210            && self.component == other.component
211            && self.incarnation == other.incarnation
212            && self.is_node_factory == other.is_node_factory
213            && (match (&self.native_context, &other.native_context) {
214                (Some(left), Some(right)) => left.same_environment(right),
215                (None, None) => true,
216                _ => false,
217            })
218    }
219}
220
221impl Eq for ScriptCallback {}
222
223impl ScriptCallback {
224    #[must_use]
225    pub fn name(&self) -> &str {
226        self.function.fn_name()
227    }
228
229    #[must_use]
230    pub fn generation(&self) -> ScriptGeneration {
231        self.generation
232    }
233
234    pub(crate) fn try_from_fn_ptr(
235        mut function: FnPtr,
236        generation: ScriptGeneration,
237    ) -> Result<Self, ScriptCallbackDefinitionError> {
238        if function.is_anonymous() {
239            return Err(ScriptCallbackDefinitionError::Anonymous);
240        }
241        let lexical_context = crate::invocation::take_function_environment(&mut function);
242        let mut binding = None;
243        let mut curry = Vec::new();
244        for (index, value) in function.iter_curry().cloned().enumerate() {
245            if value.is::<ComponentCallbackBinding>() {
246                binding = Some(value.cast::<ComponentCallbackBinding>());
247                continue;
248            }
249            curry.push(
250                UiValue::from_dynamic(value).map_err(|source| {
251                    ScriptCallbackDefinitionError::InvalidCurry { index, source }
252                })?,
253            );
254        }
255        function.set_curry(curry.iter().cloned().map(UiValue::into_dynamic));
256        let (component, incarnation, events, native_context, is_node_factory) = binding
257            .map_or_else(
258                || (None, None, BTreeMap::new(), None, false),
259                |binding| {
260                    (
261                        Some(binding.component),
262                        Some(binding.incarnation),
263                        binding.events,
264                        binding.context,
265                        binding.is_node_factory,
266                    )
267                },
268            );
269        Ok(Self {
270            function,
271            curry,
272            generation,
273            component,
274            incarnation,
275            events,
276            native_context: lexical_context.or(native_context),
277            is_node_factory,
278        })
279    }
280
281    pub(crate) fn bind_generation(&mut self, generation: ScriptGeneration) {
282        self.generation = generation;
283    }
284
285    #[cfg(test)]
286    pub(crate) fn bind_component_if_unset(
287        &mut self,
288        component: ComponentInstancePath,
289        events: BTreeMap<String, EventSchema>,
290    ) {
291        if self.component.is_none() {
292            self.component = Some(component);
293            self.events = events;
294        }
295    }
296
297    pub(crate) fn bind_component_scope_if_unset(
298        &mut self,
299        component: &ComponentInstancePath,
300        incarnation: crate::ComponentIncarnation,
301        events: BTreeMap<String, EventSchema>,
302    ) {
303        if self.component.is_none() {
304            self.component = Some(component.clone());
305            self.events = events;
306        }
307        if self.component.as_ref() == Some(component) && self.incarnation.is_none() {
308            self.incarnation = Some(incarnation);
309        }
310    }
311
312    pub(crate) fn bind_native_context_if_unset(
313        &mut self,
314        context: crate::invocation::ScriptInvocationContext,
315    ) {
316        if self.native_context.is_none() {
317            self.native_context = Some(context);
318        }
319    }
320
321    pub(crate) fn component(&self) -> Option<&ComponentInstancePath> {
322        self.component.as_ref()
323    }
324
325    pub(crate) const fn incarnation(&self) -> Option<crate::ComponentIncarnation> {
326        self.incarnation
327    }
328
329    pub(crate) fn events(&self) -> &BTreeMap<String, EventSchema> {
330        &self.events
331    }
332
333    pub(crate) fn native_context(&self) -> Option<&crate::invocation::ScriptInvocationContext> {
334        self.native_context.as_ref()
335    }
336
337    pub(crate) const fn is_node_factory(&self) -> bool {
338        self.is_node_factory
339    }
340
341    pub(crate) fn render_node(
342        &self,
343        call: &rhai::NativeCallContext<'_>,
344        context: UiContext,
345        detail: Dynamic,
346    ) -> Result<UiNode, Box<EvalAltResult>> {
347        let args = (context, detail);
348        if let Some(environment) = &self.native_context {
349            environment.call_synchronous(call, &self.function, args)
350        } else {
351            self.function.call_within_context(call, args)
352        }
353    }
354
355    /// The scope a bound Node factory calls back into: where it was bound.
356    fn factory_scope_binding(&self) -> Option<ComponentCallbackBinding> {
357        Some(ComponentCallbackBinding {
358            component: self.component.clone()?,
359            incarnation: self.incarnation?,
360            events: self.events.clone(),
361            context: self.native_context.clone(),
362            is_node_factory: false,
363        })
364    }
365
366    pub(crate) fn bind_node_factory(
367        mut function: FnPtr,
368        context: &UiContext,
369        call: &rhai::NativeCallContext<'_>,
370    ) -> FnPtr {
371        let mut already_bound = false;
372        for value in function.iter_curry_mut() {
373            if value.is::<ComponentCallbackBinding>() {
374                let mut binding = value.clone_cast::<ComponentCallbackBinding>();
375                binding.is_node_factory = true;
376                *value = Dynamic::from(binding);
377                already_bound = true;
378            }
379        }
380        if !already_bound {
381            function.add_curry(Dynamic::from(ComponentCallbackBinding {
382                component: context.callback_component_path().clone(),
383                incarnation: context.callback_component_incarnation(),
384                events: context.callback_event_schemas().clone(),
385                context: Some(crate::invocation::ScriptInvocationContext::capture_retained(call)),
386                is_node_factory: true,
387            }));
388        }
389        function
390    }
391}
392
393impl CompiledUi {
394    #[must_use]
395    pub fn generation(&self) -> ScriptGeneration {
396        self.generation
397    }
398
399    #[must_use]
400    pub fn has_function(&self, name: &str, parameter_count: usize) -> bool {
401        self.ast
402            .iter_functions()
403            .any(|function| function.name == name && function.params.len() == parameter_count)
404    }
405}
406
407struct ActiveComponentRender {
408    root_context: UiContext,
409    stack: Vec<ComponentInstancePath>,
410    contexts: Vec<UiContext>,
411    seen: BTreeSet<ComponentInstancePath>,
412    positions: BTreeMap<String, usize>,
413    transaction: RenderStateTransaction,
414    generation: ScriptGeneration,
415    state_snapshot: crate::StateStore,
416    event_handlers: BTreeMap<(ComponentInstancePath, String), ScriptCallback>,
417    invocations: BTreeMap<ComponentInstancePath, ComponentInvocationRecipe>,
418    effect_keys: Vec<Option<BTreeSet<String>>>,
419    effects: BTreeMap<crate::EffectId, crate::EffectDescriptor>,
420    timers: BTreeMap<crate::TimerId, crate::TimerDescriptor>,
421    signals: BTreeMap<crate::SignalId, crate::signal::SignalDescriptor>,
422    element_refs: BTreeSet<crate::ElementRefId>,
423    virtual_collections: BTreeMap<crate::VirtualCollectionId, VirtualCollectionRecipe>,
424    environment: ComponentRenderEnvironment,
425    reuse: Option<ComponentReuseSnapshot>,
426    reused: Vec<(String, usize)>,
427    failed_component: Option<ComponentInstancePath>,
428    /// The Node factories rendering, innermost last ([`FactoryScope`]).
429    factory_scopes: Vec<FactoryScope>,
430}
431
432/// A Node factory while it renders for the component that received it. The
433/// factory runs with the receiving component's `ctx`, but the callbacks it
434/// creates belong to the scope that bound it: the nodes it returns and the
435/// components it renders directly call back into that scope.
436struct FactoryScope {
437    /// The receiving component's callback scope.
438    receiver: ComponentInstancePath,
439    /// The scope that bound the factory.
440    binding: ComponentCallbackBinding,
441}
442
443#[derive(Clone, Copy, Debug, Eq, PartialEq)]
444struct ComponentRenderEnvironment {
445    theme_generation: Option<u64>,
446    component_style_generation: u64,
447    locale_generation: Option<u64>,
448    calendar_day: crate::GregorianDate,
449}
450
451#[derive(Clone)]
452struct ComponentReusePlan {
453    previous_root: Rc<UiNode>,
454    subtrees: crate::node::ComponentSubtreeIndex,
455    dirty: BTreeSet<ComponentInstancePath>,
456}
457
458impl ComponentReusePlan {
459    fn new(previous_root: Rc<UiNode>, dirty: BTreeSet<ComponentInstancePath>) -> Self {
460        let subtrees = crate::node::ComponentSubtreeIndex::new(&previous_root);
461        Self {
462            previous_root,
463            subtrees,
464            dirty,
465        }
466    }
467}
468
469#[derive(Clone)]
470struct ComponentReuseSnapshot {
471    previous_root: Rc<UiNode>,
472    subtrees: crate::node::ComponentSubtreeIndex,
473    dirty: BTreeSet<ComponentInstancePath>,
474    invocations: BTreeMap<ComponentInstancePath, ComponentInvocationRecipe>,
475    event_handlers: BTreeMap<(ComponentInstancePath, String), ScriptCallback>,
476    effects: BTreeMap<crate::EffectId, crate::EffectDescriptor>,
477    timers: BTreeMap<crate::TimerId, crate::TimerDescriptor>,
478    signals: BTreeMap<crate::SignalId, crate::signal::SignalDescriptor>,
479    element_refs: BTreeSet<crate::ElementRefId>,
480    virtual_collections: BTreeMap<crate::VirtualCollectionId, VirtualCollectionRecipe>,
481}
482
483struct ReusedComponentScope {
484    node: UiNode,
485    invocations: BTreeMap<ComponentInstancePath, ComponentInvocationRecipe>,
486    event_handlers: BTreeMap<(ComponentInstancePath, String), ScriptCallback>,
487    resources: ReusedComponentResources,
488}
489
490struct ReusedComponentResources {
491    effects: BTreeMap<crate::EffectId, crate::EffectDescriptor>,
492    timers: BTreeMap<crate::TimerId, crate::TimerDescriptor>,
493    signals: BTreeMap<crate::SignalId, crate::signal::SignalDescriptor>,
494    element_refs: BTreeSet<crate::ElementRefId>,
495    virtual_collections: BTreeMap<crate::VirtualCollectionId, VirtualCollectionRecipe>,
496}
497
498#[derive(Clone, Debug)]
499struct VirtualCollectionRecipe {
500    id: crate::VirtualCollectionId,
501    data: crate::VirtualCollectionData,
502    renderer: FnPtr,
503    renderer_context: crate::invocation::ScriptInvocationContext,
504    context: UiContext,
505    generation: ScriptGeneration,
506    /// Items rendered beyond the needed ones when a scroll needs new items.
507    batch_items: usize,
508    /// Items released from the realized range, shared by the clones of this
509    /// recipe. A new render of the collection makes a new recipe, so what it
510    /// kept is dropped with the data and renderer it was rendered from.
511    offscreen: Rc<RefCell<OffscreenItems>>,
512}
513
514/// Rendered items a virtual collection keeps after they leave its realized
515/// range, by index into its recipe's data, least recently released first.
516#[derive(Debug, Default)]
517struct OffscreenItems {
518    capacity: usize,
519    items: BTreeMap<usize, UiNode>,
520    order: VecDeque<usize>,
521}
522
523impl OffscreenItems {
524    fn new(capacity: usize) -> Self {
525        Self {
526            capacity,
527            ..Self::default()
528        }
529    }
530
531    /// Keep `node`, released at `index`, dropping the least recently released
532    /// items beyond the capacity.
533    fn keep(&mut self, index: usize, node: UiNode) {
534        if self.capacity == 0 {
535            return;
536        }
537        if self.items.insert(index, node).is_some() {
538            self.order.retain(|kept| *kept != index);
539        }
540        self.order.push_back(index);
541        while self.items.len() > self.capacity {
542            let Some(oldest) = self.order.pop_front() else {
543                break;
544            };
545            self.items.remove(&oldest);
546        }
547    }
548
549    /// Take back the item kept for `index`.
550    fn take(&mut self, index: usize) -> Option<UiNode> {
551        let node = self.items.remove(&index)?;
552        self.order.retain(|kept| *kept != index);
553        Some(node)
554    }
555}
556
557type ActiveComponentRenderState = Rc<RefCell<Option<ActiveComponentRender>>>;
558
559#[derive(Clone)]
560struct PendingComponentCommit {
561    root: ComponentInstancePath,
562    previous: BTreeSet<ComponentInstancePath>,
563    retained_root: Option<ComponentInstancePath>,
564    transaction: RenderStateTransaction,
565    event_handlers: BTreeMap<(ComponentInstancePath, String), ScriptCallback>,
566}
567
568#[derive(Clone, Debug)]
569pub struct ComponentInvocationRecipe {
570    path: ComponentInstancePath,
571    parent: ComponentInstancePath,
572    component: ModuleId,
573    export: String,
574    declared_key: Option<String>,
575    props: crate::ComponentProps,
576    script_props: Map,
577    component_context: UiContext,
578    caller_context: UiContext,
579    part_styles: BTreeMap<String, crate::Style>,
580    event_callbacks: Vec<(String, FnPtr)>,
581    component_events: BTreeMap<String, EventSchema>,
582    declared_effects: BTreeSet<String>,
583    render: FnPtr,
584    snapshot: crate::node::ComponentOwnedSnapshot,
585    context: crate::invocation::ScriptInvocationContext,
586    generation: ScriptGeneration,
587    environment: ComponentRenderEnvironment,
588    reusable: bool,
589}
590
591#[derive(Clone)]
592pub(crate) struct RegisteredComponentRender {
593    generation: ScriptGeneration,
594    render: FnPtr,
595}
596
597type ComponentRenderRegistry = Rc<RefCell<BTreeMap<ModuleId, RegisteredComponentRender>>>;
598
599impl ComponentInvocationRecipe {
600    #[must_use]
601    pub fn path(&self) -> &ComponentInstancePath {
602        &self.path
603    }
604
605    #[must_use]
606    pub fn parent(&self) -> &ComponentInstancePath {
607        &self.parent
608    }
609
610    #[must_use]
611    pub fn component(&self) -> &ModuleId {
612        &self.component
613    }
614
615    #[must_use]
616    pub fn export(&self) -> &str {
617        &self.export
618    }
619
620    #[must_use]
621    pub fn declared_key(&self) -> Option<&str> {
622        self.declared_key.as_deref()
623    }
624
625    #[must_use]
626    pub fn props(&self) -> &crate::ComponentProps {
627        &self.props
628    }
629
630    #[must_use]
631    pub fn render_name(&self) -> &str {
632        self.render.fn_name()
633    }
634
635    #[must_use]
636    pub fn has_invocation_context(&self) -> bool {
637        let _ = &self.context;
638        true
639    }
640
641    #[must_use]
642    pub fn generation(&self) -> ScriptGeneration {
643        self.generation
644    }
645}
646
647pub struct RuntimeEngine {
648    engine: Engine,
649    generation: ScriptGeneration,
650    preparation_generation: Option<ScriptGeneration>,
651    component_exports: ComponentExportCollector,
652    evaluation_generation: Rc<Cell<ScriptGeneration>>,
653    primitives: PrimitiveRegistry,
654    primitive_modules: BTreeMap<String, Module>,
655    timings: RefCell<Vec<ExecutionTiming>>,
656    last_failed_timing: RefCell<Option<ExecutionTiming>>,
657    last_failed_component: RefCell<Option<ComponentInstancePath>>,
658    operation_tracker: Rc<OperationTracker>,
659    operation_limit: Rc<Cell<u64>>,
660    slow_threshold: Duration,
661    component_render: ActiveComponentRenderState,
662    component_invocations: BTreeMap<ComponentInstancePath, ComponentInvocationRecipe>,
663    component_effects: BTreeMap<crate::EffectId, crate::EffectDescriptor>,
664    component_timers: BTreeMap<crate::TimerId, crate::TimerDescriptor>,
665    component_signals: BTreeMap<crate::SignalId, crate::signal::SignalDescriptor>,
666    component_element_refs: BTreeSet<crate::ElementRefId>,
667    pending_component_commits: BTreeMap<ComponentInstancePath, PendingComponentCommit>,
668    component_renderers: ComponentRenderRegistry,
669    virtual_collection_policy: Rc<Cell<crate::VirtualCollectionPolicy>>,
670    native_handlers: crate::NativeHandlerRegistry,
671    syntax_registry: crate::SyntaxRegistry,
672    document_runtime: crate::DocumentRuntimeConfig,
673    #[cfg(feature = "charts")]
674    chart_transforms: crate::ChartTransformRegistry,
675    #[cfg(feature = "charts")]
676    chart_geo: crate::ChartGeoRegistry,
677    #[cfg(feature = "charts")]
678    chart_series: crate::ChartSeriesRegistry,
679    #[cfg(feature = "charts")]
680    chart_formatters: crate::ChartFormatterRegistry,
681    virtual_collections: BTreeMap<crate::VirtualCollectionId, VirtualCollectionRecipe>,
682}
683
684pub const DEFAULT_SCRIPT_OPERATION_LIMIT: u64 = 1_000_000;
685
686#[derive(Debug, Default)]
687struct OperationTracker {
688    last_absolute: Cell<u64>,
689    total: Cell<u64>,
690}
691
692impl OperationTracker {
693    fn begin(&self, inherited_base: u64) {
694        self.last_absolute.set(inherited_base);
695        self.total.set(0);
696    }
697
698    fn observe(&self, absolute: u64) -> u64 {
699        let last_absolute = self.last_absolute.get();
700        let delta = if absolute >= last_absolute {
701            absolute - last_absolute
702        } else {
703            // Returning from a nested evaluator resumes a smaller parent
704            // counter. Rhai invokes progress once per operation, so the first
705            // lower observation represents one newly consumed parent step.
706            1
707        };
708        let total = self.total.get().saturating_add(delta);
709        self.total.set(total);
710        self.last_absolute.set(absolute);
711        total
712    }
713
714    fn align(&self, inherited_base: u64) {
715        // Stored NativeCallContext values clone the absolute counter captured
716        // in an earlier evaluator. Align only that absolute baseline before a
717        // retained call; the current execution session's aggregate must remain
718        // intact across multiple dirty components or virtual items.
719        self.last_absolute.set(inherited_base);
720    }
721}
722
723#[derive(Clone, Copy)]
724struct ExecutionTimingStart {
725    instant: Instant,
726    operations: u64,
727    operation_limit: u64,
728}
729
730#[derive(Clone)]
731pub(crate) struct RuntimeEngineCheckpoint {
732    generation: ScriptGeneration,
733    evaluation_generation: ScriptGeneration,
734    component_invocations: BTreeMap<ComponentInstancePath, ComponentInvocationRecipe>,
735    component_effects: BTreeMap<crate::EffectId, crate::EffectDescriptor>,
736    component_timers: BTreeMap<crate::TimerId, crate::TimerDescriptor>,
737    component_signals: BTreeMap<crate::SignalId, crate::signal::SignalDescriptor>,
738    component_element_refs: BTreeSet<crate::ElementRefId>,
739    pending_component_commits: BTreeMap<ComponentInstancePath, PendingComponentCommit>,
740    virtual_collections: BTreeMap<crate::VirtualCollectionId, VirtualCollectionRecipe>,
741    component_snapshots: Vec<(crate::node::ComponentOwnedSnapshot, Option<Rc<UiNode>>)>,
742}
743
744impl Default for RuntimeEngine {
745    fn default() -> Self {
746        Self::new()
747    }
748}
749
750impl RuntimeEngine {
751    #[cfg(feature = "dev-reload")]
752    pub(crate) fn candidate_engine(&self) -> Self {
753        let mut candidate = Self::new();
754        candidate.slow_threshold = self.slow_threshold;
755        candidate.operation_limit.set(self.operation_limit.get());
756        let (global, functions) = self.expression_depth_limits();
757        candidate.set_expression_depth_limits(global, functions);
758        #[cfg(feature = "charts")]
759        {
760            candidate.chart_transforms.copy_from(&self.chart_transforms);
761            candidate.chart_geo.copy_from(&self.chart_geo);
762            candidate.chart_series.copy_from(&self.chart_series);
763            candidate.chart_formatters.copy_from(&self.chart_formatters);
764        }
765        candidate
766    }
767
768    /// Create a runtime with all built-in primitive descriptors.
769    ///
770    /// # Panics
771    ///
772    /// Panics only if a compile-time built-in descriptor violates the same
773    /// validation rules enforced for downstream custom primitives.
774    #[must_use]
775    #[allow(clippy::too_many_lines)] // Wires every runtime registry into one engine.
776    pub fn new() -> Self {
777        let mut engine = Engine::new();
778        engine.set_module_resolver(crate::source::RestrictedModuleResolver::new());
779        let operation_tracker = Rc::new(OperationTracker::default());
780        let progress = Rc::clone(&operation_tracker);
781        let operation_limit = Rc::new(Cell::new(DEFAULT_SCRIPT_OPERATION_LIMIT));
782        let limit_probe = Rc::clone(&operation_limit);
783        engine.on_progress(move |operations| {
784            let total = progress.observe(operations);
785            let limit = limit_probe.get();
786            (total > limit).then(|| {
787                Dynamic::from(format!(
788                    "script operation budget exceeded: {total} > {limit}"
789                ))
790            })
791        });
792        engine.build_type::<UiNode>();
793        engine.build_type::<OpaqueHandle>();
794        engine.build_type::<TaskHandle>();
795        engine.build_type::<SubscriptionHandle>();
796        engine.build_type::<AssetId>();
797        engine.build_type::<ImageDecodeHandle>();
798        engine.build_type::<crate::NativeSignal>();
799        engine.build_type::<crate::EventResponse>();
800        engine.build_type::<crate::ElementRef>();
801        engine.build_type::<crate::NativeHandlerRef>();
802        crate::native_collection::register_native_collection_api(&mut engine);
803        crate::document::register_document_api(&mut engine);
804        #[cfg(feature = "charts")]
805        {
806            crate::chart::register_chart_data_api(&mut engine);
807            register_chart_validation_api(&mut engine);
808        }
809        engine.build_type::<crate::Span>();
810        register_ui_context_api(&mut engine);
811        register_date_api(&mut engine);
812        crate::time::register_time_api(&mut engine);
813        register_style_api(&mut engine);
814        register_motion_api(&mut engine);
815        register_text_area_api(&mut engine);
816        register_canvas_api(&mut engine);
817        crate::collection_projection::register_collection_projection_api(&mut engine);
818        let evaluation_generation = Rc::new(Cell::new(ScriptGeneration::default()));
819        let component_exports = ComponentExportCollector::new();
820        let virtual_collection_policy =
821            Rc::new(Cell::new(crate::VirtualCollectionPolicy::default()));
822        let (component_render, component_renderers) = register_component_runtime_apis(
823            &mut engine,
824            &component_exports,
825            &evaluation_generation,
826            &virtual_collection_policy,
827        );
828        let primitives = PrimitiveRegistry::new();
829        let native_handlers = crate::NativeHandlerRegistry::new();
830        let syntax_registry = crate::SyntaxRegistry::new();
831        let document_runtime = crate::DocumentRuntimeConfig::new();
832        #[cfg(feature = "charts")]
833        let chart_transforms = crate::ChartTransformRegistry::new();
834        #[cfg(feature = "charts")]
835        let chart_geo = crate::ChartGeoRegistry::new();
836        #[cfg(feature = "charts")]
837        let chart_series = crate::ChartSeriesRegistry::new();
838        #[cfg(feature = "charts")]
839        let chart_formatters = crate::ChartFormatterRegistry::new();
840        register_native_handler_api(&mut engine, &native_handlers);
841
842        register_node_apis(&mut engine);
843
844        configure_engine_limits(&mut engine);
845
846        let mut runtime = Self {
847            engine,
848            generation: ScriptGeneration::default(),
849            preparation_generation: None,
850            component_exports,
851            evaluation_generation,
852            primitives,
853            primitive_modules: BTreeMap::new(),
854            timings: RefCell::new(Vec::new()),
855            last_failed_timing: RefCell::new(None),
856            last_failed_component: RefCell::new(None),
857            operation_tracker,
858            operation_limit,
859            slow_threshold: Duration::from_millis(16),
860            component_render,
861            component_invocations: BTreeMap::new(),
862            component_effects: BTreeMap::new(),
863            component_timers: BTreeMap::new(),
864            component_signals: BTreeMap::new(),
865            component_element_refs: BTreeSet::new(),
866            pending_component_commits: BTreeMap::new(),
867            component_renderers,
868            virtual_collection_policy,
869            native_handlers,
870            syntax_registry,
871            document_runtime,
872            #[cfg(feature = "charts")]
873            chart_transforms,
874            #[cfg(feature = "charts")]
875            chart_geo,
876            #[cfg(feature = "charts")]
877            chart_series,
878            #[cfg(feature = "charts")]
879            chart_formatters,
880            virtual_collections: BTreeMap::new(),
881        };
882        runtime.register_builtin_primitives();
883        runtime
884    }
885
886    #[allow(clippy::too_many_lines)] // Declarative registration of the built-in primitive set.
887    fn register_builtin_primitives(&mut self) {
888        let column_measurements = ColumnMeasurementRegistry::default();
889        self.register_primitive(
890            column_resize_primitive_descriptor(),
891            ColumnResizePrimitiveHandler::new(column_measurements.clone()),
892        )
893        .expect("built-in column resize primitive descriptor is valid");
894        self.register_primitive(
895            intrinsic_text_measure_primitive_descriptor(),
896            IntrinsicTextMeasurePrimitiveHandler::new(column_measurements),
897        )
898        .expect("built-in intrinsic text measurement primitive descriptor is valid");
899        self.register_primitive(
900            split_resize_primitive_descriptor(),
901            SplitResizePrimitiveHandler,
902        )
903        .expect("built-in split resize primitive descriptor is valid");
904        self.register_primitive(
905            resizable_primitive_descriptor(),
906            ResizablePrimitiveHandler::default(),
907        )
908        .expect("built-in resizable primitive descriptor is valid");
909        self.register_primitive(draggable_primitive_descriptor(), DraggablePrimitiveHandler)
910            .expect("built-in draggable primitive descriptor is valid");
911        self.register_primitive(
912            drag_source_primitive_descriptor(),
913            DragSourcePrimitiveHandler::default(),
914        )
915        .expect("built-in drag source primitive descriptor is valid");
916        self.register_primitive(drop_zone_primitive_descriptor(), DropZonePrimitiveHandler)
917            .expect("built-in drop zone primitive descriptor is valid");
918        self.register_primitive(
919            sortable_primitive_descriptor(),
920            SortablePrimitiveHandler::default(),
921        )
922        .expect("built-in sortable primitive descriptor is valid");
923        self.register_primitive(
924            pan_zoom_primitive_descriptor(),
925            PanZoomPrimitiveHandler::default(),
926        )
927        .expect("built-in pan zoom primitive descriptor is valid");
928        self.register_primitive(
929            range_slider_primitive_descriptor(),
930            RangeSliderPrimitiveHandler::default(),
931        )
932        .expect("built-in range slider primitive descriptor is valid");
933        self.register_primitive(rotatable_primitive_descriptor(), RotatablePrimitiveHandler)
934            .expect("built-in rotatable primitive descriptor is valid");
935        self.register_primitive(
936            selection_area_primitive_descriptor(),
937            SelectionAreaPrimitiveHandler::default(),
938        )
939        .expect("built-in selection area primitive descriptor is valid");
940        self.register_primitive(
941            text_input_primitive_descriptor(),
942            TextInputPrimitiveHandler::default(),
943        )
944        .expect("built-in TextInput primitive descriptor is valid");
945        self.register_primitive(
946            text_area_primitive_descriptor(),
947            TextAreaPrimitiveHandler::default(),
948        )
949        .expect("built-in Textarea primitive descriptor is valid");
950        self.register_primitive(
951            range_input_primitive_descriptor(),
952            RangeInputPrimitiveHandler::default(),
953        )
954        .expect("built-in RangeInput primitive descriptor is valid");
955        self.register_primitive(
956            crate::code_viewer_primitive_descriptor(),
957            crate::CodeViewerPrimitiveHandler::new(
958                self.syntax_registry.clone(),
959                self.document_runtime.clone(),
960            ),
961        )
962        .expect("built-in CodeViewer primitive descriptor is valid");
963        self.register_primitive(
964            crate::markdown_view::markdown_viewer_primitive_descriptor(),
965            crate::markdown_view::MarkdownViewerPrimitiveHandler::new(
966                self.syntax_registry.clone(),
967                self.document_runtime.clone(),
968            ),
969        )
970        .expect("built-in MarkdownViewer primitive descriptor is valid");
971        self.register_primitive(
972            crate::diff_viewer_primitive_descriptor(),
973            crate::DiffViewerPrimitiveHandler::new(
974                self.syntax_registry.clone(),
975                self.document_runtime.clone(),
976            ),
977        )
978        .expect("built-in DiffViewer primitive descriptor is valid");
979        #[cfg(feature = "charts")]
980        self.register_primitive(
981            crate::chart_primitive_descriptor(),
982            crate::ChartPrimitiveHandler::new(
983                self.chart_transforms.clone(),
984                self.chart_geo.clone(),
985                self.chart_series.clone(),
986                self.chart_formatters.clone(),
987            ),
988        )
989        .expect("built-in Chart primitive descriptor is valid");
990    }
991
992    /// Compile the default application entry source.
993    ///
994    /// # Errors
995    ///
996    /// Returns [`RuntimeError::Compile`] when Rhai rejects the source.
997    pub fn compile(&mut self, source: &str) -> Result<CompiledUi, RuntimeError> {
998        self.compile_named("ui/main.rhai", source)
999    }
1000
1001    /// Compile source with an explicit diagnostic name and advance the script generation.
1002    ///
1003    /// # Errors
1004    ///
1005    /// Returns [`RuntimeError::Compile`] when Rhai rejects the source.
1006    pub fn compile_named(
1007        &mut self,
1008        source_name: &str,
1009        source: &str,
1010    ) -> Result<CompiledUi, RuntimeError> {
1011        let generation = self.candidate_generation();
1012        self.evaluation_generation.set(generation);
1013        self.begin_execution_session();
1014        let started = self.begin_timing();
1015        let result = self.engine.compile(source);
1016        self.record_timing(
1017            ExecutionOperation::Compile,
1018            source_name,
1019            started,
1020            result.is_ok(),
1021        );
1022        let mut ast = result
1023            .map_err(|error| RuntimeError::Compile(explain_keyword_name(source, error).into()))?;
1024        validate_runtime_ast(&ast)?;
1025        ast.set_source(source_name);
1026        Ok(CompiledUi { ast, generation })
1027    }
1028
1029    /// Compile source while eagerly resolving and embedding literal imports.
1030    ///
1031    /// # Errors
1032    ///
1033    /// Returns [`RuntimeError::Compile`] for source, import, or module errors.
1034    pub fn compile_self_contained_named(
1035        &mut self,
1036        source_name: &str,
1037        source: &str,
1038    ) -> Result<CompiledUi, RuntimeError> {
1039        let generation = self.candidate_generation();
1040        self.evaluation_generation.set(generation);
1041        self.begin_execution_session();
1042        let started = self.begin_timing();
1043        let result = self
1044            .engine
1045            .compile_into_self_contained(&Scope::new(), source);
1046        self.record_timing(
1047            ExecutionOperation::Compile,
1048            source_name,
1049            started,
1050            result.is_ok(),
1051        );
1052        let mut ast = result.map_err(|error| match *error {
1053            EvalAltResult::ErrorParsing(kind, position) => RuntimeError::Compile(
1054                explain_keyword_name(source, rhai::ParseError(Box::new(kind), position)).into(),
1055            ),
1056            error => RuntimeError::Compile(Box::new(error)),
1057        })?;
1058        validate_literal_imports(&ast)?;
1059        validate_runtime_ast(&ast)?;
1060        ast.set_source(source_name);
1061        Ok(CompiledUi { ast, generation })
1062    }
1063
1064    pub fn set_module_resolver(&mut self, resolver: impl ModuleResolver + 'static) {
1065        self.engine.set_module_resolver(resolver);
1066    }
1067
1068    /// Compile all modules and the entry AST for one candidate under one unique
1069    /// program identity. Independent calls receive different generations even
1070    /// when neither candidate has been rendered yet.
1071    ///
1072    /// # Errors
1073    ///
1074    /// Returns the error produced by `operation`.
1075    pub fn with_program_preparation<T, E>(
1076        &mut self,
1077        operation: impl FnOnce(&mut Self) -> Result<T, E>,
1078    ) -> Result<T, E> {
1079        if self.preparation_generation.is_some() {
1080            return operation(self);
1081        }
1082        let generation = Self::allocate_generation();
1083        self.preparation_generation = Some(generation);
1084        let result = operation(self);
1085        self.preparation_generation = None;
1086        result
1087    }
1088
1089    #[allow(clippy::too_many_lines)]
1090    fn begin_component_render(
1091        &self,
1092        context: UiContext,
1093        generation: ScriptGeneration,
1094        root_effects: Option<BTreeSet<String>>,
1095        reuse_plan: Option<ComponentReusePlan>,
1096    ) -> Result<(), RuntimeError> {
1097        let root = context.component_path().clone();
1098        context.reset_non_reusable_render_reads();
1099        let (state_snapshot, environment, event_handlers) = {
1100            let runtime = context.runtime().try_borrow().map_err(|_| {
1101                RuntimeError::ComponentRuntime("UI state is already borrowed".to_owned())
1102            })?;
1103            (
1104                runtime.component_state.clone(),
1105                ComponentRenderEnvironment {
1106                    theme_generation: runtime.theme.as_ref().map(crate::ThemeManager::generation),
1107                    component_style_generation: runtime.component_style_generation(),
1108                    locale_generation: runtime
1109                        .locale
1110                        .as_ref()
1111                        .map(crate::LocaleManager::generation),
1112                    calendar_day: runtime
1113                        .calendar_clock
1114                        .presentation_today(&runtime.wall_clock)
1115                        .map_err(|error| RuntimeError::ComponentRuntime(error.to_string()))?,
1116                },
1117                reuse_plan
1118                    .as_ref()
1119                    .map(|_| runtime.component_event_handlers_in_scope(&root)),
1120            )
1121        };
1122        let mut transaction = context
1123            .runtime()
1124            .try_borrow()
1125            .map_err(|_| RuntimeError::ComponentRuntime("UI state is already borrowed".to_owned()))?
1126            .component_state
1127            .begin_render_scope(root.clone());
1128        let _ = transaction.retain_existing(&root);
1129        let reuse = reuse_plan.map(|plan| ComponentReuseSnapshot {
1130            subtrees: plan.subtrees,
1131            previous_root: plan.previous_root,
1132            dirty: plan.dirty,
1133            invocations: self
1134                .component_invocations
1135                .iter()
1136                .filter(|(path, _)| path.is_within(&root))
1137                .map(|(path, recipe)| (path.clone(), recipe.clone()))
1138                .collect(),
1139            event_handlers: event_handlers.unwrap_or_default(),
1140            effects: self
1141                .component_effects
1142                .iter()
1143                .filter(|(id, _)| id.component().is_within(&root))
1144                .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
1145                .collect(),
1146            timers: self
1147                .component_timers
1148                .iter()
1149                .filter(|(id, _)| id.component().is_within(&root))
1150                .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
1151                .collect(),
1152            signals: self
1153                .component_signals
1154                .iter()
1155                .filter(|(id, _)| id.component().is_within(&root))
1156                .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
1157                .collect(),
1158            element_refs: self
1159                .component_element_refs
1160                .iter()
1161                .filter(|id| id.component().is_within(&root))
1162                .cloned()
1163                .collect(),
1164            virtual_collections: self
1165                .virtual_collections
1166                .iter()
1167                .filter(|(id, _)| id.component.is_within(&root))
1168                .map(|(id, recipe)| (id.clone(), recipe.clone()))
1169                .collect(),
1170        });
1171        let mut active = self.component_render.try_borrow_mut().map_err(|_| {
1172            RuntimeError::ComponentRuntime("component render stack is already borrowed".to_owned())
1173        })?;
1174        *active = Some(ActiveComponentRender {
1175            root_context: context.clone(),
1176            stack: vec![root],
1177            contexts: vec![context],
1178            seen: BTreeSet::new(),
1179            positions: BTreeMap::new(),
1180            transaction,
1181            generation,
1182            state_snapshot,
1183            event_handlers: BTreeMap::new(),
1184            invocations: BTreeMap::new(),
1185            effect_keys: vec![root_effects],
1186            effects: BTreeMap::new(),
1187            timers: BTreeMap::new(),
1188            signals: BTreeMap::new(),
1189            element_refs: BTreeSet::new(),
1190            virtual_collections: BTreeMap::new(),
1191            environment,
1192            reuse,
1193            reused: Vec::new(),
1194            failed_component: None,
1195            factory_scopes: Vec::new(),
1196        });
1197        Ok(())
1198    }
1199
1200    fn finish_component_render(&mut self, commit: bool) -> Result<(), RuntimeError> {
1201        let active = self
1202            .component_render
1203            .try_borrow_mut()
1204            .map_err(|_| {
1205                RuntimeError::ComponentRuntime(
1206                    "component render stack is already borrowed".to_owned(),
1207                )
1208            })?
1209            .take();
1210        let Some(active) = active else {
1211            return Ok(());
1212        };
1213        if commit {
1214            self.timings
1215                .borrow_mut()
1216                .extend(
1217                    active
1218                        .reused
1219                        .iter()
1220                        .map(|(source, components)| ExecutionTiming {
1221                            operation: ExecutionOperation::ComponentReuse(*components),
1222                            source: source.clone(),
1223                            duration: Duration::ZERO,
1224                            operations: 0,
1225                            operation_limit: self.operation_limit(),
1226                            round_operations: self.operation_total(),
1227                            operation_semantics: OPERATION_SEMANTICS_VERSION,
1228                            slow: false,
1229                            succeeded: true,
1230                        }),
1231                );
1232            let root = active.root_context.component_path().clone();
1233            let previous = active.state_snapshot.paths();
1234            self.pending_component_commits.insert(
1235                root.clone(),
1236                PendingComponentCommit {
1237                    root: root.clone(),
1238                    previous,
1239                    retained_root: (!active.invocations.contains_key(&root)
1240                        && active.transaction.retains_root())
1241                    .then_some(root.clone()),
1242                    transaction: active.transaction,
1243                    event_handlers: active.event_handlers,
1244                },
1245            );
1246            self.component_invocations
1247                .retain(|path, _| !path.is_within(&root));
1248            self.component_invocations.extend(active.invocations);
1249            self.component_effects
1250                .retain(|id, _| !id.component().is_within(&root));
1251            self.component_effects.extend(active.effects);
1252            self.component_timers
1253                .retain(|id, _| !id.component().is_within(&root));
1254            self.component_timers.extend(active.timers);
1255            self.component_signals
1256                .retain(|id, _| !id.component().is_within(&root));
1257            self.component_signals.extend(active.signals);
1258            self.component_element_refs
1259                .retain(|id| !id.component().is_within(&root));
1260            self.component_element_refs.extend(active.element_refs);
1261            self.virtual_collections
1262                .retain(|id, _| !id.component.is_within(&root));
1263            self.virtual_collections.extend(active.virtual_collections);
1264        } else {
1265            *self.last_failed_component.borrow_mut() = active
1266                .failed_component
1267                .or_else(|| active.stack.last().cloned());
1268            active
1269                .root_context
1270                .runtime()
1271                .try_borrow_mut()
1272                .map_err(|_| {
1273                    RuntimeError::ComponentRuntime("UI state is already borrowed".to_owned())
1274                })?
1275                .component_state = active.state_snapshot;
1276        }
1277        Ok(())
1278    }
1279
1280    /// Evaluate the compiled application's `view` function.
1281    ///
1282    /// # Errors
1283    ///
1284    /// Returns [`RuntimeError::Evaluate`] when `view` is missing, fails, or
1285    /// returns a value other than [`UiNode`].
1286    pub fn render(&mut self, compiled: &CompiledUi) -> Result<UiNode, RuntimeError> {
1287        self.evaluation_generation.set(compiled.generation);
1288        self.begin_execution_session();
1289        let checkpoint = self.execution_checkpoint();
1290        let root_path = ComponentInstancePath::root("App", "root");
1291        let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
1292        let context = UiContext::new(
1293            Rc::clone(&runtime),
1294            root_path.clone(),
1295            None,
1296            ExecutionPhase::Render,
1297            BTreeMap::new(),
1298        )
1299        .with_generation(compiled.generation);
1300        self.begin_component_render(context, compiled.generation, None, None)?;
1301        let started = self.begin_timing();
1302        let result = AstInterpreter::call_fn::<UiNode, _>(
1303            &self.engine,
1304            &compiled.ast,
1305            &mut Scope::new(),
1306            "view",
1307            (),
1308        );
1309        self.record_timing(
1310            ExecutionOperation::Render,
1311            compiled.ast.source().unwrap_or("<script>"),
1312            started,
1313            result.is_ok(),
1314        );
1315        self.finish_component_render(result.is_ok())?;
1316        let mut root = result.map_err(RuntimeError::Evaluate)?;
1317        if !self.component_effects_in_scope(&root_path).is_empty()
1318            || !self.component_timers_in_scope(&root_path).is_empty()
1319            || !self.component_signals_in_scope(&root_path).is_empty()
1320            || !self.component_element_refs_in_scope(&root_path).is_empty()
1321            || !self.virtual_collection_ids_in_scope(&root_path).is_empty()
1322        {
1323            self.restore_execution_checkpoint(checkpoint);
1324            return Err(RuntimeError::ComponentRuntime(
1325                "effectful, timer/signal/ref-owning, or virtual components require ScriptLifecycle"
1326                    .to_owned(),
1327            ));
1328        }
1329        if let Err(error) = self.commit_component_renders(&mut runtime.borrow_mut()) {
1330            self.restore_execution_checkpoint(checkpoint);
1331            return Err(error);
1332        }
1333        root.bind_generation(compiled.generation);
1334        self.generation = compiled.generation;
1335        Ok(root)
1336    }
1337
1338    /// Evaluate the compiled application's `view(ctx)` function.
1339    ///
1340    /// # Errors
1341    ///
1342    /// Returns [`RuntimeError::Evaluate`] when `view` fails or returns a value
1343    /// other than [`UiNode`].
1344    pub fn render_with_context(
1345        &mut self,
1346        compiled: &CompiledUi,
1347        context: UiContext,
1348    ) -> Result<UiNode, RuntimeError> {
1349        let runtime = Rc::clone(context.runtime());
1350        let root = context.component_path().clone();
1351        let snapshot = runtime
1352            .try_borrow_mut()
1353            .map_err(|_| RuntimeError::ComponentRuntime("UI state is already borrowed".to_owned()))?
1354            .begin_transaction()
1355            .map_err(|error| RuntimeError::ComponentRuntime(error.to_string()))?;
1356        let checkpoint = self.execution_checkpoint();
1357        let result = self.render_with_context_staged(compiled, context);
1358        let result = result.and_then(|node| {
1359            if !self.component_effects_in_scope(&root).is_empty()
1360                || !self.component_timers_in_scope(&root).is_empty()
1361                || !self.component_signals_in_scope(&root).is_empty()
1362                || !self.component_element_refs_in_scope(&root).is_empty()
1363                || !self.virtual_collection_ids_in_scope(&root).is_empty()
1364            {
1365                return Err(RuntimeError::ComponentRuntime(
1366                    "effectful, timer/signal/ref-owning, or virtual components require ScriptLifecycle"
1367                        .to_owned(),
1368                ));
1369            }
1370            self.commit_component_renders(&mut runtime.borrow_mut())?;
1371            Ok(node)
1372        });
1373        match result {
1374            Ok(node) => {
1375                runtime
1376                    .try_borrow_mut()
1377                    .map_err(|_| {
1378                        RuntimeError::ComponentRuntime("UI state is already borrowed".to_owned())
1379                    })?
1380                    .commit_transaction()
1381                    .map_err(|error| RuntimeError::ComponentRuntime(error.to_string()))?;
1382                Ok(node)
1383            }
1384            Err(error) => {
1385                runtime
1386                    .try_borrow_mut()
1387                    .map_err(|_| {
1388                        RuntimeError::ComponentRuntime("UI state is already borrowed".to_owned())
1389                    })?
1390                    .restore(snapshot)
1391                    .map_err(|restore| RuntimeError::ComponentRuntime(restore.to_string()))?;
1392                self.restore_execution_checkpoint(checkpoint);
1393                Err(error)
1394            }
1395        }
1396    }
1397
1398    pub(crate) fn render_with_context_staged(
1399        &mut self,
1400        compiled: &CompiledUi,
1401        context: UiContext,
1402    ) -> Result<UiNode, RuntimeError> {
1403        self.render_with_context_staged_impl(compiled, context, None)
1404    }
1405
1406    pub(crate) fn render_with_context_staged_reusing(
1407        &mut self,
1408        compiled: &CompiledUi,
1409        context: UiContext,
1410        previous_root: Rc<UiNode>,
1411        dirty: &BTreeSet<ComponentInstancePath>,
1412    ) -> Result<UiNode, RuntimeError> {
1413        self.render_with_context_staged_impl(
1414            compiled,
1415            context,
1416            Some(ComponentReusePlan::new(previous_root, dirty.clone())),
1417        )
1418    }
1419
1420    fn render_with_context_staged_impl(
1421        &mut self,
1422        compiled: &CompiledUi,
1423        context: UiContext,
1424        reuse: Option<ComponentReusePlan>,
1425    ) -> Result<UiNode, RuntimeError> {
1426        self.evaluation_generation.set(compiled.generation);
1427        self.begin_execution_session();
1428        self.begin_component_render(context.clone(), compiled.generation, None, reuse)?;
1429        let started = self.begin_timing();
1430        let result = AstInterpreter::call_fn::<UiNode, _>(
1431            &self.engine,
1432            &compiled.ast,
1433            &mut Scope::new(),
1434            "view",
1435            (context,),
1436        );
1437        self.record_timing(
1438            ExecutionOperation::Render,
1439            compiled.ast.source().unwrap_or("<script>"),
1440            started,
1441            result.is_ok(),
1442        );
1443        self.finish_component_render(result.is_ok())?;
1444        let mut root = result.map_err(RuntimeError::Evaluate)?;
1445        root.bind_generation(compiled.generation);
1446        self.generation = compiled.generation;
1447        Ok(root)
1448    }
1449
1450    pub(crate) fn rerender_component(
1451        &mut self,
1452        component: &ComponentInstancePath,
1453        previous_root: &UiNode,
1454        dirty: &BTreeSet<ComponentInstancePath>,
1455    ) -> Result<UiNode, RuntimeError> {
1456        let mut recipe = self
1457            .component_invocations
1458            .get(component)
1459            .cloned()
1460            .ok_or_else(|| RuntimeError::MissingComponentInvocation(component.clone()))?;
1461        if recipe.generation != self.generation {
1462            return Err(RuntimeError::StaleCallback {
1463                name: recipe.render.fn_name().to_owned(),
1464                callback_generation: recipe.generation,
1465                current_generation: self.generation,
1466            });
1467        }
1468        recipe
1469            .component_context
1470            .runtime()
1471            .try_borrow_mut()
1472            .map_err(|_| RuntimeError::ComponentRuntime("UI state is already borrowed".to_owned()))?
1473            .reset_component_readers(component);
1474        for value in recipe.script_props.values_mut() {
1475            hydrate_replayed_node_value(value);
1476        }
1477        let reuse = ComponentReusePlan::new(Rc::new(previous_root.clone()), dirty.clone());
1478        self.begin_component_render(
1479            recipe.component_context.clone(),
1480            recipe.generation,
1481            Some(recipe.declared_effects.clone()),
1482            Some(reuse),
1483        )?;
1484        register_component_invocation(&self.component_render, recipe.clone())
1485            .map_err(RuntimeError::Evaluate)?;
1486
1487        self.align_execution_session_to(recipe.context.operation_base());
1488        let started = self.begin_timing();
1489        let result = (|| {
1490            let mut node = recipe
1491                .context
1492                .call::<UiNode>(
1493                    self.engine(),
1494                    &recipe.render,
1495                    (
1496                        recipe.component_context.clone(),
1497                        recipe.script_props.clone(),
1498                    ),
1499                )
1500                .map_err(RuntimeError::Evaluate)?;
1501            register_component_event_callbacks(
1502                &self.component_render,
1503                &recipe.path,
1504                &recipe.caller_context,
1505                recipe.event_callbacks.clone(),
1506                &recipe.context,
1507            )
1508            .map_err(RuntimeError::Evaluate)?;
1509            node = node.with_owned_part_styles(recipe.part_styles.clone());
1510            node =
1511                node.with_component_root_snapshot(recipe.path.clone(), recipe.snapshot.reference());
1512            node.bind_component_scope(
1513                &recipe.path,
1514                recipe.component_context.component_incarnation(),
1515                &recipe.component_events,
1516                Some(&recipe.context),
1517            );
1518            node.bind_generation(recipe.generation);
1519            Ok(node)
1520        })();
1521        if result.is_err() {
1522            record_component_render_failure(&self.component_render, &recipe.path);
1523        }
1524        {
1525            let mut active = self.component_render.try_borrow_mut().map_err(|_| {
1526                RuntimeError::ComponentRuntime(
1527                    "component render stack is already borrowed".to_owned(),
1528                )
1529            })?;
1530            if let Some(active) = active.as_mut() {
1531                let environment = active.environment;
1532                if let Some(retained) = active.invocations.get_mut(&recipe.path) {
1533                    retained.environment = environment;
1534                    retained.reusable = recipe.component_context.component_render_is_reusable();
1535                    if let Ok(node) = &result {
1536                        retained.snapshot.update_if_active(node);
1537                    }
1538                }
1539            }
1540        }
1541        self.record_timing(
1542            ExecutionOperation::Render,
1543            recipe.component.as_str(),
1544            started,
1545            result.is_ok(),
1546        );
1547        self.finish_component_render(result.is_ok())?;
1548        result
1549    }
1550
1551    pub(crate) fn execution_checkpoint(&self) -> RuntimeEngineCheckpoint {
1552        RuntimeEngineCheckpoint {
1553            generation: self.generation,
1554            evaluation_generation: self.evaluation_generation.get(),
1555            component_invocations: self.component_invocations.clone(),
1556            component_effects: self.component_effects.clone(),
1557            component_timers: self.component_timers.clone(),
1558            component_signals: self.component_signals.clone(),
1559            component_element_refs: self.component_element_refs.clone(),
1560            pending_component_commits: self.pending_component_commits.clone(),
1561            virtual_collections: self.virtual_collections.clone(),
1562            component_snapshots: self
1563                .component_invocations
1564                .values()
1565                .map(|recipe| (recipe.snapshot.clone(), recipe.snapshot.current()))
1566                .collect(),
1567        }
1568    }
1569
1570    pub(crate) fn restore_execution_checkpoint(&mut self, checkpoint: RuntimeEngineCheckpoint) {
1571        for (snapshot, value) in &checkpoint.component_snapshots {
1572            snapshot.restore(value.clone());
1573        }
1574        self.generation = checkpoint.generation;
1575        self.evaluation_generation
1576            .set(checkpoint.evaluation_generation);
1577        self.component_invocations = checkpoint.component_invocations;
1578        self.component_effects = checkpoint.component_effects;
1579        self.component_timers = checkpoint.component_timers;
1580        self.component_signals = checkpoint.component_signals;
1581        self.component_element_refs = checkpoint.component_element_refs;
1582        self.pending_component_commits = checkpoint.pending_component_commits;
1583        self.virtual_collections = checkpoint.virtual_collections;
1584    }
1585
1586    pub(crate) fn commit_component_renders(
1587        &mut self,
1588        runtime: &mut UiRuntimeState,
1589    ) -> Result<(), RuntimeError> {
1590        let commits = std::mem::take(&mut self.pending_component_commits);
1591        if commits.is_empty() {
1592            return Ok(());
1593        }
1594        // One batch has one final invocation graph. Intermediate ancestor
1595        // manifests must not retire descendants prepared by later targets.
1596        let mut active = self
1597            .component_invocations
1598            .keys()
1599            .cloned()
1600            .collect::<BTreeSet<_>>();
1601        active.extend(
1602            self.virtual_collections
1603                .keys()
1604                .map(|id| id.component.child("VirtualCollection", id.key.clone())),
1605        );
1606        active.extend(
1607            commits
1608                .values()
1609                .filter_map(|commit| commit.retained_root.clone()),
1610        );
1611        let roots = crate::state::topmost_paths(&commits.keys().cloned().collect());
1612        let previous = commits
1613            .values()
1614            .flat_map(|commit| commit.previous.iter().cloned())
1615            .collect();
1616        let mut transactions = Vec::with_capacity(commits.len());
1617        for (_, commit) in commits {
1618            runtime.replace_component_event_handlers(&commit.root, commit.event_handlers);
1619            transactions.push(commit.transaction);
1620        }
1621        runtime
1622            .component_state
1623            .commit_render_batch(transactions, &active);
1624        for root in roots {
1625            runtime
1626                .reconcile_component_lifetimes(&root, &active, &previous)
1627                .map_err(|error| RuntimeError::ComponentRuntime(error.to_string()))?;
1628        }
1629        Ok(())
1630    }
1631
1632    pub(crate) fn component_effects_in_scope(
1633        &self,
1634        root: &ComponentInstancePath,
1635    ) -> BTreeMap<crate::EffectId, crate::EffectDescriptor> {
1636        self.component_effects
1637            .iter()
1638            .filter(|(id, _)| id.component().is_within(root))
1639            .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
1640            .collect()
1641    }
1642
1643    pub(crate) fn component_signals_in_scope(
1644        &self,
1645        root: &ComponentInstancePath,
1646    ) -> BTreeMap<crate::SignalId, crate::signal::SignalDescriptor> {
1647        self.component_signals
1648            .iter()
1649            .filter(|(id, _)| id.component().is_within(root))
1650            .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
1651            .collect()
1652    }
1653
1654    pub(crate) fn component_timers_in_scope(
1655        &self,
1656        root: &ComponentInstancePath,
1657    ) -> BTreeMap<crate::TimerId, crate::TimerDescriptor> {
1658        self.component_timers
1659            .iter()
1660            .filter(|(id, _)| id.component().is_within(root))
1661            .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
1662            .collect()
1663    }
1664
1665    pub(crate) fn component_element_refs_in_scope(
1666        &self,
1667        root: &ComponentInstancePath,
1668    ) -> BTreeSet<crate::ElementRefId> {
1669        self.component_element_refs
1670            .iter()
1671            .filter(|id| id.component().is_within(root))
1672            .cloned()
1673            .collect()
1674    }
1675
1676    pub(crate) fn virtual_collection_ids_in_scope(
1677        &self,
1678        root: &ComponentInstancePath,
1679    ) -> BTreeSet<crate::VirtualCollectionId> {
1680        self.virtual_collections
1681            .keys()
1682            .filter(|id| id.component.is_within(root))
1683            .cloned()
1684            .collect()
1685    }
1686
1687    pub(crate) fn realize_virtual_collection(
1688        &mut self,
1689        id: &crate::VirtualCollectionId,
1690        indices: &BTreeSet<usize>,
1691        previous: &BTreeMap<usize, UiNode>,
1692    ) -> Result<BTreeMap<usize, UiNode>, RuntimeError> {
1693        let recipe = self.virtual_collections.get(id).cloned().ok_or_else(|| {
1694            RuntimeError::ComponentRuntime(format!(
1695                "virtual collection `{}` is not retained in the active generation",
1696                id.key
1697            ))
1698        })?;
1699        if recipe.generation != self.generation || recipe.id != *id {
1700            return Err(RuntimeError::StaleCallback {
1701                name: recipe.renderer.fn_name().to_owned(),
1702                callback_generation: recipe.generation,
1703                current_generation: self.generation,
1704            });
1705        }
1706        let batched = batched_indices(indices, previous, recipe.batch_items, recipe.data.len());
1707        if batched == *indices {
1708            return self.realize_virtual_items(&recipe, indices, previous);
1709        }
1710        // The items rendered ahead are a bonus: when one of them fails, the realization
1711        // renders only the requested ones, and the failure it recovered from stays out of
1712        // the reports. A failing requested item still fails it.
1713        let failures = (
1714            self.last_failed_timing.borrow().clone(),
1715            self.last_failed_component.borrow().clone(),
1716        );
1717        self.realize_virtual_items(&recipe, &batched, previous)
1718            .or_else(|_| {
1719                let result = self.realize_virtual_items(&recipe, indices, previous);
1720                if result.is_ok() {
1721                    *self.last_failed_timing.borrow_mut() = failures.0;
1722                    *self.last_failed_component.borrow_mut() = failures.1;
1723                }
1724                result
1725            })
1726    }
1727
1728    /// Realize exactly `indices` of `recipe`'s collection, reusing what `previous` and
1729    /// the kept items have and rendering the rest.
1730    fn realize_virtual_items(
1731        &mut self,
1732        recipe: &VirtualCollectionRecipe,
1733        indices: &BTreeSet<usize>,
1734        previous: &BTreeMap<usize, UiNode>,
1735    ) -> Result<BTreeMap<usize, UiNode>, RuntimeError> {
1736        let id = &recipe.id;
1737        let scope = id.component.child("VirtualCollection", id.key.clone());
1738        let context = recipe
1739            .context
1740            .for_structural_scope(scope, BTreeMap::new())
1741            .with_generation(recipe.generation);
1742        let (retained, plan, contributing) = self.reuse_kept_items(recipe, indices, previous);
1743        let previous_root = Rc::new(UiNode::box_node(plan));
1744        prune_virtual_read_contributions(
1745            &context,
1746            id,
1747            &recipe.data,
1748            &contributing,
1749            &previous_root,
1750        )?;
1751        self.begin_component_render(
1752            context.clone(),
1753            recipe.generation,
1754            None,
1755            Some(ComponentReusePlan::new(previous_root, BTreeSet::new())),
1756        )?;
1757        retain_virtual_component_manifest(&self.component_render)?;
1758        let result = (|| {
1759            let mut realized = retained;
1760            let missing = indices
1761                .iter()
1762                .copied()
1763                .filter(|index| *index < recipe.data.len() && !realized.contains_key(index))
1764                .collect::<Vec<_>>();
1765            for index in missing {
1766                let item = recipe
1767                    .data
1768                    .item(index)
1769                    .map_err(|error| RuntimeError::ComponentRuntime(error.to_string()))?
1770                    .ok_or_else(|| {
1771                        RuntimeError::ComponentRuntime(format!(
1772                            "virtual collection item {index} disappeared"
1773                        ))
1774                    })?;
1775                let (key, mut payload) =
1776                    collection_payload(&item, index).map_err(RuntimeError::Evaluate)?;
1777                add_collection_neighbors(&recipe.data, index, &mut payload);
1778                let invocation = &recipe.renderer_context;
1779                self.align_execution_session_to(invocation.operation_base());
1780                let started = self.begin_timing();
1781                let item_context = virtual_item_context(&context, id, &key);
1782                enter_virtual_collection_scope(&self.component_render, item_context.clone())
1783                    .map_err(RuntimeError::Evaluate)?;
1784                let item = invocation.call::<UiNode>(
1785                    self.engine(),
1786                    &recipe.renderer,
1787                    (item_context, Dynamic::from_map(payload)),
1788                );
1789                leave_component_render(&self.component_render).map_err(RuntimeError::Evaluate)?;
1790                self.record_timing(
1791                    ExecutionOperation::VirtualCollection(id.key.clone()),
1792                    id.key.as_str(),
1793                    started,
1794                    item.is_ok(),
1795                );
1796                let mut node = item.map_err(RuntimeError::Evaluate)?.with_key(key);
1797                node.bind_generation(recipe.generation);
1798                node.bind_component_scope(
1799                    recipe.context.callback_component_path(),
1800                    recipe.context.callback_component_incarnation(),
1801                    recipe.context.callback_event_schemas(),
1802                    Some(&recipe.renderer_context),
1803                );
1804                realized.insert(index, node);
1805            }
1806            Ok(realized)
1807        })();
1808        if result.is_err() {
1809            record_component_render_failure(&self.component_render, context.component_path());
1810        }
1811        self.finish_component_render(result.is_ok())?;
1812        result
1813    }
1814
1815    /// Move the items leaving the realized range to the recipe's kept items and take back
1816    /// the kept items `indices` needs. Returns the items that need no render, the nodes
1817    /// the reuse plan keeps alive (those and every kept item) and the indices whose read
1818    /// dependencies stay.
1819    fn reuse_kept_items(
1820        &self,
1821        recipe: &VirtualCollectionRecipe,
1822        indices: &BTreeSet<usize>,
1823        previous: &BTreeMap<usize, UiNode>,
1824    ) -> (BTreeMap<usize, UiNode>, Vec<UiNode>, BTreeSet<usize>) {
1825        let mut retained = previous
1826            .iter()
1827            .filter(|(index, _)| indices.contains(index))
1828            .map(|(index, node)| (*index, node.clone()))
1829            .collect::<BTreeMap<_, _>>();
1830        let mut offscreen = recipe.offscreen.borrow_mut();
1831        // A failed realization rolls the items back but not what it kept: an item that is
1832        // realized again has no kept copy.
1833        for index in previous.keys() {
1834            offscreen.take(*index);
1835        }
1836        // Items leaving the realized range are kept, unless a component inside one owns an
1837        // effect, a timer or a signal: that item is released, so its work stops as before.
1838        for (index, node) in previous
1839            .iter()
1840            .filter(|(index, _)| !indices.contains(index))
1841        {
1842            let owns_work = recipe
1843                .data
1844                .key(*index)
1845                .is_some_and(|key| self.virtual_item_owns_work(&recipe.id, key));
1846            if !owns_work {
1847                offscreen.keep(*index, node.clone());
1848            }
1849        }
1850        // Kept items come back without running the renderer.
1851        let unrendered = indices
1852            .iter()
1853            .copied()
1854            .filter(|index| !retained.contains_key(index))
1855            .collect::<Vec<_>>();
1856        for index in unrendered {
1857            if let Some(node) = offscreen.take(index)
1858                && node.key().map(crate::NodeKey::as_str) == recipe.data.key(index)
1859            {
1860                retained.insert(index, node);
1861            }
1862        }
1863        // Kept items stay in the reuse plan and keep their read dependencies, so the
1864        // components inside them live on until they come back or are dropped, and a change
1865        // they read renders the collection again, which drops them.
1866        let mut contributing = indices.clone();
1867        contributing.extend(offscreen.items.keys().copied());
1868        let mut plan = retained.values().cloned().collect::<Vec<_>>();
1869        plan.extend(offscreen.items.values().cloned());
1870        (retained, plan, contributing)
1871    }
1872
1873    /// The read contributions of the items the virtual collections in `scope` keep. They
1874    /// stay with the committed items' contributions, so a change a kept item read renders
1875    /// its collection again, which drops it.
1876    pub(crate) fn kept_virtual_read_contributions(
1877        &self,
1878        scope: &ComponentInstancePath,
1879    ) -> BTreeSet<crate::read_dependency::ReadContribution> {
1880        let mut active = BTreeSet::new();
1881        for recipe in self
1882            .virtual_collections
1883            .values()
1884            .filter(|recipe| recipe.id.component.is_within(scope))
1885        {
1886            let kept = recipe.offscreen.borrow();
1887            for (index, node) in &kept.items {
1888                if let Some(key) = recipe.data.key(*index) {
1889                    active.insert(crate::read_dependency::ReadContribution::VirtualItem {
1890                        collection: recipe.id.clone(),
1891                        key: key.to_owned(),
1892                    });
1893                }
1894                active.extend(node.virtual_read_contributions());
1895            }
1896        }
1897        active
1898    }
1899
1900    /// Whether a formal component inside item `key` of collection `id` owns an
1901    /// effect, a timer or a signal.
1902    fn virtual_item_owns_work(&self, id: &crate::VirtualCollectionId, key: &str) -> bool {
1903        let item = id
1904            .component
1905            .child("VirtualCollection", id.key.clone())
1906            .child("Item", key);
1907        self.component_effects
1908            .keys()
1909            .any(|effect| effect.component().is_within(&item))
1910            || self
1911                .component_timers
1912                .keys()
1913                .any(|timer| timer.component().is_within(&item))
1914            || self
1915                .component_signals
1916                .keys()
1917                .any(|signal| signal.component().is_within(&item))
1918    }
1919
1920    pub(crate) fn update_virtual_collection_snapshot(
1921        &mut self,
1922        id: &crate::VirtualCollectionId,
1923        items: &BTreeMap<usize, UiNode>,
1924    ) {
1925        // Structural collection scopes are not executable component owners.
1926        // Update every containing invocation snapshot so a later parent bailout
1927        // cannot resurrect an older realized window (including nested lists).
1928        let mut path = Some(id.component.clone());
1929        while let Some(current_path) = path {
1930            if let Some(owner) = self.component_invocations.get_mut(&current_path)
1931                && let Some(current) = owner.snapshot.current()
1932                && current.virtual_collection_spec(id).is_some()
1933            {
1934                let mut rendered = current.as_ref().clone();
1935                rendered.replace_virtual_collection_items(id, items.clone());
1936                owner.snapshot.replace_if_active(Rc::new(rendered));
1937            }
1938            path = current_path.parent();
1939        }
1940    }
1941
1942    /// Invoke an optional one-argument lifecycle function.
1943    ///
1944    /// # Errors
1945    ///
1946    /// Returns [`RuntimeError::Evaluate`] when the function exists but fails.
1947    pub fn call_optional_lifecycle(
1948        &self,
1949        compiled: &CompiledUi,
1950        function: &str,
1951        context: UiContext,
1952    ) -> Result<bool, RuntimeError> {
1953        if !compiled.has_function(function, 1) {
1954            return Ok(false);
1955        }
1956        self.evaluation_generation.set(compiled.generation);
1957        self.begin_execution_session();
1958        let started = self.begin_timing();
1959        let result = AstInterpreter::call_fn::<Dynamic, _>(
1960            &self.engine,
1961            &compiled.ast,
1962            &mut Scope::new(),
1963            function,
1964            (context,),
1965        );
1966        self.record_timing(
1967            ExecutionOperation::Lifecycle(function.to_owned()),
1968            compiled.ast.source().unwrap_or("<script>"),
1969            started,
1970            result.is_ok(),
1971        );
1972        let _ = result.map_err(RuntimeError::Evaluate)?;
1973        Ok(true)
1974    }
1975
1976    pub(crate) fn call_optional_lifecycle_with_value(
1977        &self,
1978        compiled: &CompiledUi,
1979        function: &str,
1980        context: UiContext,
1981        value: UiValue,
1982    ) -> Result<bool, RuntimeError> {
1983        if !compiled.has_function(function, 2) {
1984            return Ok(false);
1985        }
1986        self.evaluation_generation.set(compiled.generation);
1987        self.begin_execution_session();
1988        let started = self.begin_timing();
1989        let result = AstInterpreter::call_fn::<Dynamic, _>(
1990            &self.engine,
1991            &compiled.ast,
1992            &mut Scope::new(),
1993            function,
1994            (context, value.into_dynamic()),
1995        );
1996        self.record_timing(
1997            ExecutionOperation::Lifecycle(function.to_owned()),
1998            compiled.ast.source().unwrap_or("<script>"),
1999            started,
2000            result.is_ok(),
2001        );
2002        let _ = result.map_err(RuntimeError::Evaluate)?;
2003        Ok(true)
2004    }
2005
2006    /// Decode optional root `state_schema()` from an application entry.
2007    ///
2008    /// # Errors
2009    ///
2010    /// Returns [`RuntimeError::Evaluate`] when the function fails or cannot be
2011    /// decoded as [`ComponentStateSchema`].
2012    pub fn root_state_schema(
2013        &self,
2014        compiled: &CompiledUi,
2015    ) -> Result<ComponentStateSchema, RuntimeError> {
2016        if !compiled.has_function("state_schema", 0) {
2017            return Ok(ComponentStateSchema::default());
2018        }
2019        self.begin_execution_session();
2020        let started = self.begin_timing();
2021        let result = (|| {
2022            let raw: Dynamic = self
2023                .engine
2024                .call_fn(&mut Scope::new(), &compiled.ast, "state_schema", ())
2025                .map_err(RuntimeError::Evaluate)?;
2026            let raw =
2027                normalize_state_defaults(raw, "state_schema").map_err(RuntimeError::Evaluate)?;
2028            rhai::serde::from_dynamic(&raw).map_err(RuntimeError::Evaluate)
2029        })();
2030        self.record_timing(
2031            ExecutionOperation::Lifecycle("state_schema".to_owned()),
2032            compiled.ast.source().unwrap_or("<script>"),
2033            started,
2034            result.is_ok(),
2035        );
2036        result
2037    }
2038
2039    /// Create a generation-bound callback for a script function.
2040    ///
2041    /// # Errors
2042    ///
2043    /// Returns [`RuntimeError::CallbackDefinition`] when the function name is
2044    /// not a valid Rhai function pointer name.
2045    pub fn callback(
2046        &self,
2047        compiled: &CompiledUi,
2048        function_name: &str,
2049    ) -> Result<ScriptCallback, RuntimeError> {
2050        let function =
2051            FnPtr::new(function_name).map_err(|source| RuntimeError::CallbackDefinition {
2052                name: function_name.to_owned(),
2053                source,
2054            })?;
2055        ScriptCallback::try_from_fn_ptr(function, compiled.generation).map_err(|source| {
2056            RuntimeError::RetainedCallback {
2057                name: function_name.to_owned(),
2058                source,
2059            }
2060        })
2061    }
2062
2063    /// Invoke a callback only when it belongs to the current compiled generation.
2064    ///
2065    /// # Errors
2066    ///
2067    /// Returns [`RuntimeError::StaleCallback`] for obsolete callbacks and
2068    /// [`RuntimeError::Evaluate`] when the Rhai function fails.
2069    pub fn invoke_callback(
2070        &self,
2071        compiled: &CompiledUi,
2072        callback: &ScriptCallback,
2073        args: impl FuncArgs,
2074    ) -> Result<Dynamic, RuntimeError> {
2075        if !self.is_current(callback.generation) || callback.generation != compiled.generation {
2076            return Err(RuntimeError::StaleCallback {
2077                name: callback.name().to_owned(),
2078                callback_generation: callback.generation,
2079                current_generation: self.generation,
2080            });
2081        }
2082
2083        self.invoke_callback_for_generation(compiled, callback, args)
2084    }
2085
2086    pub(crate) fn invoke_callback_for_generation(
2087        &self,
2088        compiled: &CompiledUi,
2089        callback: &ScriptCallback,
2090        args: impl FuncArgs,
2091    ) -> Result<Dynamic, RuntimeError> {
2092        if callback.generation != compiled.generation {
2093            return Err(RuntimeError::StaleCallback {
2094                name: callback.name().to_owned(),
2095                callback_generation: callback.generation,
2096                current_generation: compiled.generation,
2097            });
2098        }
2099        self.evaluation_generation.set(compiled.generation);
2100        let operation_base = callback.native_context.as_ref().map_or(
2101            0,
2102            crate::invocation::ScriptInvocationContext::operation_base,
2103        );
2104        self.begin_execution_session_from(operation_base);
2105        let started = self.begin_timing();
2106        #[allow(deprecated)]
2107        let result = if let Some(context) = callback.native_context.as_ref() {
2108            context.call(self.engine(), &callback.function, args)
2109        } else {
2110            callback.function.call(self.engine(), &compiled.ast, args)
2111        };
2112        self.record_timing(
2113            ExecutionOperation::Callback(callback.name().to_owned()),
2114            compiled.ast.source().unwrap_or("<script>"),
2115            started,
2116            result.is_ok(),
2117        );
2118        result.map_err(RuntimeError::Evaluate)
2119    }
2120
2121    #[must_use]
2122    pub fn is_current(&self, generation: ScriptGeneration) -> bool {
2123        generation == self.generation
2124    }
2125
2126    #[must_use]
2127    pub fn engine(&self) -> &Engine {
2128        &self.engine
2129    }
2130
2131    /// The Rhai engine for [`crate::ScriptViewExtension::configure_rhai_engine`].
2132    pub(crate) fn engine_mut(&mut self) -> &mut Engine {
2133        &mut self.engine
2134    }
2135
2136    /// Generate the official Rhai language-server definition source for every
2137    /// function/type/module registered on this engine.
2138    ///
2139    /// Standard packages are omitted because the language server supplies them.
2140    #[must_use]
2141    pub fn definition_source(&self) -> String {
2142        // Parameter names, doc comments and readable return types come from the
2143        // script docs; Rhai's own printer is the fallback.
2144        crate::script_docs::ScriptApi::from_engine(&self.engine).map_or_else(
2145            |_| {
2146                self.engine
2147                    .definitions()
2148                    .include_standard_packages(false)
2149                    .single_file()
2150            },
2151            |api| api.definitions(),
2152        )
2153    }
2154
2155    /// Validate statically visible direct and method call arities in an entry
2156    /// script and its installed modules.
2157    ///
2158    /// This complements real lifecycle execution because Rhai resolves
2159    /// functions dynamically and an initial render cannot cover every branch.
2160    /// The catalog comes from the same registered Engine metadata used by
2161    /// [`Self::definition_source`].
2162    ///
2163    /// # Errors
2164    ///
2165    /// Returns a metadata or parse error if the lint catalog cannot be built.
2166    pub fn lint_known_calls(
2167        &mut self,
2168        entry_name: &str,
2169        entry_source: &str,
2170        modules: &BTreeMap<ModuleId, String>,
2171    ) -> Result<Vec<crate::KnownCallDiagnostic>, crate::KnownCallLintError> {
2172        crate::script_lint::lint_known_calls(
2173            &mut self.engine,
2174            entry_name,
2175            entry_source,
2176            modules,
2177            &BTreeSet::new(),
2178        )
2179        .map(|(diagnostics, _)| diagnostics)
2180    }
2181
2182    /// [`Self::lint_known_calls`] for scripts that also call functions the
2183    /// Host registers on its own engine, such as the `[host]` declarations
2184    /// `gpui-rhai check` reads: calls to `host` count as known. Returns the
2185    /// diagnostics and the declared functions the sources call.
2186    ///
2187    /// # Errors
2188    ///
2189    /// Returns a metadata or parse error if the lint catalog cannot be built.
2190    pub fn lint_known_calls_with_host(
2191        &mut self,
2192        entry_name: &str,
2193        entry_source: &str,
2194        modules: &BTreeMap<ModuleId, String>,
2195        host: &BTreeSet<crate::HostFunction>,
2196    ) -> Result<
2197        (
2198            Vec<crate::KnownCallDiagnostic>,
2199            BTreeSet<crate::HostFunction>,
2200        ),
2201        crate::KnownCallLintError,
2202    > {
2203        crate::script_lint::lint_known_calls(
2204            &mut self.engine,
2205            entry_name,
2206            entry_source,
2207            modules,
2208            host,
2209        )
2210    }
2211
2212    /// List entry-script functions that replace a native function of the same
2213    /// name and arity. Rhai prefers the script function for every call,
2214    /// including method calls inside imported components, so a helper named
2215    /// like a built-in breaks code that never mentions it.
2216    ///
2217    /// # Errors
2218    ///
2219    /// Returns a metadata or parse error if the lint catalog cannot be built.
2220    pub fn lint_shadowed_builtins(
2221        &mut self,
2222        entry_name: &str,
2223        entry_source: &str,
2224    ) -> Result<Vec<crate::ShadowedBuiltin>, crate::KnownCallLintError> {
2225        crate::script_lint::lint_shadowed_builtins(&mut self.engine, entry_name, entry_source)
2226    }
2227
2228    /// Return a snapshot of components exported through this engine.
2229    ///
2230    /// # Errors
2231    ///
2232    /// Returns [`ComponentExportError`] if the export registry was poisoned by
2233    /// a prior panic.
2234    pub fn component_exports(&self) -> Result<ComponentRegistry, ComponentExportError> {
2235        self.component_exports.snapshot()
2236    }
2237
2238    pub fn component_invocations(
2239        &self,
2240    ) -> impl ExactSizeIterator<Item = &ComponentInvocationRecipe> {
2241        self.component_invocations.values()
2242    }
2243
2244    pub(crate) fn component_renderer_snapshot(
2245        &self,
2246    ) -> Result<BTreeMap<ModuleId, RegisteredComponentRender>, ComponentExportError> {
2247        self.component_renderers
2248            .try_borrow()
2249            .map(|renderers| renderers.clone())
2250            .map_err(|_| ComponentExportError::Borrowed)
2251    }
2252
2253    pub(crate) fn restore_component_renderers(
2254        &self,
2255        renderers: BTreeMap<ModuleId, RegisteredComponentRender>,
2256    ) -> Result<(), ComponentExportError> {
2257        *self
2258            .component_renderers
2259            .try_borrow_mut()
2260            .map_err(|_| ComponentExportError::Borrowed)? = renderers;
2261        Ok(())
2262    }
2263
2264    /// Clear component exports before evaluating a hot-reload candidate.
2265    ///
2266    /// # Errors
2267    ///
2268    /// Returns [`ComponentExportError`] if the collector is unavailable.
2269    pub fn clear_component_exports(&self) -> Result<(), ComponentExportError> {
2270        self.component_renderers
2271            .try_borrow_mut()
2272            .map_err(|_| ComponentExportError::Borrowed)?
2273            .clear();
2274        self.component_exports.clear()
2275    }
2276
2277    /// Restore a prior export snapshot after a rejected candidate.
2278    ///
2279    /// # Errors
2280    ///
2281    /// Returns [`ComponentExportError`] if the collector is unavailable.
2282    pub fn restore_component_exports(
2283        &self,
2284        registry: ComponentRegistry,
2285    ) -> Result<(), ComponentExportError> {
2286        self.component_exports.replace(registry)
2287    }
2288
2289    /// Register a namespaced Rust custom primitive and its Rhai constructor.
2290    ///
2291    /// # Errors
2292    ///
2293    /// Returns [`PrimitiveError`] when the descriptor conflicts or is invalid.
2294    pub fn register_primitive(
2295        &mut self,
2296        descriptor: PrimitiveDescriptor,
2297        handler: impl PrimitiveHandler + 'static,
2298    ) -> Result<(), PrimitiveError> {
2299        self.primitives.register(descriptor.clone(), handler)?;
2300
2301        let namespace = descriptor.id.namespace().to_owned();
2302        let export = descriptor.export.clone();
2303        let id = descriptor.id;
2304        let primitives = self.primitives.clone();
2305        let generation = Rc::clone(&self.evaluation_generation);
2306        let module = self.primitive_modules.entry(namespace.clone()).or_default();
2307        FuncRegistration::new(export).set_into_module(
2308            module,
2309            move |mut props: Map| -> Result<UiNode, Box<EvalAltResult>> {
2310                let key = props
2311                    .remove("key")
2312                    .map(|value| {
2313                        if value.is::<ImmutableString>() {
2314                            Ok(value.cast::<ImmutableString>().to_string())
2315                        } else {
2316                            Err(Box::new(EvalAltResult::ErrorRuntime(
2317                                "primitive key must be a string".into(),
2318                                Position::NONE,
2319                            )))
2320                        }
2321                    })
2322                    .transpose()?;
2323                primitives
2324                    .create_node(&id, key, &props, generation.get())
2325                    .map_err(|error| {
2326                        Box::new(EvalAltResult::ErrorRuntime(
2327                            error.to_string().into(),
2328                            Position::NONE,
2329                        ))
2330                    })
2331            },
2332        );
2333        self.engine
2334            .register_static_module(namespace, module.clone().into());
2335        Ok(())
2336    }
2337
2338    #[must_use]
2339    pub fn primitive_registry(&self) -> PrimitiveRegistry {
2340        self.primitives.clone()
2341    }
2342
2343    /// Register a trusted Rust handler attachable by Rhai through `native_handler`.
2344    ///
2345    /// # Errors
2346    ///
2347    /// Returns descriptor/duplicate registry errors.
2348    pub fn register_native_handler(
2349        &self,
2350        descriptor: crate::NativeHandlerDescriptor,
2351        handler: impl FnMut(
2352            crate::NativeEvent,
2353            &mut UiRuntimeState,
2354            &mut gpui::Window,
2355            &mut gpui::App,
2356        ) -> Result<crate::EventResponse, String>
2357        + 'static,
2358    ) -> Result<(), crate::NativeHandlerError> {
2359        self.native_handlers.register(descriptor, handler)
2360    }
2361
2362    #[must_use]
2363    pub fn native_handler_registry(&self) -> crate::NativeHandlerRegistry {
2364        self.native_handlers.clone()
2365    }
2366
2367    #[must_use]
2368    pub fn syntax_registry(&self) -> crate::SyntaxRegistry {
2369        self.syntax_registry.clone()
2370    }
2371
2372    #[must_use]
2373    pub fn document_runtime_config(&self) -> crate::DocumentRuntimeConfig {
2374        self.document_runtime.clone()
2375    }
2376
2377    /// The Host defaults for data-backed virtual collections.
2378    #[must_use]
2379    pub fn virtual_collection_policy(&self) -> crate::VirtualCollectionPolicy {
2380        self.virtual_collection_policy.get()
2381    }
2382
2383    /// Set the Host defaults for data-backed virtual collections, usually in
2384    /// `ScriptViewExtension::configure_engine`. A collection's own
2385    /// `overscan_items`, `batch_items` and `retain_items` take precedence. The
2386    /// policy applies from each collection's next render; values are clamped
2387    /// to their bounds.
2388    pub fn set_virtual_collection_policy(&self, policy: crate::VirtualCollectionPolicy) {
2389        self.virtual_collection_policy.set(policy.clamped());
2390    }
2391
2392    /// Register one trusted Rust chart transform.
2393    ///
2394    /// # Errors
2395    ///
2396    /// Returns an invalid or duplicate transform ID diagnostic.
2397    #[cfg(feature = "charts")]
2398    pub fn register_chart_transform(
2399        &self,
2400        id: impl Into<String>,
2401        transform: impl crate::HostChartTransform + 'static,
2402    ) -> Result<(), crate::ChartTransformError> {
2403        self.chart_transforms.register(id, transform)
2404    }
2405
2406    /// Register Host-owned GeoJSON/SVG geometry or typed map features.
2407    ///
2408    /// # Errors
2409    ///
2410    /// Returns an invalid or duplicate map diagnostic.
2411    #[cfg(feature = "charts")]
2412    pub fn register_chart_map(&self, map: crate::ChartGeoMap) -> Result<(), crate::ChartGeoError> {
2413        self.chart_geo.register_map(map)
2414    }
2415
2416    /// Register one trusted Rust geo projection.
2417    ///
2418    /// # Errors
2419    ///
2420    /// Returns an invalid or duplicate projection ID diagnostic.
2421    #[cfg(feature = "charts")]
2422    pub fn register_chart_projection(
2423        &self,
2424        id: impl Into<String>,
2425        projection: impl crate::ChartGeoProjection + 'static,
2426    ) -> Result<(), crate::ChartGeoError> {
2427        self.chart_geo.register_projection(id, projection)
2428    }
2429
2430    /// Register one trusted Rust custom chart series renderer.
2431    ///
2432    /// # Errors
2433    ///
2434    /// Returns an invalid or duplicate renderer ID diagnostic.
2435    #[cfg(feature = "charts")]
2436    pub fn register_chart_series(
2437        &self,
2438        id: impl Into<String>,
2439        renderer: impl crate::HostChartSeries + 'static,
2440    ) -> Result<(), crate::ChartSeriesExtensionError> {
2441        self.chart_series.register(id, renderer)
2442    }
2443
2444    /// Register one trusted Rust chart value formatter.
2445    ///
2446    /// # Errors
2447    ///
2448    /// Returns an invalid or duplicate formatter ID diagnostic.
2449    #[cfg(feature = "charts")]
2450    pub fn register_chart_formatter(
2451        &self,
2452        id: impl Into<String>,
2453        formatter: impl crate::HostChartFormatter + 'static,
2454    ) -> Result<(), crate::ChartFormatterError> {
2455        self.chart_formatters.register(id, formatter)
2456    }
2457
2458    #[cfg(feature = "charts")]
2459    #[must_use]
2460    pub fn chart_transform_registry(&self) -> crate::ChartTransformRegistry {
2461        self.chart_transforms.clone()
2462    }
2463
2464    #[cfg(feature = "charts")]
2465    #[must_use]
2466    pub fn chart_geo_registry(&self) -> crate::ChartGeoRegistry {
2467        self.chart_geo.clone()
2468    }
2469
2470    #[cfg(feature = "charts")]
2471    #[must_use]
2472    pub fn chart_series_registry(&self) -> crate::ChartSeriesRegistry {
2473        self.chart_series.clone()
2474    }
2475
2476    #[cfg(feature = "charts")]
2477    #[must_use]
2478    pub fn chart_formatter_registry(&self) -> crate::ChartFormatterRegistry {
2479        self.chart_formatters.clone()
2480    }
2481
2482    pub fn set_slow_threshold(&mut self, threshold: Duration) {
2483        self.slow_threshold = threshold;
2484    }
2485
2486    /// Set the per-execution script operation budget.
2487    ///
2488    /// The default is [`DEFAULT_SCRIPT_OPERATION_LIMIT`]. This is a cumulative
2489    /// operation quota for each execution round, not a frame-time guarantee.
2490    /// A host that runs known one-shot, cacheable
2491    /// script phases (a layout pass, an analysis sweep) may raise it; the
2492    /// wall-clock slow threshold still flags anything that stalls the
2493    /// foreground. Scripts cannot change this limit; only the embedding
2494    /// application can.
2495    /// Zero normalizes to one; it never disables protection. Changes apply to
2496    /// subsequent calls. Native Rust work is not preempted by this quota.
2497    pub fn set_operation_limit(&mut self, limit: u64) {
2498        self.operation_limit.set(limit.max(1));
2499    }
2500
2501    /// The per-execution script operation budget in force.
2502    #[must_use]
2503    pub fn operation_limit(&self) -> u64 {
2504        self.operation_limit.get()
2505    }
2506
2507    /// Configure parser depth independently of execution/recursion/data limits.
2508    /// Defaults are global=64/function=64 in both debug and release. Zero
2509    /// normalizes to one rather than adopting Rhai's unlimited convention.
2510    pub fn set_expression_depth_limits(&mut self, global: usize, functions: usize) {
2511        self.engine
2512            .set_max_expr_depths(global.max(1), functions.max(1));
2513    }
2514
2515    #[must_use]
2516    pub fn expression_depth_limits(&self) -> (usize, usize) {
2517        (
2518            self.engine.max_expr_depth(),
2519            self.engine.max_function_expr_depth(),
2520        )
2521    }
2522
2523    #[must_use]
2524    pub fn take_timings(&self) -> Vec<ExecutionTiming> {
2525        std::mem::take(&mut *self.timings.borrow_mut())
2526    }
2527
2528    /// Return the failed timing from the current execution session, if any.
2529    /// Starting the next compile, render, callback, or lifecycle call clears it.
2530    #[must_use]
2531    pub fn last_failed_timing(&self) -> Option<ExecutionTiming> {
2532        self.last_failed_timing.borrow().clone()
2533    }
2534
2535    #[must_use]
2536    pub(crate) fn last_failed_component(&self) -> Option<ComponentInstancePath> {
2537        self.last_failed_component.borrow().clone()
2538    }
2539
2540    fn record_timing(
2541        &self,
2542        operation: ExecutionOperation,
2543        source: &str,
2544        started: ExecutionTimingStart,
2545        succeeded: bool,
2546    ) {
2547        let duration = started.instant.elapsed();
2548        let operations = self.operation_total().saturating_sub(started.operations);
2549        let timing = ExecutionTiming {
2550            operation,
2551            source: source.to_owned(),
2552            duration,
2553            operations,
2554            operation_limit: started.operation_limit,
2555            round_operations: self.operation_total(),
2556            operation_semantics: OPERATION_SEMANTICS_VERSION,
2557            slow: duration >= self.slow_threshold,
2558            succeeded,
2559        };
2560        if !succeeded {
2561            *self.last_failed_timing.borrow_mut() = Some(timing.clone());
2562        }
2563        self.timings.borrow_mut().push(timing);
2564    }
2565
2566    pub(crate) fn begin_execution_session(&self) {
2567        self.begin_execution_session_from(0);
2568    }
2569
2570    fn begin_execution_session_from(&self, inherited_base: u64) {
2571        self.last_failed_timing.borrow_mut().take();
2572        self.last_failed_component.borrow_mut().take();
2573        self.operation_tracker.begin(inherited_base);
2574    }
2575
2576    fn align_execution_session_to(&self, inherited_base: u64) {
2577        self.operation_tracker.align(inherited_base);
2578    }
2579
2580    fn operation_total(&self) -> u64 {
2581        self.operation_tracker.total.get()
2582    }
2583
2584    fn begin_timing(&self) -> ExecutionTimingStart {
2585        ExecutionTimingStart {
2586            instant: Instant::now(),
2587            operations: self.operation_total(),
2588            operation_limit: self.operation_limit(),
2589        }
2590    }
2591
2592    fn candidate_generation(&mut self) -> ScriptGeneration {
2593        self.preparation_generation
2594            .unwrap_or_else(Self::allocate_generation)
2595    }
2596
2597    fn allocate_generation() -> ScriptGeneration {
2598        static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
2599        ScriptGeneration(NEXT_GENERATION.fetch_add(1, Ordering::Relaxed))
2600    }
2601}
2602
2603pub(crate) fn validate_runtime_ast(ast: &AST) -> Result<(), RuntimeError> {
2604    if ast
2605        .iter_functions()
2606        .any(|function| function.name == crate::invocation::NAMED_FUNCTION)
2607    {
2608        return Err(RuntimeError::Compile(Box::new(component_render_error(
2609            "`named_function` is reserved by the SDK's lexical Fn constructor",
2610        ))));
2611    }
2612    let mut invalid = None;
2613    ast.walk(&mut |path| {
2614        let Some(ASTNode::Stmt(Stmt::Assignment(assignment))) = path.last() else {
2615            return true;
2616        };
2617        if !matches!(
2618            assignment.1.lhs,
2619            Expr::ThisPtr(_) | Expr::Variable(..) | Expr::Index(..) | Expr::Dot(..)
2620        ) {
2621            invalid = Some(assignment.1.lhs.position());
2622            return false;
2623        }
2624        true
2625    });
2626    invalid.map_or(Ok(()), |position| {
2627        Err(RuntimeError::InvalidAssignmentTarget(position))
2628    })
2629}
2630
2631fn validate_literal_imports(ast: &AST) -> Result<(), RuntimeError> {
2632    let mut dynamic = None;
2633    ast.walk(&mut |path| {
2634        let Some(ASTNode::Stmt(Stmt::Import(import, position))) = path.last() else {
2635            return true;
2636        };
2637        if matches!(import.0, Expr::StringConstant(..)) {
2638            true
2639        } else {
2640            dynamic = Some(*position);
2641            false
2642        }
2643    });
2644    dynamic.map_or(Ok(()), |position| {
2645        Err(RuntimeError::Import(format!(
2646            "Rhai imports must use a literal module string at {position}"
2647        )))
2648    })
2649}
2650
2651fn register_node_apis(engine: &mut Engine) {
2652    // A caller-written shortcut as `#{ label, keystrokes, chords }`, formatted
2653    // like a bound action's (`cmd-p` is `⌘P` on macOS); a legend stays as is.
2654    FuncRegistration::new("key_shortcut")
2655        .in_global_namespace()
2656        .register_into_engine(engine, |text: ImmutableString| {
2657            crate::ActionShortcut::from_text(text.as_str())
2658                .to_ui_value()
2659                .into_dynamic()
2660        });
2661    FuncRegistration::new("text")
2662        .in_global_namespace()
2663        .register_into_engine(engine, text_node);
2664    FuncRegistration::new("text")
2665        .in_global_namespace()
2666        .register_into_engine(engine, rich_text_node);
2667    FuncRegistration::new("span")
2668        .in_global_namespace()
2669        .register_into_engine(engine, span_value);
2670    FuncRegistration::new("canvas")
2671        .in_global_namespace()
2672        .register_into_engine(engine, canvas_node);
2673    FuncRegistration::new("svg")
2674        .in_global_namespace()
2675        .register_into_engine(engine, svg_node);
2676    FuncRegistration::new("box")
2677        .in_global_namespace()
2678        .register_into_engine(engine, box_node);
2679    FuncRegistration::new("fragment")
2680        .in_global_namespace()
2681        .register_into_engine(engine, fragment_node);
2682    FuncRegistration::new("motion_group")
2683        .in_global_namespace()
2684        .register_into_engine(engine, motion_group_node);
2685    FuncRegistration::new("stack")
2686        .in_global_namespace()
2687        .register_into_engine(engine, stack_node);
2688    FuncRegistration::new("handled")
2689        .in_global_namespace()
2690        .register_into_engine(engine, || crate::EventResponse::new().stop());
2691    FuncRegistration::new("propagate")
2692        .in_global_namespace()
2693        .register_into_engine(engine, crate::EventResponse::new);
2694    FuncRegistration::new("event_response")
2695        .in_global_namespace()
2696        .register_into_engine(engine, crate::EventResponse::new);
2697    FuncRegistration::new("column")
2698        .in_global_namespace()
2699        .register_into_engine(engine, column_node);
2700    FuncRegistration::new("row")
2701        .in_global_namespace()
2702        .register_into_engine(engine, row_node);
2703    FuncRegistration::new("error_boundary")
2704        .in_global_namespace()
2705        .register_into_engine(engine, error_boundary_node);
2706    FuncRegistration::new("error_boundary_lazy")
2707        .in_global_namespace()
2708        .register_into_engine(engine, lazy_error_boundary_node);
2709    FuncRegistration::new("asset")
2710        .in_global_namespace()
2711        .register_into_engine(engine, asset_id_from_script);
2712    FuncRegistration::new("image")
2713        .in_global_namespace()
2714        .register_into_engine(engine, image_node);
2715    FuncRegistration::new("image")
2716        .in_global_namespace()
2717        .register_into_engine(engine, asset_image_node);
2718    FuncRegistration::new("directional_image")
2719        .in_global_namespace()
2720        .register_into_engine(engine, directional_image_node);
2721    FuncRegistration::new("directional_image")
2722        .in_global_namespace()
2723        .register_into_engine(engine, directional_asset_image_node);
2724    FuncRegistration::new("image_source")
2725        .in_global_namespace()
2726        .register_into_engine(engine, generic_image_node);
2727    FuncRegistration::new("directional_image_source")
2728        .in_global_namespace()
2729        .register_into_engine(engine, generic_directional_image_node);
2730    FuncRegistration::new("overlay")
2731        .in_global_namespace()
2732        .register_into_engine(engine, overlay_node);
2733    FuncRegistration::new("layer")
2734        .in_global_namespace()
2735        .register_into_engine(engine, layer_node);
2736}
2737
2738fn register_native_handler_api(engine: &mut Engine, registry: &crate::NativeHandlerRegistry) {
2739    let registry = registry.clone();
2740    FuncRegistration::new("native_handler")
2741        .in_global_namespace()
2742        .register_into_engine(
2743            engine,
2744            move |id: ImmutableString| -> Result<crate::NativeHandlerRef, Box<EvalAltResult>> {
2745                let id = crate::NativeHandlerId::parse(id.to_string())
2746                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
2747                registry
2748                    .resolve(&id)
2749                    .map_err(|error| Box::new(component_render_error(error.to_string())))
2750            },
2751        );
2752}
2753
2754pub(crate) const RHAI_MAX_ARRAY_SIZE: usize = 10_000;
2755pub(crate) const RHAI_MAX_MAP_SIZE: usize = 100_000;
2756pub(crate) const RHAI_MAX_STRING_SIZE: usize = 1_048_576;
2757pub(crate) const RHAI_MAX_DATA_DEPTH: usize = 64;
2758
2759/// The parser's expression depth at the top level and inside a function. A
2760/// builder-style style chain in a node in a closure costs a level per call, so
2761/// 32 in a function rejected ordinary view code; 64 still stays clear of the
2762/// main thread's stack, where scripts compile and run.
2763pub(crate) const EXPRESSION_DEPTHS: (usize, usize) = (64, 64);
2764
2765/// Rhai reports a keyword where a name belongs as a missing name: `import
2766/// "components/switch" as switch;` fails with "Expecting name of a variable".
2767/// Say which keyword it was instead.
2768pub(crate) fn explain_keyword_name(source: &str, error: rhai::ParseError) -> rhai::ParseError {
2769    let rhai::ParseError(kind, position) = &error;
2770    let (Some(line), Some(column)) = (position.line(), position.position()) else {
2771        return error;
2772    };
2773    let word: String = source
2774        .lines()
2775        .nth(line - 1)
2776        .unwrap_or_default()
2777        .chars()
2778        .skip(column - 1)
2779        .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_')
2780        .collect();
2781    // `word` holds only identifier characters, so any token it spells is a keyword.
2782    if rhai::Token::lookup_symbol_from_syntax(&word).is_none() {
2783        return error;
2784    }
2785    let misuse = match &**kind {
2786        rhai::ParseErrorType::VariableExpected => "name a variable or an import alias".to_owned(),
2787        rhai::ParseErrorType::FnMissingName => "name a function".to_owned(),
2788        rhai::ParseErrorType::PropertyExpected => {
2789            format!("name a property; index it as `[\"{word}\"]`")
2790        }
2791        rhai::ParseErrorType::MissingToken(token, description)
2792            if token == "}" && description.contains("object map literal") =>
2793        {
2794            format!("be a bare map key; quote it as `\"{word}\"`")
2795        }
2796        _ => return error,
2797    };
2798    let message = format!("`{word}` is a Rhai keyword and cannot {misuse}");
2799    rhai::ParseError(
2800        Box::new(rhai::ParseErrorType::BadInput(
2801            rhai::LexError::ImproperSymbol(word, message),
2802        )),
2803        *position,
2804    )
2805}
2806
2807fn configure_engine_limits(engine: &mut Engine) {
2808    crate::invocation::register_named_functions(engine);
2809    engine.set_max_call_levels(64);
2810    // Explicit defaults avoid Rhai's profile-dependent parser defaults. A
2811    // trusted Host may configure these separately; ordinary applications do
2812    // not inherit another application's deeper expression policy.
2813    engine.set_max_expr_depths(EXPRESSION_DEPTHS.0, EXPRESSION_DEPTHS.1);
2814    // Rhai's counter is evaluator-local and cloned into stored callback
2815    // contexts. The runtime's progress adapter enforces one cumulative budget
2816    // across nested evaluators and starts delayed callbacks with fresh quota.
2817    engine.set_max_operations(0);
2818    engine.set_max_array_size(RHAI_MAX_ARRAY_SIZE);
2819    engine.set_max_map_size(RHAI_MAX_MAP_SIZE);
2820    engine.set_max_string_size(RHAI_MAX_STRING_SIZE);
2821}
2822
2823fn register_define_component_api(
2824    engine: &mut Engine,
2825    exports: &ComponentExportCollector,
2826    renderers: &ComponentRenderRegistry,
2827    generation: &Rc<Cell<ScriptGeneration>>,
2828) {
2829    let exports = exports.clone();
2830    let renderers = Rc::clone(renderers);
2831    let generation = Rc::clone(generation);
2832    FuncRegistration::new("define_component")
2833        .in_global_namespace()
2834        .register_into_engine(
2835            engine,
2836            move |mut raw: Map| -> Result<(), Box<EvalAltResult>> {
2837                let render = raw.remove("render").ok_or_else(|| {
2838                    Box::new(component_render_error(
2839                        "define_component requires a named `render` function",
2840                    ))
2841                })?;
2842                if !render.is::<FnPtr>() {
2843                    return Err(Box::new(component_render_error(
2844                        "define_component `render` must be a function pointer",
2845                    )));
2846                }
2847                let mut render = render.cast::<FnPtr>();
2848                crate::invocation::take_function_environment(&mut render);
2849                if render.is_anonymous() || render.is_curried() {
2850                    return Err(Box::new(component_render_error(
2851                        "formal component render must be an uncurried named function",
2852                    )));
2853                }
2854                if let Some(schema) = raw.get_mut("schema")
2855                    && schema.is::<Map>()
2856                {
2857                    let mut map = schema.clone_cast::<Map>();
2858                    if let Some(state) = map.remove("state") {
2859                        map.insert(
2860                            "state".into(),
2861                            normalize_state_defaults(state, "component.schema.state")?,
2862                        );
2863                        *schema = Dynamic::from_map(map);
2864                    }
2865                }
2866                let decoded: crate::ComponentDefinition =
2867                    rhai::serde::from_dynamic(&Dynamic::from_map(raw))?;
2868                let definition = crate::ComponentDefinition::new(decoded.metadata, decoded.schema)
2869                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
2870                let id = definition.metadata.id.clone();
2871                exports
2872                    .register_definition(definition)
2873                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
2874                renderers
2875                    .try_borrow_mut()
2876                    .map_err(|_| {
2877                        Box::new(component_render_error(
2878                            "component render registry is already borrowed",
2879                        ))
2880                    })?
2881                    .insert(
2882                        id,
2883                        RegisteredComponentRender {
2884                            generation: generation.get(),
2885                            render,
2886                        },
2887                    );
2888                Ok(())
2889            },
2890        );
2891}
2892
2893/// State field defaults are plain Rhai values the field schema types, or tagged
2894/// `UiValue`s (`#{ type: "integer", value: 0 }`, tagged at every level). A map of only
2895/// `type` (a `UiValue` tag) and `value` is a tagged one; anything else is plain.
2896fn normalize_state_defaults(raw: Dynamic, path: &str) -> Result<Dynamic, Box<EvalAltResult>> {
2897    if !raw.is::<Map>() {
2898        return Ok(raw);
2899    }
2900    let mut raw = raw.cast::<Map>();
2901    let Some(fields) = raw.get_mut("fields").filter(|fields| fields.is::<Map>()) else {
2902        return Ok(Dynamic::from_map(raw));
2903    };
2904    let mut entries = fields.clone_cast::<Map>();
2905    for (name, field) in &mut entries {
2906        if !field.is::<Map>() {
2907            continue;
2908        }
2909        let mut field_map = field.clone_cast::<Map>();
2910        let Some(value) = field_map.get("default") else {
2911            continue;
2912        };
2913        if is_tagged_ui_value(value) {
2914            rhai::serde::from_dynamic::<UiValue>(value).map_err(|source| {
2915                Box::new(component_render_error(format!(
2916                    "{path}.fields.{name}.default: expected recursively tagged UiValue; a `#{{ type, value }}` default needs type/value descriptors at every level, or write the plain value ({source})"
2917                )))
2918            })?;
2919            continue;
2920        }
2921        let Some(schema) = field_map
2922            .get("schema")
2923            .and_then(|schema| rhai::serde::from_dynamic::<crate::ValueSchema>(schema).ok())
2924        else {
2925            continue;
2926        };
2927        let plain = UiValue::from_dynamic(value.clone())
2928            .map(|plain| schema.infer(plain))
2929            .map_err(|error| error.to_string())
2930            .and_then(|plain| {
2931                schema
2932                    .validate_ui_value(&plain)
2933                    .map(|()| plain)
2934                    .map_err(|error| error.to_string())
2935            })
2936            .map_err(|issue| {
2937                Box::new(component_render_error(format!(
2938                    "{path}.fields.{name}.default: {issue}"
2939                )))
2940            })?;
2941        field_map.insert("default".into(), rhai::serde::to_dynamic(&plain)?);
2942        *field = Dynamic::from_map(field_map);
2943    }
2944    *fields = Dynamic::from_map(entries);
2945    Ok(Dynamic::from_map(raw))
2946}
2947
2948fn is_tagged_ui_value(value: &Dynamic) -> bool {
2949    const TAGS: [&str; 8] = [
2950        "null", "bool", "integer", "float", "string", "array", "map", "handle",
2951    ];
2952    value.clone().try_cast::<Map>().is_some_and(|map| {
2953        map.keys().all(|key| key == "type" || key == "value")
2954            && map
2955                .get("type")
2956                .and_then(|tag| tag.clone().into_immutable_string().ok())
2957                .is_some_and(|tag| TAGS.contains(&tag.as_str()))
2958    })
2959}
2960
2961fn register_component_runtime_apis(
2962    engine: &mut Engine,
2963    exports: &ComponentExportCollector,
2964    generation: &Rc<Cell<ScriptGeneration>>,
2965    virtual_policy: &Rc<Cell<crate::VirtualCollectionPolicy>>,
2966) -> (ActiveComponentRenderState, ComponentRenderRegistry) {
2967    let active = Rc::new(RefCell::new(None));
2968    let renderers = Rc::new(RefCell::new(BTreeMap::new()));
2969    register_define_component_api(engine, exports, &renderers, generation);
2970    register_render_component_api(engine, exports, &renderers, &active);
2971    register_effect_api(engine, &active);
2972    register_timer_api(engine, &active);
2973    register_signal_api(engine, &active);
2974    register_element_ref_api(engine, &active);
2975    register_virtual_collection_api(engine, &active, virtual_policy);
2976    register_node_factory_api(engine, &active);
2977    (active, renderers)
2978}
2979
2980fn register_render_component_api(
2981    engine: &mut Engine,
2982    exports: &ComponentExportCollector,
2983    renderers: &ComponentRenderRegistry,
2984    active: &ActiveComponentRenderState,
2985) {
2986    let exports = exports.clone();
2987    let renderers = Rc::clone(renderers);
2988    let active = Rc::clone(active);
2989    FuncRegistration::new("render_component")
2990        .in_global_namespace()
2991        .register_into_engine(
2992            engine,
2993            move |call: rhai::NativeCallContext<'_>,
2994                  id: ImmutableString,
2995                  props: Map|
2996                  -> Result<UiNode, Box<EvalAltResult>> {
2997                let id = ModuleId::parse(id.to_string())
2998                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
2999                let generation = active
3000                    .try_borrow()
3001                    .map_err(|_| {
3002                        Box::new(component_render_error(
3003                            "component render stack is already borrowed",
3004                        ))
3005                    })?
3006                    .as_ref()
3007                    .ok_or_else(|| {
3008                        Box::new(component_render_error(
3009                            "render_component may run only inside view",
3010                        ))
3011                    })?
3012                    .generation;
3013                let registered = renderers
3014                    .try_borrow()
3015                    .map_err(|_| {
3016                        Box::new(component_render_error(
3017                            "component render registry is already borrowed",
3018                        ))
3019                    })?
3020                    .get(&id)
3021                    .cloned()
3022                    .ok_or_else(|| {
3023                        Box::new(component_render_error(format!(
3024                            "component `{id}` has no registered render function"
3025                        )))
3026                    })?;
3027                if registered.generation != generation {
3028                    return Err(Box::new(component_render_error(format!(
3029                        "component `{id}` render belongs to stale generation {}",
3030                        registered.generation
3031                    ))));
3032                }
3033                execute_component_render(
3034                    &call,
3035                    &exports,
3036                    &active,
3037                    id.as_str().into(),
3038                    props,
3039                    &registered.render,
3040                )
3041            },
3042        );
3043}
3044
3045#[allow(clippy::too_many_lines)] // One cohesive Rhai component transaction; splitting hides ordering.
3046fn execute_component_render(
3047    call: &rhai::NativeCallContext<'_>,
3048    exports: &ComponentExportCollector,
3049    active: &ActiveComponentRenderState,
3050    id: ImmutableString,
3051    props: Map,
3052    render: &FnPtr,
3053) -> Result<UiNode, Box<EvalAltResult>> {
3054    let generation = active
3055        .try_borrow()
3056        .map_err(|_| {
3057            Box::new(component_render_error(
3058                "component render stack is already borrowed",
3059            ))
3060        })?
3061        .as_ref()
3062        .ok_or_else(|| {
3063            Box::new(component_render_error(
3064                "formal component rendering may run only inside view",
3065            ))
3066        })?
3067        .generation;
3068    let (component, mut invocation) = resolve_component_invocation(exports, id, props, generation)?;
3069    if render.is_anonymous() || render.is_curried() {
3070        return Err(Box::new(component_render_error(
3071            "formal component render must be an uncurried named function",
3072        )));
3073    }
3074    let part_styles = component_part_styles(&invocation.props);
3075    let recipe_props = invocation.retained_props.clone();
3076    let declared_key = invocation.key.clone();
3077    let render_recipe = render.clone();
3078    let (path, caller_context) = reserve_component_path(call, &component, &invocation, active)?;
3079    if let Some(node) = try_reuse_component_subtree(
3080        active,
3081        &path,
3082        &caller_context,
3083        &component,
3084        &invocation,
3085        render,
3086    )? {
3087        return Ok(node);
3088    }
3089    let native_context = crate::invocation::ScriptInvocationContext::capture_retained(call);
3090    let caller_binding = factory_binding(active, &caller_context)
3091        .unwrap_or_else(|| caller_component_binding(call, &caller_context));
3092    bind_component_callback_props(
3093        &mut invocation.props,
3094        &component.schema.props,
3095        &caller_binding,
3096    );
3097    bind_component_node_props(
3098        &mut invocation.props,
3099        &component.schema.props,
3100        &caller_binding,
3101    );
3102    let event_callbacks = component_event_callbacks(&component, &invocation.props);
3103    let recipe_event_callbacks = event_callbacks.clone();
3104    let script_props = invocation.props.clone();
3105    let context = enter_component_render(
3106        &path,
3107        &component,
3108        &invocation,
3109        native_context.clone(),
3110        active,
3111    )?;
3112    let recipe_component_context = context.clone();
3113    let result = render.call_within_context::<UiNode>(call, (context, invocation.props));
3114    if result.is_err() {
3115        record_component_render_failure(active, &path);
3116    }
3117    register_component_event_callbacks(
3118        active,
3119        &path,
3120        &caller_context,
3121        event_callbacks,
3122        &native_context,
3123    )?;
3124    let (environment, reusable) = component_render_metadata(active, &recipe_component_context)?;
3125    leave_component_render(active)?;
3126    let mut node = result?;
3127    node = node.with_owned_part_styles(part_styles.clone());
3128    let snapshot = crate::node::ComponentOwnedSnapshot::default();
3129    node = node.with_component_root_snapshot(path.clone(), snapshot.reference());
3130    node.bind_component_scope(
3131        &path,
3132        recipe_component_context.component_incarnation(),
3133        &component.schema.events,
3134        Some(&native_context),
3135    );
3136    register_component_invocation(
3137        active,
3138        ComponentInvocationRecipe {
3139            path: path.clone(),
3140            parent: caller_context.component_path().clone(),
3141            component: component.metadata.id.clone(),
3142            export: component.metadata.export.clone(),
3143            declared_key,
3144            props: recipe_props,
3145            script_props,
3146            component_context: recipe_component_context,
3147            caller_context: caller_context.clone(),
3148            part_styles,
3149            event_callbacks: recipe_event_callbacks,
3150            component_events: component.schema.events.clone(),
3151            declared_effects: component.schema.effects.clone(),
3152            render: render_recipe,
3153            snapshot,
3154            context: native_context.clone(),
3155            generation,
3156            environment,
3157            reusable,
3158        },
3159    )?;
3160    Ok(node)
3161}
3162
3163/// The binding of the Node factory rendering for `caller`, when the caller is the
3164/// component that received it: a component the factory renders directly calls back
3165/// into the factory's scope, not into the component that rendered the factory.
3166fn factory_binding(
3167    active: &ActiveComponentRenderState,
3168    caller: &UiContext,
3169) -> Option<ComponentCallbackBinding> {
3170    let guard = active.try_borrow().ok()?;
3171    let scope = guard.as_ref()?.factory_scopes.last()?;
3172    (scope.receiver == *caller.callback_component_path()).then(|| scope.binding.clone())
3173}
3174
3175fn caller_component_binding(
3176    call: &rhai::NativeCallContext<'_>,
3177    caller_context: &UiContext,
3178) -> ComponentCallbackBinding {
3179    ComponentCallbackBinding {
3180        component: caller_context.callback_component_path().clone(),
3181        incarnation: caller_context.callback_component_incarnation(),
3182        events: caller_context.callback_event_schemas().clone(),
3183        context: Some(caller_context.native_context().cloned().unwrap_or_else(|| {
3184            crate::invocation::ScriptInvocationContext::capture_entry_retained(call)
3185        })),
3186        is_node_factory: false,
3187    }
3188}
3189
3190fn component_render_metadata(
3191    active: &ActiveComponentRenderState,
3192    context: &UiContext,
3193) -> Result<(ComponentRenderEnvironment, bool), Box<EvalAltResult>> {
3194    let guard = active.try_borrow().map_err(|_| {
3195        Box::new(component_render_error(
3196            "component render stack is already borrowed",
3197        ))
3198    })?;
3199    let render = guard.as_ref().ok_or_else(|| {
3200        Box::new(component_render_error(
3201            "formal component rendering may run only inside view",
3202        ))
3203    })?;
3204    Ok((render.environment, context.component_render_is_reusable()))
3205}
3206
3207fn record_component_render_failure(
3208    active: &ActiveComponentRenderState,
3209    component: &ComponentInstancePath,
3210) {
3211    if let Ok(mut active) = active.try_borrow_mut()
3212        && let Some(active) = active.as_mut()
3213        && active.failed_component.is_none()
3214    {
3215        active.failed_component = Some(component.clone());
3216    }
3217}
3218
3219fn try_reuse_component_subtree(
3220    shared: &ActiveComponentRenderState,
3221    path: &ComponentInstancePath,
3222    caller_context: &UiContext,
3223    component: &crate::ComponentDefinition,
3224    invocation: &crate::ComponentInvocation,
3225    render: &FnPtr,
3226) -> Result<Option<UiNode>, Box<EvalAltResult>> {
3227    let mut guard = shared.try_borrow_mut().map_err(|_| {
3228        Box::new(component_render_error(
3229            "component render stack is already borrowed",
3230        ))
3231    })?;
3232    let active = guard.as_mut().ok_or_else(|| {
3233        Box::new(component_render_error(
3234            "formal component rendering may run only inside view",
3235        ))
3236    })?;
3237    let Some(scope) =
3238        reusable_component_scope(active, path, caller_context, component, invocation, render)
3239    else {
3240        return Ok(None);
3241    };
3242
3243    let reused_components = scope.invocations.len();
3244    for candidate in scope.invocations.keys() {
3245        let retained = active.transaction.retain_existing(candidate);
3246        debug_assert!(
3247            retained,
3248            "reuse candidates were checked against the state snapshot"
3249        );
3250    }
3251    active.seen.extend(scope.invocations.keys().cloned());
3252    active.invocations.extend(scope.invocations);
3253    active.event_handlers.extend(scope.event_handlers);
3254    active.effects.extend(scope.resources.effects);
3255    active.timers.extend(scope.resources.timers);
3256    active.signals.extend(scope.resources.signals);
3257    active.element_refs.extend(scope.resources.element_refs);
3258    active
3259        .virtual_collections
3260        .extend(scope.resources.virtual_collections);
3261    active
3262        .reused
3263        .push((component.metadata.id.to_string(), reused_components));
3264    Ok(Some(scope.node))
3265}
3266
3267fn prune_virtual_read_contributions(
3268    context: &UiContext,
3269    id: &crate::VirtualCollectionId,
3270    data: &crate::VirtualCollectionData,
3271    indices: &BTreeSet<usize>,
3272    retained: &UiNode,
3273) -> Result<(), RuntimeError> {
3274    let mut active = retained.virtual_read_contributions();
3275    active.extend(
3276        indices
3277            .iter()
3278            .filter_map(|index| data.key(*index))
3279            .map(
3280                |key| crate::read_dependency::ReadContribution::VirtualItem {
3281                    collection: id.clone(),
3282                    key: key.to_owned(),
3283                },
3284            ),
3285    );
3286    context
3287        .runtime()
3288        .try_borrow_mut()
3289        .map_err(|_| RuntimeError::ComponentRuntime("UI state is already borrowed".into()))?
3290        .retain_virtual_read_contributions(context.component_path(), &active);
3291    Ok(())
3292}
3293
3294fn retain_virtual_component_manifest(
3295    shared: &ActiveComponentRenderState,
3296) -> Result<(), RuntimeError> {
3297    let mut guard = shared.try_borrow_mut().map_err(|_| {
3298        RuntimeError::ComponentRuntime("component render stack is already borrowed".to_owned())
3299    })?;
3300    let active = guard.as_mut().ok_or_else(|| {
3301        RuntimeError::ComponentRuntime("virtual render has no active transaction".to_owned())
3302    })?;
3303    let Some(reuse) = active.reuse.as_ref() else {
3304        return Ok(());
3305    };
3306    let mut retained = reuse
3307        .invocations
3308        .keys()
3309        .filter(|path| reuse.subtrees.contains(path))
3310        .cloned()
3311        .collect::<BTreeSet<_>>();
3312    // A transparent component can share its display root with its parent.
3313    // Follow committed invocation ownership, not only display-root markers.
3314    let mut children = BTreeMap::<ComponentInstancePath, Vec<ComponentInstancePath>>::new();
3315    for (path, recipe) in &reuse.invocations {
3316        children
3317            .entry(recipe.parent.clone())
3318            .or_default()
3319            .push(path.clone());
3320    }
3321    let mut pending = retained.iter().cloned().collect::<Vec<_>>();
3322    while let Some(parent) = pending.pop() {
3323        for child in children.get(&parent).into_iter().flatten() {
3324            if retained.insert(child.clone()) {
3325                pending.push(child.clone());
3326            }
3327        }
3328    }
3329    for path in &retained {
3330        if !active.transaction.retain_existing(path) {
3331            return Err(RuntimeError::ComponentRuntime(format!(
3332                "retained virtual component `{path}` has no committed state"
3333            )));
3334        }
3335    }
3336    active.seen.extend(retained.iter().cloned());
3337    active.invocations.extend(
3338        reuse
3339            .invocations
3340            .iter()
3341            .filter(|(path, _)| retained.contains(*path))
3342            .map(|(path, recipe)| (path.clone(), recipe.clone())),
3343    );
3344    active.event_handlers.extend(
3345        reuse
3346            .event_handlers
3347            .iter()
3348            .filter(|((path, _), _)| retained.contains(path))
3349            .map(|(id, callback)| (id.clone(), callback.clone())),
3350    );
3351    active.effects.extend(
3352        reuse
3353            .effects
3354            .iter()
3355            .filter(|(id, _)| retained.contains(id.component()))
3356            .map(|(id, descriptor)| (id.clone(), descriptor.clone())),
3357    );
3358    active.timers.extend(
3359        reuse
3360            .timers
3361            .iter()
3362            .filter(|(id, _)| retained.contains(id.component()))
3363            .map(|(id, descriptor)| (id.clone(), descriptor.clone())),
3364    );
3365    active.signals.extend(
3366        reuse
3367            .signals
3368            .iter()
3369            .filter(|(id, _)| retained.contains(id.component()))
3370            .map(|(id, descriptor)| (id.clone(), descriptor.clone())),
3371    );
3372    active.element_refs.extend(
3373        reuse
3374            .element_refs
3375            .iter()
3376            .filter(|id| retained.contains(id.component()))
3377            .cloned(),
3378    );
3379    active.virtual_collections.extend(
3380        reuse
3381            .virtual_collections
3382            .iter()
3383            .filter(|(id, _)| reuse.previous_root.virtual_collection_spec(id).is_some())
3384            .map(|(id, recipe)| (id.clone(), recipe.clone())),
3385    );
3386    Ok(())
3387}
3388
3389fn reusable_component_scope(
3390    active: &ActiveComponentRender,
3391    path: &ComponentInstancePath,
3392    caller_context: &UiContext,
3393    component: &crate::ComponentDefinition,
3394    invocation: &crate::ComponentInvocation,
3395    render: &FnPtr,
3396) -> Option<ReusedComponentScope> {
3397    let reuse = active.reuse.as_ref()?;
3398    if reuse.dirty.iter().any(|dirty| dirty.is_within(path)) {
3399        return None;
3400    }
3401    let recipe = reuse.invocations.get(path)?;
3402    if !recipe.reusable
3403        || recipe.generation != active.generation
3404        || recipe.environment != active.environment
3405        || recipe.parent != *caller_context.component_path()
3406        || recipe.component != component.metadata.id
3407        || recipe.export != component.metadata.export
3408        || recipe.declared_key != invocation.key
3409        || recipe.render.fn_name() != render.fn_name()
3410        || !recipe.props.reusable_eq(&invocation.retained_props)
3411    {
3412        return None;
3413    }
3414    let invocations = reuse
3415        .invocations
3416        .range(path.clone()..)
3417        .take_while(|(candidate, _)| candidate.is_within(path))
3418        .map(|(candidate, recipe)| (candidate.clone(), recipe.clone()))
3419        .collect::<BTreeMap<_, _>>();
3420    if invocations.is_empty()
3421        || invocations.values().any(|recipe| !recipe.reusable)
3422        || invocations
3423            .keys()
3424            .any(|candidate| !active.state_snapshot.contains_instance(candidate))
3425    {
3426        return None;
3427    }
3428    let node = if let Some(snapshot) = recipe.snapshot.current() {
3429        let mut node = snapshot.as_ref().clone();
3430        node.hydrate_component_subtrees();
3431        node
3432    } else {
3433        reuse.subtrees.get(&reuse.previous_root, path)?.clone()
3434    };
3435    Some(ReusedComponentScope {
3436        node,
3437        invocations,
3438        event_handlers: reuse
3439            .event_handlers
3440            .range((path.clone(), String::new())..)
3441            .take_while(|((candidate, _), _)| candidate.is_within(path))
3442            .map(|(id, callback)| (id.clone(), callback.clone()))
3443            .collect(),
3444        resources: reused_component_resources(reuse, path),
3445    })
3446}
3447
3448fn reused_component_resources(
3449    reuse: &ComponentReuseSnapshot,
3450    path: &ComponentInstancePath,
3451) -> ReusedComponentResources {
3452    ReusedComponentResources {
3453        effects: reuse
3454            .effects
3455            .iter()
3456            .filter(|(id, _)| id.component().is_within(path))
3457            .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
3458            .collect(),
3459        timers: reuse
3460            .timers
3461            .iter()
3462            .filter(|(id, _)| id.component().is_within(path))
3463            .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
3464            .collect(),
3465        signals: reuse
3466            .signals
3467            .iter()
3468            .filter(|(id, _)| id.component().is_within(path))
3469            .map(|(id, descriptor)| (id.clone(), descriptor.clone()))
3470            .collect(),
3471        element_refs: reuse
3472            .element_refs
3473            .iter()
3474            .filter(|id| id.component().is_within(path))
3475            .cloned()
3476            .collect(),
3477        virtual_collections: reuse
3478            .virtual_collections
3479            .iter()
3480            .filter(|(id, _)| id.component.is_within(path))
3481            .map(|(id, recipe)| (id.clone(), recipe.clone()))
3482            .collect(),
3483    }
3484}
3485
3486fn register_component_invocation(
3487    active: &ActiveComponentRenderState,
3488    recipe: ComponentInvocationRecipe,
3489) -> Result<(), Box<EvalAltResult>> {
3490    let mut guard = active.try_borrow_mut().map_err(|_| {
3491        Box::new(component_render_error(
3492            "component render stack is already borrowed",
3493        ))
3494    })?;
3495    let active = guard.as_mut().ok_or_else(|| {
3496        Box::new(component_render_error(
3497            "formal component rendering may run only inside view",
3498        ))
3499    })?;
3500    active.invocations.insert(recipe.path.clone(), recipe);
3501    Ok(())
3502}
3503
3504fn resolve_component_invocation(
3505    exports: &ComponentExportCollector,
3506    id: ImmutableString,
3507    props: Map,
3508    generation: ScriptGeneration,
3509) -> Result<(crate::ComponentDefinition, crate::ComponentInvocation), Box<EvalAltResult>> {
3510    let id: String = id.into();
3511    let id =
3512        ModuleId::parse(id).map_err(|error| Box::new(component_render_error(error.to_string())))?;
3513    let registry = exports
3514        .snapshot()
3515        .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3516    let component = registry.get(&id).cloned().ok_or_else(|| {
3517        Box::new(component_render_error(format!(
3518            "component `{id}` is not exported"
3519        )))
3520    })?;
3521    let key = props.get("key").and_then(|value| {
3522        value
3523            .is::<ImmutableString>()
3524            .then(|| value.clone_cast::<ImmutableString>().to_string())
3525    });
3526    let invocation = component
3527        .invoke_with_generation(key, props, generation)
3528        .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3529    Ok((component, invocation))
3530}
3531
3532fn reserve_component_path(
3533    call: &rhai::NativeCallContext<'_>,
3534    component: &crate::ComponentDefinition,
3535    invocation: &crate::ComponentInvocation,
3536    shared: &ActiveComponentRenderState,
3537) -> Result<(ComponentInstancePath, UiContext), Box<EvalAltResult>> {
3538    let mut guard = shared.try_borrow_mut().map_err(|_| {
3539        Box::new(component_render_error(
3540            "component render stack is already borrowed",
3541        ))
3542    })?;
3543    let active = guard.as_mut().ok_or_else(|| {
3544        Box::new(component_render_error(
3545            "formal component rendering may run only inside view",
3546        ))
3547    })?;
3548    let caller_context = active.contexts.last().cloned().ok_or_else(|| {
3549        Box::new(component_render_error(
3550            "component render context stack has no caller",
3551        ))
3552    })?;
3553    let parent = active.stack.last().cloned().ok_or_else(|| {
3554        Box::new(component_render_error(
3555            "component render stack has no application root",
3556        ))
3557    })?;
3558    let key = invocation.key.clone().unwrap_or_else(|| {
3559        let callsite = format!(
3560            "{}@{}",
3561            call.call_source().unwrap_or("<script>"),
3562            call.call_position()
3563        );
3564        let occurrence = active
3565            .positions
3566            .entry(format!("{parent}/{}/{callsite}", component.metadata.export))
3567            .or_default();
3568        let key = format!("{callsite}#{occurrence}");
3569        *occurrence = occurrence.saturating_add(1);
3570        key
3571    });
3572    let path = parent.child(&component.metadata.export, key);
3573    if !active.seen.insert(path.clone()) {
3574        return Err(Box::new(component_render_error(format!(
3575            "duplicate component instance path `{path}`; add a stable key"
3576        ))));
3577    }
3578    Ok((path, caller_context))
3579}
3580
3581fn enter_component_render(
3582    path: &ComponentInstancePath,
3583    component: &crate::ComponentDefinition,
3584    invocation: &crate::ComponentInvocation,
3585    native_context: crate::invocation::ScriptInvocationContext,
3586    shared: &ActiveComponentRenderState,
3587) -> Result<UiContext, Box<EvalAltResult>> {
3588    let mut guard = shared.try_borrow_mut().map_err(|_| {
3589        Box::new(component_render_error(
3590            "component render stack is already borrowed",
3591        ))
3592    })?;
3593    let active = guard.as_mut().ok_or_else(|| {
3594        Box::new(component_render_error(
3595            "formal component rendering may run only inside view",
3596        ))
3597    })?;
3598    active
3599        .transaction
3600        .mount(path.clone(), &component.schema.state)
3601        .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3602    let global_part_styles = {
3603        let mut runtime = active
3604            .root_context
3605            .runtime()
3606            .try_borrow_mut()
3607            .map_err(|_| Box::new(component_render_error("UI state is already borrowed")))?;
3608        runtime
3609            .component_state
3610            .mount_instance(path.clone(), &component.schema.state)
3611            .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3612        runtime
3613            .component_styles()
3614            .component(&component.metadata.id)
3615            .cloned()
3616            .unwrap_or_default()
3617    };
3618    let context = active
3619        .root_context
3620        .for_component(path.clone(), component.schema.events.clone())
3621        .with_component_styles(
3622            global_part_styles,
3623            component_root_style(&invocation.props),
3624            component_part_styles(&invocation.props),
3625        )
3626        .with_native_context(Some(native_context))
3627        .with_generation(active.generation);
3628    active.stack.push(path.clone());
3629    active.contexts.push(context.clone());
3630    active
3631        .effect_keys
3632        .push(Some(component.schema.effects.clone()));
3633    Ok(context)
3634}
3635
3636fn leave_component_render(active: &ActiveComponentRenderState) -> Result<(), Box<EvalAltResult>> {
3637    let mut guard = active.try_borrow_mut().map_err(|_| {
3638        Box::new(component_render_error(
3639            "component render stack is already borrowed",
3640        ))
3641    })?;
3642    if let Some(active) = guard.as_mut() {
3643        active.stack.pop();
3644        active.contexts.pop();
3645        active.effect_keys.pop();
3646    }
3647    Ok(())
3648}
3649
3650fn register_effect_api(engine: &mut Engine, active: &ActiveComponentRenderState) {
3651    let active = Rc::clone(active);
3652    FuncRegistration::new("effect")
3653        .in_global_namespace()
3654        .register_into_engine(
3655            engine,
3656            move |call: rhai::NativeCallContext<'_>,
3657                  key: ImmutableString,
3658                  dependencies: Dynamic,
3659                  start: FnPtr,
3660                  cleanup: FnPtr|
3661                  -> Result<(), Box<EvalAltResult>> {
3662                let key = key.to_string();
3663                let (component, context, generation, declared) = {
3664                    let guard = active.try_borrow().map_err(|_| {
3665                        Box::new(component_render_error(
3666                            "component render stack is already borrowed",
3667                        ))
3668                    })?;
3669                    let render = guard.as_ref().ok_or_else(|| {
3670                        Box::new(component_render_error(
3671                            "effect may run only during formal component render",
3672                        ))
3673                    })?;
3674                    let context = render.contexts.last().cloned().ok_or_else(|| {
3675                        Box::new(component_render_error(
3676                            "component render context stack is empty",
3677                        ))
3678                    })?;
3679                    let declared =
3680                        render
3681                            .effect_keys
3682                            .last()
3683                            .cloned()
3684                            .flatten()
3685                            .ok_or_else(|| {
3686                                Box::new(component_render_error(
3687                                    "effects may be declared only by formal components",
3688                                ))
3689                            })?;
3690                    (
3691                        context.component_path().clone(),
3692                        context,
3693                        render.generation,
3694                        declared,
3695                    )
3696                };
3697                if !declared.contains(&key) {
3698                    return Err(Box::new(component_render_error(
3699                        crate::EffectError::Undeclared { component, key }.to_string(),
3700                    )));
3701                }
3702                let id = crate::EffectId::new(component.clone(), key.clone())
3703                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3704                let dependencies = UiValue::from_dynamic(dependencies)
3705                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3706                let native_context =
3707                    crate::invocation::ScriptInvocationContext::capture_retained(&call);
3708                let mut start = ScriptCallback::try_from_fn_ptr(start, generation)
3709                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3710                start.bind_component_scope_if_unset(
3711                    &component,
3712                    context.component_incarnation(),
3713                    context.event_schemas().clone(),
3714                );
3715                start.bind_native_context_if_unset(native_context.clone());
3716                let mut cleanup = ScriptCallback::try_from_fn_ptr(cleanup, generation)
3717                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3718                cleanup.bind_component_scope_if_unset(
3719                    &component,
3720                    context.component_incarnation(),
3721                    context.event_schemas().clone(),
3722                );
3723                cleanup.bind_native_context_if_unset(native_context);
3724                let descriptor =
3725                    crate::EffectDescriptor::new(id.clone(), dependencies, start, cleanup);
3726                let mut guard = active.try_borrow_mut().map_err(|_| {
3727                    Box::new(component_render_error(
3728                        "component render stack is already borrowed",
3729                    ))
3730                })?;
3731                let render = guard.as_mut().ok_or_else(|| {
3732                    Box::new(component_render_error(
3733                        "effect may run only during formal component render",
3734                    ))
3735                })?;
3736                if render.effects.insert(id, descriptor).is_some() {
3737                    return Err(Box::new(component_render_error(
3738                        crate::EffectError::Duplicate { component, key }.to_string(),
3739                    )));
3740                }
3741                Ok(())
3742            },
3743        );
3744}
3745
3746fn register_timer_api(engine: &mut Engine, active: &ActiveComponentRenderState) {
3747    // `timeout` fires once; `interval` fires every period until removed,
3748    // changed or cancelled. Both share one key space per component.
3749    for (name, repeat) in [("timeout", false), ("interval", true)] {
3750        let active = Rc::clone(active);
3751        FuncRegistration::new(name)
3752            .in_global_namespace()
3753            .register_into_engine(
3754                engine,
3755                move |call: rhai::NativeCallContext<'_>,
3756                      key: ImmutableString,
3757                      delay_ms: rhai::INT,
3758                      paused: bool,
3759                      callback: FnPtr,
3760                      payload: Dynamic|
3761                      -> Result<(), Box<EvalAltResult>> {
3762                    let (component, context, generation) = {
3763                        let guard = active.try_borrow().map_err(|_| {
3764                            Box::new(component_render_error(
3765                                "component render stack is already borrowed",
3766                            ))
3767                        })?;
3768                        let render = guard.as_ref().ok_or_else(|| {
3769                            Box::new(component_render_error(format!(
3770                                "{name} may run only during formal component render"
3771                            )))
3772                        })?;
3773                        let context = render.contexts.last().cloned().ok_or_else(|| {
3774                            Box::new(component_render_error(
3775                                "component render context stack is empty",
3776                            ))
3777                        })?;
3778                        (context.component_path().clone(), context, render.generation)
3779                    };
3780                    let delay_ms = u64::try_from(delay_ms).map_err(|_| {
3781                        Box::new(component_render_error(format!(
3782                            "{name} delay must be a positive integer"
3783                        )))
3784                    })?;
3785                    let id = crate::TimerId::new(component.clone(), key.to_string())
3786                        .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3787                    let payload = UiValue::from_dynamic(payload)
3788                        .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3789                    let native_context =
3790                        crate::invocation::ScriptInvocationContext::capture_retained(&call);
3791                    let mut callback = ScriptCallback::try_from_fn_ptr(callback, generation)
3792                        .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3793                    callback.bind_component_scope_if_unset(
3794                        &component,
3795                        context.component_incarnation(),
3796                        context.event_schemas().clone(),
3797                    );
3798                    callback.bind_native_context_if_unset(native_context);
3799                    let descriptor = crate::TimerDescriptor::new(
3800                        id.clone(),
3801                        Duration::from_millis(delay_ms),
3802                        paused,
3803                        callback,
3804                        payload,
3805                    )
3806                    .and_then(|descriptor| {
3807                        if repeat {
3808                            descriptor.repeating()
3809                        } else {
3810                            Ok(descriptor)
3811                        }
3812                    })
3813                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3814                    let mut guard = active.try_borrow_mut().map_err(|_| {
3815                        Box::new(component_render_error(
3816                            "component render stack is already borrowed",
3817                        ))
3818                    })?;
3819                    let render = guard.as_mut().ok_or_else(|| {
3820                        Box::new(component_render_error(format!(
3821                            "{name} may run only during formal component render"
3822                        )))
3823                    })?;
3824                    if render.timers.insert(id.clone(), descriptor).is_some() {
3825                        return Err(Box::new(component_render_error(format!(
3826                            "{name} `{}` is declared more than once in `{}`",
3827                            id.key(),
3828                            id.component()
3829                        ))));
3830                    }
3831                    Ok(())
3832                },
3833            );
3834    }
3835}
3836
3837fn register_signal_api(engine: &mut Engine, active: &ActiveComponentRenderState) {
3838    let scalar_active = Rc::clone(active);
3839    FuncRegistration::new("signal")
3840        .in_global_namespace()
3841        .register_into_engine(
3842            engine,
3843            move |key: ImmutableString,
3844                  initial: Dynamic|
3845                  -> Result<crate::NativeSignal, Box<EvalAltResult>> {
3846                let key = key.to_string();
3847                let initial = crate::SignalValue::from_dynamic(initial)
3848                    .map_err(|error| Box::new(crate::signal::signal_runtime_error(&error)))?;
3849                declare_signal(&scalar_active, key, initial)
3850            },
3851        );
3852
3853    let optional_active = Rc::clone(active);
3854    FuncRegistration::new("optional_float_signal")
3855        .in_global_namespace()
3856        .register_into_engine(
3857            engine,
3858            move |key: ImmutableString| -> Result<crate::NativeSignal, Box<EvalAltResult>> {
3859                declare_signal(
3860                    &optional_active,
3861                    key.to_string(),
3862                    crate::SignalValue::OptionalFloat(None),
3863                )
3864            },
3865        );
3866
3867    let parent_active = Rc::clone(active);
3868    FuncRegistration::new("bind_parent_signal")
3869        .in_global_namespace()
3870        .register_into_engine(
3871            engine,
3872            move |node: &mut UiNode,
3873                  context: UiContext,
3874                  property: ImmutableString,
3875                  key: ImmutableString|
3876                  -> Result<UiNode, Box<EvalAltResult>> {
3877                let property = crate::SignalProperty::parse(property.as_str())
3878                    .map_err(|error| Box::new(crate::signal::signal_runtime_error(&error)))?;
3879                if property.signal_kind() != crate::SignalKind::OptionalFloat {
3880                    return Err(Box::new(crate::signal::signal_runtime_error(
3881                        &"parent signal binding currently supports optional-float properties",
3882                    )));
3883                }
3884                // An owner rendering in this pass has declared its signals but
3885                // not committed them yet.
3886                let pending = parent_active
3887                    .try_borrow()
3888                    .ok()
3889                    .and_then(|guard| {
3890                        guard
3891                            .as_ref()
3892                            .map(|render| render.signals.keys().cloned().collect::<Vec<_>>())
3893                    })
3894                    .unwrap_or_default();
3895                let signal = context
3896                    .parent_optional_float_signal_ref(key.as_str(), &pending)
3897                    .map_err(|error| Box::new(crate::signal::signal_runtime_error(&error)))?;
3898                node.clone()
3899                    .with_signal_binding(property, signal)
3900                    .map_err(|error| Box::new(crate::signal::signal_runtime_error(&error)))
3901            },
3902        );
3903}
3904
3905fn declare_signal(
3906    active: &ActiveComponentRenderState,
3907    key: String,
3908    initial: crate::SignalValue,
3909) -> Result<crate::NativeSignal, Box<EvalAltResult>> {
3910    let mut guard = active.try_borrow_mut().map_err(|_| {
3911        Box::new(crate::signal::signal_runtime_error(
3912            &"component render stack is already borrowed",
3913        ))
3914    })?;
3915    let render = guard.as_mut().ok_or_else(|| {
3916        Box::new(crate::signal::signal_runtime_error(
3917            &"signal may run only during formal component render",
3918        ))
3919    })?;
3920    if render.effect_keys.last().and_then(Option::as_ref).is_none() {
3921        return Err(Box::new(crate::signal::signal_runtime_error(
3922            &"signals may be declared only by formal components",
3923        )));
3924    }
3925    let context = render.contexts.last().ok_or_else(|| {
3926        Box::new(crate::signal::signal_runtime_error(
3927            &"component render context stack is empty",
3928        ))
3929    })?;
3930    let component = context.component_path().clone();
3931    let incarnation = context.component_incarnation();
3932    if render
3933        .signals
3934        .keys()
3935        .any(|id| id.component() == &component && id.key() == key)
3936    {
3937        return Err(Box::new(crate::signal::signal_runtime_error(
3938            &crate::SignalError::Duplicate { component, key },
3939        )));
3940    }
3941    let id = crate::SignalId::new_scoped(component, incarnation, key, initial.kind())
3942        .map_err(|error| Box::new(crate::signal::signal_runtime_error(&error)))?;
3943    let signal = crate::NativeSignal::new(id.clone());
3944    render
3945        .signals
3946        .insert(id, crate::signal::SignalDescriptor::new(initial));
3947    Ok(signal)
3948}
3949
3950fn register_element_ref_api(engine: &mut Engine, active: &ActiveComponentRenderState) {
3951    let active = Rc::clone(active);
3952    FuncRegistration::new("element_ref")
3953        .in_global_namespace()
3954        .register_into_engine(
3955            engine,
3956            move |key: ImmutableString| -> Result<crate::ElementRef, Box<EvalAltResult>> {
3957                let key = key.to_string();
3958                let mut guard = active.try_borrow_mut().map_err(|_| {
3959                    Box::new(component_render_error(
3960                        "component render stack is already borrowed",
3961                    ))
3962                })?;
3963                let render = guard.as_mut().ok_or_else(|| {
3964                    Box::new(component_render_error(
3965                        "element_ref may run only during formal component render",
3966                    ))
3967                })?;
3968                if render.effect_keys.last().and_then(Option::as_ref).is_none() {
3969                    return Err(Box::new(component_render_error(
3970                        "element refs may be declared only by formal components",
3971                    )));
3972                }
3973                let component = render
3974                    .contexts
3975                    .last()
3976                    .ok_or_else(|| {
3977                        Box::new(component_render_error(
3978                            "component render context stack is empty",
3979                        ))
3980                    })?
3981                    .component_path()
3982                    .clone();
3983                let id = crate::ElementRefId::new(component.clone(), key.clone())
3984                    .map_err(|error| Box::new(component_render_error(error.to_string())))?;
3985                if !render.element_refs.insert(id.clone()) {
3986                    return Err(Box::new(component_render_error(format!(
3987                        "element ref `{key}` is declared more than once by component `{component}`"
3988                    ))));
3989                }
3990                Ok(crate::ElementRef::new(id))
3991            },
3992        );
3993}
3994
3995#[derive(Debug)]
3996struct DecodedVirtualCollection {
3997    key: String,
3998    label: String,
3999    data: crate::VirtualCollectionData,
4000    estimated_height: f64,
4001    height: Option<f64>,
4002    overdraw_pixels: f64,
4003    /// The collection's own render-ahead settings, before the Host policy.
4004    ahead: RenderAhead,
4005    bottom_align: bool,
4006    follow_tail: bool,
4007    on_follow_change: Option<FnPtr>,
4008    reveal_key: Option<String>,
4009    sticky_headers: Arc<BTreeSet<usize>>,
4010}
4011
4012impl DecodedVirtualCollection {
4013    fn into_spec(
4014        self,
4015        id: crate::VirtualCollectionId,
4016        realized: BTreeMap<usize, UiNode>,
4017    ) -> crate::VirtualCollectionNodeSpec {
4018        crate::VirtualCollectionNodeSpec {
4019            id,
4020            label: self.label,
4021            data: self.data,
4022            realized,
4023            estimated_height: self.estimated_height,
4024            height: self.height,
4025            overdraw_pixels: self.overdraw_pixels,
4026            bottom_align: self.bottom_align,
4027            follow_tail: self.follow_tail,
4028            on_follow_change: None,
4029            reveal_key: self.reveal_key,
4030            sticky_headers: self.sticky_headers,
4031            inherited_motion_group: None,
4032            inherited_motion_scope: None,
4033        }
4034    }
4035}
4036
4037/// A collection's own `overscan_items`, `batch_items` and `retain_items`.
4038#[derive(Clone, Copy, Debug)]
4039struct RenderAhead {
4040    overscan: Option<usize>,
4041    batch: Option<usize>,
4042    retain: Option<usize>,
4043}
4044
4045impl RenderAhead {
4046    fn decode(config: &mut Map) -> Result<Self, Box<EvalAltResult>> {
4047        Ok(Self {
4048            overscan: collection_optional_count(
4049                config,
4050                "overscan_items",
4051                0,
4052                crate::MAX_VIRTUAL_OVERSCAN_ITEMS,
4053            )?,
4054            batch: collection_optional_count(
4055                config,
4056                "batch_items",
4057                1,
4058                crate::MAX_VIRTUAL_BATCH_ITEMS,
4059            )?,
4060            retain: collection_optional_count(
4061                config,
4062                "retain_items",
4063                0,
4064                crate::MAX_VIRTUAL_RETAIN_ITEMS,
4065            )?,
4066        })
4067    }
4068}
4069
4070fn decode_virtual_collection(
4071    mut config: Map,
4072) -> Result<DecodedVirtualCollection, Box<EvalAltResult>> {
4073    let key = collection_string(&mut config, "key")?;
4074    let label = collection_optional_string(&mut config, "label")?.unwrap_or_default();
4075    let estimated_height = collection_positive(&mut config, "estimated_height")?;
4076    let height = collection_optional_number(&mut config, "height")?;
4077    let fill_height = collection_optional_bool(&mut config, "fill_height")?.unwrap_or(false);
4078    let height = match (height, fill_height) {
4079        (Some(_), true) => {
4080            return Err(Box::new(component_render_error(
4081                "virtual collection must specify either `height` or `fill_height`, not both",
4082            )));
4083        }
4084        (None, false) => {
4085            return Err(Box::new(component_render_error(
4086                "virtual collection requires `height` or `fill_height: true`",
4087            )));
4088        }
4089        (None, true) => None,
4090        (Some(height), false) if height.is_finite() && height > 0.0 => Some(height),
4091        (Some(_), false) => {
4092            return Err(Box::new(component_render_error(
4093                "virtual collection `height` must be finite and positive",
4094            )));
4095        }
4096    };
4097    let overdraw_pixels = collection_optional_number(&mut config, "overdraw_pixels")?
4098        .unwrap_or(estimated_height * 2.0);
4099    if !overdraw_pixels.is_finite() || !(0.0..=10_000.0).contains(&overdraw_pixels) {
4100        return Err(Box::new(component_render_error(
4101            "virtual collection overdraw_pixels must be between 0 and 10000",
4102        )));
4103    }
4104    let ahead = RenderAhead::decode(&mut config)?;
4105    let alignment =
4106        collection_optional_string(&mut config, "alignment")?.unwrap_or_else(|| "top".to_owned());
4107    let bottom_align = match alignment.as_str() {
4108        "top" => false,
4109        "bottom" => true,
4110        _ => {
4111            return Err(Box::new(component_render_error(
4112                "virtual collection alignment must be `top` or `bottom`",
4113            )));
4114        }
4115    };
4116    let follow_tail = collection_optional_bool(&mut config, "follow_tail")?.unwrap_or(false);
4117    let on_follow_change = collection_optional_follow_callback(&mut config)?;
4118    let data = collection_data(&mut config)?;
4119    let reveal_key = collection_optional_string(&mut config, "reveal_key")?;
4120    if reveal_key.as_deref() == Some("") {
4121        return Err(Box::new(component_render_error(
4122            "virtual collection `reveal_key` must not be empty",
4123        )));
4124    }
4125    if let Some(reveal_key) = reveal_key.as_deref()
4126        && !(0..data.len()).any(|index| data.key(index) == Some(reveal_key))
4127    {
4128        return Err(Box::new(component_render_error(format!(
4129            "virtual collection reveal key `{reveal_key}` is not present in its data"
4130        ))));
4131    }
4132    if follow_tail && reveal_key.is_some() {
4133        return Err(Box::new(component_render_error(
4134            "virtual collection must not combine `follow_tail` with `reveal_key`",
4135        )));
4136    }
4137    let sticky_headers = collection_optional_indices(&mut config, "sticky_headers")?
4138        .map_or_else(|| data.sticky_headers(), Arc::new);
4139    if let Some(index) = sticky_headers.iter().find(|index| **index >= data.len()) {
4140        return Err(Box::new(component_render_error(format!(
4141            "virtual collection sticky header index {index} is outside {} items",
4142            data.len()
4143        ))));
4144    }
4145    if bottom_align && !sticky_headers.is_empty() {
4146        return Err(Box::new(component_render_error(
4147            "sticky headers require top-aligned virtual collections",
4148        )));
4149    }
4150    if let Some((unknown, _)) = config.into_iter().next() {
4151        return Err(Box::new(component_render_error(format!(
4152            "unknown virtual collection field `{unknown}`"
4153        ))));
4154    }
4155    Ok(DecodedVirtualCollection {
4156        key,
4157        label,
4158        data,
4159        estimated_height,
4160        height,
4161        overdraw_pixels,
4162        ahead,
4163        bottom_align,
4164        follow_tail,
4165        on_follow_change,
4166        reveal_key,
4167        sticky_headers,
4168    })
4169}
4170
4171/// `ctx.render_node(factory, detail)`: renders a Node factory with the receiving
4172/// component's `ctx`. Callbacks in the nodes it returns, and in the components it
4173/// renders directly, belong to the scope that bound the factory.
4174fn register_node_factory_api(engine: &mut Engine, active: &ActiveComponentRenderState) {
4175    let active = Rc::clone(active);
4176    engine.register_fn(
4177        "render_node",
4178        move |call: rhai::NativeCallContext<'_>,
4179              context: &mut UiContext,
4180              renderer: Dynamic,
4181              detail: Dynamic|
4182              -> Result<UiNode, Box<EvalAltResult>> {
4183            let callback = context.node_factory_callback(renderer)?;
4184            let binding = callback.factory_scope_binding();
4185            let pushed = binding.as_ref().is_some_and(|binding| {
4186                active
4187                    .try_borrow_mut()
4188                    .ok()
4189                    .and_then(|mut guard| {
4190                        guard.as_mut().map(|render| {
4191                            render.factory_scopes.push(FactoryScope {
4192                                receiver: context.callback_component_path().clone(),
4193                                binding: binding.clone(),
4194                            });
4195                        })
4196                    })
4197                    .is_some()
4198            });
4199            let result = callback.render_node(&call, context.clone(), detail);
4200            if pushed
4201                && let Ok(mut guard) = active.try_borrow_mut()
4202                && let Some(render) = guard.as_mut()
4203            {
4204                render.factory_scopes.pop();
4205            }
4206            let mut node = result?;
4207            if let Some(binding) = &binding {
4208                node.bind_component_scope(
4209                    &binding.component,
4210                    binding.incarnation,
4211                    &binding.events,
4212                    binding.context.as_ref(),
4213                );
4214            }
4215            Ok(node)
4216        },
4217    );
4218}
4219
4220fn register_virtual_collection_api(
4221    engine: &mut Engine,
4222    active: &ActiveComponentRenderState,
4223    policy: &Rc<Cell<crate::VirtualCollectionPolicy>>,
4224) {
4225    let active = Rc::clone(active);
4226    let policy = Rc::clone(policy);
4227    FuncRegistration::new("virtual_collection")
4228        .in_global_namespace()
4229        .register_into_engine(
4230            engine,
4231            move |call: rhai::NativeCallContext<'_>,
4232                  config: Map,
4233                  mut renderer: FnPtr|
4234                  -> Result<UiNode, Box<EvalAltResult>> {
4235                let renderer_context = crate::invocation::take_function_environment(&mut renderer);
4236                validate_virtual_renderer(&renderer)?;
4237                let mut decoded = decode_virtual_collection(config)?;
4238                // The collection's own settings, then the Host's, then the built-in values.
4239                // An overscan in items replaces the collection's own `overdraw_pixels`.
4240                let policy = policy.get();
4241                if let Some(items) = policy.overscan_for(decoded.ahead.overscan) {
4242                    decoded.overdraw_pixels =
4243                        (usize_to_f64(items) * decoded.estimated_height).min(10_000.0);
4244                }
4245                let batch_items = policy.batch_for(decoded.ahead.batch);
4246                let retain_items = policy.retain_for(decoded.ahead.retain);
4247
4248                let VirtualCollectionContext {
4249                    component,
4250                    context,
4251                    generation,
4252                } = virtual_collection_context(&active)?;
4253                let id = crate::VirtualCollectionId {
4254                    component: component.clone(),
4255                    key: decoded.key.clone(),
4256                };
4257                let collection_context = context
4258                    .for_structural_scope(
4259                        component.child("VirtualCollection", decoded.key.clone()),
4260                        BTreeMap::new(),
4261                    )
4262                    .with_generation(generation);
4263                let native_context =
4264                    crate::invocation::ScriptInvocationContext::capture_retained(&call);
4265                let renderer_context = renderer_context.unwrap_or_else(|| native_context.clone());
4266                let on_follow_change = decoded
4267                    .on_follow_change
4268                    .take()
4269                    .map(|callback| {
4270                        let mut callback = ScriptCallback::try_from_fn_ptr(callback, generation)
4271                            .map_err(|error| Box::new(component_render_error(error.to_string())))?;
4272                        callback.bind_component_scope_if_unset(
4273                            context.callback_component_path(),
4274                            context.callback_component_incarnation(),
4275                            context.callback_event_schemas().clone(),
4276                        );
4277                        callback.bind_native_context_if_unset(native_context.clone());
4278                        Ok::<_, Box<EvalAltResult>>(callback)
4279                    })
4280                    .transpose()?;
4281                let realized = realize_seeded_virtual_collection(
4282                    &call,
4283                    &renderer,
4284                    &renderer_context,
4285                    &collection_context,
4286                    &active,
4287                    &id,
4288                    &decoded,
4289                )?;
4290                let recipe = VirtualCollectionRecipe {
4291                    id: id.clone(),
4292                    data: decoded.data.clone(),
4293                    renderer,
4294                    renderer_context,
4295                    context: collection_context,
4296                    generation,
4297                    batch_items,
4298                    offscreen: Rc::new(RefCell::new(OffscreenItems::new(retain_items))),
4299                };
4300                let mut guard = active.try_borrow_mut().map_err(|_| {
4301                    Box::new(component_render_error(
4302                        "component render stack is already borrowed",
4303                    ))
4304                })?;
4305                let render = guard.as_mut().ok_or_else(|| {
4306                    Box::new(component_render_error(
4307                        "virtual_collection may run only during view render",
4308                    ))
4309                })?;
4310                if render
4311                    .virtual_collections
4312                    .insert(id.clone(), recipe)
4313                    .is_some()
4314                {
4315                    return Err(Box::new(component_render_error(format!(
4316                        "virtual collection `{}` is declared more than once in `{}`",
4317                        decoded.key, id.component
4318                    ))));
4319                }
4320                let mut spec = decoded.into_spec(id, realized);
4321                spec.on_follow_change = on_follow_change.map(Box::new);
4322                Ok(UiNode::virtual_collection(spec))
4323            },
4324        );
4325}
4326
4327fn collection_optional_follow_callback(
4328    config: &mut Map,
4329) -> Result<Option<FnPtr>, Box<EvalAltResult>> {
4330    config
4331        .remove("on_follow_change")
4332        .filter(|value| !value.is_unit())
4333        .map(|value| {
4334            value.try_cast::<FnPtr>().ok_or_else(|| {
4335                Box::new(component_render_error(
4336                    "virtual collection on_follow_change must be a named callback",
4337                ))
4338            })
4339        })
4340        .transpose()
4341}
4342
4343fn validate_virtual_renderer(renderer: &FnPtr) -> Result<(), Box<EvalAltResult>> {
4344    if renderer.is_anonymous() {
4345        return Err(Box::new(component_render_error(
4346            "virtual collection item renderer must be a named function",
4347        )));
4348    }
4349    for (index, value) in renderer.iter_curry().enumerate() {
4350        validate_virtual_renderer_curry(value).map_err(|error| {
4351            Box::new(component_render_error(format!(
4352                "virtual collection renderer curry {index} is not durable presentation data: {error}"
4353            )))
4354        })?;
4355    }
4356    Ok(())
4357}
4358
4359fn validate_virtual_renderer_curry(value: &Dynamic) -> Result<(), crate::UiValueError> {
4360    if value.is::<UiNode>() || value.is::<crate::NativeSignal>() || is_bound_node_factory(value) {
4361        return Ok(());
4362    }
4363    if value.is::<Array>() {
4364        for value in value.clone_cast::<Array>() {
4365            validate_virtual_renderer_curry(&value)?;
4366        }
4367        return Ok(());
4368    }
4369    if value.is::<Map>() {
4370        for value in value.clone_cast::<Map>().values() {
4371            validate_virtual_renderer_curry(value)?;
4372        }
4373        return Ok(());
4374    }
4375    UiValue::from_dynamic(value.clone()).map(|_| ())
4376}
4377
4378/// A Node factory bound with `ctx.node_factory`: an item renderer may carry one,
4379/// since it keeps the environment and scope it was bound in, and call it with
4380/// `ctx.render_node` whenever the collection realizes an item.
4381fn is_bound_node_factory(value: &Dynamic) -> bool {
4382    value.is::<FnPtr>()
4383        && value.clone_cast::<FnPtr>().iter_curry().any(|value| {
4384            value.is::<ComponentCallbackBinding>()
4385                && value
4386                    .clone_cast::<ComponentCallbackBinding>()
4387                    .is_node_factory
4388        })
4389}
4390
4391/// The context an item renderer runs in: a structural `Item[<key>]` scope under
4392/// the collection, so components inside an item are named by the item, not by
4393/// how many items the batch rendered before it.
4394fn virtual_item_context(
4395    context: &UiContext,
4396    id: &crate::VirtualCollectionId,
4397    key: &str,
4398) -> UiContext {
4399    context
4400        .for_structural_scope(context.component_path().child("Item", key), BTreeMap::new())
4401        .for_virtual_item(id, key)
4402}
4403
4404fn realize_initial_collection(
4405    call: &rhai::NativeCallContext<'_>,
4406    renderer: (&FnPtr, &crate::invocation::ScriptInvocationContext),
4407    context: &UiContext,
4408    active: &ActiveComponentRenderState,
4409    id: &crate::VirtualCollectionId,
4410    data: &crate::VirtualCollectionData,
4411    indices: &BTreeSet<usize>,
4412) -> Result<BTreeMap<usize, UiNode>, Box<EvalAltResult>> {
4413    let (renderer, renderer_context) = renderer;
4414    let mut realized = BTreeMap::new();
4415    for index in indices.iter().copied().filter(|index| *index < data.len()) {
4416        let item = data
4417            .item(index)
4418            .map_err(|error| Box::new(component_render_error(error.to_string())))?
4419            .ok_or_else(|| {
4420                Box::new(component_render_error(format!(
4421                    "virtual collection item {index} disappeared"
4422                )))
4423            })?;
4424        let (item_key, mut payload) = collection_payload(&item, index)?;
4425        add_collection_neighbors(data, index, &mut payload);
4426        let item_context = virtual_item_context(context, id, &item_key);
4427        enter_virtual_collection_scope(active, item_context.clone())?;
4428        let node =
4429            renderer_context.call_synchronous::<UiNode>(call, renderer, (item_context, payload));
4430        leave_component_render(active)?;
4431        realized.insert(index, node?.with_key(item_key));
4432    }
4433    Ok(realized)
4434}
4435
4436fn realize_seeded_virtual_collection(
4437    call: &rhai::NativeCallContext<'_>,
4438    renderer: &FnPtr,
4439    renderer_context: &crate::invocation::ScriptInvocationContext,
4440    context: &UiContext,
4441    active: &ActiveComponentRenderState,
4442    id: &crate::VirtualCollectionId,
4443    decoded: &DecodedVirtualCollection,
4444) -> Result<BTreeMap<usize, UiNode>, Box<EvalAltResult>> {
4445    let previous_metrics = context
4446        .runtime()
4447        .try_borrow()
4448        .map_err(|_| {
4449            Box::new(component_render_error(
4450                "UI state is already borrowed while seeding a virtual collection",
4451            ))
4452        })?
4453        .virtual_requests
4454        .metrics(id);
4455    let viewport = decoded.height.unwrap_or_else(|| {
4456        previous_metrics
4457            .as_ref()
4458            .map_or(decoded.estimated_height, |metrics| {
4459                if metrics.viewport_height > 0.0 {
4460                    metrics.viewport_height
4461                } else {
4462                    decoded.estimated_height
4463                }
4464            })
4465    });
4466    let count = nonnegative_usize(
4467        ((viewport + decoded.overdraw_pixels) / decoded.estimated_height).ceil() + 1.0,
4468    )
4469    .min(decoded.data.len());
4470    let indices =
4471        virtual_collection_seed_indices(active, id, decoded, count, previous_metrics.as_ref())?;
4472    enter_virtual_collection_scope(active, context.clone())?;
4473    let realized = realize_initial_collection(
4474        call,
4475        (renderer, renderer_context),
4476        context,
4477        active,
4478        id,
4479        &decoded.data,
4480        &indices,
4481    );
4482    leave_component_render(active)?;
4483    realized
4484}
4485
4486fn virtual_collection_seed_indices(
4487    active: &ActiveComponentRenderState,
4488    id: &crate::VirtualCollectionId,
4489    decoded: &DecodedVirtualCollection,
4490    count: usize,
4491    metrics: Option<&crate::VirtualCollectionMetrics>,
4492) -> Result<BTreeSet<usize>, Box<EvalAltResult>> {
4493    let mut indices = BTreeSet::new();
4494    let guard = active.try_borrow().map_err(|_| {
4495        Box::new(component_render_error(
4496            "component render stack is already borrowed",
4497        ))
4498    })?;
4499    let reuse = guard.as_ref().and_then(|render| render.reuse.as_ref());
4500    let previous = reuse.and_then(|reuse| reuse.previous_root.virtual_collection_spec(id));
4501    let preserves_scroll = previous.is_some_and(|previous| {
4502        previous.estimated_height.to_bits() == decoded.estimated_height.to_bits()
4503            && previous.overdraw_pixels.to_bits() == decoded.overdraw_pixels.to_bits()
4504            && previous.bottom_align == decoded.bottom_align
4505            && same_collection_key_order(&previous.data, &decoded.data)
4506    });
4507
4508    if preserves_scroll {
4509        let overdraw = virtual_overdraw_items(decoded);
4510        // A new render keeps the items around the last presented viewport, not the batch
4511        // a scroll rendered ahead: rendering again is what the batch saved. Before a
4512        // frame has reported what it showed, every realized item stays.
4513        let around = metrics
4514            .filter(|metrics| !metrics.visible_range.is_empty())
4515            .map(|metrics| {
4516                metrics.visible_range.start.saturating_sub(overdraw)
4517                    ..metrics.visible_range.end.saturating_add(overdraw)
4518            });
4519        if let Some(previous) = previous {
4520            indices.extend(
4521                previous
4522                    .realized
4523                    .keys()
4524                    .copied()
4525                    .filter(|index| around.as_ref().is_none_or(|around| around.contains(index))),
4526            );
4527        }
4528        if let Some(metrics) = metrics {
4529            extend_virtual_window(
4530                &mut indices,
4531                metrics.scroll_item,
4532                count,
4533                decoded.data.len(),
4534                overdraw,
4535            );
4536        }
4537    } else if decoded.reveal_key.is_none() && !decoded.bottom_align && !decoded.follow_tail {
4538        extend_virtual_window(&mut indices, 0, count, decoded.data.len(), 0);
4539    }
4540    drop(guard);
4541
4542    if let Some(reveal) = decoded.reveal_key.as_deref()
4543        && let Some(index) =
4544            (0..decoded.data.len()).find(|index| decoded.data.key(*index) == Some(reveal))
4545    {
4546        extend_virtual_window(
4547            &mut indices,
4548            index,
4549            count,
4550            decoded.data.len(),
4551            virtual_overdraw_items(decoded),
4552        );
4553        if let Some(header) = decoded.sticky_headers.range(..=index).next_back() {
4554            indices.insert(*header);
4555        }
4556    }
4557    if (decoded.bottom_align || decoded.follow_tail) && !decoded.data.is_empty() {
4558        let start = decoded.data.len().saturating_sub(count);
4559        indices.extend(start..decoded.data.len());
4560    }
4561    Ok(indices)
4562}
4563
4564fn same_collection_key_order(
4565    current: &crate::VirtualCollectionData,
4566    next: &crate::VirtualCollectionData,
4567) -> bool {
4568    current.len() == next.len()
4569        && (0..current.len()).all(|index| current.key(index) == next.key(index))
4570}
4571
4572/// The indices a realization renders: the requested ones, and when a scroll
4573/// needs items that are not rendered yet, `batch - 1` more beyond the farthest
4574/// requested index on each side the new items lie, so the next scroll steps
4575/// find their items rendered.
4576fn batched_indices(
4577    requested: &BTreeSet<usize>,
4578    previous: &BTreeMap<usize, UiNode>,
4579    batch: usize,
4580    len: usize,
4581) -> BTreeSet<usize> {
4582    let mut indices = requested.clone();
4583    let extra = batch.saturating_sub(1);
4584    let (Some(&first), Some(&last)) = (requested.first(), requested.last()) else {
4585        return indices;
4586    };
4587    if extra == 0 {
4588        return indices;
4589    }
4590    let realized = (previous.keys().next(), previous.keys().next_back());
4591    let (mut after, mut before) = (false, false);
4592    for index in requested
4593        .iter()
4594        .filter(|index| !previous.contains_key(index))
4595    {
4596        match realized {
4597            (Some(start), Some(end)) => {
4598                after |= index > end;
4599                before |= index < start;
4600            }
4601            _ => after = true,
4602        }
4603    }
4604    if after {
4605        let end = last.saturating_add(extra).saturating_add(1).min(len);
4606        indices.extend(last.saturating_add(1)..end);
4607    }
4608    if before {
4609        indices.extend(first.saturating_sub(extra)..first);
4610    }
4611    indices
4612}
4613
4614fn virtual_overdraw_items(decoded: &DecodedVirtualCollection) -> usize {
4615    nonnegative_usize((decoded.overdraw_pixels / decoded.estimated_height).ceil())
4616}
4617
4618fn extend_virtual_window(
4619    indices: &mut BTreeSet<usize>,
4620    anchor: usize,
4621    count: usize,
4622    len: usize,
4623    leading: usize,
4624) {
4625    let start = anchor.saturating_sub(leading).min(len);
4626    let end = anchor.saturating_add(count).min(len);
4627    indices.extend(start..end);
4628}
4629
4630struct VirtualCollectionContext {
4631    component: ComponentInstancePath,
4632    context: UiContext,
4633    generation: ScriptGeneration,
4634}
4635
4636fn enter_virtual_collection_scope(
4637    active: &ActiveComponentRenderState,
4638    context: UiContext,
4639) -> Result<(), Box<EvalAltResult>> {
4640    let mut guard = active.try_borrow_mut().map_err(|_| {
4641        Box::new(component_render_error(
4642            "component render stack is already borrowed",
4643        ))
4644    })?;
4645    let render = guard.as_mut().ok_or_else(|| {
4646        Box::new(component_render_error(
4647            "virtual_collection may run only during view render",
4648        ))
4649    })?;
4650    render.stack.push(context.component_path().clone());
4651    render.contexts.push(context);
4652    render.effect_keys.push(None);
4653    Ok(())
4654}
4655
4656fn virtual_collection_context(
4657    active: &ActiveComponentRenderState,
4658) -> Result<VirtualCollectionContext, Box<EvalAltResult>> {
4659    let guard = active.try_borrow().map_err(|_| {
4660        Box::new(component_render_error(
4661            "component render stack is already borrowed",
4662        ))
4663    })?;
4664    let render = guard.as_ref().ok_or_else(|| {
4665        Box::new(component_render_error(
4666            "virtual_collection may run only during view render",
4667        ))
4668    })?;
4669    let context = render.contexts.last().cloned().ok_or_else(|| {
4670        Box::new(component_render_error(
4671            "component render context stack is empty",
4672        ))
4673    })?;
4674    Ok(VirtualCollectionContext {
4675        component: context.component_path().clone(),
4676        context: context.clone(),
4677        generation: render.generation,
4678    })
4679}
4680
4681fn collection_string(config: &mut Map, name: &str) -> Result<String, Box<EvalAltResult>> {
4682    config
4683        .remove(name)
4684        .and_then(Dynamic::try_cast::<ImmutableString>)
4685        .map(|value| value.to_string())
4686        .ok_or_else(|| {
4687            Box::new(component_render_error(format!(
4688                "virtual collection `{name}` must be a string"
4689            )))
4690        })
4691}
4692
4693fn collection_optional_string(
4694    config: &mut Map,
4695    name: &str,
4696) -> Result<Option<String>, Box<EvalAltResult>> {
4697    config
4698        .remove(name)
4699        .map(|value| {
4700            value
4701                .try_cast::<ImmutableString>()
4702                .map(|value| value.to_string())
4703                .ok_or_else(|| {
4704                    Box::new(component_render_error(format!(
4705                        "virtual collection `{name}` must be a string"
4706                    )))
4707                })
4708        })
4709        .transpose()
4710}
4711
4712fn collection_optional_number(
4713    config: &mut Map,
4714    name: &str,
4715) -> Result<Option<f64>, Box<EvalAltResult>> {
4716    config
4717        .remove(name)
4718        .map(|value| {
4719            if value.is::<rhai::FLOAT>() {
4720                Ok(value.cast::<rhai::FLOAT>())
4721            } else if value.is::<rhai::INT>() {
4722                value
4723                    .cast::<rhai::INT>()
4724                    .to_string()
4725                    .parse::<f64>()
4726                    .map_err(|_| Box::new(component_render_error("invalid collection number")))
4727            } else {
4728                Err(Box::new(component_render_error(format!(
4729                    "virtual collection `{name}` must be a number"
4730                ))))
4731            }
4732        })
4733        .transpose()
4734}
4735
4736/// An optional item count between `min` and `max`.
4737fn collection_optional_count(
4738    config: &mut Map,
4739    name: &str,
4740    min: usize,
4741    max: usize,
4742) -> Result<Option<usize>, Box<EvalAltResult>> {
4743    config
4744        .remove(name)
4745        .map(|value| {
4746            let count = value
4747                .try_cast::<rhai::INT>()
4748                .and_then(|count| usize::try_from(count).ok())
4749                .filter(|count| (min..=max).contains(count));
4750            count.ok_or_else(|| {
4751                Box::new(component_render_error(format!(
4752                    "virtual collection `{name}` must be an integer from {min} to {max}"
4753                )))
4754            })
4755        })
4756        .transpose()
4757}
4758
4759fn collection_positive(config: &mut Map, name: &str) -> Result<f64, Box<EvalAltResult>> {
4760    let value = collection_optional_number(config, name)?.ok_or_else(|| {
4761        Box::new(component_render_error(format!(
4762            "virtual collection `{name}` is required"
4763        )))
4764    })?;
4765    if value.is_finite() && value > 0.0 {
4766        Ok(value)
4767    } else {
4768        Err(Box::new(component_render_error(format!(
4769            "virtual collection `{name}` must be finite and positive"
4770        ))))
4771    }
4772}
4773
4774fn collection_optional_bool(
4775    config: &mut Map,
4776    name: &str,
4777) -> Result<Option<bool>, Box<EvalAltResult>> {
4778    config
4779        .remove(name)
4780        .map(|value| {
4781            value.try_cast::<bool>().ok_or_else(|| {
4782                Box::new(component_render_error(format!(
4783                    "virtual collection `{name}` must be bool"
4784                )))
4785            })
4786        })
4787        .transpose()
4788}
4789
4790fn collection_optional_indices(
4791    config: &mut Map,
4792    name: &str,
4793) -> Result<Option<BTreeSet<usize>>, Box<EvalAltResult>> {
4794    let Some(value) = config.remove(name) else {
4795        return Ok(None);
4796    };
4797    let values = value.try_cast::<Array>().ok_or_else(|| {
4798        Box::new(component_render_error(format!(
4799            "virtual collection `{name}` must be an array of non-negative integers"
4800        )))
4801    })?;
4802    let mut indices = BTreeSet::new();
4803    for (position, value) in values.into_iter().enumerate() {
4804        let index = value.try_cast::<rhai::INT>().ok_or_else(|| {
4805            Box::new(component_render_error(format!(
4806                "virtual collection `{name}` item {position} must be an integer"
4807            )))
4808        })?;
4809        let index = usize::try_from(index).map_err(|_| {
4810            Box::new(component_render_error(format!(
4811                "virtual collection `{name}` item {position} must be non-negative"
4812            )))
4813        })?;
4814        if !indices.insert(index) {
4815            return Err(Box::new(component_render_error(format!(
4816                "virtual collection `{name}` contains duplicate index {index}"
4817            ))));
4818        }
4819    }
4820    Ok(Some(indices))
4821}
4822
4823fn collection_data(config: &mut Map) -> Result<crate::VirtualCollectionData, Box<EvalAltResult>> {
4824    let data = config.remove("data").ok_or_else(|| {
4825        Box::new(component_render_error(
4826            "virtual collection `data` is required",
4827        ))
4828    })?;
4829    if data.is::<crate::NativeCollection>() {
4830        return Ok(crate::VirtualCollectionData::Native(
4831            data.cast::<crate::NativeCollection>(),
4832        ));
4833    }
4834    let data = data.try_cast::<Array>().ok_or_else(|| {
4835        Box::new(component_render_error(
4836            "virtual collection `data` must be an array or NativeCollection",
4837        ))
4838    })?;
4839    let data = data
4840        .into_iter()
4841        .map(|value| {
4842            UiValue::from_dynamic(value)
4843                .map_err(|error| Box::new(component_render_error(error.to_string())))
4844        })
4845        .collect::<Result<Vec<_>, _>>()?;
4846    let mut keys = BTreeSet::new();
4847    for (index, item) in data.iter().enumerate() {
4848        let (key, _) = collection_payload(item, index)?;
4849        if !keys.insert(key.clone()) {
4850            return Err(Box::new(component_render_error(format!(
4851                "virtual collection data key `{key}` is duplicated"
4852            ))));
4853        }
4854    }
4855    Ok(crate::VirtualCollectionData::Values(data))
4856}
4857
4858fn collection_payload(item: &UiValue, index: usize) -> Result<(String, Map), Box<EvalAltResult>> {
4859    let UiValue::Map(map) = item else {
4860        return Err(Box::new(component_render_error(
4861            "virtual collection data items must be maps with a string `key`",
4862        )));
4863    };
4864    let key = match map.get("key") {
4865        Some(UiValue::String(key)) if !key.is_empty() => key.clone(),
4866        _ => {
4867            return Err(Box::new(component_render_error(
4868                "virtual collection data item `key` must be a non-empty string",
4869            )));
4870        }
4871    };
4872    Ok((
4873        key.clone(),
4874        Map::from_iter([
4875            ("key".into(), Dynamic::from(key)),
4876            (
4877                "index".into(),
4878                Dynamic::from_int(rhai::INT::try_from(index).unwrap_or(rhai::INT::MAX)),
4879            ),
4880            ("item".into(), item.clone().into_dynamic()),
4881        ]),
4882    ))
4883}
4884
4885fn add_collection_neighbors(data: &crate::VirtualCollectionData, index: usize, payload: &mut Map) {
4886    let key = |index: Option<usize>| {
4887        index
4888            .and_then(|index| data.key(index))
4889            .map_or(Dynamic::UNIT, |key| Dynamic::from(key.to_owned()))
4890    };
4891    payload.insert("previous_key".into(), key(index.checked_sub(1)));
4892    payload.insert(
4893        "next_key".into(),
4894        key(index.checked_add(1).filter(|index| *index < data.len())),
4895    );
4896    payload.insert("first_key".into(), key((!data.is_empty()).then_some(0)));
4897    payload.insert("last_key".into(), key(data.len().checked_sub(1)));
4898}
4899
4900fn nonnegative_usize(value: f64) -> usize {
4901    value.to_string().parse().unwrap_or(usize::MAX)
4902}
4903
4904/// An item count as pixels' factor; counts here are bounded far below `u32::MAX`.
4905fn usize_to_f64(value: usize) -> f64 {
4906    f64::from(u32::try_from(value).unwrap_or(u32::MAX))
4907}
4908
4909fn component_event_callbacks(
4910    component: &crate::ComponentDefinition,
4911    props: &Map,
4912) -> Vec<(String, FnPtr)> {
4913    component
4914        .schema
4915        .events
4916        .keys()
4917        .filter_map(|event| {
4918            props
4919                .get(format!("on_{event}").as_str())
4920                .filter(|value| value.is::<FnPtr>())
4921                .map(|value| (event.clone(), value.clone_cast::<FnPtr>()))
4922        })
4923        .collect()
4924}
4925
4926fn bind_component_callback_props(
4927    props: &mut Map,
4928    schema: &BTreeMap<String, crate::ObjectField>,
4929    binding: &ComponentCallbackBinding,
4930) {
4931    for (name, field) in schema {
4932        if schema_contains_callback(&field.schema)
4933            && let Some(value) = props.get_mut(name.as_str())
4934        {
4935            bind_component_callback_value(&field.schema, value, binding);
4936        }
4937    }
4938}
4939
4940fn schema_contains_callback(schema: &crate::ValueSchema) -> bool {
4941    match schema {
4942        crate::ValueSchema::Callback => true,
4943        crate::ValueSchema::Array { items, .. }
4944        | crate::ValueSchema::Map { values: items }
4945        | crate::ValueSchema::Optional { value: items } => schema_contains_callback(items),
4946        crate::ValueSchema::Object { fields, .. } => fields
4947            .values()
4948            .any(|field| schema_contains_callback(&field.schema)),
4949        crate::ValueSchema::OneOf { variants } => variants.iter().any(schema_contains_callback),
4950        _ => false,
4951    }
4952}
4953
4954fn bind_component_callback_value(
4955    schema: &crate::ValueSchema,
4956    value: &mut Dynamic,
4957    binding: &ComponentCallbackBinding,
4958) {
4959    match schema {
4960        crate::ValueSchema::Callback if value.is::<FnPtr>() => {
4961            let mut function = value.clone_cast::<FnPtr>();
4962            if !function
4963                .iter_curry()
4964                .any(Dynamic::is::<ComponentCallbackBinding>)
4965            {
4966                function.add_curry(Dynamic::from(binding.clone()));
4967                *value = Dynamic::from(function);
4968            }
4969        }
4970        crate::ValueSchema::Optional { value: inner } if !value.is_unit() => {
4971            bind_component_callback_value(inner, value, binding);
4972        }
4973        crate::ValueSchema::OneOf { variants } => {
4974            if let Some(variant) = variants
4975                .iter()
4976                .find(|variant| variant.validate(value).is_ok())
4977            {
4978                bind_component_callback_value(variant, value, binding);
4979            }
4980        }
4981        crate::ValueSchema::Array { items, .. }
4982            if schema_contains_callback(items) && value.is::<Array>() =>
4983        {
4984            let mut values = value.clone_cast::<Array>();
4985            for value in &mut values {
4986                bind_component_callback_value(items, value, binding);
4987            }
4988            *value = Dynamic::from_array(values);
4989        }
4990        crate::ValueSchema::Map {
4991            values: item_schema,
4992        } if schema_contains_callback(item_schema) && value.is::<Map>() => {
4993            let mut values = value.clone_cast::<Map>();
4994            for value in values.values_mut() {
4995                bind_component_callback_value(item_schema, value, binding);
4996            }
4997            *value = Dynamic::from_map(values);
4998        }
4999        crate::ValueSchema::Object { fields, .. } if value.is::<Map>() => {
5000            let mut values = value.clone_cast::<Map>();
5001            for (name, field) in fields {
5002                if schema_contains_callback(&field.schema)
5003                    && let Some(value) = values.get_mut(name.as_str())
5004                {
5005                    bind_component_callback_value(&field.schema, value, binding);
5006                }
5007            }
5008            *value = Dynamic::from_map(values);
5009        }
5010        _ => {}
5011    }
5012}
5013
5014fn bind_component_node_props(
5015    props: &mut Map,
5016    schema: &BTreeMap<String, crate::ObjectField>,
5017    binding: &ComponentCallbackBinding,
5018) {
5019    for (name, field) in schema {
5020        if schema_contains_node(&field.schema)
5021            && let Some(value) = props.get_mut(name.as_str())
5022        {
5023            bind_component_node_value(&field.schema, value, binding);
5024        }
5025    }
5026}
5027
5028fn schema_contains_node(schema: &crate::ValueSchema) -> bool {
5029    match schema {
5030        crate::ValueSchema::Node => true,
5031        crate::ValueSchema::Array { items, .. }
5032        | crate::ValueSchema::Map { values: items }
5033        | crate::ValueSchema::Optional { value: items } => schema_contains_node(items),
5034        crate::ValueSchema::Object { fields, .. } => fields
5035            .values()
5036            .any(|field| schema_contains_node(&field.schema)),
5037        crate::ValueSchema::OneOf { variants } => variants.iter().any(schema_contains_node),
5038        _ => false,
5039    }
5040}
5041
5042fn bind_component_node_value(
5043    schema: &crate::ValueSchema,
5044    value: &mut Dynamic,
5045    binding: &ComponentCallbackBinding,
5046) {
5047    match schema {
5048        crate::ValueSchema::Node if value.is::<UiNode>() => {
5049            let mut node = value.clone_cast::<UiNode>();
5050            node.bind_component_scope(
5051                &binding.component,
5052                binding.incarnation,
5053                &binding.events,
5054                binding.context.as_ref(),
5055            );
5056            node.activate_component_snapshots();
5057            *value = Dynamic::from(node);
5058        }
5059        crate::ValueSchema::Optional { value: inner } if !value.is_unit() => {
5060            bind_component_node_value(inner, value, binding);
5061        }
5062        crate::ValueSchema::OneOf { variants } => {
5063            if let Some(variant) = variants
5064                .iter()
5065                .find(|variant| variant.validate(value).is_ok())
5066            {
5067                bind_component_node_value(variant, value, binding);
5068            }
5069        }
5070        crate::ValueSchema::Array { items, .. }
5071            if schema_contains_node(items) && value.is::<Array>() =>
5072        {
5073            let mut values = value.clone_cast::<Array>();
5074            for value in &mut values {
5075                bind_component_node_value(items, value, binding);
5076            }
5077            *value = Dynamic::from_array(values);
5078        }
5079        crate::ValueSchema::Map {
5080            values: item_schema,
5081        } if schema_contains_node(item_schema) && value.is::<Map>() => {
5082            let mut values = value.clone_cast::<Map>();
5083            for value in values.values_mut() {
5084                bind_component_node_value(item_schema, value, binding);
5085            }
5086            *value = Dynamic::from_map(values);
5087        }
5088        crate::ValueSchema::Object { fields, .. } if value.is::<Map>() => {
5089            let mut values = value.clone_cast::<Map>();
5090            for (name, field) in fields {
5091                if schema_contains_node(&field.schema)
5092                    && let Some(value) = values.get_mut(name.as_str())
5093                {
5094                    bind_component_node_value(&field.schema, value, binding);
5095                }
5096            }
5097            *value = Dynamic::from_map(values);
5098        }
5099        _ => {}
5100    }
5101}
5102
5103fn hydrate_replayed_node_value(value: &mut Dynamic) {
5104    if value.is::<UiNode>() {
5105        let mut node = value.clone_cast::<UiNode>();
5106        node.hydrate_component_subtrees();
5107        *value = Dynamic::from(node);
5108    } else if value.is::<Array>() {
5109        let mut values = value.clone_cast::<Array>();
5110        for value in &mut values {
5111            hydrate_replayed_node_value(value);
5112        }
5113        *value = Dynamic::from_array(values);
5114    } else if value.is::<Map>() {
5115        let mut values = value.clone_cast::<Map>();
5116        for value in values.values_mut() {
5117            hydrate_replayed_node_value(value);
5118        }
5119        *value = Dynamic::from_map(values);
5120    }
5121}
5122
5123fn component_part_styles(props: &Map) -> BTreeMap<String, crate::Style> {
5124    props
5125        .get("part_styles")
5126        .filter(|value| value.is::<Map>())
5127        .map(Dynamic::clone_cast::<Map>)
5128        .unwrap_or_default()
5129        .into_iter()
5130        .filter_map(|(name, value)| {
5131            value
5132                .is::<crate::Style>()
5133                .then(|| (name.to_string(), value.cast::<crate::Style>()))
5134        })
5135        .collect()
5136}
5137
5138fn component_root_style(props: &Map) -> Option<crate::Style> {
5139    props
5140        .get("style")
5141        .filter(|value| value.is::<crate::Style>())
5142        .map(Dynamic::clone_cast::<crate::Style>)
5143}
5144
5145fn register_component_event_callbacks(
5146    active: &ActiveComponentRenderState,
5147    component: &ComponentInstancePath,
5148    caller: &UiContext,
5149    callbacks: Vec<(String, FnPtr)>,
5150    native_context: &crate::invocation::ScriptInvocationContext,
5151) -> Result<(), Box<EvalAltResult>> {
5152    let mut guard = active.try_borrow_mut().map_err(|_| {
5153        Box::new(component_render_error(
5154            "component render stack is already borrowed",
5155        ))
5156    })?;
5157    let active = guard.as_mut().ok_or_else(|| {
5158        Box::new(component_render_error(
5159            "formal component rendering may run only inside view",
5160        ))
5161    })?;
5162    for (event, function) in callbacks {
5163        let mut callback = ScriptCallback::try_from_fn_ptr(function, active.generation)
5164            .map_err(|error| Box::new(component_render_error(error.to_string())))?;
5165        callback.bind_component_scope_if_unset(
5166            caller.component_path(),
5167            caller.component_incarnation(),
5168            caller.event_schemas().clone(),
5169        );
5170        callback.bind_native_context_if_unset(native_context.clone());
5171        active
5172            .event_handlers
5173            .insert((component.clone(), event), callback);
5174    }
5175    Ok(())
5176}
5177
5178fn component_render_error(message: impl Into<String>) -> EvalAltResult {
5179    EvalAltResult::ErrorRuntime(Dynamic::from(message.into()), Position::NONE)
5180}
5181
5182#[cfg(feature = "charts")]
5183fn register_chart_validation_api(engine: &mut Engine) {
5184    engine.register_fn(
5185        "chart_validate",
5186        |spec: Map, data: Dynamic, key_dimension: Dynamic| -> Result<(), Box<EvalAltResult>> {
5187            let spec = UiValue::from_dynamic(Dynamic::from_map(spec))
5188                .map_err(|error| Box::new(component_render_error(error.to_string())))?;
5189            crate::ChartSpec::from_ui_value(&spec)
5190                .map_err(|error| Box::new(component_render_error(error.to_string())))?;
5191            let key_dimension = if key_dimension.is_unit() {
5192                None
5193            } else if key_dimension.is::<ImmutableString>() {
5194                Some(key_dimension.cast::<ImmutableString>().to_string())
5195            } else {
5196                return Err(Box::new(component_render_error(
5197                    "chart key_dimension must be a string or null",
5198                )));
5199            };
5200            if data.is::<crate::NativeChartData>() {
5201                return Ok(());
5202            }
5203            if !data.is::<Array>() {
5204                return Err(Box::new(component_render_error(
5205                    "chart data must be an array of objects or NativeChartData",
5206                )));
5207            }
5208            let data = UiValue::from_dynamic(Dynamic::from_array(data.cast::<Array>()))
5209                .map_err(|error| Box::new(component_render_error(error.to_string())))?;
5210            let UiValue::Array(rows) = data else {
5211                unreachable!()
5212            };
5213            if rows.len() > 10_000 {
5214                return Err(Box::new(component_render_error(
5215                    "inline chart data is limited to 10000 rows; use NativeChartData",
5216                )));
5217            }
5218            let rows = rows
5219                .into_iter()
5220                .enumerate()
5221                .map(|(index, row)| match row {
5222                    UiValue::Map(row) => Ok(row),
5223                    _ => Err(Box::new(component_render_error(format!(
5224                        "chart inline row {index} must be an object"
5225                    )))),
5226                })
5227                .collect::<Result<Vec<_>, _>>()?;
5228            crate::ChartDataset::from_rows(
5229                "main",
5230                &rows,
5231                key_dimension,
5232                crate::ChartDataLimits::default(),
5233            )
5234            .map_err(|error| Box::new(component_render_error(error.to_string())))?;
5235            Ok(())
5236        },
5237    );
5238}
5239
5240#[cfg(test)]
5241mod tests {
5242    use super::*;
5243
5244    #[test]
5245    fn offscreen_items_drop_the_least_recently_released_beyond_capacity() {
5246        let mut kept = OffscreenItems::new(3);
5247        for index in 0..5 {
5248            kept.keep(index, UiNode::text(format!("{index}")));
5249        }
5250        assert_eq!(kept.items.keys().copied().collect::<Vec<_>>(), [2, 3, 4]);
5251        // Releasing 2 again makes it the newest, so 3 goes first.
5252        kept.keep(2, UiNode::text("2"));
5253        kept.keep(5, UiNode::text("5"));
5254        assert_eq!(kept.items.keys().copied().collect::<Vec<_>>(), [2, 4, 5]);
5255        assert!(kept.take(4).is_some());
5256        assert!(kept.take(4).is_none());
5257        assert_eq!(kept.order, [2, 5]);
5258
5259        let mut none = OffscreenItems::new(0);
5260        none.keep(0, UiNode::text("0"));
5261        assert!(none.items.is_empty());
5262    }
5263
5264    #[test]
5265    fn a_batch_extends_toward_the_items_a_scroll_needs() {
5266        let realized = |range: std::ops::Range<usize>| {
5267            range
5268                .map(|index| (index, UiNode::text(format!("{index}"))))
5269                .collect::<BTreeMap<_, _>>()
5270        };
5271        let set = |range: std::ops::Range<usize>| range.collect::<BTreeSet<_>>();
5272        // Down: rows after the realized ones are needed.
5273        assert_eq!(
5274            batched_indices(&set(2..8), &realized(0..6), 4, 100),
5275            set(2..11)
5276        );
5277        // Up: rows before them are needed, clamped at the first row.
5278        assert_eq!(
5279            batched_indices(&set(1..6), &realized(2..8), 4, 100),
5280            set(0..6)
5281        );
5282        // Nothing needed, or a batch of one: the request as it is.
5283        assert_eq!(
5284            batched_indices(&set(2..6), &realized(0..8), 4, 100),
5285            set(2..6)
5286        );
5287        assert_eq!(
5288            batched_indices(&set(2..8), &realized(0..6), 1, 100),
5289            set(2..8)
5290        );
5291        // Clamped at the last row.
5292        assert_eq!(
5293            batched_indices(&set(96..100), &realized(90..98), 8, 100),
5294            set(96..100)
5295        );
5296        // Nothing realized yet: ahead.
5297        assert_eq!(
5298            batched_indices(&set(0..2), &BTreeMap::new(), 3, 100),
5299            set(0..4)
5300        );
5301    }
5302
5303    fn virtual_config(sticky: &[i64], alignment: &str) -> Map {
5304        let mut item = Map::new();
5305        item.insert("key".into(), Dynamic::from("header"));
5306        let mut config = Map::new();
5307        config.insert("key".into(), Dynamic::from("sections"));
5308        config.insert(
5309            "data".into(),
5310            Dynamic::from_array(vec![Dynamic::from_map(item)]),
5311        );
5312        config.insert("estimated_height".into(), Dynamic::from_float(30.0));
5313        config.insert("height".into(), Dynamic::from_float(120.0));
5314        config.insert("alignment".into(), Dynamic::from(alignment.to_owned()));
5315        config.insert(
5316            "sticky_headers".into(),
5317            Dynamic::from_array(sticky.iter().copied().map(Dynamic::from_int).collect()),
5318        );
5319        config
5320    }
5321
5322    #[test]
5323    fn sticky_virtual_collection_indices_are_bounded_unique_and_top_aligned() {
5324        let decoded = decode_virtual_collection(virtual_config(&[0], "top")).unwrap();
5325        assert_eq!(decoded.sticky_headers.as_ref(), &BTreeSet::from([0]));
5326
5327        for (sticky, alignment, expected) in [
5328            (&[1][..], "top", "outside 1 items"),
5329            (&[0, 0][..], "top", "duplicate index 0"),
5330            (&[0][..], "bottom", "require top-aligned"),
5331        ] {
5332            let error = decode_virtual_collection(virtual_config(sticky, alignment)).unwrap_err();
5333            assert!(error.to_string().contains(expected), "{error}");
5334        }
5335    }
5336
5337    #[test]
5338    fn virtual_collection_reveal_key_is_known_and_has_one_scroll_owner() {
5339        let mut config = virtual_config(&[], "top");
5340        config.insert("reveal_key".into(), Dynamic::from("header"));
5341        let decoded = decode_virtual_collection(config).unwrap();
5342        assert_eq!(decoded.reveal_key.as_deref(), Some("header"));
5343
5344        let mut unknown = virtual_config(&[], "top");
5345        unknown.insert("reveal_key".into(), Dynamic::from("missing"));
5346        let error = decode_virtual_collection(unknown).unwrap_err();
5347        assert!(error.to_string().contains("is not present"), "{error}");
5348
5349        let mut competing = virtual_config(&[], "top");
5350        competing.insert("reveal_key".into(), Dynamic::from("header"));
5351        competing.insert("follow_tail".into(), Dynamic::from(true));
5352        let error = decode_virtual_collection(competing).unwrap_err();
5353        assert!(error.to_string().contains("must not combine"), "{error}");
5354    }
5355
5356    #[test]
5357    fn script_builds_a_declarative_tree() {
5358        let mut runtime = RuntimeEngine::new();
5359        let compiled = runtime
5360            .compile(
5361                r#"
5362                    fn view() {
5363                        column([
5364                            text("Hello").with_key("greeting"),
5365                            text("from Rhai")
5366                        ])
5367                    }
5368                "#,
5369            )
5370            .expect("script should compile");
5371
5372        let root = runtime.render(&compiled).expect("view should render");
5373        assert_eq!(
5374            root.source().map(|source| source.module.as_str()),
5375            Some("ui/main.rhai")
5376        );
5377        let crate::UiNodeKind::Box { children } = root.kind() else {
5378            panic!("column must render a box");
5379        };
5380        assert_eq!(children.len(), 2);
5381        assert_eq!(
5382            children[0].key().map(crate::NodeKey::as_str),
5383            Some("greeting")
5384        );
5385        assert!(children.iter().all(|child| child.source().is_some()));
5386    }
5387
5388    #[test]
5389    fn runtime_emits_official_rhai_language_server_definitions() {
5390        let runtime = RuntimeEngine::new();
5391        let definitions = runtime.definition_source();
5392        assert!(definitions.starts_with("module static;"));
5393        assert!(definitions.contains("fn box"));
5394        assert!(definitions.contains("fn timeout"));
5395        assert!(definitions.contains("fn canvas_fill_path"));
5396        assert!(definitions.contains("UiNode"));
5397    }
5398
5399    #[test]
5400    fn retained_callbacks_reject_capturing_functions_and_non_data_curry() {
5401        let mut runtime = RuntimeEngine::new();
5402        let compiled = runtime
5403            .compile(r#"fn view() { text("x").on_click(|| ()) }"#)
5404            .unwrap();
5405        let error = runtime.render(&compiled).unwrap_err();
5406        assert!(
5407            error
5408                .to_string()
5409                .contains("anonymous or capturing functions")
5410        );
5411
5412        let mut callback = FnPtr::new("clicked").unwrap();
5413        callback.add_curry(Dynamic::from(UiNode::text("not durable data")));
5414        assert!(matches!(
5415            ScriptCallback::try_from_fn_ptr(callback, ScriptGeneration::initial()),
5416            Err(ScriptCallbackDefinitionError::InvalidCurry { index: 0, .. })
5417        ));
5418    }
5419
5420    #[test]
5421    fn node_factory_marker_preserves_curry_and_compares_callback_environments() {
5422        let captures = Rc::new(RefCell::new(Vec::new()));
5423        let sink = captures.clone();
5424        let context = UiContext::new(
5425            Rc::new(RefCell::new(crate::UiRuntimeState::new())),
5426            ComponentInstancePath::root("Factory", "root"),
5427            None,
5428            crate::ExecutionPhase::Render,
5429            BTreeMap::new(),
5430        );
5431        let mut engine = Engine::new();
5432        engine.register_fn(
5433            "capture_factory",
5434            move |call: rhai::NativeCallContext<'_>, function: FnPtr| {
5435                let bound = ScriptCallback::bind_node_factory(function, &context, &call);
5436                // Forwarding through an ordinary callback prop cannot discard
5437                // the explicit factory marker or its original environment.
5438                let mut forwarded = Dynamic::from(bound);
5439                bind_component_callback_value(
5440                    &crate::ValueSchema::Callback,
5441                    &mut forwarded,
5442                    &caller_component_binding(&call, &context),
5443                );
5444                let callback = ScriptCallback::try_from_fn_ptr(
5445                    forwarded.cast::<FnPtr>(),
5446                    ScriptGeneration::initial(),
5447                )
5448                .unwrap();
5449                sink.borrow_mut().push(callback);
5450            },
5451        );
5452        let source = r#"
5453            fn make(length, ctx, detail) { length }
5454            capture_factory(Fn("make").curry("short"));
5455            capture_factory(Fn("make").curry("short"));
5456        "#;
5457        engine.eval::<()>(source).unwrap();
5458        // Recompiling gives the same function name, owner and curry a new
5459        // script library, as switching between helper-module factories does.
5460        engine.eval::<()>(source).unwrap();
5461        let captures = captures.borrow();
5462        let first = &captures[0];
5463        assert!(first.is_node_factory);
5464        assert_eq!(first.curry, vec![UiValue::String("short".to_owned())]);
5465        assert_eq!(first.function.iter_curry().count(), 1);
5466        assert_eq!(first, &captures[1]);
5467        assert_ne!(first, &captures[2]);
5468
5469        let mut event_before = first.clone();
5470        let mut event_after = captures[2].clone();
5471        event_before.is_node_factory = false;
5472        event_after.is_node_factory = false;
5473        assert_ne!(
5474            event_before, event_after,
5475            "event equality must also distinguish lexical environments"
5476        );
5477    }
5478
5479    #[test]
5480    fn replay_hydrates_formal_subtrees_inside_nested_dynamic_node_shapes() {
5481        let root = ComponentInstancePath::root("View", "main");
5482        let outer = root.child("Outer", "outer");
5483        let inner = root.child("Inner", "inner");
5484        let inner_snapshot = crate::node::ComponentOwnedSnapshot::default();
5485        let mut current_inner = UiNode::text("current")
5486            .with_component_root_snapshot(inner.clone(), inner_snapshot.reference());
5487        current_inner.activate_component_snapshots();
5488        let outer_snapshot = crate::node::ComponentOwnedSnapshot::default();
5489        let mut current_outer = UiNode::box_node(vec![
5490            UiNode::text("outer"),
5491            UiNode::text("stale-inner")
5492                .with_component_root_snapshot(inner, inner_snapshot.reference()),
5493        ])
5494        .with_component_root_snapshot(outer.clone(), outer_snapshot.reference());
5495        current_outer.activate_component_snapshots();
5496        let stale = UiNode::box_node(vec![
5497            UiNode::text("stale-outer")
5498                .with_component_root_snapshot(outer, outer_snapshot.reference())
5499                .with_attribute("presentation", UiValue::Bool(true)),
5500        ]);
5501        let mut nested = Map::new();
5502        nested.insert(
5503            "object".into(),
5504            Dynamic::from_map(Map::from_iter([(
5505                "nodes".into(),
5506                Dynamic::from_array(vec![Dynamic::from(stale)]),
5507            )])),
5508        );
5509        let mut value = Dynamic::from_map(nested);
5510
5511        hydrate_replayed_node_value(&mut value);
5512
5513        let nested = value.cast::<Map>();
5514        let object = nested["object"].clone_cast::<Map>();
5515        let nodes = object["nodes"].clone_cast::<Array>();
5516        let node = nodes[0].clone_cast::<UiNode>();
5517        let crate::UiNodeKind::Box { children } = node.kind() else {
5518            panic!("nested node shape must preserve its raw wrapper");
5519        };
5520        assert_eq!(
5521            children[0].attributes().get("presentation"),
5522            Some(&UiValue::Bool(true))
5523        );
5524        let crate::UiNodeKind::Box { children } = children[0].kind() else {
5525            panic!("outer component must hydrate its owned snapshot");
5526        };
5527        assert!(
5528            matches!(children[1].kind(), crate::UiNodeKind::Text { text } if text == "current")
5529        );
5530    }
5531
5532    #[test]
5533    fn final_component_api_registers_render_once_and_invokes_by_id() {
5534        let mut runtime = RuntimeEngine::new();
5535        let compiled = runtime
5536            .compile(
5537                r#"
5538                    define_component(#{
5539                        metadata: #{
5540                            id: "components/message", "export": "Message", version: "0.1.0",
5541                            runtime_api: #{ min_inclusive: 3, max_exclusive: 4 },
5542                            dependencies: [], capabilities: #{}
5543                        },
5544                        schema: #{ props: #{}, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: [] },
5545                        render: Fn("render_Message")
5546                    });
5547                    fn Message(props) { render_component("components/message", props) }
5548                    fn render_Message(ctx, props) { text("final component api") }
5549                    fn view() { Message(#{ key: "message" }) }
5550                "#,
5551            )
5552            .unwrap();
5553        let root = runtime.render(&compiled).unwrap();
5554        assert!(matches!(
5555            root.kind(),
5556            crate::UiNodeKind::Text { text } if text == "final component api"
5557        ));
5558        let recipe = runtime.component_invocations().next().unwrap();
5559        assert_eq!(recipe.render_name(), "render_Message");
5560    }
5561
5562    #[test]
5563    fn self_contained_compile_rejects_dynamic_imports_before_evaluation() {
5564        let mut runtime = RuntimeEngine::new();
5565        assert!(matches!(
5566            runtime.compile_self_contained_named(
5567                "ui/dynamic_import.rhai",
5568                "let path = \"components/button\"; import path as button;",
5569            ),
5570            Err(RuntimeError::Import(_))
5571        ));
5572    }
5573
5574    #[test]
5575    fn script_builds_an_error_boundary() {
5576        let mut runtime = RuntimeEngine::new();
5577        let compiled = runtime
5578            .compile(
5579                r#"
5580                    fn view() {
5581                        error_boundary(text("content"), text("fallback"))
5582                    }
5583                "#,
5584            )
5585            .unwrap();
5586        let root = runtime.render(&compiled).unwrap();
5587        assert!(matches!(
5588            root.kind(),
5589            crate::UiNodeKind::ErrorBoundary { .. }
5590        ));
5591    }
5592
5593    #[test]
5594    fn lazy_error_boundary_catches_rhai_evaluation_failure() {
5595        let mut runtime = RuntimeEngine::new();
5596        let compiled = runtime
5597            .compile(
5598                r#"
5599                    fn broken() { throw "boom"; }
5600                    fn fallback() { text("fallback") }
5601                    fn view() { error_boundary_lazy(Fn("broken"), Fn("fallback")) }
5602                "#,
5603            )
5604            .unwrap();
5605        let root = runtime.render(&compiled).unwrap();
5606        assert!(matches!(root.kind(), crate::UiNodeKind::Text { text } if text == "fallback"));
5607        assert!(matches!(
5608            root.attributes().get("boundary_error"),
5609            Some(crate::UiValue::String(message)) if message.contains("boom")
5610        ));
5611    }
5612
5613    #[test]
5614    fn script_builds_a_typed_controlled_overlay() {
5615        let mut runtime = RuntimeEngine::new();
5616        let compiled = runtime
5617            .compile(
5618                r#"
5619                    fn changed(ctx, open) { () }
5620                    fn view() {
5621                        overlay(
5622                            text("trigger"),
5623                            text("content"),
5624                            #{
5625                                id: "account",
5626                                kind: "popover",
5627                                placement: "bottom",
5628                                open: true,
5629                                gap: 6
5630                            }
5631                        ).on_open_change(Fn("changed"))
5632                    }
5633                "#,
5634            )
5635            .unwrap();
5636        let root = runtime.render(&compiled).unwrap();
5637        assert!(matches!(
5638            root.kind(),
5639            crate::UiNodeKind::Overlay { spec, .. }
5640                if spec.id.as_str() == "account"
5641                    && spec.open
5642                    && (spec.gap - 6.0).abs() < f64::EPSILON
5643                    && spec.placement == crate::OverlayPlacement::Bottom
5644        ));
5645        assert_eq!(
5646            root.handler("open_change")
5647                .unwrap()
5648                .as_script()
5649                .unwrap()
5650                .generation(),
5651            compiled.generation()
5652        );
5653    }
5654
5655    #[test]
5656    fn click_handlers_can_carry_typed_semantic_payloads() {
5657        let mut runtime = RuntimeEngine::new();
5658        let compiled = runtime
5659            .compile(
5660                r#"
5661                    fn changed(ctx, value) { () }
5662                    fn view() {
5663                        text("toggle").on_click_value(
5664                            Fn("changed"), #{ checked: true, source: "pointer" }
5665                        )
5666                    }
5667                "#,
5668            )
5669            .unwrap();
5670        let root = runtime.render(&compiled).unwrap();
5671        assert_eq!(
5672            root.event_handlers("click")[0].value(),
5673            Some(&crate::UiValue::Map(BTreeMap::from([
5674                ("checked".to_owned(), crate::UiValue::Bool(true)),
5675                (
5676                    "source".to_owned(),
5677                    crate::UiValue::String("pointer".to_owned()),
5678                ),
5679            ])))
5680        );
5681        assert!(root.handlers().contains_key("click"));
5682    }
5683
5684    #[test]
5685    fn rhai_nodes_retain_ordered_handlers_for_all_event_phases() {
5686        let mut runtime = RuntimeEngine::new();
5687        let compiled = runtime
5688            .compile(
5689                r#"
5690                    fn first(ctx, event) { event_response().prevent_default() }
5691                    fn second(ctx, event) { event_response().stop_immediate() }
5692                    fn capture(ctx, event) { propagate() }
5693                    fn view() {
5694                        text("drag")
5695                            .on_capture("pointer_down", Fn("capture"))
5696                            .on("pointer_down", Fn("first"))
5697                            .on("pointer_down", Fn("second"))
5698                    }
5699                "#,
5700            )
5701            .unwrap();
5702        let root = runtime.render(&compiled).unwrap();
5703        let bindings = root.event_handlers("pointer_down");
5704        assert_eq!(bindings.len(), 3);
5705        assert_eq!(bindings[0].phase(), crate::EventPhase::Capture);
5706        assert_eq!(bindings[1].phase(), crate::EventPhase::Target);
5707        assert_eq!(bindings[2].phase(), crate::EventPhase::Target);
5708        assert_eq!(bindings[2].handler().as_script().unwrap().name(), "second");
5709    }
5710
5711    #[test]
5712    fn rhai_nodes_attach_only_registered_schema_checked_native_handlers() {
5713        let mut runtime = RuntimeEngine::new();
5714        let id = crate::NativeHandlerId::parse("timeline.drag").unwrap();
5715        runtime
5716            .register_native_handler(
5717                crate::NativeHandlerDescriptor::new(
5718                    id,
5719                    BTreeMap::from([("pointer_down".to_owned(), crate::ValueSchema::UiValue)]),
5720                )
5721                .unwrap(),
5722                |_, _, _, _| Ok(crate::EventResponse::new().capture_pointer()),
5723            )
5724            .unwrap();
5725        let compiled = runtime
5726            .compile(
5727                r#"
5728                    fn view() {
5729                        text("drag").on(
5730                            "pointer_down", native_handler("timeline.drag")
5731                        )
5732                    }
5733                "#,
5734            )
5735            .unwrap();
5736        let root = runtime.render(&compiled).unwrap();
5737        assert!(matches!(
5738            root.handler("pointer_down"),
5739            Some(crate::UiEventHandler::Native(reference))
5740                if reference.descriptor().id.as_str() == "timeline.drag"
5741        ));
5742
5743        let input = runtime
5744            .compile(
5745                r#"
5746                    fn view() {
5747                        gpui_rhai::TextInputPrimitive(#{
5748                            key: "native-input", value: "", placeholder: "Edit",
5749                            disabled: false, read_only: false, typography: "body",
5750                            on_change: native_handler("timeline.drag")
5751                        })
5752                    }
5753                "#,
5754            )
5755            .unwrap();
5756        assert!(
5757            runtime.render(&input).is_ok(),
5758            "native handlers must cross formal component and primitive callback props"
5759        );
5760
5761        let missing = runtime
5762            .compile(
5763                "fn view() { text(\"x\").on(\"pointer_down\", native_handler(\"app.missing\")) }",
5764            )
5765            .unwrap();
5766        assert!(runtime.render(&missing).is_err());
5767    }
5768
5769    #[test]
5770    fn final_box_and_fragment_atoms_are_distinct_snapshots() {
5771        let mut runtime = RuntimeEngine::new();
5772        let compiled = runtime
5773            .compile(
5774                r#"
5775                    fn view() {
5776                        box([text("a"), fragment([text("b"), text("c")])])
5777                    }
5778                "#,
5779            )
5780            .unwrap();
5781        let root = runtime.render(&compiled).unwrap();
5782        let crate::UiNodeKind::Box { children } = root.kind() else {
5783            panic!("root must be the final Box atom");
5784        };
5785        assert!(matches!(
5786            children[1].kind(),
5787            crate::UiNodeKind::Fragment { children } if children.len() == 2
5788        ));
5789    }
5790
5791    #[test]
5792    fn text_accepts_typed_inline_span_runs() {
5793        let mut runtime = RuntimeEngine::new();
5794        let compiled = runtime
5795            .compile(
5796                r#"
5797                    fn view() {
5798                        text([
5799                            span("Hello ").bold(),
5800                            span("world").color(rgb(0x22cc88)).italic()
5801                        ])
5802                    }
5803                "#,
5804            )
5805            .unwrap();
5806        let root = runtime.render(&compiled).unwrap();
5807        let crate::UiNodeKind::RichText { text, spans } = root.kind() else {
5808            panic!("typed spans must produce rich text");
5809        };
5810        assert_eq!(text.as_str(), "Hello world");
5811        assert_eq!(spans.len(), 2);
5812        assert!(spans[0].is_bold());
5813        assert!(spans[1].is_italic());
5814    }
5815
5816    #[test]
5817    fn canvas_scene_is_keyed_validated_and_script_constructible() {
5818        let mut runtime = RuntimeEngine::new();
5819        let compiled = runtime
5820            .compile(
5821                r#"
5822                    fn view() {
5823                        canvas(canvas_scene([
5824                            canvas_rect("panel", 0.0, 0.0, 100.0, 40.0, rgb(0x112233)),
5825                            canvas_circle("dot", 20.0, 20.0, 8.0, rgb(0xffcc00)),
5826                            canvas_line("axis", 0.0, 39.0, 100.0, 39.0, 1.0, rgb(0xffffff))
5827                        ]))
5828                    }
5829                "#,
5830            )
5831            .unwrap();
5832        let root = runtime.render(&compiled).unwrap();
5833        assert!(matches!(
5834            root.kind(),
5835            crate::UiNodeKind::Canvas { scene } if scene.commands().len() == 3
5836        ));
5837    }
5838
5839    #[test]
5840    fn inline_svg_atom_is_bounded_and_self_contained() {
5841        let mut runtime = RuntimeEngine::new();
5842        let compiled = runtime
5843            .compile(
5844                r#"
5845                    fn view() {
5846                        svg("<svg viewBox='0 0 10 10'><path fill='currentColor' d='M0 0L10 10'/></svg>")
5847                    }
5848                "#,
5849            )
5850            .unwrap();
5851        let root = runtime.render(&compiled).unwrap();
5852        assert!(matches!(
5853            root.kind(),
5854            crate::UiNodeKind::Svg { source } if source.as_str().contains("currentColor")
5855        ));
5856
5857        let rejected = runtime
5858            .compile(r#"fn view() { svg("<svg><image href='https://example.com/a.png'/></svg>") }"#)
5859            .unwrap();
5860        assert!(runtime.render(&rejected).is_err());
5861    }
5862
5863    #[test]
5864    fn recompilation_invalidates_previous_generation() {
5865        let mut runtime = RuntimeEngine::new();
5866        let first = runtime.compile("fn view() { text(\"first\") }").unwrap();
5867        runtime.render(&first).unwrap();
5868        let second = runtime.compile("fn view() { text(\"second\") }").unwrap();
5869
5870        assert!(runtime.is_current(first.generation()));
5871        assert!(!runtime.is_current(second.generation()));
5872        runtime.render(&second).unwrap();
5873        assert!(!runtime.is_current(first.generation()));
5874        assert!(runtime.is_current(second.generation()));
5875    }
5876
5877    #[test]
5878    fn callbacks_are_rejected_after_reload() {
5879        let mut runtime = RuntimeEngine::new();
5880        let first = runtime
5881            .compile(
5882                r#"
5883                    fn view() { text("first") }
5884                    fn add_suffix(value) { value + "!" }
5885                "#,
5886            )
5887            .unwrap();
5888        runtime.render(&first).unwrap();
5889        let callback = runtime.callback(&first, "add_suffix").unwrap();
5890
5891        let value = runtime
5892            .invoke_callback(&first, &callback, ("hello",))
5893            .unwrap();
5894        assert_eq!(value.into_immutable_string().unwrap(), "hello!");
5895
5896        let second = runtime.compile("fn view() { text(\"second\") }").unwrap();
5897        runtime.render(&second).unwrap();
5898        assert!(matches!(
5899            runtime.invoke_callback(&second, &callback, ("hello",)),
5900            Err(RuntimeError::StaleCallback { .. })
5901        ));
5902    }
5903
5904    #[test]
5905    fn failed_candidate_keeps_last_good_generation_active() {
5906        let mut runtime = RuntimeEngine::new();
5907        let active = runtime
5908            .compile(
5909                r#"
5910                    fn view() { text("active") }
5911                    fn action(value) { value }
5912                "#,
5913            )
5914            .unwrap();
5915        runtime.render(&active).unwrap();
5916        let callback = runtime.callback(&active, "action").unwrap();
5917
5918        let candidate = runtime
5919            .compile("fn view() { throw \"render failed\"; }")
5920            .unwrap();
5921        assert!(runtime.render(&candidate).is_err());
5922        assert!(runtime.is_current(active.generation()));
5923        let _ = runtime
5924            .invoke_callback(&active, &callback, ("still active",))
5925            .unwrap();
5926    }
5927
5928    #[test]
5929    fn failed_nested_component_records_the_deepest_component_path() {
5930        let mut runtime = RuntimeEngine::new();
5931        let compiled = runtime
5932            .compile(
5933                r#"
5934                    define_component(#{
5935                        metadata: #{ id: "components/broken", "export": "Broken",
5936                            version: "0.1.3",
5937                            runtime_api: #{ min_inclusive: 3, max_exclusive: 4 },
5938                            dependencies: [], capabilities: #{} },
5939                        schema: #{ props: #{}, state: #{ fields: #{} }, events: #{},
5940                            slots: #{}, parts: [] },
5941                        render: Fn("render_Broken")
5942                    });
5943                    fn Broken(props) { render_component("components/broken", props) }
5944                    fn render_Broken(ctx, props) { throw "nested failure"; }
5945                    fn view() { Broken(#{ key: "inner" }) }
5946                "#,
5947            )
5948            .unwrap();
5949
5950        assert!(runtime.render(&compiled).is_err());
5951        assert_eq!(
5952            runtime
5953                .last_failed_component()
5954                .as_ref()
5955                .map(ToString::to_string),
5956            Some("/App[root]/Broken[inner]".to_owned())
5957        );
5958        assert!(runtime.last_failed_timing().is_some());
5959
5960        let recovered = runtime
5961            .compile("fn view() { text(\"recovered\") }")
5962            .unwrap();
5963        runtime.render(&recovered).unwrap();
5964        assert_eq!(runtime.last_failed_component(), None);
5965        assert_eq!(runtime.last_failed_timing(), None);
5966    }
5967
5968    #[test]
5969    fn execution_timings_cover_compile_and_render() {
5970        let mut runtime = RuntimeEngine::new();
5971        runtime.set_slow_threshold(Duration::ZERO);
5972        let compiled = runtime
5973            .compile(
5974                r#"
5975                    fn view() { text("timed") }
5976                    fn counted() { let total = 0; for value in 0..100 { total += value; } total }
5977                "#,
5978            )
5979            .unwrap();
5980        runtime.render(&compiled).unwrap();
5981        let callback = runtime.callback(&compiled, "counted").unwrap();
5982        let _ = runtime.invoke_callback(&compiled, &callback, ()).unwrap();
5983        let timings = runtime.take_timings();
5984        assert_eq!(timings.len(), 3);
5985        assert_eq!(timings[0].operation, ExecutionOperation::Compile);
5986        assert_eq!(timings[1].operation, ExecutionOperation::Render);
5987        assert_eq!(
5988            timings[2].operation,
5989            ExecutionOperation::Callback("counted".to_owned())
5990        );
5991        assert_eq!(timings[0].operations, 0);
5992        assert!(timings[1].operations > 0);
5993        assert!(timings[2].operations > timings[1].operations);
5994        assert!(timings.iter().all(|timing| timing.slow && timing.succeeded));
5995    }
5996
5997    #[test]
5998    fn independent_candidates_never_share_callback_authority() {
5999        let mut runtime = RuntimeEngine::new();
6000        let first = runtime
6001            .compile("fn view() { text(\"first\") } fn action() { 1 }")
6002            .unwrap();
6003        let callback = runtime.callback(&first, "action").unwrap();
6004        let second = runtime
6005            .compile("fn view() { text(\"second\") } fn action() { 2 }")
6006            .unwrap();
6007        assert_ne!(first.generation(), second.generation());
6008        runtime.render(&second).unwrap();
6009        assert!(matches!(
6010            runtime.invoke_callback(&second, &callback, ()),
6011            Err(RuntimeError::StaleCallback { .. })
6012        ));
6013    }
6014
6015    #[test]
6016    fn callbacks_cannot_cross_runtime_engines() {
6017        let mut first_engine = RuntimeEngine::new();
6018        let first = first_engine
6019            .compile("fn view() { text(\"first\") } fn action() { 1 }")
6020            .unwrap();
6021        first_engine.render(&first).unwrap();
6022        let callback = first_engine.callback(&first, "action").unwrap();
6023
6024        let mut second_engine = RuntimeEngine::new();
6025        let second = second_engine
6026            .compile("fn view() { text(\"second\") } fn action() { 2 }")
6027            .unwrap();
6028        second_engine.render(&second).unwrap();
6029        assert!(matches!(
6030            second_engine.invoke_callback(&second, &callback, ()),
6031            Err(RuntimeError::StaleCallback { .. })
6032        ));
6033    }
6034
6035    #[test]
6036    fn one_program_preparation_shares_identity_across_module_and_entry_compilation() {
6037        let mut runtime = RuntimeEngine::new();
6038        let (module, entry) = runtime
6039            .with_program_preparation(|runtime| {
6040                Ok::<_, RuntimeError>((
6041                    runtime.compile_named("module", "fn helper() { 1 }")?,
6042                    runtime.compile_named("entry", "fn view() { text(\"entry\") }")?,
6043                ))
6044            })
6045            .unwrap();
6046        assert_eq!(module.generation(), entry.generation());
6047        let next = runtime.compile("fn view() { text(\"next\") }").unwrap();
6048        assert_ne!(entry.generation(), next.generation());
6049    }
6050
6051    #[test]
6052    fn unsafe_const_container_assignment_is_rejected_before_evaluation() {
6053        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6054            RuntimeEngine::new()
6055                .compile("fn view() { const m = #{ x: 1 }; m.x = 2; text(\"done\") }")
6056        }));
6057        assert!(matches!(
6058            result,
6059            Ok(Err(RuntimeError::InvalidAssignmentTarget(_)))
6060        ));
6061    }
6062
6063    #[test]
6064    fn default_runtime_rejects_filesystem_imports() {
6065        let directory = tempfile::tempdir().unwrap();
6066        let module = directory.path().join("external.rhai");
6067        std::fs::write(&module, "fn value() { \"external\" }").unwrap();
6068        let mut runtime = RuntimeEngine::new();
6069        let source = format!(
6070            "import {:?} as external; fn view() {{ text(external::value()) }}",
6071            module.with_extension("").to_string_lossy()
6072        );
6073        let compiled = runtime.compile(&source).unwrap();
6074        assert!(runtime.render(&compiled).is_err());
6075    }
6076
6077    #[test]
6078    fn nested_component_work_consumes_one_shared_operation_budget() {
6079        let module = r#"
6080            define_component(#{
6081                metadata: #{ id: "components/heavy", "export": "Heavy", version: "0.1.1",
6082                    runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
6083                schema: #{ props: #{}, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: ["root"] },
6084                render: Fn("render_Heavy")
6085            });
6086            fn Heavy(props) { render_component("components/heavy", props) }
6087            fn render_Heavy(ctx, props) {
6088                let n = 0;
6089                for i in 0..200000 { n += 1; }
6090                text(`${n}`)
6091            }
6092        "#;
6093        let mut resolver = crate::RestrictedModuleResolver::new();
6094        resolver.insert("components/heavy", module).unwrap();
6095        let mut runtime = RuntimeEngine::new();
6096        runtime.set_module_resolver(resolver);
6097        let compiled = runtime
6098            .compile_self_contained_named(
6099                "budget",
6100                r#"import "components/heavy" as h;
6101                    fn view() { column([h::Heavy(#{}), h::Heavy(#{}), h::Heavy(#{}), h::Heavy(#{} )]) }"#,
6102            )
6103            .unwrap();
6104        let result = runtime.render(&compiled);
6105        assert!(result.is_err(), "nested work must exceed the shared budget");
6106        assert!(
6107            runtime
6108                .take_timings()
6109                .iter()
6110                .any(|timing| timing.operations > DEFAULT_SCRIPT_OPERATION_LIMIT)
6111        );
6112    }
6113
6114    #[test]
6115    fn operation_limit_is_host_configurable() {
6116        let heavy = r"fn view() { let n = 0; for i in 0..400000 { n += 1; } text(`${n}`) }";
6117        let mut runtime = RuntimeEngine::new();
6118        assert_eq!(runtime.operation_limit(), DEFAULT_SCRIPT_OPERATION_LIMIT);
6119        let compiled = runtime
6120            .compile_self_contained_named("limit", heavy)
6121            .unwrap();
6122        assert!(
6123            runtime.render(&compiled).is_err(),
6124            "this finite workload actually exceeds the default budget"
6125        );
6126        assert!(runtime.last_failed_timing().unwrap().operations > DEFAULT_SCRIPT_OPERATION_LIMIT);
6127
6128        runtime.set_operation_limit(10_000);
6129        let compiled = runtime
6130            .compile_self_contained_named("limit-low", heavy)
6131            .unwrap();
6132        assert!(
6133            runtime.render(&compiled).is_err(),
6134            "a lowered budget rejects the same script"
6135        );
6136
6137        runtime.set_operation_limit(50_000_000);
6138        let compiled = runtime
6139            .compile_self_contained_named("limit-high", heavy)
6140            .unwrap();
6141        assert!(
6142            runtime.render(&compiled).is_ok(),
6143            "a raised budget admits heavier one-shot work"
6144        );
6145    }
6146
6147    #[test]
6148    fn a_keyword_used_as_a_name_is_named_in_the_parse_error() {
6149        let mut runtime = RuntimeEngine::new();
6150        for (source, expected) in [
6151            (
6152                "import \"components/switch\" as switch;\nfn view(ctx) { text(\"\") }",
6153                "`switch` is a Rhai keyword and cannot name a variable or an import alias",
6154            ),
6155            (
6156                "fn view(ctx) { let loop = 1; text(\"\") }",
6157                "`loop` is a Rhai keyword and cannot name a variable or an import alias",
6158            ),
6159            (
6160                "fn switch() { 1 }\nfn view(ctx) { text(\"\") }",
6161                "`switch` is a Rhai keyword and cannot name a function",
6162            ),
6163            (
6164                "fn view(ctx) { let options = #{ switch: 1 }; text(\"\") }",
6165                "`switch` is a Rhai keyword and cannot be a bare map key; quote it as `\"switch\"`",
6166            ),
6167            (
6168                "fn view(ctx) { let options = #{}; text(`${options.switch}`) }",
6169                "`switch` is a Rhai keyword and cannot name a property; index it as `[\"switch\"]`",
6170            ),
6171        ] {
6172            let error = runtime
6173                .compile_named("ui/main.rhai", source)
6174                .err()
6175                .unwrap()
6176                .to_string();
6177            assert!(error.contains(expected), "{source}: {error}");
6178        }
6179        let error = runtime
6180            .compile_named("ui/main.rhai", "fn view(ctx) { let a = 1 else 2; a }")
6181            .err()
6182            .unwrap()
6183            .to_string();
6184        assert!(!error.contains("keyword"), "{error}");
6185    }
6186
6187    #[test]
6188    fn host_policies_are_independent_and_reload_candidates_do_not_share_mutable_quota() {
6189        let mut engine = RuntimeEngine::new();
6190        assert_eq!(engine.expression_depth_limits(), (64, 64));
6191        engine.set_operation_limit(2_000_000);
6192        engine.set_expression_depth_limits(80, 64);
6193        assert_eq!(engine.engine().max_call_levels(), 64);
6194        assert_eq!(engine.engine().max_array_size(), RHAI_MAX_ARRAY_SIZE);
6195        #[cfg(feature = "dev-reload")]
6196        {
6197            let mut candidate = engine.candidate_engine();
6198            assert_eq!(candidate.operation_limit(), 2_000_000);
6199            assert_eq!(candidate.expression_depth_limits(), (80, 64));
6200            candidate.set_operation_limit(10);
6201            candidate.set_expression_depth_limits(20, 10);
6202            assert_eq!(engine.operation_limit(), 2_000_000);
6203            assert_eq!(engine.expression_depth_limits(), (80, 64));
6204        }
6205        engine.set_operation_limit(0);
6206        engine.set_expression_depth_limits(0, 0);
6207        assert_eq!(engine.operation_limit(), 1);
6208        assert_eq!(engine.expression_depth_limits(), (1, 1));
6209    }
6210
6211    #[test]
6212    fn retained_component_budget_ignores_parent_history_without_resetting_session_total() {
6213        let module = r#"
6214            define_component(#{
6215                metadata: #{ id: "components/probe", "export": "Probe", version: "0.1.1",
6216                    runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
6217                schema: #{ props: #{ key: #{ schema: #{ type: "string" }, required: true, sensitive: false } },
6218                    state: #{ fields: #{ heavy: #{ schema: #{ type: "bool" }, "default": #{ type: "bool", value: false } } } },
6219                    events: #{}, slots: #{}, parts: ["root"] },
6220                render: Fn("render_Probe")
6221            });
6222            fn Probe(props) { render_component("components/probe", props) }
6223            fn render_Probe(ctx, props) {
6224                let n = 0;
6225                if ctx.get_state("heavy") { for i in 0..100000 { n += 1; } }
6226                text(`${n}`)
6227            }
6228        "#;
6229        let mut measured = Vec::new();
6230        for parent_work in [0, 250_000] {
6231            let mut resolver = crate::RestrictedModuleResolver::new();
6232            resolver.insert("components/probe", module).unwrap();
6233            let mut engine = RuntimeEngine::new();
6234            engine.set_module_resolver(resolver);
6235            let source = format!(
6236                r#"import "components/probe" as probe;
6237                    fn view(ctx) {{
6238                        let n = 0;
6239                        for i in 0..{parent_work} {{ n += 1; }}
6240                        probe::Probe(#{{ key: "probe" }})
6241                    }}"#
6242            );
6243            let compiled = engine
6244                .compile_self_contained_named("incremental-budget", &source)
6245                .unwrap();
6246            let runtime = Rc::new(RefCell::new(crate::UiRuntimeState::new()));
6247            let mut lifecycle = crate::ScriptLifecycle::new(
6248                compiled,
6249                Rc::clone(&runtime),
6250                ComponentInstancePath::root("App", "budget"),
6251                None,
6252                BTreeMap::new(),
6253                &ComponentStateSchema::default(),
6254            )
6255            .unwrap();
6256            lifecycle.start(&mut engine).unwrap();
6257            let owner = engine
6258                .component_invocations()
6259                .next()
6260                .unwrap()
6261                .path()
6262                .clone();
6263            let _ = engine.take_timings();
6264            runtime
6265                .borrow_mut()
6266                .set_component_state_from_host(&owner, "heavy", UiValue::Bool(true))
6267                .unwrap();
6268            assert!(lifecycle.render_dirty(&mut engine).unwrap());
6269            let operations = engine
6270                .take_timings()
6271                .into_iter()
6272                .filter(|timing| timing.operation == ExecutionOperation::Render)
6273                .map(|timing| timing.operations)
6274                .sum::<u64>();
6275            assert!(
6276                operations < DEFAULT_SCRIPT_OPERATION_LIMIT / 2,
6277                "{operations}"
6278            );
6279            measured.push(operations);
6280        }
6281        assert_eq!(measured[0], measured[1]);
6282    }
6283
6284    #[test]
6285    fn multiple_dirty_components_share_one_incremental_budget() {
6286        let module = r#"
6287            define_component(#{
6288                metadata: #{ id: "components/probe", "export": "Probe", version: "0.1.1",
6289                    runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
6290                schema: #{ props: #{ key: #{ schema: #{ type: "string" }, required: true, sensitive: false } },
6291                    state: #{ fields: #{ heavy: #{ schema: #{ type: "bool" }, "default": #{ type: "bool", value: false } } } },
6292                    events: #{}, slots: #{}, parts: ["root"] }, render: Fn("render_Probe") }
6293            );
6294            fn Probe(props) { render_component("components/probe", props) }
6295            fn render_Probe(ctx, props) {
6296                let n = 0;
6297                if ctx.get_state("heavy") { for i in 0..200000 { n += 1; } }
6298                text(`${n}`)
6299            }
6300        "#;
6301        let mut resolver = crate::RestrictedModuleResolver::new();
6302        resolver.insert("components/probe", module).unwrap();
6303        let mut engine = RuntimeEngine::new();
6304        engine.set_module_resolver(resolver);
6305        let compiled = engine
6306            .compile_self_contained_named(
6307                "incremental-aggregate-budget",
6308                r#"import "components/probe" as probe;
6309                    fn view(ctx) {
6310                        column([
6311                            probe::Probe(#{ key: "first" }),
6312                            probe::Probe(#{ key: "second" }),
6313                        ])
6314                    }"#,
6315            )
6316            .unwrap();
6317        let runtime = Rc::new(RefCell::new(crate::UiRuntimeState::new()));
6318        let mut lifecycle = crate::ScriptLifecycle::new(
6319            compiled,
6320            Rc::clone(&runtime),
6321            ComponentInstancePath::root("App", "budget"),
6322            None,
6323            BTreeMap::new(),
6324            &ComponentStateSchema::default(),
6325        )
6326        .unwrap();
6327        lifecycle.start(&mut engine).unwrap();
6328        let owners = engine
6329            .component_invocations()
6330            .map(|recipe| recipe.path().clone())
6331            .collect::<Vec<_>>();
6332        assert_eq!(owners.len(), 2);
6333        for owner in owners {
6334            runtime
6335                .borrow_mut()
6336                .set_component_state_from_host(&owner, "heavy", UiValue::Bool(true))
6337                .unwrap();
6338        }
6339        assert!(lifecycle.render_dirty(&mut engine).is_err());
6340    }
6341
6342    #[test]
6343    fn retained_virtual_renderer_budget_ignores_parent_history() {
6344        let mut measured = Vec::new();
6345        for parent_work in [0, 250_000] {
6346            let mut engine = RuntimeEngine::new();
6347            let source = format!(
6348                r#"
6349                    fn render_item(ctx, payload) {{
6350                        let n = 0;
6351                        if payload.item.heavy {{ for i in 0..100000 {{ n += 1; }} }}
6352                        text(`${{n}}`).with_key(payload.key)
6353                    }}
6354                    fn view(ctx) {{
6355                        let n = 0;
6356                        for i in 0..{parent_work} {{ n += 1; }}
6357                        let data = [];
6358                        for index in 0..32 {{
6359                            data.push(#{{ key: `row-${{index}}`, heavy: index == 31 }});
6360                        }}
6361                        virtual_collection(#{{
6362                            key: "rows", label: "Rows", data: data,
6363                            estimated_height: 24, height: 24, overdraw_pixels: 0,
6364                            alignment: "top", follow_tail: false,
6365                        }}, Fn("render_item"))
6366                    }}
6367                "#
6368            );
6369            let compiled = engine.compile_named("virtual-budget", &source).unwrap();
6370            let runtime = Rc::new(RefCell::new(crate::UiRuntimeState::new()));
6371            let root_path = ComponentInstancePath::root("App", "budget");
6372            let mut lifecycle = crate::ScriptLifecycle::new(
6373                compiled,
6374                Rc::clone(&runtime),
6375                root_path.clone(),
6376                None,
6377                BTreeMap::new(),
6378                &ComponentStateSchema::default(),
6379            )
6380            .unwrap();
6381            lifecycle.start(&mut engine).unwrap();
6382            let id = engine
6383                .virtual_collection_ids_in_scope(&root_path)
6384                .into_iter()
6385                .next()
6386                .unwrap();
6387            let _ = engine.take_timings();
6388            runtime.borrow().virtual_requests.request(id, [31]);
6389            assert!(lifecycle.realize_virtual_requests(&mut engine).unwrap());
6390            let operations = engine
6391                .take_timings()
6392                .into_iter()
6393                .filter(|timing| {
6394                    matches!(timing.operation, ExecutionOperation::VirtualCollection(_))
6395                })
6396                .map(|timing| timing.operations)
6397                .sum::<u64>();
6398            assert!(
6399                operations < DEFAULT_SCRIPT_OPERATION_LIMIT / 2,
6400                "{operations}"
6401            );
6402            measured.push(operations);
6403        }
6404        assert_eq!(measured[0], measured[1]);
6405    }
6406
6407    #[test]
6408    fn retained_virtual_renderer_replays_curried_node_presentation() {
6409        let mut engine = RuntimeEngine::new();
6410        let compiled = engine
6411            .compile_named(
6412                "virtual-rich-presentation",
6413                r#"
6414                    fn render_item(content, ctx, payload) {
6415                        content[payload.key]
6416                    }
6417                    fn view(ctx) {
6418                        let data = [];
6419                        let content = #{};
6420                        for index in 0..32 {
6421                            let key = `row-${index}`;
6422                            data.push(#{ key: key });
6423                            content[key] = text(`Rich ${index}`);
6424                        }
6425                        virtual_collection(#{
6426                            key: "rows", label: "Rows", data: data,
6427                            estimated_height: 24, height: 24, overdraw_pixels: 0,
6428                            alignment: "top", follow_tail: false,
6429                        }, Fn("render_item").curry(content))
6430                    }
6431                "#,
6432            )
6433            .unwrap();
6434        let runtime = Rc::new(RefCell::new(crate::UiRuntimeState::new()));
6435        let root_path = ComponentInstancePath::root("App", "rich");
6436        let mut lifecycle = crate::ScriptLifecycle::new(
6437            compiled,
6438            Rc::clone(&runtime),
6439            root_path.clone(),
6440            None,
6441            BTreeMap::new(),
6442            &ComponentStateSchema::default(),
6443        )
6444        .unwrap();
6445        lifecycle.start(&mut engine).unwrap();
6446        let id = engine
6447            .virtual_collection_ids_in_scope(&root_path)
6448            .into_iter()
6449            .next()
6450            .unwrap();
6451        runtime.borrow().virtual_requests.request(id, [31]);
6452        assert!(lifecycle.realize_virtual_requests(&mut engine).unwrap());
6453        let crate::UiNodeKind::VirtualCollection { spec } = lifecycle.root().unwrap().kind() else {
6454            unreachable!()
6455        };
6456        assert!(matches!(
6457            spec.realized[&31].kind(),
6458            crate::UiNodeKind::Text { text } if text == "Rich 31"
6459        ));
6460    }
6461
6462    #[test]
6463    #[allow(clippy::too_many_lines)]
6464    fn virtual_row_formal_component_preserves_the_real_callback_owner() {
6465        let mut engine = RuntimeEngine::new();
6466        let compiled = engine
6467            .compile_named(
6468                "virtual-callback-owner",
6469                r#"
6470                    define_component(#{
6471                        metadata: #{ id: "test/action", "export": "Action", version: "0.1.8",
6472                            runtime_api: #{ min_inclusive: 3, max_exclusive: 4 },
6473                            dependencies: [], capabilities: #{} },
6474                        schema: #{ props: #{
6475                                key: #{ schema: #{ type: "string" }, required: true, sensitive: false },
6476                                on_action: #{ schema: #{ type: "callback" }, required: true, sensitive: false },
6477                            }, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: [] },
6478                        render: Fn("render_Action")
6479                    });
6480                    fn Action(props) { render_component("test/action", props) }
6481                    fn render_Action(ctx, props) { text("Action").on_click(props.on_action) }
6482                    fn increment(ctx, payload) { ctx.set_state("count", ctx.get_state("count") + 1); }
6483                    fn render_item(ctx, payload) {
6484                        Action(#{ key: payload.key, on_action: Fn("increment") })
6485                    }
6486                    fn view(ctx) {
6487                        let data=[];for index in 0..32 {data.push(#{key:`row-${index}`});}
6488                        virtual_collection(#{
6489                            key: "rows", label: "Rows", data: data,
6490                            estimated_height: 24, height: 24, overdraw_pixels: 0,
6491                            alignment: "top", follow_tail: false,
6492                        }, Fn("render_item"))
6493                    }
6494                "#,
6495            )
6496            .unwrap();
6497        let runtime = Rc::new(RefCell::new(crate::UiRuntimeState::new()));
6498        let root_path = ComponentInstancePath::root("App", "virtual-callback");
6499        let schema = ComponentStateSchema::new(BTreeMap::from([(
6500            "count".to_owned(),
6501            crate::StateField::new(
6502                crate::ValueSchema::Integer {
6503                    min: None,
6504                    max: None,
6505                },
6506                UiValue::Integer(0),
6507            ),
6508        )]))
6509        .unwrap();
6510        let mut lifecycle = crate::ScriptLifecycle::new(
6511            compiled,
6512            Rc::clone(&runtime),
6513            root_path.clone(),
6514            None,
6515            BTreeMap::new(),
6516            &schema,
6517        )
6518        .unwrap();
6519        lifecycle.start(&mut engine).unwrap();
6520        let crate::UiNodeKind::VirtualCollection { spec } = lifecycle.root().unwrap().kind() else {
6521            unreachable!()
6522        };
6523        let crate::UiEventHandler::Script(callback) =
6524            spec.realized[&0].handlers()["click"][0].handler()
6525        else {
6526            panic!("formal row component must retain its callback");
6527        };
6528        let _ = lifecycle
6529            .invoke_callback_transactional(&engine, callback, UiValue::Null)
6530            .unwrap();
6531        assert_eq!(
6532            runtime.borrow().component_state.get(&root_path, "count"),
6533            Some(&UiValue::Integer(1))
6534        );
6535        let id = engine
6536            .virtual_collection_ids_in_scope(&root_path)
6537            .into_iter()
6538            .next()
6539            .unwrap();
6540        assert!(
6541            !lifecycle
6542                .root()
6543                .unwrap()
6544                .virtual_collection_items(&id)
6545                .unwrap()
6546                .contains_key(&31)
6547        );
6548        runtime.borrow().virtual_requests.request(id.clone(), [31]);
6549        lifecycle.realize_virtual_requests(&mut engine).unwrap();
6550        let callback = lifecycle
6551            .root()
6552            .unwrap()
6553            .virtual_collection_items(&id)
6554            .unwrap()[&31]
6555            .handler("click")
6556            .unwrap()
6557            .as_script()
6558            .unwrap();
6559        let _ = lifecycle
6560            .invoke_callback_transactional(&engine, callback, UiValue::Null)
6561            .unwrap();
6562        assert_eq!(
6563            runtime.borrow().component_state.get(&root_path, "count"),
6564            Some(&UiValue::Integer(2))
6565        );
6566    }
6567
6568    #[test]
6569    fn plain_state_defaults_take_their_types_from_the_schema() {
6570        let mut engine = RuntimeEngine::new();
6571        let compiled = engine
6572            .compile(
6573                r#"
6574            fn state_schema() { #{ fields: #{
6575                count: #{ schema: #{ type: "integer" }, "default": 0 },
6576                ratio: #{ schema: #{ type: "float" }, "default": 1 },
6577                tags: #{ schema: #{ type: "array", items: #{ type: "string" } }, "default": ["a", "b"] },
6578                theme: #{ schema: #{ type: "object", fields: #{
6579                    family: #{ schema: #{ type: "string" }, required: true },
6580                    scale: #{ schema: #{ type: "float" }, required: true } } },
6581                    "default": #{ family: "Default", scale: 2 } },
6582                picked: #{ schema: #{ type: "optional", value: #{ type: "string" } }, "default": () },
6583                tagged: #{ schema: #{ type: "integer" }, "default": #{ type: "integer", value: 7 } },
6584            } } }
6585            fn view(ctx) { text("view") }
6586        "#,
6587            )
6588            .unwrap();
6589        let schema = engine.root_state_schema(&compiled).unwrap();
6590        let default = |name: &str| schema.field(name).unwrap().default.clone();
6591        assert_eq!(default("count"), UiValue::Integer(0));
6592        assert_eq!(default("ratio"), UiValue::Float(1.0));
6593        assert_eq!(
6594            default("tags"),
6595            UiValue::Array(vec![
6596                UiValue::String("a".to_owned()),
6597                UiValue::String("b".to_owned())
6598            ])
6599        );
6600        assert_eq!(
6601            default("theme"),
6602            UiValue::Map(BTreeMap::from([
6603                ("family".to_owned(), UiValue::String("Default".to_owned())),
6604                ("scale".to_owned(), UiValue::Float(2.0)),
6605            ]))
6606        );
6607        assert_eq!(default("picked"), UiValue::Null);
6608        assert_eq!(default("tagged"), UiValue::Integer(7));
6609
6610        let compiled = engine
6611            .compile(
6612                r#"
6613            fn state_schema() { #{ fields: #{ count: #{ schema: #{ type: "integer" }, "default": "zero" } } } }
6614            fn view(ctx) { text("view") }
6615        "#,
6616            )
6617            .unwrap();
6618        let error = engine.root_state_schema(&compiled).unwrap_err().to_string();
6619        assert!(
6620            error.contains("state_schema.fields.count.default")
6621                && error.contains("expected integer"),
6622            "{error}"
6623        );
6624    }
6625
6626    #[test]
6627    fn a_component_takes_plain_state_defaults() {
6628        let module = r#"
6629            define_component(#{
6630                metadata: #{ id: "components/probe", "export": "Probe", version: "0.1.1",
6631                    runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
6632                schema: #{ props: #{ key: #{ schema: #{ type: "string" }, required: true, sensitive: false } },
6633                    state: #{ fields: #{ widths: #{ schema: #{ type: "map", values: #{ type: "float" } },
6634                        "default": #{ name: 120, size: 80.5 } } } },
6635                    events: #{}, slots: #{}, parts: ["root"] },
6636                render: Fn("render_Probe")
6637            });
6638            fn Probe(props) { render_component("components/probe", props) }
6639            fn render_Probe(ctx, props) { text(`${ctx.get_state("widths").name}`) }
6640        "#;
6641        let mut resolver = crate::RestrictedModuleResolver::new();
6642        resolver.insert("components/probe", module).unwrap();
6643        let mut engine = RuntimeEngine::new();
6644        engine.set_module_resolver(resolver);
6645        let compiled = engine
6646            .compile_self_contained_named(
6647                "plain-defaults",
6648                r#"import "components/probe" as probe;
6649                    fn view(ctx) { probe::Probe(#{ key: "probe" }) }"#,
6650            )
6651            .unwrap();
6652        let runtime = Rc::new(RefCell::new(crate::UiRuntimeState::new()));
6653        let mut lifecycle = crate::ScriptLifecycle::new(
6654            compiled,
6655            Rc::clone(&runtime),
6656            ComponentInstancePath::root("App", "plain"),
6657            None,
6658            BTreeMap::new(),
6659            &ComponentStateSchema::default(),
6660        )
6661        .unwrap();
6662        lifecycle.start(&mut engine).unwrap();
6663        let owner = engine
6664            .component_invocations()
6665            .next()
6666            .unwrap()
6667            .path()
6668            .clone();
6669        assert_eq!(
6670            runtime.borrow().component_state.get(&owner, "widths"),
6671            Some(&UiValue::Map(BTreeMap::from([
6672                ("name".to_owned(), UiValue::Float(120.0)),
6673                ("size".to_owned(), UiValue::Float(80.5)),
6674            ])))
6675        );
6676    }
6677
6678    #[test]
6679    fn invalid_state_default_reports_the_field_and_tagged_encoding() {
6680        let mut engine = RuntimeEngine::new();
6681        let compiled = engine.compile(r#"
6682            fn state_schema() {#{fields:#{current_theme:#{schema:#{type:"map",values:#{type:"ui_value"}},
6683                "default":#{type:"map",value:#{family:"Default"}}}}}}
6684            fn view(ctx) {text("view")}
6685        "#).unwrap();
6686        let error = engine.root_state_schema(&compiled).unwrap_err().to_string();
6687        assert!(
6688            error.contains("state_schema.fields.current_theme.default"),
6689            "{error}"
6690        );
6691        assert!(error.contains("recursively tagged UiValue"), "{error}");
6692    }
6693
6694    #[test]
6695    fn delayed_component_callback_starts_with_a_fresh_operation_budget() {
6696        let module = r#"
6697            define_component(#{
6698                metadata: #{ id: "components/counter", "export": "Counter", version: "0.1.1",
6699                    runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
6700                schema: #{ props: #{}, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: ["root"] },
6701                render: Fn("render_Counter")
6702            });
6703            fn Counter(props) { render_component("components/counter", props) }
6704            fn render_Counter(ctx, props) { text("counter").on_click(Fn("clicked")) }
6705            fn clicked(ctx, payload) {
6706                let n = 0;
6707                for i in 0..100000 { n += 1; }
6708                n
6709            }
6710        "#;
6711        let mut resolver = crate::RestrictedModuleResolver::new();
6712        resolver.insert("components/counter", module).unwrap();
6713        let mut engine = RuntimeEngine::new();
6714        engine.set_module_resolver(resolver);
6715        let compiled = engine
6716            .compile_self_contained_named(
6717                "callback-budget",
6718                r#"import "components/counter" as c;
6719                    fn view(ctx) {
6720                        let n = 0;
6721                        for i in 0..250000 { n += 1; }
6722                        c::Counter(#{} )
6723                    }"#,
6724            )
6725            .unwrap();
6726        let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
6727        let mut lifecycle = crate::ScriptLifecycle::new(
6728            compiled,
6729            runtime,
6730            ComponentInstancePath::root("App", "budget"),
6731            None,
6732            BTreeMap::new(),
6733            &ComponentStateSchema::default(),
6734        )
6735        .unwrap();
6736        let root = lifecycle.start(&mut engine).unwrap();
6737        let crate::UiEventHandler::Script(callback) = root.handlers()["click"][0].handler() else {
6738            panic!("component must expose a script click callback");
6739        };
6740        let callback = callback.clone();
6741        assert!(
6742            lifecycle
6743                .invoke_callback_transactional(&engine, &callback, UiValue::Null)
6744                .is_ok()
6745        );
6746    }
6747
6748    #[test]
6749    fn old_component_handles_cannot_target_a_same_key_remount() {
6750        let module = r#"
6751            define_component(#{
6752                metadata: #{ id: "components/incarnation", "export": "Counter", version: "0.1.1",
6753                    runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
6754                schema: #{ props: #{ key: #{ schema: #{ type: "string" }, required: true, sensitive: false } },
6755                    state: #{ fields: #{ count: #{ schema: #{ type: "integer" }, "default": #{ type: "integer", value: 0 } } } },
6756                    events: #{}, slots: #{}, parts: ["root"] }, render: Fn("render_Counter")
6757            });
6758            fn Counter(props) { render_component("components/incarnation", props) }
6759            fn increment(ctx, payload) { ctx.set_state("count", ctx.get_state("count") + 1); }
6760            fn render_Counter(ctx, props) {
6761                let progress = signal("progress", 0.0);
6762                text(`${ctx.get_state("count")}`).bind_signal("opacity", progress).on_click(Fn("increment"))
6763            }
6764        "#;
6765        let mut resolver = crate::RestrictedModuleResolver::new();
6766        resolver.insert("components/incarnation", module).unwrap();
6767        let mut engine = RuntimeEngine::new();
6768        engine.set_module_resolver(resolver);
6769        let compiled = engine
6770            .compile_self_contained_named(
6771                "incarnation",
6772                r#"import "components/incarnation" as c;
6773                    fn view(ctx) {
6774                        if ctx.get_state("visible") { c::Counter(#{ key: "same" }) }
6775                        else { text("hidden") }
6776                    }"#,
6777            )
6778            .unwrap();
6779        let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
6780        let root_path = ComponentInstancePath::root("App", "incarnation");
6781        let schema = ComponentStateSchema::new(BTreeMap::from([(
6782            "visible".to_owned(),
6783            crate::StateField::new(crate::ValueSchema::Bool, UiValue::Bool(true)),
6784        )]))
6785        .unwrap();
6786        let mut lifecycle = crate::ScriptLifecycle::new(
6787            compiled,
6788            Rc::clone(&runtime),
6789            root_path.clone(),
6790            None,
6791            BTreeMap::new(),
6792            &schema,
6793        )
6794        .unwrap();
6795        lifecycle.start(&mut engine).unwrap();
6796        let component = engine
6797            .component_invocations()
6798            .next()
6799            .unwrap()
6800            .path()
6801            .clone();
6802        let crate::UiEventHandler::Script(old_callback) =
6803            lifecycle.root().unwrap().handlers()["click"][0].handler()
6804        else {
6805            panic!("component must expose its callback");
6806        };
6807        let old_callback = old_callback.clone();
6808        let old_signal = runtime
6809            .borrow()
6810            .signals
6811            .resolve(&component, "progress")
6812            .unwrap();
6813        runtime
6814            .borrow_mut()
6815            .set_component_state_from_host(&root_path, "visible", UiValue::Bool(false))
6816            .unwrap();
6817        lifecycle.render_dirty(&mut engine).unwrap();
6818        runtime
6819            .borrow_mut()
6820            .set_component_state_from_host(&root_path, "visible", UiValue::Bool(true))
6821            .unwrap();
6822        lifecycle.render_dirty(&mut engine).unwrap();
6823        assert!(matches!(
6824            lifecycle.invoke_callback_transactional(&engine, &old_callback, UiValue::Null),
6825            Err(crate::LifecycleError::Runtime(
6826                RuntimeError::StaleComponentCallback { .. }
6827            ))
6828        ));
6829        assert!(matches!(
6830            runtime
6831                .borrow_mut()
6832                .signals
6833                .write(&old_signal, crate::SignalValue::Float(0.5)),
6834            Err(crate::SignalError::Stale(_))
6835        ));
6836    }
6837}