1use std::{
2 cell::{Cell, RefCell},
3 ops::Range,
4 rc::Rc,
5};
6
7use gpui::{
8 AccessibleAction, AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId,
9 FocusHandle, GlobalElementId, Hsla, InspectorElementId, InteractiveElement, IntoElement,
10 LayoutId, ParentElement, Pixels, Point, RenderOnce, Role, SharedString, Size,
11 StatefulInteractiveElement, Style, Styled, Window, div, point, prelude::FluentBuilder, px,
12 relative, size,
13};
14use gpui_base::{Button as BaseButton, TestSupportExt};
15use gpui_material_foundation::{ThemeScope, color, current_material_theme, text_style};
16use gpui_material_theme::{ColorRole, Direction, TypeRole, TypographyEmphasis};
17
18use crate::{Icon, IconName, Menu, MenuItem};
19
20const ROW_MIN_HEIGHT: Pixels = px(32.);
21const ITEM_GAP: Pixels = px(4.);
22const OVERFLOW_TRIGGER_WIDTH: Pixels = px(32.);
23const OVERFLOW_TRIGGER_HEIGHT: Pixels = px(32.);
24
25type BreadcrumbSelect = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
26type SeparatorFactory = Rc<dyn Fn() -> AnyElement>;
27type DisplacedFocus = Rc<RefCell<Option<(SharedString, FocusHandle)>>>;
28
29#[derive(Clone, Copy, Debug, Default, PartialEq)]
34pub struct BreadcrumbsColors {
35 pub ancestor: Option<Hsla>,
37 pub current: Option<Hsla>,
39 pub separator: Option<Hsla>,
41 pub disabled: Option<Hsla>,
43}
44
45#[derive(Clone, Copy)]
46struct ResolvedColors {
47 ancestor: Hsla,
48 current: Hsla,
49 separator: Hsla,
50 disabled: Hsla,
51 hover: Hsla,
52 focus_ring: Hsla,
53}
54
55impl BreadcrumbsColors {
56 fn resolve(self, window: &Window, cx: &App) -> ResolvedColors {
57 let theme = current_material_theme(window, cx);
58 let role = |r| color(theme.colors.color(r));
59 let on_surface = role(ColorRole::OnSurface);
60 let on_surface_variant = role(ColorRole::OnSurfaceVariant);
61 ResolvedColors {
62 ancestor: self.ancestor.unwrap_or(on_surface_variant),
63 current: self.current.unwrap_or(on_surface),
64 separator: self.separator.unwrap_or(on_surface_variant),
65 disabled: self.disabled.unwrap_or_else(|| on_surface.opacity(0.38)),
66 hover: on_surface.opacity(0.08),
67 focus_ring: role(ColorRole::Secondary),
68 }
69 }
70}
71
72pub struct BreadcrumbItem {
74 id: SharedString,
75 label: SharedString,
76 icon: Option<AnyElement>,
77 disabled: bool,
78}
79
80impl BreadcrumbItem {
81 pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
83 Self {
84 id: id.into(),
85 label: label.into(),
86 icon: None,
87 disabled: false,
88 }
89 }
90
91 pub fn icon(mut self, icon: impl IntoElement) -> Self {
93 self.icon = Some(icon.into_any_element());
94 self
95 }
96
97 pub fn disabled(mut self, disabled: bool) -> Self {
99 self.disabled = disabled;
100 self
101 }
102}
103
104#[derive(IntoElement)]
107pub struct Breadcrumbs {
108 id: ElementId,
109 items: Vec<BreadcrumbItem>,
110 accessible_label: SharedString,
111 overflow_label: SharedString,
112 on_select: Option<BreadcrumbSelect>,
113 max_items: Option<usize>,
114 separator: Option<SeparatorFactory>,
115 colors: BreadcrumbsColors,
116}
117
118impl Breadcrumbs {
119 pub fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = BreadcrumbItem>) -> Self {
121 Self {
122 id: id.into(),
123 items: items.into_iter().collect(),
124 accessible_label: "Breadcrumb".into(),
125 overflow_label: "More breadcrumbs".into(),
126 on_select: None,
127 max_items: None,
128 separator: None,
129 colors: BreadcrumbsColors::default(),
130 }
131 }
132
133 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
135 self.accessible_label = label.into();
136 self
137 }
138
139 pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
141 self.overflow_label = label.into();
142 self
143 }
144
145 pub fn on_select(
148 mut self,
149 handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
150 ) -> Self {
151 self.on_select = Some(Rc::new(handler));
152 self
153 }
154
155 pub fn max_items(mut self, count: usize) -> Self {
158 self.max_items = Some(count.max(2));
159 self
160 }
161
162 pub fn separator<E: IntoElement>(mut self, separator: impl Fn() -> E + 'static) -> Self {
165 self.separator = Some(Rc::new(move || separator().into_any_element()));
166 self
167 }
168
169 pub fn colors(mut self, colors: BreadcrumbsColors) -> Self {
171 self.colors = colors;
172 self
173 }
174}
175
176impl RenderOnce for Breadcrumbs {
177 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
178 let id = self.id.clone();
179 let label = self.accessible_label.clone();
180 div()
181 .id(id)
182 .test_support()
183 .role(Role::Navigation)
184 .aria_label(label)
185 .w_full()
186 .child(BreadcrumbsLayout::new(self, window, cx))
187 }
188}
189
190#[derive(Clone, Debug, Eq, PartialEq)]
191struct CollapsePlan {
192 leading: Range<usize>,
193 collapsed: Range<usize>,
194 trailing: Range<usize>,
195}
196
197fn compute_collapse_plan(
198 widths: &[Pixels],
199 sep_step: Pixels,
200 trigger_width: Pixels,
201 max_items: Option<usize>,
202 available: Pixels,
203) -> CollapsePlan {
204 let n = widths.len();
205 if n == 0 {
206 return CollapsePlan {
207 leading: 0..0,
208 collapsed: 0..0,
209 trailing: 0..0,
210 };
211 }
212 if n <= 2 {
213 return CollapsePlan {
214 leading: 0..n,
215 collapsed: 0..0,
216 trailing: n..n,
217 };
218 }
219
220 let cap = max_items.map(|c| c.max(2)).unwrap_or(usize::MAX);
221 let full_width = widths.iter().copied().sum::<Pixels>() + sep_step * (n - 1) as f32;
222 if n <= cap && full_width <= available {
223 return CollapsePlan {
224 leading: 0..n,
225 collapsed: 0..0,
226 trailing: n..n,
227 };
228 }
229
230 let mut trailing_start = n - 1;
233 let mut used = widths[0] + trigger_width + widths[n - 1] + sep_step * 2.;
234
235 for idx in (2..=(n - 2)).rev() {
236 let visible_items = 1 + (n - idx);
237 if visible_items > cap {
238 break;
239 }
240 let extra = widths[idx] + sep_step;
241 if used + extra <= available {
242 used += extra;
243 trailing_start = idx;
244 } else {
245 break;
246 }
247 }
248
249 CollapsePlan {
250 leading: 0..1,
251 collapsed: 1..trailing_start,
252 trailing: trailing_start..n,
253 }
254}
255
256struct OverflowState {
257 shown: Rc<Cell<bool>>,
258 has_overflow: Rc<Cell<bool>>,
259 focus: FocusHandle,
260 displaced: DisplacedFocus,
261}
262
263#[derive(Clone)]
264struct MenuController {
265 shown: Rc<Cell<bool>>,
266 has_overflow: Rc<Cell<bool>>,
267 view: gpui::EntityId,
268}
269
270impl MenuController {
271 fn is_showing(&self) -> bool {
272 self.shown.get()
273 }
274
275 fn set(&self, shown: bool, window: &mut Window, cx: &mut App) {
276 if self.shown.replace(shown) != shown {
277 cx.notify(self.view);
278 window.refresh();
279 }
280 }
281}
282
283struct PreparedItem {
284 id: SharedString,
285 label: SharedString,
286 disabled: bool,
287 is_current: bool,
288 focus: Option<FocusHandle>,
289 inline: AnyElement,
290 preferred: Size<Pixels>,
291}
292
293struct BreadcrumbsLayout {
294 breadcrumbs: Breadcrumbs,
295 direction: Direction,
296 colors: ResolvedColors,
297 menu: MenuController,
298 overflow_focus: FocusHandle,
299 displaced: DisplacedFocus,
300}
301
302impl BreadcrumbsLayout {
303 fn new(breadcrumbs: Breadcrumbs, window: &mut Window, cx: &mut App) -> Self {
304 let overflow = window.use_keyed_state(
305 (breadcrumbs.id.clone(), "breadcrumbs-overflow"),
306 cx,
307 |_, cx| OverflowState {
308 shown: Rc::new(Cell::new(false)),
309 has_overflow: Rc::new(Cell::new(false)),
310 focus: cx.focus_handle(),
311 displaced: Rc::new(RefCell::new(None)),
312 },
313 );
314 let overflow = overflow.read(cx);
315 Self {
316 direction: current_material_theme(window, cx).layout.direction,
317 colors: breadcrumbs.colors.resolve(window, cx),
318 menu: MenuController {
319 shown: overflow.shown.clone(),
320 has_overflow: overflow.has_overflow.clone(),
321 view: window.current_view(),
322 },
323 overflow_focus: overflow.focus.clone(),
324 displaced: overflow.displaced.clone(),
325 breadcrumbs,
326 }
327 }
328
329 fn make_separator(&self) -> AnyElement {
330 let glyph = match &self.breadcrumbs.separator {
331 Some(factory) => factory(),
332 None => Icon::new(IconName::ChevronRight)
333 .size(px(16.))
334 .mirror_in_rtl(true)
335 .into_any_element(),
336 };
337 div()
338 .flex_none()
339 .flex()
340 .items_center()
341 .justify_center()
342 .px(ITEM_GAP)
343 .text_color(self.colors.separator)
344 .child(glyph)
345 .into_any_element()
346 }
347
348 fn prepare_item(
349 &self,
350 item: BreadcrumbItem,
351 is_current: bool,
352 window: &mut Window,
353 cx: &mut App,
354 ) -> PreparedItem {
355 let rtl = self.direction == Direction::Rtl;
356 let elem_id = ElementId::from((self.breadcrumbs.id.clone(), item.id.clone()));
357
358 if is_current {
359 let fg = if item.disabled {
360 self.colors.disabled
361 } else {
362 self.colors.current
363 };
364 let current_aria: SharedString = format!("{}, current page", item.label).into();
365 let mut inline = div()
366 .id(elem_id)
367 .test_support()
368 .role(Role::Label)
369 .aria_label(current_aria)
370 .h(ROW_MIN_HEIGHT)
371 .px(px(6.))
372 .flex()
373 .flex_row()
374 .items_center()
375 .gap(px(4.))
376 .when(rtl, Styled::flex_row_reverse)
377 .text_color(fg)
378 .children(
379 item.icon
380 .map(|icon| div().flex_none().text_size(px(16.)).child(icon)),
381 )
382 .child(
383 text_style(
384 div().whitespace_nowrap(),
385 TypeRole::TitleSmall.style(TypographyEmphasis::Baseline),
386 1.,
387 window,
388 cx,
389 )
390 .child(item.label.clone()),
391 )
392 .into_any_element();
393 let preferred = inline.layout_as_root(
394 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
395 window,
396 cx,
397 );
398 return PreparedItem {
399 id: item.id,
400 label: item.label,
401 disabled: item.disabled,
402 is_current: true,
403 focus: None,
404 inline,
405 preferred,
406 };
407 }
408
409 let focus = window.with_id(
410 ElementId::from((self.breadcrumbs.id.clone(), "breadcrumb-focus")),
411 |window| {
412 window
413 .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
414 .read(cx)
415 .clone()
416 },
417 );
418
419 let fg = if item.disabled {
420 self.colors.disabled
421 } else {
422 self.colors.ancestor
423 };
424 let hover_bg = self.colors.hover;
425 let focus_ring = self.colors.focus_ring;
426
427 let activate = (!item.disabled).then(|| {
428 self.breadcrumbs.on_select.as_ref().map(|on_select| {
429 let on_select = on_select.clone();
430 let item_id = item.id.clone();
431 Rc::new(ThemeScope::bind_action(
432 move |window, cx| on_select(item_id.clone(), window, cx),
433 window,
434 cx,
435 ))
436 })
437 });
438 let activate = activate.flatten();
439
440 let click_handler = activate.clone();
441 let a11y_handler = activate;
442
443 let mut inline = BaseButton::new(elem_id)
444 .track_focus(&focus)
445 .disabled(item.disabled)
446 .accessibility_label(item.label.clone())
447 .h(ROW_MIN_HEIGHT)
448 .px(px(6.))
449 .rounded(px(8.))
450 .border_2()
451 .border_color(gpui::transparent_black())
452 .flex()
453 .flex_row()
454 .items_center()
455 .gap(px(4.))
456 .when(rtl, Styled::flex_row_reverse)
457 .text_color(fg)
458 .when(!item.disabled, move |button| {
459 button
460 .hover(move |b| b.bg(hover_bg))
461 .focus_visible(move |b| b.border_color(focus_ring))
462 })
463 .when_some(click_handler, |button, handler| {
464 button.on_click(move |_, window, cx| {
465 cx.stop_propagation();
466 handler(window, cx);
467 })
468 })
469 .when_some(a11y_handler, |button, handler| {
470 button.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
471 handler(window, cx);
472 })
473 })
474 .children(
475 item.icon
476 .map(|icon| div().flex_none().text_size(px(16.)).child(icon)),
477 )
478 .child(
479 text_style(
480 div().whitespace_nowrap(),
481 TypeRole::LabelLarge.style(TypographyEmphasis::Baseline),
482 1.,
483 window,
484 cx,
485 )
486 .child(item.label.clone()),
487 )
488 .into_any_element();
489
490 let preferred = inline.layout_as_root(
491 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
492 window,
493 cx,
494 );
495
496 PreparedItem {
497 id: item.id,
498 label: item.label,
499 disabled: item.disabled,
500 is_current: false,
501 focus: Some(focus),
502 inline,
503 preferred,
504 }
505 }
506
507 fn transfer_focus(
508 &self,
509 plan: &CollapsePlan,
510 items: &[PreparedItem],
511 window: &mut Window,
512 cx: &mut App,
513 ) {
514 let overflow = !plan.collapsed.is_empty();
515 let in_overflow = self.overflow_focus.is_focused(window);
516 let previous_overflow = self.menu.has_overflow.replace(overflow);
517 let menu_was_open = self.menu.is_showing();
518 let mut displaced = self.displaced.borrow_mut();
519
520 if overflow
521 && let Some(hidden) = items[plan.collapsed.clone()].iter().find(|item| {
522 item.focus
523 .as_ref()
524 .is_some_and(|focus| focus.contains_focused(window, cx))
525 })
526 {
527 let old_focus = window
528 .focused(cx)
529 .or_else(|| hidden.focus.clone())
530 .unwrap_or_else(|| self.overflow_focus.clone());
531 *displaced = Some((hidden.id.clone(), old_focus));
532 focus_after_layout(self.overflow_focus.clone(), window, cx);
533 return;
534 }
535
536 if !overflow && previous_overflow {
537 self.menu.shown.set(false);
538 }
539
540 let is_visible = |id: &SharedString| {
541 plan.leading
542 .clone()
543 .chain(plan.trailing.clone())
544 .any(|idx| !items[idx].disabled && !items[idx].is_current && items[idx].id == *id)
545 };
546 let returned = displaced
547 .as_ref()
548 .filter(|(id, _)| is_visible(id))
549 .map(|(_, focus)| focus.clone());
550
551 let restore = if !overflow && (in_overflow || menu_was_open) {
552 returned.or_else(|| {
553 items
554 .iter()
555 .find(|item| !item.disabled && !item.is_current)
556 .and_then(|item| item.focus.clone())
557 })
558 } else if in_overflow {
559 returned
560 } else {
561 None
562 };
563
564 if let Some(focus) = restore {
565 displaced.take();
566 focus_after_layout(focus, window, cx);
567 } else if !overflow {
568 displaced.take();
569 }
570 }
571
572 fn build_overflow_menu(
573 &self,
574 collapsed: &[PreparedItem],
575 window: &mut Window,
576 cx: &mut App,
577 ) -> AnyElement {
578 let entries: Vec<MenuItem> = collapsed
579 .iter()
580 .map(|item| {
581 let mut entry = MenuItem::new(
582 ElementId::from((self.breadcrumbs.id.clone(), item.id.clone())),
583 item.label.clone(),
584 )
585 .disabled(item.disabled);
586 if !item.disabled
587 && let Some(on_select) = self.breadcrumbs.on_select.clone()
588 {
589 let item_id = item.id.clone();
590 let bound = ThemeScope::bind_action(
591 move |window, cx| on_select(item_id.clone(), window, cx),
592 window,
593 cx,
594 );
595 entry = entry.on_activate(move |window, cx| bound(window, cx));
596 }
597 entry
598 })
599 .collect();
600
601 let state = self.menu.clone();
602 let observed = state.clone();
603 let trigger_focus = self.overflow_focus.clone();
604 let trigger_id = ElementId::from((self.breadcrumbs.id.clone(), "overflow"));
605 let label = self.breadcrumbs.overflow_label.clone();
606 let ink = self.colors.ancestor;
607 let hover_bg = self.colors.hover;
608 let focus_ring = self.colors.focus_ring;
609
610 Menu::composed(
611 (self.breadcrumbs.id.clone(), "overflow-menu"),
612 entries,
613 move |_, toggle| {
614 let return_focus = trigger_focus.clone();
615 let dots = div()
616 .flex()
617 .flex_row()
618 .items_center()
619 .gap(px(2.5))
620 .children((0..3).map(|_| div().size(px(3.5)).rounded_full().bg(ink)));
621 BaseButton::new(trigger_id)
622 .track_focus(&trigger_focus)
623 .accessibility_label(label)
624 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
625 return_focus.focus(window, cx);
626 toggle(window, cx);
627 })
628 .w(OVERFLOW_TRIGGER_WIDTH)
629 .h(OVERFLOW_TRIGGER_HEIGHT)
630 .p_0()
631 .flex()
632 .items_center()
633 .justify_center()
634 .rounded(px(8.))
635 .border_2()
636 .border_color(gpui::transparent_black())
637 .text_color(ink)
638 .hover(move |button| button.bg(hover_bg))
639 .focus_visible(move |button| button.border_color(focus_ring))
640 .child(dots)
641 .into_any_element()
642 },
643 )
644 .open(state.is_showing())
645 .on_open_change(move |open, window, cx| observed.set(open, window, cx))
646 .into_any_element()
647 }
648
649 fn origin(&self, bounds: Bounds<Pixels>, child: Size<Pixels>, offset: Pixels) -> Point<Pixels> {
650 let dy = (bounds.size.height - child.height).max(px(0.)) / 2.;
651 match self.direction {
652 Direction::Ltr => point(bounds.left() + offset, bounds.top() + dy),
653 Direction::Rtl => point(bounds.right() - offset - child.width, bounds.top() + dy),
654 }
655 }
656}
657
658fn focus_after_layout(target: FocusHandle, window: &mut Window, cx: &mut App) {
659 let origin = window.focused(cx);
660 window.on_next_frame(move |window, cx| {
661 let current = window.focused(cx);
662 if current.is_none() || current == origin {
663 target.focus(window, cx);
664 }
665 });
666}
667
668impl IntoElement for BreadcrumbsLayout {
669 type Element = Self;
670
671 fn into_element(self) -> Self {
672 self
673 }
674}
675
676struct BreadcrumbsLayoutState {
677 items: Vec<PreparedItem>,
678 sep_width: Pixels,
679}
680
681struct BreadcrumbsPrepaintState {
682 plan: CollapsePlan,
683 separators: Vec<AnyElement>,
684 menu: Option<AnyElement>,
685}
686
687impl Element for BreadcrumbsLayout {
688 type RequestLayoutState = BreadcrumbsLayoutState;
689 type PrepaintState = BreadcrumbsPrepaintState;
690
691 fn id(&self) -> Option<ElementId> {
692 Some(ElementId::from((self.breadcrumbs.id.clone(), "layout")))
693 }
694
695 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
696 None
697 }
698
699 fn a11y_role(&self) -> Option<Role> {
700 None
701 }
702
703 fn request_layout(
704 &mut self,
705 _: Option<&GlobalElementId>,
706 _: Option<&InspectorElementId>,
707 window: &mut Window,
708 cx: &mut App,
709 ) -> (LayoutId, Self::RequestLayoutState) {
710 let raw_items = std::mem::take(&mut self.breadcrumbs.items);
711 let len = raw_items.len();
712 let items: Vec<PreparedItem> = raw_items
713 .into_iter()
714 .enumerate()
715 .map(|(idx, item)| self.prepare_item(item, idx + 1 == len, window, cx))
716 .collect();
717
718 let mut probe_sep = self.make_separator();
719 let sep_size = probe_sep.layout_as_root(
720 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
721 window,
722 cx,
723 );
724 let sep_width = sep_size.width;
725
726 let widths: Vec<Pixels> = items.iter().map(|i| i.preferred.width).collect();
727 let preferred_plan = compute_collapse_plan(
728 &widths,
729 sep_width,
730 OVERFLOW_TRIGGER_WIDTH,
731 self.breadcrumbs.max_items,
732 px(f32::INFINITY),
733 );
734
735 let visible_segments = preferred_plan.leading.len()
736 + usize::from(!preferred_plan.collapsed.is_empty())
737 + preferred_plan.trailing.len();
738 let mut preferred_width = preferred_plan
739 .leading
740 .clone()
741 .chain(preferred_plan.trailing.clone())
742 .map(|i| items[i].preferred.width)
743 .sum::<Pixels>();
744 if !preferred_plan.collapsed.is_empty() {
745 preferred_width += OVERFLOW_TRIGGER_WIDTH;
746 }
747 if visible_segments > 1 {
748 preferred_width += sep_width * (visible_segments - 1) as f32;
749 }
750
751 let cross = items.iter().map(|item| item.preferred.height).fold(
752 if items.is_empty() {
753 px(0.)
754 } else {
755 ROW_MIN_HEIGHT.max(sep_size.height)
756 },
757 Pixels::max,
758 );
759
760 let style = Style {
761 size: size(preferred_width.into(), cross.into()),
762 min_size: size(px(0.).into(), px(0.).into()),
763 max_size: size(relative(1.).into(), relative(1.).into()),
764 ..Default::default()
765 };
766
767 (
768 window.request_layout(style, None, cx),
769 BreadcrumbsLayoutState { items, sep_width },
770 )
771 }
772
773 fn prepaint(
774 &mut self,
775 _: Option<&GlobalElementId>,
776 _: Option<&InspectorElementId>,
777 bounds: Bounds<Pixels>,
778 state: &mut Self::RequestLayoutState,
779 window: &mut Window,
780 cx: &mut App,
781 ) -> Self::PrepaintState {
782 let widths: Vec<Pixels> = state.items.iter().map(|i| i.preferred.width).collect();
783 let plan = compute_collapse_plan(
784 &widths,
785 state.sep_width,
786 OVERFLOW_TRIGGER_WIDTH,
787 self.breadcrumbs.max_items,
788 bounds.size.width,
789 );
790 self.transfer_focus(&plan, &state.items, window, cx);
791
792 let mut offset = px(0.);
793 let mut separators = Vec::new();
794 let mut placed_any = false;
795
796 let mut place_separator = |offset: &mut Pixels, window: &mut Window, cx: &mut App| {
797 let mut sep = self.make_separator();
798 let sep_size = sep.layout_as_root(
799 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
800 window,
801 cx,
802 );
803 let origin = self.origin(bounds, sep_size, *offset);
804 window.with_content_mask(Some(ContentMask { bounds }), |window| {
805 sep.prepaint_at(origin, window, cx);
806 });
807 *offset += sep_size.width;
808 separators.push(sep);
809 };
810
811 for idx in plan.leading.clone() {
812 if placed_any {
813 place_separator(&mut offset, window, cx);
814 }
815 let item = &mut state.items[idx];
816 let origin = self.origin(bounds, item.preferred, offset);
817 window.with_content_mask(Some(ContentMask { bounds }), |window| {
818 item.inline.prepaint_at(origin, window, cx);
819 });
820 offset += item.preferred.width;
821 placed_any = true;
822 }
823
824 let menu = (!plan.collapsed.is_empty()).then(|| {
825 if placed_any {
826 place_separator(&mut offset, window, cx);
827 }
828 let mut menu =
829 self.build_overflow_menu(&state.items[plan.collapsed.clone()], window, cx);
830 let trigger_size = size(
831 OVERFLOW_TRIGGER_WIDTH,
832 OVERFLOW_TRIGGER_HEIGHT.min(bounds.size.height.max(ROW_MIN_HEIGHT)),
833 );
834 let measured =
835 menu.layout_as_root(trigger_size.map(AvailableSpace::Definite), window, cx);
836 let origin = self.origin(bounds, measured, offset);
837 menu.prepaint_at(origin, window, cx);
838 offset += measured.width;
839 placed_any = true;
840 menu
841 });
842
843 for idx in plan.trailing.clone() {
844 if placed_any {
845 place_separator(&mut offset, window, cx);
846 }
847 let item = &mut state.items[idx];
848 let origin = self.origin(bounds, item.preferred, offset);
849 window.with_content_mask(Some(ContentMask { bounds }), |window| {
850 item.inline.prepaint_at(origin, window, cx);
851 });
852 offset += item.preferred.width;
853 placed_any = true;
854 }
855
856 BreadcrumbsPrepaintState {
857 plan,
858 separators,
859 menu,
860 }
861 }
862
863 fn paint(
864 &mut self,
865 _: Option<&GlobalElementId>,
866 _: Option<&InspectorElementId>,
867 bounds: Bounds<Pixels>,
868 state: &mut Self::RequestLayoutState,
869 prepaint: &mut Self::PrepaintState,
870 window: &mut Window,
871 cx: &mut App,
872 ) {
873 window.with_content_mask(Some(ContentMask { bounds }), |window| {
874 for idx in prepaint.plan.leading.clone() {
875 state.items[idx].inline.paint(window, cx);
876 }
877 for sep in &mut prepaint.separators {
878 sep.paint(window, cx);
879 }
880 for idx in prepaint.plan.trailing.clone() {
881 state.items[idx].inline.paint(window, cx);
882 }
883 });
884 if let Some(menu) = &mut prepaint.menu {
885 menu.paint(window, cx);
886 }
887 }
888}
889
890#[cfg(test)]
891mod tests {
892 use super::*;
893
894 #[test]
895 fn collapse_plan_fits_when_space_permits_and_collapses_middle_by_max_items_or_width() {
896 let widths = [px(60.), px(90.), px(80.), px(50.), px(70.)];
897 let sep = px(20.);
898 let trigger = px(32.);
899 assert_eq!(
902 compute_collapse_plan(&widths, sep, trigger, None, px(500.)),
903 CollapsePlan {
904 leading: 0..5,
905 collapsed: 0..0,
906 trailing: 5..5,
907 }
908 );
909
910 assert_eq!(
912 compute_collapse_plan(&widths, sep, trigger, Some(3), px(500.)),
913 CollapsePlan {
914 leading: 0..1,
915 collapsed: 1..3,
916 trailing: 3..5,
917 }
918 );
919
920 assert_eq!(
922 compute_collapse_plan(&widths, sep, trigger, Some(2), px(500.)),
923 CollapsePlan {
924 leading: 0..1,
925 collapsed: 1..4,
926 trailing: 4..5,
927 }
928 );
929
930 assert_eq!(
933 compute_collapse_plan(&widths, sep, trigger, None, px(340.)),
934 CollapsePlan {
935 leading: 0..1,
936 collapsed: 1..3,
937 trailing: 3..5,
938 }
939 );
940
941 assert_eq!(
943 compute_collapse_plan(&widths, sep, trigger, None, px(220.)),
944 CollapsePlan {
945 leading: 0..1,
946 collapsed: 1..4,
947 trailing: 4..5,
948 }
949 );
950
951 assert_eq!(
953 compute_collapse_plan(&[px(80.), px(90.)], sep, trigger, Some(2), px(100.)),
954 CollapsePlan {
955 leading: 0..2,
956 collapsed: 0..0,
957 trailing: 2..2,
958 }
959 );
960 }
961}