Skip to main content

cranpose_ui/modifier/
slices.rs

1use std::{fmt, mem::size_of, rc::Rc};
2
3use cranpose_foundation::{ModifierNodeChain, NodeCapabilities, PointerEvent, PointerEventKind};
4use cranpose_ui_graphics::{
5    ColorFilter, EdgeInsets, GraphicsLayer, LayerShape, PointerIcon, RenderEffect,
6    RoundedCornerShape,
7};
8
9use super::{ModifierChainHandle, Point};
10use crate::{
11    draw::DrawCommand,
12    modifier::{
13        Modifier,
14        scroll::{MotionContextAnimatedNode, TranslatedContentContextNode},
15    },
16    modifier_nodes::{
17        BackgroundNode, ClipToBoundsNode, CornerShapeNode, DrawCommandNode, GraphicsLayerNode,
18        PaddingNode, PointerIconNode, WindowRectReporterNode,
19    },
20    text::{TextLayoutOptions, TextStyle},
21    text_field_modifier_node::{TextFieldLayoutHandle, TextFieldModifierNode, TextPanResolver},
22    text_modifier_node::{TextModifierNode, TextPreparedLayoutHandle},
23};
24
25/// Snapshot of modifier node slices that impact draw and pointer subsystems.
26#[derive(Default)]
27pub struct ModifierNodeSlices {
28    draw_commands: Vec<DrawCommand>,
29    layer_draw_boundary: Option<usize>,
30    pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
31    pointer_input_sizes: Vec<Rc<std::cell::Cell<cranpose_ui_graphics::Size>>>,
32    click_handlers: Vec<Rc<dyn Fn(Point)>>,
33    pointer_icon: Option<PointerIcon>,
34    clip_to_bounds: bool,
35    motion_context_animated: bool,
36    translated_content_context: bool,
37    translated_content_context_identity: Option<usize>,
38    translated_content_offset_reader: Option<Rc<dyn Fn() -> Point>>,
39    text_content: Option<Rc<crate::text::AnnotatedString>>,
40    text_style: Option<TextStyle>,
41    text_layout_options: Option<TextLayoutOptions>,
42    prepared_text_layout: Option<MeasuredTextLayoutSource>,
43    text_pan: Option<TextPanResolver>,
44    text_field_window_origin: Option<Rc<std::cell::Cell<Point>>>,
45    viewport_window_rect: Option<Rc<dyn crate::modifier_nodes::WindowRectSink>>,
46    graphics_layer: Option<GraphicsLayer>,
47    graphics_layer_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
48    corner_shape: Option<RoundedCornerShape>,
49    chain_guard: Option<Rc<ChainGuard>>,
50}
51
52struct ChainGuard {
53    _handle: ModifierChainHandle,
54}
55
56#[derive(Clone)]
57enum MeasuredTextLayoutSource {
58    Text(TextPreparedLayoutHandle),
59    TextField(TextFieldLayoutHandle),
60}
61
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63pub struct ModifierNodeSlicesDebugStats {
64    pub draw_command_count: usize,
65    pub draw_command_capacity: usize,
66    pub pointer_input_count: usize,
67    pub pointer_input_capacity: usize,
68    pub click_handler_count: usize,
69    pub click_handler_capacity: usize,
70    pub has_text_content: bool,
71    pub has_text_style: bool,
72    pub has_text_layout_options: bool,
73    pub has_prepared_text_layout: bool,
74    pub has_graphics_layer: bool,
75    pub has_graphics_layer_resolver: bool,
76    pub heap_bytes: usize,
77}
78
79impl Clone for ModifierNodeSlices {
80    fn clone(&self) -> Self {
81        Self {
82            draw_commands: self.draw_commands.clone(),
83            layer_draw_boundary: self.layer_draw_boundary,
84            pointer_inputs: self.pointer_inputs.clone(),
85            pointer_input_sizes: self.pointer_input_sizes.clone(),
86            click_handlers: self.click_handlers.clone(),
87            pointer_icon: self.pointer_icon.clone(),
88            clip_to_bounds: self.clip_to_bounds,
89            motion_context_animated: self.motion_context_animated,
90            translated_content_context: self.translated_content_context,
91            translated_content_context_identity: self.translated_content_context_identity,
92            translated_content_offset_reader: self.translated_content_offset_reader.clone(),
93            text_content: self.text_content.clone(),
94            text_style: self.text_style.clone(),
95            text_layout_options: self.text_layout_options,
96            prepared_text_layout: self.prepared_text_layout.clone(),
97            text_pan: self.text_pan.clone(),
98            text_field_window_origin: self.text_field_window_origin.clone(),
99            viewport_window_rect: self.viewport_window_rect.clone(),
100            graphics_layer: self.graphics_layer.clone(),
101            graphics_layer_resolver: self.graphics_layer_resolver.clone(),
102            corner_shape: self.corner_shape,
103            chain_guard: self.chain_guard.clone(),
104        }
105    }
106}
107
108fn merge_graphics_layers(base: GraphicsLayer, overlay: GraphicsLayer) -> GraphicsLayer {
109    GraphicsLayer {
110        alpha: (base.alpha * overlay.alpha).clamp(0.0, 1.0),
111        scale: base.scale * overlay.scale,
112        scale_x: base.scale_x * overlay.scale_x,
113        scale_y: base.scale_y * overlay.scale_y,
114        rotation_x: base.rotation_x + overlay.rotation_x,
115        rotation_y: base.rotation_y + overlay.rotation_y,
116        rotation_z: base.rotation_z + overlay.rotation_z,
117        camera_distance: overlay.camera_distance,
118        transform_origin: overlay.transform_origin,
119        translation_x: base.translation_x + overlay.translation_x,
120        translation_y: base.translation_y + overlay.translation_y,
121        shadow_elevation: overlay.shadow_elevation,
122        ambient_shadow_color: overlay.ambient_shadow_color,
123        spot_shadow_color: overlay.spot_shadow_color,
124        shape: merged_layer_shape(&base, &overlay),
125        clip: base.clip || overlay.clip,
126        compositing_strategy: overlay.compositing_strategy,
127        blend_mode: overlay.blend_mode,
128        color_filter: compose_color_filters(base.color_filter, overlay.color_filter),
129        render_effect: compose_render_effects(base.render_effect, overlay.render_effect),
130        backdrop_effect: overlay.backdrop_effect.or(base.backdrop_effect),
131    }
132}
133
134/// The shape of two stacked layers merged into one: the layer that clips
135/// owns it, else the layer that carries the backdrop (its effect covers that
136/// shape), else the later layer, whose default resets it like every other
137/// parent-local field.
138fn merged_layer_shape(base: &GraphicsLayer, overlay: &GraphicsLayer) -> LayerShape {
139    if overlay.clip || (!base.clip && overlay.backdrop_effect.is_some()) {
140        overlay.shape
141    } else if base.clip || base.backdrop_effect.is_some() {
142        base.shape
143    } else {
144        overlay.shape
145    }
146}
147
148fn compose_render_effects(
149    outer: Option<RenderEffect>,
150    inner: Option<RenderEffect>,
151) -> Option<RenderEffect> {
152    match (outer, inner) {
153        (None, None) => None,
154        (Some(effect), None) | (None, Some(effect)) => Some(effect),
155        (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
156    }
157}
158
159fn compose_color_filters(
160    base: Option<ColorFilter>,
161    overlay: Option<ColorFilter>,
162) -> Option<ColorFilter> {
163    match (base, overlay) {
164        (None, None) => None,
165        (Some(filter), None) | (None, Some(filter)) => Some(filter),
166        (Some(filter), Some(next)) => Some(filter.compose(next)),
167    }
168}
169
170impl ModifierNodeSlices {
171    pub fn draw_commands(&self) -> &[DrawCommand] {
172        &self.draw_commands
173    }
174
175    /// How many leading [`draw_commands`](Self::draw_commands) come from
176    /// modifiers chained before the node's graphics layer or clip. Those draw
177    /// around the layer in the parent's space, outside its clip, alpha and
178    /// transform, exactly as an outer `drawBehind` wraps a `graphicsLayer`.
179    pub fn outer_draw_command_count(&self) -> usize {
180        self.layer_draw_boundary.unwrap_or(0)
181    }
182
183    fn insert_background_draw(
184        &mut self,
185        insert_index: Option<usize>,
186        precedes_layer: bool,
187        command: DrawCommand,
188    ) {
189        let insert_index = insert_index.unwrap_or(0).min(self.draw_commands.len());
190        self.draw_commands.insert(insert_index, command);
191        if let Some(boundary) = self.layer_draw_boundary.as_mut()
192            && precedes_layer
193        {
194            *boundary += 1;
195        }
196    }
197
198    fn mark_layer_draw_boundary(&mut self) {
199        if self.layer_draw_boundary.is_none() {
200            self.layer_draw_boundary = Some(self.draw_commands.len());
201        }
202    }
203
204    pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
205        &self.pointer_inputs
206    }
207
208    /// Dispatches an event whose position is already local to this layout node.
209    /// Consumed events stop propagation except for release and cancellation,
210    /// which reach every handler so each can finish its active interaction.
211    pub fn dispatch_pointer_event(&self, event: PointerEvent) {
212        let terminal = matches!(event.kind, PointerEventKind::Up | PointerEventKind::Cancel);
213        for handler in &self.pointer_inputs {
214            if event.is_consumed() && !terminal {
215                break;
216            }
217            handler(event.clone());
218        }
219        if event.kind == PointerEventKind::Down && !event.is_consumed() {
220            for handler in &self.click_handlers {
221                handler(event.position);
222            }
223        }
224    }
225
226    /// The write targets for this node's resolved size, one per pointer-input
227    /// node that exposes a size to its handler. See
228    /// [`ModifierNodeSlices::publish_pointer_input_size`].
229    pub fn pointer_input_size_sinks(&self) -> &[Rc<std::cell::Cell<cranpose_ui_graphics::Size>>] {
230        &self.pointer_input_sizes
231    }
232
233    /// Publishes this layout node's resolved size to every pointer-input
234    /// handler attached to it, so `PointerInputScope::size()` reports the
235    /// node's real dimensions.
236    ///
237    /// Called by every pass that resolves a node's geometry (the layout `place`
238    /// passes and the per-frame scene build), so the size is current before any
239    /// pointer event for that frame is dispatched and tracks resizes.
240    ///
241    /// `size` is the node's layout box — the same box the dispatched
242    /// [`PointerEvent`] positions are made local to — so handlers can compare
243    /// event coordinates against it directly.
244    pub fn publish_pointer_input_size(&self, size: cranpose_ui_graphics::Size) {
245        for sink in &self.pointer_input_sizes {
246            sink.set(size);
247        }
248    }
249
250    pub fn click_handlers(&self) -> &[Rc<dyn Fn(Point)>] {
251        &self.click_handlers
252    }
253
254    /// The pointer's appearance over this node, when a `pointer_icon`
255    /// modifier names one. The innermost declaration in the chain wins.
256    pub fn pointer_icon(&self) -> Option<&PointerIcon> {
257        self.pointer_icon.as_ref()
258    }
259
260    pub fn clip_to_bounds(&self) -> bool {
261        self.clip_to_bounds
262    }
263
264    pub fn motion_context_animated(&self) -> bool {
265        self.motion_context_animated
266    }
267
268    pub fn translated_content_context(&self) -> bool {
269        self.translated_content_context
270    }
271
272    pub fn translated_content_context_identity(&self) -> Option<usize> {
273        self.translated_content_context_identity
274    }
275
276    pub fn translated_content_offset(&self) -> Option<Point> {
277        self.translated_content_offset_reader
278            .as_ref()
279            .map(|reader| reader())
280    }
281
282    pub fn text_content(&self) -> Option<&str> {
283        self.text_content.as_ref().map(|a| a.text.as_str())
284    }
285
286    pub fn annotated_text(&self) -> Option<&crate::text::AnnotatedString> {
287        self.text_content.as_deref()
288    }
289
290    pub fn text_style(&self) -> Option<&TextStyle> {
291        self.text_style.as_ref()
292    }
293
294    pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
295        self.text_layout_options
296    }
297
298    /// Returns the horizontal pan resolver for single-line text fields.
299    ///
300    /// The resolver takes the content viewport width (px) and returns the
301    /// horizontal scroll offset that keeps the cursor visible. Renderers
302    /// subtract this offset from the text origin so the glyphs pan together
303    /// with the cursor and selection.
304    pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
305        self.text_pan.clone()
306    }
307
308    /// The write target for a text field's composited window origin, if this
309    /// node is a `BasicTextField`. The layout pass writes the field's true
310    /// on-screen top-left here so its finger selection handles track the field
311    /// across scroll. See [`ModifierNodeSlices::text_field_window_origin`].
312    pub fn text_field_window_origin(&self) -> Option<Rc<std::cell::Cell<Point>>> {
313        self.text_field_window_origin.clone()
314    }
315
316    /// The write target for a scroll container's composited window rect, if this
317    /// node carries a `report_window_rect` modifier. The layout pass writes the
318    /// node's true on-screen viewport rect here so a `BringIntoViewResponder`
319    /// can scroll a focused field's caret above the soft keyboard.
320    pub fn viewport_window_rect(&self) -> Option<Rc<dyn crate::modifier_nodes::WindowRectSink>> {
321        self.viewport_window_rect.clone()
322    }
323
324    /// Returns the text layout this node's `Text` or text field produced when
325    /// layout last measured it, laid out at the same width.
326    ///
327    /// A text field's layout is its current text wrapped at the width its
328    /// caret and selection are placed on. `None` when the node carries no text,
329    /// or carries a `Text` that has not been measured yet.
330    pub fn measured_text_layout(&self) -> Option<crate::text::PreparedTextLayout> {
331        match self.prepared_text_layout.as_ref()? {
332            MeasuredTextLayoutSource::Text(handle) => handle.measured_layout(),
333            MeasuredTextLayoutSource::TextField(handle) => {
334                Some(handle.measured_layout(self.text_style.as_ref()?))
335            }
336        }
337    }
338
339    pub fn graphics_layer(&self) -> Option<GraphicsLayer> {
340        if let Some(resolve) = &self.graphics_layer_resolver {
341            Some(resolve())
342        } else {
343            self.graphics_layer.clone()
344        }
345    }
346
347    pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
348        self.corner_shape
349    }
350
351    fn push_graphics_layer(
352        &mut self,
353        layer: GraphicsLayer,
354        resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
355    ) {
356        let existing_snapshot = self.graphics_layer.clone();
357        let next_snapshot = existing_snapshot.as_ref().map_or_else(
358            || layer.clone(),
359            |current| merge_graphics_layers(current.clone(), layer.clone()),
360        );
361        let existing_resolver = self.graphics_layer_resolver.clone();
362
363        self.graphics_layer = Some(next_snapshot);
364        self.graphics_layer_resolver = match (existing_resolver, resolver) {
365            (None, None) => None,
366            (Some(current_resolver), None) => Some(Rc::new(move || {
367                merge_graphics_layers(current_resolver(), layer.clone())
368            })),
369            (None, Some(next_resolver)) => {
370                let base = existing_snapshot.unwrap_or_default();
371                Some(Rc::new(move || {
372                    merge_graphics_layers(base.clone(), next_resolver())
373                }))
374            }
375            (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
376                merge_graphics_layers(current_resolver(), next_resolver())
377            })),
378        };
379    }
380
381    pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
382        self.chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
383        self
384    }
385
386    pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
387        let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
388        let pointer_input_bytes =
389            self.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>();
390        let click_handler_bytes = self.click_handlers.capacity() * size_of::<Rc<dyn Fn(Point)>>();
391        ModifierNodeSlicesDebugStats {
392            draw_command_count: self.draw_commands.len(),
393            draw_command_capacity: self.draw_commands.capacity(),
394            pointer_input_count: self.pointer_inputs.len(),
395            pointer_input_capacity: self.pointer_inputs.capacity(),
396            click_handler_count: self.click_handlers.len(),
397            click_handler_capacity: self.click_handlers.capacity(),
398            has_text_content: self.text_content.is_some(),
399            has_text_style: self.text_style.is_some(),
400            has_text_layout_options: self.text_layout_options.is_some(),
401            has_prepared_text_layout: self.prepared_text_layout.is_some(),
402            has_graphics_layer: self.graphics_layer.is_some(),
403            has_graphics_layer_resolver: self.graphics_layer_resolver.is_some(),
404            heap_bytes: draw_command_bytes + pointer_input_bytes + click_handler_bytes,
405        }
406    }
407
408    /// Resets the slice collection for reuse, retaining vector capacity.
409    pub fn clear(&mut self) {
410        self.draw_commands.clear();
411        self.layer_draw_boundary = None;
412        self.pointer_inputs.clear();
413        self.pointer_input_sizes.clear();
414        self.click_handlers.clear();
415        self.pointer_icon = None;
416        self.clip_to_bounds = false;
417        self.motion_context_animated = false;
418        self.translated_content_context = false;
419        self.translated_content_context_identity = None;
420        self.translated_content_offset_reader = None;
421        self.text_content = None;
422        self.text_style = None;
423        self.text_layout_options = None;
424        self.prepared_text_layout = None;
425        self.text_pan = None;
426        self.graphics_layer = None;
427        self.graphics_layer_resolver = None;
428        self.corner_shape = None;
429        self.chain_guard = None;
430    }
431}
432
433impl fmt::Debug for ModifierNodeSlices {
434    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435        f.debug_struct("ModifierNodeSlices")
436            .field("draw_commands", &self.draw_commands.len())
437            .field("pointer_inputs", &self.pointer_inputs.len())
438            .field("click_handlers", &self.click_handlers.len())
439            .field("pointer_icon", &self.pointer_icon)
440            .field("clip_to_bounds", &self.clip_to_bounds)
441            .field("motion_context_animated", &self.motion_context_animated)
442            .field(
443                "translated_content_context",
444                &self.translated_content_context,
445            )
446            .field(
447                "translated_content_context_identity",
448                &self.translated_content_context_identity,
449            )
450            .field(
451                "translated_content_offset",
452                &self.translated_content_offset(),
453            )
454            .field("text_content", &self.text_content)
455            .field("text_style", &self.text_style)
456            .field("text_layout_options", &self.text_layout_options)
457            .field("prepared_text_layout", &self.prepared_text_layout.is_some())
458            .field("graphics_layer", &self.graphics_layer)
459            .field(
460                "graphics_layer_resolver",
461                &self.graphics_layer_resolver.is_some(),
462            )
463            .field("corner_shape", &self.corner_shape)
464            .finish()
465    }
466}
467
468/// Records `node`'s pointer icon when it declares one, leaving the icon already
469/// collected in place when it does not.
470///
471/// The chain is walked head to tail, so the innermost declaration is the last
472/// one written and the one that survives.
473fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
474    if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
475        slices.pointer_icon = Some(icon_node.icon().clone());
476    }
477}
478
479/// Collects modifier node slices directly from a reconciled [`ModifierNodeChain`].
480pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
481    let mut slices = ModifierNodeSlices::default();
482    collect_modifier_slices_into(chain, &mut slices);
483    slices
484}
485
486/// Collects modifier node slices into an existing buffer to reuse allocations.
487///
488/// Single-pass: iterates the chain once instead of 4 separate capability-filtered
489/// traversals, reducing per-node `RefCell::borrow()` overhead.
490pub fn collect_modifier_slices_into(chain: &ModifierNodeChain, slices: &mut ModifierNodeSlices) {
491    slices.clear();
492
493    let caps = chain.capabilities();
494    let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
495    let has_draw = caps.intersects(NodeCapabilities::DRAW);
496    let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
497
498    if !has_pointer && !has_draw && !has_layout {
499        return;
500    }
501
502    let mut background_color = None;
503    let mut background_insert_index = None::<usize>;
504    let mut background_precedes_layer = false;
505    let mut corner_shape = None;
506    let mut padding = EdgeInsets::default();
507
508    for node_ref in chain.head_to_tail() {
509        let node_caps = node_ref.kind_set();
510
511        node_ref.with_node(|node| {
512            let any = node.as_any();
513
514            if has_pointer
515                && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
516                && let Some(pointer_node) = node.as_pointer_input_node()
517            {
518                if let Some(handler) = pointer_node.pointer_input_handler() {
519                    slices.pointer_inputs.push(handler);
520                }
521                if let Some(sink) = pointer_node.layout_size_sink() {
522                    slices.pointer_input_sizes.push(sink);
523                }
524                collect_pointer_icon(any, slices);
525            }
526
527            if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
528                if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
529                    background_color = Some(bg_node.color());
530                    background_insert_index = Some(slices.draw_commands.len());
531                    background_precedes_layer = slices.layer_draw_boundary.is_none();
532                    if bg_node.shape().is_some() {
533                        corner_shape = bg_node.shape();
534                    }
535                }
536
537                if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
538                    corner_shape = Some(shape_node.shape());
539                }
540
541                if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
542                    slices.draw_commands.extend(commands.observed_commands());
543                }
544
545                if let Some(draw_node) = node.as_draw_node() {
546                    if let Some(closure) = draw_node.create_behind_draw_closure() {
547                        slices.draw_commands.push(DrawCommand::Behind(closure));
548                    }
549                    if let Some(closure) = draw_node.create_draw_closure() {
550                        slices.draw_commands.push(DrawCommand::Overlay(closure));
551                    } else {
552                        use cranpose_ui_graphics::{DrawScope as _, DrawScopeDefault};
553                        let mut scope = DrawScopeDefault::with_text_measurer(
554                            crate::modifier::Size {
555                                width: 0.0,
556                                height: 0.0,
557                            },
558                            crate::text::AppContextTextMeasurer::shared(),
559                        );
560                        draw_node.draw(&mut scope);
561                        let primitives = scope.into_primitives();
562                        if !primitives.is_empty() {
563                            let draw_cmd = Rc::new(
564                                move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
565                                    scope.push_recorded(primitives.clone());
566                                },
567                            );
568                            slices.draw_commands.push(DrawCommand::Overlay(draw_cmd));
569                        }
570                    }
571                }
572
573                if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
574                    slices.mark_layer_draw_boundary();
575                    slices.push_graphics_layer(
576                        layer_node.layer_snapshot(),
577                        layer_node.layer_resolver(),
578                    );
579                }
580
581                if any.is::<ClipToBoundsNode>() {
582                    slices.mark_layer_draw_boundary();
583                    slices.clip_to_bounds = true;
584                }
585            }
586
587            if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
588                if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
589                    let p = padding_node.padding();
590                    padding.left += p.left;
591                    padding.top += p.top;
592                    padding.right += p.right;
593                    padding.bottom += p.bottom;
594                }
595
596                if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
597                    slices.motion_context_animated = motion_context_node.is_active();
598                }
599
600                if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
601                    slices.viewport_window_rect = Some(reporter.window_rect_sink());
602                }
603
604                if let Some(translated_content_node) =
605                    any.downcast_ref::<TranslatedContentContextNode>()
606                {
607                    slices.translated_content_context = translated_content_node.is_active();
608                    slices.translated_content_context_identity =
609                        Some(translated_content_node.identity());
610                    slices.translated_content_offset_reader =
611                        translated_content_node.content_offset_reader();
612                }
613
614                if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
615                    slices.text_content = Some(text_node.annotated_text());
616                    slices.text_style = Some(text_node.style().clone());
617                    slices.text_layout_options = Some(text_node.options());
618                    slices.prepared_text_layout = Some(MeasuredTextLayoutSource::Text(
619                        text_node.prepared_layout_handle(),
620                    ));
621                }
622
623                if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
624                    let text = text_field_node.text();
625                    slices.text_content = Some(Rc::new(crate::text::AnnotatedString::from(text)));
626                    slices.text_style = Some(text_field_node.style().clone());
627                    slices.text_layout_options = Some(TextLayoutOptions::default());
628                    slices.prepared_text_layout = Some(MeasuredTextLayoutSource::TextField(
629                        text_field_node.layout_handle(),
630                    ));
631                    slices.text_pan = text_field_node.text_pan_resolver();
632                    slices.text_field_window_origin = Some(text_field_node.window_origin_sink());
633
634                    text_field_node.set_content_offset(padding.left);
635                    text_field_node.set_content_y_offset(padding.top);
636                }
637            }
638        });
639    }
640
641    slices.corner_shape = corner_shape;
642
643    if let Some(color) = background_color {
644        let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
645            use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
646
647            use crate::modifier::Brush;
648
649            let size = scope.size();
650            let brush = Brush::solid(color);
651            if let Some(shape) = corner_shape {
652                let radii: CornerRadii = shape.resolve(size.width, size.height);
653                scope.draw_round_rect(brush, radii);
654            } else {
655                scope.draw_rect(brush);
656            }
657        });
658
659        slices.insert_background_draw(
660            background_insert_index,
661            background_precedes_layer,
662            DrawCommand::Behind(draw_cmd),
663        );
664    }
665}
666
667/// Collects modifier node slices by instantiating a temporary node chain from a [`Modifier`].
668pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
669    let mut handle = ModifierChainHandle::new();
670    let _ = handle.update(modifier);
671    collect_modifier_slices(handle.chain()).with_chain_guard(handle)
672}
673
674#[cfg(test)]
675#[path = "tests/slices_tests.rs"]
676mod tests;