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