Skip to main content

euv_core/scene/dsl/view_runtime/
fn.rs

1use super::*;
2
3/// Mounts a `view` container node with `Style::default()` in one monomorphic call.
4///
5/// # Returns
6///
7/// - `NodeId` - Created container node handle.
8#[must_use]
9#[cfg_attr(not(target_arch = "wasm32"), inline)]
10pub fn mount_view_default() -> NodeId {
11    mount_view(Style::default())
12}
13
14/// Mounts a `view` container node with `style` in one monomorphic call.
15///
16/// # Arguments
17///
18/// - `Style` - Initial box style.
19///
20/// # Returns
21///
22/// - `NodeId` - Created container node handle.
23#[must_use]
24#[cfg_attr(not(target_arch = "wasm32"), inline)]
25pub fn mount_view(style: Style) -> NodeId {
26    with_current_context(|context: &Context| {
27        context.get_scene().with_write(
28            |tree: &mut SceneTree| tree.create_view(style),
29            NodeId::default(),
30        )
31    })
32}
33
34/// Mounts a horizontal `row` flex container with default style in one monomorphic call.
35///
36/// # Returns
37///
38/// - `NodeId` - Created row container node handle.
39#[must_use]
40#[cfg_attr(not(target_arch = "wasm32"), inline)]
41pub fn mount_row_default() -> NodeId {
42    mount_view(Style::default())
43}
44
45/// Mounts a horizontal `row` flex container enforcing `FlexDirection::Row` in one monomorphic call.
46///
47/// # Arguments
48///
49/// - `Style` - Base container style.
50///
51/// # Returns
52///
53/// - `NodeId` - Created row container node handle.
54#[must_use]
55#[cfg_attr(not(target_arch = "wasm32"), inline)]
56pub fn mount_row(mut style: Style) -> NodeId {
57    let layout: &mut LayoutStyle = style.get_mut_layout();
58    if layout.get_display() != Display::None {
59        layout.set_display(Display::Flex);
60    }
61    layout.set_flex_direction(FlexDirection::Row);
62    mount_view(style)
63}
64
65/// Mounts a vertical `column` flex container with default style in one monomorphic call.
66///
67/// # Returns
68///
69/// - `NodeId` - Created column container node handle.
70#[must_use]
71#[cfg_attr(not(target_arch = "wasm32"), inline)]
72pub fn mount_column_default() -> NodeId {
73    let mut style: Style = Style::default();
74    style
75        .get_mut_layout()
76        .set_flex_direction(FlexDirection::Column);
77    mount_view(style)
78}
79
80/// Mounts a vertical `column` flex container enforcing `FlexDirection::Column` in one monomorphic call.
81///
82/// # Arguments
83///
84/// - `Style` - Base container style.
85///
86/// # Returns
87///
88/// - `NodeId` - Created column container node handle.
89#[must_use]
90#[cfg_attr(not(target_arch = "wasm32"), inline)]
91pub fn mount_column(mut style: Style) -> NodeId {
92    let layout: &mut LayoutStyle = style.get_mut_layout();
93    if layout.get_display() != Display::None {
94        layout.set_display(Display::Flex);
95    }
96    layout.set_flex_direction(FlexDirection::Column);
97    mount_view(style)
98}
99
100/// Mounts a 2-column `grid` container with default style in one monomorphic call.
101///
102/// # Returns
103///
104/// - `NodeId` - Created grid container node handle.
105#[must_use]
106#[cfg_attr(not(target_arch = "wasm32"), inline)]
107pub fn mount_grid_default() -> NodeId {
108    let mut style: Style = Style::default();
109    style
110        .get_mut_layout()
111        .set_display(Display::Grid)
112        .set_grid_columns(2);
113    mount_view(style)
114}
115
116/// Mounts a `grid` container defaulting to 2 columns when `Display::Grid` was not explicitly set.
117///
118/// # Arguments
119///
120/// - `Style` - Base grid container style.
121///
122/// # Returns
123///
124/// - `NodeId` - Created grid container node handle.
125#[must_use]
126#[cfg_attr(not(target_arch = "wasm32"), inline)]
127pub fn mount_grid(mut style: Style) -> NodeId {
128    let layout: &mut LayoutStyle = style.get_mut_layout();
129    if layout.get_display() != Display::Grid && layout.get_display() != Display::None {
130        layout.set_display(Display::Grid).set_grid_columns(2);
131    }
132    mount_view(style)
133}
134
135/// Mounts a vertical `scroll` container with default style in one monomorphic call.
136///
137/// # Returns
138///
139/// - `NodeId` - Created scroll container node handle.
140#[must_use]
141#[cfg_attr(not(target_arch = "wasm32"), inline)]
142pub fn mount_scroll_default() -> NodeId {
143    let mut style: Style = Style::default();
144    style
145        .get_mut_layout()
146        .set_flex_direction(FlexDirection::Column);
147    mount_scroll(style)
148}
149
150/// Mounts a `scroll` container with `style` in one monomorphic call.
151///
152/// # Arguments
153///
154/// - `Style` - Scroll container style.
155///
156/// # Returns
157///
158/// - `NodeId` - Created scroll container node handle.
159#[must_use]
160#[cfg_attr(not(target_arch = "wasm32"), inline)]
161pub fn mount_scroll(style: Style) -> NodeId {
162    with_current_context(|context: &Context| {
163        context.get_scene().with_write(
164            |tree: &mut SceneTree| tree.create_scroll_view(style),
165            NodeId::default(),
166        )
167    })
168}
169
170/// Mounts a `portal` overlay node with default style in one monomorphic call.
171///
172/// # Returns
173///
174/// - `NodeId` - Created portal node handle.
175#[must_use]
176#[cfg_attr(not(target_arch = "wasm32"), inline)]
177pub fn mount_portal_default() -> NodeId {
178    mount_portal(Style::default())
179}
180
181/// Mounts a `portal` overlay node with `style` in one monomorphic call.
182///
183/// # Arguments
184///
185/// - `Style` - Portal style.
186///
187/// # Returns
188///
189/// - `NodeId` - Created portal node handle.
190#[must_use]
191#[cfg_attr(not(target_arch = "wasm32"), inline)]
192pub fn mount_portal(style: Style) -> NodeId {
193    with_current_context(|context: &Context| {
194        context.get_scene().with_write(
195            |tree: &mut SceneTree| tree.create_portal(style),
196            NodeId::default(),
197        )
198    })
199}
200
201/// Mounts a logical `fragment` grouping node in one monomorphic call.
202///
203/// # Returns
204///
205/// - `NodeId` - Created fragment node handle.
206#[must_use]
207#[cfg_attr(not(target_arch = "wasm32"), inline)]
208pub fn mount_fragment() -> NodeId {
209    with_current_context(|context: &Context| {
210        context.get_scene().with_write(
211            |tree: &mut SceneTree| tree.create_fragment(),
212            NodeId::default(),
213        )
214    })
215}
216
217/// Mounts a static `text` node with `Style::default()` from a `&str` slice in one monomorphic call.
218///
219/// # Arguments
220///
221/// - `&str` - Static UTF-8 text content.
222///
223/// # Returns
224///
225/// - `NodeId` - Created text node handle.
226#[must_use]
227#[cfg_attr(not(target_arch = "wasm32"), inline)]
228pub fn mount_plain_text_str(content: &str) -> NodeId {
229    mount_text_str(content, Style::default())
230}
231
232/// Mounts a static `text` node with `style` from a `&str` slice in one monomorphic call.
233///
234/// # Arguments
235///
236/// - `&str` - Static UTF-8 text content.
237/// - `Style` - Text style.
238///
239/// # Returns
240///
241/// - `NodeId` - Created text node handle.
242#[must_use]
243#[cfg_attr(not(target_arch = "wasm32"), inline)]
244pub fn mount_text_str(content: &str, style: Style) -> NodeId {
245    let owned_text: String = content.to_string();
246    with_current_context(|context: &Context| {
247        context.get_scene().with_write(
248            |tree: &mut SceneTree| tree.create_text(owned_text, style),
249            NodeId::default(),
250        )
251    })
252}
253
254/// Mounts an `input` leaf node from `state` and `style` in one monomorphic call.
255///
256/// # Arguments
257///
258/// - `InputNodeState` - Initial input node state.
259/// - `Style` - Input style.
260///
261/// # Returns
262///
263/// - `NodeId` - Created input node handle.
264#[must_use]
265#[cfg_attr(not(target_arch = "wasm32"), inline)]
266pub fn mount_input_node(state: InputNodeState, style: Style) -> NodeId {
267    with_current_context(|context: &Context| {
268        context.get_scene().with_write(
269            |tree: &mut SceneTree| tree.create_input(state, style),
270            NodeId::default(),
271        )
272    })
273}
274
275/// Mounts an `image` leaf node from `buffer` and `style` in one monomorphic call.
276///
277/// # Arguments
278///
279/// - `ImageBuffer` - Decoded RGBA8 image buffer.
280/// - `Style` - Image style.
281///
282/// # Returns
283///
284/// - `NodeId` - Created image node handle.
285#[must_use]
286#[cfg_attr(not(target_arch = "wasm32"), inline)]
287pub fn mount_image_node(buffer: ImageBuffer, style: Style) -> NodeId {
288    with_current_context(|context: &Context| {
289        context.get_scene().with_write(
290            |tree: &mut SceneTree| tree.create_image(buffer, style),
291            NodeId::default(),
292        )
293    })
294}
295
296/// Mounts a `canvas` leaf node with `style`, `caching`, and `painter` in one monomorphic call.
297///
298/// # Arguments
299///
300/// - `Style` - Canvas style.
301/// - `CanvasCaching` - Fragment caching strategy.
302/// - `CanvasDrawCallback` - Shared canvas draw callback.
303///
304/// # Returns
305///
306/// - `NodeId` - Created canvas node handle.
307#[must_use]
308#[cfg_attr(not(target_arch = "wasm32"), inline)]
309pub fn mount_canvas_node(
310    style: Style,
311    caching: CanvasCaching,
312    painter: CanvasDrawCallback,
313) -> NodeId {
314    with_current_context(|context: &Context| {
315        context.get_scene().with_write(
316            |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, painter),
317            NodeId::default(),
318        )
319    })
320}
321
322/// Mounts a `slot` dynamic component slot in one monomorphic call.
323///
324/// # Arguments
325///
326/// - `String` - Slot identifier.
327/// - `Style` - Slot wrapper style.
328/// - `Option<DynamicUpdateHub>` - Optional explicit dynamic hub override.
329/// - `DynamicSlotFallback` - Fallback builder closure.
330///
331/// # Returns
332///
333/// - `NodeId` - Mounted dynamic component slot node handle.
334#[must_use]
335pub fn mount_dynamic_slot(
336    slot_id: String,
337    style: Style,
338    hub: Option<DynamicUpdateHub>,
339    fallback: DynamicSlotFallback,
340) -> NodeId {
341    let mut slot: DynamicComponentSlot = DynamicComponentSlot::new(slot_id, fallback);
342    let _: &mut DynamicComponentSlot = slot.set_style(style);
343    if hub.is_some() {
344        let _: &mut DynamicComponentSlot = slot.set_hub(hub);
345    }
346    Component::mount(slot)
347}
348
349/// Mounts a `page_slot` dynamic page slot in one monomorphic call.
350///
351/// # Arguments
352///
353/// - `String` - Page route key.
354/// - `Style` - Slot wrapper style.
355/// - `Option<DynamicUpdateHub>` - Optional explicit dynamic hub override.
356/// - `DynamicSlotFallback` - Fallback builder closure.
357///
358/// # Returns
359///
360/// - `NodeId` - Mounted dynamic page slot node handle.
361#[must_use]
362pub fn mount_dynamic_page_slot(
363    route: String,
364    style: Style,
365    hub: Option<DynamicUpdateHub>,
366    fallback: DynamicSlotFallback,
367) -> NodeId {
368    let mut slot: DynamicPageSlot = DynamicPageSlot::new(route, fallback);
369    let _: &mut DynamicPageSlot = slot.set_style(style);
370    if hub.is_some() {
371        let _: &mut DynamicPageSlot = slot.set_hub(hub);
372    }
373    Component::mount(slot)
374}
375
376/// Builds an empty fallback `DynamicSlotFallback` for `slot` and `page_slot` without duplicating closure AST per macro call site.
377///
378/// # Returns
379///
380/// - `DynamicSlotFallback` - Shared empty view fallback builder.
381#[must_use]
382pub fn empty_slot_fallback() -> DynamicSlotFallback {
383    Rc::new(mount_view_default)
384}
385
386/// Mounts a full-width column wrapper used for multi-child `slot` and `page_slot` fallbacks.
387///
388/// # Returns
389///
390/// - `NodeId` - Mounted full-width column wrapper node.
391#[must_use]
392pub fn mount_slot_fallback_column() -> NodeId {
393    let mut style: Style = Style::default();
394    style
395        .get_mut_layout()
396        .set_flex_direction(FlexDirection::Column)
397        .set_width(Length::Percent(100.0));
398    mount_view(style)
399}
400
401/// Appends a single child `NodeId` to `parent` in one monomorphic call.
402///
403/// # Arguments
404///
405/// - `NodeId` - Parent container node handle.
406/// - `NodeId` - Child node handle to attach.
407#[cfg_attr(not(target_arch = "wasm32"), inline)]
408pub fn append_view_child(parent: NodeId, child: NodeId) {
409    with_current_context(|context: &Context| {
410        context.get_scene().with_write(
411            |tree: &mut SceneTree| {
412                tree.append_child(parent, child);
413            },
414            (),
415        );
416    });
417}
418
419/// Appends a slice of `children` to `parent` in one monomorphic call.
420///
421/// # Arguments
422///
423/// - `NodeId` - Parent container node handle.
424/// - `&[NodeId]` - Ordered child node handles to attach.
425#[cfg_attr(not(target_arch = "wasm32"), inline)]
426pub fn append_view_children(parent: NodeId, children: &[NodeId]) {
427    if children.is_empty() {
428        return;
429    }
430    with_current_context(|context: &Context| {
431        context.get_scene().with_write(
432            |tree: &mut SceneTree| {
433                tree.append_children(parent, children);
434            },
435            (),
436        );
437    });
438}
439
440/// Mounts every item in `items` and appends the resulting slice to `parent`.
441///
442/// # Arguments
443///
444/// - `NodeId` - Parent container node handle.
445/// - `Iter` - Iterable of mountable `Component` items.
446pub fn mount_spread_into<Iter, Item>(parent: NodeId, items: Iter)
447where
448    Iter: IntoIterator<Item = Item>,
449    Item: Component,
450{
451    let mounted: Vec<NodeId> = items.into_iter().map(Component::mount).collect();
452    append_view_children(parent, &mounted);
453}
454
455/// Mounts every item in `items` and appends the resulting `NodeId`s into `batch`.
456///
457/// # Arguments
458///
459/// - `&mut Vec<NodeId>` - Target child accumulator.
460/// - `Iter` - Iterable of mountable `Component` items.
461pub fn extend_spread_into<Iter, Item>(batch: &mut Vec<NodeId>, items: Iter)
462where
463    Iter: IntoIterator<Item = Item>,
464    Item: Component,
465{
466    batch.extend(items.into_iter().map(Component::mount));
467}
468
469/// Wraps an event closure into a `UiEventHandler` without emitting local helper functions at every `view!` call site.
470///
471/// # Arguments
472///
473/// - `HandlerFn` - Event callback closure receiving `&UiEvent`.
474///
475/// # Returns
476///
477/// - `UiEventHandler` - Shared boxed event callback.
478#[must_use]
479#[cfg_attr(not(target_arch = "wasm32"), inline)]
480pub fn into_ui_event_handler<HandlerFn>(handler: HandlerFn) -> UiEventHandler
481where
482    HandlerFn: FnMut(&UiEvent) + 'static,
483{
484    Rc::new(RefCell::new(handler))
485}
486
487/// Wraps a canvas painter closure into a `CanvasDrawCallback` without emitting local helper functions at every `view!` call site.
488///
489/// # Arguments
490///
491/// - `PainterFn` - Canvas draw closure receiving `(Rect, &mut DisplayList)`.
492///
493/// # Returns
494///
495/// - `CanvasDrawCallback` - Shared boxed canvas painter callback.
496#[must_use]
497#[cfg_attr(not(target_arch = "wasm32"), inline)]
498pub fn into_canvas_painter<PainterFn>(painter: PainterFn) -> CanvasDrawCallback
499where
500    PainterFn: FnMut(Rect, &mut DisplayList) + 'static,
501{
502    Rc::new(RefCell::new(painter))
503}
504
505/// Fast-path monomorphic helper attaching a single `on_click` handler, focusable flag, and pointer cursor onto `node`.
506///
507/// # Arguments
508///
509/// - `NodeId` - Target scene node handle.
510/// - `UiEventHandler` - Click callback handler.
511#[cfg_attr(not(target_arch = "wasm32"), inline)]
512pub fn bind_node_on_click(node: NodeId, handler: UiEventHandler) {
513    with_current_context(|context: &Context| {
514        context.get_scene().with_write(
515            |tree: &mut SceneTree| {
516                if let Some(scene_node) = tree.get_node_mut(node) {
517                    scene_node.get_mut_handlers().set_on_click(Some(handler));
518                    scene_node.get_mut_interaction().set_focusable(true);
519                    let paint: &mut PaintStyle = scene_node.get_mut_style().get_mut_paint();
520                    if paint.get_cursor() == CursorIcon::Default {
521                        paint.set_cursor(CursorIcon::Pointer);
522                    }
523                }
524            },
525            (),
526        );
527    });
528}
529
530/// Appends a single child `NodeId` to `parent` and returns `parent` for zero-local expression chaining.
531///
532/// # Arguments
533///
534/// - `NodeId` - Parent container node handle.
535/// - `NodeId` - Child node handle to attach.
536///
537/// # Returns
538///
539/// - `NodeId` - Unmodified `parent` handle.
540#[must_use]
541#[cfg_attr(not(target_arch = "wasm32"), inline)]
542pub fn finish_node_child(parent: NodeId, child: NodeId) -> NodeId {
543    append_view_child(parent, child);
544    parent
545}
546
547/// Appends a slice of `children` to `parent` and returns `parent` for zero-local expression chaining.
548///
549/// # Arguments
550///
551/// - `NodeId` - Parent container node handle.
552/// - `&[NodeId]` - Ordered child node handles to attach.
553///
554/// # Returns
555///
556/// - `NodeId` - Unmodified `parent` handle.
557#[must_use]
558#[cfg_attr(not(target_arch = "wasm32"), inline)]
559pub fn finish_node_children(parent: NodeId, children: &[NodeId]) -> NodeId {
560    append_view_children(parent, children);
561    parent
562}
563
564/// Attaches a single `on_click` handler onto `node` and returns `node` for zero-local expression chaining.
565///
566/// # Arguments
567///
568/// - `NodeId` - Target scene node handle.
569/// - `UiEventHandler` - Click callback handler.
570///
571/// # Returns
572///
573/// - `NodeId` - Unmodified `node` handle.
574#[must_use]
575#[cfg_attr(not(target_arch = "wasm32"), inline)]
576pub fn finish_node_on_click(node: NodeId, handler: UiEventHandler) -> NodeId {
577    bind_node_on_click(node, handler);
578    node
579}
580
581/// Applies `patch` onto `node` under one scene write lock and returns `node` for zero-local expression chaining.
582///
583/// # Arguments
584///
585/// - `NodeId` - Target scene node handle.
586/// - `NodeInitPatch` - Accumulated event and accessibility modifiers.
587///
588/// # Returns
589///
590/// - `NodeId` - Unmodified `node` handle.
591#[must_use]
592#[cfg_attr(not(target_arch = "wasm32"), inline)]
593pub fn finish_node_patch(node: NodeId, patch: NodeInitPatch) -> NodeId {
594    apply_node_init_patch(node, patch);
595    node
596}
597
598/// Applies all event handlers, focusability, and accessibility metadata in `patch` onto `node` under a single scene write lock.
599///
600/// # Arguments
601///
602/// - `NodeId` - Target scene node handle.
603/// - `NodeInitPatch` - Accumulated event and accessibility modifiers.
604pub fn apply_node_init_patch(node: NodeId, patch: NodeInitPatch) {
605    let NodeInitPatch {
606        focusable,
607        on_click,
608        on_change,
609        on_scroll,
610        on_pointer_down,
611        on_pointer_move,
612        on_pointer_up,
613        on_pointer_enter,
614        on_pointer_leave,
615        on_key_down,
616        on_focus,
617        on_blur,
618        a11y,
619    } = patch;
620    with_current_context(|context: &Context| {
621        context.get_scene().with_write(
622            |tree: &mut SceneTree| {
623                let Some(scene_node) = tree.get_node_mut(node) else {
624                    return;
625                };
626                if let Some(is_focusable) = focusable {
627                    scene_node.get_mut_interaction().set_focusable(is_focusable);
628                }
629                if let Some(handler) = on_click {
630                    scene_node.get_mut_handlers().set_on_click(Some(handler));
631                    scene_node.get_mut_interaction().set_focusable(true);
632                    let paint: &mut PaintStyle = scene_node.get_mut_style().get_mut_paint();
633                    if paint.get_cursor() == CursorIcon::Default {
634                        paint.set_cursor(CursorIcon::Pointer);
635                    }
636                }
637                if let Some(handler) = on_change {
638                    scene_node.get_mut_handlers().set_on_change(Some(handler));
639                }
640                if let Some(handler) = on_scroll {
641                    scene_node.get_mut_handlers().set_on_scroll(Some(handler));
642                }
643                if let Some(handler) = on_pointer_down {
644                    scene_node
645                        .get_mut_handlers()
646                        .set_on_pointer_down(Some(handler));
647                    let paint: &mut PaintStyle = scene_node.get_mut_style().get_mut_paint();
648                    if paint.get_cursor() == CursorIcon::Default {
649                        paint.set_cursor(CursorIcon::Pointer);
650                    }
651                }
652                if let Some(handler) = on_pointer_move {
653                    scene_node
654                        .get_mut_handlers()
655                        .set_on_pointer_move(Some(handler));
656                }
657                if let Some(handler) = on_pointer_up {
658                    scene_node
659                        .get_mut_handlers()
660                        .set_on_pointer_up(Some(handler));
661                }
662                if let Some(handler) = on_pointer_enter {
663                    scene_node
664                        .get_mut_handlers()
665                        .set_on_pointer_enter(Some(handler));
666                }
667                if let Some(handler) = on_pointer_leave {
668                    scene_node
669                        .get_mut_handlers()
670                        .set_on_pointer_leave(Some(handler));
671                }
672                if let Some(handler) = on_key_down {
673                    scene_node.get_mut_handlers().set_on_key_down(Some(handler));
674                    scene_node.get_mut_interaction().set_focusable(true);
675                }
676                if let Some(handler) = on_focus {
677                    scene_node.get_mut_handlers().set_on_focus(Some(handler));
678                    scene_node.get_mut_interaction().set_focusable(true);
679                }
680                if let Some(handler) = on_blur {
681                    scene_node.get_mut_handlers().set_on_blur(Some(handler));
682                }
683                if let Some(props) = a11y {
684                    scene_node.set_a11y(Some(props));
685                }
686            },
687            (),
688        );
689    });
690}