use super::projected_media::ProjectedMedia;
use arc_graphics3d::ProjectedImageParams;
use arc_motion::{ScalarTween, TweenEase, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
App, Bounds, ContentMask, Corners, ElementId, FocusHandle, Hsla, ImageSource,
ImgResourceLoader, IntoElement, Orientation, ParentElement, Pixels, Point, RenderImage,
RenderOnce, Role, SharedString, Styled, TestSupportExt as _, TextAlign, TextRun, Window,
bounds, canvas, div, fill, point, prelude::*, px, size,
};
use std::{cell::RefCell, rc::Rc, sync::Arc};
pub use arc_motion::TweenEase as AccordionGalleryEase;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AccordionGalleryTrigger {
#[default]
Hover,
Click,
}
#[derive(Clone)]
pub struct AccordionGalleryItem {
pub image: ImageSource,
pub label: SharedString,
pub link: Option<SharedString>,
pub alt: SharedString,
}
impl AccordionGalleryItem {
pub fn new(image: impl Into<ImageSource>) -> Self {
Self {
image: image.into(),
label: "".into(),
link: None,
alt: "".into(),
}
}
pub fn label(mut self, value: impl Into<SharedString>) -> Self {
self.label = value.into();
self
}
pub fn link(mut self, value: impl Into<SharedString>) -> Self {
self.link = Some(value.into());
self
}
pub fn alt(mut self, value: impl Into<SharedString>) -> Self {
self.alt = value.into();
self
}
}
#[derive(Clone, Debug)]
pub struct AccordionGalleryConfig {
pub default_index: usize,
pub accent_color: Option<Hsla>,
pub overlay_color: Option<Hsla>,
pub text_color: Option<Hsla>,
pub grayscale: bool,
pub show_labels: bool,
pub duration: f32,
pub ease: AccordionGalleryEase,
pub parallax: f32,
pub tilt: f32,
pub stagger: f32,
pub trigger: AccordionGalleryTrigger,
pub height: f32,
pub gap: f32,
pub radius: f32,
pub expand_ratio: f32,
pub orientation: Orientation,
}
impl Default for AccordionGalleryConfig {
fn default() -> Self {
Self {
default_index: 2,
accent_color: None,
overlay_color: None,
text_color: None,
grayscale: true,
show_labels: true,
duration: 0.6,
ease: TweenEase::Power3Out,
parallax: 0.5,
tilt: 8.0,
stagger: 0.06,
trigger: AccordionGalleryTrigger::Hover,
height: 460.0,
gap: 10.0,
radius: 16.0,
expand_ratio: 0.52,
orientation: Orientation::Horizontal,
}
}
}
fn finite(v: f32, default: f32, lo: f32, hi: f32) -> f32 {
if v.is_finite() {
v.clamp(lo, hi)
} else {
default
}
}
impl AccordionGalleryConfig {
fn sanitized(mut self) -> Self {
self.duration = finite(self.duration, 0.6, 0.0, 10.0);
self.parallax = finite(self.parallax, 0.5, 0.0, 4.0);
self.tilt = finite(self.tilt, 8.0, 0.0, 45.0);
self.stagger = finite(self.stagger, 0.06, 0.0, 2.0);
self.height = finite(self.height, 460.0, 84.0, 1800.0);
self.gap = finite(self.gap, 10.0, 0.0, 80.0);
self.radius = finite(self.radius, 16.0, 0.0, 100.0);
self.expand_ratio = finite(self.expand_ratio, 0.52, 0.2, 0.9);
self
}
pub fn expanded_grow(&self, count: usize) -> f32 {
let r = finite(self.expand_ratio, 0.52, 0.2, 0.9);
if count <= 1 {
1.0
} else {
r * (count - 1) as f32 / (1.0 - r)
}
}
}
#[derive(Clone)]
struct PanelMotion {
grow: ScalarTween,
angle: ScalarTween,
drift: ScalarTween,
gray: ScalarTween,
dim: ScalarTween,
bar: ScalarTween,
text: ScalarTween,
}
impl PanelMotion {
fn new(i: usize, active: usize, count: usize, c: &AccordionGalleryConfig) -> Self {
let selected = i == active;
let sign = if i < active { 1.0 } else { -1.0 };
Self {
grow: ScalarTween::new(if selected {
c.expanded_grow(count)
} else {
1.0
}),
angle: ScalarTween::new(if selected { 0.0 } else { sign * c.tilt }),
drift: ScalarTween::new(if selected {
0.0
} else {
(active as f32 - i as f32).clamp(-1.5, 1.5) * c.parallax * 0.06
}),
gray: ScalarTween::new(if !selected && c.grayscale { 1.0 } else { 0.0 }),
dim: ScalarTween::new(if selected { 0.0 } else { 0.35 }),
bar: ScalarTween::new(if selected && c.show_labels { 1.0 } else { 0.0 }),
text: ScalarTween::new(if selected && c.show_labels { 1.0 } else { 0.0 }),
}
}
fn update(
&mut self,
i: usize,
active: usize,
count: usize,
c: &AccordionGalleryConfig,
now: f64,
reduced: bool,
) {
let target = Self::new(i, active, count, c);
for (current, next) in [
(&mut self.grow, target.grow),
(&mut self.angle, target.angle),
(&mut self.drift, target.drift),
(&mut self.gray, target.gray),
(&mut self.dim, target.dim),
] {
current.retarget(next.target(), now, c.duration, 0.0, c.ease, reduced);
}
let showing = i == active && c.show_labels;
let duration = c.duration * if showing { 1.0 } else { 0.6 };
self.bar
.retarget(target.bar.target(), now, duration, 0.0, c.ease, reduced);
self.text.retarget(
target.text.target(),
now,
duration,
if showing { c.stagger } else { 0.0 },
c.ease,
reduced,
);
}
fn settled(&self, now: f64) -> bool {
[
self.grow, self.angle, self.drift, self.gray, self.dim, self.bar, self.text,
]
.iter()
.all(|t| t.settled(now))
}
}
struct GalleryState {
active: usize,
panels: Vec<PanelMotion>,
focus: Vec<FocusHandle>,
focused: Option<usize>,
total: f32,
vertical: bool,
last_focus: Option<usize>,
mouse_was_active: bool,
}
type Change = Rc<dyn Fn(&usize, &mut Window, &mut App)>;
type Activate = Rc<dyn Fn(&AccordionGalleryActivation, &mut Window, &mut App)>;
#[derive(Clone, Debug)]
pub struct AccordionGalleryActivation {
pub index: usize,
pub link: SharedString,
}
#[derive(IntoElement)]
pub struct AccordionGallery {
id: ElementId,
items: Vec<AccordionGalleryItem>,
config: AccordionGalleryConfig,
index: Option<usize>,
on_change: Option<Change>,
on_activate: Option<Activate>,
}
impl AccordionGallery {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: default_items(),
config: Default::default(),
index: None,
on_change: None,
on_activate: None,
}
}
pub fn items(mut self, items: impl IntoIterator<Item = AccordionGalleryItem>) -> Self {
self.items = items.into_iter().collect();
self
}
pub fn config(mut self, config: AccordionGalleryConfig) -> Self {
self.config = config;
self
}
pub fn index(mut self, index: usize) -> Self {
self.index = Some(index);
self
}
pub fn on_index_change(mut self, cb: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
self.on_change = Some(Rc::new(cb));
self
}
pub fn on_activate(
mut self,
cb: impl Fn(&AccordionGalleryActivation, &mut Window, &mut App) + 'static,
) -> Self {
self.on_activate = Some(Rc::new(cb));
self
}
}
pub fn default_items() -> Vec<AccordionGalleryItem> {
[
(1015, "Canyon"),
(1018, "Ridgeline"),
(1039, "Falls"),
(1043, "Harbour"),
(1044, "Skyline"),
]
.into_iter()
.map(|(id, label)| {
AccordionGalleryItem::new(format!("https://picsum.photos/id/{id}/900/1200"))
.label(label)
.alt(label)
.link("#")
})
.collect()
}
fn select(
state: &Rc<RefCell<GalleryState>>,
index: usize,
controlled: bool,
cb: &Option<Change>,
window: &mut Window,
cx: &mut App,
) {
if state.borrow().active == index {
return;
}
if !controlled {
state.borrow_mut().active = index;
}
if let Some(cb) = cb {
cb(&index, window, cx);
}
window.refresh();
}
#[cfg(test)]
fn project(x: f32, y: f32, w: f32, h: f32, angle: f32, vertical: bool) -> (f32, f32) {
let a = angle.to_radians();
let (u, v) = (x - w * 0.5, y - h * 0.5);
let (rx, ry, z) = if vertical {
(u, v * a.cos(), -v * a.sin())
} else {
(u * a.cos(), v, -u * a.sin())
};
let k = 1400.0 / (1400.0 + z);
(w * 0.5 + rx * k, h * 0.5 + ry * k)
}
#[derive(Clone, Copy)]
struct PaintSpec {
angle: f32,
vertical: bool,
media: f32,
drift: f32,
radius: f32,
dim: f32,
overlay: Hsla,
}
fn paint_media_fallback(
rect: Bounds<Pixels>,
image: Option<&Arc<RenderImage>>,
gray: bool,
spec: PaintSpec,
window: &mut Window,
) {
if let Some(image) = image {
let native = image.size(0);
let scale = (rect.size.width.as_f32() / native.width.0 as f32)
.max(rect.size.height.as_f32() / native.height.0 as f32);
let image_size = size(
px(native.width.0 as f32 * scale),
px(native.height.0 as f32 * scale),
);
let dest = bounds(
rect.center() - point(image_size.width * 0.5, image_size.height * 0.5),
image_size,
);
let _ = window.paint_image(
rect,
dest,
Corners::all(px(spec.radius)),
image.clone(),
0,
gray,
);
} else {
window.paint_quad(fill(rect, spec.overlay).corner_radii(px(spec.radius)));
}
}
fn load_image(
source: &ImageSource,
window: &mut Window,
cx: &mut App,
) -> (Option<Arc<RenderImage>>, bool) {
match source {
ImageSource::Resource(resource) => {
match window.use_asset::<ImgResourceLoader>(resource, cx) {
Some(Ok(image)) => (Some(image), false),
Some(Err(_)) => (None, true),
None => (None, false),
}
}
ImageSource::Render(image) => (Some(image.clone()), false),
ImageSource::Custom(loader) => match loader(window, cx) {
Some(Ok(image)) => (Some(image), false),
Some(Err(_)) => (None, true),
None => (None, false),
},
ImageSource::Image(image) => (image.clone().use_render_image(window, cx), false),
}
}
impl RenderOnce for AccordionGallery {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let c = self.config.sanitized();
let count = self.items.len();
let colors = cx.arc_theme().colors;
let accent = c.accent_color.unwrap_or(colors.neutral[0]);
let overlay = c.overlay_color.unwrap_or(colors.neutral[11]);
let text_color = c.text_color.unwrap_or(colors.neutral[0]);
let state = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "state".into()),
cx,
|_, _| {
Rc::new(RefCell::new(GalleryState {
active: c.default_index.min(count.saturating_sub(1)),
panels: Vec::new(),
focus: Vec::new(),
focused: None,
total: 800.0,
vertical: false,
last_focus: None,
mouse_was_active: false,
}))
},
)
.read(cx)
.clone();
let now = motion_now(cx);
let reduced = is_reduced_motion(cx);
let newly_focused = {
let mut s = state.borrow_mut();
s.active = self.index.unwrap_or(s.active).min(count.saturating_sub(1));
if s.panels.len() != count {
s.panels = (0..count)
.map(|i| PanelMotion::new(i, s.active, count, &c))
.collect();
s.focus = (0..count)
.map(|_| cx.focus_handle().tab_index(0).tab_stop(true))
.collect();
}
let focused = s.focus.iter().position(|f| f.is_focused(window));
s.focused = focused;
let newly_focused = if focused != s.last_focus {
focused
} else {
None
};
s.last_focus = focused;
newly_focused
};
let controlled = self.index.is_some();
if let Some(i) = newly_focused {
let st = state.clone();
let cb = self.on_change.clone();
window.defer(cx, move |window, cx| {
let still_focused = st
.borrow()
.focus
.get(i)
.is_some_and(|f| f.is_focused(window));
if still_focused {
select(&st, i, controlled, &cb, window, cx);
}
});
window.request_animation_frame();
}
let vertical = c.orientation == Orientation::Vertical || state.borrow().total < 520.0;
state.borrow_mut().vertical = vertical;
let height = if vertical { c.height * 1.6 } else { c.height };
let mut root = div()
.id(self.id.clone())
.test_support()
.role(Role::List)
.aria_label("Image accordion gallery")
.relative()
.w_full()
.h(px(height))
.min_w_0()
.flex()
.gap(px(c.gap))
.when(vertical, |d| d.flex_col());
if count == 0 {
return root.child(
div()
.text_color(colors.text_muted)
.child("暂无图片 / No images"),
);
}
let total = if vertical {
height
} else {
state.borrow().total
};
let media =
((total - c.gap * (count.saturating_sub(1)) as f32).max(120.0) * c.expand_ratio * 1.22)
.max(140.0);
for (i, item) in self.items.into_iter().enumerate() {
let active = state.borrow().active;
let p = {
let mut s = state.borrow_mut();
let p = &mut s.panels[i];
p.update(i, active, count, &c, now, reduced);
if !p.settled(now) {
window.request_animation_frame();
}
p.clone()
};
let focused = state.borrow().focused == Some(i);
let focus = state.borrow().focus[i].clone();
let angle = if reduced || state.borrow().total < 520.0 {
0.0
} else {
p.angle.sample(now)
};
let spec = PaintSpec {
angle,
vertical,
media,
drift: p.drift.sample(now),
radius: c.radius,
dim: p.dim.sample(now),
overlay,
};
let (image, mut error) = load_image(&item.image, window, cx);
let image = image.filter(|image| {
let valid = image.frame_count() > 0 && {
let size = image.size(0);
size.width.0 > 0 && size.height.0 > 0
};
error |= !valid;
valid
});
let gray = p.gray.sample(now);
let media_state = ProjectedMedia::state(
ElementId::NamedChild(self.id.clone().into(), format!("media-{i}").into()),
window,
cx,
);
let st_hover = state.clone();
let cb_hover = self.on_change.clone();
let st_click = state.clone();
let cb_click = self.on_change.clone();
let activate = self.on_activate.clone();
let st_down = state.clone();
let down_focus = focus.clone();
let st_key = state.clone();
let cb_key = self.on_change.clone();
let link = item.link.clone();
let label = if item.alt.is_empty() {
item.label.clone()
} else {
item.alt.clone()
};
let mut panel = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("panel-{i}").into(),
))
.test_support()
.role(Role::ListItem)
.aria_label(label)
.aria_selected(i == active)
.track_focus(&focus)
.tab_index(0)
.tab_stop(true)
.relative()
.min_w_0()
.min_h_0()
.flex_basis(px(0.0))
.flex_grow(p.grow.sample(now))
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
if *hovered && c.trigger == AccordionGalleryTrigger::Hover {
select(&st_hover, i, controlled, &cb_hover, window, cx);
}
})
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
let was_active = st_down.borrow().active == i;
st_down.borrow_mut().mouse_was_active = was_active;
window.focus(&down_focus, cx);
})
.on_click(move |event, window, cx| {
let was_active = if matches!(event, gpui_kit::ClickEvent::Mouse(_)) {
st_click.borrow().mouse_was_active
} else {
st_click.borrow().active == i
};
if !was_active {
select(&st_click, i, controlled, &cb_click, window, cx);
} else {
activate_link(i, &link, &activate, window, cx);
}
})
.on_key_down(move |event, window, cx| {
let next = match event.keystroke.key.as_str() {
"right" | "down" => Some((i + 1) % count),
"left" | "up" => Some((i + count - 1) % count),
"home" => Some(0),
"end" => Some(count - 1),
_ => None,
};
if let Some(next) = next {
select(&st_key, next, controlled, &cb_key, window, cx);
let f = st_key.borrow().focus[next].clone();
window.focus(&f, cx);
cx.stop_propagation();
}
})
.child(
canvas(
|_, _, _| (),
move |rect, _, window, cx| {
let overlay: gpui_kit::Rgba = spec.overlay.into();
let params = ProjectedImageParams {
width: rect.size.width.as_f32(),
height: rect.size.height.as_f32(),
radius: spec.radius,
angle: spec.angle.to_radians(),
vertical: spec.vertical,
media: spec.media,
drift: spec.drift,
grayscale: gray,
dim: spec.dim,
overlay: [overlay.r, overlay.g, overlay.b, overlay.a],
scale: window.scale_factor(),
};
let painted = image.as_ref().is_some_and(|image| {
ProjectedMedia::paint(
&media_state,
rect,
image.clone(),
params,
window,
cx,
)
});
if !painted {
paint_media_fallback(
rect,
image.as_ref(),
gray > 0.5,
spec,
window,
);
}
},
)
.absolute()
.size_full(),
);
let bar = p.bar.sample(now);
let caption = p.text.sample(now);
let title = item.label;
panel = panel.child(
canvas(
|_, _, _| (),
move |rect, _, window, cx| {
if focused {
window.paint_quad(gpui_kit::quad(
rect,
px(c.radius),
Hsla::transparent_black(),
gpui_kit::Edges::all(px(2.0)),
accent,
gpui_kit::BorderStyle::Solid,
));
}
window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
if error {
paint_text(
"图片加载失败".into(),
rect.origin + point(px(12.0), px(14.0)),
text_color,
12.0,
window,
cx,
);
}
if bar > 0.0 {
let b = bounds(
rect.origin
+ point(
px(20.0 - 14.0 * (1.0 - bar)),
px((rect.size.height.as_f32() - 46.0).max(4.0)),
),
size(px(3.0), px(26.0)),
);
window.paint_quad(fill(b, accent.opacity(bar)));
}
if caption > 0.0 {
paint_text(
title,
rect.origin
+ point(
px(35.0 - 14.0 * (1.0 - caption)),
px((rect.size.height.as_f32() - 47.0).max(4.0)),
),
text_color.opacity(caption),
20.0,
window,
cx,
);
}
});
},
)
.absolute()
.size_full(),
);
root = root.child(panel);
}
let st_measure = state;
root.child(
canvas(
move |rect, window, _| {
let width = rect.size.width.as_f32();
if (st_measure.borrow().total - width).abs() > 0.5 {
st_measure.borrow_mut().total = width;
window.request_animation_frame();
}
},
|_, _, _, _| (),
)
.absolute()
.size_full(),
)
}
}
fn activate_link(
index: usize,
link: &Option<SharedString>,
cb: &Option<Activate>,
window: &mut Window,
cx: &mut App,
) {
if let Some(link) = link {
if let Some(cb) = cb {
cb(
&AccordionGalleryActivation {
index,
link: link.clone(),
},
window,
cx,
);
} else if link.starts_with("https://") || link.starts_with("http://") {
cx.open_url(link);
}
}
}
fn paint_text(
text: SharedString,
origin: Point<Pixels>,
color: Hsla,
font_size: f32,
window: &mut Window,
cx: &mut App,
) {
let line = window.text_system().shape_line(
text.clone(),
px(font_size),
&[TextRun {
len: text.len(),
font: gpui_kit::font(Typography::body_family()),
color,
..Default::default()
}],
None,
);
let _ = line.paint(
origin,
px(font_size * 1.3),
TextAlign::Left,
None,
window,
cx,
);
}
#[cfg(test)]
mod tests {
use super::*;
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, TestAppContext,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
struct Host {
config: AccordionGalleryConfig,
items: usize,
changed: usize,
activated: usize,
width: f32,
controlled: Option<usize>,
}
impl Render for Host {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let image = window
.use_keyed_state("ag-test-source", cx, |_, _| {
Arc::new(RenderImage::new(vec![image::Frame::new(
image::RgbaImage::from_pixel(4, 4, image::Rgba([60, 120, 180, 255])),
)]))
})
.read(cx)
.clone();
let items = (0..self.items)
.map(|i| {
AccordionGalleryItem::new(image.clone())
.label(format!("Panel {i}"))
.link("#")
})
.collect::<Vec<_>>();
div().w(px(self.width)).child(
AccordionGallery::new("ag-test")
.items(items)
.config(self.config.clone())
.when_some(self.controlled, |gallery, index| gallery.index(index))
.on_index_change(cx.listener(|this, i: &usize, _, cx| {
this.changed = *i;
cx.notify();
}))
.on_activate(cx.listener(|this, _: &AccordionGalleryActivation, _, cx| {
this.activated += 1;
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn accordion_gallery_click_keyboard_ratio_and_empty(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let (view, cx) = cx.add_window_view(|_, _| Host {
config: AccordionGalleryConfig {
trigger: AccordionGalleryTrigger::Click,
..Default::default()
},
items: 5,
changed: 2,
activated: 0,
width: 800.0,
controlled: None,
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
let rect = window.find_by_label("Panel 0").bounds();
let active = window.find_by_label("Panel 2").bounds();
assert!(active.size.width > rect.size.width * 3.0);
window.pointer_down(rect.center(), gpui_kit::MouseButton::Left, cx);
window.pointer_up(rect.center(), gpui_kit::MouseButton::Left, cx);
window.render_frame(cx);
window.render_frame(cx);
assert_eq!(view.read(cx).changed, 0);
assert_eq!(view.read(cx).activated, 0);
window.press("right", cx);
window.render_frame(cx);
assert_eq!(view.read(cx).changed, 1);
window.press("enter", cx);
assert_eq!(view.read(cx).activated, 1);
window.press("space", cx);
assert_eq!(view.read(cx).activated, 2);
window.render_frame(cx);
let selected = window.find_by_label("Panel 1").bounds();
window.pointer_down(selected.center(), gpui_kit::MouseButton::Left, cx);
window.pointer_up(selected.center(), gpui_kit::MouseButton::Left, cx);
assert_eq!(view.read(cx).activated, 3);
window.press("end", cx);
window.render_frame(cx);
assert_eq!(view.read(cx).changed, 4);
window.press("right", cx);
window.render_frame(cx);
assert_eq!(view.read(cx).changed, 0);
view.update(cx, |v, cx| {
v.items = 1;
v.config.orientation = Orientation::Vertical;
cx.notify();
});
window.render_frame(cx);
window.render_frame(cx);
assert!(window.find_by_label("Panel 0").bounds().size.height > px(700.0));
view.update(cx, |v, cx| {
v.items = 0;
cx.notify();
});
window.render_frame(cx);
assert!(window.try_find_by_label("Panel 0").is_none());
});
}
#[gpui_kit::test]
fn accordion_gallery_hover_focus_controlled_and_resize(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
items: 5,
changed: 2,
activated: 0,
width: 800.0,
controlled: None,
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
let panel = window.find_by_label("Panel 4").bounds();
window.pointer_move(panel.center(), None, cx);
window.render_frame(cx);
assert_eq!(view.read(cx).changed, 4);
window.pointer_move(point(px(900.0), px(800.0)), None, cx);
window.focus_next(cx);
assert!(window.focused(cx).is_some(), "面板必须注册为原生 Tab stop");
window.render_frame(cx);
});
cx.run_until_parked();
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(view.read(cx).changed, 0);
view.update(cx, |v, cx| {
v.controlled = Some(2);
cx.notify();
});
window.render_frame(cx);
window.press("end", cx);
window.render_frame(cx);
window.render_frame(cx);
assert_eq!(view.read(cx).changed, 4);
let active = window.find_by_label("Panel 2").bounds();
let last = window.find_by_label("Panel 4").bounds();
assert!(active.size.width > last.size.width * 3.0);
view.update(cx, |v, cx| {
v.width = 480.0;
cx.notify();
});
for _ in 0..3 {
window.render_frame(cx);
}
let first = window.find_by_label("Panel 0").bounds();
let second = window.find_by_label("Panel 1").bounds();
assert!(second.top() > first.bottom());
assert!(window.find("ag-test").bounds().size.height > px(700.0));
install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
window.render_frame(cx);
});
}
#[test]
fn accordion_gallery_ratio_and_invalid_config() {
let c = AccordionGalleryConfig::default();
let g = c.expanded_grow(5);
assert!((g / (g + 4.0) - 0.52).abs() < 1e-6);
assert_eq!(c.expanded_grow(1), 1.0);
let c = AccordionGalleryConfig {
height: f32::NAN,
expand_ratio: 2.0,
duration: -1.0,
..c
}
.sanitized();
assert_eq!(c.height, 460.0);
assert_eq!(c.expand_ratio, 0.9);
assert_eq!(c.duration, 0.0);
}
#[test]
fn accordion_gallery_real_perspective_and_rounding() {
let left = project(0.0, 0.0, 200.0, 460.0, 8.0, false);
let right = project(200.0, 0.0, 200.0, 460.0, 8.0, false);
assert!((left.1 - right.1).abs() > 1.0);
let top = project(0.0, 0.0, 200.0, 460.0, 8.0, true);
let bottom = project(0.0, 460.0, 200.0, 460.0, 8.0, true);
assert!((top.0 - bottom.0).abs() > 1.0);
}
#[test]
fn accordion_gallery_switch_preserves_actual_motion() {
let c = AccordionGalleryConfig::default();
let mut p = PanelMotion::new(0, 2, 5, &c);
p.update(0, 0, 5, &c, 0.0, false);
let grow = p.grow.sample(0.2);
p.update(0, 1, 5, &c, 0.2, false);
assert_eq!(p.grow.sample(0.2), grow);
p.update(0, 1, 5, &c, 0.3, true);
assert_eq!(p.angle.sample(0.3), 8.0);
}
}