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.as_ref().map_or_else(
359            || layer.clone(),
360            |current| merge_graphics_layers(current.clone(), layer.clone()),
361        );
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) => Some(Rc::new(move || {
368                merge_graphics_layers(current_resolver(), layer.clone())
369            })),
370            (None, Some(next_resolver)) => {
371                let base = existing_snapshot.unwrap_or_default();
372                Some(Rc::new(move || {
373                    merge_graphics_layers(base.clone(), next_resolver())
374                }))
375            }
376            (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
377                merge_graphics_layers(current_resolver(), next_resolver())
378            })),
379        };
380    }
381
382    pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
383        self.chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
384        self
385    }
386
387    pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
388        let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
389        let pointer_input_bytes =
390            self.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>();
391        let click_handler_bytes = self.click_handlers.capacity() * size_of::<Rc<dyn Fn(Point)>>();
392        ModifierNodeSlicesDebugStats {
393            draw_command_count: self.draw_commands.len(),
394            draw_command_capacity: self.draw_commands.capacity(),
395            pointer_input_count: self.pointer_inputs.len(),
396            pointer_input_capacity: self.pointer_inputs.capacity(),
397            click_handler_count: self.click_handlers.len(),
398            click_handler_capacity: self.click_handlers.capacity(),
399            has_text_content: self.text_content.is_some(),
400            has_text_style: self.text_style.is_some(),
401            has_text_layout_options: self.text_layout_options.is_some(),
402            has_prepared_text_layout: self.prepared_text_layout.is_some(),
403            has_graphics_layer: self.graphics_layer.is_some(),
404            has_graphics_layer_resolver: self.graphics_layer_resolver.is_some(),
405            heap_bytes: draw_command_bytes + pointer_input_bytes + click_handler_bytes,
406        }
407    }
408
409    /// Resets the slice collection for reuse, retaining vector capacity.
410    pub fn clear(&mut self) {
411        self.draw_commands.clear();
412        self.layer_draw_boundary = None;
413        self.pointer_inputs.clear();
414        self.pointer_input_sizes.clear();
415        self.click_handlers.clear();
416        self.pointer_icon = None;
417        self.clip_to_bounds = false;
418        self.motion_context_animated = false;
419        self.translated_content_context = false;
420        self.translated_content_context_identity = None;
421        self.translated_content_offset_reader = None;
422        self.text_content = None;
423        self.text_style = None;
424        self.text_layout_options = None;
425        self.prepared_text_layout = None;
426        self.text_pan = None;
427        self.graphics_layer = None;
428        self.graphics_layer_resolver = None;
429        self.corner_shape = None;
430        self.chain_guard = None;
431    }
432}
433
434impl fmt::Debug for ModifierNodeSlices {
435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436        f.debug_struct("ModifierNodeSlices")
437            .field("draw_commands", &self.draw_commands.len())
438            .field("pointer_inputs", &self.pointer_inputs.len())
439            .field("click_handlers", &self.click_handlers.len())
440            .field("pointer_icon", &self.pointer_icon)
441            .field("clip_to_bounds", &self.clip_to_bounds)
442            .field("motion_context_animated", &self.motion_context_animated)
443            .field(
444                "translated_content_context",
445                &self.translated_content_context,
446            )
447            .field(
448                "translated_content_context_identity",
449                &self.translated_content_context_identity,
450            )
451            .field(
452                "translated_content_offset",
453                &self.translated_content_offset(),
454            )
455            .field("text_content", &self.text_content)
456            .field("text_style", &self.text_style)
457            .field("text_layout_options", &self.text_layout_options)
458            .field("prepared_text_layout", &self.prepared_text_layout.is_some())
459            .field("graphics_layer", &self.graphics_layer)
460            .field(
461                "graphics_layer_resolver",
462                &self.graphics_layer_resolver.is_some(),
463            )
464            .field("corner_shape", &self.corner_shape)
465            .finish()
466    }
467}
468
469/// Records `node`'s pointer icon when it declares one, leaving the icon already
470/// collected in place when it does not.
471///
472/// The chain is walked head to tail, so the innermost declaration is the last
473/// one written and the one that survives.
474fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
475    if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
476        slices.pointer_icon = Some(icon_node.icon().clone());
477    }
478}
479
480/// Collects modifier node slices directly from a reconciled [`ModifierNodeChain`].
481pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
482    let mut slices = ModifierNodeSlices::default();
483    collect_modifier_slices_into(chain, &mut slices);
484    slices
485}
486
487/// Collects modifier node slices into an existing buffer to reuse allocations.
488///
489/// Single-pass: iterates the chain once instead of 4 separate capability-filtered
490/// traversals, reducing per-node `RefCell::borrow()` overhead.
491pub fn collect_modifier_slices_into(chain: &ModifierNodeChain, slices: &mut ModifierNodeSlices) {
492    slices.clear();
493
494    let caps = chain.capabilities();
495    let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
496    let has_draw = caps.intersects(NodeCapabilities::DRAW);
497    let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
498
499    if !has_pointer && !has_draw && !has_layout {
500        return;
501    }
502
503    let mut background_color = None;
504    let mut background_insert_index = None::<usize>;
505    let mut background_precedes_layer = false;
506    let mut corner_shape = None;
507    let mut padding = EdgeInsets::default();
508
509    for node_ref in chain.head_to_tail() {
510        let node_caps = node_ref.kind_set();
511
512        node_ref.with_node(|node| {
513            let any = node.as_any();
514
515            if has_pointer
516                && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
517                && let Some(pointer_node) = node.as_pointer_input_node()
518            {
519                if let Some(handler) = pointer_node.pointer_input_handler() {
520                    slices.pointer_inputs.push(handler);
521                }
522                if let Some(sink) = pointer_node.layout_size_sink() {
523                    slices.pointer_input_sizes.push(sink);
524                }
525                collect_pointer_icon(any, slices);
526            }
527
528            if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
529                if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
530                    background_color = Some(bg_node.color());
531                    background_insert_index = Some(slices.draw_commands.len());
532                    background_precedes_layer = slices.layer_draw_boundary.is_none();
533                    if bg_node.shape().is_some() {
534                        corner_shape = bg_node.shape();
535                    }
536                }
537
538                if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
539                    corner_shape = Some(shape_node.shape());
540                }
541
542                if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
543                    slices.draw_commands.extend(commands.observed_commands());
544                }
545
546                if let Some(draw_node) = node.as_draw_node() {
547                    if let Some(closure) = draw_node.create_behind_draw_closure() {
548                        slices.draw_commands.push(DrawCommand::Behind(closure));
549                    }
550                    if let Some(closure) = draw_node.create_draw_closure() {
551                        slices.draw_commands.push(DrawCommand::Overlay(closure));
552                    } else {
553                        use cranpose_ui_graphics::{DrawScope as _, DrawScopeDefault};
554                        let mut scope = DrawScopeDefault::with_text_measurer(
555                            crate::modifier::Size {
556                                width: 0.0,
557                                height: 0.0,
558                            },
559                            crate::text::AppContextTextMeasurer::shared(),
560                        );
561                        draw_node.draw(&mut scope);
562                        let primitives = scope.into_primitives();
563                        if !primitives.is_empty() {
564                            let draw_cmd = Rc::new(
565                                move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
566                                    scope.push_recorded(primitives.clone());
567                                },
568                            );
569                            slices.draw_commands.push(DrawCommand::Overlay(draw_cmd));
570                        }
571                    }
572                }
573
574                if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
575                    slices.mark_layer_draw_boundary();
576                    slices.push_graphics_layer(
577                        layer_node.layer_snapshot(),
578                        layer_node.layer_resolver(),
579                    );
580                }
581
582                if any.is::<ClipToBoundsNode>() {
583                    slices.mark_layer_draw_boundary();
584                    slices.clip_to_bounds = true;
585                }
586            }
587
588            if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
589                if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
590                    let p = padding_node.padding();
591                    padding.left += p.left;
592                    padding.top += p.top;
593                    padding.right += p.right;
594                    padding.bottom += p.bottom;
595                }
596
597                if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
598                    slices.motion_context_animated = motion_context_node.is_active();
599                }
600
601                if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
602                    slices.viewport_window_rect = Some(reporter.window_rect_sink());
603                }
604
605                if let Some(translated_content_node) =
606                    any.downcast_ref::<TranslatedContentContextNode>()
607                {
608                    slices.translated_content_context = translated_content_node.is_active();
609                    slices.translated_content_context_identity =
610                        Some(translated_content_node.identity());
611                    slices.translated_content_offset_reader =
612                        translated_content_node.content_offset_reader();
613                }
614
615                if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
616                    slices.text_content = Some(text_node.annotated_text());
617                    slices.text_style = Some(text_node.style().clone());
618                    slices.text_layout_options = Some(text_node.options());
619                    slices.prepared_text_layout = Some(text_node.prepared_layout_handle());
620                }
621
622                if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
623                    let text = text_field_node.text();
624                    slices.text_content = Some(Rc::new(crate::text::AnnotatedString::from(text)));
625                    slices.text_style = Some(text_field_node.style().clone());
626                    slices.text_layout_options = Some(TextLayoutOptions::default());
627                    slices.prepared_text_layout = None;
628                    slices.text_pan = text_field_node.text_pan_resolver();
629                    slices.text_field_window_origin = Some(text_field_node.window_origin_sink());
630
631                    text_field_node.set_content_offset(padding.left);
632                    text_field_node.set_content_y_offset(padding.top);
633                }
634            }
635        });
636    }
637
638    slices.corner_shape = corner_shape;
639
640    if let Some(color) = background_color {
641        let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
642            use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
643
644            use crate::modifier::Brush;
645
646            let size = scope.size();
647            let brush = Brush::solid(color);
648            if let Some(shape) = corner_shape {
649                let radii: CornerRadii = shape.resolve(size.width, size.height);
650                scope.draw_round_rect(brush, radii);
651            } else {
652                scope.draw_rect(brush);
653            }
654        });
655
656        slices.insert_background_draw(
657            background_insert_index,
658            background_precedes_layer,
659            DrawCommand::Behind(draw_cmd),
660        );
661    }
662}
663
664/// Collects modifier node slices by instantiating a temporary node chain from a [`Modifier`].
665pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
666    let mut handle = ModifierChainHandle::new();
667    let _ = handle.update(modifier);
668    collect_modifier_slices(handle.chain()).with_chain_guard(handle)
669}
670
671#[cfg(test)]
672#[path = "tests/slices_tests.rs"]
673mod tests;