use std::{cell::RefCell, collections::HashMap, rc::Rc};
use arc_motion::{LayoutSnapshot, layout::layout_scope_key, sample_shared_layout};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography};
use gpui_kit::{
App, BorderStyle, Bounds, Edges, ElementId, IntoElement, ParentElement, Pixels, RenderOnce,
Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
base::Button as BaseButton, bounds, canvas, component::Icon, div, prelude::*, px, quad,
};
type PageHandler = Rc<dyn Fn(&usize, &mut Window, &mut App)>;
pub fn window_start(current: usize, page_count: usize) -> usize {
if page_count == 0 {
return 1;
}
let max_start = page_count.saturating_sub(4).max(1);
current.saturating_sub(2).clamp(1, max_start)
}
struct PaginationInternal {
page_bounds: Rc<RefCell<HashMap<usize, Bounds<Pixels>>>>,
}
#[derive(IntoElement)]
pub struct Pagination {
id: ElementId,
page: usize,
page_count: usize,
label: SharedString,
on_page_change: Option<PageHandler>,
}
impl Pagination {
pub fn new(id: impl Into<ElementId>, page: usize, page_count: usize) -> Self {
Self {
id: id.into(),
page,
page_count,
label: "Pagination".into(),
on_page_change: None,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn on_page_change(
mut self,
handler: impl Fn(&usize, &mut Window, &mut App) + 'static,
) -> Self {
self.on_page_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Pagination {
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 state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-pagination".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| PaginationInternal {
page_bounds: Rc::new(RefCell::new(HashMap::new())),
});
let page_bounds = internal.read(cx).page_bounds.clone();
let count = self.page_count;
if count == 0 {
return div().id(self.id).into_any_element();
}
let current = self.page.clamp(1, count);
let start = window_start(current, count);
let visible: Vec<usize> = (start..start + count.min(5)).collect();
let scope = layout_scope_key(&self.id);
let bounds_for_mark = page_bounds.clone();
let morph = motion.spring.morph;
let mark_bg = colors.surface;
let mark_border = colors.border;
let mark_shadows = Shadows::resting(theme.mode);
let mark = canvas(
|_, _, _| {},
move |nav_rect, _, window, cx| {
let Some(btn) = bounds_for_mark.borrow().get(¤t).copied() else {
window.request_animation_frame();
return;
};
let local = bounds(btn.origin - nav_rect.origin, btn.size);
let target = LayoutSnapshot::uniform_radius(local, Radii::CONTROL);
let flip =
sample_shared_layout(scope.clone(), "mark", target, Some(morph), window, cx);
window.paint_drop_shadows(
bounds(nav_rect.origin + flip.bounds.origin, flip.bounds.size),
flip.corner_radii,
&mark_shadows,
);
window.paint_quad(quad(
bounds(nav_rect.origin + flip.bounds.origin, flip.bounds.size),
flip.corner_radii,
mark_bg,
Edges::all(px(1.0)),
mark_border,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0();
let step_button = |idx: &'static str,
icon: IconName,
label: &'static str,
target: usize,
disabled: bool,
handler: Option<PageHandler>| {
let hover_bg = colors.surface_muted;
let hover_fg = colors.foreground;
BaseButton::new(ElementId::NamedChild(self.id.clone().into(), idx.into()))
.disabled(disabled)
.accessibility_label(label)
.on_click(move |_, window, cx| {
if !disabled && let Some(h) = &handler {
h(&target, window, cx);
}
})
.w(ControlHeights::SM)
.h(ControlHeights::SM)
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(Radii::CONTROL)
.text_color(colors.text_secondary)
.when(disabled, |this| this.opacity(0.4))
.when(!disabled, |this| {
this.cursor_pointer()
.hover(move |s| s.bg(hover_bg).text_color(hover_fg))
})
.child(Icon::new(icon).text_size(px(16.0)))
};
let mut nav = div()
.id(self.id.clone())
.test_support()
.role(Role::Group)
.aria_label(self.label.clone())
.relative()
.flex()
.flex_row()
.flex_wrap()
.items_center()
.gap(Spacing::S1)
.child(mark)
.child(step_button(
"prev",
IconName::ChevronLeft,
"Previous page",
current.saturating_sub(1).max(1),
current <= 1,
self.on_page_change.clone(),
));
for number in visible {
let is_current = number == current;
let handler = self.on_page_change.clone();
let bounds_measure = page_bounds.clone();
let probe = canvas(
move |rect, _, _| {
bounds_measure.borrow_mut().insert(number, rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let hover_bg = colors.surface_muted;
nav = nav.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("page-{number}")),
))
.accessibility_label(format!("Page {number}"))
.on_click(move |_, window, cx| {
if let Some(h) = &handler {
h(&number, window, cx);
}
})
.relative()
.w(ControlHeights::SM)
.h(ControlHeights::SM)
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(Radii::CONTROL)
.text_size(Typography::TEXT_XS)
.text_color(if is_current {
colors.foreground
} else {
colors.text_secondary
})
.cursor_pointer()
.when(!is_current, |this| this.hover(move |s| s.bg(hover_bg)))
.child(probe)
.child(format!("{number}")),
);
}
nav.child(step_button(
"next",
IconName::ChevronRight,
"Next page",
(current + 1).min(count),
current >= count,
self.on_page_change.clone(),
))
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct PageHost {
page: usize,
last: Rc<Cell<usize>>,
}
impl Render for PageHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let last = self.last.clone();
div().w(px(420.0)).p(Spacing::S4).child(
Pagination::new("pager", self.page, 10).on_page_change(cx.listener(
move |this, _: &usize, _, cx| {
let _ = (&last, this, cx);
},
)),
)
}
}
#[test]
fn window_follows_current_page_and_clamps() {
assert_eq!(window_start(1, 10), 1);
assert_eq!(window_start(3, 10), 1);
assert_eq!(window_start(6, 10), 4);
assert_eq!(window_start(10, 10), 6);
assert_eq!(window_start(2, 3), 1);
assert_eq!(window_start(5, 0), 1);
}
struct SimpleHost {
page: usize,
picked: Rc<Cell<usize>>,
}
impl Render for SimpleHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let picked = self.picked.clone();
div().w(px(420.0)).p(Spacing::S4).child(
Pagination::new("pager2", self.page, 10)
.on_page_change(move |p, _, _| picked.set(*p)),
)
}
}
#[gpui_kit::test]
fn pagination_steps_and_disables_prev_on_first_page(cx: &mut TestAppContext) {
let _ = std::marker::PhantomData::<PageHost>;
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let picked = Rc::new(Cell::new(0));
let (_view, cx) = cx.add_window_view(|_, _| SimpleHost {
page: 1,
picked: picked.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
assert_eq!(window.find_by_label("Previous page").disabled(), Some(true));
let next = window.find_by_label("Next page");
let pos = next.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
});
assert_eq!(picked.get(), 2);
}
#[gpui_kit::test]
fn pagination_page_button_reports_its_number(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let picked = Rc::new(Cell::new(0));
let (_view, cx) = cx.add_window_view(|_, _| SimpleHost {
page: 1,
picked: picked.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
let page = window.find_by_label("Page 4");
let pos = page.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
});
assert_eq!(picked.get(), 4);
}
}