1use std::rc::Rc;
2
3use gpui::{
4 AccessibleAction, AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId,
5 FocusHandle, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
6 ParentElement, Pixels, Point, RenderOnce, Role, SharedString, Size, StatefulInteractiveElement,
7 Style, Styled, Window, div, point, prelude::FluentBuilder, px, relative, size,
8};
9use gpui_base::{Button as BaseButton, TestSupportExt};
10use gpui_material_foundation::{
11 ThemeScope, current_material_strings, current_material_theme, text_style,
12};
13use gpui_material_theme::{Direction, TypeRole, TypographyEmphasis};
14
15use crate::{Icon, IconName, Menu, MenuItem, navigation::overflow_strip::OverflowStripHandle};
16
17use super::{
18 BreadcrumbItem, Breadcrumbs,
19 layout::{CollapsePlan, compute_collapse_plan},
20 types::{IconFactory, ResolvedColors},
21};
22
23const ROW_MIN_HEIGHT: Pixels = px(32.);
24const ITEM_GAP: Pixels = px(4.);
25const OVERFLOW_TRIGGER_WIDTH: Pixels = px(32.);
26const OVERFLOW_TRIGGER_HEIGHT: Pixels = px(32.);
27
28impl RenderOnce for Breadcrumbs {
29 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
30 let id = self.id.clone();
31 let label = self.accessible_label.clone().unwrap_or_else(|| {
32 SharedString::from(current_material_strings(window, cx).breadcrumb.clone())
33 });
34 div()
35 .id(id)
36 .test_support()
37 .role(Role::Navigation)
38 .aria_label(label)
39 .w_full()
40 .overflow_hidden()
41 .child(BreadcrumbsLayout::new(self, window, cx))
42 }
43}
44
45struct PreparedItem {
46 id: SharedString,
47 label: SharedString,
48 icon: Option<IconFactory>,
49 disabled: bool,
50 is_current: bool,
51 focus: Option<FocusHandle>,
52 inline: AnyElement,
53 preferred: Size<Pixels>,
54}
55
56struct BreadcrumbsLayout {
57 breadcrumbs: Breadcrumbs,
58 overflow_label: SharedString,
59 direction: Direction,
60 colors: ResolvedColors,
61 overflow: OverflowStripHandle<SharedString>,
62}
63
64impl BreadcrumbsLayout {
65 fn new(mut breadcrumbs: Breadcrumbs, window: &mut Window, cx: &mut App) -> Self {
66 let overflow_label = breadcrumbs.overflow_label.take().unwrap_or_else(|| {
67 SharedString::from(
68 current_material_strings(window, cx)
69 .more_breadcrumbs
70 .clone(),
71 )
72 });
73 let overflow =
74 OverflowStripHandle::use_state(&breadcrumbs.id, "breadcrumbs-overflow", window, cx);
75 Self {
76 direction: current_material_theme(window, cx).layout.direction,
77 colors: breadcrumbs.colors.resolve(window, cx),
78 overflow_label,
79 overflow,
80 breadcrumbs,
81 }
82 }
83
84 fn make_separator(&self) -> AnyElement {
85 let glyph = match &self.breadcrumbs.separator {
86 Some(factory) => factory(),
87 None => Icon::new(IconName::ChevronRight)
88 .size(px(16.))
89 .mirror_in_rtl(true)
90 .into_any_element(),
91 };
92 div()
93 .flex_none()
94 .flex()
95 .items_center()
96 .justify_center()
97 .px(ITEM_GAP)
98 .text_color(self.colors.separator)
99 .child(glyph)
100 .into_any_element()
101 }
102
103 fn prepare_item(
104 &self,
105 item: BreadcrumbItem,
106 is_current: bool,
107 window: &mut Window,
108 cx: &mut App,
109 ) -> PreparedItem {
110 let rtl = self.direction == Direction::Rtl;
111 let elem_id = ElementId::from((self.breadcrumbs.id.clone(), item.id.clone()));
112
113 if is_current {
114 let fg = if item.disabled {
115 self.colors.disabled
116 } else {
117 self.colors.current
118 };
119 let current_aria: SharedString = format!("{}, current page", item.label).into();
120 let mut inline = div()
121 .id(elem_id)
122 .test_support()
123 .role(Role::Label)
124 .aria_label(current_aria)
125 .h(ROW_MIN_HEIGHT)
126 .px(px(6.))
127 .flex()
128 .flex_row()
129 .items_center()
130 .gap(px(4.))
131 .when(rtl, Styled::flex_row_reverse)
132 .text_color(fg)
133 .children(
134 item.icon
135 .as_ref()
136 .map(|icon| div().flex_none().text_size(px(16.)).child(icon())),
137 )
138 .child(
139 text_style(
140 div().whitespace_nowrap(),
141 TypeRole::TitleSmall.style(TypographyEmphasis::Baseline),
142 1.,
143 window,
144 cx,
145 )
146 .child(item.label.clone()),
147 )
148 .into_any_element();
149 let preferred = inline.layout_as_root(
150 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
151 window,
152 cx,
153 );
154 return PreparedItem {
155 id: item.id,
156 label: item.label,
157 icon: item.icon,
158 disabled: item.disabled,
159 is_current: true,
160 focus: None,
161 inline,
162 preferred,
163 };
164 }
165
166 let focus = window.with_id(
167 ElementId::from((self.breadcrumbs.id.clone(), "breadcrumb-focus")),
168 |window| {
169 window
170 .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
171 .read(cx)
172 .clone()
173 },
174 );
175
176 let fg = if item.disabled {
177 self.colors.disabled
178 } else {
179 self.colors.ancestor
180 };
181 let hover_bg = self.colors.hover;
182 let focus_ring = self.colors.focus_ring;
183
184 let activate = (!item.disabled).then(|| {
185 self.breadcrumbs.on_select.as_ref().map(|on_select| {
186 let on_select = on_select.clone();
187 let item_id = item.id.clone();
188 Rc::new(ThemeScope::bind_action(
189 move |window, cx| on_select(item_id.clone(), window, cx),
190 window,
191 cx,
192 ))
193 })
194 });
195 let activate = activate.flatten();
196
197 let click_handler = activate.clone();
198 let a11y_handler = activate;
199
200 let mut inline = BaseButton::new(elem_id)
201 .track_focus(&focus)
202 .disabled(item.disabled)
203 .accessibility_label(item.label.clone())
204 .h(ROW_MIN_HEIGHT)
205 .px(px(6.))
206 .rounded(px(8.))
207 .border_2()
208 .border_color(gpui::transparent_black())
209 .flex()
210 .flex_row()
211 .items_center()
212 .gap(px(4.))
213 .when(rtl, Styled::flex_row_reverse)
214 .text_color(fg)
215 .when(!item.disabled, move |button| {
216 button
217 .hover(move |b| b.bg(hover_bg))
218 .focus_visible(move |b| b.border_color(focus_ring))
219 })
220 .when_some(click_handler, |button, handler| {
221 button.on_click(move |_, window, cx| {
222 cx.stop_propagation();
223 handler(window, cx);
224 })
225 })
226 .when_some(a11y_handler, |button, handler| {
227 button.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
228 handler(window, cx);
229 })
230 })
231 .children(
232 item.icon
233 .as_ref()
234 .map(|icon| div().flex_none().text_size(px(16.)).child(icon())),
235 )
236 .child(
237 text_style(
238 div().whitespace_nowrap(),
239 TypeRole::LabelLarge.style(TypographyEmphasis::Baseline),
240 1.,
241 window,
242 cx,
243 )
244 .child(item.label.clone()),
245 )
246 .into_any_element();
247
248 let preferred = inline.layout_as_root(
249 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
250 window,
251 cx,
252 );
253
254 PreparedItem {
255 id: item.id,
256 label: item.label,
257 icon: item.icon,
258 disabled: item.disabled,
259 is_current: false,
260 focus: Some(focus),
261 inline,
262 preferred,
263 }
264 }
265
266 fn transfer_focus(
267 &self,
268 plan: &CollapsePlan,
269 items: &[PreparedItem],
270 window: &mut Window,
271 cx: &mut App,
272 ) {
273 let has_overflow = !plan.collapsed.is_empty();
274 let hidden_focused = has_overflow.then(|| {
275 items[plan.collapsed.clone()]
276 .iter()
277 .find(|item| {
278 item.focus
279 .as_ref()
280 .is_some_and(|focus| focus.contains_focused(window, cx))
281 })
282 .map(|item| {
283 let fallback = item
284 .focus
285 .clone()
286 .unwrap_or_else(|| self.overflow.focus.clone());
287 (item.id.clone(), fallback)
288 })
289 });
290 self.overflow.transfer_focus(
291 has_overflow,
292 hidden_focused.flatten(),
293 |id| {
294 plan.leading
295 .clone()
296 .chain(plan.trailing.clone())
297 .any(|idx| {
298 !items[idx].disabled && !items[idx].is_current && items[idx].id == *id
299 })
300 },
301 || {
302 items
303 .iter()
304 .find(|item| !item.disabled && !item.is_current)
305 .and_then(|item| item.focus.clone())
306 },
307 window,
308 cx,
309 );
310 }
311
312 fn build_overflow_menu(
313 &self,
314 collapsed: &[PreparedItem],
315 trigger_size: Size<Pixels>,
316 window: &mut Window,
317 cx: &mut App,
318 ) -> AnyElement {
319 let entries: Vec<MenuItem> = collapsed
320 .iter()
321 .map(|item| {
322 let mut entry = MenuItem::new(
323 ElementId::from((self.breadcrumbs.id.clone(), item.id.clone())),
324 item.label.clone(),
325 )
326 .disabled(item.disabled);
327 if let Some(icon) = item.icon.clone() {
328 entry = entry.leading(move || icon());
329 }
330 if !item.disabled
331 && let Some(on_select) = self.breadcrumbs.on_select.clone()
332 {
333 let item_id = item.id.clone();
334 let bound = ThemeScope::bind_action(
335 move |window, cx| on_select(item_id.clone(), window, cx),
336 window,
337 cx,
338 );
339 entry = entry.on_activate(move |window, cx| bound(window, cx));
340 }
341 entry
342 })
343 .collect();
344
345 let controller = self.overflow.controller.clone();
346 let observed = controller.clone();
347 let trigger_focus = self.overflow.focus.clone();
348 let trigger_id = ElementId::from((self.breadcrumbs.id.clone(), "overflow"));
349 let label = self.overflow_label.clone();
350 let ink = self.colors.ancestor;
351 let hover_bg = self.colors.hover;
352 let focus_ring = self.colors.focus_ring;
353
354 Menu::composed(
355 (self.breadcrumbs.id.clone(), "overflow-menu"),
356 entries,
357 move |_, toggle| {
358 let return_focus = trigger_focus.clone();
359 let dots = div()
360 .flex()
361 .flex_row()
362 .items_center()
363 .gap(px(2.5))
364 .children((0..3).map(|_| div().size(px(3.5)).rounded_full().bg(ink)));
365 BaseButton::new(trigger_id)
366 .track_focus(&trigger_focus)
367 .accessibility_label(label)
368 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
369 return_focus.focus(window, cx);
370 toggle(window, cx);
371 })
372 .w(trigger_size.width)
373 .h(trigger_size.height)
374 .p_0()
375 .flex()
376 .items_center()
377 .justify_center()
378 .overflow_hidden()
379 .rounded(px(8.))
380 .border_2()
381 .border_color(gpui::transparent_black())
382 .text_color(ink)
383 .hover(move |button| button.bg(hover_bg))
384 .focus_visible(move |button| button.border_color(focus_ring))
385 .child(dots)
386 .into_any_element()
387 },
388 )
389 .open(controller.is_showing())
390 .on_open_change(move |open, window, cx| observed.set(open, window, cx))
391 .into_any_element()
392 }
393
394 fn origin(&self, bounds: Bounds<Pixels>, child: Size<Pixels>, offset: Pixels) -> Point<Pixels> {
395 let dy = (bounds.size.height - child.height).max(px(0.)) / 2.;
396 match self.direction {
397 Direction::Ltr => point(bounds.left() + offset, bounds.top() + dy),
398 Direction::Rtl => point(bounds.right() - offset - child.width, bounds.top() + dy),
399 }
400 }
401}
402
403struct BreadcrumbsLayoutState {
404 items: Vec<PreparedItem>,
405 sep_width: Pixels,
406}
407
408struct BreadcrumbsPrepaintState {
409 plan: CollapsePlan,
410 separators: Vec<AnyElement>,
411 menu: Option<AnyElement>,
412}
413
414impl Element for BreadcrumbsLayout {
415 type RequestLayoutState = BreadcrumbsLayoutState;
416 type PrepaintState = BreadcrumbsPrepaintState;
417
418 fn id(&self) -> Option<ElementId> {
419 Some(ElementId::from((self.breadcrumbs.id.clone(), "layout")))
420 }
421
422 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
423 None
424 }
425
426 fn a11y_role(&self) -> Option<Role> {
427 None
428 }
429
430 fn request_layout(
431 &mut self,
432 _: Option<&GlobalElementId>,
433 _: Option<&InspectorElementId>,
434 window: &mut Window,
435 cx: &mut App,
436 ) -> (LayoutId, Self::RequestLayoutState) {
437 let raw_items = std::mem::take(&mut self.breadcrumbs.items);
438 let len = raw_items.len();
439 let items: Vec<PreparedItem> = raw_items
440 .into_iter()
441 .enumerate()
442 .map(|(idx, item)| self.prepare_item(item, idx + 1 == len, window, cx))
443 .collect();
444
445 let mut probe_sep = self.make_separator();
446 let sep_size = probe_sep.layout_as_root(
447 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
448 window,
449 cx,
450 );
451 let sep_width = sep_size.width;
452
453 let widths: Vec<Pixels> = items.iter().map(|i| i.preferred.width).collect();
454 let preferred_plan = compute_collapse_plan(
455 &widths,
456 sep_width,
457 OVERFLOW_TRIGGER_WIDTH,
458 self.breadcrumbs.max_items,
459 px(f32::INFINITY),
460 );
461
462 let visible_segments = preferred_plan.leading.len()
463 + usize::from(!preferred_plan.collapsed.is_empty())
464 + preferred_plan.trailing.len();
465 let mut preferred_width = preferred_plan
466 .leading
467 .clone()
468 .chain(preferred_plan.trailing.clone())
469 .map(|i| items[i].preferred.width)
470 .sum::<Pixels>();
471 if !preferred_plan.collapsed.is_empty() {
472 preferred_width += OVERFLOW_TRIGGER_WIDTH;
473 }
474 if visible_segments > 1 {
475 preferred_width += sep_width * (visible_segments - 1) as f32;
476 }
477
478 let cross = items.iter().map(|item| item.preferred.height).fold(
479 if items.is_empty() {
480 px(0.)
481 } else {
482 ROW_MIN_HEIGHT.max(sep_size.height)
483 },
484 Pixels::max,
485 );
486
487 let style = Style {
488 size: size(preferred_width.into(), cross.into()),
489 min_size: size(px(0.).into(), px(0.).into()),
490 max_size: size(relative(1.).into(), relative(1.).into()),
491 ..Default::default()
492 };
493
494 (
495 window.request_layout(style, None, cx),
496 BreadcrumbsLayoutState { items, sep_width },
497 )
498 }
499
500 fn prepaint(
501 &mut self,
502 _: Option<&GlobalElementId>,
503 _: Option<&InspectorElementId>,
504 bounds: Bounds<Pixels>,
505 state: &mut Self::RequestLayoutState,
506 window: &mut Window,
507 cx: &mut App,
508 ) -> Self::PrepaintState {
509 let widths: Vec<Pixels> = state.items.iter().map(|i| i.preferred.width).collect();
510 let plan = compute_collapse_plan(
511 &widths,
512 state.sep_width,
513 OVERFLOW_TRIGGER_WIDTH,
514 self.breadcrumbs.max_items,
515 bounds.size.width,
516 );
517 self.transfer_focus(&plan, &state.items, window, cx);
518
519 let mut offset = px(0.);
520 let mut separators = Vec::new();
521 let mut placed_any = false;
522 let mask = Some(ContentMask { bounds });
523
524 let mut place_separator = |offset: &mut Pixels, window: &mut Window, cx: &mut App| {
525 let mut sep = self.make_separator();
526 let sep_size = sep.layout_as_root(
527 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
528 window,
529 cx,
530 );
531 let origin = self.origin(bounds, sep_size, *offset);
532 window.with_content_mask(mask, |window| {
533 sep.prepaint_at(origin, window, cx);
534 });
535 *offset += sep_size.width;
536 separators.push(sep);
537 };
538
539 for idx in plan.leading.clone() {
540 if placed_any {
541 place_separator(&mut offset, window, cx);
542 }
543 let item = &mut state.items[idx];
544 let origin = self.origin(bounds, item.preferred, offset);
545 window.with_content_mask(mask, |window| {
546 item.inline.prepaint_at(origin, window, cx);
547 });
548 offset += item.preferred.width;
549 placed_any = true;
550 }
551
552 let menu = (!plan.collapsed.is_empty()).then(|| {
553 if placed_any {
554 place_separator(&mut offset, window, cx);
555 }
556 let trigger_size = size(
557 OVERFLOW_TRIGGER_WIDTH.min((bounds.size.width - offset).max(px(0.))),
558 OVERFLOW_TRIGGER_HEIGHT.min(bounds.size.height.max(ROW_MIN_HEIGHT)),
559 );
560 let mut menu = self.build_overflow_menu(
561 &state.items[plan.collapsed.clone()],
562 trigger_size,
563 window,
564 cx,
565 );
566 let measured =
567 menu.layout_as_root(trigger_size.map(AvailableSpace::Definite), window, cx);
568 let origin = self.origin(bounds, measured, offset);
569 window.with_content_mask(mask, |window| {
570 menu.prepaint_at(origin, window, cx);
571 });
572 offset += measured.width;
573 placed_any = true;
574 menu
575 });
576
577 for idx in plan.trailing.clone() {
578 if placed_any {
579 place_separator(&mut offset, window, cx);
580 }
581 let item = &mut state.items[idx];
582 let origin = self.origin(bounds, item.preferred, offset);
583 window.with_content_mask(mask, |window| {
584 item.inline.prepaint_at(origin, window, cx);
585 });
586 offset += item.preferred.width;
587 placed_any = true;
588 }
589
590 BreadcrumbsPrepaintState {
591 plan,
592 separators,
593 menu,
594 }
595 }
596
597 fn paint(
598 &mut self,
599 _: Option<&GlobalElementId>,
600 _: Option<&InspectorElementId>,
601 bounds: Bounds<Pixels>,
602 state: &mut Self::RequestLayoutState,
603 prepaint: &mut Self::PrepaintState,
604 window: &mut Window,
605 cx: &mut App,
606 ) {
607 let mask = Some(ContentMask { bounds });
608 window.with_content_mask(mask, |window| {
609 for idx in prepaint.plan.leading.clone() {
610 state.items[idx].inline.paint(window, cx);
611 }
612 for sep in &mut prepaint.separators {
613 sep.paint(window, cx);
614 }
615 for idx in prepaint.plan.trailing.clone() {
616 state.items[idx].inline.paint(window, cx);
617 }
618 if let Some(menu) = &mut prepaint.menu {
619 menu.paint(window, cx);
620 }
621 });
622 }
623}