use std::{cell::RefCell, rc::Rc};
use arc_motion::{BlurFallback, arc_spring, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Spacing, Typography};
use gpui_kit::{
AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, TestSupportExt as _,
Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AccordionSize {
#[default]
Md,
Lg,
}
pub struct AccordionItem {
pub title: SharedString,
pub content: AnyElement,
}
impl AccordionItem {
pub fn new(title: impl Into<SharedString>, content: impl IntoElement) -> Self {
Self {
title: title.into(),
content: content.into_any_element(),
}
}
}
pub fn accordion_content_sample(progress: f32, reduced: bool) -> (f32, f32) {
let p = progress.clamp(0.0, 1.0);
if reduced {
return (0.0, if p >= 0.5 { 1.0 } else { 0.0 });
}
let y = -6.0 * (1.0 - p);
let blur = BlurFallback::evaluate(px((1.0 - p) * 2.0), false);
let opacity = (p * blur.opacity_multiplier).clamp(0.0, 1.0);
(y, opacity)
}
fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let cos = rad.cos();
let sin = rad.sin();
let rot =
|dx: f32, dy: f32| -> (f32, f32) { (cx + dx * cos - dy * sin, cy + dx * sin + dy * cos) };
let (x1, y1) = rot(-4.25, -1.75);
let (xm, ym) = rot(0.0, 2.5);
let (x2, y2) = rot(4.25, -1.75);
let mut b = PathBuilder::stroke(px(1.65));
b.move_to(point(px(x1), px(y1)));
b.line_to(point(px(xm), px(ym)));
b.line_to(point(px(x2), px(y2)));
if let Ok(path) = b.build() {
window.paint_path(path, color);
}
}
type ChangeCallback = Rc<dyn Fn(&Option<usize>, &mut Window, &mut App)>;
#[derive(Clone)]
struct AccordionInternal {
open_index: Option<usize>,
focused_index: usize,
hovered_index: Option<usize>,
measured_heights: Rc<RefCell<Vec<f32>>>,
focus_handle: FocusHandle,
}
impl AccordionInternal {
fn new(default_open: Option<usize>, count: usize, focus_handle: FocusHandle) -> Self {
let initial = default_open.filter(|&idx| idx < count);
Self {
open_index: initial,
focused_index: initial.unwrap_or(0),
hovered_index: None,
measured_heights: Rc::new(RefCell::new(vec![72.0; count])),
focus_handle,
}
}
}
#[derive(IntoElement)]
pub struct Accordion {
id: ElementId,
items: Vec<AccordionItem>,
default_open: Option<usize>,
open_index: Option<Option<usize>>,
size: AccordionSize,
on_change: Option<ChangeCallback>,
}
impl Accordion {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: Vec::new(),
default_open: Some(0),
open_index: None,
size: AccordionSize::Md,
on_change: None,
}
}
pub fn item(mut self, title: impl Into<SharedString>, content: impl IntoElement) -> Self {
self.items.push(AccordionItem::new(title, content));
self
}
pub fn items(mut self, items: impl IntoIterator<Item = AccordionItem>) -> Self {
self.items.extend(items);
self
}
pub fn default_open(mut self, index: Option<usize>) -> Self {
self.default_open = index;
self
}
pub fn open_index(mut self, open_index: Option<usize>) -> Self {
self.open_index = Some(open_index);
self
}
pub fn size(mut self, size: AccordionSize) -> Self {
self.size = size;
self
}
pub fn on_change(
mut self,
handler: impl Fn(&Option<usize>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Accordion {
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 count = self.items.len();
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-accordion-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
AccordionInternal::new(self.default_open, count, cx.focus_handle())
});
{
let mut heights = internal.read(cx).measured_heights.borrow_mut();
if heights.len() < count {
heights.resize(
count,
match self.size {
AccordionSize::Md => 72.0,
AccordionSize::Lg => 88.0,
},
);
}
}
let snap = internal.read(cx).clone();
let active_open = self.open_index.unwrap_or(snap.open_index);
let size = self.size;
let (trigger_min_h, trigger_py, trigger_gap, title_size, body_size, body_pr, body_pb) =
match size {
AccordionSize::Md => (
px(40.0),
Spacing::S2,
Spacing::S5,
Typography::TEXT_SM,
Typography::TEXT_SM,
Spacing::S8,
Spacing::S5,
),
AccordionSize::Lg => (
px(76.0),
Spacing::S5,
Spacing::S8,
Typography::TEXT_LG,
Typography::TEXT_BASE,
Spacing::S12,
Spacing::S6,
),
};
let int_key = internal.clone();
let on_change_key = self.on_change.clone();
let mut root = div()
.id(self.id.clone())
.test_support()
.track_focus(&snap.focus_handle)
.w_full()
.flex()
.flex_col()
.border_t_1()
.border_color(colors.border)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if count == 0 {
return;
}
let key = event.keystroke.key.as_str();
match key {
"down" | "arrowdown" => {
int_key.update(cx, |s, _| {
s.focused_index = (s.focused_index + 1) % count;
});
window.refresh();
}
"up" | "arrowup" => {
int_key.update(cx, |s, _| {
s.focused_index = (s.focused_index + count - 1) % count;
});
window.refresh();
}
"home" => {
int_key.update(cx, |s, _| {
s.focused_index = 0;
});
window.refresh();
}
"end" => {
int_key.update(cx, |s, _| {
s.focused_index = count - 1;
});
window.refresh();
}
"enter" | "space" | " " => {
let next = {
let cur = int_key.read(cx);
let idx = cur.focused_index.min(count - 1);
if cur.open_index == Some(idx) {
None
} else {
Some(idx)
}
};
int_key.update(cx, |s, _| {
s.open_index = next;
});
if let Some(h) = &on_change_key {
h(&next, window, cx);
}
window.refresh();
}
_ => {}
}
});
for (index, item) in self.items.into_iter().enumerate() {
let is_open = active_open == Some(index);
let is_hovered = snap.hovered_index == Some(index);
let target_progress = if is_open { 1.0_f32 } else { 0.0_f32 };
let progress = if reduced {
target_progress
} else {
arc_spring(
(
self.id.clone(),
SharedString::from(format!("panel-p-{index}")),
),
target_progress,
motion.spring.smooth,
window,
cx,
)
};
let chevron_deg = if reduced {
if is_open { 180.0 } else { 0.0 }
} else {
arc_spring(
(
self.id.clone(),
SharedString::from(format!("chevron-deg-{index}")),
),
if is_open { 180.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
)
};
let natural_h = snap
.measured_heights
.borrow()
.get(index)
.copied()
.unwrap_or(72.0)
.max(24.0);
let animated_h = (natural_h * progress).max(0.0);
let (content_y, content_alpha) = accordion_content_sample(progress, reduced);
let title_color = if is_hovered {
colors.text_secondary
} else {
colors.foreground
};
let icon_color = if is_open || is_hovered {
colors.foreground
} else {
colors.text_muted
};
let int_hover = internal.clone();
let int_click = internal.clone();
let on_change_click = self.on_change.clone();
let focus_click = snap.focus_handle.clone();
let trigger = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("trigger-{index}")),
))
.test_support()
.role(Role::Button)
.aria_label(item.title.clone())
.aria_expanded(is_open)
.w_full()
.min_h(trigger_min_h)
.py(trigger_py)
.flex()
.items_center()
.justify_between()
.gap(trigger_gap)
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
if *hovered {
s.hovered_index = Some(index);
} else if s.hovered_index == Some(index) {
s.hovered_index = None;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let next = if active_open == Some(index) {
None
} else {
Some(index)
};
int_click.update(cx, |s, _| {
s.open_index = next;
s.focused_index = index;
});
focus_click.focus(window, cx);
if let Some(h) = &on_change_click {
h(&next, window, cx);
}
window.refresh();
})
.child(
div()
.flex_1()
.text_size(title_size)
.font_medium()
.text_color(title_color)
.child(item.title),
)
.child(
div().w(px(17.0)).h(px(17.0)).flex_none().child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_pt =
f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy_pt = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_rotated_chevron(
cx_pt,
cy_pt,
chevron_deg,
icon_color,
window,
);
},
)
.size_full(),
),
);
let mut row = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("item-{index}")),
))
.test_support()
.w_full()
.flex()
.flex_col()
.border_b_1()
.border_color(colors.border)
.child(trigger);
if is_open || animated_h > 0.5 {
let heights_ref = snap.measured_heights.clone();
let measure_probe = canvas(
move |rect, _, _| {
let h = f32::from(rect.size.height);
if h > 4.0 {
let mut list = heights_ref.borrow_mut();
if let Some(slot) = list.get_mut(index) {
*slot = h;
}
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
row = row.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("panel-{index}")),
))
.test_support()
.w_full()
.h(px(animated_h))
.overflow_hidden()
.opacity(content_alpha)
.child(
div()
.relative()
.w_full()
.top(px(content_y))
.pr(body_pr)
.pb(body_pb)
.text_size(body_size)
.text_color(colors.text_secondary)
.child(measure_probe)
.child(item.content),
),
);
}
root = root.child(row);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accordion_content_sample_moves_from_minus_6px_to_zero() {
let (y0, a0) = accordion_content_sample(0.0, false);
assert!((y0 - (-6.0)).abs() < 1e-4);
assert!(a0.abs() < 1e-4);
let (ym, am) = accordion_content_sample(0.5, false);
assert!(ym > -6.0 && ym < 0.0);
assert!(am > 0.2 && am < 0.8);
let (y1, a1) = accordion_content_sample(1.0, false);
assert!(y1.abs() < 1e-4);
assert!((a1 - 1.0).abs() < 1e-4);
}
#[test]
fn accordion_content_sample_respects_reduced_motion() {
let (y_closed, a_closed) = accordion_content_sample(0.0, true);
assert!(y_closed.abs() < 1e-4);
assert!(a_closed.abs() < 1e-4);
let (y_open, a_open) = accordion_content_sample(1.0, true);
assert!(y_open.abs() < 1e-4);
assert!((a_open - 1.0).abs() < 1e-4);
}
}