use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, TransformOrigin, arc_spring,
arc_spring_with_options, is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SplitButtonTokens as T,
Typography, oklab_mix,
};
use gpui_kit::{
Anchor, App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, PathBuilder, RenderOnce, Role,
SharedString, Styled, TestSupportExt as _, Window, anchored, assets::IconName,
base::Button as BaseButton, canvas, deferred, div, point, prelude::*, px, quad, svg,
};
type ActionCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum SplitButtonVariant {
#[default]
Primary,
Secondary,
}
#[derive(Clone)]
pub struct SplitButtonAction {
pub label: SharedString,
pub icon: Option<IconName>,
pub disabled: bool,
pub destructive: bool,
pub on_select: Option<ActionCallback>,
}
impl SplitButtonAction {
pub fn new(label: impl Into<SharedString>) -> Self {
Self {
label: label.into(),
icon: None,
disabled: false,
destructive: false,
on_select: None,
}
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn destructive(mut self, destructive: bool) -> Self {
self.destructive = destructive;
self
}
pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_select = Some(Rc::new(handler));
self
}
}
#[derive(Clone)]
struct SplitButtonInternal {
open: bool,
opened_at_secs: f64,
highlighted: Option<usize>,
primary_hovered: bool,
primary_pressed: bool,
trigger_hovered: bool,
trigger_pressed: bool,
last_key: SharedString,
morph_armed_until_secs: f64,
label_changed_at_secs: f64,
measured_slot_width: Rc<RefCell<f32>>,
has_measured: Rc<RefCell<bool>>,
group_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
menu_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
focus_handle: FocusHandle,
trigger_focus: FocusHandle,
label: SharedString,
previous_label: SharedString,
icon: Option<IconName>,
previous_icon: Option<IconName>,
icon_changed_at_secs: f64,
}
impl SplitButtonInternal {
fn new(
initial_key: SharedString,
label: SharedString,
icon: Option<IconName>,
now: f64,
focus_handle: FocusHandle,
trigger_focus: FocusHandle,
) -> Self {
Self {
open: false,
opened_at_secs: now - 10.0,
highlighted: None,
primary_hovered: false,
primary_pressed: false,
trigger_hovered: false,
trigger_pressed: false,
last_key: initial_key,
morph_armed_until_secs: f64::NEG_INFINITY,
label_changed_at_secs: now - 10.0,
measured_slot_width: Rc::new(RefCell::new(0.0)),
has_measured: Rc::new(RefCell::new(false)),
group_bounds: Rc::new(RefCell::new(None)),
menu_bounds: Rc::new(RefCell::new(None)),
focus_handle,
trigger_focus,
label,
previous_label: "".into(),
icon,
previous_icon: None,
icon_changed_at_secs: now - 10.0,
}
}
}
#[derive(IntoElement)]
pub struct SplitButton {
id: ElementId,
label: SharedString,
icon: Option<IconName>,
actions: Vec<SplitButtonAction>,
variant: SplitButtonVariant,
disabled: bool,
on_click: Option<ActionCallback>,
}
impl SplitButton {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
icon: None,
actions: Vec::new(),
variant: SplitButtonVariant::Primary,
disabled: false,
on_click: None,
}
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
pub fn variant(mut self, variant: SplitButtonVariant) -> Self {
self.variant = variant;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn action(mut self, action: SplitButtonAction) -> Self {
self.actions.push(action);
self
}
pub fn actions(mut self, actions: impl IntoIterator<Item = SplitButtonAction>) -> Self {
self.actions.extend(actions);
self
}
pub fn on_click(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_click = Some(Rc::new(handler));
self
}
}
fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let cos_a = rad.cos();
let sin_a = rad.sin();
let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
let mut builder = PathBuilder::stroke(px(1.75));
for (i, (lx, ly)) in pts.iter().enumerate() {
let rx = cx + lx * cos_a - ly * sin_a;
let ry = cy + lx * sin_a + ly * cos_a;
let p = point(px(rx), px(ry));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
fn shared_edges(previous: &str, next: &str) -> (usize, usize) {
let previous: Vec<_> = previous.chars().collect();
let next: Vec<_> = next.chars().collect();
let mut start = previous
.iter()
.zip(&next)
.take_while(|(a, b)| a == b)
.count();
let mut end = previous[start..]
.iter()
.rev()
.zip(next[start..].iter().rev())
.take_while(|(a, b)| a == b)
.count();
if start < 2 {
start = 0;
}
if end < 2 {
end = 0;
}
(start, end)
}
fn next_enabled_index(
actions: &[SplitButtonAction],
current: Option<usize>,
step: isize,
) -> Option<usize> {
if actions.is_empty() {
return None;
}
let len = actions.len() as isize;
let start = match current {
Some(idx) => idx as isize,
None => {
if step > 0 {
-1
} else {
len
}
}
};
for offset in 1..=len {
let idx = (start + step * offset).rem_euclid(len) as usize;
if !actions[idx].disabled {
return Some(idx);
}
}
None
}
impl RenderOnce for SplitButton {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let content_key: SharedString = match self.icon {
Some(icon) => format!("{icon:?}|{}", self.label).into(),
None => self.label.clone(),
};
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-split-button-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
SplitButtonInternal::new(
content_key.clone(),
self.label.clone(),
self.icon,
now,
cx.focus_handle(),
cx.focus_handle(),
)
});
{
let prev = internal.read(cx).last_key.clone();
if prev != content_key {
internal.update(cx, |s, _| {
s.last_key = content_key.clone();
s.morph_armed_until_secs = now + T::MORPH_WINDOW;
if s.label != self.label {
s.previous_label = s.label.clone();
s.label = self.label.clone();
s.label_changed_at_secs = now;
}
if s.icon != self.icon {
s.previous_icon = s.icon;
s.icon = self.icon;
s.icon_changed_at_secs = now;
}
});
}
}
if self.disabled {
internal.update(cx, |s, _| {
s.open = false;
s.highlighted = None;
s.primary_pressed = false;
s.trigger_pressed = false;
});
}
let snap = internal.read(cx).clone();
let is_open = snap.open && !self.disabled;
let target_scale = if !self.disabled && !reduced && snap.primary_pressed {
T::PRESS_SCALE
} else {
1.0
};
let animated_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), "press-scale"),
target_scale,
motion.spring.snappy,
window,
cx,
)
};
let chevron_deg = if reduced {
if is_open { 180.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "chevron-deg"),
if is_open { 180.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
)
};
let measured_w = *snap.measured_slot_width.borrow();
let morph_active = !reduced
&& *snap.has_measured.borrow()
&& measured_w > 0.0
&& now <= snap.morph_armed_until_secs;
let morphed_w = if measured_w > 0.0 && !reduced {
let sample = arc_spring_with_options(
(self.id.clone(), "slot-width"),
measured_w,
SpringOptions::new(motion.spring.morph),
window,
cx,
);
if morph_active {
Some(sample.value)
} else {
None
}
} else {
None
};
let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
let label_dur = if reduced {
motion.duration.instant
} else {
motion.duration.standard
}
.as_secs_f64();
let (shared_start, shared_end) = shared_edges(&snap.previous_label, &self.label);
let count = self.label.chars().count();
let glyphs = self.label.chars().enumerate().map(|(index, ch)| {
let kept = index < shared_start || index >= count.saturating_sub(shared_end);
let delay = if reduced || kept {
0.0
} else {
(index as f64 * motion.stagger.char.as_secs_f64()).min(T::GLYPH_DELAY_CAP)
};
let t = if kept {
1.0
} else {
((label_elapsed - delay) / label_dur).clamp(0.0, 1.0) as f32
};
if t < 1.0 {
window.request_animation_frame();
}
let e = if reduced {
t
} else {
CubicBezier::from_spec(motion.ease.enter).sample(t)
};
let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - e), reduced);
div()
.relative()
.flex_none()
.top(if reduced {
px(0.0)
} else {
T::ENTER_Y * (1.0 - e)
})
.opacity(e * blur.opacity_multiplier)
.child(SharedString::from(if ch == ' ' {
"\u{00a0}".to_owned()
} else {
ch.to_string()
}))
});
let previous = snap.previous_label.clone();
let old_count = previous.chars().count();
let exit_progress = (label_elapsed
/ if reduced {
motion.duration.instant
} else {
motion.duration.fast
}
.as_secs_f64())
.clamp(0.0, 1.0) as f32;
let old_glyphs = previous.chars().enumerate().map(|(index, ch)| {
let kept = index < shared_start || index >= old_count.saturating_sub(shared_end);
div()
.flex_none()
.opacity(if kept { 0.0 } else { 1.0 - exit_progress })
.child(SharedString::from(if ch == ' ' {
"\u{00a0}".to_owned()
} else {
ch.to_string()
}))
});
let label_el = div()
.relative()
.flex_none()
.whitespace_nowrap()
.child(div().flex().children(glyphs))
.when(!previous.is_empty() && exit_progress < 1.0, |this| {
window.request_animation_frame();
this.child(
div()
.absolute()
.left_0()
.top(if reduced {
px(0.0)
} else {
T::EXIT_Y * exit_progress
})
.flex()
.children(old_glyphs),
)
});
let icon_progress = ((now - snap.icon_changed_at_secs).max(0.0)
/ motion.duration.fast.as_secs_f64())
.clamp(0.0, 1.0) as f32;
if icon_progress < 1.0 {
window.request_animation_frame();
}
let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: if reduced {
motion.duration.instant
} else {
motion.duration.fast
},
exit_duration: if reduced {
motion.duration.instant
} else {
T::MENU_EXIT
},
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let is_secondary = self.variant == SplitButtonVariant::Secondary;
let radius = if is_secondary {
Radii::PILL
} else {
Radii::CONTROL
};
let min_h = if is_secondary {
ControlHeights::SM
} else {
ControlHeights::MD
};
let trigger_w = if is_secondary {
T::SECONDARY_TRIGGER_WIDTH
} else {
T::TRIGGER_WIDTH
};
let (base_bg, border_color, fg, divider_color, primary_bg, trigger_bg) = if is_secondary {
let hover_bg = colors.surface_muted;
let active_bg = oklab_mix(colors.surface_muted, colors.border, 0.45);
let p_bg = if self.disabled {
colors.surface
} else if snap.primary_pressed {
active_bg
} else if snap.primary_hovered {
hover_bg
} else {
colors.surface
};
let t_bg = if self.disabled {
colors.surface
} else if snap.trigger_pressed || is_open {
active_bg
} else if snap.trigger_hovered {
hover_bg
} else {
colors.surface
};
(
colors.surface,
colors.border,
colors.foreground,
colors.border_subtle,
p_bg,
t_bg,
)
} else {
let hover_bg = oklab_mix(colors.foreground, colors.background, 0.88);
let active_bg = oklab_mix(colors.foreground, colors.background, 0.80);
let p_bg = if self.disabled {
colors.foreground
} else if snap.primary_pressed {
active_bg
} else if snap.primary_hovered {
hover_bg
} else {
colors.foreground
};
let t_bg = if self.disabled {
colors.foreground
} else if snap.trigger_pressed || is_open {
active_bg
} else if snap.trigger_hovered {
hover_bg
} else {
colors.foreground
};
(
colors.foreground,
colors.foreground,
colors.background,
oklab_mix(colors.background, colors.foreground, 0.18),
p_bg,
t_bg,
)
};
let icon_el = div()
.relative()
.flex_none()
.size(Spacing::S4)
.when_some(self.icon, |this, icon| {
this.child(
svg()
.path(icon.path())
.size_full()
.text_color(fg)
.opacity(icon_progress),
)
})
.when_some(
snap.previous_icon.filter(|_| icon_progress < 1.0),
|this, icon| {
this.child(
svg()
.absolute()
.inset_0()
.path(icon.path())
.size_full()
.text_color(fg)
.opacity(1.0 - icon_progress),
)
},
);
let group_bounds_ref = snap.group_bounds.clone();
let menu_bounds_for_outside = snap.menu_bounds.clone();
let group_bounds_for_outside = snap.group_bounds.clone();
let internal_outside = internal.clone();
let backdrop = canvas(
move |rect, _, _| {
*group_bounds_ref.borrow_mut() = Some(rect);
},
move |rect, _, window, _| {
let paint_rect = scaled_bounds(
rect,
animated_scale,
animated_scale,
TransformOrigin::CENTER,
);
window.paint_quad(quad(
paint_rect,
Corners::all(radius.min(paint_rect.size.height * 0.5)),
base_bg,
Edges::all(px(0.0)),
border_color,
BorderStyle::Solid,
));
if is_open {
let g_ref = group_bounds_for_outside.clone();
let m_ref = menu_bounds_for_outside.clone();
let st = internal_outside.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let in_group = g_ref.borrow().is_some_and(|b| b.contains(&event.position));
let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
if !in_group && !in_menu {
st.update(cx, |s, _| {
s.open = false;
s.highlighted = None;
});
window.refresh();
}
});
}
},
)
.absolute()
.inset_0();
let slot_w_ref = snap.measured_slot_width.clone();
let has_m_ref = snap.has_measured.clone();
let slot_probe = canvas(
move |rect, window, _| {
let w = f32::from(rect.size.width);
let prev = *slot_w_ref.borrow();
*slot_w_ref.borrow_mut() = w;
if w > 0.0 {
*has_m_ref.borrow_mut() = true;
}
if (w - prev).abs() > 0.5 && prev > 0.0 {
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let primary_id = ElementId::NamedChild(self.id.clone().into(), "primary".into());
let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
let int_p_hover = internal.clone();
let int_p_down = internal.clone();
let int_p_up = internal.clone();
let int_p_out = internal.clone();
let int_t_hover = internal.clone();
let int_t_down = internal.clone();
let int_t_up = internal.clone();
let int_t_out = internal.clone();
let int_t_click = internal.clone();
let on_click = self.on_click;
let is_disabled = self.disabled;
let focus_for_open = snap.focus_handle.clone();
let actions_for_trigger = self.actions.clone();
let int_t_key = internal.clone();
let actions_for_key = self.actions.clone();
let menu_key_focus = snap.focus_handle.clone();
let primary_btn = BaseButton::new(primary_id)
.disabled(self.disabled)
.accessibility_label(self.label.clone())
.on_click(move |_, window, cx| {
if is_disabled {
return;
}
if let Some(handler) = &on_click {
handler(&(), window, cx);
}
window.refresh();
})
.relative()
.flex()
.items_center()
.justify_center()
.min_h(min_h)
.when(is_secondary, |this| {
this.min_w(T::SECONDARY_MIN_WIDTH)
.px(Spacing::S3)
.text_size(Typography::TEXT_XS)
})
.when(!is_secondary, |this| {
this.px(Spacing::S4).text_size(Typography::TEXT_SM)
})
.flex_none()
.whitespace_nowrap()
.rounded_tl((radius - px(1.0)).max(px(0.0)))
.rounded_bl((radius - px(1.0)).max(px(0.0)))
.bg(primary_bg)
.text_color(fg)
.when(!self.disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_p_hover.update(cx, |s, _| {
s.primary_hovered = *hovered;
if !*hovered {
s.primary_pressed = false;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if is_disabled {
return;
}
int_p_down.update(cx, |s, _| s.primary_pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_p_up.update(cx, |s, _| s.primary_pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_p_out.update(cx, |s, _| s.primary_pressed = false);
window.refresh();
})
.child(
div()
.relative()
.flex()
.items_center()
.when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
.child(
div()
.relative()
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.child(slot_probe)
.when(
self.icon.is_some()
|| (snap.previous_icon.is_some() && icon_progress < 1.0),
|this| this.child(icon_el),
)
.child(label_el),
),
);
let trigger_label = SharedString::from(format!("{} more actions", self.label));
let trigger_btn = BaseButton::new(trigger_id)
.track_focus(&snap.trigger_focus)
.disabled(self.disabled)
.aria_expanded(is_open)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
let key = event.keystroke.key.as_str();
if !is_disabled && matches!(key, "down" | "up") && !actions_for_key.is_empty() {
let now = motion_now(cx);
int_t_key.update(cx, |s, _| {
s.open = true;
s.opened_at_secs = now;
s.highlighted = next_enabled_index(
&actions_for_key,
None,
if key == "up" { -1 } else { 1 },
);
});
window.focus(&menu_key_focus, cx);
window.refresh();
cx.stop_propagation();
}
})
.accessibility_label(trigger_label)
.on_click(move |_, window, cx| {
if is_disabled {
return;
}
let t_now = motion_now(cx);
let mut became_open = false;
int_t_click.update(cx, |s, _| {
s.open = !s.open;
became_open = s.open;
if s.open {
s.opened_at_secs = t_now;
s.highlighted = next_enabled_index(&actions_for_trigger, None, 1);
} else {
s.highlighted = None;
}
});
if became_open {
window.focus(&focus_for_open, cx);
}
window.refresh();
})
.relative()
.flex()
.items_center()
.justify_center()
.w(trigger_w)
.flex_none()
.min_h(min_h)
.border_l_1()
.border_color(divider_color)
.rounded_tr((radius - px(1.0)).max(px(0.0)))
.rounded_br((radius - px(1.0)).max(px(0.0)))
.bg(trigger_bg)
.text_color(fg)
.when(!self.disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_t_hover.update(cx, |s, _| {
s.trigger_hovered = *hovered;
if !*hovered {
s.trigger_pressed = false;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if is_disabled {
return;
}
int_t_down.update(cx, |s, _| s.trigger_pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_t_up.update(cx, |s, _| s.trigger_pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_t_out.update(cx, |s, _| s.trigger_pressed = false);
window.refresh();
})
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
paint_rotated_chevron(cx, cy, chevron_deg, fg, window);
},
)
.size(px(16.0)),
);
let menu_el = if menu_presence.should_render() && !self.actions.is_empty() {
let p = menu_presence.progress.clamp(0.0, 1.0);
let menu_y = if reduced {
0.0
} else {
-f32::from(T::ENTER_Y) * (1.0 - p)
};
let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
let menu_bounds_ref = snap.menu_bounds.clone();
let menu_probe = canvas(
move |rect, _, _| {
*menu_bounds_ref.borrow_mut() = Some(rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let int_key = internal.clone();
let actions_key = self.actions.clone();
let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
let focus_handle = snap.focus_handle.clone();
let highlighted = snap.highlighted;
let return_focus = snap.trigger_focus.clone();
let has_icons = self.actions.iter().any(|a| a.icon.is_some());
let viewport = window.viewport_size();
let menu_width =
T::MENU_MIN_WIDTH.min((viewport.width - Spacing::S3 * 2.0).max(px(0.0)));
let menu_height =
ControlHeights::SM * self.actions.len() as f32 + T::MENU_PADDING * 2.0 + px(2.0);
let target = snap.group_bounds.borrow().unwrap_or_default();
let above = target.bottom() + Spacing::S1 + menu_height > viewport.height - Spacing::S3
&& target.top() > viewport.height - target.bottom();
let layer = anchored()
.anchor(if above {
Anchor::BottomRight
} else {
Anchor::TopRight
})
.position(point(
target
.right()
.clamp(Spacing::S3 + menu_width, viewport.width - Spacing::S3),
if above {
target.top() - Spacing::S1 - px(menu_y)
} else {
target.bottom() + Spacing::S1 + px(menu_y)
},
))
.snap_to_window_with_margin(Spacing::S3);
let item_rows = self.actions.into_iter().enumerate().map(|(idx, action)| {
let is_hi = highlighted == Some(idx);
let item_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("menu-item-{idx}")),
);
let stagger_delay = if reduced {
0.0
} else {
(idx.min(4) as f64) * motion.stagger.item.as_secs_f64()
};
let item_op = if reduced || !is_open {
1.0
} else {
let t = ((menu_elapsed - stagger_delay)
/ motion.duration.standard.as_secs_f64())
.clamp(0.0, 1.0) as f32;
if t < 1.0 {
window.request_animation_frame();
}
CubicBezier::from_spec(motion.ease.enter).sample(t)
};
let int_hi = internal.clone();
let int_sel = internal.clone();
let on_select = action.on_select.clone();
let item_disabled = action.disabled;
let item_inert = item_disabled || !is_open;
let item_return_focus = snap.trigger_focus.clone();
let item_fg = if action.destructive {
colors.danger
} else {
colors.foreground
};
let hi_bg = if action.destructive {
oklab_mix(colors.danger, colors.surface, 0.08)
} else {
colors.surface_muted
};
div()
.id(item_id)
.test_support()
.role(Role::MenuItem)
.aria_label(action.label.clone())
.flex()
.flex_row()
.items_center()
.gap(T::ITEM_GAP)
.min_h(ControlHeights::SM)
.px(T::ITEM_PADDING)
.rounded(Radii::PANEL - Spacing::S1 - px(2.0))
.text_size(Typography::TEXT_SM)
.text_color(item_fg)
.bg(if is_hi && !item_disabled {
hi_bg
} else {
Hsla::transparent_black()
})
.opacity(if item_disabled { 0.45 } else { item_op })
.when(!item_disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
if item_inert {
return;
}
int_hi.update(cx, |s, _| {
if *hovered {
s.highlighted = Some(idx);
} else if s.highlighted == Some(idx) {
s.highlighted = None;
}
});
window.refresh();
})
.on_click(move |_, window, cx| {
if item_inert {
return;
}
int_sel.update(cx, |s, _| {
s.open = false;
s.highlighted = None;
});
window.focus(&item_return_focus, cx);
if let Some(cb) = &on_select {
cb(&(), window, cx);
}
cx.stop_propagation();
window.refresh();
})
.when(has_icons, |this| {
this.child(div().flex_none().size(Spacing::S4).when_some(
action.icon,
|this, icon| {
this.child(svg().path(icon.path()).size_full().text_color(item_fg))
},
))
})
.child(action.label)
});
Some(
deferred(
layer.child(
div()
.id(menu_id)
.test_support()
.track_focus(&focus_handle)
.role(Role::Menu)
.w(menu_width)
.max_h((viewport.height - Spacing::S3 * 2.0).max(ControlHeights::SM))
.overflow_y_scroll()
.p(T::MENU_PADDING)
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
.opacity(p)
.flex()
.flex_col()
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if !int_key.read(cx).open {
return;
}
let key = event.keystroke.key.as_str();
if matches!(key, "escape" | "down" | "up" | "enter" | "space") {
cx.stop_propagation();
}
match key {
"escape" => {
window.focus(&return_focus, cx);
int_key.update(cx, |s, _| {
s.open = false;
s.highlighted = None;
});
window.refresh();
}
"down" => {
int_key.update(cx, |s, _| {
s.highlighted =
next_enabled_index(&actions_key, s.highlighted, 1);
});
window.refresh();
}
"up" => {
int_key.update(cx, |s, _| {
s.highlighted =
next_enabled_index(&actions_key, s.highlighted, -1);
});
window.refresh();
}
"enter" | "space" => {
let sel = int_key.read(cx).highlighted;
if let Some(idx) = sel
&& let Some(act) = actions_key.get(idx)
&& !act.disabled
{
int_key.update(cx, |s, _| {
s.open = false;
s.highlighted = None;
});
window.focus(&return_focus, cx);
if let Some(cb) = &act.on_select {
cb(&(), window, cx);
}
window.refresh();
}
}
_ => {}
}
})
.child(menu_probe)
.children(item_rows),
),
)
.with_priority(1),
)
} else {
None
};
div()
.id(self.id)
.relative()
.flex()
.flex_row()
.items_stretch()
.flex_none()
.rounded(radius)
.border_1()
.border_color(border_color)
.when(self.disabled, |this| this.opacity(0.52))
.child(backdrop)
.child(primary_btn)
.child(trigger_btn)
.when_some(menu_el, |this, menu| this.child(menu))
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct SplitHost {
primary_clicks: Rc<Cell<usize>>,
menu_clicks: Rc<Cell<usize>>,
}
impl Render for SplitHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let p_clicks = self.primary_clicks.clone();
let m_clicks = self.menu_clicks.clone();
div().p(Spacing::S6).child(
SplitButton::new("merge-split", "Merge pull request")
.on_click(cx.listener(move |_, _, _, _| {
p_clicks.set(p_clicks.get() + 1);
}))
.actions([
SplitButtonAction::new("Squash and merge").on_select(cx.listener(
move |_, _, _, _| {
m_clicks.set(m_clicks.get() + 1);
},
)),
SplitButtonAction::new("Rebase and merge").disabled(true),
]),
)
}
}
#[test]
fn split_button_character_identity_and_navigation() {
assert_eq!(shared_edges("Copy page", "Copied"), (3, 0));
assert_eq!(shared_edges("压缩合并", "变基合并"), (0, 2));
let actions = [
SplitButtonAction::new("a"),
SplitButtonAction::new("b").disabled(true),
SplitButtonAction::new("close").destructive(true),
];
assert_eq!(next_enabled_index(&actions, Some(0), -1), Some(2));
assert_eq!(next_enabled_index(&actions, Some(2), 1), Some(0));
assert_eq!(next_enabled_index(&actions, Some(0), 1), Some(2));
}
#[gpui_kit::test]
fn split_button_keyboard_escape_returns_to_trigger(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let menu_clicks = Rc::new(Cell::new(0));
let (_, cx) = cx.add_window_view(|_, _| SplitHost {
primary_clicks: Rc::new(Cell::new(0)),
menu_clicks: menu_clicks.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let t = window
.find_by_label("Merge pull request more actions")
.bounds()
.center();
window.pointer_down(t, MouseButton::Left, cx);
window.pointer_up(t, MouseButton::Left, cx);
window.render_frame(cx);
});
cx.simulate_keystrokes("escape");
cx.update(|window, cx| {
window.render_frame(cx);
});
cx.simulate_keystrokes("down");
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(
window.find_by_label("Squash and merge").role(),
Some(Role::MenuItem)
);
});
cx.simulate_keystrokes("down enter");
cx.run_until_parked();
assert_eq!(menu_clicks.get(), 1, "跳过禁用项并循环回首项,只执行一次");
}
struct EdgeHost {
disabled: bool,
}
impl Render for EdgeHost {
fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.w(window.viewport_size().width)
.h(window.viewport_size().height)
.flex()
.items_end()
.justify_end()
.p(Spacing::S1)
.child(
SplitButton::new("edge-split", "Edge")
.disabled(self.disabled)
.actions([
SplitButtonAction::new("Alternative"),
SplitButtonAction::new("Close").destructive(true),
]),
)
}
}
#[gpui_kit::test]
fn split_button_menu_avoids_edges_and_can_reenable(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Dark, Accent::Violet, cx);
});
let (view, cx) = cx.add_window_view(|_, _| EdgeHost { disabled: false });
cx.update(|window, cx| {
window.render_frame(cx);
let t = window.find_by_label("Edge more actions").bounds().center();
window.pointer_down(t, MouseButton::Left, cx);
window.pointer_up(t, MouseButton::Left, cx);
window.render_frame(cx);
let item = window.find_by_label("Alternative").bounds();
assert!(
item.bottom() <= t.y,
"底部空间不足时应向上打开: item={item:?}, trigger={t:?}, viewport={:?}",
window.viewport_size()
);
assert!(item.left() >= Spacing::S3);
assert!(item.right() <= window.viewport_size().width - Spacing::S3);
view.update(cx, |this, cx| {
this.disabled = true;
cx.notify();
});
window.render_frame(cx);
view.update(cx, |this, cx| {
this.disabled = false;
cx.notify();
});
window.render_frame(cx);
let t = window.find_by_label("Edge more actions").bounds().center();
window.pointer_down(t, MouseButton::Left, cx);
window.pointer_up(t, MouseButton::Left, cx);
window.render_frame(cx);
assert!(window.find_by_label("Alternative").bounds().bottom() <= t.y);
});
}
#[gpui_kit::test]
fn split_button_primary_and_menu_selection_work(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let primary_clicks = Rc::new(Cell::new(0usize));
let menu_clicks = Rc::new(Cell::new(0usize));
let (_view, cx) = cx.add_window_view(|_, _| SplitHost {
primary_clicks: primary_clicks.clone(),
menu_clicks: menu_clicks.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let primary = window.find_by_label("Merge pull request");
assert_eq!(primary.role(), Some(Role::Button));
let pos = primary.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert_eq!(primary_clicks.get(), 1);
let trigger = window.find_by_label("Merge pull request more actions");
let t_pos = trigger.bounds().center();
window.pointer_down(t_pos, MouseButton::Left, cx);
window.pointer_up(t_pos, MouseButton::Left, cx);
window.render_frame(cx);
let item = window.find_by_label("Squash and merge");
assert_eq!(item.role(), Some(Role::MenuItem));
let i_pos = item.bounds().center();
window.pointer_down(i_pos, MouseButton::Left, cx);
window.pointer_up(i_pos, MouseButton::Left, cx);
assert_eq!(menu_clicks.get(), 1);
});
}
}