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
668struct BreadcrumbsLayoutState {
669 items: Vec<PreparedItem>,
670 sep_width: Pixels,
671}
672
673struct BreadcrumbsPrepaintState {
674 plan: CollapsePlan,
675 separators: Vec<AnyElement>,
676 menu: Option<AnyElement>,
677}
678
679impl Element for BreadcrumbsLayout {
680 type RequestLayoutState = BreadcrumbsLayoutState;
681 type PrepaintState = BreadcrumbsPrepaintState;
682
683 fn id(&self) -> Option<ElementId> {
684 Some(ElementId::from((self.breadcrumbs.id.clone(), "layout")))
685 }
686
687 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
688 None
689 }
690
691 fn a11y_role(&self) -> Option<Role> {
692 None
693 }
694
695 fn request_layout(
696 &mut self,
697 _: Option<&GlobalElementId>,
698 _: Option<&InspectorElementId>,
699 window: &mut Window,
700 cx: &mut App,
701 ) -> (LayoutId, Self::RequestLayoutState) {
702 let raw_items = std::mem::take(&mut self.breadcrumbs.items);
703 let len = raw_items.len();
704 let items: Vec<PreparedItem> = raw_items
705 .into_iter()
706 .enumerate()
707 .map(|(idx, item)| self.prepare_item(item, idx + 1 == len, window, cx))
708 .collect();
709
710 let mut probe_sep = self.make_separator();
711 let sep_size = probe_sep.layout_as_root(
712 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
713 window,
714 cx,
715 );
716 let sep_width = sep_size.width;
717
718 let widths: Vec<Pixels> = items.iter().map(|i| i.preferred.width).collect();
719 let preferred_plan = compute_collapse_plan(
720 &widths,
721 sep_width,
722 OVERFLOW_TRIGGER_WIDTH,
723 self.breadcrumbs.max_items,
724 px(f32::INFINITY),
725 );
726
727 let visible_segments = preferred_plan.leading.len()
728 + usize::from(!preferred_plan.collapsed.is_empty())
729 + preferred_plan.trailing.len();
730 let mut preferred_width = preferred_plan
731 .leading
732 .clone()
733 .chain(preferred_plan.trailing.clone())
734 .map(|i| items[i].preferred.width)
735 .sum::<Pixels>();
736 if !preferred_plan.collapsed.is_empty() {
737 preferred_width += OVERFLOW_TRIGGER_WIDTH;
738 }
739 if visible_segments > 1 {
740 preferred_width += sep_width * (visible_segments - 1) as f32;
741 }
742
743 let cross = items.iter().map(|item| item.preferred.height).fold(
744 if items.is_empty() {
745 px(0.)
746 } else {
747 ROW_MIN_HEIGHT.max(sep_size.height)
748 },
749 Pixels::max,
750 );
751
752 let style = Style {
753 size: size(preferred_width.into(), cross.into()),
754 min_size: size(px(0.).into(), px(0.).into()),
755 max_size: size(relative(1.).into(), relative(1.).into()),
756 ..Default::default()
757 };
758
759 (
760 window.request_layout(style, None, cx),
761 BreadcrumbsLayoutState { items, sep_width },
762 )
763 }
764
765 fn prepaint(
766 &mut self,
767 _: Option<&GlobalElementId>,
768 _: Option<&InspectorElementId>,
769 bounds: Bounds<Pixels>,
770 state: &mut Self::RequestLayoutState,
771 window: &mut Window,
772 cx: &mut App,
773 ) -> Self::PrepaintState {
774 let widths: Vec<Pixels> = state.items.iter().map(|i| i.preferred.width).collect();
775 let plan = compute_collapse_plan(
776 &widths,
777 state.sep_width,
778 OVERFLOW_TRIGGER_WIDTH,
779 self.breadcrumbs.max_items,
780 bounds.size.width,
781 );
782 self.transfer_focus(&plan, &state.items, window, cx);
783
784 let mut offset = px(0.);
785 let mut separators = Vec::new();
786 let mut placed_any = false;
787
788 let mut place_separator = |offset: &mut Pixels, window: &mut Window, cx: &mut App| {
789 let mut sep = self.make_separator();
790 let sep_size = sep.layout_as_root(
791 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
792 window,
793 cx,
794 );
795 let origin = self.origin(bounds, sep_size, *offset);
796 window.with_content_mask(Some(ContentMask { bounds }), |window| {
797 sep.prepaint_at(origin, window, cx);
798 });
799 *offset += sep_size.width;
800 separators.push(sep);
801 };
802
803 for idx in plan.leading.clone() {
804 if placed_any {
805 place_separator(&mut offset, window, cx);
806 }
807 let item = &mut state.items[idx];
808 let origin = self.origin(bounds, item.preferred, offset);
809 window.with_content_mask(Some(ContentMask { bounds }), |window| {
810 item.inline.prepaint_at(origin, window, cx);
811 });
812 offset += item.preferred.width;
813 placed_any = true;
814 }
815
816 let menu = (!plan.collapsed.is_empty()).then(|| {
817 if placed_any {
818 place_separator(&mut offset, window, cx);
819 }
820 let mut menu =
821 self.build_overflow_menu(&state.items[plan.collapsed.clone()], window, cx);
822 let trigger_size = size(
823 OVERFLOW_TRIGGER_WIDTH,
824 OVERFLOW_TRIGGER_HEIGHT.min(bounds.size.height.max(ROW_MIN_HEIGHT)),
825 );
826 let measured =
827 menu.layout_as_root(trigger_size.map(AvailableSpace::Definite), window, cx);
828 let origin = self.origin(bounds, measured, offset);
829 menu.prepaint_at(origin, window, cx);
830 offset += measured.width;
831 placed_any = true;
832 menu
833 });
834
835 for idx in plan.trailing.clone() {
836 if placed_any {
837 place_separator(&mut offset, window, cx);
838 }
839 let item = &mut state.items[idx];
840 let origin = self.origin(bounds, item.preferred, offset);
841 window.with_content_mask(Some(ContentMask { bounds }), |window| {
842 item.inline.prepaint_at(origin, window, cx);
843 });
844 offset += item.preferred.width;
845 placed_any = true;
846 }
847
848 BreadcrumbsPrepaintState {
849 plan,
850 separators,
851 menu,
852 }
853 }
854
855 fn paint(
856 &mut self,
857 _: Option<&GlobalElementId>,
858 _: Option<&InspectorElementId>,
859 bounds: Bounds<Pixels>,
860 state: &mut Self::RequestLayoutState,
861 prepaint: &mut Self::PrepaintState,
862 window: &mut Window,
863 cx: &mut App,
864 ) {
865 window.with_content_mask(Some(ContentMask { bounds }), |window| {
866 for idx in prepaint.plan.leading.clone() {
867 state.items[idx].inline.paint(window, cx);
868 }
869 for sep in &mut prepaint.separators {
870 sep.paint(window, cx);
871 }
872 for idx in prepaint.plan.trailing.clone() {
873 state.items[idx].inline.paint(window, cx);
874 }
875 });
876 if let Some(menu) = &mut prepaint.menu {
877 menu.paint(window, cx);
878 }
879 }
880}
881
882#[cfg(test)]
883mod tests {
884 use super::*;
885
886 #[test]
887 fn collapse_plan_fits_when_space_permits_and_collapses_middle_by_max_items_or_width() {
888 let widths = [px(60.), px(90.), px(80.), px(50.), px(70.)];
889 let sep = px(20.);
890 let trigger = px(32.);
891 assert_eq!(
894 compute_collapse_plan(&widths, sep, trigger, None, px(500.)),
895 CollapsePlan {
896 leading: 0..5,
897 collapsed: 0..0,
898 trailing: 5..5,
899 }
900 );
901
902 assert_eq!(
904 compute_collapse_plan(&widths, sep, trigger, Some(3), px(500.)),
905 CollapsePlan {
906 leading: 0..1,
907 collapsed: 1..3,
908 trailing: 3..5,
909 }
910 );
911
912 assert_eq!(
914 compute_collapse_plan(&widths, sep, trigger, Some(2), px(500.)),
915 CollapsePlan {
916 leading: 0..1,
917 collapsed: 1..4,
918 trailing: 4..5,
919 }
920 );
921
922 assert_eq!(
925 compute_collapse_plan(&widths, sep, trigger, None, px(340.)),
926 CollapsePlan {
927 leading: 0..1,
928 collapsed: 1..3,
929 trailing: 3..5,
930 }
931 );
932
933 assert_eq!(
935 compute_collapse_plan(&widths, sep, trigger, None, px(220.)),
936 CollapsePlan {
937 leading: 0..1,
938 collapsed: 1..4,
939 trailing: 4..5,
940 }
941 );
942
943 assert_eq!(
945 compute_collapse_plan(&[px(80.), px(90.)], sep, trigger, Some(2), px(100.)),
946 CollapsePlan {
947 leading: 0..2,
948 collapsed: 0..0,
949 trailing: 2..2,
950 }
951 );
952 }
953}