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