Skip to main content

cranpose_ui/modifier_nodes/
offset.rs

1// The offset modifiers, by points and by fractions of the content's size:
2// their elements.
3
4use cranpose_foundation::{
5    Constraints, InvalidationKind, Measurable, ModifierNodeContext, NodeCapabilities, PlainElement,
6    PlainLayout, PlainLayoutFns, PrepareAt, Size,
7};
8use cranpose_ui_layout::{LayoutDirection, round_to_px};
9
10use super::measure_pass_through;
11use crate::modifier::Point;
12
13/// Element that offsets its content by a fixed (x, y) amount.
14///
15/// Matches Kotlin: `OffsetElement` in foundation-layout/src/commonMain/kotlin/androidx/compose/foundation/layout/Offset.kt
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct OffsetElement {
18    x: f32,
19    y: f32,
20    flags: u32,
21}
22
23// A right-to-left layout direction mirrors `x`.
24const RTL_AWARE: u32 = 1;
25// A coordinator mirrored the offset for its direction and put it on the
26// device pixels of its density already: see `PlainLayout::prepared`.
27const PLACED: u32 = 1 << 1;
28
29impl OffsetElement {
30    /// Creates an element that moves content by `x` and `y`, in logical pixels. With `rtl_aware`
31    /// set, a right-to-left layout direction mirrors `x`.
32    pub fn new(x: f32, y: f32, rtl_aware: bool) -> Self {
33        Self {
34            x,
35            y,
36            flags: if rtl_aware { RTL_AWARE } else { 0 },
37        }
38    }
39
40    /// Returns the offset in logical pixels as a layout of `direction` applies it: `x` mirrored
41    /// when the element is RTL aware and the direction is right-to-left.
42    pub fn offset(&self, direction: LayoutDirection) -> Point {
43        Point {
44            x: if self.rtl_aware() && direction.is_rtl() {
45                -self.x
46            } else {
47                self.x
48            },
49            y: self.y,
50        }
51    }
52
53    /// Returns whether a right-to-left layout direction mirrors `x`.
54    pub fn rtl_aware(&self) -> bool {
55        self.flags & RTL_AWARE != 0
56    }
57
58    // Where the element places its content: on a whole device pixel of
59    // `at`'s density, where Compose's `OffsetNode` places it.
60    pub(crate) fn placed(&self, at: PrepareAt) -> Point {
61        if self.flags & PLACED != 0 {
62            return Point {
63                x: self.x,
64                y: self.y,
65            };
66        }
67        let offset = self.offset(at.direction);
68        Point {
69            x: round_to_px(offset.x, at.density),
70            y: round_to_px(offset.y, at.density),
71        }
72    }
73
74    #[inline]
75    pub(crate) fn placed_prepared(&self) -> Point {
76        Point {
77            x: self.x,
78            y: self.y,
79        }
80    }
81}
82
83impl PlainElement for OffsetElement {
84    const WORDS: usize = 3;
85    const CAPABILITIES: NodeCapabilities = NodeCapabilities::LAYOUT;
86    const UPDATE_INVALIDATION: Option<InvalidationKind> = Some(InvalidationKind::Layout);
87    const LAYOUT: Option<&'static PlainLayoutFns> = Some(&PlainLayoutFns::of::<Self>());
88
89    #[inline]
90    fn to_words(&self, words: &mut [u32]) {
91        words.copy_from_slice(&[self.x.to_bits(), self.y.to_bits(), self.flags]);
92    }
93
94    #[inline]
95    fn from_words(words: &[u32]) -> Self {
96        match *words {
97            [x, y, flags, ..] => Self {
98                x: f32::from_bits(x),
99                y: f32::from_bits(y),
100                flags,
101            },
102            _ => Self::new(0.0, 0.0, false),
103        }
104    }
105}
106
107impl PlainLayout for OffsetElement {
108    const PREPARES: bool = true;
109
110    fn prepared(self, at: PrepareAt) -> Self {
111        let Point { x, y } = self.placed(at);
112        Self {
113            x,
114            y,
115            flags: PLACED,
116        }
117    }
118
119    fn measure_hold(
120        &self,
121        _density: f32,
122        _constraints: Constraints,
123        _size: Size,
124        wrapped: cranpose_ui_layout::WrappedHold,
125    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
126        wrapped.hold
127    }
128
129    fn measure(
130        &self,
131        context: &mut dyn ModifierNodeContext,
132        measurable: &dyn Measurable,
133        constraints: Constraints,
134    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
135        // An element no coordinator prepared knows no direction.
136        let offset = self.placed(PrepareAt {
137            density: context.density(),
138            direction: LayoutDirection::Ltr,
139        });
140        measure_pass_through(measurable, constraints, |_| (offset.x, offset.y))
141    }
142}
143
144/// Element that offsets its content by a fraction of its own measured size.
145///
146/// There is no direct Jetpack Compose modifier equivalent; Compose's slide
147/// transitions receive the measured size through a lambda instead. This
148/// element backs `slide_in_vertically` / `slide_out_vertically` in
149/// `AnimatedVisibility`, where the offset is expressed as a fraction of the
150/// content height.
151#[derive(Debug, Clone, Copy, PartialEq)]
152pub struct FractionalOffsetElement {
153    x_fraction: f32,
154    y_fraction: f32,
155}
156
157impl FractionalOffsetElement {
158    /// Creates an element that moves its content by `x_fraction` of its own width and
159    /// `y_fraction` of its own height.
160    pub fn new(x_fraction: f32, y_fraction: f32) -> Self {
161        Self {
162            x_fraction,
163            y_fraction,
164        }
165    }
166
167    #[inline]
168    pub(crate) fn offset_for(self, size: Size) -> Point {
169        Point {
170            x: self.x_fraction * size.width,
171            y: self.y_fraction * size.height,
172        }
173    }
174}
175
176impl PlainElement for FractionalOffsetElement {
177    const WORDS: usize = 2;
178    const CAPABILITIES: NodeCapabilities = NodeCapabilities::LAYOUT;
179    const UPDATE_INVALIDATION: Option<InvalidationKind> = Some(InvalidationKind::Layout);
180    const LAYOUT: Option<&'static PlainLayoutFns> = Some(&PlainLayoutFns::of::<Self>());
181
182    #[inline]
183    fn to_words(&self, words: &mut [u32]) {
184        words.copy_from_slice(&[self.x_fraction.to_bits(), self.y_fraction.to_bits()]);
185    }
186
187    #[inline]
188    fn from_words(words: &[u32]) -> Self {
189        match *words {
190            [x, y, ..] => Self::new(f32::from_bits(x), f32::from_bits(y)),
191            _ => Self::new(0.0, 0.0),
192        }
193    }
194}
195
196impl PlainLayout for FractionalOffsetElement {
197    fn measure_hold(
198        &self,
199        _density: f32,
200        _constraints: Constraints,
201        _size: Size,
202        wrapped: cranpose_ui_layout::WrappedHold,
203    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
204        wrapped.hold
205    }
206
207    fn measure(
208        &self,
209        _context: &mut dyn ModifierNodeContext,
210        measurable: &dyn Measurable,
211        constraints: Constraints,
212    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
213        measure_pass_through(measurable, constraints, |size| {
214            (self.x_fraction * size.width, self.y_fraction * size.height)
215        })
216    }
217}