1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 AnyElement, App, AvailableSpace, BorderStyle, Bounds, ContentMask, Corners, ElementId, Hsla,
5 InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, Role, ScrollHandle,
6 SharedString, StatefulInteractiveElement, Styled, Window, canvas, div, point, px, quad, size,
7};
8use gpui_material_foundation::{animate, current_material_theme};
9use gpui_material_theme::{CornerShape, Direction, MotionKind, MotionSpec, MotionSpeed};
10
11use super::items::{NavigationItems, Presentation};
12
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum TabVariant {
16 #[default]
18 Primary,
19 Secondary,
21}
22
23#[derive(Clone, Copy, Debug, Default, PartialEq)]
25pub struct TabsColors {
26 pub container: Option<Hsla>,
28 pub content: Option<Hsla>,
30 pub divider: Option<Hsla>,
32}
33
34#[derive(Clone, Copy, Debug, Default, PartialEq)]
36pub enum TabIndicatorWidth {
37 #[default]
39 Default,
40 Tab,
42 Content,
44 Fixed(Pixels),
46}
47
48#[derive(Clone, Copy, Debug, Default, PartialEq)]
50pub struct TabIndicatorStyle {
51 pub width: TabIndicatorWidth,
53 pub height: Option<Pixels>,
55 pub color: Option<Hsla>,
57 pub shape: Option<CornerShape>,
59 pub motion: Option<MotionSpec>,
61}
62
63#[derive(Clone, Debug, PartialEq)]
65pub struct TabIndicatorLayout {
66 pub selected: SharedString,
68 pub bounds: Bounds<Pixels>,
70 pub tab_bounds: Bounds<Pixels>,
72 pub content_width: Pixels,
74 pub color: Hsla,
76 pub direction: Direction,
78}
79
80type Indicator = Box<dyn Fn(TabIndicatorLayout) -> AnyElement>;
81
82pub(super) struct TabOptions {
83 pub colors: TabsColors,
84 pub scroll: Option<ScrollHandle>,
85 pub edge_padding: Pixels,
86 pub min_tab_width: Pixels,
87 pub divider: Option<AnyElement>,
88 pub indicator_style: Option<TabIndicatorStyle>,
89 pub indicator_content: Option<Indicator>,
90}
91
92impl Default for TabOptions {
93 fn default() -> Self {
94 Self {
95 colors: TabsColors::default(),
96 scroll: None,
97 edge_padding: px(52.),
98 min_tab_width: px(90.),
99 divider: None,
100 indicator_style: None,
101 indicator_content: None,
102 }
103 }
104}
105
106#[derive(IntoElement)]
108pub struct Tabs {
109 items: NavigationItems,
110 variant: TabVariant,
111 scrollable: bool,
112 options: TabOptions,
113}
114
115impl Tabs {
116 pub fn new(items: NavigationItems) -> Self {
118 Self {
119 items,
120 variant: TabVariant::Primary,
121 scrollable: false,
122 options: TabOptions::default(),
123 }
124 }
125
126 pub fn variant(mut self, variant: TabVariant) -> Self {
128 self.variant = variant;
129 self
130 }
131
132 pub fn scrollable(mut self, scrollable: bool) -> Self {
134 self.scrollable = scrollable;
135 self
136 }
137
138 pub fn scroll_handle(mut self, handle: &ScrollHandle) -> Self {
140 self.options.scroll = Some(handle.clone());
141 self
142 }
143
144 pub fn edge_padding(mut self, padding: Pixels) -> Self {
146 self.options.edge_padding = length(padding).unwrap_or(px(52.));
147 self
148 }
149
150 pub fn min_tab_width(mut self, width: Pixels) -> Self {
152 self.options.min_tab_width = length(width).unwrap_or(px(90.));
153 self
154 }
155
156 pub fn colors(mut self, colors: TabsColors) -> Self {
158 self.options.colors = colors;
159 self
160 }
161
162 pub fn divider(mut self, divider: impl IntoElement) -> Self {
164 self.options.divider = Some(divider.into_any_element());
165 self
166 }
167
168 pub fn indicator_style(mut self, style: TabIndicatorStyle) -> Self {
170 self.options.indicator_style = Some(style);
171 self
172 }
173
174 pub fn indicator_content<E: IntoElement>(
176 mut self,
177 content: impl Fn(TabIndicatorLayout) -> E + 'static,
178 ) -> Self {
179 self.options.indicator_content =
180 Some(Box::new(move |layout| content(layout).into_any_element()));
181 self
182 }
183}
184
185impl RenderOnce for Tabs {
186 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
187 self.items.render_row_with_tabs(
188 Presentation::Tabs(self.variant, self.scrollable),
189 Some(self.options),
190 window,
191 cx,
192 )
193 }
194}
195
196fn length(value: Pixels) -> Option<Pixels> {
197 let value_f = f32::from(value);
198 (value_f.is_finite() && value_f >= 0.).then_some(value)
199}
200
201#[derive(Default)]
202pub(super) struct TabReveal {
203 selection: Option<SharedString>,
204 focus: Option<SharedString>,
205 target: Option<SharedString>,
206 order: Vec<SharedString>,
207 geometry: Option<(Pixels, Pixels, Pixels, Pixels)>,
208}
209
210impl TabReveal {
211 pub(super) fn choose(
212 &mut self,
213 selected: Option<&SharedString>,
214 focused: Option<&SharedString>,
215 items: &[super::items::NavigationItem],
216 scroll: &ScrollHandle,
217 ) -> Option<usize> {
218 let order_unchanged = self.order.len() == items.len()
219 && self
220 .order
221 .iter()
222 .zip(items)
223 .all(|(existing, item)| existing == &item.id);
224 if !order_unchanged {
225 self.order = items.iter().map(|item| item.id.clone()).collect();
226 }
227 let old_target = self.target.clone();
228 if self.selection.as_ref() != selected {
229 self.target = selected.or(focused).cloned();
230 } else if let Some(focused) =
231 focused.filter(|focused| self.focus.as_ref() != Some(*focused))
232 {
233 self.target = Some(focused.clone());
234 }
235 self.selection = selected.cloned();
236 self.focus = focused.cloned();
237 if self
238 .target
239 .as_ref()
240 .is_none_or(|id| !self.order.contains(id))
241 {
242 self.target = selected
243 .filter(|id| self.order.contains(id))
244 .or(focused)
245 .cloned();
246 }
247 let index = self
248 .target
249 .as_ref()
250 .and_then(|id| self.order.iter().position(|item| item == id));
251 if !order_unchanged || self.target != old_target || scroll.bounds().size.width == px(0.) {
252 self.geometry = None;
253 if let Some(index) = index {
254 scroll.scroll_to_item(index);
255 }
256 }
257 index
258 }
259
260 pub(super) fn observe_geometry(
261 &mut self,
262 index: usize,
263 scroll: &ScrollHandle,
264 window: &mut Window,
265 ) {
266 let Some(tab) = scroll.bounds_for_item(index) else {
267 return;
268 };
269 let viewport = scroll.bounds();
270 let width = viewport.size.width;
271 let left = tab.left() - viewport.left();
272 let geometry = (width, left, tab.size.width, scroll.max_offset().x);
273 if self.geometry.replace(geometry) == Some(geometry) {
274 return;
275 }
276 let visible_left = left + scroll.offset().x;
277 if visible_left < px(0.) || visible_left + tab.size.width.min(width) > width {
278 scroll.scroll_to_item(index);
279 window.request_animation_frame();
280 }
281 }
282}
283
284#[derive(Default)]
285pub(super) struct TabIndicatorTarget {
286 pub tab_bounds: Cell<Option<Bounds<Pixels>>>,
287 pub content_width: Cell<Pixels>,
288}
289
290pub(super) struct TabDecoration {
291 pub row: ElementId,
292 pub selected: SharedString,
293 pub variant: TabVariant,
294 pub direction: Direction,
295 pub target: Rc<TabIndicatorTarget>,
296 pub scroll: Option<ScrollHandle>,
297 pub style: TabIndicatorStyle,
298 pub content: Option<Indicator>,
299 pub color: Hsla,
300 pub has_default_divider: bool,
301}
302
303impl TabDecoration {
304 pub(super) fn element(self) -> impl IntoElement {
305 canvas(
306 move |viewport, window, cx| {
307 let tab = self.target.tab_bounds.get()?;
308 let offset = self
309 .scroll
310 .as_ref()
311 .map_or(px(0.), |handle| handle.offset().x);
312 let content_width = self.target.content_width.get().min(tab.size.width);
313 let default_width = if self.variant == TabVariant::Primary {
314 (tab.size.width - px(4.)).max(px(0.)) * (2. / 3.)
315 } else {
316 (tab.size.width - px(4.)).max(px(0.))
317 };
318 let width = match self.style.width {
319 TabIndicatorWidth::Default => default_width,
320 TabIndicatorWidth::Tab => tab.size.width,
321 TabIndicatorWidth::Content => content_width.max(px(24.)),
322 TabIndicatorWidth::Fixed(width) => length(width).unwrap_or(default_width),
323 }
324 .min(tab.size.width);
325 let divider_height = if self.has_default_divider {
326 px(1.)
327 } else {
328 px(0.)
329 };
330 let height = self
331 .style
332 .height
333 .and_then(length)
334 .unwrap_or(px(if self.variant == TabVariant::Primary {
335 3.
336 } else {
337 2.
338 }))
339 .min((viewport.size.height - divider_height).max(px(0.)));
340 let motion = if cx.reduce_motion() {
341 MotionSpec::Instant
342 } else {
343 self.style.motion.unwrap_or_else(|| {
344 current_material_theme(window, cx).motion.spec(
345 MotionKind::Spatial,
346 MotionSpeed::Fast,
347 false,
348 )
349 })
350 };
351 let center = animate(
354 (self.row.clone(), "indicator-center"),
355 f32::from(tab.center().x - viewport.left()),
356 motion,
357 window,
358 cx,
359 );
360 let width = px(animate(
361 (self.row.clone(), "indicator-width"),
362 f32::from(width),
363 motion,
364 window,
365 cx,
366 ))
367 .clamp(px(0.), viewport.size.width.max(tab.size.width));
368 if width == px(0.) || height == px(0.) {
369 return None;
370 }
371 let edge = viewport.bottom() - divider_height;
372 let bounds = Bounds::new(
373 point(
374 viewport.left() + offset + px(center) - width / 2.,
375 edge - height,
376 ),
377 size(width, height),
378 );
379 let tab_bounds = Bounds::new(tab.origin + point(offset, px(0.)), tab.size);
380 let layout = TabIndicatorLayout {
381 selected: self.selected,
382 bounds,
383 tab_bounds,
384 content_width,
385 color: self.color,
386 direction: self.direction,
387 };
388 let mask = ContentMask { bounds: viewport };
389 let child = self.content.map(|content| {
390 let mut child = decorative_slot(
391 (self.row, "custom-indicator").into(),
392 content(layout.clone()),
393 )
394 .w(width)
395 .h(height)
396 .text_color(self.color)
397 .into_any_element();
398 window.with_content_mask(Some(mask), |window| {
399 child.prepaint_as_root(
400 bounds.origin,
401 bounds.size.map(AvailableSpace::Definite),
402 window,
403 cx,
404 );
405 });
406 child
407 });
408 let shape = self
409 .style
410 .shape
411 .unwrap_or(if self.variant == TabVariant::Primary {
412 CornerShape::Radii([3., 3., 0., 0.])
413 } else {
414 CornerShape::Radii([0.; 4])
415 });
416 Some((layout, mask, child, shape))
417 },
418 |_, state, window, cx| {
419 if let Some((layout, mask, child, shape)) = state {
420 window.with_content_mask(Some(mask), |window| {
421 if let Some(mut child) = child {
422 child.paint(window, cx);
423 } else {
424 let rect = layout.bounds;
425 let [top_left, top_right, bottom_right, bottom_left] = shape
426 .radii(
427 rect.size.width.into(),
428 rect.size.height.into(),
429 layout.direction,
430 )
431 .map(px);
432 window.paint_quad(quad(
433 rect,
434 Corners {
435 top_left,
436 top_right,
437 bottom_right,
438 bottom_left,
439 },
440 layout.color,
441 px(0.),
442 gpui::transparent_black(),
443 BorderStyle::Solid,
444 ));
445 }
446 });
447 }
448 },
449 )
450 .absolute()
451 .inset_0()
452 }
453}
454
455pub(super) fn decorative_slot(
456 id: ElementId,
457 content: impl IntoElement,
458) -> gpui::Stateful<gpui::Div> {
459 div()
460 .id(id)
461 .role(Role::Group)
462 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
463 .min_w_0()
464 .max_w_full()
465 .overflow_hidden()
466 .child(content)
467}