1#![allow(missing_docs)]
2use gpui::{relative, CursorStyle, DefiniteLength, MouseButton};
3use gpui::{transparent_black, AnyElement, AnyView, ClickEvent, Hsla, Rems};
4use smallvec::SmallVec;
5
6use crate::{prelude::*, ElevationIndex, Spacing};
7
8/// A trait for buttons that can be Selected. Enables setting the [`ButtonStyle`] of a button when it is selected.
9pub trait SelectableButton: Selectable {
10 fn selected_style(self, style: ButtonStyle) -> Self;
11}
12
13/// A common set of traits all buttons must implement.
14pub trait ButtonCommon: Clickable + Disableable {
15 /// A unique element ID to identify the button.
16 fn id(&self) -> &ElementId;
17
18 /// The visual style of the button.
19 ///
20 /// Most commonly will be [`ButtonStyle::Subtle`], or [`ButtonStyle::Filled`]
21 /// for an emphasized button.
22 fn style(self, style: ButtonStyle) -> Self;
23
24 /// The size of the button.
25 ///
26 /// Most buttons will use the default size.
27 ///
28 /// [`ButtonSize`] can also be used to help build non-button elements
29 /// that are consistently sized with buttons.
30 fn size(self, size: ButtonSize) -> Self;
31
32 /// The tooltip that shows when a user hovers over the button.
33 ///
34 /// Nearly all interactable elements should have a tooltip. Some example
35 /// exceptions might a scroll bar, or a slider.
36 fn tooltip(self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self;
37
38 fn layer(self, elevation: ElevationIndex) -> Self;
39}
40
41#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
42pub enum IconPosition {
43 #[default]
44 Start,
45 End,
46}
47
48#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
49pub enum TintColor {
50 #[default]
51 Accent,
52 Negative,
53 Warning,
54 Positive,
55}
56
57impl TintColor {
58 fn button_like_style(self, cx: &mut WindowContext) -> ButtonLikeStyles {
59 match self {
60 TintColor::Accent => ButtonLikeStyles {
61 background: cx.theme().status().info_background,
62 border_color: cx.theme().status().info_border,
63 label_color: cx.theme().colors().text,
64 icon_color: cx.theme().colors().text,
65 },
66 TintColor::Negative => ButtonLikeStyles {
67 background: cx.theme().status().error_background,
68 border_color: cx.theme().status().error_border,
69 label_color: cx.theme().colors().text,
70 icon_color: cx.theme().colors().text,
71 },
72 TintColor::Warning => ButtonLikeStyles {
73 background: cx.theme().status().warning_background,
74 border_color: cx.theme().status().warning_border,
75 label_color: cx.theme().colors().text,
76 icon_color: cx.theme().colors().text,
77 },
78 TintColor::Positive => ButtonLikeStyles {
79 background: cx.theme().status().success_background,
80 border_color: cx.theme().status().success_border,
81 label_color: cx.theme().colors().text,
82 icon_color: cx.theme().colors().text,
83 },
84 }
85 }
86}
87
88impl From<TintColor> for Color {
89 fn from(tint: TintColor) -> Self {
90 match tint {
91 TintColor::Accent => Color::Accent,
92 TintColor::Negative => Color::Error,
93 TintColor::Warning => Color::Warning,
94 TintColor::Positive => Color::Success,
95 }
96 }
97}
98
99// Used to go from ButtonStyle -> Color through tint colors.
100impl From<ButtonStyle> for Color {
101 fn from(style: ButtonStyle) -> Self {
102 match style {
103 ButtonStyle::Tinted(tint) => tint.into(),
104 _ => Color::Default,
105 }
106 }
107}
108
109/// The visual appearance of a button.
110#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
111pub enum ButtonStyle {
112 /// A filled button with a solid background color. Provides emphasis versus
113 /// the more common subtle button.
114 Filled,
115
116 /// Used to emphasize a button in some way, like a selected state, or a semantic
117 /// coloring like an error or success button.
118 Tinted(TintColor),
119
120 /// The default button style, used for most buttons. Has a transparent background,
121 /// but has a background color to indicate states like hover and active.
122 #[default]
123 Subtle,
124
125 /// Used for buttons that only change foreground color on hover and active states.
126 ///
127 /// TODO: Better docs for this.
128 Transparent,
129}
130
131#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
132pub(crate) enum ButtonLikeRounding {
133 All,
134 Left,
135 Right,
136}
137
138#[derive(Debug, Clone)]
139pub(crate) struct ButtonLikeStyles {
140 pub background: Hsla,
141 #[allow(unused)]
142 pub border_color: Hsla,
143 #[allow(unused)]
144 pub label_color: Hsla,
145 #[allow(unused)]
146 pub icon_color: Hsla,
147}
148
149fn element_bg_from_elevation(elevation: Option<ElevationIndex>, cx: &mut WindowContext) -> Hsla {
150 match elevation {
151 Some(ElevationIndex::Background) => cx.theme().colors().element_background,
152 Some(ElevationIndex::ElevatedSurface) => cx.theme().colors().surface_background,
153 Some(ElevationIndex::Surface) => cx.theme().colors().elevated_surface_background,
154 Some(ElevationIndex::ModalSurface) => cx.theme().colors().background,
155 _ => cx.theme().colors().element_background,
156 }
157}
158
159impl ButtonStyle {
160 pub(crate) fn enabled(
161 self,
162 elevation: Option<ElevationIndex>,
163 cx: &mut WindowContext,
164 ) -> ButtonLikeStyles {
165 let filled_background = element_bg_from_elevation(elevation, cx);
166
167 match self {
168 ButtonStyle::Filled => ButtonLikeStyles {
169 background: filled_background,
170 border_color: transparent_black(),
171 label_color: Color::Default.color(cx),
172 icon_color: Color::Default.color(cx),
173 },
174 ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
175 ButtonStyle::Subtle => ButtonLikeStyles {
176 background: cx.theme().colors().ghost_element_background,
177 border_color: transparent_black(),
178 label_color: Color::Default.color(cx),
179 icon_color: Color::Default.color(cx),
180 },
181 ButtonStyle::Transparent => ButtonLikeStyles {
182 background: transparent_black(),
183 border_color: transparent_black(),
184 label_color: Color::Default.color(cx),
185 icon_color: Color::Default.color(cx),
186 },
187 }
188 }
189
190 pub(crate) fn hovered(
191 self,
192 elevation: Option<ElevationIndex>,
193 cx: &mut WindowContext,
194 ) -> ButtonLikeStyles {
195 let mut filled_background = element_bg_from_elevation(elevation, cx);
196 filled_background.fade_out(0.92);
197
198 match self {
199 ButtonStyle::Filled => ButtonLikeStyles {
200 background: filled_background,
201 border_color: transparent_black(),
202 label_color: Color::Default.color(cx),
203 icon_color: Color::Default.color(cx),
204 },
205 ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
206 ButtonStyle::Subtle => ButtonLikeStyles {
207 background: cx.theme().colors().ghost_element_hover,
208 border_color: transparent_black(),
209 label_color: Color::Default.color(cx),
210 icon_color: Color::Default.color(cx),
211 },
212 ButtonStyle::Transparent => ButtonLikeStyles {
213 background: transparent_black(),
214 border_color: transparent_black(),
215 // TODO: These are not great
216 label_color: Color::Muted.color(cx),
217 // TODO: These are not great
218 icon_color: Color::Muted.color(cx),
219 },
220 }
221 }
222
223 pub(crate) fn active(self, cx: &mut WindowContext) -> ButtonLikeStyles {
224 match self {
225 ButtonStyle::Filled => ButtonLikeStyles {
226 background: cx.theme().colors().element_active,
227 border_color: transparent_black(),
228 label_color: Color::Default.color(cx),
229 icon_color: Color::Default.color(cx),
230 },
231 ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
232 ButtonStyle::Subtle => ButtonLikeStyles {
233 background: cx.theme().colors().ghost_element_active,
234 border_color: transparent_black(),
235 label_color: Color::Default.color(cx),
236 icon_color: Color::Default.color(cx),
237 },
238 ButtonStyle::Transparent => ButtonLikeStyles {
239 background: transparent_black(),
240 border_color: transparent_black(),
241 // TODO: These are not great
242 label_color: Color::Muted.color(cx),
243 // TODO: These are not great
244 icon_color: Color::Muted.color(cx),
245 },
246 }
247 }
248
249 #[allow(unused)]
250 pub(crate) fn focused(self, cx: &mut WindowContext) -> ButtonLikeStyles {
251 match self {
252 ButtonStyle::Filled => ButtonLikeStyles {
253 background: cx.theme().colors().element_background,
254 border_color: cx.theme().colors().border_focused,
255 label_color: Color::Default.color(cx),
256 icon_color: Color::Default.color(cx),
257 },
258 ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
259 ButtonStyle::Subtle => ButtonLikeStyles {
260 background: cx.theme().colors().ghost_element_background,
261 border_color: cx.theme().colors().border_focused,
262 label_color: Color::Default.color(cx),
263 icon_color: Color::Default.color(cx),
264 },
265 ButtonStyle::Transparent => ButtonLikeStyles {
266 background: transparent_black(),
267 border_color: cx.theme().colors().border_focused,
268 label_color: Color::Accent.color(cx),
269 icon_color: Color::Accent.color(cx),
270 },
271 }
272 }
273
274 #[allow(unused)]
275 pub(crate) fn disabled(
276 self,
277 elevation: Option<ElevationIndex>,
278 cx: &mut WindowContext,
279 ) -> ButtonLikeStyles {
280 element_bg_from_elevation(elevation, cx).fade_out(0.82);
281
282 match self {
283 ButtonStyle::Filled => ButtonLikeStyles {
284 background: cx.theme().colors().element_disabled,
285 border_color: cx.theme().colors().border_disabled,
286 label_color: Color::Disabled.color(cx),
287 icon_color: Color::Disabled.color(cx),
288 },
289 ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
290 ButtonStyle::Subtle => ButtonLikeStyles {
291 background: cx.theme().colors().ghost_element_disabled,
292 border_color: cx.theme().colors().border_disabled,
293 label_color: Color::Disabled.color(cx),
294 icon_color: Color::Disabled.color(cx),
295 },
296 ButtonStyle::Transparent => ButtonLikeStyles {
297 background: transparent_black(),
298 border_color: transparent_black(),
299 label_color: Color::Disabled.color(cx),
300 icon_color: Color::Disabled.color(cx),
301 },
302 }
303 }
304}
305
306/// The height of a button.
307///
308/// Can also be used to size non-button elements to align with [`Button`]s.
309#[derive(Default, PartialEq, Clone, Copy)]
310pub enum ButtonSize {
311 Large,
312 #[default]
313 Default,
314 Compact,
315 None,
316}
317
318impl ButtonSize {
319 pub fn rems(self) -> Rems {
320 match self {
321 ButtonSize::Large => rems_from_px(32.),
322 ButtonSize::Default => rems_from_px(22.),
323 ButtonSize::Compact => rems_from_px(18.),
324 ButtonSize::None => rems_from_px(16.),
325 }
326 }
327}
328
329/// A button-like element that can be used to create a custom button when
330/// prebuilt buttons are not sufficient. Use this sparingly, as it is
331/// unconstrained and may make the UI feel less consistent.
332///
333/// This is also used to build the prebuilt buttons.
334#[derive(IntoElement)]
335pub struct ButtonLike {
336 pub(super) base: Div,
337 id: ElementId,
338 pub(super) style: ButtonStyle,
339 pub(super) disabled: bool,
340 pub(super) selected: bool,
341 pub(super) selected_style: Option<ButtonStyle>,
342 pub(super) width: Option<DefiniteLength>,
343 pub(super) height: Option<DefiniteLength>,
344 pub(super) layer: Option<ElevationIndex>,
345 size: ButtonSize,
346 rounding: Option<ButtonLikeRounding>,
347 tooltip: Option<Box<dyn Fn(&mut WindowContext) -> AnyView>>,
348 cursor_style: CursorStyle,
349 on_click: Option<Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>>,
350 children: SmallVec<[AnyElement; 2]>,
351}
352
353impl ButtonLike {
354 pub fn new(id: impl Into<ElementId>) -> Self {
355 Self {
356 base: div(),
357 id: id.into(),
358 style: ButtonStyle::default(),
359 disabled: false,
360 selected: false,
361 selected_style: None,
362 width: None,
363 height: None,
364 size: ButtonSize::Default,
365 rounding: Some(ButtonLikeRounding::All),
366 tooltip: None,
367 children: SmallVec::new(),
368 cursor_style: CursorStyle::PointingHand,
369 on_click: None,
370 layer: None,
371 }
372 }
373
374 pub fn new_rounded_left(id: impl Into<ElementId>) -> Self {
375 Self::new(id).rounding(ButtonLikeRounding::Left)
376 }
377
378 pub fn new_rounded_right(id: impl Into<ElementId>) -> Self {
379 Self::new(id).rounding(ButtonLikeRounding::Right)
380 }
381
382 pub(crate) fn height(mut self, height: DefiniteLength) -> Self {
383 self.height = Some(height);
384 self
385 }
386
387 pub(crate) fn rounding(mut self, rounding: impl Into<Option<ButtonLikeRounding>>) -> Self {
388 self.rounding = rounding.into();
389 self
390 }
391}
392
393impl Disableable for ButtonLike {
394 fn disabled(mut self, disabled: bool) -> Self {
395 self.disabled = disabled;
396 self
397 }
398}
399
400impl Selectable for ButtonLike {
401 fn selected(mut self, selected: bool) -> Self {
402 self.selected = selected;
403 self
404 }
405}
406
407impl SelectableButton for ButtonLike {
408 fn selected_style(mut self, style: ButtonStyle) -> Self {
409 self.selected_style = Some(style);
410 self
411 }
412}
413
414impl Clickable for ButtonLike {
415 fn on_click(mut self, handler: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self {
416 self.on_click = Some(Box::new(handler));
417 self
418 }
419
420 fn cursor_style(mut self, cursor_style: CursorStyle) -> Self {
421 self.cursor_style = cursor_style;
422 self
423 }
424}
425
426impl FixedWidth for ButtonLike {
427 fn width(mut self, width: DefiniteLength) -> Self {
428 self.width = Some(width);
429 self
430 }
431
432 fn full_width(mut self) -> Self {
433 self.width = Some(relative(1.));
434 self
435 }
436}
437
438impl ButtonCommon for ButtonLike {
439 fn id(&self) -> &ElementId {
440 &self.id
441 }
442
443 fn style(mut self, style: ButtonStyle) -> Self {
444 self.style = style;
445 self
446 }
447
448 fn size(mut self, size: ButtonSize) -> Self {
449 self.size = size;
450 self
451 }
452
453 fn tooltip(mut self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self {
454 self.tooltip = Some(Box::new(tooltip));
455 self
456 }
457
458 fn layer(mut self, elevation: ElevationIndex) -> Self {
459 self.layer = Some(elevation);
460 self
461 }
462}
463
464impl VisibleOnHover for ButtonLike {
465 fn visible_on_hover(mut self, group_name: impl Into<SharedString>) -> Self {
466 self.base = self.base.visible_on_hover(group_name);
467 self
468 }
469}
470
471impl ParentElement for ButtonLike {
472 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
473 self.children.extend(elements)
474 }
475}
476
477impl RenderOnce for ButtonLike {
478 fn render(self, cx: &mut WindowContext) -> impl IntoElement {
479 let style = self
480 .selected_style
481 .filter(|_| self.selected)
482 .unwrap_or(self.style);
483
484 self.base
485 .h_flex()
486 .id(self.id.clone())
487 .group("")
488 .flex_none()
489 .h(self.height.unwrap_or(self.size.rems().into()))
490 .when_some(self.width, |this, width| this.w(width).justify_center())
491 .when_some(self.rounding, |this, rounding| match rounding {
492 ButtonLikeRounding::All => this.rounded_md(),
493 ButtonLikeRounding::Left => this.rounded_l_md(),
494 ButtonLikeRounding::Right => this.rounded_r_md(),
495 })
496 .gap(Spacing::Small.rems(cx))
497 .map(|this| match self.size {
498 ButtonSize::Large => this.px(Spacing::Medium.rems(cx)),
499 ButtonSize::Default | ButtonSize::Compact => this.px(Spacing::Small.rems(cx)),
500 ButtonSize::None => this,
501 })
502 .bg(style.enabled(self.layer, cx).background)
503 .when(self.disabled, |this| this.cursor_not_allowed())
504 .when(!self.disabled, |this| {
505 this.cursor_pointer()
506 .hover(|hover| hover.bg(style.hovered(self.layer, cx).background))
507 .active(|active| active.bg(style.active(cx).background))
508 })
509 .when_some(
510 self.on_click.filter(|_| !self.disabled),
511 |this, on_click| {
512 this.on_mouse_down(MouseButton::Left, |_, cx| cx.prevent_default())
513 .on_click(move |event, cx| {
514 cx.stop_propagation();
515 (on_click)(event, cx)
516 })
517 },
518 )
519 .when_some(self.tooltip, |this, tooltip| {
520 this.tooltip(move |cx| tooltip(cx))
521 })
522 .children(self.children)
523 }
524}