1use smallvec::SmallVec;
2use taffy::style::{Display, Position};
3
4use crate::{
5 point, AnyElement, Bounds, Element, ElementContext, IntoElement, LayoutId, ParentElement,
6 Pixels, Point, Size, Style,
7};
8
9/// The state that the anchored element element uses to track its children.
10pub struct AnchoredState {
11 child_layout_ids: SmallVec<[LayoutId; 4]>,
12}
13
14/// An anchored element that can be used to display UI that
15/// will avoid overflowing the window bounds.
16pub struct Anchored {
17 children: SmallVec<[AnyElement; 2]>,
18 anchor_corner: AnchorCorner,
19 fit_mode: AnchoredFitMode,
20 anchor_position: Option<Point<Pixels>>,
21 position_mode: AnchoredPositionMode,
22}
23
24/// anchored gives you an element that will avoid overflowing the window bounds.
25/// Its children should have no margin to avoid measurement issues.
26pub fn anchored() -> Anchored {
27 Anchored {
28 children: SmallVec::new(),
29 anchor_corner: AnchorCorner::TopLeft,
30 fit_mode: AnchoredFitMode::SwitchAnchor,
31 anchor_position: None,
32 position_mode: AnchoredPositionMode::Window,
33 }
34}
35
36impl Anchored {
37 /// Sets which corner of the anchored element should be anchored to the current position.
38 pub fn anchor(mut self, anchor: AnchorCorner) -> Self {
39 self.anchor_corner = anchor;
40 self
41 }
42
43 /// Sets the position in window coordinates
44 /// (otherwise the location the anchored element is rendered is used)
45 pub fn position(mut self, anchor: Point<Pixels>) -> Self {
46 self.anchor_position = Some(anchor);
47 self
48 }
49
50 /// Sets the position mode for this anchored element. Local will have this
51 /// interpret its [`Anchored::position`] as relative to the parent element.
52 /// While Window will have it interpret the position as relative to the window.
53 pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
54 self.position_mode = mode;
55 self
56 }
57
58 /// Snap to window edge instead of switching anchor corner when an overflow would occur.
59 pub fn snap_to_window(mut self) -> Self {
60 self.fit_mode = AnchoredFitMode::SnapToWindow;
61 self
62 }
63}
64
65impl ParentElement for Anchored {
66 fn extend(&mut self, elements: impl Iterator<Item = AnyElement>) {
67 self.children.extend(elements)
68 }
69}
70
71impl Element for Anchored {
72 type BeforeLayout = AnchoredState;
73 type AfterLayout = ();
74
75 fn before_layout(&mut self, cx: &mut ElementContext) -> (crate::LayoutId, Self::BeforeLayout) {
76 let child_layout_ids = self
77 .children
78 .iter_mut()
79 .map(|child| child.before_layout(cx))
80 .collect::<SmallVec<_>>();
81
82 let anchored_style = Style {
83 position: Position::Absolute,
84 display: Display::Flex,
85 ..Style::default()
86 };
87
88 let layout_id = cx.request_layout(&anchored_style, child_layout_ids.iter().copied());
89
90 (layout_id, AnchoredState { child_layout_ids })
91 }
92
93 fn after_layout(
94 &mut self,
95 bounds: Bounds<Pixels>,
96 before_layout: &mut Self::BeforeLayout,
97 cx: &mut ElementContext,
98 ) {
99 if before_layout.child_layout_ids.is_empty() {
100 return;
101 }
102
103 let mut child_min = point(Pixels::MAX, Pixels::MAX);
104 let mut child_max = Point::default();
105 for child_layout_id in &before_layout.child_layout_ids {
106 let child_bounds = cx.layout_bounds(*child_layout_id);
107 child_min = child_min.min(&child_bounds.origin);
108 child_max = child_max.max(&child_bounds.lower_right());
109 }
110 let size: Size<Pixels> = (child_max - child_min).into();
111
112 let (origin, mut desired) = self.position_mode.get_position_and_bounds(
113 self.anchor_position,
114 self.anchor_corner,
115 size,
116 bounds,
117 );
118
119 let limits = Bounds {
120 origin: Point::default(),
121 size: cx.viewport_size(),
122 };
123
124 if self.fit_mode == AnchoredFitMode::SwitchAnchor {
125 let mut anchor_corner = self.anchor_corner;
126
127 if desired.left() < limits.left() || desired.right() > limits.right() {
128 let switched = anchor_corner
129 .switch_axis(Axis::Horizontal)
130 .get_bounds(origin, size);
131 if !(switched.left() < limits.left() || switched.right() > limits.right()) {
132 anchor_corner = anchor_corner.switch_axis(Axis::Horizontal);
133 desired = switched
134 }
135 }
136
137 if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
138 let switched = anchor_corner
139 .switch_axis(Axis::Vertical)
140 .get_bounds(origin, size);
141 if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
142 desired = switched;
143 }
144 }
145 }
146
147 // Snap the horizontal edges of the anchored element to the horizontal edges of the window if
148 // its horizontal bounds overflow, aligning to the left if it is wider than the limits.
149 if desired.right() > limits.right() {
150 desired.origin.x -= desired.right() - limits.right();
151 }
152 if desired.left() < limits.left() {
153 desired.origin.x = limits.origin.x;
154 }
155
156 // Snap the vertical edges of the anchored element to the vertical edges of the window if
157 // its vertical bounds overflow, aligning to the top if it is taller than the limits.
158 if desired.bottom() > limits.bottom() {
159 desired.origin.y -= desired.bottom() - limits.bottom();
160 }
161 if desired.top() < limits.top() {
162 desired.origin.y = limits.origin.y;
163 }
164
165 let offset = desired.origin - bounds.origin;
166 let offset = point(offset.x.round(), offset.y.round());
167
168 cx.with_element_offset(offset, |cx| {
169 for child in &mut self.children {
170 child.after_layout(cx);
171 }
172 })
173 }
174
175 fn paint(
176 &mut self,
177 _bounds: crate::Bounds<crate::Pixels>,
178 _before_layout: &mut Self::BeforeLayout,
179 _after_layout: &mut Self::AfterLayout,
180 cx: &mut ElementContext,
181 ) {
182 for child in &mut self.children {
183 child.paint(cx);
184 }
185 }
186}
187
188impl IntoElement for Anchored {
189 type Element = Self;
190
191 fn into_element(self) -> Self::Element {
192 self
193 }
194}
195
196enum Axis {
197 Horizontal,
198 Vertical,
199}
200
201/// Which algorithm to use when fitting the anchored element to be inside the window.
202#[derive(Copy, Clone, PartialEq)]
203pub enum AnchoredFitMode {
204 /// Snap the anchored element to the window edge
205 SnapToWindow,
206 /// Switch which corner anchor this anchored element is attached to
207 SwitchAnchor,
208}
209
210/// Which algorithm to use when positioning the anchored element.
211#[derive(Copy, Clone, PartialEq)]
212pub enum AnchoredPositionMode {
213 /// Position the anchored element relative to the window
214 Window,
215 /// Position the anchored element relative to its parent
216 Local,
217}
218
219impl AnchoredPositionMode {
220 fn get_position_and_bounds(
221 &self,
222 anchor_position: Option<Point<Pixels>>,
223 anchor_corner: AnchorCorner,
224 size: Size<Pixels>,
225 bounds: Bounds<Pixels>,
226 ) -> (Point<Pixels>, Bounds<Pixels>) {
227 match self {
228 AnchoredPositionMode::Window => {
229 let anchor_position = anchor_position.unwrap_or(bounds.origin);
230 let bounds = anchor_corner.get_bounds(anchor_position, size);
231 (anchor_position, bounds)
232 }
233 AnchoredPositionMode::Local => {
234 let anchor_position = anchor_position.unwrap_or_default();
235 let bounds = anchor_corner.get_bounds(bounds.origin + anchor_position, size);
236 (anchor_position, bounds)
237 }
238 }
239 }
240}
241
242/// Which corner of the anchored element should be considered the anchor.
243#[derive(Clone, Copy, PartialEq, Eq)]
244pub enum AnchorCorner {
245 /// The top left corner
246 TopLeft,
247 /// The top right corner
248 TopRight,
249 /// The bottom left corner
250 BottomLeft,
251 /// The bottom right corner
252 BottomRight,
253}
254
255impl AnchorCorner {
256 fn get_bounds(&self, origin: Point<Pixels>, size: Size<Pixels>) -> Bounds<Pixels> {
257 let origin = match self {
258 Self::TopLeft => origin,
259 Self::TopRight => Point {
260 x: origin.x - size.width,
261 y: origin.y,
262 },
263 Self::BottomLeft => Point {
264 x: origin.x,
265 y: origin.y - size.height,
266 },
267 Self::BottomRight => Point {
268 x: origin.x - size.width,
269 y: origin.y - size.height,
270 },
271 };
272
273 Bounds { origin, size }
274 }
275
276 /// Get the point corresponding to this anchor corner in `bounds`.
277 pub fn corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
278 match self {
279 Self::TopLeft => bounds.origin,
280 Self::TopRight => bounds.upper_right(),
281 Self::BottomLeft => bounds.lower_left(),
282 Self::BottomRight => bounds.lower_right(),
283 }
284 }
285
286 fn switch_axis(self, axis: Axis) -> Self {
287 match axis {
288 Axis::Vertical => match self {
289 AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
290 AnchorCorner::TopRight => AnchorCorner::BottomRight,
291 AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
292 AnchorCorner::BottomRight => AnchorCorner::TopRight,
293 },
294 Axis::Horizontal => match self {
295 AnchorCorner::TopLeft => AnchorCorner::TopRight,
296 AnchorCorner::TopRight => AnchorCorner::TopLeft,
297 AnchorCorner::BottomLeft => AnchorCorner::BottomRight,
298 AnchorCorner::BottomRight => AnchorCorner::BottomLeft,
299 },
300 }
301 }
302}