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, px,
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 client_inset = window.client_inset.unwrap_or(px(0.));
179 let edges = match self.fit_mode {
180 AnchoredFitMode::SnapToWindowWithMargin(edges) => edges,
181 _ => Edges::default(),
182 }
183 .map(|edge| *edge + client_inset);
184
185 // Snap the horizontal edges of the anchored element to the horizontal edges of the window if
186 // its horizontal bounds overflow, aligning to the left if it is wider than the limits.
187 if desired.right() > limits.right() {
188 desired.origin.x -= desired.right() - limits.right() + edges.right;
189 }
190 if desired.left() < limits.left() {
191 desired.origin.x = limits.origin.x + edges.left;
192 }
193
194 // Snap the vertical edges of the anchored element to the vertical edges of the window if
195 // its vertical bounds overflow, aligning to the top if it is taller than the limits.
196 if desired.bottom() > limits.bottom() {
197 desired.origin.y -= desired.bottom() - limits.bottom() + edges.bottom;
198 }
199 if desired.top() < limits.top() {
200 desired.origin.y = limits.origin.y + edges.top;
201 }
202
203 let offset = desired.origin - bounds.origin;
204 let offset = point(offset.x.round(), offset.y.round());
205
206 window.with_element_offset(offset, |window| {
207 for child in &mut self.children {
208 child.prepaint(window, cx);
209 }
210 })
211 }
212
213 fn paint(
214 &mut self,
215 _id: Option<&GlobalElementId>,
216 _bounds: crate::Bounds<crate::Pixels>,
217 _request_layout: &mut Self::RequestLayoutState,
218 _prepaint: &mut Self::PrepaintState,
219 window: &mut Window,
220 cx: &mut App,
221 ) {
222 for child in &mut self.children {
223 child.paint(window, cx);
224 }
225 }
226}
227
228impl IntoElement for Anchored {
229 type Element = Self;
230
231 fn into_element(self) -> Self::Element {
232 self
233 }
234}
235
236/// Which algorithm to use when fitting the anchored element to be inside the window.
237#[derive(Copy, Clone, PartialEq)]
238pub enum AnchoredFitMode {
239 /// Snap the anchored element to the window edge.
240 SnapToWindow,
241 /// Snap to window edge and leave some margins.
242 SnapToWindowWithMargin(Edges<Pixels>),
243 /// Switch which corner anchor this anchored element is attached to.
244 SwitchAnchor,
245}
246
247/// Which algorithm to use when positioning the anchored element.
248#[derive(Copy, Clone, PartialEq)]
249pub enum AnchoredPositionMode {
250 /// Position the anchored element relative to the window.
251 Window,
252 /// Position the anchored element relative to its parent.
253 Local,
254}
255
256impl AnchoredPositionMode {
257 fn get_position_and_bounds(
258 &self,
259 anchor_position: Option<Point<Pixels>>,
260 anchor_corner: Corner,
261 size: Size<Pixels>,
262 bounds: Bounds<Pixels>,
263 offset: Option<Point<Pixels>>,
264 ) -> (Point<Pixels>, Bounds<Pixels>) {
265 let offset = offset.unwrap_or_default();
266
267 match self {
268 AnchoredPositionMode::Window => {
269 let anchor_position = anchor_position.unwrap_or(bounds.origin);
270 let bounds =
271 Bounds::from_corner_and_size(anchor_corner, anchor_position + offset, size);
272 (anchor_position, bounds)
273 }
274 AnchoredPositionMode::Local => {
275 let anchor_position = anchor_position.unwrap_or_default();
276 let bounds = Bounds::from_corner_and_size(
277 anchor_corner,
278 bounds.origin + anchor_position + offset,
279 size,
280 );
281 (anchor_position, bounds)
282 }
283 }
284 }
285}