1use std::cmp::Ordering;
3
4use smallvec::SmallVec;
5
6use crate::{
7 Anchor, AnyElement, App, Axis, Bounds, Display, Edges, Element, GlobalElementId,
8 InspectorElementId, IntoElement, LayoutId, ParentElement, Pixels, Point, Position, Size, Style,
9 Window, point, px,
10};
11
12pub struct AnchoredState {
14 child_layout_ids: SmallVec<[LayoutId; 4]>,
15}
16
17pub struct Anchored {
20 children: SmallVec<[AnyElement; 2]>,
21 anchor: Anchor,
22 fit_mode: AnchoredFitMode,
23 placement: Placement,
24 position_mode: AnchoredPositionMode,
25 offset: Option<Point<Pixels>>,
26}
27
28#[derive(Clone, Copy)]
29enum Placement {
30 InPlace,
31 At(Point<Pixels>),
32 Attached {
33 target: Bounds<Pixels>,
34 corner: Anchor,
35 },
36}
37
38pub fn anchored() -> Anchored {
41 Anchored {
42 children: SmallVec::new(),
43 anchor: Anchor::TopLeft,
44 fit_mode: AnchoredFitMode::SwitchAnchor,
45 placement: Placement::InPlace,
46 position_mode: AnchoredPositionMode::Window,
47 offset: None,
48 }
49}
50
51impl Anchored {
52 pub fn anchor(mut self, anchor: Anchor) -> Self {
54 self.anchor = anchor;
55 self
56 }
57
58 pub fn position(mut self, anchor: Point<Pixels>) -> Self {
61 self.placement = Placement::At(anchor);
62 self
63 }
64
65 pub fn attach(mut self, target: Bounds<Pixels>, corner: Anchor) -> Self {
74 self.placement = Placement::Attached { target, corner };
75 self
76 }
77
78 pub fn offset(mut self, offset: Point<Pixels>) -> Self {
81 self.offset = Some(offset);
82 self
83 }
84
85 pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
90 self.position_mode = mode;
91 self
92 }
93
94 pub fn snap_to_window(mut self) -> Self {
96 self.fit_mode = AnchoredFitMode::SnapToWindow;
97 self
98 }
99
100 pub fn snap_to_window_with_margin(mut self, edges: impl Into<Edges<Pixels>>) -> Self {
102 self.fit_mode = AnchoredFitMode::SnapToWindowWithMargin(edges.into());
103 self
104 }
105}
106
107impl ParentElement for Anchored {
108 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
109 self.children.extend(elements)
110 }
111}
112
113impl Element for Anchored {
114 type RequestLayoutState = AnchoredState;
115 type PrepaintState = ();
116
117 fn id(&self) -> Option<crate::ElementId> {
118 None
119 }
120
121 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
122 None
123 }
124
125 fn request_layout(
126 &mut self,
127 _id: Option<&GlobalElementId>,
128 _inspector_id: Option<&InspectorElementId>,
129 window: &mut Window,
130 cx: &mut App,
131 ) -> (crate::LayoutId, Self::RequestLayoutState) {
132 let child_layout_ids = self
133 .children
134 .iter_mut()
135 .map(|child| child.request_layout(window, cx))
136 .collect::<SmallVec<_>>();
137
138 let anchored_style = Style {
139 position: Position::Absolute,
140 display: Display::Flex,
141 ..Style::default()
142 };
143
144 let layout_id = window.request_layout(anchored_style, child_layout_ids.iter().copied(), cx);
145
146 (layout_id, AnchoredState { child_layout_ids })
147 }
148
149 fn prepaint(
150 &mut self,
151 _id: Option<&GlobalElementId>,
152 _inspector_id: Option<&InspectorElementId>,
153 bounds: Bounds<Pixels>,
154 request_layout: &mut Self::RequestLayoutState,
155 window: &mut Window,
156 cx: &mut App,
157 ) {
158 if request_layout.child_layout_ids.is_empty() {
159 return;
160 }
161 crate::fast::layers::invalidate::note_anchored(window);
162
163 let children_bounds = request_layout
164 .child_layout_ids
165 .iter()
166 .map(|id| window.layout_bounds(*id))
167 .reduce(|acc, bounds| acc.union(&bounds))
168 .unwrap();
169
170 let anchor_position = match self.placement {
171 Placement::InPlace => None,
172 Placement::At(position) => Some(position),
173 Placement::Attached { target, corner } => Some(target.corner(corner)),
174 };
175 let (origin, mut desired) = self.position_mode.get_position_and_bounds(
176 anchor_position,
177 self.anchor,
178 children_bounds.size,
179 bounds,
180 self.offset,
181 );
182
183 let limits = Bounds {
184 origin: Point::default(),
185 size: window.viewport_size(),
186 };
187
188 if let Placement::Attached { target, mut corner } = self.placement {
189 let visible = limits.inset(window.client_inset.unwrap_or(px(0.)));
193 let overflow_along = |bounds: Bounds<Pixels>, axis: Axis| match axis {
194 Axis::Horizontal => {
195 (visible.left() - bounds.left()).max(px(0.))
196 + (bounds.right() - visible.right()).max(px(0.))
197 }
198 Axis::Vertical => {
199 (visible.top() - bounds.top()).max(px(0.))
200 + (bounds.bottom() - visible.bottom()).max(px(0.))
201 }
202 };
203 let mut anchor = self.anchor;
204 let mut offset = self.offset.unwrap_or_default();
205 for axis in [Axis::Horizontal, Axis::Vertical] {
206 let corner_side = side_along(corner, axis);
207 let is_outside_target = corner_side != Ordering::Equal
208 && side_along(anchor, axis) == corner_side.reverse();
209 let overflow = overflow_along(desired, axis);
210 if !is_outside_target || overflow == px(0.) {
211 continue;
212 }
213
214 let flipped_corner = corner.other_side_along(axis);
215 let flipped_anchor = anchor.other_side_along(axis);
216 let flipped_offset = match axis {
217 Axis::Horizontal => point(-offset.x, offset.y),
218 Axis::Vertical => point(offset.x, -offset.y),
219 };
220 let (_, flipped) = self.position_mode.get_position_and_bounds(
221 Some(target.corner(flipped_corner)),
222 flipped_anchor,
223 children_bounds.size,
224 bounds,
225 Some(flipped_offset),
226 );
227 if overflow_along(flipped, axis) < overflow {
228 corner = flipped_corner;
229 anchor = flipped_anchor;
230 offset = flipped_offset;
231 desired = flipped;
232 }
233 }
234 } else if self.fit_mode == AnchoredFitMode::SwitchAnchor {
235 let mut anchor = self.anchor;
236
237 if desired.left() < limits.left() || desired.right() > limits.right() {
238 let switched = Bounds::from_anchor_and_size(
239 anchor.other_side_along(Axis::Horizontal),
240 origin,
241 children_bounds.size,
242 );
243 if !(switched.left() < limits.left() || switched.right() > limits.right()) {
244 anchor = anchor.other_side_along(Axis::Horizontal);
245 desired = switched
246 }
247 }
248
249 if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
250 let switched = Bounds::from_anchor_and_size(
251 anchor.other_side_along(Axis::Vertical),
252 origin,
253 children_bounds.size,
254 );
255 if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
256 desired = switched;
257 }
258 }
259 }
260
261 let client_inset = window.client_inset.unwrap_or(px(0.));
262 let edges = match self.fit_mode {
263 AnchoredFitMode::SnapToWindowWithMargin(edges) => edges,
264 _ => Edges::default(),
265 }
266 .map(|edge| *edge + client_inset);
267
268 if desired.right() > limits.right() {
271 desired.origin.x -= desired.right() - limits.right() + edges.right;
272 }
273 if desired.left() < limits.left() {
274 desired.origin.x = limits.origin.x + edges.left;
275 }
276
277 if desired.bottom() > limits.bottom() {
280 desired.origin.y -= desired.bottom() - limits.bottom() + edges.bottom;
281 }
282 if desired.top() < limits.top() {
283 desired.origin.y = limits.origin.y + edges.top;
284 }
285
286 let offset = desired.origin - bounds.origin;
287 let offset = point(offset.x.round(), offset.y.round());
288
289 window.with_element_offset(offset, |window| {
290 for child in &mut self.children {
291 child.prepaint(window, cx);
292 }
293 })
294 }
295
296 fn paint(
297 &mut self,
298 _id: Option<&GlobalElementId>,
299 _inspector_id: Option<&InspectorElementId>,
300 _bounds: crate::Bounds<crate::Pixels>,
301 _request_layout: &mut Self::RequestLayoutState,
302 _prepaint: &mut Self::PrepaintState,
303 window: &mut Window,
304 cx: &mut App,
305 ) {
306 for child in &mut self.children {
307 child.paint(window, cx);
308 }
309 }
310}
311
312impl IntoElement for Anchored {
313 type Element = Self;
314
315 fn into_element(self) -> Self::Element {
316 self
317 }
318}
319
320fn side_along(anchor: Anchor, axis: Axis) -> Ordering {
323 match axis {
324 Axis::Horizontal => match anchor {
325 Anchor::TopLeft | Anchor::BottomLeft | Anchor::LeftCenter => Ordering::Less,
326 Anchor::TopCenter | Anchor::BottomCenter => Ordering::Equal,
327 Anchor::TopRight | Anchor::BottomRight | Anchor::RightCenter => Ordering::Greater,
328 },
329 Axis::Vertical => match anchor {
330 Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => Ordering::Less,
331 Anchor::LeftCenter | Anchor::RightCenter => Ordering::Equal,
332 Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => Ordering::Greater,
333 },
334 }
335}
336
337#[derive(Copy, Clone, PartialEq)]
339pub enum AnchoredFitMode {
340 SnapToWindow,
342 SnapToWindowWithMargin(Edges<Pixels>),
344 SwitchAnchor,
346}
347
348#[derive(Copy, Clone, PartialEq)]
350pub enum AnchoredPositionMode {
351 Window,
353 Local,
355}
356
357impl AnchoredPositionMode {
358 fn get_position_and_bounds(
359 &self,
360 anchor_position: Option<Point<Pixels>>,
361 anchor: Anchor,
362 size: Size<Pixels>,
363 bounds: Bounds<Pixels>,
364 offset: Option<Point<Pixels>>,
365 ) -> (Point<Pixels>, Bounds<Pixels>) {
366 let offset = offset.unwrap_or_default();
367
368 match self {
369 AnchoredPositionMode::Window => {
370 let anchor_position = anchor_position.unwrap_or(bounds.origin);
371 let bounds = Bounds::from_anchor_and_size(anchor, anchor_position + offset, size);
372 (anchor_position, bounds)
373 }
374 AnchoredPositionMode::Local => {
375 let anchor_position = anchor_position.unwrap_or_default();
376 let bounds = Bounds::from_anchor_and_size(
377 anchor,
378 bounds.origin + anchor_position + offset,
379 size,
380 );
381 (anchor_position, bounds)
382 }
383 }
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 use crate::{
390 Anchor, Bounds, Context, Pixels, PlatformInput, Point, TestAppContext, Window, deferred,
391 div, point, prelude::*, px, size,
392 };
393
394 struct AnchoredTestView {
395 position: Point<Pixels>,
396 }
397
398 impl Render for AnchoredTestView {
399 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
400 div().size_full().child(
401 div()
402 .id("scroll-container")
403 .overflow_y_scroll()
404 .size_full()
405 .child(div().h(px(2000.)).w_full())
406 .child(
407 deferred(
408 super::anchored()
409 .snap_to_window()
410 .position(self.position)
411 .child(
412 div()
413 .id("menu")
414 .debug_selector(|| "MENU".into())
415 .w(px(200.))
416 .h(px(300.)),
417 ),
418 )
419 .with_priority(1),
420 ),
421 )
422 }
423 }
424
425 #[gpui::test]
426 fn test_anchored_position_without_scroll(cx: &mut TestAppContext) {
427 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
428 position: point(px(100.), px(100.)),
429 });
430
431 cx.run_until_parked();
432
433 let menu_bounds = window
434 .update(cx, |_, window, _| {
435 window.rendered_frame.debug_bounds.get("MENU").copied()
436 })
437 .unwrap()
438 .expect("MENU debug bounds not found");
439
440 assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
441 assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
442 }
443
444 #[gpui::test]
445 fn test_anchored_position_when_scrolled(cx: &mut TestAppContext) {
446 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
447 position: point(px(100.), px(100.)),
448 });
449
450 cx.run_until_parked();
451
452 window
453 .update(cx, |_, window, cx| {
454 let event = gpui::ScrollEvent {
455 position: point(px(400.), px(300.)),
456 delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-1000.))),
457 ..Default::default()
458 };
459 window.dispatch_event(PlatformInput::Scroll(event), cx);
460 })
461 .unwrap();
462
463 cx.run_until_parked();
464
465 let menu_bounds = window
466 .update(cx, |_, window, _| {
467 window.rendered_frame.debug_bounds.get("MENU").copied()
468 })
469 .unwrap()
470 .expect("MENU debug bounds not found");
471
472 assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
473 assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
474 }
475
476 #[gpui::test]
477 fn test_anchored_snaps_to_window(cx: &mut TestAppContext) {
478 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
479 position: point(px(100.), px(500.)),
480 });
481
482 cx.run_until_parked();
483
484 let menu_bounds = window
485 .update(cx, |_, window, _| {
486 window.rendered_frame.debug_bounds.get("MENU").copied()
487 })
488 .unwrap()
489 .expect("MENU debug bounds not found");
490
491 assert_eq!(menu_bounds.origin, point(px(100.), px(300.)));
492 assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
493 }
494
495 struct AttachedTestView {
496 target: Bounds<Pixels>,
497 corner: Anchor,
498 anchor: Anchor,
499 }
500
501 impl Render for AttachedTestView {
502 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
503 div().size_full().child(
504 deferred(
505 super::anchored()
506 .attach(self.target, self.corner)
507 .anchor(self.anchor)
508 .offset(point(px(-2.), px(4.)))
509 .snap_to_window_with_margin(px(8.))
510 .child(
511 div()
512 .debug_selector(|| "MENU".into())
513 .w(px(200.))
514 .h(px(300.)),
515 ),
516 )
517 .with_priority(1),
518 )
519 }
520 }
521
522 #[gpui::test]
523 fn test_anchored_attach_moves_to_the_side_with_room(cx: &mut TestAppContext) {
524 let trigger = |x: f32, y: f32| Bounds::new(point(px(x), px(y)), size(px(100.), px(20.)));
525 let submenu = (Anchor::TopRight, Anchor::TopLeft);
527 let dropdown = (Anchor::BottomLeft, Anchor::TopLeft);
529 for (target, (corner, anchor), expected_origin) in [
530 (trigger(100., 100.), submenu, point(px(198.), px(104.))),
531 (trigger(550., 100.), submenu, point(px(352.), px(104.))),
532 (trigger(100., 400.), dropdown, point(px(98.), px(96.))),
533 (trigger(498., 100.), submenu, point(px(596.), px(104.))),
536 (
539 Bounds::new(point(px(180.), px(100.)), size(px(500.), px(20.))),
540 submenu,
541 point(px(8.), px(104.)),
542 ),
543 (
546 Bounds::new(point(px(50.), px(100.)), size(px(650.), px(20.))),
547 submenu,
548 point(px(592.), px(104.)),
549 ),
550 (trigger(700., 100.), dropdown, point(px(592.), px(124.))),
553 (
555 trigger(100., 400.),
556 (Anchor::BottomCenter, Anchor::TopCenter),
557 point(px(48.), px(96.)),
558 ),
559 ] {
560 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AttachedTestView {
561 target,
562 corner,
563 anchor,
564 });
565
566 cx.run_until_parked();
567
568 let menu_bounds = window
569 .update(cx, |_, window, _| {
570 window.rendered_frame.debug_bounds.get("MENU").copied()
571 })
572 .unwrap()
573 .expect("MENU debug bounds not found");
574
575 assert_eq!(
576 menu_bounds.origin, expected_origin,
577 "target: {target:?}, corner: {corner:?}, anchor: {anchor:?}"
578 );
579 }
580 }
581}