Skip to main content

repose_core/
modifier.rs

1use std::cell::{Cell, RefCell};
2use std::collections::HashSet;
3use std::rc::Rc;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use taffy::{
7    AlignContent, AlignItems, AlignSelf, Contain, FlexDirection, FlexWrap, JustifyContent,
8};
9
10use crate::animation::AnimationSpec;
11use crate::color::ColorFilter;
12use crate::gesture::DragOrientation;
13use crate::indication::IndicationNodeFactory;
14use crate::scroll::ScrollAxis;
15use crate::shape::Shape;
16use crate::units::{Dp, DpSize};
17use crate::view::BlendMode;
18use crate::{Brush, Color, CompositingStrategy, PointerEvent, Transform, Vec2};
19
20/// State-driven colors. Priority: disabled > dragged > pressed > focused > hovered > default.
21///
22/// Priority (paint): disabled > dragged > pressed > focused > hovered > default.
23#[derive(Clone, Copy, Debug)]
24pub struct StateColors {
25    pub default: Color,
26    pub hovered: Color,
27    /// Color while focused.
28    pub focused: Color,
29    pub pressed: Color,
30    pub disabled: Color,
31    /// While dragged (overrides hover/press/focus).
32    pub dragged: Color,
33}
34
35/// State-driven elevation (levels in [`Dp`]).
36/// Priority: disabled > dragged > pressed > focused > hovered > default.
37#[derive(Clone, Copy, Debug)]
38pub struct StateElevation {
39    pub default: Dp,
40    pub hovered: Dp,
41    /// Applied between pressed and hovered in the paint priority order.
42    pub focused: Dp,
43    pub pressed: Dp,
44    pub disabled: Dp,
45    /// Elevation while the component is being dragged (preferred over hovered/pressed/focused).
46    pub dragged: Dp,
47}
48
49impl StateColors {
50    pub const fn transparent() -> Self {
51        Self {
52            default: Color::TRANSPARENT,
53            hovered: Color::TRANSPARENT,
54            focused: Color::TRANSPARENT,
55            pressed: Color::TRANSPARENT,
56            disabled: Color::TRANSPARENT,
57            dragged: Color::TRANSPARENT,
58        }
59    }
60}
61
62impl StateElevation {
63    pub const fn zero() -> Self {
64        Self {
65            default: Dp(0.0),
66            hovered: Dp(0.0),
67            focused: Dp(0.0),
68            pressed: Dp(0.0),
69            disabled: Dp(0.0),
70            dragged: Dp(0.0),
71        }
72    }
73}
74
75macro_rules! merge_opts {
76    ($dst:ident, $src:ident; $($f:ident),+ $(,)?) => {
77        $( $dst.$f = $src.$f.or($dst.$f); )+
78    };
79}
80macro_rules! merge_flags {
81    ($dst:ident, $src:ident; $($f:ident),+ $(,)?) => {
82        $( $dst.$f |= $src.$f; )+
83    };
84}
85
86macro_rules! impl_option_fields {
87    ($ty:ty, $fn:ident) => {
88        impl $ty {
89            $fn!(replace);
90        }
91    };
92    ($ty:ident) => {
93        impl $ty {
94            /// Chain another modifier's settings onto this one.
95            /// Useful for creating reusable modifier templates.
96            pub fn then(mut self, other: Self) -> Self {
97                merge_opts!(self, other;
98                    key, size, width, height, required_size, wrap_content,
99                    padding, padding_values,
100                    min_width, min_height, max_width, max_height,
101                    required_min_width, required_max_width,
102                    required_min_height, required_max_height,
103                    default_min_width, default_min_height,
104                    fill_max, fill_max_w, fill_max_h,
105                    background, background_alpha, background_shape, state_colors, state_elevation,
106                    border, border_shape,
107                    flex_grow, flex_shrink, flex_basis, flex_wrap, flex_dir,
108                    flex_line_count,
109                    gap, row_gap, column_gap,
110                    align_self, justify_content, align_items_container, align_content,
111                    baseline_align,
112                    clip_rounded, clip_rect, clip_shape, overflow, render_z_index,
113                    on_scroll, on_scroll_with_source,
114                    scrollbar_style,
115                    nested_scroll_connection,
116                    scroll,
117                    on_pointer_down, on_pointer_move, on_pointer_up,
118                    on_pointer_cancel,
119                    on_pointer_enter, on_pointer_leave,
120                    on_click, on_double_click, on_long_click,
121                    on_globally_positioned, on_size_changed,
122                    on_key_event, on_preview_key_event, on_ime,
123                    semantics, alpha, transform,
124                    shared_element,
125                    grid, grid_col_span, grid_row_span,
126                    position_type,
127                    offset_left, offset_right, offset_top, offset_bottom,
128                    layout_offset, absolute_layout_offset,
129                    margin_left, margin_right, margin_top, margin_bottom,
130                    aspect_ratio, intrinsic_width, intrinsic_height,
131                    fit_content_width, fit_content_height,
132                    contain,
133                    painter,
134                    paint_callback,
135                    layout,
136                    blur, graphics_layer, graphics_layer_scope,
137                    fill_parent_max_size, padding_from_baseline,
138                    shadow, shadow_shape,
139                    on_drag_start, on_drag_end, on_drag_enter, on_drag_over, on_drag_leave, on_drop,
140                    drag_preview,
141                    on_action, cursor, animate_content_size, focus_requester, on_focus_changed,
142                    bring_into_view, on_focused_bounds_changed,
143                    interaction_source, text_input, text_selection,
144                    visible,
145                );
146                        merge_flags!(self, other;
147                    hit_passthrough, input_blocker, repaint_boundary, click, disabled,
148                    propagate_min, focus_group, match_parent_size,
149                );
150
151                // `flex_basis_content` is a plain bool flag: OR like the rest.
152                self.flex_basis_content |= other.flex_basis_content;
153                self.paint_order = other.paint_order;
154
155                if let Some(f) = other.focusable {
156                    self.focusable = Some(f);
157                }
158                if other.indication.is_some() {
159                    self.indication = other.indication;
160                }
161                self.nodes.extend(other.nodes);
162                // Always overwrite so `then(z_index(0.0))` resets layering.
163                self.z_index = other.z_index;
164                self
165            }
166        }
167    };
168}
169
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
171pub enum ClipOp {
172    /// Keep content inside the clip rect (default).
173    #[default]
174    Intersect,
175    /// Remove content inside the clip rect (cutout).
176    Difference,
177}
178
179/// Controls whether child content is clipped to the parent bounds.
180///
181/// Analogous to CSS `overflow`:
182/// - `Clip` (default): content extending beyond the parent is hidden.
183/// - `Visible`: content is allowed to overflow the parent bounds.
184#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
185pub enum Overflow {
186    #[default]
187    Clip,
188    Visible,
189}
190
191/// Rectangular clip with a clipping operation.
192/// The rect is relative to the element bounds, in [`Dp`].
193#[derive(Clone, Copy, Debug)]
194pub struct ClipRect {
195    pub left: Dp,
196    pub top: Dp,
197    pub right: Dp,
198    pub bottom: Dp,
199    pub op: ClipOp,
200}
201
202#[derive(Clone, Debug)]
203pub struct Border {
204    pub width: Dp,
205    /// Fill of the border ring. Mirrors Compose `BorderStroke(width, brush)`.
206    pub brush: Brush,
207    pub radius: [Dp; 4],
208}
209
210#[derive(Clone, Copy, Debug, Default)]
211pub struct PaddingValues {
212    pub left: Dp,
213    pub right: Dp,
214    pub top: Dp,
215    pub bottom: Dp,
216}
217
218#[derive(Clone, Debug)]
219pub struct GridConfig {
220    pub columns: usize,
221    pub row_gap: Dp,
222    pub column_gap: Dp,
223}
224
225/// Edge treatment for `Modifier::blur` -> controls how pixels at the edges
226/// of the blurred region are handled.
227#[derive(Clone, Copy, Debug, PartialEq)]
228pub enum BlurredEdgeTreatment {
229    /// Clip the blur to the element's bounds and clamp edge pixels
230    /// (extend the outermost pixels). This is the Compose default.
231    Rectangle,
232    /// Allow the blur to extend beyond the element's bounds.
233    /// Edge pixels are treated as transparent (decal).
234    Unbounded,
235}
236
237/// Gaussian blur parameters for `Modifier::blur`.
238#[derive(Clone, Copy, Debug)]
239pub struct BlurStyle {
240    /// Horizontal blur radius in [`Dp`].
241    pub radius_x: Dp,
242    /// Vertical blur radius in [`Dp`].
243    pub radius_y: Dp,
244    /// Controls edge pixel behavior.
245    pub edge_treatment: BlurredEdgeTreatment,
246}
247
248/// Constraints passed to the `Modifier::layout` callback.
249/// Mirrors Compose's `Constraints` -> the element's size must fall within
250/// `[min_width, max_width]` × `[min_height, max_height]`.
251/// A dimension with `INFINITY` max means unbounded in that direction.
252/// All values are in [`Dp`].
253#[derive(Clone, Copy, Debug)]
254pub struct LayoutConstraints {
255    pub min_width: Dp,
256    pub max_width: Dp,
257    pub min_height: Dp,
258    pub max_height: Dp,
259}
260
261/// Drop-shadow parameters applied to a graphics layer.
262///
263/// `blur_radius` is the Gaussian blur radius in [`Dp`] (1.0 = subtle, 8.0 = soft,
264/// 16.0 = very diffuse). `offset_x`/`offset_y` are the shadow offsets in [`Dp`].
265/// `spread` grows (or, when negative, shrinks) the silhouette before blurring.
266/// `inset` draws the shadow inside the silhouette (Compose inner shadow).
267/// `color` is the shadow color (alpha controls shadow darkness).
268#[derive(Clone, Copy, Debug, Default)]
269pub struct ShadowSpec {
270    pub blur_radius: Dp,
271    pub offset_x: Dp,
272    pub offset_y: Dp,
273    pub color: Color,
274    pub spread: Dp,
275    pub inset: bool,
276}
277
278/// Compose-style graphics layer configuration. Returned by the closure passed
279/// to [`Modifier::graphics_layer_with`]; the closure is evaluated every frame,
280/// so animating its fields does not require recomposition.
281#[derive(Clone, Debug)]
282pub struct GraphicsLayerScope {
283    pub scale_x: f32,
284    pub scale_y: f32,
285    pub alpha: f32,
286    pub translation_x: Dp,
287    pub translation_y: Dp,
288    pub rotation_x: f32,
289    pub rotation_y: f32,
290    pub rotation_z: f32,
291    pub camera_distance: f32,
292    pub transform_origin_x: f32,
293    pub transform_origin_y: f32,
294    pub shadow_elevation: Dp,
295    pub blend_mode: BlendMode,
296    pub color_filter: ColorFilter,
297    pub shape: Option<Shape>,
298    pub clip: bool,
299    pub compositing_strategy: CompositingStrategy,
300}
301
302impl Default for GraphicsLayerScope {
303    fn default() -> Self {
304        Self {
305            scale_x: 1.0,
306            scale_y: 1.0,
307            alpha: 1.0,
308            translation_x: Dp::ZERO,
309            translation_y: Dp::ZERO,
310            rotation_x: 0.0,
311            rotation_y: 0.0,
312            rotation_z: 0.0,
313            camera_distance: 0.0,
314            transform_origin_x: 0.5,
315            transform_origin_y: 0.5,
316            shadow_elevation: Dp::ZERO,
317            blend_mode: BlendMode::Alpha,
318            color_filter: ColorFilter::None,
319            shape: None,
320            clip: false,
321            compositing_strategy: CompositingStrategy::Auto,
322        }
323    }
324}
325
326#[derive(Clone, Copy, Debug)]
327#[non_exhaustive]
328pub enum PositionType {
329    Relative,
330    Absolute,
331}
332
333/// Configuration for a text input field.
334#[derive(Clone)]
335pub struct TextInputConfig {
336    pub hint: String,
337    pub multiline: bool,
338    pub on_change: Option<Rc<dyn Fn(String)>>,
339    pub on_submit: Option<Rc<dyn Fn(String)>>,
340    pub focus_tracker: Option<Rc<Cell<bool>>>,
341    pub value: String,
342    pub visual_transformation: Option<Rc<dyn crate::text::VisualTransformation>>,
343    pub keyboard_type: crate::text::KeyboardType,
344    pub capitalization: crate::text::KeyboardCapitalization,
345    pub ime_action: crate::text::ImeAction,
346    /// Platform keyboard auto-correct hint. `None` = follow platform default
347    /// (except password keyboards, which never auto-correct).
348    pub auto_correct_enabled: Option<bool>,
349    /// When false, the text field is not editable, not focusable, and input is not selectable.
350    pub enabled: bool,
351    /// When true, the text field can be focused and text can be selected/copied, but not modified.
352    pub read_only: bool,
353    pub sensitive: bool,
354    /// Maximum visible lines. Only effective when `multiline` is true.
355    pub max_lines: Option<usize>,
356    /// Minimum visible lines. Only effective when `multiline` is true.
357    pub min_lines: usize,
358    /// Override the cursor color. When None, uses the theme's `on_surface`.
359    pub cursor_color: Option<Color>,
360    /// Callback invoked after each text layout computation, providing layout details
361    /// such as line count and content size.
362    pub on_text_layout: Option<Rc<dyn Fn(&crate::text::TextLayoutResult)>>,
363    /// Style for the text content (font size, color, weight, etc.).
364    /// None = use defaults (16dp, theme color, NORMAL weight).
365    pub text_style: Option<crate::text::TextStyle>,
366    /// Per-action IME callbacks (onDone, onGo, onNext, etc.).
367    /// None = use `on_submit` for all actions.
368    pub keyboard_actions: Option<crate::text::KeyboardActions>,
369    /// Interaction source for tracking focus/press/hover state.
370    pub interaction_source: Option<InteractionSource>,
371    /// Line limits (SingleLine or MultiLine). Overrides `multiline`/`max_lines`/`min_lines`.
372    pub line_limits: Option<crate::text::TextFieldLineLimits>,
373}
374
375impl Default for TextInputConfig {
376    fn default() -> Self {
377        Self {
378            hint: String::new(),
379            multiline: false,
380            on_change: None,
381            on_submit: None,
382            focus_tracker: None,
383            value: String::new(),
384            visual_transformation: None,
385            keyboard_type: crate::text::KeyboardType::default(),
386            capitalization: crate::text::KeyboardCapitalization::default(),
387            ime_action: crate::text::ImeAction::default(),
388            auto_correct_enabled: None,
389            enabled: true,
390            read_only: false,
391            sensitive: false,
392            max_lines: None,
393            min_lines: 1,
394            cursor_color: None,
395            on_text_layout: None,
396            text_style: None,
397            keyboard_actions: None,
398            interaction_source: None,
399            line_limits: None,
400        }
401    }
402}
403
404impl std::fmt::Debug for TextInputConfig {
405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406        let mut s = f.debug_struct("TextInputConfig");
407        s.field("hint", &self.hint);
408        s.field("multiline", &self.multiline);
409        if self.on_change.is_some() {
410            s.field("on_change", &"…");
411        }
412        if self.on_submit.is_some() {
413            s.field("on_submit", &"…");
414        }
415        if self.focus_tracker.is_some() {
416            s.field("focus_tracker", &"…");
417        }
418        s.field("value", &self.value);
419        if self.visual_transformation.is_some() {
420            s.field("visual_transformation", &"…");
421        }
422        s.field("keyboard_type", &self.keyboard_type);
423        s.field("capitalization", &self.capitalization);
424        s.field("ime_action", &self.ime_action);
425        s.field("auto_correct_enabled", &self.auto_correct_enabled);
426        s.field("enabled", &self.enabled);
427        s.field("read_only", &self.read_only);
428        s.field("sensitive", &self.sensitive);
429        s.field("max_lines", &self.max_lines);
430        s.field("min_lines", &self.min_lines);
431        s.field("cursor_color", &self.cursor_color);
432        if self.on_text_layout.is_some() {
433            s.field("on_text_layout", &"…");
434        }
435        s.finish()
436    }
437}
438
439/// Intrinsic sizing mode for [`Modifier::intrinsic_width`] and [`Modifier::intrinsic_height`].
440/// When set, the node sizes itself to the intrinsic content size in that dimension.
441#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
442pub enum IntrinsicSize {
443    Min,
444    Max,
445}
446
447/// Which text baseline a `Row` child aligns by. Mirrors Compose's
448/// `FirstBaseline` / `LastBaseline` alignment lines.
449///
450/// Set via `RowScope::align_by_baseline` / `align_by_last_baseline`
451/// (or `align_by`) inside a `row_scope` block; only meaningful for direct
452/// children of a `Row`. Siblings without a baseline request keep their
453/// normal alignment.
454#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
455pub enum BaselineAlign {
456    FirstBaseline,
457    LastBaseline,
458}
459
460static PRESS_COUNTER: AtomicU64 = AtomicU64::new(1);
461
462thread_local! {
463    static INTERACTION_EPOCH: Cell<u64> = const { Cell::new(0) };
464}
465
466/// A press identifier for linking Press -> Release/Cancel pairs.
467pub type PressId = u64;
468
469/// An interaction event that can be emitted by a [`MutableInteractionSource`].
470///
471/// Compose-like per-interaction-type hierarchy:
472/// - `PressInteraction.Press(position)` / `Release(press)` / `Cancel(press)`
473/// - `HoverInteraction.Enter` / `Exit`
474/// - `FocusInteraction.Focus` / `Unfocus`
475/// - `DragInteraction.Start` / `Stop` / `Cancel`
476#[derive(Clone, Copy, Debug, PartialEq)]
477pub enum Interaction {
478    /// A press started at the given position (in local coords).
479    /// Carries a unique `PressId` so Release/Cancel can identify which press to end.
480    Press(PressId, Vec2),
481    /// The press with the given `PressId` was released.
482    Release(PressId),
483    /// The press with the given `PressId` was cancelled
484    /// (e.g. gesture disambiguation, pointer leave during press).
485    Cancel(PressId),
486    HoverEnter,
487    HoverLeave,
488    Focus,
489    Unfocus,
490    DragStart,
491    DragStop,
492    DragCancel,
493}
494
495impl Interaction {
496    /// Create a new `Press` with a fresh unique ID and the given position.
497    #[inline]
498    pub fn new_press(position: Vec2) -> Self {
499        Interaction::Press(PRESS_COUNTER.fetch_add(1, Ordering::Relaxed), position)
500    }
501}
502
503/// Read-only handle to a shared interaction state.
504///
505/// Use [`MutableInteractionSource::source`] to obtain a read handle, or
506/// [`MutableInteractionSource::new`] + `.source()` to create a new source pair.
507///
508/// Multiple clones share the same underlying state.
509#[derive(Clone)]
510pub struct InteractionSource {
511    pub(crate) state: Rc<RefCell<InteractionState>>,
512}
513
514impl InteractionSource {
515    pub fn collect_is_pressed(&self) -> bool {
516        !self.state.borrow().active_presses.is_empty()
517    }
518    pub fn collect_is_hovered(&self) -> bool {
519        self.state.borrow().hovered
520    }
521    pub fn collect_is_focused(&self) -> bool {
522        self.state.borrow().focused
523    }
524
525    /// Focused and keyboard/D-pad input mode (Compose `:focus-visible`).
526    pub fn collect_is_focus_visible(&self) -> bool {
527        crate::input::is_focus_visible(self.collect_is_focused())
528    }
529
530    pub fn collect_is_dragged(&self) -> bool {
531        self.state.borrow().dragged > 0
532    }
533    pub fn collect_last_press_position(&self) -> Option<Vec2> {
534        self.state.borrow().last_press_position
535    }
536    pub fn collect_last_press_id(&self) -> Option<PressId> {
537        self.state.borrow().last_press_id
538    }
539    /// Stable identity: the pointer of the shared state Rc.
540    pub fn stable_id(&self) -> *const () {
541        Rc::as_ptr(&self.state) as *const ()
542    }
543    /// Get a mutable handle to the same underlying state.
544    /// Both handles share the same `Rc<RefCell<..>>`, so mutations via
545    /// the returned `MutableInteractionSource` are reflected here.
546    pub fn to_mutable(&self) -> MutableInteractionSource {
547        MutableInteractionSource {
548            state: self.state.clone(),
549        }
550    }
551
552    /// Convenience: hard-reset via read handle (same Rc).
553    pub fn reset(&self) {
554        self.to_mutable().reset();
555    }
556
557    /// Convenience: clear hover only via read handle (same Rc).
558    pub fn reset_hover(&self) {
559        self.to_mutable().reset_hover();
560    }
561}
562
563pub fn interaction_epoch() -> u64 {
564    INTERACTION_EPOCH.with(Cell::get)
565}
566
567fn bump_interaction_epoch() {
568    INTERACTION_EPOCH.with(|epoch| epoch.set(epoch.get().wrapping_add(1)));
569}
570
571/// Mutable handle to a shared interaction state.
572///
573/// Create one via [`MutableInteractionSource::new`], then pass the read-only
574/// [`InteractionSource`] to modifiers via `.interaction_source(&source)`.
575///
576/// ```ignore
577/// let src = remember(MutableInteractionSource::new);
578/// m = m.clickable().interaction_source(&src).state_colors(...);
579/// ```
580#[derive(Clone)]
581pub struct MutableInteractionSource {
582    pub(crate) state: Rc<RefCell<InteractionState>>,
583}
584
585impl std::fmt::Debug for MutableInteractionSource {
586    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
587        f.debug_struct("MutableInteractionSource")
588            .finish_non_exhaustive()
589    }
590}
591
592impl MutableInteractionSource {
593    pub fn new() -> Self {
594        Self {
595            state: Rc::new(RefCell::new(InteractionState::default())),
596        }
597    }
598
599    /// Emit an interaction event, updating the shared state.
600    pub fn emit(&self, interaction: Interaction) {
601        let changed = {
602            let mut s = self.state.borrow_mut();
603            let changed = match interaction {
604                Interaction::Press(id, pos) => {
605                    let inserted = s.active_presses.insert(id);
606                    s.last_press_id = Some(id);
607                    s.last_press_position = Some(pos);
608                    inserted
609                }
610                Interaction::Release(id) | Interaction::Cancel(id) => {
611                    if s.active_presses.remove(&id) {
612                        true
613                    } else if id == 0 {
614                        if let Some(any) = s.active_presses.iter().next().copied() {
615                            s.active_presses.remove(&any);
616                            true
617                        } else {
618                            false
619                        }
620                    } else {
621                        false
622                    }
623                }
624                Interaction::HoverEnter => {
625                    let changed = !s.hovered;
626                    s.hovered = true;
627                    changed
628                }
629                Interaction::HoverLeave => {
630                    // Presses end on Release/Cancel only. Compose's hoverExit
631                    // never cancels a press; cancelling here killed the
632                    // ripple as soon as a held pointer drifted off bounds.
633                    let changed = s.hovered;
634                    s.hovered = false;
635                    changed
636                }
637                Interaction::Focus => {
638                    let changed = !s.focused;
639                    s.focused = true;
640                    changed
641                }
642                Interaction::Unfocus => {
643                    let changed = s.focused;
644                    s.focused = false;
645                    changed
646                }
647                Interaction::DragStart => {
648                    let changed = s.dragged == 0;
649                    s.dragged = s.dragged.saturating_add(1);
650                    changed
651                }
652                Interaction::DragStop | Interaction::DragCancel => {
653                    let was = s.dragged;
654                    s.dragged = s.dragged.saturating_sub(1);
655                    was != s.dragged
656                }
657            };
658            if changed {
659                bump_interaction_epoch();
660            }
661            changed
662        };
663        if changed {
664            // So source-driven paint (ripple, state layers) cannot stick stale.
665            crate::frame_clock::request_frame();
666        }
667    }
668
669    /// Get a read-only handle to the shared state.
670    pub fn source(&self) -> InteractionSource {
671        InteractionSource {
672            state: self.state.clone(),
673        }
674    }
675
676    /// Hard-reset all interaction flags.
677    pub fn reset(&self) {
678        let mut s = self.state.borrow_mut();
679        *s = InteractionState::default();
680        drop(s);
681        bump_interaction_epoch();
682        crate::frame_clock::request_frame();
683    }
684
685    /// Clear hover only (keep press/focus/drag).
686    pub fn reset_hover(&self) {
687        let mut s = self.state.borrow_mut();
688        if s.hovered {
689            s.hovered = false;
690            drop(s);
691            bump_interaction_epoch();
692            crate::frame_clock::request_frame();
693        }
694    }
695}
696
697impl Default for MutableInteractionSource {
698    fn default() -> Self {
699        Self::new()
700    }
701}
702
703#[derive(Clone, Default)]
704pub(crate) struct InteractionState {
705    /// Active press IDs (Press → Release/Cancel pairing).
706    active_presses: HashSet<PressId>,
707    hovered: bool,
708    focused: bool,
709    dragged: u32,
710    /// Most recent press position (used by ripple for origin).
711    pub(crate) last_press_position: Option<Vec2>,
712    /// Most recent press ID.
713    pub(crate) last_press_id: Option<PressId>,
714}
715
716#[derive(Clone, Default)]
717pub struct Modifier {
718    /// Optional stable identity key for this view node.
719    ///
720    /// If set, `layout_and_paint` will prefer this over child index when assigning stable ViewIds.
721    /// This is the “escape hatch” for dynamic lists / conditional UI where index-based identity
722    /// would otherwise shift.
723    pub key: Option<u64>,
724
725    pub size: Option<DpSize>,
726    pub width: Option<Dp>,
727    pub height: Option<Dp>,
728    /// Size this node to its content, aligned with `align`. The flag is
729    /// `unbounded`: when true the content is measured with infinite constraints.
730    /// Consumed by the layout engine; `None` keeps the normal sizing rules.
731    pub wrap_content: Option<(Alignment, bool)>,
732    pub required_size: Option<DpSize>,
733    pub fill_max: Option<f32>,
734    pub fill_max_w: Option<f32>,
735    pub fill_max_h: Option<f32>,
736    pub padding: Option<Dp>,
737    pub padding_values: Option<PaddingValues>,
738    pub min_width: Option<Dp>,
739    pub min_height: Option<Dp>,
740    pub max_width: Option<Dp>,
741    pub max_height: Option<Dp>,
742    /// Like [`required_size`] but only for min width. Overrides parent min constraints.
743    pub required_min_width: Option<Dp>,
744    /// Like [`required_size`] but only for max width. Overrides parent max constraints.
745    pub required_max_width: Option<Dp>,
746    /// Like [`required_size`] but only for min height. Overrides parent min constraints.
747    pub required_min_height: Option<Dp>,
748    /// Like [`required_size`] but only for max height. Overrides parent max constraints.
749    pub required_max_height: Option<Dp>,
750    /// Minimum size that only applies when the incoming constraint is 0 (unconstrained).
751    /// Use [`min_width`] for an unconditional minimum.
752    pub default_min_width: Option<Dp>,
753    pub default_min_height: Option<Dp>,
754    pub background: Option<Brush>,
755    /// Multiplies the alpha of the background brush/color when painting.
756    /// Values outside `0.0..=1.0` are clamped by the painter.
757    pub background_alpha: Option<f32>,
758    /// Shape the background is painted into. `None` means a plain rectangle.
759    pub background_shape: Option<Shape>,
760    pub state_colors: Option<StateColors>,
761    pub state_elevation: Option<StateElevation>,
762
763    pub border: Option<Border>,
764    /// Shape the border follows. `None` means the legacy radius-based border.
765    pub border_shape: Option<Shape>,
766    pub flex_grow: Option<f32>,
767    pub flex_shrink: Option<f32>,
768    pub flex_basis: Option<Dp>,
769    /// `flex-basis: content` - size from content, ignoring [`flex_basis`](Self::flex_basis).
770    /// Maps to taffy's `content` keyword (taffy 0.14+).
771    pub flex_basis_content: bool,
772    pub flex_wrap: Option<FlexWrap>,
773    /// Minimum number of flex lines for a multi-line container (taffy 0.14+).
774    /// Transport for flow config; prefer building flows via `FlowRowConfig`.
775    pub flex_line_count: Option<u16>,
776    pub flex_dir: Option<FlexDirection>,
777    pub gap: Option<Dp>,
778    pub row_gap: Option<Dp>,
779    pub column_gap: Option<Dp>,
780    pub align_self: Option<AlignSelf>,
781    pub justify_content: Option<JustifyContent>,
782    pub align_items_container: Option<AlignItems>,
783    pub align_content: Option<AlignContent>,
784    pub clip_rounded: Option<[Dp; 4]>,
785    /// Rectangular clip with a clipping operation (Intersect or Difference).
786    /// The rect is relative to the element bounds, in [`Dp`].
787    pub clip_rect: Option<ClipRect>,
788    /// Generic shape clip. Takes precedence over [`clip_rounded`](Self::clip_rounded)
789    /// and [`clip_rect`](Self::clip_rect) when the paint layer resolves it.
790    pub clip_shape: Option<Shape>,
791    /// Controls whether child content is clipped to the parent bounds.
792    ///
793    /// Defaults to `Clip`. When set to `Visible`, children can overflow
794    /// the parent's rounded rect or clip rect boundary.
795    pub overflow: Option<Overflow>,
796    /// Z-index for hit-testing order (higher = receives events first).
797    pub z_index: f32,
798    /// Z-index for render order (higher = painted on top). If None, uses tree order.
799    pub render_z_index: Option<f32>,
800    /// If true, this view does not create hit regions.
801    pub hit_passthrough: bool,
802    /// If true, this view blocks pointer/touch input for hits below it.
803    pub input_blocker: bool,
804    pub repaint_boundary: bool,
805    pub click: bool,
806    /// When true, the component ignores pointer events and appears disabled.
807    pub disabled: bool,
808    /// When `Some(false)` the node measures to zero and paints nothing.
809    /// `None` means visible.
810    pub visible: Option<bool>,
811    /// When Some(true), the component can receive keyboard focus regardless of interactivity.
812    /// When Some(false), the component cannot receive focus even if interactive.
813    /// When None, focusability is determined implicitly by interactivity (click/pointer/dnd handlers).
814    pub focusable: Option<bool>,
815    /// When true, the Box passes its min constraints to children instead of removing them.
816    pub propagate_min: bool,
817    /// When true, this node and its children form a focus group: focus cycles within
818    /// the group before moving outside it.
819    pub focus_group: bool,
820    pub on_scroll: Option<Rc<dyn Fn(Vec2) -> Vec2>>,
821    /// Scroll handler that receives the input source alongside the delta.
822    /// Takes precedence over `on_scroll` when both are set.
823    pub on_scroll_with_source: Option<Rc<dyn Fn(Vec2, crate::input::ScrollSource) -> Vec2>>,
824    /// Scroll modifier binding. When set, the layout engine treats this view as
825    /// a scroll container, applying clipping and offset to children.
826    ///
827    /// Use `Modifier::vertical_scroll()`, `Modifier::horizontal_scroll()`, or
828    /// `Modifier::scrollable()` to set this.
829    pub scroll: Option<crate::scroll::ScrollBinding>,
830    pub scrollbar_style: Option<crate::scroll::ScrollbarStyle>,
831    /// Nested scroll connection for coordinated scrolling between this element
832    /// and its scrollable descendants.
833    ///
834    /// When set on an ancestor of a scroll container (e.g. `ScrollArea`,
835    /// `LazyColumn`), the scroll container automatically discovers this
836    /// connection and dispatches pre/post scroll events to it during layout.
837    ///
838    /// Mirrors Compose's `Modifier.nestedScroll(NestedScrollConnection)`.
839    pub nested_scroll_connection: Option<crate::nested_scroll::NestedScrollConnection>,
840    pub on_pointer_down: Option<Rc<dyn Fn(PointerEvent)>>,
841    pub on_pointer_move: Option<Rc<dyn Fn(PointerEvent)>>,
842    pub on_pointer_up: Option<Rc<dyn Fn(PointerEvent)>>,
843    pub on_pointer_cancel: Option<Rc<dyn Fn(PointerEvent)>>,
844    pub on_pointer_enter: Option<Rc<dyn Fn(PointerEvent)>>,
845    pub on_pointer_leave: Option<Rc<dyn Fn(PointerEvent)>>,
846    /// Called when the element is clicked (pointer down then up within bounds).
847    pub on_click: Option<Rc<dyn Fn()>>,
848    /// Called when the element is double-clicked/tapped.
849    pub on_double_click: Option<Rc<dyn Fn()>>,
850    /// Called when the element is long-pressed.
851    pub on_long_click: Option<Rc<dyn Fn()>>,
852    /// Called when the element's global position changes after layout.
853    /// Provides the element's rect in window coordinates.
854    pub on_globally_positioned: Option<Rc<dyn Fn(crate::Rect)>>,
855    /// Called when the element's size changes after layout.
856    /// Provides the new size.
857    pub on_size_changed: Option<Rc<dyn Fn(crate::Vec2)>>,
858    /// Called when a key event is received while this element is focused.
859    /// Return `true` to consume the event. This is the normal handler.
860    pub on_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
861    /// Called before `on_key_event` -> if the preview handler returns `true`,
862    /// the event is consumed and `on_key_event` is NOT called.
863    pub on_preview_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
864    /// Called when an IME event (composition update/commit) is received
865    /// while this element is focused. Return `true` to consume the event.
866    pub on_ime: Option<Rc<dyn Fn(crate::input::ImeEvent) -> bool>>,
867    /// Apply a gaussian blur to this element's rendered content.
868    /// When set, `graphics_layer` is auto-enabled if not already set.
869    /// Use `Modifier::blur(radius)` for uniform blur, or
870    /// `Modifier::blur_with_edge(rx, ry, edge)` for per-axis control.
871    pub blur: Option<BlurStyle>,
872    /// Custom layout callback. When set, the element's measurement is delegated
873    /// to this function instead of the default Taffy-based layout.
874    /// The callback receives `LayoutConstraints` (min/max width/height in [`Dp`]).
875    /// Returns `(width, height)` for this element, in [`Dp`].
876    pub layout: Option<Rc<dyn Fn(LayoutConstraints) -> (Dp, Dp)>>,
877    pub semantics: Option<crate::Semantics>,
878    pub alpha: Option<f32>,
879    pub graphics_layer: Option<f32>,
880    /// Compose-style graphics layer configured by a per-frame closure. The
881    /// closure is re-evaluated on every paint, so animated values do not
882    /// require a recomposition.
883    pub graphics_layer_scope: Option<Rc<dyn Fn() -> GraphicsLayerScope>>,
884    /// Size to the parent's content without contributing to the parent's
885    /// measurement (Compose `Modifier.matchParentSize`).
886    pub match_parent_size: bool,
887    /// `(axis, enabled)` marker used by lazy-list items to size against the
888    /// parent's maximum cross-axis extent instead of their incoming constraints.
889    pub fill_parent_max_size: Option<(ScrollAxis, bool)>,
890    /// Baseline-relative top padding for text layering.
891    pub padding_from_baseline: Option<Dp>,
892    /// Painter draw order relative to the node's own content. `-1` paints
893    /// behind, `+1` paints on top.
894    pub paint_order: i8,
895    /// Shared-element identity whose painted bounds follow the owning node.
896    pub shared_element: Option<crate::shared::SharedElementState>,
897    /// Persistent modifier nodes, reconciled by element type and key.
898    pub nodes: Vec<crate::modifier_node::ModifierNodeHandle>,
899    pub shadow: Option<ShadowSpec>,
900    /// Corner radii the shadow silhouette is shaped to, independent of what the
901    /// layer's own alpha contains. Mirrors Compose's `Modifier.shadow(shape)`,
902    /// so a square card can still cast a rounded shadow. When `None` the
903    /// silhouette follows the layer alpha as-is.
904    pub shadow_shape: Option<[Dp; 4]>,
905    pub transform: Option<Transform>,
906    pub grid: Option<GridConfig>,
907    pub grid_col_span: Option<u16>,
908    pub grid_row_span: Option<u16>,
909    pub position_type: Option<PositionType>,
910    pub offset_left: Option<Dp>,
911    pub offset_right: Option<Dp>,
912    pub offset_top: Option<Dp>,
913    pub offset_bottom: Option<Dp>,
914    /// RTL-aware translation applied after layout: `(x, y)`. `x` flips with
915    /// the layout direction. Set by [`Modifier::offset`].
916    pub layout_offset: Option<(Dp, Dp)>,
917    /// Translation applied after layout that never flips for RTL: `(x, y)`.
918    /// Set by [`Modifier::absolute_offset`].
919    pub absolute_layout_offset: Option<(Dp, Dp)>,
920
921    pub margin_left: Option<Dp>,
922    pub margin_right: Option<Dp>,
923    pub margin_top: Option<Dp>,
924    pub margin_bottom: Option<Dp>,
925    pub aspect_ratio: Option<f32>,
926    /// Size this node's width to its min or max intrinsic content size.
927    /// Wired to taffy's `min-content`/`max-content` sizing keywords.
928    pub intrinsic_width: Option<IntrinsicSize>,
929    /// Size this node's height to its min or max intrinsic content size.
930    /// Wired to taffy's `min-content`/`max-content` sizing keywords.
931    pub intrinsic_height: Option<IntrinsicSize>,
932    /// `fit-content(limit)` width in [`Dp`]: `max(min-content, min(max-content, limit))`.
933    /// Applies when no explicit [`width`](Self::width) is set.
934    pub fit_content_width: Option<Dp>,
935    /// `fit-content(limit)` height in [`Dp`]. Applies when no explicit
936    /// [`height`](Self::height) is set.
937    pub fit_content_height: Option<Dp>,
938    /// Baseline alignment request for a `Row` child. See [`BaselineAlign`].
939    /// Set via `RowScope` methods; inert under non-`Row` parents.
940    pub baseline_align: Option<BaselineAlign>,
941    /// CSS containment (`contain: layout` / `paint` / `content`, taffy 0.14+).
942    /// Establishes an independent formatting context; useful with
943    /// `repaint_boundary`-style subtrees and virtualized lists.
944    /// Note: `contain: size` is not supported by taffy.
945    pub contain: Option<Contain>,
946    pub painter: Option<Rc<dyn Fn(&mut crate::Scene, crate::Rect, f32)>>,
947    pub paint_callback: Option<crate::PaintCallbackPayload>,
948
949    // Drag-drop (internal)
950    pub on_drag_start: Option<Rc<dyn Fn(crate::dnd::DragStart) -> Option<crate::dnd::DragPayload>>>,
951    pub on_drag_end: Option<Rc<dyn Fn(crate::dnd::DragEnd)>>,
952    pub on_drag_enter: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
953    pub on_drag_over: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
954    pub on_drag_leave: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
955    pub on_drop: Option<Rc<dyn Fn(crate::dnd::DropEvent) -> bool>>,
956    /// Compose-like `drawDragDecoration`: paints the floating preview while dragging.
957    pub drag_preview: Option<crate::dnd::DragPreview>,
958
959    pub on_action: Option<Rc<dyn Fn(crate::shortcuts::Action) -> bool>>,
960    pub on_set_progress: Option<Rc<dyn Fn(f32)>>,
961    pub on_expand: Option<Rc<dyn Fn()>>,
962    pub on_collapse: Option<Rc<dyn Fn()>>,
963    pub on_dismiss: Option<Rc<dyn Fn()>>,
964
965    /// Cursor icon hint for desktop/web runners.
966    pub cursor: Option<crate::CursorIcon>,
967
968    /// If set, the size of this node will smoothly animate to its target size
969    /// whenever content size changes. Uses the provided animation spec.
970    pub animate_content_size: Option<AnimationSpec>,
971
972    /// A `FocusRequester` handle that will be associated with this view.
973    /// When the requester's `request_focus()` is called, keyboard focus will
974    /// move to this view.
975    pub focus_requester: Option<crate::runtime::FocusRequester>,
976
977    /// A handle that, when requested, scrolls ancestor containers so this view
978    /// is visible. Compose `Modifier.bringIntoViewRequester`.
979    pub bring_into_view: Option<crate::runtime::BringIntoViewRequester>,
980
981    /// Reports this view's bounds in px whenever they change.
982    pub on_focused_bounds_changed: Option<Rc<dyn Fn(crate::Rect)>>,
983
984    /// Called when this view gains or loses focus. The boolean parameter is
985    /// `true` when focused, `false` when unfocused.
986    pub on_focus_changed: Option<Rc<dyn Fn(bool)>>,
987
988    /// If set, this view reads its interaction state (hover/press) from this source
989    /// in addition to the implicit view-ID-based matching. The source state is OR'd
990    /// with the implicit state, enabling programmatic override of hover/press visuals.
991    ///
992    /// When set, the layout engine also auto-wires the source to emit PointerDown/Up
993    /// and HoverEnter/Leave events into the source via the hit region's callbacks.
994    pub interaction_source: Option<InteractionSource>,
995
996    /// Text input configuration. When set, this box acts as a text input field.
997    pub text_input: Option<TextInputConfig>,
998
999    /// Selected range for a `Text` node. The layout engine paints the highlight
1000    /// behind the glyphs from the node's real text layout.
1001    pub text_selection: Option<crate::text::TextSelection>,
1002
1003    /// Indication (ripple/overlay) factory for visual feedback on interaction.
1004    pub indication: Option<Rc<dyn IndicationNodeFactory>>,
1005}
1006
1007impl std::fmt::Debug for Modifier {
1008    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1009        let mut s = f.debug_struct("Modifier");
1010
1011        macro_rules! opt_val {
1012            ($($name:ident),+ $(,)?) => {
1013                $( if self.$name.is_some() { s.field(stringify!($name), &self.$name); } )+
1014            };
1015        }
1016        if self.indication.is_some() {
1017            s.field("indication", &"…");
1018        }
1019        s.field("scrollbar_style", &self.scrollbar_style);
1020
1021        opt_val!(
1022            key,
1023            size,
1024            width,
1025            height,
1026            required_size,
1027            wrap_content,
1028            visible,
1029            padding,
1030            padding_values,
1031            min_width,
1032            min_height,
1033            max_width,
1034            max_height,
1035            required_min_width,
1036            required_max_width,
1037            required_min_height,
1038            required_max_height,
1039            default_min_width,
1040            default_min_height,
1041            fill_max,
1042            fill_max_w,
1043            fill_max_h,
1044            background,
1045            background_alpha,
1046            background_shape,
1047            state_colors,
1048            state_elevation,
1049            border,
1050            border_shape,
1051            flex_grow,
1052            flex_shrink,
1053            flex_basis,
1054            flex_wrap,
1055            flex_dir,
1056            gap,
1057            row_gap,
1058            column_gap,
1059            align_self,
1060            justify_content,
1061            align_items_container,
1062            align_content,
1063            clip_rounded,
1064            clip_rect,
1065            clip_shape,
1066            render_z_index,
1067            semantics,
1068            alpha,
1069            transform,
1070            grid,
1071            grid_col_span,
1072            grid_row_span,
1073            position_type,
1074            offset_left,
1075            offset_right,
1076            offset_top,
1077            offset_bottom,
1078            layout_offset,
1079            absolute_layout_offset,
1080            margin_left,
1081            margin_right,
1082            margin_top,
1083            margin_bottom,
1084            aspect_ratio,
1085            intrinsic_width,
1086            intrinsic_height,
1087            cursor,
1088            animate_content_size,
1089            blur,
1090            fill_parent_max_size,
1091            padding_from_baseline,
1092        );
1093
1094        macro_rules! opt_cb {
1095            ($($name:ident),+ $(,)?) => {
1096                $( if self.$name.is_some() { s.field(stringify!($name), &"…"); } )+
1097            };
1098        }
1099        opt_cb!(
1100            on_scroll,
1101            scroll,
1102            nested_scroll_connection,
1103            on_pointer_down,
1104            on_pointer_move,
1105            on_pointer_up,
1106            on_pointer_cancel,
1107            on_pointer_enter,
1108            on_pointer_leave,
1109            on_click,
1110            on_double_click,
1111            on_long_click,
1112            on_globally_positioned,
1113            on_size_changed,
1114            on_key_event,
1115            on_preview_key_event,
1116            on_ime,
1117            painter,
1118            paint_callback,
1119            on_drag_start,
1120            on_drag_end,
1121            on_drag_enter,
1122            on_drag_over,
1123            on_drag_leave,
1124            on_drop,
1125            drag_preview,
1126            on_action,
1127            on_focus_changed,
1128            interaction_source,
1129            text_input,
1130            text_selection,
1131            layout,
1132            graphics_layer_scope,
1133        );
1134
1135        macro_rules! flag {
1136            ($($name:ident),+ $(,)?) => {
1137                $( if self.$name { s.field(stringify!($name), &true); } )+
1138            };
1139        }
1140        flag!(
1141            hit_passthrough,
1142            input_blocker,
1143            repaint_boundary,
1144            click,
1145            disabled,
1146            propagate_min,
1147            focus_group,
1148            match_parent_size,
1149        );
1150
1151        if let Some(f) = self.focusable {
1152            s.field("focusable", &f);
1153        }
1154        if self.z_index != 0.0 {
1155            s.field("z_index", &self.z_index);
1156        }
1157        if self.paint_order != 0 {
1158            s.field("paint_order", &self.paint_order);
1159        }
1160
1161        s.finish()
1162    }
1163}
1164
1165impl_option_fields!(Modifier);
1166
1167/// Content alignment for a container, applied as the flexbox cross-axis
1168/// (`align_items`) and main-axis (`justify_content`) pair. Mirrors Compose's
1169/// `Alignment` for `Box(contentAlignment = ...)`.
1170#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1171pub enum Alignment {
1172    TopStart,
1173    TopCenter,
1174    TopEnd,
1175    CenterStart,
1176    #[default]
1177    Center,
1178    CenterEnd,
1179    BottomStart,
1180    BottomCenter,
1181    BottomEnd,
1182}
1183
1184impl Alignment {
1185    /// The corresponding (`align_items`, `justify_content`) pair for flexbox layout.
1186    pub fn to_flex(self) -> (AlignItems, JustifyContent) {
1187        use AlignItems as AI;
1188        use JustifyContent as JC;
1189        match self {
1190            Self::TopStart => (AI::START, JC::START),
1191            Self::TopCenter => (AI::START, JC::CENTER),
1192            Self::TopEnd => (AI::START, JC::END),
1193            Self::CenterStart => (AI::CENTER, JC::START),
1194            Self::Center => (AI::CENTER, JC::CENTER),
1195            Self::CenterEnd => (AI::CENTER, JC::END),
1196            Self::BottomStart => (AI::END, JC::START),
1197            Self::BottomCenter => (AI::END, JC::CENTER),
1198            Self::BottomEnd => (AI::END, JC::END),
1199        }
1200    }
1201
1202    /// Like [`to_flex`](Self::to_flex) but with CSS *safe* alignment:
1203    /// overflowing content is aligned from the start edge instead of
1204    /// overflowing both edges, so it stays reachable inside scroll
1205    /// containers (taffy 0.11+).
1206    pub fn to_flex_safe(self) -> (AlignItems, JustifyContent) {
1207        use AlignItems as AI;
1208        use JustifyContent as JC;
1209        match self {
1210            Self::TopStart => (AI::SAFE_START, JC::SAFE_START),
1211            Self::TopCenter => (AI::SAFE_START, JC::SAFE_CENTER),
1212            Self::TopEnd => (AI::SAFE_START, JC::SAFE_END),
1213            Self::CenterStart => (AI::SAFE_CENTER, JC::SAFE_START),
1214            Self::Center => (AI::SAFE_CENTER, JC::SAFE_CENTER),
1215            Self::CenterEnd => (AI::SAFE_CENTER, JC::SAFE_END),
1216            Self::BottomStart => (AI::SAFE_END, JC::SAFE_START),
1217            Self::BottomCenter => (AI::SAFE_END, JC::SAFE_CENTER),
1218            Self::BottomEnd => (AI::SAFE_END, JC::SAFE_END),
1219        }
1220    }
1221}
1222
1223impl Modifier {
1224    pub fn new() -> Self {
1225        Self::default()
1226    }
1227
1228    /// Attaches a stable identity key to this view node.
1229    /// Use for dynamic lists / conditional UI where index-based identity can shift.
1230    pub fn key(mut self, key: u64) -> Self {
1231        self.key = Some(key);
1232        self
1233    }
1234
1235    pub fn size(mut self, w: Dp, h: Dp) -> Self {
1236        self.size = Some(DpSize::new(w, h));
1237        self
1238    }
1239    /// Measure this node from its content, aligning the result with `align`.
1240    /// When `unbounded` is true the content is measured with infinite
1241    /// constraints in the wrapped dimension. Consumed by the layout engine.
1242    pub fn wrap_content_size(mut self, align: Alignment, unbounded: bool) -> Self {
1243        self.wrap_content = Some((align, unbounded));
1244        self
1245    }
1246    /// Content-driven width, aligned horizontally.
1247    pub fn wrap_content_width(self, align: Alignment, unbounded: bool) -> Self {
1248        self.wrap_content_size(align, unbounded)
1249    }
1250    /// Content-driven height, aligned vertically.
1251    pub fn wrap_content_height(self, align: Alignment, unbounded: bool) -> Self {
1252        self.wrap_content_size(align, unbounded)
1253    }
1254    pub fn width(mut self, w: Dp) -> Self {
1255        self.width = Some(w);
1256        self
1257    }
1258    pub fn height(mut self, h: Dp) -> Self {
1259        self.height = Some(h);
1260        self
1261    }
1262    /// Set a fixed size that overrides parent constraints.
1263    /// Unlike `size()` which is bounded by the parent's max constraints,
1264    /// `required_size()` forces the node to this size regardless of the parent,
1265    /// acting as both min and max.
1266    pub fn required_size(mut self, w: Dp, h: Dp) -> Self {
1267        self.required_size = Some(DpSize::new(w, h));
1268        self
1269    }
1270    pub fn required_width_in(mut self, min: Dp, max: Dp) -> Self {
1271        self.required_min_width = Some(Dp(min.0.max(0.0)));
1272        self.required_max_width = Some(Dp(max.0.max(0.0)));
1273        self
1274    }
1275    pub fn required_height_in(mut self, min: Dp, max: Dp) -> Self {
1276        self.required_min_height = Some(Dp(min.0.max(0.0)));
1277        self.required_max_height = Some(Dp(max.0.max(0.0)));
1278        self
1279    }
1280    pub fn required_min_width(mut self, w: Dp) -> Self {
1281        self.required_min_width = Some(Dp(w.0.max(0.0)));
1282        self
1283    }
1284    pub fn required_max_width(mut self, w: Dp) -> Self {
1285        self.required_max_width = Some(Dp(w.0.max(0.0)));
1286        self
1287    }
1288    pub fn required_min_height(mut self, h: Dp) -> Self {
1289        self.required_min_height = Some(Dp(h.0.max(0.0)));
1290        self
1291    }
1292    pub fn required_max_height(mut self, h: Dp) -> Self {
1293        self.required_max_height = Some(Dp(h.0.max(0.0)));
1294        self
1295    }
1296    /// Minimum size that only takes effect when the incoming constraint is 0 (unconstrained).
1297    pub fn default_min_size(mut self, w: Dp, h: Dp) -> Self {
1298        self.default_min_width = Some(Dp(w.0.max(0.0)));
1299        self.default_min_height = Some(Dp(h.0.max(0.0)));
1300        self
1301    }
1302    /// Size to the parent's content without influencing the parent's own
1303    /// measurement (Compose `Modifier.matchParentSize`).
1304    pub fn match_parent_size(mut self) -> Self {
1305        self.match_parent_size = true;
1306        self
1307    }
1308    /// Fill the available space in both dimensions.
1309    /// By default fills 100% (fraction = 1.0). Pass a fraction to fill partially.
1310    pub fn fill_max_size(mut self) -> Self {
1311        self.fill_max = Some(1.0);
1312        self
1313    }
1314    pub fn fill_max_size_frac(mut self, fraction: f32) -> Self {
1315        self.fill_max = Some(fraction.clamp(0.0, 1.0));
1316        self
1317    }
1318    /// Fill the available width. By default fills 100%.
1319    pub fn fill_max_width(mut self) -> Self {
1320        self.fill_max_w = Some(1.0);
1321        self
1322    }
1323    pub fn fill_max_width_frac(mut self, fraction: f32) -> Self {
1324        self.fill_max_w = Some(fraction.clamp(0.0, 1.0));
1325        self
1326    }
1327    /// Fill the parent's maximum width. Marker for lazy-list items whose
1328    /// incoming width constraint is unbounded.
1329    pub fn fill_parent_max_width(mut self) -> Self {
1330        self.fill_parent_max_size = Some((ScrollAxis::Horizontal, true));
1331        self
1332    }
1333    /// Fill the available height. By default fills 100%.
1334    pub fn fill_max_height(mut self) -> Self {
1335        self.fill_max_h = Some(1.0);
1336        self
1337    }
1338    pub fn fill_max_height_frac(mut self, fraction: f32) -> Self {
1339        self.fill_max_h = Some(fraction.clamp(0.0, 1.0));
1340        self
1341    }
1342    /// Fill the parent's maximum height. Marker for lazy-list items whose
1343    /// incoming height constraint is unbounded.
1344    pub fn fill_parent_max_height(mut self) -> Self {
1345        self.fill_parent_max_size = Some((ScrollAxis::Vertical, true));
1346        self
1347    }
1348    pub fn padding(mut self, v: Dp) -> Self {
1349        self.padding = Some(v);
1350        self
1351    }
1352    /// Add top padding measured from the first text baseline.
1353    pub fn padding_from_baseline(mut self, v: Dp) -> Self {
1354        self.padding_from_baseline = Some(v);
1355        self
1356    }
1357    pub fn padding_values(mut self, padding: PaddingValues) -> Self {
1358        self.padding_values = Some(padding);
1359        self
1360    }
1361    /// Add padding equal to the current IME (soft keyboard) bottom inset.
1362    /// Combine with `system_bars_padding()` to handle both system bars and keyboard.
1363    /// Window insets are stored in px and converted to [`Dp`] here.
1364    pub fn ime_padding(mut self) -> Self {
1365        use crate::units::Px;
1366        let insets = crate::locals::window_insets();
1367        let mut p = self.padding_values.unwrap_or_default();
1368        p.bottom = p.bottom + Px(insets.ime_bottom).to_dp();
1369        self.padding_values = Some(p);
1370        self
1371    }
1372    /// Add padding equal to the current system bar insets (status bar top, nav bar bottom).
1373    pub fn system_bars_padding(mut self) -> Self {
1374        use crate::units::Px;
1375        let insets = crate::locals::window_insets();
1376        let mut p = self.padding_values.unwrap_or_default();
1377        p.top = p.top + Px(insets.top).to_dp();
1378        p.bottom = p.bottom + Px(insets.bottom).to_dp();
1379        self.padding_values = Some(p);
1380        self
1381    }
1382    /// Add status bar inset as top padding.
1383    pub fn status_bars_padding(mut self) -> Self {
1384        use crate::units::Px;
1385        let insets = crate::locals::window_insets();
1386        let mut p = self.padding_values.unwrap_or_default();
1387        p.top = p.top + Px(insets.top).to_dp();
1388        self.padding_values = Some(p);
1389        self
1390    }
1391    /// Add navigation bar inset as bottom padding.
1392    pub fn navigation_bars_padding(mut self) -> Self {
1393        let insets = crate::locals::window_insets();
1394        use crate::units::Px;
1395        let mut p = self.padding_values.unwrap_or_default();
1396        p.bottom = p.bottom + Px(insets.bottom).to_dp();
1397        self.padding_values = Some(p);
1398        self
1399    }
1400    pub fn min_size(mut self, w: Dp, h: Dp) -> Self {
1401        self.min_width = Some(w);
1402        self.min_height = Some(h);
1403        self
1404    }
1405    pub fn max_size(mut self, w: Dp, h: Dp) -> Self {
1406        self.max_width = Some(w);
1407        self.max_height = Some(h);
1408        self
1409    }
1410    pub fn min_width(mut self, w: Dp) -> Self {
1411        self.min_width = Some(w);
1412        self
1413    }
1414    pub fn min_height(mut self, h: Dp) -> Self {
1415        self.min_height = Some(h);
1416        self
1417    }
1418    pub fn max_width(mut self, w: Dp) -> Self {
1419        self.max_width = Some(w);
1420        self
1421    }
1422    pub fn max_height(mut self, h: Dp) -> Self {
1423        self.max_height = Some(h);
1424        self
1425    }
1426    /// Set a solid color background.
1427    pub fn background(mut self, color: Color) -> Self {
1428        self.background = Some(Brush::Solid(color));
1429        self
1430    }
1431    /// Set a brush (solid, gradient, etc.) background.
1432    pub fn background_brush(mut self, brush: Brush) -> Self {
1433        self.background = Some(brush);
1434        self
1435    }
1436    /// Paint a brush into an arbitrary [`Shape`].
1437    pub fn background_with_shape(mut self, brush: Brush, shape: Shape, alpha: f32) -> Self {
1438        self.background = Some(brush);
1439        self.background_shape = Some(shape);
1440        self.background_alpha = Some(alpha);
1441        self
1442    }
1443    /// Solid-color convenience for [`background_with_shape`](Self::background_with_shape).
1444    pub fn background_shape_color(self, color: Color, shape: Shape) -> Self {
1445        self.background_with_shape(Brush::Solid(color), shape, 1.0)
1446    }
1447    /// Multiply the background brush/color alpha when painting.
1448    pub fn background_alpha(mut self, alpha: f32) -> Self {
1449        self.background_alpha = Some(alpha);
1450        self
1451    }
1452    pub fn border(mut self, width: Dp, color: Color, radius: Dp) -> Self {
1453        self.border = Some(Border {
1454            width,
1455            brush: Brush::Solid(color),
1456            radius: [radius; 4],
1457        });
1458        self
1459    }
1460    /// Brush border (gradient, etc.). Mirrors Compose
1461    /// `Modifier.border(width: Dp, brush: Brush, shape: Shape)`.
1462    pub fn border_brush(mut self, width: Dp, brush: Brush, radius: Dp) -> Self {
1463        self.border = Some(Border {
1464            width,
1465            brush,
1466            radius: [radius; 4],
1467        });
1468        self
1469    }
1470    pub fn border_radii(mut self, width: Dp, color: Color, radii: [Dp; 4]) -> Self {
1471        self.border = Some(Border {
1472            width,
1473            brush: Brush::Solid(color),
1474            radius: radii,
1475        });
1476        self
1477    }
1478    /// Brush border with per-corner radii.
1479    pub fn border_brush_radii(mut self, width: Dp, brush: Brush, radii: [Dp; 4]) -> Self {
1480        self.border = Some(Border {
1481            width,
1482            brush,
1483            radius: radii,
1484        });
1485        self
1486    }
1487    /// Stroke an arbitrary [`Shape`] with a brush.
1488    pub fn border_with_shape(mut self, width: Dp, brush: Brush, shape: Shape) -> Self {
1489        self.border = Some(Border {
1490            width,
1491            brush,
1492            radius: [Dp::ZERO; 4],
1493        });
1494        self.border_shape = Some(shape);
1495        self
1496    }
1497    pub fn flex_grow(mut self, v: f32) -> Self {
1498        self.flex_grow = Some(v);
1499        self
1500    }
1501    pub fn flex_shrink(mut self, v: f32) -> Self {
1502        self.flex_shrink = Some(v);
1503        self
1504    }
1505    pub fn flex_basis(mut self, v: Dp) -> Self {
1506        self.flex_basis = Some(v);
1507        self
1508    }
1509    pub fn flex_wrap(mut self, w: FlexWrap) -> Self {
1510        self.flex_wrap = Some(w);
1511        self
1512    }
1513    /// `flex-basis: content` - size from content, ignoring any
1514    /// [`flex_basis`](Self::flex_basis) value.
1515    pub fn flex_basis_content(mut self) -> Self {
1516        self.flex_basis_content = true;
1517        self
1518    }
1519    pub fn flex_dir(mut self, d: FlexDirection) -> Self {
1520        self.flex_dir = Some(d);
1521        self
1522    }
1523    pub fn gap(mut self, v: Dp) -> Self {
1524        let v = Dp(v.0.max(0.0));
1525        self.gap = Some(v);
1526        self.row_gap = Some(v);
1527        self.column_gap = Some(v);
1528        self
1529    }
1530    pub fn row_gap(mut self, v: Dp) -> Self {
1531        self.row_gap = Some(Dp(v.0.max(0.0)));
1532        self
1533    }
1534    pub fn column_gap(mut self, v: Dp) -> Self {
1535        self.column_gap = Some(Dp(v.0.max(0.0)));
1536        self
1537    }
1538    pub fn align_self(mut self, a: AlignSelf) -> Self {
1539        self.align_self = Some(a);
1540        self
1541    }
1542    pub fn align_self_center(mut self) -> Self {
1543        self.align_self = Some(AlignSelf::CENTER);
1544        self
1545    }
1546    pub fn justify_content(mut self, j: JustifyContent) -> Self {
1547        self.justify_content = Some(j);
1548        self
1549    }
1550    pub fn align_items(mut self, a: AlignItems) -> Self {
1551        self.align_items_container = Some(a);
1552        self
1553    }
1554    /// Compose-like content alignment (sets both `align_items` and
1555    /// `justify_content` in one call).
1556    pub fn content_alignment(self, alignment: Alignment) -> Self {
1557        let (ai, jc) = alignment.to_flex();
1558        self.align_items(ai).justify_content(jc)
1559    }
1560    /// Like [`content_alignment`](Self::content_alignment) but with CSS
1561    /// *safe* alignment, so overflowing content stays reachable inside
1562    /// scroll containers. Prefer this for centered dialogs and scroll
1563    /// content that may exceed the viewport.
1564    pub fn content_alignment_safe(self, alignment: Alignment) -> Self {
1565        let (ai, jc) = alignment.to_flex_safe();
1566        self.align_items(ai).justify_content(jc)
1567    }
1568    pub fn align_content(mut self, a: AlignContent) -> Self {
1569        self.align_content = Some(a);
1570        self
1571    }
1572    pub fn clip_rounded(mut self, radius: Dp) -> Self {
1573        self.clip_rounded = Some([radius; 4]);
1574        self
1575    }
1576    pub fn clip_rounded_radii(mut self, radii: [Dp; 4]) -> Self {
1577        self.clip_rounded = Some(radii);
1578        self
1579    }
1580    /// Clip a rectangular region from this element using the given operation.
1581    /// `left`, `top`, `right`, `bottom` are relative to the element bounds, in [`Dp`].
1582    pub fn clip_rect(mut self, left: Dp, top: Dp, right: Dp, bottom: Dp, op: ClipOp) -> Self {
1583        self.clip_rect = Some(ClipRect {
1584            left,
1585            top,
1586            right,
1587            bottom,
1588            op,
1589        });
1590        self
1591    }
1592    /// Clip this element's content to an arbitrary [`Shape`].
1593    pub fn clip(mut self, shape: Shape) -> Self {
1594        self.clip_shape = Some(shape);
1595        self.clip_rounded = None;
1596        self.clip_rect = None;
1597        self
1598    }
1599    /// Clip this element's content to its bounds (sharp rectangle).
1600    pub fn clip_to_bounds(self) -> Self {
1601        self.clip(Shape::Rectangle)
1602    }
1603    pub fn overflow(mut self, overflow: Overflow) -> Self {
1604        self.overflow = Some(overflow);
1605        self
1606    }
1607    pub fn z_index(mut self, z: f32) -> Self {
1608        self.z_index = z;
1609        self
1610    }
1611
1612    /// Sets the render z-index for this view. Higher values are painted on top.
1613    /// Unlike `z_index` (which only affects hit-testing), this affects visual layering.
1614    pub fn render_z_index(mut self, z: f32) -> Self {
1615        self.render_z_index = Some(z);
1616        self
1617    }
1618
1619    /// Prevent pointer/touch from reaching lower layers.
1620    pub fn input_blocker(mut self) -> Self {
1621        self.input_blocker = true;
1622        self
1623    }
1624
1625    pub fn hit_passthrough(mut self) -> Self {
1626        self.hit_passthrough = true;
1627        self
1628    }
1629    pub fn clickable(mut self) -> Self {
1630        self.click = true;
1631        if self.indication.is_none() {
1632            self.indication = crate::locals::local_indication();
1633        }
1634        self
1635    }
1636    /// Make this element clickable and attach an [`InteractionSource`] for state tracking.
1637    /// Combines `.clickable()` and `.interaction_source(&source)` in one call.
1638    pub fn clickable_with_source(mut self, source: &MutableInteractionSource) -> Self {
1639        self.click = true;
1640        self.interaction_source = Some(source.source());
1641        if self.indication.is_none() {
1642            self.indication = crate::locals::local_indication();
1643        }
1644        self
1645    }
1646    /// Set state-driven background colors for hover, press, disabled states.
1647    /// The layout engine automatically selects and animates between these based on interaction.
1648    pub fn state_colors(mut self, colors: StateColors) -> Self {
1649        self.state_colors = Some(colors);
1650        self
1651    }
1652    /// Set state-driven elevation values for hover, press, disabled states.
1653    pub fn state_elevation(mut self, elev: StateElevation) -> Self {
1654        self.state_elevation = Some(elev);
1655        self
1656    }
1657    /// Mark this component as disabled - it won't respond to pointer events.
1658    pub fn disabled(mut self) -> Self {
1659        self.disabled = true;
1660        self
1661    }
1662    /// Mark this component as enabled or disabled.
1663    pub fn enabled(mut self, enabled: bool) -> Self {
1664        self.disabled = !enabled;
1665        self
1666    }
1667    /// Control visibility. An invisible node measures to zero and paints
1668    /// nothing. Nodes are visible by default.
1669    pub fn visible(mut self, visible: bool) -> Self {
1670        self.visible = Some(visible);
1671        self
1672    }
1673    /// Resolved visibility: `true` unless explicitly set to `false`.
1674    pub fn is_visible(&self) -> bool {
1675        self.visible.unwrap_or(true)
1676    }
1677    /// Set explicit focusability for this component.
1678    /// When `true`, the component can receive keyboard focus even without
1679    /// explicit click/pointer/dnd handlers. When `false`, focus is suppressed
1680    /// even for interactive components.
1681    pub fn focusable(mut self, focusable: bool) -> Self {
1682        self.focusable = Some(focusable);
1683        self
1684    }
1685    /// Mark this node as a focus group: focus cycles within this group before
1686    /// moving to siblings outside it.
1687    pub fn focus_group(mut self) -> Self {
1688        self.focus_group = true;
1689        self
1690    }
1691    /// Attach an [`InteractionSource`] to this view. The source provides shared
1692    /// interaction state (hover/press/focus/drag) that supplements the implicit
1693    /// view-ID-based state. The layout engine auto-wires pointer events
1694    /// (press/hover), keyboard activation (Space/Enter press parity), focus
1695    /// transitions (Focus/Unfocus) and DnD drag start/end into the source so it
1696    /// stays in sync with user interaction.
1697    ///
1698    /// Use this when you need programmatic control of interaction state (e.g.,
1699    /// showing pressed state during an async operation) or to share interaction
1700    /// state between components.
1701    pub fn interaction_source(mut self, source: &MutableInteractionSource) -> Self {
1702        self.interaction_source = Some(source.source());
1703        self
1704    }
1705    /// Convenience: register hover enter/leave callbacks.
1706    /// Shorthand for setting `on_pointer_enter` and `on_pointer_leave`.
1707    pub fn hoverable(
1708        mut self,
1709        on_enter: impl Fn() + 'static,
1710        on_leave: impl Fn() + 'static,
1711    ) -> Self {
1712        self.on_pointer_enter = Some(Rc::new(move |_| on_enter()));
1713        self.on_pointer_leave = Some(Rc::new(move |_| on_leave()));
1714        self
1715    }
1716    pub fn hoverable_enabled(
1717        self,
1718        enabled: bool,
1719        on_enter: impl Fn() + 'static,
1720        on_leave: impl Fn() + 'static,
1721    ) -> Self {
1722        if enabled {
1723            self.hoverable(on_enter, on_leave)
1724        } else {
1725            self
1726        }
1727    }
1728    /// Attach an [`InteractionSource`] to track hover state without explicit callbacks.
1729    /// The source automatically receives HoverEnter/Leave events from the layout engine's
1730    /// auto-wiring, so you can use it with `collect_is_hovered()` for custom visuals.
1731    pub fn hoverable_with_source(mut self, source: &MutableInteractionSource) -> Self {
1732        self.interaction_source = Some(source.source());
1733        self
1734    }
1735    /// When true, Box passes min-width/min-height constraints to its children
1736    /// instead of allowing them to shrink below the parent's min constraints.
1737    pub fn propagate_min_constraints(mut self, propagate: bool) -> Self {
1738        self.propagate_min = propagate;
1739        self
1740    }
1741    pub fn on_scroll(mut self, f: impl Fn(Vec2) -> Vec2 + 'static) -> Self {
1742        self.on_scroll = Some(Rc::new(f));
1743        self
1744    }
1745    /// Scroll handler that also learns what produced the delta.
1746    ///
1747    /// A wheel and a one-finger drag both arrive as a bare `Vec2`, so a surface
1748    /// that zooms on one and pans on the other cannot tell them apart. Prefer
1749    /// this over [`Modifier::on_scroll`] where the difference matters; a node
1750    /// may set either, never both.
1751    pub fn on_scroll_with_source(
1752        mut self,
1753        f: impl Fn(Vec2, crate::input::ScrollSource) -> Vec2 + 'static,
1754    ) -> Self {
1755        self.on_scroll_with_source = Some(Rc::new(f));
1756        self
1757    }
1758    /// Attach a vertical scroll binding to this modifier.
1759    /// The binding provides callbacks for scroll handling, viewport tracking, etc.
1760    /// Use `ScrollState::to_binding()` to create one from a scroll state.
1761    pub fn vertical_scroll(mut self, binding: crate::scroll::ScrollAxisBinding) -> Self {
1762        self.scroll = Some(crate::scroll::ScrollBinding::Vertical(binding));
1763        self
1764    }
1765    /// Attach a horizontal scroll binding to this modifier.
1766    pub fn horizontal_scroll(mut self, binding: crate::scroll::ScrollAxisBinding) -> Self {
1767        self.scroll = Some(crate::scroll::ScrollBinding::Horizontal(binding));
1768        self
1769    }
1770    /// Attach a 2D scroll binding to this modifier.
1771    pub fn scrollable(mut self, binding: crate::scroll::ScrollBothBinding) -> Self {
1772        self.scroll = Some(crate::scroll::ScrollBinding::Both(binding));
1773        self
1774    }
1775    pub fn scrollbar_style(mut self, style: crate::scroll::ScrollbarStyle) -> Self {
1776        self.scrollbar_style = Some(style);
1777        self
1778    }
1779    pub fn scrollbar_style_or_default(&self) -> crate::scroll::ScrollbarStyle {
1780        self.scrollbar_style.clone().unwrap_or_default()
1781    }
1782    /// Attach a nested scroll connection that descendant scrollable containers
1783    /// will discover during layout. Mirrors Compose's `Modifier.nestedScroll`.
1784    ///
1785    /// The connection receives pre/post scroll and pre/post fling callbacks
1786    /// when a scrollable child dispatches events, enabling coordinated scrolling
1787    /// patterns like collapsing toolbars and pull-to-refresh.
1788    pub fn nested_scroll(mut self, conn: crate::nested_scroll::NestedScrollConnection) -> Self {
1789        self.nested_scroll_connection = Some(conn);
1790        self
1791    }
1792    pub fn on_pointer_down(mut self, f: impl Fn(PointerEvent) + 'static) -> Self {
1793        self.on_pointer_down = Some(Rc::new(f));
1794        self
1795    }
1796    pub fn on_pointer_move(mut self, f: impl Fn(PointerEvent) + 'static) -> Self {
1797        self.on_pointer_move = Some(Rc::new(f));
1798        self
1799    }
1800    pub fn on_pointer_up(mut self, f: impl Fn(PointerEvent) + 'static) -> Self {
1801        self.on_pointer_up = Some(Rc::new(f));
1802        self
1803    }
1804    pub fn on_pointer_cancel(mut self, f: impl Fn(PointerEvent) + 'static) -> Self {
1805        self.on_pointer_cancel = Some(Rc::new(f));
1806        self
1807    }
1808
1809    pub fn draggable(self, on_drag: impl Fn(Vec2) + 'static) -> Self {
1810        self.draggable_with_end(on_drag, || {})
1811    }
1812
1813    /// Like [`draggable`](Self::draggable), but also reports when the gesture
1814    /// ends (pointer up or cancel) so the consumer can settle to a rest state.
1815    pub fn draggable_with_end(
1816        self,
1817        on_drag: impl Fn(Vec2) + 'static,
1818        on_drag_end: impl Fn() + 'static,
1819    ) -> Self {
1820        let drag_pos = crate::state::remember_mutable(Vec2::default);
1821        let is_dragging = crate::state::remember_mutable(|| false);
1822        let on_drag = Rc::new(on_drag);
1823        let on_drag_end = Rc::new(on_drag_end);
1824        self.on_pointer_down({
1825            let drag_pos = drag_pos.clone();
1826            let is_dragging = is_dragging.clone();
1827            move |ev| {
1828                is_dragging.set(true);
1829                drag_pos.set(ev.position);
1830            }
1831        })
1832        .on_pointer_up({
1833            let is_dragging = is_dragging.clone();
1834            let on_drag_end = on_drag_end.clone();
1835            move |_| {
1836                if *is_dragging.get() {
1837                    is_dragging.set(false);
1838                    on_drag_end();
1839                }
1840            }
1841        })
1842        .on_pointer_cancel({
1843            let is_dragging = is_dragging.clone();
1844            let on_drag_end = on_drag_end.clone();
1845            move |_| {
1846                if *is_dragging.get() {
1847                    is_dragging.set(false);
1848                    on_drag_end();
1849                }
1850            }
1851        })
1852        .on_pointer_move({
1853            let drag_pos = drag_pos.clone();
1854            let is_dragging = is_dragging.clone();
1855            let on_drag = on_drag.clone();
1856            move |ev| {
1857                if !*is_dragging.get() {
1858                    return;
1859                }
1860                let prev = *drag_pos.get();
1861                let cur = ev.position;
1862                let delta = Vec2 {
1863                    x: cur.x - prev.x,
1864                    y: cur.y - prev.y,
1865                };
1866                drag_pos.set(cur);
1867                on_drag(delta);
1868                crate::frame_clock::request_frame();
1869            }
1870        })
1871    }
1872    pub fn transformable(
1873        self,
1874        state: &crate::gesture::TransformableState,
1875        lock_rotation_on_zoom_pan: bool,
1876        enabled: bool,
1877    ) -> Self {
1878        state.set_lock_rotation_on_zoom_pan(lock_rotation_on_zoom_pan);
1879        state.set_enabled(enabled);
1880        let state = state.clone();
1881        self.on_action(move |action| match &action {
1882            crate::shortcuts::Action::Gesture(g) => state.handle_gesture(g),
1883            _ => false,
1884        })
1885    }
1886
1887    pub fn draggable_with_config(
1888        self,
1889        config: crate::gesture::DraggableConfig,
1890        on_drag_started: impl Fn() + 'static,
1891        on_drag: impl Fn(Vec2) + 'static,
1892        on_drag_stopped: impl Fn(f32) + 'static,
1893    ) -> Self {
1894        if !config.enabled {
1895            return self;
1896        }
1897        let drag_pos = crate::state::remember_mutable(Vec2::default);
1898        let press_pos = crate::state::remember_mutable(Vec2::default);
1899        let dragging = crate::state::remember_mutable(|| false);
1900        let last_time = crate::state::remember_mutable(|| None::<web_time::Instant>);
1901        let last_pos = crate::state::remember_mutable(|| None::<Vec2>);
1902        let velocity = crate::state::remember_mutable(|| 0.0f32);
1903        let on_drag = Rc::new(on_drag);
1904        let on_drag_started = Rc::new(on_drag_started);
1905        let on_drag_stopped = Rc::new(on_drag_stopped);
1906        let axis = config.orientation;
1907        let reverse = config.reverse_direction;
1908        let slop = config.slop_px;
1909        let immediate = config.start_drag_immediately;
1910        let filter = Rc::new(move |d: Vec2| -> Vec2 {
1911            let mut d = match axis {
1912                Some(DragOrientation::Horizontal) => Vec2 { x: d.x, y: 0.0 },
1913                Some(DragOrientation::Vertical) => Vec2 { x: 0.0, y: d.y },
1914                None => d,
1915            };
1916            if reverse {
1917                d = Vec2 { x: -d.x, y: -d.y };
1918            }
1919            d
1920        });
1921        self.on_pointer_down({
1922            let drag_pos = drag_pos.clone();
1923            let press_pos = press_pos.clone();
1924            let dragging = dragging.clone();
1925            let last_time = last_time.clone();
1926            let last_pos = last_pos.clone();
1927            let velocity = velocity.clone();
1928            move |ev| {
1929                press_pos.set(ev.position);
1930                drag_pos.set(ev.position);
1931                last_pos.set(Some(ev.position));
1932                last_time.set(Some(web_time::Instant::now()));
1933                velocity.set(0.0);
1934                if immediate {
1935                    dragging.set(true);
1936                }
1937            }
1938        })
1939        .on_pointer_move({
1940            let drag_pos = drag_pos.clone();
1941            let press_pos = press_pos.clone();
1942            let dragging = dragging.clone();
1943            let last_time = last_time.clone();
1944            let last_pos = last_pos.clone();
1945            let velocity = velocity.clone();
1946            let on_drag = on_drag.clone();
1947            let on_drag_started = on_drag_started.clone();
1948            let filter = filter.clone();
1949            move |ev| {
1950                if !*dragging.get() {
1951                    let dx = ev.position.x - press_pos.get().x;
1952                    let dy = ev.position.y - press_pos.get().y;
1953                    let dist = match axis {
1954                        Some(DragOrientation::Horizontal) => dx.abs(),
1955                        Some(DragOrientation::Vertical) => dy.abs(),
1956                        None => dx.hypot(dy),
1957                    };
1958                    if dist < slop {
1959                        return;
1960                    }
1961                    dragging.set(true);
1962                    on_drag_started();
1963                    drag_pos.set(ev.position);
1964                    last_pos.set(Some(ev.position));
1965                    last_time.set(Some(web_time::Instant::now()));
1966                    return;
1967                }
1968                let prev = *drag_pos.get();
1969                let delta = filter(Vec2 {
1970                    x: ev.position.x - prev.x,
1971                    y: ev.position.y - prev.y,
1972                });
1973                drag_pos.set(ev.position);
1974                if let (Some(lp), Some(lt)) = (*last_pos.get(), *last_time.get()) {
1975                    let now = web_time::Instant::now();
1976                    let dt = (now - lt).as_secs_f32().max(1.0 / 240.0);
1977                    let axis_delta = match axis {
1978                        Some(DragOrientation::Horizontal) => ev.position.x - lp.x,
1979                        Some(DragOrientation::Vertical) => ev.position.y - lp.y,
1980                        None => (ev.position.x - lp.x).hypot(ev.position.y - lp.y),
1981                    };
1982                    velocity.set(axis_delta / dt);
1983                    last_pos.set(Some(ev.position));
1984                    last_time.set(Some(now));
1985                }
1986                on_drag(delta);
1987                crate::frame_clock::request_frame();
1988            }
1989        })
1990        .on_pointer_up({
1991            let dragging = dragging.clone();
1992            let velocity = velocity.clone();
1993            let on_drag_stopped = on_drag_stopped.clone();
1994            move |_| {
1995                if *dragging.get() {
1996                    dragging.set(false);
1997                    on_drag_stopped(*velocity.get());
1998                }
1999            }
2000        })
2001        .on_pointer_cancel({
2002            let dragging = dragging.clone();
2003            let velocity = velocity.clone();
2004            let on_drag_stopped = on_drag_stopped.clone();
2005            move |_| {
2006                if *dragging.get() {
2007                    dragging.set(false);
2008                    on_drag_stopped(*velocity.get());
2009                }
2010            }
2011        })
2012    }
2013
2014    pub fn draggable_2d(
2015        self,
2016        on_drag_started: impl Fn() + 'static,
2017        on_drag: impl Fn(Vec2) + 'static,
2018        on_drag_stopped: impl Fn(f32) + 'static,
2019    ) -> Self {
2020        self.draggable_with_config(
2021            crate::gesture::DraggableConfig::default(),
2022            on_drag_started,
2023            on_drag,
2024            on_drag_stopped,
2025        )
2026    }
2027
2028    pub fn on_pointer_enter(mut self, f: impl Fn(PointerEvent) + 'static) -> Self {
2029        self.on_pointer_enter = Some(Rc::new(f));
2030        self
2031    }
2032    pub fn on_pointer_leave(mut self, f: impl Fn(PointerEvent) + 'static) -> Self {
2033        self.on_pointer_leave = Some(Rc::new(f));
2034        self
2035    }
2036    pub fn on_click(mut self, f: impl Fn() + 'static) -> Self {
2037        self.on_click = Some(Rc::new(f));
2038        self.click = true;
2039        if self.semantics.is_none() {
2040            self.semantics = Some(crate::Semantics::new(crate::Role::Button));
2041        }
2042        self
2043    }
2044    pub fn on_double_click(mut self, f: impl Fn() + 'static) -> Self {
2045        self.on_double_click = Some(Rc::new(f));
2046        self.click = true;
2047        self
2048    }
2049    pub fn on_long_click(mut self, f: impl Fn() + 'static) -> Self {
2050        self.on_long_click = Some(Rc::new(f));
2051        self.click = true;
2052        self
2053    }
2054    pub fn clickable_ext(
2055        mut self,
2056        enabled: bool,
2057        on_click_label: Option<String>,
2058        role: Option<crate::semantics::Role>,
2059        on_click: impl Fn() + 'static,
2060    ) -> Self {
2061        if !enabled {
2062            let mut s = self.semantics.clone().unwrap_or_else(|| {
2063                crate::semantics::Semantics::new(role.unwrap_or(crate::semantics::Role::Button))
2064            });
2065            s.enabled = false;
2066            if let Some(r) = role {
2067                s.role = r;
2068            }
2069            if let Some(l) = on_click_label {
2070                s.label = Some(l);
2071            }
2072            return self
2073                .clickable()
2074                .enabled(false)
2075                .default_min_size(Dp(48.0), Dp(48.0))
2076                .semantics(s);
2077        }
2078        self = self.clickable().on_click(on_click);
2079        if role.is_some() || on_click_label.is_some() {
2080            let mut s = self.semantics.clone().unwrap_or_else(|| {
2081                crate::semantics::Semantics::new(role.unwrap_or(crate::semantics::Role::Button))
2082            });
2083            s.enabled = true;
2084            if let Some(r) = role {
2085                s.role = r;
2086            }
2087            if let Some(l) = on_click_label {
2088                s.label = Some(l);
2089            }
2090            self = self.semantics(s);
2091        }
2092        self.default_min_size(Dp(48.0), Dp(48.0))
2093    }
2094    pub fn combined_clickable(
2095        mut self,
2096        enabled: bool,
2097        on_click_label: Option<String>,
2098        role: Option<crate::semantics::Role>,
2099        on_long_click_label: Option<String>,
2100        on_click: impl Fn() + 'static,
2101        on_long_click: Option<impl Fn() + 'static>,
2102        on_double_click: Option<impl Fn() + 'static>,
2103    ) -> Self {
2104        let _ = on_long_click_label;
2105        if !enabled {
2106            return self.clickable_ext(false, on_click_label, role, || {});
2107        }
2108        self = self.clickable_ext(true, on_click_label, role, on_click);
2109        if let Some(f) = on_long_click {
2110            self = self.on_long_click(f);
2111        }
2112        if let Some(f) = on_double_click {
2113            self = self.on_double_click(f);
2114        }
2115        self.default_min_size(Dp(48.0), Dp(48.0))
2116    }
2117    pub fn semantics(mut self, s: crate::Semantics) -> Self {
2118        self.semantics = Some(s);
2119        self
2120    }
2121    /// Set a stable, test-only identifier (Compose `Modifier.testTag`).
2122    pub fn test_tag(mut self, tag: impl Into<String>) -> Self {
2123        let mut s = self.semantics.take().unwrap_or_default();
2124        s.test_tag = Some(tag.into());
2125        self.semantics = Some(s);
2126        self
2127    }
2128    pub fn alpha(mut self, a: f32) -> Self {
2129        self.alpha = Some(a);
2130        self
2131    }
2132    /// Share one element's painted bounds across locations.
2133    pub fn shared_element(mut self, state: crate::shared::SharedElementState) -> Self {
2134        self.shared_element = Some(state);
2135        self
2136    }
2137    /// Attach a persistent [`ModifierNode`](crate::modifier_node::ModifierNode).
2138    ///
2139    /// The node survives recomposition while the element type and key stay the
2140    /// same; `update` runs instead of rebuilding it.
2141    pub fn node(
2142        mut self,
2143        element: impl crate::modifier_node::ModifierNodeElement + 'static,
2144    ) -> Self {
2145        self.nodes
2146            .push(crate::modifier_node::ModifierNodeHandle::new(
2147                std::rc::Rc::new(element),
2148            ));
2149        self
2150    }
2151    /// [`node`](Self::node) for an element that is already shared.
2152    pub fn node_shared(
2153        mut self,
2154        element: std::rc::Rc<dyn crate::modifier_node::ModifierNodeElement>,
2155    ) -> Self {
2156        self.nodes
2157            .push(crate::modifier_node::ModifierNodeHandle::new(element));
2158        self
2159    }
2160    /// Attach a pointer gesture handler such as
2161    /// [`TapGestures`](crate::pointer::TapGestures). Gesture state lives in the
2162    /// modifier node, so it survives recomposition.
2163    pub fn pointer_input(
2164        self,
2165        handler: impl crate::pointer::PointerInputHandler + 'static,
2166    ) -> Self {
2167        self.node_shared(crate::pointer::element(Box::new(handler)))
2168    }
2169    /// The gesture dispatcher carried by this modifier, if any.
2170    pub fn pointer_dispatch(&self) -> Option<crate::pointer::PointerInputDispatch> {
2171        crate::pointer::dispatch_from(&self.nodes)
2172    }
2173    /// Reuse nodes from a previous modifier where identity matches.
2174    ///
2175    /// Matching is by element identity, not position, so inserting a node at
2176    /// the front of a chain does not reset the state of every node behind it.
2177    #[doc(hidden)]
2178    pub fn adopt_nodes_from(&mut self, previous: &Modifier) {
2179        let mut taken = vec![false; previous.nodes.len()];
2180        for handle in &mut self.nodes {
2181            let matched = previous
2182                .nodes
2183                .iter()
2184                .enumerate()
2185                .position(|(index, candidate)| !taken[index] && handle.same_identity(candidate));
2186            if let Some(index) = matched {
2187                taken[index] = true;
2188                handle.adopt(&previous.nodes[index]);
2189            }
2190        }
2191    }
2192    /// Whether `other` has the same node identities in the same order.
2193    #[doc(hidden)]
2194    pub fn nodes_identity_matches(&self, other: &Modifier) -> bool {
2195        self.nodes.len() == other.nodes.len()
2196            && self
2197                .nodes
2198                .iter()
2199                .zip(&other.nodes)
2200                .all(|(a, b)| a.same_identity(b))
2201    }
2202    /// Mark every attached node as live. Called when a tree node paints.
2203    #[doc(hidden)]
2204    pub fn attach_nodes(&self) {
2205        for handle in &self.nodes {
2206            handle.ensure_attached();
2207        }
2208    }
2209    /// Render this subtree into an offscreen texture, then composite it
2210    /// back into the parent with the given group `alpha` (0.0..=1.0).
2211    /// Allows correct blending when children overlap inside the layer, and
2212    /// sets up the architecture for future layer effects (shadow, blur, clip).
2213    pub fn graphics_layer(mut self, alpha: f32) -> Self {
2214        self.graphics_layer = Some(alpha.clamp(0.0, 1.0));
2215        self
2216    }
2217    /// Configure a graphics layer with a closure that is evaluated on every
2218    /// paint. Mutating animation state read by the closure updates the layer
2219    /// without recomposing the view.
2220    pub fn graphics_layer_with(mut self, block: impl Fn() -> GraphicsLayerScope + 'static) -> Self {
2221        self.graphics_layer_scope = Some(Rc::new(block));
2222        self
2223    }
2224    /// Configure a graphics layer with a fixed [`GraphicsLayerScope`].
2225    pub fn graphics_layer_scope(mut self, scope: GraphicsLayerScope) -> Self {
2226        self.graphics_layer_scope = Some(Rc::new(move || scope.clone()));
2227        self
2228    }
2229    /// Drop shadow with the given `blur_radius` ([`Dp`]) and vertical `offset_y` ([`Dp`]).
2230    /// The shadow color defaults to black with alpha 64 (~25%). Combines with
2231    /// [`Modifier::graphics_layer`] to draw a shadow underneath the layer.
2232    pub fn shadow(mut self, blur_radius: Dp, offset_y: Dp) -> Self {
2233        self.shadow = Some(ShadowSpec {
2234            blur_radius: Dp(blur_radius.0.max(0.0)),
2235            offset_x: Dp::ZERO,
2236            offset_y,
2237            color: Color(0, 0, 0, 64),
2238            spread: Dp::ZERO,
2239            inset: false,
2240        });
2241        self
2242    }
2243    /// Drop shadow with a custom color. Alpha 0..=255.
2244    pub fn shadow_with_color(mut self, blur_radius: Dp, offset_y: Dp, color: Color) -> Self {
2245        self.shadow = Some(ShadowSpec {
2246            blur_radius: Dp(blur_radius.0.max(0.0)),
2247            offset_x: Dp::ZERO,
2248            offset_y,
2249            color,
2250            spread: Dp::ZERO,
2251            inset: false,
2252        });
2253        self
2254    }
2255    /// Full Compose-style shadow: `(offset_x, offset_y)` translate the
2256    /// silhouette, `blur` is the Gaussian radius, `spread` grows it, and
2257    /// `inset` draws the shadow inside the shape.
2258    pub fn drop_shadow(
2259        mut self,
2260        offset_x: Dp,
2261        offset_y: Dp,
2262        blur: Dp,
2263        spread: Dp,
2264        color: Color,
2265        inset: bool,
2266    ) -> Self {
2267        self.shadow = Some(ShadowSpec {
2268            blur_radius: Dp(blur.0.max(0.0)),
2269            offset_x,
2270            offset_y,
2271            color,
2272            spread,
2273            inset,
2274        });
2275        self
2276    }
2277    /// Shadow drawn inside the silhouette. See [`drop_shadow`](Self::drop_shadow).
2278    pub fn inner_shadow(
2279        self,
2280        offset_x: Dp,
2281        offset_y: Dp,
2282        blur: Dp,
2283        spread: Dp,
2284        color: Color,
2285    ) -> Self {
2286        self.drop_shadow(offset_x, offset_y, blur, spread, color, true)
2287    }
2288    /// Material-style elevation. Auto-scales blur and offset by `level` ([`Dp`])
2289    /// and uses a default shadow color. Level 0 = no shadow. 4 = subtle;
2290    /// 16 = strong. Requires [`Modifier::graphics_layer`] to take effect.
2291    pub fn elevation(mut self, level: Dp) -> Self {
2292        if level.0 <= 0.0 {
2293            self.shadow = None;
2294            return self;
2295        }
2296        self.shadow = Some(ShadowSpec {
2297            blur_radius: Dp(level.0 * 2.0),
2298            offset_x: Dp::ZERO,
2299            offset_y: Dp(level.0 * 0.5),
2300            color: Color(0, 0, 0, (level.0 * 8.0).clamp(8.0, 80.0) as u8),
2301            spread: Dp::ZERO,
2302            inset: false,
2303        });
2304        self
2305    }
2306    /// [`Modifier::elevation`] with an explicit shadow color, mirroring Compose's
2307    /// `Modifier.shadow(elevation, ambientColor, spotColor)`. Alpha 0..=255.
2308    pub fn elevation_with_color(mut self, level: Dp, color: Color) -> Self {
2309        if level.0 <= 0.0 {
2310            self.shadow = None;
2311            return self;
2312        }
2313        self.shadow = Some(ShadowSpec {
2314            blur_radius: Dp(level.0 * 2.0),
2315            offset_x: Dp::ZERO,
2316            offset_y: Dp(level.0 * 0.5),
2317            color,
2318            spread: Dp::ZERO,
2319            inset: false,
2320        });
2321        self
2322    }
2323    /// Shape the shadow to a uniform corner radius, independent of the layer's
2324    /// own alpha. Mirrors Compose's `Modifier.shadow(shape = RoundedCornerShape)`,
2325    /// so unclipped square content still casts a rounded shadow. Requires a
2326    /// [`Modifier::shadow`] or [`Modifier::elevation`] to take effect.
2327    pub fn shadow_rounded(mut self, radius: Dp) -> Self {
2328        self.shadow_shape = Some([radius; 4]);
2329        self
2330    }
2331    /// Per-corner radii for the shadow silhouette, like
2332    /// [`Modifier::clip_rounded_radii`].
2333    pub fn shadow_rounded_radii(mut self, radii: [Dp; 4]) -> Self {
2334        self.shadow_shape = Some(radii);
2335        self
2336    }
2337    pub fn transform(mut self, t: Transform) -> Self {
2338        self.transform = Some(t);
2339        self
2340    }
2341    pub fn grid(mut self, columns: usize, row_gap: Dp, column_gap: Dp) -> Self {
2342        self.grid = Some(GridConfig {
2343            columns,
2344            row_gap,
2345            column_gap,
2346        });
2347        self
2348    }
2349    pub fn grid_span(mut self, col_span: u16, row_span: u16) -> Self {
2350        self.grid_col_span = Some(col_span);
2351        self.grid_row_span = Some(row_span);
2352        self
2353    }
2354    /// Take this node out of flow: siblings lay out as if it were absent
2355    /// and this node is positioned by [`offset`](Self::offset) instead.
2356    ///
2357    /// Load-bearing for hand-placed overlays: without it taffy ignores the
2358    /// offsets and every absolutely-placed sibling stacks at the same
2359    /// in-flow spot. Pair with `.size(...)` + `.inset(Some(x), Some(y),
2360    /// None, None)` to pin a box at an exact point (e.g. world-anchored
2361    /// actor surfaces over a viewport).
2362    pub fn absolute(mut self) -> Self {
2363        self.position_type = Some(PositionType::Absolute);
2364        self
2365    }
2366    /// In-flow edge offsets are ignored unless paired with
2367    /// [`absolute`](Self::absolute): taffy only applies these to
2368    /// out-of-flow nodes. Each side is independent; `None` leaves that
2369    /// edge to default flow placement. This is the CSS-style edge inset API.
2370    pub fn inset(
2371        mut self,
2372        left: Option<Dp>,
2373        top: Option<Dp>,
2374        right: Option<Dp>,
2375        bottom: Option<Dp>,
2376    ) -> Self {
2377        self.offset_left = left;
2378        self.offset_top = top;
2379        self.offset_right = right;
2380        self.offset_bottom = bottom;
2381        self
2382    }
2383    /// Translate the node by `(x, y)` after layout. Setting this field
2384    /// does not take the node out of flow; use [`absolute`](Self::absolute)
2385    /// for that. The horizontal offset is mirrored under RTL layouts.
2386    pub fn offset(mut self, x: Dp, y: Dp) -> Self {
2387        self.layout_offset = Some((x, y));
2388        self
2389    }
2390    /// Translate the node by `(x, y)` after layout without RTL mirroring.
2391    pub fn absolute_offset(mut self, x: Dp, y: Dp) -> Self {
2392        self.absolute_layout_offset = Some((x, y));
2393        self
2394    }
2395    pub fn offset_left(mut self, v: Dp) -> Self {
2396        self.offset_left = Some(v);
2397        self
2398    }
2399    pub fn offset_right(mut self, v: Dp) -> Self {
2400        self.offset_right = Some(v);
2401        self
2402    }
2403    pub fn offset_top(mut self, v: Dp) -> Self {
2404        self.offset_top = Some(v);
2405        self
2406    }
2407    pub fn offset_bottom(mut self, v: Dp) -> Self {
2408        self.offset_bottom = Some(v);
2409        self
2410    }
2411    pub fn margin(mut self, v: Dp) -> Self {
2412        self.margin_left = Some(v);
2413        self.margin_right = Some(v);
2414        self.margin_top = Some(v);
2415        self.margin_bottom = Some(v);
2416        self
2417    }
2418
2419    pub fn margin_horizontal(mut self, v: Dp) -> Self {
2420        self.margin_left = Some(v);
2421        self.margin_right = Some(v);
2422        self
2423    }
2424
2425    pub fn margin_vertical(mut self, v: Dp) -> Self {
2426        self.margin_top = Some(v);
2427        self.margin_bottom = Some(v);
2428        self
2429    }
2430    pub fn aspect_ratio(mut self, ratio: f32) -> Self {
2431        self.aspect_ratio = Some(ratio);
2432        self
2433    }
2434    /// `fit-content(limit)` width: shrink-wrap content, clamped to `limit` [`Dp`].
2435    pub fn fit_content_width(mut self, limit: Dp) -> Self {
2436        self.fit_content_width = Some(Dp(limit.0.max(0.0)));
2437        self
2438    }
2439    /// `fit-content(limit)` height: shrink-wrap content, clamped to `limit` [`Dp`].
2440    pub fn fit_content_height(mut self, limit: Dp) -> Self {
2441        self.fit_content_height = Some(Dp(limit.0.max(0.0)));
2442        self
2443    }
2444    /// CSS containment. See [`contain`](Self::contain).
2445    pub fn contain(mut self, c: Contain) -> Self {
2446        self.contain = Some(c);
2447        self
2448    }
2449    /// `contain: layout` - independent formatting context, no baseline.
2450    pub fn contain_layout(mut self) -> Self {
2451        self.contain = Some(Contain::LAYOUT);
2452        self
2453    }
2454    /// `contain: paint` - independent formatting context.
2455    pub fn contain_paint(mut self) -> Self {
2456        self.contain = Some(Contain::PAINT);
2457        self
2458    }
2459    /// `contain: content` (`layout` + `paint`).
2460    pub fn contain_content(mut self) -> Self {
2461        self.contain = Some(Contain::CONTENT);
2462        self
2463    }
2464    /// Size this node's width to its min or max intrinsic content size.
2465    pub fn intrinsic_width(mut self, mode: IntrinsicSize) -> Self {
2466        self.intrinsic_width = Some(mode);
2467        self
2468    }
2469    /// Size this node's height to its min or max intrinsic content size.
2470    pub fn intrinsic_height(mut self, mode: IntrinsicSize) -> Self {
2471        self.intrinsic_height = Some(mode);
2472        self
2473    }
2474    pub fn painter(mut self, f: impl Fn(&mut crate::Scene, crate::Rect, f32) + 'static) -> Self {
2475        self.painter = Some(Rc::new(f));
2476        self
2477    }
2478    /// Paint the given callback behind the node's own content.
2479    pub fn draw_behind(
2480        mut self,
2481        painter: impl Fn(&mut crate::Scene, crate::Rect, f32) + 'static,
2482    ) -> Self {
2483        self.painter = Some(Rc::new(painter));
2484        self.paint_order = -1;
2485        self
2486    }
2487    /// Paint the given callback on top of the node's own content.
2488    pub fn draw_with_content(
2489        mut self,
2490        painter: impl Fn(&mut crate::Scene, crate::Rect, f32) + 'static,
2491    ) -> Self {
2492        self.painter = Some(Rc::new(painter));
2493        self.paint_order = 1;
2494        self
2495    }
2496    /// Attach a custom GPU callback (like `egui::PaintCallback`). The payload
2497    /// is type-erased (`Arc<dyn Any>`) so the core crate stays backend-agnostic.
2498    /// Prefer `repose_render_wgpu::Callback::new` + `repose_ui::Embedded` or
2499    /// `repose_render_wgpu::Callback::embedded_view` over calling this directly.
2500    /// `rect` for the callback comes from layout (`SceneNode::Callback.rect`).
2501    pub fn paint_callback(mut self, payload: crate::PaintCallbackPayload) -> Self {
2502        self.paint_callback = Some(payload);
2503        self
2504    }
2505    pub fn scale(self, s: f32) -> Self {
2506        self.scale2(s, s)
2507    }
2508    pub fn scale2(mut self, sx: f32, sy: f32) -> Self {
2509        let mut t = self.transform.unwrap_or_else(Transform::identity);
2510        t.scale_x *= sx;
2511        t.scale_y *= sy;
2512        self.transform = Some(t);
2513        self
2514    }
2515    pub fn translate(mut self, x: f32, y: f32) -> Self {
2516        let t = self.transform.unwrap_or_else(Transform::identity);
2517        self.transform = Some(t.combine(&Transform::translate(x, y)));
2518        self
2519    }
2520    pub fn translate_vec2(self, v: Vec2) -> Self {
2521        self.translate(v.x, v.y)
2522    }
2523    pub fn rotate(mut self, radians: f32) -> Self {
2524        let mut t = self.transform.unwrap_or_else(Transform::identity);
2525        t.rotate += radians;
2526        self.transform = Some(t);
2527        self
2528    }
2529    pub fn transform_origin(mut self, x: f32, y: f32) -> Self {
2530        let mut t = self.transform.unwrap_or_else(Transform::identity);
2531        t.origin_x = x;
2532        t.origin_y = y;
2533        self.transform = Some(t);
2534        self
2535    }
2536    pub fn weight(mut self, w: f32) -> Self {
2537        let w = w.max(0.0);
2538        self.flex_grow = Some(w);
2539        self.flex_shrink = Some(1.0);
2540        self.flex_basis = Some(Dp::ZERO);
2541        self.flex_basis_content = false;
2542        // Zero the automatic min size so the item may shrink below its content
2543        // width (the flexbox `min-width: auto` trap). Callers that need a floor
2544        // must set it *after* `weight`.
2545        self.min_width = Some(Dp::ZERO);
2546        self.min_height = Some(Dp::ZERO);
2547        self
2548    }
2549    /// Marks this view as a repaint boundary candidate.
2550    ///
2551    /// The engine may cache its painted output.
2552    pub fn repaint_boundary(mut self) -> Self {
2553        self.repaint_boundary = true;
2554        self
2555    }
2556    pub fn on_action(mut self, f: impl Fn(crate::shortcuts::Action) -> bool + 'static) -> Self {
2557        self.on_action = Some(Rc::new(f));
2558        self
2559    }
2560    pub fn on_set_progress(mut self, f: impl Fn(f32) + 'static) -> Self {
2561        self.on_set_progress = Some(Rc::new(f));
2562        self
2563    }
2564    pub fn on_expand(mut self, f: impl Fn() + 'static) -> Self {
2565        self.on_expand = Some(Rc::new(f));
2566        self
2567    }
2568    pub fn on_collapse(mut self, f: impl Fn() + 'static) -> Self {
2569        self.on_collapse = Some(Rc::new(f));
2570        self
2571    }
2572    pub fn on_dismiss(mut self, f: impl Fn() + 'static) -> Self {
2573        self.on_dismiss = Some(Rc::new(f));
2574        self
2575    }
2576    fn with_semantics_mut(mut self, f: impl FnOnce(&mut crate::Semantics)) -> Self {
2577        let mut s = self.semantics.take().unwrap_or_default();
2578        f(&mut s);
2579        self.semantics = Some(s);
2580        self
2581    }
2582    pub fn heading(self) -> Self {
2583        self.with_semantics_mut(|s| s.heading = true)
2584    }
2585    pub fn live_region(self, region: crate::LiveRegion) -> Self {
2586        self.with_semantics_mut(|s| s.live_region = Some(region))
2587    }
2588    pub fn state_description(self, description: impl Into<String>) -> Self {
2589        self.with_semantics_mut(|s| s.state_description = Some(description.into()))
2590    }
2591    pub fn traversal_index(self, index: f32) -> Self {
2592        self.with_semantics_mut(|s| s.traversal_index = Some(index))
2593    }
2594    pub fn traversal_group(self) -> Self {
2595        self.with_semantics_mut(|s| s.is_traversal_group = true)
2596    }
2597    pub fn hidden_from_accessibility(self) -> Self {
2598        self.with_semantics_mut(|s| s.hidden = true)
2599    }
2600    pub fn collection_info(self, rows: usize, columns: usize) -> Self {
2601        self.with_semantics_mut(|s| {
2602            s.collection_rows = Some(rows);
2603            s.collection_columns = Some(columns);
2604        })
2605    }
2606    pub fn collection_item(self, row: usize, column: usize) -> Self {
2607        self.with_semantics_mut(|s| {
2608            s.row_index = Some(row);
2609            s.column_index = Some(column);
2610        })
2611    }
2612    pub fn progress_range(self, info: crate::ProgressRangeInfo) -> Self {
2613        self.with_semantics_mut(|s| s.progress = Some(info))
2614    }
2615    pub fn semantics_error(self, message: impl Into<String>) -> Self {
2616        self.with_semantics_mut(|s| s.error = Some(message.into()))
2617    }
2618    pub fn expandable(self, expanded: bool) -> Self {
2619        self.with_semantics_mut(|s| s.expanded = Some(expanded))
2620    }
2621
2622    /// Mark this node as a drag source. Return `Some(payload)` to start dragging.
2623    pub fn on_drag_start(
2624        mut self,
2625        f: impl Fn(crate::dnd::DragStart) -> Option<crate::dnd::DragPayload> + 'static,
2626    ) -> Self {
2627        self.on_drag_start = Some(Rc::new(f));
2628        self
2629    }
2630
2631    /// Called when a drag ends (drop accepted or canceled/ignored).
2632    pub fn on_drag_end(mut self, f: impl Fn(crate::dnd::DragEnd) + 'static) -> Self {
2633        self.on_drag_end = Some(Rc::new(f));
2634        self
2635    }
2636
2637    /// Called when a drag first enters this target.
2638    pub fn on_drag_enter(mut self, f: impl Fn(crate::dnd::DragOver) + 'static) -> Self {
2639        self.on_drag_enter = Some(Rc::new(f));
2640        self
2641    }
2642
2643    /// Called on every pointer move while a drag is over this target.
2644    pub fn on_drag_over(mut self, f: impl Fn(crate::dnd::DragOver) + 'static) -> Self {
2645        self.on_drag_over = Some(Rc::new(f));
2646        self
2647    }
2648
2649    /// Called when a drag leaves this target.
2650    pub fn on_drag_leave(mut self, f: impl Fn(crate::dnd::DragOver) + 'static) -> Self {
2651        self.on_drag_leave = Some(Rc::new(f));
2652        self
2653    }
2654
2655    /// Called on pointer release while a drag is over this target.
2656    /// Return `true` to accept the drop.
2657    pub fn on_drop(mut self, f: impl Fn(crate::dnd::DropEvent) -> bool + 'static) -> Self {
2658        self.on_drop = Some(Rc::new(f));
2659        self
2660    }
2661
2662    /// Custom drag preview decoration (Compose `drawDragDecoration`).
2663    ///
2664    /// Called every frame while this node is the active drag source.
2665    /// Coordinates are screen px; see [`crate::dnd::DragPreviewCtx`].
2666    pub fn draw_drag_decoration(
2667        mut self,
2668        f: impl Fn(&mut crate::Scene, &crate::dnd::DragPreviewCtx) + 'static,
2669    ) -> Self {
2670        self.drag_preview = Some(Rc::new(f));
2671        self
2672    }
2673
2674    /// Same as [`Self::draw_drag_decoration`] but takes an existing [`crate::dnd::DragPreview`] Rc.
2675    pub fn draw_drag_decoration_rc(mut self, preview: crate::dnd::DragPreview) -> Self {
2676        self.drag_preview = Some(preview);
2677        self
2678    }
2679
2680    /// Convenience: floating label chip as the drag preview.
2681    pub fn drag_preview_label(self, label: impl Into<String>, accent: crate::Color) -> Self {
2682        self.draw_drag_decoration_rc(crate::dnd::drag_preview_label(label, accent))
2683    }
2684
2685    /// Convenience: elevated chip preview.
2686    pub fn drag_preview_chip(self, label: impl Into<String>, accent: crate::Color) -> Self {
2687        self.draw_drag_decoration_rc(crate::dnd::drag_preview_chip(label, accent))
2688    }
2689
2690    /// Set the cursor icon hint for desktop/web runners.
2691    pub fn cursor(mut self, c: crate::CursorIcon) -> Self {
2692        self.cursor = Some(c);
2693        self
2694    }
2695
2696    /// Animate size changes smoothly when the content's natural size changes.
2697    /// Uses the provided `AnimationSpec` for the transition.
2698    /// The content will be clipped to the animated size during transitions.
2699    pub fn animate_content_size(mut self, spec: AnimationSpec) -> Self {
2700        self.animate_content_size = Some(spec);
2701        self
2702    }
2703
2704    /// Attach a `FocusRequester` to this view. The requester will be associated
2705    /// with the view's focusable element, allowing programmatic focus requests.
2706    pub fn focus_requester(mut self, fr: crate::runtime::FocusRequester) -> Self {
2707        self.focus_requester = Some(fr);
2708        self
2709    }
2710
2711    /// Scroll ancestor containers to reveal this view when requested.
2712    pub fn bring_into_view(mut self, r: crate::runtime::BringIntoViewRequester) -> Self {
2713        self.bring_into_view = Some(r);
2714        self
2715    }
2716
2717    /// Called when this view's bounds change (Compose `onFocusedBoundsChanged`).
2718    pub fn on_focused_bounds_changed(mut self, f: impl Fn(crate::Rect) + 'static) -> Self {
2719        self.on_focused_bounds_changed = Some(Rc::new(f));
2720        self
2721    }
2722
2723    /// Make this composable a focus target (`.focusable(true)`).
2724    /// Corresponds to Compose's `Modifier.focusTarget()`.
2725    pub fn focus_target(mut self) -> Self {
2726        self.focusable = Some(true);
2727        self
2728    }
2729
2730    /// Register a callback that fires when this view gains or loses keyboard focus.
2731    /// The argument is `true` when the view receives focus, `false` when it loses it.
2732    pub fn on_focus_changed(mut self, f: impl Fn(bool) + 'static) -> Self {
2733        self.on_focus_changed = Some(Rc::new(f));
2734        self
2735    }
2736
2737    /// Called after layout when this element's position changes.
2738    /// The callback receives the element's rect with [`Dp`] magnitudes
2739    /// (device-independent pixels).
2740    /// Fires whenever the rect changes, including on the initial layout.
2741    pub fn on_globally_positioned(mut self, f: impl Fn(crate::Rect) + 'static) -> Self {
2742        self.on_globally_positioned = Some(Rc::new(f));
2743        self
2744    }
2745
2746    /// Called after layout when this element's size changes.
2747    /// Provides the new (width, height) with [`Dp`] magnitudes.
2748    pub fn on_size_changed(mut self, f: impl Fn(crate::Vec2) + 'static) -> Self {
2749        self.on_size_changed = Some(Rc::new(f));
2750        self
2751    }
2752
2753    /// Called when a key event is received while this element is focused.
2754    /// Return `true` to indicate the event was consumed and should not
2755    /// propagate further (e.g. to text input handling or shortcut dispatch).
2756    pub fn on_key_event(mut self, f: impl Fn(crate::input::KeyEvent) -> bool + 'static) -> Self {
2757        self.on_key_event = Some(Rc::new(f));
2758        self
2759    }
2760
2761    /// Called when an IME event is received while this element is focused.
2762    /// Return `true` to indicate the event was consumed.
2763    pub fn on_ime(mut self, f: impl Fn(crate::input::ImeEvent) -> bool + 'static) -> Self {
2764        self.on_ime = Some(Rc::new(f));
2765        self
2766    }
2767
2768    /// Preview variant of `on_key_event`. Called before `on_key_event`;
2769    /// if the preview handler returns `true`, the event is consumed
2770    /// and `on_key_event` is NOT called.
2771    pub fn on_preview_key_event(
2772        mut self,
2773        f: impl Fn(crate::input::KeyEvent) -> bool + 'static,
2774    ) -> Self {
2775        self.on_preview_key_event = Some(Rc::new(f));
2776        self
2777    }
2778
2779    /// Apply a gaussian blur to this element's rendered content.
2780    /// `radius` is the uniform blur radius in [`Dp`].
2781    /// Larger values produce a stronger blur.
2782    /// Uses `Rectangle` edge treatment (clip to bounds).
2783    ///
2784    /// Requires `graphics_layer` to be enabled (set automatically if not).
2785    pub fn blur(mut self, radius: Dp) -> Self {
2786        self.blur = Some(BlurStyle {
2787            radius_x: Dp(radius.0.max(0.0)),
2788            radius_y: Dp(radius.0.max(0.0)),
2789            edge_treatment: BlurredEdgeTreatment::Rectangle,
2790        });
2791        self
2792    }
2793
2794    /// Apply a gaussian blur with separate horizontal/vertical radii ([`Dp`]).
2795    /// `edge_treatment` controls how edge pixels are handled.
2796    ///
2797    /// Requires `graphics_layer` to be enabled (set automatically if not).
2798    pub fn blur_with_edge(
2799        mut self,
2800        radius_x: Dp,
2801        radius_y: Dp,
2802        edge_treatment: BlurredEdgeTreatment,
2803    ) -> Self {
2804        self.blur = Some(BlurStyle {
2805            radius_x: Dp(radius_x.0.max(0.0)),
2806            radius_y: Dp(radius_y.0.max(0.0)),
2807            edge_treatment,
2808        });
2809        self
2810    }
2811
2812    /// Override this element's measured size with a custom callback.
2813    /// The callback receives `LayoutConstraints` (min/max width/height in [`Dp`]),
2814    /// where `max_width`/`max_height` may be `Dp::INFINITY` if unbounded.
2815    /// Returns `(width, height)` for this element, in [`Dp`].
2816    ///
2817    /// Child placement is handled by the parent layout (same as Compose's
2818    /// `Modifier.size` family).
2819    pub fn layout(mut self, f: impl Fn(LayoutConstraints) -> (Dp, Dp) + 'static) -> Self {
2820        self.layout = Some(Rc::new(f));
2821        self
2822    }
2823
2824    /// Mark this Box as a text input field with the given configuration.
2825    pub fn text_input(mut self, config: TextInputConfig) -> Self {
2826        self.text_input = Some(config);
2827        self
2828    }
2829
2830    /// Attach a text selection to this `Text` node. The layout engine paints the
2831    /// highlight behind the glyphs, using this node's real text layout.
2832    pub fn text_selection(mut self, selection: crate::text::TextSelection) -> Self {
2833        self.text_selection = Some(selection);
2834        self
2835    }
2836
2837    /// Attach an indication (ripple/highlight) factory for visual feedback.
2838    /// The factory is paired with an `InteractionSource` (via `.interaction_source(...)`)
2839    /// to draw press/hover/focus visual feedback.
2840    pub fn indication(mut self, factory: Rc<dyn IndicationNodeFactory>) -> Self {
2841        self.indication = Some(factory);
2842        self
2843    }
2844}