1use std::cmp::Ordering;
3
4use smallvec::SmallVec;
5
6use crate::{
7 Anchor, AnyElement, App, Axis, Bounds, Display, Edges, Element, GlobalElementId,
8 InspectorElementId, LayoutId, ParentElement, Pixels, Point, Position, Size, Style, Window,
9 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
312fn side_along(anchor: Anchor, axis: Axis) -> Ordering {
315 match axis {
316 Axis::Horizontal => match anchor {
317 Anchor::TopLeft | Anchor::BottomLeft | Anchor::LeftCenter => Ordering::Less,
318 Anchor::TopCenter | Anchor::BottomCenter => Ordering::Equal,
319 Anchor::TopRight | Anchor::BottomRight | Anchor::RightCenter => Ordering::Greater,
320 },
321 Axis::Vertical => match anchor {
322 Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => Ordering::Less,
323 Anchor::LeftCenter | Anchor::RightCenter => Ordering::Equal,
324 Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => Ordering::Greater,
325 },
326 }
327}
328
329#[derive(Copy, Clone, PartialEq)]
331pub enum AnchoredFitMode {
332 SnapToWindow,
334 SnapToWindowWithMargin(Edges<Pixels>),
336 SwitchAnchor,
338}
339
340#[derive(Copy, Clone, PartialEq)]
342pub enum AnchoredPositionMode {
343 Window,
345 Local,
347}
348
349impl AnchoredPositionMode {
350 fn get_position_and_bounds(
351 &self,
352 anchor_position: Option<Point<Pixels>>,
353 anchor: Anchor,
354 size: Size<Pixels>,
355 bounds: Bounds<Pixels>,
356 offset: Option<Point<Pixels>>,
357 ) -> (Point<Pixels>, Bounds<Pixels>) {
358 let offset = offset.unwrap_or_default();
359
360 match self {
361 AnchoredPositionMode::Window => {
362 let anchor_position = anchor_position.unwrap_or(bounds.origin);
363 let bounds = Bounds::from_anchor_and_size(anchor, anchor_position + offset, size);
364 (anchor_position, bounds)
365 }
366 AnchoredPositionMode::Local => {
367 let anchor_position = anchor_position.unwrap_or_default();
368 let bounds = Bounds::from_anchor_and_size(
369 anchor,
370 bounds.origin + anchor_position + offset,
371 size,
372 );
373 (anchor_position, bounds)
374 }
375 }
376 }
377}
378
379#[cfg(test)]
380mod tests {
381 use crate::{
382 Anchor, Bounds, Context, Pixels, PlatformInput, Point, TestAppContext, Window, deferred,
383 div, point, prelude::*, px, size,
384 };
385
386 struct AnchoredTestView {
387 position: Point<Pixels>,
388 }
389
390 impl Render for AnchoredTestView {
391 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
392 div().size_full().child(
393 div()
394 .id("scroll-container")
395 .overflow_y_scroll()
396 .size_full()
397 .child(div().h(px(2000.)).w_full())
398 .child(
399 deferred(
400 super::anchored()
401 .snap_to_window()
402 .position(self.position)
403 .child(
404 div()
405 .id("menu")
406 .debug_selector(|| "MENU".into())
407 .w(px(200.))
408 .h(px(300.)),
409 ),
410 )
411 .with_priority(1),
412 ),
413 )
414 }
415 }
416
417 #[gpui::test]
418 fn test_anchored_position_without_scroll(cx: &mut TestAppContext) {
419 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
420 position: point(px(100.), px(100.)),
421 });
422
423 cx.run_until_parked();
424
425 let menu_bounds = window
426 .update(cx, |_, window, _| {
427 window.rendered_frame.debug_bounds.get("MENU").copied()
428 })
429 .unwrap()
430 .expect("MENU debug bounds not found");
431
432 assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
433 assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
434 }
435
436 #[gpui::test]
437 fn test_anchored_position_when_scrolled(cx: &mut TestAppContext) {
438 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
439 position: point(px(100.), px(100.)),
440 });
441
442 cx.run_until_parked();
443
444 window
445 .update(cx, |_, window, cx| {
446 let event = gpui::ScrollEvent {
447 position: point(px(400.), px(300.)),
448 delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-1000.))),
449 ..Default::default()
450 };
451 window.dispatch_event(PlatformInput::Scroll(event), cx);
452 })
453 .unwrap();
454
455 cx.run_until_parked();
456
457 let menu_bounds = window
458 .update(cx, |_, window, _| {
459 window.rendered_frame.debug_bounds.get("MENU").copied()
460 })
461 .unwrap()
462 .expect("MENU debug bounds not found");
463
464 assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
465 assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
466 }
467
468 #[gpui::test]
469 fn test_anchored_snaps_to_window(cx: &mut TestAppContext) {
470 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
471 position: point(px(100.), px(500.)),
472 });
473
474 cx.run_until_parked();
475
476 let menu_bounds = window
477 .update(cx, |_, window, _| {
478 window.rendered_frame.debug_bounds.get("MENU").copied()
479 })
480 .unwrap()
481 .expect("MENU debug bounds not found");
482
483 assert_eq!(menu_bounds.origin, point(px(100.), px(300.)));
484 assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
485 }
486
487 struct AttachedTestView {
488 target: Bounds<Pixels>,
489 corner: Anchor,
490 anchor: Anchor,
491 }
492
493 impl Render for AttachedTestView {
494 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
495 div().size_full().child(
496 deferred(
497 super::anchored()
498 .attach(self.target, self.corner)
499 .anchor(self.anchor)
500 .offset(point(px(-2.), px(4.)))
501 .snap_to_window_with_margin(px(8.))
502 .child(
503 div()
504 .debug_selector(|| "MENU".into())
505 .w(px(200.))
506 .h(px(300.)),
507 ),
508 )
509 .with_priority(1),
510 )
511 }
512 }
513
514 #[gpui::test]
515 fn test_anchored_attach_moves_to_the_side_with_room(cx: &mut TestAppContext) {
516 let trigger = |x: f32, y: f32| Bounds::new(point(px(x), px(y)), size(px(100.), px(20.)));
517 let submenu = (Anchor::TopRight, Anchor::TopLeft);
519 let dropdown = (Anchor::BottomLeft, Anchor::TopLeft);
521 for (target, (corner, anchor), expected_origin) in [
522 (trigger(100., 100.), submenu, point(px(198.), px(104.))),
523 (trigger(550., 100.), submenu, point(px(352.), px(104.))),
524 (trigger(100., 400.), dropdown, point(px(98.), px(96.))),
525 (trigger(498., 100.), submenu, point(px(596.), px(104.))),
528 (
531 Bounds::new(point(px(180.), px(100.)), size(px(500.), px(20.))),
532 submenu,
533 point(px(8.), px(104.)),
534 ),
535 (
538 Bounds::new(point(px(50.), px(100.)), size(px(650.), px(20.))),
539 submenu,
540 point(px(592.), px(104.)),
541 ),
542 (trigger(700., 100.), dropdown, point(px(592.), px(124.))),
545 (
547 trigger(100., 400.),
548 (Anchor::BottomCenter, Anchor::TopCenter),
549 point(px(48.), px(96.)),
550 ),
551 ] {
552 let window = cx.open_window(size(px(800.), px(600.)), |_, _| AttachedTestView {
553 target,
554 corner,
555 anchor,
556 });
557
558 cx.run_until_parked();
559
560 let menu_bounds = window
561 .update(cx, |_, window, _| {
562 window.rendered_frame.debug_bounds.get("MENU").copied()
563 })
564 .unwrap()
565 .expect("MENU debug bounds not found");
566
567 assert_eq!(
568 menu_bounds.origin, expected_origin,
569 "target: {target:?}, corner: {corner:?}, anchor: {anchor:?}"
570 );
571 }
572 }
573}