1use std::{
2 cell::{Cell, RefCell},
3 rc::Rc,
4};
5
6use gpui::{
7 AccessibleAction, AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId,
8 FocusHandle, GlobalElementId, Hsla, InspectorElementId, InteractiveElement, IntoElement,
9 LayoutId, ParentElement, Pixels, Point, RenderOnce, Role, SharedString, Size,
10 StatefulInteractiveElement, Style, Styled, Window, div, point, px, relative, size,
11};
12use gpui_base::Button;
13use gpui_material_foundation::current_material_theme;
14use gpui_material_theme::Direction;
15
16use crate::{ButtonColors, IconButton, Menu, MenuItem};
17
18const TRIGGER_SIZE: Pixels = px(48.);
19type OnActivate = Rc<dyn Fn(&mut Window, &mut App)>;
20type MenuItemBuilder = Box<dyn FnOnce(AppBarMenuState) -> MenuItem>;
21type OverflowIndicator = Box<dyn FnOnce(AppBarMenuState) -> AnyElement>;
22type DisplacedFocus = Rc<RefCell<Option<(ElementId, FocusHandle)>>>;
23
24enum ItemContent {
25 Clickable {
26 label: SharedString,
27 icon: Rc<dyn Fn() -> AnyElement>,
28 on_activate: Option<OnActivate>,
29 },
30 Custom {
31 inline: AnyElement,
32 menu: MenuItemBuilder,
33 },
34}
35
36pub struct AppBarItem {
38 id: ElementId,
39 disabled: bool,
40 content: ItemContent,
41}
42
43impl AppBarItem {
44 pub fn clickable<E: IntoElement>(
47 id: impl Into<ElementId>,
48 label: impl Into<SharedString>,
49 icon: impl Fn() -> E + 'static,
50 ) -> Self {
51 Self {
52 id: id.into(),
53 disabled: false,
54 content: ItemContent::Clickable {
55 label: label.into(),
56 icon: Rc::new(move || icon().into_any_element()),
57 on_activate: None,
58 },
59 }
60 }
61
62 pub fn custom(
64 id: impl Into<ElementId>,
65 inline: impl IntoElement,
66 menu: impl FnOnce(AppBarMenuState) -> MenuItem + 'static,
67 ) -> Self {
68 Self {
69 id: id.into(),
70 disabled: false,
71 content: ItemContent::Custom {
72 inline: inline.into_any_element(),
73 menu: Box::new(menu),
74 },
75 }
76 }
77
78 pub fn disabled(mut self, disabled: bool) -> Self {
80 self.disabled = disabled;
81 self
82 }
83
84 pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
86 if let ItemContent::Clickable { on_activate, .. } = &mut self.content {
87 *on_activate = Some(Rc::new(action));
88 }
89 self
90 }
91
92 fn prepare(self, ink: Hsla, window: &mut Window, cx: &mut App) -> Prepared {
93 let focus = window
94 .use_keyed_state((self.id.clone(), "app-bar-item"), cx, |_, cx| {
95 cx.focus_handle()
96 })
97 .read(cx)
98 .clone();
99 let (mut inline, menu) = match self.content {
100 ItemContent::Clickable {
101 label,
102 icon,
103 on_activate,
104 } => {
105 let mut inline = IconButton::new(self.id.clone(), label.clone(), icon())
106 .colors(ButtonColors {
107 content: Some(ink),
108 ..Default::default()
109 })
110 .disabled(self.disabled)
111 .track_focus(&focus);
112 if let Some(on_activate) = on_activate.clone() {
113 inline = inline.on_activate(move |window, cx| on_activate(window, cx));
114 }
115 let id = self.id.clone();
116 let disabled = self.disabled;
117 let menu = move |_| {
118 let mut item = MenuItem::new(id, label)
119 .leading(move || icon())
120 .disabled(disabled);
121 if let Some(on_activate) = on_activate {
122 item = item.on_activate(move |window, cx| on_activate(window, cx));
123 }
124 item
125 };
126 (inline.into_any_element(), Box::new(menu) as MenuItemBuilder)
127 }
128 ItemContent::Custom { inline, menu } => (
129 div()
130 .id(self.id.clone())
131 .track_focus(&focus)
132 .child(inline)
133 .into_any_element(),
134 menu,
135 ),
136 };
137 let preferred = inline.layout_as_root(
138 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
139 window,
140 cx,
141 );
142 Prepared {
143 id: self.id,
144 inline,
145 menu: Some(menu),
146 focus,
147 preferred,
148 enabled: !self.disabled,
149 }
150 }
151}
152
153struct Prepared {
154 id: ElementId,
155 inline: AnyElement,
156 menu: Option<MenuItemBuilder>,
157 focus: FocusHandle,
158 preferred: Size<Pixels>,
159 enabled: bool,
160}
161
162#[derive(Clone)]
164pub struct AppBarMenuState {
165 shown: Rc<Cell<bool>>,
166 has_overflow: Rc<Cell<bool>>,
167 view: gpui::EntityId,
168}
169
170impl AppBarMenuState {
171 pub fn is_showing(&self) -> bool {
173 self.shown.get()
174 }
175
176 pub fn show(&self, window: &mut Window, cx: &mut App) {
178 if self.has_overflow.get() {
179 self.set(true, window, cx);
180 }
181 }
182
183 pub fn dismiss(&self, window: &mut Window, cx: &mut App) {
185 self.set(false, window, cx);
186 }
187
188 fn set(&self, shown: bool, window: &mut Window, cx: &mut App) {
189 if self.shown.replace(shown) != shown {
190 cx.notify(self.view);
191 window.refresh();
192 }
193 }
194}
195
196struct OverflowState {
197 shown: Rc<Cell<bool>>,
198 has_overflow: Rc<Cell<bool>>,
199 focus: FocusHandle,
200 displaced: DisplacedFocus,
201}
202
203struct Strip {
204 id: ElementId,
205 items: Vec<AppBarItem>,
206 label: SharedString,
207 overflow_label: SharedString,
208 overflow_indicator: Option<OverflowIndicator>,
209 max_item_count: usize,
210}
211
212impl Strip {
213 fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = AppBarItem>) -> Self {
214 Self {
215 id: id.into(),
216 items: items.into_iter().collect(),
217 label: "App bar actions".into(),
218 overflow_label: "More actions".into(),
219 overflow_indicator: None,
220 max_item_count: usize::MAX,
221 }
222 }
223}
224
225#[derive(IntoElement)]
227pub struct AppBarRow(Strip);
228
229#[derive(IntoElement)]
231pub struct AppBarColumn(Strip);
232
233macro_rules! action_strip {
234 ($name:ident, $axis:expr) => {
235 impl $name {
236 pub fn new(
238 id: impl Into<ElementId>,
239 items: impl IntoIterator<Item = AppBarItem>,
240 ) -> Self {
241 Self(Strip::new(id, items))
242 }
243
244 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
246 self.0.label = label.into();
247 self
248 }
249
250 pub fn max_item_count(mut self, count: usize) -> Self {
252 self.0.max_item_count = count.max(1);
253 self
254 }
255
256 pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
258 self.0.overflow_label = label.into();
259 self
260 }
261
262 pub fn overflow_indicator<E: IntoElement>(
264 mut self,
265 build: impl FnOnce(AppBarMenuState) -> E + 'static,
266 ) -> Self {
267 self.0.overflow_indicator =
268 Some(Box::new(move |state| build(state).into_any_element()));
269 self
270 }
271 }
272
273 impl RenderOnce for $name {
274 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
275 StripLayout::new(self.0, $axis, window, cx)
276 }
277 }
278 };
279}
280
281action_strip!(AppBarRow, Axis::Horizontal);
282action_strip!(AppBarColumn, Axis::Vertical);
283
284#[derive(Clone, Copy, PartialEq, Eq)]
285enum Axis {
286 Horizontal,
287 Vertical,
288}
289
290impl Axis {
291 fn extent(self, size: Size<Pixels>) -> Pixels {
292 match self {
293 Self::Horizontal => size.width,
294 Self::Vertical => size.height,
295 }
296 }
297
298 fn cross(self, size: Size<Pixels>) -> Pixels {
299 match self {
300 Self::Horizontal => size.height,
301 Self::Vertical => size.width,
302 }
303 }
304
305 fn size(self, extent: Pixels, cross: Pixels) -> Size<Pixels> {
306 match self {
307 Self::Horizontal => size(extent, cross),
308 Self::Vertical => size(cross, extent),
309 }
310 }
311
312 fn origin(
313 self,
314 bounds: Bounds<Pixels>,
315 child: Size<Pixels>,
316 offset: Pixels,
317 direction: Direction,
318 ) -> Point<Pixels> {
319 let delta = (self.cross(bounds.size) - self.cross(child)).max(px(0.)) / 2.;
320 match (self, direction) {
321 (Self::Horizontal, Direction::Rtl) => {
322 point(bounds.right() - offset - child.width, bounds.top() + delta)
323 }
324 (Self::Horizontal, Direction::Ltr) => {
325 point(bounds.left() + offset, bounds.top() + delta)
326 }
327 (Self::Vertical, _) => point(bounds.left() + delta, bounds.top() + offset),
328 }
329 }
330}
331
332struct StripLayout {
333 strip: Strip,
334 axis: Axis,
335 direction: Direction,
336 ink: Hsla,
337 menu: AppBarMenuState,
338 overflow_focus: FocusHandle,
339 displaced: DisplacedFocus,
340}
341
342impl StripLayout {
343 fn new(strip: Strip, axis: Axis, window: &mut Window, cx: &mut App) -> Self {
344 let overflow =
345 window.use_keyed_state((strip.id.clone(), "app-bar-overflow"), cx, |_, cx| {
346 OverflowState {
347 shown: Rc::new(Cell::new(false)),
348 has_overflow: Rc::new(Cell::new(false)),
349 focus: cx.focus_handle(),
350 displaced: Rc::new(RefCell::new(None)),
351 }
352 });
353 let overflow = overflow.read(cx);
354 Self {
355 strip,
356 axis,
357 direction: current_material_theme(window, cx).layout.direction,
358 ink: window.text_style().color,
359 menu: AppBarMenuState {
360 shown: overflow.shown.clone(),
361 has_overflow: overflow.has_overflow.clone(),
362 view: window.current_view(),
363 },
364 overflow_focus: overflow.focus.clone(),
365 displaced: overflow.displaced.clone(),
366 }
367 }
368
369 fn transfer_focus(
370 &self,
371 shown: usize,
372 items: &[Prepared],
373 overflow: bool,
374 window: &mut Window,
375 cx: &mut App,
376 ) {
377 let in_overflow = self.overflow_focus.is_focused(window);
378 let previous_overflow = self.menu.has_overflow.replace(overflow);
379 let menu_was_open = self.menu.is_showing();
380 let mut displaced = self.displaced.borrow_mut();
381 if overflow
382 && let Some(hidden) = items[shown..]
383 .iter()
384 .find(|item| item.focus.contains_focused(window, cx))
385 {
386 let old_focus = window.focused(cx).unwrap_or_else(|| hidden.focus.clone());
387 *displaced = Some((hidden.id.clone(), old_focus));
388 focus_after_layout(self.overflow_focus.clone(), window, cx);
389 return;
390 }
391 if !overflow && previous_overflow {
392 self.menu.shown.set(false);
393 }
394 let returned = displaced
395 .as_ref()
396 .filter(|(id, _)| {
397 items[..shown]
398 .iter()
399 .any(|item| item.enabled && item.id == *id)
400 })
401 .map(|(_, focus)| focus.clone());
402 let restore = if !overflow && (in_overflow || menu_was_open) {
403 returned.or_else(|| {
404 items[..shown]
405 .iter()
406 .find(|item| item.enabled)
407 .map(|item| item.focus.clone())
408 })
409 } else if in_overflow {
410 returned
411 } else {
412 None
413 };
414 if let Some(focus) = restore {
415 displaced.take();
416 focus_after_layout(focus, window, cx);
417 } else if !overflow {
418 displaced.take();
419 }
420 }
421
422 fn overflow_menu(&mut self, hidden: &mut [Prepared], size: Size<Pixels>) -> AnyElement {
423 let state = self.menu.clone();
424 let entries: Vec<_> = hidden
425 .iter_mut()
426 .filter_map(|item| item.menu.take().map(|build| build(state.clone())))
427 .collect();
428 let trigger_focus = self.overflow_focus.clone();
429 let label = self.strip.overflow_label.clone();
430 let trigger_id = ElementId::from((self.strip.id.clone(), "overflow"));
431 let ink = self.ink;
432 let glyph = self.strip.overflow_indicator.take().map_or_else(
433 || {
434 let unit = px(4.).min(size.width / 4.).min(size.height / 4.);
435 div()
436 .flex()
437 .flex_col()
438 .gap(unit / 2.)
439 .children((0..3).map(|_| div().size(unit).rounded_full().bg(ink)))
440 .into_any_element()
441 },
442 |build| build(state.clone()),
443 );
444 let observed = state.clone();
445 Menu::composed(
446 (self.strip.id.clone(), "menu"),
447 entries,
448 move |_, toggle| {
449 let return_focus = trigger_focus.clone();
450 Button::new(trigger_id)
451 .track_focus(&trigger_focus)
452 .accessibility_label(label)
453 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
454 return_focus.focus(window, cx);
455 toggle(window, cx);
456 })
457 .w(size.width)
458 .h(size.height)
459 .p_0()
460 .flex()
461 .items_center()
462 .justify_center()
463 .overflow_hidden()
464 .rounded_full()
465 .text_color(ink)
466 .hover(move |button| button.bg(ink.opacity(0.08)))
467 .focus_visible(move |button| button.border_2().border_color(ink))
468 .child(glyph)
469 .into_any_element()
470 },
471 )
472 .open(state.is_showing())
473 .on_open_change(move |open, window, cx| observed.set(open, window, cx))
474 .into_any_element()
475 }
476}
477
478fn focus_after_layout(target: FocusHandle, window: &mut Window, cx: &mut App) {
479 let origin = window.focused(cx);
480 window.on_next_frame(move |window, cx| {
481 let current = window.focused(cx);
482 if current.is_none() || current == origin {
483 target.focus(window, cx);
484 }
485 });
486}
487
488impl Element for StripLayout {
489 type RequestLayoutState = Vec<Prepared>;
490 type PrepaintState = (usize, Option<AnyElement>);
491
492 fn id(&self) -> Option<ElementId> {
493 Some(self.strip.id.clone())
494 }
495
496 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
497 None
498 }
499
500 fn a11y_role(&self) -> Option<Role> {
501 Some(Role::Group)
502 }
503
504 fn write_a11y_info(&self, node: &mut gpui::accesskit::Node) {
505 node.set_label(self.strip.label.as_ref());
506 }
507
508 fn request_layout(
509 &mut self,
510 _: Option<&GlobalElementId>,
511 _: Option<&InspectorElementId>,
512 window: &mut Window,
513 cx: &mut App,
514 ) -> (LayoutId, Self::RequestLayoutState) {
515 let items: Vec<_> = std::mem::take(&mut self.strip.items)
516 .into_iter()
517 .map(|item| item.prepare(self.ink, window, cx))
518 .collect();
519 let limited = items.len() > self.strip.max_item_count;
520 let preferred_count = if limited {
521 self.strip.max_item_count - 1
522 } else {
523 items.len()
524 };
525 let main = items[..preferred_count]
526 .iter()
527 .map(|item| self.axis.extent(item.preferred))
528 .sum::<Pixels>()
529 + if limited { TRIGGER_SIZE } else { px(0.) };
530 let cross = items
531 .iter()
532 .map(|item| self.axis.cross(item.preferred))
533 .fold(
534 if items.is_empty() {
535 px(0.)
536 } else {
537 TRIGGER_SIZE
538 },
539 Pixels::max,
540 );
541 let style = Style {
542 size: self.axis.size(main, cross).map(Into::into),
543 min_size: size(px(0.).into(), px(0.).into()),
544 max_size: size(relative(1.).into(), relative(1.).into()),
545 ..Default::default()
546 };
547 (window.request_layout(style, None, cx), items)
548 }
549
550 fn prepaint(
551 &mut self,
552 _: Option<&GlobalElementId>,
553 _: Option<&InspectorElementId>,
554 bounds: Bounds<Pixels>,
555 items: &mut Self::RequestLayoutState,
556 window: &mut Window,
557 cx: &mut App,
558 ) -> Self::PrepaintState {
559 let length = self.axis.extent(bounds.size);
560 let breadth = self.axis.cross(bounds.size);
561 let has_space = length > px(0.) && breadth > px(0.);
562 let shown = if has_space {
563 fit(
564 items.iter().map(|item| self.axis.extent(item.preferred)),
565 self.strip.max_item_count,
566 length,
567 TRIGGER_SIZE,
568 )
569 } else {
570 0
571 };
572 let overflow = has_space && shown < items.len();
573 self.transfer_focus(shown, items, overflow, window, cx);
574 let mut offset = px(0.);
575 for item in &mut items[..shown] {
576 let extent = self.axis.extent(item.preferred);
577 let child = if self.axis.cross(item.preferred) > breadth {
578 let cap = self.axis.size(extent, breadth);
579 item.inline
580 .layout_as_root(cap.map(AvailableSpace::Definite), window, cx)
581 } else {
582 item.preferred
583 };
584 let origin = self.axis.origin(bounds, child, offset, self.direction);
585 window.with_content_mask(Some(ContentMask { bounds }), |window| {
586 item.inline.prepaint_at(origin, window, cx)
587 });
588 offset += extent;
589 }
590 let menu = overflow.then(|| {
591 let size = self
592 .axis
593 .size(TRIGGER_SIZE.min(length - offset), TRIGGER_SIZE.min(breadth));
594 let mut menu = self.overflow_menu(&mut items[shown..], size);
595 let child = menu.layout_as_root(size.map(AvailableSpace::Definite), window, cx);
596 menu.prepaint_at(
597 self.axis.origin(bounds, child, offset, self.direction),
598 window,
599 cx,
600 );
601 menu
602 });
603 (shown, menu)
604 }
605
606 fn paint(
607 &mut self,
608 _: Option<&GlobalElementId>,
609 _: Option<&InspectorElementId>,
610 bounds: Bounds<Pixels>,
611 items: &mut Self::RequestLayoutState,
612 (shown, menu): &mut Self::PrepaintState,
613 window: &mut Window,
614 cx: &mut App,
615 ) {
616 window.with_content_mask(Some(ContentMask { bounds }), |window| {
617 for item in &mut items[..*shown] {
618 item.inline.paint(window, cx);
619 }
620 });
621 if let Some(menu) = menu {
622 menu.paint(window, cx);
623 }
624 }
625}
626
627fn fit<I: Clone + ExactSizeIterator<Item = Pixels>>(
628 extents: I,
629 max_count: usize,
630 available: Pixels,
631 trigger: Pixels,
632) -> usize {
633 if extents.len() <= max_count && extents.clone().sum::<Pixels>() <= available {
634 return extents.len();
635 }
636 let mut remaining = available - trigger;
637 extents
638 .take(max_count.saturating_sub(1))
639 .take_while(|extent| {
640 remaining -= *extent;
641 remaining >= px(0.)
642 })
643 .count()
644}