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