1use std::{
9 fmt,
10 hash::{Hash, Hasher},
11 rc::Rc,
12};
13
14use cranpose_core::{ProvidedValue, hash::default};
15use smallvec::SmallVec;
16
17mod alignment;
18mod background;
19mod blur;
20mod border;
21mod chain;
22mod clickable;
23mod coordinator_geometry;
24mod drag_and_drop;
25mod draw_cache;
26mod fill;
27mod focus;
28mod focus_ring;
29mod graphics_layer;
30mod key_input;
31mod local;
32mod minimum_interactive;
33mod offset;
34mod padding;
35mod pointer_icon;
36pub(crate) mod pointer_input;
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;
48
49pub use chain::{ModifierChainHandle, ModifierChainInspectorNode, ModifierLocalsHandle};
50pub(crate) use coordinator_geometry::{CoordinatorGeometry, CoordinatorRect};
51pub use cranpose_foundation::{
52 AnyModifierElement, DynModifierElement, FocusState, PointerEvent, PointerEventKind,
53 PointerSource, RotaryScrollEvent, SemanticsConfiguration, modifier_element,
54};
55use cranpose_foundation::{ModifierNodeElement, NodeCapabilities, ProgressBarRangeInfo};
56#[expect(unused_imports)]
57pub use cranpose_ui_graphics::{
58 BlendMode, BlurredEdgeTreatment, Brush, Color, ColorFilter, CompositingStrategy, CornerRadii,
59 CursorIcon, CustomPointerIcon, CutDirection, Dp, DpOffset, EdgeInsets, GradientCutMaskSpec,
60 GradientFadeMaskSpec, GraphicsLayer, LayerShape, Point, PointerIcon, PointerIconError, Rect,
61 RenderEffect, RoundedCornerShape, RuntimeShader, Shadow, ShadowScope, Size, TransformOrigin,
62};
63use cranpose_ui_layout::{Alignment, HorizontalAlignment, IntrinsicSize, VerticalAlignment};
64pub use drag_and_drop::{
65 DragAndDropEvent, DragAndDropOutcome, DragAndDropPayload, DragAndDropPoint, DragAndDropSource,
66 DragAndDropSourceElement, DragAndDropSourceNode, DragAndDropState, DragAndDropTarget,
67 DragAndDropTargetElement, DragAndDropTargetNode,
68};
69use focus::FocusTargetElement;
70pub use focus::{FocusDirection, FocusRequestError, FocusRequester, FocusRequesterElement};
71pub use graphics_layer::GlassMaterial;
72pub use key_input::KeyEventRoute;
73pub(crate) use local::{
74 ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
75};
76use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
77pub use local::{ModifierLocalKey, ModifierLocalReadScope};
78#[expect(unused_imports)]
79pub use pointer_input::{AwaitPointerEventScope, PointerInputScope};
80pub use rotary_input::RotaryInputModifierNode;
81#[cfg(test)]
82pub(crate) use scroll::lazy_scroll_semantics;
83#[cfg(feature = "test-helpers")]
84pub use scroll::{last_fling_velocity, reset_last_fling_velocity};
85use semantics::SemanticsElement;
86pub use semantics::{
87 SemanticsRequester, SemanticsRequesterElement, collect_semantics_from_chain,
88 collect_semantics_from_modifier, semantics_reach_of_chain,
89};
90pub(crate) use slices::SlicesSnapshot;
91pub use slices::{
92 ModifierNodeSlices, ModifierNodeSlicesDebugStats, SliceTextRef, collect_modifier_slices,
93 collect_slices_from_modifier,
94};
95pub use window_root::{
96 WindowRootDescriptor, WindowRootElement, WindowRootEntry, WindowRootNode, WindowRootRegistry,
97 WindowRootRoutingScratch, is_window_root, nearest_window_root, nearest_window_roots,
98 nearest_window_roots_into, window_roots, window_roots_revision,
99};
100
101pub use crate::draw::{DrawCacheBuilder, DrawCommand};
102use crate::modifier_nodes::ClipToBoundsElement;
103
104#[derive(Clone, Debug, Default)]
105pub struct InspectorInfo {
106 properties: Vec<InspectorProperty>,
107}
108
109impl InspectorInfo {
110 pub fn new() -> Self {
111 Self::default()
112 }
113
114 pub fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
115 self.properties.push(InspectorProperty {
116 name,
117 value: value.into(),
118 });
119 }
120
121 pub fn properties(&self) -> &[InspectorProperty] {
122 &self.properties
123 }
124
125 pub fn is_empty(&self) -> bool {
126 self.properties.is_empty()
127 }
128
129 pub fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
130 self.add_property(name, describe_dimension(constraint));
131 }
132
133 pub fn add_offset_components(
134 &mut self,
135 x_name: &'static str,
136 y_name: &'static str,
137 offset: Point,
138 ) {
139 self.add_property(x_name, offset.x.to_string());
140 self.add_property(y_name, offset.y.to_string());
141 }
142
143 pub fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
144 where
145 A: fmt::Debug,
146 {
147 self.add_property(name, format!("{alignment:?}"));
148 }
149}
150
151#[derive(Clone, Debug, PartialEq)]
152pub struct InspectorProperty {
153 pub name: &'static str,
154 pub value: String,
155}
156
157#[derive(Clone, Debug, PartialEq)]
158pub struct ModifierInspectorRecord {
159 pub name: &'static str,
160 pub properties: Vec<InspectorProperty>,
161}
162
163#[derive(Clone, Debug)]
164pub(crate) struct InspectorMetadata {
165 name: &'static str,
166 info: InspectorInfo,
167}
168
169impl InspectorMetadata {
170 pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
171 where
172 F: FnOnce(&mut InspectorInfo),
173 {
174 let mut info = InspectorInfo::new();
175 recorder(&mut info);
176 Self { name, info }
177 }
178
179 fn is_empty(&self) -> bool {
180 self.info.is_empty()
181 }
182
183 fn to_record(&self) -> ModifierInspectorRecord {
184 ModifierInspectorRecord {
185 name: self.name,
186 properties: self.info.properties().to_vec(),
187 }
188 }
189}
190
191fn describe_dimension(constraint: DimensionConstraint) -> String {
192 match constraint {
193 DimensionConstraint::Unspecified => "unspecified".to_string(),
194 DimensionConstraint::Points(value) => value.to_string(),
195 DimensionConstraint::Fraction(value) => format!("fraction({value})"),
196 DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
197 }
198}
199
200fn inspector_slice(inspector: &Option<Rc<[InspectorMetadata]>>) -> &[InspectorMetadata] {
201 inspector.as_deref().unwrap_or(&[])
202}
203
204fn merged_inspector(
207 first: &[InspectorMetadata],
208 second: &[InspectorMetadata],
209) -> Option<Rc<[InspectorMetadata]>> {
210 if first.is_empty() && second.is_empty() {
211 return None;
212 }
213 Some(first.iter().chain(second).cloned().collect())
214}
215
216pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
217where
218 F: FnOnce(&mut InspectorInfo),
219{
220 if !inspector_metadata_enabled() {
221 return InspectorMetadata::new(name, |_| {});
222 }
223 InspectorMetadata::new(name, recorder)
224}
225
226pub(crate) fn modifier_debug_enabled() -> bool {
227 #[cfg(not(target_arch = "wasm32"))]
228 {
229 cranpose_core::env_flag!("COMPOSE_DEBUG_MODIFIERS")
230 }
231 #[cfg(target_arch = "wasm32")]
232 {
233 false
234 }
235}
236
237fn inspector_metadata_enabled() -> bool {
238 cfg!(any(test, feature = "inspection")) || modifier_debug_enabled()
239}
240
241type ModifierElements = SmallVec<[DynModifierElement; 4]>;
244
245#[derive(Clone)]
250enum Elements {
251 One(DynModifierElement),
252 Many(Rc<ModifierElements>),
253}
254
255impl Elements {
256 fn from_slice(elements: &[DynModifierElement]) -> Self {
257 match elements {
258 [element] => Self::One(element.clone()),
259 _ => Self::Many(Rc::new(elements.iter().cloned().collect())),
260 }
261 }
262
263 fn extend_from(&mut self, more: &[DynModifierElement]) {
264 match self {
265 Self::Many(shared) => match Rc::get_mut(shared) {
266 Some(owned) => owned.extend(more.iter().cloned()),
267 None => *shared = Rc::new(shared.iter().chain(more).cloned().collect()),
268 },
269 Self::One(first) => {
270 *self = Self::Many(Rc::new(
271 std::iter::once(&*first).chain(more).cloned().collect(),
272 ));
273 }
274 }
275 }
276
277 fn shares_storage(&self, other: &Self) -> bool {
279 match (self, other) {
280 (Self::One(a), Self::One(b)) => Rc::ptr_eq(a, b),
281 (Self::Many(a), Self::Many(b)) => Rc::ptr_eq(a, b),
282 _ => false,
283 }
284 }
285}
286
287impl std::ops::Deref for Elements {
288 type Target = [DynModifierElement];
289
290 fn deref(&self) -> &[DynModifierElement] {
291 match self {
292 Self::One(element) => std::slice::from_ref(element),
293 Self::Many(elements) => elements.as_slice(),
294 }
295 }
296}
297
298#[derive(Clone)]
299enum ModifierKind {
300 Empty,
301 Single {
302 elements: Elements,
303 inspector: Option<Rc<[InspectorMetadata]>>,
306 },
307}
308
309const FINGERPRINT_KIND_EMPTY: u8 = 0;
310const FINGERPRINT_KIND_SINGLE: u8 = 1;
311
312const FINGERPRINT_EMPTY_STRICT_SEED: u64 = 0x243f_6a88_85a3_08d3;
313const FINGERPRINT_EMPTY_STRUCTURAL_SEED: u64 = 0x1319_8a2e_0370_7344;
314const FINGERPRINT_SINGLE_STRICT_SEED: u64 = 0xa409_3822_299f_31d0;
315const FINGERPRINT_SINGLE_STRUCTURAL_SEED: u64 = 0x082e_fa98_ec4e_6c89;
316const FINGERPRINT_SEQUENCE_MUL: u64 = 0x9e37_79b1_85eb_ca87;
317const FINGERPRINT_STRICT_UPDATE_TAG: u64 = 0xdbe6_d5d5_fe4c_ce2f;
318const FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG: u64 = 0x94d0_49bb_1331_11eb;
319
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
321struct ModifierFingerprints {
322 strict: u64,
323 structural: u64,
324}
325
326#[inline]
327fn mix_fingerprint_bits(mut value: u64) -> u64 {
328 value ^= value >> 33;
329 value = value.wrapping_mul(0xff51_afd7_ed55_8ccd);
330 value ^= value >> 33;
331 value = value.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
332 value ^ (value >> 33)
333}
334
335#[inline]
336fn fold_fingerprint(state: u64, value: u64) -> u64 {
337 mix_fingerprint_bits(state ^ value.wrapping_add(FINGERPRINT_SEQUENCE_MUL))
338 .wrapping_mul(FINGERPRINT_SEQUENCE_MUL)
339}
340
341#[inline]
342fn empty_fingerprints() -> ModifierFingerprints {
343 ModifierFingerprints {
344 strict: fold_fingerprint(FINGERPRINT_EMPTY_STRICT_SEED, FINGERPRINT_KIND_EMPTY as u64),
345 structural: fold_fingerprint(
346 FINGERPRINT_EMPTY_STRUCTURAL_SEED,
347 FINGERPRINT_KIND_EMPTY as u64,
348 ),
349 }
350}
351
352#[inline]
353fn single_fingerprint_seed() -> ModifierFingerprints {
354 let strict = fold_fingerprint(
355 FINGERPRINT_SINGLE_STRICT_SEED,
356 FINGERPRINT_KIND_SINGLE as u64,
357 );
358 let structural = fold_fingerprint(
359 FINGERPRINT_SINGLE_STRUCTURAL_SEED,
360 FINGERPRINT_KIND_SINGLE as u64,
361 );
362 ModifierFingerprints { strict, structural }
363}
364
365#[inline]
366fn element_common_fingerprint(element: &DynModifierElement) -> u64 {
367 let mut hasher = default::new();
368 element.element_type().hash(&mut hasher);
369 element.capabilities().bits().hash(&mut hasher);
370 hasher.finish()
371}
372
373#[inline]
374fn element_fingerprints(element: &DynModifierElement) -> ModifierFingerprints {
375 let common = element_common_fingerprint(element);
376 let requires_update = element.requires_update();
377 let strict_payload = if requires_update {
378 let element_ptr = Rc::as_ptr(element) as *const () as usize as u64;
379 element_ptr ^ FINGERPRINT_STRICT_UPDATE_TAG
380 } else {
381 element.hash_code()
382 };
383 let strict = mix_fingerprint_bits(common ^ strict_payload);
384
385 let is_draw_only = element.capabilities() == NodeCapabilities::DRAW;
386 let structural_payload = if is_draw_only {
387 FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG
388 } else {
389 element.hash_code()
390 };
391 let structural = mix_fingerprint_bits(common ^ structural_payload);
392
393 ModifierFingerprints { strict, structural }
394}
395
396#[inline]
397fn append_fingerprints(
398 mut fingerprints: ModifierFingerprints,
399 elements: &[DynModifierElement],
400) -> ModifierFingerprints {
401 for element in elements {
402 let element_fingerprints = element_fingerprints(element);
403 fingerprints.strict = fold_fingerprint(fingerprints.strict, element_fingerprints.strict);
404 fingerprints.structural =
405 fold_fingerprint(fingerprints.structural, element_fingerprints.structural);
406 }
407 fingerprints
408}
409
410fn single_fingerprints(elements: &[DynModifierElement]) -> ModifierFingerprints {
411 append_fingerprints(single_fingerprint_seed(), elements)
412}
413
414pub struct ModifierElementIterator<'a> {
415 inner: std::slice::Iter<'a, DynModifierElement>,
416}
417
418impl<'a> Iterator for ModifierElementIterator<'a> {
419 type Item = &'a DynModifierElement;
420
421 #[inline]
422 fn next(&mut self) -> Option<Self::Item> {
423 self.inner.next()
424 }
425
426 #[inline]
427 fn size_hint(&self) -> (usize, Option<usize>) {
428 self.inner.size_hint()
429 }
430}
431
432impl ExactSizeIterator for ModifierElementIterator<'_> {}
433
434pub(crate) struct ModifierInspectorIterator<'a> {
435 inner: std::slice::Iter<'a, InspectorMetadata>,
436}
437
438impl<'a> Iterator for ModifierInspectorIterator<'a> {
439 type Item = &'a InspectorMetadata;
440
441 #[inline]
442 fn next(&mut self) -> Option<Self::Item> {
443 self.inner.next()
444 }
445
446 #[inline]
447 fn size_hint(&self) -> (usize, Option<usize>) {
448 self.inner.size_hint()
449 }
450}
451
452impl ExactSizeIterator for ModifierInspectorIterator<'_> {}
453
454#[derive(Clone)]
472pub struct Modifier {
473 kind: ModifierKind,
474 strict_fingerprint: u64,
475 structural_fingerprint: u64,
476 element_count: usize,
477 provides_composition_locals: bool,
478}
479
480impl Default for Modifier {
481 fn default() -> Self {
482 let fingerprints = empty_fingerprints();
483 Self {
484 kind: ModifierKind::Empty,
485 strict_fingerprint: fingerprints.strict,
486 structural_fingerprint: fingerprints.structural,
487 element_count: 0,
488 provides_composition_locals: false,
489 }
490 }
491}
492
493impl Modifier {
494 pub fn empty() -> Self {
495 Self::default()
496 }
497
498 pub fn from_element<E>(element: E) -> Self
500 where
501 E: ModifierNodeElement,
502 {
503 Self::with_element(element)
504 }
505
506 pub fn clip_to_bounds(self) -> Self {
510 let modifier = crate::thread_state::with(|state| {
511 state
512 .clip_to_bounds
513 .get_or_init(|| Modifier::with_element(ClipToBoundsElement::new()))
514 .clone()
515 });
516 let modifier =
517 modifier.with_inspector_metadata(inspector_metadata("clipToBounds", |info| {
518 info.add_property("clipToBounds", "true");
519 }));
520 self.then(modifier)
521 }
522
523 pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
524 where
525 T: 'static,
526 F: Fn() -> T + 'static,
527 {
528 let element = ModifierLocalProviderElement::new(key, value);
529 let modifier = Modifier::from_parts(&[modifier_element(element)]);
530 self.then(modifier)
531 }
532
533 pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
534 where
535 F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
536 {
537 let element = ModifierLocalConsumerElement::new(consumer);
538 let modifier = Modifier::from_parts(&[modifier_element(element)]);
539 self.then(modifier)
540 }
541
542 pub fn semantics_spec(self, spec: cranpose_foundation::SemanticsSpec) -> Self {
553 self.stable_semantics(move |config: &mut SemanticsConfiguration| config.merge(&spec))
554 }
555
556 pub fn semantics<F>(self, recorder: F) -> Self
561 where
562 F: Fn(&mut SemanticsConfiguration) + 'static,
563 {
564 self.semantics_recorder(std::rc::Rc::new(recorder), true)
565 }
566
567 pub fn stable_semantics<F>(self, recorder: F) -> Self
574 where
575 F: Fn(&mut SemanticsConfiguration) + 'static,
576 {
577 self.semantics_recorder(std::rc::Rc::new(recorder), false)
578 }
579
580 fn semantics_recorder(
581 self,
582 recorder: std::rc::Rc<dyn Fn(&mut SemanticsConfiguration)>,
583 reads_live_state: bool,
584 ) -> Self {
585 let metadata = if inspector_metadata_enabled() {
586 let mut preview = SemanticsConfiguration::default();
587 recorder(&mut preview);
588 let description = preview.content_description.clone();
589 let state_description = preview.state_description.clone();
590 let role = preview.role;
591 let is_clickable = preview.is_activatable();
592 let canvas_children = preview.canvas_children.len();
593 inspector_metadata("semantics", move |info| {
594 if let Some(desc) = &description {
595 info.add_property("contentDescription", desc.clone());
596 }
597 if let Some(state) = &state_description {
598 info.add_property("stateDescription", state.clone());
599 }
600 if let Some(role) = role {
601 info.add_property("role", format!("{role:?}"));
602 }
603 if is_clickable {
604 info.add_property("isClickable", "true");
605 }
606 if canvas_children > 0 {
607 info.add_property("canvasSemanticsChildren", canvas_children.to_string());
608 }
609 })
610 } else {
611 inspector_metadata("semantics", |_| {})
612 };
613 let element = SemanticsElement::new(recorder, reads_live_state);
614 let modifier =
615 Modifier::from_parts(&[modifier_element(element)]).with_inspector_metadata(metadata);
616 self.then(modifier)
617 }
618
619 pub fn progress_semantics(self, current: f32, start: f32, end: f32, steps: u32) -> Self {
628 let info = ProgressBarRangeInfo::new(current, start, end, steps);
629 self.stable_semantics(move |config| config.progress = Some(info))
630 }
631
632 pub fn dropdown_list(self) -> Self {
636 self.role(cranpose_foundation::SemanticsWidgetRole::DropdownList)
637 }
638
639 pub fn value_picker(self) -> Self {
642 self.role(cranpose_foundation::SemanticsWidgetRole::ValuePicker)
643 }
644
645 pub fn expand(self, action: impl Fn() -> bool + 'static) -> Self {
650 let action = cranpose_foundation::SemanticsExpand::new(action);
651 self.stable_semantics(move |config| config.expand = Some(action.clone()))
652 }
653
654 pub fn on_long_click(
664 self,
665 label: impl Into<String>,
666 action: impl Fn() -> bool + 'static,
667 ) -> Self {
668 let label = label.into();
669 let action = cranpose_foundation::SemanticsLongClick::new(action);
670 self.stable_semantics(move |config| {
671 config.on_long_click_label = Some(label.clone());
672 config.on_long_click = Some(action.clone());
673 })
674 }
675
676 pub fn on_magic_tap(
681 self,
682 label: impl Into<String>,
683 action: impl Fn() -> bool + 'static,
684 ) -> Self {
685 let label = label.into();
686 let action = cranpose_foundation::SemanticsMagicTap::new(action);
687 self.stable_semantics(move |config| {
688 config.on_magic_tap_label = Some(label.clone());
689 config.on_magic_tap = Some(action.clone());
690 })
691 }
692
693 pub fn input_labels<S: Into<String>>(self, labels: impl IntoIterator<Item = S>) -> Self {
697 let labels: Vec<String> = labels.into_iter().map(Into::into).collect();
698 self.stable_semantics(move |config| config.input_labels.clone_from(&labels))
699 }
700
701 pub fn language(self, tag: impl Into<String>) -> Self {
705 let tag = tag.into();
706 self.stable_semantics(move |config| config.language = Some(tag.clone()))
707 }
708
709 pub fn collapse(self, action: impl Fn() -> bool + 'static) -> Self {
713 let action = cranpose_foundation::SemanticsExpand::new(action);
714 self.stable_semantics(move |config| config.collapse = Some(action.clone()))
715 }
716
717 pub fn dismiss(self, action: impl Fn() -> bool + 'static) -> Self {
722 let action = cranpose_foundation::SemanticsDismiss::new(action);
723 self.stable_semantics(move |config| config.dismiss = Some(action.clone()))
724 }
725
726 pub fn scroll_to_index(self, action: impl Fn(usize) -> bool + 'static) -> Self {
732 let action = cranpose_foundation::SemanticsScrollToIndex::new(action);
733 self.stable_semantics(move |config| config.scroll_to_index = Some(action.clone()))
734 }
735
736 pub fn traversal_index(self, index: f32) -> Self {
742 self.stable_semantics(move |config| config.traversal_index = index)
743 }
744
745 pub fn password(self) -> Self {
750 self.stable_semantics(|config| config.password = true)
751 }
752
753 pub fn error(self, message: impl Into<String>) -> Self {
757 let message = message.into();
758 self.stable_semantics(move |config| config.error = Some(message.clone()))
759 }
760
761 pub fn pane_title(self, title: impl Into<String>) -> Self {
765 let title = title.into();
766 self.stable_semantics(move |config| config.pane_title = Some(title.clone()))
767 }
768
769 pub fn selectable_group(self) -> Self {
774 self.stable_semantics(|config| config.selectable_group = true)
775 }
776
777 pub fn merge_descendants(self) -> Self {
782 self.stable_semantics(|config| config.merge_descendants = true)
783 }
784
785 pub fn hide_from_accessibility(self) -> Self {
790 self.stable_semantics(|config| config.hidden = true)
791 }
792
793 pub fn heading(self) -> Self {
798 self.role(cranpose_foundation::SemanticsWidgetRole::Header)
799 }
800
801 pub fn role(self, role: cranpose_foundation::SemanticsWidgetRole) -> Self {
806 self.stable_semantics(move |config| config.role = Some(role))
807 }
808
809 pub fn live_region(self, mode: cranpose_foundation::LiveRegionMode) -> Self {
815 self.stable_semantics(move |config| config.live_region = Some(mode))
816 }
817
818 pub fn content_description(self, description: impl Into<String>) -> Self {
823 let description = description.into();
824 self.stable_semantics(move |config| config.content_description = Some(description.clone()))
825 }
826
827 pub fn focus_target(self) -> Self {
833 let element = FocusTargetElement::new();
834 let modifier = Modifier::from_parts(&[modifier_element(element)]);
835 self.then(modifier)
836 }
837
838 pub fn on_focus_changed<F>(self, callback: F) -> Self
843 where
844 F: Fn(FocusState) + 'static,
845 {
846 let element = FocusTargetElement::with_callback(callback);
847 let modifier = Modifier::from_parts(&[modifier_element(element)]);
848 self.then(modifier)
849 }
850
851 pub fn focus_requester(self, requester: &FocusRequester) -> Self {
858 let element = FocusRequesterElement::new(requester.clone());
859 let modifier = Modifier::from_parts(&[modifier_element(element)]);
860 self.then(modifier)
861 }
862
863 pub fn semantics_requester(self, requester: &SemanticsRequester) -> Self {
871 let element = SemanticsRequesterElement::new(requester.clone());
872 let modifier = Modifier::from_parts(&[modifier_element(element)]);
873 self.then(modifier)
874 }
875
876 pub fn debug_chain(self, tag: &'static str) -> Self {
894 use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};
895
896 #[derive(Clone)]
897 struct DebugChainElement {
898 tag: &'static str,
899 }
900
901 impl fmt::Debug for DebugChainElement {
902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 f.debug_struct("DebugChainElement")
904 .field("tag", &self.tag)
905 .finish()
906 }
907 }
908
909 impl PartialEq for DebugChainElement {
910 fn eq(&self, other: &Self) -> bool {
911 self.tag == other.tag
912 }
913 }
914
915 impl Eq for DebugChainElement {}
916
917 impl std::hash::Hash for DebugChainElement {
918 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
919 self.tag.hash(state);
920 }
921 }
922
923 impl ModifierNodeElement for DebugChainElement {
924 type Node = DebugChainNode;
925
926 fn create(&self) -> Self::Node {
927 DebugChainNode::new(self.tag)
928 }
929
930 fn update(&self, node: &mut Self::Node) {
931 node.tag = self.tag;
932 }
933
934 fn capabilities(&self) -> NodeCapabilities {
935 NodeCapabilities::empty()
936 }
937 }
938
939 struct DebugChainNode {
940 tag: &'static str,
941 state: NodeState,
942 }
943
944 impl DebugChainNode {
945 fn new(tag: &'static str) -> Self {
946 Self {
947 tag,
948 state: NodeState::new(),
949 }
950 }
951 }
952
953 impl ModifierNode for DebugChainNode {
954 fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
955 eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
956 }
957
958 fn on_detach(&mut self) {
959 eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
960 }
961
962 fn on_reset(&mut self) {
963 eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
964 }
965 }
966
967 impl cranpose_foundation::DelegatableNode for DebugChainNode {
968 fn node_state(&self) -> &NodeState {
969 &self.state
970 }
971 }
972
973 let element = DebugChainElement { tag };
974 let modifier = Modifier::from_parts(&[modifier_element(element)]);
975 self.then(modifier)
976 .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
977 info.add_property("tag", tag);
978 }))
979 }
980
981 pub fn then(self, next: Modifier) -> Modifier {
987 let Modifier {
988 kind,
989 strict_fingerprint,
990 structural_fingerprint,
991 element_count,
992 provides_composition_locals,
993 } = self;
994 let ModifierKind::Single {
995 mut elements,
996 inspector,
997 } = kind
998 else {
999 return next;
1000 };
1001 let ModifierKind::Single {
1002 elements: next_elements,
1003 inspector: next_inspector,
1004 } = &next.kind
1005 else {
1006 return Modifier {
1007 kind: ModifierKind::Single {
1008 elements,
1009 inspector,
1010 },
1011 strict_fingerprint,
1012 structural_fingerprint,
1013 element_count,
1014 provides_composition_locals,
1015 };
1016 };
1017
1018 let fingerprints = append_fingerprints(
1019 ModifierFingerprints {
1020 strict: strict_fingerprint,
1021 structural: structural_fingerprint,
1022 },
1023 next_elements,
1024 );
1025 elements.extend_from(next_elements);
1026 let inspector = if next_inspector.is_none() {
1027 inspector
1028 } else {
1029 merged_inspector(inspector_slice(&inspector), inspector_slice(next_inspector))
1030 };
1031 Modifier {
1032 kind: ModifierKind::Single {
1033 elements,
1034 inspector,
1035 },
1036 strict_fingerprint: fingerprints.strict,
1037 structural_fingerprint: fingerprints.structural,
1038 element_count: element_count + next.element_count,
1039 provides_composition_locals: provides_composition_locals
1040 || next.provides_composition_locals,
1041 }
1042 }
1043
1044 pub(crate) fn element_count(&self) -> usize {
1046 self.element_count
1047 }
1048
1049 pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
1050 match &self.kind {
1051 ModifierKind::Empty => ModifierElementIterator { inner: [].iter() },
1052 ModifierKind::Single { elements, .. } => ModifierElementIterator {
1053 inner: elements.iter(),
1054 },
1055 }
1056 }
1057
1058 pub(crate) fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
1059 if !self.provides_composition_locals {
1060 return Vec::new();
1061 }
1062 self.iter_elements()
1063 .flat_map(|element| element.provided_composition_locals())
1064 .collect()
1065 }
1066
1067 pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
1068 match &self.kind {
1069 ModifierKind::Empty => ModifierInspectorIterator { inner: [].iter() },
1070 ModifierKind::Single { inspector, .. } => ModifierInspectorIterator {
1071 inner: inspector_slice(inspector).iter(),
1072 },
1073 }
1074 }
1075
1076 #[cfg(test)]
1077 pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
1078 match &self.kind {
1079 ModifierKind::Empty => Vec::new(),
1080 ModifierKind::Single { elements, .. } => elements.to_vec(),
1081 }
1082 }
1083
1084 pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
1085 match &self.kind {
1086 ModifierKind::Empty => Vec::new(),
1087 ModifierKind::Single { inspector, .. } => {
1088 inspector.as_deref().map(<[_]>::to_vec).unwrap_or_default()
1089 }
1090 }
1091 }
1092
1093 pub fn total_padding(&self) -> f32 {
1094 let padding = self.padding_values();
1095 padding
1096 .left
1097 .max(padding.right)
1098 .max(padding.top)
1099 .max(padding.bottom)
1100 }
1101
1102 pub fn explicit_size(&self) -> Option<Size> {
1103 let props = self.layout_properties();
1104 match (props.width, props.height) {
1105 (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
1106 Some(Size { width, height })
1107 }
1108 _ => None,
1109 }
1110 }
1111
1112 pub fn padding_values(&self) -> EdgeInsets {
1113 self.resolved_modifiers().padding()
1114 }
1115
1116 pub(crate) fn layout_properties(&self) -> LayoutProperties {
1117 self.resolved_modifiers().layout_properties()
1118 }
1119
1120 pub fn box_alignment(&self) -> Option<Alignment> {
1121 self.layout_properties().box_alignment()
1122 }
1123
1124 pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
1125 self.layout_properties().column_alignment()
1126 }
1127
1128 pub fn row_alignment(&self) -> Option<VerticalAlignment> {
1129 self.layout_properties().row_alignment()
1130 }
1131
1132 pub fn draw_commands(&self) -> Vec<DrawCommand> {
1133 collect_slices_from_modifier(self).draw_commands().to_vec()
1134 }
1135
1136 pub fn clips_to_bounds(&self) -> bool {
1137 collect_slices_from_modifier(self).clip_to_bounds()
1138 }
1139
1140 pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
1142 self.inspector_metadata()
1143 .iter()
1144 .map(InspectorMetadata::to_record)
1145 .collect()
1146 }
1147
1148 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
1149 let mut handle = ModifierChainHandle::new();
1150 let _ = handle.update(self);
1151 handle.resolved_modifiers()
1152 }
1153
1154 pub fn with_element<E>(element: E) -> Self
1157 where
1158 E: ModifierNodeElement,
1159 {
1160 Self::from_parts(&[modifier_element(element)])
1161 }
1162
1163 pub(crate) fn from_parts(elements: &[DynModifierElement]) -> Self {
1165 if elements.is_empty() {
1166 Self::default()
1167 } else {
1168 let element_count = elements.len();
1169 let provides_composition_locals = elements
1170 .iter()
1171 .any(|element| element.provides_composition_locals());
1172 let fingerprints = single_fingerprints(elements);
1173 Self {
1174 kind: ModifierKind::Single {
1175 elements: Elements::from_slice(elements),
1176 inspector: None,
1177 },
1178 strict_fingerprint: fingerprints.strict,
1179 structural_fingerprint: fingerprints.structural,
1180 element_count,
1181 provides_composition_locals,
1182 }
1183 }
1184 }
1185
1186 pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
1187 if metadata.is_empty() {
1188 return self;
1189 }
1190 match self.kind {
1191 ModifierKind::Empty => self,
1192 ModifierKind::Single {
1193 elements,
1194 inspector,
1195 } => {
1196 let new_inspector = inspector_slice(&inspector)
1197 .iter()
1198 .cloned()
1199 .chain(std::iter::once(metadata))
1200 .collect();
1201 Self {
1202 kind: ModifierKind::Single {
1203 elements,
1204 inspector: Some(new_inspector),
1205 },
1206 strict_fingerprint: self.strict_fingerprint,
1207 structural_fingerprint: self.structural_fingerprint,
1208 element_count: self.element_count,
1209 provides_composition_locals: self.provides_composition_locals,
1210 }
1211 }
1212 }
1213 }
1214
1215 pub fn structural_eq(&self, other: &Self) -> bool {
1220 self.eq_internal(other, false)
1221 }
1222
1223 pub(crate) fn differs_only_in<E: 'static>(&self, other: &Self) -> bool {
1227 if self.element_count != other.element_count {
1228 return false;
1229 }
1230 let differing = std::any::TypeId::of::<E>();
1231 self.iter_elements()
1232 .zip(other.iter_elements())
1233 .all(|(a, b)| {
1234 if a.requires_update() || b.requires_update() {
1235 false
1236 } else if a.element_type() == differing {
1237 b.element_type() == differing
1238 } else {
1239 a.equals_element(&**b)
1240 }
1241 })
1242 }
1243
1244 fn eq_internal(&self, other: &Self, consider_always_update: bool) -> bool {
1245 if self.element_count != other.element_count {
1246 return false;
1247 }
1248 if consider_always_update {
1249 if self.strict_fingerprint != other.strict_fingerprint {
1250 return false;
1251 }
1252 } else if self.structural_fingerprint != other.structural_fingerprint {
1253 return false;
1254 }
1255
1256 match (&self.kind, &other.kind) {
1257 (ModifierKind::Empty, ModifierKind::Empty) => true,
1258 (
1259 ModifierKind::Single {
1260 elements: e1,
1261 inspector: _,
1262 },
1263 ModifierKind::Single {
1264 elements: e2,
1265 inspector: _,
1266 },
1267 ) => {
1268 if e1.shares_storage(e2) {
1269 return true;
1270 }
1271
1272 if e1.len() != e2.len() {
1273 return false;
1274 }
1275
1276 for (a, b) in e1.iter().zip(e2.iter()) {
1277 if !consider_always_update
1278 && a.element_type() == b.element_type()
1279 && a.capabilities() == NodeCapabilities::DRAW
1280 && b.capabilities() == NodeCapabilities::DRAW
1281 {
1282 continue;
1283 }
1284
1285 if consider_always_update && (a.requires_update() || b.requires_update()) {
1286 if !Rc::ptr_eq(a, b) {
1287 return false;
1288 }
1289 continue;
1290 }
1291
1292 if !a.equals_element(&**b) {
1293 return false;
1294 }
1295 }
1296
1297 true
1298 }
1299 _ => false,
1300 }
1301 }
1302}
1303
1304impl PartialEq for Modifier {
1305 fn eq(&self, other: &Self) -> bool {
1306 self.eq_internal(other, true)
1307 }
1308}
1309
1310impl Eq for Modifier {}
1311
1312impl fmt::Display for Modifier {
1313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1314 match &self.kind {
1315 ModifierKind::Empty => write!(f, "Modifier.empty"),
1316 ModifierKind::Single { elements, .. } => {
1317 if elements.is_empty() {
1318 return write!(f, "Modifier.empty");
1319 }
1320 write!(f, "Modifier[")?;
1321 for (index, element) in elements.iter().enumerate() {
1322 if index > 0 {
1323 write!(f, ", ")?;
1324 }
1325 let name = element.inspector_name();
1326 let mut properties = Vec::new();
1327 element.record_inspector_properties(&mut |prop, value| {
1328 properties.push(format!("{prop}={value}"));
1329 });
1330 if properties.is_empty() {
1331 write!(f, "{name}")?;
1332 } else {
1333 write!(f, "{name}({})", properties.join(", "))?;
1334 }
1335 }
1336 write!(f, "]")
1337 }
1338 }
1339 }
1340}
1341
1342impl fmt::Debug for Modifier {
1343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1344 fmt::Display::fmt(self, f)
1345 }
1346}
1347
1348#[derive(Clone, Copy, Debug, PartialEq)]
1349pub struct ResolvedBackground {
1350 color: Color,
1351 shape: Option<RoundedCornerShape>,
1352}
1353
1354impl ResolvedBackground {
1355 pub fn new(color: Color, shape: Option<RoundedCornerShape>) -> Self {
1356 Self { color, shape }
1357 }
1358
1359 pub fn color(&self) -> Color {
1360 self.color
1361 }
1362
1363 pub fn shape(&self) -> Option<RoundedCornerShape> {
1364 self.shape
1365 }
1366
1367 pub fn set_shape(&mut self, shape: Option<RoundedCornerShape>) {
1368 self.shape = shape;
1369 }
1370}
1371
1372#[derive(Clone, Copy, Debug, PartialEq, Default)]
1373pub struct ResolvedModifiers {
1374 padding: EdgeInsets,
1375 layout: LayoutProperties,
1376 offset: Point,
1377}
1378
1379impl ResolvedModifiers {
1380 pub fn padding(&self) -> EdgeInsets {
1381 self.padding
1382 }
1383
1384 pub fn layout_properties(&self) -> LayoutProperties {
1385 self.layout
1386 }
1387
1388 pub fn offset(&self) -> Point {
1389 self.offset
1390 }
1391
1392 pub(crate) fn set_padding(&mut self, padding: EdgeInsets) {
1393 self.padding = padding;
1394 }
1395
1396 pub(crate) fn set_layout_properties(&mut self, layout: LayoutProperties) {
1397 self.layout = layout;
1398 }
1399
1400 pub(crate) fn set_offset(&mut self, offset: Point) {
1401 self.offset = offset;
1402 }
1403
1404 pub(crate) fn on_device_grid(&self, density: f32) -> Self {
1407 use cranpose_ui_layout::round_to_px;
1408
1409 let round = |value: Option<f32>| value.map(|value| round_to_px(value, density));
1410 let dimension = |dimension: DimensionConstraint| match dimension {
1411 DimensionConstraint::Points(value) => {
1412 DimensionConstraint::Points(round_to_px(value, density))
1413 }
1414 other => other,
1415 };
1416 Self {
1417 padding: crate::modifier_nodes::device_padding(self.padding, density),
1418 layout: LayoutProperties {
1419 padding: crate::modifier_nodes::device_padding(self.layout.padding, density),
1420 width: dimension(self.layout.width),
1421 height: dimension(self.layout.height),
1422 min_width: round(self.layout.min_width),
1423 min_height: round(self.layout.min_height),
1424 max_width: round(self.layout.max_width),
1425 max_height: round(self.layout.max_height),
1426 ..self.layout
1427 },
1428 offset: Point {
1429 x: round_to_px(self.offset.x, density),
1430 y: round_to_px(self.offset.y, density),
1431 },
1432 }
1433 }
1434}
1435
1436#[derive(Clone, Copy, Debug, Default, PartialEq)]
1437pub enum DimensionConstraint {
1438 #[default]
1439 Unspecified,
1440 Points(f32),
1441 Fraction(f32),
1442 Intrinsic(IntrinsicSize),
1443}
1444
1445#[derive(Clone, Copy, Debug, Default, PartialEq)]
1446pub struct LayoutWeight {
1447 pub weight: f32,
1448 pub fill: bool,
1449}
1450
1451#[derive(Clone, Copy, Debug, Default, PartialEq)]
1452pub struct LayoutProperties {
1453 padding: EdgeInsets,
1454 width: DimensionConstraint,
1455 height: DimensionConstraint,
1456 min_width: Option<f32>,
1457 min_height: Option<f32>,
1458 max_width: Option<f32>,
1459 max_height: Option<f32>,
1460 weight: Option<LayoutWeight>,
1461 box_alignment: Option<Alignment>,
1462 column_alignment: Option<HorizontalAlignment>,
1463 row_alignment: Option<VerticalAlignment>,
1464 row_baseline: bool,
1465}
1466
1467impl LayoutProperties {
1468 pub fn padding(&self) -> EdgeInsets {
1469 self.padding
1470 }
1471
1472 pub fn width(&self) -> DimensionConstraint {
1473 self.width
1474 }
1475
1476 pub fn height(&self) -> DimensionConstraint {
1477 self.height
1478 }
1479
1480 pub fn min_width(&self) -> Option<f32> {
1481 self.min_width
1482 }
1483
1484 pub fn min_height(&self) -> Option<f32> {
1485 self.min_height
1486 }
1487
1488 pub fn max_width(&self) -> Option<f32> {
1489 self.max_width
1490 }
1491
1492 pub fn max_height(&self) -> Option<f32> {
1493 self.max_height
1494 }
1495
1496 pub fn weight(&self) -> Option<LayoutWeight> {
1497 self.weight
1498 }
1499
1500 pub fn box_alignment(&self) -> Option<Alignment> {
1501 self.box_alignment
1502 }
1503
1504 pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
1505 self.column_alignment
1506 }
1507
1508 pub fn row_alignment(&self) -> Option<VerticalAlignment> {
1509 self.row_alignment
1510 }
1511
1512 pub fn row_baseline(&self) -> bool {
1514 self.row_baseline
1515 }
1516}
1517
1518#[cfg(test)]
1519#[path = "tests/modifier_tests.rs"]
1520mod tests;