1use std::{fmt, rc::Rc};
9
10mod alignment;
11mod background;
12mod blur;
13mod border;
14mod chain;
15mod clickable;
16mod coordinator_rect;
17mod drag_and_drop;
18mod draw_cache;
19mod element_match;
20mod elements;
21mod fill;
22pub(crate) mod focus;
23mod focus_ring;
24mod graphics_layer;
25mod kept_modifier;
26mod key_input;
27mod layout_data;
28mod local;
29mod long_press;
30mod minimum_interactive;
31mod offset;
32mod padding;
33mod pointer_icon;
34pub(crate) mod pointer_input;
35mod pointer_opaque;
36mod resolved_modifiers;
37mod rotary_input;
38mod scroll;
39mod selectable;
40mod semantics;
41mod shadow;
42mod size;
43mod slices;
44mod toggleable;
45mod weight;
46mod window_root;
47mod wrap_content;
48mod z_index;
49
50pub(crate) use chain::{
51 InPlaceReach, InPlaceUpdate, ModifierChainHandle, ModifierChainInspectorNode,
52 ModifierLocalsHandle, SharedParentData,
53};
54pub(crate) use coordinator_rect::CoordinatorRect;
55use cranpose_foundation::{
56 ModifierNodeElement, ProgressBarRangeInfo, SemanticsConfiguration, modifier_element,
57 plain_element,
58};
59pub use cranpose_foundation::{
60 PointerButton, PointerButtons, PointerEvent, PointerEventKind, PointerSource, RotaryScrollEvent,
61};
62pub use cranpose_ui_graphics::{
63 BlendMode, Brush, Color, CompositingStrategy, CornerRadii, DpOffset, EdgeInsets, GraphicsLayer,
64 LayerShape, Point, Rect, RenderEffect, RoundedCornerShape, RuntimeShader, Shadow, ShadowScope,
65 Size, TransformOrigin,
66};
67use cranpose_ui_layout::{Alignment, HorizontalAlignment, VerticalAlignment};
68pub use drag_and_drop::{
69 DragAndDropEvent, DragAndDropOutcome, DragAndDropPayload, DragAndDropPoint, DragAndDropSource,
70 DragAndDropSourceElement, DragAndDropSourceNode, DragAndDropState, DragAndDropTarget,
71 DragAndDropTargetElement, DragAndDropTargetNode,
72};
73pub(crate) use element_match::ElementMatch;
74use elements::ModifierKind;
75#[cfg(test)]
76pub(crate) use focus::FocusRequesterElement;
77pub use focus::{FocusDirection, FocusRequestError, FocusRequester};
78pub use graphics_layer::GlassMaterial;
79pub use kept_modifier::__kept_modifier;
80pub(crate) use kept_modifier::KeptModifiers;
81pub use key_input::KeyEventRoute;
82pub(crate) use local::{
83 ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
84};
85use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
86pub use local::{ModifierLocalKey, ModifierLocalReadScope};
87pub use pointer_input::PointerInputScope;
88pub(crate) use resolved_modifiers::{DimensionConstraint, LayoutProperties, LayoutWeight};
89pub use resolved_modifiers::{ResolvedBackground, ResolvedModifiers};
90pub use rotary_input::RotaryInputModifierNode;
91#[cfg(feature = "test-helpers")]
92pub use scroll::{last_fling_velocity, reset_last_fling_velocity};
93use semantics::SemanticsElement;
94pub use semantics::{SemanticsRequester, collect_semantics_from_modifier};
95pub(crate) use semantics::{
96 SemanticsRequesterElement, collect_semantics_from_chain, semantics_reach_of_chain,
97};
98pub(crate) use slices::SlicesSnapshot;
99pub use slices::{
100 ModifierNodeSlices, ModifierNodeSlicesDebugStats, SliceTextRef, collect_modifier_slices,
101 collect_slices_from_modifier,
102};
103pub use window_root::{
104 WindowRootDescriptor, WindowRootElement, WindowRootEntry, WindowRootNode, WindowRootRegistry,
105 WindowRootRoutingScratch, is_window_root, nearest_window_root, nearest_window_roots,
106 nearest_window_roots_into, window_roots, window_roots_revision,
107};
108pub use z_index::{z_index_in_use, z_index_modifier_in_use};
109
110pub(crate) use crate::draw::{DrawCacheBuilder, DrawCommand};
111use crate::modifier_nodes::ClipToBoundsElement;
112
113#[derive(Clone, Debug, Default)]
114pub(crate) struct InspectorInfo {
115 properties: Vec<InspectorProperty>,
116}
117
118impl InspectorInfo {
119 pub(crate) fn new() -> Self {
120 Self::default()
121 }
122
123 pub(crate) fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
124 self.properties.push(InspectorProperty {
125 name,
126 value: value.into(),
127 });
128 }
129
130 pub(crate) fn properties(&self) -> &[InspectorProperty] {
131 &self.properties
132 }
133
134 pub(crate) fn is_empty(&self) -> bool {
135 self.properties.is_empty()
136 }
137
138 pub(crate) fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
139 self.add_property(name, describe_dimension(constraint));
140 }
141
142 pub(crate) fn add_offset_components(
143 &mut self,
144 x_name: &'static str,
145 y_name: &'static str,
146 offset: Point,
147 ) {
148 self.add_property(x_name, offset.x.to_string());
149 self.add_property(y_name, offset.y.to_string());
150 }
151
152 pub(crate) fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
153 where
154 A: fmt::Debug,
155 {
156 self.add_property(name, format!("{alignment:?}"));
157 }
158}
159
160#[derive(Clone, Debug, PartialEq)]
161pub struct InspectorProperty {
162 pub name: &'static str,
163 pub value: String,
164}
165
166#[derive(Clone, Debug, PartialEq)]
167pub struct ModifierInspectorRecord {
168 pub name: &'static str,
169 pub properties: Vec<InspectorProperty>,
170}
171
172#[derive(Clone, Debug)]
173pub(crate) struct InspectorMetadata {
174 name: &'static str,
175 info: InspectorInfo,
176}
177
178impl InspectorMetadata {
179 pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
180 where
181 F: FnOnce(&mut InspectorInfo),
182 {
183 let mut info = InspectorInfo::new();
184 recorder(&mut info);
185 Self { name, info }
186 }
187
188 fn is_empty(&self) -> bool {
189 self.info.is_empty()
190 }
191
192 fn to_record(&self) -> ModifierInspectorRecord {
193 ModifierInspectorRecord {
194 name: self.name,
195 properties: self.info.properties().to_vec(),
196 }
197 }
198}
199
200fn describe_dimension(constraint: DimensionConstraint) -> String {
201 match constraint {
202 DimensionConstraint::Unspecified => "unspecified".to_string(),
203 DimensionConstraint::Points(value) => value.to_string(),
204 DimensionConstraint::Fraction(value) => format!("fraction({value})"),
205 DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
206 }
207}
208
209pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
210where
211 F: FnOnce(&mut InspectorInfo),
212{
213 if !inspector_metadata_enabled() {
214 return InspectorMetadata::new(name, |_| {});
215 }
216 InspectorMetadata::new(name, recorder)
217}
218
219pub(crate) fn modifier_debug_enabled() -> bool {
220 #[cfg(not(target_arch = "wasm32"))]
221 {
222 cranpose_core::DIAGNOSTICS.compose_debug_modifiers.is_set()
223 }
224 #[cfg(target_arch = "wasm32")]
225 {
226 false
227 }
228}
229
230fn inspector_metadata_enabled() -> bool {
231 cfg!(any(test, feature = "inspection")) || modifier_debug_enabled()
232}
233
234#[derive(Clone)]
252#[must_use = "a modifier does nothing until a composable receives it"]
253pub struct Modifier {
254 kind: ModifierKind,
255}
256
257impl Default for Modifier {
258 fn default() -> Self {
259 Self {
260 kind: ModifierKind::Empty,
261 }
262 }
263}
264
265impl Modifier {
266 pub fn empty() -> Self {
268 Self::default()
269 }
270
271 pub fn from_element<E>(element: E) -> Self
273 where
274 E: ModifierNodeElement,
275 {
276 Self::with_element(element)
277 }
278
279 pub fn clip_to_bounds(self) -> Self {
283 let modifier = crate::thread_state::with(|state| {
284 state
285 .clip_to_bounds
286 .get_or_init(|| Self::from_dyn_element(plain_element(&ClipToBoundsElement)))
287 .clone()
288 });
289 let modifier =
290 modifier.with_inspector_metadata(inspector_metadata("clipToBounds", |info| {
291 info.add_property("clipToBounds", "true");
292 }));
293 self.then(modifier)
294 }
295
296 pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
299 where
300 T: 'static,
301 F: Fn() -> T + 'static,
302 {
303 let element = ModifierLocalProviderElement::new(key, value);
304 let modifier = Self::from_dyn_element(modifier_element(element));
305 self.then(modifier)
306 }
307
308 pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
311 where
312 F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
313 {
314 let element = ModifierLocalConsumerElement::new(consumer);
315 let modifier = Self::from_dyn_element(modifier_element(element));
316 self.then(modifier)
317 }
318
319 pub fn semantics_spec(self, spec: cranpose_foundation::SemanticsSpec) -> Self {
330 self.stable_semantics(move |config: &mut SemanticsConfiguration| config.merge(&spec))
331 }
332
333 pub fn semantics<F>(self, recorder: F) -> Self
338 where
339 F: Fn(&mut SemanticsConfiguration) + 'static,
340 {
341 self.semantics_recorder(Rc::new(recorder), true)
342 }
343
344 pub fn stable_semantics<F>(self, recorder: F) -> Self
351 where
352 F: Fn(&mut SemanticsConfiguration) + 'static,
353 {
354 self.semantics_recorder(Rc::new(recorder), false)
355 }
356
357 fn semantics_recorder(
358 self,
359 recorder: Rc<dyn Fn(&mut SemanticsConfiguration)>,
360 reads_live_state: bool,
361 ) -> Self {
362 let metadata = if inspector_metadata_enabled() {
363 let mut preview = SemanticsConfiguration::default();
364 recorder(&mut preview);
365 let description = preview.content_description.clone();
366 let state_description = preview.state_description.clone();
367 let role = preview.role;
368 let is_clickable = preview.is_activatable();
369 let canvas_children = preview.canvas_children.len();
370 inspector_metadata("semantics", move |info| {
371 if let Some(desc) = &description {
372 info.add_property("contentDescription", desc.clone());
373 }
374 if let Some(state) = &state_description {
375 info.add_property("stateDescription", state.clone());
376 }
377 if let Some(role) = role {
378 info.add_property("role", format!("{role:?}"));
379 }
380 if is_clickable {
381 info.add_property("isClickable", "true");
382 }
383 if canvas_children > 0 {
384 info.add_property("canvasSemanticsChildren", canvas_children.to_string());
385 }
386 })
387 } else {
388 inspector_metadata("semantics", |_| {})
389 };
390 let element = SemanticsElement::new(recorder, reads_live_state);
391 let modifier =
392 Self::from_dyn_element(modifier_element(element)).with_inspector_metadata(metadata);
393 self.then(modifier)
394 }
395
396 pub fn progress_semantics(self, current: f32, start: f32, end: f32, steps: u32) -> Self {
405 let info = ProgressBarRangeInfo::new(current, start, end, steps);
406 self.stable_semantics(move |config| config.progress = Some(info))
407 }
408
409 pub fn dropdown_list(self) -> Self {
413 self.role(cranpose_foundation::SemanticsWidgetRole::DropdownList)
414 }
415
416 pub fn value_picker(self) -> Self {
419 self.role(cranpose_foundation::SemanticsWidgetRole::ValuePicker)
420 }
421
422 pub fn expand(self, action: impl Fn() -> bool + 'static) -> Self {
427 let action = cranpose_foundation::SemanticsExpand::new(action);
428 self.stable_semantics(move |config| config.expand = Some(action.clone()))
429 }
430
431 pub fn on_long_click(
441 self,
442 label: impl Into<String>,
443 action: impl Fn() -> bool + 'static,
444 ) -> Self {
445 let label = label.into();
446 let action = cranpose_foundation::SemanticsLongClick::new(action);
447 self.stable_semantics(move |config| {
448 config.on_long_click_label = Some(label.clone());
449 config.on_long_click = Some(action.clone());
450 })
451 }
452
453 pub fn on_magic_tap(
458 self,
459 label: impl Into<String>,
460 action: impl Fn() -> bool + 'static,
461 ) -> Self {
462 let label = label.into();
463 let action = cranpose_foundation::SemanticsMagicTap::new(action);
464 self.stable_semantics(move |config| {
465 config.on_magic_tap_label = Some(label.clone());
466 config.on_magic_tap = Some(action.clone());
467 })
468 }
469
470 pub fn input_labels<S: Into<String>>(self, labels: impl IntoIterator<Item = S>) -> Self {
474 let labels: Vec<String> = labels.into_iter().map(Into::into).collect();
475 self.stable_semantics(move |config| config.input_labels.clone_from(&labels))
476 }
477
478 pub fn language(self, tag: impl Into<String>) -> Self {
482 let tag = tag.into();
483 self.stable_semantics(move |config| config.language = Some(tag.clone()))
484 }
485
486 pub fn collapse(self, action: impl Fn() -> bool + 'static) -> Self {
490 let action = cranpose_foundation::SemanticsExpand::new(action);
491 self.stable_semantics(move |config| config.collapse = Some(action.clone()))
492 }
493
494 pub fn dismiss(self, action: impl Fn() -> bool + 'static) -> Self {
499 let action = cranpose_foundation::SemanticsDismiss::new(action);
500 self.stable_semantics(move |config| config.dismiss = Some(action.clone()))
501 }
502
503 pub fn scroll_to_index(self, action: impl Fn(usize) -> bool + 'static) -> Self {
509 let action = cranpose_foundation::SemanticsScrollToIndex::new(action);
510 self.stable_semantics(move |config| config.scroll_to_index = Some(action.clone()))
511 }
512
513 pub fn traversal_index(self, index: f32) -> Self {
519 self.stable_semantics(move |config| config.traversal_index = index)
520 }
521
522 pub fn password(self) -> Self {
527 self.stable_semantics(|config| config.password = true)
528 }
529
530 pub fn error(self, message: impl Into<String>) -> Self {
534 let message = message.into();
535 self.stable_semantics(move |config| config.error = Some(message.clone()))
536 }
537
538 pub fn hint_text(self, hint: impl Into<String>) -> Self {
542 let hint = hint.into();
543 self.stable_semantics(move |config| config.hint_text = Some(hint.clone()))
544 }
545
546 pub fn pane_title(self, title: impl Into<String>) -> Self {
550 let title = title.into();
551 self.stable_semantics(move |config| config.pane_title = Some(title.clone()))
552 }
553
554 pub fn selectable_group(self) -> Self {
559 self.stable_semantics(|config| config.selectable_group = true)
560 }
561
562 pub fn merge_descendants(self) -> Self {
567 self.stable_semantics(|config| config.merge_descendants = true)
568 }
569
570 pub fn hide_from_accessibility(self) -> Self {
575 self.stable_semantics(|config| config.hidden = true)
576 }
577
578 pub fn heading(self) -> Self {
583 self.role(cranpose_foundation::SemanticsWidgetRole::Header)
584 }
585
586 pub fn role(self, role: cranpose_foundation::SemanticsWidgetRole) -> Self {
591 self.stable_semantics(move |config| config.role = Some(role))
592 }
593
594 pub fn live_region(self, mode: cranpose_foundation::LiveRegionMode) -> Self {
600 self.stable_semantics(move |config| config.live_region = Some(mode))
601 }
602
603 pub fn content_description(self, description: impl Into<String>) -> Self {
608 let description = description.into();
609 self.stable_semantics(move |config| config.content_description = Some(description.clone()))
610 }
611
612 pub fn test_tag(self, tag: impl Into<String>) -> Self {
617 let tag = tag.into();
618 self.stable_semantics(move |config| config.test_tag = Some(tag.clone()))
619 }
620
621 pub fn semantics_requester(self, requester: &SemanticsRequester) -> Self {
629 let element = SemanticsRequesterElement::new(requester.clone());
630 let modifier = Self::from_dyn_element(modifier_element(element));
631 self.then(modifier)
632 }
633
634 pub fn debug_chain(self, tag: &'static str) -> Self {
652 use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};
653
654 #[derive(Clone)]
655 struct DebugChainElement {
656 tag: &'static str,
657 }
658
659 impl fmt::Debug for DebugChainElement {
660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 f.debug_struct("DebugChainElement")
662 .field("tag", &self.tag)
663 .finish()
664 }
665 }
666
667 impl PartialEq for DebugChainElement {
668 fn eq(&self, other: &Self) -> bool {
669 self.tag == other.tag
670 }
671 }
672
673 impl Eq for DebugChainElement {}
674
675 impl std::hash::Hash for DebugChainElement {
676 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
677 self.tag.hash(state);
678 }
679 }
680
681 impl ModifierNodeElement for DebugChainElement {
682 type Node = DebugChainNode;
683
684 fn create(&self) -> Self::Node {
685 DebugChainNode::new(self.tag)
686 }
687
688 fn update(&self, node: &mut Self::Node) {
689 node.tag = self.tag;
690 }
691
692 fn capabilities(&self) -> NodeCapabilities {
693 NodeCapabilities::empty()
694 }
695 }
696
697 struct DebugChainNode {
698 tag: &'static str,
699 state: NodeState,
700 }
701
702 impl DebugChainNode {
703 fn new(tag: &'static str) -> Self {
704 Self {
705 tag,
706 state: NodeState::new(),
707 }
708 }
709 }
710
711 #[expect(clippy::print_stderr, reason = "debug_chain prints its lifecycle")]
712 impl ModifierNode for DebugChainNode {
713 fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
714 eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
715 }
716
717 fn on_detach(&mut self) {
718 eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
719 }
720
721 fn on_reset(&mut self) {
722 eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
723 }
724 }
725
726 impl cranpose_foundation::DelegatableNode for DebugChainNode {
727 fn node_state(&self) -> &NodeState {
728 &self.state
729 }
730 }
731
732 let element = DebugChainElement { tag };
733 let modifier = Self::from_dyn_element(modifier_element(element));
734 self.then(modifier)
735 .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
736 info.add_property("tag", tag);
737 }))
738 }
739
740 pub fn total_padding(&self) -> f32 {
742 let padding = self.padding_values();
743 padding
744 .left
745 .max(padding.right)
746 .max(padding.top)
747 .max(padding.bottom)
748 }
749
750 pub fn explicit_size(&self) -> Option<Size> {
753 let props = self.layout_properties();
754 match (props.width, props.height) {
755 (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
756 Some(Size { width, height })
757 }
758 _ => None,
759 }
760 }
761
762 pub fn padding_values(&self) -> EdgeInsets {
764 self.resolved_modifiers().padding()
765 }
766
767 pub(crate) fn layout_properties(&self) -> LayoutProperties {
768 self.resolved_modifiers().layout_properties()
769 }
770
771 pub fn box_alignment(&self) -> Option<Alignment> {
773 self.layout_properties().box_alignment()
774 }
775
776 pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
778 self.layout_properties().column_alignment()
779 }
780
781 pub fn row_alignment(&self) -> Option<VerticalAlignment> {
783 self.layout_properties().row_alignment()
784 }
785
786 pub fn draw_commands(&self) -> Vec<DrawCommand> {
788 collect_slices_from_modifier(self).draw_commands().to_vec()
789 }
790
791 pub fn clips_to_bounds(&self) -> bool {
793 collect_slices_from_modifier(self).clip_to_bounds()
794 }
795
796 pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
798 self.inspector_metadata()
799 .iter()
800 .map(InspectorMetadata::to_record)
801 .collect()
802 }
803
804 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
806 let mut handle = ModifierChainHandle::new();
807 let _ = handle.update(self);
808 handle.resolved_modifiers()
809 }
810
811 pub fn with_element<E>(element: E) -> Self
814 where
815 E: ModifierNodeElement,
816 {
817 Self::from_dyn_element(modifier_element(element))
818 }
819
820 pub fn structural_eq(&self, other: &Self) -> bool {
825 element_match::modifiers_match(self, other, ElementMatch::Structural)
826 }
827}
828
829impl PartialEq for Modifier {
830 fn eq(&self, other: &Self) -> bool {
831 element_match::modifiers_match(self, other, ElementMatch::Equal)
832 }
833}
834
835impl Eq for Modifier {}
836
837impl fmt::Display for Modifier {
838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839 let elements = self.as_elements();
840 if elements.is_empty() {
841 return write!(f, "Modifier.empty");
842 }
843 write!(f, "Modifier[")?;
844 for (index, element) in elements.iter().enumerate() {
845 if index > 0 {
846 write!(f, ", ")?;
847 }
848 let name = element.inspector_name();
849 let mut properties = Vec::new();
850 element.record_inspector_properties(&mut |prop, value| {
851 properties.push(format!("{prop}={value}"));
852 });
853 if properties.is_empty() {
854 write!(f, "{name}")?;
855 } else {
856 write!(f, "{name}({})", properties.join(", "))?;
857 }
858 }
859 write!(f, "]")
860 }
861}
862
863impl fmt::Debug for Modifier {
864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
865 fmt::Display::fmt(self, f)
866 }
867}
868
869#[cfg(test)]
870#[path = "tests/modifier_tests.rs"]
871mod tests;