Add ToggleButton (as part of ButtonGroup) (#239)

![2024-09-12 19 20
46](https://github.com/user-attachments/assets/4cf9b374-2d3b-4f36-9fc7-cd6dbd1f861c)

---------

Co-authored-by: Jason Lee <huacnlee@gmail.com>
This commit is contained in:
xda 2024-09-13 11:58:10 +08:00 committed by GitHub
parent a43e78e8ae
commit b83ece3cd8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 138 additions and 19 deletions

View file

@ -21,6 +21,7 @@ pub struct ButtonStory {
loading: bool, loading: bool,
selected: bool, selected: bool,
compact: bool, compact: bool,
multiple: bool,
} }
impl ButtonStory { impl ButtonStory {
@ -31,6 +32,7 @@ impl ButtonStory {
loading: false, loading: false,
selected: false, selected: false,
compact: false, compact: false,
multiple: false,
}) })
} }
@ -69,6 +71,7 @@ impl Render for ButtonStory {
let loading = self.loading; let loading = self.loading;
let selected = self.selected; let selected = self.selected;
let compact = self.compact; let compact = self.compact;
let multiple = self.multiple;
v_flex() v_flex()
.gap_6() .gap_6()
@ -435,6 +438,7 @@ impl Render for ButtonStory {
.child( .child(
section("Button Group", cx).child( section("Button Group", cx).child(
ButtonGroup::new("button-group") ButtonGroup::new("button-group")
.disabled(disabled)
.child( .child(
Button::new("button-one", cx) Button::new("button-one", cx)
.label("One") .label("One")
@ -464,6 +468,49 @@ impl Render for ButtonStory {
), ),
), ),
) )
.child(
section("Toggle Button Group", cx)
.child(
Checkbox::new("multiple-button")
.label("Multiple")
.checked(self.multiple)
.on_click(cx.listener(|view, _, cx| {
view.multiple = !view.multiple;
cx.notify();
})),
)
.child(
ButtonGroup::new("toggle-button-group")
.multiple(multiple)
.child(
Button::new("disabled-toggle-button", cx)
.label("Disabled")
.selected(disabled),
)
.child(
Button::new("loading-toggle-button", cx)
.label("Loading")
.selected(loading),
)
.child(
Button::new("selected-toggle-button", cx)
.label("Selected")
.selected(selected),
)
.child(
Button::new("compact-toggle-button", cx)
.label("Compact")
.selected(compact),
)
.on_click(cx.listener(|view, selected: &Vec<usize>, cx| {
view.disabled = selected.contains(&0);
view.loading = selected.contains(&1);
view.selected = selected.contains(&2);
view.compact = selected.contains(&3);
cx.notify();
})),
),
)
.child( .child(
section("Icon Button", cx) section("Icon Button", cx)
.child( .child(

View file

@ -106,7 +106,7 @@ pub struct Button {
label: Option<SharedString>, label: Option<SharedString>,
children: Vec<AnyElement>, children: Vec<AnyElement>,
disabled: bool, disabled: bool,
selected: bool, pub(crate) selected: bool,
style: ButtonStyle, style: ButtonStyle,
rounded: ButtonRounded, rounded: ButtonRounded,
border_corners: Corners<bool>, border_corners: Corners<bool>,
@ -115,6 +115,7 @@ pub struct Button {
compact: bool, compact: bool,
tooltip: Option<SharedString>, tooltip: Option<SharedString>,
on_click: Option<Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>>, on_click: Option<Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>>,
pub(crate) stop_propagation: bool,
loading: bool, loading: bool,
} }
@ -141,6 +142,7 @@ impl Button {
size: Size::Medium, size: Size::Medium,
tooltip: None, tooltip: None,
on_click: None, on_click: None,
stop_propagation: true,
loading: false, loading: false,
compact: false, compact: false,
children: Vec::new(), children: Vec::new(),
@ -247,6 +249,11 @@ impl Button {
self.on_click = Some(Box::new(handler)); self.on_click = Some(Box::new(handler));
self self
} }
pub fn stop_propagation(mut self, val: bool) -> Self {
self.stop_propagation = val;
self
}
} }
impl Disableable for Button { impl Disableable for Button {
@ -371,9 +378,12 @@ impl RenderOnce for Button {
.when_some( .when_some(
self.on_click.filter(|_| !self.disabled && !self.loading), self.on_click.filter(|_| !self.disabled && !self.loading),
|this, on_click| { |this, on_click| {
this.on_mouse_down(MouseButton::Left, |_, cx| { let stop_propagation = self.stop_propagation;
this.on_mouse_down(MouseButton::Left, move |_, cx| {
cx.prevent_default(); cx.prevent_default();
cx.stop_propagation() if stop_propagation {
cx.stop_propagation();
}
}) })
.on_click(move |event, cx| { .on_click(move |event, cx| {
(on_click)(event, cx); (on_click)(event, cx);

View file

@ -1,15 +1,26 @@
use gpui::{ use gpui::{
div, Corners, Div, Edges, ElementId, InteractiveElement, IntoElement, ParentElement, div, prelude::FluentBuilder as _, Corners, Div, Edges, ElementId, InteractiveElement,
RenderOnce, Styled, WindowContext, IntoElement, ParentElement, RenderOnce, StatefulInteractiveElement as _, Styled, WindowContext,
}; };
use std::{cell::Cell, rc::Rc};
use crate::button::Button; use crate::{button::Button, Disableable};
#[derive(IntoElement)] #[derive(IntoElement)]
pub struct ButtonGroup { pub struct ButtonGroup {
pub base: Div, pub base: Div,
id: ElementId, id: ElementId,
children: Vec<Button>, children: Vec<Button>,
multiple: bool,
disabled: bool,
on_click: Option<Box<dyn Fn(&Vec<usize>, &mut WindowContext) + 'static>>,
}
impl Disableable for ButtonGroup {
fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
} }
impl ButtonGroup { impl ButtonGroup {
@ -19,12 +30,27 @@ impl ButtonGroup {
base: div(), base: div(),
children: Vec::new(), children: Vec::new(),
id: id.into(), id: id.into(),
multiple: false,
disabled: false,
on_click: None,
} }
} }
/// Adds a button as a child to the ButtonGroup. /// Adds a button as a child to the ButtonGroup.
pub fn child(mut self, child: Button) -> Self { pub fn child(mut self, child: Button) -> Self {
self.children.push(child); self.children.push(child.disabled(self.disabled));
self
}
/// Sets the multiple selection mode.
pub fn multiple(mut self, multiple: bool) -> Self {
self.multiple = multiple;
self
}
/// Sets the on_click handler for the ButtonGroup.
pub fn on_click(mut self, handler: impl Fn(&Vec<usize>, &mut WindowContext) + 'static) -> Self {
self.on_click = Some(Box::new(handler));
self self
} }
} }
@ -38,19 +64,30 @@ impl Styled for ButtonGroup {
impl RenderOnce for ButtonGroup { impl RenderOnce for ButtonGroup {
fn render(self, _cx: &mut WindowContext) -> impl IntoElement { fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
let children_len = self.children.len(); let children_len = self.children.len();
// Render a div container with a flex layout to group buttons horizontally. let mut selected: Vec<usize> = Vec::new();
let shared_state = Rc::new(Cell::new(None)); // Shared state to store the child index
for (child_index, child) in self.children.iter().enumerate() {
if child.selected {
selected.push(child_index);
}
}
self.base self.base
.id(self.id) .id(self.id)
.flex() .flex()
.items_center() .items_center()
.children(if children_len > 1 { .children(
self.children self.children
.into_iter() .into_iter()
.enumerate() .enumerate()
.map(|(index, button)| { .map(|(child_index, child)| {
if index == 0 { let shared_state_clone = Rc::clone(&shared_state);
let child = if children_len == 1 {
child
} else if child_index == 0 {
// First // First
button child
.border_corners(Corners { .border_corners(Corners {
top_left: true, top_left: true,
top_right: false, top_right: false,
@ -63,9 +100,9 @@ impl RenderOnce for ButtonGroup {
right: true, right: true,
bottom: true, bottom: true,
}) })
} else if index == children_len - 1 { } else if child_index == children_len - 1 {
// Last // Last
button child
.border_edges(Edges { .border_edges(Edges {
left: false, left: false,
top: true, top: true,
@ -80,7 +117,7 @@ impl RenderOnce for ButtonGroup {
}) })
} else { } else {
// Middle // Middle
button child
.border_corners(Corners::all(false)) .border_corners(Corners::all(false))
.border_edges(Edges { .border_edges(Edges {
left: false, left: false,
@ -89,10 +126,35 @@ impl RenderOnce for ButtonGroup {
bottom: true, bottom: true,
}) })
} }
.stop_propagation(false)
.on_click(move |_, cx| {
shared_state_clone.set(Some(child_index));
});
child
}),
)
.when_some(
self.on_click.filter(|_| !self.disabled),
move |this, on_click| {
this.on_click(move |_, cx| {
let mut selected = selected.clone();
if let Some(index) = shared_state.get() {
if self.multiple {
if let Some(pos) = selected.iter().position(|&i| i == index) {
selected.remove(pos); // Toggle off if already selected
} else {
selected.push(index); // Toggle on if not selected
}
} else {
selected.clear(); // Clear the existing selection
selected.push(index); // Replace with the new selection
}
}
on_click(&selected, cx);
}) })
.collect() },
} else { )
self.children
})
} }
} }