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