1use std::{fmt, rc::Rc};
9
10use cranpose_core::ProvidedValue;
11use smallvec::SmallVec;
12
13mod alignment;
14mod background;
15mod blur;
16mod border;
17mod chain;
18mod clickable;
19mod coordinator_rect;
20mod drag_and_drop;
21mod draw_cache;
22mod element_match;
23mod fill;
24pub(crate) mod focus;
25mod focus_ring;
26mod graphics_layer;
27mod key_input;
28mod layout_data;
29mod local;
30mod long_press;
31mod minimum_interactive;
32mod offset;
33mod padding;
34mod pointer_icon;
35pub(crate) mod pointer_input;
36mod pointer_opaque;
37mod resolved_modifiers;
38mod rotary_input;
39mod scroll;
40mod selectable;
41mod semantics;
42mod shadow;
43mod size;
44mod slices;
45mod toggleable;
46mod weight;
47mod window_root;
48mod wrap_content;
49mod z_index;
50
51pub(crate) use chain::{
52 InPlaceReach, InPlaceUpdate, ModifierChainHandle, ModifierChainInspectorNode,
53 ModifierLocalsHandle, SharedParentData,
54};
55pub(crate) use coordinator_rect::CoordinatorRect;
56use cranpose_foundation::{
57 DynModifierElement, ModifierNodeElement, ProgressBarRangeInfo, SemanticsConfiguration,
58 modifier_element, plain_element,
59};
60pub use cranpose_foundation::{
61 PointerButton, PointerButtons, PointerEvent, PointerEventKind, PointerSource, RotaryScrollEvent,
62};
63pub use cranpose_ui_graphics::{
64 BlendMode, Brush, Color, CompositingStrategy, CornerRadii, DpOffset, EdgeInsets, GraphicsLayer,
65 LayerShape, Point, Rect, RenderEffect, RoundedCornerShape, RuntimeShader, Shadow, ShadowScope,
66 Size, TransformOrigin,
67};
68use cranpose_ui_layout::{Alignment, HorizontalAlignment, VerticalAlignment};
69pub use drag_and_drop::{
70 DragAndDropEvent, DragAndDropOutcome, DragAndDropPayload, DragAndDropPoint, DragAndDropSource,
71 DragAndDropSourceElement, DragAndDropSourceNode, DragAndDropState, DragAndDropTarget,
72 DragAndDropTargetElement, DragAndDropTargetNode,
73};
74pub(crate) use element_match::ElementMatch;
75#[cfg(test)]
76pub(crate) use focus::FocusRequesterElement;
77pub use focus::{FocusDirection, FocusRequestError, FocusRequester};
78pub use graphics_layer::GlassMaterial;
79pub use key_input::KeyEventRoute;
80pub(crate) use local::{
81 ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
82};
83use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
84pub use local::{ModifierLocalKey, ModifierLocalReadScope};
85pub use pointer_input::PointerInputScope;
86pub(crate) use resolved_modifiers::{DimensionConstraint, LayoutProperties, LayoutWeight};
87pub use resolved_modifiers::{ResolvedBackground, ResolvedModifiers};
88pub use rotary_input::RotaryInputModifierNode;
89#[cfg(feature = "test-helpers")]
90pub use scroll::{last_fling_velocity, reset_last_fling_velocity};
91use semantics::SemanticsElement;
92pub use semantics::{SemanticsRequester, collect_semantics_from_modifier};
93pub(crate) use semantics::{
94 SemanticsRequesterElement, collect_semantics_from_chain, semantics_reach_of_chain,
95};
96pub(crate) use slices::SlicesSnapshot;
97pub use slices::{
98 ModifierNodeSlices, ModifierNodeSlicesDebugStats, SliceTextRef, collect_modifier_slices,
99 collect_slices_from_modifier,
100};
101pub use window_root::{
102 WindowRootDescriptor, WindowRootElement, WindowRootEntry, WindowRootNode, WindowRootRegistry,
103 WindowRootRoutingScratch, is_window_root, nearest_window_root, nearest_window_roots,
104 nearest_window_roots_into, window_roots, window_roots_revision,
105};
106pub use z_index::{z_index_in_use, z_index_modifier_in_use};
107
108pub(crate) use crate::draw::{DrawCacheBuilder, DrawCommand};
109use crate::modifier_nodes::ClipToBoundsElement;
110
111#[derive(Clone, Debug, Default)]
112pub(crate) struct InspectorInfo {
113 properties: Vec<InspectorProperty>,
114}
115
116impl InspectorInfo {
117 pub(crate) fn new() -> Self {
118 Self::default()
119 }
120
121 pub(crate) fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
122 self.properties.push(InspectorProperty {
123 name,
124 value: value.into(),
125 });
126 }
127
128 pub(crate) fn properties(&self) -> &[InspectorProperty] {
129 &self.properties
130 }
131
132 pub(crate) fn is_empty(&self) -> bool {
133 self.properties.is_empty()
134 }
135
136 pub(crate) fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
137 self.add_property(name, describe_dimension(constraint));
138 }
139
140 pub(crate) fn add_offset_components(
141 &mut self,
142 x_name: &'static str,
143 y_name: &'static str,
144 offset: Point,
145 ) {
146 self.add_property(x_name, offset.x.to_string());
147 self.add_property(y_name, offset.y.to_string());
148 }
149
150 pub(crate) fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
151 where
152 A: fmt::Debug,
153 {
154 self.add_property(name, format!("{alignment:?}"));
155 }
156}
157
158#[derive(Clone, Debug, PartialEq)]
159pub struct InspectorProperty {
160 pub name: &'static str,
161 pub value: String,
162}
163
164#[derive(Clone, Debug, PartialEq)]
165pub struct ModifierInspectorRecord {
166 pub name: &'static str,
167 pub properties: Vec<InspectorProperty>,
168}
169
170#[derive(Clone, Debug)]
171pub(crate) struct InspectorMetadata {
172 name: &'static str,
173 info: InspectorInfo,
174}
175
176impl InspectorMetadata {
177 pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
178 where
179 F: FnOnce(&mut InspectorInfo),
180 {
181 let mut info = InspectorInfo::new();
182 recorder(&mut info);
183 Self { name, info }
184 }
185
186 fn is_empty(&self) -> bool {
187 self.info.is_empty()
188 }
189
190 fn to_record(&self) -> ModifierInspectorRecord {
191 ModifierInspectorRecord {
192 name: self.name,
193 properties: self.info.properties().to_vec(),
194 }
195 }
196}
197
198fn describe_dimension(constraint: DimensionConstraint) -> String {
199 match constraint {
200 DimensionConstraint::Unspecified => "unspecified".to_string(),
201 DimensionConstraint::Points(value) => value.to_string(),
202 DimensionConstraint::Fraction(value) => format!("fraction({value})"),
203 DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
204 }
205}
206
207fn inspector_slice(inspector: &Option<Rc<Vec<InspectorMetadata>>>) -> &[InspectorMetadata] {
208 inspector.as_deref().map_or(&[], Vec::as_slice)
209}
210
211fn merged_inspector(
214 first: &[InspectorMetadata],
215 second: &[InspectorMetadata],
216) -> Option<Rc<Vec<InspectorMetadata>>> {
217 if first.is_empty() && second.is_empty() {
218 return None;
219 }
220 Some(Rc::new(first.iter().chain(second).cloned().collect()))
221}
222
223pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
224where
225 F: FnOnce(&mut InspectorInfo),
226{
227 if !inspector_metadata_enabled() {
228 return InspectorMetadata::new(name, |_| {});
229 }
230 InspectorMetadata::new(name, recorder)
231}
232
233pub(crate) fn modifier_debug_enabled() -> bool {
234 #[cfg(not(target_arch = "wasm32"))]
235 {
236 cranpose_core::DIAGNOSTICS.compose_debug_modifiers.is_set()
237 }
238 #[cfg(target_arch = "wasm32")]
239 {
240 false
241 }
242}
243
244fn inspector_metadata_enabled() -> bool {
245 cfg!(any(test, feature = "inspection")) || modifier_debug_enabled()
246}
247
248type ModifierElements = SmallVec<[DynModifierElement; 4]>;
251
252#[derive(Clone)]
257enum Elements {
258 One(DynModifierElement),
259 Many(Rc<ModifierElements>),
260}
261
262impl Elements {
263 fn joined(self, more: Self) -> Self {
266 let mut chain = match self {
267 Self::One(first) => {
268 let mut chain = ModifierElements::new();
269 chain.push(first);
270 Rc::new(chain)
271 }
272 Self::Many(chain) => chain,
273 };
274 match Rc::get_mut(&mut chain) {
275 Some(owned) => more.move_into(owned),
276 None => {
277 let mut copy: ModifierElements = chain.iter().cloned().collect();
278 more.move_into(&mut copy);
279 chain = Rc::new(copy);
280 }
281 }
282 Self::Many(chain)
283 }
284
285 fn move_into(self, chain: &mut ModifierElements) {
286 match self {
287 Self::One(element) => chain.push(element),
288 Self::Many(shared) => match Rc::try_unwrap(shared) {
289 Ok(owned) => chain.extend(owned),
290 Err(shared) => chain.extend(shared.iter().cloned()),
291 },
292 }
293 }
294
295 fn shares_storage(&self, other: &Self) -> bool {
297 match (self, other) {
298 (Self::One(a), Self::One(b)) => Rc::ptr_eq(a, b),
299 (Self::Many(a), Self::Many(b)) => Rc::ptr_eq(a, b),
300 _ => false,
301 }
302 }
303}
304
305impl std::ops::Deref for Elements {
306 type Target = [DynModifierElement];
307
308 fn deref(&self) -> &[DynModifierElement] {
309 match self {
310 Self::One(element) => std::slice::from_ref(element),
311 Self::Many(elements) => elements.as_slice(),
312 }
313 }
314}
315
316#[derive(Clone)]
317enum ModifierKind {
318 Empty,
319 Single {
320 elements: Elements,
321 inspector: Option<Rc<Vec<InspectorMetadata>>>,
324 },
325}
326
327pub(crate) type ModifierElementIterator<'a> = std::slice::Iter<'a, DynModifierElement>;
329pub(crate) type ModifierInspectorIterator<'a> = std::slice::Iter<'a, InspectorMetadata>;
330
331#[derive(Clone)]
349#[must_use = "a modifier does nothing until a composable receives it"]
350pub struct Modifier {
351 kind: ModifierKind,
352 provides_composition_locals: bool,
353}
354
355impl Default for Modifier {
356 fn default() -> Self {
357 Self {
358 kind: ModifierKind::Empty,
359 provides_composition_locals: false,
360 }
361 }
362}
363
364impl Modifier {
365 pub fn empty() -> Self {
367 Self::default()
368 }
369
370 pub fn from_element<E>(element: E) -> Self
372 where
373 E: ModifierNodeElement,
374 {
375 Self::with_element(element)
376 }
377
378 pub fn clip_to_bounds(self) -> Self {
382 let modifier = crate::thread_state::with(|state| {
383 state
384 .clip_to_bounds
385 .get_or_init(|| Self::from_dyn_element(plain_element(ClipToBoundsElement)))
386 .clone()
387 });
388 let modifier =
389 modifier.with_inspector_metadata(inspector_metadata("clipToBounds", |info| {
390 info.add_property("clipToBounds", "true");
391 }));
392 self.then(modifier)
393 }
394
395 pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
398 where
399 T: 'static,
400 F: Fn() -> T + 'static,
401 {
402 let element = ModifierLocalProviderElement::new(key, value);
403 let modifier = Self::from_dyn_element(modifier_element(element));
404 self.then(modifier)
405 }
406
407 pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
410 where
411 F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
412 {
413 let element = ModifierLocalConsumerElement::new(consumer);
414 let modifier = Self::from_dyn_element(modifier_element(element));
415 self.then(modifier)
416 }
417
418 pub fn semantics_spec(self, spec: cranpose_foundation::SemanticsSpec) -> Self {
429 self.stable_semantics(move |config: &mut SemanticsConfiguration| config.merge(&spec))
430 }
431
432 pub fn semantics<F>(self, recorder: F) -> Self
437 where
438 F: Fn(&mut SemanticsConfiguration) + 'static,
439 {
440 self.semantics_recorder(Rc::new(recorder), true)
441 }
442
443 pub fn stable_semantics<F>(self, recorder: F) -> Self
450 where
451 F: Fn(&mut SemanticsConfiguration) + 'static,
452 {
453 self.semantics_recorder(Rc::new(recorder), false)
454 }
455
456 fn semantics_recorder(
457 self,
458 recorder: Rc<dyn Fn(&mut SemanticsConfiguration)>,
459 reads_live_state: bool,
460 ) -> Self {
461 let metadata = if inspector_metadata_enabled() {
462 let mut preview = SemanticsConfiguration::default();
463 recorder(&mut preview);
464 let description = preview.content_description.clone();
465 let state_description = preview.state_description.clone();
466 let role = preview.role;
467 let is_clickable = preview.is_activatable();
468 let canvas_children = preview.canvas_children.len();
469 inspector_metadata("semantics", move |info| {
470 if let Some(desc) = &description {
471 info.add_property("contentDescription", desc.clone());
472 }
473 if let Some(state) = &state_description {
474 info.add_property("stateDescription", state.clone());
475 }
476 if let Some(role) = role {
477 info.add_property("role", format!("{role:?}"));
478 }
479 if is_clickable {
480 info.add_property("isClickable", "true");
481 }
482 if canvas_children > 0 {
483 info.add_property("canvasSemanticsChildren", canvas_children.to_string());
484 }
485 })
486 } else {
487 inspector_metadata("semantics", |_| {})
488 };
489 let element = SemanticsElement::new(recorder, reads_live_state);
490 let modifier =
491 Self::from_dyn_element(modifier_element(element)).with_inspector_metadata(metadata);
492 self.then(modifier)
493 }
494
495 pub fn progress_semantics(self, current: f32, start: f32, end: f32, steps: u32) -> Self {
504 let info = ProgressBarRangeInfo::new(current, start, end, steps);
505 self.stable_semantics(move |config| config.progress = Some(info))
506 }
507
508 pub fn dropdown_list(self) -> Self {
512 self.role(cranpose_foundation::SemanticsWidgetRole::DropdownList)
513 }
514
515 pub fn value_picker(self) -> Self {
518 self.role(cranpose_foundation::SemanticsWidgetRole::ValuePicker)
519 }
520
521 pub fn expand(self, action: impl Fn() -> bool + 'static) -> Self {
526 let action = cranpose_foundation::SemanticsExpand::new(action);
527 self.stable_semantics(move |config| config.expand = Some(action.clone()))
528 }
529
530 pub fn on_long_click(
540 self,
541 label: impl Into<String>,
542 action: impl Fn() -> bool + 'static,
543 ) -> Self {
544 let label = label.into();
545 let action = cranpose_foundation::SemanticsLongClick::new(action);
546 self.stable_semantics(move |config| {
547 config.on_long_click_label = Some(label.clone());
548 config.on_long_click = Some(action.clone());
549 })
550 }
551
552 pub fn on_magic_tap(
557 self,
558 label: impl Into<String>,
559 action: impl Fn() -> bool + 'static,
560 ) -> Self {
561 let label = label.into();
562 let action = cranpose_foundation::SemanticsMagicTap::new(action);
563 self.stable_semantics(move |config| {
564 config.on_magic_tap_label = Some(label.clone());
565 config.on_magic_tap = Some(action.clone());
566 })
567 }
568
569 pub fn input_labels<S: Into<String>>(self, labels: impl IntoIterator<Item = S>) -> Self {
573 let labels: Vec<String> = labels.into_iter().map(Into::into).collect();
574 self.stable_semantics(move |config| config.input_labels.clone_from(&labels))
575 }
576
577 pub fn language(self, tag: impl Into<String>) -> Self {
581 let tag = tag.into();
582 self.stable_semantics(move |config| config.language = Some(tag.clone()))
583 }
584
585 pub fn collapse(self, action: impl Fn() -> bool + 'static) -> Self {
589 let action = cranpose_foundation::SemanticsExpand::new(action);
590 self.stable_semantics(move |config| config.collapse = Some(action.clone()))
591 }
592
593 pub fn dismiss(self, action: impl Fn() -> bool + 'static) -> Self {
598 let action = cranpose_foundation::SemanticsDismiss::new(action);
599 self.stable_semantics(move |config| config.dismiss = Some(action.clone()))
600 }
601
602 pub fn scroll_to_index(self, action: impl Fn(usize) -> bool + 'static) -> Self {
608 let action = cranpose_foundation::SemanticsScrollToIndex::new(action);
609 self.stable_semantics(move |config| config.scroll_to_index = Some(action.clone()))
610 }
611
612 pub fn traversal_index(self, index: f32) -> Self {
618 self.stable_semantics(move |config| config.traversal_index = index)
619 }
620
621 pub fn password(self) -> Self {
626 self.stable_semantics(|config| config.password = true)
627 }
628
629 pub fn error(self, message: impl Into<String>) -> Self {
633 let message = message.into();
634 self.stable_semantics(move |config| config.error = Some(message.clone()))
635 }
636
637 pub fn hint_text(self, hint: impl Into<String>) -> Self {
641 let hint = hint.into();
642 self.stable_semantics(move |config| config.hint_text = Some(hint.clone()))
643 }
644
645 pub fn pane_title(self, title: impl Into<String>) -> Self {
649 let title = title.into();
650 self.stable_semantics(move |config| config.pane_title = Some(title.clone()))
651 }
652
653 pub fn selectable_group(self) -> Self {
658 self.stable_semantics(|config| config.selectable_group = true)
659 }
660
661 pub fn merge_descendants(self) -> Self {
666 self.stable_semantics(|config| config.merge_descendants = true)
667 }
668
669 pub fn hide_from_accessibility(self) -> Self {
674 self.stable_semantics(|config| config.hidden = true)
675 }
676
677 pub fn heading(self) -> Self {
682 self.role(cranpose_foundation::SemanticsWidgetRole::Header)
683 }
684
685 pub fn role(self, role: cranpose_foundation::SemanticsWidgetRole) -> Self {
690 self.stable_semantics(move |config| config.role = Some(role))
691 }
692
693 pub fn live_region(self, mode: cranpose_foundation::LiveRegionMode) -> Self {
699 self.stable_semantics(move |config| config.live_region = Some(mode))
700 }
701
702 pub fn content_description(self, description: impl Into<String>) -> Self {
707 let description = description.into();
708 self.stable_semantics(move |config| config.content_description = Some(description.clone()))
709 }
710
711 pub fn test_tag(self, tag: impl Into<String>) -> Self {
716 let tag = tag.into();
717 self.stable_semantics(move |config| config.test_tag = Some(tag.clone()))
718 }
719
720 pub fn semantics_requester(self, requester: &SemanticsRequester) -> Self {
728 let element = SemanticsRequesterElement::new(requester.clone());
729 let modifier = Self::from_dyn_element(modifier_element(element));
730 self.then(modifier)
731 }
732
733 pub fn debug_chain(self, tag: &'static str) -> Self {
751 use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};
752
753 #[derive(Clone)]
754 struct DebugChainElement {
755 tag: &'static str,
756 }
757
758 impl fmt::Debug for DebugChainElement {
759 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760 f.debug_struct("DebugChainElement")
761 .field("tag", &self.tag)
762 .finish()
763 }
764 }
765
766 impl PartialEq for DebugChainElement {
767 fn eq(&self, other: &Self) -> bool {
768 self.tag == other.tag
769 }
770 }
771
772 impl Eq for DebugChainElement {}
773
774 impl std::hash::Hash for DebugChainElement {
775 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
776 self.tag.hash(state);
777 }
778 }
779
780 impl ModifierNodeElement for DebugChainElement {
781 type Node = DebugChainNode;
782
783 fn create(&self) -> Self::Node {
784 DebugChainNode::new(self.tag)
785 }
786
787 fn update(&self, node: &mut Self::Node) {
788 node.tag = self.tag;
789 }
790
791 fn capabilities(&self) -> NodeCapabilities {
792 NodeCapabilities::empty()
793 }
794 }
795
796 struct DebugChainNode {
797 tag: &'static str,
798 state: NodeState,
799 }
800
801 impl DebugChainNode {
802 fn new(tag: &'static str) -> Self {
803 Self {
804 tag,
805 state: NodeState::new(),
806 }
807 }
808 }
809
810 #[expect(clippy::print_stderr, reason = "debug_chain prints its lifecycle")]
811 impl ModifierNode for DebugChainNode {
812 fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
813 eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
814 }
815
816 fn on_detach(&mut self) {
817 eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
818 }
819
820 fn on_reset(&mut self) {
821 eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
822 }
823 }
824
825 impl cranpose_foundation::DelegatableNode for DebugChainNode {
826 fn node_state(&self) -> &NodeState {
827 &self.state
828 }
829 }
830
831 let element = DebugChainElement { tag };
832 let modifier = Self::from_dyn_element(modifier_element(element));
833 self.then(modifier)
834 .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
835 info.add_property("tag", tag);
836 }))
837 }
838
839 pub fn then(self, next: Self) -> Self {
845 let ModifierKind::Single {
846 elements,
847 inspector,
848 } = self.kind
849 else {
850 return next;
851 };
852 let ModifierKind::Single {
853 elements: next_elements,
854 inspector: next_inspector,
855 } = next.kind
856 else {
857 return Self {
858 kind: ModifierKind::Single {
859 elements,
860 inspector,
861 },
862 ..self
863 };
864 };
865
866 let inspector = if next_inspector.is_none() {
867 inspector
868 } else {
869 merged_inspector(
870 inspector_slice(&inspector),
871 inspector_slice(&next_inspector),
872 )
873 };
874 Self {
875 kind: ModifierKind::Single {
876 elements: elements.joined(next_elements),
877 inspector,
878 },
879 provides_composition_locals: self.provides_composition_locals
880 || next.provides_composition_locals,
881 }
882 }
883
884 pub(crate) fn element_count(&self) -> usize {
886 match &self.kind {
887 ModifierKind::Empty => 0,
888 ModifierKind::Single { elements, .. } => elements.len(),
889 }
890 }
891
892 pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
893 self.as_elements().iter()
894 }
895
896 pub(crate) fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
897 if !self.provides_composition_locals {
898 return Vec::new();
899 }
900 self.iter_elements()
901 .flat_map(|element| element.provided_composition_locals())
902 .collect()
903 }
904
905 pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
906 match &self.kind {
907 ModifierKind::Empty => [].iter(),
908 ModifierKind::Single { inspector, .. } => inspector_slice(inspector).iter(),
909 }
910 }
911
912 #[cfg(test)]
913 pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
914 match &self.kind {
915 ModifierKind::Empty => Vec::new(),
916 ModifierKind::Single { elements, .. } => elements.to_vec(),
917 }
918 }
919
920 pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
921 match &self.kind {
922 ModifierKind::Empty => Vec::new(),
923 ModifierKind::Single { inspector, .. } => {
924 inspector.as_deref().cloned().unwrap_or_default()
925 }
926 }
927 }
928
929 pub fn total_padding(&self) -> f32 {
931 let padding = self.padding_values();
932 padding
933 .left
934 .max(padding.right)
935 .max(padding.top)
936 .max(padding.bottom)
937 }
938
939 pub fn explicit_size(&self) -> Option<Size> {
942 let props = self.layout_properties();
943 match (props.width, props.height) {
944 (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
945 Some(Size { width, height })
946 }
947 _ => None,
948 }
949 }
950
951 pub fn padding_values(&self) -> EdgeInsets {
953 self.resolved_modifiers().padding()
954 }
955
956 pub(crate) fn layout_properties(&self) -> LayoutProperties {
957 self.resolved_modifiers().layout_properties()
958 }
959
960 pub fn box_alignment(&self) -> Option<Alignment> {
962 self.layout_properties().box_alignment()
963 }
964
965 pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
967 self.layout_properties().column_alignment()
968 }
969
970 pub fn row_alignment(&self) -> Option<VerticalAlignment> {
972 self.layout_properties().row_alignment()
973 }
974
975 pub fn draw_commands(&self) -> Vec<DrawCommand> {
977 collect_slices_from_modifier(self).draw_commands().to_vec()
978 }
979
980 pub fn clips_to_bounds(&self) -> bool {
982 collect_slices_from_modifier(self).clip_to_bounds()
983 }
984
985 pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
987 self.inspector_metadata()
988 .iter()
989 .map(InspectorMetadata::to_record)
990 .collect()
991 }
992
993 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
995 let mut handle = ModifierChainHandle::new();
996 let _ = handle.update(self);
997 handle.resolved_modifiers()
998 }
999
1000 pub fn with_element<E>(element: E) -> Self
1003 where
1004 E: ModifierNodeElement,
1005 {
1006 Self::from_dyn_element(modifier_element(element))
1007 }
1008
1009 pub(crate) fn from_dyn_element(element: DynModifierElement) -> Self {
1011 Self {
1012 provides_composition_locals: element.provides_composition_locals(),
1013 kind: ModifierKind::Single {
1014 elements: Elements::One(element),
1015 inspector: None,
1016 },
1017 }
1018 }
1019
1020 pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
1021 if metadata.is_empty() {
1022 return self;
1023 }
1024 match self.kind {
1025 ModifierKind::Empty => self,
1026 ModifierKind::Single {
1027 elements,
1028 inspector,
1029 } => {
1030 let mut list = inspector.as_deref().cloned().unwrap_or_default();
1031 list.push(metadata);
1032 let new_inspector = Rc::new(list);
1033 Self {
1034 kind: ModifierKind::Single {
1035 elements,
1036 inspector: Some(new_inspector),
1037 },
1038 provides_composition_locals: self.provides_composition_locals,
1039 }
1040 }
1041 }
1042 }
1043
1044 pub fn structural_eq(&self, other: &Self) -> bool {
1049 element_match::modifiers_match(self, other, ElementMatch::Structural)
1050 }
1051
1052 fn as_elements(&self) -> &[DynModifierElement] {
1053 match &self.kind {
1054 ModifierKind::Empty => &[],
1055 ModifierKind::Single { elements, .. } => elements,
1056 }
1057 }
1058}
1059
1060impl PartialEq for Modifier {
1061 fn eq(&self, other: &Self) -> bool {
1062 element_match::modifiers_match(self, other, ElementMatch::Equal)
1063 }
1064}
1065
1066impl Eq for Modifier {}
1067
1068impl fmt::Display for Modifier {
1069 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1070 match &self.kind {
1071 ModifierKind::Empty => write!(f, "Modifier.empty"),
1072 ModifierKind::Single { elements, .. } => {
1073 if elements.is_empty() {
1074 return write!(f, "Modifier.empty");
1075 }
1076 write!(f, "Modifier[")?;
1077 for (index, element) in elements.iter().enumerate() {
1078 if index > 0 {
1079 write!(f, ", ")?;
1080 }
1081 let name = element.inspector_name();
1082 let mut properties = Vec::new();
1083 element.record_inspector_properties(&mut |prop, value| {
1084 properties.push(format!("{prop}={value}"));
1085 });
1086 if properties.is_empty() {
1087 write!(f, "{name}")?;
1088 } else {
1089 write!(f, "{name}({})", properties.join(", "))?;
1090 }
1091 }
1092 write!(f, "]")
1093 }
1094 }
1095 }
1096}
1097
1098impl fmt::Debug for Modifier {
1099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100 fmt::Display::fmt(self, f)
1101 }
1102}
1103
1104#[cfg(test)]
1105#[path = "tests/modifier_tests.rs"]
1106mod tests;