1use smallvec::SmallVec;
2use taffy::style::{Display, Position};
3
4use crate::{
5 AnyElement, App, Axis, Bounds, Corner, Edges, Element, GlobalElementId, IntoElement, LayoutId,
6 ParentElement, Pixels, Point, Size, Style, Window, point,
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 window: &mut Window,
98 cx: &mut App,
99 ) -> (crate::LayoutId, Self::RequestLayoutState) {
100 let child_layout_ids = self
101 .children
102 .iter_mut()
103 .map(|child| child.request_layout(window, cx))
104 .collect::<SmallVec<_>>();
105
106 let anchored_style = Style {
107 position: Position::Absolute,
108 display: Display::Flex,
109 ..Style::default()
110 };
111
112 let layout_id = window.request_layout(anchored_style, child_layout_ids.iter().copied(), cx);
113
114 (layout_id, AnchoredState { child_layout_ids })
115 }
116
117 fn prepaint(
118 &mut self,
119 _id: Option<&GlobalElementId>,
120 bounds: Bounds<Pixels>,
121 request_layout: &mut Self::RequestLayoutState,
122 window: &mut Window,
123 cx: &mut App,
124 ) {
125 if request_layout.child_layout_ids.is_empty() {
126 return;
127 }
128
129 let mut child_min = point(Pixels::MAX, Pixels::MAX);
130 let mut child_max = Point::default();
131 for child_layout_id in &request_layout.child_layout_ids {
132 let child_bounds = window.layout_bounds(*child_layout_id);
133 child_min = child_min.min(&child_bounds.origin);
134 child_max = child_max.max(&child_bounds.bottom_right());
135 }
136 let size: Size<Pixels> = (child_max - child_min).into();
137
138 let (origin, mut desired) = self.position_mode.get_position_and_bounds(
139 self.anchor_position,
140 self.anchor_corner,
141 size,
142 bounds,
143 self.offset,
144 );
145
146 let limits = Bounds {
147 origin: Point::default(),
148 size: window.viewport_size(),
149 };
150
151 if self.fit_mode == AnchoredFitMode::SwitchAnchor {
152 let mut anchor_corner = self.anchor_corner;
153
154 if desired.left() < limits.left() || desired.right() > limits.right() {
155 let switched = Bounds::from_corner_and_size(
156 anchor_corner.other_side_corner_along(Axis::Horizontal),
157 origin,
158 size,
159 );
160 if !(switched.left() < limits.left() || switched.right() > limits.right()) {
161 anchor_corner = anchor_corner.other_side_corner_along(Axis::Horizontal);
162 desired = switched
163 }
164 }
165
166 if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
167 let switched = Bounds::from_corner_and_size(
168 anchor_corner.other_side_corner_along(Axis::Vertical),
169 origin,
170 size,
171 );
172 if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
173 desired = switched;
174 }
175 }
176 }
177
178 let edges = match self.fit_mode {
179 AnchoredFitMode::SnapToWindowWithMargin(edges) => edges,
180 _ => Edges::default(),
181 };
182
183 // Snap the horizontal edges of the anchored element to the horizontal edges of the window if
184 // its horizontal bounds overflow, aligning to the left if it is wider than the limits.
185 if desired.right() > limits.right() {
186 desired.origin.x -= desired.right() - limits.right() + edges.right;
187 }
188 if desired.left() < limits.left() {
189 desired.origin.x = limits.origin.x + edges.left;
190 }
191
192 // Snap the vertical edges of the anchored element to the vertical edges of the window if
193 // its vertical bounds overflow, aligning to the top if it is taller than the limits.
194 if desired.bottom() > limits.bottom() {
195 desired.origin.y -= desired.bottom() - limits.bottom() + edges.bottom;
196 }
197 if desired.top() < limits.top() {
198 desired.origin.y = limits.origin.y + edges.top;
199 }
200
201 let offset = desired.origin - bounds.origin;
202 let offset = point(offset.x.round(), offset.y.round());
203
204 window.with_element_offset(offset, |window| {
205 for child in &mut self.children {
206 child.prepaint(window, cx);
207 }
208 })
209 }
210
211 fn paint(
212 &mut self,
213 _id: Option<&GlobalElementId>,
214 _bounds: crate::Bounds<crate::Pixels>,
215 _request_layout: &mut Self::RequestLayoutState,
216 _prepaint: &mut Self::PrepaintState,
217 window: &mut Window,
218 cx: &mut App,
219 ) {
220 for child in &mut self.children {
221 child.paint(window, cx);
222 }
223 }
224}
225
226impl IntoElement for Anchored {
227 type Element = Self;
228
229 fn into_element(self) -> Self::Element {
230 self
231 }
232}
233
234/// Which algorithm to use when fitting the anchored element to be inside the window.
235#[derive(Copy, Clone, PartialEq)]
236pub enum AnchoredFitMode {
237 /// Snap the anchored element to the window edge.
238 SnapToWindow,
239 /// Snap to window edge and leave some margins.
240 SnapToWindowWithMargin(Edges<Pixels>),
241 /// Switch which corner anchor this anchored element is attached to.
242 SwitchAnchor,
243}
244
245/// Which algorithm to use when positioning the anchored element.
246#[derive(Copy, Clone, PartialEq)]
247pub enum AnchoredPositionMode {
248 /// Position the anchored element relative to the window.
249 Window,
250 /// Position the anchored element relative to its parent.
251 Local,
252}
253
254impl AnchoredPositionMode {
255 fn get_position_and_bounds(
256 &self,
257 anchor_position: Option<Point<Pixels>>,
258 anchor_corner: Corner,
259 size: Size<Pixels>,
260 bounds: Bounds<Pixels>,
261 offset: Option<Point<Pixels>>,
262 ) -> (Point<Pixels>, Bounds<Pixels>) {
263 let offset = offset.unwrap_or_default();
264
265 match self {
266 AnchoredPositionMode::Window => {
267 let anchor_position = anchor_position.unwrap_or(bounds.origin);
268 let bounds =
269 Bounds::from_corner_and_size(anchor_corner, anchor_position + offset, size);
270 (anchor_position, bounds)
271 }
272 AnchoredPositionMode::Local => {
273 let anchor_position = anchor_position.unwrap_or_default();
274 let bounds = Bounds::from_corner_and_size(
275 anchor_corner,
276 bounds.origin + anchor_position + offset,
277 size,
278 );
279 (anchor_position, bounds)
280 }
281 }
282 }
283}